resource_loader.cpp 34 KB

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