resource_loader.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  1. /**************************************************************************/
  2. /* resource_loader.cpp */
  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. #include "resource_loader.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/core_bind.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/resource_importer.h"
  36. #include "core/object/script_language.h"
  37. #include "core/os/condition_variable.h"
  38. #include "core/os/os.h"
  39. #include "core/os/safe_binary_mutex.h"
  40. #include "core/string/print_string.h"
  41. #include "core/string/translation_server.h"
  42. #include "core/templates/rb_set.h"
  43. #include "core/variant/variant_parser.h"
  44. #include "servers/rendering/rendering_server.h"
  45. #ifdef DEBUG_LOAD_THREADED
  46. #define print_lt(m_text) print_line(m_text)
  47. #else
  48. #define print_lt(m_text)
  49. #endif
  50. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  51. int ResourceLoader::loader_count = 0;
  52. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  53. bool ret = false;
  54. if (GDVIRTUAL_CALL(_recognize_path, p_path, p_for_type, ret)) {
  55. return ret;
  56. }
  57. List<String> extensions;
  58. if (p_for_type.is_empty()) {
  59. get_recognized_extensions(&extensions);
  60. } else {
  61. get_recognized_extensions_for_type(p_for_type, &extensions);
  62. }
  63. for (const String &E : extensions) {
  64. const String ext = !E.begins_with(".") ? "." + E : E;
  65. if (p_path.right(ext.length()).nocasecmp_to(ext) == 0) {
  66. return true;
  67. }
  68. }
  69. return false;
  70. }
  71. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  72. bool success = false;
  73. GDVIRTUAL_CALL(_handles_type, p_type, success);
  74. return success;
  75. }
  76. void ResourceFormatLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  77. Vector<String> ret;
  78. if (GDVIRTUAL_CALL(_get_classes_used, p_path, ret)) {
  79. for (int i = 0; i < ret.size(); i++) {
  80. r_classes->insert(ret[i]);
  81. }
  82. return;
  83. }
  84. String res = get_resource_type(p_path);
  85. if (!res.is_empty()) {
  86. r_classes->insert(res);
  87. }
  88. }
  89. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  90. String ret;
  91. GDVIRTUAL_CALL(_get_resource_type, p_path, ret);
  92. return ret;
  93. }
  94. String ResourceFormatLoader::get_resource_script_class(const String &p_path) const {
  95. String ret;
  96. GDVIRTUAL_CALL(_get_resource_script_class, p_path, ret);
  97. return ret;
  98. }
  99. ResourceUID::ID ResourceFormatLoader::get_resource_uid(const String &p_path) const {
  100. int64_t uid = ResourceUID::INVALID_ID;
  101. if (has_custom_uid_support()) {
  102. GDVIRTUAL_CALL(_get_resource_uid, p_path, uid);
  103. } else {
  104. Ref<FileAccess> file = FileAccess::open(p_path + ".uid", FileAccess::READ);
  105. if (file.is_valid()) {
  106. uid = ResourceUID::get_singleton()->text_to_id(file->get_line());
  107. }
  108. }
  109. return uid;
  110. }
  111. bool ResourceFormatLoader::has_custom_uid_support() const {
  112. return GDVIRTUAL_IS_OVERRIDDEN(_get_resource_uid);
  113. }
  114. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  115. if (p_type.is_empty() || handles_type(p_type)) {
  116. get_recognized_extensions(p_extensions);
  117. }
  118. }
  119. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  120. for (int i = 0; i < loader_count; i++) {
  121. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  122. }
  123. }
  124. bool ResourceFormatLoader::exists(const String &p_path) const {
  125. bool success = false;
  126. if (GDVIRTUAL_CALL(_exists, p_path, success)) {
  127. return success;
  128. }
  129. return FileAccess::exists(p_path); // By default just check file.
  130. }
  131. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  132. PackedStringArray exts;
  133. if (GDVIRTUAL_CALL(_get_recognized_extensions, exts)) {
  134. const String *r = exts.ptr();
  135. for (int i = 0; i < exts.size(); ++i) {
  136. p_extensions->push_back(r[i]);
  137. }
  138. }
  139. }
  140. Ref<Resource> ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  141. Variant res;
  142. if (GDVIRTUAL_CALL(_load, p_path, p_original_path, p_use_sub_threads, p_cache_mode, res)) {
  143. if (res.get_type() == Variant::INT) { // Error code, abort.
  144. if (r_error) {
  145. *r_error = (Error)res.operator int64_t();
  146. }
  147. return Ref<Resource>();
  148. } else { // Success, pass on result.
  149. if (r_error) {
  150. *r_error = OK;
  151. }
  152. return res;
  153. }
  154. }
  155. return Ref<Resource>();
  156. }
  157. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  158. PackedStringArray deps;
  159. if (GDVIRTUAL_CALL(_get_dependencies, p_path, p_add_types, deps)) {
  160. const String *r = deps.ptr();
  161. for (int i = 0; i < deps.size(); ++i) {
  162. p_dependencies->push_back(r[i]);
  163. }
  164. }
  165. }
  166. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  167. Dictionary deps_dict;
  168. for (KeyValue<String, String> E : p_map) {
  169. deps_dict[E.key] = E.value;
  170. }
  171. Error err = OK;
  172. GDVIRTUAL_CALL(_rename_dependencies, p_path, deps_dict, err);
  173. return err;
  174. }
  175. void ResourceFormatLoader::_bind_methods() {
  176. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE);
  177. BIND_ENUM_CONSTANT(CACHE_MODE_REUSE);
  178. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
  179. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE_DEEP);
  180. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE_DEEP);
  181. GDVIRTUAL_BIND(_get_recognized_extensions);
  182. GDVIRTUAL_BIND(_recognize_path, "path", "type");
  183. GDVIRTUAL_BIND(_handles_type, "type");
  184. GDVIRTUAL_BIND(_get_resource_type, "path");
  185. GDVIRTUAL_BIND(_get_resource_script_class, "path");
  186. GDVIRTUAL_BIND(_get_resource_uid, "path");
  187. GDVIRTUAL_BIND(_get_dependencies, "path", "add_types");
  188. GDVIRTUAL_BIND(_rename_dependencies, "path", "renames");
  189. GDVIRTUAL_BIND(_exists, "path");
  190. GDVIRTUAL_BIND(_get_classes_used, "path");
  191. GDVIRTUAL_BIND(_load, "path", "original_path", "use_sub_threads", "cache_mode");
  192. }
  193. ///////////////////////////////////
  194. // These are used before and after a wait for a WorkerThreadPool task
  195. // because that can lead to another load started in the same thread,
  196. // something we must treat as a different stack for the purposes
  197. // of tracking nesting.
  198. #define PREPARE_FOR_WTP_WAIT \
  199. int load_nesting_backup = ResourceLoader::load_nesting; \
  200. Vector<String> load_paths_stack_backup = ResourceLoader::load_paths_stack; \
  201. ResourceLoader::load_nesting = 0; \
  202. ResourceLoader::load_paths_stack.clear();
  203. #define RESTORE_AFTER_WTP_WAIT \
  204. DEV_ASSERT(ResourceLoader::load_nesting == 0); \
  205. DEV_ASSERT(ResourceLoader::load_paths_stack.is_empty()); \
  206. ResourceLoader::load_nesting = load_nesting_backup; \
  207. ResourceLoader::load_paths_stack = load_paths_stack_backup; \
  208. load_paths_stack_backup.clear();
  209. // This should be robust enough to be called redundantly without issues.
  210. void ResourceLoader::LoadToken::clear() {
  211. WorkerThreadPool::TaskID task_to_await = 0;
  212. {
  213. MutexLock thread_load_lock(thread_load_mutex);
  214. // User-facing tokens shouldn't be deleted until completely claimed.
  215. DEV_ASSERT(user_rc == 0 && user_path.is_empty());
  216. if (!local_path.is_empty()) {
  217. if (task_if_unregistered) {
  218. memdelete(task_if_unregistered);
  219. task_if_unregistered = nullptr;
  220. } else {
  221. DEV_ASSERT(thread_load_tasks.has(local_path));
  222. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  223. if (load_task.task_id && !load_task.awaited) {
  224. task_to_await = load_task.task_id;
  225. }
  226. // Removing a task which is still in progress would be catastrophic.
  227. // Tokens must be alive until the task thread function is done.
  228. DEV_ASSERT(load_task.status == THREAD_LOAD_FAILED || load_task.status == THREAD_LOAD_LOADED);
  229. thread_load_tasks.erase(local_path);
  230. }
  231. local_path.clear(); // Mark as already cleared.
  232. if (task_to_await) {
  233. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  234. if (E.value.task_id == task_to_await) {
  235. task_to_await = 0;
  236. break; // Same task is reused by nested loads, do not wait for completion here.
  237. }
  238. }
  239. }
  240. }
  241. }
  242. // If task is unused, await it here, locally, now the token data is consistent.
  243. if (task_to_await) {
  244. PREPARE_FOR_WTP_WAIT
  245. WorkerThreadPool::get_singleton()->wait_for_task_completion(task_to_await);
  246. RESTORE_AFTER_WTP_WAIT
  247. }
  248. }
  249. ResourceLoader::LoadToken::~LoadToken() {
  250. clear();
  251. }
  252. Ref<Resource> ResourceLoader::_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) {
  253. const String &original_path = p_original_path.is_empty() ? p_path : p_original_path;
  254. load_nesting++;
  255. if (load_paths_stack.size()) {
  256. MutexLock thread_load_lock(thread_load_mutex);
  257. const String &parent_task_path = load_paths_stack.get(load_paths_stack.size() - 1);
  258. HashMap<String, ThreadLoadTask>::Iterator E = thread_load_tasks.find(parent_task_path);
  259. // Avoid double-tracking, for progress reporting, resources that boil down to a remapped path containing the real payload (e.g., imported resources).
  260. bool is_remapped_load = original_path == parent_task_path;
  261. if (E && !is_remapped_load) {
  262. E->value.sub_tasks.insert(original_path);
  263. }
  264. }
  265. load_paths_stack.push_back(original_path);
  266. print_verbose(vformat("Loading resource: %s", p_path));
  267. // Try all loaders and pick the first match for the type hint
  268. bool found = false;
  269. Ref<Resource> res;
  270. for (int i = 0; i < loader_count; i++) {
  271. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  272. continue;
  273. }
  274. found = true;
  275. res = loader[i]->load(p_path, original_path, r_error, p_use_sub_threads, r_progress, p_cache_mode);
  276. if (res.is_valid()) {
  277. break;
  278. }
  279. }
  280. load_paths_stack.resize(load_paths_stack.size() - 1);
  281. res_ref_overrides.erase(load_nesting);
  282. load_nesting--;
  283. if (res.is_valid()) {
  284. return res;
  285. } else {
  286. print_verbose(vformat("Failed loading resource: %s", p_path));
  287. }
  288. #ifdef TOOLS_ENABLED
  289. if (Engine::get_singleton()->is_editor_hint()) {
  290. if (ResourceFormatImporter::get_singleton()->get_importer_by_file(p_path).is_valid()) {
  291. // The format is known to the editor, but the file hasn't been imported
  292. // (otherwise, ResourceFormatImporter would have been found as a suitable loader).
  293. found = true;
  294. if (r_error) {
  295. *r_error = ERR_FILE_NOT_FOUND;
  296. }
  297. }
  298. }
  299. #endif
  300. ERR_FAIL_COND_V_MSG(found, Ref<Resource>(), vformat("Failed loading resource: %s.", p_path));
  301. #ifdef TOOLS_ENABLED
  302. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  303. if (!file_check->file_exists(p_path)) {
  304. if (r_error) {
  305. *r_error = ERR_FILE_NOT_FOUND;
  306. }
  307. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Resource file not found: %s (expected type: %s)", p_path, !p_type_hint.is_empty() ? p_type_hint : "unknown"));
  308. }
  309. #endif
  310. if (r_error) {
  311. *r_error = ERR_FILE_UNRECOGNIZED;
  312. }
  313. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("No loader found for resource: %s (expected type: %s)", p_path, !p_type_hint.is_empty() ? p_type_hint : "unknown"));
  314. }
  315. // This implementation must allow re-entrancy for a task that started awaiting in a deeper stack frame.
  316. // The load task token must be manually re-referenced before this is called, which includes threaded runs.
  317. void ResourceLoader::_run_load_task(void *p_userdata) {
  318. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  319. {
  320. MutexLock thread_load_lock(thread_load_mutex);
  321. if (cleaning_tasks) {
  322. load_task.status = THREAD_LOAD_FAILED;
  323. return;
  324. }
  325. }
  326. ThreadLoadTask *curr_load_task_backup = curr_load_task;
  327. curr_load_task = &load_task;
  328. // Thread-safe either if it's the current thread or a brand new one.
  329. CallQueue *own_mq_override = nullptr;
  330. if (load_nesting == 0) {
  331. DEV_ASSERT(load_paths_stack.is_empty());
  332. if (!Thread::is_main_thread()) {
  333. // Let the caller thread use its own, for added flexibility. Provide one otherwise.
  334. if (MessageQueue::get_singleton() == MessageQueue::get_main_singleton()) {
  335. own_mq_override = memnew(CallQueue);
  336. MessageQueue::set_thread_singleton_override(own_mq_override);
  337. }
  338. set_current_thread_safe_for_nodes(true);
  339. }
  340. }
  341. // --
  342. bool xl_remapped = false;
  343. const String &remapped_path = _path_remap(load_task.local_path, &xl_remapped);
  344. Error load_err = OK;
  345. Ref<Resource> res = _load(remapped_path, remapped_path != load_task.local_path ? load_task.local_path : String(), load_task.type_hint, load_task.cache_mode, &load_err, load_task.use_sub_threads, &load_task.progress);
  346. if (MessageQueue::get_singleton() != MessageQueue::get_main_singleton()) {
  347. MessageQueue::get_singleton()->flush();
  348. }
  349. thread_load_mutex.lock();
  350. load_task.resource = res;
  351. load_task.progress = 1.0; // It was fully loaded at this point, so force progress to 1.0.
  352. load_task.error = load_err;
  353. if (load_task.error != OK) {
  354. load_task.status = THREAD_LOAD_FAILED;
  355. } else {
  356. load_task.status = THREAD_LOAD_LOADED;
  357. }
  358. if (load_task.cond_var && load_task.need_wait) {
  359. load_task.cond_var->notify_all();
  360. }
  361. load_task.need_wait = false;
  362. bool ignoring = load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE || load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP;
  363. bool replacing = load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE || load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE_DEEP;
  364. bool unlock_pending = true;
  365. if (load_task.resource.is_valid()) {
  366. // From now on, no critical section needed as no one will write to the task anymore.
  367. // Moreover, the mutex being unlocked is a requirement if some of the calls below
  368. // that set the resource up invoke code that in turn requests resource loading.
  369. thread_load_mutex.unlock();
  370. unlock_pending = false;
  371. if (!ignoring) {
  372. ResourceCache::lock.lock(); // Check and operations must happen atomically.
  373. bool pending_unlock = true;
  374. Ref<Resource> old_res = ResourceCache::get_ref(load_task.local_path);
  375. if (old_res.is_valid()) {
  376. if (old_res != load_task.resource) {
  377. // Resource can already exists at this point for two reasons:
  378. // a) The load uses replace mode.
  379. // b) There were more than one load in flight for the same path because of deadlock prevention.
  380. // Either case, we want to keep the resource that was already there.
  381. ResourceCache::lock.unlock();
  382. pending_unlock = false;
  383. if (replacing) {
  384. old_res->copy_from(load_task.resource);
  385. }
  386. load_task.resource = old_res;
  387. }
  388. } else {
  389. load_task.resource->set_path(load_task.local_path);
  390. }
  391. if (pending_unlock) {
  392. ResourceCache::lock.unlock();
  393. }
  394. } else {
  395. load_task.resource->set_path_cache(load_task.local_path);
  396. }
  397. if (xl_remapped) {
  398. load_task.resource->set_as_translation_remapped(true);
  399. }
  400. #ifdef TOOLS_ENABLED
  401. load_task.resource->set_edited(false);
  402. if (timestamp_on_load) {
  403. uint64_t mt = FileAccess::get_modified_time(remapped_path);
  404. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  405. load_task.resource->set_last_modified_time(mt);
  406. }
  407. #endif
  408. if (_loaded_callback) {
  409. _loaded_callback(load_task.resource, load_task.local_path);
  410. }
  411. } else if (!ignoring) {
  412. Ref<Resource> existing = ResourceCache::get_ref(load_task.local_path);
  413. if (existing.is_valid()) {
  414. load_task.resource = existing;
  415. load_task.status = THREAD_LOAD_LOADED;
  416. load_task.progress = 1.0;
  417. thread_load_mutex.unlock();
  418. unlock_pending = false;
  419. if (_loaded_callback) {
  420. _loaded_callback(load_task.resource, load_task.local_path);
  421. }
  422. }
  423. }
  424. // It's safe now to let the task go in case no one else was grabbing the token.
  425. load_task.load_token->unreference();
  426. if (unlock_pending) {
  427. thread_load_mutex.unlock();
  428. }
  429. if (load_nesting == 0) {
  430. if (own_mq_override) {
  431. MessageQueue::set_thread_singleton_override(nullptr);
  432. memdelete(own_mq_override);
  433. }
  434. DEV_ASSERT(load_paths_stack.is_empty());
  435. }
  436. curr_load_task = curr_load_task_backup;
  437. }
  438. String ResourceLoader::_validate_local_path(const String &p_path) {
  439. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(p_path);
  440. if (uid != ResourceUID::INVALID_ID) {
  441. return ResourceUID::get_singleton()->get_id_path(uid);
  442. } else if (p_path.is_relative_path()) {
  443. return ("res://" + p_path).simplify_path();
  444. } else {
  445. return ProjectSettings::get_singleton()->localize_path(p_path);
  446. }
  447. }
  448. Error ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads, ResourceFormatLoader::CacheMode p_cache_mode) {
  449. Ref<ResourceLoader::LoadToken> token = _load_start(p_path, p_type_hint, p_use_sub_threads ? LOAD_THREAD_DISTRIBUTE : LOAD_THREAD_SPAWN_SINGLE, p_cache_mode, true);
  450. return token.is_valid() ? OK : FAILED;
  451. }
  452. ResourceLoader::LoadToken *ResourceLoader::_load_threaded_request_reuse_user_token(const String &p_path) {
  453. HashMap<String, LoadToken *>::Iterator E = user_load_tokens.find(p_path);
  454. if (E) {
  455. print_verbose("load_threaded_request(): Another threaded load for resource path '" + p_path + "' has been initiated. Not an error.");
  456. LoadToken *token = E->value;
  457. token->user_rc++;
  458. return token;
  459. } else {
  460. return nullptr;
  461. }
  462. }
  463. void ResourceLoader::_load_threaded_request_setup_user_token(LoadToken *p_token, const String &p_path) {
  464. p_token->user_path = p_path;
  465. p_token->reference(); // Extra RC until all user requests have been gotten.
  466. p_token->user_rc = 1;
  467. user_load_tokens[p_path] = p_token;
  468. print_lt("REQUEST: user load tokens: " + itos(user_load_tokens.size()));
  469. }
  470. Ref<Resource> ResourceLoader::load(const String &p_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error) {
  471. if (r_error) {
  472. *r_error = OK;
  473. }
  474. LoadThreadMode thread_mode = LOAD_THREAD_FROM_CURRENT;
  475. if (WorkerThreadPool::get_singleton()->get_caller_task_id() != WorkerThreadPool::INVALID_TASK_ID) {
  476. // If user is initiating a single-threaded load from a WorkerThreadPool task,
  477. // we instead spawn a new task so there's a precondition that a load in a pool task
  478. // is always initiated by the engine. That makes certain aspects simpler, such as
  479. // cyclic load detection and awaiting.
  480. thread_mode = LOAD_THREAD_SPAWN_SINGLE;
  481. }
  482. Ref<LoadToken> load_token = _load_start(p_path, p_type_hint, thread_mode, p_cache_mode);
  483. if (load_token.is_null()) {
  484. if (r_error) {
  485. *r_error = FAILED;
  486. }
  487. return Ref<Resource>();
  488. }
  489. Ref<Resource> res = _load_complete(*load_token.ptr(), r_error);
  490. return res;
  491. }
  492. Ref<ResourceLoader::LoadToken> ResourceLoader::_load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode, bool p_for_user) {
  493. String local_path = _validate_local_path(p_path);
  494. ERR_FAIL_COND_V(local_path.is_empty(), Ref<ResourceLoader::LoadToken>());
  495. bool ignoring_cache = p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE || p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP;
  496. Ref<LoadToken> load_token;
  497. bool must_not_register = false;
  498. ThreadLoadTask *load_task_ptr = nullptr;
  499. {
  500. MutexLock thread_load_lock(thread_load_mutex);
  501. if (p_for_user) {
  502. LoadToken *existing_token = _load_threaded_request_reuse_user_token(p_path);
  503. if (existing_token) {
  504. return Ref<LoadToken>(existing_token);
  505. }
  506. }
  507. if (!ignoring_cache && thread_load_tasks.has(local_path)) {
  508. load_token = Ref<LoadToken>(thread_load_tasks[local_path].load_token);
  509. if (load_token.is_valid()) {
  510. if (p_for_user) {
  511. // Load task exists, with no user tokens at the moment.
  512. // Let's "attach" to it.
  513. _load_threaded_request_setup_user_token(load_token.ptr(), p_path);
  514. }
  515. return load_token;
  516. } else {
  517. // The token is dying (reached 0 on another thread).
  518. // Ensure it's killed now so the path can be safely reused right away.
  519. thread_load_tasks[local_path].load_token->clear();
  520. }
  521. }
  522. load_token.instantiate();
  523. load_token->local_path = local_path;
  524. if (p_for_user) {
  525. _load_threaded_request_setup_user_token(load_token.ptr(), p_path);
  526. }
  527. //create load task
  528. {
  529. ThreadLoadTask load_task;
  530. load_task.load_token = load_token.ptr();
  531. load_task.local_path = local_path;
  532. load_task.type_hint = p_type_hint;
  533. load_task.cache_mode = p_cache_mode;
  534. load_task.use_sub_threads = p_thread_mode == LOAD_THREAD_DISTRIBUTE;
  535. if (p_cache_mode == ResourceFormatLoader::CACHE_MODE_REUSE) {
  536. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  537. if (existing.is_valid()) {
  538. //referencing is fine
  539. load_task.resource = existing;
  540. load_task.status = THREAD_LOAD_LOADED;
  541. load_task.progress = 1.0;
  542. DEV_ASSERT(!thread_load_tasks.has(local_path));
  543. thread_load_tasks[local_path] = load_task;
  544. return load_token;
  545. }
  546. }
  547. // If we want to ignore cache, but there's another task loading it, we can't add this one to the map.
  548. must_not_register = ignoring_cache && thread_load_tasks.has(local_path);
  549. if (must_not_register) {
  550. load_token->task_if_unregistered = memnew(ThreadLoadTask(load_task));
  551. load_task_ptr = load_token->task_if_unregistered;
  552. } else {
  553. DEV_ASSERT(!thread_load_tasks.has(local_path));
  554. HashMap<String, ResourceLoader::ThreadLoadTask>::Iterator E = thread_load_tasks.insert(local_path, load_task);
  555. load_task_ptr = &E->value;
  556. }
  557. }
  558. // It's important to keep the token alive because until the load completes,
  559. // which includes before the thread start, it may happen that no one is grabbing
  560. // the token anymore so it's released.
  561. load_task_ptr->load_token->reference();
  562. if (p_thread_mode == LOAD_THREAD_FROM_CURRENT) {
  563. // The current thread may happen to be a thread from the pool.
  564. WorkerThreadPool::TaskID tid = WorkerThreadPool::get_singleton()->get_caller_task_id();
  565. if (tid != WorkerThreadPool::INVALID_TASK_ID) {
  566. load_task_ptr->task_id = tid;
  567. } else {
  568. load_task_ptr->thread_id = Thread::get_caller_id();
  569. }
  570. } else {
  571. load_task_ptr->task_id = WorkerThreadPool::get_singleton()->add_native_task(&ResourceLoader::_run_load_task, load_task_ptr);
  572. }
  573. } // MutexLock(thread_load_mutex).
  574. if (p_thread_mode == LOAD_THREAD_FROM_CURRENT) {
  575. _run_load_task(load_task_ptr);
  576. }
  577. return load_token;
  578. }
  579. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  580. if (thread_load_tasks.has(p_path)) {
  581. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  582. if (load_task.in_progress_check) {
  583. // Given the fact that any resource loaded when an outer stack frame is
  584. // loading another one is considered a dependency of it, for progress
  585. // tracking purposes, a cycle can happen if even if the original resource
  586. // graphs involved have none. For instance, preload() can cause this.
  587. return load_task.max_reported_progress;
  588. }
  589. load_task.in_progress_check = true;
  590. float current_progress = 0.0;
  591. int dep_count = load_task.sub_tasks.size();
  592. if (dep_count > 0) {
  593. for (const String &E : load_task.sub_tasks) {
  594. current_progress += _dependency_get_progress(E);
  595. }
  596. current_progress /= float(dep_count);
  597. current_progress *= 0.5;
  598. current_progress += load_task.progress * 0.5;
  599. } else {
  600. current_progress = load_task.progress;
  601. }
  602. load_task.max_reported_progress = MAX(load_task.max_reported_progress, current_progress);
  603. load_task.in_progress_check = false;
  604. return load_task.max_reported_progress;
  605. } else {
  606. return 1.0; //assume finished loading it so it no longer exists
  607. }
  608. }
  609. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  610. bool ensure_progress = false;
  611. ThreadLoadStatus status = THREAD_LOAD_IN_PROGRESS;
  612. {
  613. MutexLock thread_load_lock(thread_load_mutex);
  614. if (!user_load_tokens.has(p_path)) {
  615. print_verbose("load_threaded_get_status(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  616. return THREAD_LOAD_INVALID_RESOURCE;
  617. }
  618. String local_path = _validate_local_path(p_path);
  619. LoadToken *load_token = user_load_tokens[p_path];
  620. ThreadLoadTask *load_task_ptr;
  621. if (load_token->task_if_unregistered) {
  622. load_task_ptr = load_token->task_if_unregistered;
  623. } else {
  624. ERR_FAIL_COND_V_MSG(!thread_load_tasks.has(local_path), THREAD_LOAD_INVALID_RESOURCE, "Bug in ResourceLoader logic, please report.");
  625. load_task_ptr = &thread_load_tasks[local_path];
  626. }
  627. status = load_task_ptr->status;
  628. if (r_progress) {
  629. *r_progress = _dependency_get_progress(local_path);
  630. }
  631. // Support userland polling in a loop on the main thread.
  632. if (Thread::is_main_thread() && status == THREAD_LOAD_IN_PROGRESS) {
  633. uint64_t frame = Engine::get_singleton()->get_process_frames();
  634. if (frame == load_task_ptr->last_progress_check_main_thread_frame) {
  635. ensure_progress = true;
  636. } else {
  637. load_task_ptr->last_progress_check_main_thread_frame = frame;
  638. }
  639. }
  640. }
  641. if (ensure_progress) {
  642. _ensure_load_progress();
  643. }
  644. return status;
  645. }
  646. Ref<Resource> ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  647. if (r_error) {
  648. *r_error = OK;
  649. }
  650. Ref<Resource> res;
  651. {
  652. MutexLock thread_load_lock(thread_load_mutex);
  653. if (!user_load_tokens.has(p_path)) {
  654. print_verbose("load_threaded_get(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  655. if (r_error) {
  656. *r_error = ERR_INVALID_PARAMETER;
  657. }
  658. return Ref<Resource>();
  659. }
  660. LoadToken *load_token = user_load_tokens[p_path];
  661. DEV_ASSERT(load_token->user_rc >= 1);
  662. // Support userland requesting on the main thread before the load is reported to be complete.
  663. if (Thread::is_main_thread() && !load_token->local_path.is_empty()) {
  664. ThreadLoadTask *load_task_ptr;
  665. if (load_token->task_if_unregistered) {
  666. load_task_ptr = load_token->task_if_unregistered;
  667. } else {
  668. if (!thread_load_tasks.has(load_token->local_path)) {
  669. print_error("Bug in ResourceLoader logic, please report.");
  670. if (r_error) {
  671. *r_error = ERR_BUG;
  672. }
  673. return Ref<Resource>();
  674. }
  675. load_task_ptr = &thread_load_tasks[load_token->local_path];
  676. }
  677. while (load_task_ptr->status == THREAD_LOAD_IN_PROGRESS) {
  678. thread_load_lock.temp_unlock();
  679. bool exit = !_ensure_load_progress();
  680. OS::get_singleton()->delay_usec(1000);
  681. thread_load_lock.temp_relock();
  682. if (exit) {
  683. break;
  684. }
  685. }
  686. }
  687. res = _load_complete_inner(*load_token, r_error, thread_load_lock);
  688. load_token->user_rc--;
  689. if (load_token->user_rc == 0) {
  690. load_token->user_path.clear();
  691. user_load_tokens.erase(p_path);
  692. if (load_token->unreference()) {
  693. memdelete(load_token);
  694. load_token = nullptr;
  695. }
  696. }
  697. }
  698. print_lt("GET: user load tokens: " + itos(user_load_tokens.size()));
  699. return res;
  700. }
  701. Ref<Resource> ResourceLoader::_load_complete(LoadToken &p_load_token, Error *r_error) {
  702. MutexLock thread_load_lock(thread_load_mutex);
  703. return _load_complete_inner(p_load_token, r_error, thread_load_lock);
  704. }
  705. void ResourceLoader::set_is_import_thread(bool p_import_thread) {
  706. import_thread = p_import_thread;
  707. }
  708. Ref<Resource> ResourceLoader::_load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock) {
  709. if (r_error) {
  710. *r_error = OK;
  711. }
  712. ThreadLoadTask *load_task_ptr = nullptr;
  713. if (p_load_token.task_if_unregistered) {
  714. load_task_ptr = p_load_token.task_if_unregistered;
  715. } else {
  716. if (!thread_load_tasks.has(p_load_token.local_path)) {
  717. if (r_error) {
  718. *r_error = ERR_BUG;
  719. }
  720. ERR_FAIL_V_MSG(Ref<Resource>(), "Bug in ResourceLoader logic, please report.");
  721. }
  722. ThreadLoadTask &load_task = thread_load_tasks[p_load_token.local_path];
  723. if (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  724. DEV_ASSERT((load_task.task_id == 0) != (load_task.thread_id == 0));
  725. if ((load_task.task_id != 0 && load_task.task_id == WorkerThreadPool::get_singleton()->get_caller_task_id()) ||
  726. (load_task.thread_id != 0 && load_task.thread_id == Thread::get_caller_id())) {
  727. // Load is in progress, but it's precisely this thread the one in charge.
  728. // That means this is a cyclic load.
  729. if (r_error) {
  730. *r_error = ERR_BUSY;
  731. }
  732. return Ref<Resource>();
  733. }
  734. bool loader_is_wtp = load_task.task_id != 0;
  735. if (loader_is_wtp) {
  736. // Loading thread is in the worker pool.
  737. p_thread_load_lock.temp_unlock();
  738. PREPARE_FOR_WTP_WAIT
  739. Error wait_err = WorkerThreadPool::get_singleton()->wait_for_task_completion(load_task.task_id);
  740. RESTORE_AFTER_WTP_WAIT
  741. DEV_ASSERT(!wait_err || wait_err == ERR_BUSY);
  742. if (wait_err == ERR_BUSY) {
  743. // The WorkerThreadPool has reported that the current task wants to await on an older one.
  744. // That't not allowed for safety, to avoid deadlocks. Fortunately, though, in the context of
  745. // resource loading that means that the task to wait for can be restarted here to break the
  746. // cycle, with as much recursion into this process as needed.
  747. // When the stack is eventually unrolled, the original load will have been notified to go on.
  748. load_task.load_token->reference();
  749. _run_load_task(&load_task);
  750. }
  751. p_thread_load_lock.temp_relock();
  752. load_task.awaited = true;
  753. // Mark nested loads with the same task id as awaited.
  754. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  755. if (E.value.task_id == load_task.task_id) {
  756. E.value.awaited = true;
  757. }
  758. }
  759. DEV_ASSERT(load_task.status == THREAD_LOAD_FAILED || load_task.status == THREAD_LOAD_LOADED);
  760. } else if (load_task.need_wait) {
  761. // Loading thread is main or user thread.
  762. if (!load_task.cond_var) {
  763. load_task.cond_var = memnew(ConditionVariable);
  764. }
  765. load_task.awaiters_count++;
  766. do {
  767. load_task.cond_var->wait(p_thread_load_lock);
  768. DEV_ASSERT(thread_load_tasks.has(p_load_token.local_path) && p_load_token.get_reference_count());
  769. } while (load_task.need_wait);
  770. load_task.awaiters_count--;
  771. if (load_task.awaiters_count == 0) {
  772. memdelete(load_task.cond_var);
  773. load_task.cond_var = nullptr;
  774. }
  775. DEV_ASSERT(load_task.status == THREAD_LOAD_FAILED || load_task.status == THREAD_LOAD_LOADED);
  776. }
  777. }
  778. if (cleaning_tasks) {
  779. load_task.resource = Ref<Resource>();
  780. load_task.error = FAILED;
  781. }
  782. load_task_ptr = &load_task;
  783. }
  784. p_thread_load_lock.temp_unlock();
  785. Ref<Resource> resource = load_task_ptr->resource;
  786. if (r_error) {
  787. *r_error = load_task_ptr->error;
  788. }
  789. if (resource.is_valid()) {
  790. if (curr_load_task) {
  791. // A task awaiting another => Let the awaiter accumulate the resource changed connections.
  792. DEV_ASSERT(curr_load_task != load_task_ptr);
  793. for (const ThreadLoadTask::ResourceChangedConnection &rcc : load_task_ptr->resource_changed_connections) {
  794. curr_load_task->resource_changed_connections.push_back(rcc);
  795. }
  796. } else {
  797. // A leaf task being awaited => Propagate the resource changed connections.
  798. if (Thread::is_main_thread()) {
  799. // On the main thread it's safe to migrate the connections to the standard signal mechanism.
  800. for (const ThreadLoadTask::ResourceChangedConnection &rcc : load_task_ptr->resource_changed_connections) {
  801. if (rcc.callable.is_valid()) {
  802. rcc.source->connect_changed(rcc.callable, rcc.flags);
  803. }
  804. }
  805. } else {
  806. // On non-main threads, we have to queue and call it done when processed.
  807. if (!load_task_ptr->resource_changed_connections.is_empty()) {
  808. for (const ThreadLoadTask::ResourceChangedConnection &rcc : load_task_ptr->resource_changed_connections) {
  809. if (rcc.callable.is_valid()) {
  810. MessageQueue::get_main_singleton()->push_callable(callable_mp(rcc.source, &Resource::connect_changed).bind(rcc.callable, rcc.flags));
  811. }
  812. }
  813. if (!import_thread) { // Main thread is blocked by initial resource reimport, do not wait.
  814. CoreBind::Semaphore done;
  815. MessageQueue::get_main_singleton()->push_callable(callable_mp(&done, &CoreBind::Semaphore::post).bind(1));
  816. done.wait();
  817. }
  818. }
  819. }
  820. }
  821. }
  822. p_thread_load_lock.temp_relock();
  823. return resource;
  824. }
  825. bool ResourceLoader::_ensure_load_progress() {
  826. // Some servers may need a new engine iteration to allow the load to progress.
  827. // Since the only known one is the rendering server (in single thread mode), let's keep it simple and just sync it.
  828. // This may be refactored in the future to support other servers and have less coupling.
  829. if (OS::get_singleton()->is_separate_thread_rendering_enabled()) {
  830. return false; // Not needed.
  831. }
  832. RenderingServer::get_singleton()->sync();
  833. return true;
  834. }
  835. void ResourceLoader::resource_changed_connect(Resource *p_source, const Callable &p_callable, uint32_t p_flags) {
  836. print_lt(vformat("%d\t%ud:%s\t" FUNCTION_STR "\t%d", Thread::get_caller_id(), p_source->get_instance_id(), p_source->get_class(), p_callable.get_object_id()));
  837. MutexLock lock(thread_load_mutex);
  838. for (const ThreadLoadTask::ResourceChangedConnection &rcc : curr_load_task->resource_changed_connections) {
  839. if (unlikely(rcc.source == p_source && rcc.callable == p_callable)) {
  840. return;
  841. }
  842. }
  843. ThreadLoadTask::ResourceChangedConnection rcc;
  844. rcc.source = p_source;
  845. rcc.callable = p_callable;
  846. rcc.flags = p_flags;
  847. curr_load_task->resource_changed_connections.push_back(rcc);
  848. }
  849. void ResourceLoader::resource_changed_disconnect(Resource *p_source, const Callable &p_callable) {
  850. print_lt(vformat("%d\t%ud:%s\t" FUNCTION_STR "t%d", Thread::get_caller_id(), p_source->get_instance_id(), p_source->get_class(), p_callable.get_object_id()));
  851. MutexLock lock(thread_load_mutex);
  852. for (uint32_t i = 0; i < curr_load_task->resource_changed_connections.size(); ++i) {
  853. const ThreadLoadTask::ResourceChangedConnection &rcc = curr_load_task->resource_changed_connections[i];
  854. if (unlikely(rcc.source == p_source && rcc.callable == p_callable)) {
  855. curr_load_task->resource_changed_connections.remove_at_unordered(i);
  856. return;
  857. }
  858. }
  859. }
  860. void ResourceLoader::resource_changed_emit(Resource *p_source) {
  861. print_lt(vformat("%d\t%ud:%s\t" FUNCTION_STR, Thread::get_caller_id(), p_source->get_instance_id(), p_source->get_class()));
  862. MutexLock lock(thread_load_mutex);
  863. for (const ThreadLoadTask::ResourceChangedConnection &rcc : curr_load_task->resource_changed_connections) {
  864. if (unlikely(rcc.source == p_source)) {
  865. rcc.callable.call();
  866. }
  867. }
  868. }
  869. Ref<Resource> ResourceLoader::ensure_resource_ref_override_for_outer_load(const String &p_path, const String &p_res_type) {
  870. ERR_FAIL_COND_V(load_nesting == 0, Ref<Resource>()); // It makes no sense to use this from nesting level 0.
  871. const String &local_path = _validate_local_path(p_path);
  872. HashMap<String, Ref<Resource>> &overrides = res_ref_overrides[load_nesting - 1];
  873. HashMap<String, Ref<Resource>>::Iterator E = overrides.find(local_path);
  874. if (E) {
  875. return E->value;
  876. } else {
  877. Object *obj = ClassDB::instantiate(p_res_type);
  878. ERR_FAIL_NULL_V(obj, Ref<Resource>());
  879. Ref<Resource> res(obj);
  880. if (res.is_null()) {
  881. memdelete(obj);
  882. ERR_FAIL_V(Ref<Resource>());
  883. }
  884. overrides[local_path] = res;
  885. return res;
  886. }
  887. }
  888. Ref<Resource> ResourceLoader::get_resource_ref_override(const String &p_path) {
  889. DEV_ASSERT(p_path == _validate_local_path(p_path));
  890. HashMap<int, HashMap<String, Ref<Resource>>>::Iterator E = res_ref_overrides.find(load_nesting);
  891. if (!E) {
  892. return nullptr;
  893. }
  894. HashMap<String, Ref<Resource>>::Iterator F = E->value.find(p_path);
  895. if (!F) {
  896. return nullptr;
  897. }
  898. return F->value;
  899. }
  900. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  901. String local_path = _validate_local_path(p_path);
  902. if (ResourceCache::has(local_path)) {
  903. return true; // If cached, it probably exists
  904. }
  905. bool xl_remapped = false;
  906. String path = _path_remap(local_path, &xl_remapped);
  907. // Try all loaders and pick the first match for the type hint
  908. for (int i = 0; i < loader_count; i++) {
  909. if (!loader[i]->recognize_path(path, p_type_hint)) {
  910. continue;
  911. }
  912. if (loader[i]->exists(path)) {
  913. return true;
  914. }
  915. }
  916. return false;
  917. }
  918. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  919. ERR_FAIL_COND(p_format_loader.is_null());
  920. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  921. if (p_at_front) {
  922. for (int i = loader_count; i > 0; i--) {
  923. loader[i] = loader[i - 1];
  924. }
  925. loader[0] = p_format_loader;
  926. loader_count++;
  927. } else {
  928. loader[loader_count++] = p_format_loader;
  929. }
  930. }
  931. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  932. ERR_FAIL_COND(p_format_loader.is_null());
  933. // Find loader
  934. int i = 0;
  935. for (; i < loader_count; ++i) {
  936. if (loader[i] == p_format_loader) {
  937. break;
  938. }
  939. }
  940. ERR_FAIL_COND(i >= loader_count); // Not found
  941. // Shift next loaders up
  942. for (; i < loader_count - 1; ++i) {
  943. loader[i] = loader[i + 1];
  944. }
  945. loader[loader_count - 1].unref();
  946. --loader_count;
  947. }
  948. String ResourceLoader::get_import_group_file(const String &p_path) {
  949. String local_path = _path_remap(_validate_local_path(p_path));
  950. for (int i = 0; i < loader_count; i++) {
  951. if (!loader[i]->recognize_path(local_path)) {
  952. continue;
  953. }
  954. return loader[i]->get_import_group_file(p_path);
  955. }
  956. return String(); //not found
  957. }
  958. bool ResourceLoader::is_import_valid(const String &p_path) {
  959. String local_path = _path_remap(_validate_local_path(p_path));
  960. for (int i = 0; i < loader_count; i++) {
  961. if (!loader[i]->recognize_path(local_path)) {
  962. continue;
  963. }
  964. return loader[i]->is_import_valid(p_path);
  965. }
  966. return false; //not found
  967. }
  968. bool ResourceLoader::is_imported(const String &p_path) {
  969. String local_path = _path_remap(_validate_local_path(p_path));
  970. for (int i = 0; i < loader_count; i++) {
  971. if (!loader[i]->recognize_path(local_path)) {
  972. continue;
  973. }
  974. return loader[i]->is_imported(p_path);
  975. }
  976. return false; //not found
  977. }
  978. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  979. String local_path = _path_remap(_validate_local_path(p_path));
  980. for (int i = 0; i < loader_count; i++) {
  981. if (!loader[i]->recognize_path(local_path)) {
  982. continue;
  983. }
  984. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  985. }
  986. }
  987. Error ResourceLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  988. String local_path = _path_remap(_validate_local_path(p_path));
  989. for (int i = 0; i < loader_count; i++) {
  990. if (!loader[i]->recognize_path(local_path)) {
  991. continue;
  992. }
  993. return loader[i]->rename_dependencies(local_path, p_map);
  994. }
  995. return OK; // ??
  996. }
  997. void ResourceLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  998. String local_path = _validate_local_path(p_path);
  999. for (int i = 0; i < loader_count; i++) {
  1000. if (!loader[i]->recognize_path(local_path)) {
  1001. continue;
  1002. }
  1003. return loader[i]->get_classes_used(p_path, r_classes);
  1004. }
  1005. }
  1006. String ResourceLoader::get_resource_type(const String &p_path) {
  1007. String local_path = _validate_local_path(p_path);
  1008. for (int i = 0; i < loader_count; i++) {
  1009. String result = loader[i]->get_resource_type(local_path);
  1010. if (!result.is_empty()) {
  1011. return result;
  1012. }
  1013. }
  1014. return "";
  1015. }
  1016. String ResourceLoader::get_resource_script_class(const String &p_path) {
  1017. String local_path = _validate_local_path(p_path);
  1018. for (int i = 0; i < loader_count; i++) {
  1019. String result = loader[i]->get_resource_script_class(local_path);
  1020. if (!result.is_empty()) {
  1021. return result;
  1022. }
  1023. }
  1024. return "";
  1025. }
  1026. ResourceUID::ID ResourceLoader::get_resource_uid(const String &p_path) {
  1027. const String local_path = _validate_local_path(p_path);
  1028. if (!Engine::get_singleton()->is_editor_hint()) {
  1029. return ResourceUID::get_singleton()->get_path_id(local_path);
  1030. }
  1031. for (int i = 0; i < loader_count; i++) {
  1032. ResourceUID::ID id = loader[i]->get_resource_uid(local_path);
  1033. if (id != ResourceUID::INVALID_ID) {
  1034. return id;
  1035. }
  1036. }
  1037. return ResourceUID::INVALID_ID;
  1038. }
  1039. bool ResourceLoader::should_create_uid_file(const String &p_path) {
  1040. const String local_path = _validate_local_path(p_path);
  1041. if (FileAccess::exists(local_path + ".uid")) {
  1042. return false;
  1043. }
  1044. for (int i = 0; i < loader_count; i++) {
  1045. if (loader[i]->recognize_path(local_path)) {
  1046. return !loader[i]->has_custom_uid_support();
  1047. }
  1048. }
  1049. return false;
  1050. }
  1051. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  1052. String new_path = p_path;
  1053. if (translation_remaps.has(p_path)) {
  1054. // translation_remaps has the following format:
  1055. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  1056. // To find the path of the remapped resource, we extract the locale name after
  1057. // the last ':' to match the project locale.
  1058. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  1059. String locale = TranslationServer::get_singleton()->get_locale();
  1060. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, vformat("Could not remap path '%s' for translation as configured locale '%s' is invalid.", p_path, locale));
  1061. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  1062. int best_score = 0;
  1063. for (int i = 0; i < res_remaps.size(); i++) {
  1064. int split = res_remaps[i].rfind_char(':');
  1065. if (split == -1) {
  1066. continue;
  1067. }
  1068. String l = res_remaps[i].substr(split + 1).strip_edges();
  1069. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  1070. if (score > 0 && score >= best_score) {
  1071. new_path = res_remaps[i].left(split);
  1072. best_score = score;
  1073. if (score == 10) {
  1074. break; // Exact match, skip the rest.
  1075. }
  1076. }
  1077. }
  1078. if (r_translation_remapped) {
  1079. *r_translation_remapped = true;
  1080. }
  1081. // Fallback to p_path if new_path does not exist.
  1082. if (!FileAccess::exists(new_path + ".import") &&
  1083. !FileAccess::exists(new_path + ".remap") &&
  1084. !FileAccess::exists(new_path)) {
  1085. WARN_PRINT(vformat("Translation remap '%s' does not exist. Falling back to '%s'.", new_path, p_path));
  1086. new_path = p_path;
  1087. }
  1088. }
  1089. // Usually, there's no remap file and FileAccess::exists() is faster than FileAccess::open().
  1090. new_path = ResourceUID::ensure_path(new_path);
  1091. if (FileAccess::exists(new_path + ".remap")) {
  1092. Error err;
  1093. Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
  1094. if (f.is_valid()) {
  1095. VariantParser::StreamFile stream;
  1096. stream.f = f;
  1097. String assign;
  1098. Variant value;
  1099. VariantParser::Tag next_tag;
  1100. int lines = 0;
  1101. String error_text;
  1102. while (true) {
  1103. assign = Variant();
  1104. next_tag.fields.clear();
  1105. next_tag.name = String();
  1106. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  1107. if (err == ERR_FILE_EOF) {
  1108. break;
  1109. } else if (err != OK) {
  1110. ERR_PRINT(vformat("Parse error: %s.remap:%d error: %s.", p_path, lines, error_text));
  1111. break;
  1112. }
  1113. if (assign == "path") {
  1114. new_path = value;
  1115. break;
  1116. } else if (next_tag.name != "remap") {
  1117. break;
  1118. }
  1119. }
  1120. }
  1121. }
  1122. return new_path;
  1123. }
  1124. String ResourceLoader::import_remap(const String &p_path) {
  1125. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  1126. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  1127. }
  1128. return p_path;
  1129. }
  1130. String ResourceLoader::path_remap(const String &p_path) {
  1131. return _path_remap(p_path);
  1132. }
  1133. void ResourceLoader::reload_translation_remaps() {
  1134. List<Resource *> to_reload;
  1135. {
  1136. MutexLock lock(ResourceCache::lock);
  1137. SelfList<Resource> *E = remapped_list.first();
  1138. while (E) {
  1139. to_reload.push_back(E->self());
  1140. E = E->next();
  1141. }
  1142. }
  1143. //now just make sure to not delete any of these resources while changing locale..
  1144. while (to_reload.front()) {
  1145. to_reload.front()->get()->reload_from_file();
  1146. to_reload.pop_front();
  1147. }
  1148. }
  1149. void ResourceLoader::load_translation_remaps() {
  1150. if (!ProjectSettings::get_singleton()->has_setting("internationalization/locale/translation_remaps")) {
  1151. return;
  1152. }
  1153. Dictionary remaps = GLOBAL_GET("internationalization/locale/translation_remaps");
  1154. for (const KeyValue<Variant, Variant> &kv : remaps) {
  1155. Array langs = kv.value;
  1156. Vector<String> lang_remaps;
  1157. lang_remaps.resize(langs.size());
  1158. String *lang_remaps_ptrw = lang_remaps.ptrw();
  1159. for (const Variant &lang : langs) {
  1160. *lang_remaps_ptrw++ = lang;
  1161. }
  1162. translation_remaps[String(kv.key)] = lang_remaps;
  1163. }
  1164. }
  1165. void ResourceLoader::clear_translation_remaps() {
  1166. translation_remaps.clear();
  1167. while (remapped_list.first() != nullptr) {
  1168. remapped_list.remove(remapped_list.first());
  1169. }
  1170. }
  1171. void ResourceLoader::clear_thread_load_tasks() {
  1172. // Bring the thing down as quickly as possible without causing deadlocks or leaks.
  1173. MutexLock thread_load_lock(thread_load_mutex);
  1174. cleaning_tasks = true;
  1175. while (true) {
  1176. bool none_running = true;
  1177. if (thread_load_tasks.size()) {
  1178. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  1179. if (E.value.status == THREAD_LOAD_IN_PROGRESS) {
  1180. if (E.value.cond_var && E.value.need_wait) {
  1181. E.value.cond_var->notify_all();
  1182. }
  1183. E.value.need_wait = false;
  1184. none_running = false;
  1185. }
  1186. }
  1187. }
  1188. if (none_running) {
  1189. break;
  1190. }
  1191. thread_load_lock.temp_unlock();
  1192. OS::get_singleton()->delay_usec(1000);
  1193. thread_load_lock.temp_relock();
  1194. }
  1195. while (user_load_tokens.begin()) {
  1196. LoadToken *user_token = user_load_tokens.begin()->value;
  1197. user_load_tokens.remove(user_load_tokens.begin());
  1198. DEV_ASSERT(user_token->user_rc > 0 && !user_token->user_path.is_empty());
  1199. user_token->user_path.clear();
  1200. user_token->user_rc = 0;
  1201. user_token->unreference();
  1202. }
  1203. thread_load_tasks.clear();
  1204. cleaning_tasks = false;
  1205. }
  1206. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  1207. _loaded_callback = p_callback;
  1208. }
  1209. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  1210. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(const String &path) {
  1211. for (int i = 0; i < loader_count; ++i) {
  1212. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  1213. return loader[i];
  1214. }
  1215. }
  1216. return Ref<ResourceFormatLoader>();
  1217. }
  1218. bool ResourceLoader::add_custom_resource_format_loader(const String &script_path) {
  1219. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  1220. return false;
  1221. }
  1222. Ref<Resource> res = ResourceLoader::load(script_path);
  1223. ERR_FAIL_COND_V(res.is_null(), false);
  1224. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  1225. Ref<Script> s = res;
  1226. StringName ibt = s->get_instance_base_type();
  1227. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  1228. ERR_FAIL_COND_V_MSG(!valid_type, false, vformat("Failed to add a custom resource loader, script '%s' does not inherit 'ResourceFormatLoader'.", script_path));
  1229. Object *obj = ClassDB::instantiate(ibt);
  1230. ERR_FAIL_NULL_V_MSG(obj, false, vformat("Failed to add a custom resource loader, cannot instantiate '%s'.", ibt));
  1231. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  1232. crl->set_script(s);
  1233. ResourceLoader::add_resource_format_loader(crl);
  1234. return true;
  1235. }
  1236. void ResourceLoader::set_create_missing_resources_if_class_unavailable(bool p_enable) {
  1237. create_missing_resources_if_class_unavailable = p_enable;
  1238. }
  1239. void ResourceLoader::add_custom_loaders() {
  1240. // Custom loaders registration exploits global class names
  1241. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  1242. LocalVector<StringName> global_classes;
  1243. ScriptServer::get_global_class_list(global_classes);
  1244. for (const StringName &class_name : global_classes) {
  1245. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  1246. if (base_class == custom_loader_base_class) {
  1247. String path = ScriptServer::get_global_class_path(class_name);
  1248. add_custom_resource_format_loader(path);
  1249. }
  1250. }
  1251. }
  1252. void ResourceLoader::remove_custom_loaders() {
  1253. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  1254. for (int i = 0; i < loader_count; ++i) {
  1255. if (loader[i]->get_script_instance()) {
  1256. custom_loaders.push_back(loader[i]);
  1257. }
  1258. }
  1259. for (int i = 0; i < custom_loaders.size(); ++i) {
  1260. remove_resource_format_loader(custom_loaders[i]);
  1261. }
  1262. }
  1263. bool ResourceLoader::is_cleaning_tasks() {
  1264. MutexLock lock(thread_load_mutex);
  1265. return cleaning_tasks;
  1266. }
  1267. Vector<String> ResourceLoader::list_directory(const String &p_directory) {
  1268. RBSet<String> files_found;
  1269. Ref<DirAccess> dir = DirAccess::open(p_directory);
  1270. if (dir.is_null()) {
  1271. return Vector<String>();
  1272. }
  1273. Error err = dir->list_dir_begin();
  1274. if (err != OK) {
  1275. return Vector<String>();
  1276. }
  1277. String d = dir->get_next();
  1278. while (!d.is_empty()) {
  1279. bool recognized = false;
  1280. if (dir->current_is_dir()) {
  1281. if (d != "." && d != "..") {
  1282. d += "/";
  1283. recognized = true;
  1284. }
  1285. } else {
  1286. if (d.ends_with(".import") || d.ends_with(".remap") || d.ends_with(".uid")) {
  1287. d = d.substr(0, d.rfind_char('.'));
  1288. }
  1289. if (d.ends_with(".gdc")) {
  1290. d = d.substr(0, d.rfind_char('.'));
  1291. d += ".gd";
  1292. }
  1293. const String full_path = p_directory.path_join(d);
  1294. // Try all loaders and pick the first match for the type hint.
  1295. for (int i = 0; i < loader_count; i++) {
  1296. if (loader[i]->recognize_path(full_path)) {
  1297. recognized = true;
  1298. break;
  1299. }
  1300. }
  1301. }
  1302. if (recognized) {
  1303. files_found.insert(d);
  1304. }
  1305. d = dir->get_next();
  1306. }
  1307. Vector<String> ret;
  1308. for (const String &f : files_found) {
  1309. ret.push_back(f);
  1310. }
  1311. return ret;
  1312. }
  1313. void ResourceLoader::initialize() {}
  1314. void ResourceLoader::finalize() {}
  1315. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  1316. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  1317. bool ResourceLoader::create_missing_resources_if_class_unavailable = false;
  1318. bool ResourceLoader::abort_on_missing_resource = true;
  1319. bool ResourceLoader::timestamp_on_load = false;
  1320. thread_local bool ResourceLoader::import_thread = false;
  1321. thread_local int ResourceLoader::load_nesting = 0;
  1322. thread_local Vector<String> ResourceLoader::load_paths_stack;
  1323. thread_local HashMap<int, HashMap<String, Ref<Resource>>> ResourceLoader::res_ref_overrides;
  1324. thread_local ResourceLoader::ThreadLoadTask *ResourceLoader::curr_load_task = nullptr;
  1325. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> &_get_res_loader_mutex() {
  1326. return ResourceLoader::thread_load_mutex;
  1327. }
  1328. template <>
  1329. thread_local SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::TLSData SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::tls_data(_get_res_loader_mutex());
  1330. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> ResourceLoader::thread_load_mutex;
  1331. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  1332. bool ResourceLoader::cleaning_tasks = false;
  1333. HashMap<String, ResourceLoader::LoadToken *> ResourceLoader::user_load_tokens;
  1334. SelfList<Resource>::List ResourceLoader::remapped_list;
  1335. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  1336. ResourceLoaderImport ResourceLoader::import = nullptr;