nucleation 0.10.14

A high-performance Minecraft schematic parser and utility library
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
//! mc-tick: the vanilla-accurate, headless tick engine.
//!
//! New surface — no old `ffi/` counterpart. An opaque [`ffi::TickSimulation`]
//! wraps `mc_tick::Simulation` with the full wiring recipe the engine's own
//! conformance tests use (inventories, behaviours, physics/fluid/rail tables,
//! entities, block-entity tickers), so any schematic that loads runs exactly
//! as the Rust test harness would run it.
//!
//! Design notes:
//! - Everything is headless — no rendering feature involved. Hosts pull
//!   per-tick JSON logs out and compute stats/animations themselves.
//! - Behaviours bind to *interned* states at construction, so any state a
//!   later `place_block` will write (a redstone block, typically) must be
//!   named up front: the constructors take a semicolon-separated
//!   `extra_states` list. `minecraft:redstone_block` and every facing of any
//!   shulker box held as an item are always pre-interned.
//! - Structured data crosses as JSON strings (PORTING.md rule 9).

use crate::formats::gametest::to_gametest_snbt;

/// `{simulate=true}`: simulate only the active component around this edit,
/// using nearby blocks as environmental context without allowing unrelated
/// parts of a large schematic to become part of the update.
pub(crate) fn simulate_placement_into(
    schematic: &mut crate::UniversalSchematic,
    x: i32,
    y: i32,
    z: i32,
    descriptor: &str,
) -> Result<usize, String> {
    simulate_placements_into(schematic, &[(x, y, z)], descriptor)
}

const LOCAL_COMPONENT_LINK: i32 = 2;
const LOCAL_EFFECT_MARGIN: i32 = 2;
const LOCAL_PISTON_EFFECT_MARGIN: i32 = 12;
const LOCAL_CONTEXT_MARGIN: i32 = 4;

fn block_is_air(block: Option<&crate::BlockState>) -> bool {
    block.is_none_or(|block| {
        matches!(
            block.get_name(),
            "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
        )
    })
}

fn active_near_placements(
    schematic: &crate::UniversalSchematic,
    positions: &[(i32, i32, i32)],
) -> bool {
    positions.iter().any(|&(x, y, z)| {
        for dx in -LOCAL_COMPONENT_LINK..=LOCAL_COMPONENT_LINK {
            for dy in -LOCAL_COMPONENT_LINK..=LOCAL_COMPONENT_LINK {
                for dz in -LOCAL_COMPONENT_LINK..=LOCAL_COMPONENT_LINK {
                    if dx.abs() + dy.abs() + dz.abs() > LOCAL_COMPONENT_LINK {
                        continue;
                    }
                    let Some(candidate) = x
                        .checked_add(dx)
                        .zip(y.checked_add(dy))
                        .zip(z.checked_add(dz))
                        .map(|((x, y), z)| (x, y, z))
                    else {
                        continue;
                    };
                    if schematic
                        .get_block(candidate.0, candidate.1, candidate.2)
                        .is_some_and(|block| {
                            mc_tick::vanilla::is_simulation_component(&block.to_string())
                        })
                    {
                        return true;
                    }
                }
            }
        }
        false
    })
}

/// Resolve a placement without constructing a tick engine when its complete
/// result is a pure function of local block states.
///
/// `Some` means the resolver proved the shortcut safe and applied it; `None`
/// means a component with observable events was present and the caller must
/// use the normal simulator. This is deliberately a generic dispatch point:
/// inert blocks use the identity resolver today and simple dust/source
/// networks use the static wire resolver below. More block families can add a
/// resolver without changing the public `simulate` API.
fn try_resolve_placements(
    schematic: &mut crate::UniversalSchematic,
    positions: &[(i32, i32, i32)],
    descriptor: &str,
    core: Option<&crate::BoundingBox>,
    requested_cells: usize,
) -> Result<Option<usize>, String> {
    let name = descriptor
        .split_once('[')
        .map_or(descriptor, |(name, _)| name);

    // A block the engine itself classifies as passive has no on-place or tick
    // behaviour. With no active neighbour in update range, simulation is
    // exactly the plain write regardless of how large or sparse the rest of
    // the schematic is.
    if !mc_tick::vanilla::is_simulation_component(descriptor)
        && !active_near_placements(schematic, positions)
    {
        for &(x, y, z) in positions {
            schematic.set_block_from_string(x, y, z, descriptor)?;
        }
        return Ok(Some(requested_cells));
    }

    if !matches!(name, "minecraft:redstone_wire" | "minecraft:redstone_block") {
        return Ok(None);
    }
    let Some(core) = core else {
        return Ok(None);
    };
    try_resolve_simple_wire_network(schematic, positions, descriptor, core, requested_cells)
}

fn try_resolve_simple_wire_network(
    schematic: &mut crate::UniversalSchematic,
    positions: &[(i32, i32, i32)],
    descriptor: &str,
    core: &crate::BoundingBox,
    requested_cells: usize,
) -> Result<Option<usize>, String> {
    use std::collections::{HashMap, HashSet, VecDeque};

    const WIRE: &str = "minecraft:redstone_wire";
    const SOURCE: &str = "minecraft:redstone_block";
    const HORIZONTAL: [(i32, i32, i32); 4] = [(0, 0, -1), (0, 0, 1), (-1, 0, 0), (1, 0, 0)];
    const ALL_FACES: [(i32, i32, i32); 6] = [
        (0, -1, 0),
        (0, 1, 0),
        (0, 0, -1),
        (0, 0, 1),
        (-1, 0, 0),
        (1, 0, 0),
    ];

    let placed_name = descriptor
        .split_once('[')
        .map_or(descriptor, |(name, _)| name);
    let mut wires = HashSet::new();
    let mut sources = HashSet::new();
    let mut wire_y = None;

    for x in core.min.0..=core.max.0 {
        for y in core.min.1..=core.max.1 {
            for z in core.min.2..=core.max.2 {
                let Some(block) = schematic.get_block(x, y, z) else {
                    continue;
                };
                let name = block.get_name();
                if mc_tick::vanilla::is_simulation_component(&block.to_string())
                    && !matches!(name, WIRE | SOURCE)
                {
                    return Ok(None);
                }
                if name == WIRE {
                    if wire_y.is_some_and(|level| level != y) {
                        return Ok(None); // stairs/vertical dust need vanilla shape updates
                    }
                    wire_y = Some(y);
                    wires.insert((x, y, z));
                } else if name == SOURCE {
                    sources.insert((x, y, z));
                }
            }
        }
    }

    for &position in positions {
        wires.remove(&position);
        sources.remove(&position);
        if placed_name == WIRE {
            if wire_y.is_some_and(|level| level != position.1) {
                return Ok(None);
            }
            wire_y = Some(position.1);
            wires.insert(position);
        } else {
            sources.insert(position);
        }
    }

    // Keep this resolver strictly planar. Covered dust, unsupported dust and
    // a wire climbing a neighbouring block all have observable shape rules;
    // those cases fall through to the event engine.
    for &(x, y, z) in &wires {
        if !block_is_air(schematic.get_block(x, y + 1, z)) {
            return Ok(None);
        }
        if block_is_air(schematic.get_block(x, y - 1, z)) && !sources.contains(&(x, y - 1, z)) {
            return Ok(None);
        }
        for &(dx, _, dz) in &HORIZONTAL {
            if wires.contains(&(x + dx, y + 1, z + dz)) || wires.contains(&(x + dx, y - 1, z + dz))
            {
                return Ok(None);
            }
        }
    }

    let mut power: HashMap<(i32, i32, i32), u8> = wires
        .iter()
        .copied()
        .map(|position| (position, 0))
        .collect();
    let mut queue = VecDeque::new();
    for &wire in &wires {
        if ALL_FACES
            .iter()
            .any(|&(dx, dy, dz)| sources.contains(&(wire.0 + dx, wire.1 + dy, wire.2 + dz)))
        {
            power.insert(wire, 15);
            queue.push_back(wire);
        }
    }
    while let Some(position) = queue.pop_front() {
        let next_power = power[&position].saturating_sub(1);
        if next_power == 0 {
            continue;
        }
        for &(dx, _, dz) in &HORIZONTAL {
            let next = (position.0 + dx, position.1, position.2 + dz);
            if wires.contains(&next) && power[&next] < next_power {
                power.insert(next, next_power);
                queue.push_back(next);
            }
        }
    }

    let mut written = 0;
    for &position in positions {
        if placed_name == SOURCE {
            let before = schematic
                .get_block(position.0, position.1, position.2)
                .map(ToString::to_string);
            if before.as_deref() != Some(descriptor) {
                schematic.set_block_from_string(position.0, position.1, position.2, descriptor)?;
                written += 1;
            }
        }
    }
    for &(x, y, z) in &wires {
        let mut sides = [false; 4]; // north, south, west, east
        for (index, &(dx, _, dz)) in HORIZONTAL.iter().enumerate() {
            sides[index] =
                wires.contains(&(x + dx, y, z + dz)) || sources.contains(&(x + dx, y, z + dz));
        }
        let no_north_south = !sides[0] && !sides[1];
        let no_west_east = !sides[2] && !sides[3];
        if !sides[2] && no_north_south {
            sides[2] = true;
        }
        if !sides[3] && no_north_south {
            sides[3] = true;
        }
        if !sides[0] && no_west_east {
            sides[0] = true;
        }
        if !sides[1] && no_west_east {
            sides[1] = true;
        }
        let side = |connected| if connected { "side" } else { "none" };
        let resolved = format!(
            "{WIRE}[east={},north={},power={},south={},west={}]",
            side(sides[3]),
            side(sides[0]),
            power[&(x, y, z)],
            side(sides[1]),
            side(sides[2])
        );
        let before = schematic.get_block(x, y, z).map(ToString::to_string);
        if before.as_deref() != Some(resolved.as_str()) {
            schematic.set_block_from_string(x, y, z, &resolved)?;
            written += 1;
        }
    }
    Ok(Some(written.max(requested_cells)))
}

fn checked_local_bounds(
    schematic: &crate::UniversalSchematic,
    positions: &[(i32, i32, i32)],
    descriptor: &str,
) -> Result<Option<(crate::BoundingBox, crate::BoundingBox)>, String> {
    use std::collections::{HashSet, VecDeque};

    if positions.is_empty() {
        return Ok(None);
    }

    let is_active = |position: (i32, i32, i32)| {
        schematic
            .get_block(position.0, position.1, position.2)
            .is_some_and(|block| mc_tick::vanilla::is_simulation_component(&block.to_string()))
    };
    let mut active = HashSet::new();
    let mut queue = VecDeque::new();

    // A placement into air is not itself available to the selector yet. Seed
    // from active neighbours within the maximum two-cell static interaction
    // link, and treat an active descriptor as a synthetic seed of its own.
    for &position in positions {
        if mc_tick::vanilla::is_simulation_component(descriptor) {
            active.insert(position);
            queue.push_back(position);
        }
        for dx in -LOCAL_COMPONENT_LINK..=LOCAL_COMPONENT_LINK {
            for dy in -LOCAL_COMPONENT_LINK..=LOCAL_COMPONENT_LINK {
                for dz in -LOCAL_COMPONENT_LINK..=LOCAL_COMPONENT_LINK {
                    if dx.abs() + dy.abs() + dz.abs() > LOCAL_COMPONENT_LINK {
                        continue;
                    }
                    let Some(candidate) = position
                        .0
                        .checked_add(dx)
                        .zip(position.1.checked_add(dy))
                        .zip(position.2.checked_add(dz))
                        .map(|((x, y), z)| (x, y, z))
                    else {
                        continue;
                    };
                    if is_active(candidate) && active.insert(candidate) {
                        queue.push_back(candidate);
                    }
                }
            }
        }
    }

    while let Some(position) = queue.pop_front() {
        for dx in -LOCAL_COMPONENT_LINK..=LOCAL_COMPONENT_LINK {
            for dy in -LOCAL_COMPONENT_LINK..=LOCAL_COMPONENT_LINK {
                for dz in -LOCAL_COMPONENT_LINK..=LOCAL_COMPONENT_LINK {
                    if dx.abs() + dy.abs() + dz.abs() > LOCAL_COMPONENT_LINK {
                        continue;
                    }
                    let Some(candidate) = position
                        .0
                        .checked_add(dx)
                        .zip(position.1.checked_add(dy))
                        .zip(position.2.checked_add(dz))
                        .map(|((x, y), z)| (x, y, z))
                    else {
                        continue;
                    };
                    if is_active(candidate) && active.insert(candidate) {
                        queue.push_back(candidate);
                    }
                }
            }
        }
    }

    let is_motion = |descriptor: &str| {
        matches!(
            mc_tick::machine_graph::classify(descriptor),
            mc_tick::machine_graph::PartKind::Piston { .. }
                | mc_tick::machine_graph::PartKind::Slime
                | mc_tick::machine_graph::PartKind::Honey
        ) || descriptor.starts_with("minecraft:moving_piston")
            || descriptor.starts_with("minecraft:piston_head")
    };
    let motion_component = is_motion(descriptor)
        || active.iter().any(|&(x, y, z)| {
            schematic
                .get_block(x, y, z)
                .is_some_and(|block| is_motion(&block.to_string()))
        });
    let effect_margin = if motion_component {
        LOCAL_PISTON_EFFECT_MARGIN
    } else {
        LOCAL_EFFECT_MARGIN
    };

    let mut min = positions[0];
    let mut max = positions[0];
    for &(x, y, z) in positions.iter().chain(active.iter()) {
        min.0 = min.0.min(x);
        min.1 = min.1.min(y);
        min.2 = min.2.min(z);
        max.0 = max.0.max(x);
        max.1 = max.1.max(y);
        max.2 = max.2.max(z);
    }
    let expand = |value: i32, amount: i32, lower: bool| {
        if lower {
            value.saturating_sub(amount)
        } else {
            value.saturating_add(amount)
        }
    };
    let core = crate::BoundingBox::new(
        (
            expand(min.0, effect_margin, true),
            expand(min.1, effect_margin, true),
            expand(min.2, effect_margin, true),
        ),
        (
            expand(max.0, effect_margin, false),
            expand(max.1, effect_margin, false),
            expand(max.2, effect_margin, false),
        ),
    );
    let context = crate::BoundingBox::new(
        (
            expand(core.min.0, LOCAL_CONTEXT_MARGIN, true),
            expand(core.min.1, LOCAL_CONTEXT_MARGIN, true),
            expand(core.min.2, LOCAL_CONTEXT_MARGIN, true),
        ),
        (
            expand(core.max.0, LOCAL_CONTEXT_MARGIN, false),
            expand(core.max.1, LOCAL_CONTEXT_MARGIN, false),
            expand(core.max.2, LOCAL_CONTEXT_MARGIN, false),
        ),
    );
    let dimensions = (
        i64::from(context.max.0) - i64::from(context.min.0) + 1,
        i64::from(context.max.1) - i64::from(context.min.1) + 1,
        i64::from(context.max.2) - i64::from(context.min.2) + 1,
    );
    let volume = dimensions
        .0
        .checked_mul(dimensions.1)
        .and_then(|xy| xy.checked_mul(dimensions.2))
        .unwrap_or(i64::MAX);
    if volume > MAX_VOLUME as i64 {
        return Err(format!(
            "local simulated component is {} x {} x {} = {volume} cells, over the \
             {MAX_VOLUME}-cell limit; split the placement batch by component",
            dimensions.0, dimensions.1, dimensions.2
        ));
    }
    Ok(Some((core, context)))
}

/// Sequentially place blocks in a local simulated component. Runtime depends
/// on the selected component and its propagation, not on unrelated schematic
/// volume. A four-cell context halo is loaded but treated as read-only.
pub(crate) fn simulate_placements_into(
    schematic: &mut crate::UniversalSchematic,
    positions: &[(i32, i32, i32)],
    descriptor: &str,
) -> Result<usize, String> {
    if positions.is_empty() {
        return Ok(0);
    }
    let requested_cells = positions
        .iter()
        .copied()
        .collect::<std::collections::HashSet<_>>()
        .len();
    if schematic.total_blocks() == 0 {
        for &(x, y, z) in positions {
            schematic.set_block_from_string(x, y, z, descriptor)?;
        }
        return Ok(requested_cells);
    }

    // Identity resolvers do not need component bounds at all, which matters
    // for sparse batches whose positions are millions of cells apart.
    if let Some(written) =
        try_resolve_placements(schematic, positions, descriptor, None, requested_cells)?
    {
        return Ok(written);
    }

    let Some((core, context)) = checked_local_bounds(schematic, positions, descriptor)? else {
        return Ok(0);
    };
    if let Some(written) = try_resolve_placements(
        schematic,
        positions,
        descriptor,
        Some(&core),
        requested_cells,
    )? {
        return Ok(written);
    }
    let mut local = schematic.create_schematic_from_region(&context);
    local.metadata = schematic.metadata.clone();
    let local_positions: Vec<(i32, i32, i32)> = positions
        .iter()
        .map(|&(x, y, z)| {
            (
                x.saturating_sub(context.min.0),
                y.saturating_sub(context.min.1),
                z.saturating_sub(context.min.2),
            )
        })
        .collect();
    simulate_placements_into_world(&mut local, &local_positions, descriptor)?;

    let mut written = 0;
    for x in core.min.0..=core.max.0 {
        for y in core.min.1..=core.max.1 {
            for z in core.min.2..=core.max.2 {
                let local_pos = (
                    x.saturating_sub(context.min.0),
                    y.saturating_sub(context.min.1),
                    z.saturating_sub(context.min.2),
                );
                let after = local
                    .get_block(local_pos.0, local_pos.1, local_pos.2)
                    .map(ToString::to_string)
                    .unwrap_or_else(|| "minecraft:air".to_string());
                let before = schematic
                    .get_block(x, y, z)
                    .map(ToString::to_string)
                    .unwrap_or_else(|| "minecraft:air".to_string());
                if before != after {
                    schematic.set_block_from_string(x, y, z, &after)?;
                    written += 1;
                }
            }
        }
    }
    // An explicit hand placement is a touched cell even when its final state
    // equals the one already stored, matching the full-world API's contract.
    Ok(written.max(requested_cells))
}

/// Full-world opt-in: place a block into the entire schematic and let the
/// engine react — connectivity, power, scheduled ticks, all of it — then write
/// every resulting block change back into the schematic.
///
/// The semantics are "a hand placed this block in a loaded world": the rest
/// of the schematic is trusted exactly as saved (`InWorld`), the new block
/// arrives through the engine's `place_block` (vanilla's flag-3 write, so
/// `onPlace` runs and neighbours hear about it), and the world then runs to
/// quiescence. A wire comes out with its real connections and power; a
/// repeater locks or lights; a piston that ends up powered genuinely
/// extends, head and all — the write-back records whatever the world became.
///
/// A placement more than three blocks from everything else can interact with
/// nothing, so it short-circuits to a plain write — which also covers the
/// first block of an empty schematic.
///
/// Returns the number of blocks the write-back touched (at least one: the
/// placed block itself).
pub(crate) fn simulate_placement_into_world(
    schematic: &mut crate::UniversalSchematic,
    x: i32,
    y: i32,
    z: i32,
    descriptor: &str,
) -> Result<usize, String> {
    use mc_tick::Pos;

    // Far from everything (or into an empty schematic): nothing to react.
    let bb = schematic.get_bounding_box();
    let isolated = schematic.total_blocks() == 0 || {
        let (min, max) = (bb.min, bb.max);
        x < min.0 - 3
            || x > max.0 + 3
            || y < min.1 - 3
            || y > max.1 + 3
            || z < min.2 - 3
            || z > max.2 + 3
    };
    if isolated {
        schematic.set_block_from_string(x, y, z, descriptor)?;
        return Ok(1);
    }

    check_volume((
        bb.max.0 - bb.min.0 + 1,
        bb.max.1 - bb.min.1 + 1,
        bb.max.2 - bb.min.2 + 1,
    ))?;

    // The world is the schematic *without* the new block; gametest SNBT
    // rebases everything to the bounding box's low corner, so the engine
    // works in shifted coordinates and the write-back shifts them home.
    let offset = (bb.min.0, bb.min.1, bb.min.2);
    let snbt = to_gametest_snbt(schematic);
    let structure = mc_tick::Structure::parse(&snbt)
        .map_err(|e| format!("simulate=true could not load this schematic: {e:?}"))?;
    let mut sim = wire_simulation(
        &structure,
        Pos::new(0, 0, 0),
        ffi::TickSettleMode::InWorld,
        &[descriptor],
        schematic.metadata.source_data_version,
    )
    .map_err(|e| format!("simulate=true could not simulate this schematic: {e}"))?;

    let state = sim
        .registry_mut()
        .intern(descriptor)
        .map_err(|e| format!("simulate=true: interning {descriptor}: {e:?}"))?;
    let pos = Pos::new(x - offset.0, y - offset.1, z - offset.2);
    let placed_bounds = structure.bounds(4);
    if pos.x < placed_bounds.min.x
        || pos.x > placed_bounds.max.x
        || pos.y < placed_bounds.min.y
        || pos.y > placed_bounds.max.y
        || pos.z < placed_bounds.min.z
        || pos.z > placed_bounds.max.z
    {
        // Inside the 3-block interaction range but outside the engine's
        // padded world — cannot happen while the margin is 4, but a changed
        // margin must fail loudly here rather than panic in the engine.
        return Err("simulate=true: position outside the simulated bounds".to_string());
    }
    sim.record();
    // A *genuine* hand placement: the state derives its shape from the
    // neighbourhood first (a wire arrives connected), then `onPlace` runs
    // (the wire powers, a repeater locks), then the neighbours are told.
    sim.place_block_by_hand(pos, state);
    sim.run_until_quiescent(255);

    // The placed cell first, then every recorded change on top — including
    // the placed cell's own evolved state, and anything the placement set
    // off elsewhere.
    schematic.set_block_from_string(x, y, z, descriptor)?;
    let mut finals: std::collections::HashMap<Pos, mc_tick::StateId> =
        std::collections::HashMap::new();
    for change in sim.recorded() {
        finals.insert(change.pos, change.to);
    }
    let mut written = 1;
    for (cell, state) in finals {
        let descriptor = sim
            .registry()
            .descriptor(state)
            .ok_or_else(|| "simulate=true: a written state with no descriptor".to_string())?;
        schematic.set_block_from_string(
            cell.x + offset.0,
            cell.y + offset.1,
            cell.z + offset.2,
            descriptor,
        )?;
        written += 1;
    }
    Ok(written)
}

/// Sequentially hand-place one descriptor at many positions in a single live
/// simulated world, settling after every placement and baking the final block
/// states back once.
///
/// This is the amortized counterpart to repeated `{simulate=true}` calls.
/// Repeated calls rebuild the structure, registry, behaviour tables, physics
/// tables, and world every time; this pays that O(world volume) setup once.
/// The update work itself cannot be constant-time because a placement may
/// propagate through an arbitrarily large redstone network or move structures.
pub(crate) fn simulate_placements_into_world(
    schematic: &mut crate::UniversalSchematic,
    positions: &[(i32, i32, i32)],
    descriptor: &str,
) -> Result<usize, String> {
    use mc_tick::Pos;
    use std::collections::HashMap;

    if positions.is_empty() {
        return Ok(0);
    }
    if positions.len() == 1 {
        let (x, y, z) = positions[0];
        return simulate_placement_into_world(schematic, x, y, z, descriptor);
    }

    let bb = schematic.get_bounding_box();
    let mut min = bb.min;
    let mut max = bb.max;
    for &(x, y, z) in positions {
        min.0 = min.0.min(x);
        min.1 = min.1.min(y);
        min.2 = min.2.min(z);
        max.0 = max.0.max(x);
        max.1 = max.1.max(y);
        max.2 = max.2.max(z);
    }
    let dimensions = (
        i64::from(max.0) - i64::from(min.0) + 1,
        i64::from(max.1) - i64::from(min.1) + 1,
        i64::from(max.2) - i64::from(min.2) + 1,
    );
    let volume = dimensions
        .0
        .checked_mul(dimensions.1)
        .and_then(|xy| xy.checked_mul(dimensions.2))
        .unwrap_or(i64::MAX);
    if volume > MAX_VOLUME as i64 {
        return Err(format!(
            "simulated placement span is {} x {} x {} = {volume} cells, over the \
             {MAX_VOLUME}-cell limit",
            dimensions.0, dimensions.1, dimensions.2
        ));
    }

    // The structure renderer rebases the schematic's current minimum to zero.
    // Keep that stable while the live world grows around sequential placements.
    let offset = bb.min;
    let snbt = to_gametest_snbt(schematic);
    let structure = mc_tick::Structure::parse(&snbt)
        .map_err(|e| format!("simulated batch could not load this schematic: {e:?}"))?;
    let mut sim = wire_simulation(
        &structure,
        Pos::new(0, 0, 0),
        ffi::TickSettleMode::InWorld,
        &[descriptor],
        schematic.metadata.source_data_version,
    )
    .map_err(|e| format!("simulated batch could not simulate this schematic: {e}"))?;
    let state = sim
        .registry()
        .get(descriptor)
        .ok_or_else(|| format!("simulated batch did not intern `{descriptor}`"))?;

    // wire_simulation records construction/settle changes for other callers.
    // This operation wants only changes caused by the requested placements.
    sim.clear_recorded();
    let mut placed = Vec::with_capacity(positions.len());
    for &(x, y, z) in positions {
        let pos = Pos::new(
            x.checked_sub(offset.0)
                .ok_or("simulated x coordinate overflow")?,
            y.checked_sub(offset.1)
                .ok_or("simulated y coordinate overflow")?,
            z.checked_sub(offset.2)
                .ok_or("simulated z coordinate overflow")?,
        );
        sim.place_block_by_hand(pos, state);
        sim.run_until_quiescent(255);
        placed.push(pos);
    }

    // Last write wins at each changed cell. Explicitly include each requested
    // cell as well: a placement whose final state equals its prior state may
    // legitimately produce no change record, but it was still requested.
    let mut finals: HashMap<Pos, mc_tick::StateId> = HashMap::new();
    for change in sim.recorded() {
        finals.insert(change.pos, change.to);
    }
    for pos in placed {
        finals.insert(pos, sim.world().get(pos));
    }

    let written = finals.len();
    for (cell, state) in finals {
        let block = sim
            .registry()
            .descriptor(state)
            .ok_or_else(|| "simulated batch produced a state with no descriptor".to_string())?;
        let x = cell
            .x
            .checked_add(offset.0)
            .ok_or("simulated write-back x overflow")?;
        let y = cell
            .y
            .checked_add(offset.1)
            .ok_or("simulated write-back y overflow")?;
        let z = cell
            .z
            .checked_add(offset.2)
            .ok_or("simulated write-back z overflow")?;
        schematic.set_block_from_string(x, y, z, block)?;
    }
    Ok(written)
}

/// Whether a block's simulated behaviour depends on block-entity data.
///
/// Only the ones whose *absence changes the run*: a comparator without
/// `OutputSignal` reads 0, a container without `Items` is empty and so reads
/// 0 through a comparator and has nothing to transfer. Signs, banners and
/// heads carry block entities too, and losing them changes nothing that
/// ticks — listing them would bury the two that matter.
fn needs_block_entity(name: &str) -> bool {
    let short = name.strip_prefix("minecraft:").unwrap_or(name);
    matches!(
        short,
        "comparator"
            | "chest"
            | "trapped_chest"
            | "barrel"
            | "hopper"
            | "dropper"
            | "dispenser"
            | "furnace"
            | "blast_furnace"
            | "smoker"
            | "brewing_stand"
            | "crafter"
            | "chiseled_bookshelf"
            | "jukebox"
            | "lectern"
            | "decorated_pot"
    ) || short.ends_with("shulker_box")
}

/// See [`ffi::TickSimulation::block_entity_audit_json`].
fn block_entity_audit(schematic: &crate::UniversalSchematic) -> String {
    use std::collections::{HashMap, HashSet};
    use std::fmt::Write as _;

    let have: HashSet<(i32, i32, i32)> = schematic
        .get_block_entities_as_list()
        .into_iter()
        .map(|be| be.position)
        .collect();

    let mut missing: HashMap<String, u32> = HashMap::new();
    for (pos, state) in schematic.iter_blocks() {
        if !needs_block_entity(&state.name) {
            continue;
        }
        if !have.contains(&(pos.x, pos.y, pos.z)) {
            *missing.entry(state.name.to_string()).or_default() += 1;
        }
    }

    let mut rows: Vec<(String, u32)> = missing.into_iter().collect();
    // Descending count, then name — a stable order so two runs of the same
    // file produce byte-identical JSON.
    rows.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    let total: u32 = rows.iter().map(|(_, n)| *n).sum();

    let mut json = String::from("{\"present\":");
    let _ = write!(json, "{}", have.len());
    let _ = write!(json, ",\"missing_total\":{total},\"missing\":[");
    for (i, (name, count)) in rows.iter().enumerate() {
        if i > 0 {
            json.push(',');
        }
        let _ = write!(json, "{{\"name\":\"{name}\",\"count\":{count}}}");
    }
    json.push_str("],\"summary\":\"");
    if total > 0 {
        let named: Vec<String> = rows
            .iter()
            .take(3)
            .map(|(name, count)| {
                let short = name.strip_prefix("minecraft:").unwrap_or(name);
                let plural = if *count == 1 { "" } else { "s" };
                format!("{count} {short}{plural}")
            })
            .collect();
        let more = if rows.len() > 3 { ", and others" } else { "" };
        let _ = write!(
            json,
            "This schematic contains {}{} with no block-entity data. \
             Comparator outputs and container contents are simulated as empty, \
             so results may not reflect the original build.",
            named.join(", "),
            more
        );
    }
    json.push_str("\"}");
    json
}

/// The sentence shown to whoever is holding a structure that will not load.
///
/// Two very different failures reach the same `parse` call and they need
/// opposite answers. An unsupported entity means their *build* names something
/// the engine cannot model — nothing is wrong with the file, so it is reported
/// by name and without blame. Anything else means the text itself is bad;
/// when we generated that text (`converted`), that is our bug and saying so
/// keeps us from accusing a perfectly good upload.
fn structure_parse_detail(error: &mc_tick::structure::StructureError, converted: bool) -> String {
    if let mc_tick::structure::StructureError::UnsupportedEntity { entity_type, .. } = error {
        return format!(
            "this build contains a `{entity_type}` entity, which the engine cannot simulate \
             yet — loading it would mean dropping the entity, and a run without it would not \
             match the real build"
        );
    }
    if converted {
        format!(
            "converted structure did not parse: {error:?} — this is an engine fault, \
             not a problem with the uploaded file"
        )
    } else {
        format!("structure SNBT did not parse: {error:?}")
    }
}

/// Serialise recorded updates for ticks in `[from, to)`.
///
/// Shared by the whole-log and per-tick-range accessors so both emit exactly
/// one schema. `state` is the block at dispatch time, not at the tick boundary.
fn updates_json_range(sim: &mc_tick::Simulation, from: u64, to: u64) -> String {
    use std::fmt::Write as _;
    let mut json = String::from("[");
    let mut first = true;
    for update in sim.recorded_updates() {
        if update.tick < from || update.tick >= to {
            continue;
        }
        if !first {
            json.push(',');
        }
        first = false;
        let state = sim
            .registry()
            .descriptor(update.state)
            .unwrap_or("minecraft:air");
        let kind = match update.kind {
            mc_tick::UpdateKind::Neighbor => "neighbor",
            mc_tick::UpdateKind::Shape => "shape",
        };
        // No phase means a boundary dispatch: placement, a click, a break —
        // the server loop rather than a phase of the tick.
        let phase = update.phase.map_or("boundary", |p| p.name());
        let _ = write!(
            json,
            "{{\"tick\":{},\"seq\":{},\"pos\":[{},{},{}],\"from\":\"{:?}\",\"kind\":\"{}\",\"phase\":\"{}\",\"state\":\"{}\"}}",
            update.tick,
            update.seq,
            update.pos.x,
            update.pos.y,
            update.pos.z,
            update.from,
            kind,
            phase,
            state
        );
    }
    json.push(']');
    json
}

/// One detected cycle as `{"start":T,"end":T,"period":N,"drift":[x,y,z]}`, or
/// `null` when none was found — a build with no recurrence is normal, not an
/// error.
fn cycle_json(cycle: Option<mc_tick::Cycle>) -> String {
    match cycle {
        None => "null".to_string(),
        Some(c) => format!(
            "{{\"start\":{},\"end\":{},\"period\":{},\"drift\":[{},{},{}]}}",
            c.start_tick, c.end_tick, c.period, c.drift.x, c.drift.y, c.drift.z
        ),
    }
}

/// The phase legend shared by the compact update views: index 0 is a boundary
/// dispatch (outside the phase walk), then [`mc_tick::PHASE_ORDER`].
fn phase_legend() -> Vec<&'static str> {
    let mut names = vec!["boundary"];
    names.extend(mc_tick::PHASE_ORDER.iter().map(|p| p.name()));
    names
}

/// A record's index into [`phase_legend`].
fn phase_code(update: &mc_tick::UpdateRecord) -> usize {
    match update.phase {
        None => 0,
        Some(phase) => mc_tick::PHASE_ORDER
            .iter()
            .position(|p| *p == phase)
            .map_or(0, |i| i + 1),
    }
}

/// A direction's index into [`mc_tick::ALL_DIRS`].
fn dir_code(dir: mc_tick::Dir) -> usize {
    mc_tick::ALL_DIRS
        .iter()
        .position(|d| *d == dir)
        .unwrap_or(0)
}

/// Per-tick, per-cell update counts — the resolution playback runs at.
///
/// The raw log is unusable for a UI: one tick of a 6x6 door is ~20k updates and
/// megabytes of JSON, and twenty thousand individual flares are not legible
/// anyway. Collapsing to "which cells lit up this tick, and how hot" turns that
/// into a few hundred rows while keeping the two breakdowns worth colouring by.
fn updates_heat_range(sim: &mc_tick::Simulation, from: u64, to: u64) -> String {
    use std::collections::BTreeMap;
    use std::fmt::Write as _;

    let phases = phase_legend();
    // BTreeMap so ticks and cells come out in a stable, sorted order.
    let mut per_tick: BTreeMap<u64, BTreeMap<(i32, i32, i32), (u32, u32, u32, Vec<u32>)>> =
        BTreeMap::new();
    for update in sim.recorded_updates() {
        if update.tick < from || update.tick >= to {
            continue;
        }
        let cells = per_tick.entry(update.tick).or_default();
        let cell = cells
            .entry((update.pos.x, update.pos.y, update.pos.z))
            .or_insert_with(|| (0, 0, 0, vec![0; phases.len()]));
        cell.0 += 1;
        match update.kind {
            mc_tick::UpdateKind::Neighbor => cell.1 += 1,
            mc_tick::UpdateKind::Shape => cell.2 += 1,
        }
        cell.3[phase_code(update)] += 1;
    }

    let mut json = String::from("{\"phases\":[");
    for (i, name) in phases.iter().enumerate() {
        let _ = write!(json, "{}\"{name}\"", if i > 0 { "," } else { "" });
    }
    json.push_str("],\"ticks\":[");
    for (i, (tick, cells)) in per_tick.iter().enumerate() {
        if i > 0 {
            json.push(',');
        }
        let total: u32 = cells.values().map(|c| c.0).sum();
        let _ = write!(json, "{{\"tick\":{tick},\"total\":{total},\"cells\":[");
        for (j, ((x, y, z), (n, nb, sh, ph))) in cells.iter().enumerate() {
            if j > 0 {
                json.push(',');
            }
            let _ = write!(
                json,
                "{{\"p\":[{x},{y},{z}],\"n\":{n},\"nb\":{nb},\"sh\":{sh},\"ph\":["
            );
            for (k, count) in ph.iter().enumerate() {
                let _ = write!(json, "{}{count}", if k > 0 { "," } else { "" });
            }
            json.push_str("]}");
        }
        json.push_str("]}");
    }
    json.push_str("]}");
    json
}

/// One tick's updates in delivery order, as parallel arrays.
///
/// The wavefront resolution: everything the raw log has for a single tick, but
/// without repeating a field name per record. `seq` is the array index; every
/// small enum is an integer code with its legend in the payload; and the
/// dispatch-time state is an index into a deduplicated table, which is where
/// most of the saving comes from — a tick touches thousands of cells but only
/// tens of distinct states.
fn updates_wave(sim: &mc_tick::Simulation, tick: u64) -> String {
    use std::collections::HashMap;
    use std::fmt::Write as _;

    let mut pos = String::new();
    let mut kinds = String::new();
    let mut phases_arr = String::new();
    let mut froms = String::new();
    let mut states_arr = String::new();
    let mut table: Vec<&str> = Vec::new();
    let mut seen: HashMap<mc_tick::StateId, usize> = HashMap::new();
    let mut n = 0usize;

    for update in sim.recorded_updates() {
        if update.tick != tick {
            continue;
        }
        let sep = if n > 0 { "," } else { "" };
        let _ = write!(
            pos,
            "{sep}{},{},{}",
            update.pos.x, update.pos.y, update.pos.z
        );
        let _ = write!(
            kinds,
            "{sep}{}",
            match update.kind {
                mc_tick::UpdateKind::Neighbor => 0,
                mc_tick::UpdateKind::Shape => 1,
            }
        );
        let _ = write!(phases_arr, "{sep}{}", phase_code(update));
        let _ = write!(froms, "{sep}{}", dir_code(update.from));
        let index = *seen.entry(update.state).or_insert_with(|| {
            table.push(
                sim.registry()
                    .descriptor(update.state)
                    .unwrap_or("minecraft:air"),
            );
            table.len() - 1
        });
        let _ = write!(states_arr, "{sep}{index}");
        n += 1;
    }

    let mut json = String::new();
    let _ = write!(
        json,
        "{{\"tick\":{tick},\"n\":{n},\"pos\":[{pos}],\"kind\":[{kinds}],"
    );
    let _ = write!(
        json,
        "\"phase\":[{phases_arr}],\"from\":[{froms}],\"state\":[{states_arr}],"
    );
    json.push_str("\"states\":[");
    for (i, descriptor) in table.iter().enumerate() {
        let _ = write!(json, "{}\"{descriptor}\"", if i > 0 { "," } else { "" });
    }
    json.push_str("],\"phases\":[");
    for (i, name) in phase_legend().iter().enumerate() {
        let _ = write!(json, "{}\"{name}\"", if i > 0 { "," } else { "" });
    }
    json.push_str("],\"dirs\":[");
    for (i, dir) in mc_tick::ALL_DIRS.iter().enumerate() {
        let _ = write!(json, "{}\"{dir:?}\"", if i > 0 { "," } else { "" });
    }
    json.push_str("],\"kinds\":[\"neighbor\",\"shape\"]}");
    json
}

/// Largest build the simulator will accept, in cells.
///
/// `IRIS_B.schem` is 499x379x442 — 83.5 million cells, a saved world rather
/// than a door. Loading one exhausts the wasm heap, and a Rust OOM in wasm is
/// an `unreachable` trap that poisons the whole instance: every later call on
/// it traps too, so one oversized upload takes down every door after it. Eight
/// million cells is roughly a 200-cube, far past any real door and well inside
/// what the heap survives.
const MAX_VOLUME: usize = 8_000_000;

/// Why the last constructor failed. Set on every failure path, cleared on
/// success, read back through `TickSimulation::last_error_detail` — and,
/// because the store is bridge-wide, through `NucleationError::detail` on the
/// caught error itself.
fn set_last_error(detail: impl Into<String>) {
    crate::bridge::set_last_error_detail(detail);
}

fn clear_last_error() {
    crate::bridge::clear_last_error_detail();
}

/// Refuse a build too large to load before allocating for it.
fn check_volume(size: (i32, i32, i32)) -> Result<(), String> {
    let volume = (size.0 as i64) * (size.1 as i64) * (size.2 as i64);
    if volume > MAX_VOLUME as i64 {
        return Err(format!(
            "build is {} x {} x {} = {volume} cells, over the {MAX_VOLUME}-cell limit — \
             this looks like a saved world rather than a contraption",
            size.0, size.1, size.2
        ));
    }
    Ok(())
}

pub(crate) fn wire_simulation(
    structure: &mc_tick::Structure,
    hash_origin: mc_tick::Pos,
    settle: ffi::TickSettleMode,
    extra_states: &[&str],
    source_data_version: Option<i32>,
) -> Result<mc_tick::Simulation, String> {
    use mc_tick::{Pos, Simulation};
    const MARGIN: i32 = 4;

    let mut sim = Simulation::new(structure.bounds(MARGIN));
    {
        let (registry, world) = sim.registry_and_world_mut();
        structure.place(world, registry, Pos::new(0, 0, 0));
    }
    // Which game's `Entity.load` these entities came through.
    //
    // The blocks in `structure` have been converted to the canonical data
    // version; the *entities* have not been reinterpreted, and whether a NaN
    // velocity survives being read is decided by the version of the save it
    // was read from. `Motion` handling changed at 1.21.11, and the record 3x3
    // door is 1.21.3 — under the new rules its nan carts do not exist. Only
    // the caller knows the source version, which is why it is a parameter and
    // not something the engine tries to infer. See [`mc_tick::MotionSemantics`].
    if let Some(version) = source_data_version {
        sim.set_motion_semantics(mc_tick::MotionSemantics::for_data_version(version));
    }
    // The universal actuator, plus anything the caller names.
    let mut wanted: Vec<String> = vec!["minecraft:redstone_block".to_string()];
    wanted.extend(extra_states.iter().map(|s| s.to_string()));
    // A dispenser can *place* a block it holds as an item — a shulker box, or a
    // bucket's contents. Behaviours bind only to interned states, and those
    // states are by definition absent from the build's own palette.
    for (_, stacks) in &structure.inventories {
        for stack in stacks {
            wanted.extend(mc_tick::vanilla::dispensable_states(&stack.id));
        }
    }
    for descriptor in &wanted {
        sim.registry_mut()
            .intern(descriptor)
            .map_err(|e| format!("interning {descriptor}: {e:?}"))?;
    }
    for pos in &structure.block_entities {
        sim.mark_block_entity(*pos);
    }
    for (pos, strength) in &structure.comparator_outputs {
        sim.set_comparator_output(*pos, *strength);
    }
    for (pos, stacks) in &structure.inventories {
        let entry = structure
            .blocks
            .iter()
            .find(|(p, _)| p == pos)
            .map(|(_, e)| *e)
            .ok_or_else(|| format!("inventory at {pos:?} with no block"))?;
        let name = structure.palette[entry]
            .split('[')
            .next()
            .unwrap_or_default()
            .to_string();
        let slots = mc_tick::vanilla::container_slots(&name)
            .ok_or_else(|| format!("{name} has an inventory but no slot count"))?;
        sim.set_inventory(
            *pos,
            mc_tick::Inventory {
                slots,
                stacks: stacks.clone(),
                blocked_slots: structure.blocked_slots_at(*pos),
            },
        );
    }
    mc_tick::intern_companions(sim.registry_mut());
    {
        let mut table = std::mem::take(sim.behaviours_mut());
        mc_tick::register_all_at(sim.registry_mut(), &mut table, hash_origin);
        *sim.behaviours_mut() = table;
    }
    if let Some(report) = sim.unknown_report() {
        return Err(format!("blocks without behaviour: {report}"));
    }
    {
        let (solidity, frictions, heights, webs) = mc_tick::vanilla::physics_tables(sim.registry());
        sim.set_physics_tables(solidity, frictions, heights, webs);
        let (water_kinds, bubble_kinds) = mc_tick::vanilla::fluid_tables(sim.registry());
        sim.set_fluid_tables(water_kinds, bubble_kinds);
        let (rails, conductors) = mc_tick::vanilla::rail_tables(sim.registry());
        sim.set_rail_tables(rails, conductors);
    }
    // Entities the parser can read but the engine cannot yet run.
    //
    // This is the entity half of the `unknown_report` gate above: a build is
    // refused whole rather than simulated with pieces missing. It lives here,
    // at construction, rather than in the parser, because "can this be read"
    // and "is there a behaviour for it" are different questions — the parser
    // answering both meant the behaviours agent could not even load a villager
    // to develop against.
    //
    // The match is deliberately exhaustive with no catch-all: a new
    // `SpawnedEntity` variant will fail to compile here until someone decides
    // whether it can be simulated. That is the whole point of the split — the
    // gate cannot silently fall out of date.
    // Every arm below either spawns or records a refusal. The match has no
    // catch-all on purpose: a new `SpawnedEntity` variant fails to compile here
    // until someone decides whether it can be simulated, so the gate cannot
    // silently fall out of date.
    let mut refused: Vec<String> = Vec::new();
    for spawned in &structure.entities {
        match spawned {
            mc_tick::structure::SpawnedEntity::Item(item) => {
                sim.spawn_item(item.item.clone(), item.pos, item.motion, item.pickup_delay);
            }
            mc_tick::structure::SpawnedEntity::Minecart(cart) => {
                let vehicle = sim.spawn_authored_minecart(cart, None);
                // Riders are seated immediately after their vehicle, so a
                // capture's ids line up and so the rider cannot outlive a
                // vehicle that failed to spawn.
                for rider in &cart.passengers {
                    if let Err(why) = sim.spawn_authored_rider(vehicle, rider) {
                        refused.push(why);
                    }
                }
            }
            // A furnace cart is dimensionally an ordinary cart, so an
            // *unfuelled* one needs nothing more than being a cart. A fuelled
            // one drives itself and is refused rather than run as a passenger.
            mc_tick::structure::SpawnedEntity::FurnaceMinecart(cart) => {
                if let Err(why) = sim.spawn_authored_furnace_minecart(cart, None) {
                    refused.push(why);
                }
            }
            // Fireballs and villagers exist in the record doors as scaffolding:
            // a hitbox a pressure plate can see and a piston can shove. That is
            // all that is implemented, and anything that would need more — a
            // fireball with velocity, a villager that should walk — refuses by
            // name rather than being quietly frozen.
            // A blaze reached here is one standing on its own, not riding — a
            // rider is spawned by its vehicle's arm above and never appears in
            // this list. Standing alone it is scaffolding like a villager, and a
            // blaze that should fly or fight refuses by name.
            mc_tick::structure::SpawnedEntity::Body(body) => match sim.spawn_authored_body(body) {
                Ok(vehicle) => {
                    for rider in &body.passengers {
                        if let Err(why) = sim.spawn_authored_rider(vehicle, rider) {
                            refused.push(why);
                        }
                    }
                }
                Err(why) => {
                    refused.push(why);
                }
            },
        }
    }
    if !refused.is_empty() {
        return Err(format!(
            "{} entit{} in this build need behaviour that is not implemented, and the \
             build is refused rather than simulated with them standing still:\n  - {}",
            refused.len(),
            if refused.len() == 1 { "y" } else { "ies" },
            refused.join("\n  - ")
        ));
    }
    for (pos, entry) in &structure.blocks {
        let state = sim.registry().get(&structure.palette[*entry]);
        let is_ticker = state
            .and_then(|s| sim.behaviours().get(s))
            .is_some_and(|b| b.ticks_as_block_entity());
        if is_ticker {
            sim.add_block_entity_ticker(*pos);
        }
    }
    let order = structure.placement_order(
        mc_tick::vanilla::is_collision_full_cube,
        mc_tick::vanilla::has_dynamic_shape,
    );
    if settle != ffi::TickSettleMode::InWorld {
        sim.place_on_place(&order);
    }
    if settle == ffi::TickSettleMode::Placement {
        sim.settle_with_order(&order);
    }
    sim.record();
    Ok(sim)
}

fn is_named(descriptor: &str, needle: &str) -> bool {
    descriptor
        .split('[')
        .next()
        .unwrap_or(descriptor)
        .contains(needle)
}

/// One pass over the world: (non-air count, center-of-mass x, min x, max x).
fn non_air_stats(sim: &mc_tick::Simulation) -> (u32, f64, i32, i32) {
    let mut n = 0u32;
    let mut sum = 0.0;
    let mut min = i32::MAX;
    let mut max = i32::MIN;
    for (pos, _) in sim.world().iter_non_air() {
        n += 1;
        sum += f64::from(pos.x);
        if pos.x < min {
            min = pos.x;
        }
        if pos.x > max {
            max = pos.x;
        }
    }
    (
        n,
        if n == 0 { f64::NAN } else { sum / f64::from(n) },
        min,
        max,
    )
}

/// Build a Structure directly from a flat genome-cell array — the GA fast
/// path, no SNBT text. Layout mirrors the flying-ga corridor: machine at
/// `x_off`, world size `[bx + travel, by + 2, bz + 2]`, cells flattened as
/// `((y * bz) + z) * bx + x`, `air` the palette index meaning empty. The
/// full palette rides along (indices are alphabet indices verbatim), so
/// behaviours bind to every alphabet state exactly as the SNBT path did via
/// its EXTRA_STATES list.
fn structure_from_blocks(
    bx: i32,
    by: i32,
    bz: i32,
    travel: i32,
    x_off: i32,
    palette: &[String],
    cells: &[u16],
    air: u16,
) -> Result<mc_tick::Structure, String> {
    let volume = (bx.max(0) as usize) * (by.max(0) as usize) * (bz.max(0) as usize);
    if cells.len() != volume {
        return Err(format!("cells len {} != bbox volume {volume}", cells.len()));
    }
    let mut blocks = Vec::new();
    let mut i = 0usize;
    for _y in 0..by {
        for _z in 0..bz {
            for _x in 0..bx {
                let s = cells[i];
                let (x, y, z) = (_x, _y, _z);
                i += 1;
                if s == air {
                    continue;
                }
                if s as usize >= palette.len() {
                    return Err(format!("palette index {s} out of range"));
                }
                blocks.push((mc_tick::Pos::new(x + x_off, y, z), s as usize));
            }
        }
    }
    Ok(mc_tick::Structure {
        // Genome cells, not a save: there is no file and so no version to
        // report. The caller's own default decides Motion semantics, and this
        // path authors no entities for it to apply to.
        data_version: None,
        size: (bx + travel, by + 2, bz + 2),
        palette: palette.to_vec(),
        blocks,
        inventories: Vec::new(),
        inventory_blocked_slots: Vec::new(),
        comparator_outputs: Vec::new(),
        block_entities: Vec::new(),
        entities: Vec::new(),
        item_entities: Vec::new(),
        // Genome cells carry no command blocks.
        commands: Vec::new(),
    })
}

/// The modal gait period from min-x rise gaps — bit-identical port of the
/// app's `modalGap` (mode, ties to the smaller gap, modal share >= 0.6).
fn modal_gap(gaps: &[u32]) -> u32 {
    if gaps.len() < 3 {
        return 0;
    }
    let mut order: Vec<u32> = Vec::new();
    let mut counts: Vec<u32> = Vec::new();
    for &g in gaps {
        match order.iter().position(|&o| o == g) {
            Some(i) => counts[i] += 1,
            None => {
                order.push(g);
                counts.push(1);
            }
        }
    }
    let mut best = 0u32;
    let mut best_gap: Option<u32> = None;
    for (i, &g) in order.iter().enumerate() {
        let n = counts[i];
        if n > best || (n == best && best_gap.is_some_and(|b| g < b)) {
            best = n;
            best_gap = Some(g);
        }
    }
    match best_gap {
        Some(g) if (best as f64) / (gaps.len() as f64) >= 0.6 => g,
        _ => 0,
    }
}

/// One kicked flight, mirroring the app's `evalCore.fly` exactly: quiet
/// settle at construction, redstone-block kick at tick 2 removed at tick 4,
/// the same probe schedule (must-move deadline, mid-window centre of mass),
/// optional in-eval gait detection over the last 120 ticks, and an optional
/// early exit for machines that are provably frozen — quiescent and unmoved
/// at tick 40, where every later scalar equals the tick-40 scalar, so the
/// shortcut changes wall time and nothing else.
///
/// Row layout: `[n0, startCom, startMinX, startMaxX, comAtMoveCheck(NaN =
/// no deadline), comAtMid, period, n1, endCom, endMinX, endMaxX]`.
#[allow(clippy::too_many_arguments)]
fn fly_metrics(
    structure: &mc_tick::Structure,
    extras: &[&str],
    kick: (i32, i32, i32),
    eval_ticks: u32,
    seed: i64,
    must_move_by_tick: i32,
    need_period: bool,
    early_exit: bool,
) -> Result<[f64; 11], String> {
    let mut sim = wire_simulation(
        structure,
        mc_tick::Pos::new(0, 0, 0),
        ffi::TickSettleMode::Quiet,
        extras,
        // SNBT in, and the bridge emits the canonical DataVersion — there is no
        // source version to read here. `None` keeps the engine's default,
        // which is the version every captured trace came from.
        None,
    )?;
    fly_on(
        &mut sim,
        kick,
        eval_ticks,
        seed,
        must_move_by_tick,
        need_period,
        early_exit,
    )
}

/// The flight itself, on an already-wired sim (fresh, quiet-settled).
#[allow(clippy::too_many_arguments)]
fn fly_on(
    sim: &mut mc_tick::Simulation,
    kick: (i32, i32, i32),
    eval_ticks: u32,
    seed: i64,
    must_move_by_tick: i32,
    need_period: bool,
    early_exit: bool,
) -> Result<[f64; 11], String> {
    const PERIOD_WINDOW: u32 = 120;
    const EARLY_TICK: u32 = 40;
    sim.set_rng_seed(seed);

    let (n0, start_com, start_min, start_max) = non_air_stats(sim);
    let mut row = [f64::NAN; 11];
    row[0] = f64::from(n0);
    row[1] = start_com;
    row[2] = f64::from(start_min);
    row[3] = f64::from(start_max);
    if n0 == 0 {
        return Ok(row); // the caller short-circuits on n0 before reading on
    }

    let redstone = sim
        .registry()
        .get("minecraft:redstone_block")
        .ok_or("redstone_block not interned")?;
    let kick_pos = mc_tick::Pos::new(kick.0, kick.1, kick.2);
    sim.run(2);
    sim.place_block(kick_pos, redstone);
    sim.run(2);
    sim.place_block(kick_pos, mc_tick::StateId::AIR);
    let mut elapsed: u32 = 4;

    let mid_tick = eval_ticks.min((eval_ticks / 2).max(elapsed));
    let move_check: Option<u32> = if must_move_by_tick >= 0 {
        Some((must_move_by_tick as u32).max(elapsed).min(eval_ticks))
    } else {
        None
    };
    let mut probes: Vec<u32> = Vec::new();
    if let Some(mc) = move_check {
        probes.push(mc);
    }
    probes.push(mid_tick);
    if early_exit && eval_ticks > EARLY_TICK {
        probes.push(EARLY_TICK.max(elapsed));
    }
    probes.sort_unstable();
    probes.dedup();

    let mut com_mid = start_com;
    let mut com_move = f64::NAN;
    let mut frozen = false;
    for &t in &probes {
        if t > elapsed {
            sim.run(u64::from(t - elapsed));
            elapsed = t;
        }
        let (_, com, _, _) = non_air_stats(&sim);
        if Some(t) == move_check {
            com_move = com;
        }
        if t == mid_tick {
            com_mid = com;
        }
        if early_exit && t == EARLY_TICK && sim.is_quiescent() && (com - start_com).abs() < 0.25 {
            frozen = true;
            if mid_tick > t {
                com_mid = com;
            }
            if let Some(mc) = move_check {
                if mc > t && com_move.is_nan() {
                    com_move = com;
                }
            }
            break;
        }
    }

    let mut period = 0u32;
    if need_period && !frozen {
        let win_start = elapsed.max(eval_ticks.saturating_sub(PERIOD_WINDOW));
        if win_start > elapsed {
            sim.run(u64::from(win_start - elapsed));
            elapsed = win_start;
        }
        let mut gaps: Vec<u32> = Vec::new();
        let (_, _, mut prev_min, _) = non_air_stats(&sim);
        let mut last_rise: i64 = -1;
        while elapsed < eval_ticks {
            sim.run(1);
            elapsed += 1;
            let (_, _, mx, _) = non_air_stats(&sim);
            if mx > prev_min {
                if last_rise >= 0 {
                    gaps.push(elapsed - last_rise as u32);
                }
                last_rise = i64::from(elapsed);
            }
            prev_min = mx;
        }
        period = modal_gap(&gaps);
    }
    if !frozen && eval_ticks > elapsed {
        sim.run(u64::from(eval_ticks - elapsed));
    }

    let (n1, end_com, end_min, end_max) = non_air_stats(&sim);
    row[4] = com_move;
    row[5] = com_mid;
    row[6] = f64::from(period);
    row[7] = f64::from(n1);
    row[8] = end_com;
    row[9] = f64::from(end_min);
    row[10] = f64::from(end_max);
    Ok(row)
}

#[diplomat::bridge]
pub mod ffi {
    use super::super::schematic::ffi::Schematic;
    use super::super::shared::ffi::NucleationError;
    use diplomat_runtime::{DiplomatStr, DiplomatWrite};
    use std::fmt::Write;

    /// How the loaded structure is settled before tick 0.
    #[derive(PartialEq, Eq)]
    pub enum TickSettleMode {
        /// Vanilla placement pass + ordered settle — a build saved at rest.
        Placement,
        /// `onPlace` only, no settle — a knownShape capture.
        Quiet,
        /// Neither — a build recorded mid-state in the world it stood in.
        InWorld,
    }

    /// A headless, vanilla-accurate tick simulation of one structure.
    #[diplomat::opaque_mut]
    pub struct TickSimulation {
        pub(crate) sim: mc_tick::Simulation,
        pub(crate) checkpoints: Vec<mc_tick::sim::Checkpoint>,
        /// The span the last [`TickSimulation::stop_timeline`] ended.
        ///
        /// Stop must end a recording *and keep it*: a host's Stop button leaves
        /// the span selectable and exportable, which it cannot be if stopping
        /// threw it away.
        pub(crate) stopped_timeline: Option<mc_tick::timeline::RunTimeline>,
    }

    impl TickSimulation {
        /// Why the last constructor on this thread failed, in words.
        ///
        /// The enum cannot carry a message, and "Simulation" is useless to
        /// someone holding a door that will not load: the engine already knows
        /// it is `minecraft:waxed_copper_bulb` at (4,2,1) and says so here.
        /// Empty when the last construction succeeded.
        pub fn last_error_detail(out: &mut DiplomatWrite) {
            let _ = write!(out, "{}", crate::bridge::last_error_detail());
        }

        /// Largest build this will attempt, in cells.
        ///
        /// A 500x379x442 "door" is a saved world, and loading one exhausts the
        /// wasm heap — after which every later call on that instance traps,
        /// not just the one that overflowed. Refused up front instead.
        pub fn max_volume() -> u32 {
            super::MAX_VOLUME as u32
        }

        /// Load from Java structure SNBT text.
        ///
        /// `extra_states`: semicolon-separated block-state descriptors that
        /// later `place_block` calls may write (behaviours bind at
        /// construction). `minecraft:redstone_block` is always available.
        /// `origin_*`: where the build's (0,0,0) sits in world coordinates —
        /// wire update order hashes absolute positions.
        ///
        /// The text's own `DataVersion` selects `Entity.load` Motion semantics,
        /// exactly as [`TickSimulation::from_schematic`] uses the schematic's —
        /// so `gametest_snbt` → `from_snbt` keeps a nan-cart build's NaN
        /// velocities instead of quietly sanitising them. A text with no
        /// `DataVersion` gets the engine default (the modern, NaN-dropping
        /// rule); read [`TickSimulation::motion_semantics`] to see which
        /// applied.
        pub fn from_snbt(
            snbt: &DiplomatStr,
            settle: TickSettleMode,
            origin_x: i32,
            origin_y: i32,
            origin_z: i32,
            extra_states: &DiplomatStr,
        ) -> Result<Box<TickSimulation>, NucleationError> {
            super::clear_last_error();
            let snbt = std::str::from_utf8(snbt).map_err(|_| {
                super::set_last_error("snbt is not valid UTF-8");
                NucleationError::InvalidArgument
            })?;
            let extra = std::str::from_utf8(extra_states).map_err(|_| {
                super::set_last_error("extra_states is not valid UTF-8");
                NucleationError::InvalidArgument
            })?;
            let structure = mc_tick::Structure::parse(snbt).map_err(|e| {
                super::set_last_error(super::structure_parse_detail(&e, false));
                // An entity we cannot model is not a malformed file, so it
                // reports as a simulator limit rather than a parse failure.
                if matches!(
                    e,
                    mc_tick::structure::StructureError::UnsupportedEntity { .. }
                ) {
                    NucleationError::Simulation
                } else {
                    NucleationError::Parse
                }
            })?;
            super::check_volume(structure.size).map_err(|e| {
                super::set_last_error(e);
                NucleationError::InvalidArgument
            })?;
            let extras: Vec<&str> = extra
                .split(';')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .collect();
            let sim = super::wire_simulation(
                &structure,
                mc_tick::Pos::new(origin_x, origin_y, origin_z),
                settle,
                &extras,
                // The text states the version it was saved at, and that decides
                // whether its non-finite `Motion` vectors survive being read.
                // Ignoring it made this path disagree with `from_schematic`
                // about the same build: the NaN token round-trips through the
                // SNBT fine, but the load rule chosen for it did not, so a
                // door held together by nan carts came out as ordinary carts.
                structure.data_version,
            )
            .map_err(|e| {
                super::set_last_error(e);
                NucleationError::Simulation
            })?;
            Ok(Box::new(TickSimulation {
                sim,
                checkpoints: Vec::new(),
                stopped_timeline: None,
            }))
        }

        /// Load from a schematic (any format nucleation can read), rendered
        /// to gametest-flavor structure SNBT for mc-tick's parser.
        pub fn from_schematic(
            schematic: &Schematic,
            settle: TickSettleMode,
            origin_x: i32,
            origin_y: i32,
            origin_z: i32,
            extra_states: &DiplomatStr,
        ) -> Result<Box<TickSimulation>, NucleationError> {
            super::clear_last_error();
            let extra = std::str::from_utf8(extra_states).map_err(|_| {
                super::set_last_error("extra_states is not valid UTF-8");
                NucleationError::InvalidArgument
            })?;
            // Before rendering anything: the SNBT for a world-sized build is
            // what exhausts the heap, and the trap it raises poisons the
            // instance for every door after it.
            let bb = schematic.0.get_bounding_box();
            super::check_volume((
                bb.max.0 - bb.min.0 + 1,
                bb.max.1 - bb.min.1 + 1,
                bb.max.2 - bb.min.2 + 1,
            ))
            .map_err(|e| {
                super::set_last_error(e);
                NucleationError::InvalidArgument
            })?;
            let snbt = super::to_gametest_snbt(&schematic.0);
            let structure = mc_tick::Structure::parse(&snbt).map_err(|e| {
                // The schematic loaded; either it names an entity we cannot
                // model, or our own rendering of it was rejected. Saying
                // "Parse" here blames the user's file for our bug, so both
                // report as an engine failure and the detail says which.
                super::set_last_error(super::structure_parse_detail(&e, true));
                NucleationError::Simulation
            })?;
            let extras: Vec<&str> = extra
                .split(';')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .collect();
            let sim = super::wire_simulation(
                &structure,
                mc_tick::Pos::new(origin_x, origin_y, origin_z),
                settle,
                &extras,
                // The schematic remembers which game wrote it, and that
                // decides whether a non-finite `Motion` survives
                // `Entity.load` — the mechanism of the record nan-cart
                // doors. Passed through rather than defaulted: a 1.21.3
                // door and a 1.21.11 door are different machines, and
                // only this layer knows which one this is.
                schematic.0.metadata.source_data_version,
            )
            .map_err(|e| {
                super::set_last_error(e);
                NucleationError::Simulation
            })?;
            Ok(Box::new(TickSimulation {
                sim,
                checkpoints: Vec::new(),
                stopped_timeline: None,
            }))
        }

        /// GA fast path: construct from a flat genome-cell array — no SNBT
        /// text built or parsed. Corridor layout matches the flying-ga app:
        /// machine at `x_off`, world size `[bx + travel, by + 2, bz + 2]`,
        /// cells flattened `((y * bz) + z) * bx + x`, `air_index` = empty
        /// cell. `palette` is the run's alphabet, semicolon-separated; every
        /// entry is pre-interned so behaviours bind exactly as the SNBT
        /// path's EXTRA_STATES did.
        #[allow(clippy::too_many_arguments)]
        pub fn from_blocks(
            bx: i32,
            by: i32,
            bz: i32,
            travel: i32,
            x_off: i32,
            palette: &DiplomatStr,
            cells: &[u16],
            air_index: u16,
            settle: TickSettleMode,
            origin_x: i32,
            origin_y: i32,
            origin_z: i32,
        ) -> Result<Box<TickSimulation>, NucleationError> {
            super::clear_last_error();
            let palette = std::str::from_utf8(palette).map_err(|_| {
                super::set_last_error("palette is not valid UTF-8");
                NucleationError::InvalidArgument
            })?;
            let pal: Vec<String> = palette
                .split(';')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect();
            let structure =
                super::structure_from_blocks(bx, by, bz, travel, x_off, &pal, cells, air_index)
                    .map_err(|e| {
                        super::set_last_error(e);
                        NucleationError::InvalidArgument
                    })?;
            let extras: Vec<&str> = pal.iter().map(String::as_str).collect();
            let sim = super::wire_simulation(
                &structure,
                mc_tick::Pos::new(origin_x, origin_y, origin_z),
                settle,
                &extras,
                None,
            )
            .map_err(|e| {
                super::set_last_error(e);
                NucleationError::Simulation
            })?;
            Ok(Box::new(TickSimulation {
                sim,
                checkpoints: Vec::new(),
                stopped_timeline: None,
            }))
        }

        /// Evaluate a whole batch of kicked flights inside the engine — one
        /// wasm call per generation chunk instead of a dozen boundary calls
        /// per machine. `cells` holds N genomes concatenated (each
        /// `bx*by*bz` entries), `kicks` N structure-space `[x,y,z]` triples.
        /// The flight protocol, probe schedule and gait detection mirror the
        /// app's evalCore exactly; `early_exit` stops provably-frozen
        /// machines at tick 40 without changing any reported value. Writes
        /// JSON rows `[n0, startCom, startMinX, startMaxX, comAtMoveCheck |
        /// null, comAtMid, period, n1, endCom, endMinX, endMaxX]`.
        #[allow(clippy::too_many_arguments)]
        pub fn eval_flight_batch(
            bx: i32,
            by: i32,
            bz: i32,
            travel: i32,
            x_off: i32,
            palette: &DiplomatStr,
            cells: &[u16],
            air_index: u16,
            kicks: &[i32],
            eval_ticks: u32,
            seed: i64,
            must_move_by_tick: i32,
            need_period: bool,
            early_exit: bool,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let palette =
                std::str::from_utf8(palette).map_err(|_| NucleationError::InvalidArgument)?;
            let pal: Vec<String> = palette
                .split(';')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect();
            let extras: Vec<&str> = pal.iter().map(String::as_str).collect();
            let volume = (bx.max(0) as usize) * (by.max(0) as usize) * (bz.max(0) as usize);
            if volume == 0 || cells.len() % volume != 0 || kicks.len() != (cells.len() / volume) * 3
            {
                return Err(NucleationError::InvalidArgument);
            }
            let n_genomes = cells.len() / volume;
            // Wire ONE empty-corridor sim (registry, behaviours, physics
            // tables — the expensive part), checkpoint it pristine, and per
            // genome restore + place. Construction cost is paid once per
            // batch instead of once per machine.
            let empty = vec![air_index; volume];
            let empty_structure =
                super::structure_from_blocks(bx, by, bz, travel, x_off, &pal, &empty, air_index)
                    .map_err(|_| NucleationError::InvalidArgument)?;
            let mut sim = super::wire_simulation(
                &empty_structure,
                mc_tick::Pos::new(0, 0, 0),
                TickSettleMode::Quiet,
                &extras,
                None,
            )
            .map_err(|_| NucleationError::Simulation)?;
            let pristine = sim.checkpoint();
            let mut json = String::from("[");
            for g in 0..n_genomes {
                let slice = &cells[g * volume..(g + 1) * volume];
                let structure =
                    super::structure_from_blocks(bx, by, bz, travel, x_off, &pal, slice, air_index)
                        .map_err(|_| NucleationError::InvalidArgument)?;
                sim.restore(&pristine);
                {
                    let (registry, world) = sim.registry_and_world_mut();
                    structure.place(world, registry, mc_tick::Pos::new(0, 0, 0));
                }
                // Quiet settle for the placed genome, exactly as
                // wire_simulation would have done for a fresh sim.
                let order = structure.placement_order(
                    mc_tick::vanilla::is_collision_full_cube,
                    mc_tick::vanilla::has_dynamic_shape,
                );
                sim.place_on_place(&order);
                sim.record();
                let kick = (kicks[g * 3], kicks[g * 3 + 1], kicks[g * 3 + 2]);
                let row = super::fly_on(
                    &mut sim,
                    kick,
                    eval_ticks,
                    seed,
                    must_move_by_tick,
                    need_period,
                    early_exit,
                )
                .map_err(|_| NucleationError::Simulation)?;
                if g > 0 {
                    json.push(',');
                }
                json.push('[');
                for (i, v) in row.iter().enumerate() {
                    if i > 0 {
                        json.push(',');
                    }
                    if v.is_nan() {
                        json.push_str("null");
                    } else {
                        let _ = write!(json, "{v:?}");
                    }
                }
                json.push(']');
            }
            json.push(']');
            let _ = write!(out, "{json}");
            Ok(())
        }

        /// Seed the vanilla random source (`java.util.Random`'s LCG,
        /// bit-for-bit). Unseeded, jittering behaviours use each
        /// distribution's mean — fully deterministic, no noise.
        pub fn set_rng_seed(&mut self, seed: i64) {
            self.sim.set_rng_seed(seed);
        }

        /// Advance one game tick.
        pub fn step(&mut self) {
            self.sim.step();
        }

        /// Advance `ticks` game ticks.
        pub fn run(&mut self, ticks: u32) {
            self.sim.run(u64::from(ticks));
        }

        /// Run until nothing is scheduled or `budget` ticks pass. Returns
        /// whether the world went quiet.
        pub fn run_until_quiescent(&mut self, budget: u32) -> bool {
            self.sim.run_until_quiescent(u64::from(budget));
            self.sim.is_quiescent()
        }

        /// Game ticks elapsed since settle.
        pub fn tick_count(&self) -> u32 {
            self.sim.tick_count() as u32
        }

        /// Whether nothing is scheduled or queued.
        pub fn is_quiescent(&self) -> bool {
            self.sim.is_quiescent()
        }

        /// Right-click a block with an empty hand (lever, button, note block).
        pub fn use_block(&mut self, x: i32, y: i32, z: i32) {
            self.sim.use_block(mc_tick::Pos::new(x, y, z));
        }

        /// Write a block state (`minecraft:air` breaks). The state must be in
        /// the structure, in `extra_states`, or `minecraft:redstone_block`.
        pub fn place_block(
            &mut self,
            x: i32,
            y: i32,
            z: i32,
            state: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let state = std::str::from_utf8(state).map_err(|_| NucleationError::InvalidArgument)?;
            let id = self
                .sim
                .registry()
                .get(state)
                .ok_or(NucleationError::NotFound)?;
            self.sim.place_block(mc_tick::Pos::new(x, y, z), id);
            Ok(())
        }

        /// The block state descriptor at a position (`minecraft:air` for empty).
        pub fn get_block(&self, x: i32, y: i32, z: i32, out: &mut DiplomatWrite) {
            let id = self.sim.world().get(mc_tick::Pos::new(x, y, z));
            let descriptor = self
                .sim
                .registry()
                .descriptor(id)
                .unwrap_or("minecraft:air");
            let _ = write!(out, "{descriptor}");
        }

        /// Batched block-state reads: `positions_json` is `[[x,y,z], ...]`,
        /// the answer a JSON array of descriptors in the same order
        /// (`"minecraft:air"` for empty).
        ///
        /// A verification sweep over a computational build is thousands of
        /// probe reads per settle; one boundary call per sweep instead of one
        /// per probe is the difference between the FFI being the throughput
        /// ceiling and not.
        pub fn read_probes(
            &self,
            positions_json: &DiplomatStr,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let positions: Vec<[i32; 3]> = serde_json::from_slice(positions_json).map_err(|e| {
                crate::bridge::set_last_error_detail(format!(
                    "positions_json must be [[x,y,z], ...]: {e}"
                ));
                NucleationError::InvalidArgument
            })?;
            let states: Vec<&str> = positions
                .iter()
                .map(|&[x, y, z]| {
                    let id = self.sim.world().get(mc_tick::Pos::new(x, y, z));
                    self.sim
                        .registry()
                        .descriptor(id)
                        .unwrap_or("minecraft:air")
                })
                .collect();
            let json = serde_json::to_string(&states).map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{json}");
            Ok(())
        }

        /// Who powers this cell and why — a power-source tree from the
        /// simulation's current state, as JSON.
        ///
        /// Each node carries `pos`, `state`, `kind` (`wire` / `conductor` /
        /// `source` / `block`), the `power` the cell carries or emits, and
        /// `inputs`: the per-side contributions that explain it, each with a
        /// `mechanism` (`block_signal`, `wire`, `wire_up`, `wire_down`,
        /// `strong`, `signal`), the arriving `power`, and a recursive
        /// `source` node. Cycles stop with `"cycle": true`. Coordinates are
        /// the same structure-local space `get_block` reads.
        ///
        /// This is the static complement of running the sim: an open (a dead
        /// route that settles quiescent) shows up as an empty `inputs` list
        /// exactly where the feed should have been.
        pub fn conduction_trace(&self, x: i32, y: i32, z: i32, out: &mut DiplomatWrite) {
            let _ = write!(
                out,
                "{}",
                super::conduction_trace_json(&self.sim, mc_tick::Pos::new(x, y, z))
            );
        }

        /// Write every settled non-air state back into `schematic` — the bulk
        /// form of `{simulate=true}`: settle once, keep the world the engine
        /// ended on. Returns how many blocks changed.
        ///
        /// The schematic's bounding-box minimum corresponds to the
        /// simulation's `(0, 0, 0)`, which is exactly how `from_schematic`
        /// loaded it. A file baked this way carries real wire connections and
        /// power in its palette, loads quiescent under `InWorld`, and renders
        /// correctly in any static consumer. Cells the simulation turned into
        /// air (a popped-off component) are left as the schematic had them.
        pub fn bake_to(&self, schematic: &mut Schematic) -> u32 {
            super::bake_into(&self.sim, &mut schematic.0)
        }

        /// Snapshot the entire simulation; returns a checkpoint id.
        pub fn checkpoint(&mut self) -> u32 {
            self.checkpoints.push(self.sim.checkpoint());
            (self.checkpoints.len() - 1) as u32
        }

        /// Restore a checkpoint taken earlier on this simulation.
        pub fn restore(&mut self, id: u32) -> Result<(), NucleationError> {
            let checkpoint = self
                .checkpoints
                .get(id as usize)
                .ok_or(NucleationError::NotFound)?;
            self.sim.restore(checkpoint);
            Ok(())
        }

        /// Render a schematic as gametest-flavor structure SNBT — the text
        /// `from_snbt` and the corpus/render tooling consume. Lets hosts hand
        /// a converted `.litematic`/`.schem` to the video renderer.
        pub fn gametest_snbt(schematic: &Schematic, out: &mut DiplomatWrite) {
            let _ = write!(out, "{}", super::to_gametest_snbt(&schematic.0));
        }

        /// Report blocks whose behaviour is defined by block-entity data the
        /// file does not carry.
        ///
        /// Some exporters write the blocks and drop the block entities. The
        /// build then loads clean and simulates *wrongly but plausibly*: a
        /// comparator with no `OutputSignal` reads 0, a barrel holding the
        /// item that latched a repeater reads empty, and the door quietly
        /// fails to reset. Two files with identical block arrays get
        /// different verdicts and nothing says why. `0.45_4x4_funnel.schem`
        /// is exactly this — 4 comparators, 2 furnaces, `BlockEntities` of
        /// length 0, while its `.litematic` twin carries all 9.
        ///
        /// This does not refuse the build; it names the doubt so a host can.
        /// JSON: `{"present":N,"missing_total":N,"missing":[{"name":..,
        /// "count":N}],"summary":"..."}` — `summary` is empty when nothing
        /// is missing, and otherwise a sentence fit to show as-is.
        pub fn block_entity_audit_json(schematic: &Schematic, out: &mut DiplomatWrite) {
            let _ = write!(out, "{}", super::block_entity_audit(&schematic.0));
        }

        /// Start (or stop) recording every delivered redstone update.
        ///
        /// Off by default and much larger than the block-change log — a door's
        /// cycle runs several updates per change — so a propagation view asks
        /// for it explicitly and pages with
        /// [`TickSimulation::updates_json_between`].
        ///
        /// Switching it off keeps what was recorded; use
        /// [`TickSimulation::clear_updates`] to free it.
        pub fn record_updates(&mut self, on: bool) {
            self.sim.record_updates(on);
        }

        /// Drop the recorded updates without changing whether recording is on.
        ///
        /// A cycle of a 6x6 door is tens of megabytes of log, so a page that
        /// certifies several builds on one instance needs to release one
        /// before recording the next.
        pub fn clear_updates(&mut self) {
            self.sim.clear_updates();
        }

        /// Start recording a run timeline from the current tick.
        ///
        /// A timeline is what makes a span of simulation reviewable after the
        /// fact: block deltas, the inputs that caused them and the piston
        /// strokes they drove, plus one whole-world frame to replay them from.
        /// Off by default — a simulation used for timing should not pay for it.
        ///
        /// Called again, it restarts from the current tick, and the previously
        /// stopped span is released.
        ///
        /// Starting a recording also wipes the plain block-change log that
        /// [`TickSimulation::changes_json`] and [`TickSimulation::changes_count`]
        /// read back to empty — a separate reset from
        /// [`TickSimulation::record_updates`]/[`TickSimulation::clear_updates`],
        /// which govern a different log. A host holding a cursor into the
        /// change log (the sim lab keeps a cumulative one) must reset that
        /// cursor when it calls this, or it will read past the end of a log
        /// that is no longer the one it was walking.
        pub fn record_timeline(&mut self) {
            self.stopped_timeline = None;
            self.sim.record_timeline();
        }

        /// End the recording, keeping the span readable.
        ///
        /// This is a host's Stop button, and it is not a rewind: the span stays
        /// readable and exportable until the next
        /// [`TickSimulation::record_timeline`], while the simulation is free to
        /// run on without the recording following it. No-op if nothing was
        /// recording.
        pub fn stop_timeline(&mut self) {
            if let Some(timeline) = self.sim.stop_timeline() {
                self.stopped_timeline = Some(timeline);
            }
        }

        /// Which timeline a read query answers from.
        ///
        /// The live recorder if one is running, otherwise the span the last
        /// [`TickSimulation::stop_timeline`] ended — a stopped span stays
        /// readable until the next [`TickSimulation::record_timeline`]. Every
        /// timeline reader resolves through here so that they cannot disagree
        /// about which recording the host is looking at.
        ///
        /// It hands back a **borrowed** view because most readers only want the
        /// event vectors, and a host draws a timeline strip by polling. An
        /// owned `RunTimeline` carries the initial frame — every non-air block
        /// in the world, near a megabyte on a real build — so resolving to one
        /// here would copy that on every poll, which is the unbounded copying
        /// this recording model exists to avoid. Readers that genuinely need a
        /// whole timeline call `.to_timeline()` on the result, and say in their
        /// own docs that they pay for it.
        fn timeline(&self) -> Option<mc_tick::timeline::TimelineView<'_>> {
            self.sim.timeline_view().or_else(|| {
                self.stopped_timeline
                    .as_ref()
                    .map(mc_tick::timeline::TimelineView::of)
            })
        }

        /// Where the recorded run was busy, as JSON:
        /// `{"start":T,"end":T,"ticks":[{"tick":T,"changes":N,"inputs":N,
        ///   "pistons":N}]}`.
        ///
        /// The strip a host draws to let someone pick a span worth exporting.
        /// Only ticks that did something appear: an idle tick is **absent**
        /// rather than present with zeroes, so a build that sits still does not
        /// advance the strip and a long quiet run stays cheap to send.
        ///
        /// `{"start":0,"end":0,"ticks":[]}` when nothing has been recorded.
        pub fn timeline_activity_json(&self, out: &mut DiplomatWrite) {
            let Some(timeline) = self.timeline() else {
                let _ = write!(out, "{{\"start\":0,\"end\":0,\"ticks\":[]}}");
                return;
            };
            // Counted straight off the three borrowed event vectors: this
            // copies nothing, unlike the other timeline queries (no world-sized
            // clone, no frame or digest rebuild). But it is not free — it is
            // O(changes + inputs + pistons), re-scanning the whole accumulated
            // log into a fresh `BTreeMap` on every call, so a host should choose
            // its poll rate knowing the cost grows with the recording, not just
            // call this as often as it likes.
            let mut active: std::collections::BTreeMap<u64, [u32; 3]> =
                std::collections::BTreeMap::new();
            for change in timeline.changes {
                active.entry(change.tick).or_default()[0] += 1;
            }
            for input in timeline.inputs {
                active.entry(input.tick()).or_default()[1] += 1;
            }
            for piston in timeline.pistons {
                active.entry(piston.tick).or_default()[2] += 1;
            }
            let mut json = format!(
                "{{\"start\":{},\"end\":{},\"ticks\":[",
                timeline.start_tick, timeline.end_tick
            );
            for (i, (tick, counts)) in active.iter().enumerate() {
                if i > 0 {
                    json.push(',');
                }
                let _ = write!(
                    json,
                    "{{\"tick\":{},\"changes\":{},\"inputs\":{},\"pistons\":{}}}",
                    tick, counts[0], counts[1], counts[2]
                );
            }
            json.push_str("]}");
            let _ = write!(out, "{json}");
        }

        /// Exact and translated recurrence in the timeline a read query would
        /// resolve to (see [`Self::timeline`]), as JSON:
        /// `{"exact":{"start":T,"end":T,"period":N,"drift":[x,y,z]}|null,
        ///   "translated":{...}|null}`.
        ///
        /// **An absent cycle is `null`, not an error.** Most builds — an
        /// adder, a door — never repeat their own state, and that is the
        /// ordinary outcome, not a failed search.
        ///
        /// **O(ticks × blocks): replays the whole recorded span to build one
        /// digest per tick boundary**, then rebuilds full frames for the
        /// handful of candidates that survive. This is an on-demand "find
        /// cycles" action for a host UI button, never something to call per
        /// tick or per frame — poll [`Self::timeline_activity_json`] instead.
        ///
        /// Materialises the whole recorded timeline once to answer this call
        /// (an owned `RunTimeline`'s `initial` frame copies every non-air
        /// block) — acceptable for one on-demand press, not for a loop.
        ///
        /// `{"exact":null,"translated":null}` when nothing has been recorded.
        pub fn timeline_cycles_json(&self, out: &mut DiplomatWrite) {
            let Some(view) = self.timeline() else {
                let _ = write!(out, "{{\"exact\":null,\"translated\":null}}");
                return;
            };
            let timeline = view.to_timeline();
            let report = timeline.detect_cycles(self.sim.registry());
            let _ = write!(
                out,
                "{{\"exact\":{},\"translated\":{}}}",
                super::cycle_json(report.exact),
                super::cycle_json(report.translated)
            );
        }

        /// Project `[start_tick, end_tick)` of the timeline a read query would
        /// resolve to (see [`Self::timeline`]) into the animated-GLB mesher's
        /// `Timeline` JSON — `{"origin":[x,y,z],"tick_ms":F,
        /// "events":[{"kind":"set_block"|"piston",...}]}` — via
        /// `crate::tick_timeline::mesher_timeline_json`.
        ///
        /// **Materialises the whole recorded timeline to answer this call**
        /// (an owned `RunTimeline`'s `initial` frame copies every non-air
        /// block in the world) — this is an on-demand "export this
        /// selection" action, not something to call per frame or poll.
        ///
        /// Fails if no timeline has been recorded, or if `start_tick..
        /// end_tick` is empty or outside the recorded span.
        pub fn animation_timeline_json(
            &self,
            start_tick: u32,
            end_tick: u32,
            tick_ms: f32,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let Some(view) = self.timeline() else {
                super::set_last_error("no timeline has been recorded on this simulation");
                return Err(NucleationError::NotFound);
            };
            // One materialisation for this call: `select_ticks` and the
            // projection below both need an owned `RunTimeline` to read, and
            // there is nothing else in this call to share the copy with.
            let timeline = view.to_timeline();
            let selection = timeline
                .select_ticks(u64::from(start_tick), u64::from(end_tick))
                .map_err(|e| {
                    super::set_last_error(e.to_string());
                    NucleationError::InvalidArgument
                })?;
            // The `ProjectionWarnings` are discarded here: the host has no
            // channel to show them yet, and inventing one before anything
            // needs it is YAGNI.
            let (json, _warnings) = crate::tick_timeline::mesher_timeline_json(
                &timeline,
                selection,
                self.sim.registry(),
                tick_ms,
            )
            .map_err(|e| {
                super::set_last_error(e);
                NucleationError::Simulation
            })?;
            let _ = write!(out, "{json}");
            Ok(())
        }

        /// The selection's starting scene — `[start_tick, end_tick)` of the
        /// timeline a read query would resolve to (see [`Self::timeline`]) —
        /// as schematic bytes, base64-encoded.
        ///
        /// A WASM handle cannot cross a worker boundary, so this exists for a
        /// host to hand the bytes to a worker, which rebuilds the schematic
        /// with `Schematic.fromData`.
        ///
        /// **Materialises the whole recorded timeline to answer this call**
        /// — see [`Self::animation_timeline_json`]; an on-demand export
        /// action, not a per-frame poll.
        ///
        /// Fails if no timeline has been recorded, or if `start_tick..
        /// end_tick` is empty or outside the recorded span.
        pub fn selection_schematic_b64(
            &self,
            start_tick: u32,
            end_tick: u32,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let Some(view) = self.timeline() else {
                super::set_last_error("no timeline has been recorded on this simulation");
                return Err(NucleationError::NotFound);
            };
            let timeline = view.to_timeline();
            let selection = timeline
                .select_ticks(u64::from(start_tick), u64::from(end_tick))
                .map_err(|e| {
                    super::set_last_error(e.to_string());
                    NucleationError::InvalidArgument
                })?;
            let schematic = crate::tick_timeline::selection_schematic(
                &timeline,
                selection,
                self.sim.registry(),
            )
            .map_err(|e| {
                super::set_last_error(e);
                NucleationError::Simulation
            })?;
            // Same serialisation `Schematic::to_schematic_b64` uses, so a
            // worker's `Schematic.fromData` reads this back identically.
            let data = crate::formats::schematic::to_schematic(&schematic).map_err(|e| {
                super::set_last_error(e.to_string());
                NucleationError::Serialize
            })?;
            // `schematic`'s b64 helper, not `meshing`'s: this module is gated on
            // `mc-tick` alone and must stay buildable without `meshing`.
            let _ = write!(out, "{}", super::super::schematic::b64(&data));
            Ok(())
        }

        /// How many updates have been recorded — page before pulling them.
        pub fn updates_count(&self) -> u32 {
            self.sim.recorded_updates().len() as u32
        }

        /// Every recorded update, in delivery order.
        ///
        /// `seq` counts from 0 within each tick: that is the sub-tick axis, and
        /// `(tick, seq)` is the order the engine actually delivered them in.
        /// `state` is the block as it stood **at dispatch time**, which is what
        /// makes intra-tick order legible — a snapshot cannot show it.
        pub fn updates_json(&self, out: &mut DiplomatWrite) {
            let _ = write!(out, "{}", super::updates_json_range(&self.sim, 0, u64::MAX));
        }

        /// The recorded updates for ticks in `[from_tick, to_tick)`.
        ///
        /// The whole log for a 6x6 door's cycle is megabytes; a scrubber only
        /// ever shows one tick, so it should ask for one tick.
        pub fn updates_json_between(&self, from_tick: u32, to_tick: u32, out: &mut DiplomatWrite) {
            let _ = write!(
                out,
                "{}",
                super::updates_json_range(&self.sim, u64::from(from_tick), u64::from(to_tick))
            );
        }

        /// Per-tick, per-cell update counts for ticks in `[from_tick, to_tick)`.
        ///
        /// The resolution playback should run at: `{phases, ticks:[{tick, total,
        /// cells:[{p:[x,y,z], n, nb, sh, ph:[…]}]}]}`, where `nb`/`sh` split
        /// neighbour from shape and `ph` indexes the `phases` legend. Collapses
        /// a tick's tens of thousands of updates into a few hundred cells.
        pub fn updates_heat_json(&self, from_tick: u32, to_tick: u32, out: &mut DiplomatWrite) {
            let _ = write!(
                out,
                "{}",
                super::updates_heat_range(&self.sim, u64::from(from_tick), u64::from(to_tick))
            );
        }

        /// One tick's updates in delivery order, as parallel arrays.
        ///
        /// For stepping *within* a tick: `seq` is the array index, `pos` is flat
        /// x,y,z triples, `kind`/`phase`/`from` are integer codes with legends
        /// in the payload, and `state` indexes a deduplicated `states` table.
        pub fn updates_wave_json(&self, tick: u32, out: &mut DiplomatWrite) {
            let _ = write!(out, "{}", super::updates_wave(&self.sim, u64::from(tick)));
        }

        /// Every block a piston currently has in flight, as JSON:
        /// `[{"to":[x,y,z],"from":[x,y,z],"state":"...","carried":"...",
        ///    "carried_short":"..."|null,"remains":"..."|null,"dir":"east",
        ///    "extending":bool,"started":T,"lands":T,"source_piston":bool}]`.
        ///
        /// Draw `carried` travelling `from` -> `to`, and `remains` (when it is
        /// not null) parked at `to` for the whole move. They differ from
        /// `state` — what actually lands — only for a retracting piston, whose
        /// body stays put while its head comes home; vanilla's
        /// `PistonHeadRenderer` splits exactly these two slots.
        ///
        /// `carried_short` is the same arm with `short=true`. Draw it while the
        /// head is **within half a block of its body** — `progress <= 0.5`
        /// extending, `progress >= 0.5` retracting — or the shaft passes
        /// visibly through the back of the piston as it comes home. Which form
        /// to use is yours; naming the state is the engine's.
        ///
        /// What a renderer needs to animate a stroke, from the simulator that
        /// dispatched it. The block-change stream cannot answer this: it says a
        /// cell became a `moving_piston` placeholder, not which block set off,
        /// which cell it left, or which tick it arrives — so a host that
        /// reconstructs strokes from changes is reimplementing piston mechanics
        /// downstream of the engine, and animating on a clock the simulation
        /// does not share. That desync is what draws a block twice, leaves a
        /// gap where one should be, and shears a piston head off its load.
        ///
        /// `started` and `lands` are tick numbers in the engine's frame, where
        /// [`Self::tick_count`] counts *completed* ticks: after stepping to
        /// `tick_count == t`, a flight's progress is
        /// `(t - started) / (lands - started)`, clamped to 1. Draw it while it
        /// is listed and drop it when it stops being listed — the same call
        /// that stops reporting it is the tick the real block is written, so
        /// there is no frame with both and none with neither.
        pub fn moving_blocks_json(&self, out: &mut DiplomatWrite) {
            let mut json = String::from("[");
            for (i, m) in self.sim.moving_blocks().iter().enumerate() {
                if i > 0 {
                    json.push(',');
                }
                let state = self.sim.registry().descriptor(m.state).unwrap_or("?");
                let carried = self.sim.registry().descriptor(m.carried).unwrap_or("?");
                let quoted = |s: Option<mc_tick::StateId>| match s
                    .and_then(|s| self.sim.registry().descriptor(s))
                {
                    Some(descriptor) => format!("\"{descriptor}\""),
                    None => "null".to_string(),
                };
                let carried_short = quoted(m.carried_short);
                let remains = quoted(m.remains);
                let _ = write!(
                    json,
                    "{{\"to\":[{},{},{}],\"from\":[{},{},{}],\"state\":\"{}\",\
                     \"carried\":\"{}\",\"carried_short\":{},\"remains\":{},\
                     \"dir\":\"{}\",\"extending\":{},\"started\":{},\"lands\":{},\
                     \"source_piston\":{}}}",
                    m.to.x,
                    m.to.y,
                    m.to.z,
                    m.from.x,
                    m.from.y,
                    m.from.z,
                    state,
                    carried,
                    carried_short,
                    remains,
                    m.travel.name(),
                    m.extending,
                    m.started_on,
                    m.lands_on,
                    m.source_piston
                );
            }
            json.push(']');
            let _ = write!(out, "{json}");
        }

        /// Drop the recorded block changes without stopping recording.
        ///
        /// The log grows for as long as the simulation runs and nothing
        /// empties it, so a long-running host — a browser session driving
        /// thousands of ticks — accumulates every block change forever. A
        /// host that has already consumed [`TickSimulation::changes_json`]
        /// can say so here and keep recording on. A host holding a cursor
        /// into the change log must reset that cursor when it calls this, or
        /// it will read past the end of a log that is no longer the one it
        /// was walking — the same hazard [`TickSimulation::record_timeline`]
        /// names for its own reset of this log.
        ///
        /// Refuses — and leaves the log untouched — while
        /// [`TickSimulation::record_timeline`] is recording: a run timeline
        /// is a seed frame plus this same log, and every timeline reader
        /// trusts that the log describes every mutation since recording
        /// began. Clearing it out from under a live recording would make
        /// replay silently wrong rather than fail loudly. Returns `true` if
        /// the log was cleared, `false` if the call was refused — following
        /// [`TickSimulation::run_until_quiescent`]'s convention of reporting
        /// whether the call achieved what it was asked, rather than swallowing
        /// a no-op.
        pub fn clear_changes(&mut self) -> bool {
            self.sim.clear_recorded()
        }

        pub fn changes_json(&self, out: &mut DiplomatWrite) {
            self.changes_json_from(0, out);
        }

        /// The same JSON array [`TickSimulation::changes_json`] produces,
        /// but only the entries from index `start` onward.
        ///
        /// Exists for a host draining the log every frame while a run
        /// timeline recording refuses [`TickSimulation::clear_changes`]: the
        /// log only ever grows in that state, so without this,
        /// `changes_json` re-serialises the whole backlog on every single
        /// drain — a cost that climbs for as long as the recording runs,
        /// which is exactly when a session runs longest. Reading from a
        /// cursor keeps a drain's cost to what is actually new.
        ///
        /// `start` at or past the end of the log yields `[]`, not an error —
        /// a host racing a draining cursor against a growing log should not
        /// have to special-case "nothing new yet".
        pub fn changes_json_from(&self, start: u32, out: &mut DiplomatWrite) {
            let recorded = self.sim.recorded();
            let start = (start as usize).min(recorded.len());
            let mut json = String::from("[");
            for (i, change) in recorded[start..].iter().enumerate() {
                if i > 0 {
                    json.push(',');
                }
                let from = self.sim.registry().descriptor(change.from).unwrap_or("?");
                let to = self.sim.registry().descriptor(change.to).unwrap_or("?");
                let _ = write!(
                    json,
                    "{{\"tick\":{},\"pos\":[{},{},{}],\"from\":\"{}\",\"to\":\"{}\"}}",
                    change.tick, change.pos.x, change.pos.y, change.pos.z, from, to
                );
            }
            json.push(']');
            let _ = write!(out, "{json}");
        }

        /// Live item entities and minecarts, as JSON:
        /// `{"items":[{"id":N,"item":"...","count":N,"pos":[..],"vel":[..],
        ///   "on_ground":bool,"contents":[{"id":"...","count":N}]}],
        ///  "minecarts":[{"id":N,"kind":"...","pos":[..],"vel":[..]}]}`.
        pub fn item_entities_json(&self, out: &mut DiplomatWrite) {
            let mut json = String::from("{\"items\":[");
            let mut first = true;
            for entity in self.sim.item_entities() {
                if entity.removed {
                    continue;
                }
                if !first {
                    json.push(',');
                }
                first = false;
                let _ = write!(
                    json,
                    "{{\"id\":{},\"item\":\"{}\",\"count\":{},\"pos\":[{},{},{}],\"vel\":[{},{},{}],\"on_ground\":{}",
                    entity.id,
                    entity.item.0,
                    entity.item.1,
                    entity.pos[0], entity.pos[1], entity.pos[2],
                    entity.vel[0], entity.vel[1], entity.vel[2],
                    entity.on_ground,
                );
                json.push_str(",\"contents\":[");
                let contents = self.sim.item_contents(entity.id).unwrap_or(&[]);
                for (i, stack) in contents.iter().enumerate() {
                    if i > 0 {
                        json.push(',');
                    }
                    let _ = write!(
                        json,
                        "{{\"id\":\"{}\",\"count\":{}}}",
                        stack.id, stack.count
                    );
                }
                json.push_str("]}");
            }
            json.push_str("],\"minecarts\":[");
            let mut first = true;
            for cart in self.sim.minecarts() {
                if cart.removed {
                    continue;
                }
                if !first {
                    json.push(',');
                }
                first = false;
                let _ = write!(
                    json,
                    "{{\"id\":{},\"kind\":\"{}\",\"pos\":[{},{},{}],\"vel\":[{},{},{}]}}",
                    cart.id,
                    cart.kind,
                    cart.pos[0],
                    cart.pos[1],
                    cart.pos[2],
                    cart.vel[0],
                    cart.vel[1],
                    cart.vel[2],
                );
            }
            json.push_str("],\"frozen\":[");
            let mut first = true;
            for body in self.sim.entity_bodies() {
                if body.is_minecart {
                    continue;
                }
                if !first {
                    json.push(',');
                }
                first = false;
                // `size` is the measured hitbox, not a guess a viewer would
                // otherwise have to make from the kind name — a boat is
                // 1.375 x 0.5625 and nothing about "minecraft:oak_boat" says
                // so. `leashed` distinguishes a tethered boat from one resting
                // on the ground; they are the same box and not the same thing.
                let _ = write!(
                    json,
                    "{{\"id\":{},\"kind\":\"{}\",\"pos\":[{},{},{}],\"size\":[{},{},{}],\"leashed\":{}}}",
                    body.id,
                    body.kind,
                    (body.min[0] + body.max[0]) / 2.0,
                    body.min[1],
                    (body.min[2] + body.max[2]) / 2.0,
                    body.max[0] - body.min[0],
                    body.max[1] - body.min[1],
                    body.max[2] - body.min[2],
                    body.leashed,
                );
            }
            json.push_str("]}");
            let _ = write!(out, "{json}");
        }

        /// Which `Entity.load` Motion semantics this run uses:
        /// `"clamp_abs_ten"` (DataVersion <= 4556 — NaN survives a cold load)
        /// or `"drop_non_finite"` (>= 4671 — it does not).
        ///
        /// Exposed because a door built on nan carts is a *different machine*
        /// under the two, and a caller that cannot tell them apart cannot
        /// report why it came apart.
        pub fn motion_semantics(&self, out: &mut DiplomatWrite) {
            let name = match self.sim.motion_semantics() {
                mc_tick::MotionSemantics::ClampAbsTen => "clamp_abs_ten",
                mc_tick::MotionSemantics::DropNonFinite => "drop_non_finite",
            };
            let _ = write!(out, "{name}");
        }

        /// How many times an entity stood in a **retracting** piston's sweep
        /// that the engine could not reproduce.
        ///
        /// A tripwire from when retraction was unmodelled — extension
        /// displacement was measured and implemented while
        /// `tools/gametest/captures/piston_pull.entities.log`'s sub-0.03
        /// movements, not uniformly backwards, had no model here. All three
        /// retraction geometries are implemented now, so this reports **0**,
        /// including on the record 3x3 door, which used to name six. It is kept
        /// because the next geometry that turns out not to be covered should be
        /// reported rather than guessed at: non-zero means this run leaned on
        /// behaviour we do not reproduce and its result is not trustworthy.
        pub fn piston_retract_contacts(&self) -> u32 {
            self.sim.piston_retract_contacts().len() as u32
        }

        /// Per-tick aggregates over the recorded changes, as JSON:
        /// `[{"tick":N,"changes":N,"piston":N,"redstone":N}]` — `piston`
        /// counts changes touching piston blocks (base, head, moving), and
        /// `redstone` changes touching wire/torch/repeater/comparator/
        /// observer/lamp/lever/button/pressure-plate states.
        pub fn events_summary_json(&self, out: &mut DiplomatWrite) {
            use std::collections::BTreeMap;
            #[derive(Default)]
            struct Row {
                changes: u32,
                piston: u32,
                redstone: u32,
            }
            let mut rows: BTreeMap<u64, Row> = BTreeMap::new();
            for change in self.sim.recorded() {
                let from = self.sim.registry().descriptor(change.from).unwrap_or("");
                let to = self.sim.registry().descriptor(change.to).unwrap_or("");
                let row = rows.entry(change.tick).or_default();
                row.changes += 1;
                let named =
                    |needle: &str| super::is_named(from, needle) || super::is_named(to, needle);
                if named("piston") {
                    row.piston += 1;
                }
                if named("redstone")
                    || named("repeater")
                    || named("comparator")
                    || named("observer")
                    || named("lever")
                    || named("button")
                    || named("pressure_plate")
                    || named("lamp")
                {
                    row.redstone += 1;
                }
            }
            let mut json = String::from("[");
            for (i, (tick, row)) in rows.iter().enumerate() {
                if i > 0 {
                    json.push(',');
                }
                let _ = write!(
                    json,
                    "{{\"tick\":{},\"changes\":{},\"piston\":{},\"redstone\":{}}}",
                    tick, row.changes, row.piston, row.redstone
                );
            }
            json.push(']');
            let _ = write!(out, "{json}");
        }

        /// Every non-air block, as JSON:
        /// `[{"pos":[x,y,z],"state":"..."}]`.
        /// How many non-air blocks stand in the world right now.
        pub fn non_air_count(&self) -> u32 {
            self.sim.world().non_air_count() as u32
        }

        /// Center of mass (x) of every non-air block — the GA's displacement
        /// metric without a JSON round-trip. NaN when the world is empty.
        pub fn non_air_center_x(&self) -> f64 {
            let mut sum = 0.0;
            let mut n = 0u32;
            for (pos, _) in self.sim.world().iter_non_air() {
                sum += f64::from(pos.x);
                n += 1;
            }
            if n == 0 {
                f64::NAN
            } else {
                sum / f64::from(n)
            }
        }

        /// Smallest x holding a non-air block; `i32::MAX` when empty.
        pub fn non_air_min_x(&self) -> i32 {
            self.sim
                .world()
                .iter_non_air()
                .map(|(pos, _)| pos.x)
                .min()
                .unwrap_or(i32::MAX)
        }

        /// Largest x holding a non-air block; `i32::MIN` when empty.
        pub fn non_air_max_x(&self) -> i32 {
            self.sim
                .world()
                .iter_non_air()
                .map(|(pos, _)| pos.x)
                .max()
                .unwrap_or(i32::MIN)
        }

        /// How many block changes recording has captured so far.
        pub fn changes_count(&self) -> u32 {
            self.sim.recorded().len() as u32
        }

        pub fn world_snapshot_json(&self, out: &mut DiplomatWrite) {
            let mut json = String::from("[");
            let mut first = true;
            for (pos, id) in self.sim.world().iter_non_air() {
                if !first {
                    json.push(',');
                }
                first = false;
                let state = self.sim.registry().descriptor(id).unwrap_or("?");
                let _ = write!(
                    json,
                    "{{\"pos\":[{},{},{}],\"state\":\"{}\"}}",
                    pos.x, pos.y, pos.z, state
                );
            }
            json.push(']');
            let _ = write!(out, "{json}");
        }

        /// Static structural analysis of the build standing in this world.
        ///
        /// One call, one JSON document: adhesion groups, piston/observer/source
        /// nodes, the four edge kinds, every minimal self-translating subgraph
        /// (the engine), payload, kickers, dead weight, and any proof that the
        /// machine cannot move.
        ///
        /// The analysis lives in the engine rather than in the caller on
        /// purpose. Every "what would this piston move?" answer comes from
        /// `resolve_push`/`resolve_pull` — the same oracle-verified resolver the
        /// tick loop runs — and a second copy of Minecraft's push rules written
        /// on the far side of this boundary would drift from it silently.
        pub fn machine_graph_json(&self, out: &mut DiplomatWrite) {
            let graph = super::analyse_world(self.sim.world(), self.sim.registry());
            let _ = write!(out, "{}", graph.to_json());
        }

        /// GA pre-filter: static verdicts for a whole batch of genomes.
        ///
        /// Same flat-cell layout as [`Self::eval_flight_batch`], and meant to run
        /// immediately before it: whatever this rejects never needs simulating.
        /// Writes one row per genome, `[rejected, rejected_for_sustained,
        /// engine_cell_count, payload_cell_count, dead_cell_count, "codes"]`.
        ///
        /// The registry, behaviour table and movability rules are built once for
        /// the batch — building them per genome costs more than the analysis.
        #[allow(clippy::too_many_arguments)]
        pub fn machine_graph_batch_json(
            bx: i32,
            by: i32,
            bz: i32,
            travel: i32,
            x_off: i32,
            palette: &DiplomatStr,
            cells: &[u16],
            air_index: u16,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let palette =
                std::str::from_utf8(palette).map_err(|_| NucleationError::InvalidArgument)?;
            let json =
                super::machine_graph_batch(bx, by, bz, travel, x_off, palette, cells, air_index)
                    .map_err(|_| NucleationError::InvalidArgument)?;
            let _ = write!(out, "{json}");
            Ok(())
        }
    }
}

/// Static verdicts for a batch of genomes, as JSON rows.
///
/// Split out of the bridge method so the GA's contract can be tested without
/// standing up a `DiplomatWrite`.
fn machine_graph_batch(
    bx: i32,
    by: i32,
    bz: i32,
    travel: i32,
    x_off: i32,
    palette: &str,
    cells: &[u16],
    air_index: u16,
) -> Result<String, String> {
    use std::fmt::Write as _;

    let pal: Vec<String> = palette
        .split(';')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .collect();
    let volume = (bx.max(0) as usize) * (by.max(0) as usize) * (bz.max(0) as usize);
    if volume == 0 || cells.is_empty() || cells.len() % volume != 0 {
        return Err("cells length is not a whole number of bbox volumes".into());
    }
    let n_genomes = cells.len() / volume;

    // One registry, one behaviour table and one set of movability rules for the
    // whole batch. Building them per genome costs more than the analysis does.
    let mut registry = mc_tick::StateRegistry::new();
    for descriptor in &pal {
        registry.intern(descriptor).map_err(|e| format!("{e:?}"))?;
    }
    mc_tick::intern_companions(&mut registry);
    let mut table = mc_tick::BehaviourTable::default();
    let rules = mc_tick::register_all_at(&mut registry, &mut table, mc_tick::Pos::new(0, 0, 0));

    let empty = vec![air_index; volume];
    let reference = structure_from_blocks(bx, by, bz, travel, x_off, &pal, &empty, air_index)?;
    let bounds = reference.bounds(4);

    let mut json = String::from("[");
    for g in 0..n_genomes {
        let slice = &cells[g * volume..(g + 1) * volume];
        let structure = structure_from_blocks(bx, by, bz, travel, x_off, &pal, slice, air_index)?;
        let mut world = mc_tick::World::new(bounds);
        structure.place(&mut world, &mut registry, mc_tick::Pos::new(0, 0, 0));
        let graph = mc_tick::machine_graph::analyse(&world, &registry, &rules);
        let codes: Vec<&str> = graph.rejections.iter().map(|r| r.code).collect();
        let engine_cells: usize = graph.engines.iter().map(|e| e.cells.len()).sum();
        if g > 0 {
            json.push(',');
        }
        let _ = write!(
            json,
            "[{},{},{},{},{},\"{}\"]",
            graph.rejected(),
            graph.rejected_for_sustained(),
            engine_cells,
            graph.payload.len(),
            graph.dead_weight.len(),
            codes.join("|")
        );
    }
    json.push(']');
    Ok(json)
}

/// Build the machine graph for a world, deriving the movability rules it needs.
///
/// `Simulation` does not keep the [`mc_tick::vanilla::VanillaRules`] its wiring
/// produced, so they are rebuilt against a *clone* of the registry: cloning
/// preserves every existing [`mc_tick::StateId`], so the rules are valid for the
/// caller's world, and re-registering cannot disturb a live simulation.
fn analyse_world(
    world: &mc_tick::World,
    registry: &mc_tick::StateRegistry,
) -> mc_tick::machine_graph::MachineGraph {
    let rules = rebuild_rules(registry);
    mc_tick::machine_graph::analyse(world, registry, &rules)
}

/// Rebuild the [`mc_tick::VanillaRules`] a simulation's wiring produced but
/// did not keep, against a *clone* of its registry: cloning preserves every
/// existing [`mc_tick::StateId`], so the rules are valid for the caller's
/// world, and re-registering cannot disturb a live simulation.
fn rebuild_rules(registry: &mc_tick::StateRegistry) -> mc_tick::VanillaRules {
    let mut scratch = registry.clone();
    let mut table = mc_tick::BehaviourTable::default();
    mc_tick::register_all_at(&mut scratch, &mut table, mc_tick::Pos::new(0, 0, 0))
}

/// A power-source tree for one cell of a live simulation — see
/// [`mc_tick::VanillaRules::conduction_trace`] for the shape. The rules are
/// rebuilt per call (they carry only power tables, and the query is a
/// diagnostic, not a hot path); the comparator strengths come from the
/// simulation so a comparator-fed line traces truthfully.
fn conduction_trace_json(sim: &mc_tick::Simulation, pos: mc_tick::Pos) -> String {
    let rules = rebuild_rules(sim.registry());
    rules.conduction_trace(sim.registry(), sim.world(), sim.comparator_outputs(), pos)
}

/// Write every settled non-air state of `sim` back into `schem`, mapping the
/// simulation's `(0, 0, 0)` onto the schematic's bounding-box minimum — the
/// inverse of how `from_schematic` loaded it. Returns how many blocks changed.
pub(crate) fn bake_into(sim: &mc_tick::Simulation, schem: &mut crate::UniversalSchematic) -> u32 {
    let (mx, my, mz) = schem.get_bounding_box().min;
    let mut changed = 0u32;
    for (pos, id) in sim.world().iter_non_air() {
        let Some(descriptor) = sim.registry().descriptor(id) else {
            continue;
        };
        let (x, y, z) = (pos.x + mx, pos.y + my, pos.z + mz);
        // Comparing rendered strings, because both sides render sorted
        // properties; a cell the settle never touched writes nothing.
        if schem
            .get_block(x, y, z)
            .is_some_and(|current| current.to_string() == descriptor)
        {
            continue;
        }
        if schem.set_block_from_string(x, y, z, descriptor).is_ok() {
            changed += 1;
        }
    }
    changed
}

#[cfg(test)]
mod tests {
    use super::{
        block_entity_audit, machine_graph_batch, needs_block_entity, simulate_placement_into,
        simulate_placement_into_world, simulate_placements_into, simulate_placements_into_world,
        to_gametest_snbt,
    };
    use crate::{BlockState, UniversalSchematic};

    /// `{simulate=true}` places through the engine: a wire set next to a
    /// redstone block comes back with its real power and connections, not the
    /// default state — and the write-back also carries whatever the placement
    /// caused elsewhere.
    #[test]
    fn simulate_tag_derives_wire_power_and_connections() {
        let mut schem = UniversalSchematic::new("wired".into());
        for x in 0..4 {
            schem.set_block(x, 0, 0, &BlockState::new("minecraft:smooth_stone"));
        }
        schem.set_block(0, 1, 0, &BlockState::new("minecraft:redstone_block"));
        schem
            .set_block_from_string(1, 1, 0, "minecraft:redstone_wire{simulate=true}")
            .expect("simulated placement");
        let wire = schem.get_block(1, 1, 0).expect("wire exists").to_string();
        assert!(
            wire.contains("power=15"),
            "wire next to a redstone block reads 15, got {wire}"
        );
        assert!(
            wire.contains("west=side"),
            "wire connects toward the block powering it, got {wire}"
        );
    }

    #[test]
    fn simulate_world_tag_is_an_explicit_full_world_opt_in() {
        let mut schem = UniversalSchematic::new("wired world".into());
        for x in 0..4 {
            schem.set_block(x, 0, 0, &BlockState::new("minecraft:smooth_stone"));
        }
        schem.set_block(0, 1, 0, &BlockState::new("minecraft:redstone_block"));
        schem
            .set_block_from_string(1, 1, 0, "minecraft:redstone_wire{simulate=world}")
            .expect("full-world simulated placement");
        let wire = schem.get_block(1, 1, 0).expect("wire exists").to_string();
        assert!(
            wire.contains("power=15"),
            "unexpected full-world result: {wire}"
        );
    }

    #[test]
    fn simulated_batch_matches_sequential_convenience_placements() {
        fn base() -> UniversalSchematic {
            let mut schematic = UniversalSchematic::new("wired".into());
            for x in 0..7 {
                schematic.set_block(x, 0, 0, &BlockState::new("minecraft:smooth_stone"));
            }
            schematic.set_block(0, 1, 0, &BlockState::new("minecraft:redstone_block"));
            schematic
        }

        let positions = [(1, 1, 0), (2, 1, 0), (3, 1, 0), (4, 1, 0)];
        let mut sequential = base();
        for &(x, y, z) in &positions {
            sequential
                .set_block_from_string(x, y, z, "minecraft:redstone_wire{simulate=true}")
                .expect("sequential simulated placement");
        }

        let mut batched = base();
        let written = simulate_placements_into(&mut batched, &positions, "minecraft:redstone_wire")
            .expect("batched simulated placements");
        assert!(written >= positions.len());

        for x in 0..7 {
            for y in 0..=1 {
                assert_eq!(
                    batched.get_block(x, y, 0).map(ToString::to_string),
                    sequential.get_block(x, y, 0).map(ToString::to_string),
                    "different final state at ({x},{y},0)"
                );
            }
        }
        let last = batched
            .get_block(4, 1, 0)
            .expect("last wire exists")
            .to_string();
        assert!(last.contains("power=12"), "unexpected final wire: {last}");
    }

    #[test]
    fn simple_wire_resolver_matches_the_event_engine() {
        fn base() -> UniversalSchematic {
            let mut schematic = UniversalSchematic::new("wired".into());
            for x in 0..7 {
                schematic.set_block(x, 0, 0, &BlockState::new("minecraft:smooth_stone"));
            }
            schematic.set_block(0, 1, 0, &BlockState::new("minecraft:redstone_block"));
            schematic
        }

        let positions = [(1, 1, 0), (2, 1, 0), (3, 1, 0), (4, 1, 0)];
        let mut resolved = base();
        simulate_placements_into(&mut resolved, &positions, "minecraft:redstone_wire")
            .expect("static resolver");

        let mut simulated = base();
        simulate_placements_into_world(&mut simulated, &positions, "minecraft:redstone_wire")
            .expect("event engine");

        for x in 0..7 {
            for y in 0..=1 {
                assert_eq!(
                    resolved.get_block(x, y, 0).map(ToString::to_string),
                    simulated.get_block(x, y, 0).map(ToString::to_string),
                    "different final state at ({x},{y},0)"
                );
            }
        }
    }

    #[test]
    fn source_placement_resolver_matches_the_event_engine() {
        fn base() -> UniversalSchematic {
            let mut schematic = UniversalSchematic::new("unpowered line".into());
            for x in 0..7 {
                schematic.set_block(x, 0, 0, &BlockState::new("minecraft:smooth_stone"));
            }
            for x in 1..=4 {
                schematic
                    .set_block_from_string(
                        x,
                        1,
                        0,
                        "minecraft:redstone_wire[east=side,north=none,power=0,south=none,west=side]",
                    )
                    .unwrap();
            }
            schematic
        }

        let positions = [(0, 1, 0)];
        let mut resolved = base();
        simulate_placements_into(&mut resolved, &positions, "minecraft:redstone_block")
            .expect("static source resolver");
        let mut simulated = base();
        simulate_placements_into_world(&mut simulated, &positions, "minecraft:redstone_block")
            .expect("event engine");
        for x in 0..7 {
            for y in 0..=1 {
                assert_eq!(
                    resolved.get_block(x, y, 0).map(ToString::to_string),
                    simulated.get_block(x, y, 0).map(ToString::to_string),
                    "different final state at ({x},{y},0)"
                );
            }
        }
    }

    #[test]
    fn active_neighbour_forces_the_event_engine_fallback() {
        let mut schematic = UniversalSchematic::new("lamp".into());
        for x in 0..4 {
            schematic.set_block(x, 0, 0, &BlockState::new("minecraft:smooth_stone"));
        }
        schematic.set_block(0, 1, 0, &BlockState::new("minecraft:redstone_block"));
        schematic.set_block(
            2,
            1,
            0,
            &BlockState::from_block_string("minecraft:redstone_lamp[lit=false]").unwrap(),
        );
        simulate_placement_into(&mut schematic, 1, 1, 0, "minecraft:redstone_wire")
            .expect("wire placement beside a lamp");
        let lamp = schematic
            .get_block(2, 1, 0)
            .expect("lamp exists")
            .to_string();
        assert!(
            lamp.contains("lit=true"),
            "event side effect was lost: {lamp}"
        );
    }

    #[test]
    fn passive_resolver_skips_simulation_even_for_a_sparse_batch() {
        let mut schematic = UniversalSchematic::new("sparse passive edits".into());
        schematic.set_block(0, 0, 0, &BlockState::new("minecraft:smooth_stone"));
        let positions = [(10, 0, 0), (10_000_000, 0, 0)];
        let written =
            simulate_placements_into(&mut schematic, &positions, "minecraft:quartz_block")
                .expect("passive writes need no bounded simulated world");
        assert_eq!(written, 2);
        for &(x, y, z) in &positions {
            assert_eq!(
                schematic
                    .get_block(x, y, z)
                    .expect("block exists")
                    .get_name(),
                "minecraft:quartz_block"
            );
        }
    }

    #[test]
    fn local_simulation_cost_ignores_unrelated_world_span() {
        let mut local = UniversalSchematic::new("sparse world".into());
        for x in 0..4 {
            local.set_block(x, 0, 0, &BlockState::new("minecraft:smooth_stone"));
        }
        local.set_block(0, 1, 0, &BlockState::new("minecraft:redstone_block"));
        local.set_block(10_000_000, 0, 0, &BlockState::new("minecraft:smooth_stone"));

        let mut whole_world = local.clone();
        let full_error =
            simulate_placement_into_world(&mut whole_world, 1, 1, 0, "minecraft:redstone_wire")
                .expect_err("the complete sparse span is intentionally over the world limit");
        assert!(full_error.contains("over the 8000000-cell limit"));

        simulate_placement_into(&mut local, 1, 1, 0, "minecraft:redstone_wire")
            .expect("local component remains small");
        let wire = local.get_block(1, 1, 0).expect("wire exists").to_string();
        assert!(wire.contains("power=15"), "unexpected local result: {wire}");
        assert_eq!(
            local
                .get_block(10_000_000, 0, 0)
                .expect("unrelated environment survives")
                .get_name(),
            "minecraft:smooth_stone"
        );
    }

    /// The tag on an isolated placement (or the first block of an empty
    /// schematic) degrades to a plain write instead of refusing.
    #[test]
    fn simulate_tag_on_an_isolated_block_is_a_plain_write() {
        let mut schem = UniversalSchematic::new("empty".into());
        schem
            .set_block_from_string(0, 0, 0, "minecraft:redstone_wire{simulate=true}")
            .expect("plain write");
        let wire = schem.get_block(0, 0, 0).expect("wire exists").to_string();
        assert!(wire.contains("redstone_wire"), "got {wire}");
    }

    /// Combining simulate with the other brace shorthands is refused, not
    /// half-honoured.
    #[test]
    fn simulate_tag_refuses_company_in_the_braces() {
        let mut schem = UniversalSchematic::new("combo".into());
        let err = schem
            .set_block_from_string(0, 0, 0, "minecraft:barrel{signal=3,simulate=true}")
            .unwrap_err();
        assert!(err.contains("only tag"), "got {err}");
    }

    /// The GA's pre-filter contract, over the batch path it actually calls.
    ///
    /// Two genomes in one call: engine B, which must survive both tiers, and a
    /// lone slime block, which must be rejected outright. The order of the rows
    /// is the order of the genomes — the app maps them back positionally, so a
    /// silent reordering here would score the wrong machines zero.
    #[test]
    fn the_batch_prefilter_keeps_an_engine_and_rejects_a_lone_block() {
        // Same palette shape the app builds: air first, then the alphabet.
        const PALETTE: &str = "minecraft:air;minecraft:slime_block;\
            minecraft:sticky_piston[extended=false,facing=east];\
            minecraft:sticky_piston[extended=false,facing=west];\
            minecraft:observer[facing=east,powered=false];\
            minecraft:observer[facing=west,powered=false]";
        // bbox 4x1x2. `structure_from_blocks` walks y, then z, then x.
        // z=0: obsW slime stickyW  _        z=1: _ stickyE slime obsE
        let engine_b: [u16; 8] = [5, 1, 3, 0, 0, 2, 1, 4];
        let lone_slime: [u16; 8] = [0, 1, 0, 0, 0, 0, 0, 0];
        let mut cells = engine_b.to_vec();
        cells.extend_from_slice(&lone_slime);

        let json =
            machine_graph_batch(4, 1, 2, 26, 1, PALETTE, &cells, 0).expect("batch analysis runs");

        // [rejected, rejected_for_sustained, engine, payload, dead, "codes"]
        let rows: Vec<&str> = json
            .trim_start_matches('[')
            .trim_end_matches(']')
            .split("],[")
            .map(|r| r.trim_matches(|c| c == '[' || c == ']'))
            .collect();
        assert_eq!(rows.len(), 2, "one row per genome: {json}");

        assert!(
            rows[0].starts_with("false,false,"),
            "engine B must survive both filter tiers, got {}",
            rows[0]
        );
        assert!(
            rows[0].contains(",6,"),
            "engine B's engine is its six blocks, got {}",
            rows[0]
        );
        assert!(
            rows[1].starts_with("true,true,"),
            "a lone slime block cannot move, got {}",
            rows[1]
        );
        assert!(
            rows[1].contains("no_piston"),
            "and the reason is why: {}",
            rows[1]
        );
    }

    /// A 1.12 build must reach the engine flattened.
    ///
    /// The trap this pins is `minecraft:slime`: in 1.12 that is the *slime
    /// block*, and no modern block has the id — so an unconverted bore loads
    /// with every sticky cell inert and simulates as a machine that cannot
    /// fly, without erroring anywhere.
    #[test]
    fn pre_flattening_ids_are_converted_before_the_engine_sees_them() {
        let mut schem = UniversalSchematic::new("legacy".into());
        schem.metadata.source_data_version = Some(1343); // 1.12.2
        schem.set_block(0, 0, 0, &BlockState::new("minecraft:slime"));
        // 1.12 stored the sub-type as a property; the flattening rules key on
        // it, so a realistic file carries `variant` and a bare id does not
        // convert. Real .litematic/.schem imports always have it.
        schem.set_block(
            1,
            0,
            0,
            &BlockState::new("minecraft:stonebrick").with_property("variant", "stonebrick"),
        );

        let snbt = to_gametest_snbt(&schem);
        assert!(
            snbt.contains("minecraft:slime_block"),
            "slime block not flattened: {snbt}"
        );
        assert!(
            snbt.contains("minecraft:stone_bricks"),
            "stone brick not flattened: {snbt}"
        );
        assert!(
            !snbt.contains("\"minecraft:slime\""),
            "the 1.12 id survived into the engine's input: {snbt}"
        );
    }

    #[test]
    fn modern_builds_are_passed_through_untouched() {
        let mut schem = UniversalSchematic::new("modern".into());
        schem.metadata.source_data_version = Some(3955);
        schem.set_block(0, 0, 0, &BlockState::new("minecraft:slime_block"));
        assert!(to_gametest_snbt(&schem).contains("minecraft:slime_block"));
    }

    #[test]
    fn audit_names_blocks_whose_block_entity_is_missing() {
        let mut schem = UniversalSchematic::new("stripped".into());
        schem.set_block(0, 0, 0, &BlockState::new("minecraft:comparator"));
        schem.set_block(1, 0, 0, &BlockState::new("minecraft:comparator"));
        schem.set_block(2, 0, 0, &BlockState::new("minecraft:furnace"));
        // Carries no block-entity state that ticks; must not be reported.
        schem.set_block(3, 0, 0, &BlockState::new("minecraft:stone"));

        let json = block_entity_audit(&schem);
        assert!(json.contains("\"missing_total\":3"), "{json}");
        assert!(
            json.contains("\"name\":\"minecraft:comparator\",\"count\":2"),
            "{json}"
        );
        assert!(
            json.contains("\"name\":\"minecraft:furnace\",\"count\":1"),
            "{json}"
        );
        assert!(
            !json.contains("stone"),
            "a block with no ticking NBT was reported: {json}"
        );
        assert!(
            json.contains("2 comparators"),
            "summary not written: {json}"
        );
    }

    #[test]
    fn audit_is_silent_when_nothing_is_missing() {
        let mut schem = UniversalSchematic::new("plain".into());
        schem.set_block(0, 0, 0, &BlockState::new("minecraft:stone"));
        let json = block_entity_audit(&schem);
        assert!(json.contains("\"missing_total\":0"), "{json}");
        assert!(json.contains("\"summary\":\"\""), "{json}");
    }

    #[test]
    fn every_colour_of_shulker_box_counts_as_a_container() {
        assert!(needs_block_entity("minecraft:shulker_box"));
        assert!(needs_block_entity("minecraft:lime_shulker_box"));
        assert!(!needs_block_entity("minecraft:oak_sign"));
    }

    /// Entities survive the trip from schematic to engine input.
    ///
    /// The converter used to write a hardcoded `entities: []`, so a build whose
    /// mechanism depends on entities loaded clean and simulated as though they
    /// were not there. This asserts the whole path: emitted, re-read by the
    /// engine's own parser, with the fields that change a run intact.
    #[test]
    fn entities_round_trip_from_schematic_into_the_engines_parser() {
        use crate::entity::{Entity, NbtValue};
        use std::collections::HashMap;

        let mut schem = UniversalSchematic::new("carts".into());
        // Away from the origin on purpose: entity positions are absolute in
        // the schematic and structure-relative in the SNBT, so a missing
        // `bb.min` shift would sail through a build placed at 0,0,0.
        schem.set_block(10, 0, 5, &BlockState::new("minecraft:rail"));
        schem.set_block(12, 2, 7, &BlockState::new("minecraft:stone"));

        let mut cart = Entity::new("minecraft:minecart".into(), (10.5, 0.0625, 5.5));
        cart.nbt.insert(
            "Motion".into(),
            NbtValue::List(vec![
                NbtValue::Double(0.25),
                NbtValue::Double(0.0),
                NbtValue::Double(-0.5),
            ]),
        );
        assert!(schem.add_entity(cart));

        let mut stack = HashMap::new();
        stack.insert(
            "id".to_string(),
            NbtValue::String("minecraft:redstone".into()),
        );
        stack.insert("count".to_string(), NbtValue::Byte(7));
        let mut item = Entity::new("minecraft:item".into(), (11.5, 1.0, 6.5));
        item.nbt.insert("Item".into(), NbtValue::Compound(stack));
        item.nbt.insert("PickupDelay".into(), NbtValue::Short(40));
        assert!(schem.add_entity(item));

        let snbt = to_gametest_snbt(&schem);
        let parsed = mc_tick::Structure::parse(&snbt)
            .unwrap_or_else(|e| panic!("engine rejected our own output: {e}\n{snbt}"));

        assert_eq!(parsed.entities.len(), 2, "entities dropped: {snbt}");
        match &parsed.entities[0] {
            mc_tick::structure::SpawnedEntity::Minecart(cart) => {
                assert_eq!(cart.kind, "minecraft:minecart");
                assert_eq!(
                    cart.pos,
                    [0.5, 0.0625, 0.5],
                    "position not shifted into structure space"
                );
                assert_eq!(cart.motion, [0.25, 0.0, -0.5]);
            }
            other => panic!("expected a minecart, got {other:?}"),
        }
        match &parsed.entities[1] {
            mc_tick::structure::SpawnedEntity::Item(item) => {
                assert_eq!(item.pos, [1.5, 1.0, 1.5]);
                assert_eq!(item.item, ("minecraft:redstone".to_string(), 7));
                assert_eq!(item.pickup_delay, 40);
            }
            other => panic!("expected an item, got {other:?}"),
        }
        // The same list also reaches the item-entity view the simulator spawns from.
        assert_eq!(parsed.item_entities.len(), 1);
    }

    /// A denormal motion must not corrupt the entity it belongs to.
    ///
    /// Real furnace minecarts in the 55_3x3 door carry motions like 4.3e-59.
    /// Written with an exponent, the engine's reader takes `4.3` and `-59` as
    /// two numbers, turning a three-element `Motion` into four — which it then
    /// silently discards. The value has to be spelled out in full.
    #[test]
    fn tiny_motions_are_written_without_an_exponent() {
        use crate::entity::{Entity, NbtValue};

        let mut schem = UniversalSchematic::new("denormal".into());
        schem.set_block(0, 0, 0, &BlockState::new("minecraft:rail"));
        let mut cart = Entity::new("minecraft:minecart".into(), (0.5, 0.0, 0.5));
        cart.nbt.insert(
            "Motion".into(),
            NbtValue::List(vec![
                NbtValue::Double(4.27987680632209e-59),
                NbtValue::Double(0.0),
                NbtValue::Double(0.0),
            ]),
        );
        assert!(schem.add_entity(cart));

        let snbt = to_gametest_snbt(&schem);
        let (_, entities) = snbt.split_once("entities:").expect("an entities section");
        assert!(
            !entities.contains("e-") && !entities.contains("e+"),
            "an exponent reached the engine's input: {entities}"
        );

        let parsed = mc_tick::Structure::parse(&snbt).expect("parse");
        match &parsed.entities[0] {
            mc_tick::structure::SpawnedEntity::Minecart(cart) => {
                assert_eq!(cart.motion, [4.27987680632209e-59, 0.0, 0.0]);
            }
            other => panic!("expected a minecart, got {other:?}"),
        }
    }

    /// A nan cart's velocity must reach the engine as NaN, not as zero.
    ///
    /// These exact numbers are lifted from `55_3x3.zip`: a furnace minecart
    /// whose `Motion` is `[4.27987680632209e-59, 0.0, NaN]`. The NaN is the
    /// mechanism — it is what makes the cart's physics dead so it can be used
    /// as glue — so rewriting it to 0.0 turns the cart back into an ordinary
    /// one that moves, and the door quietly falls apart. This pins both halves
    /// at once: the denormal must not become an exponent, and the NaN must not
    /// become a number.
    #[test]
    fn a_nan_cart_velocity_survives_the_round_trip() {
        use crate::entity::{Entity, NbtValue};

        let mut schem = UniversalSchematic::new("nan cart".into());
        schem.set_block(0, 0, 0, &BlockState::new("minecraft:rail"));
        let mut cart = Entity::new("minecraft:minecart".into(), (0.5, 0.0, 0.5));
        cart.nbt.insert(
            "Motion".into(),
            NbtValue::List(vec![
                NbtValue::Double(4.27987680632209e-59),
                NbtValue::Double(0.0),
                NbtValue::Double(f64::NAN),
            ]),
        );
        assert!(schem.add_entity(cart));

        let snbt = to_gametest_snbt(&schem);
        let parsed = mc_tick::Structure::parse(&snbt)
            .unwrap_or_else(|e| panic!("a NaN motion must parse, not error: {e}\n{snbt}"));

        match &parsed.entities[0] {
            mc_tick::structure::SpawnedEntity::Minecart(cart) => {
                assert_eq!(
                    cart.motion[0], 4.27987680632209e-59,
                    "denormal mangled: {snbt}"
                );
                assert_eq!(cart.motion[1], 0.0);
                assert!(
                    cart.motion[2].is_nan(),
                    "the NaN was sanitised to {} — this un-glues the door: {snbt}",
                    cart.motion[2]
                );
            }
            other => panic!("expected a minecart, got {other:?}"),
        }
    }

    /// The ±Infinity that a nan cart is made from round-trips too.
    ///
    /// Overflowed-but-not-yet-collided carts hold these, and a build captured
    /// mid-sequence carries them. Signed, because `+Inf` and `-Inf` are what
    /// collide to produce the NaN in the first place.
    #[test]
    fn infinite_velocities_survive_the_round_trip() {
        use crate::entity::{Entity, NbtValue};

        let mut schem = UniversalSchematic::new("overflowed".into());
        schem.set_block(0, 0, 0, &BlockState::new("minecraft:rail"));
        let mut cart = Entity::new("minecraft:minecart".into(), (0.5, 0.0, 0.5));
        cart.nbt.insert(
            "Motion".into(),
            NbtValue::List(vec![
                NbtValue::Double(f64::INFINITY),
                NbtValue::Double(f64::NEG_INFINITY),
                NbtValue::Double(0.0),
            ]),
        );
        assert!(schem.add_entity(cart));

        let snbt = to_gametest_snbt(&schem);
        let parsed = mc_tick::Structure::parse(&snbt).expect("infinities must parse");
        match &parsed.entities[0] {
            mc_tick::structure::SpawnedEntity::Minecart(cart) => {
                assert_eq!(cart.motion[0], f64::INFINITY);
                assert_eq!(
                    cart.motion[1],
                    f64::NEG_INFINITY,
                    "the sign was lost: {snbt}"
                );
            }
            other => panic!("expected a minecart, got {other:?}"),
        }
    }

    /// The record 3x3 door sample, as a schematic.
    fn record_door_schematic() -> UniversalSchematic {
        let path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/samples/55_3x3.zip");
        let bytes = std::fs::read(&path).expect("the record-door sample must be present");
        crate::formats::world::from_world_zip(&bytes).expect("the sample loads")
    }

    /// How many of a run's minecarts hold a NaN anywhere in their velocity.
    ///
    /// The carts the record door is glued together by. Counted off the live
    /// simulation rather than off the text, because the question is what
    /// `Entity.load` did with the token, not whether the token was written.
    fn nan_carts(sim: &mc_tick::Simulation) -> usize {
        sim.minecarts()
            .iter()
            .filter(|c| c.vel.iter().any(|v| v.is_nan()))
            .count()
    }

    /// Load gametest SNBT through the shipped bridge entry point.
    fn from_snbt(snbt: &str) -> mc_tick::Simulation {
        super::ffi::TickSimulation::from_snbt(
            snbt.as_bytes(),
            super::ffi::TickSettleMode::InWorld,
            0,
            0,
            0,
            b"",
        )
        .expect("the round-tripped text must load")
        .sim
    }

    /// A lever driving a dust line: the settled world bakes back into the
    /// schematic with real wire power, and the far dust's conduction trace
    /// walks the chain back to the lever.
    #[test]
    fn a_settled_line_bakes_back_and_traces_to_its_lever() {
        let mut schem = UniversalSchematic::new("line".into());
        for x in 0..3 {
            schem.set_block(x, 0, 0, &BlockState::new("minecraft:smooth_stone"));
        }
        schem
            .set_block_from_string(
                0,
                1,
                0,
                "minecraft:lever[face=floor,facing=north,powered=true]",
            )
            .expect("lever");
        for x in 1..3 {
            schem
                .set_block_from_string(
                    x,
                    1,
                    0,
                    "minecraft:redstone_wire[east=none,north=none,power=0,south=none,west=none]",
                )
                .expect("wire");
        }
        let mut sim = super::ffi::TickSimulation::from_snbt(
            to_gametest_snbt(&schem).as_bytes(),
            super::ffi::TickSettleMode::Placement,
            0,
            0,
            0,
            b"",
        )
        .expect("the line loads")
        .sim;
        sim.run_until_quiescent(64);

        let trace = super::conduction_trace_json(&sim, mc_tick::Pos::new(2, 1, 0));
        assert!(
            trace.contains("\"kind\":\"wire\",\"power\":14"),
            "the far dust carries 14: {trace}"
        );
        assert!(
            trace.contains("\"mechanism\":\"wire\""),
            "it is fed by a one-level wire step: {trace}"
        );
        assert!(
            trace.contains("minecraft:lever"),
            "the tree reaches the lever: {trace}"
        );

        let changed = super::bake_into(&sim, &mut schem);
        assert!(changed >= 2, "both dust cells changed, got {changed}");
        let near = schem.get_block(1, 1, 0).expect("dust stays").to_string();
        assert!(
            near.contains("power=15"),
            "the baked schematic carries settled power: {near}"
        );
        assert_eq!(
            super::bake_into(&sim, &mut schem),
            0,
            "a second bake finds nothing left to write"
        );
    }

    /// A schematic's own DataVersion reaches the engine through the SNBT.
    ///
    /// The write half of the round trip. `to_gametest_snbt` used to stamp the
    /// canonical oracle version unconditionally, throwing the source's away
    /// before any reader could see it.
    #[test]
    fn the_emitted_snbt_states_the_schematics_own_data_version() {
        let mut schem = UniversalSchematic::new("versioned".into());
        schem.set_block(0, 0, 0, &BlockState::new("minecraft:stone"));

        schem.metadata.source_data_version = Some(4082);
        let snbt = to_gametest_snbt(&schem);
        assert!(
            snbt.contains("DataVersion: 4082"),
            "the file's own version must win: {snbt}"
        );
        assert_eq!(
            mc_tick::Structure::parse(&snbt)
                .expect("parses")
                .data_version,
            Some(4082),
            "and it must survive being read back"
        );

        // No provenance is not evidence of an old save, so it falls back to the
        // canonical version — a value, not a silent absence.
        schem.metadata.source_data_version = None;
        schem.metadata.mc_version = None;
        let snbt = to_gametest_snbt(&schem);
        assert!(
            snbt.contains(&format!(
                "DataVersion: {}",
                crate::dataconverter::CANONICAL_DATA_VERSION
            )),
            "a schematic with no version must still stamp one: {snbt}"
        );
    }

    /// `gametest_snbt` → `from_snbt` must not un-glue a nan-cart build.
    ///
    /// The NaN *token* always survived the text; the *load rule* did not. The
    /// emitted SNBT hardcoded the canonical oracle version (>= 4671) and
    /// mc-tick's parser never read `DataVersion` at all, so `from_snbt` chose
    /// `drop_non_finite` for a 1.21.3 save and its six nan carts came back as
    /// ordinary carts — live physics, in a machine whose whole construction
    /// depends on dead physics.
    ///
    /// `from_schematic` is the reference: it has always read the version off the
    /// file. Both sides assert `motion_semantics` *and* the cart count, because
    /// either alone can pass for the wrong reason — the semantics could be right
    /// while the entities were dropped, and the count could be right on a build
    /// that never had a NaN.
    #[test]
    fn the_snbt_round_trip_keeps_the_record_doors_nan_carts() {
        let schematic = record_door_schematic();
        assert_eq!(
            schematic.metadata.source_data_version,
            Some(4082),
            "the record door is a 1.21.3 save — if that changed, this test is measuring nothing"
        );

        let direct = wire_record_door(super::ffi::TickSettleMode::InWorld);
        assert_eq!(
            direct.motion_semantics(),
            mc_tick::MotionSemantics::ClampAbsTen,
            "4082 is below the boundary, so a cold load keeps NaN"
        );
        assert_eq!(nan_carts(&direct), 6, "the reference path's nan carts");

        let snbt = to_gametest_snbt(&schematic);
        let round_tripped = from_snbt(&snbt);
        assert_eq!(
            round_tripped.motion_semantics(),
            mc_tick::MotionSemantics::ClampAbsTen,
            "the round trip changed which game loaded the door"
        );
        assert_eq!(
            nan_carts(&round_tripped),
            nan_carts(&direct),
            "the same door, through its own SNBT, must be the same machine"
        );
    }

    /// The negative control: after the boundary, the NaN really is dropped.
    ///
    /// Without this, the test above could pass by the engine having simply
    /// stopped sanitising anything, which would be a different bug wearing the
    /// same result. The identical door stamped 4671 must lose every nan cart.
    #[test]
    fn a_build_stamped_after_the_boundary_still_drops_its_nan_carts() {
        let mut schematic = record_door_schematic();
        schematic.metadata.source_data_version =
            Some(mc_tick::motion::FIRST_NAN_DROPPING_DATA_VERSION);

        let snbt = to_gametest_snbt(&schematic);
        assert!(
            snbt.contains("DataVersion: 4671"),
            "the restamp must reach the text"
        );
        let sim = from_snbt(&snbt);
        assert_eq!(
            sim.motion_semantics(),
            mc_tick::MotionSemantics::DropNonFinite,
            "4671 and later guard the whole vector on `isFinite`"
        );
        assert_eq!(
            nan_carts(&sim),
            0,
            "the same six carts must come back finite — the door is un-glued, correctly"
        );
    }

    /// Load the record 3x3 door sample and wire it under `settle`.
    ///
    /// This goes through the product path — world zip, schematic, gametest
    /// SNBT, `wire_simulation` — because the question is about that path and a
    /// test that reached past it would answer a different one.
    fn wire_record_door(settle: super::ffi::TickSettleMode) -> mc_tick::Simulation {
        let schematic = record_door_schematic();
        let snbt = to_gametest_snbt(&schematic);
        let structure = mc_tick::Structure::parse(&snbt).expect("the sample parses");
        super::wire_simulation(
            &structure,
            mc_tick::Pos::new(0, 0, 0),
            settle,
            &[],
            schematic.metadata.source_data_version,
        )
        .expect("the engine must accept the record door")
    }

    /// A build cut out of a running world must load into that world's state.
    ///
    /// `--in-world` capture of this same save records **zero** block changes:
    /// the door is at rest in the game, so it must be at rest in us. The mode
    /// that means "the build *is* the world" is `InWorld`, and this pins that
    /// it genuinely places nothing and settles nothing.
    ///
    /// The `Quiet` half is the negative control, and it is not decoration —
    /// it is the entire reason this test is trustworthy. `Quiet` runs
    /// [`Simulation::place_on_place`], which blanks the region to air and
    /// re-writes every block one at a time, handing each landing block's
    /// already-placed neighbours a shape update. Every observer in the build
    /// therefore watches its facing neighbour *appear*, and pulses. That is
    /// correct for a paste and catastrophic for a load, and it is what made
    /// this door look like it actuated itself: the diagnostic was asking for
    /// `Quiet`. If the two modes ever stop differing here, one of them has
    /// silently become the other and this assertion says so.
    #[test]
    fn the_record_door_is_at_rest_under_in_world_and_disturbed_under_quiet() {
        let mut at_rest = wire_record_door(super::ffi::TickSettleMode::InWorld);
        at_rest.run(200);
        assert_eq!(
            at_rest.recorded().len(),
            0,
            "nobody touched this door: vanilla changes no block ticking the same save in \
             place, so neither may we. First few: {:?}",
            at_rest.recorded().iter().take(4).collect::<Vec<_>>()
        );
        assert!(
            at_rest.is_quiescent(),
            "a build at rest has nothing pending"
        );

        // The control. Placement *should* perturb this build, and if it does
        // not then the assertion above is passing for the wrong reason.
        let mut placed = wire_record_door(super::ffi::TickSettleMode::Quiet);
        placed.run(200);
        assert!(
            !placed.recorded().is_empty(),
            "placing this build must disturb it — an observer whose neighbour just \
             appeared pulses. If this is empty, `InWorld` proves nothing."
        );
    }

    /// The record door's two blazes are **passengers**, and they are now here.
    ///
    /// The save holds 22 top-level entities; vanilla's own capture of it
    /// (`tools/gametest/captures/door55_in_world.entities.log`) counts 24,
    /// because two of the four plain minecarts carry a `minecraft:blaze` in
    /// their `Passengers` list. This asserts both halves — that the top level is
    /// still 22, so the 24 cannot be a miscount of it, and that the two extra
    /// bodies are blazes seated at exactly the y the save records.
    ///
    /// `2.2500` and `2.1875` are lifted from the file, not from the seat
    /// constant: each is its vehicle's y plus 0.1875, which is what
    /// `blaze_ride.entities.log` measures a blaze's seat on a minecart to be,
    /// and getting them from the door as well makes this two independent
    /// measurements agreeing rather than one restated.
    #[test]
    fn the_record_doors_two_blazes_are_seated_passengers() {
        let path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/samples/55_3x3.zip");
        let bytes = std::fs::read(&path).expect("the record-door sample must be present");
        let schematic = crate::formats::world::from_world_zip(&bytes).expect("the sample loads");
        let snbt = to_gametest_snbt(&schematic);
        let structure = mc_tick::Structure::parse(&snbt).expect("the sample parses");
        assert_eq!(
            structure.entities.len(),
            22,
            "the control: the *top level* is 22, so a 24 below cannot be a recount \
             of it — the two extra bodies have to come from somewhere else"
        );

        let sim = wire_record_door(super::ffi::TickSettleMode::InWorld);
        assert_eq!(
            sim.entity_bodies().len(),
            24,
            "22 top-level entities plus two riders is what vanilla counts in this world"
        );

        let riders = sim.riders();
        assert_eq!(
            riders.len(),
            2,
            "two blazes ride two of the four plain carts"
        );
        let mut seats: Vec<f64> = riders
            .iter()
            .map(|(_, kind, pos)| {
                assert_eq!(kind, "minecraft:blaze");
                pos[1]
            })
            .collect();
        seats.sort_by(f64::total_cmp);
        assert_eq!(seats, vec![2.1875, 2.25], "the exact y the save records");

        // And each sits 0.1875 above the cart it is on, horizontally identical.
        for (_, _, pos) in &riders {
            let vehicle = sim
                .minecarts()
                .iter()
                .find(|c| (c.pos[1] + 0.1875 - pos[1]).abs() < 1.0e-12)
                .expect("every rider has a vehicle 0.1875 below it");
            assert_eq!([vehicle.pos[0], vehicle.pos[2]], [pos[0], pos[2]]);
        }
    }

    /// Wire a one-rail structure carrying `entities`, as the app would.
    fn wire_with_entities(entities: &str) -> Result<mc_tick::Simulation, String> {
        let snbt = format!(
            "{{DataVersion: 4903, size: [1, 1, 1], \
              palette: [{{Name: \"minecraft:rail\"}}], \
              blocks: [{{pos: [0, 0, 0], state: 0}}], entities: [{entities}]}}"
        );
        let structure = mc_tick::Structure::parse(&snbt)
            .unwrap_or_else(|e| panic!("the parser must accept this: {e}\n{snbt}"));
        super::wire_simulation(
            &structure,
            mc_tick::Pos::new(0, 0, 0),
            super::ffi::TickSettleMode::InWorld,
            &[],
            None,
        )
    }

    /// The refusal moved from the parser to the simulator, and still names the
    /// type — but it now fires on *capability*, not on the type existing.
    ///
    /// Furnace carts, fireballs and villagers all load today, as the mass and
    /// hitboxes the record doors use them for. What is refused is any of them
    /// that would need behaviour nobody has implemented: a cart with fuel to
    /// drive itself, a fireball with velocity to fly, a villager with velocity
    /// to walk. That distinction is the whole gate — running one of those as a
    /// stationary box is a confident wrong answer, and the wrongness is
    /// invisible unless it is refused here.
    #[test]
    fn entities_needing_unimplemented_behaviour_are_refused_by_name() {
        for (entity, expected) in [
            (
                r#"{pos: [0.5d, 0.0d, 0.5d], nbt: {id: "minecraft:furnace_minecart", Fuel: 3600}}"#,
                "minecraft:furnace_minecart",
            ),
            (
                r#"{pos: [0.5d, 0.0d, 0.5d], nbt: {id: "minecraft:furnace_minecart", PushX: 1.0d}}"#,
                "minecraft:furnace_minecart",
            ),
            (
                r#"{pos: [0.5d, 0.0d, 0.5d], nbt: {id: "minecraft:dragon_fireball", Motion: [0.5d, 0.0d, 0.0d]}}"#,
                "minecraft:dragon_fireball",
            ),
            (
                r#"{pos: [0.5d, 0.0d, 0.5d], nbt: {id: "minecraft:small_fireball", Motion: [0.0d, -0.1d, 0.0d]}}"#,
                "minecraft:small_fireball",
            ),
            (
                r#"{pos: [0.5d, 0.0d, 0.5d], nbt: {id: "minecraft:villager", Motion: [0.0d, 0.0d, 0.2d]}}"#,
                "minecraft:villager",
            ),
        ] {
            let error = wire_with_entities(entity)
                .err()
                .unwrap_or_else(|| panic!("{expected} needs behaviour that does not exist"));
            assert!(
                error.contains(expected),
                "refusal does not name the type: {error}"
            );
        }
    }

    /// The scaffolding the record doors actually contain does load.
    ///
    /// An unfuelled furnace cart, a frozen fireball of each size and a
    /// motionless villager: mass and hitboxes, which is all those builds ask
    /// of them. Without this, a gate that refused every one of these types
    /// would pass the test above and look correct.
    #[test]
    fn frozen_scaffolding_entities_load_as_hitboxes() {
        let sim = wire_with_entities(
            r#"{pos: [0.5d, 0.0625d, 0.5d], nbt: {id: "minecraft:furnace_minecart", Fuel: 0}},
               {pos: [1.5d, 1.0d, 0.5d], nbt: {id: "minecraft:dragon_fireball"}},
               {pos: [2.5d, 1.0d, 0.5d], nbt: {id: "minecraft:small_fireball"}},
               {pos: [3.5d, 1.0d, 0.5d], nbt: {id: "minecraft:villager"}}"#,
        )
        .expect("the record doors' scaffolding is exactly what this supports");
        assert_eq!(sim.minecarts().len(), 1, "a furnace cart is a cart");
        let frozen: Vec<&str> = sim
            .entity_bodies()
            .iter()
            .filter(|b| !b.is_minecart)
            .map(|b| b.kind.as_str())
            .collect();
        assert_eq!(
            frozen,
            [
                "minecraft:dragon_fireball",
                "minecraft:small_fireball",
                "minecraft:villager"
            ],
            "each keeps its own identity, because each has its own hitbox"
        );
    }

    /// Negative control: the gate refuses the unmodelled, not everything.
    ///
    /// Without this, a gate that rejected every build in existence would pass
    /// the test above and look correct.
    #[test]
    fn entities_that_do_have_behaviour_still_load() {
        let sim = wire_with_entities(
            r#"{pos: [0.5d, 0.0625d, 0.5d], nbt: {id: "minecraft:minecart", Motion: [0.0d, 0.0d, 0.0d]}},
               {pos: [0.5d, 1.0d, 0.5d], nbt: {id: "minecraft:item", Item: {id: "minecraft:redstone", count: 1b}}}"#,
        )
        .expect("a plain cart and an item are both simulated today");
        assert_eq!(sim.minecarts().len(), 1, "the cart should be live");
        assert_eq!(sim.item_entities().len(), 1, "the item should be live");
    }

    /// A type the reader cannot even represent is still refused by name.
    ///
    /// This is the *other* refusal — not "no behaviour yet" but "no idea what
    /// this is". A creeper has no `SpawnedEntity` variant, so it cannot be
    /// carried at all, and saying so beats inventing a shape for it.
    #[test]
    fn an_unrepresentable_entity_is_refused_and_named() {
        use crate::entity::Entity;

        let mut schem = UniversalSchematic::new("creeper".into());
        schem.set_block(0, 0, 0, &BlockState::new("minecraft:rail"));
        assert!(schem.add_entity(Entity::new("minecraft:creeper".into(), (0.5, 0.0, 0.5))));

        let snbt = to_gametest_snbt(&schem);
        let err = mc_tick::Structure::parse(&snbt).expect_err("should refuse the creeper");
        assert!(
            matches!(
                &err,
                mc_tick::structure::StructureError::UnsupportedEntity { entity_type, .. }
                    if entity_type == "minecraft:creeper"
            ),
            "wrong error: {err}"
        );
        // And the sentence the app shows blames the build, not the converter.
        let detail = super::structure_parse_detail(&err, true);
        assert!(detail.contains("minecraft:creeper"), "{detail}");
        assert!(!detail.contains("engine fault"), "{detail}");
    }
}