Debian Codegraph @

scene/resources/packed_scene.cpp

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