resource_loader.cpp 34 KB

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