resource_loader.cpp 48 KB

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