resource_loader.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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/io/file_access.h"
  33. #include "core/io/resource_importer.h"
  34. #include "core/object/script_language.h"
  35. #include "core/os/condition_variable.h"
  36. #include "core/os/os.h"
  37. #include "core/string/print_string.h"
  38. #include "core/string/translation.h"
  39. #include "core/variant/variant_parser.h"
  40. #ifdef DEBUG_LOAD_THREADED
  41. #define print_lt(m_text) print_line(m_text)
  42. #else
  43. #define print_lt(m_text)
  44. #endif
  45. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  46. int ResourceLoader::loader_count = 0;
  47. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  48. bool ret = false;
  49. if (GDVIRTUAL_CALL(_recognize_path, p_path, p_for_type, ret)) {
  50. return ret;
  51. }
  52. String extension = p_path.get_extension();
  53. List<String> extensions;
  54. if (p_for_type.is_empty()) {
  55. get_recognized_extensions(&extensions);
  56. } else {
  57. get_recognized_extensions_for_type(p_for_type, &extensions);
  58. }
  59. for (const String &E : extensions) {
  60. if (E.nocasecmp_to(extension) == 0) {
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  67. bool success = false;
  68. GDVIRTUAL_CALL(_handles_type, p_type, success);
  69. return success;
  70. }
  71. void ResourceFormatLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  72. Vector<String> ret;
  73. if (GDVIRTUAL_CALL(_get_classes_used, p_path, ret)) {
  74. for (int i = 0; i < ret.size(); i++) {
  75. r_classes->insert(ret[i]);
  76. }
  77. return;
  78. }
  79. String res = get_resource_type(p_path);
  80. if (!res.is_empty()) {
  81. r_classes->insert(res);
  82. }
  83. }
  84. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  85. String ret;
  86. GDVIRTUAL_CALL(_get_resource_type, p_path, ret);
  87. return ret;
  88. }
  89. String ResourceFormatLoader::get_resource_script_class(const String &p_path) const {
  90. String ret;
  91. GDVIRTUAL_CALL(_get_resource_script_class, p_path, ret);
  92. return ret;
  93. }
  94. ResourceUID::ID ResourceFormatLoader::get_resource_uid(const String &p_path) const {
  95. int64_t uid = ResourceUID::INVALID_ID;
  96. GDVIRTUAL_CALL(_get_resource_uid, p_path, uid);
  97. return uid;
  98. }
  99. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  100. if (p_type.is_empty() || handles_type(p_type)) {
  101. get_recognized_extensions(p_extensions);
  102. }
  103. }
  104. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  105. for (int i = 0; i < loader_count; i++) {
  106. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  107. }
  108. }
  109. bool ResourceFormatLoader::exists(const String &p_path) const {
  110. bool success = false;
  111. if (GDVIRTUAL_CALL(_exists, p_path, success)) {
  112. return success;
  113. }
  114. return FileAccess::exists(p_path); // By default just check file.
  115. }
  116. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  117. PackedStringArray exts;
  118. if (GDVIRTUAL_CALL(_get_recognized_extensions, exts)) {
  119. const String *r = exts.ptr();
  120. for (int i = 0; i < exts.size(); ++i) {
  121. p_extensions->push_back(r[i]);
  122. }
  123. }
  124. }
  125. 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) {
  126. Variant res;
  127. if (GDVIRTUAL_CALL(_load, p_path, p_original_path, p_use_sub_threads, p_cache_mode, res)) {
  128. if (res.get_type() == Variant::INT) { // Error code, abort.
  129. if (r_error) {
  130. *r_error = (Error)res.operator int64_t();
  131. }
  132. return Ref<Resource>();
  133. } else { // Success, pass on result.
  134. if (r_error) {
  135. *r_error = OK;
  136. }
  137. return res;
  138. }
  139. }
  140. ERR_FAIL_V_MSG(Ref<Resource>(), "Failed to load resource '" + p_path + "'. ResourceFormatLoader::load was not implemented for this resource type.");
  141. }
  142. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  143. PackedStringArray deps;
  144. if (GDVIRTUAL_CALL(_get_dependencies, p_path, p_add_types, deps)) {
  145. const String *r = deps.ptr();
  146. for (int i = 0; i < deps.size(); ++i) {
  147. p_dependencies->push_back(r[i]);
  148. }
  149. }
  150. }
  151. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  152. Dictionary deps_dict;
  153. for (KeyValue<String, String> E : p_map) {
  154. deps_dict[E.key] = E.value;
  155. }
  156. Error err = OK;
  157. GDVIRTUAL_CALL(_rename_dependencies, p_path, deps_dict, err);
  158. return err;
  159. }
  160. void ResourceFormatLoader::_bind_methods() {
  161. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE);
  162. BIND_ENUM_CONSTANT(CACHE_MODE_REUSE);
  163. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
  164. GDVIRTUAL_BIND(_get_recognized_extensions);
  165. GDVIRTUAL_BIND(_recognize_path, "path", "type");
  166. GDVIRTUAL_BIND(_handles_type, "type");
  167. GDVIRTUAL_BIND(_get_resource_type, "path");
  168. GDVIRTUAL_BIND(_get_resource_script_class, "path");
  169. GDVIRTUAL_BIND(_get_resource_uid, "path");
  170. GDVIRTUAL_BIND(_get_dependencies, "path", "add_types");
  171. GDVIRTUAL_BIND(_rename_dependencies, "path", "renames");
  172. GDVIRTUAL_BIND(_exists, "path");
  173. GDVIRTUAL_BIND(_get_classes_used, "path");
  174. GDVIRTUAL_BIND(_load, "path", "original_path", "use_sub_threads", "cache_mode");
  175. }
  176. ///////////////////////////////////
  177. // This should be robust enough to be called redundantly without issues.
  178. void ResourceLoader::LoadToken::clear() {
  179. thread_load_mutex.lock();
  180. WorkerThreadPool::TaskID task_to_await = 0;
  181. if (!local_path.is_empty()) { // Empty is used for the special case where the load task is not registered.
  182. DEV_ASSERT(thread_load_tasks.has(local_path));
  183. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  184. if (!load_task.awaited) {
  185. task_to_await = load_task.task_id;
  186. load_task.awaited = true;
  187. }
  188. thread_load_tasks.erase(local_path);
  189. local_path.clear();
  190. }
  191. if (!user_path.is_empty()) {
  192. DEV_ASSERT(user_load_tokens.has(user_path));
  193. user_load_tokens.erase(user_path);
  194. user_path.clear();
  195. }
  196. thread_load_mutex.unlock();
  197. // If task is unused, await it here, locally, now the token data is consistent.
  198. if (task_to_await) {
  199. WorkerThreadPool::get_singleton()->wait_for_task_completion(task_to_await);
  200. }
  201. }
  202. ResourceLoader::LoadToken::~LoadToken() {
  203. clear();
  204. }
  205. 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) {
  206. load_nesting++;
  207. if (load_paths_stack->size()) {
  208. thread_load_mutex.lock();
  209. HashMap<String, ThreadLoadTask>::Iterator E = thread_load_tasks.find(load_paths_stack->get(load_paths_stack->size() - 1));
  210. if (E) {
  211. E->value.sub_tasks.insert(p_path);
  212. }
  213. thread_load_mutex.unlock();
  214. }
  215. load_paths_stack->push_back(p_path);
  216. // Try all loaders and pick the first match for the type hint
  217. bool found = false;
  218. Ref<Resource> res;
  219. for (int i = 0; i < loader_count; i++) {
  220. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  221. continue;
  222. }
  223. found = true;
  224. res = loader[i]->load(p_path, !p_original_path.is_empty() ? p_original_path : p_path, r_error, p_use_sub_threads, r_progress, p_cache_mode);
  225. if (!res.is_null()) {
  226. break;
  227. }
  228. }
  229. load_paths_stack->resize(load_paths_stack->size() - 1);
  230. load_nesting--;
  231. if (!res.is_null()) {
  232. return res;
  233. }
  234. ERR_FAIL_COND_V_MSG(found, Ref<Resource>(),
  235. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  236. #ifdef TOOLS_ENABLED
  237. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  238. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), Ref<Resource>(), vformat("Resource file not found: %s (expected type: %s)", p_path, p_type_hint));
  239. #endif
  240. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("No loader found for resource: %s (expected type: %s)", p_path, p_type_hint));
  241. }
  242. void ResourceLoader::_thread_load_function(void *p_userdata) {
  243. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  244. thread_load_mutex.lock();
  245. caller_task_id = load_task.task_id;
  246. if (cleaning_tasks) {
  247. load_task.status = THREAD_LOAD_FAILED;
  248. thread_load_mutex.unlock();
  249. return;
  250. }
  251. thread_load_mutex.unlock();
  252. // Thread-safe either if it's the current thread or a brand new one.
  253. CallQueue *mq_override = nullptr;
  254. if (load_nesting == 0) {
  255. load_paths_stack = memnew(Vector<String>);
  256. if (!load_task.dependent_path.is_empty()) {
  257. load_paths_stack->push_back(load_task.dependent_path);
  258. }
  259. if (!Thread::is_main_thread()) {
  260. mq_override = memnew(CallQueue);
  261. MessageQueue::set_thread_singleton_override(mq_override);
  262. set_current_thread_safe_for_nodes(true);
  263. }
  264. } else {
  265. DEV_ASSERT(load_task.dependent_path.is_empty());
  266. }
  267. // --
  268. if (!Thread::is_main_thread()) {
  269. set_current_thread_safe_for_nodes(true);
  270. }
  271. Ref<Resource> res = _load(load_task.remapped_path, load_task.remapped_path != load_task.local_path ? load_task.local_path : String(), load_task.type_hint, load_task.cache_mode, &load_task.error, load_task.use_sub_threads, &load_task.progress);
  272. if (mq_override) {
  273. mq_override->flush();
  274. }
  275. thread_load_mutex.lock();
  276. load_task.resource = res;
  277. load_task.progress = 1.0; //it was fully loaded at this point, so force progress to 1.0
  278. if (load_task.error != OK) {
  279. load_task.status = THREAD_LOAD_FAILED;
  280. } else {
  281. load_task.status = THREAD_LOAD_LOADED;
  282. }
  283. if (load_task.cond_var) {
  284. load_task.cond_var->notify_all();
  285. memdelete(load_task.cond_var);
  286. load_task.cond_var = nullptr;
  287. }
  288. if (load_task.resource.is_valid()) {
  289. if (load_task.cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  290. load_task.resource->set_path(load_task.local_path);
  291. } else if (!load_task.local_path.is_resource_file()) {
  292. load_task.resource->set_path_cache(load_task.local_path);
  293. }
  294. if (load_task.xl_remapped) {
  295. load_task.resource->set_as_translation_remapped(true);
  296. }
  297. #ifdef TOOLS_ENABLED
  298. load_task.resource->set_edited(false);
  299. if (timestamp_on_load) {
  300. uint64_t mt = FileAccess::get_modified_time(load_task.remapped_path);
  301. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  302. load_task.resource->set_last_modified_time(mt);
  303. }
  304. #endif
  305. if (_loaded_callback) {
  306. _loaded_callback(load_task.resource, load_task.local_path);
  307. }
  308. }
  309. thread_load_mutex.unlock();
  310. if (load_nesting == 0) {
  311. if (mq_override) {
  312. memdelete(mq_override);
  313. }
  314. memdelete(load_paths_stack);
  315. }
  316. }
  317. static String _validate_local_path(const String &p_path) {
  318. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(p_path);
  319. if (uid != ResourceUID::INVALID_ID) {
  320. return ResourceUID::get_singleton()->get_id_path(uid);
  321. } else if (p_path.is_relative_path()) {
  322. return ("res://" + p_path).simplify_path();
  323. } else {
  324. return ProjectSettings::get_singleton()->localize_path(p_path);
  325. }
  326. }
  327. Error ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads, ResourceFormatLoader::CacheMode p_cache_mode) {
  328. thread_load_mutex.lock();
  329. if (user_load_tokens.has(p_path)) {
  330. print_verbose("load_threaded_request(): Another threaded load for resource path '" + p_path + "' has been initiated. Not an error.");
  331. user_load_tokens[p_path]->reference(); // Additional request.
  332. thread_load_mutex.unlock();
  333. return OK;
  334. }
  335. user_load_tokens[p_path] = nullptr;
  336. thread_load_mutex.unlock();
  337. 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);
  338. if (token.is_valid()) {
  339. thread_load_mutex.lock();
  340. token->user_path = p_path;
  341. token->reference(); // First request.
  342. user_load_tokens[p_path] = token.ptr();
  343. print_lt("REQUEST: user load tokens: " + itos(user_load_tokens.size()));
  344. thread_load_mutex.unlock();
  345. return OK;
  346. } else {
  347. return FAILED;
  348. }
  349. }
  350. Ref<Resource> ResourceLoader::load(const String &p_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error) {
  351. if (r_error) {
  352. *r_error = OK;
  353. }
  354. Ref<LoadToken> load_token = _load_start(p_path, p_type_hint, LOAD_THREAD_FROM_CURRENT, p_cache_mode);
  355. if (!load_token.is_valid()) {
  356. if (r_error) {
  357. *r_error = FAILED;
  358. }
  359. return Ref<Resource>();
  360. }
  361. Ref<Resource> res = _load_complete(*load_token.ptr(), r_error);
  362. return res;
  363. }
  364. Ref<ResourceLoader::LoadToken> ResourceLoader::_load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode) {
  365. String local_path = _validate_local_path(p_path);
  366. Ref<LoadToken> load_token;
  367. bool must_not_register = false;
  368. ThreadLoadTask unregistered_load_task; // Once set, must be valid up to the call to do the load.
  369. ThreadLoadTask *load_task_ptr = nullptr;
  370. bool run_on_current_thread = false;
  371. {
  372. MutexLock thread_load_lock(thread_load_mutex);
  373. if (thread_load_tasks.has(local_path)) {
  374. load_token = Ref<LoadToken>(thread_load_tasks[local_path].load_token);
  375. if (!load_token.is_valid()) {
  376. // The token is dying (reached 0 on another thread).
  377. // Ensure it's killed now so the path can be safely reused right away.
  378. thread_load_tasks[local_path].load_token->clear();
  379. } else {
  380. if (p_cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  381. return load_token;
  382. }
  383. }
  384. }
  385. load_token.instantiate();
  386. load_token->local_path = local_path;
  387. //create load task
  388. {
  389. ThreadLoadTask load_task;
  390. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  391. load_task.load_token = load_token.ptr();
  392. load_task.local_path = local_path;
  393. load_task.type_hint = p_type_hint;
  394. load_task.cache_mode = p_cache_mode;
  395. load_task.use_sub_threads = p_thread_mode == LOAD_THREAD_DISTRIBUTE;
  396. if (p_cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  397. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  398. if (existing.is_valid()) {
  399. //referencing is fine
  400. load_task.resource = existing;
  401. load_task.status = THREAD_LOAD_LOADED;
  402. load_task.progress = 1.0;
  403. thread_load_tasks[local_path] = load_task;
  404. return load_token;
  405. }
  406. }
  407. // If we want to ignore cache, but there's another task loading it, we can't add this one to the map and we also have to finish unconditionally synchronously.
  408. must_not_register = thread_load_tasks.has(local_path) && p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE;
  409. if (must_not_register) {
  410. load_token->local_path.clear();
  411. unregistered_load_task = load_task;
  412. } else {
  413. thread_load_tasks[local_path] = load_task;
  414. }
  415. load_task_ptr = must_not_register ? &unregistered_load_task : &thread_load_tasks[local_path];
  416. }
  417. run_on_current_thread = must_not_register || p_thread_mode == LOAD_THREAD_FROM_CURRENT;
  418. if (run_on_current_thread) {
  419. load_task_ptr->thread_id = Thread::get_caller_id();
  420. } else {
  421. load_task_ptr->task_id = WorkerThreadPool::get_singleton()->add_native_task(&ResourceLoader::_thread_load_function, load_task_ptr);
  422. }
  423. }
  424. if (run_on_current_thread) {
  425. _thread_load_function(load_task_ptr);
  426. if (must_not_register) {
  427. load_token->res_if_unregistered = load_task_ptr->resource;
  428. }
  429. }
  430. return load_token;
  431. }
  432. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  433. if (thread_load_tasks.has(p_path)) {
  434. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  435. float current_progress = 0.0;
  436. int dep_count = load_task.sub_tasks.size();
  437. if (dep_count > 0) {
  438. for (const String &E : load_task.sub_tasks) {
  439. current_progress += _dependency_get_progress(E);
  440. }
  441. current_progress /= float(dep_count);
  442. current_progress *= 0.5;
  443. current_progress += load_task.progress * 0.5;
  444. } else {
  445. current_progress = load_task.progress;
  446. }
  447. load_task.max_reported_progress = MAX(load_task.max_reported_progress, current_progress);
  448. return load_task.max_reported_progress;
  449. } else {
  450. return 1.0; //assume finished loading it so it no longer exists
  451. }
  452. }
  453. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  454. MutexLock thread_load_lock(thread_load_mutex);
  455. if (!user_load_tokens.has(p_path)) {
  456. print_verbose("load_threaded_get_status(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  457. return THREAD_LOAD_INVALID_RESOURCE;
  458. }
  459. String local_path = _validate_local_path(p_path);
  460. if (!thread_load_tasks.has(local_path)) {
  461. #ifdef DEV_ENABLED
  462. CRASH_NOW();
  463. #endif
  464. // On non-dev, be defensive and at least avoid crashing (at this point at least).
  465. return THREAD_LOAD_INVALID_RESOURCE;
  466. }
  467. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  468. ThreadLoadStatus status;
  469. status = load_task.status;
  470. if (r_progress) {
  471. *r_progress = _dependency_get_progress(local_path);
  472. }
  473. return status;
  474. }
  475. Ref<Resource> ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  476. if (r_error) {
  477. *r_error = OK;
  478. }
  479. Ref<Resource> res;
  480. {
  481. MutexLock thread_load_lock(thread_load_mutex);
  482. if (!user_load_tokens.has(p_path)) {
  483. print_verbose("load_threaded_get(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  484. if (r_error) {
  485. *r_error = ERR_INVALID_PARAMETER;
  486. }
  487. return Ref<Resource>();
  488. }
  489. LoadToken *load_token = user_load_tokens[p_path];
  490. if (!load_token) {
  491. // This happens if requested from one thread and rapidly querying from another.
  492. if (r_error) {
  493. *r_error = ERR_BUSY;
  494. }
  495. return Ref<Resource>();
  496. }
  497. res = _load_complete_inner(*load_token, r_error, thread_load_lock);
  498. if (load_token->unreference()) {
  499. memdelete(load_token);
  500. }
  501. }
  502. print_lt("GET: user load tokens: " + itos(user_load_tokens.size()));
  503. return res;
  504. }
  505. Ref<Resource> ResourceLoader::_load_complete(LoadToken &p_load_token, Error *r_error) {
  506. MutexLock thread_load_lock(thread_load_mutex);
  507. return _load_complete_inner(p_load_token, r_error, thread_load_lock);
  508. }
  509. Ref<Resource> ResourceLoader::_load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock) {
  510. if (r_error) {
  511. *r_error = OK;
  512. }
  513. if (!p_load_token.local_path.is_empty()) {
  514. if (!thread_load_tasks.has(p_load_token.local_path)) {
  515. #ifdef DEV_ENABLED
  516. CRASH_NOW();
  517. #endif
  518. // On non-dev, be defensive and at least avoid crashing (at this point at least).
  519. if (r_error) {
  520. *r_error = ERR_BUG;
  521. }
  522. return Ref<Resource>();
  523. }
  524. ThreadLoadTask &load_task = thread_load_tasks[p_load_token.local_path];
  525. if (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  526. DEV_ASSERT((load_task.task_id == 0) != (load_task.thread_id == 0));
  527. if ((load_task.task_id != 0 && load_task.task_id == caller_task_id) ||
  528. (load_task.thread_id != 0 && load_task.thread_id == Thread::get_caller_id())) {
  529. // Load is in progress, but it's precisely this thread the one in charge.
  530. // That means this is a cyclic load.
  531. if (r_error) {
  532. *r_error = ERR_BUSY;
  533. }
  534. return Ref<Resource>();
  535. }
  536. if (load_task.task_id != 0) {
  537. // Loading thread is in the worker pool.
  538. load_task.awaited = true;
  539. thread_load_mutex.unlock();
  540. Error err = WorkerThreadPool::get_singleton()->wait_for_task_completion(load_task.task_id);
  541. if (err == ERR_BUSY) {
  542. // The WorkerThreadPool has scheduled tasks in a way that the current load depends on
  543. // another one in a lower stack frame. Restart such load here. When the stack is eventually
  544. // unrolled, the original load will have been notified to go on.
  545. #ifdef DEV_ENABLED
  546. print_verbose("ResourceLoader: Load task happened to wait on another one deep in the call stack. Attempting to avoid deadlock by re-issuing the load now.");
  547. #endif
  548. // CACHE_MODE_IGNORE is needed because, otherwise, the new request would just see there's
  549. // an ongoing load for that resource and wait for it again. This value forces a new load.
  550. Ref<ResourceLoader::LoadToken> token = _load_start(load_task.local_path, load_task.type_hint, LOAD_THREAD_DISTRIBUTE, ResourceFormatLoader::CACHE_MODE_IGNORE);
  551. Ref<Resource> resource = _load_complete(*token.ptr(), &err);
  552. if (r_error) {
  553. *r_error = err;
  554. }
  555. thread_load_mutex.lock();
  556. return resource;
  557. } else {
  558. DEV_ASSERT(err == OK);
  559. thread_load_mutex.lock();
  560. }
  561. } else {
  562. // Loading thread is main or user thread.
  563. if (!load_task.cond_var) {
  564. load_task.cond_var = memnew(ConditionVariable);
  565. }
  566. do {
  567. load_task.cond_var->wait(p_thread_load_lock);
  568. DEV_ASSERT(thread_load_tasks.has(p_load_token.local_path) && p_load_token.get_reference_count());
  569. } while (load_task.cond_var);
  570. }
  571. }
  572. if (cleaning_tasks) {
  573. load_task.resource = Ref<Resource>();
  574. load_task.error = FAILED;
  575. }
  576. Ref<Resource> resource = load_task.resource;
  577. if (r_error) {
  578. *r_error = load_task.error;
  579. }
  580. return resource;
  581. } else {
  582. // Special case of an unregistered task.
  583. // The resource should have been loaded by now.
  584. Ref<Resource> resource = p_load_token.res_if_unregistered;
  585. if (!resource.is_valid()) {
  586. if (r_error) {
  587. *r_error = FAILED;
  588. }
  589. }
  590. return resource;
  591. }
  592. }
  593. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  594. String local_path = _validate_local_path(p_path);
  595. if (ResourceCache::has(local_path)) {
  596. return true; // If cached, it probably exists
  597. }
  598. bool xl_remapped = false;
  599. String path = _path_remap(local_path, &xl_remapped);
  600. // Try all loaders and pick the first match for the type hint
  601. for (int i = 0; i < loader_count; i++) {
  602. if (!loader[i]->recognize_path(path, p_type_hint)) {
  603. continue;
  604. }
  605. if (loader[i]->exists(path)) {
  606. return true;
  607. }
  608. }
  609. return false;
  610. }
  611. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  612. ERR_FAIL_COND(p_format_loader.is_null());
  613. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  614. if (p_at_front) {
  615. for (int i = loader_count; i > 0; i--) {
  616. loader[i] = loader[i - 1];
  617. }
  618. loader[0] = p_format_loader;
  619. loader_count++;
  620. } else {
  621. loader[loader_count++] = p_format_loader;
  622. }
  623. }
  624. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  625. ERR_FAIL_COND(p_format_loader.is_null());
  626. // Find loader
  627. int i = 0;
  628. for (; i < loader_count; ++i) {
  629. if (loader[i] == p_format_loader) {
  630. break;
  631. }
  632. }
  633. ERR_FAIL_COND(i >= loader_count); // Not found
  634. // Shift next loaders up
  635. for (; i < loader_count - 1; ++i) {
  636. loader[i] = loader[i + 1];
  637. }
  638. loader[loader_count - 1].unref();
  639. --loader_count;
  640. }
  641. int ResourceLoader::get_import_order(const String &p_path) {
  642. String local_path = _path_remap(_validate_local_path(p_path));
  643. for (int i = 0; i < loader_count; i++) {
  644. if (!loader[i]->recognize_path(local_path)) {
  645. continue;
  646. }
  647. return loader[i]->get_import_order(p_path);
  648. }
  649. return 0;
  650. }
  651. String ResourceLoader::get_import_group_file(const String &p_path) {
  652. String local_path = _path_remap(_validate_local_path(p_path));
  653. for (int i = 0; i < loader_count; i++) {
  654. if (!loader[i]->recognize_path(local_path)) {
  655. continue;
  656. }
  657. return loader[i]->get_import_group_file(p_path);
  658. }
  659. return String(); //not found
  660. }
  661. bool ResourceLoader::is_import_valid(const String &p_path) {
  662. String local_path = _path_remap(_validate_local_path(p_path));
  663. for (int i = 0; i < loader_count; i++) {
  664. if (!loader[i]->recognize_path(local_path)) {
  665. continue;
  666. }
  667. return loader[i]->is_import_valid(p_path);
  668. }
  669. return false; //not found
  670. }
  671. bool ResourceLoader::is_imported(const String &p_path) {
  672. String local_path = _path_remap(_validate_local_path(p_path));
  673. for (int i = 0; i < loader_count; i++) {
  674. if (!loader[i]->recognize_path(local_path)) {
  675. continue;
  676. }
  677. return loader[i]->is_imported(p_path);
  678. }
  679. return false; //not found
  680. }
  681. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  682. String local_path = _path_remap(_validate_local_path(p_path));
  683. for (int i = 0; i < loader_count; i++) {
  684. if (!loader[i]->recognize_path(local_path)) {
  685. continue;
  686. }
  687. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  688. }
  689. }
  690. Error ResourceLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  691. String local_path = _path_remap(_validate_local_path(p_path));
  692. for (int i = 0; i < loader_count; i++) {
  693. if (!loader[i]->recognize_path(local_path)) {
  694. continue;
  695. }
  696. return loader[i]->rename_dependencies(local_path, p_map);
  697. }
  698. return OK; // ??
  699. }
  700. void ResourceLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  701. String local_path = _validate_local_path(p_path);
  702. for (int i = 0; i < loader_count; i++) {
  703. if (!loader[i]->recognize_path(local_path)) {
  704. continue;
  705. }
  706. return loader[i]->get_classes_used(p_path, r_classes);
  707. }
  708. }
  709. String ResourceLoader::get_resource_type(const String &p_path) {
  710. String local_path = _validate_local_path(p_path);
  711. for (int i = 0; i < loader_count; i++) {
  712. String result = loader[i]->get_resource_type(local_path);
  713. if (!result.is_empty()) {
  714. return result;
  715. }
  716. }
  717. return "";
  718. }
  719. String ResourceLoader::get_resource_script_class(const String &p_path) {
  720. String local_path = _validate_local_path(p_path);
  721. for (int i = 0; i < loader_count; i++) {
  722. String result = loader[i]->get_resource_script_class(local_path);
  723. if (!result.is_empty()) {
  724. return result;
  725. }
  726. }
  727. return "";
  728. }
  729. ResourceUID::ID ResourceLoader::get_resource_uid(const String &p_path) {
  730. String local_path = _validate_local_path(p_path);
  731. for (int i = 0; i < loader_count; i++) {
  732. ResourceUID::ID id = loader[i]->get_resource_uid(local_path);
  733. if (id != ResourceUID::INVALID_ID) {
  734. return id;
  735. }
  736. }
  737. return ResourceUID::INVALID_ID;
  738. }
  739. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  740. String new_path = p_path;
  741. if (translation_remaps.has(p_path)) {
  742. // translation_remaps has the following format:
  743. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  744. // To find the path of the remapped resource, we extract the locale name after
  745. // the last ':' to match the project locale.
  746. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  747. String locale = TranslationServer::get_singleton()->get_locale();
  748. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  749. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  750. int best_score = 0;
  751. for (int i = 0; i < res_remaps.size(); i++) {
  752. int split = res_remaps[i].rfind(":");
  753. if (split == -1) {
  754. continue;
  755. }
  756. String l = res_remaps[i].substr(split + 1).strip_edges();
  757. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  758. if (score > 0 && score >= best_score) {
  759. new_path = res_remaps[i].left(split);
  760. best_score = score;
  761. if (score == 10) {
  762. break; // Exact match, skip the rest.
  763. }
  764. }
  765. }
  766. if (r_translation_remapped) {
  767. *r_translation_remapped = true;
  768. }
  769. // Fallback to p_path if new_path does not exist.
  770. if (!FileAccess::exists(new_path + ".import") && !FileAccess::exists(new_path)) {
  771. WARN_PRINT(vformat("Translation remap '%s' does not exist. Falling back to '%s'.", new_path, p_path));
  772. new_path = p_path;
  773. }
  774. }
  775. if (path_remaps.has(new_path)) {
  776. new_path = path_remaps[new_path];
  777. } else {
  778. // Try file remap.
  779. Error err;
  780. Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
  781. if (f.is_valid()) {
  782. VariantParser::StreamFile stream;
  783. stream.f = f;
  784. String assign;
  785. Variant value;
  786. VariantParser::Tag next_tag;
  787. int lines = 0;
  788. String error_text;
  789. while (true) {
  790. assign = Variant();
  791. next_tag.fields.clear();
  792. next_tag.name = String();
  793. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  794. if (err == ERR_FILE_EOF) {
  795. break;
  796. } else if (err != OK) {
  797. ERR_PRINT("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  798. break;
  799. }
  800. if (assign == "path") {
  801. new_path = value;
  802. break;
  803. } else if (next_tag.name != "remap") {
  804. break;
  805. }
  806. }
  807. }
  808. }
  809. return new_path;
  810. }
  811. String ResourceLoader::import_remap(const String &p_path) {
  812. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  813. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  814. }
  815. return p_path;
  816. }
  817. String ResourceLoader::path_remap(const String &p_path) {
  818. return _path_remap(p_path);
  819. }
  820. void ResourceLoader::reload_translation_remaps() {
  821. ResourceCache::lock.lock();
  822. List<Resource *> to_reload;
  823. SelfList<Resource> *E = remapped_list.first();
  824. while (E) {
  825. to_reload.push_back(E->self());
  826. E = E->next();
  827. }
  828. ResourceCache::lock.unlock();
  829. //now just make sure to not delete any of these resources while changing locale..
  830. while (to_reload.front()) {
  831. to_reload.front()->get()->reload_from_file();
  832. to_reload.pop_front();
  833. }
  834. }
  835. void ResourceLoader::load_translation_remaps() {
  836. if (!ProjectSettings::get_singleton()->has_setting("internationalization/locale/translation_remaps")) {
  837. return;
  838. }
  839. Dictionary remaps = GLOBAL_GET("internationalization/locale/translation_remaps");
  840. List<Variant> keys;
  841. remaps.get_key_list(&keys);
  842. for (const Variant &E : keys) {
  843. Array langs = remaps[E];
  844. Vector<String> lang_remaps;
  845. lang_remaps.resize(langs.size());
  846. for (int i = 0; i < langs.size(); i++) {
  847. lang_remaps.write[i] = langs[i];
  848. }
  849. translation_remaps[String(E)] = lang_remaps;
  850. }
  851. }
  852. void ResourceLoader::clear_translation_remaps() {
  853. translation_remaps.clear();
  854. while (remapped_list.first() != nullptr) {
  855. remapped_list.remove(remapped_list.first());
  856. }
  857. }
  858. void ResourceLoader::clear_thread_load_tasks() {
  859. // Bring the thing down as quickly as possible without causing deadlocks or leaks.
  860. thread_load_mutex.lock();
  861. cleaning_tasks = true;
  862. while (true) {
  863. bool none_running = true;
  864. if (thread_load_tasks.size()) {
  865. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  866. if (E.value.status == THREAD_LOAD_IN_PROGRESS) {
  867. if (E.value.cond_var) {
  868. E.value.cond_var->notify_all();
  869. memdelete(E.value.cond_var);
  870. E.value.cond_var = nullptr;
  871. }
  872. none_running = false;
  873. }
  874. }
  875. }
  876. if (none_running) {
  877. break;
  878. }
  879. thread_load_mutex.unlock();
  880. OS::get_singleton()->delay_usec(1000);
  881. thread_load_mutex.lock();
  882. }
  883. while (user_load_tokens.begin()) {
  884. // User load tokens remove themselves from the map on destruction.
  885. memdelete(user_load_tokens.begin()->value);
  886. }
  887. user_load_tokens.clear();
  888. thread_load_tasks.clear();
  889. cleaning_tasks = false;
  890. thread_load_mutex.unlock();
  891. }
  892. void ResourceLoader::load_path_remaps() {
  893. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
  894. return;
  895. }
  896. Vector<String> remaps = GLOBAL_GET("path_remap/remapped_paths");
  897. int rc = remaps.size();
  898. ERR_FAIL_COND(rc & 1); //must be even
  899. const String *r = remaps.ptr();
  900. for (int i = 0; i < rc; i += 2) {
  901. path_remaps[r[i]] = r[i + 1];
  902. }
  903. }
  904. void ResourceLoader::clear_path_remaps() {
  905. path_remaps.clear();
  906. }
  907. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  908. _loaded_callback = p_callback;
  909. }
  910. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  911. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  912. for (int i = 0; i < loader_count; ++i) {
  913. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  914. return loader[i];
  915. }
  916. }
  917. return Ref<ResourceFormatLoader>();
  918. }
  919. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  920. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  921. return false;
  922. }
  923. Ref<Resource> res = ResourceLoader::load(script_path);
  924. ERR_FAIL_COND_V(res.is_null(), false);
  925. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  926. Ref<Script> s = res;
  927. StringName ibt = s->get_instance_base_type();
  928. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  929. ERR_FAIL_COND_V_MSG(!valid_type, false, vformat("Failed to add a custom resource loader, script '%s' does not inherit 'ResourceFormatLoader'.", script_path));
  930. Object *obj = ClassDB::instantiate(ibt);
  931. ERR_FAIL_NULL_V_MSG(obj, false, vformat("Failed to add a custom resource loader, cannot instantiate '%s'.", ibt));
  932. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  933. crl->set_script(s);
  934. ResourceLoader::add_resource_format_loader(crl);
  935. return true;
  936. }
  937. void ResourceLoader::set_create_missing_resources_if_class_unavailable(bool p_enable) {
  938. create_missing_resources_if_class_unavailable = p_enable;
  939. }
  940. void ResourceLoader::add_custom_loaders() {
  941. // Custom loaders registration exploits global class names
  942. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  943. List<StringName> global_classes;
  944. ScriptServer::get_global_class_list(&global_classes);
  945. for (const StringName &class_name : global_classes) {
  946. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  947. if (base_class == custom_loader_base_class) {
  948. String path = ScriptServer::get_global_class_path(class_name);
  949. add_custom_resource_format_loader(path);
  950. }
  951. }
  952. }
  953. void ResourceLoader::remove_custom_loaders() {
  954. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  955. for (int i = 0; i < loader_count; ++i) {
  956. if (loader[i]->get_script_instance()) {
  957. custom_loaders.push_back(loader[i]);
  958. }
  959. }
  960. for (int i = 0; i < custom_loaders.size(); ++i) {
  961. remove_resource_format_loader(custom_loaders[i]);
  962. }
  963. }
  964. bool ResourceLoader::is_cleaning_tasks() {
  965. MutexLock lock(thread_load_mutex);
  966. return cleaning_tasks;
  967. }
  968. void ResourceLoader::initialize() {}
  969. void ResourceLoader::finalize() {}
  970. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  971. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  972. bool ResourceLoader::create_missing_resources_if_class_unavailable = false;
  973. bool ResourceLoader::abort_on_missing_resource = true;
  974. bool ResourceLoader::timestamp_on_load = false;
  975. thread_local int ResourceLoader::load_nesting = 0;
  976. thread_local WorkerThreadPool::TaskID ResourceLoader::caller_task_id = 0;
  977. thread_local Vector<String> *ResourceLoader::load_paths_stack;
  978. template <>
  979. thread_local uint32_t SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::count = 0;
  980. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> ResourceLoader::thread_load_mutex;
  981. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  982. bool ResourceLoader::cleaning_tasks = false;
  983. HashMap<String, ResourceLoader::LoadToken *> ResourceLoader::user_load_tokens;
  984. SelfList<Resource>::List ResourceLoader::remapped_list;
  985. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  986. HashMap<String, String> ResourceLoader::path_remaps;
  987. ResourceLoaderImport ResourceLoader::import = nullptr;