resource_format_text.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  1. /**************************************************************************/
  2. /* resource_format_text.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_format_text.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/dir_access.h"
  33. #include "core/io/missing_resource.h"
  34. #include "core/object/script_language.h"
  35. #include "scene/property_utils.h"
  36. void ResourceLoaderText::_printerr() {
  37. ERR_PRINT(vformat("%s:%d - Parse Error: %s.", res_path, lines, error_text));
  38. }
  39. Ref<Resource> ResourceLoaderText::get_resource() {
  40. return resource;
  41. }
  42. Error ResourceLoaderText::_parse_sub_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  43. VariantParser::Token token;
  44. VariantParser::get_token(p_stream, token, line, r_err_str);
  45. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  46. r_err_str = "Expected number (old style) or string (sub-resource index)";
  47. return ERR_PARSE_ERROR;
  48. }
  49. if (p_data->no_placeholders) {
  50. r_res.unref();
  51. } else {
  52. String unique_id = token.value;
  53. if (!p_data->resource_map.has(unique_id)) {
  54. r_err_str = "Found unique_id reference before mapping, sub-resources stored out of order in resource file";
  55. return ERR_PARSE_ERROR;
  56. }
  57. r_res = p_data->resource_map[unique_id];
  58. }
  59. VariantParser::get_token(p_stream, token, line, r_err_str);
  60. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  61. r_err_str = "Expected ')'";
  62. return ERR_PARSE_ERROR;
  63. }
  64. return OK;
  65. }
  66. Error ResourceLoaderText::_parse_ext_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  67. VariantParser::Token token;
  68. VariantParser::get_token(p_stream, token, line, r_err_str);
  69. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  70. r_err_str = "Expected number (old style sub-resource index) or String (ext-resource ID)";
  71. return ERR_PARSE_ERROR;
  72. }
  73. if (p_data->no_placeholders) {
  74. r_res.unref();
  75. } else {
  76. String id = token.value;
  77. ERR_FAIL_COND_V(!p_data->rev_external_resources.has(id), ERR_PARSE_ERROR);
  78. r_res = p_data->rev_external_resources[id];
  79. }
  80. VariantParser::get_token(p_stream, token, line, r_err_str);
  81. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  82. r_err_str = "Expected ')'";
  83. return ERR_PARSE_ERROR;
  84. }
  85. return OK;
  86. }
  87. Error ResourceLoaderText::_parse_sub_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  88. VariantParser::Token token;
  89. VariantParser::get_token(p_stream, token, line, r_err_str);
  90. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  91. r_err_str = "Expected number (old style sub-resource index) or string";
  92. return ERR_PARSE_ERROR;
  93. }
  94. String id = token.value;
  95. ERR_FAIL_COND_V(!int_resources.has(id), ERR_INVALID_PARAMETER);
  96. r_res = int_resources[id];
  97. VariantParser::get_token(p_stream, token, line, r_err_str);
  98. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  99. r_err_str = "Expected ')'";
  100. return ERR_PARSE_ERROR;
  101. }
  102. return OK;
  103. }
  104. Error ResourceLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  105. VariantParser::Token token;
  106. VariantParser::get_token(p_stream, token, line, r_err_str);
  107. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  108. r_err_str = "Expected number (old style sub-resource index) or String (ext-resource ID)";
  109. return ERR_PARSE_ERROR;
  110. }
  111. String id = token.value;
  112. Error err = OK;
  113. if (!ignore_resource_parsing) {
  114. if (!ext_resources.has(id)) {
  115. r_err_str = "Can't load cached ext-resource id: " + id;
  116. return ERR_PARSE_ERROR;
  117. }
  118. String path = ext_resources[id].path;
  119. String type = ext_resources[id].type;
  120. Ref<ResourceLoader::LoadToken> &load_token = ext_resources[id].load_token;
  121. if (load_token.is_valid()) { // If not valid, it's OK since then we know this load accepts broken dependencies.
  122. Ref<Resource> res = ResourceLoader::_load_complete(*load_token.ptr(), &err);
  123. if (res.is_null()) {
  124. if (!ResourceLoader::is_cleaning_tasks()) {
  125. if (ResourceLoader::get_abort_on_missing_resources()) {
  126. error = ERR_FILE_MISSING_DEPENDENCIES;
  127. error_text = "[ext_resource] referenced non-existent resource at: " + path;
  128. _printerr();
  129. err = error;
  130. } else {
  131. ResourceLoader::notify_dependency_error(local_path, path, type);
  132. }
  133. }
  134. } else {
  135. r_res = res;
  136. }
  137. } else {
  138. r_res = Ref<Resource>();
  139. }
  140. #ifdef TOOLS_ENABLED
  141. if (r_res.is_null()) {
  142. // Hack to allow checking original path.
  143. r_res.instantiate();
  144. r_res->set_meta("__load_path__", ext_resources[id].path);
  145. }
  146. #endif
  147. }
  148. VariantParser::get_token(p_stream, token, line, r_err_str);
  149. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  150. r_err_str = "Expected ')'";
  151. return ERR_PARSE_ERROR;
  152. }
  153. return err;
  154. }
  155. Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourceParser &parser) {
  156. Ref<PackedScene> packed_scene = ResourceLoader::get_resource_ref_override(local_path);
  157. if (packed_scene.is_null()) {
  158. packed_scene.instantiate();
  159. }
  160. while (true) {
  161. if (next_tag.name == "node") {
  162. int parent = -1;
  163. int owner = -1;
  164. int type = -1;
  165. int name = -1;
  166. int instance = -1;
  167. int index = -1;
  168. int unique_id = Node::UNIQUE_SCENE_ID_UNASSIGNED;
  169. //int base_scene=-1;
  170. if (next_tag.fields.has("name")) {
  171. name = packed_scene->get_state()->add_name(next_tag.fields["name"]);
  172. }
  173. if (next_tag.fields.has("parent")) {
  174. NodePath np = next_tag.fields["parent"];
  175. np.prepend_period();
  176. PackedInt32Array np_id;
  177. if (next_tag.fields.has("parent_id_path")) {
  178. np_id = next_tag.fields["parent_id_path"];
  179. }
  180. parent = packed_scene->get_state()->add_node_path(np, np_id);
  181. }
  182. if (next_tag.fields.has("unique_id")) {
  183. unique_id = next_tag.fields["unique_id"];
  184. }
  185. if (next_tag.fields.has("type")) {
  186. type = packed_scene->get_state()->add_name(next_tag.fields["type"]);
  187. } else {
  188. type = SceneState::TYPE_INSTANTIATED; //no type? assume this was instantiated
  189. }
  190. HashSet<StringName> path_properties;
  191. if (next_tag.fields.has("node_paths")) {
  192. Vector<String> paths = next_tag.fields["node_paths"];
  193. for (int i = 0; i < paths.size(); i++) {
  194. path_properties.insert(paths[i]);
  195. }
  196. }
  197. if (next_tag.fields.has("instance")) {
  198. instance = packed_scene->get_state()->add_value(next_tag.fields["instance"]);
  199. if (packed_scene->get_state()->get_node_count() == 0 && parent == -1) {
  200. packed_scene->get_state()->set_base_scene(instance);
  201. instance = -1;
  202. }
  203. }
  204. if (next_tag.fields.has("instance_placeholder")) {
  205. String path = next_tag.fields["instance_placeholder"];
  206. int path_v = packed_scene->get_state()->add_value(path);
  207. if (packed_scene->get_state()->get_node_count() == 0) {
  208. error = ERR_FILE_CORRUPT;
  209. error_text = "Instance Placeholder can't be used for inheritance";
  210. _printerr();
  211. return Ref<PackedScene>();
  212. }
  213. instance = path_v | SceneState::FLAG_INSTANCE_IS_PLACEHOLDER;
  214. }
  215. if (next_tag.fields.has("owner")) {
  216. PackedInt32Array np_id;
  217. if (next_tag.fields.has("owner_uid_path")) {
  218. np_id = next_tag.fields["owner_uid_path"];
  219. }
  220. owner = packed_scene->get_state()->add_node_path(next_tag.fields["owner"], np_id);
  221. } else {
  222. if (parent != -1 && !(type == SceneState::TYPE_INSTANTIATED && instance == -1)) {
  223. owner = 0; //if no owner, owner is root
  224. }
  225. }
  226. if (next_tag.fields.has("index")) {
  227. index = next_tag.fields["index"];
  228. }
  229. int node_id = packed_scene->get_state()->add_node(parent, owner, type, name, instance, index, unique_id);
  230. if (next_tag.fields.has("groups")) {
  231. Array groups = next_tag.fields["groups"];
  232. for (const Variant &group : groups) {
  233. packed_scene->get_state()->add_node_group(node_id, packed_scene->get_state()->add_name(group));
  234. }
  235. }
  236. while (true) {
  237. String assign;
  238. Variant value;
  239. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &parser);
  240. if (error) {
  241. if (error == ERR_FILE_MISSING_DEPENDENCIES) {
  242. // Resource loading error, just skip it.
  243. } else if (error != ERR_FILE_EOF) {
  244. ERR_PRINT(vformat("Parse Error: %s. [Resource file %s:%d]", error_names[error], res_path, lines));
  245. return Ref<PackedScene>();
  246. } else {
  247. error = OK;
  248. return packed_scene;
  249. }
  250. }
  251. if (!assign.is_empty()) {
  252. StringName assign_name = assign;
  253. int nameidx = packed_scene->get_state()->add_name(assign_name);
  254. int valueidx = packed_scene->get_state()->add_value(value);
  255. packed_scene->get_state()->add_node_property(node_id, nameidx, valueidx, path_properties.has(assign_name));
  256. //it's assignment
  257. } else if (!next_tag.name.is_empty()) {
  258. break;
  259. }
  260. }
  261. } else if (next_tag.name == "connection") {
  262. if (!next_tag.fields.has("from")) {
  263. error = ERR_FILE_CORRUPT;
  264. error_text = "missing 'from' field from connection tag";
  265. return Ref<PackedScene>();
  266. }
  267. if (!next_tag.fields.has("to")) {
  268. error = ERR_FILE_CORRUPT;
  269. error_text = "missing 'to' field from connection tag";
  270. return Ref<PackedScene>();
  271. }
  272. if (!next_tag.fields.has("signal")) {
  273. error = ERR_FILE_CORRUPT;
  274. error_text = "missing 'signal' field from connection tag";
  275. return Ref<PackedScene>();
  276. }
  277. if (!next_tag.fields.has("method")) {
  278. error = ERR_FILE_CORRUPT;
  279. error_text = "missing 'method' field from connection tag";
  280. return Ref<PackedScene>();
  281. }
  282. NodePath from = next_tag.fields["from"];
  283. NodePath to = next_tag.fields["to"];
  284. StringName method = next_tag.fields["method"];
  285. StringName signal = next_tag.fields["signal"];
  286. int flags = Object::CONNECT_PERSIST;
  287. int unbinds = 0;
  288. Array binds;
  289. PackedInt32Array from_id;
  290. if (next_tag.fields.has("from_uid_path")) {
  291. from_id = next_tag.fields["from_uid_path"];
  292. }
  293. PackedInt32Array to_id;
  294. if (next_tag.fields.has("to_uid_path")) {
  295. to_id = next_tag.fields["to_uid_path"];
  296. }
  297. if (next_tag.fields.has("flags")) {
  298. flags = next_tag.fields["flags"];
  299. }
  300. if (next_tag.fields.has("binds")) {
  301. binds = next_tag.fields["binds"];
  302. }
  303. if (next_tag.fields.has("unbinds")) {
  304. unbinds = next_tag.fields["unbinds"];
  305. }
  306. Vector<int> bind_ints;
  307. for (const Variant &bind : binds) {
  308. bind_ints.push_back(packed_scene->get_state()->add_value(bind));
  309. }
  310. packed_scene->get_state()->add_connection(
  311. packed_scene->get_state()->add_node_path(from.simplified(), from_id),
  312. packed_scene->get_state()->add_node_path(to.simplified(), to_id),
  313. packed_scene->get_state()->add_name(signal),
  314. packed_scene->get_state()->add_name(method),
  315. flags,
  316. unbinds,
  317. bind_ints);
  318. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
  319. if (error) {
  320. if (error != ERR_FILE_EOF) {
  321. _printerr();
  322. return Ref<PackedScene>();
  323. } else {
  324. error = OK;
  325. return packed_scene;
  326. }
  327. }
  328. } else if (next_tag.name == "editable") {
  329. if (!next_tag.fields.has("path")) {
  330. error = ERR_FILE_CORRUPT;
  331. error_text = "Missing 'path' field from editable tag";
  332. _printerr();
  333. return Ref<PackedScene>();
  334. }
  335. NodePath path = next_tag.fields["path"];
  336. packed_scene->get_state()->add_editable_instance(path.simplified());
  337. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
  338. if (error) {
  339. if (error != ERR_FILE_EOF) {
  340. _printerr();
  341. return Ref<PackedScene>();
  342. } else {
  343. error = OK;
  344. return packed_scene;
  345. }
  346. }
  347. } else {
  348. error = ERR_FILE_CORRUPT;
  349. error_text = vformat("Unknown tag '%s' in file", next_tag.name);
  350. _printerr();
  351. return Ref<PackedScene>();
  352. }
  353. }
  354. }
  355. void ResourceLoaderText::_count_resources() {
  356. Ref<FileAccess> scan_f = FileAccess::open(f->get_path(), FileAccess::READ);
  357. if (scan_f.is_null()) {
  358. return;
  359. }
  360. resources_total = 0;
  361. resource_current = 0;
  362. bool has_main_resource = false;
  363. while (!scan_f->eof_reached()) {
  364. String line = scan_f->get_line().strip_edges();
  365. // Only count resources that contribute to progress
  366. // (ext_resources are loaded asynchronously and don't count).
  367. // Note: nodes are all parsed together as part of the main resource (PackedScene),
  368. // so they only contribute 1 to the progress count, not one per node.
  369. if (line.begins_with("[sub_resource ")) {
  370. resources_total++;
  371. } else if (line.begins_with("[resource]") || line.begins_with("[node ")) {
  372. // Main resource or scene with nodes - only count once.
  373. if (!has_main_resource) {
  374. resources_total++;
  375. has_main_resource = true;
  376. }
  377. }
  378. }
  379. }
  380. Error ResourceLoaderText::load() {
  381. if (error != OK) {
  382. return error;
  383. }
  384. if (progress) {
  385. _count_resources();
  386. }
  387. while (true) {
  388. if (next_tag.name != "ext_resource") {
  389. break;
  390. }
  391. if (!next_tag.fields.has("path")) {
  392. error = ERR_FILE_CORRUPT;
  393. error_text = "Missing 'path' in external resource tag";
  394. _printerr();
  395. return error;
  396. }
  397. if (!next_tag.fields.has("type")) {
  398. error = ERR_FILE_CORRUPT;
  399. error_text = "Missing 'type' in external resource tag";
  400. _printerr();
  401. return error;
  402. }
  403. if (!next_tag.fields.has("id")) {
  404. error = ERR_FILE_CORRUPT;
  405. error_text = "Missing 'id' in external resource tag";
  406. _printerr();
  407. return error;
  408. }
  409. String path = next_tag.fields["path"];
  410. String type = next_tag.fields["type"];
  411. String id = next_tag.fields["id"];
  412. if (next_tag.fields.has("uid")) {
  413. String uidt = next_tag.fields["uid"];
  414. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(uidt);
  415. if (uid != ResourceUID::INVALID_ID && ResourceUID::get_singleton()->has_id(uid)) {
  416. // If a UID is found and the path is valid, it will be used, otherwise, it falls back to the path.
  417. path = ResourceUID::get_singleton()->get_id_path(uid);
  418. } else {
  419. #ifdef TOOLS_ENABLED
  420. // Silence a warning that can happen during the initial filesystem scan due to cache being regenerated.
  421. if (ResourceLoader::get_resource_uid(path) != uid) {
  422. WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data());
  423. }
  424. #else
  425. WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data());
  426. #endif
  427. }
  428. }
  429. if (!path.contains("://") && path.is_relative_path()) {
  430. // path is relative to file being loaded, so convert to a resource path
  431. path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().path_join(path));
  432. }
  433. if (remaps.has(path)) {
  434. path = remaps[path];
  435. }
  436. ext_resources[id].path = path;
  437. ext_resources[id].type = type;
  438. ext_resources[id].load_token = ResourceLoader::_load_start(path, type, use_sub_threads ? ResourceLoader::LOAD_THREAD_DISTRIBUTE : ResourceLoader::LOAD_THREAD_FROM_CURRENT, cache_mode_for_external);
  439. if (ext_resources[id].load_token.is_null()) {
  440. if (ResourceLoader::get_abort_on_missing_resources()) {
  441. error = ERR_FILE_CORRUPT;
  442. error_text = "[ext_resource] referenced non-existent resource at: " + path;
  443. _printerr();
  444. return error;
  445. } else {
  446. ResourceLoader::notify_dependency_error(local_path, path, type);
  447. }
  448. }
  449. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  450. if (error) {
  451. _printerr();
  452. return error;
  453. }
  454. }
  455. #ifdef TOOLS_ENABLED
  456. for (const KeyValue<String, ExtResource> &E : ext_resources) {
  457. // Remember ID for saving.
  458. Resource::set_resource_id_for_path(local_path, E.value.path, E.key);
  459. }
  460. #endif
  461. while (true) {
  462. if (next_tag.name != "sub_resource") {
  463. break;
  464. }
  465. if (!next_tag.fields.has("type")) {
  466. error = ERR_FILE_CORRUPT;
  467. error_text = "Missing 'type' in external resource tag";
  468. _printerr();
  469. return error;
  470. }
  471. if (!next_tag.fields.has("id")) {
  472. error = ERR_FILE_CORRUPT;
  473. error_text = "Missing 'id' in external resource tag";
  474. _printerr();
  475. return error;
  476. }
  477. String type = next_tag.fields["type"];
  478. String id = next_tag.fields["id"];
  479. String path = local_path + "::" + id;
  480. //bool exists=ResourceCache::has(path);
  481. Ref<Resource> res;
  482. bool do_assign = false;
  483. if (cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE && ResourceCache::has(path)) {
  484. //reuse existing
  485. Ref<Resource> cache = ResourceCache::get_ref(path);
  486. if (cache.is_valid() && cache->get_class() == type) {
  487. res = cache;
  488. res->reset_state();
  489. do_assign = true;
  490. }
  491. }
  492. MissingResource *missing_resource = nullptr;
  493. if (res.is_null()) { //not reuse
  494. Ref<Resource> cache = ResourceCache::get_ref(path);
  495. if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE && cache.is_valid()) { //only if it doesn't exist
  496. //cached, do not assign
  497. res = cache;
  498. } else {
  499. //create
  500. Object *obj = ClassDB::instantiate(type);
  501. if (!obj) {
  502. if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  503. missing_resource = memnew(MissingResource);
  504. missing_resource->set_original_class(type);
  505. missing_resource->set_recording_properties(true);
  506. obj = missing_resource;
  507. } else {
  508. error_text = vformat("Can't create sub resource of type '%s'", type);
  509. _printerr();
  510. error = ERR_FILE_CORRUPT;
  511. return error;
  512. }
  513. }
  514. Resource *r = Object::cast_to<Resource>(obj);
  515. if (!r) {
  516. error_text = vformat("Can't create sub resource of type '%s' as it's not a resource type", type);
  517. _printerr();
  518. error = ERR_FILE_CORRUPT;
  519. return error;
  520. }
  521. res = Ref<Resource>(r);
  522. do_assign = true;
  523. }
  524. }
  525. resource_current++;
  526. if (progress && resources_total > 0) {
  527. *progress = resource_current / float(resources_total);
  528. }
  529. int_resources[id] = res; // Always assign int resources.
  530. if (do_assign) {
  531. if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  532. res->set_path(path, cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE);
  533. } else {
  534. res->set_path_cache(path);
  535. }
  536. res->set_scene_unique_id(id);
  537. }
  538. Dictionary missing_resource_properties;
  539. while (true) {
  540. String assign;
  541. Variant value;
  542. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  543. if (error) {
  544. _printerr();
  545. return error;
  546. }
  547. if (!assign.is_empty()) {
  548. if (do_assign) {
  549. bool set_valid = true;
  550. if (value.get_type() == Variant::OBJECT && missing_resource == nullptr && ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  551. // If the property being set is a missing resource (and the parent is not),
  552. // then setting it will most likely not work.
  553. // Instead, save it as metadata.
  554. Ref<MissingResource> mr = value;
  555. if (mr.is_valid()) {
  556. missing_resource_properties[assign] = mr;
  557. set_valid = false;
  558. }
  559. }
  560. if (value.get_type() == Variant::ARRAY) {
  561. Array set_array = value;
  562. bool is_get_valid = false;
  563. Variant get_value = res->get(assign, &is_get_valid);
  564. if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
  565. Array get_array = get_value;
  566. if (!set_array.is_same_typed(get_array)) {
  567. value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
  568. }
  569. }
  570. }
  571. if (value.get_type() == Variant::DICTIONARY) {
  572. Dictionary set_dict = value;
  573. bool is_get_valid = false;
  574. Variant get_value = res->get(assign, &is_get_valid);
  575. if (is_get_valid && get_value.get_type() == Variant::DICTIONARY) {
  576. Dictionary get_dict = get_value;
  577. if (!set_dict.is_same_typed(get_dict)) {
  578. value = Dictionary(set_dict, get_dict.get_typed_key_builtin(), get_dict.get_typed_key_class_name(), get_dict.get_typed_key_script(),
  579. get_dict.get_typed_value_builtin(), get_dict.get_typed_value_class_name(), get_dict.get_typed_value_script());
  580. }
  581. }
  582. }
  583. if (set_valid) {
  584. res->set(assign, value);
  585. }
  586. }
  587. //it's assignment
  588. } else if (!next_tag.name.is_empty()) {
  589. error = OK;
  590. break;
  591. } else {
  592. error = ERR_FILE_CORRUPT;
  593. error_text = "Premature end of file while parsing [sub_resource]";
  594. _printerr();
  595. return error;
  596. }
  597. }
  598. if (missing_resource) {
  599. missing_resource->set_recording_properties(false);
  600. }
  601. if (!missing_resource_properties.is_empty()) {
  602. res->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
  603. }
  604. }
  605. while (true) {
  606. if (next_tag.name != "resource") {
  607. break;
  608. }
  609. if (is_scene) {
  610. error_text = "Unexpected 'resource' tag in a scene file";
  611. _printerr();
  612. error = ERR_FILE_CORRUPT;
  613. return error;
  614. }
  615. MissingResource *missing_resource = nullptr;
  616. resource = ResourceLoader::get_resource_ref_override(local_path);
  617. if (resource.is_null()) {
  618. Ref<Resource> cache = ResourceCache::get_ref(local_path);
  619. if (cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE && cache.is_valid() && cache->get_class() == res_type) {
  620. cache->reset_state();
  621. resource = cache;
  622. }
  623. if (resource.is_null()) {
  624. Object *obj = ClassDB::instantiate(res_type);
  625. if (!obj) {
  626. if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  627. missing_resource = memnew(MissingResource);
  628. missing_resource->set_original_class(res_type);
  629. missing_resource->set_recording_properties(true);
  630. obj = missing_resource;
  631. } else {
  632. error_text = vformat("Can't create sub resource of type '%s'", res_type);
  633. _printerr();
  634. error = ERR_FILE_CORRUPT;
  635. return error;
  636. }
  637. }
  638. Resource *r = Object::cast_to<Resource>(obj);
  639. if (!r) {
  640. error_text = vformat("Can't create sub resource of type '%s' as it's not a resource type", res_type);
  641. _printerr();
  642. error = ERR_FILE_CORRUPT;
  643. return error;
  644. }
  645. resource = Ref<Resource>(r);
  646. }
  647. }
  648. Dictionary missing_resource_properties;
  649. while (true) {
  650. String assign;
  651. Variant value;
  652. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  653. if (error) {
  654. if (error != ERR_FILE_EOF) {
  655. _printerr();
  656. return error;
  657. }
  658. // EOF, Done parsing.
  659. error = OK;
  660. if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  661. if (!ResourceCache::has(res_path)) {
  662. resource->set_path(res_path);
  663. }
  664. resource->set_as_translation_remapped(translation_remapped);
  665. } else {
  666. resource->set_path_cache(res_path);
  667. }
  668. break;
  669. }
  670. if (!assign.is_empty()) {
  671. bool set_valid = true;
  672. if (value.get_type() == Variant::OBJECT && missing_resource == nullptr && ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  673. // If the property being set is a missing resource (and the parent is not),
  674. // then setting it will most likely not work.
  675. // Instead, save it as metadata.
  676. Ref<MissingResource> mr = value;
  677. if (mr.is_valid()) {
  678. missing_resource_properties[assign] = mr;
  679. set_valid = false;
  680. }
  681. }
  682. if (value.get_type() == Variant::ARRAY) {
  683. Array set_array = value;
  684. bool is_get_valid = false;
  685. Variant get_value = resource->get(assign, &is_get_valid);
  686. if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
  687. Array get_array = get_value;
  688. if (!set_array.is_same_typed(get_array)) {
  689. value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
  690. }
  691. }
  692. }
  693. if (value.get_type() == Variant::DICTIONARY) {
  694. Dictionary set_dict = value;
  695. bool is_get_valid = false;
  696. Variant get_value = resource->get(assign, &is_get_valid);
  697. if (is_get_valid && get_value.get_type() == Variant::DICTIONARY) {
  698. Dictionary get_dict = get_value;
  699. if (!set_dict.is_same_typed(get_dict)) {
  700. value = Dictionary(set_dict, get_dict.get_typed_key_builtin(), get_dict.get_typed_key_class_name(), get_dict.get_typed_key_script(),
  701. get_dict.get_typed_value_builtin(), get_dict.get_typed_value_class_name(), get_dict.get_typed_value_script());
  702. }
  703. }
  704. }
  705. if (set_valid) {
  706. resource->set(assign, value);
  707. }
  708. //it's assignment
  709. } else if (!next_tag.name.is_empty()) {
  710. error = ERR_FILE_CORRUPT;
  711. error_text = "Extra tag found when parsing main resource file";
  712. _printerr();
  713. return error;
  714. } else {
  715. break;
  716. }
  717. }
  718. resource_current++;
  719. if (progress && resources_total > 0) {
  720. *progress = resource_current / float(resources_total);
  721. }
  722. if (missing_resource) {
  723. missing_resource->set_recording_properties(false);
  724. }
  725. if (!missing_resource_properties.is_empty()) {
  726. resource->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
  727. }
  728. error = OK;
  729. return error;
  730. }
  731. //for scene files
  732. if (next_tag.name == "node") {
  733. if (!is_scene) {
  734. error_text = "Unexpected 'node' tag in a resource file";
  735. _printerr();
  736. error = ERR_FILE_CORRUPT;
  737. return error;
  738. }
  739. Ref<PackedScene> packed_scene = _parse_node_tag(rp);
  740. if (packed_scene.is_null()) {
  741. return error;
  742. }
  743. error = OK;
  744. //get it here
  745. resource = packed_scene;
  746. if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  747. if (!ResourceCache::has(res_path)) {
  748. packed_scene->set_path(res_path);
  749. }
  750. } else {
  751. packed_scene->get_state()->set_path(res_path);
  752. packed_scene->set_path_cache(res_path);
  753. }
  754. resource_current++;
  755. if (progress && resources_total > 0) {
  756. *progress = resource_current / float(resources_total);
  757. }
  758. return error;
  759. } else {
  760. error_text = vformat("Unknown tag '%s' in file", next_tag.name);
  761. _printerr();
  762. error = ERR_FILE_CORRUPT;
  763. return error;
  764. }
  765. }
  766. int ResourceLoaderText::get_stage() const {
  767. return resource_current;
  768. }
  769. int ResourceLoaderText::get_stage_count() const {
  770. return resources_total; //+ext_resources;
  771. }
  772. void ResourceLoaderText::set_translation_remapped(bool p_remapped) {
  773. translation_remapped = p_remapped;
  774. }
  775. ResourceLoaderText::ResourceLoaderText() :
  776. stream(false), format_version(FORMAT_VERSION) {}
  777. void ResourceLoaderText::get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types) {
  778. open(p_f);
  779. ignore_resource_parsing = true;
  780. ERR_FAIL_COND(error != OK);
  781. while (next_tag.name == "ext_resource") {
  782. if (!next_tag.fields.has("type")) {
  783. error = ERR_FILE_CORRUPT;
  784. error_text = "Missing 'type' in external resource tag";
  785. _printerr();
  786. return;
  787. }
  788. if (!next_tag.fields.has("id")) {
  789. error = ERR_FILE_CORRUPT;
  790. error_text = "Missing 'id' in external resource tag";
  791. _printerr();
  792. return;
  793. }
  794. String path = next_tag.fields["path"];
  795. String type = next_tag.fields["type"];
  796. String fallback_path;
  797. bool using_uid = false;
  798. if (next_tag.fields.has("uid")) {
  799. // If uid exists, return uid in text format, not the path.
  800. String uidt = next_tag.fields["uid"];
  801. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(uidt);
  802. if (uid != ResourceUID::INVALID_ID) {
  803. fallback_path = path; // Used by Dependency Editor, in case uid path fails.
  804. path = ResourceUID::get_singleton()->id_to_text(uid);
  805. using_uid = true;
  806. }
  807. }
  808. if (!using_uid && !path.contains("://") && path.is_relative_path()) {
  809. // Path is relative to file being loaded, so convert to a resource path.
  810. path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().path_join(path));
  811. }
  812. if (p_add_types) {
  813. path += "::" + type;
  814. }
  815. if (!fallback_path.is_empty()) {
  816. if (!p_add_types) {
  817. path += "::"; // Ensure that path comes third, even if there is no type.
  818. }
  819. path += "::" + fallback_path;
  820. }
  821. p_dependencies->push_back(path);
  822. Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  823. if (err) {
  824. print_line(error_text + " - " + itos(lines));
  825. error_text = "Unexpected end of file";
  826. _printerr();
  827. error = ERR_FILE_CORRUPT;
  828. return;
  829. }
  830. }
  831. }
  832. Error ResourceLoaderText::rename_dependencies(Ref<FileAccess> p_f, const String &p_path, const HashMap<String, String> &p_map) {
  833. open(p_f, true);
  834. ERR_FAIL_COND_V(error != OK, error);
  835. ignore_resource_parsing = true;
  836. //FileAccess
  837. Ref<FileAccess> fw;
  838. String base_path = local_path.get_base_dir();
  839. uint64_t tag_end = f->get_position();
  840. while (true) {
  841. Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  842. if (err != OK) {
  843. error = ERR_FILE_CORRUPT;
  844. ERR_FAIL_V(error);
  845. }
  846. if (next_tag.name != "ext_resource") {
  847. //nothing was done
  848. if (fw.is_null()) {
  849. return OK;
  850. }
  851. break;
  852. } else {
  853. if (fw.is_null()) {
  854. fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE);
  855. if (res_uid == ResourceUID::INVALID_ID) {
  856. res_uid = ResourceSaver::get_resource_id_for_path(p_path);
  857. }
  858. String uid_text = "";
  859. if (res_uid != ResourceUID::INVALID_ID) {
  860. uid_text = " uid=\"" + ResourceUID::get_singleton()->id_to_text(res_uid) + "\"";
  861. }
  862. if (is_scene) {
  863. fw->store_line("[gd_scene format=" + itos(format_version) + uid_text + "]\n");
  864. } else {
  865. String script_res_text;
  866. if (!script_class.is_empty()) {
  867. script_res_text = "script_class=\"" + script_class + "\" ";
  868. }
  869. fw->store_line("[gd_resource type=\"" + res_type + "\" " + script_res_text + "format=" + itos(format_version) + uid_text + "]\n");
  870. }
  871. }
  872. if (!next_tag.fields.has("path") || !next_tag.fields.has("id") || !next_tag.fields.has("type")) {
  873. error = ERR_FILE_CORRUPT;
  874. ERR_FAIL_V(error);
  875. }
  876. String path = next_tag.fields["path"];
  877. String id = next_tag.fields["id"];
  878. String type = next_tag.fields["type"];
  879. if (next_tag.fields.has("uid")) {
  880. String uidt = next_tag.fields["uid"];
  881. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(uidt);
  882. if (uid != ResourceUID::INVALID_ID && ResourceUID::get_singleton()->has_id(uid)) {
  883. // If a UID is found and the path is valid, it will be used, otherwise, it falls back to the path.
  884. path = ResourceUID::get_singleton()->get_id_path(uid);
  885. }
  886. }
  887. bool relative = false;
  888. if (!path.begins_with("res://")) {
  889. path = base_path.path_join(path).simplify_path();
  890. relative = true;
  891. }
  892. if (p_map.has(path)) {
  893. path = p_map[path];
  894. }
  895. if (relative) {
  896. //restore relative
  897. path = base_path.path_to_file(path);
  898. }
  899. String s = "[ext_resource type=\"" + type + "\"";
  900. ResourceUID::ID uid = ResourceSaver::get_resource_id_for_path(path);
  901. if (uid != ResourceUID::INVALID_ID) {
  902. s += " uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\"";
  903. }
  904. s += " path=\"" + path + "\" id=\"" + id + "\"]";
  905. fw->store_line(s); // Bundled.
  906. tag_end = f->get_position();
  907. }
  908. }
  909. f->seek(tag_end);
  910. const uint32_t buffer_size = 2048;
  911. uint8_t *buffer = (uint8_t *)alloca(buffer_size);
  912. uint32_t num_read;
  913. num_read = f->get_buffer(buffer, buffer_size);
  914. ERR_FAIL_COND_V_MSG(num_read == UINT32_MAX, ERR_CANT_CREATE, "Failed to allocate memory for buffer.");
  915. ERR_FAIL_COND_V(num_read == 0, ERR_FILE_CORRUPT);
  916. if (*buffer == '\n') {
  917. // Skip first newline character since we added one.
  918. if (num_read > 1) {
  919. fw->store_buffer(buffer + 1, num_read - 1);
  920. }
  921. } else {
  922. fw->store_buffer(buffer, num_read);
  923. }
  924. while (!f->eof_reached()) {
  925. num_read = f->get_buffer(buffer, buffer_size);
  926. fw->store_buffer(buffer, num_read);
  927. }
  928. bool all_ok = fw->get_error() == OK;
  929. if (!all_ok) {
  930. return ERR_CANT_CREATE;
  931. }
  932. return OK;
  933. }
  934. void ResourceLoaderText::open(Ref<FileAccess> p_f, bool p_skip_first_tag) {
  935. error = OK;
  936. lines = 1;
  937. f = p_f;
  938. stream.f = f;
  939. is_scene = false;
  940. ignore_resource_parsing = false;
  941. VariantParser::Tag tag;
  942. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  943. if (err) {
  944. error = err;
  945. _printerr();
  946. return;
  947. }
  948. if (tag.fields.has("format")) {
  949. format_version = tag.fields["format"];
  950. if (format_version > FORMAT_VERSION) {
  951. error_text = "Saved with newer format version";
  952. _printerr();
  953. error = ERR_FILE_UNRECOGNIZED;
  954. return;
  955. }
  956. } else {
  957. format_version = FORMAT_VERSION;
  958. }
  959. if (tag.name == "gd_scene") {
  960. is_scene = true;
  961. } else if (tag.name == "gd_resource") {
  962. if (!tag.fields.has("type")) {
  963. error_text = "Missing 'type' field in 'gd_resource' tag";
  964. _printerr();
  965. error = ERR_PARSE_ERROR;
  966. return;
  967. }
  968. if (tag.fields.has("script_class")) {
  969. script_class = tag.fields["script_class"];
  970. }
  971. res_type = tag.fields["type"];
  972. } else {
  973. error_text = vformat("Unrecognized file type '%s'", tag.name);
  974. _printerr();
  975. error = ERR_PARSE_ERROR;
  976. return;
  977. }
  978. if (tag.fields.has("uid")) {
  979. res_uid = ResourceUID::get_singleton()->text_to_id(tag.fields["uid"]);
  980. } else {
  981. res_uid = ResourceUID::INVALID_ID;
  982. }
  983. if (!p_skip_first_tag) {
  984. err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  985. if (err) {
  986. error_text = "Unexpected end of file";
  987. _printerr();
  988. error = ERR_FILE_CORRUPT;
  989. }
  990. }
  991. rp.ext_func = _parse_ext_resources;
  992. rp.sub_func = _parse_sub_resources;
  993. rp.userdata = this;
  994. }
  995. Error ResourceLoaderText::get_classes_used(HashSet<StringName> *r_classes) {
  996. if (error) {
  997. return error;
  998. }
  999. ignore_resource_parsing = true;
  1000. DummyReadData dummy_read;
  1001. dummy_read.no_placeholders = true;
  1002. VariantParser::ResourceParser rp_new;
  1003. rp_new.ext_func = _parse_ext_resource_dummys;
  1004. rp_new.sub_func = _parse_sub_resource_dummys;
  1005. rp_new.userdata = &dummy_read;
  1006. while (next_tag.name == "ext_resource") {
  1007. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp_new);
  1008. if (error) {
  1009. _printerr();
  1010. return error;
  1011. }
  1012. }
  1013. while (next_tag.name == "sub_resource" || next_tag.name == "resource") {
  1014. if (next_tag.name == "sub_resource") {
  1015. if (!next_tag.fields.has("type")) {
  1016. error = ERR_FILE_CORRUPT;
  1017. error_text = "Missing 'type' in external resource tag";
  1018. _printerr();
  1019. return error;
  1020. }
  1021. r_classes->insert(next_tag.fields["type"]);
  1022. } else {
  1023. r_classes->insert(next_tag.fields["res_type"]);
  1024. }
  1025. while (true) {
  1026. String assign;
  1027. Variant value;
  1028. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp_new);
  1029. if (error) {
  1030. if (error == ERR_FILE_EOF) {
  1031. return OK;
  1032. }
  1033. _printerr();
  1034. return error;
  1035. }
  1036. if (!assign.is_empty()) {
  1037. continue;
  1038. } else if (!next_tag.name.is_empty()) {
  1039. error = OK;
  1040. break;
  1041. } else {
  1042. error = ERR_FILE_CORRUPT;
  1043. error_text = "Premature end of file while parsing [sub_resource]";
  1044. _printerr();
  1045. return error;
  1046. }
  1047. }
  1048. }
  1049. while (next_tag.name == "node") {
  1050. // This is a node, must save one more!
  1051. if (!is_scene) {
  1052. error = ERR_FILE_CORRUPT;
  1053. error_text = "Unexpected 'node' tag in a resource file";
  1054. _printerr();
  1055. return error;
  1056. }
  1057. if (next_tag.fields.has("type")) {
  1058. r_classes->insert(next_tag.fields["type"]);
  1059. }
  1060. while (true) {
  1061. String assign;
  1062. Variant value;
  1063. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp_new);
  1064. if (error) {
  1065. if (error == ERR_FILE_MISSING_DEPENDENCIES) {
  1066. // Resource loading error, just skip it.
  1067. } else if (error != ERR_FILE_EOF) {
  1068. _printerr();
  1069. return error;
  1070. } else {
  1071. return OK;
  1072. }
  1073. }
  1074. if (!assign.is_empty()) {
  1075. continue;
  1076. } else if (!next_tag.name.is_empty()) {
  1077. error = OK;
  1078. break;
  1079. } else {
  1080. error = ERR_FILE_CORRUPT;
  1081. error_text = "Premature end of file while parsing [sub_resource]";
  1082. _printerr();
  1083. return error;
  1084. }
  1085. }
  1086. }
  1087. return OK;
  1088. }
  1089. String ResourceLoaderText::recognize_script_class(Ref<FileAccess> p_f) {
  1090. error = OK;
  1091. lines = 1;
  1092. f = p_f;
  1093. stream.f = f;
  1094. ignore_resource_parsing = true;
  1095. VariantParser::Tag tag;
  1096. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  1097. if (err) {
  1098. _printerr();
  1099. return "";
  1100. }
  1101. if (tag.fields.has("format")) {
  1102. int fmt = tag.fields["format"];
  1103. if (fmt > FORMAT_VERSION) {
  1104. error_text = "Saved with newer format version";
  1105. _printerr();
  1106. return "";
  1107. }
  1108. }
  1109. if (tag.name != "gd_resource") {
  1110. return "";
  1111. }
  1112. if (tag.fields.has("script_class")) {
  1113. return tag.fields["script_class"];
  1114. }
  1115. return "";
  1116. }
  1117. String ResourceLoaderText::recognize(Ref<FileAccess> p_f) {
  1118. error = OK;
  1119. lines = 1;
  1120. f = p_f;
  1121. stream.f = f;
  1122. ignore_resource_parsing = true;
  1123. VariantParser::Tag tag;
  1124. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  1125. if (err) {
  1126. _printerr();
  1127. return "";
  1128. }
  1129. if (tag.fields.has("format")) {
  1130. int fmt = tag.fields["format"];
  1131. if (fmt > FORMAT_VERSION) {
  1132. error_text = "Saved with newer format version";
  1133. _printerr();
  1134. return "";
  1135. }
  1136. }
  1137. if (tag.name == "gd_scene") {
  1138. return "PackedScene";
  1139. }
  1140. if (tag.name != "gd_resource") {
  1141. return "";
  1142. }
  1143. if (!tag.fields.has("type")) {
  1144. error_text = "Missing 'type' field in 'gd_resource' tag";
  1145. _printerr();
  1146. return "";
  1147. }
  1148. return tag.fields["type"];
  1149. }
  1150. ResourceUID::ID ResourceLoaderText::get_uid(Ref<FileAccess> p_f) {
  1151. error = OK;
  1152. lines = 1;
  1153. f = p_f;
  1154. stream.f = f;
  1155. ignore_resource_parsing = true;
  1156. VariantParser::Tag tag;
  1157. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  1158. if (err) {
  1159. _printerr();
  1160. return ResourceUID::INVALID_ID;
  1161. }
  1162. if (tag.fields.has("uid")) { //field is optional
  1163. String uidt = tag.fields["uid"];
  1164. return ResourceUID::get_singleton()->text_to_id(uidt);
  1165. }
  1166. return ResourceUID::INVALID_ID;
  1167. }
  1168. /////////////////////
  1169. Ref<Resource> ResourceFormatLoaderText::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) {
  1170. if (r_error) {
  1171. *r_error = ERR_CANT_OPEN;
  1172. }
  1173. Error err;
  1174. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
  1175. ERR_FAIL_COND_V_MSG(err != OK, Ref<Resource>(), "Cannot open file '" + p_path + "'.");
  1176. ResourceLoaderText loader;
  1177. String path = !p_original_path.is_empty() ? p_original_path : p_path;
  1178. switch (p_cache_mode) {
  1179. case CACHE_MODE_IGNORE:
  1180. case CACHE_MODE_REUSE:
  1181. case CACHE_MODE_REPLACE:
  1182. loader.cache_mode = p_cache_mode;
  1183. loader.cache_mode_for_external = CACHE_MODE_REUSE;
  1184. break;
  1185. case CACHE_MODE_IGNORE_DEEP:
  1186. loader.cache_mode = ResourceFormatLoader::CACHE_MODE_IGNORE;
  1187. loader.cache_mode_for_external = p_cache_mode;
  1188. break;
  1189. case CACHE_MODE_REPLACE_DEEP:
  1190. loader.cache_mode = ResourceFormatLoader::CACHE_MODE_REPLACE;
  1191. loader.cache_mode_for_external = p_cache_mode;
  1192. break;
  1193. }
  1194. loader.use_sub_threads = p_use_sub_threads;
  1195. loader.local_path = ProjectSettings::get_singleton()->localize_path(path);
  1196. loader.progress = r_progress;
  1197. loader.res_path = loader.local_path;
  1198. loader.open(f);
  1199. err = loader.load();
  1200. if (r_error) {
  1201. *r_error = err;
  1202. }
  1203. if (err == OK) {
  1204. return loader.get_resource();
  1205. } else {
  1206. return Ref<Resource>();
  1207. }
  1208. }
  1209. void ResourceFormatLoaderText::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  1210. if (p_type.is_empty()) {
  1211. get_recognized_extensions(p_extensions);
  1212. return;
  1213. }
  1214. if (ClassDB::is_parent_class("PackedScene", p_type)) {
  1215. p_extensions->push_back("tscn");
  1216. }
  1217. // Don't allow .tres for PackedScenes or GDExtension.
  1218. if (p_type != "PackedScene" && p_type != "GDExtension") {
  1219. p_extensions->push_back("tres");
  1220. }
  1221. }
  1222. void ResourceFormatLoaderText::get_recognized_extensions(List<String> *p_extensions) const {
  1223. p_extensions->push_back("tscn");
  1224. p_extensions->push_back("tres");
  1225. }
  1226. bool ResourceFormatLoaderText::handles_type(const String &p_type) const {
  1227. return true;
  1228. }
  1229. void ResourceFormatLoaderText::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  1230. const String type = get_resource_type(p_path);
  1231. if (!type.is_empty()) {
  1232. r_classes->insert(type);
  1233. }
  1234. // ...for anything else must test...
  1235. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1236. if (f.is_null()) {
  1237. return; // Could not read.
  1238. }
  1239. ResourceLoaderText loader;
  1240. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1241. loader.res_path = loader.local_path;
  1242. loader.open(f);
  1243. loader.get_classes_used(r_classes);
  1244. }
  1245. String ResourceFormatLoaderText::get_resource_type(const String &p_path) const {
  1246. const String ext = p_path.get_extension().to_lower();
  1247. if (ext == "tscn") {
  1248. return "PackedScene";
  1249. } else if (ext != "tres") {
  1250. return String();
  1251. }
  1252. // ...for anything else must test...
  1253. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1254. if (f.is_null()) {
  1255. return ""; //could not read
  1256. }
  1257. ResourceLoaderText loader;
  1258. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1259. loader.res_path = loader.local_path;
  1260. String r = loader.recognize(f);
  1261. return ClassDB::get_compatibility_remapped_class(r);
  1262. }
  1263. String ResourceFormatLoaderText::get_resource_script_class(const String &p_path) const {
  1264. if (!p_path.has_extension("tres")) {
  1265. return String();
  1266. }
  1267. // ...for anything else must test...
  1268. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1269. if (f.is_null()) {
  1270. return ""; //could not read
  1271. }
  1272. ResourceLoaderText loader;
  1273. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1274. loader.res_path = loader.local_path;
  1275. return loader.recognize_script_class(f);
  1276. }
  1277. ResourceUID::ID ResourceFormatLoaderText::get_resource_uid(const String &p_path) const {
  1278. const String ext = p_path.get_extension().to_lower();
  1279. if (ext != "tscn" && ext != "tres") {
  1280. return ResourceUID::INVALID_ID;
  1281. }
  1282. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1283. if (f.is_null()) {
  1284. return ResourceUID::INVALID_ID; //could not read
  1285. }
  1286. ResourceLoaderText loader;
  1287. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1288. loader.res_path = loader.local_path;
  1289. return loader.get_uid(f);
  1290. }
  1291. bool ResourceFormatLoaderText::has_custom_uid_support() const {
  1292. return true;
  1293. }
  1294. void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  1295. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1296. if (f.is_null()) {
  1297. ERR_FAIL();
  1298. }
  1299. ResourceLoaderText loader;
  1300. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1301. loader.res_path = loader.local_path;
  1302. loader.get_dependencies(f, p_dependencies, p_add_types);
  1303. }
  1304. Error ResourceFormatLoaderText::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  1305. Error err = OK;
  1306. {
  1307. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1308. if (f.is_null()) {
  1309. ERR_FAIL_V(ERR_CANT_OPEN);
  1310. }
  1311. ResourceLoaderText loader;
  1312. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1313. loader.res_path = loader.local_path;
  1314. err = loader.rename_dependencies(f, p_path, p_map);
  1315. }
  1316. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1317. if (err == OK && da->file_exists(p_path + ".depren")) {
  1318. da->remove(p_path);
  1319. da->rename(p_path + ".depren", p_path);
  1320. }
  1321. return err;
  1322. }
  1323. ResourceFormatLoaderText *ResourceFormatLoaderText::singleton = nullptr;
  1324. /*****************************************************************************************************/
  1325. String ResourceFormatSaverTextInstance::_write_resources(void *ud, const Ref<Resource> &p_resource) {
  1326. ResourceFormatSaverTextInstance *rsi = static_cast<ResourceFormatSaverTextInstance *>(ud);
  1327. return rsi->_write_resource(p_resource);
  1328. }
  1329. String ResourceFormatSaverTextInstance::_write_resource(const Ref<Resource> &res) {
  1330. if (res->get_meta(SNAME("_skip_save_"), false)) {
  1331. return "null";
  1332. }
  1333. if (external_resources.has(res)) {
  1334. return "ExtResource(\"" + external_resources[res] + "\")";
  1335. } else {
  1336. if (internal_resources.has(res)) {
  1337. return "SubResource(\"" + internal_resources[res] + "\")";
  1338. } else if (!res->is_built_in()) {
  1339. if (res->get_path() == local_path) { //circular reference attempt
  1340. return "null";
  1341. }
  1342. //external resource
  1343. String path = relative_paths ? local_path.path_to_file(res->get_path()) : res->get_path();
  1344. return "Resource(\"" + path + "\")";
  1345. } else {
  1346. ERR_FAIL_V_MSG("null", "Resource was not pre cached for the resource section, bug?");
  1347. //internal resource
  1348. }
  1349. }
  1350. }
  1351. void ResourceFormatSaverTextInstance::_find_resources(const Variant &p_variant, bool p_main) {
  1352. switch (p_variant.get_type()) {
  1353. case Variant::OBJECT: {
  1354. Ref<Resource> res = p_variant;
  1355. if (res.is_null() || external_resources.has(res) || res->get_meta(SNAME("_skip_save_"), false)) {
  1356. return;
  1357. }
  1358. if (!p_main && (!bundle_resources) && !res->is_built_in()) {
  1359. if (res->get_path() == local_path) {
  1360. ERR_PRINT("Circular reference to resource being saved found: '" + local_path + "' will be null next time it's loaded.");
  1361. return;
  1362. }
  1363. // Use a numeric ID as a base, because they are sorted in natural order before saving.
  1364. // This increases the chances of thread loading to fetch them first.
  1365. String id = itos(external_resources.size() + 1) + "_" + Resource::generate_scene_unique_id();
  1366. external_resources[res] = id;
  1367. return;
  1368. }
  1369. if (resource_set.has(res)) {
  1370. return;
  1371. }
  1372. resource_set.insert(res);
  1373. List<PropertyInfo> property_list;
  1374. res->get_property_list(&property_list);
  1375. property_list.sort();
  1376. List<PropertyInfo>::Element *I = property_list.front();
  1377. while (I) {
  1378. PropertyInfo pi = I->get();
  1379. if (pi.usage & PROPERTY_USAGE_STORAGE) {
  1380. Variant v = res->get(I->get().name);
  1381. if (pi.usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
  1382. NonPersistentKey npk;
  1383. npk.base = res;
  1384. npk.property = pi.name;
  1385. non_persistent_map[npk] = v;
  1386. Ref<Resource> sres = v;
  1387. if (sres.is_valid()) {
  1388. resource_set.insert(sres);
  1389. saved_resources.push_back(sres);
  1390. } else {
  1391. _find_resources(v);
  1392. }
  1393. } else {
  1394. _find_resources(v);
  1395. }
  1396. }
  1397. I = I->next();
  1398. }
  1399. saved_resources.push_back(res); // Saved after, so the children it needs are available when loaded
  1400. } break;
  1401. case Variant::ARRAY: {
  1402. Array varray = p_variant;
  1403. _find_resources(varray.get_typed_script());
  1404. for (const Variant &var : varray) {
  1405. _find_resources(var);
  1406. }
  1407. } break;
  1408. case Variant::DICTIONARY: {
  1409. Dictionary d = p_variant;
  1410. _find_resources(d.get_typed_key_script());
  1411. _find_resources(d.get_typed_value_script());
  1412. for (const KeyValue<Variant, Variant> &kv : d) {
  1413. // Of course keys should also be cached, after all we can't prevent users from using resources as keys, right?
  1414. // See also ResourceFormatSaverBinaryInstance::_find_resources (when p_variant is of type Variant::DICTIONARY)
  1415. _find_resources(kv.key);
  1416. _find_resources(kv.value);
  1417. }
  1418. } break;
  1419. case Variant::PACKED_BYTE_ARRAY: {
  1420. // Balance between compatibility and performance.
  1421. if (use_compat && p_variant.operator PackedByteArray().size() > 64) {
  1422. use_compat = false;
  1423. }
  1424. } break;
  1425. case Variant::PACKED_VECTOR4_ARRAY: {
  1426. use_compat = false;
  1427. } break;
  1428. default: {
  1429. }
  1430. }
  1431. }
  1432. static String _resource_get_class(Ref<Resource> p_resource) {
  1433. Ref<MissingResource> missing_resource = p_resource;
  1434. if (missing_resource.is_valid()) {
  1435. return missing_resource->get_original_class();
  1436. } else {
  1437. return p_resource->get_class();
  1438. }
  1439. }
  1440. Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Resource> &p_resource, uint32_t p_flags) {
  1441. Resource::seed_scene_unique_id(p_path.hash()); // Seeding for save path should make it deterministic for importers.
  1442. if (p_path.ends_with(".tscn")) {
  1443. packed_scene = p_resource;
  1444. }
  1445. Error err;
  1446. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1447. ERR_FAIL_COND_V_MSG(err, ERR_CANT_OPEN, "Cannot save file '" + p_path + "'.");
  1448. Ref<FileAccess> _fref(f);
  1449. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1450. relative_paths = p_flags & ResourceSaver::FLAG_RELATIVE_PATHS;
  1451. skip_editor = p_flags & ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
  1452. bundle_resources = p_flags & ResourceSaver::FLAG_BUNDLE_RESOURCES;
  1453. takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
  1454. if (!p_path.begins_with("res://")) {
  1455. takeover_paths = false;
  1456. }
  1457. // Save resources.
  1458. use_compat = true; // _find_resources() changes this.
  1459. _find_resources(p_resource, true);
  1460. if (packed_scene.is_valid()) {
  1461. // Add instances to external resources if saving a packed scene.
  1462. for (int i = 0; i < packed_scene->get_state()->get_node_count(); i++) {
  1463. if (packed_scene->get_state()->is_node_instance_placeholder(i)) {
  1464. continue;
  1465. }
  1466. Ref<PackedScene> instance = packed_scene->get_state()->get_node_instance(i);
  1467. if (instance.is_valid() && !external_resources.has(instance)) {
  1468. int index = external_resources.size() + 1;
  1469. external_resources[instance] = itos(index) + "_" + Resource::generate_scene_unique_id(); // Keep the order for improved thread loading performance.
  1470. }
  1471. }
  1472. }
  1473. {
  1474. String title = packed_scene.is_valid() ? "[gd_scene " : "[gd_resource ";
  1475. if (packed_scene.is_null()) {
  1476. title += "type=\"" + _resource_get_class(p_resource) + "\" ";
  1477. Ref<Script> script = p_resource->get_script();
  1478. if (script.is_valid() && script->get_global_name()) {
  1479. title += "script_class=\"" + String(script->get_global_name()) + "\" ";
  1480. }
  1481. }
  1482. title += "format=" + itos(use_compat ? ResourceLoaderText::FORMAT_VERSION_COMPAT : ResourceLoaderText::FORMAT_VERSION) + "";
  1483. ResourceUID::ID uid = ResourceSaver::get_resource_id_for_path(local_path, true);
  1484. if (uid != ResourceUID::INVALID_ID) {
  1485. title += " uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\"";
  1486. }
  1487. f->store_string(title);
  1488. f->store_line("]\n"); // One empty line.
  1489. }
  1490. #ifdef TOOLS_ENABLED
  1491. // Keep order from cached ids.
  1492. HashSet<String> cached_ids_found;
  1493. for (KeyValue<Ref<Resource>, String> &E : external_resources) {
  1494. String cached_id = E.key->get_id_for_path(local_path);
  1495. if (cached_id.is_empty() || cached_ids_found.has(cached_id)) {
  1496. int sep_pos = E.value.find_char('_');
  1497. if (sep_pos != -1) {
  1498. E.value = E.value.substr(0, sep_pos + 1); // Keep the order found, for improved thread loading performance.
  1499. } else {
  1500. E.value = "";
  1501. }
  1502. } else {
  1503. E.value = cached_id;
  1504. cached_ids_found.insert(cached_id);
  1505. }
  1506. }
  1507. // Create IDs for non cached resources.
  1508. for (KeyValue<Ref<Resource>, String> &E : external_resources) {
  1509. if (cached_ids_found.has(E.value)) { // Already cached, go on.
  1510. continue;
  1511. }
  1512. String attempt;
  1513. while (true) {
  1514. attempt = E.value + Resource::generate_scene_unique_id();
  1515. if (!cached_ids_found.has(attempt)) {
  1516. break;
  1517. }
  1518. }
  1519. cached_ids_found.insert(attempt);
  1520. E.value = attempt;
  1521. // Update also in resource.
  1522. Ref<Resource> res = E.key;
  1523. res->set_id_for_path(local_path, attempt);
  1524. }
  1525. #else
  1526. // Make sure to start from one, as it makes format more readable.
  1527. int counter = 1;
  1528. for (KeyValue<Ref<Resource>, String> &E : external_resources) {
  1529. E.value = itos(counter++);
  1530. }
  1531. #endif
  1532. Vector<ResourceSort> sorted_er;
  1533. for (const KeyValue<Ref<Resource>, String> &E : external_resources) {
  1534. ResourceSort rs;
  1535. rs.resource = E.key;
  1536. rs.id = E.value;
  1537. sorted_er.push_back(rs);
  1538. }
  1539. sorted_er.sort();
  1540. for (int i = 0; i < sorted_er.size(); i++) {
  1541. String p = sorted_er[i].resource->get_path();
  1542. String s = "[ext_resource type=\"" + sorted_er[i].resource->get_save_class() + "\"";
  1543. ResourceUID::ID uid = ResourceSaver::get_resource_id_for_path(p, false);
  1544. if (uid != ResourceUID::INVALID_ID) {
  1545. s += " uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\"";
  1546. }
  1547. s += " path=\"" + p + "\" id=\"" + sorted_er[i].id + "\"]\n";
  1548. f->store_string(s); // Bundled.
  1549. }
  1550. if (external_resources.size()) {
  1551. f->store_line(String()); // Separate.
  1552. }
  1553. HashSet<String> used_unique_ids;
  1554. for (List<Ref<Resource>>::Element *E = saved_resources.front(); E; E = E->next()) {
  1555. Ref<Resource> res = E->get();
  1556. if (E->next() && res->is_built_in()) {
  1557. if (!res->get_scene_unique_id().is_empty()) {
  1558. if (used_unique_ids.has(res->get_scene_unique_id())) {
  1559. res->set_scene_unique_id(""); // Repeated.
  1560. } else {
  1561. used_unique_ids.insert(res->get_scene_unique_id());
  1562. }
  1563. }
  1564. }
  1565. }
  1566. for (List<Ref<Resource>>::Element *E = saved_resources.front(); E; E = E->next()) {
  1567. Ref<Resource> res = E->get();
  1568. ERR_CONTINUE(!resource_set.has(res));
  1569. bool main = (E->next() == nullptr);
  1570. if (main && packed_scene.is_valid()) {
  1571. break; // Save as a scene.
  1572. }
  1573. if (main) {
  1574. f->store_line("[resource]");
  1575. } else {
  1576. String line = "[sub_resource ";
  1577. if (res->get_scene_unique_id().is_empty()) {
  1578. String new_id;
  1579. while (true) {
  1580. new_id = _resource_get_class(res) + "_" + Resource::generate_scene_unique_id();
  1581. if (!used_unique_ids.has(new_id)) {
  1582. break;
  1583. }
  1584. }
  1585. res->set_scene_unique_id(new_id);
  1586. used_unique_ids.insert(new_id);
  1587. }
  1588. String id = res->get_scene_unique_id();
  1589. line += "type=\"" + _resource_get_class(res) + "\" id=\"" + id;
  1590. f->store_line(line + "\"]");
  1591. if (takeover_paths) {
  1592. res->set_path(p_path + "::" + id, true);
  1593. }
  1594. internal_resources[res] = id;
  1595. #ifdef TOOLS_ENABLED
  1596. res->set_edited(false);
  1597. #endif
  1598. }
  1599. Dictionary missing_resource_properties = res->get_meta(META_MISSING_RESOURCES, Dictionary());
  1600. List<PropertyInfo> property_list;
  1601. res->get_property_list(&property_list);
  1602. for (const PropertyInfo &pi : property_list) {
  1603. if (skip_editor && pi.name.begins_with("__editor")) {
  1604. continue;
  1605. }
  1606. if (pi.name == META_PROPERTY_MISSING_RESOURCES) {
  1607. continue;
  1608. }
  1609. if (pi.usage & PROPERTY_USAGE_STORAGE || missing_resource_properties.has(pi.name)) {
  1610. String name = pi.name;
  1611. Variant value;
  1612. if (pi.usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
  1613. NonPersistentKey npk;
  1614. npk.base = res;
  1615. npk.property = name;
  1616. if (non_persistent_map.has(npk)) {
  1617. value = non_persistent_map[npk];
  1618. }
  1619. } else {
  1620. value = res->get(name);
  1621. }
  1622. if (pi.type == Variant::OBJECT && missing_resource_properties.has(pi.name)) {
  1623. // Was this missing resource overridden? If so do not save the old value.
  1624. Ref<Resource> ures = value;
  1625. if (ures.is_null()) {
  1626. value = missing_resource_properties[pi.name];
  1627. }
  1628. }
  1629. bool is_script = name == CoreStringName(script);
  1630. Variant default_value = is_script ? Variant() : PropertyUtils::get_property_default_value(res.ptr(), name);
  1631. if (default_value.get_type() != Variant::NIL && bool(Variant::evaluate(Variant::OP_EQUAL, value, default_value))) {
  1632. continue;
  1633. }
  1634. if (pi.type == Variant::OBJECT && value.is_zero() && !(pi.usage & PROPERTY_USAGE_STORE_IF_NULL)) {
  1635. continue;
  1636. }
  1637. String vars;
  1638. VariantWriter::write_to_string(value, vars, _write_resources, this, use_compat);
  1639. f->store_string(name.property_name_encode() + " = " + vars + "\n");
  1640. }
  1641. }
  1642. if (E->next()) {
  1643. f->store_line(String());
  1644. }
  1645. }
  1646. if (packed_scene.is_valid()) {
  1647. // If this is a scene, save nodes and connections!
  1648. Ref<SceneState> state = packed_scene->get_state();
  1649. for (int i = 0; i < state->get_node_count(); i++) {
  1650. StringName type = state->get_node_type(i);
  1651. StringName name = state->get_node_name(i);
  1652. int index = state->get_node_index(i);
  1653. int unique_id = state->get_node_unique_id(i);
  1654. NodePath parent_path = state->get_node_path(i, true);
  1655. PackedInt32Array parent_id_path = state->get_node_parent_id_path(i);
  1656. PackedInt32Array owner_id_path = state->get_node_owner_id_path(i);
  1657. NodePath owner = state->get_node_owner_path(i);
  1658. Ref<PackedScene> instance = state->get_node_instance(i);
  1659. String instance_placeholder = state->get_node_instance_placeholder(i);
  1660. Vector<StringName> groups = state->get_node_groups(i);
  1661. Vector<String> deferred_node_paths = state->get_node_deferred_nodepath_properties(i);
  1662. String header = "[node";
  1663. header += " name=\"" + String(name).c_escape() + "\"";
  1664. if (type != StringName()) {
  1665. header += " type=\"" + String(type) + "\"";
  1666. }
  1667. if (parent_path != NodePath()) {
  1668. header += " parent=\"" + String(parent_path.simplified()).c_escape() + "\"";
  1669. if (parent_id_path.size()) {
  1670. header += " parent_id_path=" + Variant(parent_id_path).get_construct_string();
  1671. }
  1672. }
  1673. if (owner != NodePath() && owner != NodePath(".")) {
  1674. header += " owner=\"" + String(owner.simplified()).c_escape() + "\"";
  1675. if (owner_id_path.size()) {
  1676. header += " owner_uid_path=" + Variant(owner_id_path).get_construct_string();
  1677. }
  1678. }
  1679. if (index >= 0) {
  1680. header += " index=\"" + itos(index) + "\"";
  1681. }
  1682. if (unique_id != Node::UNIQUE_SCENE_ID_UNASSIGNED) {
  1683. header += " unique_id=" + itos(unique_id) + "";
  1684. }
  1685. if (deferred_node_paths.size()) {
  1686. header += " node_paths=" + Variant(deferred_node_paths).get_construct_string();
  1687. }
  1688. if (groups.size()) {
  1689. // Write all groups on the same line as they're part of a section header.
  1690. // This improves readability while not impacting VCS friendliness too much,
  1691. // since it's rare to have more than 5 groups assigned to a single node.
  1692. groups.sort_custom<StringName::AlphCompare>();
  1693. String sgroups = " groups=[";
  1694. for (int j = 0; j < groups.size(); j++) {
  1695. sgroups += "\"" + String(groups[j]).c_escape() + "\"";
  1696. if (j < groups.size() - 1) {
  1697. sgroups += ", ";
  1698. }
  1699. }
  1700. sgroups += "]";
  1701. header += sgroups;
  1702. }
  1703. f->store_string(header);
  1704. if (!instance_placeholder.is_empty()) {
  1705. String vars;
  1706. f->store_string(" instance_placeholder=");
  1707. VariantWriter::write_to_string(instance_placeholder, vars, _write_resources, this, use_compat);
  1708. f->store_string(vars);
  1709. }
  1710. if (instance.is_valid()) {
  1711. String vars;
  1712. f->store_string(" instance=");
  1713. VariantWriter::write_to_string(instance, vars, _write_resources, this, use_compat);
  1714. f->store_string(vars);
  1715. }
  1716. f->store_line("]");
  1717. for (int j = 0; j < state->get_node_property_count(i); j++) {
  1718. String vars;
  1719. VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, _write_resources, this, use_compat);
  1720. f->store_string(String(state->get_node_property_name(i, j)).property_name_encode() + " = " + vars + "\n");
  1721. }
  1722. if (i < state->get_node_count() - 1) {
  1723. f->store_line(String());
  1724. }
  1725. }
  1726. for (int i = 0; i < state->get_connection_count(); i++) {
  1727. if (i == 0) {
  1728. f->store_line("");
  1729. }
  1730. String connstr = "[connection";
  1731. connstr += " signal=\"" + String(state->get_connection_signal(i)).c_escape() + "\"";
  1732. connstr += " from=\"" + String(state->get_connection_source(i).simplified()).c_escape() + "\"";
  1733. connstr += " to=\"" + String(state->get_connection_target(i).simplified()).c_escape() + "\"";
  1734. connstr += " method=\"" + String(state->get_connection_method(i)).c_escape() + "\"";
  1735. int flags = state->get_connection_flags(i);
  1736. if (flags != Object::CONNECT_PERSIST) {
  1737. connstr += " flags=" + itos(flags);
  1738. }
  1739. {
  1740. PackedInt32Array from_idp = state->get_connection_source_id_path(i);
  1741. if (from_idp.size()) {
  1742. connstr += " from_uid_path=" + Variant(from_idp).get_construct_string();
  1743. }
  1744. }
  1745. {
  1746. PackedInt32Array to_idp = state->get_connection_target_id_path(i);
  1747. if (to_idp.size()) {
  1748. connstr += " to_uid_path=" + Variant(to_idp).get_construct_string();
  1749. }
  1750. }
  1751. int unbinds = state->get_connection_unbinds(i);
  1752. if (unbinds > 0) {
  1753. connstr += " unbinds=" + itos(unbinds);
  1754. }
  1755. Array binds = state->get_connection_binds(i);
  1756. f->store_string(connstr);
  1757. if (binds.size()) {
  1758. String vars;
  1759. VariantWriter::write_to_string(binds, vars, _write_resources, this, use_compat);
  1760. f->store_string(" binds= " + vars);
  1761. }
  1762. f->store_line("]");
  1763. }
  1764. Vector<NodePath> editable_instances = state->get_editable_instances();
  1765. for (int i = 0; i < editable_instances.size(); i++) {
  1766. if (i == 0) {
  1767. f->store_line("");
  1768. }
  1769. f->store_line("[editable path=\"" + editable_instances[i].operator String().c_escape() + "\"]");
  1770. }
  1771. }
  1772. if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
  1773. return ERR_CANT_CREATE;
  1774. }
  1775. return OK;
  1776. }
  1777. Error ResourceLoaderText::set_uid(Ref<FileAccess> p_f, ResourceUID::ID p_uid) {
  1778. open(p_f, true);
  1779. ERR_FAIL_COND_V(error != OK, error);
  1780. ignore_resource_parsing = true;
  1781. Ref<FileAccess> fw;
  1782. fw = FileAccess::open(local_path + ".uidren", FileAccess::WRITE);
  1783. if (is_scene) {
  1784. fw->store_string("[gd_scene format=" + itos(format_version) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]");
  1785. } else {
  1786. String script_res_text;
  1787. if (!script_class.is_empty()) {
  1788. script_res_text = "script_class=\"" + script_class + "\" ";
  1789. }
  1790. fw->store_string("[gd_resource type=\"" + res_type + "\" " + script_res_text + "format=" + itos(format_version) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]");
  1791. }
  1792. uint8_t c = f->get_8();
  1793. while (!f->eof_reached()) {
  1794. fw->store_8(c);
  1795. c = f->get_8();
  1796. }
  1797. bool all_ok = fw->get_error() == OK;
  1798. if (!all_ok) {
  1799. return ERR_CANT_CREATE;
  1800. }
  1801. return OK;
  1802. }
  1803. Error ResourceFormatSaverText::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  1804. if (p_path.ends_with(".tscn") && Ref<PackedScene>(p_resource).is_null()) {
  1805. return ERR_FILE_UNRECOGNIZED;
  1806. }
  1807. ResourceFormatSaverTextInstance saver;
  1808. return saver.save(p_path, p_resource, p_flags);
  1809. }
  1810. Error ResourceFormatSaverText::set_uid(const String &p_path, ResourceUID::ID p_uid) {
  1811. String lc = p_path.to_lower();
  1812. if (!lc.ends_with(".tscn") && !lc.ends_with(".tres")) {
  1813. return ERR_FILE_UNRECOGNIZED;
  1814. }
  1815. String local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1816. Error err = OK;
  1817. {
  1818. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ);
  1819. if (file.is_null()) {
  1820. ERR_FAIL_V(ERR_CANT_OPEN);
  1821. }
  1822. ResourceLoaderText loader;
  1823. loader.local_path = local_path;
  1824. loader.res_path = loader.local_path;
  1825. err = loader.set_uid(file, p_uid);
  1826. }
  1827. if (err == OK) {
  1828. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1829. da->remove(local_path);
  1830. da->rename(local_path + ".uidren", local_path);
  1831. }
  1832. return err;
  1833. }
  1834. bool ResourceFormatSaverText::recognize(const Ref<Resource> &p_resource) const {
  1835. return true; // All resources recognized!
  1836. }
  1837. void ResourceFormatSaverText::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  1838. if (Ref<PackedScene>(p_resource).is_valid()) {
  1839. p_extensions->push_back("tscn"); // Text scene.
  1840. } else {
  1841. p_extensions->push_back("tres"); // Text resource.
  1842. }
  1843. }
  1844. ResourceFormatSaverText *ResourceFormatSaverText::singleton = nullptr;
  1845. ResourceFormatSaverText::ResourceFormatSaverText() {
  1846. singleton = this;
  1847. }