rusting_engine 2.0.3

Vulkan 3D game engine with GPU-accelerated physics for massive physics-heavy scenes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
//! Windowed runtime runner for native Rust game projects.

use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::Arc;
use std::time::Instant;

use bevy_ecs::entity::Entity;
use bevy_ecs::prelude::{Mut, Resource, World};
use vulkano::format::Format;
use vulkano::image::ImageUsage;
use vulkano::swapchain::Surface;
use vulkano::VulkanError;
use vulkano_util::context::VulkanoContext;
use vulkano_util::window::{VulkanoWindows, WindowDescriptor};
use winit::application::ApplicationHandler;
use winit::dpi::PhysicalSize;
use winit::event::{DeviceEvent, DeviceId, WindowEvent};
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::keyboard::PhysicalKey;
use winit::window::{CursorGrabMode, Fullscreen, Window, WindowId};

use crate::rendering::frame_pacer::{select_present_mode, FramePacer};
use crate::rendering::render_scale::ScaledTarget;
use crate::rendering::scene_renderer::SceneRenderer;
use crate::runtime::{
    apply_gpu_state_samples, load_scene, load_scene_document,
    record_gpu_state_hashes, route_gpu_physics_events, scene_document,
    write_atomic, AppError, EventQueue, FrameTime, GpuEventRegistry,
    GpuPhysicsClassWatches, GpuPhysicsEvent, GpuPhysicsEventsLost,
    GpuPhysicsRule, GpuPhysicsWatch, HybridPhysicsPlugin, MeshRenderer, Name,
    PhysicsBackendStatus, Plugin, RenderExtractPlugin, RenderSettings,
    RenderWorld, RuntimeInput, SceneDocument, SceneLoadMode, ScheduleStage,
};
use crate::{App, AssetPlugin, AssetServer, Transform};

/// Result returned by the convenient native game entry point.
pub type GameResult<T = ()> = Result<T, Box<dyn Error>>;

/// Options applied when one class becomes GPU simulated.
#[derive(Clone, Debug)]
pub struct GpuBodySettings {
    /// Compute solver selected for every matching object.
    pub solver: crate::runtime::PhysicsSolver,
    /// Project-relative shader used when `solver` is Custom.
    pub custom_shader: Option<String>,
    /// Mass, velocity, and gravity values copied into GPU body state.
    pub rigid_body: crate::runtime::RigidBody,
    /// Collision shape and surface values used by collision solvers.
    pub collider: crate::runtime::Collider,
    /// Collision groups used when collision solvers are connected.
    pub collision_layers: crate::runtime::CollisionLayers,
    /// What the GPU sends back. `SelectedState` fills
    /// [`GameScene::gpu_state`] every physics frame; the default sends only
    /// events.
    pub sync: crate::runtime::PhysicsSyncMode,
}

impl Default for GpuBodySettings {
    fn default() -> Self {
        Self {
            solver: crate::runtime::PhysicsSolver::Full,
            custom_shader: None,
            rigid_body: crate::runtime::RigidBody::default(),
            collider: crate::runtime::Collider::default(),
            collision_layers: crate::runtime::CollisionLayers::default(),
            sync: crate::runtime::PhysicsSyncMode::default(),
        }
    }
}

/// Reusable settings for cubes created by native Rust game code.
#[derive(Clone, Debug, Default)]
pub struct CubeSpawn {
    /// Classes assigned to every cube created with this template.
    pub classes: crate::runtime::ObjectClasses,
}

impl CubeSpawn {
    /// Creates an empty cube template.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds one class to every cube created with this template.
    #[must_use]
    pub fn class(mut self, class: impl Into<String>) -> Self {
        self.classes.add(class);
        self
    }
}

/// Reusable settings for spheres created by native Rust game code.
#[derive(Clone, Debug, Default)]
pub struct SphereSpawn {
    /// Classes assigned to every sphere created with this template.
    pub classes: crate::runtime::ObjectClasses,
    /// Number of vertical sphere subdivisions used by the shared mesh.
    pub subdivisions: u32,
}

impl SphereSpawn {
    /// Creates a sphere template with moderate mesh quality.
    #[must_use]
    pub fn new() -> Self {
        Self {
            subdivisions: 16,
            ..Self::default()
        }
    }

    /// Changes the sphere mesh quality. Meshes are cached by this value.
    #[must_use]
    pub fn subdivisions(mut self, value: u32) -> Self {
        self.subdivisions = value.clamp(2, 128);
        self
    }

    /// Adds one class to every sphere created with this template.
    #[must_use]
    pub fn class(mut self, class: impl Into<String>) -> Self {
        self.classes.add(class);
        self
    }
}

/// Cached procedural sphere meshes shared by all native-spawned spheres.
#[derive(Resource, Clone, Default)]
struct SphereMeshCache(
    HashMap<u32, crate::assets::Handle<crate::assets::MeshAsset>>,
);

/// The scene as it was loaded when the game started, for
/// [`GameScene::restart`].
#[derive(Resource)]
struct StartingScene(SceneDocument);

/// The folder holding the game's `project.json`, which
/// [`GameScene::load_scene`] resolves scene paths against.
#[derive(Resource)]
pub(crate) struct ProjectFolder(pub(crate) PathBuf);

/// A copy of the scene taken by [`GameScene::snapshot`], for
/// [`GameScene::restore`].
#[derive(Clone)]
pub struct GameSnapshot {
    scene: SceneDocument,
    once: GameOnceState,
    physics: Option<crate::runtime::PhysicsWorld>,
    next_order: Option<crate::runtime::NextSpawnOrder>,
    fluids: Vec<(uuid::Uuid, crate::runtime::Fluid)>,
    /// Each scene object's id, entity, solve order and sleep state.
    objects:
        Vec<(uuid::Uuid, Entity, Option<crate::runtime::SpawnOrder>, bool)>,
}

/// [`GameScene::restart`], for scenario `restart` steps.
pub(crate) fn restart_scene(world: &mut World) -> bool {
    let Some(start) = world.remove_resource::<StartingScene>() else {
        return false;
    };
    let loaded = load_scene_document(world, &start.0, SceneLoadMode::Replace);
    world.insert_resource(start);
    if let Err(error) = loaded {
        eprintln!("restart: the starting scene no longer loads: {error}");
        return false;
    }
    forget_old_scene(world);
    true
}

/// `key` inside the user data folder, refusing paths that leave it.
fn user_data_path(key: &str) -> std::io::Result<PathBuf> {
    let relative = Path::new(key);
    let inside = relative
        .components()
        .all(|part| matches!(part, std::path::Component::Normal(_)));
    if !inside || key.is_empty() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("data key `{key}` must be a relative path without `..`"),
        ));
    }
    Ok(crate::project::user_data_folder().join(relative))
}

/// Keys already executed through [`GameScene::once`].
#[derive(Resource, Clone, Default)]
struct GameOnceState(HashSet<String>);

/// Window changes game code asked for. The window runner applies them.
#[derive(Resource, Default)]
struct WindowRequest {
    fullscreen: bool,
    size: Option<[u32; 2]>,
}

/// Convenient access to objects in the loaded scene.
///
/// This is a small API over the ECS, not another scripting language. Advanced
/// systems can still query the ECS world directly.
pub struct GameScene<'world> {
    /// ECS world that owns all scene objects and components.
    pub(crate) world: &'world mut World,
}

impl GameScene<'_> {
    /// Runs setup code once per round: [`Self::restart`] runs it again.
    ///
    /// This keeps large procedural scene creation out of the per-frame path
    /// while preserving the short `rusting_game!` API.
    pub fn once(
        &mut self,
        key: impl Into<String>,
        action: impl FnOnce(&mut GameScene<'_>),
    ) {
        let key = key.into();
        let should_run = self
            .world
            .get_resource_or_insert_with(GameOnceState::default)
            .0
            .insert(key);
        if should_run {
            action(self);
        }
    }

    /// Reads a text file (a JSON level, a dialogue script) relative to the
    /// project's `assets` folder, as sounds are: `"charts/easy.json"`. It
    /// works from any working directory. `rusting check` reports a literal
    /// path here that is not a file.
    ///
    /// # Errors
    /// Returns the error from reading the file.
    pub fn load_text(&self, path: &str) -> std::io::Result<String> {
        let folder = self
            .world
            .get_resource::<ProjectFolder>()
            .map(|folder| folder.0.join("assets"))
            .unwrap_or_else(|| PathBuf::from("assets"));
        std::fs::read_to_string(folder.join(path))
    }

    /// Plays a clip once. `clip` is relative to the project's `assets`
    /// folder (`"sfx/hit.wav"`); WAV, Ogg, MP3 and FLAC load. Returns an ID
    /// for [`Self::stop_sound`]. Headless runs have no audio device: the
    /// request is counted by [`Self::sounds_requested`] and dropped.
    pub fn play_sound(
        &mut self,
        clip: &str,
        volume: f32,
    ) -> crate::runtime::SoundId {
        self.play_sound_with(
            clip,
            crate::runtime::Sound {
                volume,
                ..Default::default()
            },
        )
    }

    /// Plays a clip again and again until [`Self::stop_sound`].
    pub fn play_sound_looped(
        &mut self,
        clip: &str,
        volume: f32,
    ) -> crate::runtime::SoundId {
        self.play_sound_with(
            clip,
            crate::runtime::Sound {
                volume,
                looped: true,
                ..Default::default()
            },
        )
    }

    /// Plays a clip with a pan, a bus, a start tick or a world position:
    ///
    /// ```ignore
    /// scene.play_sound_with("music/bar.ogg", Sound {
    ///     bus: "music".into(),
    ///     at_tick: Some(next_bar_tick),
    ///     ..Sound::default()
    /// });
    /// ```
    ///
    /// Every sound starts a fixed delay after the fixed tick it belongs to,
    /// whatever the frame rate, so sounds keep in time with fixed ticks.
    /// With `position`, the active camera is the listener: the sound pans
    /// to its side and its volume falls as `2 / distance` past 2 m.
    pub fn play_sound_with(
        &mut self,
        clip: &str,
        mut sound: crate::runtime::Sound,
    ) -> crate::runtime::SoundId {
        if let Some(position) = sound.position {
            if let Some((camera, _)) = self.active_camera() {
                let matrix = world_matrix(self.world, camera);
                let ear = matrix.transform_point(&nalgebra::Point3::origin());
                let right = matrix
                    .transform_vector(&nalgebra::Vector3::x())
                    .normalize();
                let offset = nalgebra::Point3::from(position) - ear;
                let distance = offset.norm();
                if distance > 1e-4 {
                    sound.pan = offset.dot(&right) / distance;
                }
                sound.volume *= (2.0 / distance).min(1.0);
            }
        }
        let tick = self
            .world
            .get_resource::<FrameTime>()
            .map_or(0, |time| time.fixed_tick);
        self.audio().play(clip, &sound, tick)
    }

    /// Moves a playing sound's volume to `volume` over `fade` seconds; 0 is
    /// at once.
    pub fn set_sound_volume(
        &mut self,
        id: crate::runtime::SoundId,
        volume: f32,
        fade: f32,
    ) {
        self.audio().set_volume(id, volume, fade);
    }

    /// Moves a bus's volume (see [`crate::runtime::Sound::bus`]) to
    /// `volume` over `fade` seconds. Duck the music under an alarm with
    /// `set_bus_volume("music", 0.3, 0.2)` while the alarm plays on `sfx`.
    pub fn set_bus_volume(&mut self, bus: &str, volume: f32, fade: f32) {
        self.audio().set_bus_volume(bus, volume, fade);
    }

    /// Stops one sound. An ID that already ended is ignored.
    pub fn stop_sound(&mut self, id: crate::runtime::SoundId) {
        self.audio().stop(id);
    }

    /// Stops every playing sound.
    pub fn stop_all_sounds(&mut self) {
        self.audio().stop_all();
    }

    /// Linear gain for every sound, 1 by default.
    pub fn set_master_volume(&mut self, volume: f32) {
        self.audio().set_master_volume(volume);
    }

    /// Sounds requested since the game started, whether or not a device
    /// played them. Includes [`SoundCue`](crate::runtime::SoundCue)s.
    pub fn sounds_requested(&mut self) -> u64 {
        self.audio().requested()
    }

    fn audio(&mut self) -> Mut<'_, crate::runtime::AudioQueue> {
        self.world
            .get_resource_or_insert_with(crate::runtime::AudioQueue::default)
    }

    /// Puts every scene object back as the game started: objects spawned
    /// since are removed, and moved, hidden or despawned ones return with
    /// their starting components. [`Self::once`] blocks run again. Time,
    /// input and resources carry on. Returns false when the game was not
    /// started from a scene file, or when that file no longer loads (the
    /// error is logged and the scene stays as it was).
    pub fn restart(&mut self) -> bool {
        restart_scene(self.world)
    }

    /// Replaces every scene object with the scene at `path`, relative to
    /// the project folder (the one holding `project.json`), for example
    /// `"scenes/level_2.rscene"`. The new scene becomes the one
    /// [`Self::restart`] returns to, and [`Self::once`] blocks run again.
    /// Time, input and resources carry on. Counters are scene objects, so
    /// read any value to keep before loading and set it again after.
    ///
    /// # Errors
    /// Returns an error when the file is missing or is not a valid scene;
    /// the current scene then stays as it was.
    pub fn load_scene(
        &mut self,
        path: impl AsRef<Path>,
    ) -> Result<(), crate::runtime::SceneIoError> {
        let path = match self.world.get_resource::<ProjectFolder>() {
            Some(folder) => folder.0.join(path),
            None => path.as_ref().to_path_buf(),
        };
        load_scene(self.world, &path, SceneLoadMode::Replace)?;
        let start = scene_document(self.world, "start")?;
        self.world.insert_resource(StartingScene(start));
        forget_old_scene(self.world);
        Ok(())
    }

    /// Copies every scene object, the `once` keys and the physics solver
    /// state, to put back later with [`Self::restore`] while the game runs
    /// (a rewind, a checkpoint).
    ///
    /// # Errors
    /// Returns an error when a scene object cannot be saved, as for saving
    /// the scene to a file.
    pub fn snapshot(
        &mut self,
    ) -> Result<GameSnapshot, crate::runtime::SceneIoError> {
        let scene = scene_document(self.world, "snapshot")?;
        let mut query = self.world.query::<(
            Entity,
            &crate::runtime::SceneId,
            Option<&crate::runtime::SpawnOrder>,
            bevy_ecs::query::Has<crate::runtime::Sleeping>,
        )>();
        let objects = query
            .iter(self.world)
            .map(|(entity, id, order, asleep)| {
                (id.0, entity, order.copied(), asleep)
            })
            .collect();
        Ok(GameSnapshot {
            scene,
            once: self
                .world
                .get_resource::<GameOnceState>()
                .cloned()
                .unwrap_or_default(),
            physics: self
                .world
                .get_resource::<crate::runtime::PhysicsWorld>()
                .cloned(),
            next_order: self
                .world
                .get_resource::<crate::runtime::NextSpawnOrder>()
                .copied(),
            fluids: crate::runtime::capture_fluids(self.world),
            objects,
        })
    }

    /// Puts the scene back as it was at [`Self::snapshot`]: objects spawned
    /// since are removed and the others return with their components,
    /// velocities and sleep state. Physics then continues exactly as it did
    /// after the snapshot. Time, input, resources and the scene
    /// [`Self::restart`] returns to carry on. Return from `update` after
    /// this, as after `restart`.
    ///
    /// # Errors
    /// Returns an error when the copy cannot be loaded; the scene then
    /// stays as it was.
    pub fn restore(
        &mut self,
        snapshot: &GameSnapshot,
    ) -> Result<(), crate::runtime::SceneIoError> {
        load_scene_document(
            self.world,
            &snapshot.scene,
            SceneLoadMode::Replace,
        )?;
        let mut query =
            self.world.query::<(Entity, &crate::runtime::SceneId)>();
        let now: HashMap<uuid::Uuid, Entity> = query
            .iter(self.world)
            .map(|(entity, id)| (id.0, entity))
            .collect();
        let mut renamed = HashMap::new();
        for (id, old, order, asleep) in &snapshot.objects {
            let Some(&entity) = now.get(id) else {
                continue;
            };
            renamed.insert(*old, entity);
            let mut entity = self.world.entity_mut(entity);
            match order {
                Some(order) => entity.insert(*order),
                None => entity.remove::<crate::runtime::SpawnOrder>(),
            };
            if *asleep {
                entity.insert(crate::runtime::Sleeping);
            }
        }
        if let Some(next) = snapshot.next_order {
            self.world.insert_resource(next);
        }
        if let Some(physics) = &snapshot.physics {
            let mut physics = physics.clone();
            physics.rename_bodies(&renamed);
            self.world.insert_resource(physics);
        }
        crate::runtime::restore_fluids(self.world, &snapshot.fluids);
        self.world.insert_resource(snapshot.once.clone());
        self.world.remove_resource::<SceneNameIndex>();
        Ok(())
    }

    /// egui context for this frame's runtime UI, drawn over the game view.
    /// See [`crate::runtime::RuntimeUi`].
    #[cfg(feature = "ui")]
    #[must_use]
    pub fn ui(&self) -> egui::Context {
        self.world
            .resource::<crate::runtime::RuntimeUi>()
            .context()
            .clone()
    }

    /// Creates one visible built-in cube with a unique object name.
    pub fn spawn_cube(
        &mut self,
        name: impl Into<String>,
        transform: Transform,
        template: &CubeSpawn,
    ) -> Entity {
        let (mesh, material) = {
            let assets = self.world.resource::<AssetServer>();
            (assets.fallback_mesh, assets.fallback_material)
        };
        self.spawn_renderable(
            name.into(),
            transform,
            mesh,
            material,
            template.classes.clone(),
        )
    }

    /// Creates a cube using a material handle from the asset server.
    pub fn spawn_cube_with_material(
        &mut self,
        name: impl Into<String>,
        transform: Transform,
        template: &CubeSpawn,
        material: crate::assets::Handle<crate::assets::MaterialAsset>,
    ) -> Entity {
        let mesh = self.world.resource::<AssetServer>().fallback_mesh;
        self.spawn_renderable(
            name.into(),
            transform,
            mesh,
            material,
            template.classes.clone(),
        )
    }

    /// Registers a material and returns its generational asset handle.
    pub fn create_material(
        &mut self,
        material: crate::assets::MaterialAsset,
    ) -> crate::assets::Handle<crate::assets::MaterialAsset> {
        self.world
            .resource_mut::<AssetServer>()
            .materials
            .insert(material)
    }

    /// Changes the color used to clear the game render target.
    pub fn set_background_color(&mut self, color: [f32; 4]) {
        self.world.resource_mut::<RenderSettings>().background_color = color;
    }

    /// Turns screen-space reflections on or off. Off saves the scene copy,
    /// mip chain and depth pyramid passes when nothing refracts; a game with
    /// no mirror-like surfaces gains about half a millisecond a frame.
    pub fn set_reflections(&mut self, enabled: bool) {
        self.world.resource_mut::<RenderSettings>().reflections = enabled;
    }

    /// Renders the 3D scene at `scale` of the window size, from 0.25 to 2.0,
    /// and stretches it over the window. Below 1 trades sharpness for frame
    /// rate; above 1 supersamples. UI stays at full resolution. Captures and
    /// scenario screenshots use it too.
    pub fn set_render_scale(&mut self, scale: f32) {
        if scale.is_finite() {
            let (low, high) =
                crate::rendering::render_scale::RENDER_SCALE_RANGE;
            self.world.resource_mut::<RenderSettings>().render_scale =
                scale.clamp(low, high);
        }
    }

    /// Stretches a [`Self::set_render_scale`] frame with nearest-neighbour
    /// filtering (`true`) for square pixels, a retro or CCTV look, or with
    /// smooth filtering (`false`, the default).
    pub fn set_pixelated(&mut self, pixelated: bool) {
        self.world.resource_mut::<RenderSettings>().pixelated = pixelated;
    }

    /// The scale from [`Self::set_render_scale`].
    #[must_use]
    pub fn render_scale(&self) -> f32 {
        self.world.resource::<RenderSettings>().render_scale
    }

    /// Waits for the display refresh before showing each frame.
    pub fn set_vsync(&mut self, enabled: bool) {
        self.world.resource_mut::<RenderSettings>().vsync = enabled;
    }

    /// Caps the frame rate. `None` removes the cap.
    pub fn set_max_fps(&mut self, fps: Option<u32>) {
        let mut settings = self.world.resource_mut::<RenderSettings>();
        settings.limit_fps = fps.is_some();
        if let Some(fps) = fps {
            settings.max_fps = fps.max(1);
        }
    }

    /// Switches the window to borderless fullscreen on its current monitor,
    /// or back to a window. Applied after this frame; headless runs ignore
    /// it.
    pub fn set_fullscreen(&mut self, fullscreen: bool) {
        self.world
            .get_resource_or_insert_with(WindowRequest::default)
            .fullscreen = fullscreen;
    }

    /// The value from [`Self::set_fullscreen`].
    #[must_use]
    pub fn fullscreen(&self) -> bool {
        self.world
            .get_resource::<WindowRequest>()
            .is_some_and(|request| request.fullscreen)
    }

    /// Asks for a window of `size` pixels after this frame. The platform may
    /// pick another size, and fullscreen ignores it; read the result with
    /// [`Self::viewport_size`] on a later frame.
    pub fn set_window_size(&mut self, size: [u32; 2]) {
        self.world
            .get_resource_or_insert_with(WindowRequest::default)
            .size = Some(size.map(|side| side.max(1)));
    }

    /// Creates one visible procedural sphere with a unique object name.
    pub fn spawn_sphere(
        &mut self,
        name: impl Into<String>,
        transform: Transform,
        template: &SphereSpawn,
    ) -> Entity {
        let subdivisions = template.subdivisions;
        let mesh = self
            .world
            .get_resource::<SphereMeshCache>()
            .and_then(|cache| cache.0.get(&subdivisions).copied())
            .unwrap_or_else(|| {
                let mesh =
                    self.world.resource_mut::<AssetServer>().meshes.insert(
                        crate::assets::procedural_sphere_mesh(subdivisions),
                    );
                self.world
                    .get_resource_or_insert_with(SphereMeshCache::default)
                    .0
                    .insert(subdivisions, mesh);
                mesh
            });
        self.spawn_renderable(
            name.into(),
            transform,
            mesh,
            self.world.resource::<AssetServer>().fallback_material,
            template.classes.clone(),
        )
    }

    /// Creates a sphere using a material handle from the asset server.
    pub fn spawn_sphere_with_material(
        &mut self,
        name: impl Into<String>,
        transform: Transform,
        template: &SphereSpawn,
        material: crate::assets::Handle<crate::assets::MaterialAsset>,
    ) -> Entity {
        let subdivisions = template.subdivisions;
        let mesh = self
            .world
            .get_resource::<SphereMeshCache>()
            .and_then(|cache| cache.0.get(&subdivisions).copied())
            .unwrap_or_else(|| {
                let mesh =
                    self.world.resource_mut::<AssetServer>().meshes.insert(
                        crate::assets::procedural_sphere_mesh(subdivisions),
                    );
                self.world
                    .get_resource_or_insert_with(SphereMeshCache::default)
                    .0
                    .insert(subdivisions, mesh);
                mesh
            });
        self.spawn_renderable(
            name.into(),
            transform,
            mesh,
            material,
            template.classes.clone(),
        )
    }

    /// Inserts the shared components used by cube and sphere primitives.
    fn spawn_renderable(
        &mut self,
        name: String,
        transform: Transform,
        mesh: crate::assets::Handle<crate::assets::MeshAsset>,
        material: crate::assets::Handle<crate::assets::MaterialAsset>,
        classes: crate::runtime::ObjectClasses,
    ) -> Entity {
        // The index keeps names of despawned or renamed objects, so only a
        // live entity that still carries the name blocks the spawn.
        if find_named_entity(self.world, &name).is_some() {
            panic!("scene object `{name}` already exists");
        }
        let order = crate::runtime::next_spawn_order(self.world);
        let entity = self
            .world
            .spawn((
                crate::runtime::SceneId::new(),
                order,
                Name(name.clone()),
                transform,
                crate::runtime::MeshRenderer {
                    mesh,
                    material,
                    cast_shadows: true,
                    receive_shadows: true,
                },
                crate::runtime::Visibility::default(),
            ))
            .id();
        if !classes.names.is_empty() {
            self.world.entity_mut(entity).insert(classes);
        }
        self.world
            .resource_mut::<SceneNameIndex>()
            .entities
            .insert(name, entity);
        entity
    }

    /// Enables GPU physics for every object in one class.
    ///
    /// Call this from [`Self::once`] after procedural objects are spawned.
    pub fn apply_gpu_physics_to_class(
        &mut self,
        class: &str,
        settings: &GpuBodySettings,
    ) -> usize {
        let entities = {
            let mut query = self
                .world
                .query::<(Entity, &crate::runtime::ObjectClasses)>();
            query
                .iter(self.world)
                .filter_map(|(entity, classes)| {
                    classes.contains(class).then_some(entity)
                })
                .collect::<Vec<_>>()
        };
        for entity in &entities {
            self.world.entity_mut(*entity).insert((
                crate::runtime::PhysicsBody {
                    simulation: crate::runtime::SimulationClass::Gpu,
                    solver: settings.solver,
                    custom_shader: settings.custom_shader.clone(),
                },
                settings.rigid_body,
                settings.collider,
                settings.collision_layers,
                settings.sync,
            ));
        }
        entities.len()
    }

    /// Applies `edit` to the rigid body of `name` and wakes it. Returns
    /// false when the object or its rigid body does not exist.
    fn edit_body(
        &mut self,
        name: &str,
        edit: impl FnOnce(&mut crate::runtime::RigidBody),
    ) -> bool {
        let Some(entity) = find_named_entity(self.world, name) else {
            return false;
        };
        let Some(mut rigid_body) =
            self.world.get_mut::<crate::runtime::RigidBody>(entity)
        else {
            return false;
        };
        edit(&mut rigid_body);
        self.world
            .entity_mut(entity)
            .remove::<crate::runtime::Sleeping>();
        true
    }

    /// Sets a body's linear velocity, in metres per second, and wakes it.
    ///
    /// A CPU body moves with it from the next physics step. A GPU body reads
    /// it at the next GPU extraction, after which the compute shader owns it,
    /// so set it during setup.
    pub fn set_linear_velocity(
        &mut self,
        name: &str,
        velocity: [f32; 3],
    ) -> bool {
        self.edit_body(name, |body| body.linear_velocity = velocity)
    }

    /// A body's linear velocity in metres per second, or `None` when the
    /// object or its rigid body does not exist.
    #[must_use]
    pub fn linear_velocity(&mut self, name: &str) -> Option<[f32; 3]> {
        let entity = find_named_entity(self.world, name)?;
        self.world
            .get::<crate::runtime::RigidBody>(entity)
            .map(|body| body.linear_velocity)
    }

    /// Sets a body's angular velocity, in radians per second about each
    /// world axis, and wakes it. GPU bodies read it as for
    /// [`Self::set_linear_velocity`].
    pub fn set_angular_velocity(
        &mut self,
        name: &str,
        velocity: [f32; 3],
    ) -> bool {
        self.edit_body(name, |body| body.angular_velocity = velocity)
    }

    /// A body's angular velocity in radians per second, or `None` when the
    /// object or its rigid body does not exist.
    #[must_use]
    pub fn angular_velocity(&mut self, name: &str) -> Option<[f32; 3]> {
        let entity = find_named_entity(self.world, name)?;
        self.world
            .get::<crate::runtime::RigidBody>(entity)
            .map(|body| body.angular_velocity)
    }

    /// Stops a body completely: zeroes both velocities, forgets the
    /// solver's contact impulses and sleep count for it, and wakes it. Put
    /// it back in place first with [`GameObject::set_position`] and
    /// [`GameObject::set_rotation`]. Returns false when the object or its
    /// rigid body does not exist.
    pub fn reset_body(&mut self, name: &str) -> bool {
        let reset = self.edit_body(name, |body| {
            body.linear_velocity = [0.0; 3];
            body.angular_velocity = [0.0; 3];
        });
        if let (true, Some(entity)) =
            (reset, find_named_entity(self.world, name))
        {
            if let Some(mut physics) = self
                .world
                .get_resource_mut::<crate::runtime::PhysicsWorld>()
            {
                physics.forget_body(entity);
            }
        }
        reset
    }

    /// Changes a body's kind, for example a `Kinematic` template copied
    /// with [`Self::spawn_copy`] into a `Dynamic` projectile. A body that
    /// becomes `Kinematic` or `Fixed` stops where it is: kinematic bodies
    /// move by their velocity, so an old one would carry it away. Returns
    /// false when the object or its rigid body does not exist.
    pub fn set_body_kind(
        &mut self,
        name: &str,
        kind: crate::runtime::RigidBodyKind,
    ) -> bool {
        self.edit_body(name, |body| {
            if body.kind != kind
                && kind != crate::runtime::RigidBodyKind::Dynamic
            {
                body.linear_velocity = [0.0; 3];
                body.angular_velocity = [0.0; 3];
            }
            body.kind = kind;
        })
    }

    /// How the object called `name` was when the current scene loaded (by
    /// [`Self::restart`] and [`Self::load_scene`] too), so a round can put
    /// it back without reloading. `None` for objects spawned during play
    /// and when the game was not started from a scene file.
    #[must_use]
    pub fn initial(&self, name: &str) -> Option<InitialState> {
        use crate::runtime::SceneMaterial;
        let start = self.world.get_resource::<StartingScene>()?;
        let entity = start
            .0
            .entities
            .iter()
            .find(|entity| entity.name.as_deref() == Some(name))?;
        let material =
            entity
                .mesh_renderer
                .as_ref()
                .and_then(|renderer| match &renderer.material {
                    SceneMaterial::Inline(material) => Some(material),
                    SceneMaterial::BuiltinError => None,
                });
        Some(InitialState {
            transform: entity
                .transform
                .map(Transform::from)
                .unwrap_or_default(),
            color: material.map(|material| material.base_color),
            emissive: material.map(|material| material.emissive),
            body_kind: entity.rigid_body.map(|body| body.kind),
            visible: entity.visible.unwrap_or(true),
        })
    }

    /// Points the player controller on `name` at `yaw` and `pitch`, in
    /// radians (yaw 0 faces -Z). Returns false when the object has no
    /// player controller.
    pub fn set_look(&mut self, name: &str, yaw: f32, pitch: f32) -> bool {
        let Some(entity) = find_named_entity(self.world, name) else {
            return false;
        };
        let Some(mut player) = self
            .world
            .get_mut::<crate::runtime::PlayerController>(entity)
        else {
            return false;
        };
        player.yaw = yaw;
        player.pitch = pitch;
        true
    }

    /// Returns a scene object by name.
    ///
    /// # Panics
    ///
    /// Panics with a descriptive message if the object or its transform does
    /// not exist. Use [`Self::try_object`] when absence is expected.
    pub fn object(&mut self, name: &str) -> GameObject<'_> {
        if self.try_object(name).is_none() {
            panic!(
                "scene object `{name}` does not exist or has no Transform{}",
                nearest_names_hint(self.world, name)
            );
        }
        self.try_object(name).expect("checked above")
    }

    /// The ECS world, for anything this API does not cover.
    ///
    /// Preferred: the other `GameScene` methods; use this only when none fits.
    pub fn world(&mut self) -> &mut World {
        self.world
    }

    /// The `rusting.counter` called `name`, to read or change its `value`.
    /// With duplicate names, the one with the lowest scene ID wins, as for
    /// pickups and HUD text.
    ///
    /// Preferred: [`Self::counter_value`], [`Self::add_to_counter`] and
    /// [`Self::set_counter`], which keep no borrow of the scene.
    pub fn counter(
        &mut self,
        name: &str,
    ) -> Option<Mut<'_, crate::runtime::Counter>> {
        let mut counters = self.world.query::<(
            &mut crate::runtime::Counter,
            Option<&crate::runtime::SceneId>,
        )>();
        crate::runtime::find_counter(counters.iter_mut(self.world), name)
    }

    /// The value of the counter called `name` (counters are `i32`; store
    /// fractions as thousandths), or 0 when there is none.
    /// Reading a counter that does not exist prints a warning once per
    /// name, because it is usually a typo or a missing scene object.
    /// Takes `&self`, so read-only helpers need no `&mut GameScene`.
    #[must_use]
    pub fn counter_value(&self, name: &str) -> i32 {
        self.read_counter(name, |counter| counter.value)
            .unwrap_or_default()
    }

    /// Applies `read` to the counter called `name`, or warns once and gives
    /// `None` when there is none.
    fn read_counter<T>(
        &self,
        name: &str,
        read: impl FnOnce(&crate::runtime::Counter) -> T,
    ) -> Option<T> {
        let found = self
            .world
            .try_query::<(
                &crate::runtime::Counter,
                Option<&crate::runtime::SceneId>,
            )>()
            .and_then(|mut counters| {
                crate::runtime::find_counter(counters.iter(self.world), name)
                    .map(read)
            });
        if found.is_none() {
            warn_missing_counter(name);
        }
        found
    }

    /// Adds `amount` (which may be negative) to the counter called `name`
    /// and returns its new value. A missing counter is created at 0 first,
    /// as for [`Self::set_counter`].
    pub fn add_to_counter(&mut self, name: &str, amount: i32) -> i32 {
        let mut counter = self.counter_or_create(name);
        counter.value += amount;
        counter.value
    }

    /// Sets the counter called `name` to `value`. A missing counter is
    /// created: an object named `name` holding only a `rusting.counter`
    /// with no target, so game state needs no scene object per value.
    /// Scenarios reach it with `{"counter": "name", ...}`; `restart` drops
    /// it with the rest of the round.
    pub fn set_counter(&mut self, name: &str, value: i32) {
        self.counter_or_create(name).value = value;
    }

    fn counter_or_create(
        &mut self,
        name: &str,
    ) -> Mut<'_, crate::runtime::Counter> {
        if self.counter(name).is_none() {
            let order = crate::runtime::next_spawn_order(self.world);
            self.world.spawn((
                Name(name.to_owned()),
                crate::runtime::SceneId::new(),
                order,
                crate::runtime::Counter {
                    name: name.to_owned(),
                    value: 0,
                    target: None,
                },
            ));
        }
        self.counter(name).expect("created above")
    }

    /// A value in `[0, 1)` from the run's seed, the fixed tick and
    /// `stream`. The same seed gives the same game, so scenarios repeat;
    /// draw with a different `stream` for each value needed in one tick.
    #[must_use]
    pub fn random(&self, stream: u64) -> f32 {
        let tick = self
            .world
            .get_resource::<FrameTime>()
            .map_or(0, |time| time.fixed_tick);
        let seed = self
            .world
            .get_resource::<crate::runtime::RandomSeed>()
            .copied()
            .unwrap_or_default();
        seed.unit(tick, crate::runtime::RandomSeed::stream("game", stream))
    }

    /// True when the counter called `name` has reached its target. A
    /// missing counter is false and warns once, as for
    /// [`Self::counter_value`].
    #[must_use]
    pub fn counter_complete(&self, name: &str) -> bool {
        self.read_counter(name, crate::runtime::Counter::complete)
            .unwrap_or_default()
    }

    /// True on the frame `action` was pressed. Actions come from
    /// `rusting.input_action` components, the built-in `player.*` actions,
    /// or [`crate::runtime::ActionMap`] bindings made in code.
    #[must_use]
    pub fn pressed(&self, action: &str) -> bool {
        self.world
            .resource::<crate::runtime::ActionMap>()
            .just_pressed(self.world.resource::<RuntimeInput>(), action)
    }

    /// When `action` was pressed this frame, in fractional fixed ticks:
    /// `121.4` is 40% of a tick after tick 121. A window records the key or
    /// mouse event's own time, so a rhythm game can judge finer than a tick.
    /// Scenario presses and gamepads give the frame's tick. `None` when the
    /// action was not pressed this frame.
    #[must_use]
    pub fn press_tick(&self, action: &str) -> Option<f64> {
        if !self.pressed(action) {
            return None;
        }
        let actions = self.world.resource::<crate::runtime::ActionMap>();
        actions
            .press_tick(self.world.resource::<RuntimeInput>(), action)
            .or_else(|| {
                let time = self.world.get_resource::<FrameTime>()?;
                Some(time.fixed_tick as f64)
            })
    }

    /// True while `action` is held down.
    #[must_use]
    pub fn held(&self, action: &str) -> bool {
        self.world
            .resource::<crate::runtime::ActionMap>()
            .held(self.world.resource::<RuntimeInput>(), action)
    }

    /// Cursor position in pixels from the top-left corner of the view, or
    /// `None` before the cursor first enters it.
    #[must_use]
    pub fn cursor(&self) -> Option<[f32; 2]> {
        self.world.resource::<RuntimeInput>().cursor_position()
    }

    /// View size in pixels. In `rusting test` it is the scenario's
    /// `capture_size` from tick 0.
    #[must_use]
    pub fn viewport_size(&self) -> [f32; 2] {
        self.world.resource::<RuntimeInput>().viewport_size()
    }

    /// Names of the keys and gamepad buttons pressed this frame (`KeyA`,
    /// `Space`, `ArrowUp`, `PadSouth`), for a "press a key" rebinding
    /// prompt; pass one to [`Self::rebind`].
    #[must_use]
    pub fn keys_pressed(&self) -> Vec<String> {
        let input = self.world.resource::<RuntimeInput>();
        input
            .keys_pressed()
            .map(|key| format!("{key:?}"))
            .chain(input.pads_pressed().map(|button| format!("Pad{button:?}")))
            .collect()
    }

    /// A gamepad stick's tilt, each axis -1..1 with `[0, 1]` fully up;
    /// `[0, 0]` with no pad. For analog control; for digital actions bind
    /// `PadLeftStickUp` and the other stick directions instead.
    #[must_use]
    pub fn stick(&self, stick: crate::runtime::Stick) -> [f32; 2] {
        self.world.resource::<RuntimeInput>().stick(stick)
    }

    /// The inputs the scene's `rusting.input_action` binds to `action`,
    /// as [`Self::rebind`] takes them; empty when there is none. Bindings
    /// made in code with [`crate::runtime::ActionMap`] are left out.
    #[must_use]
    pub fn binding(&mut self, action: &str) -> Vec<String> {
        let mut query = self.world.query::<&crate::runtime::InputAction>();
        query
            .iter(self.world)
            .find(|found| found.action == action)
            .map(|found| found.inputs.clone())
            .unwrap_or_default()
    }

    /// Binds `action` to exactly `inputs` (key names as in
    /// [`Self::keys_pressed`], or `MouseLeft`, `MouseRight`, `MouseMiddle`)
    /// by editing the scene's `rusting.input_action` for it, or adding one.
    /// Bindings made in code with [`crate::runtime::ActionMap`] stay. The
    /// new binding is not saved; store it with [`Self::save_data`] and call
    /// this again at start.
    ///
    /// # Errors
    /// Returns an error naming the first unknown input; nothing changes.
    pub fn rebind(
        &mut self,
        action: &str,
        inputs: &[&str],
    ) -> Result<(), String> {
        for input in inputs {
            crate::runtime::parse_input(input)?;
        }
        let inputs: Vec<String> =
            inputs.iter().map(|&input| input.to_owned()).collect();
        let mut query = self.world.query::<&mut crate::runtime::InputAction>();
        if let Some(mut found) = query
            .iter_mut(self.world)
            .find(|found| found.action == action)
        {
            found.inputs = inputs;
            return Ok(());
        }
        self.world.spawn((
            Name(format!("input {action}")),
            crate::runtime::SceneId::new(),
            crate::runtime::InputAction {
                action: action.to_owned(),
                inputs,
            },
        ));
        Ok(())
    }

    /// Writes `text` to the file `key` in the game's user data folder,
    /// creating folders as needed. The folder is `RUSTING_USER_DATA` when
    /// set, else `~/.local/share/<game>` on Linux,
    /// `~/Library/Application Support/<game>` on macOS and
    /// `%APPDATA%\<game>` on Windows, where `<game>` is the executable name.
    /// `key` is a relative path such as `settings.txt` or `saves/1.json`.
    /// `rusting test` gives each scenario its own empty folder; a
    /// scenario's `files` field seeds it before tick 0.
    ///
    /// # Errors
    /// Returns an error for an absolute `key` or one with `..`, or when
    /// the file cannot be written.
    pub fn save_data(&self, key: &str, text: &str) -> std::io::Result<()> {
        let path = user_data_path(key)?;
        if let Some(folder) = path.parent() {
            std::fs::create_dir_all(folder)?;
        }
        std::fs::write(path, text)
    }

    /// The text [`Self::save_data`] stored under `key`, or `None` when
    /// there is no such file.
    #[must_use]
    pub fn load_data(&self, key: &str) -> Option<String> {
        std::fs::read_to_string(user_data_path(key).ok()?).ok()
    }

    /// Deletes the file [`Self::save_data`] stored under `key`. Returns
    /// false when there was none.
    pub fn delete_data(&self, key: &str) -> bool {
        user_data_path(key).is_ok_and(|path| std::fs::remove_file(path).is_ok())
    }

    /// Ends the game after this frame: the window closes, a headless run
    /// stops, and a scenario ends its run (check it with `expect_quit`).
    pub fn quit(&mut self) {
        self.world
            .resource_mut::<crate::runtime::ExitState>()
            .requested = true;
    }

    /// Stops fixed ticks while `paused`: physics, tweens, player
    /// controllers, emitters and `rusting.counter` changes from pickups.
    /// This update function still runs every frame, so a pause menu draws
    /// and reads input. Scenario tick numbers count frames and keep going.
    pub fn set_paused(&mut self, paused: bool) {
        self.world
            .resource_mut::<crate::runtime::TimeControl>()
            .paused = paused;
    }

    /// True while [`Self::set_paused`] holds fixed ticks.
    #[must_use]
    pub fn paused(&self) -> bool {
        self.world.resource::<crate::runtime::TimeControl>().paused
    }

    /// Every counter's name and value, sorted by name, for saving game
    /// state that lives in counters.
    #[must_use]
    pub fn counters(&self) -> Vec<(String, i32)> {
        let mut counters: Vec<_> = self
            .world
            .try_query::<&crate::runtime::Counter>()
            .map(|mut query| {
                query
                    .iter(self.world)
                    .map(|counter| (counter.name.clone(), counter.value))
                    .collect()
            })
            .unwrap_or_default();
        counters.sort();
        counters.dedup_by(|a, b| a.0 == b.0);
        counters
    }

    /// First collider on a ray from `origin` along `direction` within
    /// `max_distance` metres, sensors included. A ray starting inside a
    /// collider passes through it. The hit holds the object's `name`, the
    /// world `point`, the surface `normal` and the `distance` from `origin`.
    #[must_use]
    pub fn raycast(
        &self,
        origin: [f32; 3],
        direction: [f32; 3],
        max_distance: f32,
    ) -> Option<RayHit> {
        self.raycast_skipping(origin, direction, max_distance, &[])
    }

    /// [`Self::raycast`] that passes through objects in any of
    /// `skip_classes`: `raycast_skipping(eye, dir, 20.0, &["glass"])`.
    #[must_use]
    pub fn raycast_skipping(
        &self,
        origin: [f32; 3],
        direction: [f32; 3],
        max_distance: f32,
        skip_classes: &[&str],
    ) -> Option<RayHit> {
        let keep = |entity| {
            skip_classes.is_empty()
                || self
                    .world
                    .get::<crate::runtime::ObjectClasses>(entity)
                    .is_none_or(|classes| {
                        !skip_classes
                            .iter()
                            .any(|class| classes.contains(class))
                    })
        };
        let hit = self
            .world
            .get_resource::<crate::runtime::PhysicsWorld>()?
            .raycast_where(origin, direction, max_distance, u32::MAX, keep)?;
        Some(RayHit {
            name: self
                .world
                .get::<Name>(hit.entity)
                .map(|name| name.0.clone())
                .unwrap_or_default(),
            point: hit.point,
            normal: hit.normal,
            distance: hit.distance,
        })
    }

    /// Casts [`Self::raycast`] from the active camera through the center of
    /// the view: what a first-person crosshair points at. Uses the camera's
    /// transforms as they are now, so an aim set this frame counts.
    #[must_use]
    pub fn aim(&mut self, max_distance: f32) -> Option<RayHit> {
        let (origin, forward) = self.camera_ray()?;
        self.raycast(origin, forward, max_distance)
    }

    /// The named object's world `[right, up, forward]` unit vectors, from
    /// its transform and its parents' as they are now. Forward is -Z.
    /// Rotations apply X first, then Y, then Z.
    #[must_use]
    pub fn basis(&mut self, name: &str) -> Option<[[f32; 3]; 3]> {
        let entity = find_named_entity(self.world, name)?;
        let matrix = world_matrix(self.world, entity);
        let axis = |v: nalgebra::Vector3<f32>| -> [f32; 3] {
            matrix.transform_vector(&v).normalize().into()
        };
        Some([
            axis(nalgebra::Vector3::x()),
            axis(nalgebra::Vector3::y()),
            axis(-nalgebra::Vector3::z()),
        ])
    }

    /// The active camera's world position and unit forward direction, from
    /// its transforms as they are now: where a thrown or fired object
    /// starts and which way it goes. `None` without an active camera.
    #[must_use]
    pub fn camera_ray(&mut self) -> Option<([f32; 3], [f32; 3])> {
        let (camera, _) = self.active_camera()?;
        let matrix = world_matrix(self.world, camera);
        let forward = matrix
            .transform_vector(&-nalgebra::Vector3::z())
            .normalize();
        let origin = matrix.transform_point(&nalgebra::Point3::origin());
        Some((origin.coords.into(), forward.into()))
    }

    /// The world ray under the mouse cursor, from the active camera: where
    /// a top-down or point-and-click game aims. Pass it to
    /// [`Self::raycast`] to find the ground point under the cursor. `None`
    /// before the cursor has entered the window or without an active
    /// camera.
    #[must_use]
    pub fn pointer_ray(&mut self) -> Option<([f32; 3], [f32; 3])> {
        let input = self.world.resource::<RuntimeInput>();
        let (cursor, size) = (input.cursor_position()?, input.viewport_size());
        if size.contains(&0.0) {
            return None;
        }
        let (entity, camera) = self.active_camera()?;
        let transform = crate::runtime::GlobalTransform {
            matrix: world_matrix(self.world, entity).into(),
        };
        let ray = crate::runtime::picking::scene_ray(
            cursor, [0.0; 2], size, camera, transform,
        )?;
        Some((ray.origin.into(), ray.direction.into()))
    }

    /// Makes the named camera the only active one, so it renders and aims.
    /// Returns false, changing nothing, when no camera has that name.
    pub fn set_active_camera(&mut self, name: &str) -> bool {
        let Some(chosen) =
            find_named_entity(self.world, name).filter(|entity| {
                self.world.get::<crate::runtime::Camera>(*entity).is_some()
            })
        else {
            return false;
        };
        let mut cameras =
            self.world.query::<(Entity, &mut crate::runtime::Camera)>();
        for (entity, mut camera) in cameras.iter_mut(self.world) {
            let active = entity == chosen;
            if camera.active != active {
                camera.active = active;
            }
        }
        true
    }

    /// Turns the named camera on or off and sets the part of the window it
    /// draws into (`[x, y, width, height]` fractions, `None` for all of
    /// it), leaving other cameras alone; two active cameras with
    /// viewports make split screen. Returns false when no camera has that
    /// name.
    pub fn set_camera(
        &mut self,
        name: &str,
        active: bool,
        viewport: Option<[f32; 4]>,
    ) -> bool {
        let Some(mut camera) =
            find_named_entity(self.world, name).and_then(|entity| {
                self.world.get_mut::<crate::runtime::Camera>(entity)
            })
        else {
            return false;
        };
        camera.active = active;
        camera.viewport = viewport;
        true
    }

    /// The camera that aims: the highest-priority active one, preferring
    /// one that fills the window.
    fn active_camera(&mut self) -> Option<(Entity, crate::runtime::Camera)> {
        let mut cameras =
            self.world.query::<(Entity, &crate::runtime::Camera)>();
        cameras
            .iter(self.world)
            .filter(|(_, camera)| camera.active)
            .max_by_key(|(entity, camera)| {
                // Same tie-break as the renderer, so aim matches the screen.
                (
                    camera.viewport.is_none(),
                    camera.priority,
                    std::cmp::Reverse(entity.to_bits()),
                )
            })
            .map(|(entity, camera)| (entity, *camera))
    }

    /// Removes the named object and its children. Returns false when no
    /// object has that name.
    pub fn despawn(&mut self, name: &str) -> bool {
        let Some(entity) = find_named_entity(self.world, name) else {
            return false;
        };
        let _ = rusting_core::hierarchy::clear_parent(self.world, entity);
        despawn_tree(self.world, entity);
        true
    }

    /// Copies the named object and its children, with every component, as a
    /// new object called `name` at local `position` under the same parent.
    /// Use it to spawn enemies or projectiles from an object authored in the
    /// scene: keep that template hidden and out of the way, then show each
    /// copy with [`Self::set_visible`]. A copied child is named
    /// `"<name>/<child name>"`, so names stay unique. Returns `None` when
    /// `template` does not exist.
    ///
    /// # Panics
    ///
    /// Panics if an object called `name`, or one of the copied children's
    /// names, already exists.
    pub fn spawn_copy(
        &mut self,
        template: &str,
        name: impl Into<String>,
        position: [f32; 3],
    ) -> Option<Entity> {
        let name = name.into();
        let template = find_named_entity(self.world, template)?;
        let copy = copy_tree(self.world, template, Some(&name));
        if let Some(mut transform) = self.world.get_mut::<Transform>(copy) {
            transform.position = position;
        }
        if let Some(parent) = self
            .world
            .get::<crate::runtime::Parent>(template)
            .map(|p| p.0)
        {
            let _ =
                rusting_core::hierarchy::set_parent(self.world, copy, parent);
        }
        Some(copy)
    }

    /// The name of `entity`, such as [`crate::runtime::PlayerController`]'s
    /// `wall` or `floor`; `None` when it is unnamed or gone.
    #[must_use]
    pub fn name_of(&self, entity: Entity) -> Option<String> {
        self.world.get::<Name>(entity).map(|name| name.0.clone())
    }

    /// Whether `entity` is in `class`; `false` when it is gone.
    #[must_use]
    pub fn has_class(&self, entity: Entity, class: &str) -> bool {
        self.world
            .get::<crate::runtime::ObjectClasses>(entity)
            .is_some_and(|classes| classes.contains(class))
    }

    /// Names of the objects in `class`, sorted, so game code can loop over
    /// spawned copies. Unnamed objects are left out.
    #[must_use]
    pub fn in_class(&mut self, class: &str) -> Vec<String> {
        let mut query = self
            .world
            .query::<(&Name, &crate::runtime::ObjectClasses)>();
        let mut names: Vec<_> = query
            .iter(self.world)
            .filter(|(_, classes)| classes.contains(class))
            .map(|(name, _)| name.0.clone())
            .collect();
        names.sort();
        names
    }

    /// A hash of the positions, rotations, scales and velocities of the
    /// named objects in `class`, in name order. Unlike the full state hash
    /// it leaves out the clock and everything else, so two rounds that
    /// leave the class in the same state hash the same at any tick. Equal
    /// floats bit for bit give equal hashes; any drift changes it.
    #[must_use]
    pub fn state_hash(&mut self, class: &str) -> u64 {
        let mut hasher = crate::runtime::StateHasher::default();
        for name in self.in_class(class) {
            let Some(entity) = find_named_entity(self.world, &name) else {
                continue;
            };
            std::fmt::Write::write_str(&mut hasher, &name).ok();
            if let Some(transform) = self.world.get::<Transform>(entity) {
                hasher.floats(&transform.position);
                hasher.floats(&transform.rotation);
                hasher.floats(&transform.scale);
            }
            if let Some(body) =
                self.world.get::<crate::runtime::RigidBody>(entity)
            {
                hasher.floats(&body.linear_velocity);
                hasher.floats(&body.angular_velocity);
            }
        }
        hasher.finish()
    }

    /// Moves the named object under `parent` (`None` makes it a root). Its
    /// `Transform` is kept as is, so it is now relative to the new parent:
    /// set its position after the call, such as a lantern's offset in a
    /// hand. False when an object is missing or the move would make a loop.
    pub fn reparent(&mut self, name: &str, parent: Option<&str>) -> bool {
        let Some(child) = find_named_entity(self.world, name) else {
            return false;
        };
        match parent {
            Some(parent) => {
                find_named_entity(self.world, parent).is_some_and(|parent| {
                    crate::runtime::hierarchy::set_parent(
                        self.world, child, parent,
                    )
                    .is_ok()
                })
            }
            None => crate::runtime::hierarchy::clear_parent(self.world, child)
                .is_ok(),
        }
    }

    /// Changes the point or spot light on the named object: its linear RGB
    /// `color`, `intensity` and `range` in metres, each kept when `None`.
    /// An intensity of 0 turns it off. False when it has no such light.
    pub fn set_light(
        &mut self,
        name: &str,
        color: Option<[f32; 3]>,
        intensity: Option<f32>,
        range: Option<f32>,
    ) -> bool {
        let Some(entity) = find_named_entity(self.world, name) else {
            return false;
        };
        let mut entity = self.world.entity_mut(entity);
        let apply = |light_color: &mut [f32; 3],
                     light_intensity: &mut f32,
                     light_range: &mut f32| {
            *light_color = color.unwrap_or(*light_color);
            *light_intensity = intensity.unwrap_or(*light_intensity);
            *light_range = range.unwrap_or(*light_range);
        };
        if let Some(mut light) = entity.get_mut::<crate::runtime::PointLight>()
        {
            let light = &mut *light;
            apply(&mut light.color, &mut light.intensity, &mut light.range);
            true
        } else if let Some(mut light) =
            entity.get_mut::<crate::runtime::SpotLight>()
        {
            let light = &mut *light;
            apply(&mut light.color, &mut light.intensity, &mut light.range);
            true
        } else {
            false
        }
    }

    /// Changes the named object's `rusting.hud` element: its text, size,
    /// color, anchor or offset. Returns false when it has none.
    ///
    /// ```ignore
    /// scene.set_hud("Judgement", |hud| {
    ///     hud.text = "PERFECT".into();
    ///     hud.color = [1.0, 0.8, 0.2, 1.0];
    ///     hud.font_size = 40.0;
    /// });
    /// ```
    pub fn set_hud(
        &mut self,
        name: &str,
        edit: impl FnOnce(&mut crate::runtime::HudElement),
    ) -> bool {
        let Some(entity) = find_named_entity(self.world, name) else {
            return false;
        };
        let Some(mut hud) =
            self.world.get_mut::<crate::runtime::HudElement>(entity)
        else {
            return false;
        };
        edit(&mut hud);
        true
    }

    /// Shows or hides the named object. Hidden objects still collide.
    pub fn set_visible(&mut self, name: &str, visible: bool) {
        if let Some(entity) = find_named_entity(self.world, name) {
            self.world
                .entity_mut(entity)
                .insert(crate::runtime::Visibility { visible });
        }
    }

    /// The named object's base color (RGBA, linear), if it has a mesh.
    #[must_use]
    pub fn color(&mut self, name: &str) -> Option<[f32; 4]> {
        let entity = find_named_entity(self.world, name)?;
        let handle = self.world.get::<MeshRenderer>(entity)?.material;
        let assets = self.world.get_resource::<AssetServer>()?;
        Some(assets.materials.get(handle)?.base_color)
    }

    /// Changes the named object's base color (RGBA, linear). Other objects
    /// that shared its material keep theirs.
    pub fn set_color(&mut self, name: &str, color: [f32; 4]) {
        self.edit_material(name, |material| material.base_color = color);
    }

    /// Changes the named object's emitted light (RGB, linear; above 1
    /// glows with bloom). Other objects that shared its material keep theirs.
    pub fn set_emissive(&mut self, name: &str, emissive: [f32; 3]) {
        self.edit_material(name, |material| material.emissive = emissive);
    }

    /// Gives the named object a changed copy of its material. Equal
    /// materials are shared, as the scene loader shares them, so switching
    /// between a few colors does not grow the material list.
    fn edit_material(
        &mut self,
        name: &str,
        edit: impl FnOnce(&mut crate::assets::MaterialAsset),
    ) {
        let Some(entity) = find_named_entity(self.world, name) else {
            return;
        };
        let Some(handle) = self
            .world
            .get::<MeshRenderer>(entity)
            .map(|renderer| renderer.material)
        else {
            return;
        };
        let Some(mut assets) = self.world.get_resource_mut::<AssetServer>()
        else {
            return;
        };
        let Some(mut material) = assets.materials.get(handle).cloned() else {
            return;
        };
        edit(&mut material);
        // ponytail: linear scan of every material; index them by value if
        // a game recolors thousands of objects per frame.
        let shared = assets.materials.iter().find_map(|(handle, existing)| {
            (*existing == material).then_some(handle)
        });
        let handle =
            shared.unwrap_or_else(|| assets.materials.insert(material));
        if let Some(mut renderer) = self.world.get_mut::<MeshRenderer>(entity) {
            renderer.material = handle;
        }
    }

    /// The character in the named `rusting.tile_map` cell under world
    /// `position` (x and y; z is ignored), `.` for an empty cell or one past
    /// the grid. `None` when the map does not exist or `position` is left of
    /// or above the map origin.
    #[must_use]
    pub fn tile(&mut self, map: &str, position: [f32; 3]) -> Option<char> {
        let entity = find_named_entity(self.world, map)?;
        let origin = self.world.get::<Transform>(entity)?.position;
        let map = self.world.get::<crate::runtime::TileMap>(entity)?;
        let (column, row) =
            map.cell_at([position[0] - origin[0], position[1] - origin[1]])?;
        Some(map.cell(column, row))
    }

    /// Writes `character` into the named tile map's cell under world
    /// `position`, growing the grid as needed; the map's tiles and colliders
    /// rebuild on the next fixed step. Returns false when the map does not
    /// exist, `position` is outside it, or the cell already held it.
    pub fn set_tile(
        &mut self,
        map: &str,
        position: [f32; 3],
        character: char,
    ) -> bool {
        let Some(entity) = find_named_entity(self.world, map) else {
            return false;
        };
        let Some(origin) =
            self.world.get::<Transform>(entity).map(|t| t.position)
        else {
            return false;
        };
        let Some(mut map) =
            self.world.get_mut::<crate::runtime::TileMap>(entity)
        else {
            return false;
        };
        let local = [position[0] - origin[0], position[1] - origin[1]];
        let Some((column, row)) = map.cell_at(local) else {
            return false;
        };
        // Compare first so an unchanged cell does not mark the map changed.
        map.cell(column, row) != character
            && map.set_cell(column, row, character)
    }

    /// Fires the named object's `rusting.sound_cue` and
    /// `rusting.burst_emitter` and restarts its `rusting.particle_emitter`,
    /// the way a pickup does when collected.
    pub fn trigger(&mut self, name: &str) {
        let Some(entity) = find_named_entity(self.world, name) else {
            return;
        };
        if let Some(mut cue) =
            self.world.get_mut::<crate::runtime::SoundCue>(entity)
        {
            cue.trigger();
        }
        if let Some(mut emitter) =
            self.world.get_mut::<crate::runtime::BurstEmitter>(entity)
        {
            emitter.trigger();
        }
        self.particles(name, crate::runtime::ParticleCommand::Restart);
    }

    /// Plays, pauses, stops or restarts the named object's
    /// `rusting.particle_emitter` on the next fixed tick. `Stop` lets live
    /// particles finish.
    pub fn particles(
        &mut self,
        name: &str,
        command: crate::runtime::ParticleCommand,
    ) {
        let Some(entity) = find_named_entity(self.world, name) else {
            return;
        };
        if let Some(mut emitter) = self
            .world
            .get_mut::<crate::runtime::ParticleEmitter>(entity)
        {
            emitter.command = command;
        }
    }

    /// Plays the named object's `rusting.animation` clip from its start on
    /// the next fixed tick.
    pub fn play_animation(&mut self, name: &str, clip: &str) {
        self.animate(name, crate::runtime::AnimationCommand::Play(clip.into()));
    }

    /// Blends the named object from its current clip into `clip` over
    /// `seconds`.
    pub fn crossfade(&mut self, name: &str, clip: &str, seconds: f32) {
        self.animate(
            name,
            crate::runtime::AnimationCommand::Crossfade(clip.into(), seconds),
        );
    }

    /// Stops the named object's animation, holding its current pose.
    pub fn stop_animation(&mut self, name: &str) {
        self.animate(name, crate::runtime::AnimationCommand::Stop);
    }

    /// Sets how fast the named object's animation plays; 1 is real time.
    pub fn set_animation_speed(&mut self, name: &str, speed: f32) {
        let Some(entity) = find_named_entity(self.world, name) else {
            return;
        };
        if let Some(mut animation) =
            self.world.get_mut::<crate::runtime::Animation>(entity)
        {
            animation.speed = speed.max(0.0);
        }
    }

    /// Makes the named character's `rusting.ragdoll` go limp (`true`) or
    /// get back up (`false`) next fixed step.
    pub fn set_ragdoll(&mut self, name: &str, limp: bool) {
        let Some(entity) = find_named_entity(self.world, name) else {
            return;
        };
        if let Some(mut ragdoll) =
            self.world.get_mut::<crate::runtime::Ragdoll>(entity)
        {
            ragdoll.command = Some(limp);
        }
    }

    /// Sets the named character's ragdoll muscle stiffness in Hz. Above 0
    /// makes it an active ragdoll; 0 lets it go limp and then return to
    /// plain animation.
    pub fn set_ragdoll_muscle(&mut self, name: &str, hz: f32) {
        let Some(entity) = find_named_entity(self.world, name) else {
            return;
        };
        if let Some(mut ragdoll) =
            self.world.get_mut::<crate::runtime::Ragdoll>(entity)
        {
            ragdoll.muscle = hz.max(0.0);
        }
    }

    /// Whether the named character is limp (not animated or blending back).
    #[must_use]
    pub fn is_limp(&mut self, name: &str) -> bool {
        find_named_entity(self.world, name)
            .and_then(|entity| {
                self.world.get::<crate::runtime::RagdollState>(entity)
            })
            .is_some_and(|state| {
                state.phase == crate::runtime::RagdollPhase::Limp
            })
    }

    /// Sets a parameter the named object's animation transitions test,
    /// such as `speed` or `grounded`. The next fixed tick follows the first
    /// transition that matches.
    pub fn set_animation_parameter(
        &mut self,
        name: &str,
        parameter: &str,
        value: f32,
    ) {
        let Some(entity) = find_named_entity(self.world, name) else {
            return;
        };
        if let Some(mut animation) =
            self.world.get_mut::<crate::runtime::Animation>(entity)
        {
            animation.parameters.insert(parameter.into(), value);
        }
    }

    fn animate(
        &mut self,
        name: &str,
        command: crate::runtime::AnimationCommand,
    ) {
        let Some(entity) = find_named_entity(self.world, name) else {
            return;
        };
        if let Some(mut animation) =
            self.world.get_mut::<crate::runtime::Animation>(entity)
        {
            animation.command = Some(command);
        }
    }

    /// True while the named object plays `clip`. A `Once` clip stops
    /// playing at its end.
    #[must_use]
    pub fn is_playing(&mut self, name: &str, clip: &str) -> bool {
        let Some(entity) = find_named_entity(self.world, name) else {
            return false;
        };
        let (Some(animation), Some(player)) = (
            self.world.get::<crate::runtime::Animation>(entity),
            self.world.get::<crate::runtime::AnimationPlayer>(entity),
        ) else {
            return false;
        };
        player.playing
            && player.current.is_some_and(|current| {
                Some(current.clip) == animation.clip(clip)
            })
    }

    /// Root motion the object's clips produced since the last call, in its
    /// local frame, and resets it. Needs `root_motion` set on its
    /// animation; `InPlace` leaves applying it to game code.
    pub fn take_root_motion(&mut self, name: &str) -> [f32; 3] {
        find_named_entity(self.world, name)
            .and_then(|entity| {
                self.world
                    .get_mut::<crate::runtime::AnimationPlayer>(entity)
            })
            .map(|mut player| std::mem::take(&mut player.root_motion))
            .unwrap_or_default()
    }

    /// Animation markers passed since the last frame, in tick order.
    #[must_use]
    pub fn animation_events(&self) -> Vec<crate::runtime::AnimationEvent> {
        self.world
            .resource::<EventQueue<crate::runtime::AnimationEvent>>()
            .iter()
            .cloned()
            .collect()
    }

    /// Names of the objects touching `name` in the last physics step, sensors
    /// included. Empty when `name` does not exist.
    #[must_use]
    pub fn touching(&mut self, name: &str) -> Vec<String> {
        let Some(entity) = find_named_entity(self.world, name) else {
            return Vec::new();
        };
        let Some(physics) =
            self.world.get_resource::<crate::runtime::PhysicsWorld>()
        else {
            return Vec::new();
        };
        let mut others: Vec<Entity> = physics
            .contacts()
            .iter()
            .filter_map(|contact| match (contact.a, contact.b) {
                (a, other) | (other, a) if a == entity => Some(other),
                _ => None,
            })
            .collect();
        // A player controller stops a skin short of what it stands on or
        // walks into, so the solver never lists those contacts.
        if let Some(player) =
            self.world.get::<crate::runtime::PlayerController>(entity)
        {
            for other in player
                .floor
                .map(|(floor, _)| floor)
                .into_iter()
                .chain(player.wall)
            {
                if !others.contains(&other) {
                    others.push(other);
                }
            }
        }
        others
            .into_iter()
            .filter_map(|other| self.world.get::<Name>(other))
            .map(|other| other.0.clone())
            .collect()
    }

    /// The player controller on a named object, with its live state:
    /// `grounded`, `velocity` (what the body really moved per second last
    /// step), `vertical_speed`, `yaw` and `pitch`. `None` when the object or
    /// its controller does not exist.
    #[must_use]
    pub fn player(
        &mut self,
        name: &str,
    ) -> Option<crate::runtime::PlayerController> {
        let entity = find_named_entity(self.world, name)?;
        self.world
            .get::<crate::runtime::PlayerController>(entity)
            .copied()
    }

    /// Tries to return a scene object by name.
    pub fn try_object(&mut self, name: &str) -> Option<GameObject<'_>> {
        let entity = find_named_entity(self.world, name)?;
        self.world
            .get_mut::<Transform>(entity)
            .map(|transform| GameObject { entity, transform })
    }

    /// Adds one GPU condition to a named object if it is not already present.
    ///
    /// This method is safe to call from the short update function every frame.
    pub fn watch_gpu_object(&mut self, name: &str, rule: GpuPhysicsRule) {
        let entity = find_named_entity(self.world, name).unwrap_or_else(|| {
            panic!(
                "scene object `{name}` does not exist{}",
                nearest_names_hint(self.world, name)
            )
        });
        if let Some(mut watch) = self.world.get_mut::<GpuPhysicsWatch>(entity) {
            if !watch.rules.contains(&rule) {
                watch.rules.push(rule);
            }
        } else {
            self.world
                .entity_mut(entity)
                .insert(GpuPhysicsWatch { rules: vec![rule] });
        }
    }

    /// Adds one GPU condition to every GPU body in the requested class.
    ///
    /// Objects receive classes in the editor Inspector or through the
    /// [`crate::runtime::ObjectClasses`] component. One object may have several
    /// classes, but the same rule is never added to it twice.
    /// This method is safe to call from the short update function every frame.
    pub fn watch_gpu_class(&mut self, class: &str, rule: GpuPhysicsRule) {
        self.world
            .resource_mut::<GpuPhysicsClassWatches>()
            .add(class, rule);
    }

    /// Replaces the custom GLSL that runs over every GPU body after each
    /// fixed step; see `rusting docs show guide/gpu-condition-shaders`.
    /// Calling it every frame with new `params` and the same `glsl` does not
    /// recompile.
    pub fn set_gpu_condition_shaders(
        &mut self,
        shaders: Vec<crate::runtime::GpuConditionShader>,
    ) {
        self.world
            .insert_resource(crate::runtime::GpuConditionShaders(shaders));
    }

    /// Returns GPU physics events with the requested registered name.
    #[must_use]
    pub fn gpu_events(&self, name: &str) -> Vec<GpuPhysicsEvent> {
        let Some(event_id) = self.world.resource::<GpuEventRegistry>().id(name)
        else {
            return Vec::new();
        };
        self.world
            .resource::<EventQueue<GpuPhysicsEvent>>()
            .iter()
            .filter(|event| event.event_id == event_id)
            .copied()
            .collect()
    }

    /// Where the GPU last put a GPU body, one to three frames late. The
    /// object's `Transform` keeps its spawn pose. Filled every physics frame
    /// for bodies with `sync: PhysicsSyncMode::SelectedState`, or once after
    /// `request_gpu_class_snapshot(scene.world(), class)`; `None` before
    /// that.
    #[must_use]
    pub fn gpu_state(
        &mut self,
        name: &str,
    ) -> Option<crate::runtime::GpuStateMirror> {
        let entity = find_named_entity(self.world, name)?;
        self.world
            .get::<crate::runtime::GpuStateMirror>(entity)
            .copied()
    }
}

/// Mutable high-level access to one scene object's transform.
pub struct GameObject<'world> {
    entity: Entity,
    /// Transform borrowed from the real ECS object.
    transform: Mut<'world, Transform>,
}

impl GameObject<'_> {
    /// The ECS entity, for components this API does not wrap; reach them
    /// through [`GameScene::world`] after this borrow ends.
    #[must_use]
    pub fn entity(&self) -> Entity {
        self.entity
    }

    /// Returns the current local X, Y, and Z position.
    #[must_use]
    pub fn position(&self) -> [f32; 3] {
        self.transform.position
    }

    /// Replaces the local X, Y, and Z position.
    pub fn set_position(&mut self, position: [f32; 3]) -> &mut Self {
        self.transform.position = position;
        self
    }

    /// Adds an X, Y, and Z offset to the current position.
    pub fn move_by(&mut self, offset: [f32; 3]) -> &mut Self {
        for (position, offset) in self.transform.position.iter_mut().zip(offset)
        {
            *position += offset;
        }
        self
    }

    /// Moves the object along its X axis.
    pub fn move_x(&mut self, distance: f32) -> &mut Self {
        self.transform.position[0] += distance;
        self
    }

    /// Moves the object along its Y axis.
    pub fn move_y(&mut self, distance: f32) -> &mut Self {
        self.transform.position[1] += distance;
        self
    }

    /// Moves the object along its Z axis.
    pub fn move_z(&mut self, distance: f32) -> &mut Self {
        self.transform.position[2] += distance;
        self
    }

    /// Returns the local X, Y, and Z rotation in radians.
    #[must_use]
    pub fn rotation(&self) -> [f32; 3] {
        self.transform.rotation
    }

    /// Returns the local X, Y, and Z scale.
    #[must_use]
    pub fn scale(&self) -> [f32; 3] {
        self.transform.scale
    }

    /// Replaces the local X, Y, and Z rotation in radians.
    pub fn set_rotation(&mut self, rotation: [f32; 3]) -> &mut Self {
        self.transform.rotation = rotation;
        self
    }

    /// Adds rotation in radians to all three axes.
    pub fn rotate_by(&mut self, rotation: [f32; 3]) -> &mut Self {
        for (current, rotation) in
            self.transform.rotation.iter_mut().zip(rotation)
        {
            *current += rotation;
        }
        self
    }

    /// Adds rotation in radians to X axis
    pub fn rotate_x(&mut self, rotation: f32) -> &mut Self {
        self.transform.rotation[0] += rotation;
        self
    }
    /// Adds rotation in radians to Y axis
    pub fn rotate_y(&mut self, rotation: f32) -> &mut Self {
        self.transform.rotation[1] += rotation;
        self
    }
    /// Adds rotation in radians to Y axis
    pub fn rotate_z(&mut self, rotation: f32) -> &mut Self {
        self.transform.rotation[2] += rotation;
        self
    }

    /// Replaces the local size on all three axes
    pub fn set_scale(&mut self, scale: [f32; 3]) -> &mut Self {
        self.transform.scale = scale;
        self
    }
}

/// Counter names game code read without such a counter, warned once each
/// per process. Only feeds warnings, never game state.
static MISSING_COUNTERS: std::sync::Mutex<std::collections::BTreeSet<String>> =
    std::sync::Mutex::new(std::collections::BTreeSet::new());

fn warn_missing_counter(name: &str) {
    let mut missing = MISSING_COUNTERS
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if missing.insert(name.to_owned()) {
        eprintln!(
            "warning: game code read counter `{name}`, which does not exist; \
             it reads as 0. Add a `rusting.counter` named `{name}` to the \
             scene, or create it with `set_counter` or `add_to_counter`."
        );
    }
}

/// Connects object names to ECS IDs after the first lookup.
///
/// This avoids searching every object again on later frames.
#[derive(Resource, Clone, Default)]
struct SceneNameIndex {
    /// Object names resolved once instead of searching 10,000 objects again.
    entities: HashMap<String, Entity>,
    /// True after names from the loaded scene were copied into this map.
    initialized: bool,
}

/// Builds the fast name index once after a scene is loaded.
fn ensure_scene_name_index(world: &mut World) {
    if world
        .get_resource::<SceneNameIndex>()
        .is_some_and(|index| index.initialized)
    {
        return;
    }
    let entries = {
        let mut query = world.query::<(Entity, &Name)>();
        query
            .iter(world)
            .map(|(entity, name)| (name.0.clone(), entity))
            .collect::<Vec<_>>()
    };
    let mut entities = HashMap::with_capacity(entries.len());
    for (name, entity) in entries {
        assert!(
            entities.insert(name.clone(), entity).is_none(),
            "scene object name `{name}` is not unique"
        );
    }
    world.insert_resource(SceneNameIndex {
        entities,
        initialized: true,
    });
}

/// `; did you mean `A`, `B`?` with the scene object names closest to `name`,
/// or an empty string when none is close.
fn nearest_names_hint(world: &mut World, name: &str) -> String {
    let mut names = world.query::<&Name>();
    let limit = (name.chars().count() / 2).max(2);
    let mut close: Vec<(usize, &str)> = names
        .iter(world)
        .filter_map(|other| {
            let distance = crate::scene_patch::edit_distance(
                &name.to_lowercase(),
                &other.0.to_lowercase(),
            );
            (distance <= limit).then_some((distance, other.0.as_str()))
        })
        .collect();
    close.sort_unstable();
    close.truncate(3);
    if close.is_empty() {
        return String::new();
    }
    let list: Vec<String> = close
        .iter()
        .map(|(_, other)| format!("`{other}`"))
        .collect();
    format!("; did you mean {}?", list.join(", "))
}

/// Finds a named ECS object and saves the result for later calls.
fn find_named_entity(world: &mut World, name: &str) -> Option<Entity> {
    ensure_scene_name_index(world);
    let indexed = world
        .resource::<SceneNameIndex>()
        .entities
        .get(name)
        .copied()
        .filter(|entity| {
            world
                .get::<Name>(*entity)
                .is_some_and(|current| current.0 == name)
        });
    if indexed.is_some() {
        return indexed;
    }
    // Spawned or renamed through `world()`, which the index does not see.
    // ponytail: linear scan on a miss; track Name changes if misses get hot.
    let mut names = world.query::<(Entity, &Name)>();
    let entity = names
        .iter(world)
        .find(|(_, current)| current.0 == name)
        .map(|(entity, _)| entity)?;
    world
        .resource_mut::<SceneNameIndex>()
        .entities
        .insert(name.to_owned(), entity);
    Some(entity)
}

/// How an object was when the current scene loaded; see
/// [`GameScene::initial`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct InitialState {
    /// Local transform, relative to the parent if there is one.
    pub transform: Transform,
    /// Base color and emitted light of an inline material; `None` without
    /// a mesh or with a material file.
    pub color: Option<[f32; 4]>,
    pub emissive: Option<[f32; 3]>,
    pub body_kind: Option<crate::runtime::RigidBodyKind>,
    pub visible: bool,
}

/// What [`GameScene::raycast`] and [`GameScene::aim`] hit.
#[derive(Clone, Debug, PartialEq)]
pub struct RayHit {
    /// Scene name of the object hit; empty for an unnamed one.
    pub name: String,
    /// World position where the ray meets the surface.
    pub point: [f32; 3],
    /// Unit surface normal at `point`, facing the ray.
    pub normal: [f32; 3],
    /// Metres from the ray origin to `point`.
    pub distance: f32,
}

/// `entity`'s world matrix from the current transforms of it and its
/// parents.
fn world_matrix(world: &World, entity: Entity) -> nalgebra::Matrix4<f32> {
    let mut matrix = nalgebra::Matrix4::identity();
    let mut current = Some(entity);
    while let Some(entity) = current {
        if let Some(transform) = world.get::<Transform>(entity) {
            matrix = nalgebra::Matrix4::from(transform.to_matrix()) * matrix;
        }
        current = world
            .get::<crate::runtime::Parent>(entity)
            .map(|parent| parent.0);
    }
    matrix
}

/// Drops state that belonged to the replaced scene: the name index, the
/// `once` keys, and the solver's contacts, warm starts and sleep counters,
/// so physics after a reload repeats the first load exactly.
fn forget_old_scene(world: &mut World) {
    world.remove_resource::<SceneNameIndex>();
    world.remove_resource::<GameOnceState>();
    if world.contains_resource::<crate::runtime::PhysicsWorld>() {
        world.insert_resource(crate::runtime::PhysicsWorld::default());
    }
}

/// Clones `entity` and its descendants, naming the copy `name` (unnamed
/// when `None`). Each copy gets a new `SceneId`; named children become
/// `"<name>/<child>"`, parented to the copy. Panics when a copy's name is
/// taken, so the name index never points two names at one object.
fn copy_tree(world: &mut World, entity: Entity, name: Option<&str>) -> Entity {
    if let Some(name) = name {
        if find_named_entity(world, name).is_some() {
            panic!("scene object `{name}` already exists");
        }
    }
    let copy =
        world
            .entity_mut(entity)
            .clone_and_spawn_with_opt_out(|builder| {
                builder.deny::<(
                    crate::runtime::Parent,
                    crate::runtime::Children,
                    crate::runtime::SceneId,
                    crate::runtime::Sleeping,
                    Name,
                )>();
            });
    let order = crate::runtime::next_spawn_order(world);
    world
        .entity_mut(copy)
        .insert((crate::runtime::SceneId::new(), order));
    if let Some(name) = name {
        world.entity_mut(copy).insert(Name(name.to_owned()));
        world
            .resource_mut::<SceneNameIndex>()
            .entities
            .insert(name.to_owned(), copy);
    }
    let children = world
        .get::<crate::runtime::Children>(entity)
        .map(|children| children.0.clone())
        .unwrap_or_default();
    for child in children {
        let child_name = world
            .get::<Name>(child)
            .zip(name)
            .map(|(child, parent)| format!("{parent}/{}", child.0));
        let child = copy_tree(world, child, child_name.as_deref());
        let _ = rusting_core::hierarchy::set_parent(world, child, copy);
    }
    copy
}

fn despawn_tree(world: &mut World, entity: Entity) {
    let children = world
        .get::<crate::runtime::Children>(entity)
        .map(|children| children.0.clone())
        .unwrap_or_default();
    for child in children {
        despawn_tree(world, child);
    }
    world.despawn(entity);
}

/// Signature used by the concise native Rust game update API.
pub type GameUpdate = for<'world> fn(&mut GameScene<'world>, &FrameTime);

/// Update function stored inside the ECS world.
#[derive(Resource, Clone, Copy)]
struct GameUpdateFunction(GameUpdate);

/// Installs the easy game update function into the normal ECS schedule.
#[derive(Clone, Copy)]
struct SimpleGamePlugin {
    /// User function called once per rendered frame.
    update: GameUpdate,
}

impl Plugin for SimpleGamePlugin {
    fn build(&self, app: &mut App) -> Result<(), AppError> {
        app.insert_resource(GameUpdateFunction(self.update));
        app.add_system(ScheduleStage::Update, run_simple_game_update);
        app.register_snapshot_component::<GameUpdateFunction>()
            .register_snapshot_component::<GameOnceState>()
            .register_snapshot_component::<SceneNameIndex>()
            .register_snapshot_component::<SphereMeshCache>();
        Ok(())
    }
}

fn run_simple_game_update(world: &mut World) {
    // Copy these small values before giving the whole world to GameScene.
    let time = *world.resource::<FrameTime>();
    let update = world.resource::<GameUpdateFunction>().0;
    update(&mut GameScene { world }, &time);
}

/// What a code reload carries from the old game process to the new one.
#[derive(serde::Serialize, serde::Deserialize)]
struct CodeReloadState {
    /// Every scene object with its reflected components.
    scene: SceneDocument,
    /// [`GameScene::once`] keys that already ran.
    once: Vec<String>,
}

/// Writes the scene objects and the finished [`GameScene::once`] keys to
/// `path`. Resources and components with no reflection registration are
/// not kept.
fn save_code_reload_state(
    runtime: &mut App,
    path: &Path,
) -> Result<(), Box<dyn Error>> {
    let world = runtime.world_mut();
    let scene = scene_document(world, "code reload")?;
    let mut once = world
        .get_resource::<GameOnceState>()
        .map(|state| state.0.iter().cloned().collect::<Vec<_>>())
        .unwrap_or_default();
    once.sort();
    write_atomic(path, &serde_json::to_vec(&CodeReloadState { scene, once })?)?;
    Ok(())
}

/// Replaces the freshly loaded scene with the state saved before a code
/// reload. Startup systems and [`GameScene::once`] blocks that already ran
/// do not run again. On error the fresh scene stays, so the game starts
/// clean.
fn restore_code_reload_state(
    runtime: &mut App,
    path: &Path,
) -> Result<(), Box<dyn Error>> {
    let state: CodeReloadState = serde_json::from_slice(&std::fs::read(path)?)?;
    let world = runtime.world_mut();
    load_scene_document(world, &state.scene, SceneLoadMode::Replace)?;
    world.insert_resource(GameOnceState(state.once.into_iter().collect()));
    // Names now belong to the restored entities.
    world.remove_resource::<SceneNameIndex>();
    runtime.skip_startup();
    Ok(())
}

/// Builds the same ECS and asset stack for windowed and headless games.
fn load_project_runtime<P: Plugin>(
    scene_path: &Path,
    plugin: P,
) -> Result<App, Box<dyn Error>> {
    let mut runtime = App::new();
    runtime.add_plugin(AssetPlugin)?;
    runtime.add_plugin(HybridPhysicsPlugin)?;
    runtime.add_plugin(RenderExtractPlugin)?;
    runtime.add_plugin(plugin)?;
    load_scene(runtime.world_mut(), scene_path, SceneLoadMode::Replace)?;
    let start = scene_document(runtime.world_mut(), "start")?;
    runtime.insert_resource(StartingScene(start));
    let folder = scene_path
        .ancestors()
        .skip(1)
        .find(|folder| folder.join("project.json").is_file())
        .or_else(|| scene_path.parent())
        .unwrap_or(Path::new("."));
    runtime.insert_resource(ProjectFolder(folder.to_path_buf()));
    crate::runtime::check_determinism(runtime.world_mut())?;
    Ok(runtime)
}

/// egui input translation and painting for [`crate::runtime::RuntimeUi`].
#[cfg(feature = "ui")]
struct RuntimeUiPainter {
    input: egui_winit::State,
    painter: crate::rendering::egui_painter::EguiPainter,
    textures: egui::TexturesDelta,
    primitives: Vec<egui::ClippedPrimitive>,
    pixels_per_point: f32,
}

/// Images the game's swapchain asks for. [`probe_swapchain_images`] lowers it
/// when the surface allows fewer.
static SWAPCHAIN_IMAGES: AtomicU32 = AtomicU32::new(4);
/// Whether swapchain images accept a blit, which render scale needs.
static SWAPCHAIN_BLIT: AtomicBool = AtomicBool::new(false);

/// Sets [`SWAPCHAIN_IMAGES`] to four, or to the surface's maximum when that is
/// lower. Only a window has a surface, so a hidden one is made and dropped;
/// on any failure the default stays and window creation reports the error.
fn probe_swapchain_images(
    event_loop: &ActiveEventLoop,
    vulkan: &VulkanoContext,
) {
    let Ok(window) = event_loop
        .create_window(Window::default_attributes().with_visible(false))
    else {
        return;
    };
    let Ok(surface) =
        Surface::from_window(vulkan.instance().clone(), Arc::new(window))
    else {
        return;
    };
    let Ok(capabilities) = vulkan
        .device()
        .physical_device()
        .surface_capabilities(&surface, Default::default())
    else {
        return;
    };
    let wanted = capabilities.max_image_count.map_or(4, |max| max.min(4));
    SWAPCHAIN_IMAGES.store(wanted, Ordering::Relaxed);
    SWAPCHAIN_BLIT.store(
        capabilities
            .supported_usage_flags
            .contains(ImageUsage::TRANSFER_DST),
        Ordering::Relaxed,
    );
}

/// Owns the operating-system window and all Vulkan presentation state.
struct WindowRunner {
    /// Text shown in the game window title bar.
    title: String,
    /// Vulkan device, queues, and memory allocators.
    vulkan: VulkanoContext,
    /// Winit windows connected to Vulkan swapchains.
    windows: VulkanoWindows,
    /// Renderer created after the operating system opens the window.
    scene_renderer: Option<SceneRenderer>,
    /// Requests frames immediately or waits when an FPS limit is enabled.
    frame_pacer: FramePacer,
    /// VSync value currently applied to the swapchain.
    applied_vsync: Option<bool>,
    /// Cursor capture currently applied to the window.
    applied_cursor_capture: bool,
    /// Fullscreen state currently applied to the window.
    applied_fullscreen: bool,
    /// Offscreen image for `RenderSettings::render_scale`.
    scaled: Option<ScaledTarget>,
    #[cfg(feature = "ui")]
    ui: Option<RuntimeUiPainter>,
}

impl WindowRunner {
    fn new(title: String) -> Self {
        Self {
            title,
            vulkan: VulkanoContext::new(crate::rendering::vulkano_config()),
            windows: VulkanoWindows::default(),
            scene_renderer: None,
            frame_pacer: FramePacer::default(),
            applied_vsync: None,
            applied_cursor_capture: false,
            applied_fullscreen: false,
            scaled: None,
            #[cfg(feature = "ui")]
            ui: None,
        }
    }

    fn resumed(&mut self, event_loop: &ActiveEventLoop, runtime: &mut App) {
        // Winit can resume more than once. The renderer must be created once.
        if self.scene_renderer.is_some() {
            return;
        }
        probe_swapchain_images(event_loop, &self.vulkan);
        // Create the operating-system window and its Vulkan swapchain.
        self.windows.create_window(
            event_loop,
            &self.vulkan,
            &WindowDescriptor {
                title: self.title.clone(),
                width: 1440.0,
                height: 900.0,
                ..WindowDescriptor::default()
            },
            |create_info| {
                create_info.image_format = Format::B8G8R8A8_UNORM;
                create_info.min_image_count = create_info
                    .min_image_count
                    .max(SWAPCHAIN_IMAGES.load(Ordering::Relaxed));
                if SWAPCHAIN_BLIT.load(Ordering::Relaxed) {
                    create_info.image_usage |= ImageUsage::TRANSFER_DST;
                }
            },
        );
        // Apply project render settings before the first presented frame.
        let renderer = self.windows.get_primary_renderer_mut().unwrap();
        let settings = runtime.world().resource::<RenderSettings>();
        let mode = select_present_mode(
            &renderer.graphics_queue(),
            &renderer.surface(),
            settings.vsync,
        );
        if std::env::var_os(PERF_ENV).is_some() {
            eprintln!(
                "[rusting] present mode {mode:?}, render scale blit {}",
                SWAPCHAIN_BLIT.load(Ordering::Relaxed)
            );
        }
        renderer.set_present_mode(mode);
        self.applied_vsync = Some(settings.vsync);
        let initial_size = renderer.window().inner_size();
        runtime
            .world_mut()
            .resource_mut::<RuntimeInput>()
            .record_viewport_size([
                initial_size.width as f32,
                initial_size.height as f32,
            ]);
        self.scene_renderer = Some(
            SceneRenderer::new(
                renderer.graphics_queue(),
                self.vulkan.memory_allocator().clone(),
                renderer.swapchain_format(),
                renderer.swapchain_image_size(),
            )
            .expect("failed to create game scene renderer"),
        );
        self.scaled = SWAPCHAIN_BLIT
            .load(Ordering::Relaxed)
            .then(|| ScaledTarget::new(self.vulkan.memory_allocator().clone()));
        #[cfg(feature = "ui")]
        if let Some(runtime_ui) =
            runtime.world().get_resource::<crate::runtime::RuntimeUi>()
        {
            let painter = crate::rendering::egui_painter::EguiPainter::new(
                renderer.graphics_queue(),
                self.vulkan.memory_allocator().clone(),
                renderer.swapchain_format(),
            )
            .expect("failed to create runtime UI painter");
            let context = runtime_ui.context();
            let input = egui_winit::State::new(
                context.clone(),
                context.viewport_id(),
                event_loop,
                Some(renderer.window().scale_factor() as f32),
                None,
                Some(painter.max_texture_side()),
            );
            self.ui = Some(RuntimeUiPainter {
                input,
                painter,
                textures: egui::TexturesDelta::default(),
                primitives: Vec::new(),
                pixels_per_point: 1.0,
            });
        }
    }

    /// Gives a window event to the runtime UI. Returns true when the UI
    /// used it, so gameplay input should not see it.
    fn ui_event(&mut self, window_id: WindowId, event: &WindowEvent) -> bool {
        #[cfg(feature = "ui")]
        if let (Some(ui), Some(renderer)) =
            (self.ui.as_mut(), self.windows.get_renderer(window_id))
        {
            return ui.input.on_window_event(renderer.window(), event).consumed;
        }
        let _ = (window_id, event);
        false
    }

    /// Hands window input to the UI pass that the next update runs.
    fn begin_ui_frame(&mut self, window_id: WindowId, runtime: &mut App) {
        #[cfg(feature = "ui")]
        if let (Some(ui), Some(renderer), Some(mut runtime_ui)) = (
            self.ui.as_mut(),
            self.windows.get_renderer(window_id),
            runtime
                .world_mut()
                .get_resource_mut::<crate::runtime::RuntimeUi>(),
        ) {
            runtime_ui.set_input(ui.input.take_egui_input(renderer.window()));
        }
        let _ = (window_id, runtime);
    }

    /// Tessellates the finished UI pass for [`Self::render`].
    fn finish_ui_frame(&mut self, window_id: WindowId, runtime: &mut App) {
        #[cfg(feature = "ui")]
        if let (Some(ui), Some(renderer), Some(output)) = (
            self.ui.as_mut(),
            self.windows.get_renderer(window_id),
            runtime
                .world_mut()
                .get_resource_mut::<crate::runtime::RuntimeUi>()
                .and_then(|mut runtime_ui| runtime_ui.take_output()),
        ) {
            ui.input.handle_platform_output(
                renderer.window(),
                output.platform_output,
            );
            ui.textures.append(output.textures_delta);
            ui.pixels_per_point = output.pixels_per_point;
            ui.primitives = ui
                .input
                .egui_ctx()
                .tessellate(output.shapes, output.pixels_per_point);
        }
        let _ = (window_id, runtime);
    }

    fn request_next_frame(
        &mut self,
        event_loop: &ActiveEventLoop,
        runtime: &App,
    ) {
        if let Some(renderer) = self.windows.get_primary_renderer_mut() {
            self.frame_pacer.request_next_frame(
                event_loop,
                renderer.window(),
                runtime.world().resource::<RenderSettings>(),
            );
        }
    }

    /// Applies [`GameScene::set_fullscreen`] and
    /// [`GameScene::set_window_size`].
    fn apply_window_request(&mut self, world: &mut World) {
        let Some(mut request) = world.get_resource_mut::<WindowRequest>()
        else {
            return;
        };
        let size = request.size.take();
        let fullscreen = request.fullscreen;
        let Some(renderer) = self.windows.get_primary_renderer() else {
            return;
        };
        let window = renderer.window();
        if self.applied_fullscreen != fullscreen {
            window.set_fullscreen(
                fullscreen.then_some(Fullscreen::Borderless(None)),
            );
            self.applied_fullscreen = fullscreen;
        }
        if let Some([width, height]) = size {
            let _ = window.request_inner_size(PhysicalSize::new(width, height));
        }
    }

    /// Hides and locks the cursor while gameplay asks for mouse look.
    fn apply_cursor_capture(&mut self, captured: bool) {
        if self.applied_cursor_capture == captured {
            return;
        }
        let Some(renderer) = self.windows.get_primary_renderer() else {
            return;
        };
        let window = renderer.window();
        let grab = if captured {
            // Some platforms support only one of the two grab modes.
            window
                .set_cursor_grab(CursorGrabMode::Locked)
                .or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined))
        } else {
            window.set_cursor_grab(CursorGrabMode::None)
        };
        if let Err(error) = grab {
            eprintln!("cursor capture failed: {error}");
        }
        window.set_cursor_visible(!captured);
        self.applied_cursor_capture = captured;
    }

    fn resize(&mut self, window_id: WindowId) {
        self.windows.get_renderer_mut(window_id).unwrap().resize();
    }

    fn render(
        &mut self,
        window_id: WindowId,
        runtime: &App,
    ) -> Result<(), String> {
        let renderer = self.windows.get_renderer_mut(window_id).unwrap();
        let vsync = runtime.world().resource::<RenderSettings>().vsync;
        if self.applied_vsync != Some(vsync) {
            renderer.set_present_mode(select_present_mode(
                &renderer.graphics_queue(),
                &renderer.surface(),
                vsync,
            ));
            self.applied_vsync = Some(vsync);
        }

        let acquired = renderer.acquire(None, |_| {});
        match acquired {
            Ok(future) => {
                let world = runtime.world();
                let future = crate::rendering::render_scale::render_game(
                    self.scene_renderer.as_mut().unwrap(),
                    self.scaled.as_mut(),
                    future,
                    renderer.swapchain_image_view(),
                    world.resource::<RenderSettings>(),
                    world.resource::<RenderWorld>(),
                    world.resource::<AssetServer>(),
                    |_, future, _| Ok(future),
                )
                .map_err(|error| format!("scene rendering failed: {error}"))?;
                #[cfg(feature = "ui")]
                let future = match self.ui.as_mut() {
                    Some(ui) => {
                        let future = ui
                            .painter
                            .paint(
                                future,
                                renderer.swapchain_image_view(),
                                ui.pixels_per_point,
                                &ui.primitives,
                                &ui.textures,
                            )
                            .map_err(|error| {
                                format!("runtime UI painting failed: {error}")
                            })?;
                        ui.textures.clear();
                        future
                    }
                    None => future,
                };
                renderer.present(future, false);
                Ok(())
            }
            Err(VulkanError::OutOfDate) => {
                renderer.resize();
                Ok(())
            }
            Err(error) => Err(format!("swapchain acquisition failed: {error}")),
        }
    }
}

struct ProjectApplication {
    window: WindowRunner,
    /// ECS world, schedules, assets, and game plugin.
    runtime: App,
    /// Time of the previous frame, used to calculate delta time.
    previous_frame: Instant,
    gamepads: crate::runtime::Gamepads,
    /// State file and the flag the standard input reader sets when the
    /// editor asks for a code reload.
    code_reload: Option<(PathBuf, Arc<AtomicBool>)>,
    /// Set by `RUSTING_PERF`: frames counted since the last printed line.
    perf: Option<(Instant, u32)>,
    /// Time spent in `runtime.update` and in `render` since the last line.
    perf_spent: [std::time::Duration; 2],
    /// Plays the audio queue; `None` without the `audio` feature or a device.
    audio: Option<crate::audio_output::AudioOutput>,
    /// Set by [`crate::project::QUIT_AFTER_MS_ENV`]: close at this time.
    quit_at: Option<Instant>,
}

/// Environment variable that makes a running game print, once a second, its
/// frame rate and where the frame time goes.
pub const PERF_ENV: &str = "RUSTING_PERF";

impl ProjectApplication {
    /// Wraps a prepared runtime. The window opens when winit resumes.
    fn new(title: String, mut runtime: App) -> Self {
        runtime
            .world_mut()
            .resource_mut::<PhysicsBackendStatus>()
            .gpu_dynamic_available = true;
        Self {
            window: WindowRunner::new(title),
            runtime,
            previous_frame: Instant::now(),
            gamepads: crate::runtime::Gamepads::new(),
            code_reload: None,
            perf: std::env::var_os(PERF_ENV).map(|_| (Instant::now(), 0)),
            perf_spent: [std::time::Duration::ZERO; 2],
            audio: crate::audio_output::AudioOutput::open(),
            quit_at: std::env::var(crate::project::QUIT_AFTER_MS_ENV)
                .ok()
                .and_then(|ms| ms.parse().ok())
                .map(|ms| {
                    Instant::now() + std::time::Duration::from_millis(ms)
                }),
        }
    }

    /// The fractional fixed tick of an input event arriving now: the game
    /// stood at `fixed_tick + accumulator` when the frame started.
    fn event_tick(&self) -> f64 {
        let world = self.runtime.world();
        let control = world.resource::<crate::runtime::TimeControl>();
        let step = control.fixed_delta.as_secs_f64();
        let since = match control.paused {
            true => 0.0,
            false => {
                (control.accumulator().as_secs_f64()
                    + self.previous_frame.elapsed().as_secs_f64()
                        * control.time_scale.max(0.0))
                    / step
            }
        };
        world.resource::<FrameTime>().fixed_tick as f64 + since
    }

    /// Hands this frame's sound requests to the audio device, or drops them.
    fn play_audio(&mut self) {
        let world = self.runtime.world_mut();
        crate::runtime::route_sound_events(world);
        let commands =
            world.resource_mut::<crate::runtime::AudioQueue>().drain();
        let Some(audio) = &mut self.audio else {
            return;
        };
        let root = world
            .get_resource::<ProjectFolder>()
            .map(|folder| folder.0.join("assets"))
            .unwrap_or_default();
        // Real time now is `accumulator` plus the time since the frame
        // started past tick `now`. A sound for tick T starts one fixed step
        // after T's real time, so start jitter does not depend on the frame.
        let control = world.resource::<crate::runtime::TimeControl>();
        let (step, paused) = (control.fixed_delta, control.paused);
        let past = control.accumulator().as_secs_f64()
            / control.time_scale.max(1e-6)
            + self.previous_frame.elapsed().as_secs_f64();
        let now = world.resource::<FrameTime>().fixed_tick;
        let delay = |tick: u64| {
            let ahead = (tick as f64 - now as f64 + 1.0) * step.as_secs_f64();
            match paused {
                true => std::time::Duration::ZERO,
                false => std::time::Duration::from_secs_f64(
                    (ahead - past).clamp(0.0, 3600.0),
                ),
            }
        };
        for command in commands {
            audio.run(&root, command, delay);
        }
    }

    /// Prints `[rusting] perf` once a second when `RUSTING_PERF` is set.
    fn report_perf(&mut self) {
        let Some((since, frames)) = &mut self.perf else {
            return;
        };
        *frames += 1;
        let elapsed = since.elapsed();
        if elapsed < std::time::Duration::from_secs(1) {
            return;
        }
        let fps = f64::from(*frames) / elapsed.as_secs_f64();
        let [update, render] =
            std::mem::take(&mut self.perf_spent).map(|time| time / *frames);
        (*since, *frames) = (Instant::now(), 0);
        if let Some(window) = self.window.windows.get_primary_window() {
            window.set_title(&format!(
                "{} - {fps:.0} fps ({:.2} ms)",
                self.window.title,
                1000.0 / fps
            ));
        }
        let ms = |time: std::time::Duration| time.as_secs_f64() * 1000.0;
        let mut cpu = *self
            .runtime
            .world()
            .resource::<crate::runtime::CpuFrameTimings>();
        let Some(renderer) = self.window.scene_renderer.as_mut() else {
            return;
        };
        renderer.write_cpu_timings(&mut cpu);
        let gpu = renderer.gpu_pass_times();
        let counters = renderer.render_counters();
        let mut line = format!(
            "[rusting] perf {fps:.0} fps ({:.2} ms/frame) | update {:.2} render {:.2} ms | CPU physics {:.2} extract {:.2} prepare {:.2} record {:.2} ms | GPU {:.2} ms",
            1000.0 / fps,
            ms(update),
            ms(render),
            ms(cpu.physics),
            ms(cpu.extraction),
            ms(cpu.preparation),
            ms(cpu.recording),
            ms(gpu.total()),
        );
        for (pass, time) in &gpu.0 {
            line += &format!(" | {} {:.2}", pass.label(), ms(*time));
        }
        line += &format!(
            " | draws {} dispatches {} triangles {}",
            counters.draws, counters.dispatches, counters.triangles
        );
        eprintln!("{line}");
    }
}

impl ApplicationHandler for ProjectApplication {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        self.window.resumed(event_loop, &mut self.runtime);
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        window_id: WindowId,
        event: WindowEvent,
    ) {
        // The swapchain probe's hidden window reports events too.
        if self.window.windows.get_renderer(window_id).is_none() {
            return;
        }
        // Presses the UI uses stay out of gameplay; releases always pass so
        // no key or button stays held.
        if self.window.ui_event(window_id, &event)
            && match &event {
                WindowEvent::KeyboardInput { event, .. } => {
                    event.state.is_pressed()
                }
                WindowEvent::MouseInput { state, .. } => state.is_pressed(),
                _ => false,
            }
        {
            return;
        }
        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::Resized(size) => {
                self.window.resize(window_id);
                self.runtime
                    .world_mut()
                    .resource_mut::<RuntimeInput>()
                    .record_viewport_size([
                        size.width as f32,
                        size.height as f32,
                    ]);
            }
            WindowEvent::ScaleFactorChanged { .. } => {
                self.window.resize(window_id);
            }
            WindowEvent::Focused(false) => {
                self.runtime
                    .world_mut()
                    .resource_mut::<RuntimeInput>()
                    .release_all();
            }
            WindowEvent::KeyboardInput { event, .. } => {
                if let PhysicalKey::Code(code) = event.physical_key {
                    let tick = self.event_tick();
                    let mut input =
                        self.runtime.world_mut().resource_mut::<RuntimeInput>();
                    input.record_key(code, event.state.is_pressed());
                    if event.state.is_pressed() && !event.repeat {
                        input.record_press_tick(
                            crate::runtime::InputBinding::Key(code),
                            tick,
                        );
                    }
                }
            }
            WindowEvent::MouseInput { state, button, .. } => {
                let tick = self.event_tick();
                let mut input =
                    self.runtime.world_mut().resource_mut::<RuntimeInput>();
                if state.is_pressed() {
                    input.record_press_tick(
                        crate::runtime::InputBinding::Mouse(button),
                        tick,
                    );
                }
                input.record_mouse_button(button, state.is_pressed());
            }
            WindowEvent::CursorMoved { position, .. } => {
                self.runtime
                    .world_mut()
                    .resource_mut::<RuntimeInput>()
                    .record_cursor_position([
                        position.x as f32,
                        position.y as f32,
                    ]);
            }
            WindowEvent::RedrawRequested => {
                // Completed GPU events and synchronized state enter ECS before
                // this frame starts, so Rust update systems can read them.
                let scene_renderer =
                    self.window.scene_renderer.as_mut().unwrap();
                let raw_events = scene_renderer.take_completed_physics_events();
                let states = scene_renderer.take_completed_physics_states();
                let hashes =
                    scene_renderer.take_completed_physics_state_hashes();
                let lost = scene_renderer.take_physics_events_lost();
                if lost > 0 {
                    self.runtime
                        .world_mut()
                        .resource_mut::<EventQueue<GpuPhysicsEventsLost>>()
                        .send(GpuPhysicsEventsLost { count: lost });
                }
                if !raw_events.is_empty() {
                    route_gpu_physics_events(
                        self.runtime.world_mut(),
                        &raw_events,
                    );
                }
                if !states.is_empty() {
                    apply_gpu_state_samples(self.runtime.world_mut(), &states);
                }
                record_gpu_state_hashes(self.runtime.world_mut(), &hashes);
                // Delta time tells gameplay how much real time passed.
                let now = Instant::now();
                let delta = now.saturating_duration_since(self.previous_frame);
                self.previous_frame = now;
                self.gamepads.poll(
                    &mut self
                        .runtime
                        .world_mut()
                        .resource_mut::<RuntimeInput>(),
                );
                self.window.begin_ui_frame(window_id, &mut self.runtime);
                let update_start = Instant::now();
                let updated = self.runtime.update(delta);
                self.perf_spent[0] += update_start.elapsed();
                if let Err(error) = updated {
                    eprintln!("runtime update failed: {error}");
                    event_loop.exit();
                    return;
                }
                self.window.finish_ui_frame(window_id, &mut self.runtime);
                if self.runtime.exit_requested()
                    || self.quit_at.is_some_and(|at| Instant::now() >= at)
                {
                    event_loop.exit();
                    return;
                }
                self.play_audio();
                if let Some(mut assets) =
                    self.runtime.world_mut().get_resource_mut::<AssetServer>()
                {
                    for failure in assets.take_reload_failures() {
                        eprintln!("hot reload failed: {failure}");
                    }
                }
                let mut input =
                    self.runtime.world_mut().resource_mut::<RuntimeInput>();
                input.clear_frame_edges();
                let captured = input.cursor_captured();
                self.window.apply_cursor_capture(captured);
                self.window.apply_window_request(self.runtime.world_mut());
                let render_start = Instant::now();
                let rendered = self.window.render(window_id, &self.runtime);
                self.perf_spent[1] += render_start.elapsed();
                match rendered {
                    Ok(()) => {
                        announce_first_frame();
                        self.report_perf();
                    }
                    Err(error) => {
                        eprintln!("{error}");
                        event_loop.exit();
                    }
                }
            }
            _ => {}
        }
    }

    fn device_event(
        &mut self,
        _event_loop: &ActiveEventLoop,
        _device_id: DeviceId,
        event: DeviceEvent,
    ) {
        if let DeviceEvent::MouseMotion { delta } = event {
            self.runtime
                .world_mut()
                .resource_mut::<RuntimeInput>()
                .record_mouse_motion([delta.0 as f32, delta.1 as f32]);
        }
    }

    fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
        // The egui clipboard talks to the Wayland connection, which closes
        // when the event loop returns; dropping it later crashes the exit.
        #[cfg(feature = "ui")]
        {
            self.window.ui = None;
        }
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        if let Some((path, requested)) = &self.code_reload {
            if requested.load(Ordering::Relaxed) {
                // The editor rebuilds and starts the game again after this
                // process exits.
                if let Err(error) =
                    save_code_reload_state(&mut self.runtime, path)
                {
                    eprintln!(
                        "{} could not save the scene: {error}",
                        crate::project::CODE_RELOAD_CLEAN_MARKER
                    );
                }
                event_loop.exit();
                return;
            }
        }
        self.window.request_next_frame(event_loop, &self.runtime);
    }
}

/// Opens a window and runs a prepared runtime until the window closes.
/// With [`crate::project::REPLAY_OUT_ENV`] set, records the session and
/// writes the replay there on exit.
pub(crate) fn run_windowed(
    title: String,
    mut runtime: App,
) -> Result<(), Box<dyn Error>> {
    let replay_out = std::env::var_os(crate::project::REPLAY_OUT_ENV);
    if replay_out.is_some() {
        runtime.start_recording();
    }
    let event_loop = EventLoop::new()?;
    let mut application = ProjectApplication::new(title, runtime);
    if let Some(path) = std::env::var_os(crate::project::CODE_RELOAD_STATE_ENV)
    {
        let requested = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&requested);
        std::thread::spawn(move || {
            for line in std::io::stdin().lines().map_while(Result::ok) {
                if line.trim() == crate::project::CODE_RELOAD_SAVE_COMMAND {
                    flag.store(true, Ordering::Relaxed);
                }
            }
        });
        application.code_reload = Some((PathBuf::from(path), requested));
    }
    event_loop.run_app(&mut application)?;
    if let (Some(path), Some(replay)) =
        (replay_out, application.runtime.finish_recording())
    {
        std::fs::write(path, serde_json::to_vec(&replay)?)?;
    }
    Ok(())
}

pub use crate::project::HEADLESS_TICKS_ENV;

/// Set when [`run_project`] starts; first-frame timing counts from here.
static GAME_START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();

/// Prints [`crate::project::FIRST_FRAME_MARKER`] once, so the editor and
/// `rusting run` can measure save-to-first-playable-frame time.
fn announce_first_frame() {
    static ANNOUNCED: std::sync::Once = std::sync::Once::new();
    ANNOUNCED.call_once(|| {
        let start = GAME_START.get_or_init(Instant::now);
        eprintln!(
            "{} {} ms",
            crate::project::FIRST_FRAME_MARKER,
            start.elapsed().as_millis()
        );
    });
}

/// Runs a cooked scene with a native game-defined Rust plugin.
///
/// With [`HEADLESS_TICKS_ENV`] set, runs that many ticks through
/// [`run_project_headless`] instead of opening a window. With
/// [`crate::scenario::TEST_SCENARIO_ENV`] set, runs that scenario file
/// through [`run_project_scenario`] instead. With
/// [`crate::project::REPLAY_PLAY_ENV`] set, plays that replay headless and
/// fails if it diverges.
///
/// # Arguments
/// * `title` - Text shown in the game window title bar.
/// * `scene_path` - Path to cooked `.rscene.bin` data.
/// * `plugin` - Native Rust systems and resources used by this game.
pub fn run_project<P: Plugin>(
    title: impl Into<String>,
    scene_path: impl Into<PathBuf>,
    plugin: P,
) -> Result<(), Box<dyn Error>> {
    GAME_START.get_or_init(Instant::now);
    if std::env::var_os(crate::debug_session::DEBUG_SESSION_ENV).is_some() {
        let mut runtime = load_project_runtime(&scene_path.into(), plugin)?;
        crate::debug_session::run_debug_session(
            &mut runtime,
            std::io::stdin().lock(),
            std::io::stdout().lock(),
        )?;
        return Ok(());
    }
    if let Some(scenario) = std::env::var_os(crate::scenario::TEST_SCENARIO_ENV)
    {
        let report = std::env::var_os(crate::scenario::TEST_REPORT_ENV);
        return run_project_scenario(
            scene_path,
            plugin,
            PathBuf::from(scenario),
            report.map(PathBuf::from),
        );
    }
    if let Some(ticks) = std::env::var_os(HEADLESS_TICKS_ENV) {
        let ticks = ticks
            .to_str()
            .and_then(|ticks| ticks.parse().ok())
            .ok_or(format!("{HEADLESS_TICKS_ENV} must be a tick count"))?;
        return run_project_headless(scene_path, plugin, ticks);
    }
    let mut runtime = load_project_runtime(&scene_path.into(), plugin)?;
    if let Some(path) = std::env::var_os(crate::project::REPLAY_PLAY_ENV) {
        let replay: crate::runtime::Replay =
            serde_json::from_slice(&std::fs::read(path)?)?;
        return match crate::runtime::play_replay(&mut runtime, &replay)? {
            None => Ok(()),
            Some(tick) => Err(format!(
                "replay diverges from the recording at tick {tick}"
            )
            .into()),
        };
    }
    if let Some(path) = std::env::var_os(crate::project::CODE_RELOAD_STATE_ENV)
        .map(PathBuf::from)
        .filter(|path| path.is_file())
    {
        match restore_code_reload_state(&mut runtime, &path) {
            Ok(()) => eprintln!("{}", crate::project::CODE_RELOAD_KEPT_MARKER),
            Err(error) => eprintln!(
                "{} the saved scene does not fit the new code: {error}",
                crate::project::CODE_RELOAD_CLEAN_MARKER
            ),
        }
        // A crash on the next run must not restore this state again.
        let _ = std::fs::remove_file(&path);
    }
    run_windowed(title.into(), runtime)
}

/// Runs a cooked scene for a fixed number of ticks with no window, Vulkan
/// device, or renderer, then returns. For CI and machines with no display.
/// With [`crate::project::STATE_HASH_OUT_ENV`] set, writes the run's
/// [`crate::runtime::StateHashReport`] to that file. With
/// [`crate::project::FINAL_SCENE_OUT_ENV`] set, saves the scene as it stands
/// after the last tick to that file.
///
/// # Arguments
/// * `scene_path` - Path to cooked `.rscene.bin` data.
/// * `plugin` - Native Rust systems and resources used by this game.
/// * `ticks` - Number of fixed-step updates to run before returning.
pub fn run_project_headless<P: Plugin>(
    scene_path: impl Into<PathBuf>,
    plugin: P,
    ticks: u32,
) -> Result<(), Box<dyn Error>> {
    let (mut runtime, report, elapsed) =
        simulate_timed(scene_path.into(), plugin, ticks)?;
    eprintln!(
        "{} {:.3}",
        crate::project::TICK_TIME_MARKER,
        elapsed.as_secs_f64() * 1000.0 / f64::from(ticks.max(1))
    );
    if let Some(path) = std::env::var_os(crate::project::FINAL_SCENE_OUT_ENV) {
        crate::runtime::save_scene(
            runtime.world_mut(),
            path,
            format!("after tick {ticks}"),
        )?;
    }
    if let Some(path) = std::env::var_os(crate::project::STATE_HASH_OUT_ENV) {
        std::fs::write(path, serde_json::to_vec(&report)?)?;
    }
    Ok(())
}

/// Loads a cooked scene and runs `ticks` updates of one `fixed_delta` each
/// (one fixed step each at time scale 1) with no window, surface, Vulkan
/// device, or renderer, then returns the runtime and a report of every
/// tick's state hash (`StateHashes` keeps only the recent ones). GPU-class
/// bodies do not move without a renderer; a warning names how many there
/// are.
pub fn simulate_project_headless<P: Plugin>(
    scene_path: impl Into<PathBuf>,
    plugin: P,
    ticks: u32,
) -> Result<(App, crate::runtime::StateHashReport), Box<dyn Error>> {
    let (runtime, report, _) =
        simulate_timed(scene_path.into(), plugin, ticks)?;
    Ok((runtime, report))
}

/// [`simulate_project_headless`] plus the wall time of the tick loop alone,
/// without the scene load.
fn simulate_timed<P: Plugin>(
    scene_path: PathBuf,
    plugin: P,
    ticks: u32,
) -> Result<
    (App, crate::runtime::StateHashReport, std::time::Duration),
    Box<dyn Error>,
> {
    let mut runtime = load_project_runtime(&scene_path, plugin)?;
    let world = runtime.world_mut();
    let gpu_bodies = world
        .query::<&crate::runtime::PhysicsBody>()
        .iter(world)
        .filter(|body| body.uses_gpu())
        .count();
    if gpu_bodies > 0 {
        eprintln!(
            "headless run: {gpu_bodies} GPU physics bodies stay still without a renderer"
        );
    }

    let delta = runtime.world().resource::<FrameTime>().fixed_delta;
    let mut hashes = Vec::with_capacity(ticks as usize);
    let start = Instant::now();
    for _ in 0..ticks {
        runtime.update(delta)?;
        announce_first_frame();
        if runtime.exit_requested() {
            break;
        }
        hashes.extend(
            runtime
                .world()
                .get_resource::<crate::runtime::StateHashes>()
                .and_then(|recorded| recorded.recent.back().copied()),
        );
    }
    let elapsed = start.elapsed();
    let entities =
        crate::runtime::named_entity_state_hashes(runtime.world_mut());
    let report = crate::runtime::StateHashReport {
        ticks: hashes,
        entities,
    };
    Ok((runtime, report, elapsed))
}

/// Runs a [`crate::scenario::Scenario`] file against a cooked scene with no
/// window. Captures render offscreen when Vulkan is available. Writes the
/// [`crate::scenario::ScenarioReport`] as JSON to `report_path`, or to
/// standard output without one, and fails when the scenario fails.
pub fn run_project_scenario<P: Plugin>(
    scene_path: impl Into<PathBuf>,
    plugin: P,
    scenario_path: PathBuf,
    report_path: Option<PathBuf>,
) -> Result<(), Box<dyn Error>> {
    let mut scenario: crate::scenario::Scenario =
        serde_json::from_str(&std::fs::read_to_string(&scenario_path)?)?;
    scenario.update_golden =
        std::env::var_os(crate::scenario::UPDATE_GOLDEN_ENV).is_some();
    scenario.keep_going |=
        std::env::var_os(crate::scenario::KEEP_GOING_ENV).is_some();
    let mut runtime = load_project_runtime(&scene_path.into(), plugin)?;
    let base = scenario_path.parent().unwrap_or(Path::new("."));
    let report = crate::scenario::run_scenario(&mut runtime, &scenario, base);
    let text = serde_json::to_string_pretty(&report)?;
    match report_path {
        Some(path) => std::fs::write(path, text)?,
        None => println!("{text}"),
    }
    match report.first_failure {
        None => Ok(()),
        Some(failure) => Err(format!(
            "scenario `{}` failed at tick {} step {}: {}",
            report.name, failure.tick, failure.step, failure.message
        )
        .into()),
    }
}

/// Runs a cooked scene using one short native Rust update function.
///
/// # Arguments
/// * `scene_path` - Path to cooked `.rscene.bin` data.
/// * `update` - Function called once per rendered frame.
pub fn run_game(
    scene_path: impl Into<PathBuf>,
    update: GameUpdate,
) -> GameResult {
    run_project(
        "RustingEngine Game",
        scene_path,
        SimpleGamePlugin { update },
    )
}

/// Finds cooked data beside an exported executable, then falls back to the
/// Cargo project path used during development.
#[must_use]
pub fn resolve_game_scene_path(
    relative: impl AsRef<std::path::Path>,
    project_root: impl AsRef<std::path::Path>,
) -> PathBuf {
    let relative = relative.as_ref();
    if let Some(path) = std::env::var_os("RUSTING_SCENE_PATH") {
        return PathBuf::from(path);
    }
    if let Ok(executable) = std::env::current_exe() {
        if let Some(folder) = executable.parent() {
            let packaged = folder.join(relative);
            if packaged.is_file() {
                return packaged;
            }
        }
    }
    project_root.as_ref().join(relative)
}

/// Generates the native game entry point while keeping gameplay in normal
/// Rust. The scene path is relative to the game project's `Cargo.toml`.
#[macro_export]
macro_rules! rusting_game {
    ($update:path) => {
        $crate::rusting_game!("build/main.rscene.bin", $update);
    };
    ($scene:literal, $update:path) => {
        fn main() -> $crate::project_runner::GameResult {
            let scene = $crate::project_runner::resolve_game_scene_path(
                $scene,
                env!("CARGO_MANIFEST_DIR"),
            );
            $crate::project_runner::run_game(scene, $update)
        }
    };
}

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

    #[test]
    fn headless_simulation_runs_exact_ticks_from_a_cooked_scene() {
        let directory = std::env::temp_dir()
            .join(format!("rusting-headless-{}", uuid::Uuid::new_v4()));
        let source = directory.join("main.rscene");
        let cooked = directory.join("main.rscene.bin");
        let mut editor = App::new();
        editor.add_plugin(AssetPlugin).unwrap();
        editor.spawn((
            Name("Ball".into()),
            Transform::new([0.0, 5.0, 0.0]),
            crate::runtime::PhysicsBody::default(),
            crate::runtime::RigidBody::default(),
            crate::runtime::Collider::default(),
        ));
        crate::runtime::save_scene(editor.world_mut(), &source, "main")
            .unwrap();
        crate::runtime::cook_scene(&source, &cooked).unwrap();
        fn idle(_: &mut GameScene<'_>, _: &FrameTime) {}
        let (mut runtime, report) = simulate_project_headless(
            &cooked,
            SimpleGamePlugin { update: idle },
            30,
        )
        .unwrap();
        std::fs::remove_dir_all(&directory).unwrap();

        assert_eq!(runtime.world().resource::<FrameTime>().fixed_tick, 30);
        let hashes = &runtime
            .world()
            .resource::<crate::runtime::StateHashes>()
            .recent;
        assert_eq!(hashes.len(), 30);
        assert!(hashes.iter().eq(&report.ticks));
        assert_eq!(hashes.back().unwrap().0, 30);
        let mut scene = GameScene {
            world: runtime.world_mut(),
        };
        assert!(scene.object("Ball").position()[1] < 5.0);
    }

    #[derive(
        bevy_ecs::component::Component,
        Clone,
        Default,
        serde::Serialize,
        serde::Deserialize,
    )]
    struct Health {
        hp: i32,
    }

    crate::reflect! {
        struct Health {
            hp: i32,
        }
    }

    /// The same component after a change that old saved values do not fit.
    #[derive(
        bevy_ecs::component::Component,
        Clone,
        Default,
        serde::Serialize,
        serde::Deserialize,
    )]
    struct HealthText {
        hp: String,
    }

    crate::reflect! {
        struct HealthText {
            hp: String,
        }
    }

    /// One build of a test game: its update function and its `Health`.
    struct TestGame {
        update: GameUpdate,
        changed_health: bool,
    }

    impl Plugin for TestGame {
        fn build(&self, app: &mut App) -> Result<(), AppError> {
            let registered = if self.changed_health {
                app.register_scene_component::<HealthText>("test.health")
                    .map(drop)
            } else {
                app.register_scene_component::<Health>("test.health")
                    .map(drop)
            };
            registered.map_err(|error| AppError::PluginSetup {
                plugin: "TestGame",
                message: error.to_string(),
            })?;
            app.add_plugin(SimpleGamePlugin {
                update: self.update,
            })?;
            app.add_system(ScheduleStage::Startup, |world: &mut World| {
                world.spawn((
                    crate::runtime::SceneId::new(),
                    Name("Marker".into()),
                ));
            });
            Ok(())
        }
    }

    fn count_named(world: &mut World, name: &str) -> usize {
        let mut query = world.query::<&Name>();
        query.iter(world).filter(|named| named.0 == name).count()
    }

    #[test]
    fn code_reload_keeps_the_scene_and_runs_the_new_code() {
        let directory = std::env::temp_dir()
            .join(format!("rusting-code-reload-{}", uuid::Uuid::new_v4()));
        let source = directory.join("main.rscene");
        let cooked = directory.join("main.rscene.bin");
        let state = directory.join("state.json");
        let mut editor = App::new();
        editor.add_plugin(AssetPlugin).unwrap();
        editor.spawn((Name("Ball".into()), Transform::new([0.0, 0.0, 0.0])));
        crate::runtime::save_scene(editor.world_mut(), &source, "main")
            .unwrap();
        crate::runtime::cook_scene(&source, &cooked).unwrap();

        // The old code spawns a coin, gives the ball health, then moves the
        // ball right and hurts it every frame.
        fn old_code(scene: &mut GameScene<'_>, _: &FrameTime) {
            scene.once("setup", |scene| {
                scene.spawn_cube(
                    "Coin",
                    Transform::default(),
                    &CubeSpawn::new(),
                );
                let ball = find_named_entity(scene.world, "Ball").unwrap();
                scene.world.entity_mut(ball).insert(Health { hp: 10 });
            });
            scene.object("Ball").move_x(1.0);
            let ball = find_named_entity(scene.world, "Ball").unwrap();
            scene.world.get_mut::<Health>(ball).unwrap().hp -= 1;
        }
        // The changed system moves it up instead. Its setup runs only on a
        // clean start.
        fn new_code(scene: &mut GameScene<'_>, _: &FrameTime) {
            scene.once("setup", |scene| {
                scene.spawn_cube(
                    "Fresh",
                    Transform::default(),
                    &CubeSpawn::new(),
                );
            });
            scene.object("Ball").move_y(1.0);
        }
        let frame = std::time::Duration::from_millis(16);
        let mut old = load_project_runtime(
            &cooked,
            TestGame {
                update: old_code,
                changed_health: false,
            },
        )
        .unwrap();
        for _ in 0..3 {
            old.update(frame).unwrap();
        }
        save_code_reload_state(&mut old, &state).unwrap();

        let mut new = load_project_runtime(
            &cooked,
            TestGame {
                update: new_code,
                changed_health: false,
            },
        )
        .unwrap();
        restore_code_reload_state(&mut new, &state).unwrap();
        for _ in 0..2 {
            new.update(frame).unwrap();
        }
        let world = new.world_mut();
        let ball = find_named_entity(world, "Ball").unwrap();
        assert_eq!(
            world.get::<Transform>(ball).unwrap().position,
            [3.0, 2.0, 0.0]
        );
        assert_eq!(world.get::<Health>(ball).unwrap().hp, 7);
        assert_eq!(count_named(world, "Coin"), 1);
        assert_eq!(count_named(world, "Fresh"), 0);
        // Startup ran in the old process only.
        assert_eq!(count_named(world, "Marker"), 1);

        // Saved values that do not fit the changed component start clean.
        let mut changed = load_project_runtime(
            &cooked,
            TestGame {
                update: new_code,
                changed_health: true,
            },
        )
        .unwrap();
        let error = restore_code_reload_state(&mut changed, &state)
            .unwrap_err()
            .to_string();
        assert!(error.contains("test.health"), "{error}");
        changed.update(frame).unwrap();
        let world = changed.world_mut();
        let ball = find_named_entity(world, "Ball").unwrap();
        assert_eq!(
            world.get::<Transform>(ball).unwrap().position,
            [0.0, 1.0, 0.0]
        );
        assert_eq!(count_named(world, "Coin"), 0);
        assert_eq!(count_named(world, "Fresh"), 1);
        assert_eq!(count_named(world, "Marker"), 1);
        std::fs::remove_dir_all(&directory).unwrap();
    }

    #[test]
    fn press_tick_is_the_event_time_or_the_frame_tick() {
        use crate::runtime::{ActionMap, InputBinding, KeyCode};
        let mut world = World::new();
        world.insert_resource(FrameTime {
            fixed_tick: 122,
            ..FrameTime::default()
        });
        let mut actions = ActionMap::default();
        actions.bind("mine", InputBinding::Key(KeyCode::Space));
        actions.bind("menu", InputBinding::Key(KeyCode::Escape));
        world.insert_resource(actions);
        let mut input = RuntimeInput::default();
        input.record_key(KeyCode::Space, true);
        input.record_press_tick(InputBinding::Key(KeyCode::Space), 121.4);
        input.record_press_tick(InputBinding::Key(KeyCode::Space), 121.9);
        input.record_key(KeyCode::Escape, true);
        world.insert_resource(input);
        let scene = GameScene { world: &mut world };
        assert_eq!(scene.press_tick("mine"), Some(121.4));
        assert_eq!(scene.press_tick("menu"), Some(122.0));
        assert_eq!(scene.press_tick("jump"), None);
    }

    #[test]
    fn sound_requests_are_queued_counted_and_drained() {
        let mut world = World::new();
        let mut scene = GameScene { world: &mut world };
        let id = scene.play_sound("sfx/hit.wav", 0.5);
        scene.play_sound_looped("sfx/hum.ogg", 1.0);
        scene.stop_sound(id);
        scene.set_master_volume(0.2);
        assert_eq!(scene.sounds_requested(), 2);
        let commands =
            world.resource_mut::<crate::runtime::AudioQueue>().drain();
        assert_eq!(commands.len(), 4);
        assert!(matches!(
            &commands[1],
            crate::runtime::AudioCommand::Play { looped: true, .. }
        ));
    }

    #[test]
    fn restart_puts_the_starting_scene_back_and_reruns_setup() {
        let directory = std::env::temp_dir()
            .join(format!("rusting-restart-{}", uuid::Uuid::new_v4()));
        let source = directory.join("main.rscene");
        let cooked = directory.join("main.rscene.bin");
        let mut editor = App::new();
        editor.add_plugin(AssetPlugin).unwrap();
        editor.spawn((Name("Ball".into()), Transform::new([0.0, 0.0, 0.0])));
        editor.spawn((Name("Gate".into()), Transform::default()));
        crate::runtime::save_scene(editor.world_mut(), &source, "main")
            .unwrap();
        crate::runtime::cook_scene(&source, &cooked).unwrap();

        // Setup spawns a coin; the ball moves right each frame, the gate is
        // removed, and the third frame restarts.
        fn code(scene: &mut GameScene<'_>, _: &FrameTime) {
            scene.once("setup", |scene| {
                scene.spawn_cube(
                    "Coin",
                    Transform::default(),
                    &CubeSpawn::new(),
                );
            });
            scene.despawn("Gate");
            scene.object("Ball").move_x(1.0);
            if scene.object("Ball").position()[0] >= 3.0 {
                assert!(scene.restart());
            }
        }
        let frame = std::time::Duration::from_millis(16);
        let mut game = load_project_runtime(
            &cooked,
            TestGame {
                update: code,
                changed_health: false,
            },
        )
        .unwrap();
        for _ in 0..3 {
            game.update(frame).unwrap();
        }
        let world = game.world_mut();
        let ball = find_named_entity(world, "Ball").unwrap();
        assert_eq!(world.get::<Transform>(ball).unwrap().position, [0.0; 3]);
        assert_eq!(count_named(world, "Gate"), 1);
        assert_eq!(count_named(world, "Coin"), 0);
        game.update(frame).unwrap();
        let world = game.world_mut();
        assert_eq!(count_named(world, "Coin"), 1, "setup ran again");
        assert_eq!(count_named(world, "Gate"), 0);
        let ball = find_named_entity(world, "Ball").unwrap();
        assert_eq!(world.get::<Transform>(ball).unwrap().position[0], 1.0);

        let mut world = World::new();
        assert!(!GameScene { world: &mut world }.restart());
        std::fs::remove_dir_all(&directory).unwrap();
    }

    #[test]
    fn basis_forward_follows_the_rotation_order() {
        let mut world = World::new();
        let rotation = [0.3_f32, 1.0, 0.0];
        world.spawn((
            Name("Cam".into()),
            Transform {
                rotation,
                ..Transform::default()
            },
        ));
        let mut scene = GameScene { world: &mut world };
        let [_, _, forward] = scene.basis("Cam").unwrap();
        let (x, y) = (rotation[0], rotation[1]);
        let expected = [-y.sin() * x.cos(), x.sin(), -y.cos() * x.cos()];
        for (a, b) in forward.iter().zip(expected) {
            assert!((a - b).abs() < 1e-5, "{forward:?} {expected:?}");
        }
    }

    #[test]
    fn reparent_and_set_light_move_and_dim_a_lantern() {
        use crate::runtime::{Parent, PointLight};
        let mut world = World::new();
        let lantern = world
            .spawn((
                Name("Lantern".into()),
                Transform::default(),
                PointLight {
                    color: [1.0; 3],
                    intensity: 5.0,
                    range: 4.0,
                },
            ))
            .id();
        let hand = world
            .spawn((Name("Hand".into()), Transform::default()))
            .id();
        let mut scene = GameScene { world: &mut world };
        assert!(scene.reparent("Lantern", Some("Hand")));
        assert_eq!(
            scene.world().get::<Parent>(lantern).map(|p| p.0),
            Some(hand)
        );
        assert!(!scene.reparent("Hand", Some("Lantern")), "a loop");
        assert!(scene.reparent("Lantern", None));
        assert!(scene.world().get::<Parent>(lantern).is_none());
        assert!(scene.set_light("Lantern", None, Some(0.0), Some(2.0)));
        assert!(!scene.set_light("Hand", None, Some(1.0), None));
        let light = scene.world().get::<PointLight>(lantern).unwrap();
        assert_eq!(
            (light.color, light.intensity, light.range),
            ([1.0; 3], 0.0, 2.0)
        );
    }

    #[test]
    fn video_settings_write_render_settings_and_the_window_request() {
        let mut world = World::new();
        world.insert_resource(RenderSettings::default());
        let mut scene = GameScene { world: &mut world };
        scene.set_render_scale(0.1);
        assert_eq!(scene.render_scale(), 0.25);
        scene.set_render_scale(f32::NAN);
        assert_eq!(scene.render_scale(), 0.25);
        scene.set_vsync(true);
        scene.set_max_fps(Some(0));
        assert!(!scene.fullscreen());
        scene.set_fullscreen(true);
        scene.set_window_size([1280, 0]);
        assert!(scene.fullscreen());
        let settings = world.resource::<RenderSettings>();
        assert!(settings.vsync && settings.limit_fps);
        assert_eq!(settings.max_fps, 1);
        assert_eq!(world.resource::<WindowRequest>().size, Some([1280, 1]));
        GameScene { world: &mut world }.set_max_fps(None);
        assert!(!world.resource::<RenderSettings>().limit_fps);
    }

    #[test]
    fn body_calls_stop_spin_and_reset_bodies_and_set_look_turns_the_player() {
        use crate::runtime::{PlayerController, RigidBody, RigidBodyKind};
        let mut world = World::new();
        let crate_entity = world
            .spawn((
                Name("Crate".into()),
                Transform::default(),
                RigidBody {
                    kind: RigidBodyKind::Dynamic,
                    ..RigidBody::default()
                },
                crate::runtime::Sleeping,
            ))
            .id();
        world.spawn((
            Name("Player".into()),
            Transform::default(),
            PlayerController::default(),
        ));
        let mut scene = GameScene { world: &mut world };
        assert!(scene.set_angular_velocity("Crate", [0.0, 2.0, 0.0]));
        assert_eq!(scene.angular_velocity("Crate"), Some([0.0, 2.0, 0.0]));
        assert!(scene.set_linear_velocity("Crate", [1.0, 0.0, 0.0]));
        // Becoming kinematic freezes the body instead of carrying it off.
        assert!(scene.set_body_kind("Crate", RigidBodyKind::Kinematic));
        assert_eq!(scene.linear_velocity("Crate"), Some([0.0; 3]));
        assert_eq!(scene.angular_velocity("Crate"), Some([0.0; 3]));
        assert!(scene.set_body_kind("Crate", RigidBodyKind::Dynamic));
        assert!(scene.set_angular_velocity("Crate", [3.0, 0.0, 0.0]));
        assert!(scene.set_linear_velocity("Crate", [0.0, 5.0, 0.0]));
        assert!(scene.reset_body("Crate"));
        assert_eq!(scene.linear_velocity("Crate"), Some([0.0; 3]));
        assert_eq!(scene.angular_velocity("Crate"), Some([0.0; 3]));
        assert!(!scene.reset_body("Nothing"));
        assert!(scene
            .world()
            .get::<crate::runtime::Sleeping>(crate_entity)
            .is_none());

        assert!(scene.set_look("Player", 1.5, -0.25));
        assert!(!scene.set_look("Crate", 0.0, 0.0), "no controller");
        let mut players = scene.world().query::<&PlayerController>();
        let player = players.single(scene.world()).unwrap();
        assert_eq!((player.yaw, player.pitch), (1.5, -0.25));
    }

    #[test]
    fn restart_repeats_a_physics_pile_exactly() {
        use crate::runtime::{
            Collider, ColliderShape, PhysicsBody, RigidBody, RigidBodyKind,
            SimulationClass,
        };
        let directory = std::env::temp_dir()
            .join(format!("rusting-restart-pile-{}", uuid::Uuid::new_v4()));
        let source = directory.join("main.rscene");
        let cooked = directory.join("main.rscene.bin");
        let mut editor = App::new();
        editor.add_plugin(AssetPlugin).unwrap();
        let body = |kind| {
            (
                PhysicsBody {
                    simulation: SimulationClass::Cpu,
                    ..PhysicsBody::default()
                },
                RigidBody {
                    kind,
                    ..RigidBody::default()
                },
                Collider {
                    shape: ColliderShape::Box {
                        half_extents: [0.5; 3],
                    },
                    ..Collider::default()
                },
            )
        };
        let mut floor = Transform::new([0.0, -0.5, 0.0]);
        floor.scale = [20.0, 1.0, 20.0];
        editor.spawn((Name("Floor".into()), floor, body(RigidBodyKind::Fixed)));
        for index in 0..12 {
            let offset = index as f32;
            editor.spawn((
                Name(format!("Box {index}")),
                crate::runtime::ObjectClasses::new(["box"]),
                Transform::new([
                    (offset * 0.37).sin() * 0.4,
                    0.6 + offset * 1.05,
                    (offset * 0.61).cos() * 0.4,
                ]),
                body(RigidBodyKind::Dynamic),
            ));
        }
        crate::runtime::save_scene(editor.world_mut(), &source, "main")
            .unwrap();
        // Patched files list objects in creation order, not by id, while a
        // restart reloads a capture sorted by id.
        let mut json: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&source).unwrap()).unwrap();
        json["entities"].as_array_mut().unwrap().reverse();
        std::fs::write(&source, json.to_string()).unwrap();
        crate::runtime::cook_scene(&source, &cooked).unwrap();

        fn code(_: &mut GameScene<'_>, _: &FrameTime) {}
        let mut game = load_project_runtime(
            &cooked,
            TestGame {
                update: code,
                changed_health: false,
            },
        )
        .unwrap();
        let frame = game.world().resource::<FrameTime>().fixed_delta;
        let run = |game: &mut App| {
            for _ in 0..90 {
                game.update(frame).unwrap();
            }
            let world = game.world_mut();
            let hash = GameScene { world: &mut *world }.state_hash("box");
            let poses = (0..12)
                .map(|index| {
                    let entity =
                        find_named_entity(world, &format!("Box {index}"))
                            .unwrap();
                    let transform = world.get::<Transform>(entity).unwrap();
                    (transform.position, transform.rotation)
                })
                .collect::<Vec<_>>();
            (hash, poses)
        };
        let start = GameScene {
            world: game.world_mut(),
        }
        .state_hash("box");
        let first = run(&mut game);
        let mut scene = GameScene {
            world: game.world_mut(),
        };
        let initial = scene.initial("Box 11").unwrap();
        assert_eq!(
            initial.transform.position,
            [
                (11.0f32 * 0.37).sin() * 0.4,
                0.6 + 11.0 * 1.05,
                (11.0f32 * 0.61).cos() * 0.4
            ]
        );
        assert_eq!(initial.body_kind, Some(RigidBodyKind::Dynamic));
        assert!(initial.visible);
        assert_eq!(scene.initial("Nothing"), None);
        assert!(scene.restart());
        let second = run(&mut game);
        assert_ne!(first.0, start, "the pile moved");
        assert_eq!(first, second, "tolerance 0, and equal class hashes");

        // A snapshot taken mid-fall, with warm starts and some sleepers,
        // resumes exactly as the run that went on from it.
        for _ in 0..20 {
            game.update(frame).unwrap();
        }
        let snapshot = GameScene {
            world: game.world_mut(),
        }
        .snapshot()
        .unwrap();
        let went_on = run(&mut game);
        GameScene {
            world: game.world_mut(),
        }
        .restore(&snapshot)
        .unwrap();
        assert_eq!(run(&mut game), went_on, "restored run matches");
        std::fs::remove_dir_all(&directory).unwrap();
    }

    #[test]
    fn load_scene_switches_to_another_project_scene() {
        let directory = std::env::temp_dir()
            .join(format!("rusting-load-scene-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(directory.join("levels")).unwrap();
        std::fs::write(directory.join("project.json"), "{}").unwrap();
        let source = directory.join("main.rscene");
        let cooked = directory.join("build/main.rscene.bin");
        let mut editor = App::new();
        editor.add_plugin(AssetPlugin).unwrap();
        let ball = editor.spawn((Name("Ball".into()), Transform::default()));
        crate::runtime::save_scene(editor.world_mut(), &source, "main")
            .unwrap();
        crate::runtime::cook_scene(&source, &cooked).unwrap();
        editor.world_mut().despawn(ball);
        editor.spawn((Name("Door".into()), Transform::default()));
        crate::runtime::save_scene(
            editor.world_mut(),
            directory.join("levels/2.rscene"),
            "level 2",
        )
        .unwrap();

        // The first level loads the second at once; the second spawns a coin
        // once per round and restarts when the door has moved twice.
        fn code(scene: &mut GameScene<'_>, _: &FrameTime) {
            if scene.try_object("Ball").is_some() {
                assert!(scene.load_scene("levels/missing.rscene").is_err());
                assert!(scene.try_object("Ball").is_some(), "scene kept");
                scene.load_scene("levels/2.rscene").unwrap();
                return;
            }
            scene.once("setup", |scene| {
                scene.spawn_cube(
                    "Coin",
                    Transform::default(),
                    &CubeSpawn::new(),
                );
            });
            scene.object("Door").move_x(1.0);
            if scene.object("Door").position()[0] >= 2.0 {
                assert!(scene.restart());
            }
        }
        let frame = std::time::Duration::from_millis(16);
        let mut game = load_project_runtime(
            &cooked,
            TestGame {
                update: code,
                changed_health: false,
            },
        )
        .unwrap();
        game.update(frame).unwrap();
        let world = game.world_mut();
        assert_eq!(count_named(world, "Ball"), 0);
        assert_eq!(count_named(world, "Door"), 1);
        game.update(frame).unwrap();
        assert_eq!(count_named(game.world_mut(), "Coin"), 1);
        // Restarting returns to the second level, not the first.
        game.update(frame).unwrap();
        let world = game.world_mut();
        assert_eq!(count_named(world, "Ball"), 0);
        assert_eq!(count_named(world, "Coin"), 0);
        let door = find_named_entity(world, "Door").unwrap();
        assert_eq!(world.get::<Transform>(door).unwrap().position, [0.0; 3]);
        std::fs::remove_dir_all(&directory).unwrap();
    }

    #[test]
    fn named_game_object_moves_without_an_ecs_query_in_game_code() {
        let mut world = World::new();
        world.spawn((Name("Orange Cube".into()), Transform::default()));

        let mut scene = GameScene { world: &mut world };
        scene
            .object("Orange Cube")
            .move_x(2.0)
            .move_y(3.0)
            .move_z(4.0);

        assert_eq!(scene.object("Orange Cube").position(), [2.0, 3.0, 4.0]);
    }

    #[test]
    fn despawned_name_can_be_spawned_again() {
        let mut world = World::new();
        world.insert_resource(AssetServer::default());
        let mut scene = GameScene { world: &mut world };
        let first =
            scene.spawn_cube("Shot", Transform::default(), &CubeSpawn::new());
        scene.world.despawn(first);
        let second =
            scene.spawn_cube("Shot", Transform::default(), &CubeSpawn::new());
        assert_ne!(first, second);
    }

    #[test]
    fn game_randomness_repeats_for_a_seed_and_varies_by_tick_and_stream() {
        let draw = |seed: u64, tick: u64, stream: u64| {
            let mut world = World::new();
            world.insert_resource(crate::runtime::RandomSeed(seed));
            world.insert_resource(FrameTime {
                fixed_tick: tick,
                ..FrameTime::default()
            });
            GameScene { world: &mut world }.random(stream)
        };
        let value = draw(7, 3, 0);
        assert!((0.0..1.0).contains(&value));
        assert_eq!(value, draw(7, 3, 0));
        assert_ne!(value, draw(8, 3, 0));
        assert_ne!(value, draw(7, 4, 0));
        assert_ne!(value, draw(7, 3, 1));
        // A world without a seed or time still draws.
        let mut world = World::new();
        let _ = GameScene { world: &mut world }.random(0);
    }

    #[test]
    fn game_code_reads_and_sets_counters_by_name() {
        let mut world = World::new();
        world.spawn(crate::runtime::Counter {
            name: "gems".into(),
            value: 2,
            target: Some(5),
        });
        let mut scene = GameScene { world: &mut world };
        scene.counter("gems").unwrap().value += 3;
        assert!(scene.counter("gems").unwrap().complete());
        assert!(scene.counter("coins").is_none());
        // The shorthands read, add and check without a borrow held open.
        assert_eq!(scene.add_to_counter("gems", -1), 4);
        assert_eq!(scene.counter_value("gems"), 4);
        assert!(!scene.counter_complete("gems"));
        // Reading a missing counter is 0; writing one creates it.
        assert_eq!(scene.counter_value("coins"), 0);
        assert!(!scene.counter_complete("coins"));
        assert!(scene.counter("coins").is_none(), "reads create nothing");
        assert_eq!(scene.add_to_counter("coins", 1), 1);
        scene.set_counter("gems", 9);
        assert_eq!(scene.counter_value("gems"), 9);
        scene.set_counter("coins", 3);
        assert_eq!(scene.counter_value("coins"), 3);
        scene.set_counter("night", 2);
        assert_eq!(scene.counter_value("night"), 2);
        assert!(!scene.counter_complete("night"), "created with no target");
        assert!(MISSING_COUNTERS.lock().unwrap().contains("coins"));
    }

    #[test]
    fn game_code_recolors_one_object_without_touching_shared_materials() {
        let mut app = crate::App::new();
        app.add_plugin(crate::AssetPlugin).unwrap();
        let world = app.world_mut();
        let (mesh, material) = {
            let assets = world.resource::<AssetServer>();
            (assets.fallback_mesh, assets.fallback_material)
        };
        let renderer = MeshRenderer {
            mesh,
            material,
            cast_shadows: true,
            receive_shadows: true,
        };
        world.spawn((Name("A".into()), Transform::default(), renderer));
        world.spawn((Name("B".into()), Transform::default(), renderer));
        let count =
            |world: &World| world.resource::<AssetServer>().materials.len();
        let before = count(world);
        let mut scene = GameScene { world };
        let original = scene.color("A").unwrap();
        scene.set_color("A", [1.0, 0.0, 0.0, 1.0]);
        scene.set_emissive("A", [2.0, 0.0, 0.0]);
        assert_eq!(scene.color("A"), Some([1.0, 0.0, 0.0, 1.0]));
        assert_eq!(scene.color("B"), Some(original));
        assert_eq!(scene.color("Nowhere"), None);
        // Recoloring B the same way shares A's material.
        scene.set_color("B", [1.0, 0.0, 0.0, 1.0]);
        scene.set_emissive("B", [2.0, 0.0, 0.0]);
        let material = |scene: &mut GameScene<'_>, name| {
            let entity = find_named_entity(scene.world, name).unwrap();
            scene.world.get::<MeshRenderer>(entity).unwrap().material
        };
        assert_eq!(material(&mut scene, "A"), material(&mut scene, "B"));
        assert_eq!(count(scene.world), before + 2);
    }

    #[test]
    #[should_panic(expected = "did you mean `Crate`")]
    fn a_missing_object_name_panic_lists_the_nearest_names() {
        let mut world = World::new();
        world.spawn((Name("Crate".into()), Transform::new([0.0; 3])));
        world.spawn((Name("Ground".into()), Transform::new([0.0; 3])));
        GameScene { world: &mut world }.object("crate_");
    }

    #[test]
    fn game_code_reads_and_writes_tile_map_cells_by_world_position() {
        let mut world = World::new();
        world.spawn((
            Name("Level".into()),
            Transform::new([-2.0, 1.0, 0.0]),
            crate::runtime::TileMap {
                rows: vec!["#.o".into()],
                ..Default::default()
            },
        ));
        let mut scene = GameScene { world: &mut world };
        assert_eq!(scene.tile("Level", [-1.5, 0.5, 3.0]), Some('#'));
        assert_eq!(scene.tile("Level", [0.2, 0.9, 0.0]), Some('o'));
        assert_eq!(scene.tile("Level", [5.0, -4.0, 0.0]), Some('.'));
        assert_eq!(scene.tile("Level", [-2.5, 0.5, 0.0]), None);
        assert_eq!(scene.tile("Nowhere", [0.0; 3]), None);
        assert!(scene.set_tile("Level", [0.2, 0.9, 0.0], '*'));
        assert!(!scene.set_tile("Level", [0.2, 0.9, 0.0], '*'));
        assert!(scene.set_tile("Level", [-1.5, -0.5, 0.0], '#'));
        assert!(!scene.set_tile("Level", [-2.5, 0.5, 0.0], '#'));
        let map = world
            .query::<&crate::runtime::TileMap>()
            .single(&world)
            .unwrap();
        assert_eq!(map.rows, vec!["#.*", "#"]);
    }

    #[test]
    fn aim_hits_what_the_camera_faces_and_despawn_removes_it() {
        let mut app = App::new();
        let world = app.world_mut();
        let player = world
            .spawn((Name("Player".into()), Transform::new([0.0, 1.0, 0.0])))
            .id();
        let camera = world
            .spawn((
                Name("Camera".into()),
                // Turned 90 degrees left, so it faces -X.
                Transform::new([0.0, 0.5, 0.0]).with_rotation(
                    0.0,
                    std::f32::consts::FRAC_PI_2,
                    0.0,
                ),
                crate::runtime::Camera {
                    active: true,
                    ..Default::default()
                },
            ))
            .id();
        rusting_core::hierarchy::set_parent(world, camera, player).unwrap();
        for (name, x) in [("Left", -5.0), ("Right", 5.0)] {
            world.spawn((
                Name(name.into()),
                Transform::new([x, 1.5, 0.0]),
                crate::runtime::PhysicsBody::default(),
                crate::runtime::RigidBody {
                    kind: crate::runtime::RigidBodyKind::Fixed,
                    ..Default::default()
                },
                crate::runtime::Collider::default(),
            ));
        }
        let step = app.world().resource::<FrameTime>().fixed_delta;
        app.update(step).unwrap();
        let mut scene = GameScene {
            world: app.world_mut(),
        };
        let hit = scene.aim(20.0).expect("the camera faces Left");
        assert_eq!(hit.name, "Left");
        assert!((hit.point[0] + 4.5).abs() < 1e-3, "{hit:?}");
        assert!(scene.despawn("Left"));
        assert!(!scene.despawn("Left"));
        assert!(scene.try_object("Left").is_none());

        // Switching to a camera that faces +X aims at Right instead.
        let back = scene
            .world()
            .spawn((
                Name("Back Camera".into()),
                Transform::new([0.0, 1.5, 0.0]).with_rotation(
                    0.0,
                    -std::f32::consts::FRAC_PI_2,
                    0.0,
                ),
                crate::runtime::Camera::default(),
            ))
            .id();
        assert!(!scene.set_active_camera("Right"), "not a camera");
        assert!(scene.set_active_camera("Back Camera"));
        assert_eq!(scene.object("Back Camera").entity(), back);
        assert!(
            !scene
                .world()
                .get::<crate::runtime::Camera>(camera)
                .unwrap()
                .active
        );
        let hit = scene.aim(20.0).expect("the back camera faces Right");
        assert_eq!(
            scene.world().get::<Name>(back).unwrap().as_str(),
            "Back Camera"
        );
        assert_eq!(hit.name, "Right");
    }

    #[test]
    fn a_kinematic_template_copy_launches_along_the_camera_ray() {
        let mut app = App::new();
        let world = app.world_mut();
        world.spawn((
            Name("Camera".into()),
            // Turned 90 degrees left, so it faces -X.
            Transform::new([0.0, 2.0, 0.0]).with_rotation(
                0.0,
                std::f32::consts::FRAC_PI_2,
                0.0,
            ),
            crate::runtime::Camera {
                active: true,
                ..Default::default()
            },
        ));
        world.spawn((
            crate::runtime::SceneId::new(),
            Name("Ball".into()),
            Transform::new([0.0, -30.0, 0.0]),
            crate::runtime::PhysicsBody::default(),
            crate::runtime::RigidBody {
                kind: crate::runtime::RigidBodyKind::Kinematic,
                ..Default::default()
            },
            crate::runtime::Collider {
                shape: crate::runtime::ColliderShape::Sphere { radius: 0.2 },
                ..Default::default()
            },
        ));
        let step = app.world().resource::<FrameTime>().fixed_delta;
        let mut scene = GameScene {
            world: app.world_mut(),
        };
        let (origin, forward) = scene.camera_ray().unwrap();
        assert!((origin[1] - 2.0).abs() < 1e-5, "{origin:?}");
        assert!((forward[0] + 1.0).abs() < 1e-5, "{forward:?}");
        scene.spawn_copy("Ball", "Ball 1", origin);
        assert!(scene
            .set_body_kind("Ball 1", crate::runtime::RigidBodyKind::Dynamic));
        assert!(scene.set_linear_velocity("Ball 1", forward.map(|v| v * 10.0)));
        assert_eq!(
            scene.linear_velocity("Ball 1"),
            Some(forward.map(|v| v * 10.0))
        );
        assert_eq!(scene.linear_velocity("Nothing"), None);
        assert!(!scene
            .set_body_kind("Nothing", crate::runtime::RigidBodyKind::Dynamic));
        for _ in 0..30 {
            app.update(step).unwrap();
        }
        let mut scene = GameScene {
            world: app.world_mut(),
        };
        let ball = scene.object("Ball 1").position();
        assert!(ball[0] < -4.0 && ball[1] < 2.0, "flew and fell: {ball:?}");
        assert_eq!(scene.object("Ball").position(), [0.0, -30.0, 0.0]);
    }

    #[test]
    fn pointer_ray_goes_through_the_cursor() {
        let mut app = App::new();
        app.world_mut().spawn((
            Transform::new([0.0, 10.0, 0.0]).with_rotation(
                -std::f32::consts::FRAC_PI_2,
                0.0,
                0.0,
            ),
            crate::runtime::Camera {
                active: true,
                ..Default::default()
            },
        ));
        let mut scene = GameScene {
            world: app.world_mut(),
        };
        assert_eq!(scene.pointer_ray(), None, "no cursor yet");
        let mut input = scene.world.resource_mut::<RuntimeInput>();
        input.record_viewport_size([800.0, 600.0]);
        input.record_cursor_position([400.0, 300.0]);
        let (origin, down) = scene.pointer_ray().unwrap();
        assert!((origin[0].abs() + origin[2].abs()) < 1e-4, "{origin:?}");
        assert!((down[1] + 1.0).abs() < 1e-4, "{down:?}");
        scene
            .world
            .resource_mut::<RuntimeInput>()
            .record_cursor_position([800.0, 300.0]);
        let (_, right) = scene.pointer_ray().unwrap();
        assert!(right[0] > 0.1 && right[1] < 0.0, "{right:?}");
    }

    #[test]
    #[should_panic(expected = "`Copy/Glow` already exists")]
    fn spawn_copy_refuses_a_child_name_that_is_taken() {
        let mut app = App::new();
        let world = app.world_mut();
        let template = world.spawn(Name("Ember".into())).id();
        let glow = world.spawn(Name("Glow".into())).id();
        rusting_core::hierarchy::set_parent(world, glow, template).unwrap();
        world.spawn(Name("Copy/Glow".into()));
        let mut scene = GameScene {
            world: app.world_mut(),
        };
        scene.spawn_copy("Ember", "Copy", [0.0; 3]);
    }

    #[test]
    fn spawn_copy_clones_the_template_tree_and_in_class_lists_it() {
        let mut app = App::new();
        let world = app.world_mut();
        let arena = world
            .spawn((Name("Arena".into()), Transform::default()))
            .id();
        let template = world
            .spawn((
                crate::runtime::SceneId::new(),
                Name("Ember".into()),
                Transform::new([0.0, -50.0, 0.0]),
                crate::runtime::ObjectClasses {
                    names: vec!["ember".into()],
                },
                crate::runtime::PhysicsBody::default(),
                crate::runtime::Collider::default(),
                crate::runtime::Visibility { visible: false },
            ))
            .id();
        let glow = world
            .spawn((Name("Glow".into()), Transform::new([0.0, 1.0, 0.0])))
            .id();
        rusting_core::hierarchy::set_parent(world, glow, template).unwrap();
        rusting_core::hierarchy::set_parent(world, template, arena).unwrap();
        let mut scene = GameScene {
            world: app.world_mut(),
        };
        let copy = scene
            .spawn_copy("Ember", "Ember 1", [3.0, 0.5, 0.0])
            .unwrap();
        scene.set_visible("Ember 1", true);
        assert!(scene.spawn_copy("Missing", "Ember 2", [0.0; 3]).is_none());
        assert_eq!(scene.in_class("ember"), ["Ember", "Ember 1"]);
        assert_eq!(scene.name_of(copy).as_deref(), Some("Ember 1"));
        assert!(scene.has_class(copy, "ember"));
        assert!(!scene.has_class(glow, "ember"));
        assert!(scene.binding("jump").is_empty());
        scene.rebind("jump", &["Space", "PadSouth"]).unwrap();
        assert_eq!(scene.binding("jump"), ["Space", "PadSouth"]);
        assert_eq!(scene.object("Ember 1").position(), [3.0, 0.5, 0.0]);
        assert_eq!(scene.object("Ember").position(), [0.0, -50.0, 0.0]);
        let world = app.world();
        assert!(world.get::<crate::runtime::Collider>(copy).is_some());
        assert!(
            world
                .get::<crate::runtime::Visibility>(copy)
                .unwrap()
                .visible
        );
        assert!(
            !world
                .get::<crate::runtime::Visibility>(template)
                .unwrap()
                .visible
        );
        assert_ne!(
            world.get::<crate::runtime::SceneId>(copy),
            world.get::<crate::runtime::SceneId>(template)
        );
        assert_eq!(world.get::<crate::runtime::Parent>(copy).unwrap().0, arena);
        assert_eq!(
            world
                .get::<crate::runtime::Children>(arena)
                .unwrap()
                .0
                .len(),
            2
        );
        let children = &world.get::<crate::runtime::Children>(copy).unwrap().0;
        assert_eq!(children.len(), 1);
        assert_ne!(children[0], glow);
        assert_eq!(world.get::<Name>(children[0]).unwrap().0, "Ember 1/Glow");
        assert_eq!(
            world.get::<crate::runtime::Parent>(children[0]).unwrap().0,
            copy
        );
        assert_eq!(
            world.get::<crate::runtime::Children>(template).unwrap().0,
            [glow]
        );
        let child = children[0];
        let step = world.resource::<FrameTime>().fixed_delta;
        app.update(step).unwrap();
        let global = app
            .world()
            .get::<crate::runtime::GlobalTransform>(child)
            .expect("the copied child gets a world transform");
        assert_eq!(global.matrix[3][..3], [3.0, 1.5, 0.0]);
    }

    #[test]
    fn scene_input_actions_bind_and_report_presses() {
        let mut app = App::new();
        app.world_mut().spawn(crate::runtime::InputAction {
            action: "fire".into(),
            inputs: vec!["KeyF".into(), "MouseLeft".into()],
        });
        app.update(std::time::Duration::from_millis(16)).unwrap();
        app.world_mut()
            .resource_mut::<RuntimeInput>()
            .record_mouse_button(crate::runtime::MouseButton::Left, true);
        let scene = GameScene {
            world: app.world_mut(),
        };
        assert!(scene.pressed("fire") && scene.held("fire"));
        assert!(!scene.pressed("jump"));
        let bad = serde_json::from_str::<crate::runtime::InputAction>(
            r#"{"action": "fire", "inputs": ["KeyQQ"]}"#,
        );
        assert!(bad
            .unwrap_err()
            .to_string()
            .contains("unknown input `KeyQQ`"));
    }

    #[test]
    fn optional_object_lookup_handles_missing_names() {
        let mut world = World::new();
        let mut scene = GameScene { world: &mut world };
        assert!(scene.try_object("Missing").is_none());
    }

    #[test]
    fn concise_gpu_watch_registration_is_idempotent() {
        let mut app = App::new();
        app.add_plugin(HybridPhysicsPlugin).unwrap();
        let entity = app.spawn((
            Name("Cube".into()),
            Transform::default(),
            crate::runtime::PhysicsBody {
                simulation: crate::runtime::SimulationClass::Gpu,
                ..Default::default()
            },
        ));
        let rule = GpuPhysicsRule::new(
            "cube_fell",
            crate::runtime::GpuCondition::position_y().less_than(-100.0),
        );

        let mut scene = GameScene {
            world: app.world_mut(),
        };
        scene.watch_gpu_object("Cube", rule.clone());
        scene.watch_gpu_object("Cube", rule);

        assert_eq!(
            scene
                .world
                .get::<GpuPhysicsWatch>(entity)
                .unwrap()
                .rules
                .len(),
            1
        );
    }

    #[test]
    fn class_gpu_watch_registration_is_idempotent() {
        let mut app = App::new();
        app.add_plugin(HybridPhysicsPlugin).unwrap();
        let rule = GpuPhysicsRule::new(
            "body_fell",
            crate::runtime::GpuCondition::position_y().less_than(-100.0),
        );

        let mut scene = GameScene {
            world: app.world_mut(),
        };
        scene.watch_gpu_class("falling_cubes", rule.clone());
        scene.watch_gpu_class("falling_cubes", rule);

        assert_eq!(
            scene.world.resource::<GpuPhysicsClassWatches>().classes
                ["falling_cubes"]
                .len(),
            1
        );
    }

    #[test]
    fn concise_api_spawns_ten_thousand_gpu_cubes_only_once() {
        const BODY_COUNT: usize = 10_000;

        let mut app = App::new();
        app.add_plugin(AssetPlugin).unwrap();
        app.add_plugin(HybridPhysicsPlugin).unwrap();
        let mut scene = GameScene {
            world: app.world_mut(),
        };
        scene.once("spawn_test_cubes", |scene| {
            let cube = CubeSpawn::new().class("gravity").class("falling_cubes");
            for index in 0..BODY_COUNT {
                scene.spawn_cube(
                    format!("Physics Cube {index}"),
                    Transform::new([index as f32, 0.0, 0.0]),
                    &cube,
                );
            }
            assert_eq!(
                scene.apply_gpu_physics_to_class(
                    "gravity",
                    &GpuBodySettings::default(),
                ),
                BODY_COUNT
            );
        });
        scene.once("spawn_test_cubes", |_| {
            panic!("a completed once block ran twice")
        });

        let mut query = scene.world.query::<(
            &crate::runtime::ObjectClasses,
            &crate::runtime::PhysicsBody,
        )>();
        assert_eq!(query.iter(scene.world).count(), BODY_COUNT);
        assert!(query.iter(scene.world).all(|(classes, physics)| {
            classes.contains("falling_cubes") && physics.uses_gpu()
        }));
    }

    #[test]
    fn sphere_spawning_reuses_mesh_for_matching_subdivisions() {
        let mut app = App::new();
        app.add_plugin(AssetPlugin).unwrap();
        let mut scene = GameScene {
            world: app.world_mut(),
        };
        let sphere = SphereSpawn::new().subdivisions(8).class("gravity");
        let first = scene.spawn_sphere(
            "Sphere A",
            Transform::new([0.0, 1.0, 0.0]),
            &sphere,
        );
        let second = scene.spawn_sphere(
            "Sphere B",
            Transform::new([0.0, 2.0, 0.0]),
            &sphere,
        );
        let first_mesh = scene
            .world
            .get::<crate::runtime::MeshRenderer>(first)
            .unwrap()
            .mesh;
        let second_mesh = scene
            .world
            .get::<crate::runtime::MeshRenderer>(second)
            .unwrap()
            .mesh;
        assert_eq!(first_mesh, second_mesh);
        let mesh = scene
            .world
            .resource::<AssetServer>()
            .meshes
            .get(first_mesh)
            .unwrap();
        assert!(!mesh.vertices.is_empty());
        assert!(!mesh.indices.is_empty());
        assert!(scene
            .world
            .get::<crate::runtime::ObjectClasses>(first)
            .unwrap()
            .contains("gravity"));
    }
}