2
0

resource_loader.cpp 34 KB

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