packed_scene.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629
  1. /**************************************************************************/
  2. /* packed_scene.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 "packed_scene.h"
  31. #include "core/config/engine.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/missing_resource.h"
  34. #include "core/io/resource_loader.h"
  35. #include "core/object/script_language.h"
  36. #include "core/templates/local_vector.h"
  37. #include "core/variant/callable_bind.h"
  38. #include "scene/2d/node_2d.h"
  39. #include "scene/gui/control.h"
  40. #include "scene/main/instance_placeholder.h"
  41. #include "scene/main/missing_node.h"
  42. #include "scene/property_utils.h"
  43. #ifndef _3D_DISABLED
  44. #include "scene/3d/node_3d.h"
  45. #endif // _3D_DISABLED
  46. #define PACKED_SCENE_VERSION 3
  47. #ifdef TOOLS_ENABLED
  48. SceneState::InstantiationWarningNotify SceneState::instantiation_warn_notify = nullptr;
  49. #endif
  50. bool SceneState::can_instantiate() const {
  51. return nodes.size() > 0;
  52. }
  53. static Array _sanitize_node_pinned_properties(Node *p_node) {
  54. Array pinned = p_node->get_meta("_edit_pinned_properties_", Array());
  55. if (pinned.is_empty()) {
  56. return Array();
  57. }
  58. HashSet<StringName> storable_properties;
  59. p_node->get_storable_properties(storable_properties);
  60. int i = 0;
  61. do {
  62. if (storable_properties.has(pinned[i])) {
  63. i++;
  64. } else {
  65. pinned.remove_at(i);
  66. }
  67. } while (i < pinned.size());
  68. if (pinned.is_empty()) {
  69. p_node->remove_meta("_edit_pinned_properties_");
  70. }
  71. return pinned;
  72. }
  73. Ref<Resource> SceneState::get_remap_resource(const Ref<Resource> &p_resource, HashMap<Node *, HashMap<Ref<Resource>, Ref<Resource>>> &remap_cache, const Ref<Resource> &p_fallback, Node *p_for_scene) {
  74. ERR_FAIL_COND_V(p_resource.is_null(), Ref<Resource>());
  75. // Find the shared copy of the source resource.
  76. HashMap<Ref<Resource>, Ref<Resource>>::Iterator R = remap_cache[p_for_scene].find(p_resource);
  77. if (R) {
  78. return R->value;
  79. }
  80. bool reuse_fallback = p_fallback.is_valid() && p_fallback->is_local_to_scene() && p_fallback->get_class_name() == p_resource->get_class_name();
  81. if (reuse_fallback) {
  82. // The fallback resource can only be mapped at most once when it is valid.
  83. for (const KeyValue<Ref<Resource>, Ref<Resource>> &E : remap_cache[p_for_scene]) {
  84. if (E.value == p_fallback) {
  85. reuse_fallback = false;
  86. break;
  87. }
  88. }
  89. }
  90. if (reuse_fallback) { // Simply copy the data from the source resource to update the fallback resource that was previously set.
  91. p_fallback->reset_state(); // May want to reset state.
  92. List<PropertyInfo> pi;
  93. p_resource->get_property_list(&pi);
  94. for (const PropertyInfo &E : pi) {
  95. if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
  96. continue;
  97. }
  98. if (E.name == "resource_path") {
  99. continue; // Do not change path.
  100. }
  101. Variant value = p_resource->get(E.name);
  102. // The local-to-scene subresource instance is preserved, thus maintaining the previous sharing relationship.
  103. // This is mainly used when the sub-scene root is reset in the main scene.
  104. Ref<Resource> sub_res_of_from = value;
  105. if (sub_res_of_from.is_valid() && sub_res_of_from->is_local_to_scene()) {
  106. value = get_remap_resource(sub_res_of_from, remap_cache, p_fallback->get(E.name), p_fallback->get_local_scene());
  107. }
  108. p_fallback->set(E.name, value);
  109. }
  110. remap_cache[p_for_scene][p_resource] = p_fallback;
  111. return p_fallback;
  112. }
  113. // A copy of the source resource is required to overwrite the previous one.
  114. Ref<Resource> local_dupe = p_resource->duplicate_for_local_scene(p_for_scene, remap_cache[p_for_scene]);
  115. remap_cache[p_for_scene][p_resource] = local_dupe;
  116. return local_dupe;
  117. }
  118. static Node *_find_node_by_id(Node *p_owner, Node *p_node, int32_t p_id) {
  119. if (p_owner == p_node || p_node->get_owner() == p_owner) {
  120. if (p_node->get_unique_scene_id() == p_id) {
  121. return p_node;
  122. }
  123. }
  124. for (int i = 0; i < p_node->get_child_count(); i++) {
  125. Node *found = _find_node_by_id(p_owner, p_node->get_child(i), p_id);
  126. if (found) {
  127. return found;
  128. }
  129. }
  130. return nullptr;
  131. }
  132. Node *SceneState::instantiate(GenEditState p_edit_state) const {
  133. // Nodes where instantiation failed (because something is missing.)
  134. List<Node *> stray_instances;
  135. #define NODE_FROM_ID(p_name, p_id) \
  136. Node *p_name; \
  137. if (p_id & FLAG_ID_IS_PATH) { \
  138. NodePath np = node_paths[p_id & FLAG_MASK]; \
  139. p_name = ret_nodes[0]->get_node_or_null(np); \
  140. if (!p_name) { \
  141. p_name = _recover_node_path_index(ret_nodes[0], p_id & FLAG_MASK); \
  142. } \
  143. } else { \
  144. ERR_FAIL_INDEX_V(p_id & FLAG_MASK, nc, nullptr); \
  145. p_name = ret_nodes[p_id & FLAG_MASK]; \
  146. }
  147. int nc = nodes.size();
  148. ERR_FAIL_COND_V_MSG(nc == 0, nullptr, vformat("Failed to instantiate scene state of \"%s\", node count is 0. Make sure the PackedScene resource is valid.", path));
  149. const StringName *snames = nullptr;
  150. int sname_count = names.size();
  151. if (sname_count) {
  152. snames = &names[0];
  153. }
  154. const Variant *props = nullptr;
  155. int prop_count = variants.size();
  156. if (prop_count) {
  157. props = &variants[0];
  158. }
  159. //Vector<Variant> properties;
  160. const NodeData *nd = &nodes[0];
  161. Node **ret_nodes = (Node **)alloca(sizeof(Node *) * nc);
  162. ret_nodes[0] = nullptr; // Sidesteps "maybe uninitialized" false-positives on GCC.
  163. bool gen_node_path_cache = p_edit_state != GEN_EDIT_STATE_DISABLED && node_path_cache.is_empty();
  164. HashMap<Node *, HashMap<Ref<Resource>, Ref<Resource>>> resources_local_to_scenes; // Record the mappings in sub-scenes.
  165. LocalVector<DeferredNodePathProperties> deferred_node_paths;
  166. bool deep_search_warned = false;
  167. for (int i = 0; i < nc; i++) {
  168. const NodeData &n = nd[i];
  169. Node *parent = nullptr;
  170. String old_parent_path;
  171. if (i > 0) {
  172. ERR_FAIL_COND_V_MSG(n.parent == -1, nullptr, vformat("Invalid scene: node %s does not specify its parent node.", snames[n.name]));
  173. NODE_FROM_ID(nparent, n.parent);
  174. #ifdef DEBUG_ENABLED
  175. if (!nparent && (n.parent & FLAG_ID_IS_PATH)) {
  176. WARN_PRINT(String("Parent path '" + String(node_paths[n.parent & FLAG_MASK]) + "' for node '" + String(snames[n.name]) + "' has vanished when instantiating: '" + get_path() + "'.").ascii().get_data());
  177. old_parent_path = String(node_paths[n.parent & FLAG_MASK]).trim_prefix("./").replace_char('/', '@');
  178. nparent = ret_nodes[0];
  179. }
  180. #endif
  181. parent = nparent;
  182. } else {
  183. // i == 0 is root node.
  184. ERR_FAIL_COND_V_MSG(n.parent != -1, nullptr, vformat("Invalid scene: root node %s cannot specify a parent node.", snames[n.name]));
  185. ERR_FAIL_COND_V_MSG(n.type == TYPE_INSTANTIATED && base_scene_idx < 0, nullptr, vformat("Invalid scene: root node %s in an instance, but there's no base scene.", snames[n.name]));
  186. }
  187. Node *node = nullptr;
  188. MissingNode *missing_node = nullptr;
  189. bool is_inherited_scene = false;
  190. if (i == 0 && base_scene_idx >= 0) {
  191. // Scene inheritance on root node.
  192. Ref<PackedScene> sdata = props[base_scene_idx];
  193. ERR_FAIL_COND_V(sdata.is_null(), nullptr);
  194. node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); //only main gets main edit state
  195. ERR_FAIL_NULL_V(node, nullptr);
  196. if (p_edit_state != GEN_EDIT_STATE_DISABLED) {
  197. node->set_scene_inherited_state(sdata->get_state());
  198. }
  199. is_inherited_scene = true;
  200. } else if (n.instance >= 0) {
  201. // Instance a scene into this node.
  202. if (n.instance & FLAG_INSTANCE_IS_PLACEHOLDER) {
  203. const String scene_path = props[n.instance & FLAG_MASK];
  204. if (disable_placeholders) {
  205. Ref<PackedScene> sdata = ResourceLoader::load(scene_path, "PackedScene");
  206. if (sdata.is_valid()) {
  207. node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
  208. ERR_FAIL_NULL_V(node, nullptr);
  209. } else if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  210. missing_node = memnew(MissingNode);
  211. missing_node->set_original_scene(scene_path);
  212. missing_node->set_recording_properties(true);
  213. node = missing_node;
  214. } else {
  215. ERR_FAIL_V_MSG(nullptr, "Placeholder scene is missing.");
  216. }
  217. } else {
  218. InstancePlaceholder *ip = memnew(InstancePlaceholder);
  219. ip->set_instance_path(scene_path);
  220. node = ip;
  221. }
  222. node->set_scene_instance_load_placeholder(true);
  223. } else {
  224. Ref<Resource> res = props[n.instance & FLAG_MASK];
  225. Ref<PackedScene> sdata = res;
  226. if (sdata.is_valid()) {
  227. node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
  228. ERR_FAIL_NULL_V_MSG(node, nullptr, vformat("Failed to load scene dependency: \"%s\". Make sure the required scene is valid.", sdata->get_path()));
  229. } else if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  230. missing_node = memnew(MissingNode);
  231. #ifdef TOOLS_ENABLED
  232. if (res.is_valid()) {
  233. missing_node->set_original_scene(res->get_meta("__load_path__", ""));
  234. }
  235. #endif
  236. missing_node->set_recording_properties(true);
  237. node = missing_node;
  238. } else {
  239. ERR_FAIL_V_MSG(nullptr, "Scene instance is missing.");
  240. }
  241. }
  242. } else if (n.type == TYPE_INSTANTIATED) {
  243. // Get the node from somewhere, it likely already exists from another instance.
  244. if (parent) {
  245. node = parent->_get_child_by_name(snames[n.name]);
  246. if (i < ids.size()) {
  247. if (!node) {
  248. // Can't get by name, try to fetch by ID. This is slow, but should be fixed after re-save.
  249. int32_t id = ids[i];
  250. if (id != Node::UNIQUE_SCENE_ID_UNASSIGNED) {
  251. if (!deep_search_warned) {
  252. WARN_PRINT(vformat("%sA node in the scene this one inherits from has been removed or moved, so a recovery process needs to take place. Please re-save this scene to avoid the cost of this process next time.", !get_path().is_empty() ? get_path() + ": " : ""));
  253. deep_search_warned = true;
  254. }
  255. Node *base = parent;
  256. while (base != ret_nodes[0] && !base->is_instance()) {
  257. base = base->get_parent();
  258. }
  259. node = _find_node_by_id(base, base, id);
  260. }
  261. } else {
  262. if (ids[i] != node->get_unique_scene_id()) {
  263. // This may be a scene that did not originally have ids and
  264. // was saved before the parent, so force the id to match the
  265. // parent scene node id.
  266. ids.write[i] = node->get_unique_scene_id();
  267. }
  268. }
  269. }
  270. #ifdef DEBUG_ENABLED
  271. if (!node) {
  272. WARN_PRINT(String("Node '" + String(ret_nodes[0]->get_path_to(parent)) + "/" + String(snames[n.name]) + "' was modified from inside an instance, but it has vanished.").ascii().get_data());
  273. }
  274. #endif
  275. }
  276. } else {
  277. // Node belongs to this scene and must be created.
  278. Object *obj = ClassDB::instantiate(snames[n.type]);
  279. node = Object::cast_to<Node>(obj);
  280. if (!node) {
  281. if (obj) {
  282. memdelete(obj);
  283. obj = nullptr;
  284. }
  285. if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  286. missing_node = memnew(MissingNode);
  287. missing_node->set_original_class(snames[n.type]);
  288. missing_node->set_recording_properties(true);
  289. node = missing_node;
  290. obj = missing_node;
  291. } else {
  292. WARN_PRINT(vformat("Node %s of type %s cannot be created. A placeholder will be created instead.", snames[n.name], snames[n.type]).ascii().get_data());
  293. if (n.parent >= 0 && n.parent < nc && ret_nodes[n.parent]) {
  294. if (Object::cast_to<Control>(ret_nodes[n.parent])) {
  295. obj = memnew(Control);
  296. } else if (Object::cast_to<Node2D>(ret_nodes[n.parent])) {
  297. obj = memnew(Node2D);
  298. #ifndef _3D_DISABLED
  299. } else if (Object::cast_to<Node3D>(ret_nodes[n.parent])) {
  300. obj = memnew(Node3D);
  301. #endif // _3D_DISABLED
  302. }
  303. }
  304. if (!obj) {
  305. obj = memnew(Node);
  306. }
  307. node = Object::cast_to<Node>(obj);
  308. }
  309. }
  310. }
  311. if (node) {
  312. if (i < ids.size()) {
  313. node->set_unique_scene_id(ids[i]);
  314. }
  315. // may not have found the node (part of instantiated scene and removed)
  316. // if found all is good, otherwise ignore
  317. //properties
  318. int nprop_count = n.properties.size();
  319. if (nprop_count) {
  320. const NodeData::Property *nprops = &n.properties[0];
  321. Dictionary missing_resource_properties;
  322. for (int j = 0; j < nprop_count; j++) {
  323. bool valid;
  324. ERR_FAIL_INDEX_V(nprops[j].value, prop_count, nullptr);
  325. if (nprops[j].name & FLAG_PATH_PROPERTY_IS_NODE) {
  326. if (!Engine::get_singleton()->is_editor_hint() && node->get_scene_instance_load_placeholder()) {
  327. // We cannot know if the referenced nodes exist yet, so instead of deferring, we write the NodePaths directly.
  328. uint32_t name_idx = nprops[j].name & (FLAG_PATH_PROPERTY_IS_NODE - 1);
  329. ERR_FAIL_UNSIGNED_INDEX_V(name_idx, (uint32_t)sname_count, nullptr);
  330. node->set(snames[name_idx], props[nprops[j].value], &valid);
  331. continue;
  332. }
  333. uint32_t name_idx = nprops[j].name & (FLAG_PATH_PROPERTY_IS_NODE - 1);
  334. ERR_FAIL_UNSIGNED_INDEX_V(name_idx, (uint32_t)sname_count, nullptr);
  335. DeferredNodePathProperties dnp;
  336. dnp.value = props[nprops[j].value];
  337. dnp.base = node->get_instance_id();
  338. dnp.property = snames[name_idx];
  339. deferred_node_paths.push_back(dnp);
  340. continue;
  341. }
  342. ERR_FAIL_INDEX_V(nprops[j].name, sname_count, nullptr);
  343. if (snames[nprops[j].name] == CoreStringName(script)) {
  344. //work around to avoid old script variables from disappearing, should be the proper fix to:
  345. //https://github.com/godotengine/godot/issues/2958
  346. //store old state
  347. List<Pair<StringName, Variant>> old_state;
  348. if (node->get_script_instance()) {
  349. node->get_script_instance()->get_property_state(old_state);
  350. }
  351. #ifdef TOOLS_ENABLED
  352. const Ref<Script> value_as_script = props[nprops[j].value];
  353. // It is possible that the user changed an existing script to abstract after it was attached to a node.
  354. // When this happens, the user needs to fix it. See https://github.com/godotengine/godot/issues/109171
  355. if (value_as_script.is_valid() && value_as_script->is_abstract()) {
  356. const String global_class_name = value_as_script->get_global_name();
  357. if (global_class_name.is_empty()) {
  358. ERR_PRINT("Node \"" + snames[n.name] + "\" previously had a script, but that script is now abstract. Please assign a different script (right-click -> Attach Script...) or change the node to a different type (right-click -> Change Type...) to fix this, then re-save the scene.");
  359. } else {
  360. ERR_PRINT("Node \"" + snames[n.name] + "\" previously had a class of type \"" + global_class_name + "\", but that class is now abstract. Please assign a different script (right-click -> Attach Script...) or change the node to a different type (right-click -> Change Type...) to fix this, then re-save the scene.");
  361. }
  362. callable_mp((Object *)node, &Object::remove_meta).call_deferred(SceneStringName(_custom_type_script));
  363. } else {
  364. node->set_script(props[nprops[j].value]);
  365. }
  366. #else
  367. node->set_script(props[nprops[j].value]);
  368. #endif // TOOLS_ENABLED
  369. //restore old state for new script, if exists
  370. for (const Pair<StringName, Variant> &E : old_state) {
  371. node->set(E.first, E.second);
  372. }
  373. } else {
  374. Variant value = props[nprops[j].value];
  375. if (value.get_type() == Variant::OBJECT) {
  376. //handle resources that are local to scene by duplicating them if needed
  377. Ref<Resource> res = value;
  378. if (res.is_valid()) {
  379. value = make_local_resource(value, n, resources_local_to_scenes, node, snames[nprops[j].name], i, ret_nodes, p_edit_state);
  380. }
  381. } else {
  382. // Making sure that instances of inherited scenes don't share the same
  383. // reference between them.
  384. if (is_inherited_scene) {
  385. value = value.duplicate(true);
  386. }
  387. }
  388. if (value.get_type() == Variant::ARRAY) {
  389. Array set_array = value;
  390. bool is_get_valid = false;
  391. Variant get_value = node->get(snames[nprops[j].name], &is_get_valid);
  392. if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
  393. Array get_array = get_value;
  394. if (set_array.is_same_typed(get_array)) {
  395. set_array = set_array.duplicate();
  396. } else {
  397. set_array = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
  398. }
  399. }
  400. value = setup_resources_in_array(set_array, n, resources_local_to_scenes, node, snames[nprops[j].name], i, ret_nodes, p_edit_state);
  401. }
  402. if (value.get_type() == Variant::DICTIONARY) {
  403. Dictionary set_dict = value;
  404. bool is_get_valid = false;
  405. Variant get_value = node->get(snames[nprops[j].name], &is_get_valid);
  406. if (is_get_valid && get_value.get_type() == Variant::DICTIONARY) {
  407. Dictionary get_dict = get_value;
  408. if (set_dict.is_same_typed(get_dict)) {
  409. set_dict = set_dict.duplicate();
  410. } else {
  411. set_dict = Dictionary(set_dict, get_dict.get_typed_key_builtin(), get_dict.get_typed_key_class_name(), get_dict.get_typed_key_script(), get_dict.get_typed_value_builtin(), get_dict.get_typed_value_class_name(), get_dict.get_typed_value_script());
  412. }
  413. }
  414. value = setup_resources_in_dictionary(set_dict, n, resources_local_to_scenes, node, snames[nprops[j].name], i, ret_nodes, p_edit_state);
  415. }
  416. bool set_valid = true;
  417. if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled() && value.get_type() == Variant::OBJECT) {
  418. Ref<MissingResource> mr = value;
  419. if (mr.is_valid()) {
  420. missing_resource_properties[snames[nprops[j].name]] = mr;
  421. set_valid = false;
  422. }
  423. }
  424. if (set_valid) {
  425. node->set(snames[nprops[j].name], value, &valid);
  426. }
  427. if (p_edit_state == GEN_EDIT_STATE_INSTANCE && value.get_type() != Variant::OBJECT) {
  428. value = value.duplicate(true); // Duplicate arrays and dictionaries for the editor.
  429. }
  430. }
  431. }
  432. if (!missing_resource_properties.is_empty()) {
  433. node->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
  434. }
  435. }
  436. //name
  437. //groups
  438. for (int j = 0; j < n.groups.size(); j++) {
  439. ERR_FAIL_INDEX_V(n.groups[j], sname_count, nullptr);
  440. node->add_to_group(snames[n.groups[j]], true);
  441. }
  442. if (n.instance >= 0 || n.type != TYPE_INSTANTIATED || i == 0) {
  443. //if node was not part of instance, must set its name, parenthood and ownership
  444. if (i > 0) {
  445. if (parent) {
  446. bool pending_add = true;
  447. #ifdef TOOLS_ENABLED
  448. if (Engine::get_singleton()->is_editor_hint()) {
  449. Node *existing = parent->_get_child_by_name(snames[n.name]);
  450. if (existing) {
  451. // There's already a node in the same parent with the same name.
  452. // This means that somehow the node was added both to the scene being
  453. // loaded and another one instantiated in the former, maybe because of
  454. // manual editing, or a bug in scene saving, or a loophole in the workflow
  455. // (with any of the bugs possibly already fixed).
  456. // Bring consistency back by letting it be assigned a non-clashing name.
  457. // This simple workaround at least avoids leaks and helps the user realize
  458. // something awkward has happened.
  459. if (instantiation_warn_notify) {
  460. instantiation_warn_notify(vformat(
  461. TTR("An incoming node's name clashes with %s already in the scene (presumably, from a more nested instance).\nThe less nested node will be renamed. Please fix and re-save the scene."),
  462. ret_nodes[0]->get_path_to(existing)));
  463. }
  464. node->set_name(snames[n.name]);
  465. parent->add_child(node, true);
  466. pending_add = false;
  467. }
  468. }
  469. #endif
  470. if (pending_add) {
  471. parent->_add_child_nocheck(node, snames[n.name]);
  472. }
  473. if (n.index >= 0 && n.index < parent->get_child_count() - 1) {
  474. parent->move_child(node, n.index);
  475. }
  476. } else {
  477. //it may be possible that an instantiated scene has changed
  478. //and the node has nowhere to go anymore
  479. stray_instances.push_back(node); //can't be added, go to stray list
  480. }
  481. } else {
  482. if (Engine::get_singleton()->is_editor_hint()) {
  483. //validate name if using editor, to avoid broken
  484. node->set_name(snames[n.name]);
  485. } else {
  486. node->_set_name_nocheck(snames[n.name]);
  487. }
  488. }
  489. }
  490. if (!old_parent_path.is_empty()) {
  491. node->set_name(old_parent_path + "#" + node->get_name());
  492. }
  493. if (n.owner >= 0) {
  494. NODE_FROM_ID(owner, n.owner);
  495. if (owner) {
  496. node->_set_owner_nocheck(owner);
  497. if (node->data.unique_name_in_owner) {
  498. node->_acquire_unique_name_in_owner();
  499. }
  500. }
  501. }
  502. // We only want to deal with pinned flag if instantiating as pure main (no instance, no inheriting.)
  503. if (p_edit_state == GEN_EDIT_STATE_MAIN) {
  504. _sanitize_node_pinned_properties(node);
  505. } else {
  506. node->remove_meta("_edit_pinned_properties_");
  507. }
  508. }
  509. if (missing_node) {
  510. missing_node->set_recording_properties(false);
  511. }
  512. ret_nodes[i] = node;
  513. if (node && gen_node_path_cache && ret_nodes[0]) {
  514. NodePath n2 = ret_nodes[0]->get_path_to(node);
  515. node_path_cache[n2] = i;
  516. }
  517. }
  518. for (const DeferredNodePathProperties &dnp : deferred_node_paths) {
  519. // Replace properties stored as NodePaths with actual Nodes.
  520. Node *base = ObjectDB::get_instance<Node>(dnp.base);
  521. ERR_CONTINUE_EDMSG(!base, vformat("Failed to set deferred property '%s' as the base node disappeared.", dnp.property));
  522. if (dnp.value.get_type() == Variant::ARRAY) {
  523. Array paths = dnp.value;
  524. bool valid;
  525. Array array = base->get(dnp.property, &valid);
  526. ERR_CONTINUE_EDMSG(!valid, vformat("Failed to get property '%s' from node '%s'.", dnp.property, base->get_name()));
  527. array = array.duplicate();
  528. array.resize(paths.size());
  529. for (int i = 0; i < array.size(); i++) {
  530. array.set(i, base->get_node_or_null(paths[i]));
  531. }
  532. base->set(dnp.property, array);
  533. } else if (dnp.value.get_type() == Variant::DICTIONARY) {
  534. Dictionary paths = dnp.value;
  535. bool valid;
  536. Dictionary dict = base->get(dnp.property, &valid);
  537. ERR_CONTINUE_EDMSG(!valid, vformat("Failed to get property '%s' from node '%s'.", dnp.property, base->get_name()));
  538. dict = dict.duplicate();
  539. bool convert_key = dict.get_typed_key_builtin() == Variant::OBJECT &&
  540. ClassDB::is_parent_class(dict.get_typed_key_class_name(), "Node");
  541. bool convert_value = dict.get_typed_value_builtin() == Variant::OBJECT &&
  542. ClassDB::is_parent_class(dict.get_typed_value_class_name(), "Node");
  543. for (const KeyValue<Variant, Variant> &kv : paths) {
  544. Variant key = kv.key;
  545. if (convert_key) {
  546. key = base->get_node_or_null(key);
  547. }
  548. Variant value = kv.value;
  549. if (convert_value) {
  550. value = base->get_node_or_null(value);
  551. }
  552. dict[key] = value;
  553. }
  554. base->set(dnp.property, dict);
  555. } else {
  556. base->set(dnp.property, base->get_node_or_null(dnp.value));
  557. }
  558. }
  559. for (KeyValue<Node *, HashMap<Ref<Resource>, Ref<Resource>>> &E : resources_local_to_scenes) {
  560. for (KeyValue<Ref<Resource>, Ref<Resource>> &R : E.value) {
  561. R.value->setup_local_to_scene(); // Setup may be required for the resource to work properly.
  562. }
  563. }
  564. //do connections
  565. int cc = connections.size();
  566. const ConnectionData *cdata = connections.ptr();
  567. for (int i = 0; i < cc; i++) {
  568. const ConnectionData &c = cdata[i];
  569. //ERR_FAIL_INDEX_V( c.from, nc, nullptr );
  570. //ERR_FAIL_INDEX_V( c.to, nc, nullptr );
  571. NODE_FROM_ID(cfrom, c.from);
  572. NODE_FROM_ID(cto, c.to);
  573. if (!cfrom || !cto) {
  574. continue;
  575. }
  576. Callable callable(cto, snames[c.method]);
  577. Array binds;
  578. for (int bind : c.binds) {
  579. binds.push_back(props[bind]);
  580. }
  581. if (!binds.is_empty()) {
  582. callable = callable.bindv(binds);
  583. }
  584. if (c.unbinds > 0) {
  585. callable = callable.unbind(c.unbinds);
  586. }
  587. cfrom->connect(snames[c.signal], callable, CONNECT_PERSIST | c.flags | (p_edit_state == GEN_EDIT_STATE_MAIN ? 0 : CONNECT_INHERITED));
  588. }
  589. //Node *s = ret_nodes[0];
  590. //remove nodes that could not be added, likely as a result that
  591. while (stray_instances.size()) {
  592. memdelete(stray_instances.front()->get());
  593. stray_instances.pop_front();
  594. }
  595. for (int i = 0; i < editable_instances.size(); i++) {
  596. Node *ei = ret_nodes[0]->get_node_or_null(editable_instances[i]);
  597. if (ei) {
  598. ret_nodes[0]->set_editable_instance(ei, true);
  599. }
  600. }
  601. return ret_nodes[0];
  602. }
  603. Variant SceneState::make_local_resource(Variant &p_value, const SceneState::NodeData &p_node_data, HashMap<Node *, HashMap<Ref<Resource>, Ref<Resource>>> &p_resources_local_to_scenes, Node *p_node, const StringName p_sname, int p_i, Node **p_ret_nodes, SceneState::GenEditState p_edit_state) const {
  604. Ref<Resource> res = p_value;
  605. if (res.is_null() || !res->is_local_to_scene()) {
  606. return p_value;
  607. }
  608. Node *base = (p_i == 0 || p_node->is_instance()) ? p_node : (p_node->get_owner() ? p_node->get_owner() : p_ret_nodes[0]);
  609. if (p_node_data.type == TYPE_INSTANTIATED) { // For the (root) nodes of sub-scenes, treat them as parts of the sub-scenes.
  610. return get_remap_resource(res, p_resources_local_to_scenes, p_node->get(p_sname), base);
  611. }
  612. // Find the shared copy of the source resource.
  613. HashMap<Ref<Resource>, Ref<Resource>>::Iterator R = p_resources_local_to_scenes[base].find(res);
  614. if (R) {
  615. return R->value;
  616. }
  617. if (p_edit_state == GEN_EDIT_STATE_MAIN) { // For the main scene, use the resource as is
  618. res->configure_for_local_scene(base, p_resources_local_to_scenes[base]);
  619. p_resources_local_to_scenes[base][res] = res;
  620. return res;
  621. }
  622. // For instances, a copy must be made.
  623. Ref<Resource> local_dupe = res->duplicate_for_local_scene(base, p_resources_local_to_scenes[base]);
  624. p_resources_local_to_scenes[base][res] = local_dupe;
  625. return local_dupe;
  626. }
  627. Array SceneState::setup_resources_in_array(Array &p_array_to_scan, const SceneState::NodeData &p_n, HashMap<Node *, HashMap<Ref<Resource>, Ref<Resource>>> &p_resources_local_to_scenes, Node *p_node, const StringName p_sname, int p_i, Node **p_ret_nodes, SceneState::GenEditState p_edit_state) const {
  628. for (int i = 0; i < p_array_to_scan.size(); i++) {
  629. if (p_array_to_scan[i].get_type() == Variant::OBJECT) {
  630. p_array_to_scan[i] = make_local_resource(p_array_to_scan[i], p_n, p_resources_local_to_scenes, p_node, p_sname, p_i, p_ret_nodes, p_edit_state);
  631. }
  632. }
  633. return p_array_to_scan;
  634. }
  635. Dictionary SceneState::setup_resources_in_dictionary(Dictionary &p_dictionary_to_scan, const SceneState::NodeData &p_n, HashMap<Node *, HashMap<Ref<Resource>, Ref<Resource>>> &p_resources_local_to_scenes, Node *p_node, const StringName p_sname, int p_i, Node **p_ret_nodes, SceneState::GenEditState p_edit_state) const {
  636. const Array keys = p_dictionary_to_scan.keys();
  637. const Array values = p_dictionary_to_scan.values();
  638. if (has_local_resource(values) || has_local_resource(keys)) {
  639. Array duplicated_keys = keys.duplicate(true);
  640. Array duplicated_values = values.duplicate(true);
  641. duplicated_keys = setup_resources_in_array(duplicated_keys, p_n, p_resources_local_to_scenes, p_node, p_sname, p_i, p_ret_nodes, p_edit_state);
  642. duplicated_values = setup_resources_in_array(duplicated_values, p_n, p_resources_local_to_scenes, p_node, p_sname, p_i, p_ret_nodes, p_edit_state);
  643. p_dictionary_to_scan.clear();
  644. for (int i = 0; i < keys.size(); i++) {
  645. p_dictionary_to_scan[duplicated_keys[i]] = duplicated_values[i];
  646. }
  647. }
  648. return p_dictionary_to_scan;
  649. }
  650. bool SceneState::has_local_resource(const Array &p_array) const {
  651. for (int i = 0; i < p_array.size(); i++) {
  652. Ref<Resource> res = p_array[i];
  653. if (res.is_valid() && res->is_local_to_scene()) {
  654. return true;
  655. }
  656. }
  657. return false;
  658. }
  659. static int _nm_get_string(const String &p_string, HashMap<StringName, int> &name_map) {
  660. if (name_map.has(p_string)) {
  661. return name_map[p_string];
  662. }
  663. int idx = name_map.size();
  664. name_map[p_string] = idx;
  665. return idx;
  666. }
  667. static int _vm_get_variant(const Variant &p_variant, HashMap<Variant, int> &variant_map) {
  668. if (variant_map.has(p_variant)) {
  669. return variant_map[p_variant];
  670. }
  671. int idx = variant_map.size();
  672. variant_map[p_variant] = idx;
  673. return idx;
  674. }
  675. Error SceneState::_parse_node(Node *p_owner, Node *p_node, int p_parent_idx, HashMap<StringName, int> &name_map, HashMap<Variant, int> &variant_map, HashMap<Node *, int> &node_map, HashMap<Node *, int> &nodepath_map, HashSet<int32_t> &ids_saved) {
  676. // this function handles all the work related to properly packing scenes, be it
  677. // instantiated or inherited.
  678. // given the complexity of this process, an attempt will be made to properly
  679. // document it. if you fail to understand something, please ask!
  680. //discard nodes that do not belong to be processed
  681. if (p_node != p_owner && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner())) {
  682. return OK;
  683. }
  684. bool is_editable_instance = false;
  685. // save the child instantiated scenes that are chosen as editable, so they can be restored
  686. // upon load back
  687. if (p_node != p_owner && p_node->is_instance() && p_owner->is_editable_instance(p_node)) {
  688. editable_instances.push_back(p_owner->get_path_to(p_node));
  689. // Node is the root of an editable instance.
  690. is_editable_instance = true;
  691. } else if (p_node->get_owner() && p_owner->is_ancestor_of(p_node->get_owner()) && p_owner->is_editable_instance(p_node->get_owner())) {
  692. // Node is part of an editable instance.
  693. is_editable_instance = true;
  694. }
  695. NodeData nd;
  696. nd.name = _nm_get_string(p_node->get_name(), name_map);
  697. nd.instance = -1; //not instantiated by default
  698. //really convoluted condition, but it basically checks that index is only saved when part of an inherited scene OR the node parent is from the edited scene
  699. if (p_owner->get_scene_inherited_state().is_null() && (p_node == p_owner || (p_node->get_owner() == p_owner && (p_node->get_parent() == p_owner || p_node->get_parent()->get_owner() == p_owner)))) {
  700. //do not save index, because it belongs to saved scene and scene is not inherited
  701. nd.index = -1;
  702. } else if (p_node == p_owner) {
  703. //This (hopefully) happens if the node is a scene root, so its index is irrelevant.
  704. nd.index = -1;
  705. } else {
  706. //part of an inherited scene, or parent is from an instantiated scene
  707. nd.index = p_node->get_index();
  708. }
  709. // if this node is part of an instantiated scene or sub-instantiated scene
  710. // we need to get the corresponding instance states.
  711. // with the instance states, we can query for identical properties/groups
  712. // and only save what has changed
  713. bool instantiated_by_owner = false;
  714. Vector<SceneState::PackState> states_stack = PropertyUtils::get_node_states_stack(p_node, p_owner, &instantiated_by_owner);
  715. if (p_node->is_instance() && p_node->get_owner() == p_owner && instantiated_by_owner) {
  716. if (p_node->get_scene_instance_load_placeholder()) {
  717. //it's a placeholder, use the placeholder path
  718. nd.instance = _vm_get_variant(p_node->get_scene_file_path(), variant_map);
  719. nd.instance |= FLAG_INSTANCE_IS_PLACEHOLDER;
  720. } else {
  721. //must instance ourselves
  722. Ref<PackedScene> instance = ResourceLoader::load(p_node->get_scene_file_path());
  723. if (instance.is_null()) {
  724. return ERR_CANT_OPEN;
  725. }
  726. nd.instance = _vm_get_variant(instance, variant_map);
  727. }
  728. }
  729. // all setup, we then proceed to check all properties for the node
  730. // and save the ones that are worth saving
  731. List<PropertyInfo> plist;
  732. p_node->get_property_list(&plist);
  733. Array pinned_props = _sanitize_node_pinned_properties(p_node);
  734. Dictionary missing_resource_properties = p_node->get_meta(META_MISSING_RESOURCES, Dictionary());
  735. for (const PropertyInfo &E : plist) {
  736. if (!(E.usage & PROPERTY_USAGE_STORAGE) && !missing_resource_properties.has(E.name)) {
  737. continue;
  738. }
  739. if (E.name == META_PROPERTY_MISSING_RESOURCES) {
  740. continue; // Ignore this property when packing.
  741. }
  742. // If instance or inheriting, not saving if property requested so.
  743. if (!states_stack.is_empty()) {
  744. if ((E.usage & PROPERTY_USAGE_NO_INSTANCE_STATE)) {
  745. continue;
  746. }
  747. }
  748. StringName name = E.name;
  749. Variant value = p_node->get(name);
  750. bool use_deferred_node_path_bit = false;
  751. if (E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_NODE_TYPE) {
  752. if (value.get_type() == Variant::OBJECT) {
  753. if (Node *n = Object::cast_to<Node>(value)) {
  754. value = p_node->get_path_to(n);
  755. }
  756. use_deferred_node_path_bit = true;
  757. }
  758. if (value.get_type() != Variant::NODE_PATH) {
  759. continue; //was never set, ignore.
  760. }
  761. } else if (E.type == Variant::OBJECT && missing_resource_properties.has(E.name)) {
  762. // Was this missing resource overridden? If so do not save the old value.
  763. Ref<Resource> ures = value;
  764. if (ures.is_null()) {
  765. value = missing_resource_properties[E.name];
  766. }
  767. } else if (E.type == Variant::ARRAY && E.hint == PROPERTY_HINT_TYPE_STRING) {
  768. int hint_subtype_separator = E.hint_string.find_char(':');
  769. if (hint_subtype_separator >= 0) {
  770. String subtype_string = E.hint_string.substr(0, hint_subtype_separator);
  771. int slash_pos = subtype_string.find_char('/');
  772. PropertyHint subtype_hint = PropertyHint::PROPERTY_HINT_NONE;
  773. if (slash_pos >= 0) {
  774. subtype_hint = PropertyHint(subtype_string.get_slicec('/', 1).to_int());
  775. subtype_string = subtype_string.substr(0, slash_pos);
  776. }
  777. Variant::Type subtype = Variant::Type(subtype_string.to_int());
  778. if (subtype == Variant::OBJECT && subtype_hint == PROPERTY_HINT_NODE_TYPE) {
  779. use_deferred_node_path_bit = true;
  780. Array array = value;
  781. Array new_array;
  782. for (int i = 0; i < array.size(); i++) {
  783. Variant elem = array[i];
  784. if (elem.get_type() == Variant::OBJECT) {
  785. if (Node *n = Object::cast_to<Node>(elem)) {
  786. new_array.push_back(p_node->get_path_to(n));
  787. continue;
  788. }
  789. }
  790. new_array.push_back(elem);
  791. }
  792. value = new_array;
  793. }
  794. }
  795. } else if (E.type == Variant::DICTIONARY && E.hint == PROPERTY_HINT_TYPE_STRING) {
  796. int key_value_separator = E.hint_string.find_char(';');
  797. if (key_value_separator >= 0) {
  798. int key_subtype_separator = E.hint_string.find_char(':');
  799. String key_subtype_string = E.hint_string.substr(0, key_subtype_separator);
  800. int key_slash_pos = key_subtype_string.find_char('/');
  801. PropertyHint key_subtype_hint = PropertyHint::PROPERTY_HINT_NONE;
  802. if (key_slash_pos >= 0) {
  803. key_subtype_hint = PropertyHint(key_subtype_string.get_slicec('/', 1).to_int());
  804. key_subtype_string = key_subtype_string.substr(0, key_slash_pos);
  805. }
  806. Variant::Type key_subtype = Variant::Type(key_subtype_string.to_int());
  807. bool convert_key = key_subtype == Variant::OBJECT && key_subtype_hint == PROPERTY_HINT_NODE_TYPE;
  808. int value_subtype_separator = E.hint_string.find_char(':', key_value_separator) - (key_value_separator + 1);
  809. String value_subtype_string = E.hint_string.substr(key_value_separator + 1, value_subtype_separator);
  810. int value_slash_pos = value_subtype_string.find_char('/');
  811. PropertyHint value_subtype_hint = PropertyHint::PROPERTY_HINT_NONE;
  812. if (value_slash_pos >= 0) {
  813. value_subtype_hint = PropertyHint(value_subtype_string.get_slicec('/', 1).to_int());
  814. value_subtype_string = value_subtype_string.substr(0, value_slash_pos);
  815. }
  816. Variant::Type value_subtype = Variant::Type(value_subtype_string.to_int());
  817. bool convert_value = value_subtype == Variant::OBJECT && value_subtype_hint == PROPERTY_HINT_NODE_TYPE;
  818. if (convert_key || convert_value) {
  819. use_deferred_node_path_bit = true;
  820. Dictionary dict = value;
  821. Dictionary new_dict;
  822. for (const KeyValue<Variant, Variant> &kv : dict) {
  823. Variant new_key = kv.key;
  824. if (convert_key && new_key.get_type() == Variant::OBJECT) {
  825. if (Node *n = Object::cast_to<Node>(new_key)) {
  826. new_key = p_node->get_path_to(n);
  827. }
  828. }
  829. Variant new_value = kv.value;
  830. if (convert_value && new_value.get_type() == Variant::OBJECT) {
  831. if (Node *n = Object::cast_to<Node>(new_value)) {
  832. new_value = p_node->get_path_to(n);
  833. }
  834. }
  835. new_dict[new_key] = new_value;
  836. }
  837. value = new_dict;
  838. }
  839. }
  840. }
  841. if (!pinned_props.has(name)) {
  842. bool is_valid_default = false;
  843. Variant default_value = PropertyUtils::get_property_default_value(p_node, name, &is_valid_default, &states_stack, true);
  844. if (is_valid_default && !PropertyUtils::is_property_value_different(p_node, value, default_value)) {
  845. if (value.get_type() == Variant::ARRAY && has_local_resource(value)) {
  846. // Save anyway
  847. } else if (value.get_type() == Variant::DICTIONARY) {
  848. Dictionary dictionary = value;
  849. if (!has_local_resource(dictionary.values()) && !has_local_resource(dictionary.keys())) {
  850. continue;
  851. }
  852. } else {
  853. continue;
  854. }
  855. }
  856. }
  857. NodeData::Property prop;
  858. prop.name = _nm_get_string(name, name_map);
  859. prop.value = _vm_get_variant(value, variant_map);
  860. if (use_deferred_node_path_bit) {
  861. prop.name |= FLAG_PATH_PROPERTY_IS_NODE;
  862. }
  863. nd.properties.push_back(prop);
  864. }
  865. // save the groups this node is into
  866. // discard groups that come from the original scene
  867. List<Node::GroupInfo> groups;
  868. p_node->get_groups(&groups);
  869. for (const Node::GroupInfo &gi : groups) {
  870. if (!gi.persistent) {
  871. continue;
  872. }
  873. bool skip = false;
  874. for (const SceneState::PackState &ia : states_stack) {
  875. //check all levels of pack to see if the group was added somewhere
  876. if (ia.state->is_node_in_group(ia.node, gi.name)) {
  877. skip = true;
  878. break;
  879. }
  880. }
  881. if (skip) {
  882. continue;
  883. }
  884. nd.groups.push_back(_nm_get_string(gi.name, name_map));
  885. }
  886. // save the right owner
  887. // for the saved scene root this is -1
  888. // for nodes of the saved scene this is 0
  889. // for nodes of instantiated scenes this is >0
  890. if (p_node == p_owner) {
  891. //saved scene root
  892. nd.owner = -1;
  893. } else if (p_node->get_owner() == p_owner) {
  894. //part of saved scene
  895. nd.owner = 0;
  896. } else {
  897. nd.owner = -1;
  898. }
  899. MissingNode *missing_node = Object::cast_to<MissingNode>(p_node);
  900. // Save the right type. If this node was created by an instance
  901. // then flag that the node should not be created but reused
  902. if (states_stack.is_empty() && !is_editable_instance) {
  903. //This node is not part of an instantiation process, so save the type.
  904. if (missing_node != nullptr) {
  905. // It's a missing node (type non existent on load).
  906. nd.type = _nm_get_string(missing_node->get_original_class(), name_map);
  907. } else {
  908. nd.type = _nm_get_string(p_node->get_class(), name_map);
  909. }
  910. } else {
  911. // this node is part of an instantiated process, so do not save the type.
  912. // instead, save that it was instantiated
  913. nd.type = TYPE_INSTANTIATED;
  914. }
  915. // determine whether to save this node or not
  916. // if this node is part of an instantiated sub-scene, we can skip storing it if basically
  917. // no properties changed and no groups were added to it.
  918. // below condition is true for all nodes of the scene being saved, and ones in subscenes
  919. // that hold changes
  920. bool save_node = p_node == p_owner; // owner is always saved
  921. save_node = save_node || (p_node->get_owner() == p_owner && instantiated_by_owner); //part of scene and not instanced
  922. bool save_data = nd.properties.size() || nd.groups.size(); // some local properties or groups exist
  923. int idx = nodes.size();
  924. int parent_node = NO_PARENT_SAVED;
  925. if (save_node || save_data) {
  926. //don't save the node if nothing and subscene
  927. node_map[p_node] = idx;
  928. //ok validate parent node
  929. if (p_parent_idx == NO_PARENT_SAVED) {
  930. int sidx;
  931. if (nodepath_map.has(p_node->get_parent())) {
  932. sidx = nodepath_map[p_node->get_parent()];
  933. } else {
  934. sidx = nodepath_map.size();
  935. nodepath_map[p_node->get_parent()] = sidx;
  936. }
  937. nd.parent = FLAG_ID_IS_PATH | sidx;
  938. } else {
  939. nd.parent = p_parent_idx;
  940. }
  941. int32_t unique_scene_id = p_node->get_unique_scene_id();
  942. if (save_node && (unique_scene_id == Node::UNIQUE_SCENE_ID_UNASSIGNED || ids_saved.has(unique_scene_id))) {
  943. // Unassigned or clash somehow.
  944. // Clashes will always happen with instantiated scenes, so it is normal
  945. // to expect them to be resolved.
  946. while (true) {
  947. uint32_t data = ResourceUID::get_singleton()->create_id();
  948. unique_scene_id = data & 0x7FFFFFFF; // keep positive.
  949. if (unique_scene_id == Node::UNIQUE_SCENE_ID_UNASSIGNED) {
  950. unique_scene_id = 1;
  951. }
  952. if (ids_saved.has(unique_scene_id)) {
  953. // While there is one in a four billion chance for a clash, the scenario where one scene is instantiated multiple times is common, so it must reassign the local id.
  954. continue;
  955. }
  956. break;
  957. }
  958. p_node->set_unique_scene_id(unique_scene_id);
  959. }
  960. ids_saved.insert(unique_scene_id);
  961. ids.push_back(unique_scene_id);
  962. parent_node = idx;
  963. nodes.push_back(nd);
  964. }
  965. for (int i = 0; i < p_node->get_child_count(); i++) {
  966. Node *c = p_node->get_child(i);
  967. Error err = _parse_node(p_owner, c, parent_node, name_map, variant_map, node_map, nodepath_map, ids_saved);
  968. if (err) {
  969. return err;
  970. }
  971. }
  972. return OK;
  973. }
  974. Error SceneState::_parse_connections(Node *p_owner, Node *p_node, HashMap<StringName, int> &name_map, HashMap<Variant, int> &variant_map, HashMap<Node *, int> &node_map, HashMap<Node *, int> &nodepath_map) {
  975. // Ignore nodes that are within a scene instance.
  976. if (p_node != p_owner && p_node->get_owner() && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner())) {
  977. return OK;
  978. }
  979. List<MethodInfo> _signals;
  980. p_node->get_signal_list(&_signals);
  981. _signals.sort();
  982. //ERR_FAIL_COND_V( !node_map.has(p_node), ERR_BUG);
  983. //NodeData &nd = nodes[node_map[p_node]];
  984. for (const MethodInfo &E : _signals) {
  985. List<Node::Connection> conns;
  986. p_node->get_signal_connection_list(E.name, &conns);
  987. conns.sort();
  988. for (const Node::Connection &F : conns) {
  989. const Node::Connection &c = F;
  990. // Don't save connections that are not persistent.
  991. if (!(c.flags & CONNECT_PERSIST)) {
  992. continue;
  993. }
  994. // only connections that originate or end into main saved scene are saved
  995. // everything else is discarded
  996. Node *target = Object::cast_to<Node>(c.callable.get_object());
  997. if (!target) {
  998. continue;
  999. }
  1000. Vector<Variant> binds;
  1001. int unbinds = 0;
  1002. Callable base_callable;
  1003. if (c.callable.is_custom()) {
  1004. CallableCustomBind *ccb = dynamic_cast<CallableCustomBind *>(c.callable.get_custom());
  1005. if (ccb) {
  1006. binds = ccb->get_binds();
  1007. unbinds = ccb->get_unbound_arguments_count();
  1008. base_callable = ccb->get_callable();
  1009. }
  1010. CallableCustomUnbind *ccu = dynamic_cast<CallableCustomUnbind *>(c.callable.get_custom());
  1011. if (ccu) {
  1012. ccu->get_bound_arguments(binds);
  1013. unbinds = ccu->get_unbinds();
  1014. base_callable = ccu->get_callable();
  1015. }
  1016. } else {
  1017. base_callable = c.callable;
  1018. }
  1019. //find if this connection already exists
  1020. Node *common_parent = target->find_common_parent_with(p_node);
  1021. ERR_CONTINUE(!common_parent);
  1022. if (common_parent != p_owner && !common_parent->is_instance()) {
  1023. common_parent = common_parent->get_owner();
  1024. }
  1025. bool exists = false;
  1026. //go through ownership chain to see if this exists
  1027. while (common_parent) {
  1028. Ref<SceneState> ps;
  1029. if (common_parent == p_owner) {
  1030. ps = common_parent->get_scene_inherited_state();
  1031. } else {
  1032. ps = common_parent->get_scene_instance_state();
  1033. }
  1034. if (ps.is_valid()) {
  1035. NodePath signal_from = common_parent->get_path_to(p_node);
  1036. NodePath signal_to = common_parent->get_path_to(target);
  1037. if (ps->has_connection(signal_from, c.signal.get_name(), signal_to, base_callable.get_method())) {
  1038. exists = true;
  1039. break;
  1040. }
  1041. }
  1042. if (common_parent == p_owner) {
  1043. break;
  1044. } else {
  1045. common_parent = common_parent->get_owner();
  1046. }
  1047. }
  1048. if (exists) { //already exists (comes from instance or inheritance), so don't save
  1049. continue;
  1050. }
  1051. {
  1052. Node *nl = p_node;
  1053. bool exists2 = false;
  1054. while (nl) {
  1055. if (nl == p_owner) {
  1056. Ref<SceneState> state = nl->get_scene_inherited_state();
  1057. if (state.is_valid()) {
  1058. int from_node = state->find_node_by_path(nl->get_path_to(p_node));
  1059. int to_node = state->find_node_by_path(nl->get_path_to(target));
  1060. if (from_node >= 0 && to_node >= 0) {
  1061. //this one has state for this node, save
  1062. if (state->is_connection(from_node, c.signal.get_name(), to_node, base_callable.get_method())) {
  1063. exists2 = true;
  1064. break;
  1065. }
  1066. }
  1067. }
  1068. nl = nullptr;
  1069. } else {
  1070. if (nl->is_instance()) {
  1071. Ref<SceneState> state = nl->get_scene_instance_state();
  1072. if (state.is_valid()) {
  1073. int from_node = state->find_node_by_path(nl->get_path_to(p_node));
  1074. int to_node = state->find_node_by_path(nl->get_path_to(target));
  1075. if (from_node >= 0 && to_node >= 0) {
  1076. //this one has state for this node, save
  1077. if (state->is_connection(from_node, c.signal.get_name(), to_node, base_callable.get_method())) {
  1078. exists2 = true;
  1079. break;
  1080. }
  1081. }
  1082. }
  1083. }
  1084. nl = nl->get_owner();
  1085. }
  1086. }
  1087. if (exists2) {
  1088. continue;
  1089. }
  1090. }
  1091. int src_id;
  1092. if (node_map.has(p_node)) {
  1093. src_id = node_map[p_node];
  1094. } else {
  1095. if (nodepath_map.has(p_node)) {
  1096. src_id = FLAG_ID_IS_PATH | nodepath_map[p_node];
  1097. } else {
  1098. int sidx = nodepath_map.size();
  1099. nodepath_map[p_node] = sidx;
  1100. src_id = FLAG_ID_IS_PATH | sidx;
  1101. }
  1102. }
  1103. int target_id;
  1104. if (node_map.has(target)) {
  1105. target_id = node_map[target];
  1106. } else {
  1107. if (nodepath_map.has(target)) {
  1108. target_id = FLAG_ID_IS_PATH | nodepath_map[target];
  1109. } else {
  1110. int sidx = nodepath_map.size();
  1111. nodepath_map[target] = sidx;
  1112. target_id = FLAG_ID_IS_PATH | sidx;
  1113. }
  1114. }
  1115. ConnectionData cd;
  1116. cd.from = src_id;
  1117. cd.to = target_id;
  1118. cd.method = _nm_get_string(base_callable.get_method(), name_map);
  1119. cd.signal = _nm_get_string(c.signal.get_name(), name_map);
  1120. cd.flags = c.flags & ~CONNECT_INHERITED; // Do not store inherited.
  1121. cd.unbinds = unbinds;
  1122. for (int i = 0; i < binds.size(); i++) {
  1123. cd.binds.push_back(_vm_get_variant(binds[i], variant_map));
  1124. }
  1125. connections.push_back(cd);
  1126. }
  1127. }
  1128. // Recursively parse child connections.
  1129. for (int i = 0; i < p_node->get_child_count(); i++) {
  1130. Node *child = p_node->get_child(i);
  1131. Error err = _parse_connections(p_owner, child, name_map, variant_map, node_map, nodepath_map);
  1132. if (err) {
  1133. return err;
  1134. }
  1135. }
  1136. return OK;
  1137. }
  1138. Error SceneState::pack(Node *p_scene) {
  1139. ERR_FAIL_NULL_V(p_scene, ERR_INVALID_PARAMETER);
  1140. clear();
  1141. Node *scene = p_scene;
  1142. HashMap<StringName, int> name_map;
  1143. HashMap<Variant, int> variant_map;
  1144. HashMap<Node *, int> node_map;
  1145. HashMap<Node *, int> nodepath_map;
  1146. HashSet<int32_t> ids_saved;
  1147. // If using scene inheritance, pack the scene it inherits from.
  1148. if (scene->get_scene_inherited_state().is_valid()) {
  1149. String scene_path = scene->get_scene_inherited_state()->get_path();
  1150. Ref<PackedScene> instance = ResourceLoader::load(scene_path);
  1151. if (instance.is_valid()) {
  1152. base_scene_idx = _vm_get_variant(instance, variant_map);
  1153. }
  1154. }
  1155. // Instanced, only direct sub-scenes are supported of course.
  1156. Error err = _parse_node(scene, scene, -1, name_map, variant_map, node_map, nodepath_map, ids_saved);
  1157. if (err) {
  1158. clear();
  1159. ERR_FAIL_V(err);
  1160. }
  1161. err = _parse_connections(scene, scene, name_map, variant_map, node_map, nodepath_map);
  1162. if (err) {
  1163. clear();
  1164. ERR_FAIL_V(err);
  1165. }
  1166. names.resize(name_map.size());
  1167. for (const KeyValue<StringName, int> &E : name_map) {
  1168. names.write[E.value] = E.key;
  1169. }
  1170. variants.resize(variant_map.size());
  1171. for (const KeyValue<Variant, int> &E : variant_map) {
  1172. int idx = E.value;
  1173. variants.write[idx] = E.key;
  1174. }
  1175. node_paths.resize(nodepath_map.size());
  1176. id_paths.resize(nodepath_map.size());
  1177. for (const KeyValue<Node *, int> &E : nodepath_map) {
  1178. node_paths.write[E.value] = scene->get_path_to(E.key);
  1179. // Build a path of IDs to reach the node.
  1180. PackedInt32Array id_path;
  1181. bool id_path_valid = false;
  1182. Node *base = E.key;
  1183. while (base && base->get_unique_scene_id() != Node::UNIQUE_SCENE_ID_UNASSIGNED) {
  1184. id_path.push_back(base->get_unique_scene_id());
  1185. base = base->get_owner();
  1186. if (base == p_scene) {
  1187. id_path_valid = true;
  1188. break;
  1189. }
  1190. }
  1191. if (!id_path_valid) {
  1192. id_path.clear();
  1193. }
  1194. // Reverse it since we went from node to owner, and we seek from owner to node.
  1195. id_path.reverse();
  1196. id_paths.write[E.value] = id_path;
  1197. }
  1198. if (Engine::get_singleton()->is_editor_hint()) {
  1199. // Build node path cache
  1200. for (const KeyValue<Node *, int> &E : node_map) {
  1201. node_path_cache[scene->get_path_to(E.key)] = E.value;
  1202. }
  1203. }
  1204. return OK;
  1205. }
  1206. void SceneState::set_path(const String &p_path) {
  1207. path = p_path;
  1208. }
  1209. String SceneState::get_path() const {
  1210. return path;
  1211. }
  1212. void SceneState::clear() {
  1213. names.clear();
  1214. variants.clear();
  1215. nodes.clear();
  1216. connections.clear();
  1217. node_path_cache.clear();
  1218. node_paths.clear();
  1219. editable_instances.clear();
  1220. ids.clear();
  1221. id_paths.clear();
  1222. base_scene_idx = -1;
  1223. }
  1224. Error SceneState::copy_from(const Ref<SceneState> &p_scene_state) {
  1225. ERR_FAIL_COND_V(p_scene_state.is_null(), ERR_INVALID_PARAMETER);
  1226. clear();
  1227. for (const StringName &E : p_scene_state->names) {
  1228. names.append(E);
  1229. }
  1230. for (const Variant &E : p_scene_state->variants) {
  1231. variants.append(E);
  1232. }
  1233. for (const SceneState::NodeData &E : p_scene_state->nodes) {
  1234. nodes.append(E);
  1235. }
  1236. for (const SceneState::ConnectionData &E : p_scene_state->connections) {
  1237. connections.append(E);
  1238. }
  1239. for (KeyValue<NodePath, int> &E : p_scene_state->node_path_cache) {
  1240. node_path_cache.insert(E.key, E.value);
  1241. }
  1242. for (const NodePath &E : p_scene_state->node_paths) {
  1243. node_paths.append(E);
  1244. }
  1245. for (const PackedInt32Array &E : p_scene_state->id_paths) {
  1246. id_paths.append(E);
  1247. }
  1248. for (const NodePath &E : p_scene_state->editable_instances) {
  1249. editable_instances.append(E);
  1250. }
  1251. base_scene_idx = p_scene_state->base_scene_idx;
  1252. return OK;
  1253. }
  1254. Ref<SceneState> SceneState::get_base_scene_state() const {
  1255. if (base_scene_idx >= 0) {
  1256. Ref<PackedScene> ps = variants[base_scene_idx];
  1257. if (ps.is_valid()) {
  1258. return ps->get_state();
  1259. }
  1260. }
  1261. return Ref<SceneState>();
  1262. }
  1263. int SceneState::find_node_by_path(const NodePath &p_node) const {
  1264. ERR_FAIL_COND_V_MSG(node_path_cache.is_empty(), -1, "This operation requires the node cache to have been built.");
  1265. if (!node_path_cache.has(p_node)) {
  1266. // If not in this scene state, find node path by scene inheritance.
  1267. if (get_base_scene_state().is_valid()) {
  1268. int idx = get_base_scene_state()->find_node_by_path(p_node);
  1269. if (idx != -1) {
  1270. int rkey = _find_base_scene_node_remap_key(idx);
  1271. if (rkey == -1) {
  1272. rkey = nodes.size() + base_scene_node_remap.size();
  1273. base_scene_node_remap[rkey] = idx;
  1274. }
  1275. return rkey;
  1276. }
  1277. }
  1278. return -1;
  1279. }
  1280. int nid = node_path_cache[p_node];
  1281. if (get_base_scene_state().is_valid() && !base_scene_node_remap.has(nid)) {
  1282. //for nodes that _do_ exist in current scene, still try to look for
  1283. //the node in the instantiated scene, as a property may be missing
  1284. //from the local one
  1285. int idx = get_base_scene_state()->find_node_by_path(p_node);
  1286. if (idx != -1) {
  1287. base_scene_node_remap[nid] = idx;
  1288. }
  1289. }
  1290. return nid;
  1291. }
  1292. int SceneState::_find_base_scene_node_remap_key(int p_idx) const {
  1293. for (const KeyValue<int, int> &E : base_scene_node_remap) {
  1294. if (E.value == p_idx) {
  1295. return E.key;
  1296. }
  1297. }
  1298. return -1;
  1299. }
  1300. Variant SceneState::get_property_value(int p_node, const StringName &p_property, bool &r_found, bool &r_node_deferred) const {
  1301. r_found = false;
  1302. r_node_deferred = false;
  1303. ERR_FAIL_COND_V(p_node < 0, Variant());
  1304. if (p_node < nodes.size()) {
  1305. // Find in built-in nodes.
  1306. int pc = nodes[p_node].properties.size();
  1307. const StringName *namep = names.ptr();
  1308. const NodeData::Property *p = nodes[p_node].properties.ptr();
  1309. for (int i = 0; i < pc; i++) {
  1310. if (p_property == namep[p[i].name & FLAG_PROP_NAME_MASK]) {
  1311. r_found = true;
  1312. r_node_deferred = p[i].name & FLAG_PATH_PROPERTY_IS_NODE;
  1313. return variants[p[i].value];
  1314. }
  1315. }
  1316. #ifndef DISABLE_DEPRECATED
  1317. #ifdef TOOLS_ENABLED
  1318. // Compatibility: In 4.5 and earlier, AnimationMixer used a single "libraries" Dictionary property.
  1319. // In 4.6+, each library is stored as a separate "libraries/<name>" property.
  1320. // If we're looking for "libraries/<name>" and didn't find it, check the old format.
  1321. String prop_str = p_property.operator String();
  1322. if (prop_str.begins_with("libraries/")) {
  1323. StringName node_type = get_node_type(p_node);
  1324. if (node_type != StringName() && ClassDB::is_parent_class(node_type, SNAME("AnimationMixer"))) {
  1325. String library_name = prop_str.get_slicec('/', 1);
  1326. static const StringName libraries_sname = "libraries";
  1327. for (int i = 0; i < pc; i++) {
  1328. if (namep[p[i].name & FLAG_PROP_NAME_MASK] == libraries_sname) {
  1329. Variant libs_variant = variants[p[i].value];
  1330. if (libs_variant.get_type() == Variant::DICTIONARY) {
  1331. Dictionary libs_dict = libs_variant;
  1332. if (libs_dict.has(library_name)) {
  1333. r_found = true;
  1334. r_node_deferred = false;
  1335. return libs_dict[library_name];
  1336. }
  1337. }
  1338. break;
  1339. }
  1340. }
  1341. }
  1342. }
  1343. #endif // TOOLS_ENABLED
  1344. #endif // DISABLE_DEPRECATED
  1345. }
  1346. // Property not found, try on instance.
  1347. HashMap<int, int>::ConstIterator I = base_scene_node_remap.find(p_node);
  1348. if (I) {
  1349. return get_base_scene_state()->get_property_value(I->value, p_property, r_found, r_node_deferred);
  1350. }
  1351. return Variant();
  1352. }
  1353. bool SceneState::is_node_in_group(int p_node, const StringName &p_group) const {
  1354. ERR_FAIL_COND_V(p_node < 0, false);
  1355. if (p_node < nodes.size()) {
  1356. const StringName *namep = names.ptr();
  1357. for (int i = 0; i < nodes[p_node].groups.size(); i++) {
  1358. if (namep[nodes[p_node].groups[i]] == p_group) {
  1359. return true;
  1360. }
  1361. }
  1362. }
  1363. if (base_scene_node_remap.has(p_node)) {
  1364. return get_base_scene_state()->is_node_in_group(base_scene_node_remap[p_node], p_group);
  1365. }
  1366. return false;
  1367. }
  1368. bool SceneState::disable_placeholders = false;
  1369. void SceneState::set_disable_placeholders(bool p_disable) {
  1370. disable_placeholders = p_disable;
  1371. }
  1372. bool SceneState::is_connection(int p_node, const StringName &p_signal, int p_to_node, const StringName &p_to_method) const {
  1373. ERR_FAIL_COND_V(p_node < 0, false);
  1374. ERR_FAIL_COND_V(p_to_node < 0, false);
  1375. if (p_node < nodes.size() && p_to_node < nodes.size()) {
  1376. int signal_idx = -1;
  1377. int method_idx = -1;
  1378. for (int i = 0; i < names.size(); i++) {
  1379. if (names[i] == p_signal) {
  1380. signal_idx = i;
  1381. } else if (names[i] == p_to_method) {
  1382. method_idx = i;
  1383. }
  1384. }
  1385. if (signal_idx >= 0 && method_idx >= 0) {
  1386. //signal and method strings are stored..
  1387. for (int i = 0; i < connections.size(); i++) {
  1388. if (connections[i].from == p_node && connections[i].to == p_to_node && connections[i].signal == signal_idx && connections[i].method == method_idx) {
  1389. return true;
  1390. }
  1391. }
  1392. }
  1393. }
  1394. if (base_scene_node_remap.has(p_node) && base_scene_node_remap.has(p_to_node)) {
  1395. return get_base_scene_state()->is_connection(base_scene_node_remap[p_node], p_signal, base_scene_node_remap[p_to_node], p_to_method);
  1396. }
  1397. return false;
  1398. }
  1399. void SceneState::set_bundled_scene(const Dictionary &p_dictionary) {
  1400. ERR_FAIL_COND(!p_dictionary.has("names"));
  1401. ERR_FAIL_COND(!p_dictionary.has("variants"));
  1402. ERR_FAIL_COND(!p_dictionary.has("node_count"));
  1403. ERR_FAIL_COND(!p_dictionary.has("nodes"));
  1404. ERR_FAIL_COND(!p_dictionary.has("conn_count"));
  1405. ERR_FAIL_COND(!p_dictionary.has("conns"));
  1406. //ERR_FAIL_COND( !p_dictionary.has("path"));
  1407. int version = 1;
  1408. if (p_dictionary.has("version")) {
  1409. version = p_dictionary["version"];
  1410. }
  1411. ERR_FAIL_COND_MSG(version > PACKED_SCENE_VERSION, "Save format version too new.");
  1412. const int node_count = p_dictionary["node_count"];
  1413. const Vector<int> snodes = p_dictionary["nodes"];
  1414. ERR_FAIL_COND(snodes.size() < node_count);
  1415. const int conn_count = p_dictionary["conn_count"];
  1416. const Vector<int> sconns = p_dictionary["conns"];
  1417. ERR_FAIL_COND(sconns.size() < conn_count);
  1418. Vector<String> snames = p_dictionary["names"];
  1419. if (snames.size()) {
  1420. int namecount = snames.size();
  1421. names.resize(namecount);
  1422. const String *r = snames.ptr();
  1423. for (int i = 0; i < names.size(); i++) {
  1424. names.write[i] = r[i];
  1425. }
  1426. }
  1427. Array svariants = p_dictionary["variants"];
  1428. if (svariants.size()) {
  1429. int varcount = svariants.size();
  1430. variants.resize(varcount);
  1431. for (int i = 0; i < varcount; i++) {
  1432. variants.write[i] = svariants[i];
  1433. }
  1434. } else {
  1435. variants.clear();
  1436. }
  1437. nodes.resize(node_count);
  1438. if (node_count) {
  1439. const int *r = snodes.ptr();
  1440. int idx = 0;
  1441. for (int i = 0; i < node_count; i++) {
  1442. NodeData &nd = nodes.write[i];
  1443. nd.parent = r[idx++];
  1444. nd.owner = r[idx++];
  1445. nd.type = r[idx++];
  1446. uint32_t name_index = r[idx++];
  1447. nd.name = name_index & ((1 << NAME_INDEX_BITS) - 1);
  1448. nd.index = (name_index >> NAME_INDEX_BITS);
  1449. nd.index--; //0 is invalid, stored as 1
  1450. nd.instance = r[idx++];
  1451. nd.properties.resize(r[idx++]);
  1452. for (int j = 0; j < nd.properties.size(); j++) {
  1453. nd.properties.write[j].name = r[idx++];
  1454. nd.properties.write[j].value = r[idx++];
  1455. }
  1456. nd.groups.resize(r[idx++]);
  1457. for (int j = 0; j < nd.groups.size(); j++) {
  1458. nd.groups.write[j] = r[idx++];
  1459. }
  1460. }
  1461. }
  1462. connections.resize(conn_count);
  1463. if (conn_count) {
  1464. const int *r = sconns.ptr();
  1465. int idx = 0;
  1466. for (int i = 0; i < conn_count; i++) {
  1467. ConnectionData &cd = connections.write[i];
  1468. cd.from = r[idx++];
  1469. cd.to = r[idx++];
  1470. cd.signal = r[idx++];
  1471. cd.method = r[idx++];
  1472. cd.flags = r[idx++];
  1473. cd.binds.resize(r[idx++]);
  1474. for (int j = 0; j < cd.binds.size(); j++) {
  1475. cd.binds.write[j] = r[idx++];
  1476. }
  1477. if (version >= 3) {
  1478. cd.unbinds = r[idx++];
  1479. }
  1480. }
  1481. }
  1482. if (p_dictionary.has("node_ids")) {
  1483. ids = p_dictionary["node_ids"];
  1484. }
  1485. Array np;
  1486. if (p_dictionary.has("node_paths")) {
  1487. np = p_dictionary["node_paths"];
  1488. }
  1489. node_paths.resize(np.size());
  1490. for (int i = 0; i < np.size(); i++) {
  1491. node_paths.write[i] = np[i];
  1492. }
  1493. Array idp;
  1494. if (p_dictionary.has("id_paths") && ids.size()) {
  1495. idp = p_dictionary["id_paths"];
  1496. }
  1497. id_paths.resize(idp.size());
  1498. for (int i = 0; i < idp.size(); i++) {
  1499. id_paths.write[i] = idp[i];
  1500. }
  1501. Array ei;
  1502. if (p_dictionary.has("editable_instances")) {
  1503. ei = p_dictionary["editable_instances"];
  1504. }
  1505. if (p_dictionary.has("base_scene")) {
  1506. base_scene_idx = p_dictionary["base_scene"];
  1507. }
  1508. editable_instances.resize(ei.size());
  1509. for (int i = 0; i < editable_instances.size(); i++) {
  1510. editable_instances.write[i] = ei[i];
  1511. }
  1512. //path=p_dictionary["path"];
  1513. }
  1514. Dictionary SceneState::get_bundled_scene() const {
  1515. Vector<String> rnames;
  1516. rnames.resize(names.size());
  1517. if (names.size()) {
  1518. String *r = rnames.ptrw();
  1519. for (int i = 0; i < names.size(); i++) {
  1520. r[i] = names[i];
  1521. }
  1522. }
  1523. Dictionary d;
  1524. d["names"] = rnames;
  1525. d["variants"] = variants;
  1526. Vector<int> rnodes;
  1527. d["node_count"] = nodes.size();
  1528. for (int i = 0; i < nodes.size(); i++) {
  1529. const NodeData &nd = nodes[i];
  1530. rnodes.push_back(nd.parent);
  1531. rnodes.push_back(nd.owner);
  1532. rnodes.push_back(nd.type);
  1533. uint32_t name_index = nd.name;
  1534. if (nd.index < (1 << (32 - NAME_INDEX_BITS)) - 1) { //save if less than 16k children
  1535. name_index |= uint32_t(nd.index + 1) << NAME_INDEX_BITS; //for backwards compatibility, index 0 is no index
  1536. }
  1537. rnodes.push_back(name_index);
  1538. rnodes.push_back(nd.instance);
  1539. rnodes.push_back(nd.properties.size());
  1540. for (int j = 0; j < nd.properties.size(); j++) {
  1541. rnodes.push_back(nd.properties[j].name);
  1542. rnodes.push_back(nd.properties[j].value);
  1543. }
  1544. rnodes.push_back(nd.groups.size());
  1545. for (int j = 0; j < nd.groups.size(); j++) {
  1546. rnodes.push_back(nd.groups[j]);
  1547. }
  1548. }
  1549. d["nodes"] = rnodes;
  1550. d["node_ids"] = ids;
  1551. Vector<int> rconns;
  1552. d["conn_count"] = connections.size();
  1553. for (int i = 0; i < connections.size(); i++) {
  1554. const ConnectionData &cd = connections[i];
  1555. rconns.push_back(cd.from);
  1556. rconns.push_back(cd.to);
  1557. rconns.push_back(cd.signal);
  1558. rconns.push_back(cd.method);
  1559. rconns.push_back(cd.flags);
  1560. rconns.push_back(cd.binds.size());
  1561. for (int j = 0; j < cd.binds.size(); j++) {
  1562. rconns.push_back(cd.binds[j]);
  1563. }
  1564. rconns.push_back(cd.unbinds);
  1565. }
  1566. d["conns"] = rconns;
  1567. Array rnode_paths;
  1568. rnode_paths.resize(node_paths.size());
  1569. for (int i = 0; i < node_paths.size(); i++) {
  1570. rnode_paths[i] = node_paths[i];
  1571. }
  1572. d["node_paths"] = rnode_paths;
  1573. Array rid_paths;
  1574. rid_paths.resize(id_paths.size());
  1575. for (int i = 0; i < id_paths.size(); i++) {
  1576. rid_paths[i] = id_paths[i];
  1577. }
  1578. d["id_paths"] = rid_paths;
  1579. Array reditable_instances;
  1580. reditable_instances.resize(editable_instances.size());
  1581. for (int i = 0; i < editable_instances.size(); i++) {
  1582. reditable_instances[i] = editable_instances[i];
  1583. }
  1584. d["editable_instances"] = reditable_instances;
  1585. if (base_scene_idx >= 0) {
  1586. d["base_scene"] = base_scene_idx;
  1587. }
  1588. d["version"] = PACKED_SCENE_VERSION;
  1589. return d;
  1590. }
  1591. int SceneState::get_node_count() const {
  1592. return nodes.size();
  1593. }
  1594. StringName SceneState::get_node_type(int p_idx) const {
  1595. ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
  1596. if (nodes[p_idx].type == TYPE_INSTANTIATED) {
  1597. return StringName();
  1598. }
  1599. return names[nodes[p_idx].type];
  1600. }
  1601. StringName SceneState::get_node_name(int p_idx) const {
  1602. ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
  1603. return names[nodes[p_idx].name];
  1604. }
  1605. int SceneState::get_node_index(int p_idx) const {
  1606. ERR_FAIL_INDEX_V(p_idx, nodes.size(), -1);
  1607. return nodes[p_idx].index;
  1608. }
  1609. bool SceneState::is_node_instance_placeholder(int p_idx) const {
  1610. ERR_FAIL_INDEX_V(p_idx, nodes.size(), false);
  1611. return nodes[p_idx].instance >= 0 && (nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER);
  1612. }
  1613. Ref<PackedScene> SceneState::get_node_instance(int p_idx) const {
  1614. ERR_FAIL_INDEX_V(p_idx, nodes.size(), Ref<PackedScene>());
  1615. if (nodes[p_idx].instance >= 0) {
  1616. if (nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER) {
  1617. return Ref<PackedScene>();
  1618. } else {
  1619. return variants[nodes[p_idx].instance & FLAG_MASK];
  1620. }
  1621. } else if (nodes[p_idx].parent < 0 || nodes[p_idx].parent == NO_PARENT_SAVED) {
  1622. if (base_scene_idx >= 0) {
  1623. return variants[base_scene_idx];
  1624. }
  1625. }
  1626. return Ref<PackedScene>();
  1627. }
  1628. String SceneState::get_node_instance_placeholder(int p_idx) const {
  1629. ERR_FAIL_INDEX_V(p_idx, nodes.size(), String());
  1630. if (nodes[p_idx].instance >= 0 && (nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER)) {
  1631. return variants[nodes[p_idx].instance & FLAG_MASK];
  1632. }
  1633. return String();
  1634. }
  1635. Vector<StringName> SceneState::get_node_groups(int p_idx) const {
  1636. ERR_FAIL_INDEX_V(p_idx, nodes.size(), Vector<StringName>());
  1637. Vector<StringName> groups;
  1638. for (int i = 0; i < nodes[p_idx].groups.size(); i++) {
  1639. groups.push_back(names[nodes[p_idx].groups[i]]);
  1640. }
  1641. return groups;
  1642. }
  1643. Node *SceneState::_recover_node_path_index(Node *p_base, int p_idx) const {
  1644. // ID paths are only used for recovery, since they are slower to traverse.
  1645. // This function attempts to recover a node by using IDs in case the path
  1646. // has disappeared.
  1647. if (p_idx >= id_paths.size()) {
  1648. return nullptr;
  1649. }
  1650. const PackedInt32Array &id_path = id_paths[p_idx & FLAG_MASK];
  1651. Vector<StringName> full_path;
  1652. const SceneState *ss = this;
  1653. for (int i = 0; i < id_path.size(); i++) {
  1654. int idx = ss->ids.find(id_path[i]);
  1655. if (idx == -1) {
  1656. // Not found, but may belong to a base scene, so search.
  1657. while (ss && idx == -1 && ss->base_scene_idx >= 0) {
  1658. Ref<PackedScene> sdata = ss->variants[ss->base_scene_idx];
  1659. if (sdata.is_null()) {
  1660. return nullptr;
  1661. }
  1662. Ref<SceneState> ssd = sdata->get_state();
  1663. if (!ssd.is_valid()) {
  1664. return nullptr;
  1665. }
  1666. ss = ssd.ptr();
  1667. idx = ss->ids.find(id_path[i]);
  1668. if (idx != -1) {
  1669. break;
  1670. }
  1671. }
  1672. if (idx == -1) {
  1673. //No luck.
  1674. return nullptr;
  1675. }
  1676. }
  1677. ERR_FAIL_COND_V(idx >= ss->nodes.size(), nullptr); // Should be a node.
  1678. NodePath so_far = ss->get_node_path(idx);
  1679. for (int j = 0; j < so_far.get_name_count(); j++) {
  1680. full_path.push_back(so_far.get_name(j));
  1681. }
  1682. if (i == id_path.size() - 1) {
  1683. break; // Do not go further, we have the path.
  1684. }
  1685. const NodeData &nd = ss->nodes[idx];
  1686. // Get instance
  1687. ERR_FAIL_COND_V(nd.instance < 0, nullptr); // Not an instance, middle of path should be an instance.
  1688. ERR_FAIL_COND_V(nd.instance & FLAG_INSTANCE_IS_PLACEHOLDER, nullptr); // Instance is somehow a placeholder?!
  1689. Ref<PackedScene> sdata = ss->variants[nd.instance & FLAG_MASK];
  1690. ERR_FAIL_COND_V(sdata.is_null(), nullptr);
  1691. Ref<SceneState> sstate = sdata->get_state();
  1692. ss = sstate.ptr();
  1693. }
  1694. NodePath recovered_path(full_path, false);
  1695. return p_base->get_node_or_null(recovered_path);
  1696. }
  1697. int32_t SceneState::get_node_unique_id(int p_idx) const {
  1698. if (p_idx >= ids.size()) {
  1699. return Node::UNIQUE_SCENE_ID_UNASSIGNED;
  1700. }
  1701. return ids[p_idx];
  1702. }
  1703. NodePath SceneState::get_node_path(int p_idx, bool p_for_parent) const {
  1704. ERR_FAIL_INDEX_V(p_idx, nodes.size(), NodePath());
  1705. if (nodes[p_idx].parent < 0 || nodes[p_idx].parent == NO_PARENT_SAVED) {
  1706. if (p_for_parent) {
  1707. return NodePath();
  1708. } else {
  1709. return NodePath(".");
  1710. }
  1711. }
  1712. Vector<StringName> sub_path;
  1713. NodePath base_path;
  1714. int nidx = p_idx;
  1715. while (true) {
  1716. if (nodes[nidx].parent == NO_PARENT_SAVED || nodes[nidx].parent < 0) {
  1717. sub_path.insert(0, ".");
  1718. break;
  1719. }
  1720. if (!p_for_parent || p_idx != nidx) {
  1721. sub_path.insert(0, names[nodes[nidx].name]);
  1722. }
  1723. if (nodes[nidx].parent & FLAG_ID_IS_PATH) {
  1724. base_path = node_paths[nodes[nidx].parent & FLAG_MASK];
  1725. break;
  1726. } else {
  1727. nidx = nodes[nidx].parent & FLAG_MASK;
  1728. }
  1729. }
  1730. for (int i = base_path.get_name_count() - 1; i >= 0; i--) {
  1731. sub_path.insert(0, base_path.get_name(i));
  1732. }
  1733. if (sub_path.is_empty()) {
  1734. return NodePath(".");
  1735. }
  1736. return NodePath(sub_path, false);
  1737. }
  1738. PackedInt32Array SceneState::get_node_id_path(int p_idx) const {
  1739. PackedInt32Array pp = get_node_parent_id_path(p_idx);
  1740. if (pp.is_empty()) {
  1741. return pp;
  1742. }
  1743. if (p_idx < ids.size()) {
  1744. pp.push_back(ids[p_idx]);
  1745. return pp;
  1746. }
  1747. return PackedInt32Array();
  1748. }
  1749. PackedInt32Array SceneState::get_node_parent_id_path(int p_idx) const {
  1750. if (nodes[p_idx].parent < 0 || nodes[p_idx].parent == NO_PARENT_SAVED) {
  1751. return PackedInt32Array();
  1752. }
  1753. if (nodes[p_idx].parent & FLAG_ID_IS_PATH) {
  1754. int id = nodes[p_idx].parent & FLAG_MASK;
  1755. if (id >= id_paths.size()) {
  1756. return PackedInt32Array();
  1757. }
  1758. return id_paths[id];
  1759. }
  1760. return PackedInt32Array();
  1761. }
  1762. PackedInt32Array SceneState::get_node_owner_id_path(int p_idx) const {
  1763. if (nodes[p_idx].owner < 0) {
  1764. return PackedInt32Array();
  1765. }
  1766. if (nodes[p_idx].owner & FLAG_ID_IS_PATH) {
  1767. int id = nodes[p_idx].owner & FLAG_MASK;
  1768. if (id >= id_paths.size()) {
  1769. return PackedInt32Array();
  1770. }
  1771. return id_paths[id];
  1772. }
  1773. return PackedInt32Array();
  1774. }
  1775. int SceneState::get_node_property_count(int p_idx) const {
  1776. ERR_FAIL_INDEX_V(p_idx, nodes.size(), -1);
  1777. return nodes[p_idx].properties.size();
  1778. }
  1779. StringName SceneState::get_node_property_name(int p_idx, int p_prop) const {
  1780. ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
  1781. ERR_FAIL_INDEX_V(p_prop, nodes[p_idx].properties.size(), StringName());
  1782. return names[nodes[p_idx].properties[p_prop].name & FLAG_PROP_NAME_MASK];
  1783. }
  1784. Vector<String> SceneState::get_node_deferred_nodepath_properties(int p_idx) const {
  1785. Vector<String> ret;
  1786. ERR_FAIL_COND_V(p_idx < 0, ret);
  1787. if (p_idx < nodes.size()) {
  1788. // Find in built-in nodes.
  1789. for (int i = 0; i < nodes[p_idx].properties.size(); i++) {
  1790. uint32_t idx = nodes[p_idx].properties[i].name;
  1791. if (idx & FLAG_PATH_PROPERTY_IS_NODE) {
  1792. ret.push_back(names[idx & FLAG_PROP_NAME_MASK]);
  1793. }
  1794. }
  1795. return ret;
  1796. }
  1797. // Property not found, try on instance.
  1798. HashMap<int, int>::ConstIterator I = base_scene_node_remap.find(p_idx);
  1799. if (I) {
  1800. return get_base_scene_state()->get_node_deferred_nodepath_properties(I->value);
  1801. }
  1802. return ret;
  1803. }
  1804. Variant SceneState::get_node_property_value(int p_idx, int p_prop) const {
  1805. ERR_FAIL_INDEX_V(p_idx, nodes.size(), Variant());
  1806. ERR_FAIL_INDEX_V(p_prop, nodes[p_idx].properties.size(), Variant());
  1807. return variants[nodes[p_idx].properties[p_prop].value];
  1808. }
  1809. NodePath SceneState::get_node_owner_path(int p_idx) const {
  1810. ERR_FAIL_INDEX_V(p_idx, nodes.size(), NodePath());
  1811. if (nodes[p_idx].owner < 0 || nodes[p_idx].owner == NO_PARENT_SAVED) {
  1812. return NodePath(); //root likely
  1813. }
  1814. if (nodes[p_idx].owner & FLAG_ID_IS_PATH) {
  1815. return node_paths[nodes[p_idx].owner & FLAG_MASK];
  1816. } else {
  1817. return get_node_path(nodes[p_idx].owner & FLAG_MASK);
  1818. }
  1819. }
  1820. int SceneState::get_connection_count() const {
  1821. return connections.size();
  1822. }
  1823. NodePath SceneState::get_connection_source(int p_idx) const {
  1824. ERR_FAIL_INDEX_V(p_idx, connections.size(), NodePath());
  1825. if (connections[p_idx].from & FLAG_ID_IS_PATH) {
  1826. return node_paths[connections[p_idx].from & FLAG_MASK];
  1827. } else {
  1828. return get_node_path(connections[p_idx].from & FLAG_MASK);
  1829. }
  1830. }
  1831. StringName SceneState::get_connection_signal(int p_idx) const {
  1832. ERR_FAIL_INDEX_V(p_idx, connections.size(), StringName());
  1833. return names[connections[p_idx].signal];
  1834. }
  1835. NodePath SceneState::get_connection_target(int p_idx) const {
  1836. ERR_FAIL_INDEX_V(p_idx, connections.size(), NodePath());
  1837. if (connections[p_idx].to & FLAG_ID_IS_PATH) {
  1838. return node_paths[connections[p_idx].to & FLAG_MASK];
  1839. } else {
  1840. return get_node_path(connections[p_idx].to & FLAG_MASK);
  1841. }
  1842. }
  1843. PackedInt32Array SceneState::get_connection_target_id_path(int p_idx) const {
  1844. ERR_FAIL_INDEX_V(p_idx, connections.size(), PackedInt32Array());
  1845. if (connections[p_idx].to & FLAG_ID_IS_PATH && connections[p_idx].to < id_paths.size()) {
  1846. return id_paths[connections[p_idx].to];
  1847. } else {
  1848. return PackedInt32Array();
  1849. }
  1850. }
  1851. PackedInt32Array SceneState::get_connection_source_id_path(int p_idx) const {
  1852. ERR_FAIL_INDEX_V(p_idx, connections.size(), PackedInt32Array());
  1853. if (connections[p_idx].from & FLAG_ID_IS_PATH && connections[p_idx].from < id_paths.size()) {
  1854. return id_paths[connections[p_idx].from];
  1855. } else {
  1856. return PackedInt32Array();
  1857. }
  1858. }
  1859. StringName SceneState::get_connection_method(int p_idx) const {
  1860. ERR_FAIL_INDEX_V(p_idx, connections.size(), StringName());
  1861. return names[connections[p_idx].method];
  1862. }
  1863. int SceneState::get_connection_flags(int p_idx) const {
  1864. ERR_FAIL_INDEX_V(p_idx, connections.size(), -1);
  1865. return connections[p_idx].flags;
  1866. }
  1867. int SceneState::get_connection_unbinds(int p_idx) const {
  1868. ERR_FAIL_INDEX_V(p_idx, connections.size(), -1);
  1869. return connections[p_idx].unbinds;
  1870. }
  1871. Array SceneState::get_connection_binds(int p_idx) const {
  1872. ERR_FAIL_INDEX_V(p_idx, connections.size(), Array());
  1873. Array binds;
  1874. for (int i = 0; i < connections[p_idx].binds.size(); i++) {
  1875. binds.push_back(variants[connections[p_idx].binds[i]]);
  1876. }
  1877. return binds;
  1878. }
  1879. bool SceneState::has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method, bool p_no_inheritance) {
  1880. // this method cannot be const because of this
  1881. Ref<SceneState> ss = this;
  1882. do {
  1883. for (int i = 0; i < ss->connections.size(); i++) {
  1884. const ConnectionData &c = ss->connections[i];
  1885. NodePath np_from;
  1886. if (c.from & FLAG_ID_IS_PATH) {
  1887. np_from = ss->node_paths[c.from & FLAG_MASK];
  1888. } else {
  1889. np_from = ss->get_node_path(c.from);
  1890. }
  1891. NodePath np_to;
  1892. if (c.to & FLAG_ID_IS_PATH) {
  1893. np_to = ss->node_paths[c.to & FLAG_MASK];
  1894. } else {
  1895. np_to = ss->get_node_path(c.to);
  1896. }
  1897. StringName sn_signal = ss->names[c.signal];
  1898. StringName sn_method = ss->names[c.method];
  1899. if (np_from == p_node_from && sn_signal == p_signal && np_to == p_node_to && sn_method == p_method) {
  1900. return true;
  1901. }
  1902. }
  1903. if (p_no_inheritance) {
  1904. break;
  1905. }
  1906. ss = ss->get_base_scene_state();
  1907. } while (ss.is_valid());
  1908. return false;
  1909. }
  1910. Vector<NodePath> SceneState::get_editable_instances() const {
  1911. return editable_instances;
  1912. }
  1913. Ref<Resource> SceneState::get_sub_resource(const String &p_path) {
  1914. for (const Variant &v : variants) {
  1915. const Ref<Resource> &res = v;
  1916. if (res.is_valid() && res->get_path() == p_path) {
  1917. return res;
  1918. }
  1919. }
  1920. return Ref<Resource>();
  1921. }
  1922. Vector<Ref<Resource>> SceneState::get_sub_resources() {
  1923. const String path_prefix = get_path() + "::";
  1924. Vector<Ref<Resource>> sub_resources;
  1925. for (const Variant &v : variants) {
  1926. const Ref<Resource> &res = v;
  1927. if (res.is_valid() && res->get_path().begins_with(path_prefix)) {
  1928. sub_resources.push_back(res);
  1929. }
  1930. }
  1931. return sub_resources;
  1932. }
  1933. //add
  1934. int SceneState::add_name(const StringName &p_name) {
  1935. names.push_back(p_name);
  1936. return names.size() - 1;
  1937. }
  1938. int SceneState::add_value(const Variant &p_value) {
  1939. variants.push_back(p_value);
  1940. return variants.size() - 1;
  1941. }
  1942. int SceneState::add_node_path(const NodePath &p_path, const PackedInt32Array &p_uid_path) {
  1943. node_paths.push_back(p_path);
  1944. id_paths.push_back(p_uid_path);
  1945. return (node_paths.size() - 1) | FLAG_ID_IS_PATH;
  1946. }
  1947. int SceneState::add_node(int p_parent, int p_owner, int p_type, int p_name, int p_instance, int p_index, int32_t p_unique_id) {
  1948. NodeData nd;
  1949. nd.parent = p_parent;
  1950. nd.owner = p_owner;
  1951. nd.type = p_type;
  1952. nd.name = p_name;
  1953. nd.instance = p_instance;
  1954. nd.index = p_index;
  1955. nodes.push_back(nd);
  1956. ids.push_back(p_unique_id);
  1957. return nodes.size() - 1;
  1958. }
  1959. void SceneState::add_node_property(int p_node, int p_name, int p_value, bool p_deferred_node_path) {
  1960. ERR_FAIL_INDEX(p_node, nodes.size());
  1961. ERR_FAIL_INDEX(p_name, names.size());
  1962. ERR_FAIL_INDEX(p_value, variants.size());
  1963. NodeData::Property prop;
  1964. prop.name = p_name;
  1965. if (p_deferred_node_path) {
  1966. prop.name |= FLAG_PATH_PROPERTY_IS_NODE;
  1967. }
  1968. prop.value = p_value;
  1969. nodes.write[p_node].properties.push_back(prop);
  1970. }
  1971. void SceneState::add_node_group(int p_node, int p_group) {
  1972. ERR_FAIL_INDEX(p_node, nodes.size());
  1973. ERR_FAIL_INDEX(p_group, names.size());
  1974. nodes.write[p_node].groups.push_back(p_group);
  1975. }
  1976. void SceneState::set_base_scene(int p_idx) {
  1977. ERR_FAIL_INDEX(p_idx, variants.size());
  1978. base_scene_idx = p_idx;
  1979. }
  1980. void SceneState::add_connection(int p_from, int p_to, int p_signal, int p_method, int p_flags, int p_unbinds, const Vector<int> &p_binds) {
  1981. ERR_FAIL_INDEX(p_signal, names.size());
  1982. ERR_FAIL_INDEX(p_method, names.size());
  1983. for (int i = 0; i < p_binds.size(); i++) {
  1984. ERR_FAIL_INDEX(p_binds[i], variants.size());
  1985. }
  1986. ConnectionData c;
  1987. c.from = p_from;
  1988. c.to = p_to;
  1989. c.signal = p_signal;
  1990. c.method = p_method;
  1991. c.flags = p_flags;
  1992. c.unbinds = p_unbinds;
  1993. c.binds = p_binds;
  1994. connections.push_back(c);
  1995. }
  1996. void SceneState::add_editable_instance(const NodePath &p_path) {
  1997. editable_instances.push_back(p_path);
  1998. }
  1999. bool SceneState::remove_group_references(const StringName &p_name) {
  2000. bool edited = false;
  2001. for (NodeData &node : nodes) {
  2002. for (const int &group : node.groups) {
  2003. if (names[group] == p_name) {
  2004. node.groups.erase(group);
  2005. edited = true;
  2006. break;
  2007. }
  2008. }
  2009. }
  2010. return edited;
  2011. }
  2012. bool SceneState::rename_group_references(const StringName &p_old_name, const StringName &p_new_name) {
  2013. bool edited = false;
  2014. for (const NodeData &node : nodes) {
  2015. for (const int &group : node.groups) {
  2016. if (names[group] == p_old_name) {
  2017. names.write[group] = p_new_name;
  2018. edited = true;
  2019. break;
  2020. }
  2021. }
  2022. }
  2023. return edited;
  2024. }
  2025. HashSet<StringName> SceneState::get_all_groups() {
  2026. HashSet<StringName> ret;
  2027. for (const NodeData &node : nodes) {
  2028. for (const int &group : node.groups) {
  2029. ret.insert(names[group]);
  2030. }
  2031. }
  2032. return ret;
  2033. }
  2034. Vector<String> SceneState::_get_node_groups(int p_idx) const {
  2035. Vector<StringName> groups = get_node_groups(p_idx);
  2036. Vector<String> ret;
  2037. for (int i = 0; i < groups.size(); i++) {
  2038. ret.push_back(groups[i]);
  2039. }
  2040. return ret;
  2041. }
  2042. void SceneState::_bind_methods() {
  2043. //unbuild API
  2044. ClassDB::bind_method(D_METHOD("get_path"), &SceneState::get_path);
  2045. ClassDB::bind_method(D_METHOD("get_base_scene_state"), &SceneState::get_base_scene_state);
  2046. ClassDB::bind_method(D_METHOD("get_node_count"), &SceneState::get_node_count);
  2047. ClassDB::bind_method(D_METHOD("get_node_type", "idx"), &SceneState::get_node_type);
  2048. ClassDB::bind_method(D_METHOD("get_node_name", "idx"), &SceneState::get_node_name);
  2049. ClassDB::bind_method(D_METHOD("get_node_path", "idx", "for_parent"), &SceneState::get_node_path, DEFVAL(false));
  2050. ClassDB::bind_method(D_METHOD("get_node_owner_path", "idx"), &SceneState::get_node_owner_path);
  2051. ClassDB::bind_method(D_METHOD("is_node_instance_placeholder", "idx"), &SceneState::is_node_instance_placeholder);
  2052. ClassDB::bind_method(D_METHOD("get_node_instance_placeholder", "idx"), &SceneState::get_node_instance_placeholder);
  2053. ClassDB::bind_method(D_METHOD("get_node_instance", "idx"), &SceneState::get_node_instance);
  2054. ClassDB::bind_method(D_METHOD("get_node_groups", "idx"), &SceneState::_get_node_groups);
  2055. ClassDB::bind_method(D_METHOD("get_node_index", "idx"), &SceneState::get_node_index);
  2056. ClassDB::bind_method(D_METHOD("get_node_property_count", "idx"), &SceneState::get_node_property_count);
  2057. ClassDB::bind_method(D_METHOD("get_node_property_name", "idx", "prop_idx"), &SceneState::get_node_property_name);
  2058. ClassDB::bind_method(D_METHOD("get_node_property_value", "idx", "prop_idx"), &SceneState::get_node_property_value);
  2059. ClassDB::bind_method(D_METHOD("get_connection_count"), &SceneState::get_connection_count);
  2060. ClassDB::bind_method(D_METHOD("get_connection_source", "idx"), &SceneState::get_connection_source);
  2061. ClassDB::bind_method(D_METHOD("get_connection_signal", "idx"), &SceneState::get_connection_signal);
  2062. ClassDB::bind_method(D_METHOD("get_connection_target", "idx"), &SceneState::get_connection_target);
  2063. ClassDB::bind_method(D_METHOD("get_connection_method", "idx"), &SceneState::get_connection_method);
  2064. ClassDB::bind_method(D_METHOD("get_connection_flags", "idx"), &SceneState::get_connection_flags);
  2065. ClassDB::bind_method(D_METHOD("get_connection_binds", "idx"), &SceneState::get_connection_binds);
  2066. ClassDB::bind_method(D_METHOD("get_connection_unbinds", "idx"), &SceneState::get_connection_unbinds);
  2067. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_DISABLED);
  2068. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_INSTANCE);
  2069. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_MAIN);
  2070. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_MAIN_INHERITED);
  2071. }
  2072. SceneState::SceneState() {
  2073. }
  2074. ////////////////
  2075. void PackedScene::_set_bundled_scene(const Dictionary &p_scene) {
  2076. state->set_bundled_scene(p_scene);
  2077. }
  2078. Dictionary PackedScene::_get_bundled_scene() const {
  2079. return state->get_bundled_scene();
  2080. }
  2081. Error PackedScene::pack(Node *p_scene) {
  2082. return state->pack(p_scene);
  2083. }
  2084. void PackedScene::clear() {
  2085. state->clear();
  2086. }
  2087. void PackedScene::reload_from_file() {
  2088. String path = get_path();
  2089. if (!path.is_resource_file()) {
  2090. return;
  2091. }
  2092. Ref<PackedScene> s = ResourceLoader::load(ResourceLoader::path_remap(path), get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE);
  2093. if (s.is_null()) {
  2094. return;
  2095. }
  2096. // Backup the loaded_state
  2097. Ref<SceneState> loaded_state = s->get_state();
  2098. // This assigns a new state to s->state
  2099. // We do this because of the next step
  2100. s->recreate_state();
  2101. // This has a side-effect to clear s->state
  2102. copy_from(s);
  2103. // Then, we copy the backed-up loaded_state to state
  2104. state->copy_from(loaded_state);
  2105. }
  2106. bool PackedScene::can_instantiate() const {
  2107. return state->can_instantiate();
  2108. }
  2109. Node *PackedScene::instantiate(GenEditState p_edit_state) const {
  2110. #ifndef TOOLS_ENABLED
  2111. ERR_FAIL_COND_V_MSG(p_edit_state != GEN_EDIT_STATE_DISABLED, nullptr, "Edit state is only for editors, does not work without tools compiled.");
  2112. #endif
  2113. Node *s = state->instantiate((SceneState::GenEditState)p_edit_state);
  2114. if (!s) {
  2115. return nullptr;
  2116. }
  2117. if (p_edit_state != GEN_EDIT_STATE_DISABLED) {
  2118. s->set_scene_instance_state(state);
  2119. }
  2120. if (!is_built_in()) {
  2121. s->set_scene_file_path(get_path());
  2122. }
  2123. s->notification(Node::NOTIFICATION_SCENE_INSTANTIATED);
  2124. return s;
  2125. }
  2126. void PackedScene::replace_state(Ref<SceneState> p_by) {
  2127. state = p_by;
  2128. state->set_path(get_path());
  2129. #ifdef TOOLS_ENABLED
  2130. state->set_last_modified_time(get_last_modified_time());
  2131. #endif
  2132. }
  2133. void PackedScene::recreate_state() {
  2134. state.instantiate();
  2135. state->set_path(get_path());
  2136. #ifdef TOOLS_ENABLED
  2137. state->set_last_modified_time(get_last_modified_time());
  2138. #endif
  2139. }
  2140. #ifdef TOOLS_ENABLED
  2141. HashSet<StringName> PackedScene::get_scene_groups(const String &p_path) {
  2142. {
  2143. Ref<PackedScene> packed_scene = ResourceCache::get_ref(p_path);
  2144. if (packed_scene.is_valid()) {
  2145. return packed_scene->get_state()->get_all_groups();
  2146. }
  2147. }
  2148. if (p_path.get_extension() == "tscn") {
  2149. Ref<FileAccess> scene_file = FileAccess::open(p_path, FileAccess::READ);
  2150. ERR_FAIL_COND_V(scene_file.is_null(), HashSet<StringName>());
  2151. HashSet<StringName> ret;
  2152. while (!scene_file->eof_reached()) {
  2153. const String line = scene_file->get_line();
  2154. if (!line.begins_with("[node")) {
  2155. continue;
  2156. }
  2157. int i = line.find("groups=[");
  2158. if (i == -1) {
  2159. continue;
  2160. }
  2161. int j = line.find_char(']', i);
  2162. while (i < j) {
  2163. i = line.find_char('"', i);
  2164. if (i == -1) {
  2165. break;
  2166. }
  2167. int k = line.find_char('"', i + 1);
  2168. if (k == -1) {
  2169. break;
  2170. }
  2171. ret.insert(line.substr(i + 1, k - i - 1));
  2172. i = k + 1;
  2173. }
  2174. }
  2175. return ret;
  2176. } else {
  2177. Ref<PackedScene> packed_scene = ResourceLoader::load(p_path);
  2178. ERR_FAIL_COND_V(packed_scene.is_null(), HashSet<StringName>());
  2179. return packed_scene->get_state()->get_all_groups();
  2180. }
  2181. }
  2182. #endif
  2183. Ref<SceneState> PackedScene::get_state() const {
  2184. return state;
  2185. }
  2186. void PackedScene::set_path(const String &p_path, bool p_take_over) {
  2187. state->set_path(p_path);
  2188. Resource::set_path(p_path, p_take_over);
  2189. }
  2190. void PackedScene::set_path_cache(const String &p_path) {
  2191. state->set_path(p_path);
  2192. Resource::set_path_cache(p_path);
  2193. }
  2194. void PackedScene::reset_state() {
  2195. clear();
  2196. }
  2197. void PackedScene::_bind_methods() {
  2198. ClassDB::bind_method(D_METHOD("pack", "path"), &PackedScene::pack);
  2199. ClassDB::bind_method(D_METHOD("instantiate", "edit_state"), &PackedScene::instantiate, DEFVAL(GEN_EDIT_STATE_DISABLED));
  2200. ClassDB::bind_method(D_METHOD("can_instantiate"), &PackedScene::can_instantiate);
  2201. ClassDB::bind_method(D_METHOD("_set_bundled_scene", "scene"), &PackedScene::_set_bundled_scene);
  2202. ClassDB::bind_method(D_METHOD("_get_bundled_scene"), &PackedScene::_get_bundled_scene);
  2203. ClassDB::bind_method(D_METHOD("get_state"), &PackedScene::get_state);
  2204. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_bundled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL), "_set_bundled_scene", "_get_bundled_scene");
  2205. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_DISABLED);
  2206. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_INSTANCE);
  2207. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_MAIN);
  2208. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_MAIN_INHERITED);
  2209. }
  2210. PackedScene::PackedScene() {
  2211. state.instantiate();
  2212. }