concinnity-cook 0.18.64

Asset cook pipeline that bakes an authored Concinnity world into a blob
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
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
//! Compile stage of the build pipeline. The world is loaded, expanded, and
//! validated upstream by crate::world::prepare_world; this module takes the
//! resulting WorldJsonlAsset list and:
//! - Resolves each asset to a BlobAssetDef via asset_api::create_asset_def()
//! - Compiles payloads for assets that need compilation
//! - Packs all payloads into blobs using PayloadPacker (fills locators)
//! - Sorts: components first, then systems in declared order

use std::path::Path;

use concinnity_core::blob::{MeshBoundsRecord, PhysicsBudgetRecord, ResourceKind, SceneGroup};
use serde::Deserialize;

use crate::components::FileKind;
use crate::world::WorldJsonlAsset;

use crate::asset_api::{self, AssetRequest};
use crate::blob::PayloadPacker;
use crate::ecs::asset_id;
use crate::ecs::{AssetKind, BlobAssetDef, ResourceRecord};
use crate::registry::RegisteredType;
use crate::resource_handles::ResourceAssetCompile;

// The resource kind of a job selected by `collect_resource_jobs`. Every entry
// there was chosen by having one, so the lookup cannot fail.
fn job_resource_kind(rt: crate::registry::RegisteredType) -> crate::resource_handles::ResourceKind {
    rt.resource_kind()
        .expect("a resource job carries a resource type")
}

// The mesh kinds' declarable type names. Both are resource assets (no
// `Component` impl, so no `::NAME` const); the desugar passes and the cache
// probe match on these.
const MESH_TYPE: &str = "Mesh";
const SKINNED_MESH_TYPE: &str = "SkinnedMesh";

/// Build the world at `json_path` and write its blobs to disk, against the
/// installed state root: sources resolve under its `assets/` and the blobs land
/// in its `data/`. The one entry point anchored to the process-wide state tree;
/// a host that builds against its own directories calls
/// [`prepare_world`](crate::world::prepare_world) + [`build_compiled`].
pub fn build_from_path(json_path: &str) -> std::io::Result<()> {
    let content = std::fs::read_to_string(json_path)?;
    let assets_dir = crate::paths::assets_dir();
    let loaded = crate::world::prepare_world(&content, assets_dir.as_deref())
        .map_err(|errs| crate::check::report_validation_errors(&errs))?;

    let result = build_compiled(loaded.assets, assets_dir.as_deref(), None)?;

    let pack_result = write_build_outputs(&result, &loaded.injected, &loaded.shadowed)?;
    for (blob_idx, path) in pack_result.blob_paths.iter().enumerate() {
        let payload_bytes = result.payloads.get(blob_idx).map(|b| b.len()).unwrap_or(0);
        println!("Wrote {} ({} payload bytes)", path, payload_bytes);
    }

    if result.cache_hits + result.cache_misses > 0 {
        println!(
            "Build cache: {} reused, {} compiled",
            result.cache_hits, result.cache_misses
        );
    }

    if !loaded.injected.is_empty() {
        println!(
            "Injected {} default asset(s) (see world-lock.json)",
            loaded.injected.len()
        );
    }
    println!("Wrote world-lock.json");

    Ok(())
}

/// Write a compiled world's blob files, naming the primary blob `primary`.
/// Every overflow payload blob is written as its sibling named by index, which
/// is the layout the runtime reads back. No lock file and no thumbnails: this
/// is the blob output alone.
pub fn write_blobs_to(
    result: &PipelineResult,
    primary: &std::path::Path,
) -> std::io::Result<crate::blob::PackResult> {
    crate::blob::write_blobs(
        crate::blob::BlobStreams {
            defs: &result.defs,
            resources: &result.resources,
            scene_groups: &result.scene_groups,
            mesh_bounds: &result.mesh_bounds,
            physics_budget: result.physics_budget,
        },
        &result.payloads,
        primary,
    )
}

/// Write the blobs and world-lock.json for a compiled world: the shared build
/// tail used by the CLI and the FFI host. The lock records each asset under its
/// real name plus every injected default with its full args.
pub fn write_build_outputs(
    result: &PipelineResult,
    injected: &[crate::world::InjectedAsset],
    shadowed: &[crate::world::ShadowedAsset],
) -> std::io::Result<crate::blob::PackResult> {
    let primary = crate::blob::blob_path(0).ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "no project state directory to write blobs into",
        )
    })?;
    let pack_result = write_blobs_to(result, std::path::Path::new(&primary))?;
    let named_refs: Vec<(&str, &BlobAssetDef)> = result
        .names
        .iter()
        .map(|n| n.as_str())
        .zip(result.defs.iter())
        .collect();
    crate::blob::write_lock(
        &named_refs,
        &result.resource_locks,
        injected,
        shadowed,
        &pack_result.blob_paths,
    )?;
    // Thumbnails are a best-effort side product: a bake failure must never
    // fail the build that produced valid blobs.
    match crate::thumbnail::bake_thumbnails(result) {
        Ok(r) if r.baked > 0 => println!("Baked {} thumbnail(s) ({} reused)", r.baked, r.reused),
        Ok(_) => {}
        Err(e) => println!("Thumbnail bake skipped: {e}"),
    }
    Ok(pack_result)
}

// Collapse a list of validation errors into a single io::Error. The messages
// are newline-joined so an upstream caller (e.g. the infra agentic loop) sees
// every problem from one call.
fn errors_to_io(errors: Vec<String>) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::InvalidData, errors.join("\n"))
}

/// A texture's identity + on-disk source, in `TextureHandle` order. Now that
/// Texture is a resource (no `source`/`asset_id` on a component the renderer
/// drains), this is how a dev build hands the `cn debug` tools what they need: the
/// hot-reload watcher maps `source` -> handle, and the runtime spawn-by-name path
/// maps `name_id` -> handle. `source` is empty for a procedural texture (nothing
/// to watch). `name_id` is the interned asset name (same interner the runtime
/// shares in-process under `cn debug`), so nothing is interned at runtime.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TextureSourceInfo {
    /// The interned asset name.
    pub name_id: u32,
    /// Authored source path; empty for a procedural texture.
    pub source: String,
    /// Index of the image within the source document.
    pub image_index: u32,
}

/// A file-backed Mesh's re-import inputs, in `MeshHandle` order (the Mesh block
/// leads the shared mesh-source handle space, so Mesh handles are dense from 0).
/// Now that Mesh is a resource (no `source` on a component the renderer drains),
/// this is how a dev build hands the `cn debug` hot-reload watcher what it needs
/// to re-import a saved `.glb`/`.fbx`. `source` is empty for an inline-authored
/// mesh (nothing to watch).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MeshSourceInfo {
    /// Authored source path; empty for an inline-authored mesh.
    pub source: String,
    /// Index of the primitive within the source document.
    pub primitive_index: u32,
    /// How many LODs the mesh declares, including LOD0.
    pub lod_levels: u32,
    /// Camera distance at which each LOD past 0 takes over.
    pub lod_distances: Vec<f32>,
}

/// The in-memory result of a complete build pipeline run.
/// Defs have payload locators filled in; `payloads[i]` is the raw bytes for
/// blob i. This can be used directly without touching disk.
pub struct PipelineResult {
    /// The compiled component defs, with payload locators filled in.
    pub defs: Vec<BlobAssetDef>,
    /// Asset name of each def, index-aligned with `defs` (defs only carry the
    /// interned id; the lock file records the readable name).
    pub names: Vec<String>,
    /// The blob's resource stream: compiled resources addressed by their dense
    /// per-kind handle, carried alongside the component defs. Empty until a
    /// resource kind migrates off the component registry (AudioClip first).
    pub resources: Vec<ResourceRecord>,
    /// Per-scene exclusively-owned blob content, in scene declaration order.
    pub scene_groups: Vec<SceneGroup>,
    /// Baked AABB + counts per static mesh payload, by mesh-source handle.
    pub mesh_bounds: Vec<MeshBoundsRecord>,
    /// The world's physics reservation, or `None` when it runs no physics.
    pub physics_budget: Option<PhysicsBudgetRecord>,
    // Unified mesh-source handle -> asset name for mesh payloads compiled as
    // component defs (ProceduralMesh and friends). Resource-stream Mesh
    // handles lead the space and resolve through `resources`; these resolve
    // through `names`/`defs`. Consumed by the thumbnail baker to compose a
    // Model's sub-meshes.
    pub(crate) mesh_component_names: Vec<(u32, String)>,
    /// Raw bytes of each blob, indexed by blob number.
    pub payloads: Vec<Vec<u8>>,
    // Compiled-asset payloads served from the build cache this run.
    pub(crate) cache_hits: usize,
    // Compiled-asset payloads compiled fresh this run.
    pub(crate) cache_misses: usize,
    /// File-backed texture sources in `TextureHandle` order, for the `cn debug`
    /// hot-reload watcher. Dev-only info; not written to the shipped blob.
    pub texture_sources: Vec<TextureSourceInfo>,
    /// File-backed mesh sources in `MeshHandle` order (dense over the Mesh block
    /// of the shared mesh-source space), for the `cn debug` hot-reload watcher.
    /// Dev-only info; not written to the shipped blob.
    pub mesh_sources: Vec<MeshSourceInfo>,
    // Lock-file provenance for the resource stream, index-aligned with
    // `resources` (records only carry the kind tag + handle; the lock records
    // the readable name and args hash).
    pub(crate) resource_locks: Vec<crate::blob::LockedResource>,
}

impl PipelineResult {
    /// The interned asset name of every compiled resource of `kind`, dense by
    /// its per-kind handle: the identity a runtime that addresses resources by
    /// handle has no other way to recover (a resource record carries its kind
    /// and handle, not its name). 0 where the build recorded no id.
    pub fn resource_names(&self, kind: ResourceKind) -> Vec<u32> {
        let mut names = Vec::new();
        for (record, lock) in self.resources.iter().zip(self.resource_locks.iter()) {
            if record.resource_kind != kind as u8 {
                continue;
            }
            let slot = record.handle as usize;
            if names.len() <= slot {
                names.resize(slot + 1, 0);
            }
            names[slot] = lock.id.unwrap_or_default();
        }
        names
    }

    /// The compiled payload bytes of the resource of `kind` declared under
    /// `name`, sliced out of the in-memory blob sections. `None` when no such
    /// resource was compiled or it carries no payload. The editor's glTF
    /// export reads a SkinnedMesh's composed geometry through this.
    pub fn resource_payload(&self, kind: ResourceKind, name: &str) -> Option<&[u8]> {
        let record = self
            .resources
            .iter()
            .zip(self.resource_locks.iter())
            .find(|(r, l)| r.resource_kind == kind as u8 && l.name == name)?
            .0;
        let loc = record.payload.as_ref()?;
        let blob = self.payloads.get(loc.blob_index as usize)?;
        let start = usize::try_from(loc.offset).ok()?;
        let end = start.checked_add(usize::try_from(loc.len).ok()?)?;
        blob.get(start..end)
    }
}

/// Validate a single asset's type and generator without running the full build
/// pipeline. Called by the server on each world_add so the LLM gets per-asset
/// feedback without waiting for a WebSocket round-trip.
///
/// Checks:
///
/// - asset type is registered (via `asset_api::create_asset_def`)
/// - per-type structural checks via `crate::check`
///
/// Shader assets are not compiled here; use the validate_shader tool for that.
pub fn validate_asset(
    asset_type: &str,
    name: &str,
    args: &serde_json::Value,
) -> Result<(), String> {
    // Single-asset validation has no surrounding world to intern against; the
    // resulting ids are throwaway. Reset so calls do not accumulate entries.
    // Clear the resource handle map too: with no world there are no handles, so
    // a resource reference falls back to the interner (parses without resolving
    // to a real slot, which single-asset validation never needs).
    asset_id::reset_interner();
    crate::resource_handles::reset_resource_handles();
    let type_norm = asset_type.to_lowercase().replace('_', "");

    // Build-time types are valid in world.jsonl; they are consumed by expansion
    // functions before the runtime asset registry sees them.
    if matches!(
        type_norm.as_str(),
        "environment"
            | "lightrig"
            | "materialpalette"
            | "camerashot"
            | "prefab"
            | "sceneimport"
            | "characterschema"
            | "charactermodel"
    ) {
        return Ok(());
    }

    // A resource asset never builds a component def; validate it as a known type
    // with a structural check instead of routing through `create_asset_def`.
    if crate::registry::RegisteredType::parse(asset_type).is_some_and(|t| t.is_resource()) {
        crate::check::check_asset(&type_norm, name, args)?;
        return Ok(());
    }

    let req = AssetRequest {
        asset_type: asset_type.to_string(),
        args: Some(args.clone()),
    };
    asset_api::create_asset_def(&req).map_err(|e| format!("Asset '{}': {}", name, e))?;

    crate::check::check_asset(&type_norm, name, args)?;

    Ok(())
}

/// Run the full build pipeline on an in-memory JSONL string without writing any
/// blobs. Loads, expands, and validates the world (crate::world::prepare_world),
/// then compiles it. `assets_dir` is the asset search root a bare `source`
/// filename is searched under; `artifacts_dir` is an optional directory
/// consulted when resolving bare shader filenames not found there, so pass the
/// account's artifact directory to compile user-written shaders.
pub fn build_pipeline_from_str(
    content: &str,
    assets_dir: Option<&Path>,
    artifacts_dir: Option<&str>,
) -> std::io::Result<PipelineResult> {
    let loaded = crate::world::prepare_world(content, assets_dir).map_err(errors_to_io)?;
    build_compiled(loaded.assets, assets_dir, artifacts_dir)
}

/// A progress report from the compile pipeline: the stage's name and its
/// done / total counts. `total == 0` marks a stage that cannot count its work
/// (progress there is indeterminate).
#[derive(Debug, Clone, Copy)]
pub struct BuildProgress {
    /// The stage's name.
    pub stage: &'static str,
    /// Work completed in this stage.
    pub done: u32,
    /// Total work in this stage; 0 when the stage cannot count it.
    pub total: u32,
}

/// Compile an already-prepared world (expanded + structurally and semantically
/// validated) into in-memory blobs. This is the compile-only stage; it assumes
/// the assets have passed crate::world::prepare_world, which should have been
/// given the same `assets_dir`: an asset resolves its source the same way in
/// both halves.
pub fn build_compiled(
    assets: Vec<WorldJsonlAsset>,
    assets_dir: Option<&Path>,
    artifacts_dir: Option<&str>,
) -> std::io::Result<PipelineResult> {
    build_compiled_with_progress(assets, assets_dir, artifacts_dir, None)
}

/// [`build_compiled`] with a progress callback. The callback fires from the
/// desugar stage and, concurrently, from the parallel payload compile (hence
/// `Sync`); it must be cheap and non-blocking.
pub fn build_compiled_with_progress(
    mut assets: Vec<WorldJsonlAsset>,
    assets_dir: Option<&Path>,
    artifacts_dir: Option<&str>,
    progress: Option<&(dyn Fn(BuildProgress) + Sync)>,
) -> std::io::Result<PipelineResult> {
    if let Some(p) = progress {
        p(BuildProgress {
            stage: "desugar",
            done: 0,
            total: 0,
        });
    }

    // Cache probe runs before desugar. For every glTF-sourced Mesh /
    // SkinnedMesh, hash the un-desugared args + referenced .glb and look up
    // the compiled payload by that key. On a hit, we hold the bytes and skip
    // the .glb parse entirely (the original goal: an unchanged source file
    // means no work). On a miss, the recorded key is used when the compile
    // step stores the freshly produced payload, so the next build's probe
    // can re-use it.
    let mesh_cache = probe_mesh_payload_cache(&assets, assets_dir, artifacts_dir);

    // Expand any glTF-sourced SkinnedMesh and Mesh assets into inline geometry
    // before anything else looks at their args. Animations expand after the
    // skinned-mesh pass so an importer that wanted to share state could read
    // already-imported skeletons; today both passes parse the .glb fresh,
    // but the ordering keeps that option open without an API churn.
    desugar_gltf_skinned_meshes(&mut assets, &mesh_cache, assets_dir)?;
    desugar_fbx_skinned_meshes(&mut assets, &mesh_cache)?;
    desugar_gltf_meshes(&mut assets, &mesh_cache, assets_dir)?;
    desugar_fbx_meshes(&mut assets, &mesh_cache)?;
    desugar_animation_imports(&mut assets, assets_dir)?;
    desugar_root_motion(&mut assets)?;
    crate::character_shape::warn_unresolved(&assets);
    crate::character::bake::bake_shapes(&mut assets, |name| {
        mesh_cache.get(name).and_then(|e| e.bytes.as_deref())
    })?;

    // Intern every asset name to a dense AssetId in declaration order, then
    // resolve the scene-by-naming-convention references that the runtime can
    asset_id::reset_interner();
    let names: Vec<&str> = assets.iter().map(|a| a.name.as_str()).collect();
    asset_id::intern_all(&names);
    resolve_scene_refs(&mut assets);

    // Assign each resource its dense per-kind handle in declaration order and
    // install the map so resource references resolve during the reserialize pass
    // below: texture references (Material.albedo, Room.*_texture,
    // Decal/ParticleEmitter.texture) to a `TextureHandle`, and audio-clip
    // references (AudioEmitter.clip, AudioCue.clip, Story music/sounds) to an
    // `AudioClipHandle`. The assignment walks this same `assets` list that the
    // blob is emitted from, so a resource's handle equals the position the
    // runtime encounters it (a texture's albedo pool slot, an audio clip's drain
    // index / resource-table slot).
    crate::resource_handles::reset_resource_handles();
    let resource_assets = assets.iter().filter_map(|a| {
        crate::resource_handles::asset_resource_kind(&a.asset_type)
            .map(|kind| (asset_id::intern(&a.name), kind))
    });
    let mut resource_handles =
        crate::resource_handles::ResourceHandles::from_assets(resource_assets);
    // The mesh-source handle space spans four kinds (Mesh, ProceduralMesh,
    // VoxelChunk, mesh-kind File) and File is polymorphic, so it is assigned in a
    // second pass in the fixed block order the runtime enumerates mesh sources
    // rather than through the per-type classifier above.
    crate::resource_handles::assign_mesh_source_handles(&mut resource_handles, &assets);
    // Shader handles walk the same list, so a Material's `shader` reference
    // bakes to the position the runtime encounters that Shader at drain time.
    crate::resource_handles::assign_shader_handles(&mut resource_handles, &assets);
    // Install a clone; the original is kept to look up each resource asset's
    // handle while partitioning below.
    crate::resource_handles::install_resource_handles(resource_handles.clone());

    // Partition the world into component assets (each becomes a `BlobAssetDef`)
    // and resource assets (each becomes a resource-stream record). A resource
    // asset (AudioClip) has left the component registry, so it never goes through
    // `create_asset_def`; it is compiled + packed as a resource below. `named` is
    // therefore no longer 1:1 with `assets`, so `named_src[i]` records the source
    // asset index of each component def.
    use crate::registry::RegisteredType;
    let mut named: Vec<(String, BlobAssetDef)> = Vec::new();
    let mut named_src: Vec<usize> = Vec::new();
    let mut resource_jobs: Vec<(usize, RegisteredType, u32)> = Vec::new();
    for (i, asset) in assets.iter().enumerate() {
        if let Some((rt, kind)) =
            RegisteredType::parse(&asset.asset_type).and_then(|t| t.resource_kind().map(|k| (t, k)))
        {
            let id = asset_id::intern(&asset.name);
            let handle = resource_handles
                .get(kind, id)
                .expect("resource asset was assigned a handle above");
            resource_jobs.push((i, rt, handle));
            continue;
        }
        let req = AssetRequest {
            asset_type: asset.asset_type.clone(),
            args: Some(asset.args.clone()),
        };
        let mut def = asset_api::create_asset_def(&req).map_err(|e| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Asset '{}': {}", asset.name, e),
            )
        })?;
        def.name = Some(asset_id::intern(&asset.name));
        named.push((asset.name.clone(), def));
        named_src.push(i);
    }

    // Dev-only: the file source behind each texture handle, so `cn debug`'s
    // hot-reload watcher can map a saved file back to its handle. Built in
    // handle order from the same resource jobs; a procedural texture (generator
    // set) leaves an empty source (nothing to watch).
    let texture_count = resource_jobs
        .iter()
        .filter(|(_, rt, _)| *rt == RegisteredType::Texture)
        .map(|(_, _, h)| *h as usize + 1)
        .max()
        .unwrap_or(0);
    let mut texture_sources = vec![TextureSourceInfo::default(); texture_count];
    for (asset_idx, rt, handle) in &resource_jobs {
        if *rt != RegisteredType::Texture {
            continue;
        }
        let asset = &assets[*asset_idx];
        let generator = asset
            .args
            .get("generator")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let (source, image_index) = if generator.is_empty() {
            (
                asset
                    .args
                    .get("source")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string(),
                asset
                    .args
                    .get("image_index")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) as u32,
            )
        } else {
            (String::new(), 0)
        };
        texture_sources[*handle as usize] = TextureSourceInfo {
            name_id: asset_id::intern(&asset.name).0,
            source,
            image_index,
        };
    }

    // Dev-only: the file source behind each mesh handle, so `cn debug`'s
    // hot-reload watcher can re-import a saved `.glb`/`.fbx` into its draw
    // slots. Mesh handles are dense from 0 (the Mesh block leads the shared
    // mesh-source space); an inline-authored mesh leaves an empty source.
    let mesh_count = resource_jobs
        .iter()
        .filter(|(_, rt, _)| *rt == RegisteredType::Mesh)
        .map(|(_, _, h)| *h as usize + 1)
        .max()
        .unwrap_or(0);
    let mut mesh_sources = vec![MeshSourceInfo::default(); mesh_count];
    for (asset_idx, rt, handle) in &resource_jobs {
        if *rt != RegisteredType::Mesh {
            continue;
        }
        let args = &assets[*asset_idx].args;
        let str_arg = |key: &str| {
            args.get(key)
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string()
        };
        let u32_arg = |key: &str, default: u32| {
            args.get(key)
                .and_then(|v| v.as_u64())
                .unwrap_or(default as u64) as u32
        };
        mesh_sources[*handle as usize] = MeshSourceInfo {
            source: str_arg("source"),
            primitive_index: u32_arg("primitive_index", 0),
            lod_levels: u32_arg("lod_levels", 1),
            lod_distances: args
                .get("lod_distances")
                .and_then(|v| v.as_array())
                .map(|a| {
                    a.iter()
                        .filter_map(|d| d.as_f64())
                        .map(|d| d as f32)
                        .collect()
                })
                .unwrap_or_default(),
        };
    }

    // Scene payload ownership, derived from the resolved scene memberships and
    // the reference graph; drives the grouped packing below.
    let partition = crate::scene_partition::partition_scenes(&assets);

    // The world's physics reservation, counted from the same fully expanded
    // asset list the blob is emitted from.
    let physics_budget = crate::physics_budget::compute(&assets);
    crate::physics_budget::report_spawn_reservation(&assets);

    let compiled = compile_and_pack_payloads(
        &mut named,
        &named_src,
        PackContext {
            assets: &assets,
            resource_jobs: &resource_jobs,
            partition: &partition,
            mesh_source_handles: &resource_handles,
            max_blob_bytes: crate::blob::DEFAULT_MAX_BLOB_BYTES,
            assets_dir,
            artifacts_dir,
            mesh_cache: &mesh_cache,
            progress,
        },
    )?;

    // Lock-file provenance for the resource stream: `compiled.resources` is
    // emitted in `resource_jobs` order, so the two zip index-aligned. Texture
    // and Mesh records also carry their hot-reload source info so a blob boot
    // can reconstruct the catalogues without the authored args.
    let resource_locks: Vec<crate::blob::LockedResource> = resource_jobs
        .iter()
        .zip(compiled.resources.iter())
        .map(|((asset_idx, rt, handle), record)| {
            let asset = &assets[*asset_idx];
            crate::blob::LockedResource {
                name: asset.name.clone(),
                // Already interned by the declaration-order pass above, so
                // this is a lookup of the id the build assigned.
                id: Some(asset_id::intern(&asset.name).0),
                kind: rt.as_str().to_string(),
                handle: *handle,
                args_hash: crate::blob::checksum(asset.args.to_string().as_bytes()),
                payload_blob: record.payload.as_ref().map(|p| p.blob_index),
                texture_source: (*rt == RegisteredType::Texture).then(|| {
                    let t = &texture_sources[*handle as usize];
                    crate::blob::LockedTextureSource {
                        source: t.source.clone(),
                        image_index: t.image_index,
                    }
                }),
                mesh_source: (*rt == RegisteredType::Mesh).then(|| {
                    let m = &mesh_sources[*handle as usize];
                    crate::blob::LockedMeshSource {
                        source: m.source.clone(),
                        primitive_index: m.primitive_index,
                        lod_levels: m.lod_levels,
                        lod_distances: m.lod_distances.clone(),
                    }
                }),
            }
        })
        .collect();

    // The blob carries components (emitted in declaration order) plus the
    // resource stream. (System run order is no longer a build concern: every
    // system is internal client code ordered by the client's
    // `World::start` schedule.)
    let (names, defs): (Vec<String>, Vec<BlobAssetDef>) = named.into_iter().unzip();

    Ok(PipelineResult {
        defs,
        names,
        resources: compiled.resources,
        scene_groups: compiled.scene_groups,
        mesh_bounds: compiled.mesh_bounds,
        physics_budget,
        mesh_component_names: compiled.mesh_component_names,
        payloads: compiled.blobs,
        cache_hits: compiled.cache_hits,
        cache_misses: compiled.cache_misses,
        texture_sources,
        mesh_sources,
        resource_locks,
    })
}

// Per-asset state recorded by `probe_mesh_payload_cache`. `key` is the cache key
// computed from the asset's pre-desugar args; `bytes` is `Some` when the
// cache already held a compiled payload for that key. On a hit, the desugar
// pass skips the .glb parse for this asset; on a miss, compile_and_pack
// stores the freshly compiled payload under the same `key` so the next
// build's probe can re-use it.
#[derive(Clone)]
struct MeshCacheEntry {
    key: String,
    bytes: Option<Vec<u8>>,
}

// Hash every source-backed Mesh / SkinnedMesh asset's pre-desugar args and
// referenced source file (`.glb` or `.fbx`), then probe the content-addressed
// payload cache. Returns one entry per source-backed asset name. Assets
// without a `source` are not probed: their args don't depend on a file, so the
// regular per-asset cache path inside compile_and_pack_payloads is sufficient.
fn probe_mesh_payload_cache(
    assets: &[WorldJsonlAsset],
    assets_dir: Option<&Path>,
    artifacts_dir: Option<&str>,
) -> std::collections::HashMap<String, MeshCacheEntry> {
    use crate::resource_handles::{RegisteredType, ResourceAssetCompile};

    let mut out = std::collections::HashMap::new();
    let empty: [WorldJsonlAsset; 0] = [];
    for asset in assets {
        let has_source = asset
            .args
            .get("source")
            .and_then(|v| v.as_str())
            .map(|s| !s.is_empty())
            .unwrap_or(false);
        if !has_source && asset.args.get("character_model").is_none() {
            continue;
        }

        // Both mesh kinds are resource assets: their caches key on the
        // resource discriminant and resource source list.
        let rt = if asset.asset_type == MESH_TYPE {
            RegisteredType::Mesh
        } else if asset.asset_type == SKINNED_MESH_TYPE {
            RegisteredType::SkinnedMesh
        } else {
            continue;
        };
        let ctx = crate::asset::BuildCtx {
            name: asset.name.as_str(),
            assets_dir,
            artifacts_dir,
            all_assets: &empty,
        };
        let discriminant = RESOURCE_CACHE_DISC_BASE + job_resource_kind(rt) as u8;
        let inputs = crate::asset::CacheInputs::extra(rt.source_files(&asset.args, assets_dir));
        // A shape baked into the mesh changes its payload as much as the
        // source does, so its args join the key.
        let keyed = match crate::character::bake::baking_shape_args(assets, &asset.name) {
            Some(shape) => serde_json::json!({"mesh": asset.args, "baked_shape": shape}),
            None => asset.args.clone(),
        };
        let key = crate::cache::payload_key(discriminant, &keyed, &ctx, &inputs);
        let bytes = crate::cache::load(&key);
        out.insert(asset.name.clone(), MeshCacheEntry { key, bytes });
    }
    out
}

// Which skinned mesh of the asset's source file it selects; absent means the
// file's first.
fn skin_index_arg(asset: &WorldJsonlAsset) -> u32 {
    asset
        .args
        .get("skin_index")
        .and_then(|v| v.as_u64())
        .unwrap_or(0) as u32
}

// Skin selector per SkinnedMesh asset name. An Animation resolves its channels
// against its target's skeleton, so it inherits the target's selector rather
// than carrying its own: the two must agree or joint indices bind to a
// different skeleton and the clip silently mis-poses.
fn skin_index_by_target(assets: &[WorldJsonlAsset]) -> std::collections::HashMap<String, u32> {
    assets
        .iter()
        .filter(|a| a.asset_type == SKINNED_MESH_TYPE)
        .map(|a| (a.name.clone(), skin_index_arg(a)))
        .collect()
}

// Expand glTF-sourced SkinnedMesh assets in place: parse the referenced .glb
// and write the imported geometry + skeleton into the asset's inline
// `vertices` / `indices` / `skeleton` args. A SkinnedMesh with no `source` is
// left untouched, so an inline-authored mesh is byte-for-byte unchanged;
// `.fbx` sources belong to `desugar_fbx_skinned_meshes`.
// Skips an asset whose cache probe found a precompiled payload: there is no
// reason to parse the .glb when the bytes are already in hand.
fn desugar_gltf_skinned_meshes(
    assets: &mut [WorldJsonlAsset],
    mesh_cache: &std::collections::HashMap<String, MeshCacheEntry>,
    assets_dir: Option<&Path>,
) -> std::io::Result<()> {
    for asset in assets.iter_mut() {
        if asset.asset_type != SKINNED_MESH_TYPE {
            continue;
        }
        let source = asset
            .args
            .get("source")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let character_model = asset.args.get("character_model").cloned();
        if character_model.is_none()
            && (source.is_empty() || source.to_lowercase().ends_with(".fbx"))
        {
            continue;
        }
        // Cache probe found a compiled payload for this asset, no need
        // to parse the .glb. compile_and_pack_payloads will use the bytes
        // directly. Leave the args un-desugared so they keep matching the
        // pre-desugar cache key on the next build.
        if matches!(
            mesh_cache.get(&asset.name),
            Some(MeshCacheEntry { bytes: Some(_), .. })
        ) {
            continue;
        }

        let invalid = |msg: String| std::io::Error::new(std::io::ErrorKind::InvalidData, msg);
        let imported = match character_model {
            Some(arg) => {
                let arg: crate::character::import::CharacterModelArg = serde_json::from_value(arg)
                    .map_err(|e| {
                        invalid(format!("Asset '{}': character_model: {e}", asset.name))
                    })?;
                crate::character::import::import_model(
                    &asset.name,
                    &arg.schema,
                    &arg.model,
                    assets_dir,
                )
                .map_err(invalid)?
            }
            None => crate::gltf::import_skinned_glb(&source, skin_index_arg(asset), assets_dir)
                .map_err(|e| {
                    invalid(format!("Asset '{}': glTF import failed: {}", asset.name, e))
                })?,
        };

        let name = asset.name.clone();
        let obj = asset.args.as_object_mut().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Asset '{}': args is not a JSON object", name),
            )
        })?;
        let encode = |field: &str, value: serde_json::Result<serde_json::Value>| {
            value.map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "Asset '{}': failed to encode imported {}: {}",
                        name, field, e
                    ),
                )
            })
        };
        obj.insert(
            "vertices".to_string(),
            encode("vertices", serde_json::to_value(&imported.vertices))?,
        );
        obj.insert(
            "indices".to_string(),
            encode("indices", serde_json::to_value(&imported.indices))?,
        );
        obj.insert(
            "skeleton".to_string(),
            encode("skeleton", serde_json::to_value(&imported.skeleton))?,
        );
        if !imported.morph_target_names.is_empty() {
            obj.insert(
                "morph_target_names".to_string(),
                encode(
                    "morph_target_names",
                    serde_json::to_value(&imported.morph_target_names),
                )?,
            );
            obj.insert(
                "morph_deltas".to_string(),
                encode("morph_deltas", serde_json::to_value(&imported.morph_deltas))?,
            );
        }
        obj.remove("character_model");
        tracing::info!(
            "Asset '{}': imported glTF '{}': {} vertices, {} indices, {} joints, {} morph target(s)",
            asset.name,
            if source.is_empty() {
                "character model"
            } else {
                &source
            },
            imported.vertices.len(),
            imported.indices.len(),
            imported.skeleton.len(),
            imported.morph_target_names.len()
        );
    }
    Ok(())
}

// Expand FBX-sourced SkinnedMesh assets in place, mirroring the glTF pass:
// the file's first skinned geometry lands in the asset's inline `vertices` /
// `indices` / `skeleton` args.
fn desugar_fbx_skinned_meshes(
    assets: &mut [WorldJsonlAsset],
    mesh_cache: &std::collections::HashMap<String, MeshCacheEntry>,
) -> std::io::Result<()> {
    for asset in assets.iter_mut() {
        if asset.asset_type != SKINNED_MESH_TYPE {
            continue;
        }
        let source = asset
            .args
            .get("source")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        if !source.to_lowercase().ends_with(".fbx") {
            continue;
        }
        if matches!(
            mesh_cache.get(&asset.name),
            Some(MeshCacheEntry { bytes: Some(_), .. })
        ) {
            continue;
        }

        let imported =
            crate::fbx::import_skinned_fbx(&source, skin_index_arg(asset)).map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Asset '{}': FBX import failed: {}", asset.name, e),
                )
            })?;

        let name = asset.name.clone();
        let obj = asset.args.as_object_mut().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Asset '{}': args is not a JSON object", name),
            )
        })?;
        let encode = |field: &str, value: serde_json::Result<serde_json::Value>| {
            value.map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "Asset '{}': failed to encode imported {}: {}",
                        name, field, e
                    ),
                )
            })
        };
        obj.insert(
            "vertices".to_string(),
            encode("vertices", serde_json::to_value(&imported.vertices))?,
        );
        obj.insert(
            "indices".to_string(),
            encode("indices", serde_json::to_value(&imported.indices))?,
        );
        obj.insert(
            "skeleton".to_string(),
            encode("skeleton", serde_json::to_value(&imported.skeleton))?,
        );
        tracing::info!(
            "Asset '{}': imported FBX '{}': {} vertices, {} indices, {} joints",
            asset.name,
            source,
            imported.vertices.len(),
            imported.indices.len(),
            imported.skeleton.len()
        );
    }
    Ok(())
}

// Expand glTF-sourced static `Mesh` assets in place: parse the referenced
// `.glb` and write the imported primitive geometry into the asset's inline
// `vertices` / `indices` args. A Mesh with no `source` is left untouched. The
// GLB is parsed once per unique path; ABeautifulGame fans 35+ Mesh assets out
// of one file, so memoization keeps this O(files) rather than O(primitives).
fn desugar_gltf_meshes(
    assets: &mut [WorldJsonlAsset],
    mesh_cache: &std::collections::HashMap<String, MeshCacheEntry>,
    assets_dir: Option<&Path>,
) -> std::io::Result<()> {
    use crate::components::VertexData;
    use std::collections::HashMap;

    // One split chunk: its vertices and index buffer.
    type Chunk = (Vec<VertexData>, Vec<u16>);

    let mut parsed_cache: HashMap<String, crate::gltf_source::GltfDoc> = HashMap::new();
    // Memoize the chunk split per (source, primitive_index) so an oversized
    // primitive that fans into N chunked Mesh assets is split exactly once.
    let mut chunk_cache: HashMap<(String, u32), Vec<Chunk>> = HashMap::new();

    for asset in assets.iter_mut() {
        if asset.asset_type != MESH_TYPE {
            continue;
        }
        let source = asset
            .args
            .get("source")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        if source.is_empty() {
            continue;
        }
        // `.fbx` sources are handled by `desugar_fbx_meshes`; this pass owns
        // only the glTF containers.
        let lower = source.to_lowercase();
        if !lower.ends_with(".glb") && !lower.ends_with(".gltf") {
            continue;
        }
        // Skip the .glb parse when the cache probe already produced bytes
        // for this asset (see `desugar_gltf_skinned_meshes` for the same
        // pattern). Args stay pre-desugar so the next build's probe hits.
        if matches!(
            mesh_cache.get(&asset.name),
            Some(MeshCacheEntry { bytes: Some(_), .. })
        ) {
            continue;
        }
        let primitive_index = asset
            .args
            .get("primitive_index")
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as u32;
        let chunk_index = asset
            .args
            .get("chunk_index")
            .and_then(|v| v.as_u64())
            .map(|n| n as usize);

        if !parsed_cache.contains_key(&source) {
            let doc = crate::glb::parse_glb(&source, assets_dir).map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Asset '{}': glTF import failed: {}", asset.name, e),
                )
            })?;
            parsed_cache.insert(source.clone(), doc);
        }
        let doc = parsed_cache.get(&source).expect("just inserted");

        let (vertices, indices) = if let Some(chunk_idx) = chunk_index {
            let key = (source.clone(), primitive_index);
            if !chunk_cache.contains_key(&key) {
                let (verts, indices32) =
                    crate::glb::read_primitive_geometry(doc, &source, primitive_index).map_err(
                        |e| {
                            std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                format!("Asset '{}': glTF import failed: {}", asset.name, e),
                            )
                        },
                    )?;
                let chunks = crate::glb::split_into_u16_chunks(&verts, &indices32);
                chunk_cache.insert(key.clone(), chunks);
            }
            let chunks = chunk_cache.get(&key).expect("just inserted");
            let chunk = chunks.get(chunk_idx).ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "Asset '{}': chunk_index {} out of range, '{}' primitive {} \
                         splits into {} chunk(s)",
                        asset.name,
                        chunk_idx,
                        source,
                        primitive_index,
                        chunks.len(),
                    ),
                )
            })?;
            chunk.clone()
        } else {
            crate::glb::import_static_glb_primitive_from_doc(doc, &source, primitive_index)
                .map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Asset '{}': glTF import failed: {}", asset.name, e),
                    )
                })?
        };

        let name = asset.name.clone();
        let obj = asset.args.as_object_mut().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Asset '{}': args is not a JSON object", name),
            )
        })?;
        let encode = |field: &str, value: serde_json::Result<serde_json::Value>| {
            value.map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "Asset '{}': failed to encode imported {}: {}",
                        name, field, e
                    ),
                )
            })
        };
        let vlen = vertices.len();
        let ilen = indices.len();
        obj.insert(
            "vertices".to_string(),
            encode("vertices", serde_json::to_value(&vertices))?,
        );
        obj.insert(
            "indices".to_string(),
            encode("indices", serde_json::to_value(&indices))?,
        );
        match chunk_index {
            Some(c) => tracing::info!(
                "Asset '{}': imported glTF '{}' primitive {} chunk {}: {} vertices, {} indices",
                asset.name,
                source,
                primitive_index,
                c,
                vlen,
                ilen,
            ),
            None => tracing::info!(
                "Asset '{}': imported glTF '{}' primitive {}: {} vertices, {} indices",
                asset.name,
                source,
                primitive_index,
                vlen,
                ilen,
            ),
        }
    }
    Ok(())
}

// Expand FBX-sourced Mesh assets in place: parse the `.fbx` into an FbxScene
// and write the imported geometry into each asset's inline `vertices` /
// `indices` args, keyed by `primitive_index` and optional `chunk_index`. A Mesh
// whose source is not a `.fbx` is left to `desugar_gltf_meshes`. The FBX is
// parsed once per unique path (Bistro fans thousands of Mesh assets out of one
// file) and each primitive's u16 chunk split is memoized.
fn desugar_fbx_meshes(
    assets: &mut [WorldJsonlAsset],
    mesh_cache: &std::collections::HashMap<String, MeshCacheEntry>,
) -> std::io::Result<()> {
    use crate::components::VertexData;
    use crate::fbx::FbxScene;
    use std::collections::HashMap;

    type Chunk = (Vec<VertexData>, Vec<u16>);

    let mut parsed_cache: HashMap<String, FbxScene> = HashMap::new();
    let mut chunk_cache: HashMap<(String, u32), Vec<Chunk>> = HashMap::new();

    for asset in assets.iter_mut() {
        if asset.asset_type != MESH_TYPE {
            continue;
        }
        let source = asset
            .args
            .get("source")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        if !source.to_lowercase().ends_with(".fbx") {
            continue;
        }
        // Honour the same content-addressed cache the glTF pass uses: a probe
        // hit means the compiled payload is already in hand, so skip the parse.
        if matches!(
            mesh_cache.get(&asset.name),
            Some(MeshCacheEntry { bytes: Some(_), .. })
        ) {
            continue;
        }
        let primitive_index = asset
            .args
            .get("primitive_index")
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as u32;
        let chunk_index = asset
            .args
            .get("chunk_index")
            .and_then(|v| v.as_u64())
            .map(|n| n as usize)
            .unwrap_or(0);

        if !parsed_cache.contains_key(&source) {
            let scene = crate::fbx::parse_fbx(&source).map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Asset '{}': FBX import failed: {}", asset.name, e),
                )
            })?;
            parsed_cache.insert(source.clone(), scene);
        }
        let scene = parsed_cache.get(&source).expect("just inserted");

        let key = (source.clone(), primitive_index);
        if !chunk_cache.contains_key(&key) {
            let (verts, indices32) = crate::fbx::read_primitive_geometry(scene, primitive_index)
                .map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Asset '{}': FBX import failed: {}", asset.name, e),
                    )
                })?;
            let chunks = crate::glb::split_into_u16_chunks(&verts, &indices32);
            chunk_cache.insert(key.clone(), chunks);
        }
        let chunks = chunk_cache.get(&key).expect("just inserted");
        let chunk = chunks.get(chunk_index).ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "Asset '{}': chunk_index {} out of range, '{}' primitive {} splits into {} chunk(s)",
                    asset.name,
                    chunk_index,
                    source,
                    primitive_index,
                    chunks.len(),
                ),
            )
        })?;
        let (vertices, indices) = chunk.clone();

        let name = asset.name.clone();
        let obj = asset.args.as_object_mut().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Asset '{}': args is not a JSON object", name),
            )
        })?;
        let vlen = vertices.len();
        let ilen = indices.len();
        obj.insert(
            "vertices".to_string(),
            serde_json::to_value(&vertices).map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "Asset '{}': failed to encode imported vertices: {}",
                        name, e
                    ),
                )
            })?,
        );
        obj.insert(
            "indices".to_string(),
            serde_json::to_value(&indices).map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Asset '{}': failed to encode imported indices: {}", name, e),
                )
            })?,
        );
        tracing::info!(
            "Asset '{}': imported FBX '{}' primitive {} chunk {}: {} vertices, {} indices",
            asset.name,
            source,
            primitive_index,
            chunk_index,
            vlen,
            ilen,
        );
    }
    Ok(())
}

// Expand file-sourced `Animation` assets in place, dispatching on the source
// extension: `.fbx` clips bake through the FBX importer (at the asset's
// `sample_rate`), everything else parses as glTF. The clip is picked by
// `animation_name` (preferred) or `animation_index` and the asset's
// `duration` + `tracks` are replaced with the imported data. An Animation
// with no `source` is left untouched, so inline-authored clips are
// byte-for-byte unchanged. Channels targeting non-joint nodes are dropped
// silently by the importers.
fn desugar_animation_imports(
    assets: &mut [WorldJsonlAsset],
    assets_dir: Option<&Path>,
) -> std::io::Result<()> {
    use crate::components::Animation;
    use crate::ecs::Component;

    let skin_by_target = skin_index_by_target(assets);

    for asset in assets.iter_mut() {
        if asset.asset_type != Animation::NAME {
            continue;
        }
        let source = asset
            .args
            .get("source")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        if source.is_empty() {
            continue;
        }
        let animation_name = asset
            .args
            .get("animation_name")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let animation_index = asset
            .args
            .get("animation_index")
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as usize;
        let skin_index = asset
            .args
            .get("target")
            .and_then(|v| v.as_str())
            .and_then(|t| skin_by_target.get(t))
            .copied()
            .unwrap_or(0);

        let imported = if source.to_lowercase().ends_with(".fbx") {
            let sample_rate = asset
                .args
                .get("sample_rate")
                .and_then(|v| v.as_f64())
                .unwrap_or(30.0) as f32;
            crate::fbx::import_fbx_animation(
                &source,
                animation_index as u32,
                &animation_name,
                sample_rate,
                skin_index,
            )
            .map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Asset '{}': FBX import failed: {}", asset.name, e),
                )
            })?
        } else {
            // Look up by name when authored; fall back to the numeric index.
            let resolved_index = if !animation_name.is_empty() {
                let names = crate::gltf::glb_animation_names(&source, assets_dir).map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Asset '{}': glTF import failed: {}", asset.name, e),
                    )
                })?;
                names
                    .iter()
                    .position(|n| n == &animation_name)
                    .ok_or_else(|| {
                        std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            format!(
                                "Asset '{}': glTF '{}' has no animation named '{}' \
                                 (file contains: {:?})",
                                asset.name, source, animation_name, names
                            ),
                        )
                    })?
            } else {
                animation_index
            };

            crate::gltf::import_glb_animation(&source, resolved_index, skin_index, assets_dir)
                .map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Asset '{}': glTF import failed: {}", asset.name, e),
                    )
                })?
        };

        // Convert ImportedAnimation -> the asset's serialised track shape.
        let tracks_json: Vec<serde_json::Value> = imported
            .tracks
            .iter()
            .map(|track| {
                let keyframes: Vec<serde_json::Value> = track
                    .keys
                    .iter()
                    .map(|k| {
                        serde_json::json!({
                            "time": k.time,
                            "translation": k.pose.translation,
                            "rotation_deg": k.pose.rotation_deg,
                            "scale": k.pose.scale,
                        })
                    })
                    .collect();
                serde_json::json!({
                    "joint": track.joint,
                    "keyframes": keyframes,
                })
            })
            .collect();

        let name = asset.name.clone();
        let obj = asset.args.as_object_mut().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Asset '{}': args is not a JSON object", name),
            )
        })?;
        obj.insert("duration".to_string(), serde_json::json!(imported.duration));
        obj.insert("tracks".to_string(), serde_json::Value::Array(tracks_json));
        if !imported.morph_track.is_empty() {
            let morph_json: Vec<serde_json::Value> = imported
                .morph_track
                .iter()
                .map(|k| serde_json::json!({"time": k.time, "weights": k.weights}))
                .collect();
            obj.insert(
                "morph_track".to_string(),
                serde_json::Value::Array(morph_json),
            );
        }
        tracing::info!(
            "Asset '{}': imported '{}' animation '{}': {:.3} s, {} track(s), {} morph key(s)",
            asset.name,
            source,
            imported.name,
            imported.duration,
            imported.tracks.len(),
            imported.morph_track.len(),
        );
    }
    Ok(())
}

// Bake root motion on every Animation that opted in: strip the root joint's
// travel out of the pose tracks into the asset's `root_track` (see
// `root_motion::bake_root_motion`). Runs after the glTF pass so imported
// tracks are already inline; an Animation without `root_motion` is
// untouched. A root-motion clip whose root joint has no track produces an
// empty curve, which would silently never move a character, so it warns.
fn desugar_root_motion(assets: &mut [WorldJsonlAsset]) -> std::io::Result<()> {
    use crate::components::Animation;
    use crate::ecs::Component;

    // This deserializes each flagged clip (whose `target` is a name reference),
    // so the name resolver must be installed. The full pipeline resets the
    // interner before reaching here; installing it again is a cheap no-op and
    // keeps this pass correct when called on its own.
    crate::ecs::asset_id::ensure_name_resolver();

    for asset in assets.iter_mut() {
        if asset.asset_type != Animation::NAME
            || asset.args.get("root_motion").and_then(|v| v.as_bool()) != Some(true)
        {
            continue;
        }
        let mut anim: Animation = Deserialize::deserialize(&asset.args).map_err(|e| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "Asset '{}': root-motion bake failed to parse args: {}",
                    asset.name, e
                ),
            )
        })?;
        crate::root_motion::bake_root_motion(&mut anim);
        if anim.root_track.is_empty() {
            tracing::warn!(
                "Asset '{}': root_motion is set but the clip has no track on the root \
                 joint; the character will not move",
                asset.name
            );
        }
        let name = asset.name.clone();
        let obj = asset.args.as_object_mut().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Asset '{}': args is not a JSON object", name),
            )
        })?;
        obj.insert(
            "tracks".to_string(),
            serde_json::to_value(&anim.tracks).expect("serialize animation tracks"),
        );
        obj.insert(
            "root_track".to_string(),
            serde_json::to_value(&anim.root_track).expect("serialize root track"),
        );
        tracing::info!(
            "Asset '{}': baked root motion ({} key(s){})",
            asset.name,
            anim.root_track.len(),
            if anim.root_motion_y { ", incl. Y" } else { "" },
        );
    }
    Ok(())
}

/// Validate world JSONL without running compilation. Runs the full front half
/// of the pipeline (load, expand, semantic checks) plus a per-asset type/args
/// resolution, but stops short of compiling payloads: intended for fast
/// server-side pre-deploy checks where shader compilation is not needed.
/// `assets_dir` is the asset search root the expansion passes resolve their
/// sources and presets against. Every problem found is reported in a single
/// newline-joined error.
pub fn validate_world_jsonl(content: &str, assets_dir: Option<&Path>) -> std::io::Result<()> {
    let loaded = crate::world::prepare_world(content, assets_dir).map_err(errors_to_io)?;

    let mut errors: Vec<String> = Vec::new();
    for asset in &loaded.assets {
        // A resource asset does not build a component def, so skip the component
        // resolution for it.
        if crate::registry::RegisteredType::parse(&asset.asset_type)
            .is_some_and(|t| t.is_resource())
        {
            continue;
        }
        let req = AssetRequest {
            asset_type: asset.asset_type.clone(),
            args: Some(asset.args.clone()),
        };
        if let Err(e) = asset_api::create_asset_def(&req) {
            errors.push(format!("Asset '{}': {}", asset.name, e));
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors_to_io(errors))
    }
}

// Cache-key discriminant base for resource payloads. Resource kinds are keyed
// as `128 + ResourceKind as u8` so their cache keys never collide with a
// component discriminant (all < 128, the `ComponentMask` ceiling).
const RESOURCE_CACHE_DISC_BASE: u8 = 128;

// One compiled resource awaiting packing: its kind tag + handle, the compiled
// bytes, whether those bytes are the record's inline data (a data resource like
// Material) or a blob payload, and the baked runtime data a hybrid kind
// (SkinnedMesh) carries alongside its payload (empty for everything else; it
// bakes from the authored args, so it sits outside the payload cache).
struct PendingResource {
    kind: u8,
    handle: u32,
    bytes: Vec<u8>,
    is_data: bool,
    extra_data: Vec<u8>,
}

// The output of the compile + pack pass: the packed blob payload sections, the
// resource-stream records (each with its payload locator), and cache accounting.
struct CompiledOutput {
    scene_groups: Vec<SceneGroup>,
    mesh_bounds: Vec<MeshBoundsRecord>,
    mesh_component_names: Vec<(u32, String)>,
    blobs: Vec<Vec<u8>>,
    resources: Vec<ResourceRecord>,
    cache_hits: usize,
    cache_misses: usize,
}

// Baked geometry summary of one compiled static-mesh payload, keyed by its
// unified mesh-source handle. None when the payload does not parse as a
// static mesh (VoxelChunk voxel data, a malformed payload); absence means the
// runtime decodes that payload eagerly.
fn mesh_bounds_record(handle: u32, bytes: &[u8]) -> Option<MeshBoundsRecord> {
    let (verts, idxs, _) = concinnity_core::gfx::mesh_payload::deserialise_with_lods(bytes).ok()?;
    let first = verts.first()?;
    let mut min = first.pos;
    let mut max = first.pos;
    for v in &verts {
        for axis in 0..3 {
            min[axis] = min[axis].min(v.pos[axis]);
            max[axis] = max[axis].max(v.pos[axis]);
        }
    }
    Some(MeshBoundsRecord {
        handle,
        min,
        max,
        vertex_count: verts.len() as u32,
        index_count: idxs.len() as u32,
    })
}

// Read-only inputs to the compile + pack pass: the world being packed and the
// build context, as opposed to the def stream the pass mutates.
#[derive(Clone, Copy)]
struct PackContext<'a> {
    assets: &'a [WorldJsonlAsset],
    resource_jobs: &'a [(usize, crate::registry::RegisteredType, u32)],
    partition: &'a crate::scene_partition::ScenePartition,
    mesh_source_handles: &'a crate::resource_handles::ResourceHandles,
    max_blob_bytes: u64,
    assets_dir: Option<&'a Path>,
    artifacts_dir: Option<&'a str>,
    mesh_cache: &'a std::collections::HashMap<String, MeshCacheEntry>,
    progress: Option<&'a (dyn Fn(BuildProgress) + Sync)>,
}

fn compile_and_pack_payloads(
    named: &mut [(String, BlobAssetDef)],
    named_src: &[usize],
    pack_ctx: PackContext<'_>,
) -> std::io::Result<CompiledOutput> {
    use rayon::prelude::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    let PackContext {
        assets,
        resource_jobs,
        partition,
        mesh_source_handles,
        max_blob_bytes,
        assets_dir,
        artifacts_dir,
        mesh_cache,
        progress,
    } = pack_ctx;

    let compiled_indices: Vec<usize> = named
        .iter()
        .enumerate()
        .filter(|(i, (_, def))| {
            if def.kind != AssetKind::Component {
                return false;
            }
            let Some(ct) = RegisteredType::from_discriminant(def.discriminant) else {
                return false;
            };
            if ct.as_str() == "File" {
                // only compile File assets whose kind maps to a supported payload
                // `named[i]` maps to `assets[named_src[i]]`.
                return assets[named_src[*i]]
                    .args
                    .get("kind")
                    .and_then(|k| k.as_str())
                    .and_then(FileKind::from_ext)
                    .map(|fk| fk.is_mesh())
                    .unwrap_or(false);
            }
            ct.registration().needs_compilation()
        })
        .map(|(i, _)| i)
        .collect();

    // Snapshot each job's inputs so the parallel compile borrows nothing from
    // `named`, which is mutated afterwards to record payload locators.
    let jobs: Vec<(usize, String, u8)> = compiled_indices
        .iter()
        .map(|&idx| {
            let (name, def) = &named[idx];
            (idx, name.clone(), def.discriminant)
        })
        .collect();

    // Compile assets in parallel. Each job is independent (it reads only its
    // own args and produces its own payload bytes) and the payload cache is
    // content-addressed, so concurrent hits and stores never collide. The
    // collected order follows `jobs`, so packing below stays deterministic.
    let cache_hits = AtomicUsize::new(0);
    let compile_total = jobs.len() as u32;
    let compiled_count = AtomicUsize::new(0);
    let report_one = || {
        if let Some(p) = progress {
            let done = compiled_count.fetch_add(1, Ordering::Relaxed) as u32 + 1;
            p(BuildProgress {
                stage: "compile",
                done,
                total: compile_total,
            });
        }
    };
    let pending: Vec<(usize, Vec<u8>)> = jobs
        .par_iter()
        .map(
            |(idx, name, discriminant)| -> std::io::Result<(usize, Vec<u8>)> {
                let ct = RegisteredType::from_discriminant(*discriminant).ok_or_else(|| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Invalid RegisteredType discriminant for asset '{}'", name),
                    )
                })?;

                // The job carries the `named` index; map it to its source asset
                // via `named_src` (`named` is not 1:1 with `assets` once resource
                // assets are partitioned out).
                let asset_args = &assets[named_src[*idx]].args;

                let ctx = crate::asset::BuildCtx {
                    name: name.as_str(),
                    assets_dir,
                    artifacts_dir,
                    all_assets: assets,
                };

                // GLB-sourced Mesh / SkinnedMesh assets are probed before
                // desugar; honor those results here so the .glb parse really
                // is skipped on cache hits. On a miss the precomputed key is
                // used at store time, keeping the next build's probe valid.
                if let Some(entry) = mesh_cache.get(name) {
                    if let Some(bytes) = &entry.bytes {
                        cache_hits.fetch_add(1, Ordering::Relaxed);
                        return Ok((*idx, bytes.clone()));
                    }
                    let compiled_bytes = compile_by_type(ct, asset_args, &ctx)?;
                    crate::cache::store(&entry.key, &compiled_bytes);
                    return Ok((*idx, compiled_bytes));
                }

                // Reuse a cached payload when the asset's inputs are unchanged;
                // otherwise compile and populate the cache for the next build.
                let inputs = cache_inputs_by_type(ct, asset_args, &ctx);
                let key = crate::cache::payload_key(*discriminant, asset_args, &ctx, &inputs);
                if let Some(bytes) = crate::cache::load(&key) {
                    cache_hits.fetch_add(1, Ordering::Relaxed);
                    return Ok((*idx, bytes));
                }
                let compiled_bytes = compile_by_type(ct, asset_args, &ctx)?;
                crate::cache::store(&key, &compiled_bytes);
                Ok((*idx, compiled_bytes))
            },
        )
        .inspect(|_| report_one())
        .collect::<std::io::Result<Vec<_>>>()?;

    let component_hits = cache_hits.into_inner();

    // Compile the resource-stream payloads (AudioClip today). Few and cheap, so
    // this stays serial; the content-addressed payload cache still short-circuits
    // an unchanged source. Bypasses the `BuildAsset`/`RegisteredType` path a
    // component takes -- a resource is no longer a component.
    let mut resource_hits = 0usize;
    let mut resource_pending: Vec<PendingResource> = Vec::new();
    for (asset_idx, rt, handle) in resource_jobs {
        let asset = &assets[*asset_idx];
        let ctx = crate::asset::BuildCtx {
            name: asset.name.as_str(),
            assets_dir,
            artifacts_dir,
            all_assets: assets,
        };
        let extra_data = rt
            .compile_data(&asset.name, &asset.args)?
            .unwrap_or_default();
        // A glTF/FBX-sourced mesh was probed before desugar; honor that result so
        // the source parse really is skipped on a hit and the pre-desugar key is
        // reused at store time (same contract as the component gltf-cache path).
        let bytes = if let Some(entry) = mesh_cache.get(&asset.name) {
            match &entry.bytes {
                Some(bytes) => {
                    resource_hits += 1;
                    bytes.clone()
                }
                None => {
                    let compiled = rt.compile_payload(&asset.args, assets_dir)?;
                    crate::cache::store(&entry.key, &compiled);
                    compiled
                }
            }
        } else {
            // Every resource asset compiles identically on every backend, so its
            // entry is shared across a DirectX and a Vulkan cook.
            let inputs = crate::asset::CacheInputs::extra(rt.source_files(&asset.args, assets_dir));
            let key = crate::cache::payload_key(
                RESOURCE_CACHE_DISC_BASE + job_resource_kind(*rt) as u8,
                &asset.args,
                &ctx,
                &inputs,
            );
            match crate::cache::load(&key) {
                Some(bytes) => {
                    resource_hits += 1;
                    bytes
                }
                None => {
                    let compiled = rt.compile_payload(&asset.args, assets_dir)?;
                    crate::cache::store(&key, &compiled);
                    compiled
                }
            }
        };
        resource_pending.push(PendingResource {
            kind: job_resource_kind(*rt) as u8,
            handle: *handle,
            bytes,
            is_data: rt.is_data(),
            extra_data,
        });
    }

    let cache_hits = component_hits + resource_hits;
    let cache_misses = (pending.len() - component_hits) + (resource_pending.len() - resource_hits);

    // Ownership of each payload, precomputed so the packing loops below can
    // mutate `named` freely. Resource jobs and `resource_pending` are
    // index-aligned.
    use crate::scene_partition::Owner;
    let comp_owners: Vec<Owner> = pending
        .iter()
        .map(|(idx, _)| partition.owner(&named[*idx].0))
        .collect();
    let res_owners: Vec<Owner> = resource_jobs
        .iter()
        .map(|(asset_idx, _, _)| partition.owner(&assets[*asset_idx].name))
        .collect();

    // Baked AABB + counts for every static mesh payload, resource-stream Mesh
    // entries first (their resource handle IS the mesh-source handle) then the
    // compiled mesh-source components, sorted by handle for determinism.
    let mut mesh_bounds: Vec<MeshBoundsRecord> = Vec::new();
    for ((_, rt, handle), res) in resource_jobs.iter().zip(&resource_pending) {
        if *rt == crate::registry::RegisteredType::Mesh
            && let Some(record) = mesh_bounds_record(*handle, &res.bytes)
        {
            mesh_bounds.push(record);
        }
    }
    let mut mesh_component_names: Vec<(u32, String)> = Vec::new();
    for (idx, bytes) in &pending {
        let asset = &assets[named_src[*idx]];
        if !crate::resource_handles::is_mesh_source(&asset.asset_type, &asset.args) {
            continue;
        }
        let id = asset_id::intern(&asset.name);
        if let Some(handle) =
            mesh_source_handles.get(crate::resource_handles::ResourceKind::Mesh, id)
        {
            // Handle -> asset name for mesh payloads riding component defs,
            // so a consumer can find any sub-mesh payload by unified handle
            // (resource-stream Mesh handles lead the space and resolve
            // through the resource records instead).
            mesh_component_names.push((handle, asset.name.clone()));
            if let Some(record) = mesh_bounds_record(handle, bytes) {
                mesh_bounds.push(record);
            }
        }
    }
    mesh_bounds.sort_unstable_by_key(|r| r.handle);

    // One group per scene (declaration order, possibly empty), carrying the
    // resource-stream entries and payload defs that scene exclusively owns.
    let scene_groups: Vec<SceneGroup> = (0..partition.scenes.len())
        .map(|s| SceneGroup {
            scene: asset_id::intern(&partition.scenes[s]),
            resources: resource_jobs
                .iter()
                .zip(&res_owners)
                .filter(|(_, o)| **o == Owner::Scene(s))
                .map(|((_, rt, handle), _)| (job_resource_kind(*rt) as u8, *handle))
                .collect(),
            defs: pending
                .iter()
                .zip(&comp_owners)
                .filter(|(_, o)| **o == Owner::Scene(s))
                .filter_map(|((idx, _), _)| named[*idx].1.name)
                .collect(),
        })
        .collect();

    if pending.is_empty() && resource_pending.is_empty() {
        return Ok(CompiledOutput {
            scene_groups,
            mesh_bounds,
            mesh_component_names,
            blobs: vec![Vec::new()],
            resources: Vec::new(),
            cache_hits: 0,
            cache_misses: 0,
        });
    }

    // Pack payloads by ownership group: the global set first (blob 0 onward),
    // then each scene's exclusive set starting at a fresh blob, so a scene's
    // payloads are contiguous and stay unread until the scene loads. Within a
    // group, component payloads pack before resource payloads, both in their
    // stream order. One packer, so every group addresses the same blob space;
    // record order in the metadata streams is unchanged (locators are
    // per-record, so packing order is independent).
    let mut packer = PayloadPacker::new(max_blob_bytes);
    let mut resource_locators: Vec<Option<concinnity_core::ecs::PayloadLocator>> =
        vec![None; resource_pending.len()];

    for group in 0..=partition.scenes.len() {
        let owner = match group {
            0 => Owner::Global,
            s => Owner::Scene(s - 1),
        };
        if group > 0 {
            packer.start_group();
        }
        for ((idx, bytes), item_owner) in pending.iter().zip(&comp_owners) {
            if *item_owner == owner {
                named[*idx].1.payload = Some(packer.push(bytes));
            }
        }
        for (i, (res, item_owner)) in resource_pending.iter().zip(&res_owners).enumerate() {
            if !res.is_data && *item_owner == owner {
                resource_locators[i] = Some(packer.push(&res.bytes));
            }
        }
    }

    let mut resources: Vec<ResourceRecord> = Vec::with_capacity(resource_pending.len());
    for (pending, locator) in resource_pending.iter().zip(resource_locators) {
        // A data resource (Material) carries its bytes inline; a payload
        // resource parks its bytes in a blob section and records the locator,
        // plus any hybrid baked data (SkinnedMesh) inline beside it.
        let (payload, data_bytes) = if pending.is_data {
            (None, pending.bytes.clone())
        } else {
            (locator, pending.extra_data.clone())
        };
        resources.push(ResourceRecord {
            resource_kind: pending.kind,
            handle: pending.handle,
            payload,
            data_bytes,
        });
    }

    Ok(CompiledOutput {
        scene_groups,
        mesh_bounds,
        mesh_component_names,
        blobs: packer.finish(),
        resources,
        cache_hits,
        cache_misses,
    })
}

// Dispatch payload compilation by RegisteredType. Every variant listed below
// has a `BuildAsset` impl in its asset file; the body of each call here is a
// one-liner that delegates to the trait. Adding a new compiled component
// means:
//   1. impl `Component` with `PAYLOAD = AssetPayload::Compiled` for the type
//   2. impl `BuildAsset` for the type in its asset file
//   3. Add one match arm here
fn compile_by_type(
    ct: RegisteredType,
    args: &serde_json::Value,
    ctx: &crate::asset::BuildCtx<'_>,
) -> std::io::Result<Vec<u8>> {
    use crate::asset::BuildAsset;
    use crate::components::{File, ProceduralMesh, Room, SdfVolume, Shader, VoxelChunk};
    match ct {
        RegisteredType::ProceduralMesh => {
            <ProceduralMesh as BuildAsset>::compile_payload(args, ctx)
        }
        RegisteredType::VoxelChunk => <VoxelChunk as BuildAsset>::compile_payload(args, ctx),
        RegisteredType::File => <File as BuildAsset>::compile_payload(args, ctx),
        RegisteredType::Room => <Room as BuildAsset>::compile_payload(args, ctx),
        RegisteredType::Shader => <Shader as BuildAsset>::compile_payload(args, ctx),
        RegisteredType::SdfVolume => <SdfVolume as BuildAsset>::compile_payload(args, ctx),
        other => Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "Asset '{}' is marked Compiled but has no BuildAsset impl (RegisteredType {:?})",
                ctx.name, other
            ),
        )),
    }
}

// Dispatch each asset's payload-cache contribution by RegisteredType. Mirrors
// `compile_by_type` so the cache layer can fold a hash of every input the
// compile reads into its payload key. Types with no `BuildAsset` impl, or with
// the trait default, contribute nothing.
//
// `source_files` and `TARGET_DEPENDENT` are read together per arm: a new
// asset whose payload differs per backend cannot pick up one without the
// other.
fn cache_inputs_by_type(
    ct: RegisteredType,
    args: &serde_json::Value,
    ctx: &crate::asset::BuildCtx<'_>,
) -> crate::asset::CacheInputs {
    use crate::asset::{BuildAsset, CacheInputs};
    use crate::components::{File, ProceduralMesh, Room, SdfVolume, Shader, VoxelChunk};
    macro_rules! inputs {
        ($t:ty) => {
            CacheInputs {
                sources: <$t as BuildAsset>::source_files(args, ctx),
                target_dependent: <$t as BuildAsset>::TARGET_DEPENDENT,
            }
        };
    }
    match ct {
        RegisteredType::ProceduralMesh => inputs!(ProceduralMesh),
        RegisteredType::VoxelChunk => inputs!(VoxelChunk),
        RegisteredType::File => inputs!(File),
        RegisteredType::Room => inputs!(Room),
        RegisteredType::Shader => inputs!(Shader),
        RegisteredType::SdfVolume => inputs!(SdfVolume),
        _ => CacheInputs::extra(Vec::new()),
    }
}

// Resolve scene + screen associations that the runtime can no longer derive
// from name strings, baking them into the asset args so they survive as
// AssetId ids.
//
// Naming-convention relationships handled:
//   - A Prop named `<scene>_*` belongs to Scene `<scene>`. The matched scene
//     name is written into the prop's `scene` arg.
//   - A UI element (Sprite, ImageOverlay, TextLabel, Text, TextInput,
//     HitRegion, ScrollPanel) named `<screen>_*` belongs to Screen `<screen>`.
//     The matched screen name is written into the asset's `screen` arg.
//   - A HitRegion or KeyBinding `action` of the form `scene:<name>`,
//     `screen:show:<name>`, `screen:push:<name>`, or `screen:toggle:<name>`
//     has its `<name>` part rewritten to the interned id, so `UiInputSystem`
//     can parse an integer at runtime instead of a name.
fn resolve_scene_refs(assets: &mut [WorldJsonlAsset]) {
    let norm = |s: &str| s.to_lowercase().replace('_', "");

    let scene_names: Vec<String> = assets
        .iter()
        .filter(|a| norm(&a.asset_type) == "scene")
        .map(|a| a.name.clone())
        .collect();

    let screen_names: Vec<String> = assets
        .iter()
        .filter(|a| norm(&a.asset_type) == "screen")
        .map(|a| a.name.clone())
        .collect();

    // Longest matching prefix wins so a nested name (e.g. `level_boss_*` under
    // both `level` and `level_boss`) binds to the most specific host.
    // Equivalent to first-match when no host name prefixes another.
    let longest_prefix_host = |name: &str, hosts: &[String]| -> Option<String> {
        hosts
            .iter()
            .filter(|h| name.starts_with(&format!("{h}_")))
            .max_by_key(|h| h.len())
            .cloned()
    };

    // Rewrite an action string, replacing the trailing `<name>` after the
    // given action prefix with its interned id. Returns Some(new_action) when
    // the action used the prefix with an unresolved name; None otherwise.
    let resolve_action = |action: &str| -> Option<String> {
        for prefix in ["scene:", "screen:show:", "screen:push:", "screen:toggle:"] {
            if let Some(rest) = action.strip_prefix(prefix) {
                if !rest.is_empty() && rest.parse::<u32>().is_err() {
                    return Some(format!("{prefix}{}", asset_id::intern(rest).0));
                }
                return None;
            }
        }
        None
    };

    for asset in assets.iter_mut() {
        let ty = norm(&asset.asset_type);

        // Host binding by name prefix: a Prop takes its Scene, a UI element
        // takes its Screen. An asset that already names its host is left alone.
        let host = match ty.as_str() {
            "prop" => Some(("scene", &scene_names)),
            "sprite" | "imageoverlay" | "textlabel" | "text" | "textinput" | "hitregion"
            | "scrollpanel" => Some(("screen", &screen_names)),
            _ => None,
        };
        if let Some((key, hosts)) = host
            && asset.args.get(key).is_none()
            && let Some(matched) = longest_prefix_host(&asset.name, hosts)
            && let serde_json::Value::Object(m) = &mut asset.args
        {
            m.insert(key.to_string(), serde_json::Value::String(matched));
        }

        // Resolve screen:* / scene:* action targets to interned ids.
        if matches!(ty.as_str(), "hitregion" | "keybinding") {
            let new_action = asset
                .args
                .get("action")
                .and_then(|v| v.as_str())
                .and_then(resolve_action);
            if let (Some(action), serde_json::Value::Object(m)) = (new_action, &mut asset.args) {
                m.insert("action".to_string(), serde_json::Value::String(action));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Default-shader compilation writes intermediates to a shared
    // data path keyed by asset name, so tests whose worlds pull in
    // the default Shader (any rendering world) must not build concurrently.
    static SHADER_BUILD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn build_pipeline_interns_names_and_resolves_refs() {
        let _guard = SHADER_BUILD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        crate::shader::install_stub_toolchain();
        // box=0, day=1, day_crate=2 in declaration order.
        let world = concat!(
            r#"{"name":"box","type":"ProceduralMesh","args":{"generator":"box","half_extents":[1,1,1]}}"#,
            "\n",
            r#"{"name":"day","type":"Scene","args":{}}"#,
            "\n",
            r#"{"name":"day_crate","type":"Prop","args":{"mesh":"box"}}"#,
            "\n",
        );
        let result = build_pipeline_from_str(world, None, None).expect("build pipeline");

        // The Prop def's identity is the interned id, not a name string.
        let prop = result
            .defs
            .iter()
            .find(|d| d.name == Some(crate::ecs::asset_id::AssetId(2)))
            .expect("day_crate def present with interned id 2");

        let baked: crate::components::Prop = postcard::from_bytes(&prop.args_bytes).unwrap();
        // The `mesh` reference resolved to box's handle (0).
        assert_eq!(baked.mesh, Some(crate::ecs::MeshHandle(0)));
        // The `day_` name prefix resolved to Scene `day`'s id (1).
        assert_eq!(baked.scene, Some(crate::ecs::asset_id::AssetId(1)));
    }

    // A world with physics content but no PhysicsConfig has one injected during
    // expansion; it must compile to the same values the runtime falls back to,
    // and leave the shipped budget alone.
    #[test]
    fn an_injected_physics_config_round_trips_through_the_blob() {
        let _guard = SHADER_BUILD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        crate::shader::install_stub_toolchain();
        let world = concat!(
            r#"{"name":"box","type":"ProceduralMesh","args":{"generator":"box","half_extents":[1,1,1]}}"#,
            "\n",
            r#"{"name":"crate_a","type":"Prop","args":{"mesh":"box","collider":{"shape":"cuboid"}}}"#,
            "\n",
            r#"{"name":"crate_body","type":"PropBody","args":{"prop_name":"crate_a"}}"#,
            "\n",
        );
        let result = build_pipeline_from_str(world, None, None).expect("build pipeline");

        let index = result
            .names
            .iter()
            .position(|n| n == "physics_config")
            .expect("the injected config compiled into the blob");
        let baked: crate::components::PhysicsConfig =
            postcard::from_bytes(&result.defs[index].args_bytes).unwrap();
        let default = crate::components::PhysicsConfig::default();
        assert_eq!(baked.floor_y, default.floor_y);
        assert_eq!(baked.terrain_subdivisions, default.terrain_subdivisions);
        assert_eq!(baked.terrain_mesh, default.terrain_mesh);
        assert!(baked.layers.is_empty());
        assert!(baked.no_collide.is_empty());
        assert_eq!(baked.contact_min_impulse, default.contact_min_impulse);
        assert_eq!(baked.spawn_headroom, 0, "the strict spawn cap is untouched");

        // The reservation is the authored content plus the floor, unchanged by
        // the config becoming visible.
        let budget = result.physics_budget.expect("a physics budget");
        assert_eq!(budget.spawn_headroom, 0);
        assert_eq!(budget.dynamic, 1, "the crate");
    }

    #[test]
    fn resource_payload_slices_the_named_resource() {
        let _guard = SHADER_BUILD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        crate::shader::install_stub_toolchain();
        let world = concat!(
            r#"{"name":"prism","type":"SkinnedMesh","args":{"#,
            r#""vertices":[{"pos":[0,0,0]},{"pos":[1,0,0]},{"pos":[0,1,0]}],"#,
            r#""indices":[0,1,2],"skeleton":[{"name":"root","parent":-1}],"#,
            r#""scale":[1,1,1]}}"#,
            "\n",
        );
        let result = build_pipeline_from_str(world, None, None).expect("build");
        let bytes = result
            .resource_payload(ResourceKind::SkinnedMesh, "prism")
            .expect("named payload");
        let payload =
            concinnity_core::gfx::mesh_payload::deserialise_skinned_with_lods(bytes).unwrap();
        assert_eq!(payload.vertices.len(), 3);
        assert_eq!(payload.joints[0].name, "root");
        // The wrong name or the wrong kind finds nothing.
        assert!(
            result
                .resource_payload(ResourceKind::SkinnedMesh, "ghost")
                .is_none()
        );
        assert!(
            result
                .resource_payload(ResourceKind::Texture, "prism")
                .is_none()
        );
    }

    // A resource asset (here a Font) leaves no component def, so the lock
    // records it through `resource_locks` instead: name, kind, handle, args
    // hash, and the blob its payload landed in.
    #[test]
    fn build_pipeline_records_resource_lock_provenance() {
        let _guard = SHADER_BUILD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        crate::shader::install_stub_toolchain();
        let world = concat!(
            r#"{"name":"f","type":"Font","args":{"size_px":20}}"#,
            "\n",
            r#"{"name":"pause","type":"Screen","args":{}}"#,
            "\n",
        );
        let result = build_pipeline_from_str(world, None, None).expect("build");

        assert_eq!(result.resource_locks.len(), result.resources.len());
        let font = result
            .resource_locks
            .iter()
            .find(|r| r.name == "f")
            .expect("font provenance recorded");
        assert_eq!(font.kind, "Font");
        assert_eq!(font.handle, 0);
        assert_eq!(font.args_hash.len(), 64);
        // A payload resource records which blob holds its bytes.
        assert!(font.payload_blob.is_some());
        // The resource is not in the component asset list.
        assert!(!result.names.iter().any(|n| n == "f"));
    }

    // The visual_novel demo world (in concinnity-infra/worlds) exercises
    // Sprite + Screen + KeyBinding together. Validating it here catches asset
    // registration / pipeline regressions before we ship the world.
    #[test]
    fn visual_novel_world_validates() {
        // Inline a representative subset of the world so the test stays
        // hermetic (no infra path lookup needed). Covers: an initial Screen,
        // a Sprite under that screen's prefix, a TextLabel under it, a
        // HitRegion firing screen:show on another Screen, and a KeyBinding to
        // toggle a third (modal) Screen.
        let world = r#"{"name":"gfx","type":"GraphicsConfig","args":{}}
{"name":"f","type":"Font","args":{"size_px":20}}
{"name":"title_menu","type":"Screen","args":{"initial":true}}
{"name":"title_menu_bg","type":"Sprite","args":{"x":0,"y":0,"width":640,"height":360,"tint":[0.1,0.1,0.1,1]}}
{"name":"title_menu_lbl","type":"TextLabel","args":{"font":"f","content":"Start","x":260,"y":160}}
{"name":"title_menu_btn","type":"HitRegion","args":{"x":260,"y":156,"width":120,"height":40,"label":"title_menu_lbl","action":"screen:show:vn_page_1"}}
{"name":"vn_page_1","type":"Screen","args":{}}
{"name":"vn_page_1_text","type":"TextLabel","args":{"font":"f","content":"hello","x":40,"y":40}}
{"name":"vn_page_1_next","type":"HitRegion","args":{"x":0,"y":0,"width":640,"height":360,"action":"screen:show:title_menu"}}
{"name":"pause_menu","type":"Screen","args":{}}
{"name":"pause_menu_dim","type":"Sprite","args":{"x":0,"y":0,"width":640,"height":360,"tint":[0,0,0,0.6]}}
{"name":"esc","type":"KeyBinding","args":{"key":"Escape","action":"screen:toggle:pause_menu"}}
"#;
        validate_world_jsonl(world, None).expect("visual_novel-shaped world should validate");
    }

    // `screen:show:<name>` / `screen:toggle:<name>` action targets are
    // rewritten to interned ids at build time, like `scene:<name>`.
    #[test]
    fn build_pipeline_resolves_screen_action_refs() {
        let world = concat!(
            r#"{"name":"pause_menu","type":"Screen","args":{}}"#,
            "\n",
            r#"{"name":"btn","type":"HitRegion","args":{"x":0,"y":0,"width":10,"height":10,"action":"screen:toggle:pause_menu"}}"#,
            "\n",
            r#"{"name":"esc","type":"KeyBinding","args":{"key":"Escape","action":"screen:toggle:pause_menu"}}"#,
            "\n",
        );
        let result = build_pipeline_from_str(world, None, None).expect("build");
        // pause_menu interned id = 0 (first declared name).
        let btn = result
            .defs
            .iter()
            .find(|d| d.name == Some(crate::ecs::asset_id::AssetId(1)))
            .expect("HitRegion def");
        let baked: crate::components::HitRegion = postcard::from_bytes(&btn.args_bytes).unwrap();
        assert_eq!(baked.action, "screen:toggle:0");

        let esc = result
            .defs
            .iter()
            .find(|d| d.name == Some(crate::ecs::asset_id::AssetId(2)))
            .expect("KeyBinding def");
        let baked: crate::components::KeyBinding = postcard::from_bytes(&esc.args_bytes).unwrap();
        assert_eq!(baked.action, "screen:toggle:0");
    }

    // A Sprite/TextLabel/HitRegion named `<screen>_*` has its `screen` arg
    // resolved from the prefix at build time, mirroring Prop scene refs.
    #[test]
    fn build_pipeline_resolves_screen_prefix_on_ui_assets() {
        let _guard = SHADER_BUILD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        crate::shader::install_stub_toolchain();
        let world = concat!(
            r#"{"name":"pause_menu","type":"Screen","args":{}}"#,
            "\n",
            r#"{"name":"pause_menu_dim","type":"Sprite","args":{"x":0,"y":0,"width":10,"height":10}}"#,
            "\n",
            r#"{"name":"pause_menu_title","type":"TextLabel","args":{"font":"f","content":"x","x":0,"y":0}}"#,
            "\n",
            r#"{"name":"pause_menu_btn","type":"HitRegion","args":{"x":0,"y":0,"width":10,"height":10,"action":"screen:hide"}}"#,
            "\n",
            r#"{"name":"f","type":"Font","args":{"size_px":16}}"#,
            "\n",
        );
        let result = build_pipeline_from_str(world, None, None).expect("build");
        // pause_menu interned id = 0; the UI assets intern in declaration order.
        let baked_view = |id: u32, expect: &str| {
            let def = result
                .defs
                .iter()
                .find(|d| d.name == Some(crate::ecs::asset_id::AssetId(id)))
                .unwrap_or_else(|| panic!("expected a def for {expect}"));
            let ct = crate::registry::RegisteredType::from_discriminant(def.discriminant)
                .unwrap_or_else(|| panic!("{expect}: unknown discriminant"));
            match ct {
                crate::registry::RegisteredType::Sprite => {
                    postcard::from_bytes::<crate::components::Sprite>(&def.args_bytes)
                        .unwrap()
                        .screen
                }
                crate::registry::RegisteredType::TextLabel => {
                    postcard::from_bytes::<crate::components::TextLabel>(&def.args_bytes)
                        .unwrap()
                        .screen
                }
                crate::registry::RegisteredType::HitRegion => {
                    postcard::from_bytes::<crate::components::HitRegion>(&def.args_bytes)
                        .unwrap()
                        .screen
                }
                other => panic!("{expect}: unexpected type {other:?}"),
            }
        };
        for (id, name) in [
            (1, "pause_menu_dim"),
            (2, "pause_menu_title"),
            (3, "pause_menu_btn"),
        ] {
            assert_eq!(
                baked_view(id, name),
                Some(crate::ecs::asset_id::AssetId(0)),
                "expected {name} to have screen=0"
            );
        }
    }

    // Nested screen names resolve by longest prefix: `<menu>_settings_*` binds
    // to the `<menu>_settings` screen, not the enclosing `<menu>` screen that is
    // declared first. (Regression: first-match claimed the nested elements,
    // so a MainMenu's settings sub-screen rendered on top of the main menu.)
    #[test]
    fn resolve_scene_refs_picks_longest_screen_prefix() {
        let mk = |name: &str, ty: &str| crate::world::WorldJsonlAsset {
            name: name.to_string(),
            asset_type: ty.to_string(),
            args: serde_json::json!({}),
        };
        let mut assets = vec![
            mk("menu", "Screen"),
            mk("menu_settings", "Screen"),
            mk("menu_title", "TextLabel"),
            mk("menu_settings_title", "TextLabel"),
        ];
        super::resolve_scene_refs(&mut assets);
        let view_of = |n: &str| {
            assets
                .iter()
                .find(|a| a.name == n)
                .and_then(|a| a.args.get("screen"))
                .and_then(|v| v.as_str())
                .map(str::to_string)
        };
        assert_eq!(view_of("menu_title").as_deref(), Some("menu"));
        assert_eq!(
            view_of("menu_settings_title").as_deref(),
            Some("menu_settings")
        );
    }

    // Animation with no `source` is left byte-for-byte unchanged: the
    // inline-authored path must not regress.
    #[test]
    fn desugar_animation_imports_skips_inline_clips() {
        let original = serde_json::json!({
            "target": "flag",
            "duration": 2.0,
            "tracks": [{"joint": 0, "keyframes": [{"time": 0.0, "rotation_deg": [0,0,0]}]}],
        });
        let mut assets = vec![crate::world::WorldJsonlAsset {
            name: "wave".to_string(),
            asset_type: "Animation".to_string(),
            args: original.clone(),
        }];
        desugar_animation_imports(&mut assets, None).expect("desugar succeeds");
        assert_eq!(assets[0].args, original);
    }

    // Opting into root motion strips the root joint's X/Z travel into
    // `root_track` and anchors the pose; a clip without the flag is
    // untouched, and a second pass over already-baked args is a no-op.
    #[test]
    fn desugar_root_motion_bakes_the_root_track() {
        let walk = serde_json::json!({
            "target": "hero",
            "duration": 1.0,
            "root_motion": true,
            "tracks": [{"joint": 0, "keyframes": [
                {"time": 0.0, "translation": [0.0, 1.0, 0.0]},
                {"time": 1.0, "translation": [2.0, 1.0, 0.0]}
            ]}],
        });
        let plain = serde_json::json!({
            "target": "hero",
            "duration": 1.0,
            "tracks": [{"joint": 0, "keyframes": [
                {"time": 1.0, "translation": [2.0, 1.0, 0.0]}
            ]}],
        });
        let mut assets = vec![
            crate::world::WorldJsonlAsset {
                name: "walk".to_string(),
                asset_type: "Animation".to_string(),
                args: walk,
            },
            crate::world::WorldJsonlAsset {
                name: "plain".to_string(),
                asset_type: "Animation".to_string(),
                args: plain.clone(),
            },
        ];
        desugar_root_motion(&mut assets).expect("desugar succeeds");

        let baked = &assets[0].args;
        assert_eq!(baked["root_track"][1]["translation"][0], 2.0);
        assert_eq!(baked["root_track"][1]["translation"][1], 0.0);
        // The pose keeps Y but stays anchored on X.
        assert_eq!(baked["tracks"][0]["keyframes"][1]["translation"][0], 0.0);
        assert_eq!(baked["tracks"][0]["keyframes"][1]["translation"][1], 1.0);
        assert_eq!(assets[1].args, plain, "flag-less clip untouched");

        let after_first = assets[0].args.clone();
        desugar_root_motion(&mut assets).expect("second pass succeeds");
        assert_eq!(assets[0].args, after_first, "re-bake is a no-op");
    }

    #[test]
    fn voxel_chunk_payload_compiles_end_to_end() {
        let world = r#"{"name":"scene_shader","type":"Shader","args":{"vertex":{"source":"x.metal"},"fragment":{"source":"x.metal"}}}
{"name":"air","type":"BlockType","args":{"solid":false}}
{"name":"stone","type":"BlockType","args":{"uv_min":[0,0],"uv_max":[1,1]}}
{"name":"chunk","type":"VoxelChunk","args":{"palette":["air","stone"],"dim":[2,1,1],"blocks":[1,1]}}
"#;
        // We can't easily compile shaders here, so go through the geometry
        // entry point directly to verify the voxel chunk produces a non-empty
        // payload for two adjacent solid blocks (10 faces after interior cull).
        let chunk_args = serde_json::json!({
            "palette": ["air", "stone"],
            "dim": [2, 1, 1],
            "blocks": [1, 1],
            "block_size": 1.0,
        });
        let bt = |name: &str| -> Option<serde_json::Value> {
            match name {
                "air" => Some(serde_json::json!({"solid": false})),
                "stone" => Some(serde_json::json!({"uv_min":[0,0],"uv_max":[1,1]})),
                _ => None,
            }
        };
        let bytes = crate::geometry::compile_voxel_chunk_payload(&chunk_args, bt).unwrap();
        assert!(!bytes.is_empty());
        let _ = world; // keeps the inline jsonl reference for documentation
    }

    fn wja(name: &str, ty: &str, args: serde_json::Value) -> crate::world::WorldJsonlAsset {
        crate::world::WorldJsonlAsset {
            name: name.to_string(),
            asset_type: ty.to_string(),
            args,
        }
    }

    fn ctx() -> crate::asset::BuildCtx<'static> {
        crate::asset::BuildCtx {
            name: "test",
            assets_dir: None,
            artifacts_dir: None,
            all_assets: &[],
        }
    }

    // A cache map that claims a compiled payload is already in hand for the
    // named asset, so every desugar pass must skip its source parse.
    fn hit_cache(name: &str) -> std::collections::HashMap<String, MeshCacheEntry> {
        let mut m = std::collections::HashMap::new();
        m.insert(
            name.to_string(),
            MeshCacheEntry {
                key: "k".to_string(),
                bytes: Some(vec![1, 2, 3]),
            },
        );
        m
    }

    #[test]
    fn build_from_path_missing_world_file_errors() {
        assert!(build_from_path("/no/such/world.jsonl").is_err());
    }

    #[test]
    fn build_from_path_reports_a_malformed_world_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let world = dir.path().join("world.jsonl");
        std::fs::write(&world, "{not json\n").expect("write world");
        let err = build_from_path(world.to_str().unwrap()).expect_err("malformed world");
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
    }

    // A lock that cannot be written fails the build: shipping blobs without the
    // record of what went into them would leave the output unexplainable.
    #[test]
    fn write_build_outputs_fails_when_the_lock_cannot_be_written() {
        let _output = crate::blob::test_output::LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _state = crate::blob::test_output::StateDir::new();
        let _lock_file = crate::blob::test_output::LockFile;
        // A directory where the lock file belongs makes the write fail.
        std::fs::create_dir_all(crate::blob::LOCK_PATH).expect("occupy the lock path");

        let result = PipelineResult {
            defs: Vec::new(),
            names: Vec::new(),
            resources: Vec::new(),
            scene_groups: Vec::new(),
            mesh_bounds: Vec::new(),
            physics_budget: None,
            mesh_component_names: Vec::new(),
            payloads: vec![vec![1, 2, 3]],
            cache_hits: 0,
            cache_misses: 0,
            texture_sources: Vec::new(),
            mesh_sources: Vec::new(),
            resource_locks: Vec::new(),
        };
        assert!(
            write_build_outputs(&result, &[], &[]).is_err(),
            "an unwritable lock must fail the build"
        );
    }

    // The full build tail: compile the world, ship the blobs under the state
    // root, and record every asset in the lock beside them.
    #[test]
    fn build_from_path_writes_the_blobs_and_the_lock_beside_them() {
        let _shaders = SHADER_BUILD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        crate::shader::install_stub_toolchain();
        let _output = crate::blob::test_output::LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _state = crate::blob::test_output::StateDir::new();
        let _lock_file = crate::blob::test_output::LockFile;

        let dir = tempfile::tempdir().expect("tempdir");
        let world_path = dir.path().join("world.jsonl");
        std::fs::write(
            &world_path,
            concat!(
                r#"{"name":"gfx","type":"GraphicsConfig","args":{}}"#,
                "\n",
                r#"{"name":"f","type":"Font","args":{"size_px":20}}"#,
                "\n",
                r#"{"name":"pause","type":"Screen","args":{}}"#,
                "\n",
            ),
        )
        .expect("write world");

        build_from_path(world_path.to_str().unwrap()).expect("build");

        let raw = std::fs::read_to_string(crate::blob::LOCK_PATH).expect("lock written");
        let lock: crate::blob::BlobLock = serde_json::from_str(&raw).expect("lock is valid json");
        assert_eq!(lock.blobs.len(), 1);

        let (meta, _) = crate::blob::read_cnb(&lock.blobs[0].path).expect("blob 0 parses");
        assert_eq!(
            meta.defs.len(),
            lock.assets.len(),
            "the lock names every def the blob ships"
        );
        assert_eq!(meta.resources.len(), lock.resources.len());
        assert!(lock.assets.iter().any(|a| a.name == "pause"));

        let font = lock
            .resources
            .iter()
            .find(|r| r.name == "f")
            .expect("the font is recorded in the resource stream");
        assert_eq!(font.kind, "Font");
        assert_eq!(font.payload_blob, Some(0));
        assert!(
            !lock.injected.is_empty(),
            "engine defaults are recorded so they can be overridden"
        );
    }

    #[test]
    fn build_pipeline_from_str_rejects_malformed_jsonl() {
        let Err(err) = build_pipeline_from_str("{not json\n", None, None) else {
            panic!("malformed line must not build");
        };
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
    }

    #[test]
    fn build_pipeline_from_str_reports_unknown_asset_types() {
        let world = r#"{"name":"mystery","type":"NotAType","args":{}}"#;
        let Err(err) = build_pipeline_from_str(world, None, None) else {
            panic!("unknown type must not build");
        };
        assert!(
            err.to_string().contains("NotAType"),
            "error should name the unknown type: {err}"
        );
    }

    #[test]
    fn validate_asset_accepts_build_time_expansion_types() {
        // Build-time types are expanded before the runtime registry sees
        // them, so they validate structurally regardless of args.
        for ty in [
            "SceneImport",
            "Environment",
            "LightRig",
            "Prefab",
            "CharacterSchema",
            "CharacterModel",
        ] {
            validate_asset(ty, "x", &serde_json::json!({}))
                .unwrap_or_else(|e| panic!("{ty} should validate: {e}"));
        }
    }

    // A resource-only type never builds a component def, so it is validated
    // through the structural check alone rather than `create_asset_def`.
    #[test]
    fn validate_asset_routes_resource_only_types_past_the_component_registry() {
        validate_asset("AudioClip", "clip", &serde_json::json!({"source": "a.wav"}))
            .expect("a source-backed AudioClip validates");
        let err = validate_asset("Texture", "tex", &serde_json::json!({"generator": "nope"}))
            .expect_err("an unknown texture generator is rejected");
        assert!(err.contains("nope"), "got: {err}");
    }

    // A type that resolves through `create_asset_def` still has to satisfy its
    // structural check, and a clean asset returns Ok.
    #[test]
    fn validate_asset_runs_the_structural_check_after_type_resolution() {
        validate_asset("Scene", "day", &serde_json::json!({})).expect("a Scene validates");
        // A Prop resolves as a type but has no mesh source to render.
        let err = validate_asset("Prop", "empty_prop", &serde_json::json!({}))
            .expect_err("a source-less Prop is rejected");
        assert!(err.contains("empty_prop"), "got: {err}");
    }

    #[test]
    fn validate_asset_unknown_type_mentions_the_asset_name() {
        let err =
            validate_asset("Bogus", "my_thing", &serde_json::json!({})).expect_err("unknown type");
        assert!(err.contains("my_thing"), "got: {err}");
    }

    #[test]
    fn validate_asset_bad_args_mention_the_asset_name() {
        // `generator` must be a string; a number fails args deserialization.
        let err = validate_asset(
            "ProceduralMesh",
            "bad_mesh",
            &serde_json::json!({"generator": 5}),
        )
        .expect_err("bad args");
        assert!(err.contains("bad_mesh"), "got: {err}");
    }

    #[test]
    fn desugar_gltf_skinned_meshes_leaves_inline_and_cached_untouched() {
        let inline_args = serde_json::json!({"vertices": [], "indices": []});
        let cached_args = serde_json::json!({"source": "/no/such/hero.glb"});
        let mut assets = vec![
            wja("inline", SKINNED_MESH_TYPE, inline_args.clone()),
            wja("cached", SKINNED_MESH_TYPE, cached_args.clone()),
        ];
        desugar_gltf_skinned_meshes(&mut assets, &hit_cache("cached"), None).expect("desugar");
        // No source: untouched. Cache hit: the missing .glb is never parsed
        // and the args stay pre-desugar so the next probe key matches.
        assert_eq!(assets[0].args, inline_args);
        assert_eq!(assets[1].args, cached_args);
    }

    // Write a fixture container into `dir` and return its path as a string.
    fn write_fixture(dir: &tempfile::TempDir, name: &str, bytes: &[u8]) -> String {
        let path = dir.path().join(name);
        std::fs::write(&path, bytes).expect("write fixture");
        path.to_string_lossy().into_owned()
    }

    // A source-backed SkinnedMesh has its geometry and skeleton written into
    // the asset's inline args, replacing the `source` reference for the
    // compile step that follows.
    #[test]
    fn desugar_gltf_skinned_meshes_inlines_geometry_and_skeleton() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.glb", &crate::glb::test_fixtures::skinned_glb());
        let mut assets = vec![wja(
            "hero",
            SKINNED_MESH_TYPE,
            serde_json::json!({"source": src}),
        )];
        desugar_gltf_skinned_meshes(&mut assets, &Default::default(), None).expect("desugar");

        let args = &assets[0].args;
        assert_eq!(args["vertices"].as_array().unwrap().len(), 3);
        assert_eq!(args["indices"].as_array().unwrap(), &vec![0, 1, 2]);
        // The two-joint skin is reordered parents-before-children, so the
        // skeleton lands with the root first.
        assert_eq!(args["skeleton"].as_array().unwrap().len(), 2);
        // The fixture carries no morph targets, so no morph args appear.
        assert!(args.get("morph_target_names").is_none());
        assert!(args.get("morph_deltas").is_none());
    }

    // The shared skinned fixture with one morph target ("bulge", +Y on every
    // vertex) and an animation channel driving its weight from 0 to 1.
    fn morphing_skinned_glb() -> Vec<u8> {
        use crate::glb::test_fixtures::{f32s, make_glb, skinned_bin, skinned_json};

        let mut bin = skinned_bin(); // 136 bytes
        bin.extend(f32s(&[0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0])); // deltas -> 172
        bin.extend(f32s(&[0.0, 1.0])); // morph weights -> 180

        let mut json = skinned_json(true, true, true);
        json["buffers"][0]["byteLength"] = 180.into();
        let views = json["bufferViews"].as_array_mut().expect("bufferViews");
        views.push(serde_json::json!({"buffer": 0, "byteOffset": 136, "byteLength": 36}));
        views.push(serde_json::json!({"buffer": 0, "byteOffset": 172, "byteLength": 8}));
        let accessors = json["accessors"].as_array_mut().expect("accessors");
        accessors.push(
            serde_json::json!({"bufferView": 6, "componentType": 5126, "count": 3, "type": "VEC3"}),
        );
        accessors.push(serde_json::json!(
            {"bufferView": 7, "componentType": 5126, "count": 2, "type": "SCALAR"}
        ));
        json["meshes"][0]["primitives"][0]["targets"] = serde_json::json!([{"POSITION": 6}]);
        json["meshes"][0]["extras"] = serde_json::json!({"targetNames": ["bulge"]});
        json["animations"][0]["samplers"]
            .as_array_mut()
            .expect("samplers")
            .push(serde_json::json!({"input": 4, "output": 7, "interpolation": "LINEAR"}));
        json["animations"][0]["channels"]
            .as_array_mut()
            .expect("channels")
            .push(serde_json::json!({"sampler": 2, "target": {"node": 0, "path": "weights"}}));

        make_glb(&json, Some(&bin))
    }

    // A source carrying morph targets writes the target names and the dense
    // delta block into the asset alongside the base geometry.
    #[test]
    fn desugar_gltf_skinned_meshes_inlines_morph_targets() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.glb", &morphing_skinned_glb());
        let mut assets = vec![wja(
            "hero",
            SKINNED_MESH_TYPE,
            serde_json::json!({"source": src}),
        )];
        desugar_gltf_skinned_meshes(&mut assets, &Default::default(), None).expect("desugar");

        let args = &assets[0].args;
        assert_eq!(args["morph_target_names"], serde_json::json!(["bulge"]));
        // One target over three vertices: a dense target-major delta block.
        assert_eq!(args["morph_deltas"].as_array().unwrap().len(), 3);
    }

    // A clip that animates morph weights carries a morph track beside its
    // joint tracks.
    #[test]
    fn desugar_animation_imports_inlines_a_morph_weight_track() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.glb", &morphing_skinned_glb());
        let mut assets = vec![wja(
            "wave",
            "Animation",
            serde_json::json!({"source": src, "animation_index": 0}),
        )];
        desugar_animation_imports(&mut assets, None).expect("desugar");

        let morph = assets[0].args["morph_track"]
            .as_array()
            .expect("morph track inlined");
        assert_eq!(morph.len(), 2);
        assert_eq!(morph[0], serde_json::json!({"time": 0.0, "weights": [0.0]}));
        assert_eq!(morph[1], serde_json::json!({"time": 1.0, "weights": [1.0]}));
    }

    #[test]
    fn desugar_gltf_skinned_meshes_missing_source_errors() {
        let mut assets = vec![wja(
            "hero",
            SKINNED_MESH_TYPE,
            serde_json::json!({"source": "/no/such/hero.glb"}),
        )];
        let err = desugar_gltf_skinned_meshes(&mut assets, &Default::default(), None)
            .expect_err("missing .glb");
        assert!(err.to_string().contains("Asset 'hero'"), "got: {err}");
    }

    #[test]
    fn desugar_gltf_meshes_skips_non_glb_sources_and_cache_hits() {
        let fbx_args = serde_json::json!({"source": "/no/such/scene.fbx"});
        let cached_args = serde_json::json!({"source": "/no/such/scene.glb"});
        let inline_args = serde_json::json!({"vertices": [], "indices": []});
        let mut assets = vec![
            wja("from_fbx", MESH_TYPE, fbx_args.clone()),
            wja("cached", MESH_TYPE, cached_args.clone()),
            wja("inline", MESH_TYPE, inline_args.clone()),
        ];
        desugar_gltf_meshes(&mut assets, &hit_cache("cached"), None).expect("desugar");
        assert_eq!(
            assets[0].args, fbx_args,
            ".fbx sources belong to the fbx pass"
        );
        assert_eq!(assets[1].args, cached_args, "cache hit skips the parse");
        assert_eq!(assets[2].args, inline_args, "no source: untouched");
    }

    #[test]
    fn desugar_gltf_meshes_missing_source_errors() {
        let mut assets = vec![wja(
            "crate_mesh",
            MESH_TYPE,
            serde_json::json!({"source": "/no/such/scene.glb"}),
        )];
        let err =
            desugar_gltf_meshes(&mut assets, &Default::default(), None).expect_err("missing .glb");
        assert!(err.to_string().contains("Asset 'crate_mesh'"), "got: {err}");
    }

    // The text `.gltf` container flows through the same desugar as `.glb`:
    // geometry lands inline from the external `.bin` beside the source.
    #[test]
    fn desugar_gltf_meshes_imports_a_text_gltf_with_an_external_buffer() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("geo.bin"),
            crate::glb::test_fixtures::static_triangle_bin(),
        )
        .unwrap();
        let mut json = crate::glb::test_fixtures::static_triangle_json();
        json["buffers"][0]["uri"] = "geo.bin".into();
        let gltf = dir.path().join("tri.gltf");
        std::fs::write(&gltf, serde_json::to_vec(&json).unwrap()).unwrap();

        let mut assets = vec![wja(
            "tri",
            MESH_TYPE,
            serde_json::json!({"source": gltf.to_str().unwrap(), "primitive_index": 0}),
        )];
        desugar_gltf_meshes(&mut assets, &Default::default(), None).expect("desugar");
        let vertices = assets[0].args.get("vertices").expect("inline vertices");
        assert_eq!(vertices.as_array().unwrap().len(), 3);
        assert_eq!(
            assets[0]
                .args
                .get("indices")
                .unwrap()
                .as_array()
                .unwrap()
                .len(),
            3
        );
    }

    // Two Mesh assets fanned out of one container parse the file once; both
    // still land with their own inline geometry.
    #[test]
    fn desugar_gltf_meshes_parses_a_shared_source_once_for_every_asset() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(
            &dir,
            "scene.glb",
            &crate::glb::test_fixtures::static_triangle_glb(),
        );
        let mut assets = vec![
            wja(
                "part_a",
                MESH_TYPE,
                serde_json::json!({"source": src, "primitive_index": 0}),
            ),
            wja(
                "part_b",
                MESH_TYPE,
                serde_json::json!({"source": src, "primitive_index": 0}),
            ),
        ];
        desugar_gltf_meshes(&mut assets, &Default::default(), None).expect("desugar");
        for asset in &assets {
            assert_eq!(asset.args["vertices"].as_array().unwrap().len(), 3);
            assert_eq!(asset.args["indices"].as_array().unwrap().len(), 3);
        }
    }

    // A primitive the container does not have fails on both the chunked and
    // the whole-primitive route, naming the asset either way.
    #[test]
    fn desugar_gltf_meshes_reports_a_primitive_the_file_does_not_have() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(
            &dir,
            "scene.glb",
            &crate::glb::test_fixtures::static_triangle_glb(),
        );
        for extra in [serde_json::json!({}), serde_json::json!({"chunk_index": 0})] {
            let mut args = serde_json::json!({"source": src, "primitive_index": 7});
            for (k, v) in extra.as_object().unwrap() {
                args[k] = v.clone();
            }
            let mut assets = vec![wja("ghost", MESH_TYPE, args)];
            let err = desugar_gltf_meshes(&mut assets, &Default::default(), None)
                .expect_err("primitive 7 does not exist");
            let msg = err.to_string();
            assert!(msg.contains("Asset 'ghost'"), "got: {msg}");
            assert!(msg.contains("glTF import failed"), "got: {msg}");
        }
    }

    // An oversized primitive fanned into several chunked Mesh assets is split
    // exactly once; every asset still gets its own inline geometry.
    #[test]
    fn desugar_gltf_meshes_splits_a_primitive_once_for_every_chunk_asset() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(
            &dir,
            "scene.glb",
            &crate::glb::test_fixtures::static_triangle_glb(),
        );
        let chunk = |name: &str| {
            wja(
                name,
                MESH_TYPE,
                serde_json::json!({"source": src, "primitive_index": 0, "chunk_index": 0}),
            )
        };
        let mut assets = vec![chunk("part_a"), chunk("part_b")];
        desugar_gltf_meshes(&mut assets, &Default::default(), None).expect("desugar");
        for asset in &assets {
            assert_eq!(asset.args["vertices"].as_array().unwrap().len(), 3);
        }
    }

    // An authored `chunk_index` routes through the u16 chunk split instead of
    // the whole-primitive import; an index past the last chunk names the file,
    // the primitive, and how many chunks it really produced.
    #[test]
    fn desugar_gltf_meshes_reads_a_chunk_and_rejects_one_out_of_range() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(
            &dir,
            "scene.glb",
            &crate::glb::test_fixtures::static_triangle_glb(),
        );
        let mut assets = vec![wja(
            "chunk0",
            MESH_TYPE,
            serde_json::json!({"source": src, "chunk_index": 0}),
        )];
        desugar_gltf_meshes(&mut assets, &Default::default(), None).expect("desugar");
        assert_eq!(assets[0].args["vertices"].as_array().unwrap().len(), 3);

        let mut past_end = vec![wja(
            "chunk9",
            MESH_TYPE,
            serde_json::json!({"source": src, "chunk_index": 9}),
        )];
        let err = desugar_gltf_meshes(&mut past_end, &Default::default(), None)
            .expect_err("chunk 9 does not exist");
        let msg = err.to_string();
        assert!(msg.contains("Asset 'chunk9'"), "got: {msg}");
        assert!(msg.contains("chunk_index 9 out of range"), "got: {msg}");
        assert!(msg.contains("1 chunk(s)"), "got: {msg}");
    }

    // Synthetic binary FBX containers. The importer walks a node tree, so the
    // fixtures are described as one and serialized by `write_fbx`; no binary
    // asset needs to live in the repo.
    enum Attr {
        Int(i64),
        Double(f64),
        Text(String),
        Doubles(Vec<f64>),
        Ints(Vec<i32>),
        Longs(Vec<i64>),
        Floats(Vec<f32>),
    }

    struct Node {
        name: &'static str,
        attrs: Vec<Attr>,
        children: Vec<Node>,
    }

    fn node(name: &'static str, attrs: Vec<Attr>, children: Vec<Node>) -> Node {
        Node {
            name,
            attrs,
            children,
        }
    }

    // An FBX object's second attribute: the authored name, the object class,
    // and the `\0\u{1}` separator between them.
    fn object_name(name: &str, class: &str) -> Attr {
        Attr::Text(format!("{name}\u{0}\u{1}{class}"))
    }

    fn connection(child: i64, parent: i64) -> Node {
        node(
            "C",
            vec![
                Attr::Text("OO".to_string()),
                Attr::Int(child),
                Attr::Int(parent),
            ],
            Vec::new(),
        )
    }

    // An object-to-property connection: the parent's named property is what
    // the child drives.
    fn property_connection(child: i64, parent: i64, property: &str) -> Node {
        node(
            "C",
            vec![
                Attr::Text("OP".to_string()),
                Attr::Int(child),
                Attr::Int(parent),
                Attr::Text(property.to_string()),
            ],
            Vec::new(),
        )
    }

    fn write_fbx(nodes: &[Node]) -> Vec<u8> {
        use fbxcel::low::FbxVersion;
        use fbxcel::writer::v7400::binary::{FbxFooter, Writer};

        fn emit<W: std::io::Write + std::io::Seek>(
            w: &mut Writer<W>,
            n: &Node,
        ) -> std::io::Result<()> {
            {
                let mut attrs = w.new_node(n.name).expect("open node");
                for a in &n.attrs {
                    match a {
                        Attr::Int(v) => attrs.append_i64(*v),
                        Attr::Double(v) => attrs.append_f64(*v),
                        Attr::Text(s) => attrs.append_string_direct(s),
                        Attr::Doubles(v) => attrs.append_arr_f64_from_iter(None, v.iter().copied()),
                        Attr::Ints(v) => attrs.append_arr_i32_from_iter(None, v.iter().copied()),
                        Attr::Longs(v) => attrs.append_arr_i64_from_iter(None, v.iter().copied()),
                        Attr::Floats(v) => attrs.append_arr_f32_from_iter(None, v.iter().copied()),
                    }
                    .expect("append attribute");
                }
            }
            for c in &n.children {
                emit(w, c)?;
            }
            w.close_node().expect("close node");
            Ok(())
        }

        let mut w =
            Writer::new(std::io::Cursor::new(Vec::new()), FbxVersion::V7_4).expect("fbx writer");
        for n in nodes {
            emit(&mut w, n).expect("emit node");
        }
        w.finalize_and_flush(&FbxFooter::default())
            .expect("finalize")
            .into_inner()
    }

    // One triangle as an FBX Geometry object. The last corner of a polygon is
    // stored bitwise-negated, which is how the importer finds polygon bounds.
    fn triangle_geometry(id: i64) -> Node {
        node(
            "Geometry",
            vec![
                Attr::Int(id),
                object_name("tri", "Geometry"),
                Attr::Text("Mesh".to_string()),
            ],
            vec![
                node(
                    "Vertices",
                    vec![Attr::Doubles(vec![
                        0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0,
                    ])],
                    Vec::new(),
                ),
                node(
                    "PolygonVertexIndex",
                    vec![Attr::Ints(vec![0, 1, !2])],
                    Vec::new(),
                ),
            ],
        )
    }

    // One Model connected to one Geometry: `parse_fbx` yields a single
    // primitive from it.
    fn static_triangle_fbx() -> Vec<u8> {
        const GEOMETRY: i64 = 1000;
        const MODEL: i64 = 2000;
        write_fbx(&[
            node(
                "Objects",
                Vec::new(),
                vec![
                    triangle_geometry(GEOMETRY),
                    node(
                        "Model",
                        vec![
                            Attr::Int(MODEL),
                            object_name("tri", "Model"),
                            Attr::Text("Mesh".to_string()),
                        ],
                        Vec::new(),
                    ),
                ],
            ),
            node("Connections", Vec::new(), vec![connection(GEOMETRY, MODEL)]),
        ])
    }

    // FBX time unit: ticks per second.
    const KTIME_PER_SEC: i64 = 46_186_158_000;

    fn skinned_triangle_fbx() -> Vec<u8> {
        skinned_fbx(false)
    }

    // The same triangle bound to a one-bone skin: a Skin deformer over the
    // geometry, a Cluster linking every control point to the bone Model at an
    // identity bind, and a unit scale of 100 so file units are already meters.
    // With `animated`, a one-second stack slides the bone 0 -> 2 along X.
    fn skinned_fbx(animated: bool) -> Vec<u8> {
        const GEOMETRY: i64 = 3000;
        const MESH_MODEL: i64 = 4000;
        const BONE: i64 = 5000;
        const SKIN: i64 = 6000;
        const CLUSTER: i64 = 7000;
        const STACK: i64 = 8000;
        const LAYER: i64 = 8100;
        const CURVE_NODE: i64 = 8200;
        const CURVE: i64 = 8300;
        let identity = vec![
            1.0, 0.0, 0.0, 0.0, //
            0.0, 1.0, 0.0, 0.0, //
            0.0, 0.0, 1.0, 0.0, //
            0.0, 0.0, 0.0, 1.0,
        ];
        let unit_scale = node(
            "GlobalSettings",
            Vec::new(),
            vec![node(
                "Properties70",
                Vec::new(),
                vec![node(
                    "P",
                    vec![
                        Attr::Text("UnitScaleFactor".to_string()),
                        Attr::Text("double".to_string()),
                        Attr::Text("Number".to_string()),
                        Attr::Text(String::new()),
                        Attr::Double(100.0),
                    ],
                    Vec::new(),
                )],
            )],
        );
        let mut objects = vec![
            triangle_geometry(GEOMETRY),
            node(
                "Model",
                vec![
                    Attr::Int(MESH_MODEL),
                    object_name("mesh", "Model"),
                    Attr::Text("Mesh".to_string()),
                ],
                Vec::new(),
            ),
            node(
                "Model",
                vec![
                    Attr::Int(BONE),
                    object_name("Root", "Model"),
                    Attr::Text("LimbNode".to_string()),
                ],
                Vec::new(),
            ),
            node(
                "Deformer",
                vec![
                    Attr::Int(SKIN),
                    object_name("skin", "Deformer"),
                    Attr::Text("Skin".to_string()),
                ],
                Vec::new(),
            ),
            node(
                "Deformer",
                vec![
                    Attr::Int(CLUSTER),
                    object_name("cluster", "SubDeformer"),
                    Attr::Text("Cluster".to_string()),
                ],
                vec![
                    node("Indexes", vec![Attr::Ints(vec![0, 1, 2])], Vec::new()),
                    node(
                        "Weights",
                        vec![Attr::Doubles(vec![1.0, 1.0, 1.0])],
                        Vec::new(),
                    ),
                    node(
                        "TransformLink",
                        vec![Attr::Doubles(identity.clone())],
                        Vec::new(),
                    ),
                    node("Transform", vec![Attr::Doubles(identity)], Vec::new()),
                ],
            ),
        ];
        let mut connections = vec![
            connection(GEOMETRY, MESH_MODEL),
            connection(SKIN, GEOMETRY),
            connection(CLUSTER, SKIN),
            connection(BONE, CLUSTER),
        ];

        if animated {
            objects.extend([
                node(
                    "AnimationStack",
                    vec![Attr::Int(STACK), object_name("wave", "AnimStack")],
                    Vec::new(),
                ),
                node(
                    "AnimationLayer",
                    vec![Attr::Int(LAYER), object_name("Base Layer", "AnimLayer")],
                    Vec::new(),
                ),
                node(
                    "AnimationCurveNode",
                    vec![Attr::Int(CURVE_NODE), object_name("T", "AnimCurveNode")],
                    Vec::new(),
                ),
                node(
                    "AnimationCurve",
                    vec![Attr::Int(CURVE), object_name("", "AnimCurve")],
                    vec![
                        node(
                            "KeyTime",
                            vec![Attr::Longs(vec![0, KTIME_PER_SEC])],
                            Vec::new(),
                        ),
                        node(
                            "KeyValueFloat",
                            vec![Attr::Floats(vec![0.0, 2.0])],
                            Vec::new(),
                        ),
                    ],
                ),
            ]);
            connections.extend([
                connection(LAYER, STACK),
                connection(CURVE_NODE, LAYER),
                property_connection(CURVE, CURVE_NODE, "d|X"),
                property_connection(CURVE_NODE, BONE, "Lcl Translation"),
            ]);
        }

        write_fbx(&[
            unit_scale,
            node("Objects", Vec::new(), objects),
            node("Connections", Vec::new(), connections),
        ])
    }

    #[test]
    fn fbx_fixture_parses_into_one_primitive() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "tri.fbx", &static_triangle_fbx());
        let scene = crate::fbx::parse_fbx(&src).expect("fixture parses");
        let (vertices, indices) =
            crate::fbx::read_primitive_geometry(&scene, 0).expect("primitive 0");
        assert_eq!(vertices.len(), 3);
        assert_eq!(indices, vec![0, 1, 2]);
    }

    // A `.fbx`-sourced Mesh lands with inline geometry, and several assets fanned
    // out of one file share a single parse and a single chunk split.
    #[test]
    fn desugar_fbx_meshes_inlines_geometry_for_every_asset_sharing_a_source() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "scene.fbx", &static_triangle_fbx());
        let mut assets = vec![
            wja(
                "part_a",
                MESH_TYPE,
                serde_json::json!({"source": src, "primitive_index": 0}),
            ),
            wja(
                "part_b",
                MESH_TYPE,
                serde_json::json!({"source": src, "primitive_index": 0, "chunk_index": 0}),
            ),
        ];
        desugar_fbx_meshes(&mut assets, &Default::default()).expect("desugar");
        for asset in &assets {
            assert_eq!(asset.args["vertices"].as_array().unwrap().len(), 3);
            assert_eq!(asset.args["indices"].as_array().unwrap(), &vec![0, 1, 2]);
        }
    }

    // The two failure modes past the parse: a primitive the file does not have,
    // and a chunk index past the split.
    #[test]
    fn desugar_fbx_meshes_rejects_an_unknown_primitive_and_chunk() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "scene.fbx", &static_triangle_fbx());

        let mut ghost = vec![wja(
            "ghost",
            MESH_TYPE,
            serde_json::json!({"source": src, "primitive_index": 7}),
        )];
        let err =
            desugar_fbx_meshes(&mut ghost, &Default::default()).expect_err("primitive 7 is absent");
        let msg = err.to_string();
        assert!(msg.contains("Asset 'ghost'"), "got: {msg}");
        assert!(msg.contains("FBX import failed"), "got: {msg}");

        let mut past_end = vec![wja(
            "chunk9",
            MESH_TYPE,
            serde_json::json!({"source": src, "chunk_index": 9}),
        )];
        let err = desugar_fbx_meshes(&mut past_end, &Default::default())
            .expect_err("chunk 9 is past the split");
        let msg = err.to_string();
        assert!(msg.contains("chunk_index 9 out of range"), "got: {msg}");
        assert!(msg.contains("1 chunk(s)"), "got: {msg}");
    }

    // A `.fbx`-sourced SkinnedMesh lands with inline geometry and a skeleton,
    // mirroring the glTF pass; the `source` reference is what the compile step
    // no longer needs.
    #[test]
    fn desugar_fbx_skinned_meshes_inlines_geometry_and_skeleton() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.fbx", &skinned_triangle_fbx());
        let mut assets = vec![wja(
            "hero",
            SKINNED_MESH_TYPE,
            serde_json::json!({"source": src}),
        )];
        desugar_fbx_skinned_meshes(&mut assets, &Default::default()).expect("desugar");

        let args = &assets[0].args;
        assert_eq!(args["vertices"].as_array().unwrap().len(), 3);
        assert_eq!(args["indices"].as_array().unwrap(), &vec![0, 1, 2]);
        let skeleton = args["skeleton"].as_array().expect("skeleton inlined");
        assert_eq!(skeleton.len(), 1);
        assert_eq!(skeleton[0]["name"], "Root");
        assert_eq!(skeleton[0]["parent"], -1);
        // Every control point binds fully to the single cluster bone.
        assert_eq!(
            args["vertices"][0]["weights"],
            serde_json::json!([1.0, 0.0, 0.0, 0.0])
        );
    }

    #[test]
    fn desugar_skinned_meshes_import_the_selected_skin() {
        use crate::glb::test_fixtures::two_skin_glb;

        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.glb", &two_skin_glb());
        let mut assets = vec![
            wja(
                "body",
                SKINNED_MESH_TYPE,
                serde_json::json!({"source": src, "skin_index": 0}),
            ),
            wja(
                "hair",
                SKINNED_MESH_TYPE,
                serde_json::json!({"source": src, "skin_index": 1}),
            ),
        ];
        desugar_gltf_skinned_meshes(&mut assets, &Default::default(), None).expect("desugar");

        // Each asset inlines its own part's geometry.
        assert_eq!(
            assets[0].args["vertices"][0]["pos"],
            serde_json::json!([0.0, 0.0, 0.0])
        );
        assert_eq!(
            assets[1].args["vertices"][0]["pos"],
            serde_json::json!([5.0, 0.0, 0.0])
        );
    }

    #[test]
    fn desugar_animation_imports_inherit_the_targets_skin() {
        use crate::glb::test_fixtures::two_skin_glb;

        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.glb", &two_skin_glb());
        let mut assets = vec![
            wja(
                "hair",
                SKINNED_MESH_TYPE,
                serde_json::json!({"source": src, "skin_index": 1}),
            ),
            wja(
                "hair_wave",
                "Animation",
                serde_json::json!({"target": "hair", "source": src}),
            ),
        ];
        // The clip carries no selector of its own; resolving it against the
        // target's skin is what keeps the joint indices in the same space.
        assert_eq!(skin_index_by_target(&assets).get("hair"), Some(&1));
        desugar_animation_imports(&mut assets, None).expect("desugar");
        assert!(
            !assets[1].args["tracks"]
                .as_array()
                .expect("tracks")
                .is_empty()
        );
    }

    #[test]
    fn an_animation_without_a_resolvable_target_falls_back_to_the_first_skin() {
        let assets = vec![
            wja(
                "body",
                SKINNED_MESH_TYPE,
                serde_json::json!({"skin_index": 2}),
            ),
            wja("orphan", "Animation", serde_json::json!({"target": "gone"})),
        ];
        let by_target = skin_index_by_target(&assets);
        assert_eq!(by_target.get("body"), Some(&2));
        assert!(!by_target.contains_key("gone"));
    }

    // `.glb` sources belong to the glTF pass, and a probe hit means the
    // compiled payload is already in hand; neither is parsed here.
    #[test]
    fn desugar_fbx_skinned_meshes_skips_glb_sources_and_cache_hits() {
        let glb_args = serde_json::json!({"source": "/no/such/hero.glb"});
        let cached_args = serde_json::json!({"source": "/no/such/hero.fbx"});
        let mut assets = vec![
            wja("from_glb", SKINNED_MESH_TYPE, glb_args.clone()),
            wja("cached", SKINNED_MESH_TYPE, cached_args.clone()),
        ];
        desugar_fbx_skinned_meshes(&mut assets, &hit_cache("cached")).expect("desugar");
        assert_eq!(assets[0].args, glb_args);
        assert_eq!(assets[1].args, cached_args);
    }

    // A file with no skin deformer is a hard error, named against the asset.
    #[test]
    fn desugar_fbx_skinned_meshes_reports_a_file_without_a_skin() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "static.fbx", &static_triangle_fbx());
        let mut assets = vec![wja(
            "hero",
            SKINNED_MESH_TYPE,
            serde_json::json!({"source": src}),
        )];
        let err = desugar_fbx_skinned_meshes(&mut assets, &Default::default())
            .expect_err("a static file has no skin");
        let msg = err.to_string();
        assert!(msg.contains("Asset 'hero'"), "got: {msg}");
        assert!(msg.contains("FBX import failed"), "got: {msg}");
    }

    #[test]
    fn desugar_fbx_meshes_missing_source_errors() {
        let mut assets = vec![wja(
            "bistro",
            MESH_TYPE,
            serde_json::json!({"source": "/no/such/scene.fbx"}),
        )];
        let err = desugar_fbx_meshes(&mut assets, &Default::default()).expect_err("missing .fbx");
        assert!(err.to_string().contains("Asset 'bistro'"), "got: {err}");
    }

    #[test]
    fn desugar_fbx_meshes_skips_cache_hits_and_non_fbx_sources() {
        let cached_args = serde_json::json!({"source": "/no/such/scene.fbx"});
        let glb_args = serde_json::json!({"source": "/no/such/scene.glb"});
        let mut assets = vec![
            wja("cached", MESH_TYPE, cached_args.clone()),
            wja("from_glb", MESH_TYPE, glb_args.clone()),
        ];
        desugar_fbx_meshes(&mut assets, &hit_cache("cached")).expect("desugar");
        assert_eq!(assets[0].args, cached_args);
        assert_eq!(assets[1].args, glb_args);
    }

    // An `.fbx` source routes to the FBX importer, which bakes the clip at the
    // asset's `sample_rate` rather than replaying authored keys.
    #[test]
    fn desugar_animation_imports_bakes_an_fbx_clip_at_the_sample_rate() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.fbx", &skinned_fbx(true));
        let mut assets = vec![wja(
            "wave",
            "Animation",
            serde_json::json!({"source": src, "sample_rate": 10.0}),
        )];
        desugar_animation_imports(&mut assets, None).expect("desugar");

        let args = &assets[0].args;
        assert!(
            (args["duration"].as_f64().expect("duration") - 1.0).abs() < 1e-3,
            "got: {}",
            args["duration"]
        );
        let tracks = args["tracks"].as_array().expect("tracks inlined");
        assert_eq!(tracks.len(), 1);
        let keys = tracks[0]["keyframes"].as_array().expect("keyframes");
        // One second at 10 samples per second, inclusive of both ends.
        assert_eq!(keys.len(), 11);
        assert_eq!(keys[0]["translation"][0], 0.0);
        assert_eq!(keys[10]["translation"][0], 2.0);
    }

    // A clip named by `animation_name` that the file does not contain fails
    // through the FBX importer too.
    #[test]
    fn desugar_animation_imports_reports_an_unknown_fbx_clip_name() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.fbx", &skinned_fbx(true));
        let mut assets = vec![wja(
            "run",
            "Animation",
            serde_json::json!({"source": src, "animation_name": "sprint"}),
        )];
        let err = desugar_animation_imports(&mut assets, None).expect_err("no 'sprint' clip");
        let msg = err.to_string();
        assert!(msg.contains("Asset 'run'"), "got: {msg}");
        assert!(msg.contains("FBX import failed"), "got: {msg}");
    }

    #[test]
    fn desugar_animation_imports_missing_source_errors() {
        let mut assets = vec![wja(
            "walk",
            "Animation",
            serde_json::json!({"source": "/no/such/anim.glb"}),
        )];
        let err = desugar_animation_imports(&mut assets, None).expect_err("missing .glb");
        assert!(err.to_string().contains("Asset 'walk'"), "got: {err}");
    }

    #[test]
    fn desugar_animation_imports_missing_named_clip_errors() {
        // The by-name lookup also starts by reading the file, so a missing
        // source fails before the name search; the error still names the asset.
        let mut assets = vec![wja(
            "run",
            "Animation",
            serde_json::json!({"source": "/no/such/anim.glb", "animation_name": "Run"}),
        )];
        let err = desugar_animation_imports(&mut assets, None).expect_err("missing .glb");
        assert!(err.to_string().contains("Asset 'run'"), "got: {err}");
    }

    // A source-backed Animation is replaced by the imported clip's duration
    // and tracks. Channels targeting non-joint nodes are dropped, so the
    // fixture's two channels yield one track.
    #[test]
    fn desugar_animation_imports_inlines_the_indexed_clip() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.glb", &crate::glb::test_fixtures::skinned_glb());
        let mut assets = vec![wja(
            "wave",
            "Animation",
            serde_json::json!({"source": src, "animation_index": 0}),
        )];
        desugar_animation_imports(&mut assets, None).expect("desugar");

        let args = &assets[0].args;
        assert_eq!(args["duration"], 1.0);
        let tracks = args["tracks"].as_array().expect("tracks inlined");
        assert_eq!(tracks.len(), 1, "the non-joint channel is dropped");
        let keys = tracks[0]["keyframes"].as_array().expect("keyframes");
        assert_eq!(keys.len(), 2);
        assert_eq!(keys[0]["time"], 0.0);
        assert_eq!(keys[1]["translation"], serde_json::json!([0.0, 2.0, 0.0]));
        // The fixture animates no morph weights, so no morph track appears.
        assert!(args.get("morph_track").is_none());
    }

    // `animation_name` picks the clip by name; a name the file does not carry
    // is a hard error that lists what it does contain.
    #[test]
    fn desugar_animation_imports_resolves_and_rejects_clip_names() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = write_fixture(&dir, "hero.glb", &crate::glb::test_fixtures::skinned_glb());
        let mut assets = vec![wja(
            "wave",
            "Animation",
            serde_json::json!({"source": src, "animation_name": "wave"}),
        )];
        desugar_animation_imports(&mut assets, None).expect("desugar");
        assert_eq!(assets[0].args["tracks"].as_array().unwrap().len(), 1);

        let mut missing = vec![wja(
            "run",
            "Animation",
            serde_json::json!({"source": src, "animation_name": "sprint"}),
        )];
        let err = desugar_animation_imports(&mut missing, None)
            .expect_err("the file has no 'sprint' clip");
        let msg = err.to_string();
        assert!(
            msg.contains("has no animation named 'sprint'"),
            "got: {msg}"
        );
        assert!(msg.contains("wave"), "the error lists the clips: {msg}");
    }

    #[test]
    fn desugar_root_motion_rejects_malformed_args() {
        let mut assets = vec![wja(
            "walk",
            "Animation",
            serde_json::json!({"root_motion": true, "duration": "long"}),
        )];
        let err = desugar_root_motion(&mut assets).expect_err("bad duration");
        assert!(
            err.to_string()
                .contains("root-motion bake failed to parse args"),
            "got: {err}"
        );
    }

    #[test]
    fn desugar_root_motion_tolerates_a_clip_with_no_root_track() {
        // Only joint 1 is animated: there is nothing to strip from the root,
        // so the bake warns and leaves an empty curve rather than failing.
        let mut assets = vec![wja(
            "wave",
            "Animation",
            serde_json::json!({
                "root_motion": true,
                "duration": 1.0,
                "tracks": [{"joint": 1, "keyframes": [
                    {"time": 0.0, "translation": [1.0, 0.0, 0.0]}
                ]}],
            }),
        )];
        desugar_root_motion(&mut assets).expect("bake succeeds");
        assert_eq!(assets[0].args["root_track"], serde_json::json!([]));
        // The non-root track is untouched.
        assert_eq!(
            assets[0].args["tracks"][0]["keyframes"][0]["translation"][0],
            1.0
        );
    }

    // Opting into vertical root motion keeps the Y travel in the root track
    // instead of anchoring it back into the pose.
    #[test]
    fn desugar_root_motion_keeps_y_travel_when_asked() {
        let clip = |root_motion_y: bool| {
            serde_json::json!({
                "target": "hero",
                "duration": 1.0,
                "root_motion": true,
                "root_motion_y": root_motion_y,
                "tracks": [{"joint": 0, "keyframes": [
                    {"time": 0.0, "translation": [0.0, 0.0, 0.0]},
                    {"time": 1.0, "translation": [0.0, 3.0, 0.0]}
                ]}],
            })
        };
        let mut assets = vec![
            wja("jump", "Animation", clip(true)),
            wja("walk", "Animation", clip(false)),
        ];
        desugar_root_motion(&mut assets).expect("bake succeeds");

        assert_eq!(assets[0].args["root_track"][1]["translation"][1], 3.0);
        assert_eq!(
            assets[0].args["tracks"][0]["keyframes"][1]["translation"][1],
            0.0
        );
        // Without the flag the rise stays in the pose and the root track is flat.
        assert_eq!(assets[1].args["root_track"][1]["translation"][1], 0.0);
        assert_eq!(
            assets[1].args["tracks"][0]["keyframes"][1]["translation"][1],
            3.0
        );
    }

    // An authored `screen` arg wins over the name-prefix convention, exactly
    // as an authored `scene` does on a Prop.
    #[test]
    fn resolve_scene_refs_keeps_an_authored_screen_arg() {
        let mut assets = vec![
            wja("menu", "Screen", serde_json::json!({})),
            wja("other", "Screen", serde_json::json!({})),
            wja(
                "menu_title",
                "TextLabel",
                serde_json::json!({"screen": "other"}),
            ),
        ];
        super::resolve_scene_refs(&mut assets);
        assert_eq!(assets[2].args["screen"], "other");
    }

    #[test]
    fn resolve_scene_refs_prop_scene_prefix_rules() {
        let mut assets = vec![
            wja("level", "Scene", serde_json::json!({})),
            wja("level_boss", "Scene", serde_json::json!({})),
            wja("level_boss_door", "Prop", serde_json::json!({})),
            wja("level_gate", "Prop", serde_json::json!({"scene": "other"})),
            wja("solo_thing", "Prop", serde_json::json!({})),
        ];
        super::resolve_scene_refs(&mut assets);

        // Longest scene prefix wins for the nested name.
        assert_eq!(assets[2].args["scene"], "level_boss");
        // An authored `scene` arg is never overwritten.
        assert_eq!(assets[3].args["scene"], "other");
        // No matching prefix: no `scene` arg appears.
        assert!(assets[4].args.get("scene").is_none());
    }

    #[test]
    fn resolve_scene_refs_rewrites_action_names_to_interned_ids() {
        crate::ecs::asset_id::reset_interner();
        let mut assets = vec![
            wja(
                "btn",
                "HitRegion",
                serde_json::json!({"action": "screen:show:pause"}),
            ),
            wja(
                "key",
                "KeyBinding",
                serde_json::json!({"action": "scene:day"}),
            ),
        ];
        super::resolve_scene_refs(&mut assets);

        // Names intern in resolution order on this thread's fresh interner:
        // "pause" -> 0, "day" -> 1.
        assert_eq!(assets[0].args["action"], "screen:show:0");
        assert_eq!(assets[1].args["action"], "scene:1");
    }

    #[test]
    fn resolve_scene_refs_leaves_numeric_and_foreign_actions_alone() {
        let mut assets = vec![
            wja(
                "a",
                "HitRegion",
                serde_json::json!({"action": "screen:toggle:3"}),
            ),
            wja("b", "HitRegion", serde_json::json!({"action": "quit"})),
            wja("c", "KeyBinding", serde_json::json!({"action": "scene:"})),
        ];
        super::resolve_scene_refs(&mut assets);

        // Already an id, not a recognised prefix, and an empty target: all
        // pass through unchanged.
        assert_eq!(assets[0].args["action"], "screen:toggle:3");
        assert_eq!(assets[1].args["action"], "quit");
        assert_eq!(assets[2].args["action"], "scene:");
    }

    #[test]
    fn probe_mesh_payload_cache_probes_only_source_backed_mesh_assets() {
        let assets = vec![
            wja("m", MESH_TYPE, serde_json::json!({"source": "x.glb"})),
            wja("inline", MESH_TYPE, serde_json::json!({"vertices": []})),
            wja(
                "s",
                SKINNED_MESH_TYPE,
                serde_json::json!({"source": "y.glb"}),
            ),
            wja(
                "p",
                "ProceduralMesh",
                serde_json::json!({"generator": "box"}),
            ),
        ];
        let probed = probe_mesh_payload_cache(&assets, None, None);

        let mut names: Vec<&str> = probed.keys().map(|s| s.as_str()).collect();
        names.sort_unstable();
        assert_eq!(names, vec!["m", "s"]);
        for entry in probed.values() {
            assert!(!entry.key.is_empty());
            // The payload cache is disabled under cargo test, so a probe can
            // only ever record a miss here.
            assert!(entry.bytes.is_none());
        }
    }

    // `build_compiled` runs on an already-prepared world, so a type the
    // component registry cannot resolve surfaces here rather than upstream.
    #[test]
    fn build_compiled_names_the_asset_whose_type_will_not_resolve() {
        let assets = vec![wja("mystery", "NotAType", serde_json::json!({}))];
        let Err(err) = build_compiled(assets, None, None) else {
            panic!("unknown type must not compile");
        };
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
        assert!(err.to_string().contains("Asset 'mystery'"), "got: {err}");
    }

    // A payload that will not compile fails the whole build; the error names
    // the asset so the author knows which line to fix.
    #[test]
    fn build_compiled_surfaces_a_payload_compile_failure() {
        let assets = vec![wja(
            "shape",
            "ProceduralMesh",
            serde_json::json!({"generator": "not_a_generator"}),
        )];
        let Err(err) = build_compiled(assets, None, None) else {
            panic!("an uncompilable payload must not build");
        };
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
        assert!(err.to_string().contains("not_a_generator"), "got: {err}");
    }

    // The per-asset resolution pass reports every asset that fails, not just
    // the first, and a clean world returns Ok.
    #[test]
    fn validate_world_jsonl_collects_every_resolution_failure() {
        let world = concat!(
            r#"{"name":"first","type":"ProceduralMesh","args":{"generator":"box"}}"#,
            "\n",
            r#"{"name":"clip","type":"AudioClip","args":{"source":"a.wav"}}"#,
            "\n",
        );
        validate_world_jsonl(world, None).expect("a resolvable world validates");

        // Args of the wrong shape survive the structural world checks and are
        // rejected when the def is built.
        let bad = concat!(
            r#"{"name":"t1","type":"PointLight","args":{"intensity":"soon"}}"#,
            "\n",
            r#"{"name":"t2","type":"PointLight","args":{"intensity":"later"}}"#,
            "\n",
        );
        let err = validate_world_jsonl(bad, None).expect_err("mistyped args do not resolve");
        let msg = err.to_string();
        assert!(msg.contains("Asset 't1'"), "got: {msg}");
        assert!(msg.contains("Asset 't2'"), "got: {msg}");
    }

    // An uncompressed 24-bit BGR Targa, the cheapest real image source to
    // author inline.
    fn tga_2x2() -> Vec<u8> {
        let mut v = vec![0u8; 18];
        v[2] = 2; // uncompressed true-color
        v[12..14].copy_from_slice(&2u16.to_le_bytes());
        v[14..16].copy_from_slice(&2u16.to_le_bytes());
        v[16] = 24;
        v[17] = 0x20; // top origin
        v.extend_from_slice(&[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]);
        v
    }

    // `cn debug`'s hot-reload watcher maps a saved file back to the handle it
    // feeds, so every file-backed texture and mesh records its source in handle
    // order. A generated asset has nothing to watch and records an empty source.
    #[test]
    fn build_compiled_records_hot_reload_sources_in_handle_order() {
        let dir = tempfile::tempdir().expect("tempdir");
        let tga = write_fixture(&dir, "wall.tga", &tga_2x2());
        let glb = write_fixture(
            &dir,
            "scene.glb",
            &crate::glb::test_fixtures::static_triangle_glb(),
        );
        let assets = vec![
            wja(
                "proc_tex",
                "Texture",
                serde_json::json!({"generator": "checker", "resolution": 8}),
            ),
            wja(
                "wall_tex",
                "Texture",
                serde_json::json!({"source": tga, "image_index": 3}),
            ),
            wja(
                "inline_mesh",
                MESH_TYPE,
                serde_json::json!({"generator": "box", "half_extents": [1, 1, 1]}),
            ),
            wja(
                "file_mesh",
                MESH_TYPE,
                serde_json::json!({
                    "source": glb,
                    "primitive_index": 0,
                    "lod_levels": 3,
                    "lod_distances": [10.0, 20.0],
                }),
            ),
        ];
        let result = build_compiled(assets, None, None).expect("build");

        assert_eq!(result.texture_sources.len(), 2);
        assert_eq!(
            result.texture_sources[0],
            TextureSourceInfo {
                name_id: 0,
                source: String::new(),
                image_index: 0,
            },
            "a generated texture has no file to watch"
        );
        assert_eq!(
            result.texture_sources[1],
            TextureSourceInfo {
                name_id: 1,
                source: tga.clone(),
                image_index: 3,
            }
        );

        assert_eq!(result.mesh_sources.len(), 2);
        assert_eq!(
            result.mesh_sources[0],
            MeshSourceInfo {
                source: String::new(),
                primitive_index: 0,
                lod_levels: 1,
                lod_distances: Vec::new(),
            },
            "a generated mesh has no file to watch"
        );
        assert_eq!(
            result.mesh_sources[1],
            MeshSourceInfo {
                source: glb.clone(),
                primitive_index: 0,
                lod_levels: 3,
                lod_distances: vec![10.0, 20.0],
            }
        );

        // The lock records mirror the catalogues so a blob boot can rebuild
        // them without the authored args.
        let lock_tex: Vec<_> = result
            .resource_locks
            .iter()
            .filter(|r| r.kind == "Texture")
            .collect();
        assert_eq!(lock_tex.len(), 2);
        assert_eq!(lock_tex[0].texture_source.as_ref().unwrap().source, "");
        let wall = lock_tex[1].texture_source.as_ref().unwrap();
        assert_eq!(wall.source, tga);
        assert_eq!(wall.image_index, 3);
        assert!(lock_tex[1].mesh_source.is_none());

        let lock_mesh: Vec<_> = result
            .resource_locks
            .iter()
            .filter(|r| r.kind == "Mesh")
            .collect();
        assert_eq!(lock_mesh.len(), 2);
        assert!(lock_mesh[0].texture_source.is_none());
        let file_mesh = lock_mesh[1].mesh_source.as_ref().unwrap();
        assert_eq!(file_mesh.source, glb);
        assert_eq!(file_mesh.lod_levels, 3);
        assert_eq!(file_mesh.lod_distances, vec![10.0, 20.0]);
    }

    // A data resource carries its bytes inline in the record rather than in a
    // blob payload section, so the lock records no payload blob for it.
    #[test]
    fn build_compiled_keeps_a_data_resource_out_of_the_payload_sections() {
        let assets = vec![
            wja("wood", "Material", serde_json::json!({})),
            wja(
                "shape",
                "ProceduralMesh",
                serde_json::json!({"generator": "box"}),
            ),
        ];
        let result = build_compiled(assets, None, None).expect("build");

        assert_eq!(result.resources.len(), 1);
        let material = &result.resources[0];
        assert!(material.payload.is_none(), "a Material rides inline");
        assert!(!material.data_bytes.is_empty());
        postcard::from_bytes::<crate::components::Material>(&material.data_bytes)
            .expect("the inline bytes decode as a Material");
        assert_eq!(result.resource_locks[0].name, "wood");
        assert_eq!(result.resource_locks[0].payload_blob, None);
        // The component's payload is what actually occupies the blob.
        assert_eq!(result.defs.len(), 1);
        assert!(result.defs[0].payload.is_some());
    }

    // Only a File whose kind maps to a mesh payload is compiled; every other
    // kind stays a plain reference with no blob bytes.
    #[test]
    fn build_compiled_compiles_only_mesh_kind_file_assets() {
        let dir = tempfile::tempdir().expect("tempdir");
        let obj = write_fixture(&dir, "tri.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n");
        let png = write_fixture(&dir, "icon.png", b"not read");
        let assets = vec![
            wja(
                "model",
                "File",
                serde_json::json!({"path": obj, "kind": "obj"}),
            ),
            wja(
                "icon",
                "File",
                serde_json::json!({"path": png, "kind": "png"}),
            ),
        ];
        let result = build_compiled(assets, None, None).expect("build");

        assert_eq!(result.names, vec!["model".to_string(), "icon".to_string()]);
        let mesh_payload = result.defs[0]
            .payload
            .as_ref()
            .expect("the obj File compiles");
        assert!(mesh_payload.len > 0);
        assert!(
            result.defs[1].payload.is_none(),
            "a png File produces no blob payload"
        );
    }

    // A source-backed asset that is neither mesh kind is skipped: its payload
    // cache is handled by the per-asset path inside the compile pass.
    #[test]
    fn probe_mesh_payload_cache_skips_a_source_backed_non_mesh_asset() {
        let assets = vec![
            wja("tex", "Texture", serde_json::json!({"source": "wall.png"})),
            wja("m", MESH_TYPE, serde_json::json!({"source": "x.glb"})),
        ];
        let probed = probe_mesh_payload_cache(&assets, None, None);
        assert_eq!(probed.len(), 1);
        assert!(probed.contains_key("m"));
    }

    use crate::resource_handles::{RegisteredType, ResourceKind};

    fn procedural_mesh_def() -> BlobAssetDef {
        asset_api::create_asset_def(&AssetRequest {
            asset_type: "ProceduralMesh".to_string(),
            args: Some(serde_json::json!({"generator": "box"})),
        })
        .expect("ProceduralMesh def")
    }

    // The pre-desugar probe is the whole point of the glTF cache: when it holds
    // bytes for an asset, neither the component nor the resource path may touch
    // the source again. Both assets here name inputs that would fail to
    // compile, so a recompile would be loud.
    #[test]
    fn compile_and_pack_payloads_serves_probed_bytes_without_recompiling() {
        let assets = vec![
            wja(
                "shape",
                "ProceduralMesh",
                serde_json::json!({"generator": "not_a_generator"}),
            ),
            wja(
                "body",
                MESH_TYPE,
                serde_json::json!({"source": "/no/such/body.glb"}),
            ),
        ];
        let mut named = vec![("shape".to_string(), procedural_mesh_def())];
        let resource_jobs = vec![(1usize, RegisteredType::Mesh, 0u32)];
        let mut cache = std::collections::HashMap::new();
        cache.insert(
            "shape".to_string(),
            MeshCacheEntry {
                key: "shape-key".to_string(),
                bytes: Some(vec![1, 2, 3]),
            },
        );
        cache.insert(
            "body".to_string(),
            MeshCacheEntry {
                key: "body-key".to_string(),
                bytes: Some(vec![4, 5, 6, 7]),
            },
        );

        let out = compile_and_pack_payloads(
            &mut named,
            &[0],
            PackContext {
                assets: &assets,
                resource_jobs: &resource_jobs,
                partition: &crate::scene_partition::partition_scenes(&assets),
                mesh_source_handles: &Default::default(),
                max_blob_bytes: 1024,
                assets_dir: None,
                artifacts_dir: None,
                mesh_cache: &cache,
                progress: None,
            },
        )
        .expect("probed payloads need no compiler");

        assert_eq!(out.cache_hits, 2);
        assert_eq!(out.cache_misses, 0);
        // Components pack first, then the resource stream, into one blob.
        assert_eq!(out.blobs, vec![vec![1, 2, 3, 4, 5, 6, 7]]);
        let component = named[0].1.payload.as_ref().expect("component locator");
        assert_eq!(
            (component.blob_index, component.offset, component.len),
            (0, 0, 3)
        );
        let resource = out.resources[0].payload.as_ref().expect("resource locator");
        assert_eq!(
            (resource.blob_index, resource.offset, resource.len),
            (0, 3, 4)
        );
        assert_eq!(out.resources[0].resource_kind, ResourceKind::Mesh as u8);
        assert_eq!(out.resources[0].handle, 0);
    }

    // A scene-exclusive resource packs into its own blob after the global set,
    // and the scene group records it; record order stays resource_jobs order.
    #[test]
    fn scene_owned_payloads_pack_into_their_own_blob() {
        let assets = vec![
            wja("day", "Scene", serde_json::json!({})),
            wja(
                "day_prop",
                "Prop",
                serde_json::json!({"mesh":"day_mesh","scene":"day"}),
            ),
            wja("bg_prop", "Prop", serde_json::json!({"mesh":"bg_mesh"})),
            wja(
                "day_mesh",
                MESH_TYPE,
                serde_json::json!({"source": "/no/such/day.glb"}),
            ),
            wja(
                "bg_mesh",
                MESH_TYPE,
                serde_json::json!({"source": "/no/such/bg.glb"}),
            ),
        ];
        let mut named: Vec<(String, BlobAssetDef)> = Vec::new();
        let resource_jobs = vec![
            (3usize, RegisteredType::Mesh, 0u32),
            (4usize, RegisteredType::Mesh, 1u32),
        ];
        let cache = std::collections::HashMap::from([
            (
                "day_mesh".to_string(),
                MeshCacheEntry {
                    key: "day-key".to_string(),
                    bytes: Some(vec![0xDD; 4]),
                },
            ),
            (
                "bg_mesh".to_string(),
                MeshCacheEntry {
                    key: "bg-key".to_string(),
                    bytes: Some(vec![0xBB; 2]),
                },
            ),
        ]);

        let out = compile_and_pack_payloads(
            &mut named,
            &[],
            PackContext {
                assets: &assets,
                resource_jobs: &resource_jobs,
                partition: &crate::scene_partition::partition_scenes(&assets),
                mesh_source_handles: &Default::default(),
                max_blob_bytes: 1 << 20,
                assets_dir: None,
                artifacts_dir: None,
                mesh_cache: &cache,
                progress: None,
            },
        )
        .expect("probed payloads need no compiler");

        // Global set (bg) fills blob 0; day's exclusive mesh starts blob 1.
        assert_eq!(out.blobs, vec![vec![0xBB; 2], vec![0xDD; 4]]);
        let day = out.resources[0].payload.as_ref().expect("day locator");
        assert_eq!((day.blob_index, day.offset, day.len), (1, 0, 4));
        let bg = out.resources[1].payload.as_ref().expect("bg locator");
        assert_eq!((bg.blob_index, bg.offset, bg.len), (0, 0, 2));

        assert_eq!(out.scene_groups.len(), 1);
        assert_eq!(
            out.scene_groups[0].resources,
            vec![(ResourceKind::Mesh as u8, 0)]
        );
        assert!(out.scene_groups[0].defs.is_empty());
    }

    // Every compiled static-mesh payload gets a baked AABB + counts record
    // keyed by its mesh-source handle.
    #[test]
    fn mesh_bounds_are_baked_for_compiled_mesh_sources() {
        let assets = vec![wja(
            "shape",
            "ProceduralMesh",
            serde_json::json!({"generator": "box"}),
        )];
        let mut named = vec![("shape".to_string(), procedural_mesh_def())];
        let mut handles = crate::resource_handles::ResourceHandles::default();
        crate::resource_handles::assign_mesh_source_handles(&mut handles, &assets);
        let out = compile_and_pack_payloads(
            &mut named,
            &[0],
            PackContext {
                assets: &assets,
                resource_jobs: &[],
                partition: &crate::scene_partition::partition_scenes(&assets),
                mesh_source_handles: &handles,
                max_blob_bytes: 1 << 20,
                assets_dir: None,
                artifacts_dir: None,
                mesh_cache: &Default::default(),
                progress: None,
            },
        )
        .expect("box compiles");
        assert_eq!(out.mesh_bounds.len(), 1);
        let record = out.mesh_bounds[0];
        assert_eq!(record.handle, 0);
        assert!(record.vertex_count > 0 && record.index_count > 0);
        for axis in 0..3 {
            assert!(record.min[axis] < record.max[axis]);
        }
    }

    // A probe that recorded a miss compiles for real, on both the component and
    // the resource path, and both payloads land in the packed blob.
    #[test]
    fn compile_and_pack_payloads_compiles_a_probe_miss() {
        let assets = vec![
            wja(
                "shape",
                "ProceduralMesh",
                serde_json::json!({"generator": "box"}),
            ),
            wja(
                "body",
                MESH_TYPE,
                serde_json::json!({"generator": "sphere", "radius": 1.0}),
            ),
        ];
        let mut named = vec![("shape".to_string(), procedural_mesh_def())];
        let resource_jobs = vec![(1usize, RegisteredType::Mesh, 0u32)];
        let miss = |key: &str| MeshCacheEntry {
            key: key.to_string(),
            bytes: None,
        };
        let cache = std::collections::HashMap::from([
            ("shape".to_string(), miss("shape-key")),
            ("body".to_string(), miss("body-key")),
        ]);

        let out = compile_and_pack_payloads(
            &mut named,
            &[0],
            PackContext {
                assets: &assets,
                resource_jobs: &resource_jobs,
                partition: &crate::scene_partition::partition_scenes(&assets),
                mesh_source_handles: &Default::default(),
                max_blob_bytes: 1 << 20,
                assets_dir: None,
                artifacts_dir: None,
                mesh_cache: &cache,
                progress: None,
            },
        )
        .expect("a probe miss compiles");

        assert_eq!(out.cache_hits, 0);
        assert_eq!(out.cache_misses, 2);
        let component = named[0].1.payload.as_ref().expect("component locator");
        let resource = out.resources[0].payload.as_ref().expect("resource locator");
        assert!(component.len > 0);
        assert!(resource.len > 0);
        assert_eq!(
            out.blobs[0].len() as u64,
            component.len + resource.len,
            "both compiled payloads land in the blob"
        );
    }

    // A world whose assets all carry inline args produces no payload sections
    // at all, and still reports one (empty) blob for the metadata to ride in.
    #[test]
    fn compile_and_pack_payloads_returns_one_empty_blob_for_a_payload_less_world() {
        let assets = vec![wja("day", "Scene", serde_json::json!({}))];
        let mut named = vec![(
            "day".to_string(),
            asset_api::create_asset_def(&AssetRequest {
                asset_type: "Scene".to_string(),
                args: Some(serde_json::json!({})),
            })
            .expect("Scene def"),
        )];
        let out = compile_and_pack_payloads(
            &mut named,
            &[0],
            PackContext {
                assets: &assets,
                resource_jobs: &[],
                partition: &crate::scene_partition::partition_scenes(&assets),
                mesh_source_handles: &Default::default(),
                max_blob_bytes: 1024,
                assets_dir: None,
                artifacts_dir: None,
                mesh_cache: &Default::default(),
                progress: None,
            },
        )
        .expect("pack");

        assert_eq!(out.blobs, vec![Vec::<u8>::new()]);
        assert!(out.resources.is_empty());
        assert_eq!((out.cache_hits, out.cache_misses), (0, 0));
        assert!(named[0].1.payload.is_none());
    }

    // The compile pass selects its work by discriminant. A def carrying one the
    // component registry does not know is skipped, so an unrecognised record
    // cannot abort a build.
    #[test]
    fn compile_and_pack_payloads_skips_a_def_with_an_unknown_discriminant() {
        let assets = vec![wja("mystery", "ProceduralMesh", serde_json::json!({}))];
        let mut named = vec![(
            "mystery".to_string(),
            BlobAssetDef {
                name: None,
                kind: AssetKind::Component,
                discriminant: 200,
                args_bytes: Vec::new(),
                payload: None,
            },
        )];
        assert!(
            RegisteredType::from_discriminant(200).is_none(),
            "200 must stay outside the registered discriminant range"
        );

        let out = compile_and_pack_payloads(
            &mut named,
            &[0],
            PackContext {
                assets: &assets,
                resource_jobs: &[],
                partition: &crate::scene_partition::partition_scenes(&assets),
                mesh_source_handles: &Default::default(),
                max_blob_bytes: 1024,
                assets_dir: None,
                artifacts_dir: None,
                mesh_cache: &Default::default(),
                progress: None,
            },
        )
        .expect("pack");

        assert!(named[0].1.payload.is_none());
        assert_eq!(out.blobs, vec![Vec::<u8>::new()]);
    }

    // The blob size ceiling is packing policy, not a format limit: payloads
    // that overflow it roll into the next blob and their locators follow.
    #[test]
    fn compile_and_pack_payloads_rolls_payloads_into_overflow_blobs() {
        let assets = vec![
            wja("a", "ProceduralMesh", serde_json::json!({})),
            wja("b", "ProceduralMesh", serde_json::json!({})),
        ];
        let mut named = vec![
            ("a".to_string(), procedural_mesh_def()),
            ("b".to_string(), procedural_mesh_def()),
        ];
        let cache = std::collections::HashMap::from([
            (
                "a".to_string(),
                MeshCacheEntry {
                    key: "a".to_string(),
                    bytes: Some(vec![0xAA; 6]),
                },
            ),
            (
                "b".to_string(),
                MeshCacheEntry {
                    key: "b".to_string(),
                    bytes: Some(vec![0xBB; 6]),
                },
            ),
        ]);

        let out = compile_and_pack_payloads(
            &mut named,
            &[0, 1],
            PackContext {
                assets: &assets,
                resource_jobs: &[],
                partition: &crate::scene_partition::partition_scenes(&assets),
                mesh_source_handles: &Default::default(),
                max_blob_bytes: 8,
                assets_dir: None,
                artifacts_dir: None,
                mesh_cache: &cache,
                progress: None,
            },
        )
        .expect("pack");

        assert_eq!(out.blobs, vec![vec![0xAA; 6], vec![0xBB; 6]]);
        assert_eq!(named[0].1.payload.as_ref().unwrap().blob_index, 0);
        let second = named[1].1.payload.as_ref().unwrap();
        assert_eq!((second.blob_index, second.offset), (1, 0));
    }

    #[test]
    fn compile_by_type_without_build_impl_errors() {
        let ct = RegisteredType::parse("Prop").expect("Prop is a registered component");
        let err = compile_by_type(ct, &serde_json::json!({}), &ctx())
            .expect_err("Prop has no BuildAsset impl");
        assert!(err.to_string().contains("no BuildAsset impl"), "got: {err}");
    }

    #[test]
    fn cache_inputs_by_type_defaults_to_empty_extras() {
        use crate::asset::SourceFiles;
        let ct = RegisteredType::parse("Prop").expect("Prop is a registered component");
        let inputs = cache_inputs_by_type(ct, &serde_json::json!({}), &ctx());
        assert_eq!(inputs.sources, SourceFiles::Extra(Vec::new()));
        assert!(!inputs.target_dependent);
    }

    // The arms that take the trait default report no inputs of their own: every
    // file they read is named by an args string, which the payload cache's
    // generic walk already hashes.
    #[test]
    fn cache_inputs_by_type_covers_the_args_walk_arms() {
        use crate::asset::SourceFiles;
        for name in ["ProceduralMesh", "VoxelChunk", "File", "Room"] {
            let inputs = cache_inputs_by_type(ct(name), &serde_json::json!({}), &ctx());
            assert_eq!(
                inputs.sources,
                SourceFiles::Extra(Vec::new()),
                "{name} must not narrow the generic args walk"
            );
            assert!(
                !inputs.target_dependent,
                "{name} compiles the same everywhere"
            );
        }
    }

    // AudioClip compiles through `RegisteredType` now, not `compile_by_type`
    // (it left the component registry). Its source-less error still surfaces, and
    // its source file is folded into the payload cache key.
    #[test]
    fn resource_asset_types_compile_audio_clip_texture_cubemap_env_lut_and_font() {
        use crate::registry::RegisteredType;
        let rt = RegisteredType::parse("AudioClip").expect("AudioClip is a resource asset");
        let err = rt
            .compile_payload(&serde_json::json!({}), None)
            .expect_err("a source-less AudioClip must fail to compile");
        assert!(err.to_string().contains("missing 'source'"), "got: {err}");
        assert_eq!(
            rt.source_files(&serde_json::json!({"source": "a.wav"}), None),
            vec!["a.wav".to_string()]
        );
        assert!(rt.source_files(&serde_json::json!({}), None).is_empty());

        // Texture is also a resource asset (it left the component registry). A
        // procedural texture compiles a non-empty payload, and a file-backed one
        // folds its source into the payload cache key.
        let tex = RegisteredType::parse("Texture").expect("Texture is a resource asset");
        let bytes = tex
            .compile_payload(
                &serde_json::json!({"generator": "checker", "resolution": 32}),
                None,
            )
            .expect("a procedural texture compiles");
        assert!(!bytes.is_empty());
        assert_eq!(
            tex.source_files(&serde_json::json!({"source": "a.png"}), None),
            vec!["a.png".to_string()]
        );

        // CubemapTexture is a resource asset too. Source-less args fail, and its
        // `.hdr` source folds into the payload cache key.
        let cube =
            RegisteredType::parse("CubemapTexture").expect("CubemapTexture is a resource asset");
        let err = cube
            .compile_payload(&serde_json::json!({}), None)
            .expect_err("a source-less CubemapTexture must fail to compile");
        assert!(
            err.to_string().contains("requires a `source` path"),
            "got: {err}"
        );
        assert_eq!(
            cube.source_files(&serde_json::json!({"source": "c.hdr"}), None),
            vec!["c.hdr".to_string()]
        );

        // EnvironmentMap and ColorLut are resource assets too. Both surface their
        // source-less error through `RegisteredType::compile_payload`, and fold
        // their `source` into the payload cache key.
        let env =
            RegisteredType::parse("EnvironmentMap").expect("EnvironmentMap is a resource asset");
        let err = env
            .compile_payload(&serde_json::json!({}), None)
            .expect_err("a source-less EnvironmentMap must fail to compile");
        assert!(
            err.to_string()
                .contains("requires either `source` or `generator`"),
            "got: {err}"
        );
        assert_eq!(
            env.source_files(&serde_json::json!({"source": "e.hdr"}), None),
            vec!["e.hdr".to_string()]
        );

        let lut = RegisteredType::parse("ColorLut").expect("ColorLut is a resource asset");
        let err = lut
            .compile_payload(&serde_json::json!({}), None)
            .expect_err("a source-less ColorLut must fail to compile");
        assert!(
            err.to_string().contains("requires a `source` path"),
            "got: {err}"
        );
        assert_eq!(
            lut.source_files(&serde_json::json!({"source": "l.cube"}), None),
            vec!["l.cube".to_string()]
        );

        // Font is a resource asset. The built-in font (empty `path`) compiles a
        // non-empty atlas, and a file-backed font folds its `path` (not `source`)
        // into the payload cache key.
        let font = RegisteredType::parse("Font").expect("Font is a resource asset");
        let bytes = font
            .compile_payload(&serde_json::json!({"size_px": 20}), None)
            .expect("the built-in font compiles");
        assert!(!bytes.is_empty());
        assert_eq!(
            font.source_files(&serde_json::json!({"path": "f.ttf"}), None),
            vec!["f.ttf".to_string()]
        );
        assert!(
            font.source_files(&serde_json::json!({"source": "x.ttf"}), None)
                .is_empty()
        );
    }

    // A mesh whose source is a text `.gltf` reads sibling files the args never
    // name; `source_files` must report them so an edited external buffer or
    // image busts the payload cache.
    #[test]
    fn gltf_sources_fold_referenced_sibling_files_into_source_files() {
        use crate::registry::RegisteredType;

        let dir = tempfile::tempdir().unwrap();
        let json = serde_json::json!({
            "asset": {"version": "2.0"},
            "buffers": [{"byteLength": 4, "uri": "geo.bin"}],
            "images": [{"uri": "albedo.png"}]
        });
        let gltf_path = dir.path().join("tri.gltf");
        std::fs::write(&gltf_path, serde_json::to_vec(&json).unwrap()).unwrap();
        let src = gltf_path.to_str().unwrap().to_string();

        for rt in [RegisteredType::Mesh, RegisteredType::SkinnedMesh] {
            let files = rt.source_files(&serde_json::json!({"source": src}), None);
            assert_eq!(files.len(), 3, "{rt:?}: {files:?}");
            assert_eq!(files[0], src);
            assert!(files.iter().any(|f| f.ends_with("geo.bin")), "{files:?}");
            assert!(files.iter().any(|f| f.ends_with("albedo.png")), "{files:?}");
        }

        // A `.glb` source reports only itself.
        let glb =
            RegisteredType::Mesh.source_files(&serde_json::json!({"source": "scene.glb"}), None);
        assert_eq!(glb, vec!["scene.glb".to_string()]);
    }

    // Dispatch coverage: compile_by_type / source_files_by_type route each
    // compiled RegisteredType to its asset_impls wrapper.

    fn ct(name: &str) -> RegisteredType {
        RegisteredType::parse(name).unwrap_or_else(|| panic!("{name} is a registered component"))
    }

    // Arms whose outcome is deterministic from inline args alone: a valid
    // minimal payload for the ones that need no source file, and the expected
    // error for the ones that require a source but got none.
    #[test]
    fn compile_by_type_dispatches_deterministic_arms() {
        // Mesh is a resource asset now: it compiles through
        // `RegisteredType::compile_payload`, not the RegisteredType dispatch.
        let mesh_bytes = crate::registry::RegisteredType::Mesh
            .compile_payload(
                &serde_json::json!({"generator": "box", "half_extents": [1, 1, 1]}),
                None,
            )
            .expect("Mesh compiles through the resource path");
        assert!(!mesh_bytes.is_empty());

        let ok_cases: &[(&str, serde_json::Value)] = &[
            (
                "ProceduralMesh",
                serde_json::json!({"generator": "sphere", "radius": 1.0}),
            ),
            ("Room", serde_json::json!({})),
        ];
        for case in ok_cases {
            let name = case.0;
            let args = &case.1;
            let bytes = compile_by_type(ct(name), args, &ctx())
                .unwrap_or_else(|e| panic!("{name} should compile: {e}"));
            assert!(!bytes.is_empty(), "{name} payload should be non-empty");
        }

        let err_cases: &[(&str, serde_json::Value, &str)] =
            &[("File", serde_json::json!({}), "unsupported File kind")];
        for case in err_cases {
            let name = case.0;
            let args = &case.1;
            let needle = case.2;
            let err = compile_by_type(ct(name), args, &ctx())
                .expect_err(&format!("{name} with empty args should error"));
            assert!(
                err.to_string().contains(needle),
                "{name} error should mention '{needle}', got: {err}"
            );
        }
    }

    // The File wrapper decodes an OBJ mesh source into a non-empty payload.
    #[test]
    fn compile_by_type_file_compiles_an_obj_source() {
        let dir = tempfile::tempdir().expect("tempdir");
        let obj = dir.path().join("tri.obj");
        std::fs::write(&obj, "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n").expect("write obj");
        let args = serde_json::json!({"path": obj.to_str().unwrap(), "kind": "obj"});
        let bytes = compile_by_type(ct("File"), &args, &ctx()).expect("obj compiles");
        assert!(!bytes.is_empty());
    }

    // The SkinnedMesh resource compiler deserialises args + an optional
    // skeleton, then bakes geometry: one vertex is enough for a payload, no
    // vertices and a malformed skeleton are the two error arms. Its baked
    // data form carries the interned name id and drops the geometry.
    #[test]
    fn skinned_mesh_resource_compile_paths() {
        use crate::registry::RegisteredType;
        let rt = RegisteredType::SkinnedMesh;

        let ok = serde_json::json!({"vertices": [{"pos": [0.0, 0.0, 0.0]}], "indices": []});
        let bytes = rt.compile_payload(&ok, None).expect("skinned compiles");
        assert!(!bytes.is_empty());

        let no_verts = rt
            .compile_payload(&serde_json::json!({}), None)
            .expect_err("no vertices");
        assert!(
            no_verts.to_string().contains("at least one vertex"),
            "got: {no_verts}"
        );

        let bad_skeleton = rt
            .compile_payload(
                &serde_json::json!({"vertices": [{"pos": [0.0, 0.0, 0.0]}], "skeleton": 5}),
                None,
            )
            .expect_err("malformed skeleton");
        assert!(
            bad_skeleton.to_string().contains("invalid skeleton args"),
            "got: {bad_skeleton}"
        );

        // The baked data tuple: name id first, then the clamped mesh with its
        // geometry cleared.
        crate::ecs::asset_id::reset_interner();
        let name_id = crate::ecs::asset_id::intern("hero");
        let data = rt
            .compile_data(
                "hero",
                &serde_json::json!({
                    "vertices": [{"pos": [0.0, 0.0, 0.0]}],
                    "scale": [0.0, 0.0, 0.0],
                    "max_instances": 999999,
                    "capsule": {"half_height": 0.6, "radius": 0.2},
                }),
            )
            .expect("data bakes")
            .expect("skinned mesh carries baked data");
        let (baked_name, sm): (u32, crate::components::SkinnedMesh) =
            postcard::from_bytes(&data).unwrap();
        assert_eq!(baked_name, name_id.0);
        assert_eq!(sm.scale, [1.0, 1.0, 1.0], "zero scale clamps to unit");
        assert_eq!(sm.max_instances, 4096, "reserve caps at 4096");
        assert!(sm.vertices.is_empty(), "geometry rides the payload");
        assert!(sm.capsule.is_some());
    }

    // The VoxelChunk wrapper resolves its palette from sibling BlockType assets
    // in the build context.
    #[test]
    fn compile_by_type_voxel_chunk_resolves_palette_from_ctx() {
        let blocks = vec![
            wja("air", "BlockType", serde_json::json!({"solid": false})),
            wja(
                "stone",
                "BlockType",
                serde_json::json!({"uv_min": [0, 0], "uv_max": [1, 1]}),
            ),
        ];
        let vctx = crate::asset::BuildCtx {
            name: "chunk",
            assets_dir: None,
            artifacts_dir: None,
            all_assets: &blocks,
        };
        let args = serde_json::json!({
            "palette": ["air", "stone"],
            "dim": [2, 1, 1],
            "blocks": [1, 1],
            "block_size": 1.0,
        });
        let bytes = compile_by_type(ct("VoxelChunk"), &args, &vctx).expect("voxel compiles");
        assert!(!bytes.is_empty());
    }

    // The SdfVolume wrapper transports the current backend's fragment shader
    // bytes verbatim (no MSL/GLSL compilation); a missing source is a hard
    // error rather than a silent empty payload.
    #[test]
    fn compile_by_type_sdf_volume_transports_shader_bytes() {
        let dir = tempfile::tempdir().expect("tempdir");
        let shader = dir.path().join("blob.metal");
        let source = b"// sdf fragment source\n";
        std::fs::write(&shader, source).expect("write shader");
        let path = shader.to_str().unwrap();
        // Set every backend's key to the same file so the test is
        // platform-independent: only the current backend's entry is read.
        let args = serde_json::json!({
            "fragment_shaders": {"metal": path, "hlsl": path, "glsl": path}
        });
        let bytes = compile_by_type(ct("SdfVolume"), &args, &ctx()).expect("sdf reads source");
        assert_eq!(bytes, source);

        let err = compile_by_type(ct("SdfVolume"), &serde_json::json!({}), &ctx())
            .expect_err("no fragment shader source");
        assert!(
            err.to_string().contains("no fragment shader source"),
            "got: {err}"
        );
    }

    // The Shader wrapper's non-compiling arms: a missing stage source is
    // either a hard error (Metal/HLSL) or the inline-GLSL stub (Vulkan).
    // Neither shells out to a shader toolchain, so the test stays
    // backend-agnostic.
    #[test]
    fn compile_by_type_shader_missing_source_does_not_shell_out() {
        let out = compile_by_type(
            ct("Shader"),
            &serde_json::json!({"vertex": {}, "fragment": {}}),
            &ctx(),
        );
        match out {
            Ok(bytes) => {
                let payload = concinnity_core::components::ShaderPayload::decode(&bytes)
                    .expect("empty container decodes");
                assert!(payload.stages.is_empty(), "glsl stub compiles no stages");
            }
            Err(e) => assert!(e.to_string().contains("no shader source"), "got: {e}"),
        }
    }

    // cache_inputs_by_type routes to the two overriding wrappers. Both report
    // `Only` -- the complete input set the current backend reads -- so an edit
    // to a sibling backend's shader leaves this backend's payload cached.
    #[test]
    fn cache_inputs_by_type_covers_the_overriding_wrappers() {
        use crate::asset::SourceFiles;
        let dir = tempfile::tempdir().expect("tempdir");
        let shader = dir.path().join("blob.metal");
        std::fs::write(&shader, b"x").expect("write shader");
        let path = shader.to_str().unwrap();

        // SdfVolume reports the resolved path for the current backend, and
        // transports it verbatim, so the compile target is not an input.
        let sdf_args = serde_json::json!({
            "fragment_shaders": {"metal": path, "hlsl": path, "glsl": path}
        });
        let sdf = cache_inputs_by_type(ct("SdfVolume"), &sdf_args, &ctx());
        assert_eq!(sdf.sources, SourceFiles::Only(vec![path.to_string()]));
        assert!(!sdf.target_dependent);
        assert_eq!(
            cache_inputs_by_type(ct("SdfVolume"), &serde_json::json!({}), &ctx()).sources,
            SourceFiles::Only(Vec::new())
        );

        // Shader compiles its stage sources, so the target is an input.
        let no_source = cache_inputs_by_type(ct("Shader"), &serde_json::json!({}), &ctx());
        assert_eq!(no_source.sources, SourceFiles::Only(Vec::new()));
        assert!(no_source.target_dependent);
    }
}