Debian Codegraph @

core/io/resource_loader.cpp

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