resource_loader.cpp 51 KB

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