fyrox_impl/scene/graph/
mod.rs

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
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
//! Contains all methods and structures to create and manage scene graphs.
//!
//! Scene graph is the foundation of the engine. Graph is a hierarchical data
//! structure where each element called node. Each node can have zero to one parent
//! node, and any children nodes. Node with no parent node called root, with no
//! children nodes - leaf. Graphical representation can be something like this:
//!
//! ```text
//!     Root____
//!       |    |
//!       D    A___
//!       |    |  |
//!       E    C  B
//!     ............
//! ```
//!
//! This picture clearly shows relations between nodes. Such structure allows us
//! to create scenes of any complexity by just linking nodes with each other.
//! Connections between nodes are used to traverse tree, to calculate global
//! transforms, global visibility and many other things. Most interesting here -
//! is global transform calculation - it allows you to produce complex movements
//! just by linking nodes to each other. Good example of this is skeleton which
//! is used in skinning (animating 3d model by set of bones).

use crate::{
    asset::{manager::ResourceManager, untyped::UntypedResource},
    core::{
        algebra::{Matrix4, Rotation3, UnitQuaternion, Vector2, Vector3},
        instant,
        log::{Log, MessageKind},
        math::{aabb::AxisAlignedBoundingBox, Matrix4Ext},
        pool::{ErasedHandle, Handle, MultiBorrowContext, Pool, Ticket},
        reflect::prelude::*,
        sstorage::ImmutableString,
        visitor::{Visit, VisitResult, Visitor},
    },
    graph::{AbstractSceneGraph, AbstractSceneNode, BaseSceneGraph, NodeHandleMap, SceneGraph},
    material::{shader::SamplerFallback, MaterialResource, PropertyValue},
    resource::model::{Model, ModelResource, ModelResourceExtension},
    scene::{
        base::{NodeScriptMessage, SceneNodeId},
        camera::Camera,
        dim2::{self},
        graph::{
            event::{GraphEvent, GraphEventBroadcaster},
            physics::{PhysicsPerformanceStatistics, PhysicsWorld},
        },
        mesh::Mesh,
        navmesh,
        node::{container::NodeContainer, Node, NodeTrait, SyncContext, UpdateContext},
        pivot::Pivot,
        sound::context::SoundContext,
        transform::TransformBuilder,
    },
    script::ScriptTrait,
    utils::lightmap::{self, Lightmap},
};
use fxhash::{FxHashMap, FxHashSet};
use std::{
    any::{Any, TypeId},
    fmt::Debug,
    ops::{Index, IndexMut},
    sync::mpsc::{channel, Receiver, Sender},
    time::Duration,
};

pub mod event;
pub mod physics;

/// Graph performance statistics. Allows you to find out "hot" parts of the scene graph, which
/// parts takes the most time to update.
#[derive(Clone, Default, Debug)]
pub struct GraphPerformanceStatistics {
    /// Amount of time that was needed to update global transform, visibility, and every other
    /// property of every object which depends on the state of a parent node.
    pub hierarchical_properties_time: Duration,

    /// Amount of time that was needed to synchronize state of the graph with the state of
    /// backing native objects (Rapier's rigid bodies, colliders, joints, sound sources, etc.)
    pub sync_time: Duration,

    /// Physics performance statistics.
    pub physics: PhysicsPerformanceStatistics,

    /// 2D Physics performance statistics.
    pub physics2d: PhysicsPerformanceStatistics,

    /// A time which was required to render sounds.
    pub sound_update_time: Duration,
}

impl GraphPerformanceStatistics {
    /// Returns total amount of time.
    pub fn total(&self) -> Duration {
        self.hierarchical_properties_time
            + self.sync_time
            + self.physics.total()
            + self.physics2d.total()
            + self.sound_update_time
    }
}

/// A helper type alias for node pool.
pub type NodePool = Pool<Node, NodeContainer>;

/// See module docs.
#[derive(Debug, Reflect)]
pub struct Graph {
    #[reflect(hidden)]
    root: Handle<Node>,

    pool: NodePool,

    #[reflect(hidden)]
    stack: Vec<Handle<Node>>,

    /// Backing physics "world". It is responsible for the physics simulation.
    pub physics: PhysicsWorld,

    /// Backing 2D physics "world". It is responsible for the 2D physics simulation.
    pub physics2d: dim2::physics::PhysicsWorld,

    /// Backing sound context. It is responsible for sound rendering.
    #[reflect(hidden)]
    pub sound_context: SoundContext,

    /// Performance statistics of a last [`Graph::update`] call.
    #[reflect(hidden)]
    pub performance_statistics: GraphPerformanceStatistics,

    /// Allows you to "subscribe" for graph events.
    #[reflect(hidden)]
    pub event_broadcaster: GraphEventBroadcaster,

    /// Current lightmap.
    lightmap: Option<Lightmap>,

    #[reflect(hidden)]
    pub(crate) script_message_sender: Sender<NodeScriptMessage>,
    #[reflect(hidden)]
    pub(crate) script_message_receiver: Receiver<NodeScriptMessage>,

    instance_id_map: FxHashMap<SceneNodeId, Handle<Node>>,
}

impl Default for Graph {
    fn default() -> Self {
        let (tx, rx) = channel();

        Self {
            physics: PhysicsWorld::new(),
            physics2d: dim2::physics::PhysicsWorld::new(),
            root: Handle::NONE,
            pool: Pool::new(),
            stack: Vec::new(),
            sound_context: Default::default(),
            performance_statistics: Default::default(),
            event_broadcaster: Default::default(),
            script_message_receiver: rx,
            script_message_sender: tx,
            lightmap: None,
            instance_id_map: Default::default(),
        }
    }
}

/// Sub-graph is a piece of graph that was extracted from a graph. It has ownership
/// over its nodes. It is used to temporarily take ownership of a sub-graph. This could
/// be used if you making a scene editor with a command stack - once you reverted a command,
/// that created a complex nodes hierarchy (for example you loaded a model) you must store
/// all added nodes somewhere to be able put nodes back into graph when user decide to re-do
/// command. Sub-graph allows you to do this without invalidating handles to nodes.
#[derive(Debug)]
pub struct SubGraph {
    /// A root node and its [ticket](/fyrox-core/model/struct.Ticket.html).
    pub root: (Ticket<Node>, Node),

    /// A set of descendant nodes with their tickets.
    pub descendants: Vec<(Ticket<Node>, Node)>,

    /// A handle to the parent node from which the sub-graph was extracted (it it parent node of
    /// the root of this sub-graph).
    pub parent: Handle<Node>,
}

fn remap_handles(old_new_mapping: &NodeHandleMap<Node>, dest_graph: &mut Graph) {
    // Iterate over instantiated nodes and remap handles.
    for (_, &new_node_handle) in old_new_mapping.inner().iter() {
        old_new_mapping.remap_handles(
            &mut dest_graph.pool[new_node_handle],
            &[TypeId::of::<UntypedResource>()],
        );
    }
}

fn isometric_local_transform(nodes: &NodePool, node: Handle<Node>) -> Matrix4<f32> {
    let transform = nodes[node].local_transform();
    TransformBuilder::new()
        .with_local_position(**transform.position())
        .with_local_rotation(**transform.rotation())
        .with_pre_rotation(**transform.pre_rotation())
        .with_post_rotation(**transform.post_rotation())
        .build()
        .matrix()
}

fn isometric_global_transform(nodes: &NodePool, node: Handle<Node>) -> Matrix4<f32> {
    let parent = nodes[node].parent();
    if parent.is_some() {
        isometric_global_transform(nodes, parent) * isometric_local_transform(nodes, node)
    } else {
        isometric_local_transform(nodes, node)
    }
}

// Clears all information about parent-child relations of a given node. This is needed in some
// cases (mostly when copying a node), because `Graph::add_node` uses children list to attach
// children to the given node, and when copying a node it is important that this step is skipped.
fn clear_links(mut node: Node) -> Node {
    node.children.clear();
    node.parent = Handle::NONE;
    node
}

/// A set of switches that allows you to disable a particular step of graph update pipeline.
#[derive(Clone, PartialEq, Eq)]
pub struct GraphUpdateSwitches {
    /// Enables or disables update of the 2D physics.
    pub physics2d: bool,
    /// Enables or disables update of the 3D physics.
    pub physics: bool,
    /// A set of nodes that will be updated, everything else won't be updated.
    pub node_overrides: Option<FxHashSet<Handle<Node>>>,
    /// Enables or disables deletion of the nodes with ended lifetime (lifetime <= 0.0). If set to `false` the lifetime
    /// of the nodes won't be changed.
    pub delete_dead_nodes: bool,
    /// Whether the graph update is paused or not. Paused graphs won't be updated and their sound content will be also paused
    /// so it won't emit any sounds.
    pub paused: bool,
}

impl Default for GraphUpdateSwitches {
    fn default() -> Self {
        Self {
            physics2d: true,
            physics: true,
            node_overrides: Default::default(),
            delete_dead_nodes: true,
            paused: false,
        }
    }
}

impl Graph {
    /// Creates new graph instance with single root node.
    #[inline]
    pub fn new() -> Self {
        let (tx, rx) = channel();

        // Create root node.
        let mut root_node = Pivot::default();
        let instance_id = root_node.instance_id;
        root_node.script_message_sender = Some(tx.clone());
        root_node.set_name("__ROOT__");

        // Add it to the pool.
        let mut pool = Pool::new();
        let root = pool.spawn(Node::new(root_node));
        pool[root].self_handle = root;

        let instance_id_map = FxHashMap::from_iter([(instance_id, root)]);

        Self {
            physics: Default::default(),
            stack: Vec::new(),
            root,
            pool,
            physics2d: Default::default(),
            sound_context: SoundContext::new(),
            performance_statistics: Default::default(),
            event_broadcaster: Default::default(),
            script_message_receiver: rx,
            script_message_sender: tx,
            lightmap: None,
            instance_id_map,
        }
    }

    /// Creates a new graph using a hierarchy of nodes specified by the `root`.
    pub fn from_hierarchy(root: Handle<Node>, other_graph: &Self) -> Self {
        let mut graph = Self::default();
        other_graph.copy_node(
            root,
            &mut graph,
            &mut |_, _| true,
            &mut |_, _| {},
            &mut |_, _, _| {},
        );
        graph
    }

    /// Sets new root of the graph and attaches the old root to the new root. Old root becomes a child
    /// node of the new root.
    pub fn change_root_node(&mut self, root: Node) {
        let prev_root = self.root;
        self.root = Handle::NONE;
        let handle = self.add_node(root);
        assert_eq!(self.root, handle);
        self.link_nodes(prev_root, handle);
    }

    /// Tries to find references of the given node in other scene nodes. It could be used to check if the node is
    /// used by some other scene node or not. Returns an array of nodes, that references the given node. This method
    /// is reflection-based, so it is quite slow and should not be used every frame.
    pub fn find_references_to(&self, target: Handle<Node>) -> Vec<Handle<Node>> {
        let mut references = Vec::new();
        for (node_handle, node) in self.pair_iter() {
            (node as &dyn Reflect).apply_recursively(
                &mut |object| {
                    object.as_any(&mut |any| {
                        if let Some(handle) = any.downcast_ref::<Handle<Node>>() {
                            if *handle == target {
                                references.push(node_handle);
                            }
                        }
                    })
                },
                &[],
            );
        }
        references
    }

    /// Tries to borrow mutable references to two nodes at the same time by given handles. Will
    /// panic if handles overlaps (points to same node).
    #[inline]
    pub fn get_two_mut(&mut self, nodes: (Handle<Node>, Handle<Node>)) -> (&mut Node, &mut Node) {
        self.pool.borrow_two_mut(nodes)
    }

    /// Tries to borrow mutable references to three nodes at the same time by given handles. Will
    /// return Err of handles overlaps (points to same node).
    #[inline]
    pub fn get_three_mut(
        &mut self,
        nodes: (Handle<Node>, Handle<Node>, Handle<Node>),
    ) -> (&mut Node, &mut Node, &mut Node) {
        self.pool.borrow_three_mut(nodes)
    }

    /// Tries to borrow mutable references to four nodes at the same time by given handles. Will
    /// panic if handles overlaps (points to same node).
    #[inline]
    pub fn get_four_mut(
        &mut self,
        nodes: (Handle<Node>, Handle<Node>, Handle<Node>, Handle<Node>),
    ) -> (&mut Node, &mut Node, &mut Node, &mut Node) {
        self.pool.borrow_four_mut(nodes)
    }

    /// Returns root node of current graph.
    #[inline]
    pub fn get_root(&self) -> Handle<Node> {
        self.root
    }

    /// Tries to mutably borrow a node, returns Some(node) if the handle is valid, None - otherwise.
    #[inline]
    pub fn try_get_mut(&mut self, handle: Handle<Node>) -> Option<&mut Node> {
        self.pool.try_borrow_mut(handle)
    }

    /// Begins multi-borrow that allows you borrow to as many shared references to the graph
    /// nodes as you need and only one mutable reference to a node. See
    /// [`MultiBorrowContext::try_get`] for more info.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// # use fyrox_impl::{
    /// #     core::pool::Handle,
    /// #     scene::{base::BaseBuilder, graph::Graph, node::Node, pivot::PivotBuilder},
    /// # };
    /// #
    /// let mut graph = Graph::new();
    ///
    /// let handle1 = PivotBuilder::new(BaseBuilder::new()).build(&mut graph);
    /// let handle2 = PivotBuilder::new(BaseBuilder::new()).build(&mut graph);
    /// let handle3 = PivotBuilder::new(BaseBuilder::new()).build(&mut graph);
    /// let handle4 = PivotBuilder::new(BaseBuilder::new()).build(&mut graph);
    ///
    /// let mut ctx = graph.begin_multi_borrow();
    ///
    /// let node1 = ctx.try_get(handle1);
    /// let node2 = ctx.try_get(handle2);
    /// let node3 = ctx.try_get(handle3);
    /// let node4 = ctx.try_get(handle4);
    ///
    /// assert!(node1.is_ok());
    /// assert!(node2.is_ok());
    /// assert!(node3.is_ok());
    /// assert!(node4.is_ok());
    ///
    /// // An attempt to borrow the same node twice as immutable and mutable will fail.
    /// assert!(ctx.try_get_mut(handle1).is_err());
    /// ```
    #[inline]
    pub fn begin_multi_borrow(&mut self) -> MultiBorrowContext<Node, NodeContainer> {
        self.pool.begin_multi_borrow()
    }

    /// Links specified child with specified parent while keeping the
    /// child's global position and rotation.
    #[inline]
    pub fn link_nodes_keep_global_position_rotation(
        &mut self,
        child: Handle<Node>,
        parent: Handle<Node>,
    ) {
        let parent_transform_inv = self.pool[parent]
            .global_transform()
            .try_inverse()
            .unwrap_or_default();
        let child_transform = self.pool[child].global_transform();
        let relative_transform = parent_transform_inv * child_transform;
        let local_position = relative_transform.position();
        let local_rotation = UnitQuaternion::from_matrix(&relative_transform.basis());
        self.pool[child]
            .local_transform_mut()
            .set_position(local_position)
            .set_rotation(local_rotation);
        self.link_nodes(child, parent);
    }

    /// Searches for a **first** node with a script of the given type `S` in the hierarchy starting from the
    /// given `root_node`.
    #[inline]
    pub fn find_first_by_script<S>(&self, root_node: Handle<Node>) -> Option<(Handle<Node>, &Node)>
    where
        S: ScriptTrait,
    {
        self.find(root_node, &mut |node| {
            for script in &node.scripts {
                if script.as_ref().and_then(|s| s.cast::<S>()).is_some() {
                    return true;
                }
            }
            false
        })
    }

    /// Creates deep copy of node with all children. This is relatively heavy operation!
    /// In case if any error happened it returns `Handle::NONE`. This method can be used
    /// to create exact copy of given node hierarchy. For example you can prepare rocket
    /// model: case of rocket will be mesh, and fire from nozzle will be particle system,
    /// and when you fire from rocket launcher you just need to create a copy of such
    /// "prefab".
    ///
    /// # Implementation notes
    ///
    /// Returns tuple where first element is handle to copy of node, and second element -
    /// old-to-new hash map, which can be used to easily find copy of node by its original.
    ///
    /// Filter allows to exclude some nodes from copied hierarchy. It must return false for
    /// odd nodes. Filtering applied only to descendant nodes.
    #[inline]
    pub fn copy_node<F, Pre, Post>(
        &self,
        node_handle: Handle<Node>,
        dest_graph: &mut Graph,
        filter: &mut F,
        pre_process_callback: &mut Pre,
        post_process_callback: &mut Post,
    ) -> (Handle<Node>, NodeHandleMap<Node>)
    where
        F: FnMut(Handle<Node>, &Node) -> bool,
        Pre: FnMut(Handle<Node>, &mut Node),
        Post: FnMut(Handle<Node>, Handle<Node>, &mut Node),
    {
        let mut old_new_mapping = NodeHandleMap::default();
        let root_handle = self.copy_node_raw(
            node_handle,
            dest_graph,
            &mut old_new_mapping,
            filter,
            pre_process_callback,
            post_process_callback,
        );

        remap_handles(&old_new_mapping, dest_graph);

        (root_handle, old_new_mapping)
    }

    /// Creates deep copy of node with all children. This is relatively heavy operation!
    /// In case if any error happened it returns `Handle::NONE`. This method can be used
    /// to create exact copy of given node hierarchy. For example you can prepare rocket
    /// model: case of rocket will be mesh, and fire from nozzle will be particle system,
    /// and when you fire from rocket launcher you just need to create a copy of such
    /// "prefab".
    ///
    /// # Implementation notes
    ///
    /// Returns tuple where first element is handle to copy of node, and second element -
    /// old-to-new hash map, which can be used to easily find copy of node by its original.
    ///
    /// Filter allows to exclude some nodes from copied hierarchy. It must return false for
    /// odd nodes. Filtering applied only to descendant nodes.
    #[inline]
    pub fn copy_node_inplace<F>(
        &mut self,
        node_handle: Handle<Node>,
        filter: &mut F,
    ) -> (Handle<Node>, NodeHandleMap<Node>)
    where
        F: FnMut(Handle<Node>, &Node) -> bool,
    {
        let mut old_new_mapping = NodeHandleMap::default();

        let to_copy = self
            .traverse_handle_iter(node_handle)
            .map(|node| (node, self.pool[node].children.clone()))
            .collect::<Vec<_>>();

        let mut root_handle = Handle::NONE;

        for (parent, children) in to_copy.iter() {
            // Copy parent first.
            let parent_copy = clear_links(self.pool[*parent].clone_box());
            let parent_copy_handle = self.add_node(parent_copy);
            old_new_mapping.insert(*parent, parent_copy_handle);

            if root_handle.is_none() {
                root_handle = parent_copy_handle;
            }

            // Copy children and link to new parent.
            for &child in children {
                if filter(child, &self.pool[child]) {
                    let child_copy = clear_links(self.pool[child].clone_box());
                    let child_copy_handle = self.add_node(child_copy);
                    old_new_mapping.insert(child, child_copy_handle);
                    self.link_nodes(child_copy_handle, parent_copy_handle);
                }
            }
        }

        remap_handles(&old_new_mapping, self);

        (root_handle, old_new_mapping)
    }

    /// Creates copy of a node and breaks all connections with other nodes. Keep in mind that
    /// this method may give unexpected results when the node has connections with other nodes.
    /// For example if you'll try to copy a skinned mesh, its copy won't be skinned anymore -
    /// you'll get just a "shallow" mesh. Also unlike [copy_node](struct.Graph.html#method.copy_node)
    /// this method returns copied node directly, it does not inserts it in any graph.
    #[inline]
    pub fn copy_single_node(&self, node_handle: Handle<Node>) -> Node {
        let node = &self.pool[node_handle];
        let mut clone = clear_links(node.clone_box());
        if let Some(ref mut mesh) = clone.cast_mut::<Mesh>() {
            for surface in mesh.surfaces_mut() {
                surface.bones.clear();
            }
        }
        clone
    }

    fn copy_node_raw<F, Pre, Post>(
        &self,
        root_handle: Handle<Node>,
        dest_graph: &mut Graph,
        old_new_mapping: &mut NodeHandleMap<Node>,
        filter: &mut F,
        pre_process_callback: &mut Pre,
        post_process_callback: &mut Post,
    ) -> Handle<Node>
    where
        F: FnMut(Handle<Node>, &Node) -> bool,
        Pre: FnMut(Handle<Node>, &mut Node),
        Post: FnMut(Handle<Node>, Handle<Node>, &mut Node),
    {
        let src_node = &self.pool[root_handle];
        let mut dest_node = clear_links(src_node.clone_box());
        pre_process_callback(root_handle, &mut dest_node);
        let dest_copy_handle = dest_graph.add_node(dest_node);
        old_new_mapping.insert(root_handle, dest_copy_handle);
        for &src_child_handle in src_node.children() {
            if filter(src_child_handle, &self.pool[src_child_handle]) {
                let dest_child_handle = self.copy_node_raw(
                    src_child_handle,
                    dest_graph,
                    old_new_mapping,
                    filter,
                    pre_process_callback,
                    post_process_callback,
                );
                if !dest_child_handle.is_none() {
                    dest_graph.link_nodes(dest_child_handle, dest_copy_handle);
                }
            }
        }
        post_process_callback(
            dest_copy_handle,
            root_handle,
            &mut dest_graph[dest_copy_handle],
        );
        dest_copy_handle
    }

    fn restore_dynamic_node_data(&mut self) {
        for (handle, node) in self.pool.pair_iter_mut() {
            node.self_handle = handle;
            node.script_message_sender = Some(self.script_message_sender.clone());
        }
    }

    // Fix property flags for scenes made before inheritance system was fixed. By default, all inheritable properties
    // must be marked as modified in nodes without any parent resource.
    pub(crate) fn mark_ancestor_nodes_as_modified(&mut self) {
        for node in self.linear_iter_mut() {
            if node.resource.is_none() {
                node.mark_inheritable_variables_as_modified();
            }
        }
    }

    pub(crate) fn resolve(&mut self, resource_manager: &ResourceManager) {
        Log::writeln(MessageKind::Information, "Resolving graph...");

        self.restore_dynamic_node_data();
        self.mark_ancestor_nodes_as_modified();
        self.restore_original_handles_and_inherit_properties(
            &[TypeId::of::<navmesh::Container>()],
            |resource_node, node| {
                node.inv_bind_pose_transform = resource_node.inv_bind_pose_transform;
            },
        );
        self.update_hierarchical_data();
        let instances = self.restore_integrity(|model, model_data, handle, dest_graph| {
            ModelResource::instantiate_from(model, model_data, handle, dest_graph, &mut |_, _| {})
        });
        self.remap_handles(&instances);

        // Update cube maps for sky boxes.
        for node in self.linear_iter_mut() {
            if let Some(camera) = node.cast_mut::<Camera>() {
                if let Some(skybox) = camera.skybox_mut() {
                    Log::verify(skybox.create_cubemap());
                }
            }
        }

        // Sync materials with shaders.
        let mut materials = FxHashSet::default();
        for node in self.linear_iter_mut() {
            (node as &mut dyn Reflect).enumerate_fields_recursively(
                &mut |_, _, v| {
                    v.downcast_ref::<MaterialResource>(&mut |material| {
                        if let Some(material) = material {
                            materials.insert(material.clone());
                        }
                    })
                },
                &[TypeId::of::<UntypedResource>()],
            );
        }

        for material in materials {
            let mut material_state = material.state();
            if let Some(material) = material_state.data() {
                material.sync_to_shader(resource_manager);
            }
        }

        self.apply_lightmap();

        Log::writeln(MessageKind::Information, "Graph resolved successfully!");
    }

    /// Tries to set new lightmap to scene.
    pub fn set_lightmap(&mut self, lightmap: Lightmap) -> Result<Option<Lightmap>, &'static str> {
        // Assign textures to surfaces.
        for (handle, lightmaps) in lightmap.map.iter() {
            if let Some(mesh) = self[*handle].cast_mut::<Mesh>() {
                if mesh.surfaces().len() != lightmaps.len() {
                    return Err("failed to set lightmap, surface count mismatch");
                }

                for (surface, entry) in mesh.surfaces_mut().iter_mut().zip(lightmaps) {
                    // This unwrap() call must never panic in normal conditions, because texture wrapped in Option
                    // only to implement Default trait to be serializable.
                    let texture = entry.texture.clone().unwrap();
                    let mut material_state = surface.material().state();
                    if let Some(material) = material_state.data() {
                        if let Err(e) = material.set_property(
                            &ImmutableString::new("lightmapTexture"),
                            PropertyValue::Sampler {
                                value: Some(texture),
                                fallback: SamplerFallback::Black,
                            },
                        ) {
                            Log::writeln(
                                MessageKind::Error,
                                format!(
                                    "Failed to apply light map texture to material. Reason {:?}",
                                    e
                                ),
                            )
                        }
                    }
                }
            }
        }
        Ok(std::mem::replace(&mut self.lightmap, Some(lightmap)))
    }

    /// Returns current lightmap.
    pub fn lightmap(&self) -> Option<&Lightmap> {
        self.lightmap.as_ref()
    }

    fn apply_lightmap(&mut self) {
        // Re-apply lightmap if any. This has to be done after resolve because we must patch surface
        // data at this stage, but if we'd do this before we wouldn't be able to do this because
        // meshes contains invalid surface data.
        if let Some(lightmap) = self.lightmap.as_mut() {
            // Patch surface data first. To do this we gather all surface data instances and
            // look in patch data if we have patch for data.
            let mut unique_data_set = FxHashMap::default();
            for &handle in lightmap.map.keys() {
                if let Some(mesh) = self.pool[handle].cast_mut::<Mesh>() {
                    for surface in mesh.surfaces() {
                        let data = surface.data();
                        unique_data_set.entry(data.key()).or_insert(data);
                    }
                }
            }

            for (_, data) in unique_data_set.into_iter() {
                let mut data = data.lock();

                if let Some(patch) = lightmap.patches.get(&data.content_hash()) {
                    lightmap::apply_surface_data_patch(&mut data, &patch.0);
                } else {
                    Log::writeln(
                        MessageKind::Warning,
                        "Failed to get surface data patch while resolving lightmap!\
                    This means that surface has changed and lightmap must be regenerated!",
                    );
                }
            }

            // Apply textures.
            for (&handle, entries) in lightmap.map.iter_mut() {
                if let Some(mesh) = self.pool[handle].cast_mut::<Mesh>() {
                    for (entry, surface) in entries.iter_mut().zip(mesh.surfaces_mut()) {
                        let mut material_state = surface.material().state();
                        if let Some(material) = material_state.data() {
                            if let Err(e) = material.set_property(
                                &ImmutableString::new("lightmapTexture"),
                                PropertyValue::Sampler {
                                    value: entry.texture.clone(),
                                    fallback: SamplerFallback::Black,
                                },
                            ) {
                                Log::writeln(
                                    MessageKind::Error,
                                    format!(
                                    "Failed to apply light map texture to material. Reason {:?}",
                                    e
                                ),
                                )
                            }
                        }
                    }
                }
            }
        }
    }

    pub(crate) fn update_hierarchical_data_recursively(
        nodes: &NodePool,
        sound_context: &mut SoundContext,
        physics: &mut PhysicsWorld,
        physics2d: &mut dim2::physics::PhysicsWorld,
        node_handle: Handle<Node>,
    ) {
        let node = &nodes[node_handle];

        let (parent_global_transform, parent_visibility, parent_enabled) =
            if let Some(parent) = nodes.try_borrow(node.parent()) {
                (
                    parent.global_transform(),
                    parent.global_visibility(),
                    parent.is_globally_enabled(),
                )
            } else {
                (Matrix4::identity(), true, true)
            };

        let new_global_transform = parent_global_transform * node.local_transform().matrix();

        // TODO: Detect changes from user code here.
        node.sync_transform(
            &new_global_transform,
            &mut SyncContext {
                nodes,
                physics,
                physics2d,
                sound_context,
                switches: None,
            },
        );

        node.global_transform.set(new_global_transform);
        node.global_visibility
            .set(parent_visibility && node.visibility());
        node.global_enabled.set(parent_enabled && node.is_enabled());

        for &child in node.children() {
            Self::update_hierarchical_data_recursively(
                nodes,
                sound_context,
                physics,
                physics2d,
                child,
            );
        }
    }

    /// Tries to compute combined axis-aligned bounding box (AABB) in world-space of the hierarchy starting from the given
    /// scene node. It will return [`None`] if the scene node handle is invalid, otherwise it will return AABB that enclosing
    /// all the nodes in the hierarchy.
    pub fn aabb_of_descendants<F>(
        &self,
        root: Handle<Node>,
        mut filter: F,
    ) -> Option<AxisAlignedBoundingBox>
    where
        F: FnMut(Handle<Node>, &Node) -> bool,
    {
        fn aabb_of_descendants_recursive<F>(
            graph: &Graph,
            node: Handle<Node>,
            filter: &mut F,
        ) -> Option<AxisAlignedBoundingBox>
        where
            F: FnMut(Handle<Node>, &Node) -> bool,
        {
            graph.try_get(node).and_then(|n| {
                if filter(node, n) {
                    let mut aabb = n.local_bounding_box();
                    if aabb.is_invalid_or_degenerate() {
                        aabb = AxisAlignedBoundingBox::collapsed().transform(&n.global_transform());
                    } else {
                        aabb = aabb.transform(&n.global_transform());
                    }
                    for child in n.children() {
                        if let Some(child_aabb) =
                            aabb_of_descendants_recursive(graph, *child, filter)
                        {
                            aabb.add_box(child_aabb);
                        }
                    }
                    Some(aabb)
                } else {
                    None
                }
            })
        }
        aabb_of_descendants_recursive(self, root, &mut filter)
    }

    /// Calculates local and global transform, global visibility for each node in graph starting from the
    /// specified node and down the tree. The main use case of the method is to update global position (etc.)
    /// of an hierarchy of the nodes of some new prefab instance.
    #[inline]
    pub fn update_hierarchical_data_for_descendants(&mut self, node_handle: Handle<Node>) {
        Self::update_hierarchical_data_recursively(
            &self.pool,
            &mut self.sound_context,
            &mut self.physics,
            &mut self.physics2d,
            node_handle,
        );
    }

    /// Calculates local and global transform, global visibility for each node in graph.
    /// Normally you not need to call this method directly, it will be called automatically
    /// on each frame. However there is one use case - when you setup complex hierarchy and
    /// need to know global transform of nodes before entering update loop, then you can call
    /// this method.
    #[inline]
    pub fn update_hierarchical_data(&mut self) {
        Self::update_hierarchical_data_recursively(
            &self.pool,
            &mut self.sound_context,
            &mut self.physics,
            &mut self.physics2d,
            self.root,
        );
    }

    fn sync_native(&mut self, switches: &GraphUpdateSwitches) {
        let mut sync_context = SyncContext {
            nodes: &self.pool,
            physics: &mut self.physics,
            physics2d: &mut self.physics2d,
            sound_context: &mut self.sound_context,
            switches: Some(switches),
        };

        for (handle, node) in self.pool.pair_iter() {
            node.sync_native(handle, &mut sync_context);
        }
    }

    fn update_node(
        &mut self,
        handle: Handle<Node>,
        frame_size: Vector2<f32>,
        dt: f32,
        delete_dead_nodes: bool,
    ) {
        if let Some((ticket, mut node)) = self.pool.try_take_reserve(handle) {
            node.transform_modified.set(false);

            let mut is_alive = node.is_alive();

            if node.is_globally_enabled() {
                node.update(&mut UpdateContext {
                    frame_size,
                    dt,
                    nodes: &mut self.pool,
                    physics: &mut self.physics,
                    physics2d: &mut self.physics2d,
                    sound_context: &mut self.sound_context,
                });

                if delete_dead_nodes {
                    if let Some(lifetime) = node.lifetime.get_value_mut_silent().as_mut() {
                        *lifetime -= dt;
                        if *lifetime <= 0.0 {
                            is_alive = false;
                        }
                    }
                }
            }

            self.pool.put_back(ticket, node);

            if !is_alive && delete_dead_nodes {
                self.remove_node(handle);
            }
        }
    }

    /// Updates nodes in the graph using given delta time.
    ///
    /// # Update Switches
    ///
    /// Update switches allows you to disable update for parts of the update pipeline, it could be useful for editors
    /// where you need to have preview mode to update only specific set of nodes, etc.
    pub fn update(&mut self, frame_size: Vector2<f32>, dt: f32, switches: GraphUpdateSwitches) {
        self.sound_context.state().pause(switches.paused);

        if switches.paused {
            return;
        }

        let last_time = instant::Instant::now();
        self.update_hierarchical_data();
        self.performance_statistics.hierarchical_properties_time =
            instant::Instant::now() - last_time;

        let last_time = instant::Instant::now();
        self.sync_native(&switches);
        self.performance_statistics.sync_time = instant::Instant::now() - last_time;

        if switches.physics {
            self.physics.performance_statistics.reset();
            self.physics.update(dt);
            self.performance_statistics.physics = self.physics.performance_statistics.clone();
        }

        if switches.physics2d {
            self.physics2d.performance_statistics.reset();
            self.physics2d.update(dt);
            self.performance_statistics.physics2d = self.physics2d.performance_statistics.clone();
        }

        self.performance_statistics.sound_update_time =
            self.sound_context.state().full_render_duration();

        if let Some(overrides) = switches.node_overrides.as_ref() {
            for handle in overrides {
                self.update_node(*handle, frame_size, dt, switches.delete_dead_nodes);
            }
        } else {
            for i in 0..self.pool.get_capacity() {
                self.update_node(
                    self.pool.handle_from_index(i),
                    frame_size,
                    dt,
                    switches.delete_dead_nodes,
                );
            }
        }
    }

    /// Returns capacity of internal pool. Can be used to iterate over all **potentially**
    /// available indices and try to convert them to handles.
    ///
    /// ```
    /// # use fyrox_impl::scene::node::Node;
    /// # use fyrox_impl::scene::graph::Graph;
    /// # use fyrox_impl::scene::pivot::Pivot;
    /// # use fyrox_graph::BaseSceneGraph;
    /// let mut graph = Graph::new();
    /// graph.add_node(Node::new(Pivot::default()));
    /// graph.add_node(Node::new(Pivot::default()));
    /// for i in 0..graph.capacity() {
    ///     let handle = graph.handle_from_index(i);
    ///     if handle.is_some() {
    ///         let node = &mut graph[handle];
    ///         // Do something with node.
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn capacity(&self) -> u32 {
        self.pool.get_capacity()
    }

    /// Makes new handle from given index. Handle will be none if index was either out-of-bounds
    /// or point to a vacant pool entry.
    ///
    /// ```
    /// # use fyrox_impl::scene::node::Node;
    /// # use fyrox_impl::scene::graph::Graph;
    /// # use fyrox_impl::scene::pivot::Pivot;
    /// # use fyrox_graph::BaseSceneGraph;
    /// let mut graph = Graph::new();
    /// graph.add_node(Node::new(Pivot::default()));
    /// graph.add_node(Node::new(Pivot::default()));
    /// for i in 0..graph.capacity() {
    ///     let handle = graph.handle_from_index(i);
    ///     if handle.is_some() {
    ///         let node = &mut graph[handle];
    ///         // Do something with node.
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn handle_from_index(&self, index: u32) -> Handle<Node> {
        self.pool.handle_from_index(index)
    }

    /// Generates a set of handles that could be used to spawn a set of nodes.
    #[inline]
    pub fn generate_free_handles(&self, amount: usize) -> Vec<Handle<Node>> {
        self.pool.generate_free_handles(amount)
    }

    /// Creates an iterator that has linear iteration order over internal collection
    /// of nodes. It does *not* perform any tree traversal!
    #[inline]
    pub fn linear_iter(&self) -> impl Iterator<Item = &Node> {
        self.pool.iter()
    }

    /// Creates new iterator that iterates over internal collection giving (handle; node) pairs.
    #[inline]
    pub fn pair_iter_mut(&mut self) -> impl Iterator<Item = (Handle<Node>, &mut Node)> {
        self.pool.pair_iter_mut()
    }

    /// Extracts node from graph and reserves its handle. It is used to temporarily take
    /// ownership over node, and then put node back using given ticket. Extracted node is
    /// detached from its parent!
    #[inline]
    pub fn take_reserve(&mut self, handle: Handle<Node>) -> (Ticket<Node>, Node) {
        self.isolate_node(handle);
        let (ticket, node) = self.take_reserve_internal(handle);
        self.instance_id_map.remove(&node.instance_id);
        (ticket, node)
    }

    pub(crate) fn take_reserve_internal(&mut self, handle: Handle<Node>) -> (Ticket<Node>, Node) {
        let (ticket, mut node) = self.pool.take_reserve(handle);
        self.instance_id_map.remove(&node.instance_id);
        node.on_removed_from_graph(self);
        (ticket, node)
    }

    /// Puts node back by given ticket. Attaches back to root node of graph.
    #[inline]
    pub fn put_back(&mut self, ticket: Ticket<Node>, node: Node) -> Handle<Node> {
        let handle = self.put_back_internal(ticket, node);
        self.link_nodes(handle, self.root);
        handle
    }

    pub(crate) fn put_back_internal(&mut self, ticket: Ticket<Node>, node: Node) -> Handle<Node> {
        let instance_id = node.instance_id;
        let handle = self.pool.put_back(ticket, node);
        self.instance_id_map.insert(instance_id, handle);
        handle
    }

    /// Makes node handle vacant again.
    #[inline]
    pub fn forget_ticket(&mut self, ticket: Ticket<Node>, node: Node) -> Node {
        self.pool.forget_ticket(ticket);
        node
    }

    /// Extracts sub-graph starting from a given node. All handles to extracted nodes
    /// becomes reserved and will be marked as "occupied", an attempt to borrow a node
    /// at such handle will result in panic!. Please note that root node will be
    /// detached from its parent!
    #[inline]
    pub fn take_reserve_sub_graph(&mut self, root: Handle<Node>) -> SubGraph {
        // Take out descendants first.
        let mut descendants = Vec::new();
        let root_ref = &mut self[root];
        let mut stack = root_ref.children().to_vec();
        let parent = root_ref.parent;
        while let Some(handle) = stack.pop() {
            stack.extend_from_slice(self[handle].children());
            descendants.push(self.take_reserve_internal(handle));
        }

        SubGraph {
            // Root must be extracted with detachment from its parent (if any).
            root: self.take_reserve(root),
            descendants,
            parent,
        }
    }

    /// Puts previously extracted sub-graph into graph. Handles to nodes will become valid
    /// again. After that you probably want to re-link returned handle with its previous
    /// parent.
    #[inline]
    pub fn put_sub_graph_back(&mut self, sub_graph: SubGraph) -> Handle<Node> {
        for (ticket, node) in sub_graph.descendants {
            self.pool.put_back(ticket, node);
        }

        let (ticket, node) = sub_graph.root;
        let root_handle = self.put_back(ticket, node);

        self.link_nodes(root_handle, sub_graph.parent);

        root_handle
    }

    /// Forgets the entire sub-graph making handles to nodes invalid.
    #[inline]
    pub fn forget_sub_graph(&mut self, sub_graph: SubGraph) {
        for (ticket, _) in sub_graph.descendants {
            self.pool.forget_ticket(ticket);
        }
        let (ticket, _) = sub_graph.root;
        self.pool.forget_ticket(ticket);
    }

    /// Returns the number of nodes in the graph.
    #[inline]
    pub fn node_count(&self) -> u32 {
        self.pool.alive_count()
    }

    /// Creates deep copy of graph. Allows filtering while copying, returns copy and
    /// old-to-new node mapping.
    #[inline]
    pub fn clone<F, Pre, Post>(
        &self,
        root: Handle<Node>,
        filter: &mut F,
        pre_process_callback: &mut Pre,
        post_process_callback: &mut Post,
    ) -> (Self, NodeHandleMap<Node>)
    where
        F: FnMut(Handle<Node>, &Node) -> bool,
        Pre: FnMut(Handle<Node>, &mut Node),
        Post: FnMut(Handle<Node>, Handle<Node>, &mut Node),
    {
        let mut copy = Self {
            sound_context: self.sound_context.deep_clone(),
            ..Default::default()
        };

        let (copy_root, old_new_map) = self.copy_node(
            root,
            &mut copy,
            filter,
            pre_process_callback,
            post_process_callback,
        );
        assert_eq!(copy.root, copy_root);

        let mut lightmap = self.lightmap.clone();
        if let Some(lightmap) = lightmap.as_mut() {
            let mut map = FxHashMap::default();
            for (mut handle, mut entries) in std::mem::take(&mut lightmap.map) {
                for entry in entries.iter_mut() {
                    for light_handle in entry.lights.iter_mut() {
                        old_new_map.try_map(light_handle);
                    }
                }

                if old_new_map.try_map(&mut handle) {
                    map.insert(handle, entries);
                }
            }
            lightmap.map = map;
        }
        copy.lightmap = lightmap;

        (copy, old_new_map)
    }

    /// Returns local transformation matrix of a node without scale.
    #[inline]
    pub fn local_transform_no_scale(&self, node: Handle<Node>) -> Matrix4<f32> {
        let mut transform = self[node].local_transform().clone();
        transform.set_scale(Vector3::new(1.0, 1.0, 1.0));
        transform.matrix()
    }

    /// Returns world transformation matrix of a node without scale.
    #[inline]
    pub fn global_transform_no_scale(&self, node: Handle<Node>) -> Matrix4<f32> {
        let parent = self[node].parent();
        if parent.is_some() {
            self.global_transform_no_scale(parent) * self.local_transform_no_scale(node)
        } else {
            self.local_transform_no_scale(node)
        }
    }

    /// Returns isometric local transformation matrix of a node. Such transform has
    /// only translation and rotation.
    #[inline]
    pub fn isometric_local_transform(&self, node: Handle<Node>) -> Matrix4<f32> {
        isometric_local_transform(&self.pool, node)
    }

    /// Returns world transformation matrix of a node only.  Such transform has
    /// only translation and rotation.
    #[inline]
    pub fn isometric_global_transform(&self, node: Handle<Node>) -> Matrix4<f32> {
        isometric_global_transform(&self.pool, node)
    }

    /// Returns global scale matrix of a node.
    #[inline]
    pub fn global_scale_matrix(&self, node: Handle<Node>) -> Matrix4<f32> {
        let node = &self[node];
        let local_scale_matrix = Matrix4::new_nonuniform_scaling(node.local_transform().scale());
        if node.parent().is_some() {
            self.global_scale_matrix(node.parent()) * local_scale_matrix
        } else {
            local_scale_matrix
        }
    }

    /// Returns rotation quaternion of a node in world coordinates.
    #[inline]
    pub fn global_rotation(&self, node: Handle<Node>) -> UnitQuaternion<f32> {
        UnitQuaternion::from(Rotation3::from_matrix_eps(
            &self.global_transform_no_scale(node).basis(),
            f32::EPSILON,
            16,
            Rotation3::identity(),
        ))
    }

    /// Returns rotation quaternion of a node in world coordinates without pre- and post-rotations.
    #[inline]
    pub fn isometric_global_rotation(&self, node: Handle<Node>) -> UnitQuaternion<f32> {
        UnitQuaternion::from(Rotation3::from_matrix_eps(
            &self.isometric_global_transform(node).basis(),
            f32::EPSILON,
            16,
            Rotation3::identity(),
        ))
    }

    /// Returns rotation quaternion and position of a node in world coordinates, scale is eliminated.
    #[inline]
    pub fn global_rotation_position_no_scale(
        &self,
        node: Handle<Node>,
    ) -> (UnitQuaternion<f32>, Vector3<f32>) {
        (self.global_rotation(node), self[node].global_position())
    }

    /// Returns isometric global rotation and position.
    #[inline]
    pub fn isometric_global_rotation_position(
        &self,
        node: Handle<Node>,
    ) -> (UnitQuaternion<f32>, Vector3<f32>) {
        (
            self.isometric_global_rotation(node),
            self[node].global_position(),
        )
    }

    /// Returns global scale of a node.
    #[inline]
    pub fn global_scale(&self, node: Handle<Node>) -> Vector3<f32> {
        let m = self.global_scale_matrix(node);
        Vector3::new(m[0], m[5], m[10])
    }

    /// Tries to borrow a node using the given handle and searches the script buffer for a script
    /// of type T and cast the first script, that could be found to the specified type.
    #[inline]
    pub fn try_get_script_of<T>(&self, node: Handle<Node>) -> Option<&T>
    where
        T: ScriptTrait,
    {
        self.try_get(node)
            .and_then(|node| node.try_get_script::<T>())
    }

    /// Tries to borrow a node and query all scripts of the given type `T`. This method returns
    /// [`None`] if the given node handle is invalid, otherwise it returns an iterator over the
    /// scripts of the type `T`.
    #[inline]
    pub fn try_get_scripts_of<T: ScriptTrait>(
        &self,
        node: Handle<Node>,
    ) -> Option<impl Iterator<Item = &T>> {
        self.try_get(node).map(|n| n.try_get_scripts())
    }

    /// Tries to borrow a node using the given handle and searches the script buffer for a script
    /// of type T and cast the first script, that could be found to the specified type.
    #[inline]
    pub fn try_get_script_of_mut<T>(&mut self, node: Handle<Node>) -> Option<&mut T>
    where
        T: ScriptTrait,
    {
        self.try_get_mut(node)
            .and_then(|node| node.try_get_script_mut::<T>())
    }

    /// Tries to borrow a node and query all scripts of the given type `T`. This method returns
    /// [`None`] if the given node handle is invalid, otherwise it returns an iterator over the
    /// scripts of the type `T`.
    #[inline]
    pub fn try_get_scripts_of_mut<T: ScriptTrait>(
        &mut self,
        node: Handle<Node>,
    ) -> Option<impl Iterator<Item = &mut T>> {
        self.try_get_mut(node).map(|n| n.try_get_scripts_mut())
    }

    /// Tries to borrow a node and find a component of the given type `C` across **all** available
    /// scripts of the node. If you want to search a component `C` in a particular script, then use
    /// [`Self::try_get_script_of`] and then search for component in it.
    #[inline]
    pub fn try_get_script_component_of<C>(&self, node: Handle<Node>) -> Option<&C>
    where
        C: Any,
    {
        self.try_get(node)
            .and_then(|node| node.try_get_script_component())
    }

    /// Tries to borrow a node and find a component of the given type `C` across **all** available
    /// scripts of the node. If you want to search a component `C` in a particular script, then use
    /// [`Self::try_get_script_of_mut`] and then search for component in it.
    #[inline]
    pub fn try_get_script_component_of_mut<C>(&mut self, node: Handle<Node>) -> Option<&mut C>
    where
        C: Any,
    {
        self.try_get_mut(node)
            .and_then(|node| node.try_get_script_component_mut())
    }

    /// Returns a handle of the node that has the given id.
    pub fn id_to_node_handle(&self, id: SceneNodeId) -> Option<&Handle<Node>> {
        self.instance_id_map.get(&id)
    }

    /// Tries to borrow a node by its id.
    pub fn node_by_id(&self, id: SceneNodeId) -> Option<(Handle<Node>, &Node)> {
        self.instance_id_map
            .get(&id)
            .and_then(|h| self.pool.try_borrow(*h).map(|n| (*h, n)))
    }

    /// Tries to borrow a node by its id.
    pub fn node_by_id_mut(&mut self, id: SceneNodeId) -> Option<(Handle<Node>, &mut Node)> {
        self.instance_id_map
            .get(&id)
            .and_then(|h| self.pool.try_borrow_mut(*h).map(|n| (*h, n)))
    }
}

impl Index<Handle<Node>> for Graph {
    type Output = Node;

    #[inline]
    fn index(&self, index: Handle<Node>) -> &Self::Output {
        &self.pool[index]
    }
}

impl IndexMut<Handle<Node>> for Graph {
    #[inline]
    fn index_mut(&mut self, index: Handle<Node>) -> &mut Self::Output {
        &mut self.pool[index]
    }
}

impl<T> Index<Handle<T>> for Graph
where
    T: NodeTrait,
{
    type Output = T;

    #[inline]
    fn index(&self, typed_handle: Handle<T>) -> &Self::Output {
        let node = &self.pool[typed_handle.transmute()];
        node.cast().unwrap_or_else(|| {
            panic!(
                "Downcasting of node {} ({}:{}) to type {} failed!",
                node.name(),
                typed_handle.index(),
                typed_handle.generation(),
                node.type_name()
            )
        })
    }
}

impl<T> IndexMut<Handle<T>> for Graph
where
    T: NodeTrait,
{
    #[inline]
    fn index_mut(&mut self, typed_handle: Handle<T>) -> &mut Self::Output {
        let node = &mut self.pool[typed_handle.transmute()];

        // SAFETY: This is safe to do, because we only read node's values for panicking.
        let second_node_ref = unsafe { &*(node as *const Node) };

        if let Some(downcasted) = node.cast_mut() {
            downcasted
        } else {
            panic!(
                "Downcasting of node {} ({}:{}) to type {} failed!",
                second_node_ref.name(),
                typed_handle.index(),
                typed_handle.generation(),
                second_node_ref.type_name()
            )
        }
    }
}

impl Visit for Graph {
    fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
        // Pool must be empty, otherwise handles will be invalid and everything will blow up.
        if visitor.is_reading() && self.pool.get_capacity() != 0 {
            panic!("Graph pool must be empty on load!")
        }

        let mut region = visitor.enter_region(name)?;

        self.root.visit("Root", &mut region)?;
        self.pool.visit("Pool", &mut region)?;
        self.sound_context.visit("SoundContext", &mut region)?;
        self.physics.visit("PhysicsWorld", &mut region)?;
        self.physics2d.visit("PhysicsWorld2D", &mut region)?;
        let _ = self.lightmap.visit("Lightmap", &mut region);

        Ok(())
    }
}

impl AbstractSceneGraph for Graph {
    fn try_get_node_untyped(&self, handle: ErasedHandle) -> Option<&dyn AbstractSceneNode> {
        self.pool
            .try_borrow(handle.into())
            .map(|n| n as &dyn AbstractSceneNode)
    }

    fn try_get_node_untyped_mut(
        &mut self,
        handle: ErasedHandle,
    ) -> Option<&mut dyn AbstractSceneNode> {
        self.pool
            .try_borrow_mut(handle.into())
            .map(|n| n as &mut dyn AbstractSceneNode)
    }
}

impl BaseSceneGraph for Graph {
    type Prefab = Model;
    type Node = Node;

    #[inline]
    fn root(&self) -> Handle<Self::Node> {
        self.root
    }

    #[inline]
    fn set_root(&mut self, root: Handle<Self::Node>) {
        self.root = root;
    }

    #[inline]
    fn is_valid_handle(&self, handle: Handle<Self::Node>) -> bool {
        self.pool.is_valid_handle(handle)
    }

    #[inline]
    fn add_node(&mut self, mut node: Self::Node) -> Handle<Self::Node> {
        let children = node.children.clone();
        node.children.clear();
        let script_count = node.scripts.len();
        let handle = self.pool.spawn(node);

        if self.root.is_none() {
            self.root = handle;
        } else {
            self.link_nodes(handle, self.root);
        }

        for child in children {
            self.link_nodes(child, handle);
        }

        self.event_broadcaster.broadcast(GraphEvent::Added(handle));
        for i in 0..script_count {
            self.script_message_sender
                .send(NodeScriptMessage::InitializeScript {
                    handle,
                    script_index: i,
                })
                .unwrap();
        }

        let sender = self.script_message_sender.clone();
        let node = &mut self.pool[handle];
        node.self_handle = handle;
        node.script_message_sender = Some(sender);

        self.instance_id_map.insert(node.instance_id, handle);

        handle
    }

    #[inline]
    fn remove_node(&mut self, node_handle: Handle<Self::Node>) {
        self.isolate_node(node_handle);

        self.stack.clear();
        self.stack.push(node_handle);
        while let Some(handle) = self.stack.pop() {
            for &child in self.pool[handle].children().iter() {
                self.stack.push(child);
            }

            // Remove associated entities.
            let mut node = self.pool.free(handle);
            self.instance_id_map.remove(&node.instance_id);
            node.on_removed_from_graph(self);

            self.event_broadcaster
                .broadcast(GraphEvent::Removed(handle));
        }
    }

    #[inline]
    fn link_nodes(&mut self, child: Handle<Self::Node>, parent: Handle<Self::Node>) {
        self.isolate_node(child);
        self.pool[child].parent = parent;
        self.pool[parent].children.push(child);
    }

    #[inline]
    fn unlink_node(&mut self, node_handle: Handle<Node>) {
        self.isolate_node(node_handle);
        self.link_nodes(node_handle, self.root);
        self.pool[node_handle]
            .local_transform_mut()
            .set_position(Vector3::default());
    }

    #[inline]
    fn isolate_node(&mut self, node_handle: Handle<Self::Node>) {
        // Replace parent handle of child
        let parent_handle = std::mem::replace(&mut self.pool[node_handle].parent, Handle::NONE);

        // Remove child from parent's children list
        if let Some(parent) = self.pool.try_borrow_mut(parent_handle) {
            if let Some(i) = parent.children().iter().position(|h| *h == node_handle) {
                parent.children.remove(i);
            }
        }

        let (ticket, mut node) = self.pool.take_reserve(node_handle);
        node.on_unlink(self);
        self.pool.put_back(ticket, node);
    }

    #[inline]
    fn try_get(&self, handle: Handle<Self::Node>) -> Option<&Self::Node> {
        self.pool.try_borrow(handle)
    }

    #[inline]
    fn try_get_mut(&mut self, handle: Handle<Self::Node>) -> Option<&mut Self::Node> {
        self.pool.try_borrow_mut(handle)
    }
}

impl SceneGraph for Graph {
    #[inline]
    fn pair_iter(&self) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)> {
        self.pool.pair_iter()
    }

    #[inline]
    fn linear_iter(&self) -> impl Iterator<Item = &Self::Node> {
        self.pool.iter()
    }

    #[inline]
    fn linear_iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Node> {
        self.pool.iter_mut()
    }
}

#[cfg(test)]
mod test {
    use crate::{
        asset::{io::FsResourceIo, manager::ResourceManager},
        core::{
            algebra::{Matrix4, Vector3},
            futures::executor::block_on,
            pool::Handle,
            reflect::prelude::*,
            type_traits::prelude::*,
            visitor::prelude::*,
        },
        engine::{self, SerializationContext},
        graph::{BaseSceneGraph, SceneGraph},
        resource::model::{Model, ModelResourceExtension},
        scene::{
            base::BaseBuilder,
            graph::Graph,
            mesh::{
                surface::{SurfaceBuilder, SurfaceData, SurfaceSharedData},
                MeshBuilder,
            },
            node::Node,
            pivot::{Pivot, PivotBuilder},
            transform::TransformBuilder,
            Scene, SceneLoader,
        },
        script::ScriptTrait,
    };
    use std::{fs, path::Path, sync::Arc};

    #[derive(Clone, Debug, PartialEq, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "722feb80-a10b-4ee0-8cef-5d1473df8457")]
    struct MyScript {
        foo: String,
        bar: f32,
    }

    impl ScriptTrait for MyScript {}

    #[derive(Clone, Debug, PartialEq, Reflect, Visit, TypeUuidProvider, ComponentProvider)]
    #[type_uuid(id = "722feb80-a10b-4ee0-8cef-5d1473df8458")]
    struct MyOtherScript {
        baz: u32,
        foobar: Vec<u32>,
    }

    impl ScriptTrait for MyOtherScript {}

    #[test]
    fn test_graph_scripts() {
        let node = PivotBuilder::new(
            BaseBuilder::new()
                .with_script(MyScript {
                    foo: "Stuff".to_string(),
                    bar: 123.321,
                })
                .with_script(MyScript {
                    foo: "OtherStuff".to_string(),
                    bar: 321.123,
                })
                .with_script(MyOtherScript {
                    baz: 321,
                    foobar: vec![1, 2, 3],
                }),
        )
        .build_node();

        let mut graph = Graph::new();

        let handle = graph.add_node(node);

        assert_eq!(
            graph.try_get_script_of::<MyScript>(handle),
            Some(&MyScript {
                foo: "Stuff".to_string(),
                bar: 123.321,
            })
        );
        assert_eq!(
            graph.try_get_script_of_mut::<MyScript>(handle),
            Some(&mut MyScript {
                foo: "Stuff".to_string(),
                bar: 123.321,
            })
        );

        let mut immutable_iterator = graph
            .try_get_scripts_of::<MyScript>(handle)
            .expect("The handle expected to be valid!");
        assert_eq!(
            immutable_iterator.next(),
            Some(&MyScript {
                foo: "Stuff".to_string(),
                bar: 123.321,
            })
        );
        assert_eq!(
            immutable_iterator.next(),
            Some(&MyScript {
                foo: "OtherStuff".to_string(),
                bar: 321.123,
            })
        );
        drop(immutable_iterator);

        assert_eq!(
            graph.try_get_script_of::<MyOtherScript>(handle),
            Some(&MyOtherScript {
                baz: 321,
                foobar: vec![1, 2, 3],
            })
        );
        assert_eq!(
            graph.try_get_script_of_mut::<MyOtherScript>(handle),
            Some(&mut MyOtherScript {
                baz: 321,
                foobar: vec![1, 2, 3],
            })
        );

        let mut mutable_iterator = graph
            .try_get_scripts_of_mut::<MyScript>(handle)
            .expect("The handle expected to be valid!");
        assert_eq!(
            mutable_iterator.next(),
            Some(&mut MyScript {
                foo: "Stuff".to_string(),
                bar: 123.321,
            })
        );
        assert_eq!(
            mutable_iterator.next(),
            Some(&mut MyScript {
                foo: "OtherStuff".to_string(),
                bar: 321.123,
            })
        );
    }

    #[test]
    fn graph_init_test() {
        let graph = Graph::new();
        assert_ne!(graph.root, Handle::NONE);
        assert_eq!(graph.pool.alive_count(), 1);
    }

    #[test]
    fn graph_node_test() {
        let mut graph = Graph::new();
        graph.add_node(Node::new(Pivot::default()));
        graph.add_node(Node::new(Pivot::default()));
        graph.add_node(Node::new(Pivot::default()));
        assert_eq!(graph.pool.alive_count(), 4);
    }

    #[test]
    fn test_graph_search() {
        let mut graph = Graph::new();

        // Root_
        //      |_A_
        //          |_B
        //          |_C_
        //             |_D
        let b;
        let c;
        let d;
        let a = PivotBuilder::new(BaseBuilder::new().with_name("A").with_children(&[
            {
                b = PivotBuilder::new(BaseBuilder::new().with_name("B")).build(&mut graph);
                b
            },
            {
                c = PivotBuilder::new(BaseBuilder::new().with_name("C").with_children(&[{
                    d = PivotBuilder::new(BaseBuilder::new().with_name("D")).build(&mut graph);
                    d
                }]))
                .build(&mut graph);
                c
            },
        ]))
        .build(&mut graph);

        // Test down search.
        assert!(graph.find_by_name(a, "X").is_none());
        assert_eq!(graph.find_by_name(a, "A").unwrap().0, a);
        assert_eq!(graph.find_by_name(a, "D").unwrap().0, d);

        let result = graph
            .find_map(a, &mut |n| if n.name() == "D" { Some("D") } else { None })
            .unwrap();
        assert_eq!(result.0, d);
        assert_eq!(result.1, "D");

        // Test up search.
        assert!(graph.find_up_by_name(d, "X").is_none());
        assert_eq!(graph.find_up_by_name(d, "D").unwrap().0, d);
        assert_eq!(graph.find_up_by_name(d, "A").unwrap().0, a);

        let result = graph
            .find_up_map(d, &mut |n| if n.name() == "A" { Some("A") } else { None })
            .unwrap();
        assert_eq!(result.0, a);
        assert_eq!(result.1, "A");
    }

    fn create_scene() -> Scene {
        let mut scene = Scene::new();

        PivotBuilder::new(BaseBuilder::new().with_name("Pivot")).build(&mut scene.graph);

        PivotBuilder::new(BaseBuilder::new().with_name("MeshPivot").with_children(&[{
            MeshBuilder::new(
                BaseBuilder::new().with_name("Mesh").with_local_transform(
                    TransformBuilder::new()
                        .with_local_position(Vector3::new(3.0, 2.0, 1.0))
                        .build(),
                ),
            )
            .with_surfaces(vec![SurfaceBuilder::new(SurfaceSharedData::new(
                SurfaceData::make_cone(16, 1.0, 1.0, &Matrix4::identity()),
            ))
            .build()])
            .build(&mut scene.graph)
        }]))
        .build(&mut scene.graph);

        scene
    }

    fn save_scene(scene: &mut Scene, path: &Path) {
        let mut visitor = Visitor::new();
        scene.save("Scene", &mut visitor).unwrap();
        visitor.save_binary(path).unwrap();
    }

    fn make_resource_manager() -> ResourceManager {
        let resource_manager = ResourceManager::new(Arc::new(Default::default()));
        engine::initialize_resource_manager_loaders(
            &resource_manager,
            Arc::new(SerializationContext::new()),
        );
        resource_manager
    }

    #[test]
    fn test_restore_integrity() {
        if !Path::new("test_output").exists() {
            fs::create_dir_all("test_output").unwrap();
        }

        let root_asset_path = Path::new("test_output/root2.rgs");
        let derived_asset_path = Path::new("test_output/derived2.rgs");

        // Create root scene and save it.
        {
            let mut scene = create_scene();
            save_scene(&mut scene, root_asset_path);
        }

        // Create root resource instance in a derived resource. This creates a derived asset.
        {
            let resource_manager = make_resource_manager();
            let root_asset = block_on(resource_manager.request::<Model>(root_asset_path)).unwrap();

            let mut derived = Scene::new();
            root_asset.instantiate(&mut derived);
            save_scene(&mut derived, derived_asset_path);
        }

        // Now load the root asset, modify it, save it back and reload the derived asset.
        {
            let resource_manager = make_resource_manager();
            let mut scene = block_on(
                block_on(SceneLoader::from_file(
                    root_asset_path,
                    &FsResourceIo,
                    Arc::new(SerializationContext::new()),
                    resource_manager.clone(),
                ))
                .unwrap()
                .0
                .finish(&resource_manager),
            );

            // Add a new node to the root node of the scene.
            PivotBuilder::new(BaseBuilder::new().with_name("AddedLater")).build(&mut scene.graph);

            // Add a new node to the mesh.
            let mesh = scene.graph.find_by_name_from_root("Mesh").unwrap().0;
            let pivot = PivotBuilder::new(BaseBuilder::new().with_name("NewChildOfMesh"))
                .build(&mut scene.graph);
            scene.graph.link_nodes(pivot, mesh);

            // Remove existing nodes.
            let existing_pivot = scene.graph.find_by_name_from_root("Pivot").unwrap().0;
            scene.graph.remove_node(existing_pivot);

            // Save the scene back.
            save_scene(&mut scene, root_asset_path);
        }

        // Load the derived scene and check if its content was synced with the content of the root asset.
        {
            let resource_manager = make_resource_manager();
            let derived_asset =
                block_on(resource_manager.request::<Model>(derived_asset_path)).unwrap();

            let derived_data = derived_asset.data_ref();
            let derived_scene = derived_data.get_scene();

            // Pivot must also be removed from the derived asset, because it is deleted in the root asset.
            assert_eq!(
                derived_scene
                    .graph
                    .find_by_name_from_root("Pivot")
                    .map(|(h, _)| h),
                None
            );

            let mesh_pivot = derived_scene
                .graph
                .find_by_name_from_root("MeshPivot")
                .unwrap()
                .0;
            let mesh = derived_scene
                .graph
                .find_by_name(mesh_pivot, "Mesh")
                .unwrap()
                .0;
            derived_scene
                .graph
                .find_by_name_from_root("AddedLater")
                .unwrap();
            derived_scene
                .graph
                .find_by_name(mesh, "NewChildOfMesh")
                .unwrap();
        }
    }
}