resource_loader.cpp 33 KB

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