resource_format_text.cpp 48 KB

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