resource_format_text.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  1. /*************************************************************************/
  2. /* resource_format_text.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_format_text.h"
  31. #include "core/io/resource_format_binary.h"
  32. #include "core/os/dir_access.h"
  33. #include "core/project_settings.h"
  34. #include "core/version.h"
  35. //version 2: changed names for basis, aabb, poolvectors, etc.
  36. #define FORMAT_VERSION 2
  37. #include "core/os/dir_access.h"
  38. #include "core/version.h"
  39. #define _printerr() ERR_PRINT(String(res_path + ":" + itos(lines) + " - Parse Error: " + error_text).utf8().get_data());
  40. ///
  41. void ResourceInteractiveLoaderText::set_local_path(const String &p_local_path) {
  42. res_path = p_local_path;
  43. }
  44. Ref<Resource> ResourceInteractiveLoaderText::get_resource() {
  45. return resource;
  46. }
  47. Error ResourceInteractiveLoaderText::_parse_sub_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  48. VariantParser::Token token;
  49. VariantParser::get_token(p_stream, token, line, r_err_str);
  50. if (token.type != VariantParser::TK_NUMBER) {
  51. r_err_str = "Expected number (sub-resource index)";
  52. return ERR_PARSE_ERROR;
  53. }
  54. int index = token.value;
  55. if (!p_data->resource_map.has(index)) {
  56. Ref<DummyResource> dr;
  57. dr.instance();
  58. dr->set_subindex(index);
  59. p_data->resource_map[index] = dr;
  60. p_data->resource_set.insert(dr);
  61. }
  62. r_res = p_data->resource_map[index];
  63. VariantParser::get_token(p_stream, token, line, r_err_str);
  64. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  65. r_err_str = "Expected ')'";
  66. return ERR_PARSE_ERROR;
  67. }
  68. return OK;
  69. }
  70. Error ResourceInteractiveLoaderText::_parse_ext_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  71. VariantParser::Token token;
  72. VariantParser::get_token(p_stream, token, line, r_err_str);
  73. if (token.type != VariantParser::TK_NUMBER) {
  74. r_err_str = "Expected number (sub-resource index)";
  75. return ERR_PARSE_ERROR;
  76. }
  77. int id = token.value;
  78. ERR_FAIL_COND_V(!p_data->rev_external_resources.has(id), ERR_PARSE_ERROR);
  79. r_res = p_data->rev_external_resources[id];
  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 ResourceInteractiveLoaderText::_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) {
  91. r_err_str = "Expected number (sub-resource index)";
  92. return ERR_PARSE_ERROR;
  93. }
  94. int index = token.value;
  95. String path = local_path + "::" + itos(index);
  96. if (!ignore_resource_parsing) {
  97. if (!ResourceCache::has(path)) {
  98. r_err_str = "Can't load cached sub-resource: " + path;
  99. return ERR_PARSE_ERROR;
  100. }
  101. r_res = RES(ResourceCache::get(path));
  102. } else {
  103. r_res = RES();
  104. }
  105. VariantParser::get_token(p_stream, token, line, r_err_str);
  106. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  107. r_err_str = "Expected ')'";
  108. return ERR_PARSE_ERROR;
  109. }
  110. return OK;
  111. }
  112. Error ResourceInteractiveLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  113. VariantParser::Token token;
  114. VariantParser::get_token(p_stream, token, line, r_err_str);
  115. if (token.type != VariantParser::TK_NUMBER) {
  116. r_err_str = "Expected number (sub-resource index)";
  117. return ERR_PARSE_ERROR;
  118. }
  119. int id = token.value;
  120. if (!ignore_resource_parsing) {
  121. if (!ext_resources.has(id)) {
  122. r_err_str = "Can't load cached ext-resource #" + itos(id);
  123. return ERR_PARSE_ERROR;
  124. }
  125. String path = ext_resources[id].path;
  126. String type = ext_resources[id].type;
  127. if (path.find("://") == -1 && path.is_rel_path()) {
  128. // path is relative to file being loaded, so convert to a resource path
  129. path = ProjectSettings::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path));
  130. }
  131. r_res = ResourceLoader::load(path, type);
  132. if (r_res.is_null()) {
  133. WARN_PRINT(String("Couldn't load external resource: " + path).utf8().get_data());
  134. }
  135. } else {
  136. r_res = RES();
  137. }
  138. VariantParser::get_token(p_stream, token, line, r_err_str);
  139. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  140. r_err_str = "Expected ')'";
  141. return ERR_PARSE_ERROR;
  142. }
  143. return OK;
  144. }
  145. Ref<PackedScene> ResourceInteractiveLoaderText::_parse_node_tag(VariantParser::ResourceParser &parser) {
  146. Ref<PackedScene> packed_scene;
  147. packed_scene.instance();
  148. while (true) {
  149. if (next_tag.name == "node") {
  150. int parent = -1;
  151. int owner = -1;
  152. int type = -1;
  153. int name = -1;
  154. int instance = -1;
  155. int index = -1;
  156. //int base_scene=-1;
  157. if (next_tag.fields.has("name")) {
  158. name = packed_scene->get_state()->add_name(next_tag.fields["name"]);
  159. }
  160. if (next_tag.fields.has("parent")) {
  161. NodePath np = next_tag.fields["parent"];
  162. np.prepend_period(); //compatible to how it manages paths internally
  163. parent = packed_scene->get_state()->add_node_path(np);
  164. }
  165. if (next_tag.fields.has("type")) {
  166. type = packed_scene->get_state()->add_name(next_tag.fields["type"]);
  167. } else {
  168. type = SceneState::TYPE_INSTANCED; //no type? assume this was instanced
  169. }
  170. if (next_tag.fields.has("instance")) {
  171. instance = packed_scene->get_state()->add_value(next_tag.fields["instance"]);
  172. if (packed_scene->get_state()->get_node_count() == 0 && parent == -1) {
  173. packed_scene->get_state()->set_base_scene(instance);
  174. instance = -1;
  175. }
  176. }
  177. if (next_tag.fields.has("instance_placeholder")) {
  178. String path = next_tag.fields["instance_placeholder"];
  179. int path_v = packed_scene->get_state()->add_value(path);
  180. if (packed_scene->get_state()->get_node_count() == 0) {
  181. error = ERR_FILE_CORRUPT;
  182. error_text = "Instance Placeholder can't be used for inheritance.";
  183. _printerr();
  184. return Ref<PackedScene>();
  185. }
  186. instance = path_v | SceneState::FLAG_INSTANCE_IS_PLACEHOLDER;
  187. }
  188. if (next_tag.fields.has("owner")) {
  189. owner = packed_scene->get_state()->add_node_path(next_tag.fields["owner"]);
  190. } else {
  191. if (parent != -1 && !(type == SceneState::TYPE_INSTANCED && instance == -1))
  192. owner = 0; //if no owner, owner is root
  193. }
  194. if (next_tag.fields.has("index")) {
  195. index = next_tag.fields["index"];
  196. }
  197. int node_id = packed_scene->get_state()->add_node(parent, owner, type, name, instance, index);
  198. if (next_tag.fields.has("groups")) {
  199. Array groups = next_tag.fields["groups"];
  200. for (int i = 0; i < groups.size(); i++) {
  201. packed_scene->get_state()->add_node_group(node_id, packed_scene->get_state()->add_name(groups[i]));
  202. }
  203. }
  204. while (true) {
  205. String assign;
  206. Variant value;
  207. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &parser);
  208. if (error) {
  209. if (error != ERR_FILE_EOF) {
  210. _printerr();
  211. return Ref<PackedScene>();
  212. } else {
  213. return packed_scene;
  214. }
  215. }
  216. if (assign != String()) {
  217. int nameidx = packed_scene->get_state()->add_name(assign);
  218. int valueidx = packed_scene->get_state()->add_value(value);
  219. packed_scene->get_state()->add_node_property(node_id, nameidx, valueidx);
  220. //it's assignment
  221. } else if (next_tag.name != String()) {
  222. break;
  223. }
  224. }
  225. } else if (next_tag.name == "connection") {
  226. if (!next_tag.fields.has("from")) {
  227. error = ERR_FILE_CORRUPT;
  228. error_text = "missing 'from' field from connection tag";
  229. return Ref<PackedScene>();
  230. }
  231. if (!next_tag.fields.has("to")) {
  232. error = ERR_FILE_CORRUPT;
  233. error_text = "missing 'to' field from connection tag";
  234. return Ref<PackedScene>();
  235. }
  236. if (!next_tag.fields.has("signal")) {
  237. error = ERR_FILE_CORRUPT;
  238. error_text = "missing 'signal' field from connection tag";
  239. return Ref<PackedScene>();
  240. }
  241. if (!next_tag.fields.has("method")) {
  242. error = ERR_FILE_CORRUPT;
  243. error_text = "missing 'method' field from connection tag";
  244. return Ref<PackedScene>();
  245. }
  246. NodePath from = next_tag.fields["from"];
  247. NodePath to = next_tag.fields["to"];
  248. StringName method = next_tag.fields["method"];
  249. StringName signal = next_tag.fields["signal"];
  250. int flags = CONNECT_PERSIST;
  251. Array binds;
  252. if (next_tag.fields.has("flags")) {
  253. flags = next_tag.fields["flags"];
  254. }
  255. if (next_tag.fields.has("binds")) {
  256. binds = next_tag.fields["binds"];
  257. }
  258. Vector<int> bind_ints;
  259. for (int i = 0; i < binds.size(); i++) {
  260. bind_ints.push_back(packed_scene->get_state()->add_value(binds[i]));
  261. }
  262. packed_scene->get_state()->add_connection(
  263. packed_scene->get_state()->add_node_path(from.simplified()),
  264. packed_scene->get_state()->add_node_path(to.simplified()),
  265. packed_scene->get_state()->add_name(signal),
  266. packed_scene->get_state()->add_name(method),
  267. flags,
  268. bind_ints);
  269. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
  270. if (error) {
  271. if (error != ERR_FILE_EOF) {
  272. _printerr();
  273. return Ref<PackedScene>();
  274. } else {
  275. return packed_scene;
  276. }
  277. }
  278. } else if (next_tag.name == "editable") {
  279. if (!next_tag.fields.has("path")) {
  280. error = ERR_FILE_CORRUPT;
  281. error_text = "missing 'path' field from connection tag";
  282. _printerr();
  283. return Ref<PackedScene>();
  284. }
  285. NodePath path = next_tag.fields["path"];
  286. packed_scene->get_state()->add_editable_instance(path.simplified());
  287. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
  288. if (error) {
  289. if (error != ERR_FILE_EOF) {
  290. _printerr();
  291. return Ref<PackedScene>();
  292. } else {
  293. return packed_scene;
  294. }
  295. }
  296. } else {
  297. error = ERR_FILE_CORRUPT;
  298. _printerr();
  299. return Ref<PackedScene>();
  300. }
  301. }
  302. return packed_scene;
  303. }
  304. Error ResourceInteractiveLoaderText::poll() {
  305. if (error != OK)
  306. return error;
  307. if (next_tag.name == "ext_resource") {
  308. if (!next_tag.fields.has("path")) {
  309. error = ERR_FILE_CORRUPT;
  310. error_text = "Missing 'path' in external resource tag";
  311. _printerr();
  312. return error;
  313. }
  314. if (!next_tag.fields.has("type")) {
  315. error = ERR_FILE_CORRUPT;
  316. error_text = "Missing 'type' in external resource tag";
  317. _printerr();
  318. return error;
  319. }
  320. if (!next_tag.fields.has("id")) {
  321. error = ERR_FILE_CORRUPT;
  322. error_text = "Missing 'id' in external resource tag";
  323. _printerr();
  324. return error;
  325. }
  326. String path = next_tag.fields["path"];
  327. String type = next_tag.fields["type"];
  328. int index = next_tag.fields["id"];
  329. if (path.find("://") == -1 && path.is_rel_path()) {
  330. // path is relative to file being loaded, so convert to a resource path
  331. path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path));
  332. }
  333. if (remaps.has(path)) {
  334. path = remaps[path];
  335. }
  336. RES res = ResourceLoader::load(path, type);
  337. if (res.is_null()) {
  338. if (ResourceLoader::get_abort_on_missing_resources()) {
  339. error = ERR_FILE_CORRUPT;
  340. error_text = "[ext_resource] referenced nonexistent resource at: " + path;
  341. _printerr();
  342. return error;
  343. } else {
  344. ResourceLoader::notify_dependency_error(local_path, path, type);
  345. }
  346. } else {
  347. resource_cache.push_back(res);
  348. #ifdef TOOLS_ENABLED
  349. //remember ID for saving
  350. res->set_id_for_path(local_path, index);
  351. #endif
  352. }
  353. ExtResource er;
  354. er.path = path;
  355. er.type = type;
  356. ext_resources[index] = er;
  357. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  358. if (error) {
  359. _printerr();
  360. }
  361. resource_current++;
  362. return error;
  363. } else if (next_tag.name == "sub_resource") {
  364. if (!next_tag.fields.has("type")) {
  365. error = ERR_FILE_CORRUPT;
  366. error_text = "Missing 'type' in external resource tag";
  367. _printerr();
  368. return error;
  369. }
  370. if (!next_tag.fields.has("id")) {
  371. error = ERR_FILE_CORRUPT;
  372. error_text = "Missing 'index' in external resource tag";
  373. _printerr();
  374. return error;
  375. }
  376. String type = next_tag.fields["type"];
  377. int id = next_tag.fields["id"];
  378. String path = local_path + "::" + itos(id);
  379. //bool exists=ResourceCache::has(path);
  380. Ref<Resource> res;
  381. if (!ResourceCache::has(path)) { //only if it doesn't exist
  382. Object *obj = ClassDB::instance(type);
  383. if (!obj) {
  384. error_text += "Can't create sub resource of type: " + type;
  385. _printerr();
  386. error = ERR_FILE_CORRUPT;
  387. return error;
  388. }
  389. Resource *r = Object::cast_to<Resource>(obj);
  390. if (!r) {
  391. error_text += "Can't create sub resource of type, because not a resource: " + type;
  392. _printerr();
  393. error = ERR_FILE_CORRUPT;
  394. return error;
  395. }
  396. res = Ref<Resource>(r);
  397. resource_cache.push_back(res);
  398. res->set_path(path);
  399. }
  400. resource_current++;
  401. while (true) {
  402. String assign;
  403. Variant value;
  404. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  405. if (error) {
  406. _printerr();
  407. return error;
  408. }
  409. if (assign != String()) {
  410. if (res.is_valid()) {
  411. res->set(assign, value);
  412. }
  413. //it's assignment
  414. } else if (next_tag.name != String()) {
  415. error = OK;
  416. break;
  417. } else {
  418. error = ERR_FILE_CORRUPT;
  419. error_text = "Premature end of file while parsing [sub_resource]";
  420. _printerr();
  421. return error;
  422. }
  423. }
  424. return OK;
  425. } else if (next_tag.name == "resource") {
  426. if (is_scene) {
  427. error_text += "found the 'resource' tag on a scene file!";
  428. _printerr();
  429. error = ERR_FILE_CORRUPT;
  430. return error;
  431. }
  432. Object *obj = ClassDB::instance(res_type);
  433. if (!obj) {
  434. error_text += "Can't create sub resource of type: " + res_type;
  435. _printerr();
  436. error = ERR_FILE_CORRUPT;
  437. return error;
  438. }
  439. Resource *r = Object::cast_to<Resource>(obj);
  440. if (!r) {
  441. error_text += "Can't create sub resource of type, because not a resource: " + res_type;
  442. _printerr();
  443. error = ERR_FILE_CORRUPT;
  444. return error;
  445. }
  446. resource = Ref<Resource>(r);
  447. resource_current++;
  448. while (true) {
  449. String assign;
  450. Variant value;
  451. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  452. if (error) {
  453. if (error != ERR_FILE_EOF) {
  454. _printerr();
  455. } else {
  456. if (!ResourceCache::has(res_path)) {
  457. resource->set_path(res_path);
  458. }
  459. resource->set_as_translation_remapped(translation_remapped);
  460. }
  461. return error;
  462. }
  463. if (assign != String()) {
  464. resource->set(assign, value);
  465. //it's assignment
  466. } else if (next_tag.name != String()) {
  467. error = ERR_FILE_CORRUPT;
  468. error_text = "Extra tag found when parsing main resource file";
  469. _printerr();
  470. return error;
  471. } else {
  472. error = ERR_FILE_EOF;
  473. return error;
  474. }
  475. }
  476. return OK;
  477. } else if (next_tag.name == "node") {
  478. if (!is_scene) {
  479. error_text += "found the 'node' tag on a resource file!";
  480. _printerr();
  481. error = ERR_FILE_CORRUPT;
  482. return error;
  483. }
  484. Ref<PackedScene> packed_scene = _parse_node_tag(rp);
  485. if (!packed_scene.is_valid())
  486. return error;
  487. error = ERR_FILE_EOF;
  488. //get it here
  489. resource = packed_scene;
  490. if (!ResourceCache::has(res_path)) {
  491. packed_scene->set_path(res_path);
  492. }
  493. return error;
  494. } else {
  495. error_text += "Unknown tag in file: " + next_tag.name;
  496. _printerr();
  497. error = ERR_FILE_CORRUPT;
  498. return error;
  499. }
  500. return OK;
  501. }
  502. int ResourceInteractiveLoaderText::get_stage() const {
  503. return resource_current;
  504. }
  505. int ResourceInteractiveLoaderText::get_stage_count() const {
  506. return resources_total; //+ext_resources;
  507. }
  508. void ResourceInteractiveLoaderText::set_translation_remapped(bool p_remapped) {
  509. translation_remapped = p_remapped;
  510. }
  511. ResourceInteractiveLoaderText::ResourceInteractiveLoaderText() {
  512. translation_remapped = false;
  513. }
  514. ResourceInteractiveLoaderText::~ResourceInteractiveLoaderText() {
  515. memdelete(f);
  516. }
  517. void ResourceInteractiveLoaderText::get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types) {
  518. open(p_f);
  519. ignore_resource_parsing = true;
  520. ERR_FAIL_COND(error != OK);
  521. while (next_tag.name == "ext_resource") {
  522. if (!next_tag.fields.has("type")) {
  523. error = ERR_FILE_CORRUPT;
  524. error_text = "Missing 'type' in external resource tag";
  525. _printerr();
  526. return;
  527. }
  528. if (!next_tag.fields.has("id")) {
  529. error = ERR_FILE_CORRUPT;
  530. error_text = "Missing 'index' in external resource tag";
  531. _printerr();
  532. return;
  533. }
  534. String path = next_tag.fields["path"];
  535. String type = next_tag.fields["type"];
  536. if (path.find("://") == -1 && path.is_rel_path()) {
  537. // path is relative to file being loaded, so convert to a resource path
  538. path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path));
  539. }
  540. if (p_add_types) {
  541. path += "::" + type;
  542. }
  543. p_dependencies->push_back(path);
  544. Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  545. if (err) {
  546. print_line(error_text + " - " + itos(lines));
  547. error_text = "Unexpected end of file";
  548. _printerr();
  549. error = ERR_FILE_CORRUPT;
  550. }
  551. }
  552. }
  553. Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map) {
  554. open(p_f, true);
  555. ERR_FAIL_COND_V(error != OK, error);
  556. ignore_resource_parsing = true;
  557. //FileAccess
  558. FileAccess *fw = NULL;
  559. String base_path = local_path.get_base_dir();
  560. uint64_t tag_end = f->get_position();
  561. while (true) {
  562. Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  563. if (err != OK) {
  564. if (fw) {
  565. memdelete(fw);
  566. }
  567. error = ERR_FILE_CORRUPT;
  568. ERR_FAIL_V(error);
  569. }
  570. if (next_tag.name != "ext_resource") {
  571. //nothing was done
  572. if (!fw)
  573. return OK;
  574. break;
  575. } else {
  576. if (!fw) {
  577. fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE);
  578. if (is_scene) {
  579. fw->store_line("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n");
  580. } else {
  581. fw->store_line("[gd_resource type=\"" + res_type + "\" load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n");
  582. }
  583. }
  584. if (!next_tag.fields.has("path") || !next_tag.fields.has("id") || !next_tag.fields.has("type")) {
  585. memdelete(fw);
  586. error = ERR_FILE_CORRUPT;
  587. ERR_FAIL_V(error);
  588. }
  589. String path = next_tag.fields["path"];
  590. int index = next_tag.fields["id"];
  591. String type = next_tag.fields["type"];
  592. bool relative = false;
  593. if (!path.begins_with("res://")) {
  594. path = base_path.plus_file(path).simplify_path();
  595. relative = true;
  596. }
  597. if (p_map.has(path)) {
  598. String np = p_map[path];
  599. path = np;
  600. }
  601. if (relative) {
  602. //restore relative
  603. path = base_path.path_to_file(path);
  604. }
  605. fw->store_line("[ext_resource path=\"" + path + "\" type=\"" + type + "\" id=" + itos(index) + "]");
  606. tag_end = f->get_position();
  607. }
  608. }
  609. f->seek(tag_end);
  610. uint8_t c = f->get_8();
  611. while (!f->eof_reached()) {
  612. fw->store_8(c);
  613. c = f->get_8();
  614. }
  615. f->close();
  616. bool all_ok = fw->get_error() == OK;
  617. memdelete(fw);
  618. if (!all_ok) {
  619. return ERR_CANT_CREATE;
  620. }
  621. DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  622. da->remove(p_path);
  623. da->rename(p_path + ".depren", p_path);
  624. memdelete(da);
  625. return OK;
  626. }
  627. void ResourceInteractiveLoaderText::open(FileAccess *p_f, bool p_skip_first_tag) {
  628. error = OK;
  629. lines = 1;
  630. f = p_f;
  631. stream.f = f;
  632. is_scene = false;
  633. ignore_resource_parsing = false;
  634. resource_current = 0;
  635. VariantParser::Tag tag;
  636. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  637. if (err) {
  638. error = err;
  639. _printerr();
  640. return;
  641. }
  642. if (tag.fields.has("format")) {
  643. int fmt = tag.fields["format"];
  644. if (fmt > FORMAT_VERSION) {
  645. error_text = "Saved with newer format version";
  646. _printerr();
  647. error = ERR_PARSE_ERROR;
  648. return;
  649. }
  650. }
  651. if (tag.name == "gd_scene") {
  652. is_scene = true;
  653. } else if (tag.name == "gd_resource") {
  654. if (!tag.fields.has("type")) {
  655. error_text = "Missing 'type' field in 'gd_resource' tag";
  656. _printerr();
  657. error = ERR_PARSE_ERROR;
  658. return;
  659. }
  660. res_type = tag.fields["type"];
  661. } else {
  662. error_text = "Unrecognized file type: " + tag.name;
  663. _printerr();
  664. error = ERR_PARSE_ERROR;
  665. return;
  666. }
  667. if (tag.fields.has("load_steps")) {
  668. resources_total = tag.fields["load_steps"];
  669. } else {
  670. resources_total = 0;
  671. }
  672. if (!p_skip_first_tag) {
  673. err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  674. if (err) {
  675. error_text = "Unexpected end of file";
  676. _printerr();
  677. error = ERR_FILE_CORRUPT;
  678. }
  679. }
  680. rp.ext_func = _parse_ext_resources;
  681. rp.sub_func = _parse_sub_resources;
  682. rp.func = NULL;
  683. rp.userdata = this;
  684. }
  685. static void bs_save_unicode_string(FileAccess *f, const String &p_string, bool p_bit_on_len = false) {
  686. CharString utf8 = p_string.utf8();
  687. if (p_bit_on_len) {
  688. f->store_32((utf8.length() + 1) | 0x80000000);
  689. } else {
  690. f->store_32(utf8.length() + 1);
  691. }
  692. f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1);
  693. }
  694. Error ResourceInteractiveLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) {
  695. if (error)
  696. return error;
  697. FileAccessRef wf = FileAccess::open(p_path, FileAccess::WRITE);
  698. if (!wf) {
  699. return ERR_CANT_OPEN;
  700. }
  701. //save header compressed
  702. static const uint8_t header[4] = { 'R', 'S', 'R', 'C' };
  703. wf->store_buffer(header, 4);
  704. wf->store_32(0); //endianness, little endian
  705. wf->store_32(0); //64 bits file, false for now
  706. wf->store_32(VERSION_MAJOR);
  707. wf->store_32(VERSION_MINOR);
  708. static const int save_format_version = 3; //use format version 3 for saving
  709. wf->store_32(save_format_version);
  710. bs_save_unicode_string(wf.f, is_scene ? "PackedScene" : resource_type);
  711. wf->store_64(0); //offset to import metadata, this is no longer used
  712. for (int i = 0; i < 14; i++)
  713. wf->store_32(0); // reserved
  714. wf->store_32(0); //string table size, will not be in use
  715. size_t ext_res_count_pos = wf->get_position();
  716. wf->store_32(0); //zero ext resources, still parsing them
  717. //go with external resources
  718. DummyReadData dummy_read;
  719. VariantParser::ResourceParser rp;
  720. rp.ext_func = _parse_ext_resource_dummys;
  721. rp.sub_func = _parse_sub_resource_dummys;
  722. rp.userdata = &dummy_read;
  723. while (next_tag.name == "ext_resource") {
  724. if (!next_tag.fields.has("path")) {
  725. error = ERR_FILE_CORRUPT;
  726. error_text = "Missing 'path' in external resource tag";
  727. _printerr();
  728. return error;
  729. }
  730. if (!next_tag.fields.has("type")) {
  731. error = ERR_FILE_CORRUPT;
  732. error_text = "Missing 'type' in external resource tag";
  733. _printerr();
  734. return error;
  735. }
  736. if (!next_tag.fields.has("id")) {
  737. error = ERR_FILE_CORRUPT;
  738. error_text = "Missing 'id' in external resource tag";
  739. _printerr();
  740. return error;
  741. }
  742. String path = next_tag.fields["path"];
  743. String type = next_tag.fields["type"];
  744. int index = next_tag.fields["id"];
  745. bs_save_unicode_string(wf.f, type);
  746. bs_save_unicode_string(wf.f, path);
  747. int lindex = dummy_read.external_resources.size();
  748. Ref<DummyResource> dr;
  749. dr.instance();
  750. dr->set_path("res://dummy" + itos(lindex)); //anything is good to detect it for saving as external
  751. dummy_read.external_resources[dr] = lindex;
  752. dummy_read.rev_external_resources[index] = dr;
  753. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  754. if (error) {
  755. _printerr();
  756. return error;
  757. }
  758. }
  759. // save external resource table
  760. wf->seek(ext_res_count_pos);
  761. wf->store_32(dummy_read.external_resources.size());
  762. wf->seek_end();
  763. //now, save resources to a separate file, for now
  764. size_t sub_res_count_pos = wf->get_position();
  765. wf->store_32(0); //zero sub resources, still parsing them
  766. String temp_file = p_path + ".temp";
  767. FileAccessRef wf2 = FileAccess::open(temp_file, FileAccess::WRITE);
  768. if (!wf2) {
  769. return ERR_CANT_OPEN;
  770. }
  771. Vector<size_t> local_offsets;
  772. Vector<size_t> local_pointers_pos;
  773. while (next_tag.name == "sub_resource" || next_tag.name == "resource") {
  774. String type;
  775. int id = -1;
  776. bool main_res;
  777. if (next_tag.name == "sub_resource") {
  778. if (!next_tag.fields.has("type")) {
  779. error = ERR_FILE_CORRUPT;
  780. error_text = "Missing 'type' in external resource tag";
  781. _printerr();
  782. return error;
  783. }
  784. if (!next_tag.fields.has("id")) {
  785. error = ERR_FILE_CORRUPT;
  786. error_text = "Missing 'index' in external resource tag";
  787. _printerr();
  788. return error;
  789. }
  790. type = next_tag.fields["type"];
  791. id = next_tag.fields["id"];
  792. main_res = false;
  793. } else {
  794. type = res_type;
  795. id = 0; //used for last anyway
  796. main_res = true;
  797. }
  798. local_offsets.push_back(wf2->get_position());
  799. bs_save_unicode_string(wf, "local://" + itos(id));
  800. local_pointers_pos.push_back(wf->get_position());
  801. wf->store_64(0); //temp local offset
  802. bs_save_unicode_string(wf2, type);
  803. size_t propcount_ofs = wf2->get_position();
  804. wf2->store_32(0);
  805. int prop_count = 0;
  806. while (true) {
  807. String assign;
  808. Variant value;
  809. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  810. if (error) {
  811. if (main_res && error == ERR_FILE_EOF) {
  812. next_tag.name = ""; //exit
  813. break;
  814. }
  815. _printerr();
  816. return error;
  817. }
  818. if (assign != String()) {
  819. Map<StringName, int> empty_string_map; //unused
  820. bs_save_unicode_string(wf2, assign, true);
  821. ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_set, dummy_read.external_resources, empty_string_map);
  822. prop_count++;
  823. } else if (next_tag.name != String()) {
  824. error = OK;
  825. break;
  826. } else {
  827. error = ERR_FILE_CORRUPT;
  828. error_text = "Premature end of file while parsing [sub_resource]";
  829. _printerr();
  830. return error;
  831. }
  832. }
  833. wf2->seek(propcount_ofs);
  834. wf2->store_32(prop_count);
  835. wf2->seek_end();
  836. }
  837. if (next_tag.name == "node") {
  838. //this is a node, must save one more!
  839. if (!is_scene) {
  840. error_text += "found the 'node' tag on a resource file!";
  841. _printerr();
  842. error = ERR_FILE_CORRUPT;
  843. return error;
  844. }
  845. Ref<PackedScene> packed_scene = _parse_node_tag(rp);
  846. if (!packed_scene.is_valid())
  847. return error;
  848. error = OK;
  849. //get it here
  850. List<PropertyInfo> props;
  851. packed_scene->get_property_list(&props);
  852. bs_save_unicode_string(wf, "local://0");
  853. local_pointers_pos.push_back(wf->get_position());
  854. wf->store_64(0); //temp local offset
  855. local_offsets.push_back(wf2->get_position());
  856. bs_save_unicode_string(wf2, "PackedScene");
  857. size_t propcount_ofs = wf2->get_position();
  858. wf2->store_32(0);
  859. int prop_count = 0;
  860. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  861. if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
  862. continue;
  863. String name = E->get().name;
  864. Variant value = packed_scene->get(name);
  865. Map<StringName, int> empty_string_map; //unused
  866. bs_save_unicode_string(wf2, name, true);
  867. ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_set, dummy_read.external_resources, empty_string_map);
  868. prop_count++;
  869. }
  870. wf2->seek(propcount_ofs);
  871. wf2->store_32(prop_count);
  872. wf2->seek_end();
  873. }
  874. wf2->close();
  875. size_t offset_from = wf->get_position();
  876. wf->seek(sub_res_count_pos); //plus one because the saved one
  877. wf->store_32(local_offsets.size());
  878. for (int i = 0; i < local_offsets.size(); i++) {
  879. wf->seek(local_pointers_pos[i]);
  880. wf->store_64(local_offsets[i] + offset_from);
  881. }
  882. wf->seek_end();
  883. Vector<uint8_t> data = FileAccess::get_file_as_array(temp_file);
  884. wf->store_buffer(data.ptr(), data.size());
  885. {
  886. DirAccessRef dar = DirAccess::open(temp_file.get_base_dir());
  887. dar->remove(temp_file);
  888. }
  889. wf->store_buffer((const uint8_t *)"RSRC", 4); //magic at end
  890. wf->close();
  891. return OK;
  892. }
  893. String ResourceInteractiveLoaderText::recognize(FileAccess *p_f) {
  894. error = OK;
  895. lines = 1;
  896. f = p_f;
  897. stream.f = f;
  898. ignore_resource_parsing = true;
  899. VariantParser::Tag tag;
  900. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  901. if (err) {
  902. _printerr();
  903. return "";
  904. }
  905. if (tag.fields.has("format")) {
  906. int fmt = tag.fields["format"];
  907. if (fmt > FORMAT_VERSION) {
  908. error_text = "Saved with newer format version";
  909. _printerr();
  910. return "";
  911. }
  912. }
  913. if (tag.name == "gd_scene")
  914. return "PackedScene";
  915. if (tag.name != "gd_resource")
  916. return "";
  917. if (!tag.fields.has("type")) {
  918. error_text = "Missing 'type' field in 'gd_resource' tag";
  919. _printerr();
  920. return "";
  921. }
  922. return tag.fields["type"];
  923. }
  924. /////////////////////
  925. Ref<ResourceInteractiveLoader> ResourceFormatLoaderText::load_interactive(const String &p_path, const String &p_original_path, Error *r_error) {
  926. if (r_error)
  927. *r_error = ERR_CANT_OPEN;
  928. Error err;
  929. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  930. ERR_FAIL_COND_V_MSG(err != OK, Ref<ResourceInteractiveLoader>(), "Cannot open file '" + p_path + "'.");
  931. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  932. String path = p_original_path != "" ? p_original_path : p_path;
  933. ria->local_path = ProjectSettings::get_singleton()->localize_path(path);
  934. ria->res_path = ria->local_path;
  935. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  936. ria->open(f);
  937. return ria;
  938. }
  939. void ResourceFormatLoaderText::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  940. if (p_type == "") {
  941. get_recognized_extensions(p_extensions);
  942. return;
  943. }
  944. if (p_type == "PackedScene")
  945. p_extensions->push_back("tscn");
  946. else
  947. p_extensions->push_back("tres");
  948. }
  949. void ResourceFormatLoaderText::get_recognized_extensions(List<String> *p_extensions) const {
  950. p_extensions->push_back("tscn");
  951. p_extensions->push_back("tres");
  952. }
  953. bool ResourceFormatLoaderText::handles_type(const String &p_type) const {
  954. return true;
  955. }
  956. String ResourceFormatLoaderText::get_resource_type(const String &p_path) const {
  957. String ext = p_path.get_extension().to_lower();
  958. if (ext == "tscn")
  959. return "PackedScene";
  960. else if (ext != "tres")
  961. return String();
  962. //for anyhting else must test..
  963. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  964. if (!f) {
  965. return ""; //could not rwead
  966. }
  967. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  968. ria->local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  969. ria->res_path = ria->local_path;
  970. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  971. String r = ria->recognize(f);
  972. return r;
  973. }
  974. void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  975. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  976. if (!f) {
  977. ERR_FAIL();
  978. }
  979. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  980. ria->local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  981. ria->res_path = ria->local_path;
  982. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  983. ria->get_dependencies(f, p_dependencies, p_add_types);
  984. }
  985. Error ResourceFormatLoaderText::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  986. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  987. if (!f) {
  988. ERR_FAIL_V(ERR_CANT_OPEN);
  989. }
  990. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  991. ria->local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  992. ria->res_path = ria->local_path;
  993. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  994. return ria->rename_dependencies(f, p_path, p_map);
  995. }
  996. ResourceFormatLoaderText *ResourceFormatLoaderText::singleton = NULL;
  997. Error ResourceFormatLoaderText::convert_file_to_binary(const String &p_src_path, const String &p_dst_path) {
  998. Error err;
  999. FileAccess *f = FileAccess::open(p_src_path, FileAccess::READ, &err);
  1000. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_OPEN, "Cannot open file '" + p_src_path + "'.");
  1001. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  1002. const String &path = p_src_path;
  1003. ria->local_path = ProjectSettings::get_singleton()->localize_path(path);
  1004. ria->res_path = ria->local_path;
  1005. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  1006. ria->open(f);
  1007. return ria->save_as_binary(f, p_dst_path);
  1008. }
  1009. /*****************************************************************************************************/
  1010. /*****************************************************************************************************/
  1011. /*****************************************************************************************************/
  1012. /*****************************************************************************************************/
  1013. /*****************************************************************************************************/
  1014. /*****************************************************************************************************/
  1015. /*****************************************************************************************************/
  1016. /*****************************************************************************************************/
  1017. /*****************************************************************************************************/
  1018. /*****************************************************************************************************/
  1019. String ResourceFormatSaverTextInstance::_write_resources(void *ud, const RES &p_resource) {
  1020. ResourceFormatSaverTextInstance *rsi = (ResourceFormatSaverTextInstance *)ud;
  1021. return rsi->_write_resource(p_resource);
  1022. }
  1023. String ResourceFormatSaverTextInstance::_write_resource(const RES &res) {
  1024. if (external_resources.has(res)) {
  1025. return "ExtResource( " + itos(external_resources[res]) + " )";
  1026. } else {
  1027. if (internal_resources.has(res)) {
  1028. return "SubResource( " + itos(internal_resources[res]) + " )";
  1029. } else if (res->get_path().length() && res->get_path().find("::") == -1) {
  1030. if (res->get_path() == local_path) { //circular reference attempt
  1031. return "null";
  1032. }
  1033. //external resource
  1034. String path = relative_paths ? local_path.path_to_file(res->get_path()) : res->get_path();
  1035. return "Resource( \"" + path + "\" )";
  1036. } else {
  1037. ERR_FAIL_V_MSG("null", "Resource was not pre cached for the resource section, bug?");
  1038. //internal resource
  1039. }
  1040. }
  1041. }
  1042. void ResourceFormatSaverTextInstance::_find_resources(const Variant &p_variant, bool p_main) {
  1043. switch (p_variant.get_type()) {
  1044. case Variant::OBJECT: {
  1045. RES res = p_variant.operator RefPtr();
  1046. if (res.is_null() || external_resources.has(res))
  1047. return;
  1048. if (!p_main && (!bundle_resources) && res->get_path().length() && res->get_path().find("::") == -1) {
  1049. if (res->get_path() == local_path) {
  1050. ERR_PRINTS("Circular reference to resource being saved found: '" + local_path + "' will be null next time it's loaded.");
  1051. return;
  1052. }
  1053. int index = external_resources.size();
  1054. external_resources[res] = index;
  1055. return;
  1056. }
  1057. if (resource_set.has(res))
  1058. return;
  1059. List<PropertyInfo> property_list;
  1060. res->get_property_list(&property_list);
  1061. property_list.sort();
  1062. List<PropertyInfo>::Element *I = property_list.front();
  1063. while (I) {
  1064. PropertyInfo pi = I->get();
  1065. if (pi.usage & PROPERTY_USAGE_STORAGE) {
  1066. Variant v = res->get(I->get().name);
  1067. if (pi.usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
  1068. RES sres = v;
  1069. if (sres.is_valid()) {
  1070. NonPersistentKey npk;
  1071. npk.base = res;
  1072. npk.property = pi.name;
  1073. non_persistent_map[npk] = sres;
  1074. resource_set.insert(sres);
  1075. saved_resources.push_back(sres);
  1076. }
  1077. } else {
  1078. _find_resources(v);
  1079. }
  1080. }
  1081. I = I->next();
  1082. }
  1083. resource_set.insert(res); //saved after, so the children it needs are available when loaded
  1084. saved_resources.push_back(res);
  1085. } break;
  1086. case Variant::ARRAY: {
  1087. Array varray = p_variant;
  1088. int len = varray.size();
  1089. for (int i = 0; i < len; i++) {
  1090. const Variant &v = varray.get(i);
  1091. _find_resources(v);
  1092. }
  1093. } break;
  1094. case Variant::DICTIONARY: {
  1095. Dictionary d = p_variant;
  1096. List<Variant> keys;
  1097. d.get_key_list(&keys);
  1098. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  1099. Variant v = d[E->get()];
  1100. _find_resources(v);
  1101. }
  1102. } break;
  1103. default: {
  1104. }
  1105. }
  1106. }
  1107. Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1108. if (p_path.ends_with(".tscn")) {
  1109. packed_scene = p_resource;
  1110. }
  1111. Error err;
  1112. f = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1113. ERR_FAIL_COND_V_MSG(err, ERR_CANT_OPEN, "Cannot save file '" + p_path + "'.");
  1114. FileAccessRef _fref(f);
  1115. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1116. relative_paths = p_flags & ResourceSaver::FLAG_RELATIVE_PATHS;
  1117. skip_editor = p_flags & ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
  1118. bundle_resources = p_flags & ResourceSaver::FLAG_BUNDLE_RESOURCES;
  1119. takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
  1120. if (!p_path.begins_with("res://")) {
  1121. takeover_paths = false;
  1122. }
  1123. // save resources
  1124. _find_resources(p_resource, true);
  1125. if (packed_scene.is_valid()) {
  1126. //add instances to external resources if saving a packed scene
  1127. for (int i = 0; i < packed_scene->get_state()->get_node_count(); i++) {
  1128. if (packed_scene->get_state()->is_node_instance_placeholder(i))
  1129. continue;
  1130. Ref<PackedScene> instance = packed_scene->get_state()->get_node_instance(i);
  1131. if (instance.is_valid() && !external_resources.has(instance)) {
  1132. int index = external_resources.size();
  1133. external_resources[instance] = index;
  1134. }
  1135. }
  1136. }
  1137. {
  1138. String title = packed_scene.is_valid() ? "[gd_scene " : "[gd_resource ";
  1139. if (packed_scene.is_null())
  1140. title += "type=\"" + p_resource->get_class() + "\" ";
  1141. int load_steps = saved_resources.size() + external_resources.size();
  1142. /*
  1143. if (packed_scene.is_valid()) {
  1144. load_steps+=packed_scene->get_node_count();
  1145. }
  1146. //no, better to not use load steps from nodes, no point to that
  1147. */
  1148. if (load_steps > 1) {
  1149. title += "load_steps=" + itos(load_steps) + " ";
  1150. }
  1151. title += "format=" + itos(FORMAT_VERSION) + "";
  1152. f->store_string(title);
  1153. f->store_line("]\n"); //one empty line
  1154. }
  1155. #ifdef TOOLS_ENABLED
  1156. //keep order from cached ids
  1157. Set<int> cached_ids_found;
  1158. for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
  1159. int cached_id = E->key()->get_id_for_path(local_path);
  1160. if (cached_id < 0 || cached_ids_found.has(cached_id)) {
  1161. E->get() = -1; //reset
  1162. } else {
  1163. E->get() = cached_id;
  1164. cached_ids_found.insert(cached_id);
  1165. }
  1166. }
  1167. //create IDs for non cached resources
  1168. for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
  1169. if (cached_ids_found.has(E->get())) { //already cached, go on
  1170. continue;
  1171. }
  1172. int attempt = 1; //start from one, more readable format
  1173. while (cached_ids_found.has(attempt)) {
  1174. attempt++;
  1175. }
  1176. cached_ids_found.insert(attempt);
  1177. E->get() = attempt;
  1178. //update also in resource
  1179. Ref<Resource> res = E->key();
  1180. res->set_id_for_path(local_path, attempt);
  1181. }
  1182. #else
  1183. //make sure to start from one, as it makes format more readable
  1184. for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
  1185. E->get() = E->get() + 1;
  1186. }
  1187. #endif
  1188. Vector<ResourceSort> sorted_er;
  1189. for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
  1190. ResourceSort rs;
  1191. rs.resource = E->key();
  1192. rs.index = E->get();
  1193. sorted_er.push_back(rs);
  1194. }
  1195. sorted_er.sort();
  1196. for (int i = 0; i < sorted_er.size(); i++) {
  1197. String p = sorted_er[i].resource->get_path();
  1198. f->store_string("[ext_resource path=\"" + p + "\" type=\"" + sorted_er[i].resource->get_save_class() + "\" id=" + itos(sorted_er[i].index) + "]\n"); //bundled
  1199. }
  1200. if (external_resources.size())
  1201. f->store_line(String()); //separate
  1202. Set<int> used_indices;
  1203. for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) {
  1204. RES res = E->get();
  1205. if (E->next() && (res->get_path() == "" || res->get_path().find("::") != -1)) {
  1206. if (res->get_subindex() != 0) {
  1207. if (used_indices.has(res->get_subindex())) {
  1208. res->set_subindex(0); //repeated
  1209. } else {
  1210. used_indices.insert(res->get_subindex());
  1211. }
  1212. }
  1213. }
  1214. }
  1215. for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) {
  1216. RES res = E->get();
  1217. ERR_CONTINUE(!resource_set.has(res));
  1218. bool main = (E->next() == NULL);
  1219. if (main && packed_scene.is_valid())
  1220. break; //save as a scene
  1221. if (main) {
  1222. f->store_line("[resource]");
  1223. } else {
  1224. String line = "[sub_resource ";
  1225. if (res->get_subindex() == 0) {
  1226. int new_subindex = 1;
  1227. if (used_indices.size()) {
  1228. new_subindex = used_indices.back()->get() + 1;
  1229. }
  1230. res->set_subindex(new_subindex);
  1231. used_indices.insert(new_subindex);
  1232. }
  1233. int idx = res->get_subindex();
  1234. line += "type=\"" + res->get_class() + "\" id=" + itos(idx);
  1235. f->store_line(line + "]");
  1236. if (takeover_paths) {
  1237. res->set_path(p_path + "::" + itos(idx), true);
  1238. }
  1239. internal_resources[res] = idx;
  1240. #ifdef TOOLS_ENABLED
  1241. res->set_edited(false);
  1242. #endif
  1243. }
  1244. List<PropertyInfo> property_list;
  1245. res->get_property_list(&property_list);
  1246. //property_list.sort();
  1247. for (List<PropertyInfo>::Element *PE = property_list.front(); PE; PE = PE->next()) {
  1248. if (skip_editor && PE->get().name.begins_with("__editor"))
  1249. continue;
  1250. if (PE->get().usage & PROPERTY_USAGE_STORAGE) {
  1251. String name = PE->get().name;
  1252. Variant value;
  1253. if (PE->get().usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
  1254. NonPersistentKey npk;
  1255. npk.base = res;
  1256. npk.property = name;
  1257. if (non_persistent_map.has(npk)) {
  1258. value = non_persistent_map[npk];
  1259. }
  1260. } else {
  1261. value = res->get(name);
  1262. }
  1263. Variant default_value = ClassDB::class_get_default_property_value(res->get_class(), name);
  1264. if (default_value.get_type() != Variant::NIL && bool(Variant::evaluate(Variant::OP_EQUAL, value, default_value))) {
  1265. continue;
  1266. }
  1267. if (PE->get().type == Variant::OBJECT && value.is_zero() && !(PE->get().usage & PROPERTY_USAGE_STORE_IF_NULL))
  1268. continue;
  1269. String vars;
  1270. VariantWriter::write_to_string(value, vars, _write_resources, this);
  1271. f->store_string(name.property_name_encode() + " = " + vars + "\n");
  1272. }
  1273. }
  1274. if (E->next())
  1275. f->store_line(String());
  1276. }
  1277. if (packed_scene.is_valid()) {
  1278. //if this is a scene, save nodes and connections!
  1279. Ref<SceneState> state = packed_scene->get_state();
  1280. for (int i = 0; i < state->get_node_count(); i++) {
  1281. StringName type = state->get_node_type(i);
  1282. StringName name = state->get_node_name(i);
  1283. int index = state->get_node_index(i);
  1284. NodePath path = state->get_node_path(i, true);
  1285. NodePath owner = state->get_node_owner_path(i);
  1286. Ref<PackedScene> instance = state->get_node_instance(i);
  1287. String instance_placeholder = state->get_node_instance_placeholder(i);
  1288. Vector<StringName> groups = state->get_node_groups(i);
  1289. String header = "[node";
  1290. header += " name=\"" + String(name).c_escape() + "\"";
  1291. if (type != StringName()) {
  1292. header += " type=\"" + String(type) + "\"";
  1293. }
  1294. if (path != NodePath()) {
  1295. header += " parent=\"" + String(path.simplified()).c_escape() + "\"";
  1296. }
  1297. if (owner != NodePath() && owner != NodePath(".")) {
  1298. header += " owner=\"" + String(owner.simplified()).c_escape() + "\"";
  1299. }
  1300. if (index >= 0) {
  1301. header += " index=\"" + itos(index) + "\"";
  1302. }
  1303. if (groups.size()) {
  1304. groups.sort_custom<StringName::AlphCompare>();
  1305. String sgroups = " groups=[\n";
  1306. for (int j = 0; j < groups.size(); j++) {
  1307. sgroups += "\"" + String(groups[j]).c_escape() + "\",\n";
  1308. }
  1309. sgroups += "]";
  1310. header += sgroups;
  1311. }
  1312. f->store_string(header);
  1313. if (instance_placeholder != String()) {
  1314. String vars;
  1315. f->store_string(" instance_placeholder=");
  1316. VariantWriter::write_to_string(instance_placeholder, vars, _write_resources, this);
  1317. f->store_string(vars);
  1318. }
  1319. if (instance.is_valid()) {
  1320. String vars;
  1321. f->store_string(" instance=");
  1322. VariantWriter::write_to_string(instance, vars, _write_resources, this);
  1323. f->store_string(vars);
  1324. }
  1325. f->store_line("]");
  1326. for (int j = 0; j < state->get_node_property_count(i); j++) {
  1327. String vars;
  1328. VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, _write_resources, this);
  1329. f->store_string(String(state->get_node_property_name(i, j)).property_name_encode() + " = " + vars + "\n");
  1330. }
  1331. if (i < state->get_node_count() - 1)
  1332. f->store_line(String());
  1333. }
  1334. for (int i = 0; i < state->get_connection_count(); i++) {
  1335. String connstr = "[connection";
  1336. connstr += " signal=\"" + String(state->get_connection_signal(i)) + "\"";
  1337. connstr += " from=\"" + String(state->get_connection_source(i).simplified()) + "\"";
  1338. connstr += " to=\"" + String(state->get_connection_target(i).simplified()) + "\"";
  1339. connstr += " method=\"" + String(state->get_connection_method(i)) + "\"";
  1340. int flags = state->get_connection_flags(i);
  1341. if (flags != Object::CONNECT_PERSIST) {
  1342. connstr += " flags=" + itos(flags);
  1343. }
  1344. Array binds = state->get_connection_binds(i);
  1345. f->store_string(connstr);
  1346. if (binds.size()) {
  1347. String vars;
  1348. VariantWriter::write_to_string(binds, vars, _write_resources, this);
  1349. f->store_string(" binds= " + vars);
  1350. }
  1351. f->store_line("]");
  1352. }
  1353. Vector<NodePath> editable_instances = state->get_editable_instances();
  1354. for (int i = 0; i < editable_instances.size(); i++) {
  1355. f->store_line("\n[editable path=\"" + editable_instances[i].operator String() + "\"]");
  1356. }
  1357. }
  1358. if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
  1359. f->close();
  1360. return ERR_CANT_CREATE;
  1361. }
  1362. f->close();
  1363. //memdelete(f);
  1364. return OK;
  1365. }
  1366. Error ResourceFormatSaverText::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1367. if (p_path.ends_with(".sct") && p_resource->get_class() != "PackedScene") {
  1368. return ERR_FILE_UNRECOGNIZED;
  1369. }
  1370. ResourceFormatSaverTextInstance saver;
  1371. return saver.save(p_path, p_resource, p_flags);
  1372. }
  1373. bool ResourceFormatSaverText::recognize(const RES &p_resource) const {
  1374. return true; // all recognized!
  1375. }
  1376. void ResourceFormatSaverText::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  1377. if (p_resource->get_class() == "PackedScene")
  1378. p_extensions->push_back("tscn"); //text scene
  1379. else
  1380. p_extensions->push_back("tres"); //text resource
  1381. }
  1382. ResourceFormatSaverText *ResourceFormatSaverText::singleton = NULL;
  1383. ResourceFormatSaverText::ResourceFormatSaverText() {
  1384. singleton = this;
  1385. }