summaryrefslogtreecommitdiff
path: root/scene/main/scene_tree.cpp
blob: 58bc6099f65d93996e43cb031c68c006efe10159 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
/*************************************************************************/
/*  scene_tree.cpp                                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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 "scene_tree.h"

#include "core/config/project_settings.h"
#include "core/debugger/engine_debugger.h"
#include "core/input/input.h"
#include "core/io/marshalls.h"
#include "core/io/resource_loader.h"
#include "core/object/message_queue.h"
#include "core/os/dir_access.h"
#include "core/os/keyboard.h"
#include "core/os/os.h"
#include "core/string/print_string.h"
#include "node.h"
#include "scene/debugger/scene_debugger.h"
#include "scene/resources/font.h"
#include "scene/resources/material.h"
#include "scene/resources/mesh.h"
#include "scene/resources/packed_scene.h"
#include "scene/scene_string_names.h"
#include "servers/display_server.h"
#include "servers/navigation_server_3d.h"
#include "servers/physics_server_2d.h"
#include "servers/physics_server_3d.h"
#include "window.h"

#include <stdio.h>

void SceneTreeTimer::_bind_methods() {
	ClassDB::bind_method(D_METHOD("set_time_left", "time"), &SceneTreeTimer::set_time_left);
	ClassDB::bind_method(D_METHOD("get_time_left"), &SceneTreeTimer::get_time_left);

	ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_left"), "set_time_left", "get_time_left");

	ADD_SIGNAL(MethodInfo("timeout"));
}

void SceneTreeTimer::set_time_left(float p_time) {
	time_left = p_time;
}

float SceneTreeTimer::get_time_left() const {
	return time_left;
}

void SceneTreeTimer::set_pause_mode_process(bool p_pause_mode_process) {
	process_pause = p_pause_mode_process;
}

bool SceneTreeTimer::is_pause_mode_process() {
	return process_pause;
}

void SceneTreeTimer::release_connections() {
	List<Connection> connections;
	get_all_signal_connections(&connections);

	for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {
		Connection const &connection = E->get();
		disconnect(connection.signal.get_name(), connection.callable);
	}
}

SceneTreeTimer::SceneTreeTimer() {
	time_left = 0;
	process_pause = true;
}

void SceneTree::tree_changed() {
	tree_version++;
	emit_signal(tree_changed_name);
}

void SceneTree::node_added(Node *p_node) {
	emit_signal(node_added_name, p_node);
}

void SceneTree::node_removed(Node *p_node) {
	if (current_scene == p_node) {
		current_scene = nullptr;
	}
	emit_signal(node_removed_name, p_node);
	if (call_lock > 0) {
		call_skip.insert(p_node);
	}
}

void SceneTree::node_renamed(Node *p_node) {
	emit_signal(node_renamed_name, p_node);
}

SceneTree::Group *SceneTree::add_to_group(const StringName &p_group, Node *p_node) {
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	if (!E) {
		E = group_map.insert(p_group, Group());
	}

	ERR_FAIL_COND_V_MSG(E->get().nodes.find(p_node) != -1, &E->get(), "Already in group: " + p_group + ".");
	E->get().nodes.push_back(p_node);
	//E->get().last_tree_version=0;
	E->get().changed = true;
	return &E->get();
}

void SceneTree::remove_from_group(const StringName &p_group, Node *p_node) {
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	ERR_FAIL_COND(!E);

	E->get().nodes.erase(p_node);
	if (E->get().nodes.is_empty()) {
		group_map.erase(E);
	}
}

void SceneTree::make_group_changed(const StringName &p_group) {
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	if (E) {
		E->get().changed = true;
	}
}

void SceneTree::flush_transform_notifications() {
	SelfList<Node> *n = xform_change_list.first();
	while (n) {
		Node *node = n->self();
		SelfList<Node> *nx = n->next();
		xform_change_list.remove(n);
		n = nx;
		node->notification(NOTIFICATION_TRANSFORM_CHANGED);
	}
}

void SceneTree::_flush_ugc() {
	ugc_locked = true;

	while (unique_group_calls.size()) {
		Map<UGCall, Vector<Variant>>::Element *E = unique_group_calls.front();

		Variant v[VARIANT_ARG_MAX];
		for (int i = 0; i < E->get().size(); i++) {
			v[i] = E->get()[i];
		}

		static_assert(VARIANT_ARG_MAX == 5, "This code needs to be updated if VARIANT_ARG_MAX != 5");
		call_group_flags(GROUP_CALL_REALTIME, E->key().group, E->key().call, v[0], v[1], v[2], v[3], v[4]);

		unique_group_calls.erase(E);
	}

	ugc_locked = false;
}

void SceneTree::_update_group_order(Group &g, bool p_use_priority) {
	if (!g.changed) {
		return;
	}
	if (g.nodes.is_empty()) {
		return;
	}

	Node **nodes = g.nodes.ptrw();
	int node_count = g.nodes.size();

	if (p_use_priority) {
		SortArray<Node *, Node::ComparatorWithPriority> node_sort;
		node_sort.sort(nodes, node_count);
	} else {
		SortArray<Node *, Node::Comparator> node_sort;
		node_sort.sort(nodes, node_count);
	}
	g.changed = false;
}

void SceneTree::call_group_flags(uint32_t p_call_flags, const StringName &p_group, const StringName &p_function, VARIANT_ARG_DECLARE) {
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	if (!E) {
		return;
	}
	Group &g = E->get();
	if (g.nodes.is_empty()) {
		return;
	}

	if (p_call_flags & GROUP_CALL_UNIQUE && !(p_call_flags & GROUP_CALL_REALTIME)) {
		ERR_FAIL_COND(ugc_locked);

		UGCall ug;
		ug.call = p_function;
		ug.group = p_group;

		if (unique_group_calls.has(ug)) {
			return;
		}

		VARIANT_ARGPTRS;

		Vector<Variant> args;
		for (int i = 0; i < VARIANT_ARG_MAX; i++) {
			if (argptr[i]->get_type() == Variant::NIL) {
				break;
			}
			args.push_back(*argptr[i]);
		}

		unique_group_calls[ug] = args;
		return;
	}

	_update_group_order(g);

	Vector<Node *> nodes_copy = g.nodes;
	Node **nodes = nodes_copy.ptrw();
	int node_count = nodes_copy.size();

	call_lock++;

	if (p_call_flags & GROUP_CALL_REVERSE) {
		for (int i = node_count - 1; i >= 0; i--) {
			if (call_lock && call_skip.has(nodes[i])) {
				continue;
			}

			if (p_call_flags & GROUP_CALL_REALTIME) {
				nodes[i]->call(p_function, VARIANT_ARG_PASS);
			} else {
				MessageQueue::get_singleton()->push_call(nodes[i], p_function, VARIANT_ARG_PASS);
			}
		}

	} else {
		for (int i = 0; i < node_count; i++) {
			if (call_lock && call_skip.has(nodes[i])) {
				continue;
			}

			if (p_call_flags & GROUP_CALL_REALTIME) {
				nodes[i]->call(p_function, VARIANT_ARG_PASS);
			} else {
				MessageQueue::get_singleton()->push_call(nodes[i], p_function, VARIANT_ARG_PASS);
			}
		}
	}

	call_lock--;
	if (call_lock == 0) {
		call_skip.clear();
	}
}

void SceneTree::notify_group_flags(uint32_t p_call_flags, const StringName &p_group, int p_notification) {
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	if (!E) {
		return;
	}
	Group &g = E->get();
	if (g.nodes.is_empty()) {
		return;
	}

	_update_group_order(g);

	Vector<Node *> nodes_copy = g.nodes;
	Node **nodes = nodes_copy.ptrw();
	int node_count = nodes_copy.size();

	call_lock++;

	if (p_call_flags & GROUP_CALL_REVERSE) {
		for (int i = node_count - 1; i >= 0; i--) {
			if (call_lock && call_skip.has(nodes[i])) {
				continue;
			}

			if (p_call_flags & GROUP_CALL_REALTIME) {
				nodes[i]->notification(p_notification);
			} else {
				MessageQueue::get_singleton()->push_notification(nodes[i], p_notification);
			}
		}

	} else {
		for (int i = 0; i < node_count; i++) {
			if (call_lock && call_skip.has(nodes[i])) {
				continue;
			}

			if (p_call_flags & GROUP_CALL_REALTIME) {
				nodes[i]->notification(p_notification);
			} else {
				MessageQueue::get_singleton()->push_notification(nodes[i], p_notification);
			}
		}
	}

	call_lock--;
	if (call_lock == 0) {
		call_skip.clear();
	}
}

void SceneTree::set_group_flags(uint32_t p_call_flags, const StringName &p_group, const String &p_name, const Variant &p_value) {
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	if (!E) {
		return;
	}
	Group &g = E->get();
	if (g.nodes.is_empty()) {
		return;
	}

	_update_group_order(g);

	Vector<Node *> nodes_copy = g.nodes;
	Node **nodes = nodes_copy.ptrw();
	int node_count = nodes_copy.size();

	call_lock++;

	if (p_call_flags & GROUP_CALL_REVERSE) {
		for (int i = node_count - 1; i >= 0; i--) {
			if (call_lock && call_skip.has(nodes[i])) {
				continue;
			}

			if (p_call_flags & GROUP_CALL_REALTIME) {
				nodes[i]->set(p_name, p_value);
			} else {
				MessageQueue::get_singleton()->push_set(nodes[i], p_name, p_value);
			}
		}

	} else {
		for (int i = 0; i < node_count; i++) {
			if (call_lock && call_skip.has(nodes[i])) {
				continue;
			}

			if (p_call_flags & GROUP_CALL_REALTIME) {
				nodes[i]->set(p_name, p_value);
			} else {
				MessageQueue::get_singleton()->push_set(nodes[i], p_name, p_value);
			}
		}
	}

	call_lock--;
	if (call_lock == 0) {
		call_skip.clear();
	}
}

void SceneTree::call_group(const StringName &p_group, const StringName &p_function, VARIANT_ARG_DECLARE) {
	call_group_flags(0, p_group, p_function, VARIANT_ARG_PASS);
}

void SceneTree::notify_group(const StringName &p_group, int p_notification) {
	notify_group_flags(0, p_group, p_notification);
}

void SceneTree::set_group(const StringName &p_group, const String &p_name, const Variant &p_value) {
	set_group_flags(0, p_group, p_name, p_value);
}

void SceneTree::initialize() {
	initialized = true;
	root->_set_tree(this);
	MainLoop::initialize();
}

bool SceneTree::physics_process(float p_time) {
	root_lock++;

	current_frame++;

	flush_transform_notifications();

	MainLoop::physics_process(p_time);
	physics_process_time = p_time;

	emit_signal("physics_frame");

	_notify_group_pause("physics_process_internal", Node::NOTIFICATION_INTERNAL_PHYSICS_PROCESS);
	_notify_group_pause("physics_process", Node::NOTIFICATION_PHYSICS_PROCESS);
	_flush_ugc();
	MessageQueue::get_singleton()->flush(); //small little hack
	flush_transform_notifications();
	call_group_flags(GROUP_CALL_REALTIME, "_viewports", "update_worlds");
	root_lock--;

	_flush_delete_queue();
	_call_idle_callbacks();

	return _quit;
}

bool SceneTree::process(float p_time) {
	root_lock++;

	MainLoop::process(p_time);

	process_time = p_time;

	if (multiplayer_poll) {
		multiplayer->poll();
	}

	emit_signal("process_frame");

	MessageQueue::get_singleton()->flush(); //small little hack

	flush_transform_notifications();

	_notify_group_pause("process_internal", Node::NOTIFICATION_INTERNAL_PROCESS);
	_notify_group_pause("process", Node::NOTIFICATION_PROCESS);

	_flush_ugc();
	MessageQueue::get_singleton()->flush(); //small little hack
	flush_transform_notifications(); //transforms after world update, to avoid unnecessary enter/exit notifications
	call_group_flags(GROUP_CALL_REALTIME, "_viewports", "update_worlds");

	root_lock--;

	_flush_delete_queue();

	//go through timers

	List<Ref<SceneTreeTimer>>::Element *L = timers.back(); //last element

	for (List<Ref<SceneTreeTimer>>::Element *E = timers.front(); E;) {
		List<Ref<SceneTreeTimer>>::Element *N = E->next();
		if (pause && !E->get()->is_pause_mode_process()) {
			if (E == L) {
				break; //break on last, so if new timers were added during list traversal, ignore them.
			}
			E = N;
			continue;
		}
		float time_left = E->get()->get_time_left();
		time_left -= p_time;
		E->get()->set_time_left(time_left);

		if (time_left < 0) {
			E->get()->emit_signal("timeout");
			timers.erase(E);
		}
		if (E == L) {
			break; //break on last, so if new timers were added during list traversal, ignore them.
		}
		E = N;
	}

	flush_transform_notifications(); //additional transforms after timers update

	_call_idle_callbacks();

#ifdef TOOLS_ENABLED

	if (Engine::get_singleton()->is_editor_hint()) {
		//simple hack to reload fallback environment if it changed from editor
		String env_path = ProjectSettings::get_singleton()->get("rendering/environment/default_environment");
		env_path = env_path.strip_edges(); //user may have added a space or two
		String cpath;
		Ref<Environment> fallback = get_root()->get_world_3d()->get_fallback_environment();
		if (fallback.is_valid()) {
			cpath = fallback->get_path();
		}
		if (cpath != env_path) {
			if (env_path != String()) {
				fallback = ResourceLoader::load(env_path);
				if (fallback.is_null()) {
					//could not load fallback, set as empty
					ProjectSettings::get_singleton()->set("rendering/environment/default_environment", "");
				}
			} else {
				fallback.unref();
			}
			get_root()->get_world_3d()->set_fallback_environment(fallback);
		}
	}

#endif

	return _quit;
}

void SceneTree::finalize() {
	_flush_delete_queue();

	_flush_ugc();

	initialized = false;

	MainLoop::finalize();

	if (root) {
		root->_set_tree(nullptr);
		root->_propagate_after_exit_tree();
		memdelete(root); //delete root
		root = nullptr;
	}

	// cleanup timers
	for (List<Ref<SceneTreeTimer>>::Element *E = timers.front(); E; E = E->next()) {
		E->get()->release_connections();
	}
	timers.clear();
}

void SceneTree::quit(int p_exit_code) {
	if (p_exit_code >= 0) {
		// Override the exit code if a positive argument is given (the default is `-1`).
		// This is a shorthand for calling `set_exit_code()` on the OS singleton then quitting.
		OS::get_singleton()->set_exit_code(p_exit_code);
	}

	_quit = true;
}

void SceneTree::_main_window_close() {
	if (accept_quit) {
		_quit = true;
	}
}

void SceneTree::_main_window_go_back() {
	if (quit_on_go_back) {
		_quit = true;
	}
}

void SceneTree::_main_window_focus_in() {
	Input *id = Input::get_singleton();
	if (id) {
		id->ensure_touch_mouse_raised();
	}
}

void SceneTree::_notification(int p_notification) {
	switch (p_notification) {
		case NOTIFICATION_TRANSLATION_CHANGED: {
			if (!Engine::get_singleton()->is_editor_hint()) {
				get_root()->propagate_notification(p_notification);
			}
		} break;
		case NOTIFICATION_OS_MEMORY_WARNING:
		case NOTIFICATION_OS_IME_UPDATE:
		case NOTIFICATION_WM_ABOUT:
		case NOTIFICATION_CRASH:
		case NOTIFICATION_APPLICATION_RESUMED:
		case NOTIFICATION_APPLICATION_PAUSED:
		case NOTIFICATION_APPLICATION_FOCUS_IN:
		case NOTIFICATION_APPLICATION_FOCUS_OUT: {
			get_root()->propagate_notification(p_notification); //pass these to nodes, since they are mirrored
		} break;

		default:
			break;
	};
};

void SceneTree::set_auto_accept_quit(bool p_enable) {
	accept_quit = p_enable;
}

void SceneTree::set_quit_on_go_back(bool p_enable) {
	quit_on_go_back = p_enable;
}

#ifdef TOOLS_ENABLED

bool SceneTree::is_node_being_edited(const Node *p_node) const {
	return Engine::get_singleton()->is_editor_hint() && edited_scene_root && (edited_scene_root->is_a_parent_of(p_node) || edited_scene_root == p_node);
}
#endif

#ifdef DEBUG_ENABLED
void SceneTree::set_debug_collisions_hint(bool p_enabled) {
	debug_collisions_hint = p_enabled;
}

bool SceneTree::is_debugging_collisions_hint() const {
	return debug_collisions_hint;
}

void SceneTree::set_debug_navigation_hint(bool p_enabled) {
	debug_navigation_hint = p_enabled;
}

bool SceneTree::is_debugging_navigation_hint() const {
	return debug_navigation_hint;
}
#endif

void SceneTree::set_debug_collisions_color(const Color &p_color) {
	debug_collisions_color = p_color;
}

Color SceneTree::get_debug_collisions_color() const {
	return debug_collisions_color;
}

void SceneTree::set_debug_collision_contact_color(const Color &p_color) {
	debug_collision_contact_color = p_color;
}

Color SceneTree::get_debug_collision_contact_color() const {
	return debug_collision_contact_color;
}

void SceneTree::set_debug_navigation_color(const Color &p_color) {
	debug_navigation_color = p_color;
}

Color SceneTree::get_debug_navigation_color() const {
	return debug_navigation_color;
}

void SceneTree::set_debug_navigation_disabled_color(const Color &p_color) {
	debug_navigation_disabled_color = p_color;
}

Color SceneTree::get_debug_navigation_disabled_color() const {
	return debug_navigation_disabled_color;
}

Ref<Material> SceneTree::get_debug_navigation_material() {
	if (navigation_material.is_valid()) {
		return navigation_material;
	}

	Ref<StandardMaterial3D> line_material = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
	line_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
	line_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
	line_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
	line_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
	line_material->set_albedo(get_debug_navigation_color());

	navigation_material = line_material;

	return navigation_material;
}

Ref<Material> SceneTree::get_debug_navigation_disabled_material() {
	if (navigation_disabled_material.is_valid()) {
		return navigation_disabled_material;
	}

	Ref<StandardMaterial3D> line_material = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
	line_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
	line_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
	line_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
	line_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
	line_material->set_albedo(get_debug_navigation_disabled_color());

	navigation_disabled_material = line_material;

	return navigation_disabled_material;
}

Ref<Material> SceneTree::get_debug_collision_material() {
	if (collision_material.is_valid()) {
		return collision_material;
	}

	Ref<StandardMaterial3D> line_material = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
	line_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
	line_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
	line_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
	line_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
	line_material->set_albedo(get_debug_collisions_color());

	collision_material = line_material;

	return collision_material;
}

Ref<ArrayMesh> SceneTree::get_debug_contact_mesh() {
	if (debug_contact_mesh.is_valid()) {
		return debug_contact_mesh;
	}

	debug_contact_mesh = Ref<ArrayMesh>(memnew(ArrayMesh));

	Ref<StandardMaterial3D> mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
	mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
	mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
	mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
	mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
	mat->set_albedo(get_debug_collision_contact_color());

	Vector3 diamond[6] = {
		Vector3(-1, 0, 0),
		Vector3(1, 0, 0),
		Vector3(0, -1, 0),
		Vector3(0, 1, 0),
		Vector3(0, 0, -1),
		Vector3(0, 0, 1)
	};

	/* clang-format off */
	int diamond_faces[8 * 3] = {
		0, 2, 4,
		0, 3, 4,
		1, 2, 4,
		1, 3, 4,
		0, 2, 5,
		0, 3, 5,
		1, 2, 5,
		1, 3, 5,
	};
	/* clang-format on */

	Vector<int> indices;
	for (int i = 0; i < 8 * 3; i++) {
		indices.push_back(diamond_faces[i]);
	}

	Vector<Vector3> vertices;
	for (int i = 0; i < 6; i++) {
		vertices.push_back(diamond[i] * 0.1);
	}

	Array arr;
	arr.resize(Mesh::ARRAY_MAX);
	arr[Mesh::ARRAY_VERTEX] = vertices;
	arr[Mesh::ARRAY_INDEX] = indices;

	debug_contact_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
	debug_contact_mesh->surface_set_material(0, mat);

	return debug_contact_mesh;
}

void SceneTree::set_pause(bool p_enabled) {
	if (p_enabled == pause) {
		return;
	}
	pause = p_enabled;
	NavigationServer3D::get_singleton()->set_active(!p_enabled);
	PhysicsServer3D::get_singleton()->set_active(!p_enabled);
	PhysicsServer2D::get_singleton()->set_active(!p_enabled);
	if (get_root()) {
		get_root()->propagate_notification(p_enabled ? Node::NOTIFICATION_PAUSED : Node::NOTIFICATION_UNPAUSED);
	}
}

bool SceneTree::is_paused() const {
	return pause;
}

void SceneTree::_notify_group_pause(const StringName &p_group, int p_notification) {
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	if (!E) {
		return;
	}
	Group &g = E->get();
	if (g.nodes.is_empty()) {
		return;
	}

	_update_group_order(g, p_notification == Node::NOTIFICATION_PROCESS || p_notification == Node::NOTIFICATION_INTERNAL_PROCESS || p_notification == Node::NOTIFICATION_PHYSICS_PROCESS || p_notification == Node::NOTIFICATION_INTERNAL_PHYSICS_PROCESS);

	//copy, so copy on write happens in case something is removed from process while being called
	//performance is not lost because only if something is added/removed the vector is copied.
	Vector<Node *> nodes_copy = g.nodes;

	int node_count = nodes_copy.size();
	Node **nodes = nodes_copy.ptrw();

	call_lock++;

	for (int i = 0; i < node_count; i++) {
		Node *n = nodes[i];
		if (call_lock && call_skip.has(n)) {
			continue;
		}

		if (!n->can_process()) {
			continue;
		}
		if (!n->can_process_notification(p_notification)) {
			continue;
		}

		n->notification(p_notification);
		//ERR_FAIL_COND(node_count != g.nodes.size());
	}

	call_lock--;
	if (call_lock == 0) {
		call_skip.clear();
	}
}

/*
void SceneMainLoop::_update_listener_2d() {
	if (listener_2d.is_valid()) {
		SpatialSound2DServer::get_singleton()->listener_set_space( listener_2d, world_2d->get_sound_space() );
	}
}

*/

void SceneTree::_call_input_pause(const StringName &p_group, const StringName &p_method, const Ref<InputEvent> &p_input, Viewport *p_viewport) {
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	if (!E) {
		return;
	}
	Group &g = E->get();
	if (g.nodes.is_empty()) {
		return;
	}

	_update_group_order(g);

	//copy, so copy on write happens in case something is removed from process while being called
	//performance is not lost because only if something is added/removed the vector is copied.
	Vector<Node *> nodes_copy = g.nodes;

	int node_count = nodes_copy.size();
	Node **nodes = nodes_copy.ptrw();

	Variant arg = p_input;
	const Variant *v[1] = { &arg };

	call_lock++;

	for (int i = node_count - 1; i >= 0; i--) {
		if (p_viewport->is_input_handled()) {
			break;
		}

		Node *n = nodes[i];
		if (call_lock && call_skip.has(n)) {
			continue;
		}

		if (!n->can_process()) {
			continue;
		}

		Callable::CallError err;
		// Call both script and native method.
		if (n->get_script_instance()) {
			n->get_script_instance()->call(p_method, (const Variant **)v, 1, err);
		}
		MethodBind *method = ClassDB::get_method(n->get_class_name(), p_method);
		if (method) {
			method->call(n, (const Variant **)v, 1, err);
		}
	}

	call_lock--;
	if (call_lock == 0) {
		call_skip.clear();
	}
}

Variant SceneTree::_call_group_flags(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
	r_error.error = Callable::CallError::CALL_OK;

	ERR_FAIL_COND_V(p_argcount < 3, Variant());
	ERR_FAIL_COND_V(!p_args[0]->is_num(), Variant());
	ERR_FAIL_COND_V(p_args[1]->get_type() != Variant::STRING_NAME && p_args[1]->get_type() != Variant::STRING, Variant());
	ERR_FAIL_COND_V(p_args[2]->get_type() != Variant::STRING_NAME && p_args[2]->get_type() != Variant::STRING, Variant());

	int flags = *p_args[0];
	StringName group = *p_args[1];
	StringName method = *p_args[2];
	Variant v[VARIANT_ARG_MAX];

	for (int i = 0; i < MIN(p_argcount - 3, 5); i++) {
		v[i] = *p_args[i + 3];
	}

	static_assert(VARIANT_ARG_MAX == 5, "This code needs to be updated if VARIANT_ARG_MAX != 5");
	call_group_flags(flags, group, method, v[0], v[1], v[2], v[3], v[4]);
	return Variant();
}

Variant SceneTree::_call_group(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
	r_error.error = Callable::CallError::CALL_OK;

	ERR_FAIL_COND_V(p_argcount < 2, Variant());
	ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING, Variant());
	ERR_FAIL_COND_V(p_args[1]->get_type() != Variant::STRING_NAME && p_args[1]->get_type() != Variant::STRING, Variant());

	StringName group = *p_args[0];
	StringName method = *p_args[1];
	Variant v[VARIANT_ARG_MAX];

	for (int i = 0; i < MIN(p_argcount - 2, 5); i++) {
		v[i] = *p_args[i + 2];
	}

	static_assert(VARIANT_ARG_MAX == 5, "This code needs to be updated if VARIANT_ARG_MAX != 5");
	call_group_flags(0, group, method, v[0], v[1], v[2], v[3], v[4]);
	return Variant();
}

int64_t SceneTree::get_frame() const {
	return current_frame;
}

Array SceneTree::_get_nodes_in_group(const StringName &p_group) {
	Array ret;
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	if (!E) {
		return ret;
	}

	_update_group_order(E->get()); //update order just in case
	int nc = E->get().nodes.size();
	if (nc == 0) {
		return ret;
	}

	ret.resize(nc);

	Node **ptr = E->get().nodes.ptrw();
	for (int i = 0; i < nc; i++) {
		ret[i] = ptr[i];
	}

	return ret;
}

bool SceneTree::has_group(const StringName &p_identifier) const {
	return group_map.has(p_identifier);
}

void SceneTree::get_nodes_in_group(const StringName &p_group, List<Node *> *p_list) {
	Map<StringName, Group>::Element *E = group_map.find(p_group);
	if (!E) {
		return;
	}

	_update_group_order(E->get()); //update order just in case
	int nc = E->get().nodes.size();
	if (nc == 0) {
		return;
	}
	Node **ptr = E->get().nodes.ptrw();
	for (int i = 0; i < nc; i++) {
		p_list->push_back(ptr[i]);
	}
}

void SceneTree::_flush_delete_queue() {
	_THREAD_SAFE_METHOD_

	while (delete_queue.size()) {
		Object *obj = ObjectDB::get_instance(delete_queue.front()->get());
		if (obj) {
			memdelete(obj);
		}
		delete_queue.pop_front();
	}
}

void SceneTree::queue_delete(Object *p_object) {
	_THREAD_SAFE_METHOD_
	ERR_FAIL_NULL(p_object);
	p_object->_is_queued_for_deletion = true;
	delete_queue.push_back(p_object->get_instance_id());
}

int SceneTree::get_node_count() const {
	return node_count;
}

void SceneTree::set_edited_scene_root(Node *p_node) {
#ifdef TOOLS_ENABLED
	edited_scene_root = p_node;
#endif
}

Node *SceneTree::get_edited_scene_root() const {
#ifdef TOOLS_ENABLED
	return edited_scene_root;
#else
	return nullptr;
#endif
}

void SceneTree::set_current_scene(Node *p_scene) {
	ERR_FAIL_COND(p_scene && p_scene->get_parent() != root);
	current_scene = p_scene;
}

Node *SceneTree::get_current_scene() const {
	return current_scene;
}

void SceneTree::_change_scene(Node *p_to) {
	if (current_scene) {
		memdelete(current_scene);
		current_scene = nullptr;
	}

	// If we're quitting, abort.
	if (unlikely(_quit)) {
		if (p_to) { // Prevent memory leak.
			memdelete(p_to);
		}
		return;
	}

	if (p_to) {
		current_scene = p_to;
		root->add_child(p_to);
	}
}

Error SceneTree::change_scene(const String &p_path) {
	Ref<PackedScene> new_scene = ResourceLoader::load(p_path);
	if (new_scene.is_null()) {
		return ERR_CANT_OPEN;
	}

	return change_scene_to(new_scene);
}

Error SceneTree::change_scene_to(const Ref<PackedScene> &p_scene) {
	Node *new_scene = nullptr;
	if (p_scene.is_valid()) {
		new_scene = p_scene->instance();
		ERR_FAIL_COND_V(!new_scene, ERR_CANT_CREATE);
	}

	call_deferred("_change_scene", new_scene);
	return OK;
}

Error SceneTree::reload_current_scene() {
	ERR_FAIL_COND_V(!current_scene, ERR_UNCONFIGURED);
	String fname = current_scene->get_filename();
	return change_scene(fname);
}

void SceneTree::add_current_scene(Node *p_current) {
	current_scene = p_current;
	root->add_child(p_current);
}

Ref<SceneTreeTimer> SceneTree::create_timer(float p_delay_sec, bool p_process_pause) {
	Ref<SceneTreeTimer> stt;
	stt.instance();
	stt->set_pause_mode_process(p_process_pause);
	stt->set_time_left(p_delay_sec);
	timers.push_back(stt);
	return stt;
}

void SceneTree::_network_peer_connected(int p_id) {
	emit_signal("network_peer_connected", p_id);
}

void SceneTree::_network_peer_disconnected(int p_id) {
	emit_signal("network_peer_disconnected", p_id);
}

void SceneTree::_connected_to_server() {
	emit_signal("connected_to_server");
}

void SceneTree::_connection_failed() {
	emit_signal("connection_failed");
}

void SceneTree::_server_disconnected() {
	emit_signal("server_disconnected");
}

Ref<MultiplayerAPI> SceneTree::get_multiplayer() const {
	return multiplayer;
}

void SceneTree::set_multiplayer_poll_enabled(bool p_enabled) {
	multiplayer_poll = p_enabled;
}

bool SceneTree::is_multiplayer_poll_enabled() const {
	return multiplayer_poll;
}

void SceneTree::set_multiplayer(Ref<MultiplayerAPI> p_multiplayer) {
	ERR_FAIL_COND(!p_multiplayer.is_valid());

	if (multiplayer.is_valid()) {
		multiplayer->disconnect("network_peer_connected", callable_mp(this, &SceneTree::_network_peer_connected));
		multiplayer->disconnect("network_peer_disconnected", callable_mp(this, &SceneTree::_network_peer_disconnected));
		multiplayer->disconnect("connected_to_server", callable_mp(this, &SceneTree::_connected_to_server));
		multiplayer->disconnect("connection_failed", callable_mp(this, &SceneTree::_connection_failed));
		multiplayer->disconnect("server_disconnected", callable_mp(this, &SceneTree::_server_disconnected));
	}

	multiplayer = p_multiplayer;
	multiplayer->set_root_node(root);

	multiplayer->connect("network_peer_connected", callable_mp(this, &SceneTree::_network_peer_connected));
	multiplayer->connect("network_peer_disconnected", callable_mp(this, &SceneTree::_network_peer_disconnected));
	multiplayer->connect("connected_to_server", callable_mp(this, &SceneTree::_connected_to_server));
	multiplayer->connect("connection_failed", callable_mp(this, &SceneTree::_connection_failed));
	multiplayer->connect("server_disconnected", callable_mp(this, &SceneTree::_server_disconnected));
}

void SceneTree::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_network_peer) {
	multiplayer->set_network_peer(p_network_peer);
}

Ref<NetworkedMultiplayerPeer> SceneTree::get_network_peer() const {
	return multiplayer->get_network_peer();
}

bool SceneTree::is_network_server() const {
	return multiplayer->is_network_server();
}

bool SceneTree::has_network_peer() const {
	return multiplayer->has_network_peer();
}

int SceneTree::get_network_unique_id() const {
	return multiplayer->get_network_unique_id();
}

Vector<int> SceneTree::get_network_connected_peers() const {
	return multiplayer->get_network_connected_peers();
}

int SceneTree::get_rpc_sender_id() const {
	return multiplayer->get_rpc_sender_id();
}

void SceneTree::set_refuse_new_network_connections(bool p_refuse) {
	multiplayer->set_refuse_new_network_connections(p_refuse);
}

bool SceneTree::is_refusing_new_network_connections() const {
	return multiplayer->is_refusing_new_network_connections();
}

void SceneTree::_bind_methods() {
	ClassDB::bind_method(D_METHOD("get_root"), &SceneTree::get_root);
	ClassDB::bind_method(D_METHOD("has_group", "name"), &SceneTree::has_group);

	ClassDB::bind_method(D_METHOD("set_auto_accept_quit", "enabled"), &SceneTree::set_auto_accept_quit);
	ClassDB::bind_method(D_METHOD("set_quit_on_go_back", "enabled"), &SceneTree::set_quit_on_go_back);

	ClassDB::bind_method(D_METHOD("set_debug_collisions_hint", "enable"), &SceneTree::set_debug_collisions_hint);
	ClassDB::bind_method(D_METHOD("is_debugging_collisions_hint"), &SceneTree::is_debugging_collisions_hint);
	ClassDB::bind_method(D_METHOD("set_debug_navigation_hint", "enable"), &SceneTree::set_debug_navigation_hint);
	ClassDB::bind_method(D_METHOD("is_debugging_navigation_hint"), &SceneTree::is_debugging_navigation_hint);

	ClassDB::bind_method(D_METHOD("set_edited_scene_root", "scene"), &SceneTree::set_edited_scene_root);
	ClassDB::bind_method(D_METHOD("get_edited_scene_root"), &SceneTree::get_edited_scene_root);

	ClassDB::bind_method(D_METHOD("set_pause", "enable"), &SceneTree::set_pause);
	ClassDB::bind_method(D_METHOD("is_paused"), &SceneTree::is_paused);

	ClassDB::bind_method(D_METHOD("create_timer", "time_sec", "pause_mode_process"), &SceneTree::create_timer, DEFVAL(true));

	ClassDB::bind_method(D_METHOD("get_node_count"), &SceneTree::get_node_count);
	ClassDB::bind_method(D_METHOD("get_frame"), &SceneTree::get_frame);
	ClassDB::bind_method(D_METHOD("quit", "exit_code"), &SceneTree::quit, DEFVAL(-1));

	ClassDB::bind_method(D_METHOD("queue_delete", "obj"), &SceneTree::queue_delete);

	MethodInfo mi;
	mi.name = "call_group_flags";
	mi.arguments.push_back(PropertyInfo(Variant::INT, "flags"));
	mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "group"));
	mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));

	ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group_flags", &SceneTree::_call_group_flags, mi);

	ClassDB::bind_method(D_METHOD("notify_group_flags", "call_flags", "group", "notification"), &SceneTree::notify_group_flags);
	ClassDB::bind_method(D_METHOD("set_group_flags", "call_flags", "group", "property", "value"), &SceneTree::set_group_flags);

	MethodInfo mi2;
	mi2.name = "call_group";
	mi2.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "group"));
	mi2.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));

	ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group", &SceneTree::_call_group, mi2);

	ClassDB::bind_method(D_METHOD("notify_group", "group", "notification"), &SceneTree::notify_group);
	ClassDB::bind_method(D_METHOD("set_group", "group", "property", "value"), &SceneTree::set_group);

	ClassDB::bind_method(D_METHOD("get_nodes_in_group", "group"), &SceneTree::_get_nodes_in_group);

	ClassDB::bind_method(D_METHOD("set_current_scene", "child_node"), &SceneTree::set_current_scene);
	ClassDB::bind_method(D_METHOD("get_current_scene"), &SceneTree::get_current_scene);

	ClassDB::bind_method(D_METHOD("change_scene", "path"), &SceneTree::change_scene);
	ClassDB::bind_method(D_METHOD("change_scene_to", "packed_scene"), &SceneTree::change_scene_to);

	ClassDB::bind_method(D_METHOD("reload_current_scene"), &SceneTree::reload_current_scene);

	ClassDB::bind_method(D_METHOD("_change_scene"), &SceneTree::_change_scene);

	ClassDB::bind_method(D_METHOD("set_multiplayer", "multiplayer"), &SceneTree::set_multiplayer);
	ClassDB::bind_method(D_METHOD("get_multiplayer"), &SceneTree::get_multiplayer);
	ClassDB::bind_method(D_METHOD("set_multiplayer_poll_enabled", "enabled"), &SceneTree::set_multiplayer_poll_enabled);
	ClassDB::bind_method(D_METHOD("is_multiplayer_poll_enabled"), &SceneTree::is_multiplayer_poll_enabled);
	ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &SceneTree::set_network_peer);
	ClassDB::bind_method(D_METHOD("get_network_peer"), &SceneTree::get_network_peer);
	ClassDB::bind_method(D_METHOD("is_network_server"), &SceneTree::is_network_server);
	ClassDB::bind_method(D_METHOD("has_network_peer"), &SceneTree::has_network_peer);
	ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &SceneTree::get_network_connected_peers);
	ClassDB::bind_method(D_METHOD("get_network_unique_id"), &SceneTree::get_network_unique_id);
	ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &SceneTree::get_rpc_sender_id);
	ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &SceneTree::set_refuse_new_network_connections);
	ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &SceneTree::is_refusing_new_network_connections);

	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_collisions_hint"), "set_debug_collisions_hint", "is_debugging_collisions_hint");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_navigation_hint"), "set_debug_navigation_hint", "is_debugging_navigation_hint");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "paused"), "set_pause", "is_paused");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
	ADD_PROPERTY_DEFAULT("refuse_new_network_connections", false);
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "edited_scene_root", PROPERTY_HINT_RESOURCE_TYPE, "Node", 0), "set_edited_scene_root", "get_edited_scene_root");
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "current_scene", PROPERTY_HINT_RESOURCE_TYPE, "Node", 0), "set_current_scene", "get_current_scene");
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", 0), "set_network_peer", "get_network_peer");
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "root", PROPERTY_HINT_RESOURCE_TYPE, "Node", 0), "", "get_root");
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "multiplayer", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerAPI", 0), "set_multiplayer", "get_multiplayer");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "multiplayer_poll"), "set_multiplayer_poll_enabled", "is_multiplayer_poll_enabled");

	ADD_SIGNAL(MethodInfo("tree_changed"));
	ADD_SIGNAL(MethodInfo("node_added", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
	ADD_SIGNAL(MethodInfo("node_removed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
	ADD_SIGNAL(MethodInfo("node_renamed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
	ADD_SIGNAL(MethodInfo("node_configuration_warning_changed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));

	ADD_SIGNAL(MethodInfo("process_frame"));
	ADD_SIGNAL(MethodInfo("physics_frame"));

	ADD_SIGNAL(MethodInfo("files_dropped", PropertyInfo(Variant::PACKED_STRING_ARRAY, "files"), PropertyInfo(Variant::INT, "screen")));
	ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
	ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
	ADD_SIGNAL(MethodInfo("connected_to_server"));
	ADD_SIGNAL(MethodInfo("connection_failed"));
	ADD_SIGNAL(MethodInfo("server_disconnected"));

	BIND_ENUM_CONSTANT(GROUP_CALL_DEFAULT);
	BIND_ENUM_CONSTANT(GROUP_CALL_REVERSE);
	BIND_ENUM_CONSTANT(GROUP_CALL_REALTIME);
	BIND_ENUM_CONSTANT(GROUP_CALL_UNIQUE);
}

SceneTree *SceneTree::singleton = nullptr;

SceneTree::IdleCallback SceneTree::idle_callbacks[SceneTree::MAX_IDLE_CALLBACKS];
int SceneTree::idle_callback_count = 0;

void SceneTree::_call_idle_callbacks() {
	for (int i = 0; i < idle_callback_count; i++) {
		idle_callbacks[i]();
	}
}

void SceneTree::add_idle_callback(IdleCallback p_callback) {
	ERR_FAIL_COND(idle_callback_count >= MAX_IDLE_CALLBACKS);
	idle_callbacks[idle_callback_count++] = p_callback;
}

void SceneTree::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
	if (p_function == "change_scene") {
		DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES);
		List<String> directories;
		directories.push_back(dir_access->get_current_dir());

		while (!directories.is_empty()) {
			dir_access->change_dir(directories.back()->get());
			directories.pop_back();

			dir_access->list_dir_begin();
			String filename = dir_access->get_next();

			while (filename != "") {
				if (filename == "." || filename == "..") {
					filename = dir_access->get_next();
					continue;
				}

				if (dir_access->dir_exists(filename)) {
					directories.push_back(dir_access->get_current_dir().plus_file(filename));
				} else if (filename.ends_with(".tscn") || filename.ends_with(".scn")) {
					r_options->push_back("\"" + dir_access->get_current_dir().plus_file(filename) + "\"");
				}

				filename = dir_access->get_next();
			}
		}
	}
}

SceneTree::SceneTree() {
	if (singleton == nullptr) {
		singleton = this;
	}
	debug_collisions_color = GLOBAL_DEF("debug/shapes/collision/shape_color", Color(0.0, 0.6, 0.7, 0.5));
	debug_collision_contact_color = GLOBAL_DEF("debug/shapes/collision/contact_color", Color(1.0, 0.2, 0.1, 0.8));
	debug_navigation_color = GLOBAL_DEF("debug/shapes/navigation/geometry_color", Color(0.1, 1.0, 0.7, 0.4));
	debug_navigation_disabled_color = GLOBAL_DEF("debug/shapes/navigation/disabled_geometry_color", Color(1.0, 0.7, 0.1, 0.4));
	collision_debug_contacts = GLOBAL_DEF("debug/shapes/collision/max_contacts_displayed", 10000);
	ProjectSettings::get_singleton()->set_custom_property_info("debug/shapes/collision/max_contacts_displayed", PropertyInfo(Variant::INT, "debug/shapes/collision/max_contacts_displayed", PROPERTY_HINT_RANGE, "0,20000,1")); // No negative

	// Create with mainloop.

	root = memnew(Window);
	root->set_name("root");
	if (!root->get_world_3d().is_valid()) {
		root->set_world_3d(Ref<World3D>(memnew(World3D)));
	}

	// Initialize network state.
	set_multiplayer(Ref<MultiplayerAPI>(memnew(MultiplayerAPI)));

	//root->set_world_2d( Ref<World2D>( memnew( World2D )));
	root->set_as_audio_listener(true);
	root->set_as_audio_listener_2d(true);
	current_scene = nullptr;

	const int msaa_mode = GLOBAL_DEF("rendering/quality/screen_filters/msaa", 0);
	ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/screen_filters/msaa", PropertyInfo(Variant::INT, "rendering/quality/screen_filters/msaa", PROPERTY_HINT_ENUM, "Disabled (Fastest),2x (Fast),4x (Average),8x (Slow),16x (Slower)"));
	root->set_msaa(Viewport::MSAA(msaa_mode));

	const int ssaa_mode = GLOBAL_DEF("rendering/quality/screen_filters/screen_space_aa", 0);
	ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/screen_filters/screen_space_aa", PropertyInfo(Variant::INT, "rendering/quality/screen_filters/screen_space_aa", PROPERTY_HINT_ENUM, "Disabled (Fastest),FXAA (Fast)"));
	root->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode));

	const bool use_debanding = GLOBAL_DEF("rendering/quality/screen_filters/use_debanding", false);
	root->set_use_debanding(use_debanding);

	float lod_threshold = GLOBAL_DEF("rendering/quality/mesh_lod/threshold_pixels", 1.0);
	ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/mesh_lod/threshold_pixels", PropertyInfo(Variant::FLOAT, "rendering/quality/mesh_lod/threshold_pixels", PROPERTY_HINT_RANGE, "0,1024,0.1"));
	root->set_lod_threshold(lod_threshold);

	bool snap_2d_transforms = GLOBAL_DEF("rendering/quality/2d/snap_2d_transforms_to_pixel", false);
	root->set_snap_2d_transforms_to_pixel(snap_2d_transforms);

	bool snap_2d_vertices = GLOBAL_DEF("rendering/quality/2d/snap_2d_vertices_to_pixel", false);
	root->set_snap_2d_vertices_to_pixel(snap_2d_vertices);

	Viewport::SDFOversize sdf_oversize = Viewport::SDFOversize(int(GLOBAL_DEF("rendering/quality/2d_sdf/oversize", 1)));
	root->set_sdf_oversize(sdf_oversize);
	Viewport::SDFScale sdf_scale = Viewport::SDFScale(int(GLOBAL_DEF("rendering/quality/2d_sdf/scale", 1)));
	root->set_sdf_scale(sdf_scale);

	ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/2d_sdf/oversize", PropertyInfo(Variant::INT, "rendering/quality/2d_sdf/oversize", PROPERTY_HINT_ENUM, "100%,120%,150%,200%"));
	ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/2d_sdf/scale", PropertyInfo(Variant::INT, "rendering/quality/2d_sdf/scale", PROPERTY_HINT_ENUM, "100%,50%,25%"));

	{ // Load default fallback environment.
		// Get possible extensions.
		List<String> exts;
		ResourceLoader::get_recognized_extensions_for_type("Environment", &exts);
		String ext_hint;
		for (List<String>::Element *E = exts.front(); E; E = E->next()) {
			if (ext_hint != String()) {
				ext_hint += ",";
			}
			ext_hint += "*." + E->get();
		}
		// Get path.
		String env_path = GLOBAL_DEF("rendering/environment/default_environment", "");
		// Setup property.
		ProjectSettings::get_singleton()->set_custom_property_info("rendering/environment/default_environment", PropertyInfo(Variant::STRING, "rendering/viewport/default_environment", PROPERTY_HINT_FILE, ext_hint));
		env_path = env_path.strip_edges();
		if (env_path != String()) {
			Ref<Environment> env = ResourceLoader::load(env_path);
			if (env.is_valid()) {
				root->get_world_3d()->set_fallback_environment(env);
			} else {
				if (Engine::get_singleton()->is_editor_hint()) {
					// File was erased, clear the field.
					ProjectSettings::get_singleton()->set("rendering/environment/default_environment", "");
				} else {
					// File was erased, notify user.
					ERR_PRINT(RTR("Default Environment as specified in Project Settings (Rendering -> Environment -> Default Environment) could not be loaded."));
				}
			}
		}
	}

	root->set_physics_object_picking(GLOBAL_DEF("physics/common/enable_object_picking", true));

	root->connect("close_requested", callable_mp(this, &SceneTree::_main_window_close));
	root->connect("go_back_requested", callable_mp(this, &SceneTree::_main_window_go_back));
	root->connect("focus_entered", callable_mp(this, &SceneTree::_main_window_focus_in));

#ifdef TOOLS_ENABLED
	edited_scene_root = nullptr;
#endif
}

SceneTree::~SceneTree() {
	if (root) {
		root->_set_tree(nullptr);
		root->_propagate_after_exit_tree();
		memdelete(root);
	}

	if (singleton == this) {
		singleton = nullptr;
	}
}