resource_loader.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. /*************************************************************************/
  2. /* resource_loader.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  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/io/resource_importer.h"
  32. #include "core/os/file_access.h"
  33. #include "core/os/os.h"
  34. #include "core/print_string.h"
  35. #include "core/project_settings.h"
  36. #include "core/translation.h"
  37. #include "core/variant_parser.h"
  38. #ifdef DEBUG_LOAD_THREADED
  39. #define print_lt(m_text) print_line(m_text)
  40. #else
  41. #define print_lt(m_text)
  42. #endif
  43. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  44. int ResourceLoader::loader_count = 0;
  45. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  46. String extension = p_path.get_extension();
  47. List<String> extensions;
  48. if (p_for_type == String()) {
  49. get_recognized_extensions(&extensions);
  50. } else {
  51. get_recognized_extensions_for_type(p_for_type, &extensions);
  52. }
  53. for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
  54. if (E->get().nocasecmp_to(extension) == 0) {
  55. return true;
  56. }
  57. }
  58. return false;
  59. }
  60. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  61. if (get_script_instance() && get_script_instance()->has_method("handles_type")) {
  62. // I guess custom loaders for custom resources should use "Resource"
  63. return get_script_instance()->call("handles_type", p_type);
  64. }
  65. return false;
  66. }
  67. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  68. if (get_script_instance() && get_script_instance()->has_method("get_resource_type")) {
  69. return get_script_instance()->call("get_resource_type", p_path);
  70. }
  71. return "";
  72. }
  73. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  74. if (p_type == "" || handles_type(p_type)) {
  75. get_recognized_extensions(p_extensions);
  76. }
  77. }
  78. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  79. for (int i = 0; i < loader_count; i++) {
  80. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  81. }
  82. }
  83. bool ResourceFormatLoader::exists(const String &p_path) const {
  84. return FileAccess::exists(p_path); //by default just check file
  85. }
  86. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  87. if (get_script_instance() && get_script_instance()->has_method("get_recognized_extensions")) {
  88. PackedStringArray exts = get_script_instance()->call("get_recognized_extensions");
  89. {
  90. const String *r = exts.ptr();
  91. for (int i = 0; i < exts.size(); ++i) {
  92. p_extensions->push_back(r[i]);
  93. }
  94. }
  95. }
  96. }
  97. RES ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
  98. if (get_script_instance() && get_script_instance()->has_method("load")) {
  99. Variant res = get_script_instance()->call("load", p_path, p_original_path, p_use_sub_threads);
  100. if (res.get_type() == Variant::INT) {
  101. if (r_error) {
  102. *r_error = (Error)res.operator int64_t();
  103. }
  104. } else {
  105. if (r_error) {
  106. *r_error = OK;
  107. }
  108. return res;
  109. }
  110. return res;
  111. }
  112. ERR_FAIL_V_MSG(RES(), "Failed to load resource '" + p_path + "', ResourceFormatLoader::load was not implemented for this resource type.");
  113. }
  114. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  115. if (get_script_instance() && get_script_instance()->has_method("get_dependencies")) {
  116. PackedStringArray deps = get_script_instance()->call("get_dependencies", p_path, p_add_types);
  117. {
  118. const String *r = deps.ptr();
  119. for (int i = 0; i < deps.size(); ++i) {
  120. p_dependencies->push_back(r[i]);
  121. }
  122. }
  123. }
  124. }
  125. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  126. if (get_script_instance() && get_script_instance()->has_method("rename_dependencies")) {
  127. Dictionary deps_dict;
  128. for (Map<String, String>::Element *E = p_map.front(); E; E = E->next()) {
  129. deps_dict[E->key()] = E->value();
  130. }
  131. int64_t res = get_script_instance()->call("rename_dependencies", deps_dict);
  132. return (Error)res;
  133. }
  134. return OK;
  135. }
  136. void ResourceFormatLoader::_bind_methods() {
  137. {
  138. MethodInfo info = MethodInfo(Variant::NIL, "load", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "original_path"));
  139. info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  140. ClassDB::add_virtual_method(get_class_static(), info);
  141. }
  142. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::PACKED_STRING_ARRAY, "get_recognized_extensions"));
  143. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "handles_type", PropertyInfo(Variant::STRING_NAME, "typename")));
  144. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::STRING, "get_resource_type", PropertyInfo(Variant::STRING, "path")));
  145. ClassDB::add_virtual_method(get_class_static(), MethodInfo("get_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "add_types")));
  146. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::INT, "rename_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "renames")));
  147. }
  148. ///////////////////////////////////
  149. RES ResourceLoader::_load(const String &p_path, const String &p_original_path, const String &p_type_hint, bool p_no_cache, Error *r_error, bool p_use_sub_threads, float *r_progress) {
  150. bool found = false;
  151. // Try all loaders and pick the first match for the type hint
  152. for (int i = 0; i < loader_count; i++) {
  153. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  154. continue;
  155. }
  156. found = true;
  157. RES res = loader[i]->load(p_path, p_original_path != String() ? p_original_path : p_path, r_error, p_use_sub_threads, r_progress, p_no_cache);
  158. if (res.is_null()) {
  159. continue;
  160. }
  161. return res;
  162. }
  163. ERR_FAIL_COND_V_MSG(found, RES(), "Failed loading resource: " + p_path + ".");
  164. #ifdef TOOLS_ENABLED
  165. FileAccessRef file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  166. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), RES(), "Resource file not found: " + p_path + ".");
  167. #endif
  168. ERR_FAIL_V_MSG(RES(), "No loader found for resource: " + p_path + ".");
  169. }
  170. void ResourceLoader::_thread_load_function(void *p_userdata) {
  171. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  172. load_task.loader_id = Thread::get_caller_id();
  173. if (load_task.semaphore) {
  174. //this is an actual thread, so wait for Ok fom semaphore
  175. thread_load_semaphore->wait(); //wait until its ok to start loading
  176. }
  177. load_task.resource = _load(load_task.remapped_path, load_task.remapped_path != load_task.local_path ? load_task.local_path : String(), load_task.type_hint, false, &load_task.error, load_task.use_sub_threads, &load_task.progress);
  178. load_task.progress = 1.0; //it was fully loaded at this point, so force progress to 1.0
  179. thread_load_mutex->lock();
  180. if (load_task.error != OK) {
  181. load_task.status = THREAD_LOAD_FAILED;
  182. } else {
  183. load_task.status = THREAD_LOAD_LOADED;
  184. }
  185. if (load_task.semaphore) {
  186. if (load_task.start_next && thread_waiting_count > 0) {
  187. thread_waiting_count--;
  188. //thread loading count remains constant, this ends but another one begins
  189. thread_load_semaphore->post();
  190. } else {
  191. thread_loading_count--; //no threads waiting, just reduce loading count
  192. }
  193. print_lt("END: load count: " + itos(thread_loading_count) + " / wait count: " + itos(thread_waiting_count) + " / suspended count: " + itos(thread_suspended_count) + " / active: " + itos(thread_loading_count - thread_suspended_count));
  194. for (int i = 0; i < load_task.poll_requests; i++) {
  195. load_task.semaphore->post();
  196. }
  197. memdelete(load_task.semaphore);
  198. load_task.semaphore = nullptr;
  199. }
  200. if (load_task.resource.is_valid()) {
  201. load_task.resource->set_path(load_task.local_path);
  202. if (load_task.xl_remapped) {
  203. load_task.resource->set_as_translation_remapped(true);
  204. }
  205. #ifdef TOOLS_ENABLED
  206. load_task.resource->set_edited(false);
  207. if (timestamp_on_load) {
  208. uint64_t mt = FileAccess::get_modified_time(load_task.remapped_path);
  209. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  210. load_task.resource->set_last_modified_time(mt);
  211. }
  212. #endif
  213. if (_loaded_callback) {
  214. _loaded_callback(load_task.resource, load_task.local_path);
  215. }
  216. }
  217. thread_load_mutex->unlock();
  218. }
  219. Error ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads, const String &p_source_resource) {
  220. String local_path;
  221. if (p_path.is_rel_path()) {
  222. local_path = "res://" + p_path;
  223. } else {
  224. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  225. }
  226. thread_load_mutex->lock();
  227. if (p_source_resource != String()) {
  228. //must be loading from this resource
  229. if (!thread_load_tasks.has(p_source_resource)) {
  230. thread_load_mutex->unlock();
  231. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "There is no thread loading source resource '" + p_source_resource + "'.");
  232. }
  233. //must be loading from this thread
  234. if (thread_load_tasks[p_source_resource].loader_id != Thread::get_caller_id()) {
  235. thread_load_mutex->unlock();
  236. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Threading loading resource'" + local_path + " failed: Source specified: '" + p_source_resource + "' but was not called by it.");
  237. }
  238. //must not be already added as s sub tasks
  239. if (thread_load_tasks[p_source_resource].sub_tasks.has(local_path)) {
  240. thread_load_mutex->unlock();
  241. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Thread loading source resource '" + p_source_resource + "' already is loading '" + local_path + "'.");
  242. }
  243. }
  244. if (thread_load_tasks.has(local_path)) {
  245. thread_load_tasks[local_path].requests++;
  246. if (p_source_resource != String()) {
  247. thread_load_tasks[p_source_resource].sub_tasks.insert(local_path);
  248. }
  249. thread_load_mutex->unlock();
  250. return OK;
  251. }
  252. {
  253. //create load task
  254. ThreadLoadTask load_task;
  255. load_task.requests = 1;
  256. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  257. load_task.local_path = local_path;
  258. load_task.type_hint = p_type_hint;
  259. load_task.use_sub_threads = p_use_sub_threads;
  260. { //must check if resource is already loaded before attempting to load it in a thread
  261. if (load_task.loader_id == Thread::get_caller_id()) {
  262. thread_load_mutex->unlock();
  263. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Attempted to load a resource already being loaded from this thread, cyclic reference?");
  264. }
  265. //lock first if possible
  266. if (ResourceCache::lock) {
  267. ResourceCache::lock->read_lock();
  268. }
  269. //get ptr
  270. Resource **rptr = ResourceCache::resources.getptr(local_path);
  271. if (rptr) {
  272. RES res(*rptr);
  273. //it is possible this resource was just freed in a thread. If so, this referencing will not work and resource is considered not cached
  274. if (res.is_valid()) {
  275. //referencing is fine
  276. load_task.resource = res;
  277. load_task.status = THREAD_LOAD_LOADED;
  278. load_task.progress = 1.0;
  279. }
  280. }
  281. if (ResourceCache::lock) {
  282. ResourceCache::lock->read_unlock();
  283. }
  284. }
  285. if (p_source_resource != String()) {
  286. thread_load_tasks[p_source_resource].sub_tasks.insert(local_path);
  287. }
  288. thread_load_tasks[local_path] = load_task;
  289. }
  290. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  291. if (load_task.resource.is_null()) { //needs to be loaded in thread
  292. load_task.semaphore = memnew(Semaphore);
  293. if (thread_loading_count < thread_load_max) {
  294. thread_loading_count++;
  295. thread_load_semaphore->post(); //we have free threads, so allow one
  296. } else {
  297. thread_waiting_count++;
  298. }
  299. print_lt("REQUEST: load count: " + itos(thread_loading_count) + " / wait count: " + itos(thread_waiting_count) + " / suspended count: " + itos(thread_suspended_count) + " / active: " + itos(thread_loading_count - thread_suspended_count));
  300. load_task.thread = Thread::create(_thread_load_function, &thread_load_tasks[local_path]);
  301. load_task.loader_id = load_task.thread->get_id();
  302. }
  303. thread_load_mutex->unlock();
  304. return OK;
  305. }
  306. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  307. if (thread_load_tasks.has(p_path)) {
  308. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  309. int dep_count = load_task.sub_tasks.size();
  310. if (dep_count > 0) {
  311. float dep_progress = 0;
  312. for (Set<String>::Element *E = load_task.sub_tasks.front(); E; E = E->next()) {
  313. dep_progress += _dependency_get_progress(E->get());
  314. }
  315. dep_progress /= float(dep_count);
  316. dep_progress *= 0.5;
  317. dep_progress += load_task.progress * 0.5;
  318. return dep_progress;
  319. } else {
  320. return load_task.progress;
  321. }
  322. } else {
  323. return 1.0; //assume finished loading it so it no longer exists
  324. }
  325. }
  326. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  327. String local_path;
  328. if (p_path.is_rel_path()) {
  329. local_path = "res://" + p_path;
  330. } else {
  331. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  332. }
  333. thread_load_mutex->lock();
  334. if (!thread_load_tasks.has(local_path)) {
  335. thread_load_mutex->unlock();
  336. return THREAD_LOAD_INVALID_RESOURCE;
  337. }
  338. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  339. ThreadLoadStatus status;
  340. status = load_task.status;
  341. if (r_progress) {
  342. *r_progress = _dependency_get_progress(local_path);
  343. }
  344. thread_load_mutex->unlock();
  345. return status;
  346. }
  347. RES ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  348. String local_path;
  349. if (p_path.is_rel_path()) {
  350. local_path = "res://" + p_path;
  351. } else {
  352. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  353. }
  354. thread_load_mutex->lock();
  355. if (!thread_load_tasks.has(local_path)) {
  356. thread_load_mutex->unlock();
  357. if (r_error) {
  358. *r_error = ERR_INVALID_PARAMETER;
  359. }
  360. return RES();
  361. }
  362. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  363. //semaphore still exists, meaning its still loading, request poll
  364. Semaphore *semaphore = load_task.semaphore;
  365. if (semaphore) {
  366. load_task.poll_requests++;
  367. {
  368. // As we got a semaphore, this means we are going to have to wait
  369. // until the sub-resource is done loading
  370. //
  371. // As this thread will become 'blocked' we should "echange" its
  372. // active status with a waiting one, to ensure load continues.
  373. //
  374. // This ensures loading is never blocked and that is also within
  375. // the maximum number of active threads.
  376. if (thread_waiting_count > 0) {
  377. thread_waiting_count--;
  378. thread_loading_count++;
  379. thread_load_semaphore->post();
  380. load_task.start_next = false; //do not start next since we are doing it here
  381. }
  382. thread_suspended_count++;
  383. print_lt("GET: load count: " + itos(thread_loading_count) + " / wait count: " + itos(thread_waiting_count) + " / suspended count: " + itos(thread_suspended_count) + " / active: " + itos(thread_loading_count - thread_suspended_count));
  384. }
  385. thread_load_mutex->unlock();
  386. semaphore->wait();
  387. thread_load_mutex->lock();
  388. thread_suspended_count--;
  389. if (!thread_load_tasks.has(local_path)) { //may have been erased during unlock and this was always an invalid call
  390. thread_load_mutex->unlock();
  391. if (r_error) {
  392. *r_error = ERR_INVALID_PARAMETER;
  393. }
  394. return RES();
  395. }
  396. }
  397. RES resource = load_task.resource;
  398. if (r_error) {
  399. *r_error = load_task.error;
  400. }
  401. load_task.requests--;
  402. if (load_task.requests == 0) {
  403. if (load_task.thread) { //thread may not have been used
  404. Thread::wait_to_finish(load_task.thread);
  405. memdelete(load_task.thread);
  406. }
  407. thread_load_tasks.erase(local_path);
  408. }
  409. thread_load_mutex->unlock();
  410. return resource;
  411. }
  412. RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  413. if (r_error) {
  414. *r_error = ERR_CANT_OPEN;
  415. }
  416. String local_path;
  417. if (p_path.is_rel_path()) {
  418. local_path = "res://" + p_path;
  419. } else {
  420. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  421. }
  422. if (!p_no_cache) {
  423. thread_load_mutex->lock();
  424. //Is it already being loaded? poll until done
  425. if (thread_load_tasks.has(local_path)) {
  426. Error err = load_threaded_request(p_path, p_type_hint);
  427. if (err != OK) {
  428. if (r_error) {
  429. *r_error = err;
  430. }
  431. thread_load_mutex->unlock();
  432. return RES();
  433. }
  434. thread_load_mutex->unlock();
  435. return load_threaded_get(p_path, r_error);
  436. }
  437. //Is it cached?
  438. if (ResourceCache::lock) {
  439. ResourceCache::lock->read_lock();
  440. }
  441. Resource **rptr = ResourceCache::resources.getptr(local_path);
  442. if (rptr) {
  443. RES res(*rptr);
  444. //it is possible this resource was just freed in a thread. If so, this referencing will not work and resource is considered not cached
  445. if (res.is_valid()) {
  446. if (ResourceCache::lock) {
  447. ResourceCache::lock->read_unlock();
  448. }
  449. thread_load_mutex->unlock();
  450. if (r_error) {
  451. *r_error = OK;
  452. }
  453. return res; //use cached
  454. }
  455. }
  456. if (ResourceCache::lock) {
  457. ResourceCache::lock->read_unlock();
  458. }
  459. //load using task (but this thread)
  460. ThreadLoadTask load_task;
  461. load_task.requests = 1;
  462. load_task.local_path = local_path;
  463. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  464. load_task.type_hint = p_type_hint;
  465. load_task.loader_id = Thread::get_caller_id();
  466. thread_load_tasks[local_path] = load_task;
  467. thread_load_mutex->unlock();
  468. _thread_load_function(&thread_load_tasks[local_path]);
  469. return load_threaded_get(p_path, r_error);
  470. } else {
  471. bool xl_remapped = false;
  472. String path = _path_remap(local_path, &xl_remapped);
  473. if (path == "") {
  474. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  475. }
  476. print_verbose("Loading resource: " + path);
  477. float p;
  478. RES res = _load(path, local_path, p_type_hint, p_no_cache, r_error, false, &p);
  479. if (res.is_null()) {
  480. print_verbose("Failed loading resource: " + path);
  481. return RES();
  482. }
  483. if (xl_remapped) {
  484. res->set_as_translation_remapped(true);
  485. }
  486. #ifdef TOOLS_ENABLED
  487. res->set_edited(false);
  488. if (timestamp_on_load) {
  489. uint64_t mt = FileAccess::get_modified_time(path);
  490. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  491. res->set_last_modified_time(mt);
  492. }
  493. #endif
  494. return res;
  495. }
  496. }
  497. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  498. String local_path;
  499. if (p_path.is_rel_path()) {
  500. local_path = "res://" + p_path;
  501. } else {
  502. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  503. }
  504. if (ResourceCache::has(local_path)) {
  505. return true; // If cached, it probably exists
  506. }
  507. bool xl_remapped = false;
  508. String path = _path_remap(local_path, &xl_remapped);
  509. // Try all loaders and pick the first match for the type hint
  510. for (int i = 0; i < loader_count; i++) {
  511. if (!loader[i]->recognize_path(path, p_type_hint)) {
  512. continue;
  513. }
  514. if (loader[i]->exists(path)) {
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  521. ERR_FAIL_COND(p_format_loader.is_null());
  522. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  523. if (p_at_front) {
  524. for (int i = loader_count; i > 0; i--) {
  525. loader[i] = loader[i - 1];
  526. }
  527. loader[0] = p_format_loader;
  528. loader_count++;
  529. } else {
  530. loader[loader_count++] = p_format_loader;
  531. }
  532. }
  533. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  534. ERR_FAIL_COND(p_format_loader.is_null());
  535. // Find loader
  536. int i = 0;
  537. for (; i < loader_count; ++i) {
  538. if (loader[i] == p_format_loader) {
  539. break;
  540. }
  541. }
  542. ERR_FAIL_COND(i >= loader_count); // Not found
  543. // Shift next loaders up
  544. for (; i < loader_count - 1; ++i) {
  545. loader[i] = loader[i + 1];
  546. }
  547. loader[loader_count - 1].unref();
  548. --loader_count;
  549. }
  550. int ResourceLoader::get_import_order(const String &p_path) {
  551. String path = _path_remap(p_path);
  552. String local_path;
  553. if (path.is_rel_path()) {
  554. local_path = "res://" + path;
  555. } else {
  556. local_path = ProjectSettings::get_singleton()->localize_path(path);
  557. }
  558. for (int i = 0; i < loader_count; i++) {
  559. if (!loader[i]->recognize_path(local_path)) {
  560. continue;
  561. }
  562. /*
  563. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  564. continue;
  565. */
  566. return loader[i]->get_import_order(p_path);
  567. }
  568. return 0;
  569. }
  570. String ResourceLoader::get_import_group_file(const String &p_path) {
  571. String path = _path_remap(p_path);
  572. String local_path;
  573. if (path.is_rel_path()) {
  574. local_path = "res://" + path;
  575. } else {
  576. local_path = ProjectSettings::get_singleton()->localize_path(path);
  577. }
  578. for (int i = 0; i < loader_count; i++) {
  579. if (!loader[i]->recognize_path(local_path)) {
  580. continue;
  581. }
  582. /*
  583. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  584. continue;
  585. */
  586. return loader[i]->get_import_group_file(p_path);
  587. }
  588. return String(); //not found
  589. }
  590. bool ResourceLoader::is_import_valid(const String &p_path) {
  591. String path = _path_remap(p_path);
  592. String local_path;
  593. if (path.is_rel_path()) {
  594. local_path = "res://" + path;
  595. } else {
  596. local_path = ProjectSettings::get_singleton()->localize_path(path);
  597. }
  598. for (int i = 0; i < loader_count; i++) {
  599. if (!loader[i]->recognize_path(local_path)) {
  600. continue;
  601. }
  602. /*
  603. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  604. continue;
  605. */
  606. return loader[i]->is_import_valid(p_path);
  607. }
  608. return false; //not found
  609. }
  610. bool ResourceLoader::is_imported(const String &p_path) {
  611. String path = _path_remap(p_path);
  612. String local_path;
  613. if (path.is_rel_path()) {
  614. local_path = "res://" + path;
  615. } else {
  616. local_path = ProjectSettings::get_singleton()->localize_path(path);
  617. }
  618. for (int i = 0; i < loader_count; i++) {
  619. if (!loader[i]->recognize_path(local_path)) {
  620. continue;
  621. }
  622. /*
  623. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  624. continue;
  625. */
  626. return loader[i]->is_imported(p_path);
  627. }
  628. return false; //not found
  629. }
  630. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  631. String path = _path_remap(p_path);
  632. String local_path;
  633. if (path.is_rel_path()) {
  634. local_path = "res://" + path;
  635. } else {
  636. local_path = ProjectSettings::get_singleton()->localize_path(path);
  637. }
  638. for (int i = 0; i < loader_count; i++) {
  639. if (!loader[i]->recognize_path(local_path)) {
  640. continue;
  641. }
  642. /*
  643. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  644. continue;
  645. */
  646. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  647. }
  648. }
  649. Error ResourceLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  650. String path = _path_remap(p_path);
  651. String local_path;
  652. if (path.is_rel_path()) {
  653. local_path = "res://" + path;
  654. } else {
  655. local_path = ProjectSettings::get_singleton()->localize_path(path);
  656. }
  657. for (int i = 0; i < loader_count; i++) {
  658. if (!loader[i]->recognize_path(local_path)) {
  659. continue;
  660. }
  661. /*
  662. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  663. continue;
  664. */
  665. return loader[i]->rename_dependencies(local_path, p_map);
  666. }
  667. return OK; // ??
  668. }
  669. String ResourceLoader::get_resource_type(const String &p_path) {
  670. String local_path;
  671. if (p_path.is_rel_path()) {
  672. local_path = "res://" + p_path;
  673. } else {
  674. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  675. }
  676. for (int i = 0; i < loader_count; i++) {
  677. String result = loader[i]->get_resource_type(local_path);
  678. if (result != "") {
  679. return result;
  680. }
  681. }
  682. return "";
  683. }
  684. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  685. String new_path = p_path;
  686. if (translation_remaps.has(p_path)) {
  687. // translation_remaps has the following format:
  688. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  689. // To find the path of the remapped resource, we extract the locale name after
  690. // the last ':' to match the project locale.
  691. // We also fall back in case of regional locales as done in TranslationServer::translate
  692. // (e.g. 'ru_RU' -> 'ru' if the former has no specific mapping).
  693. String locale = TranslationServer::get_singleton()->get_locale();
  694. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  695. String lang = TranslationServer::get_language_code(locale);
  696. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  697. bool near_match = false;
  698. for (int i = 0; i < res_remaps.size(); i++) {
  699. int split = res_remaps[i].find_last(":");
  700. if (split == -1) {
  701. continue;
  702. }
  703. String l = res_remaps[i].right(split + 1).strip_edges();
  704. if (l == locale) { // Exact match.
  705. new_path = res_remaps[i].left(split);
  706. break;
  707. } else if (near_match) {
  708. continue; // Already found near match, keep going for potential exact match.
  709. }
  710. // No exact match (e.g. locale 'ru_RU' but remap is 'ru'), let's look further
  711. // for a near match (same language code, i.e. first 2 or 3 letters before
  712. // regional code, if included).
  713. if (TranslationServer::get_language_code(l) == lang) {
  714. // Language code matches, that's a near match. Keep looking for exact match.
  715. near_match = true;
  716. new_path = res_remaps[i].left(split);
  717. continue;
  718. }
  719. }
  720. if (r_translation_remapped) {
  721. *r_translation_remapped = true;
  722. }
  723. }
  724. if (path_remaps.has(new_path)) {
  725. new_path = path_remaps[new_path];
  726. }
  727. if (new_path == p_path) { // Did not remap.
  728. // Try file remap.
  729. Error err;
  730. FileAccess *f = FileAccess::open(p_path + ".remap", FileAccess::READ, &err);
  731. if (f) {
  732. VariantParser::StreamFile stream;
  733. stream.f = f;
  734. String assign;
  735. Variant value;
  736. VariantParser::Tag next_tag;
  737. int lines = 0;
  738. String error_text;
  739. while (true) {
  740. assign = Variant();
  741. next_tag.fields.clear();
  742. next_tag.name = String();
  743. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  744. if (err == ERR_FILE_EOF) {
  745. break;
  746. } else if (err != OK) {
  747. ERR_PRINT("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  748. break;
  749. }
  750. if (assign == "path") {
  751. new_path = value;
  752. break;
  753. } else if (next_tag.name != "remap") {
  754. break;
  755. }
  756. }
  757. memdelete(f);
  758. }
  759. }
  760. return new_path;
  761. }
  762. String ResourceLoader::import_remap(const String &p_path) {
  763. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  764. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  765. }
  766. return p_path;
  767. }
  768. String ResourceLoader::path_remap(const String &p_path) {
  769. return _path_remap(p_path);
  770. }
  771. void ResourceLoader::reload_translation_remaps() {
  772. if (ResourceCache::lock) {
  773. ResourceCache::lock->read_lock();
  774. }
  775. List<Resource *> to_reload;
  776. SelfList<Resource> *E = remapped_list.first();
  777. while (E) {
  778. to_reload.push_back(E->self());
  779. E = E->next();
  780. }
  781. if (ResourceCache::lock) {
  782. ResourceCache::lock->read_unlock();
  783. }
  784. //now just make sure to not delete any of these resources while changing locale..
  785. while (to_reload.front()) {
  786. to_reload.front()->get()->reload_from_file();
  787. to_reload.pop_front();
  788. }
  789. }
  790. void ResourceLoader::load_translation_remaps() {
  791. if (!ProjectSettings::get_singleton()->has_setting("locale/translation_remaps")) {
  792. return;
  793. }
  794. Dictionary remaps = ProjectSettings::get_singleton()->get("locale/translation_remaps");
  795. List<Variant> keys;
  796. remaps.get_key_list(&keys);
  797. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  798. Array langs = remaps[E->get()];
  799. Vector<String> lang_remaps;
  800. lang_remaps.resize(langs.size());
  801. for (int i = 0; i < langs.size(); i++) {
  802. lang_remaps.write[i] = langs[i];
  803. }
  804. translation_remaps[String(E->get())] = lang_remaps;
  805. }
  806. }
  807. void ResourceLoader::clear_translation_remaps() {
  808. translation_remaps.clear();
  809. }
  810. void ResourceLoader::load_path_remaps() {
  811. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
  812. return;
  813. }
  814. Vector<String> remaps = ProjectSettings::get_singleton()->get("path_remap/remapped_paths");
  815. int rc = remaps.size();
  816. ERR_FAIL_COND(rc & 1); //must be even
  817. const String *r = remaps.ptr();
  818. for (int i = 0; i < rc; i += 2) {
  819. path_remaps[r[i]] = r[i + 1];
  820. }
  821. }
  822. void ResourceLoader::clear_path_remaps() {
  823. path_remaps.clear();
  824. }
  825. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  826. _loaded_callback = p_callback;
  827. }
  828. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  829. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  830. for (int i = 0; i < loader_count; ++i) {
  831. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  832. return loader[i];
  833. }
  834. }
  835. return Ref<ResourceFormatLoader>();
  836. }
  837. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  838. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  839. return false;
  840. }
  841. Ref<Resource> res = ResourceLoader::load(script_path);
  842. ERR_FAIL_COND_V(res.is_null(), false);
  843. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  844. Ref<Script> s = res;
  845. StringName ibt = s->get_instance_base_type();
  846. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  847. ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
  848. Object *obj = ClassDB::instance(ibt);
  849. ERR_FAIL_COND_V_MSG(obj == nullptr, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
  850. ResourceFormatLoader *crl = Object::cast_to<ResourceFormatLoader>(obj);
  851. crl->set_script(s);
  852. ResourceLoader::add_resource_format_loader(crl);
  853. return true;
  854. }
  855. void ResourceLoader::remove_custom_resource_format_loader(String script_path) {
  856. Ref<ResourceFormatLoader> custom_loader = _find_custom_resource_format_loader(script_path);
  857. if (custom_loader.is_valid()) {
  858. remove_resource_format_loader(custom_loader);
  859. }
  860. }
  861. void ResourceLoader::add_custom_loaders() {
  862. // Custom loaders registration exploits global class names
  863. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  864. List<StringName> global_classes;
  865. ScriptServer::get_global_class_list(&global_classes);
  866. for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) {
  867. StringName class_name = E->get();
  868. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  869. if (base_class == custom_loader_base_class) {
  870. String path = ScriptServer::get_global_class_path(class_name);
  871. add_custom_resource_format_loader(path);
  872. }
  873. }
  874. }
  875. void ResourceLoader::remove_custom_loaders() {
  876. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  877. for (int i = 0; i < loader_count; ++i) {
  878. if (loader[i]->get_script_instance()) {
  879. custom_loaders.push_back(loader[i]);
  880. }
  881. }
  882. for (int i = 0; i < custom_loaders.size(); ++i) {
  883. remove_resource_format_loader(custom_loaders[i]);
  884. }
  885. }
  886. void ResourceLoader::initialize() {
  887. thread_load_mutex = memnew(Mutex);
  888. thread_load_max = OS::get_singleton()->get_processor_count();
  889. thread_loading_count = 0;
  890. thread_waiting_count = 0;
  891. thread_suspended_count = 0;
  892. thread_load_semaphore = memnew(Semaphore);
  893. }
  894. void ResourceLoader::finalize() {
  895. memdelete(thread_load_mutex);
  896. memdelete(thread_load_semaphore);
  897. }
  898. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  899. void *ResourceLoader::err_notify_ud = nullptr;
  900. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  901. void *ResourceLoader::dep_err_notify_ud = nullptr;
  902. bool ResourceLoader::abort_on_missing_resource = true;
  903. bool ResourceLoader::timestamp_on_load = false;
  904. Mutex *ResourceLoader::thread_load_mutex = nullptr;
  905. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  906. Semaphore *ResourceLoader::thread_load_semaphore = nullptr;
  907. int ResourceLoader::thread_loading_count = 0;
  908. int ResourceLoader::thread_waiting_count = 0;
  909. int ResourceLoader::thread_suspended_count = 0;
  910. int ResourceLoader::thread_load_max = 0;
  911. SelfList<Resource>::List ResourceLoader::remapped_list;
  912. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  913. HashMap<String, String> ResourceLoader::path_remaps;
  914. ResourceLoaderImport ResourceLoader::import = nullptr;