resource_loader.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. /*************************************************************************/
  2. /* resource_loader.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "resource_loader.h"
  31. #include "core/io/resource_importer.h"
  32. #include "core/os/file_access.h"
  33. #include "core/os/os.h"
  34. #include "core/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. PackedStringArray exts = get_script_instance()->call("get_recognized_extensions");
  124. {
  125. const String *r = exts.ptr();
  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. PackedStringArray deps = get_script_instance()->call("get_dependencies", p_path, p_add_types);
  164. {
  165. const String *r = deps.ptr();
  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::PACKED_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(), "Failed loading resource: " + p_path + ".");
  211. #ifdef TOOLS_ENABLED
  212. FileAccessRef file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  213. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), RES(), "Resource file not found: " + p_path + ".");
  214. #endif
  215. ERR_FAIL_V_MSG(RES(), "No loader found for resource: " + p_path + ".");
  216. }
  217. bool ResourceLoader::_add_to_loading_map(const String &p_path) {
  218. bool success;
  219. if (loading_map_mutex) {
  220. loading_map_mutex->lock();
  221. }
  222. LoadingMapKey key;
  223. key.path = p_path;
  224. key.thread = Thread::get_caller_id();
  225. if (loading_map.has(key)) {
  226. success = false;
  227. } else {
  228. loading_map[key] = true;
  229. success = true;
  230. }
  231. if (loading_map_mutex) {
  232. loading_map_mutex->unlock();
  233. }
  234. return success;
  235. }
  236. void ResourceLoader::_remove_from_loading_map(const String &p_path) {
  237. if (loading_map_mutex) {
  238. loading_map_mutex->lock();
  239. }
  240. LoadingMapKey key;
  241. key.path = p_path;
  242. key.thread = Thread::get_caller_id();
  243. loading_map.erase(key);
  244. if (loading_map_mutex) {
  245. loading_map_mutex->unlock();
  246. }
  247. }
  248. void ResourceLoader::_remove_from_loading_map_and_thread(const String &p_path, Thread::ID p_thread) {
  249. if (loading_map_mutex) {
  250. loading_map_mutex->lock();
  251. }
  252. LoadingMapKey key;
  253. key.path = p_path;
  254. key.thread = p_thread;
  255. loading_map.erase(key);
  256. if (loading_map_mutex) {
  257. loading_map_mutex->unlock();
  258. }
  259. }
  260. RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  261. if (r_error)
  262. *r_error = ERR_CANT_OPEN;
  263. String local_path;
  264. if (p_path.is_rel_path())
  265. local_path = "res://" + p_path;
  266. else
  267. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  268. if (!p_no_cache) {
  269. {
  270. bool success = _add_to_loading_map(local_path);
  271. ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
  272. }
  273. //lock first if possible
  274. if (ResourceCache::lock) {
  275. ResourceCache::lock->read_lock();
  276. }
  277. //get ptr
  278. Resource **rptr = ResourceCache::resources.getptr(local_path);
  279. if (rptr) {
  280. RES res(*rptr);
  281. //it is possible this resource was just freed in a thread. If so, this referencing will not work and resource is considered not cached
  282. if (res.is_valid()) {
  283. //referencing is fine
  284. if (r_error)
  285. *r_error = OK;
  286. if (ResourceCache::lock) {
  287. ResourceCache::lock->read_unlock();
  288. }
  289. _remove_from_loading_map(local_path);
  290. return res;
  291. }
  292. }
  293. if (ResourceCache::lock) {
  294. ResourceCache::lock->read_unlock();
  295. }
  296. }
  297. bool xl_remapped = false;
  298. String path = _path_remap(local_path, &xl_remapped);
  299. if (path == "") {
  300. if (!p_no_cache) {
  301. _remove_from_loading_map(local_path);
  302. }
  303. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  304. }
  305. print_verbose("Loading resource: " + path);
  306. RES res = _load(path, local_path, p_type_hint, p_no_cache, r_error);
  307. if (res.is_null()) {
  308. if (!p_no_cache) {
  309. _remove_from_loading_map(local_path);
  310. }
  311. print_verbose("Failed loading resource: " + path);
  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. }
  556. return "";
  557. }
  558. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  559. String new_path = p_path;
  560. if (translation_remaps.has(p_path)) {
  561. // translation_remaps has the following format:
  562. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  563. // To find the path of the remapped resource, we extract the locale name after
  564. // the last ':' to match the project locale.
  565. // We also fall back in case of regional locales as done in TranslationServer::translate
  566. // (e.g. 'ru_RU' -> 'ru' if the former has no specific mapping).
  567. String locale = TranslationServer::get_singleton()->get_locale();
  568. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  569. String lang = TranslationServer::get_language_code(locale);
  570. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  571. bool near_match = false;
  572. for (int i = 0; i < res_remaps.size(); i++) {
  573. int split = res_remaps[i].find_last(":");
  574. if (split == -1) {
  575. continue;
  576. }
  577. String l = res_remaps[i].right(split + 1).strip_edges();
  578. if (l == locale) { // Exact match.
  579. new_path = res_remaps[i].left(split);
  580. break;
  581. } else if (near_match) {
  582. continue; // Already found near match, keep going for potential exact match.
  583. }
  584. // No exact match (e.g. locale 'ru_RU' but remap is 'ru'), let's look further
  585. // for a near match (same language code, i.e. first 2 or 3 letters before
  586. // regional code, if included).
  587. if (TranslationServer::get_language_code(l) == lang) {
  588. // Language code matches, that's a near match. Keep looking for exact match.
  589. near_match = true;
  590. new_path = res_remaps[i].left(split);
  591. continue;
  592. }
  593. }
  594. if (r_translation_remapped) {
  595. *r_translation_remapped = true;
  596. }
  597. }
  598. if (path_remaps.has(new_path)) {
  599. new_path = path_remaps[new_path];
  600. }
  601. if (new_path == p_path) { // Did not remap.
  602. // Try file remap.
  603. Error err;
  604. FileAccess *f = FileAccess::open(p_path + ".remap", FileAccess::READ, &err);
  605. if (f) {
  606. VariantParser::StreamFile stream;
  607. stream.f = f;
  608. String assign;
  609. Variant value;
  610. VariantParser::Tag next_tag;
  611. int lines = 0;
  612. String error_text;
  613. while (true) {
  614. assign = Variant();
  615. next_tag.fields.clear();
  616. next_tag.name = String();
  617. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true);
  618. if (err == ERR_FILE_EOF) {
  619. break;
  620. } else if (err != OK) {
  621. ERR_PRINT("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  622. break;
  623. }
  624. if (assign == "path") {
  625. new_path = value;
  626. break;
  627. } else if (next_tag.name != "remap") {
  628. break;
  629. }
  630. }
  631. memdelete(f);
  632. }
  633. }
  634. return new_path;
  635. }
  636. String ResourceLoader::import_remap(const String &p_path) {
  637. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  638. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  639. }
  640. return p_path;
  641. }
  642. String ResourceLoader::path_remap(const String &p_path) {
  643. return _path_remap(p_path);
  644. }
  645. void ResourceLoader::reload_translation_remaps() {
  646. if (ResourceCache::lock) {
  647. ResourceCache::lock->read_lock();
  648. }
  649. List<Resource *> to_reload;
  650. SelfList<Resource> *E = remapped_list.first();
  651. while (E) {
  652. to_reload.push_back(E->self());
  653. E = E->next();
  654. }
  655. if (ResourceCache::lock) {
  656. ResourceCache::lock->read_unlock();
  657. }
  658. //now just make sure to not delete any of these resources while changing locale..
  659. while (to_reload.front()) {
  660. to_reload.front()->get()->reload_from_file();
  661. to_reload.pop_front();
  662. }
  663. }
  664. void ResourceLoader::load_translation_remaps() {
  665. if (!ProjectSettings::get_singleton()->has_setting("locale/translation_remaps"))
  666. return;
  667. Dictionary remaps = ProjectSettings::get_singleton()->get("locale/translation_remaps");
  668. List<Variant> keys;
  669. remaps.get_key_list(&keys);
  670. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  671. Array langs = remaps[E->get()];
  672. Vector<String> lang_remaps;
  673. lang_remaps.resize(langs.size());
  674. for (int i = 0; i < langs.size(); i++) {
  675. lang_remaps.write[i] = langs[i];
  676. }
  677. translation_remaps[String(E->get())] = lang_remaps;
  678. }
  679. }
  680. void ResourceLoader::clear_translation_remaps() {
  681. translation_remaps.clear();
  682. }
  683. void ResourceLoader::load_path_remaps() {
  684. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths"))
  685. return;
  686. Vector<String> remaps = ProjectSettings::get_singleton()->get("path_remap/remapped_paths");
  687. int rc = remaps.size();
  688. ERR_FAIL_COND(rc & 1); //must be even
  689. const String *r = remaps.ptr();
  690. for (int i = 0; i < rc; i += 2) {
  691. path_remaps[r[i]] = r[i + 1];
  692. }
  693. }
  694. void ResourceLoader::clear_path_remaps() {
  695. path_remaps.clear();
  696. }
  697. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  698. _loaded_callback = p_callback;
  699. }
  700. ResourceLoadedCallback ResourceLoader::_loaded_callback = NULL;
  701. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  702. for (int i = 0; i < loader_count; ++i) {
  703. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  704. return loader[i];
  705. }
  706. }
  707. return Ref<ResourceFormatLoader>();
  708. }
  709. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  710. if (_find_custom_resource_format_loader(script_path).is_valid())
  711. return false;
  712. Ref<Resource> res = ResourceLoader::load(script_path);
  713. ERR_FAIL_COND_V(res.is_null(), false);
  714. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  715. Ref<Script> s = res;
  716. StringName ibt = s->get_instance_base_type();
  717. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  718. ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
  719. Object *obj = ClassDB::instance(ibt);
  720. ERR_FAIL_COND_V_MSG(obj == NULL, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
  721. ResourceFormatLoader *crl = Object::cast_to<ResourceFormatLoader>(obj);
  722. crl->set_script(s);
  723. ResourceLoader::add_resource_format_loader(crl);
  724. return true;
  725. }
  726. void ResourceLoader::remove_custom_resource_format_loader(String script_path) {
  727. Ref<ResourceFormatLoader> custom_loader = _find_custom_resource_format_loader(script_path);
  728. if (custom_loader.is_valid())
  729. remove_resource_format_loader(custom_loader);
  730. }
  731. void ResourceLoader::add_custom_loaders() {
  732. // Custom loaders registration exploits global class names
  733. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  734. List<StringName> global_classes;
  735. ScriptServer::get_global_class_list(&global_classes);
  736. for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) {
  737. StringName class_name = E->get();
  738. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  739. if (base_class == custom_loader_base_class) {
  740. String path = ScriptServer::get_global_class_path(class_name);
  741. add_custom_resource_format_loader(path);
  742. }
  743. }
  744. }
  745. void ResourceLoader::remove_custom_loaders() {
  746. Vector<Ref<ResourceFormatLoader> > custom_loaders;
  747. for (int i = 0; i < loader_count; ++i) {
  748. if (loader[i]->get_script_instance()) {
  749. custom_loaders.push_back(loader[i]);
  750. }
  751. }
  752. for (int i = 0; i < custom_loaders.size(); ++i) {
  753. remove_resource_format_loader(custom_loaders[i]);
  754. }
  755. }
  756. Mutex *ResourceLoader::loading_map_mutex = NULL;
  757. HashMap<ResourceLoader::LoadingMapKey, int, ResourceLoader::LoadingMapKeyHasher> ResourceLoader::loading_map;
  758. void ResourceLoader::initialize() {
  759. #ifndef NO_THREADS
  760. loading_map_mutex = Mutex::create();
  761. #endif
  762. }
  763. void ResourceLoader::finalize() {
  764. #ifndef NO_THREADS
  765. const LoadingMapKey *K = NULL;
  766. while ((K = loading_map.next(K))) {
  767. ERR_PRINT("Exited while resource is being loaded: " + K->path);
  768. }
  769. loading_map.clear();
  770. memdelete(loading_map_mutex);
  771. loading_map_mutex = NULL;
  772. #endif
  773. }
  774. ResourceLoadErrorNotify ResourceLoader::err_notify = NULL;
  775. void *ResourceLoader::err_notify_ud = NULL;
  776. DependencyErrorNotify ResourceLoader::dep_err_notify = NULL;
  777. void *ResourceLoader::dep_err_notify_ud = NULL;
  778. bool ResourceLoader::abort_on_missing_resource = true;
  779. bool ResourceLoader::timestamp_on_load = false;
  780. SelfList<Resource>::List ResourceLoader::remapped_list;
  781. HashMap<String, Vector<String> > ResourceLoader::translation_remaps;
  782. HashMap<String, String> ResourceLoader::path_remaps;
  783. ResourceLoaderImport ResourceLoader::import = NULL;