resource_format_text.cpp 62 KB

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