bevy_gltf 0.19.0

Bevy Engine GLTF loading
Documentation
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
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
pub mod extensions;
pub mod gltf_ext;

use alloc::sync::Arc;
use async_lock::RwLock;
#[cfg(feature = "bevy_animation")]
use bevy_animation::{prelude::*, AnimatedBy, AnimationTargetId};
use bevy_asset::{
    io::Reader, AssetLoadError, AssetLoader, AssetPath, Handle, LoadContext, ParseAssetPathError,
    ReadAssetBytesError, RenderAssetUsages,
};
use bevy_camera::{
    primitives::Aabb,
    visibility::{DynamicSkinnedMeshBounds, NoFrustumCulling, Visibility},
    Camera, Camera3d, OrthographicProjection, PerspectiveProjection, Projection, ScalingMode,
};
use bevy_color::{Color, LinearRgba};
use bevy_ecs::{
    entity::{Entity, EntityHashMap},
    hierarchy::ChildSpawner,
    name::Name,
    world::World,
};
use bevy_image::{
    CompressedImageFormats, Image, ImageLoaderSettings, ImageSampler, ImageSamplerDescriptor,
    ImageType, TextureError,
};
use bevy_light::{DirectionalLight, PointLight, SpotLight};
use bevy_math::{Mat4, Vec3};
#[cfg(feature = "pbr_transmission_textures")]
use bevy_mesh::UvChannel;
use bevy_mesh::{
    morph::{MeshMorphWeights, MorphAttributes, MorphWeights},
    skinning::{SkinnedMesh, SkinnedMeshInverseBindposes},
    Indices, Mesh, Mesh3d, MeshVertexAttribute, PrimitiveTopology,
};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_reflect::TypePath;
#[cfg(not(target_arch = "wasm32"))]
use bevy_tasks::IoTaskPool;
use bevy_transform::components::Transform;
use bevy_world_serialization::WorldAsset;
use gltf::{
    accessor::Iter,
    image::Source,
    mesh::{util::ReadIndices, Mode},
    Material, Node, Semantic,
};
use serde::{Deserialize, Serialize};
#[cfg(feature = "bevy_animation")]
use smallvec::SmallVec;
use std::{io::Error, sync::Mutex};
use thiserror::Error;
use tracing::{error, info_span, warn};
use wgpu_types::Face;

use crate::{
    convert_coordinates::ConvertCoordinates as _, vertex_attributes::convert_attribute, Gltf,
    GltfAssetLabel, GltfExtras, GltfMaterial, GltfMaterialExtras, GltfMaterialName, GltfMeshExtras,
    GltfMeshName, GltfNode, GltfSceneExtras, GltfSceneName, GltfSkin, GltfSkinnedMeshBoundsPolicy,
};

#[cfg(feature = "bevy_animation")]
use self::gltf_ext::scene::collect_path;
use self::{
    extensions::{AnisotropyExtension, ClearcoatExtension, SpecularExtension},
    gltf_ext::{
        check_for_cycles, get_linear_textures,
        material::{
            alpha_mode, material_label, needs_tangents, uv_channel,
            warn_on_differing_texture_transforms,
        },
        mesh::{primitive_name, primitive_topology},
        scene::{node_name, node_transform},
        texture::{texture_sampler, texture_transform_to_affine2},
    },
};
use crate::convert_coordinates::GltfConvertCoordinates;

/// Must match [`MAX_JOINTS`](https://docs.rs/bevy/latest/bevy/pbr/constant.MAX_JOINTS.html)
pub const MAX_JOINTS: usize = 256;

/// An error that occurs when loading a glTF file.
#[derive(Error, Debug)]
pub enum GltfError {
    /// Unsupported primitive mode.
    #[error("unsupported primitive mode")]
    UnsupportedPrimitive {
        /// The primitive mode.
        mode: Mode,
    },
    /// Invalid glTF file.
    #[error("invalid glTF file: {0}")]
    Gltf(#[from] gltf::Error),
    /// Binary blob is missing.
    #[error("binary blob is missing")]
    MissingBlob,
    /// Decoding the base64 mesh data failed.
    #[error("failed to decode base64 mesh data")]
    Base64Decode(#[from] base64::DecodeError),
    /// Unsupported buffer format.
    #[error("unsupported buffer format")]
    BufferFormatUnsupported,
    /// The buffer URI was unable to be resolved with respect to the asset path.
    #[error("invalid buffer uri: {0}. asset path error={1}")]
    InvalidBufferUri(String, ParseAssetPathError),
    /// Invalid image mime type.
    #[error("invalid image mime type: {0}")]
    #[from(ignore)]
    InvalidImageMimeType(String),
    /// Error when loading a texture. Might be due to a disabled image file format feature.
    #[error("You may need to add the feature for the file format: {0}")]
    ImageError(#[from] TextureError),
    /// The image URI was unable to be resolved with respect to the asset path.
    #[error("invalid image uri: {0}. asset path error={1}")]
    InvalidImageUri(String, ParseAssetPathError),
    /// Failed to read bytes from an asset path.
    #[error("failed to read bytes from an asset path: {0}")]
    ReadAssetBytesError(#[from] ReadAssetBytesError),
    /// Failed to load asset from an asset path.
    #[error("failed to load asset from an asset path: {0}")]
    AssetLoadError(#[from] AssetLoadError),
    /// Missing sampler for an animation.
    #[error("Missing sampler for animation {0}")]
    #[from(ignore)]
    MissingAnimationSampler(usize),
    /// Failed to generate tangents.
    #[error("failed to generate tangents: {0}")]
    GenerateTangentsError(#[from] bevy_mesh::GenerateTangentsError),
    /// Failed to generate morph targets.
    #[error("failed to generate morph targets: {0}")]
    MorphTarget(#[from] bevy_mesh::morph::MorphBuildError),
    /// Circular children in Nodes
    #[error("GLTF model must be a tree, found cycle instead at node indices: {0:?}")]
    #[from(ignore)]
    CircularChildren(String),
    /// Failed to load a file.
    #[error("failed to load file: {0}")]
    Io(#[from] Error),
}

/// Loads glTF files with all of their data as their corresponding bevy representations.
#[derive(TypePath)]
pub struct GltfLoader {
    /// List of compressed image formats handled by the loader.
    pub supported_compressed_formats: CompressedImageFormats,
    /// Custom vertex attributes that will be recognized when loading a glTF file.
    ///
    /// Keys must be the attribute names as found in the glTF data, which must start with an underscore.
    /// See [this section of the glTF specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview)
    /// for additional details on custom attributes.
    pub custom_vertex_attributes: HashMap<Box<str>, MeshVertexAttribute>,
    /// Arc to default [`ImageSamplerDescriptor`].
    pub default_sampler: Arc<Mutex<ImageSamplerDescriptor>>,
    /// The default glTF coordinate conversion setting. This can be overridden
    /// per-load by [`GltfLoaderSettings::convert_coordinates`].
    pub default_convert_coordinates: GltfConvertCoordinates,
    /// glTF extension data processors.
    /// These are Bevy-side processors designed to access glTF
    /// extension data during the loading process.
    pub extensions: Arc<RwLock<Vec<Box<dyn extensions::ErasedGltfExtensionHandler>>>>,
    /// The default policy for skinned mesh bounds. Can be overridden by
    /// [`GltfLoaderSettings::skinned_mesh_bounds_policy`].
    pub default_skinned_mesh_bounds_policy: GltfSkinnedMeshBoundsPolicy,
}

/// Specifies optional settings for processing gltfs at load time. By default, all recognized contents of
/// the gltf will be loaded.
///
/// # Example
///
/// To load a gltf but exclude the cameras, replace a call to `asset_server.load("my.gltf")` with
/// ```no_run
/// # use bevy_asset::{AssetServer, Handle};
/// # use bevy_gltf::*;
/// # let asset_server: AssetServer = panic!();
/// let gltf_handle: Handle<Gltf> = asset_server.load_builder().with_settings(
///         |s: &mut GltfLoaderSettings| {
///             s.load_cameras = false;
///         }
///     )
///     .load("my.gltf");
/// ```
#[derive(Serialize, Deserialize)]
pub struct GltfLoaderSettings {
    /// If empty, the gltf mesh nodes will be skipped.
    ///
    /// Otherwise, nodes will be loaded and retained in RAM/VRAM according to the active flags.
    pub load_meshes: RenderAssetUsages,
    /// If empty, the gltf materials will be skipped.
    ///
    /// Otherwise, materials will be loaded and retained in RAM/VRAM according to the active flags.
    pub load_materials: RenderAssetUsages,
    /// If true, the loader will spawn cameras for gltf camera nodes.
    pub load_cameras: bool,
    /// If true, the loader will spawn lights for gltf light nodes.
    pub load_lights: bool,
    /// If true, the loader will load `AnimationClip` assets, and also add
    /// `AnimationTarget` and `AnimationPlayer` components to hierarchies
    /// affected by animation. Requires the `bevy_animation` feature.
    pub load_animations: bool,
    /// If true, the loader will include the root of the gltf root node.
    pub include_source: bool,
    /// Overrides the default sampler. Data from sampler node is added on top of that.
    ///
    /// If None, uses the global default which is stored in the [`DefaultGltfImageSampler`](crate::DefaultGltfImageSampler) resource.
    pub default_sampler: Option<ImageSamplerDescriptor>,
    /// If true, the loader will ignore sampler data from gltf and use the default sampler.
    pub override_sampler: bool,
    /// If false, the loader will load gltf json without validation, for unsupported extension it will ignore validation check.
    pub validate: bool,
    /// Overrides the default glTF coordinate conversion setting.
    ///
    /// If `None`, uses the global default set by [`GltfPlugin::convert_coordinates`](crate::GltfPlugin::convert_coordinates).
    pub convert_coordinates: Option<GltfConvertCoordinates>,
    /// Optionally overrides [`GltfPlugin::skinned_mesh_bounds_policy`](crate::GltfPlugin).
    pub skinned_mesh_bounds_policy: Option<GltfSkinnedMeshBoundsPolicy>,
}

impl Default for GltfLoaderSettings {
    fn default() -> Self {
        Self {
            load_meshes: RenderAssetUsages::default(),
            load_materials: RenderAssetUsages::default(),
            load_cameras: true,
            load_lights: true,
            load_animations: true,
            include_source: false,
            default_sampler: None,
            override_sampler: false,
            validate: true,
            convert_coordinates: None,
            skinned_mesh_bounds_policy: None,
        }
    }
}

impl GltfLoader {
    /// Loads an entire glTF file.
    pub async fn load_gltf<'a, 'b, 'c>(
        loader: &GltfLoader,
        bytes: &'a [u8],
        load_context: &'b mut LoadContext<'c>,
        settings: &'b GltfLoaderSettings,
    ) -> Result<Gltf, GltfError> {
        let gltf = if settings.validate {
            gltf::Gltf::from_slice(bytes)?
        } else {
            gltf::Gltf::from_slice_without_validation(bytes)?
        };

        // clone extensions to start with a fresh processing state
        let mut extensions = loader.extensions.read().await.clone();

        // Extensions can have data on the "root" of the glTF data.
        // Let extensions process the root data for the extension ids
        // they've subscribed to.
        for extension in extensions.iter_mut() {
            extension.on_root(load_context, &gltf, settings);
        }

        let file_name = load_context
            .path()
            .path()
            .to_str()
            .ok_or(GltfError::Gltf(gltf::Error::Io(Error::new(
                std::io::ErrorKind::InvalidInput,
                "Gltf file name invalid",
            ))))?
            .to_string();
        let buffer_data = load_buffers(&gltf, load_context).await?;

        let linear_textures = get_linear_textures(&gltf.document);

        #[cfg(feature = "bevy_animation")]
        let paths = if settings.load_animations {
            let mut paths = HashMap::<usize, (usize, Vec<Name>)>::default();
            for scene in gltf.scenes() {
                for node in scene.nodes() {
                    let root_index = node.index();
                    collect_path(&node, &[], &mut paths, root_index, &mut HashSet::default());
                }
            }
            paths
        } else {
            Default::default()
        };

        let convert_coordinates = match settings.convert_coordinates {
            Some(convert_coordinates) => convert_coordinates,
            None => loader.default_convert_coordinates,
        };

        let skinned_mesh_bounds_policy = settings
            .skinned_mesh_bounds_policy
            .unwrap_or(loader.default_skinned_mesh_bounds_policy);

        #[cfg(feature = "bevy_animation")]
        let (animations, named_animations, animation_roots) = if settings.load_animations {
            use bevy_animation::{
                animated_field, animation_curves::*, gltf_curves::*, VariableCurve,
            };
            use bevy_math::{
                curve::{ConstantCurve, Interval, UnevenSampleAutoCurve},
                Quat, Vec4,
            };
            use gltf::animation::util::ReadOutputs;
            let mut animations = vec![];
            let mut named_animations = <HashMap<_, _>>::default();
            let mut animation_roots = <HashSet<_>>::default();
            for animation in gltf.animations() {
                let mut animation_clip = AnimationClip::default();
                for channel in animation.channels() {
                    let node = channel.target().node();
                    let interpolation = channel.sampler().interpolation();
                    let reader = channel.reader(|buffer| Some(&buffer_data[buffer.index()]));
                    let keyframe_timestamps: Vec<f32> = if let Some(inputs) = reader.read_inputs() {
                        match inputs {
                            Iter::Standard(times) => times.collect(),
                            Iter::Sparse(_) => {
                                warn!("Sparse accessor not supported for animation sampler input");
                                continue;
                            }
                        }
                    } else {
                        warn!("Animations without a sampler input are not supported");
                        return Err(GltfError::MissingAnimationSampler(animation.index()));
                    };

                    if keyframe_timestamps.is_empty() {
                        warn!("Tried to load animation with no keyframe timestamps");
                        continue;
                    }

                    let maybe_curve: Option<VariableCurve> = if let Some(outputs) =
                        reader.read_outputs()
                    {
                        match outputs {
                            ReadOutputs::Translations(tr) => {
                                let translation_property = animated_field!(Transform::translation);
                                let translations: Vec<Vec3> = tr.map(Vec3::from).collect();
                                if keyframe_timestamps.len() == 1 {
                                    Some(VariableCurve::new(AnimatableCurve::new(
                                        translation_property,
                                        ConstantCurve::new(Interval::EVERYWHERE, translations[0]),
                                    )))
                                } else {
                                    match interpolation {
                                        gltf::animation::Interpolation::Linear => {
                                            UnevenSampleAutoCurve::new(
                                                keyframe_timestamps.into_iter().zip(translations),
                                            )
                                            .ok()
                                            .map(
                                                |curve| {
                                                    VariableCurve::new(AnimatableCurve::new(
                                                        translation_property,
                                                        curve,
                                                    ))
                                                },
                                            )
                                        }
                                        gltf::animation::Interpolation::Step => {
                                            SteppedKeyframeCurve::new(
                                                keyframe_timestamps.into_iter().zip(translations),
                                            )
                                            .ok()
                                            .map(
                                                |curve| {
                                                    VariableCurve::new(AnimatableCurve::new(
                                                        translation_property,
                                                        curve,
                                                    ))
                                                },
                                            )
                                        }
                                        gltf::animation::Interpolation::CubicSpline => {
                                            CubicKeyframeCurve::new(
                                                keyframe_timestamps,
                                                translations,
                                            )
                                            .ok()
                                            .map(
                                                |curve| {
                                                    VariableCurve::new(AnimatableCurve::new(
                                                        translation_property,
                                                        curve,
                                                    ))
                                                },
                                            )
                                        }
                                    }
                                }
                            }
                            ReadOutputs::Rotations(rots) => {
                                let rotation_property = animated_field!(Transform::rotation);
                                let rotations: Vec<Quat> =
                                    rots.into_f32().map(Quat::from_array).collect();
                                if keyframe_timestamps.len() == 1 {
                                    Some(VariableCurve::new(AnimatableCurve::new(
                                        rotation_property,
                                        ConstantCurve::new(Interval::EVERYWHERE, rotations[0]),
                                    )))
                                } else {
                                    match interpolation {
                                        gltf::animation::Interpolation::Linear => {
                                            UnevenSampleAutoCurve::new(
                                                keyframe_timestamps.into_iter().zip(rotations),
                                            )
                                            .ok()
                                            .map(
                                                |curve| {
                                                    VariableCurve::new(AnimatableCurve::new(
                                                        rotation_property,
                                                        curve,
                                                    ))
                                                },
                                            )
                                        }
                                        gltf::animation::Interpolation::Step => {
                                            SteppedKeyframeCurve::new(
                                                keyframe_timestamps.into_iter().zip(rotations),
                                            )
                                            .ok()
                                            .map(
                                                |curve| {
                                                    VariableCurve::new(AnimatableCurve::new(
                                                        rotation_property,
                                                        curve,
                                                    ))
                                                },
                                            )
                                        }
                                        gltf::animation::Interpolation::CubicSpline => {
                                            CubicRotationCurve::new(
                                                keyframe_timestamps,
                                                rotations.into_iter().map(Vec4::from),
                                            )
                                            .ok()
                                            .map(
                                                |curve| {
                                                    VariableCurve::new(AnimatableCurve::new(
                                                        rotation_property,
                                                        curve,
                                                    ))
                                                },
                                            )
                                        }
                                    }
                                }
                            }
                            ReadOutputs::Scales(scale) => {
                                let scale_property = animated_field!(Transform::scale);
                                let scales: Vec<Vec3> = scale.map(Vec3::from).collect();
                                if keyframe_timestamps.len() == 1 {
                                    Some(VariableCurve::new(AnimatableCurve::new(
                                        scale_property,
                                        ConstantCurve::new(Interval::EVERYWHERE, scales[0]),
                                    )))
                                } else {
                                    match interpolation {
                                        gltf::animation::Interpolation::Linear => {
                                            UnevenSampleAutoCurve::new(
                                                keyframe_timestamps.into_iter().zip(scales),
                                            )
                                            .ok()
                                            .map(
                                                |curve| {
                                                    VariableCurve::new(AnimatableCurve::new(
                                                        scale_property,
                                                        curve,
                                                    ))
                                                },
                                            )
                                        }
                                        gltf::animation::Interpolation::Step => {
                                            SteppedKeyframeCurve::new(
                                                keyframe_timestamps.into_iter().zip(scales),
                                            )
                                            .ok()
                                            .map(
                                                |curve| {
                                                    VariableCurve::new(AnimatableCurve::new(
                                                        scale_property,
                                                        curve,
                                                    ))
                                                },
                                            )
                                        }
                                        gltf::animation::Interpolation::CubicSpline => {
                                            CubicKeyframeCurve::new(keyframe_timestamps, scales)
                                                .ok()
                                                .map(|curve| {
                                                    VariableCurve::new(AnimatableCurve::new(
                                                        scale_property,
                                                        curve,
                                                    ))
                                                })
                                        }
                                    }
                                }
                            }
                            ReadOutputs::MorphTargetWeights(weights) => {
                                let weights: Vec<f32> = weights.into_f32().collect();
                                if keyframe_timestamps.len() == 1 {
                                    #[expect(
                                        clippy::unnecessary_map_on_constructor,
                                        reason = "While the mapping is unnecessary, it is much more readable at this level of indentation. Additionally, mapping makes it more consistent with the other branches."
                                    )]
                                    Some(ConstantCurve::new(Interval::EVERYWHERE, weights))
                                        .map(WeightsCurve)
                                        .map(VariableCurve::new)
                                } else {
                                    match interpolation {
                                        gltf::animation::Interpolation::Linear => {
                                            WideLinearKeyframeCurve::new(
                                                keyframe_timestamps,
                                                weights,
                                            )
                                            .ok()
                                            .map(WeightsCurve)
                                            .map(VariableCurve::new)
                                        }
                                        gltf::animation::Interpolation::Step => {
                                            WideSteppedKeyframeCurve::new(
                                                keyframe_timestamps,
                                                weights,
                                            )
                                            .ok()
                                            .map(WeightsCurve)
                                            .map(VariableCurve::new)
                                        }
                                        gltf::animation::Interpolation::CubicSpline => {
                                            WideCubicKeyframeCurve::new(
                                                keyframe_timestamps,
                                                weights,
                                            )
                                            .ok()
                                            .map(WeightsCurve)
                                            .map(VariableCurve::new)
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        warn!("Animations without a sampler output are not supported");
                        return Err(GltfError::MissingAnimationSampler(animation.index()));
                    };

                    let Some(curve) = maybe_curve else {
                        warn!(
                            "Invalid keyframe data for node {}; curve could not be constructed",
                            node.index()
                        );
                        continue;
                    };

                    if let Some((root_index, path)) = paths.get(&node.index()) {
                        animation_roots.insert(*root_index);
                        animation_clip.add_variable_curve_to_target(
                            AnimationTargetId::from_names(path.iter()),
                            curve,
                        );
                    } else {
                        warn!(
                        "Animation ignored for node {}: part of its hierarchy is missing a name",
                        node.index()
                    );
                    }
                }

                // let extensions handle extension data placed on animations before creating
                // the `Handle`
                for extension in extensions.iter_mut() {
                    extension.on_animation(load_context, &animation, &mut animation_clip);
                }

                let handle = load_context.add_labeled_asset(
                    GltfAssetLabel::Animation(animation.index()).to_string(),
                    animation_clip,
                );
                if let Some(name) = animation.name() {
                    named_animations.insert(name.into(), handle.clone());
                }

                animations.push(handle);
            }

            // let extensions process the collection of animation data
            // this only happens once for each GltfExtensionHandler because
            // it is a hook for Bevy's finalized representation of the animations
            for extension in extensions.iter_mut() {
                extension.on_animations_collected(
                    load_context,
                    &animations,
                    &named_animations,
                    &animation_roots,
                );
            }

            (animations, named_animations, animation_roots)
        } else {
            Default::default()
        };

        let default_sampler = match settings.default_sampler.as_ref() {
            Some(sampler) => sampler,
            None => &loader.default_sampler.lock().unwrap().clone(),
        };
        // We collect handles to ensure loaded images from paths are not unloaded before they are used elsewhere
        // in the loader. This prevents "reloads", but it also prevents dropping the is_srgb context on reload.
        //
        // In theory we could store a mapping between texture.index() and handle to use
        // later in the loader when looking up handles for materials. However this would mean
        // that the material's load context would no longer track those images as dependencies.
        let mut texture_handles = Vec::new();
        if gltf.textures().len() == 1 || cfg!(target_arch = "wasm32") {
            for texture in gltf.textures() {
                let image = load_image(
                    texture.clone(),
                    &buffer_data,
                    &linear_textures,
                    load_context.path(),
                    loader.supported_compressed_formats,
                    default_sampler,
                    settings,
                )
                .await?;
                image.process_loaded_texture(load_context, &mut texture_handles);
                // let extensions handle texture data
                for extension in extensions.iter_mut() {
                    extension.on_texture(&texture, texture_handles.last().unwrap().clone());
                }
            }
        } else {
            // This cfg is redundant, but if we don't explicitly cfg it out, Wasm will compile it
            // and fail.
            #[cfg(not(target_arch = "wasm32"))]
            {
                let textures = IoTaskPool::get().scope(|scope| {
                    gltf.textures().for_each(|gltf_texture| {
                        let asset_path = load_context.path().clone();
                        let linear_textures = &linear_textures;
                        let buffer_data = &buffer_data;
                        scope.spawn(async move {
                            load_image(
                                gltf_texture,
                                buffer_data,
                                linear_textures,
                                &asset_path,
                                loader.supported_compressed_formats,
                                default_sampler,
                                settings,
                            )
                            .await
                        });
                    });
                });
                // order is preserved if the futures are only spawned from the root scope
                for (result, texture) in textures.into_iter().zip(gltf.textures()) {
                    result?.process_loaded_texture(load_context, &mut texture_handles);
                    // let extensions handle texture data
                    for extension in extensions.iter_mut() {
                        extension.on_texture(&texture, texture_handles.last().unwrap().clone());
                    }
                }
            }
        }

        let mut materials = vec![];
        let mut named_materials = <HashMap<_, _>>::default();
        // Only include materials in the output if they're set to be retained in the MAIN_WORLD and/or RENDER_WORLD by the load_materials flag
        if !settings.load_materials.is_empty() {
            // NOTE: materials must be loaded after textures because image load() calls will happen
            // before load_builder().with_settings().load(), preventing is_srgb from being set
            // properly.
            for material in gltf.materials() {
                let (label, gltf_material) = load_material(
                    &material,
                    &texture_handles,
                    false,
                    load_context.path().clone(),
                );
                let handle = load_context.add_labeled_asset(label.clone(), gltf_material.clone());

                if let Some(name) = material.name() {
                    named_materials.insert(name.into(), handle.clone());
                }

                // let extensions handle material data
                for extension in extensions.iter_mut() {
                    extension.on_material(
                        load_context,
                        &material,
                        handle.clone(),
                        &gltf_material,
                        &label.clone(),
                    );
                }

                materials.push(handle);
            }
        }
        let mut meshes = vec![];
        let mut named_meshes = <HashMap<_, _>>::default();
        let mut meshes_on_skinned_nodes = <HashSet<_>>::default();
        let mut meshes_on_non_skinned_nodes = <HashSet<_>>::default();
        for gltf_node in gltf.nodes() {
            if gltf_node.skin().is_some() {
                if let Some(mesh) = gltf_node.mesh() {
                    meshes_on_skinned_nodes.insert(mesh.index());
                }
            } else if let Some(mesh) = gltf_node.mesh() {
                meshes_on_non_skinned_nodes.insert(mesh.index());
            }
        }
        for gltf_mesh in gltf.meshes() {
            let mut primitives = vec![];

            let gltf_mesh_on_skinned_nodes = meshes_on_skinned_nodes.contains(&gltf_mesh.index());
            let gltf_mesh_on_non_skinned_nodes =
                meshes_on_non_skinned_nodes.contains(&gltf_mesh.index());

            for primitive in gltf_mesh.primitives() {
                let primitive_label = GltfAssetLabel::Primitive {
                    mesh: gltf_mesh.index(),
                    primitive: primitive.index(),
                };

                // a Mesh that can be generated by a user's extension,
                // such as when decompressing draco buffers
                let mut user_mesh: Option<Mesh> = None;
                for extension in extensions.iter_mut() {
                    extension
                        .on_gltf_primitive(
                            load_context,
                            &gltf,
                            &gltf_mesh,
                            &primitive,
                            &buffer_data,
                            &loader.custom_vertex_attributes,
                            gltf_mesh_on_skinned_nodes,
                            gltf_mesh_on_non_skinned_nodes,
                            &mut user_mesh,
                        )
                        .await;
                }

                let mut mesh = if let Some(user_mesh_provided) = user_mesh {
                    user_mesh_provided
                } else {
                    let primitive_topology = primitive_topology(primitive.mode())?;

                    let mut mesh = Mesh::new(primitive_topology, settings.load_meshes);

                    // Read vertex attributes
                    for (semantic, accessor) in primitive.attributes() {
                        if [Semantic::Joints(0), Semantic::Weights(0)].contains(&semantic) {
                            if !gltf_mesh_on_skinned_nodes {
                                warn!(
                                    "Ignoring attribute {:?} for skinned mesh {} used on non skinned nodes (NODE_SKINNED_MESH_WITHOUT_SKIN)",
                                    semantic,
                                    primitive_label
                                );
                                continue;
                            } else if gltf_mesh_on_non_skinned_nodes {
                                error!("Skinned mesh {} used on both skinned and non skin nodes, this is likely to cause an error (NODE_SKINNED_MESH_WITHOUT_SKIN)", primitive_label);
                            }
                        }
                        match convert_attribute(
                            semantic,
                            accessor,
                            &buffer_data,
                            &loader.custom_vertex_attributes,
                            convert_coordinates.rotate_meshes,
                        ) {
                            Ok((attribute, values)) => mesh.insert_attribute(attribute, values),
                            Err(err) => warn!("{}", err),
                        }
                    }

                    // Read vertex indices
                    let reader =
                        primitive.reader(|buffer| Some(buffer_data[buffer.index()].as_slice()));
                    if let Some(indices) = reader.read_indices() {
                        mesh.insert_indices(match indices {
                            ReadIndices::U8(is) => Indices::U16(is.map(|x| x as u16).collect()),
                            ReadIndices::U16(is) => Indices::U16(is.collect()),
                            ReadIndices::U32(is) => Indices::U32(is.collect()),
                        });
                    };

                    {
                        let morph_target_reader = reader.read_morph_targets();
                        if morph_target_reader.len() != 0 {
                            mesh.set_morph_targets(
                                morph_target_reader
                                    .flat_map(|i| PrimitiveMorphAttributesIter {
                                        convert_coordinates: convert_coordinates.rotate_meshes,
                                        positions: i.0,
                                        normals: i.1,
                                        tangents: i.2,
                                    })
                                    .collect(),
                            );

                            let extras = gltf_mesh.extras().as_ref();
                            if let Some(names) = extras.and_then(|extras| {
                                serde_json::from_str::<MorphTargetNames>(extras.get()).ok()
                            }) {
                                mesh.set_morph_target_names(names.target_names);
                            }
                        }
                    }
                    mesh
                };

                if mesh.attribute(Mesh::ATTRIBUTE_NORMAL).is_none()
                    && matches!(mesh.primitive_topology(), PrimitiveTopology::TriangleList)
                {
                    tracing::debug!(
                        "Automatically calculating missing vertex normals for geometry."
                    );
                    let vertex_count_before = mesh.count_vertices();
                    mesh.duplicate_vertices();
                    mesh.compute_flat_normals();
                    let vertex_count_after = mesh.count_vertices();
                    if vertex_count_before != vertex_count_after {
                        tracing::debug!("Missing vertex normals in indexed geometry, computing them as flat. Vertex count increased from {} to {}", vertex_count_before, vertex_count_after);
                    } else {
                        tracing::debug!(
                            "Missing vertex normals in indexed geometry, computing them as flat."
                        );
                    }
                }

                if !mesh.contains_attribute(Mesh::ATTRIBUTE_TANGENT)
                    && mesh.contains_attribute(Mesh::ATTRIBUTE_NORMAL)
                    && needs_tangents(&primitive.material())
                {
                    tracing::debug!(
                        "Missing vertex tangents for {}, computing them using the mikktspace algorithm. Consider using a tool such as Blender to pre-compute the tangents.", file_name
                    );

                    let generate_tangents_span = info_span!("generate_tangents", name = file_name);

                    generate_tangents_span.in_scope(|| {
                        if let Err(err) = mesh.generate_tangents() {
                            warn!(
                                "Failed to generate vertex tangents using the mikktspace algorithm: {}",
                                err
                            );
                        }
                    });
                }

                if (skinned_mesh_bounds_policy == GltfSkinnedMeshBoundsPolicy::Dynamic)
                    && meshes_on_skinned_nodes.contains(&gltf_mesh.index())
                    && let Err(err) = mesh.generate_skinned_mesh_bounds()
                {
                    warn!("Failed to generate skinned mesh bounds: {err}");
                }

                let mesh_handle = load_context.add_labeled_asset(primitive_label.to_string(), mesh);
                primitives.push(super::GltfPrimitive::new(
                    &gltf_mesh,
                    &primitive,
                    mesh_handle,
                    primitive
                        .material()
                        .index()
                        .and_then(|i| materials.get(i).cloned()),
                    primitive.extras().as_deref().map(GltfExtras::from),
                    primitive
                        .material()
                        .extras()
                        .as_deref()
                        .map(GltfExtras::from),
                ));
            }

            let mesh = super::GltfMesh::new(
                &gltf_mesh,
                primitives,
                gltf_mesh.extras().as_deref().map(GltfExtras::from),
            );

            let handle = load_context.add_labeled_asset(mesh.asset_label().to_string(), mesh);
            if let Some(name) = gltf_mesh.name() {
                named_meshes.insert(name.into(), handle.clone());
            }
            for extension in extensions.iter_mut() {
                extension.on_gltf_mesh(load_context, &gltf_mesh, handle.clone());
            }

            meshes.push(handle);
        }

        let skinned_mesh_inverse_bindposes: Vec<_> = gltf
            .skins()
            .map(|gltf_skin| {
                let reader = gltf_skin.reader(|buffer| Some(&buffer_data[buffer.index()]));
                let local_to_bone_bind_matrices: Vec<Mat4> = reader
                    .read_inverse_bind_matrices()
                    .map(|mats| {
                        mats.map(|mat| {
                            Mat4::from_cols_array_2d(&mat)
                                * convert_coordinates.mesh_conversion_mat4()
                        })
                        .collect()
                    })
                    .unwrap_or_else(|| {
                        core::iter::repeat_n(Mat4::IDENTITY, gltf_skin.joints().len()).collect()
                    });

                load_context.add_labeled_asset(
                    GltfAssetLabel::InverseBindMatrices(gltf_skin.index()).to_string(),
                    SkinnedMeshInverseBindposes::from(local_to_bone_bind_matrices),
                )
            })
            .collect();

        let mut nodes = HashMap::<usize, Handle<GltfNode>>::default();
        let mut named_nodes = <HashMap<_, _>>::default();
        let mut skins = <HashMap<_, _>>::default();
        let mut named_skins = <HashMap<_, _>>::default();

        // First, create the node handles.
        for node in gltf.nodes() {
            let label = GltfAssetLabel::Node(node.index());
            let label_handle = load_context.get_label_handle(label.to_string());
            nodes.insert(node.index(), label_handle);
        }

        // Then check for cycles.
        check_for_cycles(&gltf)?;

        // Now populate the nodes.
        for node in gltf.nodes() {
            let skin = node.skin().map(|skin| {
                skins
                    .entry(skin.index())
                    .or_insert_with(|| {
                        let joints: Vec<_> = skin
                            .joints()
                            .map(|joint| nodes.get(&joint.index()).unwrap().clone())
                            .collect();

                        if joints.len() > MAX_JOINTS {
                            warn!(
                                "The glTF skin {} has {} joints, but the maximum supported is {}",
                                skin.name()
                                    .map(ToString::to_string)
                                    .unwrap_or_else(|| skin.index().to_string()),
                                joints.len(),
                                MAX_JOINTS
                            );
                        }

                        let gltf_skin = GltfSkin::new(
                            &skin,
                            joints,
                            skinned_mesh_inverse_bindposes[skin.index()].clone(),
                            skin.extras().as_deref().map(GltfExtras::from),
                        );

                        let handle = load_context
                            .add_labeled_asset(gltf_skin.asset_label().to_string(), gltf_skin);

                        if let Some(name) = skin.name() {
                            named_skins.insert(name.into(), handle.clone());
                        }

                        handle
                    })
                    .clone()
            });

            let children = node
                .children()
                .map(|child| nodes.get(&child.index()).unwrap().clone())
                .collect();

            let mesh = node
                .mesh()
                .map(|mesh| mesh.index())
                .and_then(|i| meshes.get(i).cloned());

            let gltf_node = GltfNode::new(
                &node,
                children,
                mesh,
                node_transform(&node),
                skin,
                node.extras().as_deref().map(GltfExtras::from),
            );

            #[cfg(feature = "bevy_animation")]
            let gltf_node = gltf_node.with_animation_root(animation_roots.contains(&node.index()));

            let handle =
                load_context.add_labeled_asset(gltf_node.asset_label().to_string(), gltf_node);
            nodes.insert(node.index(), handle.clone());
            if let Some(name) = node.name() {
                named_nodes.insert(name.into(), handle);
            }
        }

        let mut nodes_to_sort = nodes.into_iter().collect::<Vec<_>>();
        nodes_to_sort.sort_by_key(|(i, _)| *i);
        let nodes = nodes_to_sort
            .into_iter()
            .map(|(_, resolved)| resolved)
            .collect();

        let mut scenes = vec![];
        let mut named_scenes = <HashMap<_, _>>::default();
        let mut active_camera_found = false;
        for scene in gltf.scenes() {
            let mut err = None;
            let mut world = World::default();
            let mut node_index_to_entity_map = <HashMap<_, _>>::default();
            let mut entity_to_skin_index_map = EntityHashMap::default();
            let mut scene_load_context = load_context.begin_labeled_asset();

            let world_root_transform = convert_coordinates.scene_conversion_transform();

            let world_root_id = world
                .spawn((
                    world_root_transform,
                    Visibility::default(),
                    Name::new(
                        scene
                            .name()
                            .map(ToOwned::to_owned)
                            .unwrap_or_else(|| format!("Scene{}", scene.index())),
                    ),
                ))
                .with_children(|parent| {
                    for node in scene.nodes() {
                        let result = load_node(
                            &node,
                            parent,
                            load_context,
                            &mut scene_load_context,
                            settings,
                            &mut node_index_to_entity_map,
                            &mut entity_to_skin_index_map,
                            &mut active_camera_found,
                            &Transform::default(),
                            #[cfg(feature = "bevy_animation")]
                            &animation_roots,
                            #[cfg(feature = "bevy_animation")]
                            None,
                            &texture_handles,
                            &convert_coordinates,
                            &mut extensions,
                            skinned_mesh_bounds_policy,
                        );
                        if result.is_err() {
                            err = Some(result);
                            return;
                        }
                    }
                })
                .id();

            if let Some(scene_name) = scene.name() {
                world
                    .entity_mut(world_root_id)
                    .insert(GltfSceneName(scene_name.to_owned()));
            };

            if let Some(extras) = scene.extras().as_ref() {
                world.entity_mut(world_root_id).insert(GltfSceneExtras {
                    value: extras.get().to_string(),
                });
            }

            if let Some(Err(err)) = err {
                return Err(err);
            }

            #[cfg(feature = "bevy_animation")]
            {
                // for each node root in a scene, check if it's the root of an animation
                // if it is, add the AnimationPlayer component
                for node in scene.nodes() {
                    if animation_roots.contains(&node.index()) {
                        world
                            .entity_mut(*node_index_to_entity_map.get(&node.index()).unwrap())
                            .insert(AnimationPlayer::default());
                    }
                }
            }

            for (&entity, &skin_index) in &entity_to_skin_index_map {
                let mut entity = world.entity_mut(entity);
                let skin = gltf.skins().nth(skin_index).unwrap();
                let joint_entities: Vec<_> = skin
                    .joints()
                    .map(|node| node_index_to_entity_map[&node.index()])
                    .collect();

                entity.insert(SkinnedMesh {
                    inverse_bindposes: skinned_mesh_inverse_bindposes[skin_index].clone(),
                    joints: joint_entities,
                });
            }

            // let extensions handle scene extension data
            for extension in extensions.iter_mut() {
                extension.on_scene_completed(
                    &mut scene_load_context,
                    &scene,
                    world_root_id,
                    &mut world,
                );
            }

            let loaded_scene = scene_load_context.finish(WorldAsset::new(world));
            let scene_handle = load_context.add_loaded_labeled_asset(
                GltfAssetLabel::Scene(scene.index()).to_string(),
                loaded_scene,
            );

            if let Some(name) = scene.name() {
                named_scenes.insert(name.into(), scene_handle.clone());
            }
            scenes.push(scene_handle);
        }

        Ok(Gltf {
            default_scene: gltf
                .default_scene()
                .and_then(|scene| scenes.get(scene.index()))
                .cloned(),
            scenes,
            named_scenes,
            meshes,
            named_meshes,
            skins: skins.into_values().collect(),
            named_skins,
            materials,
            named_materials,
            nodes,
            named_nodes,
            #[cfg(feature = "bevy_animation")]
            animations,
            #[cfg(feature = "bevy_animation")]
            named_animations,
            source: if settings.include_source {
                Some(gltf)
            } else {
                None
            },
        })
    }
}

impl AssetLoader for GltfLoader {
    type Asset = Gltf;
    type Settings = GltfLoaderSettings;
    type Error = GltfError;
    async fn load(
        &self,
        reader: &mut dyn Reader,
        settings: &GltfLoaderSettings,
        load_context: &mut LoadContext<'_>,
    ) -> Result<Gltf, Self::Error> {
        let mut bytes = Vec::new();
        reader.read_to_end(&mut bytes).await?;

        Self::load_gltf(self, &bytes, load_context, settings).await
    }

    fn extensions(&self) -> &[&str] {
        &["gltf", "glb"]
    }
}

/// Loads a glTF texture as a bevy [`Image`] and returns it together with its label.
async fn load_image<'a, 'b>(
    gltf_texture: gltf::Texture<'a>,
    buffer_data: &[Vec<u8>],
    linear_textures: &HashSet<usize>,
    gltf_path: &'b AssetPath<'b>,
    supported_compressed_formats: CompressedImageFormats,
    default_sampler: &ImageSamplerDescriptor,
    settings: &GltfLoaderSettings,
) -> Result<ImageOrPath, GltfError> {
    let is_srgb = !linear_textures.contains(&gltf_texture.index());
    let sampler_descriptor = if settings.override_sampler {
        default_sampler.clone()
    } else {
        texture_sampler(&gltf_texture, default_sampler)
    };

    match gltf_texture.source().source() {
        Source::View { view, mime_type } => {
            let start = view.offset();
            let end = view.offset() + view.length();
            let buffer = &buffer_data[view.buffer().index()][start..end];
            let image = Image::from_buffer(
                buffer,
                ImageType::MimeType(mime_type),
                supported_compressed_formats,
                is_srgb,
                ImageSampler::Descriptor(sampler_descriptor),
                settings.load_materials,
            )?;
            Ok(ImageOrPath::Image {
                image,
                label: GltfAssetLabel::Texture(gltf_texture.index()),
            })
        }
        Source::Uri { uri, mime_type } => {
            let uri = percent_encoding::percent_decode_str(uri)
                .decode_utf8()
                .unwrap();
            let uri = uri.as_ref();
            if let Ok(data_uri) = DataUri::parse(uri) {
                let bytes = data_uri.decode()?;
                let image_type = ImageType::MimeType(data_uri.mime_type);
                Ok(ImageOrPath::Image {
                    image: Image::from_buffer(
                        &bytes,
                        mime_type.map(ImageType::MimeType).unwrap_or(image_type),
                        supported_compressed_formats,
                        is_srgb,
                        ImageSampler::Descriptor(sampler_descriptor),
                        settings.load_materials,
                    )?,
                    label: GltfAssetLabel::Texture(gltf_texture.index()),
                })
            } else {
                let image_path = gltf_path
                    .resolve_embed_str(uri)
                    .map_err(|err| GltfError::InvalidImageUri(uri.to_owned(), err))?;
                Ok(ImageOrPath::Path {
                    path: image_path,
                    is_srgb,
                    sampler_descriptor,
                    render_asset_usages: settings.load_materials,
                })
            }
        }
    }
}

/// Loads a glTF material as a bevy [`GltfMaterial`] and returns the label and material.
fn load_material(
    material: &Material,
    textures: &[Handle<Image>],
    is_scale_inverted: bool,
    asset_path: AssetPath<'_>,
) -> (String, GltfMaterial) {
    let pbr = material.pbr_metallic_roughness();

    // TODO: handle missing label handle errors here?
    let color = pbr.base_color_factor();
    let base_color_channel = pbr
        .base_color_texture()
        .map(|info| uv_channel(material, "base color", info.tex_coord()))
        .unwrap_or_default();
    let base_color_texture = pbr.base_color_texture().map(|info| {
        textures
            .get(info.texture().index())
            .cloned()
            .unwrap_or_default()
    });

    let uv_transform = pbr
        .base_color_texture()
        .and_then(|info| info.texture_transform().map(texture_transform_to_affine2))
        .unwrap_or_default();

    let normal_map_channel = material
        .normal_texture()
        .map(|info| uv_channel(material, "normal map", info.tex_coord()))
        .unwrap_or_default();
    let normal_map_texture: Option<Handle<Image>> =
        material.normal_texture().map(|normal_texture| {
            // TODO: handle normal_texture.scale
            textures
                .get(normal_texture.texture().index())
                .cloned()
                .unwrap_or_default()
        });

    let metallic_roughness_channel = pbr
        .metallic_roughness_texture()
        .map(|info| uv_channel(material, "metallic/roughness", info.tex_coord()))
        .unwrap_or_default();
    let metallic_roughness_texture = pbr.metallic_roughness_texture().map(|info| {
        warn_on_differing_texture_transforms(material, &info, uv_transform, "metallic/roughness");
        textures
            .get(info.texture().index())
            .cloned()
            .unwrap_or_default()
    });

    let occlusion_channel = material
        .occlusion_texture()
        .map(|info| uv_channel(material, "occlusion", info.tex_coord()))
        .unwrap_or_default();
    let occlusion_texture = material.occlusion_texture().map(|occlusion_texture| {
        // TODO: handle occlusion_texture.strength() (a scalar multiplier for occlusion strength)
        textures
            .get(occlusion_texture.texture().index())
            .cloned()
            .unwrap_or_default()
    });

    let emissive = material.emissive_factor();
    let emissive_channel = material
        .emissive_texture()
        .map(|info| uv_channel(material, "emissive", info.tex_coord()))
        .unwrap_or_default();
    let emissive_texture = material.emissive_texture().map(|info| {
        // TODO: handle occlusion_texture.strength() (a scalar multiplier for occlusion strength)
        warn_on_differing_texture_transforms(material, &info, uv_transform, "emissive");
        textures
            .get(info.texture().index())
            .cloned()
            .unwrap_or_default()
    });

    #[cfg(feature = "pbr_transmission_textures")]
    let (specular_transmission, specular_transmission_channel, specular_transmission_texture) =
        material
            .transmission()
            .map_or((0.0, UvChannel::Uv0, None), |transmission| {
                let specular_transmission_channel = transmission
                    .transmission_texture()
                    .map(|info| uv_channel(material, "specular/transmission", info.tex_coord()))
                    .unwrap_or_default();
                let transmission_texture: Option<Handle<Image>> = transmission
                    .transmission_texture()
                    .map(|transmission_texture| {
                        textures
                            .get(transmission_texture.texture().index())
                            .cloned()
                            .unwrap_or_default()
                    });

                (
                    transmission.transmission_factor(),
                    specular_transmission_channel,
                    transmission_texture,
                )
            });

    #[cfg(not(feature = "pbr_transmission_textures"))]
    let specular_transmission = material
        .transmission()
        .map_or(0.0, |transmission| transmission.transmission_factor());

    #[cfg(feature = "pbr_transmission_textures")]
    let (thickness, thickness_channel, thickness_texture, attenuation_distance, attenuation_color) =
        material.volume().map_or(
            (0.0, UvChannel::Uv0, None, f32::INFINITY, [1.0, 1.0, 1.0]),
            |volume| {
                let thickness_channel = volume
                    .thickness_texture()
                    .map(|info| uv_channel(material, "thickness", info.tex_coord()))
                    .unwrap_or_default();
                let thickness_texture: Option<Handle<Image>> =
                    volume.thickness_texture().map(|thickness_texture| {
                        textures
                            .get(thickness_texture.texture().index())
                            .cloned()
                            .unwrap_or_default()
                    });

                (
                    volume.thickness_factor(),
                    thickness_channel,
                    thickness_texture,
                    volume.attenuation_distance(),
                    volume.attenuation_color(),
                )
            },
        );

    #[cfg(not(feature = "pbr_transmission_textures"))]
    let (thickness, attenuation_distance, attenuation_color) =
        material
            .volume()
            .map_or((0.0, f32::INFINITY, [1.0, 1.0, 1.0]), |volume| {
                (
                    volume.thickness_factor(),
                    volume.attenuation_distance(),
                    volume.attenuation_color(),
                )
            });

    let ior = material.ior().unwrap_or(1.5);

    // Parse the `KHR_materials_clearcoat` extension data if necessary.
    let clearcoat =
        ClearcoatExtension::parse(material, textures, asset_path.clone()).unwrap_or_default();

    // Parse the `KHR_materials_anisotropy` extension data if necessary.
    let anisotropy =
        AnisotropyExtension::parse(material, textures, asset_path.clone()).unwrap_or_default();

    // Parse the `KHR_materials_specular` extension data if necessary.
    let specular =
        SpecularExtension::parse(material, textures, asset_path.clone()).unwrap_or_default();

    // We need to operate in the Linear color space and be willing to exceed 1.0 in our channels
    let base_emissive = LinearRgba::rgb(emissive[0], emissive[1], emissive[2]);
    let emissive = base_emissive * material.emissive_strength().unwrap_or(1.0);

    let gltf_material = GltfMaterial {
        base_color: Color::linear_rgba(color[0], color[1], color[2], color[3]),
        base_color_channel,
        base_color_texture,
        perceptual_roughness: pbr.roughness_factor(),
        metallic: pbr.metallic_factor(),
        metallic_roughness_channel,
        metallic_roughness_texture,
        normal_map_channel,
        normal_map_texture,
        double_sided: material.double_sided(),
        cull_mode: if material.double_sided() {
            None
        } else if is_scale_inverted {
            Some(Face::Front)
        } else {
            Some(Face::Back)
        },
        occlusion_channel,
        occlusion_texture,
        emissive,
        emissive_channel,
        emissive_texture,
        specular_transmission,
        #[cfg(feature = "pbr_transmission_textures")]
        specular_transmission_channel,
        #[cfg(feature = "pbr_transmission_textures")]
        specular_transmission_texture,
        thickness,
        #[cfg(feature = "pbr_transmission_textures")]
        thickness_channel,
        #[cfg(feature = "pbr_transmission_textures")]
        thickness_texture,
        ior,
        attenuation_distance,
        attenuation_color: Color::linear_rgb(
            attenuation_color[0],
            attenuation_color[1],
            attenuation_color[2],
        ),
        unlit: material.unlit(),
        alpha_mode: alpha_mode(material),
        uv_transform,
        clearcoat: clearcoat.clearcoat_factor.unwrap_or_default() as f32,
        clearcoat_perceptual_roughness: clearcoat.clearcoat_roughness_factor.unwrap_or_default()
            as f32,
        #[cfg(feature = "pbr_multi_layer_material_textures")]
        clearcoat_channel: clearcoat.clearcoat_channel,
        #[cfg(feature = "pbr_multi_layer_material_textures")]
        clearcoat_texture: clearcoat.clearcoat_texture,
        #[cfg(feature = "pbr_multi_layer_material_textures")]
        clearcoat_roughness_channel: clearcoat.clearcoat_roughness_channel,
        #[cfg(feature = "pbr_multi_layer_material_textures")]
        clearcoat_roughness_texture: clearcoat.clearcoat_roughness_texture,
        #[cfg(feature = "pbr_multi_layer_material_textures")]
        clearcoat_normal_channel: clearcoat.clearcoat_normal_channel,
        #[cfg(feature = "pbr_multi_layer_material_textures")]
        clearcoat_normal_texture: clearcoat.clearcoat_normal_texture,
        anisotropy_strength: anisotropy.anisotropy_strength.unwrap_or_default() as f32,
        anisotropy_rotation: anisotropy.anisotropy_rotation.unwrap_or_default() as f32,
        #[cfg(feature = "pbr_anisotropy_texture")]
        anisotropy_channel: anisotropy.anisotropy_channel,
        #[cfg(feature = "pbr_anisotropy_texture")]
        anisotropy_texture: anisotropy.anisotropy_texture,
        // From the `KHR_materials_specular` spec:
        // <https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_specular#materials-with-reflectance-parameter>
        reflectance: specular.specular_factor.unwrap_or(1.0) as f32 * 0.5,
        #[cfg(feature = "pbr_specular_textures")]
        specular_channel: specular.specular_channel,
        #[cfg(feature = "pbr_specular_textures")]
        specular_texture: specular.specular_texture,
        specular_tint: match specular.specular_color_factor {
            Some(color) => Color::linear_rgb(color[0] as f32, color[1] as f32, color[2] as f32),
            None => Color::WHITE,
        },
        #[cfg(feature = "pbr_specular_textures")]
        specular_tint_channel: specular.specular_color_channel,
        #[cfg(feature = "pbr_specular_textures")]
        specular_tint_texture: specular.specular_color_texture,
    };

    (
        material_label(material, is_scale_inverted).to_string(),
        gltf_material,
    )
}

/// Loads a glTF node.
#[cfg_attr(
    not(target_arch = "wasm32"),
    expect(
        clippy::result_large_err,
        reason = "`GltfError` is only barely past the threshold for large errors."
    )
)]
fn load_node(
    gltf_node: &Node,
    child_spawner: &mut ChildSpawner,
    root_load_context: &LoadContext,
    load_context: &mut LoadContext,
    settings: &GltfLoaderSettings,
    node_index_to_entity_map: &mut HashMap<usize, Entity>,
    entity_to_skin_index_map: &mut EntityHashMap<usize>,
    active_camera_found: &mut bool,
    parent_transform: &Transform,
    #[cfg(feature = "bevy_animation")] animation_roots: &HashSet<usize>,
    #[cfg(feature = "bevy_animation")] mut animation_context: Option<AnimationContext>,
    textures: &[Handle<Image>],
    convert_coordinates: &GltfConvertCoordinates,
    extensions: &mut [Box<dyn extensions::ErasedGltfExtensionHandler>],
    skinned_mesh_bounds_policy: GltfSkinnedMeshBoundsPolicy,
) -> Result<(), GltfError> {
    let mut gltf_error = None;
    let transform = node_transform(gltf_node);
    let world_transform = *parent_transform * transform;
    // according to https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#instantiation,
    // if the determinant of the transform is negative we must invert the winding order of
    // triangles in meshes on the node.
    // instead we equivalently test if the global scale is inverted by checking if the number
    // of negative scale factors is odd. if so we will assign a copy of the material with face
    // culling inverted, rather than modifying the mesh data directly.
    let is_scale_inverted = world_transform.scale.is_negative_bitmask().count_ones() & 1 == 1;
    let mut node = child_spawner.spawn((transform, Visibility::default()));

    let name = node_name(gltf_node);
    node.insert(name.clone());

    #[cfg(feature = "bevy_animation")]
    if animation_context.is_none() && animation_roots.contains(&gltf_node.index()) {
        // This is an animation root. Make a new animation context.
        animation_context = Some(AnimationContext {
            root: node.id(),
            path: SmallVec::new(),
        });
    }

    #[cfg(feature = "bevy_animation")]
    if let Some(ref mut animation_context) = animation_context {
        animation_context.path.push(name);

        node.insert((
            AnimationTargetId::from_names(animation_context.path.iter()),
            AnimatedBy(animation_context.root),
        ));
    }

    if let Some(extras) = gltf_node.extras() {
        node.insert(GltfExtras {
            value: extras.get().to_string(),
        });
    }

    // create camera node
    if settings.load_cameras
        && let Some(camera) = gltf_node.camera()
    {
        let projection = match camera.projection() {
            gltf::camera::Projection::Orthographic(orthographic) => {
                let xmag = orthographic.xmag();
                let orthographic_projection = OrthographicProjection {
                    near: orthographic.znear(),
                    far: orthographic.zfar(),
                    scaling_mode: ScalingMode::FixedHorizontal {
                        viewport_width: xmag,
                    },
                    ..OrthographicProjection::default_3d()
                };
                Projection::Orthographic(orthographic_projection)
            }
            gltf::camera::Projection::Perspective(perspective) => {
                let mut perspective_projection: PerspectiveProjection = PerspectiveProjection {
                    fov: perspective.yfov(),
                    near: perspective.znear(),
                    ..Default::default()
                };
                if let Some(zfar) = perspective.zfar() {
                    perspective_projection.far = zfar;
                }
                if let Some(aspect_ratio) = perspective.aspect_ratio() {
                    perspective_projection.aspect_ratio = aspect_ratio;
                }
                Projection::Perspective(perspective_projection)
            }
        };

        node.insert((
            Camera3d::default(),
            projection,
            transform,
            Camera {
                is_active: !*active_camera_found,
                ..Default::default()
            },
        ));

        *active_camera_found = true;
    }

    // Map node index to entity
    node_index_to_entity_map.insert(gltf_node.index(), node.id());

    let mut max_morph_target_count = 0;

    node.with_children(|parent| {
        // Only include meshes in the output if they're set to be retained in the MAIN_WORLD and/or RENDER_WORLD by the load_meshes flag
        if !settings.load_meshes.is_empty()
            && let Some(mesh) = gltf_node.mesh()
        {
            // append primitives
            for primitive in mesh.primitives() {
                let material = primitive.material();
                let mat_label = material_label(&material, is_scale_inverted);
                let material_label = mat_label.to_string();

                // This adds materials that Bevy modifies depending on how they're used, like those with inverted scale.
                if !root_load_context.has_labeled_asset(&material_label)
                    && !load_context.has_labeled_asset(&material_label)
                {
                    let (label, gltf_material) = load_material(
                        &material,
                        textures,
                        is_scale_inverted,
                        load_context.path().clone(),
                    );
                    // TODO: maybe move this into `load_material` ?
                    let handle =
                        load_context.add_labeled_asset(label.clone(), gltf_material.clone());

                    // let extensions handle material data
                    for extension in extensions.iter_mut() {
                        extension.on_material(
                            load_context,
                            &material,
                            handle.clone(),
                            &gltf_material,
                            &label.clone(),
                        );
                    }
                }

                let primitive_label = GltfAssetLabel::Primitive {
                    mesh: mesh.index(),
                    primitive: primitive.index(),
                };
                let bounds = primitive.bounding_box();
                let parent_entity = parent.target_entity();

                // Apply the inverse of the conversion transform that's been
                // applied to the mesh asset. This preserves the mesh's relation
                // to the node transform.
                let mesh_entity_transform = convert_coordinates.mesh_conversion_transform_inverse();

                let mut mesh_entity = parent.spawn((
                    // TODO: handle missing label handle errors here?
                    Mesh3d(load_context.get_label_handle(primitive_label.to_string())),
                    // TODO: could add the `GltfMaterial` here
                    mesh_entity_transform,
                ));

                if gltf_node.skin().is_some() {
                    match skinned_mesh_bounds_policy {
                        GltfSkinnedMeshBoundsPolicy::Dynamic => {
                            mesh_entity.insert(DynamicSkinnedMeshBounds);
                        }
                        GltfSkinnedMeshBoundsPolicy::NoFrustumCulling => {
                            mesh_entity.insert(NoFrustumCulling);
                        }
                        _ => {}
                    }
                }

                let target_count = primitive.morph_targets().len();
                if target_count != 0 {
                    max_morph_target_count = max_morph_target_count.max(target_count);
                    mesh_entity.insert(MeshMorphWeights::Reference(parent_entity));
                }

                let mut bounds_min = Vec3::from_slice(&bounds.min);
                let mut bounds_max = Vec3::from_slice(&bounds.max);

                if convert_coordinates.rotate_meshes {
                    let converted_min = bounds_min.convert_coordinates();
                    let converted_max = bounds_max.convert_coordinates();

                    bounds_min = converted_min.min(converted_max);
                    bounds_max = converted_min.max(converted_max);
                }

                mesh_entity.insert(Aabb::from_min_max(bounds_min, bounds_max));

                if let Some(extras) = primitive.extras() {
                    mesh_entity.insert(GltfExtras {
                        value: extras.get().to_string(),
                    });
                }

                if let Some(extras) = mesh.extras() {
                    mesh_entity.insert(GltfMeshExtras {
                        value: extras.get().to_string(),
                    });
                }

                if let Some(extras) = material.extras() {
                    mesh_entity.insert(GltfMaterialExtras {
                        value: extras.get().to_string(),
                    });
                }

                if let Some(name) = mesh.name() {
                    mesh_entity.insert(GltfMeshName(name.to_string()));
                }

                if let Some(name) = material.name() {
                    mesh_entity.insert(GltfMaterialName(name.to_string()));
                }

                mesh_entity.insert(Name::new(primitive_name(&mesh, &material)));

                // Mark for adding skinned mesh
                if let Some(skin) = gltf_node.skin() {
                    entity_to_skin_index_map.insert(mesh_entity.id(), skin.index());
                }

                // enable extension processing for a Bevy-created construct
                // that is the Mesh and Material merged on a single entity
                for extension in extensions.iter_mut() {
                    extension.on_spawn_mesh_and_material(
                        load_context,
                        &primitive,
                        &mesh,
                        &material,
                        &mut mesh_entity,
                        &mat_label.to_string(),
                    );
                }
            }
        }

        if settings.load_lights
            && let Some(light) = gltf_node.light()
        {
            match light.kind() {
                gltf::khr_lights_punctual::Kind::Directional => {
                    let mut entity = parent.spawn(DirectionalLight {
                        color: Color::srgb_from_array(light.color()),
                        // NOTE: KHR_punctual_lights defines the intensity units for directional
                        // lights in lux (lm/m^2) which is what we need.
                        illuminance: light.intensity(),
                        ..Default::default()
                    });
                    if let Some(name) = light.name() {
                        entity.insert(Name::new(name.to_string()));
                    }
                    if let Some(extras) = light.extras() {
                        entity.insert(GltfExtras {
                            value: extras.get().to_string(),
                        });
                    }
                    for extension in extensions.iter_mut() {
                        extension.on_spawn_light_directional(load_context, gltf_node, &mut entity);
                    }
                }
                gltf::khr_lights_punctual::Kind::Point => {
                    let mut entity = parent.spawn(PointLight {
                        color: Color::srgb_from_array(light.color()),
                        // NOTE: KHR_punctual_lights defines the intensity units for point lights in
                        // candela (lm/sr) which is luminous intensity and we need luminous power.
                        // For a point light, luminous power = 4 * pi * luminous intensity
                        intensity: light.intensity() * core::f32::consts::PI * 4.0,
                        range: light.range().unwrap_or(20.0),
                        radius: 0.0,
                        ..Default::default()
                    });
                    if let Some(name) = light.name() {
                        entity.insert(Name::new(name.to_string()));
                    }
                    if let Some(extras) = light.extras() {
                        entity.insert(GltfExtras {
                            value: extras.get().to_string(),
                        });
                    }
                    for extension in extensions.iter_mut() {
                        extension.on_spawn_light_point(load_context, gltf_node, &mut entity);
                    }
                }
                gltf::khr_lights_punctual::Kind::Spot {
                    inner_cone_angle,
                    outer_cone_angle,
                } => {
                    let mut entity = parent.spawn(SpotLight {
                        color: Color::srgb_from_array(light.color()),
                        // NOTE: KHR_punctual_lights defines the intensity units for spot lights in
                        // candela (lm/sr) which is luminous intensity and we need luminous power.
                        // For a spot light, we map luminous power = 4 * pi * luminous intensity
                        intensity: light.intensity() * core::f32::consts::PI * 4.0,
                        range: light.range().unwrap_or(20.0),
                        radius: light.range().unwrap_or(0.0),
                        inner_angle: inner_cone_angle,
                        outer_angle: outer_cone_angle,
                        ..Default::default()
                    });
                    if let Some(name) = light.name() {
                        entity.insert(Name::new(name.to_string()));
                    }
                    if let Some(extras) = light.extras() {
                        entity.insert(GltfExtras {
                            value: extras.get().to_string(),
                        });
                    }
                    for extension in extensions.iter_mut() {
                        extension.on_spawn_light_spot(load_context, gltf_node, &mut entity);
                    }
                }
            }
        }

        // append other nodes
        for child in gltf_node.children() {
            if let Err(err) = load_node(
                &child,
                parent,
                root_load_context,
                load_context,
                settings,
                node_index_to_entity_map,
                entity_to_skin_index_map,
                active_camera_found,
                &world_transform,
                #[cfg(feature = "bevy_animation")]
                animation_roots,
                #[cfg(feature = "bevy_animation")]
                animation_context.clone(),
                textures,
                convert_coordinates,
                extensions,
                skinned_mesh_bounds_policy,
            ) {
                gltf_error = Some(err);
                return;
            }
        }
    });

    // Only include meshes in the output if they're set to be retained in the MAIN_WORLD and/or RENDER_WORLD by the load_meshes flag
    if !settings.load_meshes.is_empty()
        && let Some(mesh) = gltf_node.mesh()
    {
        // Create the `MorphWeights` component. The weights will be copied
        // from `mesh.weights()` if present. If not then the weights are
        // zero.
        //
        // The glTF spec says that all primitives within a mesh must have
        // the same number of morph targets, and `mesh.weights()` should be
        // equal to that number if present. We're more forgiving and take
        // whichever is largest, leaving any unspecified weights at zero.
        if (max_morph_target_count > 0) || mesh.weights().is_some() {
            let mut weights = Vec::from(mesh.weights().unwrap_or(&[]));

            if max_morph_target_count > weights.len() {
                weights.resize(max_morph_target_count, 0.0);
            }

            let primitive_label = mesh.primitives().next().map(|p| GltfAssetLabel::Primitive {
                mesh: mesh.index(),
                primitive: p.index(),
            });
            let first_mesh =
                primitive_label.map(|label| load_context.get_label_handle(label.to_string()));
            node.insert(MorphWeights::new(weights, first_mesh)?);
        }
    }

    // let extensions process node data
    // This can be *many* kinds of object, so we also
    // give access to the gltf_node, which is needed for
    // accessing Mesh and Material extension data, which
    // are merged onto the same entity in Bevy
    for extension in extensions.iter_mut() {
        extension.on_gltf_node(load_context, gltf_node, &mut node);
    }

    if let Some(err) = gltf_error {
        Err(err)
    } else {
        Ok(())
    }
}

/// Loads the raw glTF buffer data for a specific glTF file.
async fn load_buffers(
    gltf: &gltf::Gltf,
    load_context: &mut LoadContext<'_>,
) -> Result<Vec<Vec<u8>>, GltfError> {
    const VALID_MIME_TYPES: &[&str] = &["application/octet-stream", "application/gltf-buffer"];

    let mut buffer_data = Vec::new();
    for buffer in gltf.buffers() {
        match buffer.source() {
            gltf::buffer::Source::Uri(uri) => {
                let uri = percent_encoding::percent_decode_str(uri)
                    .decode_utf8()
                    .unwrap();
                let uri = uri.as_ref();
                let buffer_bytes = match DataUri::parse(uri) {
                    Ok(data_uri) if VALID_MIME_TYPES.contains(&data_uri.mime_type) => {
                        data_uri.decode()?
                    }
                    Ok(_) => return Err(GltfError::BufferFormatUnsupported),
                    Err(()) => {
                        // TODO: Remove this and add dep
                        let buffer_path = load_context
                            .path()
                            .resolve_embed_str(uri)
                            .map_err(|err| GltfError::InvalidBufferUri(uri.to_owned(), err))?;
                        load_context.read_asset_bytes(buffer_path).await?
                    }
                };
                buffer_data.push(buffer_bytes);
            }
            gltf::buffer::Source::Bin => {
                if let Some(blob) = gltf.blob.as_deref() {
                    buffer_data.push(blob.into());
                } else {
                    return Err(GltfError::MissingBlob);
                }
            }
        }
    }

    Ok(buffer_data)
}

struct DataUri<'a> {
    pub mime_type: &'a str,
    pub base64: bool,
    pub data: &'a str,
}

impl<'a> DataUri<'a> {
    fn parse(uri: &'a str) -> Result<DataUri<'a>, ()> {
        let uri = uri.strip_prefix("data:").ok_or(())?;
        let (mime_type, data) = Self::split_once(uri, ',').ok_or(())?;

        let (mime_type, base64) = match mime_type.strip_suffix(";base64") {
            Some(mime_type) => (mime_type, true),
            None => (mime_type, false),
        };

        Ok(DataUri {
            mime_type,
            base64,
            data,
        })
    }

    fn decode(&self) -> Result<Vec<u8>, base64::DecodeError> {
        if self.base64 {
            base64::Engine::decode(&base64::engine::general_purpose::STANDARD, self.data)
        } else {
            Ok(self.data.as_bytes().to_owned())
        }
    }

    fn split_once(input: &str, delimiter: char) -> Option<(&str, &str)> {
        let mut iter = input.splitn(2, delimiter);
        Some((iter.next()?, iter.next()?))
    }
}

enum ImageOrPath {
    Image {
        image: Image,
        label: GltfAssetLabel,
    },
    Path {
        path: AssetPath<'static>,
        is_srgb: bool,
        sampler_descriptor: ImageSamplerDescriptor,
        render_asset_usages: RenderAssetUsages,
    },
}

impl ImageOrPath {
    // TODO: use the threaded impl on wasm once wasm thread pool doesn't deadlock on it
    // See https://github.com/bevyengine/bevy/issues/1924 for more details
    // The taskpool use is also avoided when there is only one texture for performance reasons and
    // to avoid https://github.com/bevyengine/bevy/pull/2725
    // PERF: could this be a Vec instead? Are gltf texture indices dense?
    fn process_loaded_texture(
        self,
        load_context: &mut LoadContext,
        handles: &mut Vec<Handle<Image>>,
    ) {
        let handle = match self {
            ImageOrPath::Image { label, image } => {
                load_context.add_labeled_asset(label.to_string(), image)
            }
            ImageOrPath::Path {
                path,
                is_srgb,
                sampler_descriptor,
                render_asset_usages,
            } => load_context
                .load_builder()
                .with_settings(move |settings: &mut ImageLoaderSettings| {
                    settings.is_srgb = is_srgb;
                    settings.sampler = ImageSampler::Descriptor(sampler_descriptor.clone());
                    settings.asset_usage = render_asset_usages;
                })
                .load(path),
        };
        handles.push(handle);
    }
}

/// An Iterator that iterates over morph target positions, normals,
/// and tangents while optionally handling coordinate conversions.
/// Used when setting morph targets on a `Mesh` while reading them
/// from a primitive.
pub struct PrimitiveMorphAttributesIter<'s> {
    /// Should the values be converted
    pub convert_coordinates: bool,
    /// Vertex position displacements
    pub positions: Option<Iter<'s, [f32; 3]>>,
    /// Vertex normal displacements
    pub normals: Option<Iter<'s, [f32; 3]>>,
    /// Vertex tangent displacements
    pub tangents: Option<Iter<'s, [f32; 3]>>,
}

impl<'s> Iterator for PrimitiveMorphAttributesIter<'s> {
    type Item = MorphAttributes;

    fn next(&mut self) -> Option<Self::Item> {
        let position = self.positions.as_mut().and_then(Iterator::next);
        let normal = self.normals.as_mut().and_then(Iterator::next);
        let tangent = self.tangents.as_mut().and_then(Iterator::next);
        if position.is_none() && normal.is_none() && tangent.is_none() {
            return None;
        }

        let mut attributes = MorphAttributes {
            position: position.map(Into::into).unwrap_or(Vec3::ZERO),
            normal: normal.map(Into::into).unwrap_or(Vec3::ZERO),
            tangent: tangent.map(Into::into).unwrap_or(Vec3::ZERO),
            pad_a: 0.0,
            pad_b: 0.0,
            pad_c: 0.0,
        };

        if self.convert_coordinates {
            attributes = MorphAttributes {
                position: attributes.position.convert_coordinates(),
                normal: attributes.normal.convert_coordinates(),
                tangent: attributes.tangent.convert_coordinates(),
                pad_a: 0.0,
                pad_b: 0.0,
                pad_c: 0.0,
            }
        }

        Some(attributes)
    }
}

/// A helper structure for `load_node` that contains information about the
/// nearest ancestor animation root.
#[cfg(feature = "bevy_animation")]
#[derive(Clone)]
struct AnimationContext {
    /// The nearest ancestor animation root.
    pub root: Entity,
    /// The path to the animation root. This is used for constructing the
    /// animation target UUIDs.
    pub path: SmallVec<[Name; 8]>,
}

/// Applications like Blender place shape key names in
/// the glTF extras as a list of target names.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MorphTargetNames {
    /// The list of target names (or shape keys)
    pub target_names: Vec<String>,
}

#[cfg(test)]
mod test {
    use std::path::Path;

    use crate::{Gltf, GltfAssetLabel, GltfMaterial, GltfNode, GltfSkin};
    use bevy_app::{App, TaskPoolPlugin};
    use bevy_asset::{
        io::{
            memory::{Dir, MemoryAssetReader},
            AssetSourceBuilder, AssetSourceId,
        },
        AssetApp, AssetLoader, AssetPlugin, AssetServer, Assets, Handle, LoadContext, LoadState,
    };
    use bevy_ecs::{resource::Resource, world::World};
    use bevy_image::{Image, ImageLoaderSettings};
    use bevy_log::LogPlugin;
    use bevy_mesh::skinning::SkinnedMeshInverseBindposes;
    use bevy_mesh::MeshPlugin;
    use bevy_reflect::TypePath;
    use bevy_world_serialization::WorldSerializationPlugin;

    fn test_app(dir: Dir) -> App {
        let mut app = App::new();
        let reader = MemoryAssetReader { root: dir };
        app.register_asset_source(
            AssetSourceId::Default,
            AssetSourceBuilder::new(move || Box::new(reader.clone())),
        )
        .add_plugins((
            LogPlugin::default(),
            TaskPoolPlugin::default(),
            AssetPlugin::default(),
            WorldSerializationPlugin,
            MeshPlugin,
            crate::GltfPlugin::default(),
        ));

        app.finish();
        app.cleanup();

        app
    }

    const LARGE_ITERATION_COUNT: usize = 10000;

    fn run_app_until(app: &mut App, mut predicate: impl FnMut(&mut World) -> Option<()>) {
        for _ in 0..LARGE_ITERATION_COUNT {
            app.update();
            if predicate(app.world_mut()).is_some() {
                return;
            }
        }

        panic!("Ran out of loops to return `Some` from `predicate`");
    }

    fn load_gltf_into_app(gltf_path: &str, gltf: &str) -> App {
        #[expect(
            dead_code,
            reason = "This struct is used to keep the handle alive. As such, we have no need to handle the handle directly."
        )]
        #[derive(Resource)]
        struct GltfHandle(Handle<Gltf>);

        let dir = Dir::default();
        dir.insert_asset_text(Path::new(gltf_path), gltf);
        let mut app = test_app(dir);
        app.update();
        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<Gltf> = asset_server.load(gltf_path.to_string());
        let handle_id = handle.id();
        app.insert_resource(GltfHandle(handle));
        app.update();
        run_app_until(&mut app, |_world| {
            let load_state = asset_server.get_load_state(handle_id).unwrap();
            match load_state {
                LoadState::Loaded => Some(()),
                LoadState::Failed(err) => panic!("{err}"),
                _ => None,
            }
        });
        app
    }

    #[test]
    fn single_node() {
        let gltf_path = "test.gltf";
        let app = load_gltf_into_app(
            gltf_path,
            r#"
{
    "asset": {
        "version": "2.0"
    },
    "nodes": [
        {
            "name": "TestSingleNode"
        }
    ],
    "scene": 0,
    "scenes": [{ "nodes": [0] }]
}
"#,
        );
        let asset_server = app.world().resource::<AssetServer>();
        let handle = asset_server.load(gltf_path);
        let gltf_root_assets = app.world().resource::<Assets<Gltf>>();
        let gltf_node_assets = app.world().resource::<Assets<GltfNode>>();
        let gltf_root = gltf_root_assets.get(&handle).unwrap();
        assert!(gltf_root.nodes.len() == 1, "Single node");
        assert!(
            gltf_root.named_nodes.contains_key("TestSingleNode"),
            "Named node is in named nodes"
        );
        let gltf_node = gltf_node_assets
            .get(gltf_root.named_nodes.get("TestSingleNode").unwrap())
            .unwrap();
        assert_eq!(gltf_node.name, "TestSingleNode", "Correct name");
        assert_eq!(gltf_node.index, 0, "Correct index");
        assert_eq!(gltf_node.children.len(), 0, "No children");
        assert_eq!(gltf_node.asset_label(), GltfAssetLabel::Node(0));
    }

    #[test]
    fn node_hierarchy_no_hierarchy() {
        let gltf_path = "test.gltf";
        let app = load_gltf_into_app(
            gltf_path,
            r#"
{
    "asset": {
        "version": "2.0"
    },
    "nodes": [
        {
            "name": "l1"
        },
        {
            "name": "l2"
        }
    ],
    "scene": 0,
    "scenes": [{ "nodes": [0] }]
}
"#,
        );
        let asset_server = app.world().resource::<AssetServer>();
        let handle = asset_server.load(gltf_path);
        let gltf_root_assets = app.world().resource::<Assets<Gltf>>();
        let gltf_node_assets = app.world().resource::<Assets<GltfNode>>();
        let gltf_root = gltf_root_assets.get(&handle).unwrap();
        let result = gltf_root
            .nodes
            .iter()
            .map(|h| gltf_node_assets.get(h).unwrap())
            .collect::<Vec<_>>();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "l1");
        assert_eq!(result[0].children.len(), 0);
        assert_eq!(result[1].name, "l2");
        assert_eq!(result[1].children.len(), 0);
    }

    #[test]
    fn node_hierarchy_simple_hierarchy() {
        let gltf_path = "test.gltf";
        let app = load_gltf_into_app(
            gltf_path,
            r#"
{
    "asset": {
        "version": "2.0"
    },
    "nodes": [
        {
            "name": "l1",
            "children": [1]
        },
        {
            "name": "l2"
        }
    ],
    "scene": 0,
    "scenes": [{ "nodes": [0] }]
}
"#,
        );
        let asset_server = app.world().resource::<AssetServer>();
        let handle = asset_server.load(gltf_path);
        let gltf_root_assets = app.world().resource::<Assets<Gltf>>();
        let gltf_node_assets = app.world().resource::<Assets<GltfNode>>();
        let gltf_root = gltf_root_assets.get(&handle).unwrap();
        let result = gltf_root
            .nodes
            .iter()
            .map(|h| gltf_node_assets.get(h).unwrap())
            .collect::<Vec<_>>();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "l1");
        assert_eq!(result[0].children.len(), 1);
        assert_eq!(result[1].name, "l2");
        assert_eq!(result[1].children.len(), 0);
    }

    #[test]
    fn node_hierarchy_hierarchy() {
        let gltf_path = "test.gltf";
        let app = load_gltf_into_app(
            gltf_path,
            r#"
{
    "asset": {
        "version": "2.0"
    },
    "nodes": [
        {
            "name": "l1",
            "children": [1]
        },
        {
            "name": "l2",
            "children": [2]
        },
        {
            "name": "l3",
            "children": [3, 4, 5]
        },
        {
            "name": "l4",
            "children": [6]
        },
        {
            "name": "l5"
        },
        {
            "name": "l6"
        },
        {
            "name": "l7"
        }
    ],
    "scene": 0,
    "scenes": [{ "nodes": [0] }]
}
"#,
        );
        let asset_server = app.world().resource::<AssetServer>();
        let handle = asset_server.load(gltf_path);
        let gltf_root_assets = app.world().resource::<Assets<Gltf>>();
        let gltf_node_assets = app.world().resource::<Assets<GltfNode>>();
        let gltf_root = gltf_root_assets.get(&handle).unwrap();
        let result = gltf_root
            .nodes
            .iter()
            .map(|h| gltf_node_assets.get(h).unwrap())
            .collect::<Vec<_>>();
        assert_eq!(result.len(), 7);
        assert_eq!(result[0].name, "l1");
        assert_eq!(result[0].children.len(), 1);
        assert_eq!(result[1].name, "l2");
        assert_eq!(result[1].children.len(), 1);
        assert_eq!(result[2].name, "l3");
        assert_eq!(result[2].children.len(), 3);
        assert_eq!(result[3].name, "l4");
        assert_eq!(result[3].children.len(), 1);
        assert_eq!(result[4].name, "l5");
        assert_eq!(result[4].children.len(), 0);
        assert_eq!(result[5].name, "l6");
        assert_eq!(result[5].children.len(), 0);
        assert_eq!(result[6].name, "l7");
        assert_eq!(result[6].children.len(), 0);
    }

    #[test]
    fn node_hierarchy_cyclic() {
        let gltf_path = "test.gltf";
        let gltf_str = r#"
{
    "asset": {
        "version": "2.0"
    },
    "nodes": [
        {
            "name": "l1",
            "children": [1]
        },
        {
            "name": "l2",
            "children": [0]
        }
    ],
    "scene": 0,
    "scenes": [{ "nodes": [0] }]
}
"#;

        let dir = Dir::default();
        dir.insert_asset_text(Path::new(gltf_path), gltf_str);
        let mut app = test_app(dir);
        app.update();
        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<Gltf> = asset_server.load(gltf_path);
        let handle_id = handle.id();
        app.update();
        run_app_until(&mut app, |_world| {
            let load_state = asset_server.get_load_state(handle_id).unwrap();
            if load_state.is_failed() {
                Some(())
            } else {
                None
            }
        });
        let load_state = asset_server.get_load_state(handle_id).unwrap();
        assert!(load_state.is_failed());
    }

    #[test]
    fn node_hierarchy_missing_node() {
        let gltf_path = "test.gltf";
        let gltf_str = r#"
{
    "asset": {
        "version": "2.0"
    },
    "nodes": [
        {
            "name": "l1",
            "children": [2]
        },
        {
            "name": "l2"
        }
    ],
    "scene": 0,
    "scenes": [{ "nodes": [0] }]
}
"#;

        let dir = Dir::default();
        dir.insert_asset_text(Path::new(gltf_path), gltf_str);
        let mut app = test_app(dir);
        app.update();
        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<Gltf> = asset_server.load(gltf_path);
        let handle_id = handle.id();
        app.update();
        run_app_until(&mut app, |_world| {
            let load_state = asset_server.get_load_state(handle_id).unwrap();
            if load_state.is_failed() {
                Some(())
            } else {
                None
            }
        });
        let load_state = asset_server.get_load_state(handle_id).unwrap();
        assert!(load_state.is_failed());
    }

    #[test]
    fn skin_node() {
        let gltf_path = "test.gltf";
        let app = load_gltf_into_app(
            gltf_path,
            r#"
{
    "asset": {
        "version": "2.0"
    },
    "nodes": [
        {
            "name": "skinned",
            "skin": 0,
            "children": [1, 2]
        },
        {
            "name": "joint1"
        },
        {
            "name": "joint2"
        }
    ],
    "skins": [
        {
            "inverseBindMatrices": 0,
            "joints": [1, 2]
        }
    ],
    "buffers": [
        {
            "uri" : "data:application/gltf-buffer;base64,AACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAIC/AAAAAAAAgD8=",
            "byteLength" : 128
        }
    ],
    "bufferViews": [
        {
            "buffer": 0,
            "byteLength": 128
        }
    ],
    "accessors": [
        {
            "bufferView" : 0,
            "componentType" : 5126,
            "count" : 2,
            "type" : "MAT4"
        }
    ],
    "scene": 0,
    "scenes": [{ "nodes": [0] }]
}
"#,
        );
        let asset_server = app.world().resource::<AssetServer>();
        let handle = asset_server.load(gltf_path);
        let gltf_root_assets = app.world().resource::<Assets<Gltf>>();
        let gltf_node_assets = app.world().resource::<Assets<GltfNode>>();
        let gltf_skin_assets = app.world().resource::<Assets<GltfSkin>>();
        let gltf_inverse_bind_matrices = app
            .world()
            .resource::<Assets<SkinnedMeshInverseBindposes>>();
        let gltf_root = gltf_root_assets.get(&handle).unwrap();

        assert_eq!(gltf_root.skins.len(), 1);
        assert_eq!(gltf_root.nodes.len(), 3);

        let skin = gltf_skin_assets.get(&gltf_root.skins[0]).unwrap();
        assert_eq!(skin.joints.len(), 2);
        assert_eq!(skin.joints[0], gltf_root.nodes[1]);
        assert_eq!(skin.joints[1], gltf_root.nodes[2]);
        assert!(gltf_inverse_bind_matrices.contains(&skin.inverse_bind_matrices));

        let skinned_node = gltf_node_assets.get(&gltf_root.nodes[0]).unwrap();
        assert_eq!(skinned_node.name, "skinned");
        assert_eq!(skinned_node.children.len(), 2);
        assert_eq!(skinned_node.skin.as_ref(), Some(&gltf_root.skins[0]));
    }

    fn test_app_custom_asset_source() -> (App, Dir) {
        let dir = Dir::default();

        let mut app = App::new();
        let custom_reader = MemoryAssetReader { root: dir.clone() };
        // Create a default asset source so we definitely don't try to read from disk.
        app.register_asset_source(
            AssetSourceId::Default,
            AssetSourceBuilder::new(move || {
                Box::new(MemoryAssetReader {
                    root: Dir::default(),
                })
            }),
        )
        .register_asset_source(
            "custom",
            AssetSourceBuilder::new(move || Box::new(custom_reader.clone())),
        )
        .add_plugins((
            LogPlugin::default(),
            TaskPoolPlugin::default(),
            AssetPlugin::default(),
            WorldSerializationPlugin,
            MeshPlugin,
            crate::GltfPlugin::default(),
        ));

        app.finish();
        app.cleanup();

        (app, dir)
    }

    #[test]
    fn reads_buffer_in_custom_asset_source() {
        let (mut app, dir) = test_app_custom_asset_source();

        dir.insert_asset_text(
            Path::new("abc.gltf"),
            r#"
{
    "asset": {
        "version": "2.0"
    },
    "buffers": [
        {
            "uri": "abc.bin",
            "byteLength": 3
        }
    ]
}
"#,
        );
        // We don't care that the buffer contains reasonable info since we won't actually use it.
        dir.insert_asset_text(Path::new("abc.bin"), "Sup");

        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<Gltf> = asset_server.load("custom://abc.gltf");
        run_app_until(&mut app, |_world| {
            let load_state = asset_server.get_load_state(handle.id()).unwrap();
            match load_state {
                LoadState::Loaded => Some(()),
                LoadState::Failed(err) => panic!("{err}"),
                _ => None,
            }
        });
    }

    #[test]
    fn reads_images_in_custom_asset_source() {
        let (mut app, dir) = test_app_custom_asset_source();

        app.init_asset::<GltfMaterial>();

        // Note: We need the material here since otherwise we don't store the texture handle, which
        // can result in the image getting dropped leading to the gltf never being loaded with
        // dependencies.
        dir.insert_asset_text(
            Path::new("abc.gltf"),
            r#"
{
    "asset": {
        "version": "2.0"
    },
    "textures": [
        {
            "source": 0,
            "sampler": 0
        }
    ],
    "images": [
        {
            "uri": "abc.png"
        }
    ],
    "samplers": [
        {
            "magFilter": 9729,
            "minFilter": 9729
        }
    ],
    "materials": [
        {
            "pbrMetallicRoughness": {
                "baseColorTexture": {
                    "index": 0,
                    "texCoord": 0
                }
            }
        }
    ]
}
"#,
        );
        // We don't care that the image contains reasonable info since we won't actually use it.
        dir.insert_asset_text(Path::new("abc.png"), "Sup");

        /// A fake loader to avoid actually loading any image data and just return an image.
        #[derive(TypePath)]
        struct FakePngLoader;

        impl AssetLoader for FakePngLoader {
            type Asset = Image;
            type Error = std::io::Error;
            type Settings = ImageLoaderSettings;

            async fn load(
                &self,
                _reader: &mut dyn bevy_asset::io::Reader,
                _settings: &Self::Settings,
                _load_context: &mut LoadContext<'_>,
            ) -> Result<Self::Asset, Self::Error> {
                Ok(Image::default())
            }

            fn extensions(&self) -> &[&str] {
                &["png"]
            }
        }

        app.init_asset::<Image>()
            .register_asset_loader(FakePngLoader);

        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<Gltf> = asset_server.load("custom://abc.gltf");
        run_app_until(&mut app, |_world| {
            // Note: we can't assert for failure since it's the nested load that fails, not the GLTF
            // load.
            asset_server
                .is_loaded_with_dependencies(&handle)
                .then_some(())
        });
    }

    #[test]
    fn image_error_is_an_error() {
        let (mut app, dir) = test_app_custom_asset_source();

        dir.insert_asset_text(
            Path::new("abc.gltf"),
            r#"
{
    "asset": {
        "version": "2.0"
    },
    "textures": [
        {
            "source": 0,
            "sampler": 0
        }
    ],
    "images": [
        {
            "bufferView": 0,
            "mimeType": "image/png"
        }
    ],
    "samplers": [
        {
            "magFilter": 9729,
            "minFilter": 9729
        }
    ],
    "buffers": [
        {
          "byteLength": 1,
          "uri": "data:application/gltf-buffer;base64,AAAA"
        }
    ],
    "bufferViews": [
        {
            "buffer": 0,
            "byteLength": 1
        }
    ]
}
"#,
        );

        app.init_asset::<Image>();

        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<Gltf> = asset_server.load("custom://abc.gltf");
        run_app_until(&mut app, |_| match asset_server.load_state(&handle) {
            LoadState::Failed(err) => {
                let err = err.to_string();
                assert!(
                    // Depending on the `image` crate's feature flags, we may get different errors.
                    // Specifically, either the `image/png` mime type is warned about, or the buffer
                    // is not big enough to be valid PNG data.
                    err.contains("failed to load an image: unexpected end of file")
                        || err.contains("invalid image mime type: image/png"),
                    "incorrect error message: {err}"
                );
                Some(())
            }
            LoadState::Loading => None,
            state => panic!("Unexpected load state: {state:?}"),
        });
    }
}