-
-
Notifications
You must be signed in to change notification settings - Fork 21.5k
/
Copy pathpacked_scene.cpp
2299 lines (1927 loc) · 73.2 KB
/
packed_scene.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************/
/* packed_scene.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "packed_scene.h"
#include "core/config/engine.h"
#include "core/config/project_settings.h"
#include "core/io/missing_resource.h"
#include "core/io/resource_loader.h"
#include "core/templates/local_vector.h"
#include "scene/2d/node_2d.h"
#ifndef _3D_DISABLED
#include "scene/3d/node_3d.h"
#endif // _3D_DISABLED
#include "scene/gui/control.h"
#include "scene/main/instance_placeholder.h"
#include "scene/main/missing_node.h"
#include "scene/property_utils.h"
#define PACKED_SCENE_VERSION 3
#ifdef TOOLS_ENABLED
SceneState::InstantiationWarningNotify SceneState::instantiation_warn_notify = nullptr;
#endif
bool SceneState::can_instantiate() const {
return nodes.size() > 0;
}
static Array _sanitize_node_pinned_properties(Node *p_node) {
Array pinned = p_node->get_meta("_edit_pinned_properties_", Array());
if (pinned.is_empty()) {
return Array();
}
HashSet<StringName> storable_properties;
p_node->get_storable_properties(storable_properties);
int i = 0;
do {
if (storable_properties.has(pinned[i])) {
i++;
} else {
pinned.remove_at(i);
}
} while (i < pinned.size());
if (pinned.is_empty()) {
p_node->remove_meta("_edit_pinned_properties_");
}
return pinned;
}
Ref<Resource> SceneState::get_remap_resource(const Ref<Resource> &p_resource, HashMap<Ref<Resource>, Ref<Resource>> &remap_cache, const Ref<Resource> &p_fallback, Node *p_for_scene) {
ERR_FAIL_COND_V(p_resource.is_null(), Ref<Resource>());
Ref<Resource> remap_resource;
// Find the shared copy of the source resource.
HashMap<Ref<Resource>, Ref<Resource>>::Iterator R = remap_cache.find(p_resource);
if (R) {
remap_resource = R->value;
} else if (p_fallback.is_valid() && p_fallback->is_local_to_scene() && p_fallback->get_class() == p_resource->get_class()) {
// Simply copy the data from the source resource to update the fallback resource that was previously set.
p_fallback->reset_state(); // May want to reset state.
List<PropertyInfo> pi;
p_resource->get_property_list(&pi);
for (const PropertyInfo &E : pi) {
if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
continue;
}
if (E.name == "resource_path") {
continue; // Do not change path.
}
Variant value = p_resource->get(E.name);
// The local-to-scene subresource instance is preserved, thus maintaining the previous sharing relationship.
// This is mainly used when the sub-scene root is reset in the main scene.
Ref<Resource> sub_res_of_from = value;
if (sub_res_of_from.is_valid() && sub_res_of_from->is_local_to_scene()) {
value = get_remap_resource(sub_res_of_from, remap_cache, p_fallback->get(E.name), p_fallback->get_local_scene());
}
p_fallback->set(E.name, value);
}
p_fallback->set_scene_unique_id(p_resource->get_scene_unique_id()); // Get the id from the main scene, in case the id changes again when saving the scene.
remap_cache[p_resource] = p_fallback;
remap_resource = p_fallback;
} else { // A copy of the source resource is required to overwrite the previous one.
Ref<Resource> local_dupe = p_resource->duplicate_for_local_scene(p_for_scene, remap_cache);
remap_cache[p_resource] = local_dupe;
remap_resource = local_dupe;
}
return remap_resource;
}
Node *SceneState::instantiate(GenEditState p_edit_state) const {
// Nodes where instantiation failed (because something is missing.)
List<Node *> stray_instances;
#define NODE_FROM_ID(p_name, p_id) \
Node *p_name; \
if (p_id & FLAG_ID_IS_PATH) { \
NodePath np = node_paths[p_id & FLAG_MASK]; \
p_name = ret_nodes[0]->get_node_or_null(np); \
} else { \
ERR_FAIL_INDEX_V(p_id &FLAG_MASK, nc, nullptr); \
p_name = ret_nodes[p_id & FLAG_MASK]; \
}
int nc = nodes.size();
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));
const StringName *snames = nullptr;
int sname_count = names.size();
if (sname_count) {
snames = &names[0];
}
const Variant *props = nullptr;
int prop_count = variants.size();
if (prop_count) {
props = &variants[0];
}
//Vector<Variant> properties;
const NodeData *nd = &nodes[0];
Node **ret_nodes = (Node **)alloca(sizeof(Node *) * nc);
bool gen_node_path_cache = p_edit_state != GEN_EDIT_STATE_DISABLED && node_path_cache.is_empty();
HashMap<Ref<Resource>, Ref<Resource>> resources_local_to_scene;
LocalVector<DeferredNodePathProperties> deferred_node_paths;
for (int i = 0; i < nc; i++) {
const NodeData &n = nd[i];
Node *parent = nullptr;
String old_parent_path;
if (i > 0) {
ERR_FAIL_COND_V_MSG(n.parent == -1, nullptr, vformat("Invalid scene: node %s does not specify its parent node.", snames[n.name]));
NODE_FROM_ID(nparent, n.parent);
#ifdef DEBUG_ENABLED
if (!nparent && (n.parent & FLAG_ID_IS_PATH)) {
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());
old_parent_path = String(node_paths[n.parent & FLAG_MASK]).trim_prefix("./").replace("/", "@");
nparent = ret_nodes[0];
}
#endif
parent = nparent;
} else {
// i == 0 is root node.
ERR_FAIL_COND_V_MSG(n.parent != -1, nullptr, vformat("Invalid scene: root node %s cannot specify a parent node.", snames[n.name]));
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]));
}
Node *node = nullptr;
MissingNode *missing_node = nullptr;
bool is_inherited_scene = false;
if (i == 0 && base_scene_idx >= 0) {
// Scene inheritance on root node.
Ref<PackedScene> sdata = props[base_scene_idx];
ERR_FAIL_COND_V(!sdata.is_valid(), nullptr);
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
ERR_FAIL_NULL_V(node, nullptr);
if (p_edit_state != GEN_EDIT_STATE_DISABLED) {
node->set_scene_inherited_state(sdata->get_state());
}
is_inherited_scene = true;
} else if (n.instance >= 0) {
// Instance a scene into this node.
if (n.instance & FLAG_INSTANCE_IS_PLACEHOLDER) {
const String scene_path = props[n.instance & FLAG_MASK];
if (disable_placeholders) {
Ref<PackedScene> sdata = ResourceLoader::load(scene_path, "PackedScene");
if (sdata.is_valid()) {
node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
ERR_FAIL_NULL_V(node, nullptr);
} else if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
missing_node = memnew(MissingNode);
missing_node->set_original_scene(scene_path);
missing_node->set_recording_properties(true);
node = missing_node;
} else {
ERR_FAIL_V_MSG(nullptr, "Placeholder scene is missing.");
}
} else {
InstancePlaceholder *ip = memnew(InstancePlaceholder);
ip->set_instance_path(scene_path);
node = ip;
}
node->set_scene_instance_load_placeholder(true);
} else {
Ref<Resource> res = props[n.instance & FLAG_MASK];
Ref<PackedScene> sdata = res;
if (sdata.is_valid()) {
node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
ERR_FAIL_NULL_V_MSG(node, nullptr, vformat("Failed to load scene dependency: \"%s\". Make sure the required scene is valid.", sdata->get_path()));
} else if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
missing_node = memnew(MissingNode);
#ifdef TOOLS_ENABLED
if (res.is_valid()) {
missing_node->set_original_scene(res->get_meta("__load_path__", ""));
}
#endif
missing_node->set_recording_properties(true);
node = missing_node;
} else {
ERR_FAIL_V_MSG(nullptr, "Scene instance is missing.");
}
}
} else if (n.type == TYPE_INSTANTIATED) {
// Get the node from somewhere, it likely already exists from another instance.
if (parent) {
node = parent->_get_child_by_name(snames[n.name]);
#ifdef DEBUG_ENABLED
if (!node) {
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());
}
#endif
}
} else {
// Node belongs to this scene and must be created.
Object *obj = ClassDB::instantiate(snames[n.type]);
node = Object::cast_to<Node>(obj);
if (!node) {
if (obj) {
memdelete(obj);
obj = nullptr;
}
if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
missing_node = memnew(MissingNode);
missing_node->set_original_class(snames[n.type]);
missing_node->set_recording_properties(true);
node = missing_node;
obj = missing_node;
} else {
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());
if (n.parent >= 0 && n.parent < nc && ret_nodes[n.parent]) {
if (Object::cast_to<Control>(ret_nodes[n.parent])) {
obj = memnew(Control);
} else if (Object::cast_to<Node2D>(ret_nodes[n.parent])) {
obj = memnew(Node2D);
#ifndef _3D_DISABLED
} else if (Object::cast_to<Node3D>(ret_nodes[n.parent])) {
obj = memnew(Node3D);
#endif // _3D_DISABLED
}
}
if (!obj) {
obj = memnew(Node);
}
node = Object::cast_to<Node>(obj);
}
}
}
if (node) {
// may not have found the node (part of instantiated scene and removed)
// if found all is good, otherwise ignore
//properties
int nprop_count = n.properties.size();
if (nprop_count) {
const NodeData::Property *nprops = &n.properties[0];
Dictionary missing_resource_properties;
HashMap<Ref<Resource>, Ref<Resource>> resources_local_to_sub_scene; // Record the mappings in the sub-scene.
for (int j = 0; j < nprop_count; j++) {
bool valid;
ERR_FAIL_INDEX_V(nprops[j].value, prop_count, nullptr);
if (nprops[j].name & FLAG_PATH_PROPERTY_IS_NODE) {
if (!Engine::get_singleton()->is_editor_hint() && node->get_scene_instance_load_placeholder()) {
// We cannot know if the referenced nodes exist yet, so instead of deferring, we write the NodePaths directly.
uint32_t name_idx = nprops[j].name & (FLAG_PATH_PROPERTY_IS_NODE - 1);
ERR_FAIL_UNSIGNED_INDEX_V(name_idx, (uint32_t)sname_count, nullptr);
node->set(snames[name_idx], props[nprops[j].value], &valid);
continue;
}
uint32_t name_idx = nprops[j].name & (FLAG_PATH_PROPERTY_IS_NODE - 1);
ERR_FAIL_UNSIGNED_INDEX_V(name_idx, (uint32_t)sname_count, nullptr);
DeferredNodePathProperties dnp;
dnp.value = props[nprops[j].value];
dnp.base = node;
dnp.property = snames[name_idx];
deferred_node_paths.push_back(dnp);
continue;
}
ERR_FAIL_INDEX_V(nprops[j].name, sname_count, nullptr);
if (snames[nprops[j].name] == CoreStringName(script)) {
//work around to avoid old script variables from disappearing, should be the proper fix to:
//https://github.com/godotengine/godot/issues/2958
//store old state
List<Pair<StringName, Variant>> old_state;
if (node->get_script_instance()) {
node->get_script_instance()->get_property_state(old_state);
}
node->set(snames[nprops[j].name], props[nprops[j].value], &valid);
//restore old state for new script, if exists
for (const Pair<StringName, Variant> &E : old_state) {
node->set(E.first, E.second);
}
} else {
Variant value = props[nprops[j].value];
// Making sure that instances of inherited scenes don't share the same
// reference between them.
if (is_inherited_scene) {
value = value.duplicate(true);
}
if (value.get_type() == Variant::OBJECT) {
//handle resources that are local to scene by duplicating them if needed
Ref<Resource> res = value;
if (res.is_valid()) {
value = make_local_resource(value, n, resources_local_to_sub_scene, node, snames[nprops[j].name], resources_local_to_scene, i, ret_nodes, p_edit_state);
}
}
if (value.get_type() == Variant::ARRAY) {
Array set_array = value;
value = setup_resources_in_array(set_array, n, resources_local_to_sub_scene, node, snames[nprops[j].name], resources_local_to_scene, i, ret_nodes, p_edit_state);
bool is_get_valid = false;
Variant get_value = node->get(snames[nprops[j].name], &is_get_valid);
if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
Array get_array = get_value;
if (!set_array.is_same_typed(get_array)) {
value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
}
}
}
if (value.get_type() == Variant::DICTIONARY) {
Dictionary set_dict = value;
value = setup_resources_in_dictionary(set_dict, n, resources_local_to_sub_scene, node, snames[nprops[j].name], resources_local_to_scene, i, ret_nodes, p_edit_state);
bool is_get_valid = false;
Variant get_value = node->get(snames[nprops[j].name], &is_get_valid);
if (is_get_valid && get_value.get_type() == Variant::DICTIONARY) {
Dictionary get_dict = get_value;
if (!set_dict.is_same_typed(get_dict)) {
value = 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());
}
}
}
bool set_valid = true;
if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled() && value.get_type() == Variant::OBJECT) {
Ref<MissingResource> mr = value;
if (mr.is_valid()) {
missing_resource_properties[snames[nprops[j].name]] = mr;
set_valid = false;
}
}
if (set_valid) {
node->set(snames[nprops[j].name], value, &valid);
}
if (p_edit_state == GEN_EDIT_STATE_INSTANCE && value.get_type() != Variant::OBJECT) {
value = value.duplicate(true); // Duplicate arrays and dictionaries for the editor.
}
}
}
if (!missing_resource_properties.is_empty()) {
node->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
}
for (KeyValue<Ref<Resource>, Ref<Resource>> &E : resources_local_to_sub_scene) {
if (E.value->get_local_scene() == node) {
E.value->setup_local_to_scene(); // Setup may be required for the resource to work properly.
}
}
}
//name
//groups
for (int j = 0; j < n.groups.size(); j++) {
ERR_FAIL_INDEX_V(n.groups[j], sname_count, nullptr);
node->add_to_group(snames[n.groups[j]], true);
}
if (n.instance >= 0 || n.type != TYPE_INSTANTIATED || i == 0) {
//if node was not part of instance, must set its name, parenthood and ownership
if (i > 0) {
if (parent) {
bool pending_add = true;
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
Node *existing = parent->_get_child_by_name(snames[n.name]);
if (existing) {
// There's already a node in the same parent with the same name.
// This means that somehow the node was added both to the scene being
// loaded and another one instantiated in the former, maybe because of
// manual editing, or a bug in scene saving, or a loophole in the workflow
// (with any of the bugs possibly already fixed).
// Bring consistency back by letting it be assigned a non-clashing name.
// This simple workaround at least avoids leaks and helps the user realize
// something awkward has happened.
if (instantiation_warn_notify) {
instantiation_warn_notify(vformat(
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."),
ret_nodes[0]->get_path_to(existing)));
}
node->set_name(snames[n.name]);
parent->add_child(node, true);
pending_add = false;
}
}
#endif
if (pending_add) {
parent->_add_child_nocheck(node, snames[n.name]);
}
if (n.index >= 0 && n.index < parent->get_child_count() - 1) {
parent->move_child(node, n.index);
}
} else {
//it may be possible that an instantiated scene has changed
//and the node has nowhere to go anymore
stray_instances.push_back(node); //can't be added, go to stray list
}
} else {
if (Engine::get_singleton()->is_editor_hint()) {
//validate name if using editor, to avoid broken
node->set_name(snames[n.name]);
} else {
node->_set_name_nocheck(snames[n.name]);
}
}
}
if (!old_parent_path.is_empty()) {
node->set_name(old_parent_path + "#" + node->get_name());
}
if (n.owner >= 0) {
NODE_FROM_ID(owner, n.owner);
if (owner) {
node->_set_owner_nocheck(owner);
if (node->data.unique_name_in_owner) {
node->_acquire_unique_name_in_owner();
}
}
}
// We only want to deal with pinned flag if instantiating as pure main (no instance, no inheriting.)
if (p_edit_state == GEN_EDIT_STATE_MAIN) {
_sanitize_node_pinned_properties(node);
} else {
node->remove_meta("_edit_pinned_properties_");
}
}
if (missing_node) {
missing_node->set_recording_properties(false);
}
ret_nodes[i] = node;
if (node && gen_node_path_cache && ret_nodes[0]) {
NodePath n2 = ret_nodes[0]->get_path_to(node);
node_path_cache[n2] = i;
}
}
for (const DeferredNodePathProperties &dnp : deferred_node_paths) {
// Replace properties stored as NodePaths with actual Nodes.
if (dnp.value.get_type() == Variant::ARRAY) {
Array paths = dnp.value;
bool valid;
Array array = dnp.base->get(dnp.property, &valid);
ERR_CONTINUE_EDMSG(!valid, vformat("Failed to get property '%s' from node '%s'.", dnp.property, dnp.base->get_name()));
array = array.duplicate();
array.resize(paths.size());
for (int i = 0; i < array.size(); i++) {
array.set(i, dnp.base->get_node_or_null(paths[i]));
}
dnp.base->set(dnp.property, array);
} else if (dnp.value.get_type() == Variant::DICTIONARY) {
Dictionary paths = dnp.value;
bool valid;
Dictionary dict = dnp.base->get(dnp.property, &valid);
ERR_CONTINUE_EDMSG(!valid, vformat("Failed to get property '%s' from node '%s'.", dnp.property, dnp.base->get_name()));
dict = dict.duplicate();
bool convert_key = dict.get_typed_key_builtin() == Variant::OBJECT &&
ClassDB::is_parent_class(dict.get_typed_key_class_name(), "Node");
bool convert_value = dict.get_typed_value_builtin() == Variant::OBJECT &&
ClassDB::is_parent_class(dict.get_typed_value_class_name(), "Node");
for (int i = 0; i < paths.size(); i++) {
Variant key = paths.get_key_at_index(i);
if (convert_key) {
key = dnp.base->get_node_or_null(key);
}
Variant value = paths.get_value_at_index(i);
if (convert_value) {
value = dnp.base->get_node_or_null(value);
}
dict[key] = value;
}
dnp.base->set(dnp.property, dict);
} else {
dnp.base->set(dnp.property, dnp.base->get_node_or_null(dnp.value));
}
}
for (KeyValue<Ref<Resource>, Ref<Resource>> &E : resources_local_to_scene) {
if (E.value->get_local_scene() == ret_nodes[0]) {
E.value->setup_local_to_scene();
}
}
//do connections
int cc = connections.size();
const ConnectionData *cdata = connections.ptr();
for (int i = 0; i < cc; i++) {
const ConnectionData &c = cdata[i];
//ERR_FAIL_INDEX_V( c.from, nc, nullptr );
//ERR_FAIL_INDEX_V( c.to, nc, nullptr );
NODE_FROM_ID(cfrom, c.from);
NODE_FROM_ID(cto, c.to);
if (!cfrom || !cto) {
continue;
}
Callable callable(cto, snames[c.method]);
if (c.unbinds > 0) {
callable = callable.unbind(c.unbinds);
} else if (!c.binds.is_empty()) {
Vector<Variant> binds;
if (c.binds.size()) {
binds.resize(c.binds.size());
for (int j = 0; j < c.binds.size(); j++) {
binds.write[j] = props[c.binds[j]];
}
}
const Variant **argptrs = (const Variant **)alloca(sizeof(Variant *) * binds.size());
for (int j = 0; j < binds.size(); j++) {
argptrs[j] = &binds[j];
}
callable = callable.bindp(argptrs, binds.size());
}
cfrom->connect(snames[c.signal], callable, CONNECT_PERSIST | c.flags | (p_edit_state == GEN_EDIT_STATE_MAIN ? 0 : CONNECT_INHERITED));
}
//Node *s = ret_nodes[0];
//remove nodes that could not be added, likely as a result that
while (stray_instances.size()) {
memdelete(stray_instances.front()->get());
stray_instances.pop_front();
}
for (int i = 0; i < editable_instances.size(); i++) {
Node *ei = ret_nodes[0]->get_node_or_null(editable_instances[i]);
if (ei) {
ret_nodes[0]->set_editable_instance(ei, true);
}
}
return ret_nodes[0];
}
Variant SceneState::make_local_resource(Variant &p_value, const SceneState::NodeData &p_node_data, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_sub_scene, Node *p_node, const StringName p_sname, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_scene, int p_i, Node **p_ret_nodes, SceneState::GenEditState p_edit_state) const {
Ref<Resource> res = p_value;
if (res.is_null() || !res->is_local_to_scene()) {
return p_value;
}
if (p_node_data.instance >= 0) { // For the root node of a sub-scene, treat it as part of the sub-scene.
return get_remap_resource(res, p_resources_local_to_sub_scene, p_node->get(p_sname), p_node);
} else {
HashMap<Ref<Resource>, Ref<Resource>>::Iterator E = p_resources_local_to_scene.find(res);
Node *base = p_i == 0 ? p_node : p_ret_nodes[0];
if (E) {
return E->value;
} else if (p_edit_state == GEN_EDIT_STATE_MAIN) { // For the main scene, use the resource as is
res->configure_for_local_scene(base, p_resources_local_to_scene);
p_resources_local_to_scene[res] = res;
return res;
} else { // For instances, a copy must be made.
Ref<Resource> local_dupe = res->duplicate_for_local_scene(base, p_resources_local_to_scene);
p_resources_local_to_scene[res] = local_dupe;
return local_dupe;
}
}
}
Array SceneState::setup_resources_in_array(Array &p_array_to_scan, const SceneState::NodeData &p_n, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_sub_scene, Node *p_node, const StringName p_sname, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_scene, int p_i, Node **p_ret_nodes, SceneState::GenEditState p_edit_state) const {
for (int i = 0; i < p_array_to_scan.size(); i++) {
if (p_array_to_scan[i].get_type() == Variant::OBJECT) {
p_array_to_scan[i] = make_local_resource(p_array_to_scan[i], p_n, p_resources_local_to_sub_scene, p_node, p_sname, p_resources_local_to_scene, p_i, p_ret_nodes, p_edit_state);
}
}
return p_array_to_scan;
}
Dictionary SceneState::setup_resources_in_dictionary(Dictionary &p_dictionary_to_scan, const SceneState::NodeData &p_n, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_sub_scene, Node *p_node, const StringName p_sname, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_scene, int p_i, Node **p_ret_nodes, SceneState::GenEditState p_edit_state) const {
const Array keys = p_dictionary_to_scan.keys();
const Array values = p_dictionary_to_scan.values();
if (has_local_resource(values) || has_local_resource(keys)) {
Array duplicated_keys = keys.duplicate(true);
Array duplicated_values = values.duplicate(true);
duplicated_keys = setup_resources_in_array(duplicated_keys, p_n, p_resources_local_to_sub_scene, p_node, p_sname, p_resources_local_to_scene, p_i, p_ret_nodes, p_edit_state);
duplicated_values = setup_resources_in_array(duplicated_values, p_n, p_resources_local_to_sub_scene, p_node, p_sname, p_resources_local_to_scene, p_i, p_ret_nodes, p_edit_state);
p_dictionary_to_scan.clear();
for (int i = 0; i < keys.size(); i++) {
p_dictionary_to_scan[duplicated_keys[i]] = duplicated_values[i];
}
}
return p_dictionary_to_scan;
}
bool SceneState::has_local_resource(const Array &p_array) const {
for (int i = 0; i < p_array.size(); i++) {
Ref<Resource> res = p_array[i];
if (res.is_valid() && res->is_local_to_scene()) {
return true;
}
}
return false;
}
static int _nm_get_string(const String &p_string, HashMap<StringName, int> &name_map) {
if (name_map.has(p_string)) {
return name_map[p_string];
}
int idx = name_map.size();
name_map[p_string] = idx;
return idx;
}
static int _vm_get_variant(const Variant &p_variant, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map) {
if (variant_map.has(p_variant)) {
return variant_map[p_variant];
}
int idx = variant_map.size();
variant_map[p_variant] = idx;
return idx;
}
Error SceneState::_parse_node(Node *p_owner, Node *p_node, int p_parent_idx, HashMap<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, HashMap<Node *, int> &node_map, HashMap<Node *, int> &nodepath_map) {
// this function handles all the work related to properly packing scenes, be it
// instantiated or inherited.
// given the complexity of this process, an attempt will be made to properly
// document it. if you fail to understand something, please ask!
//discard nodes that do not belong to be processed
if (p_node != p_owner && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner())) {
return OK;
}
bool is_editable_instance = false;
// save the child instantiated scenes that are chosen as editable, so they can be restored
// upon load back
if (p_node != p_owner && !p_node->get_scene_file_path().is_empty() && p_owner->is_editable_instance(p_node)) {
editable_instances.push_back(p_owner->get_path_to(p_node));
// Node is the root of an editable instance.
is_editable_instance = true;
} else if (p_node->get_owner() && p_owner->is_ancestor_of(p_node->get_owner()) && p_owner->is_editable_instance(p_node->get_owner())) {
// Node is part of an editable instance.
is_editable_instance = true;
}
NodeData nd;
nd.name = _nm_get_string(p_node->get_name(), name_map);
nd.instance = -1; //not instantiated by default
//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
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)))) {
//do not save index, because it belongs to saved scene and scene is not inherited
nd.index = -1;
} else if (p_node == p_owner) {
//This (hopefully) happens if the node is a scene root, so its index is irrelevant.
nd.index = -1;
} else {
//part of an inherited scene, or parent is from an instantiated scene
nd.index = p_node->get_index();
}
// if this node is part of an instantiated scene or sub-instantiated scene
// we need to get the corresponding instance states.
// with the instance states, we can query for identical properties/groups
// and only save what has changed
bool instantiated_by_owner = false;
Vector<SceneState::PackState> states_stack = PropertyUtils::get_node_states_stack(p_node, p_owner, &instantiated_by_owner);
if (!p_node->get_scene_file_path().is_empty() && p_node->get_owner() == p_owner && instantiated_by_owner) {
if (p_node->get_scene_instance_load_placeholder()) {
//it's a placeholder, use the placeholder path
nd.instance = _vm_get_variant(p_node->get_scene_file_path(), variant_map);
nd.instance |= FLAG_INSTANCE_IS_PLACEHOLDER;
} else {
//must instance ourselves
Ref<PackedScene> instance = ResourceLoader::load(p_node->get_scene_file_path());
if (!instance.is_valid()) {
return ERR_CANT_OPEN;
}
nd.instance = _vm_get_variant(instance, variant_map);
}
}
// all setup, we then proceed to check all properties for the node
// and save the ones that are worth saving
List<PropertyInfo> plist;
p_node->get_property_list(&plist);
Array pinned_props = _sanitize_node_pinned_properties(p_node);
Dictionary missing_resource_properties = p_node->get_meta(META_MISSING_RESOURCES, Dictionary());
for (const PropertyInfo &E : plist) {
if (!(E.usage & PROPERTY_USAGE_STORAGE) && !missing_resource_properties.has(E.name)) {
continue;
}
if (E.name == META_PROPERTY_MISSING_RESOURCES) {
continue; // Ignore this property when packing.
}
// If instance or inheriting, not saving if property requested so.
if (!states_stack.is_empty()) {
if ((E.usage & PROPERTY_USAGE_NO_INSTANCE_STATE)) {
continue;
}
}
StringName name = E.name;
Variant value = p_node->get(name);
bool use_deferred_node_path_bit = false;
if (E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_NODE_TYPE) {
if (value.get_type() == Variant::OBJECT) {
if (Node *n = Object::cast_to<Node>(value)) {
value = p_node->get_path_to(n);
}
use_deferred_node_path_bit = true;
}
if (value.get_type() != Variant::NODE_PATH) {
continue; //was never set, ignore.
}
} else if (E.type == Variant::OBJECT && missing_resource_properties.has(E.name)) {
// Was this missing resource overridden? If so do not save the old value.
Ref<Resource> ures = value;
if (ures.is_null()) {
value = missing_resource_properties[E.name];
}
} else if (E.type == Variant::ARRAY && E.hint == PROPERTY_HINT_TYPE_STRING) {
int hint_subtype_separator = E.hint_string.find_char(':');
if (hint_subtype_separator >= 0) {
String subtype_string = E.hint_string.substr(0, hint_subtype_separator);
int slash_pos = subtype_string.find_char('/');
PropertyHint subtype_hint = PropertyHint::PROPERTY_HINT_NONE;
if (slash_pos >= 0) {
subtype_hint = PropertyHint(subtype_string.get_slice("/", 1).to_int());
subtype_string = subtype_string.substr(0, slash_pos);
}
Variant::Type subtype = Variant::Type(subtype_string.to_int());
if (subtype == Variant::OBJECT && subtype_hint == PROPERTY_HINT_NODE_TYPE) {
use_deferred_node_path_bit = true;
Array array = value;
Array new_array;
for (int i = 0; i < array.size(); i++) {
Variant elem = array[i];
if (elem.get_type() == Variant::OBJECT) {
if (Node *n = Object::cast_to<Node>(elem)) {
new_array.push_back(p_node->get_path_to(n));
continue;
}
}
new_array.push_back(elem);
}
value = new_array;
}
}
} else if (E.type == Variant::DICTIONARY && E.hint == PROPERTY_HINT_TYPE_STRING) {
int key_value_separator = E.hint_string.find_char(';');
if (key_value_separator >= 0) {
int key_subtype_separator = E.hint_string.find_char(':');
String key_subtype_string = E.hint_string.substr(0, key_subtype_separator);
int key_slash_pos = key_subtype_string.find_char('/');
PropertyHint key_subtype_hint = PropertyHint::PROPERTY_HINT_NONE;
if (key_slash_pos >= 0) {
key_subtype_hint = PropertyHint(key_subtype_string.get_slice("/", 1).to_int());
key_subtype_string = key_subtype_string.substr(0, key_slash_pos);
}
Variant::Type key_subtype = Variant::Type(key_subtype_string.to_int());
bool convert_key = key_subtype == Variant::OBJECT && key_subtype_hint == PROPERTY_HINT_NODE_TYPE;
int value_subtype_separator = E.hint_string.find_char(':', key_value_separator) - (key_value_separator + 1);
String value_subtype_string = E.hint_string.substr(key_value_separator + 1, value_subtype_separator);
int value_slash_pos = value_subtype_string.find_char('/');
PropertyHint value_subtype_hint = PropertyHint::PROPERTY_HINT_NONE;
if (value_slash_pos >= 0) {
value_subtype_hint = PropertyHint(value_subtype_string.get_slice("/", 1).to_int());
value_subtype_string = value_subtype_string.substr(0, value_slash_pos);
}
Variant::Type value_subtype = Variant::Type(value_subtype_string.to_int());
bool convert_value = value_subtype == Variant::OBJECT && value_subtype_hint == PROPERTY_HINT_NODE_TYPE;
if (convert_key || convert_value) {
use_deferred_node_path_bit = true;
Dictionary dict = value;
Dictionary new_dict;
for (int i = 0; i < dict.size(); i++) {
Variant new_key = dict.get_key_at_index(i);
if (convert_key && new_key.get_type() == Variant::OBJECT) {
if (Node *n = Object::cast_to<Node>(new_key)) {
new_key = p_node->get_path_to(n);
}
}
Variant new_value = dict.get_value_at_index(i);
if (convert_value && new_value.get_type() == Variant::OBJECT) {
if (Node *n = Object::cast_to<Node>(new_value)) {
new_value = p_node->get_path_to(n);
}
}
new_dict[new_key] = new_value;
}
value = new_dict;
}
}
}
if (!pinned_props.has(name)) {
bool is_valid_default = false;
Variant default_value = PropertyUtils::get_property_default_value(p_node, name, &is_valid_default, &states_stack, true);
if (is_valid_default && !PropertyUtils::is_property_value_different(p_node, value, default_value)) {
if (value.get_type() == Variant::ARRAY && has_local_resource(value)) {
// Save anyway
} else if (value.get_type() == Variant::DICTIONARY) {
Dictionary dictionary = value;
if (!has_local_resource(dictionary.values()) && !has_local_resource(dictionary.keys())) {
continue;
}
} else {
continue;
}
}
}
NodeData::Property prop;
prop.name = _nm_get_string(name, name_map);
prop.value = _vm_get_variant(value, variant_map);
if (use_deferred_node_path_bit) {
prop.name |= FLAG_PATH_PROPERTY_IS_NODE;
}
nd.properties.push_back(prop);
}
// save the groups this node is into
// discard groups that come from the original scene
List<Node::GroupInfo> groups;
p_node->get_groups(&groups);
for (const Node::GroupInfo &gi : groups) {
if (!gi.persistent) {
continue;
}
bool skip = false;
for (const SceneState::PackState &ia : states_stack) {
//check all levels of pack to see if the group was added somewhere
if (ia.state->is_node_in_group(ia.node, gi.name)) {
skip = true;
break;
}
}
if (skip) {
continue;
}
nd.groups.push_back(_nm_get_string(gi.name, name_map));
}
// save the right owner
// for the saved scene root this is -1
// for nodes of the saved scene this is 0
// for nodes of instantiated scenes this is >0
if (p_node == p_owner) {
//saved scene root
nd.owner = -1;
} else if (p_node->get_owner() == p_owner) {
//part of saved scene
nd.owner = 0;
} else {
nd.owner = -1;
}
MissingNode *missing_node = Object::cast_to<MissingNode>(p_node);
// Save the right type. If this node was created by an instance
// then flag that the node should not be created but reused
if (states_stack.is_empty() && !is_editable_instance) {
//This node is not part of an instantiation process, so save the type.
if (missing_node != nullptr) {
// It's a missing node (type non existent on load).
nd.type = _nm_get_string(missing_node->get_original_class(), name_map);
} else {
nd.type = _nm_get_string(p_node->get_class(), name_map);
}
} else {
// this node is part of an instantiated process, so do not save the type.
// instead, save that it was instantiated
nd.type = TYPE_INSTANTIATED;
}
// determine whether to save this node or not
// if this node is part of an instantiated sub-scene, we can skip storing it if basically
// no properties changed and no groups were added to it.
// below condition is true for all nodes of the scene being saved, and ones in subscenes
// that hold changes
bool save_node = nd.properties.size() || nd.groups.size(); // some local properties or groups exist
save_node = save_node || p_node == p_owner; // owner is always saved
save_node = save_node || (p_node->get_owner() == p_owner && instantiated_by_owner); //part of scene and not instanced
int idx = nodes.size();
int parent_node = NO_PARENT_SAVED;