resource_loader.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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/io/resource_importer.h"
  32. #include "core/os/file_access.h"
  33. #include "core/os/os.h"
  34. #include "core/path_remap.h"
  35. #include "core/print_string.h"
  36. #include "core/project_settings.h"
  37. #include "core/translation.h"
  38. #include "core/variant_parser.h"
  39. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  40. int ResourceLoader::loader_count = 0;
  41. Error ResourceInteractiveLoader::wait() {
  42. Error err = poll();
  43. while (err == OK) {
  44. err = poll();
  45. }
  46. return err;
  47. }
  48. ResourceInteractiveLoader::~ResourceInteractiveLoader() {
  49. if (path_loading != String()) {
  50. ResourceLoader::_remove_from_loading_map_and_thread(path_loading, path_loading_thread);
  51. }
  52. }
  53. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  54. String extension = p_path.get_extension();
  55. List<String> extensions;
  56. if (p_for_type == String()) {
  57. get_recognized_extensions(&extensions);
  58. } else {
  59. get_recognized_extensions_for_type(p_for_type, &extensions);
  60. }
  61. for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
  62. if (E->get().nocasecmp_to(extension) == 0)
  63. return true;
  64. }
  65. return false;
  66. }
  67. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  68. if (get_script_instance() && get_script_instance()->has_method("handles_type")) {
  69. // I guess custom loaders for custom resources should use "Resource"
  70. return get_script_instance()->call("handles_type", p_type);
  71. }
  72. return false;
  73. }
  74. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  75. if (get_script_instance() && get_script_instance()->has_method("get_resource_type")) {
  76. return get_script_instance()->call("get_resource_type", p_path);
  77. }
  78. return "";
  79. }
  80. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  81. if (p_type == "" || handles_type(p_type))
  82. get_recognized_extensions(p_extensions);
  83. }
  84. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  85. for (int i = 0; i < loader_count; i++) {
  86. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  87. }
  88. }
  89. void ResourceInteractiveLoader::_bind_methods() {
  90. ClassDB::bind_method(D_METHOD("get_resource"), &ResourceInteractiveLoader::get_resource);
  91. ClassDB::bind_method(D_METHOD("poll"), &ResourceInteractiveLoader::poll);
  92. ClassDB::bind_method(D_METHOD("wait"), &ResourceInteractiveLoader::wait);
  93. ClassDB::bind_method(D_METHOD("get_stage"), &ResourceInteractiveLoader::get_stage);
  94. ClassDB::bind_method(D_METHOD("get_stage_count"), &ResourceInteractiveLoader::get_stage_count);
  95. }
  96. class ResourceInteractiveLoaderDefault : public ResourceInteractiveLoader {
  97. GDCLASS(ResourceInteractiveLoaderDefault, ResourceInteractiveLoader);
  98. public:
  99. Ref<Resource> resource;
  100. virtual void set_local_path(const String &p_local_path) { /*scene->set_filename(p_local_path);*/
  101. }
  102. virtual Ref<Resource> get_resource() { return resource; }
  103. virtual Error poll() { return ERR_FILE_EOF; }
  104. virtual int get_stage() const { return 1; }
  105. virtual int get_stage_count() const { return 1; }
  106. virtual void set_translation_remapped(bool p_remapped) { resource->set_as_translation_remapped(p_remapped); }
  107. ResourceInteractiveLoaderDefault() {}
  108. };
  109. Ref<ResourceInteractiveLoader> ResourceFormatLoader::load_interactive(const String &p_path, const String &p_original_path, Error *r_error) {
  110. //either this
  111. Ref<Resource> res = load(p_path, p_original_path, r_error);
  112. if (res.is_null())
  113. return Ref<ResourceInteractiveLoader>();
  114. Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
  115. ril->resource = res;
  116. return ril;
  117. }
  118. bool ResourceFormatLoader::exists(const String &p_path) const {
  119. return FileAccess::exists(p_path); //by default just check file
  120. }
  121. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  122. if (get_script_instance() && get_script_instance()->has_method("get_recognized_extensions")) {
  123. PoolStringArray exts = get_script_instance()->call("get_recognized_extensions");
  124. {
  125. PoolStringArray::Read r = exts.read();
  126. for (int i = 0; i < exts.size(); ++i) {
  127. p_extensions->push_back(r[i]);
  128. }
  129. }
  130. }
  131. }
  132. RES ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error) {
  133. if (get_script_instance() && get_script_instance()->has_method("load")) {
  134. Variant res = get_script_instance()->call("load", p_path, p_original_path);
  135. if (res.get_type() == Variant::INT) {
  136. if (r_error)
  137. *r_error = (Error)res.operator int64_t();
  138. } else {
  139. if (r_error)
  140. *r_error = OK;
  141. return res;
  142. }
  143. }
  144. //or this must be implemented
  145. Ref<ResourceInteractiveLoader> ril = load_interactive(p_path, p_original_path, r_error);
  146. if (!ril.is_valid())
  147. return RES();
  148. ril->set_local_path(p_original_path);
  149. while (true) {
  150. Error err = ril->poll();
  151. if (err == ERR_FILE_EOF) {
  152. if (r_error)
  153. *r_error = OK;
  154. return ril->get_resource();
  155. }
  156. if (r_error)
  157. *r_error = err;
  158. ERR_FAIL_COND_V_MSG(err != OK, RES(), "Failed to load resource '" + p_path + "'.");
  159. }
  160. }
  161. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  162. if (get_script_instance() && get_script_instance()->has_method("get_dependencies")) {
  163. PoolStringArray deps = get_script_instance()->call("get_dependencies", p_path, p_add_types);
  164. {
  165. PoolStringArray::Read r = deps.read();
  166. for (int i = 0; i < deps.size(); ++i) {
  167. p_dependencies->push_back(r[i]);
  168. }
  169. }
  170. }
  171. }
  172. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  173. if (get_script_instance() && get_script_instance()->has_method("rename_dependencies")) {
  174. Dictionary deps_dict;
  175. for (Map<String, String>::Element *E = p_map.front(); E; E = E->next()) {
  176. deps_dict[E->key()] = E->value();
  177. }
  178. int64_t res = get_script_instance()->call("rename_dependencies", deps_dict);
  179. return (Error)res;
  180. }
  181. return OK;
  182. }
  183. void ResourceFormatLoader::_bind_methods() {
  184. {
  185. MethodInfo info = MethodInfo(Variant::NIL, "load", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "original_path"));
  186. info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  187. ClassDB::add_virtual_method(get_class_static(), info);
  188. }
  189. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::POOL_STRING_ARRAY, "get_recognized_extensions"));
  190. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "handles_type", PropertyInfo(Variant::STRING, "typename")));
  191. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::STRING, "get_resource_type", PropertyInfo(Variant::STRING, "path")));
  192. ClassDB::add_virtual_method(get_class_static(), MethodInfo("get_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "add_types")));
  193. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::INT, "rename_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "renames")));
  194. }
  195. ///////////////////////////////////
  196. RES ResourceLoader::_load(const String &p_path, const String &p_original_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  197. bool found = false;
  198. // Try all loaders and pick the first match for the type hint
  199. for (int i = 0; i < loader_count; i++) {
  200. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  201. continue;
  202. }
  203. found = true;
  204. RES res = loader[i]->load(p_path, p_original_path != String() ? p_original_path : p_path, r_error);
  205. if (res.is_null()) {
  206. continue;
  207. }
  208. return res;
  209. }
  210. ERR_FAIL_COND_V_MSG(found, RES(),
  211. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  212. #ifdef TOOLS_ENABLED
  213. FileAccessRef file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  214. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), RES(), "Resource file not found: " + p_path + ".");
  215. #endif
  216. ERR_FAIL_V_MSG(RES(), "No loader found for resource: " + p_path + ".");
  217. }
  218. bool ResourceLoader::_add_to_loading_map(const String &p_path) {
  219. bool success;
  220. if (loading_map_mutex) {
  221. loading_map_mutex->lock();
  222. }
  223. LoadingMapKey key;
  224. key.path = p_path;
  225. key.thread = Thread::get_caller_id();
  226. if (loading_map.has(key)) {
  227. success = false;
  228. } else {
  229. loading_map[key] = true;
  230. success = true;
  231. }
  232. if (loading_map_mutex) {
  233. loading_map_mutex->unlock();
  234. }
  235. return success;
  236. }
  237. void ResourceLoader::_remove_from_loading_map(const String &p_path) {
  238. if (loading_map_mutex) {
  239. loading_map_mutex->lock();
  240. }
  241. LoadingMapKey key;
  242. key.path = p_path;
  243. key.thread = Thread::get_caller_id();
  244. loading_map.erase(key);
  245. if (loading_map_mutex) {
  246. loading_map_mutex->unlock();
  247. }
  248. }
  249. void ResourceLoader::_remove_from_loading_map_and_thread(const String &p_path, Thread::ID p_thread) {
  250. if (loading_map_mutex) {
  251. loading_map_mutex->lock();
  252. }
  253. LoadingMapKey key;
  254. key.path = p_path;
  255. key.thread = p_thread;
  256. loading_map.erase(key);
  257. if (loading_map_mutex) {
  258. loading_map_mutex->unlock();
  259. }
  260. }
  261. RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  262. if (r_error)
  263. *r_error = ERR_CANT_OPEN;
  264. String local_path;
  265. if (p_path.is_rel_path())
  266. local_path = "res://" + p_path;
  267. else
  268. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  269. if (!p_no_cache) {
  270. {
  271. bool success = _add_to_loading_map(local_path);
  272. ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
  273. }
  274. //lock first if possible
  275. if (ResourceCache::lock) {
  276. ResourceCache::lock->read_lock();
  277. }
  278. //get ptr
  279. Resource **rptr = ResourceCache::resources.getptr(local_path);
  280. if (rptr) {
  281. RES res(*rptr);
  282. //it is possible this resource was just freed in a thread. If so, this referencing will not work and resource is considered not cached
  283. if (res.is_valid()) {
  284. //referencing is fine
  285. if (r_error)
  286. *r_error = OK;
  287. if (ResourceCache::lock) {
  288. ResourceCache::lock->read_unlock();
  289. }
  290. _remove_from_loading_map(local_path);
  291. return res;
  292. }
  293. }
  294. if (ResourceCache::lock) {
  295. ResourceCache::lock->read_unlock();
  296. }
  297. }
  298. bool xl_remapped = false;
  299. String path = _path_remap(local_path, &xl_remapped);
  300. if (path == "") {
  301. if (!p_no_cache) {
  302. _remove_from_loading_map(local_path);
  303. }
  304. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  305. }
  306. print_verbose("Loading resource: " + path);
  307. RES res = _load(path, local_path, p_type_hint, p_no_cache, r_error);
  308. if (res.is_null()) {
  309. if (!p_no_cache) {
  310. _remove_from_loading_map(local_path);
  311. }
  312. return RES();
  313. }
  314. if (!p_no_cache)
  315. res->set_path(local_path);
  316. if (xl_remapped)
  317. res->set_as_translation_remapped(true);
  318. #ifdef TOOLS_ENABLED
  319. res->set_edited(false);
  320. if (timestamp_on_load) {
  321. uint64_t mt = FileAccess::get_modified_time(path);
  322. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  323. res->set_last_modified_time(mt);
  324. }
  325. #endif
  326. if (!p_no_cache) {
  327. _remove_from_loading_map(local_path);
  328. }
  329. if (_loaded_callback) {
  330. _loaded_callback(res, p_path);
  331. }
  332. return res;
  333. }
  334. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  335. String local_path;
  336. if (p_path.is_rel_path())
  337. local_path = "res://" + p_path;
  338. else
  339. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  340. if (ResourceCache::has(local_path)) {
  341. return true; // If cached, it probably exists
  342. }
  343. bool xl_remapped = false;
  344. String path = _path_remap(local_path, &xl_remapped);
  345. // Try all loaders and pick the first match for the type hint
  346. for (int i = 0; i < loader_count; i++) {
  347. if (!loader[i]->recognize_path(path, p_type_hint)) {
  348. continue;
  349. }
  350. if (loader[i]->exists(path))
  351. return true;
  352. }
  353. return false;
  354. }
  355. Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  356. if (r_error)
  357. *r_error = ERR_CANT_OPEN;
  358. String local_path;
  359. if (p_path.is_rel_path())
  360. local_path = "res://" + p_path;
  361. else
  362. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  363. if (!p_no_cache) {
  364. bool success = _add_to_loading_map(local_path);
  365. ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
  366. if (ResourceCache::has(local_path)) {
  367. print_verbose("Loading resource: " + local_path + " (cached)");
  368. Ref<Resource> res_cached = ResourceCache::get(local_path);
  369. Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
  370. ril->resource = res_cached;
  371. ril->path_loading = local_path;
  372. ril->path_loading_thread = Thread::get_caller_id();
  373. return ril;
  374. }
  375. }
  376. bool xl_remapped = false;
  377. String path = _path_remap(local_path, &xl_remapped);
  378. if (path == "") {
  379. if (!p_no_cache) {
  380. _remove_from_loading_map(local_path);
  381. }
  382. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  383. }
  384. print_verbose("Loading resource: " + path);
  385. bool found = false;
  386. for (int i = 0; i < loader_count; i++) {
  387. if (!loader[i]->recognize_path(path, p_type_hint))
  388. continue;
  389. found = true;
  390. Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(path, local_path, r_error);
  391. if (ril.is_null())
  392. continue;
  393. if (!p_no_cache) {
  394. ril->set_local_path(local_path);
  395. ril->path_loading = local_path;
  396. ril->path_loading_thread = Thread::get_caller_id();
  397. }
  398. if (xl_remapped)
  399. ril->set_translation_remapped(true);
  400. return ril;
  401. }
  402. if (!p_no_cache) {
  403. _remove_from_loading_map(local_path);
  404. }
  405. ERR_FAIL_COND_V_MSG(found, Ref<ResourceInteractiveLoader>(), "Failed loading resource: " + path + ".");
  406. ERR_FAIL_V_MSG(Ref<ResourceInteractiveLoader>(), "No loader found for resource: " + path + ".");
  407. }
  408. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  409. ERR_FAIL_COND(p_format_loader.is_null());
  410. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  411. if (p_at_front) {
  412. for (int i = loader_count; i > 0; i--) {
  413. loader[i] = loader[i - 1];
  414. }
  415. loader[0] = p_format_loader;
  416. loader_count++;
  417. } else {
  418. loader[loader_count++] = p_format_loader;
  419. }
  420. }
  421. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  422. ERR_FAIL_COND(p_format_loader.is_null());
  423. // Find loader
  424. int i = 0;
  425. for (; i < loader_count; ++i) {
  426. if (loader[i] == p_format_loader)
  427. break;
  428. }
  429. ERR_FAIL_COND(i >= loader_count); // Not found
  430. // Shift next loaders up
  431. for (; i < loader_count - 1; ++i) {
  432. loader[i] = loader[i + 1];
  433. }
  434. loader[loader_count - 1].unref();
  435. --loader_count;
  436. }
  437. int ResourceLoader::get_import_order(const String &p_path) {
  438. String path = _path_remap(p_path);
  439. String local_path;
  440. if (path.is_rel_path())
  441. local_path = "res://" + path;
  442. else
  443. local_path = ProjectSettings::get_singleton()->localize_path(path);
  444. for (int i = 0; i < loader_count; i++) {
  445. if (!loader[i]->recognize_path(local_path))
  446. continue;
  447. /*
  448. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  449. continue;
  450. */
  451. return loader[i]->get_import_order(p_path);
  452. }
  453. return 0;
  454. }
  455. String ResourceLoader::get_import_group_file(const String &p_path) {
  456. String path = _path_remap(p_path);
  457. String local_path;
  458. if (path.is_rel_path())
  459. local_path = "res://" + path;
  460. else
  461. local_path = ProjectSettings::get_singleton()->localize_path(path);
  462. for (int i = 0; i < loader_count; i++) {
  463. if (!loader[i]->recognize_path(local_path))
  464. continue;
  465. /*
  466. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  467. continue;
  468. */
  469. return loader[i]->get_import_group_file(p_path);
  470. }
  471. return String(); //not found
  472. }
  473. bool ResourceLoader::is_import_valid(const String &p_path) {
  474. String path = _path_remap(p_path);
  475. String local_path;
  476. if (path.is_rel_path())
  477. local_path = "res://" + path;
  478. else
  479. local_path = ProjectSettings::get_singleton()->localize_path(path);
  480. for (int i = 0; i < loader_count; i++) {
  481. if (!loader[i]->recognize_path(local_path))
  482. continue;
  483. /*
  484. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  485. continue;
  486. */
  487. return loader[i]->is_import_valid(p_path);
  488. }
  489. return false; //not found
  490. }
  491. bool ResourceLoader::is_imported(const String &p_path) {
  492. String path = _path_remap(p_path);
  493. String local_path;
  494. if (path.is_rel_path())
  495. local_path = "res://" + path;
  496. else
  497. local_path = ProjectSettings::get_singleton()->localize_path(path);
  498. for (int i = 0; i < loader_count; i++) {
  499. if (!loader[i]->recognize_path(local_path))
  500. continue;
  501. /*
  502. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  503. continue;
  504. */
  505. return loader[i]->is_imported(p_path);
  506. }
  507. return false; //not found
  508. }
  509. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  510. String path = _path_remap(p_path);
  511. String local_path;
  512. if (path.is_rel_path())
  513. local_path = "res://" + path;
  514. else
  515. local_path = ProjectSettings::get_singleton()->localize_path(path);
  516. for (int i = 0; i < loader_count; i++) {
  517. if (!loader[i]->recognize_path(local_path))
  518. continue;
  519. /*
  520. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  521. continue;
  522. */
  523. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  524. }
  525. }
  526. Error ResourceLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  527. String path = _path_remap(p_path);
  528. String local_path;
  529. if (path.is_rel_path())
  530. local_path = "res://" + path;
  531. else
  532. local_path = ProjectSettings::get_singleton()->localize_path(path);
  533. for (int i = 0; i < loader_count; i++) {
  534. if (!loader[i]->recognize_path(local_path))
  535. continue;
  536. /*
  537. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  538. continue;
  539. */
  540. return loader[i]->rename_dependencies(local_path, p_map);
  541. }
  542. return OK; // ??
  543. }
  544. String ResourceLoader::get_resource_type(const String &p_path) {
  545. String local_path;
  546. if (p_path.is_rel_path())
  547. local_path = "res://" + p_path;
  548. else
  549. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  550. for (int i = 0; i < loader_count; i++) {
  551. String result = loader[i]->get_resource_type(local_path);
  552. if (result != "")
  553. return result;
  554. }
  555. return "";
  556. }
  557. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  558. String new_path = p_path;
  559. if (translation_remaps.has(p_path)) {
  560. // translation_remaps has the following format:
  561. // { "res://path.png": PoolStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  562. // To find the path of the remapped resource, we extract the locale name after
  563. // the last ':' to match the project locale.
  564. // We also fall back in case of regional locales as done in TranslationServer::translate
  565. // (e.g. 'ru_RU' -> 'ru' if the former has no specific mapping).
  566. String locale = TranslationServer::get_singleton()->get_locale();
  567. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  568. String lang = TranslationServer::get_language_code(locale);
  569. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  570. bool near_match = false;
  571. for (int i = 0; i < res_remaps.size(); i++) {
  572. int split = res_remaps[i].find_last(":");
  573. if (split == -1) {
  574. continue;
  575. }
  576. String l = res_remaps[i].right(split + 1).strip_edges();
  577. if (l == locale) { // Exact match.
  578. new_path = res_remaps[i].left(split);
  579. break;
  580. } else if (near_match) {
  581. continue; // Already found near match, keep going for potential exact match.
  582. }
  583. // No exact match (e.g. locale 'ru_RU' but remap is 'ru'), let's look further
  584. // for a near match (same language code, i.e. first 2 or 3 letters before
  585. // regional code, if included).
  586. if (TranslationServer::get_language_code(l) == lang) {
  587. // Language code matches, that's a near match. Keep looking for exact match.
  588. near_match = true;
  589. new_path = res_remaps[i].left(split);
  590. continue;
  591. }
  592. }
  593. if (r_translation_remapped) {
  594. *r_translation_remapped = true;
  595. }
  596. }
  597. if (path_remaps.has(new_path)) {
  598. new_path = path_remaps[new_path];
  599. }
  600. if (new_path == p_path) { // Did not remap.
  601. // Try file remap.
  602. Error err;
  603. FileAccess *f = FileAccess::open(p_path + ".remap", FileAccess::READ, &err);
  604. if (f) {
  605. VariantParser::StreamFile stream;
  606. stream.f = f;
  607. String assign;
  608. Variant value;
  609. VariantParser::Tag next_tag;
  610. int lines = 0;
  611. String error_text;
  612. while (true) {
  613. assign = Variant();
  614. next_tag.fields.clear();
  615. next_tag.name = String();
  616. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true);
  617. if (err == ERR_FILE_EOF) {
  618. break;
  619. } else if (err != OK) {
  620. ERR_PRINTS("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  621. break;
  622. }
  623. if (assign == "path") {
  624. new_path = value;
  625. break;
  626. } else if (next_tag.name != "remap") {
  627. break;
  628. }
  629. }
  630. memdelete(f);
  631. }
  632. }
  633. return new_path;
  634. }
  635. String ResourceLoader::import_remap(const String &p_path) {
  636. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  637. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  638. }
  639. return p_path;
  640. }
  641. String ResourceLoader::path_remap(const String &p_path) {
  642. return _path_remap(p_path);
  643. }
  644. void ResourceLoader::reload_translation_remaps() {
  645. if (ResourceCache::lock) {
  646. ResourceCache::lock->read_lock();
  647. }
  648. List<Resource *> to_reload;
  649. SelfList<Resource> *E = remapped_list.first();
  650. while (E) {
  651. to_reload.push_back(E->self());
  652. E = E->next();
  653. }
  654. if (ResourceCache::lock) {
  655. ResourceCache::lock->read_unlock();
  656. }
  657. //now just make sure to not delete any of these resources while changing locale..
  658. while (to_reload.front()) {
  659. to_reload.front()->get()->reload_from_file();
  660. to_reload.pop_front();
  661. }
  662. }
  663. void ResourceLoader::load_translation_remaps() {
  664. if (!ProjectSettings::get_singleton()->has_setting("locale/translation_remaps"))
  665. return;
  666. Dictionary remaps = ProjectSettings::get_singleton()->get("locale/translation_remaps");
  667. List<Variant> keys;
  668. remaps.get_key_list(&keys);
  669. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  670. Array langs = remaps[E->get()];
  671. Vector<String> lang_remaps;
  672. lang_remaps.resize(langs.size());
  673. for (int i = 0; i < langs.size(); i++) {
  674. lang_remaps.write[i] = langs[i];
  675. }
  676. translation_remaps[String(E->get())] = lang_remaps;
  677. }
  678. }
  679. void ResourceLoader::clear_translation_remaps() {
  680. translation_remaps.clear();
  681. while (remapped_list.first() != nullptr) {
  682. remapped_list.remove(remapped_list.first());
  683. }
  684. }
  685. void ResourceLoader::load_path_remaps() {
  686. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths"))
  687. return;
  688. PoolVector<String> remaps = ProjectSettings::get_singleton()->get("path_remap/remapped_paths");
  689. int rc = remaps.size();
  690. ERR_FAIL_COND(rc & 1); //must be even
  691. PoolVector<String>::Read r = remaps.read();
  692. for (int i = 0; i < rc; i += 2) {
  693. path_remaps[r[i]] = r[i + 1];
  694. }
  695. }
  696. void ResourceLoader::clear_path_remaps() {
  697. path_remaps.clear();
  698. }
  699. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  700. _loaded_callback = p_callback;
  701. }
  702. ResourceLoadedCallback ResourceLoader::_loaded_callback = NULL;
  703. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  704. for (int i = 0; i < loader_count; ++i) {
  705. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  706. return loader[i];
  707. }
  708. }
  709. return Ref<ResourceFormatLoader>();
  710. }
  711. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  712. if (_find_custom_resource_format_loader(script_path).is_valid())
  713. return false;
  714. Ref<Resource> res = ResourceLoader::load(script_path);
  715. ERR_FAIL_COND_V(res.is_null(), false);
  716. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  717. Ref<Script> s = res;
  718. StringName ibt = s->get_instance_base_type();
  719. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  720. ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
  721. Object *obj = ClassDB::instance(ibt);
  722. ERR_FAIL_COND_V_MSG(obj == NULL, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
  723. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  724. crl->set_script(s.get_ref_ptr());
  725. ResourceLoader::add_resource_format_loader(crl);
  726. return true;
  727. }
  728. void ResourceLoader::remove_custom_resource_format_loader(String script_path) {
  729. Ref<ResourceFormatLoader> custom_loader = _find_custom_resource_format_loader(script_path);
  730. if (custom_loader.is_valid())
  731. remove_resource_format_loader(custom_loader);
  732. }
  733. void ResourceLoader::add_custom_loaders() {
  734. // Custom loaders registration exploits global class names
  735. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  736. List<StringName> global_classes;
  737. ScriptServer::get_global_class_list(&global_classes);
  738. for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) {
  739. StringName class_name = E->get();
  740. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  741. if (base_class == custom_loader_base_class) {
  742. String path = ScriptServer::get_global_class_path(class_name);
  743. add_custom_resource_format_loader(path);
  744. }
  745. }
  746. }
  747. void ResourceLoader::remove_custom_loaders() {
  748. Vector<Ref<ResourceFormatLoader> > custom_loaders;
  749. for (int i = 0; i < loader_count; ++i) {
  750. if (loader[i]->get_script_instance()) {
  751. custom_loaders.push_back(loader[i]);
  752. }
  753. }
  754. for (int i = 0; i < custom_loaders.size(); ++i) {
  755. remove_resource_format_loader(custom_loaders[i]);
  756. }
  757. }
  758. Mutex *ResourceLoader::loading_map_mutex = NULL;
  759. HashMap<ResourceLoader::LoadingMapKey, int, ResourceLoader::LoadingMapKeyHasher> ResourceLoader::loading_map;
  760. void ResourceLoader::initialize() {
  761. #ifndef NO_THREADS
  762. loading_map_mutex = Mutex::create();
  763. #endif
  764. }
  765. void ResourceLoader::finalize() {
  766. #ifndef NO_THREADS
  767. const LoadingMapKey *K = NULL;
  768. while ((K = loading_map.next(K))) {
  769. ERR_PRINTS("Exited while resource is being loaded: " + K->path);
  770. }
  771. loading_map.clear();
  772. memdelete(loading_map_mutex);
  773. loading_map_mutex = NULL;
  774. #endif
  775. }
  776. ResourceLoadErrorNotify ResourceLoader::err_notify = NULL;
  777. void *ResourceLoader::err_notify_ud = NULL;
  778. DependencyErrorNotify ResourceLoader::dep_err_notify = NULL;
  779. void *ResourceLoader::dep_err_notify_ud = NULL;
  780. bool ResourceLoader::abort_on_missing_resource = true;
  781. bool ResourceLoader::timestamp_on_load = false;
  782. SelfList<Resource>::List ResourceLoader::remapped_list;
  783. HashMap<String, Vector<String> > ResourceLoader::translation_remaps;
  784. HashMap<String, String> ResourceLoader::path_remaps;
  785. ResourceLoaderImport ResourceLoader::import = NULL;