sim-logic 0.1.0

A code-first application and logic layer for Sim;Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
//! Atomic CPU extraction into bounded Sim;Engine visual state.

use crate::{
    assets::ImageAssetId,
    identity::{LogicEntity, WorldGeneration},
    render::RenderLimits,
    screen::{ImageVisualError, ScreenVisualError},
    three_d::{
        CuboidSource, MeshSource, ResolvedCuboid3d, ResolvedMesh3d, ThreeDExtractionBuffer,
        ThreeDExtractionError, ThreeDRenderLimits, ThreeDSnapshot, View3d,
    },
    visual::{
        ActiveCamera2d, CircleVisual, LineVisual, RectangleVisual, Transform2d, VisualValueError,
        line_stroke_style,
    },
};
use sim_engine::{
    Camera2d, Color, Layer, Rect, Scene, SceneBudgetResource, SceneError, ShapeStyle, Vec2,
};
use std::{cmp::Ordering, error::Error, fmt, mem::size_of};

#[path = "extraction/screen.rs"]
mod screen;
#[cfg(feature = "headless-text")]
pub use screen::ResolvedScreenText;
use screen::ScreenExtractionBuffer;
#[cfg(feature = "headless-text")]
pub(crate) use screen::ScreenTextSource;
pub use screen::{
    ResolvedScreenImage, ResolvedScreenPrimitive, ResolvedScreenRectangle, ScreenDraw,
    ScreenExtractionUpdates,
};
pub(crate) use screen::{ScreenImageSource, ScreenRectangleSource, ScreenSource};

/// One fully resolved circle retained for headless parity and diagnostics.
///
/// Records preserve their relative order from the single deterministic mixed
/// Sim;Engine scene. The interpolated position is presentation state and is
/// never written back to the ECS World.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ResolvedCircle {
    source: LogicEntity,
    position: Vec2,
    radius: f32,
    color: Color,
    layer: Layer,
    draw_order_depth: f32,
}

/// One fully resolved rectangle retained for headless parity and diagnostics.
///
/// Records preserve their relative order from the single deterministic mixed
/// Sim;Engine scene. Position is the interpolated world-space center; size and
/// style are sampled directly from the canonical component.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ResolvedRectangle {
    source: LogicEntity,
    position: Vec2,
    size: Vec2,
    corner_radius: f32,
    color: Color,
    layer: Layer,
    draw_order_depth: f32,
}

/// One fully resolved anchored line retained for headless parity and diagnostics.
///
/// `from` and `to` are presentation-space world points after Transform
/// interpolation. Vector and style are sampled from the current component and
/// never written back to the ECS World.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ResolvedLine {
    source: LogicEntity,
    from: Vec2,
    to: Vec2,
    stroke_width_logical_pixels: f32,
    color: Color,
    layer: Layer,
    draw_order_depth: f32,
}

impl ResolvedLine {
    /// Returns the managed entity that produced this visual.
    pub const fn source(self) -> LogicEntity {
        self.source
    }

    /// Returns the interpolated anchor in world coordinates.
    pub const fn from(self) -> Vec2 {
        self.from
    }

    /// Returns the resolved endpoint in world coordinates.
    pub const fn to(self) -> Vec2 {
        self.to
    }

    /// Returns stroke width in logical screen pixels.
    pub const fn stroke_width_logical_pixels(self) -> f32 {
        self.stroke_width_logical_pixels
    }

    /// Returns the normalized straight-linear RGBA stroke color.
    pub const fn color(self) -> Color {
        self.color
    }

    /// Returns the primary Sim;Engine draw layer.
    pub const fn layer(self) -> Layer {
        self.layer
    }

    /// Returns the within-layer ordering value used by Sim;Logic.
    ///
    /// This is not Sim;Engine projection depth.
    pub const fn draw_order_depth(self) -> f32 {
        self.draw_order_depth
    }
}

impl ResolvedRectangle {
    /// Returns the managed entity that produced this visual.
    pub const fn source(self) -> LogicEntity {
        self.source
    }

    /// Returns the interpolated world-space center.
    pub const fn position(self) -> Vec2 {
        self.position
    }

    /// Returns the full width and height in caller-defined world units.
    pub const fn size(self) -> Vec2 {
        self.size
    }

    /// Returns the requested corner radius before renderer-side clamping.
    pub const fn corner_radius(self) -> f32 {
        self.corner_radius
    }

    /// Returns the normalized straight-linear RGBA fill color.
    pub const fn color(self) -> Color {
        self.color
    }

    /// Returns the primary Sim;Engine draw layer.
    pub const fn layer(self) -> Layer {
        self.layer
    }

    /// Returns the within-layer ordering value used by Sim;Logic.
    ///
    /// This is not Sim;Engine projection depth.
    pub const fn draw_order_depth(self) -> f32 {
        self.draw_order_depth
    }
}

impl ResolvedCircle {
    /// Returns the managed entity that produced this visual.
    pub const fn source(self) -> LogicEntity {
        self.source
    }

    /// Returns the interpolated world-space center.
    pub const fn position(self) -> Vec2 {
        self.position
    }

    /// Returns the circle radius in caller-defined world units.
    pub const fn radius(self) -> f32 {
        self.radius
    }

    /// Returns the normalized straight-linear RGBA fill color.
    pub const fn color(self) -> Color {
        self.color
    }

    /// Returns the primary Sim;Engine draw layer.
    pub const fn layer(self) -> Layer {
        self.layer
    }

    /// Returns the within-layer ordering value used by Sim;Logic.
    ///
    /// This is not Sim;Engine projection depth.
    pub const fn draw_order_depth(self) -> f32 {
        self.draw_order_depth
    }
}

/// Complete renderer-independent visual snapshot for one World generation.
///
/// A snapshot is published only after every required visual and its CPU/Scene
/// limits have been validated. The desktop bridge must compare
/// [`ExtractedFrame::world_generation`] with the active World immediately
/// before submission so a retired generation is never rendered.
pub struct ExtractedFrame {
    world_generation: WorldGeneration,
    background: Color,
    camera: Camera2d,
    storage: ExtractionBuffer,
}

struct ExtractionBuffer {
    resolved_circles: Vec<ResolvedCircle>,
    resolved_rectangles: Vec<ResolvedRectangle>,
    resolved_lines: Vec<ResolvedLine>,
    #[cfg_attr(
        not(feature = "desktop"),
        allow(dead_code, reason = "the headless build retains CPU parity data only")
    )]
    world_scene: Scene,
    screen: ScreenExtractionBuffer,
    three_d: ThreeDExtractionBuffer,
}

#[derive(Debug, Clone, Copy)]
struct ExtractedMetadata {
    world_generation: WorldGeneration,
    background: Color,
    camera: Camera2d,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct ExtractionParameters {
    world_generation: WorldGeneration,
    background: Color,
    alpha: f32,
    limits: RenderLimits,
}

/// Application-owned published/work storage for atomic CPU extraction.
pub(crate) struct ExtractionBuffers {
    published: Option<ExtractedFrame>,
    spare: Option<ExtractionBuffer>,
    staged: Option<ExtractedMetadata>,
}

impl ExtractedFrame {
    /// CPU screen work for this snapshot, independent of native GPU preparation.
    /// Complete-frame publication uses two alternating buffers; each warms its
    /// own exact-value cache. World geometry/interpolation are not cached here.
    pub const fn screen_extraction_updates(&self) -> ScreenExtractionUpdates {
        self.storage.screen.updates
    }
    /// Returns the World generation from which this snapshot was extracted.
    pub const fn world_generation(&self) -> WorldGeneration {
        self.world_generation
    }

    /// Returns the normalized clear color for the composed frame.
    pub const fn background(&self) -> Color {
        self.background
    }

    /// Returns the validated, interpolated presentation camera for this frame.
    ///
    /// This may differ from the active component's canonical camera during a
    /// partial fixed interval.
    pub const fn camera(&self) -> Camera2d {
        self.camera
    }

    /// Returns value-comparable circles in their relative mixed-scene order.
    pub fn resolved_circles(&self) -> &[ResolvedCircle] {
        &self.storage.resolved_circles
    }

    /// Returns value-comparable rectangles in their relative mixed-scene order.
    pub fn resolved_rectangles(&self) -> &[ResolvedRectangle] {
        &self.storage.resolved_rectangles
    }

    /// Returns nonzero lines in their relative mixed-scene order.
    pub fn resolved_lines(&self) -> &[ResolvedLine] {
        &self.storage.resolved_lines
    }

    /// Returns screen rectangles in their deterministic screen-layer order.
    ///
    /// Positions and sizes are current logical pixels, not interpolated world
    /// coordinates. All these records are composed above the world scene.
    pub fn resolved_screen_rectangles(&self) -> &[ResolvedScreenRectangle] {
        self.storage.screen.resolved()
    }

    /// Iterates over sorted screen rectangles, lines, circles and paths without allocating.
    /// Path clones share their immutable CPU points.
    /// Values are current FrameUpdate presentation, independent of fixed interpolation.
    pub fn screen_primitives(&self) -> impl Iterator<Item = ResolvedScreenPrimitive> + '_ {
        self.storage.screen.primitive_records()
    }

    /// Returns current screen images in their relative mixed-screen order.
    ///
    /// Records contain immutable asset IDs, not GPU resources. Use
    /// `HeadlessRunner::image_asset` to inspect the registered source pixels.
    pub fn resolved_screen_images(&self) -> &[ResolvedScreenImage] {
        self.storage.screen.images()
    }

    /// Returns current prepared labels in their relative mixed-screen order.
    ///
    /// Strings, metrics, and fonts share their component's immutable CPU
    /// preparation. No shaping, GPU allocation, or fixed interpolation occurs.
    #[cfg(feature = "headless-text")]
    pub fn resolved_screen_texts(&self) -> &[ResolvedScreenText] {
        self.storage.screen.texts()
    }

    /// Returns the enabled 3D view and cuboids, or None when 3D is suppressed.
    ///
    /// Desktop composition places this opaque depth target above the 2D world
    /// and below all screen draws. The snapshot contains no GPU resources.
    pub fn three_d(&self) -> Option<ThreeDSnapshot<'_>> {
        self.storage.three_d.snapshot()
    }

    /// Returns current visible cuboids in stable managed-identity order.
    ///
    /// Missing or disabled View3d resources produce an empty slice.
    pub fn resolved_cuboids(&self) -> &[ResolvedCuboid3d] {
        self.storage.three_d.resolved()
    }

    /// Returns current visible custom meshes in stable managed-identity order.
    /// Missing or disabled View3d resources produce an empty slice.
    pub fn resolved_meshes(&self) -> &[ResolvedMesh3d] {
        self.storage
            .three_d
            .snapshot()
            .map_or(&[], |snapshot| snapshot.meshes())
    }

    /// Returns the exact screen composition after the world scene.
    ///
    /// Contiguous primitive runs, images, and optional text share layer, depth,
    /// and stable source order. Exact same-source ties put rectangles first,
    /// then lines, circles, paths, images, and text. Empty screen content produces no
    /// items. This plan does not replace desktop aggregate budget checks.
    pub fn screen_draws(&self) -> &[ScreenDraw] {
        self.storage.screen.draws()
    }

    /// Inspects one `ScreenDraw::Primitives` or `ScreenDraw::Rectangles` run.
    /// Returns no iterator for an absent run; records borrow this snapshot and
    /// retain exactly the order submitted to Engine, without allocation.
    pub fn screen_primitive_run_records(
        &self,
        run: usize,
    ) -> Option<impl Iterator<Item = ResolvedScreenPrimitive> + '_> {
        self.storage.screen.primitive_run_records(run)
    }

    /// Returns just the rectangle records for one run in `screen_draws`.
    /// A vector-only run returns an empty slice; an absent run returns None.
    pub fn screen_rectangle_run_records(&self, run: usize) -> Option<&[ResolvedScreenRectangle]> {
        self.storage.screen.run_records(run)
    }

    #[cfg(feature = "desktop")]
    pub(crate) fn screen_rectangle_run(&self, run: usize) -> Option<&sim_engine::ScreenScene> {
        self.storage.screen.run_scene(run)
    }

    /// Returns the camera-independent scene for the optional desktop bridge.
    #[cfg(feature = "desktop")]
    pub(crate) fn screen_scene(&self) -> &sim_engine::ScreenScene {
        self.storage.screen.scene()
    }

    /// Returns the bounded world scene used by the desktop bridge.
    #[cfg_attr(
        not(feature = "desktop"),
        allow(dead_code, reason = "used by the optional desktop bridge")
    )]
    pub(crate) const fn world_scene(&self) -> &Scene {
        &self.storage.world_scene
    }
}

impl ExtractionBuffer {
    fn new(limits: RenderLimits) -> Result<Self, ExtractionError> {
        let world_scene = Scene::with_budget(Color::BLACK, limits.world_scene_budget())
            .map_err(ExtractionError::Scene)?;
        Ok(Self {
            resolved_circles: Vec::new(),
            resolved_rectangles: Vec::new(),
            resolved_lines: Vec::new(),
            world_scene,
            screen: ScreenExtractionBuffer::new(limits)?,
            three_d: ThreeDExtractionBuffer::new(),
        })
    }
}

impl ExtractedMetadata {
    fn with_storage(self, storage: ExtractionBuffer) -> ExtractedFrame {
        ExtractedFrame {
            world_generation: self.world_generation,
            background: self.background,
            camera: self.camera,
            storage,
        }
    }
}

impl ExtractionParameters {
    pub(crate) const fn new(
        world_generation: WorldGeneration,
        background: Color,
        alpha: f32,
        limits: RenderLimits,
    ) -> Self {
        Self {
            world_generation,
            background,
            alpha,
            limits,
        }
    }
}

impl ExtractionBuffers {
    pub(crate) const fn new() -> Self {
        Self {
            published: None,
            spare: None,
            staged: None,
        }
    }

    /// Invalidates metadata from an abandoned candidate before more fallible work.
    pub(crate) fn discard_staged(&mut self) {
        self.staged = None;
    }

    pub(crate) fn stage(
        &mut self,
        parameters: ExtractionParameters,
        cameras: impl IntoIterator<Item = ActiveCamera2d>,
        circles: impl IntoIterator<Item = CircleSource>,
        rectangles: impl IntoIterator<Item = RectangleSource>,
        lines: impl IntoIterator<Item = LineSource>,
        screen_rectangles: impl IntoIterator<Item = ScreenSource>,
    ) -> Result<(), ExtractionError> {
        self.staged = None;
        let mut spare = match self.spare.take() {
            Some(spare) => spare,
            None => ExtractionBuffer::new(parameters.limits)?,
        };
        let result = extract_frame_into(
            &mut spare,
            parameters,
            cameras,
            circles,
            rectangles,
            lines,
            screen_rectangles,
        );
        self.spare = Some(spare);
        let metadata = result?;
        self.staged = Some(metadata);
        Ok(())
    }

    #[cfg(test)]
    fn stage_world_only(
        &mut self,
        parameters: ExtractionParameters,
        cameras: impl IntoIterator<Item = ActiveCamera2d>,
        circles: impl IntoIterator<Item = CircleSource>,
        rectangles: impl IntoIterator<Item = RectangleSource>,
        lines: impl IntoIterator<Item = LineSource>,
    ) -> Result<(), ExtractionError> {
        self.stage(parameters, cameras, circles, rectangles, lines, [])
    }

    pub(crate) fn stage_three_d(
        &mut self,
        generation: WorldGeneration,
        limits: ThreeDRenderLimits,
        view: Option<View3d>,
        sources: impl IntoIterator<Item = CuboidSource>,
        meshes: impl IntoIterator<Item = MeshSource>,
    ) -> Result<(), ExtractionError> {
        let Some(metadata) = self.staged.take() else {
            return Err(ExtractionError::MissingStagedFrame);
        };
        let Some(spare) = self.spare.as_mut() else {
            return Err(ExtractionError::MissingStagedFrame);
        };
        spare
            .three_d
            .extract(generation, limits, view, sources)
            .map_err(ExtractionError::ThreeD)?;
        spare
            .three_d
            .extract_meshes(generation, limits, meshes)
            .map_err(ExtractionError::ThreeD)?;
        self.staged = Some(metadata);
        Ok(())
    }

    /// Publishes the complete staged buffer and recycles the previous one.
    pub(crate) fn publish(&mut self) -> Option<WorldGeneration> {
        let metadata = self.staged.take()?;
        let Some(storage) = self.spare.take() else {
            self.staged = Some(metadata);
            return None;
        };
        let generation = metadata.world_generation;
        let previous = self.published.replace(metadata.with_storage(storage));
        self.spare = previous.map(|frame| frame.storage);
        Some(generation)
    }

    pub(crate) const fn published(&self) -> Option<&ExtractedFrame> {
        self.published.as_ref()
    }
}

/// Structured reason why a new CPU visual snapshot was not published.
#[derive(Debug)]
#[non_exhaustive]
pub enum ExtractionError {
    /// A screen line/circle/path source count exceeded its explicit per-kind limit.
    ScreenPrimitiveLimitExceeded {
        /// First source that exceeded the limit.
        entity: LogicEntity,
        /// Configured maximum for this primitive kind.
        limit: usize,
    },
    /// Enabled path points exceeded their aggregate CPU limit, including hidden clips.
    ScreenPolylinePointsLimitExceeded {
        /// Path that would exceed the limit.
        entity: LogicEntity,
        /// Configured aggregate path-point limit.
        limit: usize,
        /// Requested total, or usize::MAX on arithmetic overflow.
        requested: usize,
    },
    /// A private staged snapshot was unavailable for completing 3D extraction.
    MissingStagedFrame,
    /// Independent bounded 3D snapshot preparation failed.
    ThreeD(ThreeDExtractionError),
    /// The active World did not contain a camera marked for extraction.
    MissingActiveCamera,
    /// The active World contained more than one marked camera.
    MultipleActiveCameras,
    /// Interpolation alpha was non-finite or outside the inclusive `0.0..=1.0` range.
    InvalidInterpolationAlpha {
        /// Rejected accumulator fraction.
        alpha: f32,
    },
    /// A visual entity did not belong to the generation being extracted.
    ForeignEntity {
        /// Entity that carried stale or foreign provenance.
        entity: LogicEntity,
        /// Generation accepted by this extraction.
        expected: WorldGeneration,
    },
    /// A component contained a value outside its public visual contract.
    InvalidVisual {
        /// Entity whose visual data was rejected.
        entity: LogicEntity,
        /// Exact invalid value category.
        error: VisualValueError,
    },
    /// Interpolation of two finite translations did not produce a finite result.
    InvalidInterpolatedTranslation {
        /// Entity whose interpolation failed.
        entity: LogicEntity,
    },
    /// A finite center and size produced collapsed or non-finite f32 bounds.
    InvalidResolvedRectangle {
        /// Entity whose derived bounds were not representable.
        entity: LogicEntity,
    },
    /// An interpolated anchor and finite vector did not form a representable segment.
    InvalidResolvedLine {
        /// Entity whose resolved segment was rejected.
        entity: LogicEntity,
    },
    /// The configured extracted-circle count was exceeded.
    CircleLimitExceeded {
        /// Configured maximum resolved circle count.
        limit: usize,
    },
    /// The configured extracted-rectangle count was exceeded.
    RectangleLimitExceeded {
        /// Configured maximum resolved rectangle count.
        limit: usize,
    },
    /// The configured enabled line-source count was exceeded.
    LineLimitExceeded {
        /// Configured maximum line-source count.
        limit: usize,
    },
    /// The configured enabled screen-rectangle count was exceeded.
    ScreenRectangleLimitExceeded {
        /// Maximum number of screen rectangles accepted in one extraction.
        limit: usize,
    },
    /// The opted-in enabled screen-image source count was exceeded.
    ScreenImageLimitExceeded {
        /// Configured image source limit (zero by default).
        limit: usize,
    },
    /// The opted-in enabled screen-text source count was exceeded.
    #[cfg(feature = "headless-text")]
    ScreenTextLimitExceeded {
        /// Configured label count limit, zero by default.
        limit: usize,
    },
    /// Aggregate enabled label strings exceed the UTF-8 byte allowance.
    #[cfg(feature = "headless-text")]
    ScreenTextBytesLimitExceeded {
        /// Configured inclusive UTF-8 byte limit.
        limit: usize,
        /// Requested aggregate bytes; usize::MAX also represents overflow.
        requested: usize,
    },
    /// Aggregate enabled labels exceed the shaped-glyph allowance.
    #[cfg(feature = "headless-text")]
    ScreenTextGlyphLimitExceeded {
        /// Configured inclusive shaped-glyph count limit.
        limit: usize,
        /// Requested aggregate glyphs; usize::MAX also represents overflow.
        requested: usize,
    },
    /// A label uses a font not registered by this Application.
    #[cfg(feature = "headless-text")]
    UnregisteredTextFont {
        /// Managed source of the foreign or unavailable font.
        entity: LogicEntity,
        /// Shared immutable font whose Application provenance was rejected.
        font: crate::text::TextFont,
    },
    /// A label violated its prepared-text, position, or tint contract.
    #[cfg(feature = "headless-text")]
    InvalidScreenText {
        /// Managed source whose text visual was rejected.
        entity: LogicEntity,
        /// Exact component validation failure.
        error: crate::text::TextError,
    },
    /// An image handle was not registered by this Application.
    UnregisteredImageAsset {
        /// Managed source of the invalid reference.
        entity: LogicEntity,
        /// Rejected immutable image handle.
        image: ImageAssetId,
    },
    /// An image component violated its geometry, tint, or source-region contract.
    InvalidScreenImage {
        /// Managed source whose visual was rejected.
        entity: LogicEntity,
        /// Exact component validation failure.
        error: ImageVisualError,
    },
    /// A screen visual violated its validated logical-pixel contract.
    InvalidScreenVisual {
        /// Managed entity whose screen visual was rejected.
        entity: LogicEntity,
        /// Exact invalid value category.
        error: ScreenVisualError,
    },
    /// CPU storage for a bounded fixed-size resolved record could not be reserved.
    AllocationFailed {
        /// Minimum bytes requested for the next fixed-size record.
        requested_bytes: usize,
    },
    /// Sim;Engine rejected bounded scene construction.
    Scene(SceneError),
    /// Sim;Engine rejected bounded screen-scene construction.
    ScreenScene(SceneError),
}

impl fmt::Display for ExtractionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingStagedFrame => formatter.write_str("no staged CPU frame is available"),
            Self::ThreeD(error) => write!(formatter, "3D extraction failed: {error}"),
            Self::MissingActiveCamera => formatter.write_str("active World has no 2D camera"),
            Self::MultipleActiveCameras => {
                formatter.write_str("active World has more than one 2D camera")
            }
            Self::InvalidInterpolationAlpha { alpha } => write!(
                formatter,
                "interpolation alpha must be finite and within 0..=1, got {alpha}"
            ),
            Self::ForeignEntity { entity, expected } => write!(
                formatter,
                "visual entity {entity:?} does not belong to World generation {expected:?}"
            ),
            Self::InvalidVisual { entity, error } => {
                write!(formatter, "visual entity {entity:?} is invalid: {error}")
            }
            Self::InvalidInterpolatedTranslation { entity } => write!(
                formatter,
                "visual entity {entity:?} produced a non-finite interpolated translation"
            ),
            Self::InvalidResolvedRectangle { entity } => write!(
                formatter,
                "visual entity {entity:?} produced collapsed or non-finite rectangle bounds"
            ),
            Self::InvalidResolvedLine { entity } => write!(
                formatter,
                "visual entity {entity:?} produced a collapsed or non-finite line"
            ),
            Self::CircleLimitExceeded { limit } => {
                write!(
                    formatter,
                    "extracted circle count exceeds the limit of {limit}"
                )
            }
            Self::RectangleLimitExceeded { limit } => write!(
                formatter,
                "extracted rectangle count exceeds the limit of {limit}"
            ),
            Self::LineLimitExceeded { limit } => write!(
                formatter,
                "enabled line-source count exceeds the limit of {limit}"
            ),
            Self::ScreenRectangleLimitExceeded { limit } => write!(
                formatter,
                "extracted screen rectangle count exceeds the limit of {limit}"
            ),
            Self::ScreenPolylinePointsLimitExceeded {
                entity,
                limit,
                requested,
            } => write!(
                formatter,
                "screen path {entity:?} exceeds point limit {limit}, requested {requested}"
            ),
            Self::ScreenPrimitiveLimitExceeded { entity, limit } => write!(
                formatter,
                "screen primitive {entity:?} exceeds its source limit {limit}"
            ),
            Self::ScreenImageLimitExceeded { limit } => write!(
                formatter,
                "extracted screen image count exceeds the limit of {limit}"
            ),
            #[cfg(feature = "headless-text")]
            Self::ScreenTextLimitExceeded { limit } => write!(
                formatter,
                "extracted screen text count exceeds the limit of {limit}"
            ),
            #[cfg(feature = "headless-text")]
            Self::ScreenTextBytesLimitExceeded { limit, requested } => write!(
                formatter,
                "screen text requests {requested} UTF-8 bytes, exceeding {limit}"
            ),
            #[cfg(feature = "headless-text")]
            Self::ScreenTextGlyphLimitExceeded { limit, requested } => write!(
                formatter,
                "screen text requests {requested} shaped glyphs, exceeding {limit}"
            ),
            #[cfg(feature = "headless-text")]
            Self::UnregisteredTextFont { entity, font } => write!(
                formatter,
                "screen text entity {entity:?} references unregistered font {font:?}"
            ),
            #[cfg(feature = "headless-text")]
            Self::InvalidScreenText { entity, error } => write!(
                formatter,
                "screen text entity {entity:?} is invalid: {error}"
            ),
            Self::UnregisteredImageAsset { entity, image } => write!(
                formatter,
                "screen image entity {entity:?} references unregistered image {image:?}"
            ),
            Self::InvalidScreenImage { entity, error } => write!(
                formatter,
                "screen image entity {entity:?} is invalid: {error}"
            ),
            Self::InvalidScreenVisual { entity, error } => write!(
                formatter,
                "screen visual entity {entity:?} is invalid: {error}"
            ),
            Self::AllocationFailed { requested_bytes } => write!(
                formatter,
                "failed to reserve {requested_bytes} bytes for an extracted visual record"
            ),
            Self::Scene(error) => write!(formatter, "Sim;Engine scene extraction failed: {error}"),
            Self::ScreenScene(error) => {
                write!(formatter, "Sim;Engine screen extraction failed: {error}")
            }
        }
    }
}

impl Error for ExtractionError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::ThreeD(error) => Some(error),
            Self::InvalidVisual { error, .. } => Some(error),
            Self::Scene(error) => Some(error),
            Self::ScreenScene(error) => Some(error),
            Self::InvalidScreenVisual { error, .. } => Some(error),
            Self::InvalidScreenImage { error, .. } => Some(error),
            #[cfg(feature = "headless-text")]
            Self::InvalidScreenText { error, .. } => Some(error),
            _ => None,
        }
    }
}

/// Copied ECS values consumed by the bounded extractor.
///
/// Keeping this adapter record private prevents raw Bevy identity from
/// becoming public render API while allowing the ECS query to feed extraction
/// without first allocating an unbounded intermediate collection.
#[derive(Debug, Clone, Copy)]
pub(crate) struct CircleSource {
    entity: LogicEntity,
    previous_translation: Vec2,
    current_translation: Vec2,
    radius: f32,
    color: Color,
    layer: Layer,
    draw_order_depth: f32,
}

/// Copied rectangle values consumed by the bounded extractor.
#[derive(Debug, Clone, Copy)]
pub(crate) struct RectangleSource {
    entity: LogicEntity,
    previous_translation: Vec2,
    current_translation: Vec2,
    size: Vec2,
    corner_radius: f32,
    color: Color,
    layer: Layer,
    draw_order_depth: f32,
}

/// Copied anchored-line values consumed by the bounded extractor.
#[derive(Debug, Clone, Copy)]
pub(crate) struct LineSource {
    entity: LogicEntity,
    previous_translation: Vec2,
    current_translation: Vec2,
    vector: Vec2,
    stroke_width_logical_pixels: f32,
    color: Color,
    layer: Layer,
    draw_order_depth: f32,
}

impl LineSource {
    pub(crate) fn new(entity: LogicEntity, transform: &Transform2d, visual: &LineVisual) -> Self {
        Self {
            entity,
            previous_translation: transform.previous_translation(),
            current_translation: transform.translation(),
            vector: visual.vector(),
            stroke_width_logical_pixels: visual.stroke_width_logical_pixels(),
            color: visual.color(),
            layer: visual.layer(),
            draw_order_depth: visual.draw_order_depth(),
        }
    }
}

impl RectangleSource {
    pub(crate) fn new(
        entity: LogicEntity,
        transform: &Transform2d,
        visual: &RectangleVisual,
    ) -> Self {
        Self {
            entity,
            previous_translation: transform.previous_translation(),
            current_translation: transform.translation(),
            size: visual.size(),
            corner_radius: visual.corner_radius(),
            color: visual.color(),
            layer: visual.layer(),
            draw_order_depth: visual.draw_order_depth(),
        }
    }
}

impl CircleSource {
    pub(crate) fn new(entity: LogicEntity, transform: &Transform2d, visual: &CircleVisual) -> Self {
        Self {
            entity,
            previous_translation: transform.previous_translation(),
            current_translation: transform.translation(),
            radius: visual.radius(),
            color: visual.color(),
            layer: visual.layer(),
            draw_order_depth: visual.draw_order_depth(),
        }
    }
}

/// Builds one complete bounded CPU visual snapshot for focused extractor tests.
#[cfg(test)]
pub(crate) fn extract_frame(
    parameters: ExtractionParameters,
    cameras: impl IntoIterator<Item = ActiveCamera2d>,
    circles: impl IntoIterator<Item = CircleSource>,
    rectangles: impl IntoIterator<Item = RectangleSource>,
    lines: impl IntoIterator<Item = LineSource>,
) -> Result<ExtractedFrame, ExtractionError> {
    let mut storage = ExtractionBuffer::new(parameters.limits)?;
    let metadata = extract_frame_into(
        &mut storage,
        parameters,
        cameras,
        circles,
        rectangles,
        lines,
        [],
    )?;
    Ok(metadata.with_storage(storage))
}

fn extract_frame_into(
    storage: &mut ExtractionBuffer,
    parameters: ExtractionParameters,
    cameras: impl IntoIterator<Item = ActiveCamera2d>,
    circles: impl IntoIterator<Item = CircleSource>,
    rectangles: impl IntoIterator<Item = RectangleSource>,
    lines: impl IntoIterator<Item = LineSource>,
    screen_rectangles: impl IntoIterator<Item = ScreenSource>,
) -> Result<ExtractedMetadata, ExtractionError> {
    let ExtractionParameters {
        world_generation,
        background,
        alpha,
        limits,
    } = parameters;
    debug_assert_eq!(
        storage.world_scene.budget(),
        Some(limits.world_scene_budget()),
        "an extraction buffer cannot cross a frozen render-limit boundary"
    );
    storage.resolved_circles.clear();
    storage.resolved_rectangles.clear();
    storage.resolved_lines.clear();
    storage.world_scene.clear();
    storage.three_d.clear();

    if !alpha.is_finite() || !(0.0..=1.0).contains(&alpha) {
        return Err(ExtractionError::InvalidInterpolationAlpha { alpha });
    }

    let mut cameras = cameras.into_iter();
    let camera = cameras.next().ok_or(ExtractionError::MissingActiveCamera)?;
    if cameras.next().is_some() {
        return Err(ExtractionError::MultipleActiveCameras);
    }
    let camera = camera.interpolated_camera(alpha);

    for source in circles {
        if source.entity.world_generation() != world_generation {
            return Err(ExtractionError::ForeignEntity {
                entity: source.entity,
                expected: world_generation,
            });
        }
        if storage.resolved_circles.len() == limits.max_world_circles() {
            return Err(ExtractionError::CircleLimitExceeded {
                limit: limits.max_world_circles(),
            });
        }
        validate_aggregate_command_capacity(storage.resolved_circles.len(), limits)?;

        validate_source(source)?;
        let position = source
            .previous_translation
            .lerp(source.current_translation, alpha);
        if !position.is_finite() {
            return Err(ExtractionError::InvalidInterpolatedTranslation {
                entity: source.entity,
            });
        }

        storage
            .resolved_circles
            .try_reserve(1)
            .map_err(|_| ExtractionError::AllocationFailed {
                requested_bytes: size_of::<ResolvedCircle>(),
            })?;
        storage.resolved_circles.push(ResolvedCircle {
            source: source.entity,
            position,
            radius: source.radius,
            color: source.color,
            layer: source.layer,
            draw_order_depth: source.draw_order_depth,
        });
    }

    for source in rectangles {
        if source.entity.world_generation() != world_generation {
            return Err(ExtractionError::ForeignEntity {
                entity: source.entity,
                expected: world_generation,
            });
        }
        if storage.resolved_rectangles.len() == limits.max_world_rectangles() {
            return Err(ExtractionError::RectangleLimitExceeded {
                limit: limits.max_world_rectangles(),
            });
        }
        validate_aggregate_command_capacity(
            storage
                .resolved_circles
                .len()
                .saturating_add(storage.resolved_rectangles.len()),
            limits,
        )?;

        validate_rectangle_source(source)?;
        let position = source
            .previous_translation
            .lerp(source.current_translation, alpha);
        if !position.is_finite() {
            return Err(ExtractionError::InvalidInterpolatedTranslation {
                entity: source.entity,
            });
        }
        let bounds = Rect::from_center_size(position, source.size);
        if !rectangle_bounds_are_representable(bounds) {
            return Err(ExtractionError::InvalidResolvedRectangle {
                entity: source.entity,
            });
        }

        storage.resolved_rectangles.try_reserve(1).map_err(|_| {
            ExtractionError::AllocationFailed {
                requested_bytes: size_of::<ResolvedRectangle>(),
            }
        })?;
        storage.resolved_rectangles.push(ResolvedRectangle {
            source: source.entity,
            position,
            size: source.size,
            corner_radius: source.corner_radius,
            color: source.color,
            layer: source.layer,
            draw_order_depth: source.draw_order_depth,
        });
    }

    let mut line_sources_seen = 0usize;
    for source in lines {
        if source.entity.world_generation() != world_generation {
            return Err(ExtractionError::ForeignEntity {
                entity: source.entity,
                expected: world_generation,
            });
        }
        if line_sources_seen == limits.max_world_lines() {
            return Err(ExtractionError::LineLimitExceeded {
                limit: limits.max_world_lines(),
            });
        }
        line_sources_seen = line_sources_seen.saturating_add(1);

        validate_line_source(source)?;
        if source.vector.x() == 0.0 && source.vector.y() == 0.0 {
            continue;
        }
        validate_aggregate_command_capacity(
            storage
                .resolved_circles
                .len()
                .saturating_add(storage.resolved_rectangles.len())
                .saturating_add(storage.resolved_lines.len()),
            limits,
        )?;

        let from = source
            .previous_translation
            .lerp(source.current_translation, alpha);
        if !from.is_finite() {
            return Err(ExtractionError::InvalidInterpolatedTranslation {
                entity: source.entity,
            });
        }
        let to = from + source.vector;
        let delta = to - from;
        if !to.is_finite() || !delta.is_finite() || (delta.x() == 0.0 && delta.y() == 0.0) {
            return Err(ExtractionError::InvalidResolvedLine {
                entity: source.entity,
            });
        }

        storage
            .resolved_lines
            .try_reserve(1)
            .map_err(|_| ExtractionError::AllocationFailed {
                requested_bytes: size_of::<ResolvedLine>(),
            })?;
        storage.resolved_lines.push(ResolvedLine {
            source: source.entity,
            from,
            to,
            stroke_width_logical_pixels: source.stroke_width_logical_pixels,
            color: source.color,
            layer: source.layer,
            draw_order_depth: source.draw_order_depth,
        });
    }

    storage.resolved_circles.sort_unstable_by(|left, right| {
        compare_visual_order(
            left.layer,
            left.draw_order_depth,
            left.source,
            right.layer,
            right.draw_order_depth,
            right.source,
        )
    });
    storage.resolved_rectangles.sort_unstable_by(|left, right| {
        compare_visual_order(
            left.layer,
            left.draw_order_depth,
            left.source,
            right.layer,
            right.draw_order_depth,
            right.source,
        )
    });
    storage.resolved_lines.sort_unstable_by(|left, right| {
        compare_visual_order(
            left.layer,
            left.draw_order_depth,
            left.source,
            right.layer,
            right.draw_order_depth,
            right.source,
        )
    });

    storage
        .world_scene
        .set_background(background)
        .map_err(ExtractionError::Scene)?;
    populate_scene(
        &mut storage.world_scene,
        &storage.resolved_circles,
        &storage.resolved_rectangles,
        &storage.resolved_lines,
    )?;
    storage
        .screen
        .extract(world_generation, limits, screen_rectangles)?;

    Ok(ExtractedMetadata {
        world_generation,
        background,
        camera,
    })
}

fn validate_aggregate_command_capacity(
    retained_visuals: usize,
    limits: RenderLimits,
) -> Result<(), ExtractionError> {
    let limit = limits.world_scene_budget().max_commands();
    if retained_visuals == limit {
        return Err(ExtractionError::Scene(SceneError::BudgetExceeded {
            resource: SceneBudgetResource::Commands,
            limit,
            requested: retained_visuals.saturating_add(1),
        }));
    }
    Ok(())
}

fn rectangle_bounds_are_representable(bounds: Rect) -> bool {
    bounds.min().is_finite()
        && bounds.max().is_finite()
        && bounds.width().is_finite()
        && bounds.height().is_finite()
        && bounds.width() > 0.0
        && bounds.height() > 0.0
}

fn compare_visual_order(
    left_layer: Layer,
    left_depth: f32,
    left_entity: LogicEntity,
    right_layer: Layer,
    right_depth: f32,
    right_entity: LogicEntity,
) -> Ordering {
    left_layer
        .cmp(&right_layer)
        .then_with(|| {
            if left_depth == right_depth {
                Ordering::Equal
            } else {
                left_depth.total_cmp(&right_depth)
            }
        })
        .then_with(|| left_entity.stable_bits().cmp(&right_entity.stable_bits()))
}

fn populate_scene(
    scene: &mut Scene,
    circles: &[ResolvedCircle],
    rectangles: &[ResolvedRectangle],
    lines: &[ResolvedLine],
) -> Result<(), ExtractionError> {
    if lines.is_empty() && rectangles.is_empty() {
        for circle in circles {
            push_circle(scene, circle)?;
        }
        return Ok(());
    }
    if lines.is_empty() && circles.is_empty() {
        for rectangle in rectangles {
            push_rectangle(scene, rectangle)?;
        }
        return Ok(());
    }
    if lines.is_empty() {
        let mut circle_index = 0;
        let mut rectangle_index = 0;
        while circle_index < circles.len() && rectangle_index < rectangles.len() {
            let circle = &circles[circle_index];
            let rectangle = &rectangles[rectangle_index];
            let order = compare_visual_order(
                rectangle.layer,
                rectangle.draw_order_depth,
                rectangle.source,
                circle.layer,
                circle.draw_order_depth,
                circle.source,
            );
            if order != Ordering::Greater {
                // Rectangle has the lower primitive rank for an otherwise exact tie.
                push_rectangle(scene, rectangle)?;
                rectangle_index += 1;
            } else {
                push_circle(scene, circle)?;
                circle_index += 1;
            }
        }
        for circle in &circles[circle_index..] {
            push_circle(scene, circle)?;
        }
        for rectangle in &rectangles[rectangle_index..] {
            push_rectangle(scene, rectangle)?;
        }
        return Ok(());
    }
    if circles.is_empty() && rectangles.is_empty() {
        for line in lines {
            push_line(scene, line)?;
        }
        return Ok(());
    }

    #[derive(Clone, Copy)]
    enum VisualKind {
        Rectangle,
        Circle,
        Line,
    }

    let mut circle_index = 0;
    let mut rectangle_index = 0;
    let mut line_index = 0;
    while circle_index < circles.len()
        || rectangle_index < rectangles.len()
        || line_index < lines.len()
    {
        let next = [
            rectangles.get(rectangle_index).map(|visual| {
                (
                    VisualKind::Rectangle,
                    visual.layer,
                    visual.draw_order_depth,
                    visual.source,
                    0_u8,
                )
            }),
            circles.get(circle_index).map(|visual| {
                (
                    VisualKind::Circle,
                    visual.layer,
                    visual.draw_order_depth,
                    visual.source,
                    1_u8,
                )
            }),
            lines.get(line_index).map(|visual| {
                (
                    VisualKind::Line,
                    visual.layer,
                    visual.draw_order_depth,
                    visual.source,
                    2_u8,
                )
            }),
        ]
        .into_iter()
        .flatten()
        .min_by(|left, right| {
            compare_visual_order(left.1, left.2, left.3, right.1, right.2, right.3)
                .then_with(|| left.4.cmp(&right.4))
        });
        let Some(next) = next else {
            break;
        };

        match next.0 {
            VisualKind::Rectangle => {
                push_rectangle(scene, &rectangles[rectangle_index])?;
                rectangle_index += 1;
            }
            VisualKind::Circle => {
                push_circle(scene, &circles[circle_index])?;
                circle_index += 1;
            }
            VisualKind::Line => {
                push_line(scene, &lines[line_index])?;
                line_index += 1;
            }
        }
    }
    Ok(())
}

fn push_circle(scene: &mut Scene, circle: &ResolvedCircle) -> Result<(), ExtractionError> {
    scene
        .try_circle_on_layer(
            circle.layer,
            circle.position,
            circle.radius,
            ShapeStyle::filled(circle.color),
        )
        .map_err(ExtractionError::Scene)
}

fn push_rectangle(scene: &mut Scene, rectangle: &ResolvedRectangle) -> Result<(), ExtractionError> {
    scene
        .try_rect_on_layer(
            rectangle.layer,
            Rect::from_center_size(rectangle.position, rectangle.size),
            rectangle.corner_radius,
            ShapeStyle::filled(rectangle.color),
        )
        .map_err(ExtractionError::Scene)
}

fn push_line(scene: &mut Scene, line: &ResolvedLine) -> Result<(), ExtractionError> {
    scene
        .try_styled_line_on_layer(
            line.layer,
            line.from,
            line.to,
            line_stroke_style(line.stroke_width_logical_pixels, line.color),
        )
        .map_err(ExtractionError::Scene)
}

fn validate_source(source: CircleSource) -> Result<(), ExtractionError> {
    crate::visual::validate_translation(source.previous_translation).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_translation(source.current_translation).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_radius(source.radius).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_color(source.color).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_draw_order_depth(source.draw_order_depth).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    Ok(())
}

fn validate_rectangle_source(source: RectangleSource) -> Result<(), ExtractionError> {
    crate::visual::validate_translation(source.previous_translation).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_translation(source.current_translation).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_size(source.size).map_err(|error| ExtractionError::InvalidVisual {
        entity: source.entity,
        error,
    })?;
    crate::visual::validate_corner_radius(source.corner_radius).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_color(source.color).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_draw_order_depth(source.draw_order_depth).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    Ok(())
}

fn validate_line_source(source: LineSource) -> Result<(), ExtractionError> {
    crate::visual::validate_translation(source.previous_translation).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_translation(source.current_translation).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_line_vector(source.vector).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_line_width(source.stroke_width_logical_pixels).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_color(source.color).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    crate::visual::validate_draw_order_depth(source.draw_order_depth).map_err(|error| {
        ExtractionError::InvalidVisual {
            entity: source.entity,
            error,
        }
    })?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{identity::ApplicationId, render::DEFAULT_WORLD_SCENE_BUDGET};
    use bevy_ecs::world::World;
    use sim_engine::{DrawCommand, StrokeCap2d, StrokeWidthMode2d};

    fn generation(sequence: u64) -> WorldGeneration {
        WorldGeneration::new(ApplicationId::from_raw(1), sequence)
    }

    fn entity(world: &mut World, generation: WorldGeneration) -> LogicEntity {
        let raw = world.spawn_empty().id();
        LogicEntity::new(ApplicationId::from_raw(1), generation, raw)
    }

    fn camera() -> Result<ActiveCamera2d, sim_engine::Camera2dError> {
        Camera2d::new(Vec2::ZERO, 32.0).map(ActiveCamera2d::new)
    }

    fn source(
        entity: LogicEntity,
        previous: Vec2,
        current: Vec2,
        layer: i32,
        depth: f32,
    ) -> CircleSource {
        CircleSource {
            entity,
            previous_translation: previous,
            current_translation: current,
            radius: 2.0,
            color: Color::WHITE,
            layer: Layer::new(layer),
            draw_order_depth: depth,
        }
    }

    fn rectangle_source(
        entity: LogicEntity,
        previous: Vec2,
        current: Vec2,
        size: Vec2,
        layer: i32,
        depth: f32,
    ) -> RectangleSource {
        RectangleSource {
            entity,
            previous_translation: previous,
            current_translation: current,
            size,
            corner_radius: 0.25,
            color: Color::WHITE,
            layer: Layer::new(layer),
            draw_order_depth: depth,
        }
    }

    fn line_source(
        entity: LogicEntity,
        previous: Vec2,
        current: Vec2,
        vector: Vec2,
        layer: i32,
        depth: f32,
    ) -> LineSource {
        LineSource {
            entity,
            previous_translation: previous,
            current_translation: current,
            vector,
            stroke_width_logical_pixels: 2.5,
            color: Color::rgb8(255, 160, 40),
            layer: Layer::new(layer),
            draw_order_depth: depth,
        }
    }

    #[test]
    fn interpolation_covers_zero_middle_and_just_below_one() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let entity = entity(&mut world, generation);
        let previous = Vec2::new(0.0, 4.0);
        let current = Vec2::new(8.0, 12.0);
        let just_below_one = f32::from_bits(1.0_f32.to_bits() - 1);

        for (alpha, expected) in [
            (0.0, previous),
            (0.5, Vec2::new(4.0, 8.0)),
            (just_below_one, previous.lerp(current, just_below_one)),
        ] {
            let frame = extract_frame(
                ExtractionParameters::new(generation, Color::BLACK, alpha, RenderLimits::default()),
                [camera()?],
                [source(entity, previous, current, 0, 0.0)],
                [],
                [],
            )?;

            assert_eq!(frame.resolved_circles()[0].position(), expected);
            assert_eq!(frame.world_scene().command_count(), 1);
        }
        Ok(())
    }

    #[test]
    fn rectangle_interpolation_and_scene_bounds_match() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let entity = entity(&mut world, generation);
        let previous = Vec2::new(-4.0, 2.0);
        let current = Vec2::new(8.0, 6.0);
        let size = Vec2::new(6.0, 2.0);

        for (alpha, expected) in [(0.0, previous), (0.5, Vec2::new(2.0, 4.0)), (1.0, current)] {
            let frame = extract_frame(
                ExtractionParameters::new(generation, Color::BLACK, alpha, RenderLimits::default()),
                [camera()?],
                [],
                [rectangle_source(entity, previous, current, size, 0, 0.0)],
                [],
            )?;
            let [resolved] = frame.resolved_rectangles() else {
                return Err("expected one resolved rectangle".into());
            };
            assert_eq!(resolved.position(), expected);
            assert_eq!(resolved.size(), size);
            assert_eq!(resolved.corner_radius(), 0.25);

            let [command] = frame.world_scene().commands() else {
                return Err("expected one rectangle command".into());
            };
            let DrawCommand::Rect(rectangle) = command.command() else {
                return Err("resolved rectangle produced another command kind".into());
            };
            assert_eq!(rectangle.rect().min(), expected - size * 0.5);
            assert_eq!(rectangle.rect().max(), expected + size * 0.5);
            assert_eq!(rectangle.corner_radius(), 0.25);
        }
        Ok(())
    }

    #[test]
    fn line_interpolates_only_its_anchor_and_uses_an_exact_butt_stroke()
    -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let entity = entity(&mut world, generation);
        let previous = Vec2::new(-4.0, 2.0);
        let current = Vec2::new(8.0, 6.0);
        let vector = Vec2::new(3.0, -1.0);
        let color = Color::rgb8(255, 160, 40);

        let frame = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.5, RenderLimits::default()),
            [camera()?],
            [],
            [],
            [line_source(entity, previous, current, vector, 4, -2.0)],
        )?;
        let [resolved] = frame.resolved_lines() else {
            return Err("expected one resolved line".into());
        };
        assert_eq!(resolved.source(), entity);
        assert_eq!(resolved.from(), Vec2::new(2.0, 4.0));
        assert_eq!(resolved.to(), Vec2::new(5.0, 3.0));
        assert_eq!(resolved.stroke_width_logical_pixels(), 2.5);
        assert_eq!(resolved.color(), color);
        assert_eq!(resolved.layer(), Layer::new(4));
        assert_eq!(resolved.draw_order_depth(), -2.0);

        let [command] = frame.world_scene().commands() else {
            return Err("expected one line command".into());
        };
        assert_eq!(command.layer(), Layer::new(4));
        let DrawCommand::Line(line) = command.command() else {
            return Err("resolved line produced another command kind".into());
        };
        assert_eq!(line.from(), resolved.from());
        assert_eq!(line.to(), resolved.to());
        assert_eq!(line.stroke().width(), 2.5);
        assert_eq!(line.stroke().color(), color);
        assert_eq!(
            line.stroke_style().width_mode(),
            StrokeWidthMode2d::LogicalPixels
        );
        assert_eq!(line.stroke_style().cap(), StrokeCap2d::Butt);
        assert_eq!(line.stroke_style().start_marker(), None);
        assert_eq!(line.stroke_style().end_marker(), None);
        Ok(())
    }

    #[test]
    fn zero_lines_are_omitted_but_still_count_toward_the_source_limit() -> Result<(), Box<dyn Error>>
    {
        let generation = generation(1);
        let mut world = World::new();
        let first = entity(&mut world, generation);
        let second = entity(&mut world, generation);
        let limits = RenderLimits::default().with_max_world_lines(1);

        let frame = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [],
            [],
            [line_source(
                first,
                Vec2::ZERO,
                Vec2::ZERO,
                Vec2::ZERO,
                0,
                0.0,
            )],
        )?;
        assert!(frame.resolved_lines().is_empty());
        assert_eq!(frame.world_scene().command_count(), 0);

        let result = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [],
            [],
            [
                line_source(first, Vec2::ZERO, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
                line_source(second, Vec2::ZERO, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
            ],
        );
        assert!(matches!(
            result,
            Err(ExtractionError::LineLimitExceeded { limit: 1 })
        ));
        Ok(())
    }

    #[test]
    fn line_resolution_keeps_representable_subnormal_and_maximum_vectors()
    -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let entity = entity(&mut world, generation);

        for vector in [Vec2::new(f32::from_bits(1), 0.0), Vec2::new(f32::MAX, 0.0)] {
            let frame = extract_frame(
                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
                [camera()?],
                [],
                [],
                [line_source(entity, Vec2::ZERO, Vec2::ZERO, vector, 0, 0.0)],
            )?;
            let [line] = frame.resolved_lines() else {
                return Err("representable nonzero vector should resolve".into());
            };
            assert_eq!(line.from(), Vec2::ZERO);
            assert_eq!(line.to().x().to_bits(), vector.x().to_bits());
            assert_eq!(line.to().y().to_bits(), vector.y().to_bits());
        }
        Ok(())
    }

    #[test]
    fn camera_center_uses_the_same_interpolation_alpha() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let previous = Vec2::new(-4.0, 2.0);
        let current = Vec2::new(8.0, 6.0);
        let mut configured = Camera2d::new(previous, 24.0)?;
        configured.set_rotation(0.75)?;
        configured.set_projection(sim_engine::Projection2d::new(0.25, 2.0)?);
        let mut camera = ActiveCamera2d::new(configured);
        camera.set_center(current)?;

        for (alpha, expected) in [(0.0, previous), (0.5, Vec2::new(2.0, 4.0)), (1.0, current)] {
            let frame = extract_frame(
                ExtractionParameters::new(generation, Color::BLACK, alpha, RenderLimits::default()),
                [camera],
                [],
                [],
                [],
            )?;

            assert_eq!(frame.camera().center(), expected);
            assert_eq!(frame.camera().zoom(), 24.0);
            assert_eq!(frame.camera().rotation(), 0.75);
            assert_eq!(
                frame.camera().projection(),
                sim_engine::Projection2d::new(0.25, 2.0)?
            );
            assert_eq!(camera.center(), current);
            assert_eq!(camera.previous_center(), previous);
        }
        Ok(())
    }

    #[test]
    fn sorting_uses_layer_then_depth_then_stable_entity() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let first = entity(&mut world, generation);
        let second = entity(&mut world, generation);
        let third = entity(&mut world, generation);
        let frame = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
            [camera()?],
            [
                source(third, Vec2::new(3.0, 0.0), Vec2::new(3.0, 0.0), 1, 0.0),
                source(second, Vec2::new(2.0, 0.0), Vec2::new(2.0, 0.0), 0, 1.0),
                source(first, Vec2::new(1.0, 0.0), Vec2::new(1.0, 0.0), 0, 1.0),
            ],
            [],
            [
                line_source(
                    third,
                    Vec2::new(3.0, 0.0),
                    Vec2::new(3.0, 0.0),
                    Vec2::ONE,
                    1,
                    0.0,
                ),
                line_source(
                    second,
                    Vec2::new(2.0, 0.0),
                    Vec2::new(2.0, 0.0),
                    Vec2::ONE,
                    0,
                    1.0,
                ),
                line_source(
                    first,
                    Vec2::new(1.0, 0.0),
                    Vec2::new(1.0, 0.0),
                    Vec2::ONE,
                    0,
                    1.0,
                ),
            ],
        )?;

        let ordered_sources: Vec<_> = frame
            .resolved_circles()
            .iter()
            .map(|circle| circle.source())
            .collect();
        let mut same_layer = [first, second];
        same_layer.sort_by_key(|entity| entity.stable_bits());
        let expected_sources = vec![same_layer[0], same_layer[1], third];
        assert_eq!(ordered_sources, expected_sources);
        let ordered_lines: Vec<_> = frame
            .resolved_lines()
            .iter()
            .map(|line| line.source())
            .collect();
        assert_eq!(ordered_lines, expected_sources);

        let scene_centers: Vec<_> = frame
            .world_scene()
            .commands()
            .iter()
            .filter_map(|command| match command.command() {
                DrawCommand::Circle(circle) => Some(circle.center()),
                _ => None,
            })
            .collect();
        let expected_center = |entity: LogicEntity| {
            if entity == first {
                Vec2::new(1.0, 0.0)
            } else {
                Vec2::new(2.0, 0.0)
            }
        };
        assert_eq!(
            scene_centers,
            vec![
                expected_center(same_layer[0]),
                expected_center(same_layer[1]),
                Vec2::new(3.0, 0.0)
            ]
        );
        Ok(())
    }

    #[test]
    fn mixed_scene_uses_one_total_order_with_rectangle_circle_line_on_exact_tie()
    -> Result<(), Box<dyn Error>> {
        #[derive(Debug, PartialEq)]
        enum Observed {
            Circle(Vec2),
            Rectangle(Vec2),
            Line(Vec2, Vec2),
        }

        let generation = generation(1);
        let mut world = World::new();
        let tied = entity(&mut world, generation);
        let early = entity(&mut world, generation);
        let late = entity(&mut world, generation);
        let frame = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
            [camera()?],
            [
                source(late, Vec2::new(30.0, 0.0), Vec2::new(30.0, 0.0), 1, 0.0),
                source(tied, Vec2::new(20.0, 0.0), Vec2::new(20.0, 0.0), 0, 1.0),
            ],
            [
                rectangle_source(
                    tied,
                    Vec2::new(20.0, 0.0),
                    Vec2::new(20.0, 0.0),
                    Vec2::ONE,
                    0,
                    1.0,
                ),
                rectangle_source(
                    early,
                    Vec2::new(10.0, 0.0),
                    Vec2::new(10.0, 0.0),
                    Vec2::ONE,
                    0,
                    0.0,
                ),
            ],
            [line_source(
                tied,
                Vec2::new(20.0, 0.0),
                Vec2::new(20.0, 0.0),
                Vec2::new(2.0, 0.0),
                0,
                1.0,
            )],
        )?;

        let observed: Vec<_> = frame
            .world_scene()
            .commands()
            .iter()
            .map(|command| match command.command() {
                DrawCommand::Circle(circle) => Observed::Circle(circle.center()),
                DrawCommand::Rect(rectangle) => Observed::Rectangle(rectangle.rect().center()),
                DrawCommand::Line(line) => Observed::Line(line.from(), line.to()),
                _ => unreachable!("extractor emitted an unsupported command kind"),
            })
            .collect();
        assert_eq!(
            observed,
            [
                Observed::Rectangle(Vec2::new(10.0, 0.0)),
                Observed::Rectangle(Vec2::new(20.0, 0.0)),
                Observed::Circle(Vec2::new(20.0, 0.0)),
                Observed::Line(Vec2::new(20.0, 0.0), Vec2::new(22.0, 0.0)),
                Observed::Circle(Vec2::new(30.0, 0.0)),
            ]
        );

        for (circle_depth, rectangle_depth) in [(-0.0, 0.0), (0.0, -0.0)] {
            let frame = extract_frame(
                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
                [camera()?],
                [source(tied, Vec2::ZERO, Vec2::ZERO, 0, circle_depth)],
                [rectangle_source(
                    tied,
                    Vec2::ZERO,
                    Vec2::ZERO,
                    Vec2::ONE,
                    0,
                    rectangle_depth,
                )],
                [line_source(
                    tied,
                    Vec2::ZERO,
                    Vec2::ZERO,
                    Vec2::ONE,
                    0,
                    circle_depth,
                )],
            )?;
            let [first, second, third] = frame.world_scene().commands() else {
                return Err("signed-zero tie should produce three commands".into());
            };
            assert!(matches!(first.command(), DrawCommand::Rect(_)));
            assert!(matches!(second.command(), DrawCommand::Circle(_)));
            assert!(matches!(third.command(), DrawCommand::Line(_)));
        }
        Ok(())
    }

    #[test]
    fn circle_count_is_bounded_before_an_extra_record_is_retained() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let first = entity(&mut world, generation);
        let second = entity(&mut world, generation);
        let limits = RenderLimits::new(1, DEFAULT_WORLD_SCENE_BUDGET, Default::default());

        let result = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [
                source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
                source(second, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
            ],
            [],
            [],
        );

        assert!(matches!(
            result,
            Err(ExtractionError::CircleLimitExceeded { limit: 1 })
        ));
        Ok(())
    }

    #[test]
    fn rectangle_and_aggregate_command_limits_are_distinct() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let first = entity(&mut world, generation);
        let second = entity(&mut world, generation);
        let rectangle_limit = RenderLimits::default().with_max_world_rectangles(1);
        let rectangles = [
            rectangle_source(first, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
            rectangle_source(second, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
        ];
        let result = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, rectangle_limit),
            [camera()?],
            [],
            rectangles,
            [],
        );
        assert!(matches!(
            result,
            Err(ExtractionError::RectangleLimitExceeded { limit: 1 })
        ));

        let standard = DEFAULT_WORLD_SCENE_BUDGET;
        let one_command = sim_engine::SceneBudget::new(
            1,
            standard.max_points(),
            standard.max_tessellated_vertices(),
            standard.max_retained_bytes(),
            standard.max_allocation_bytes(),
            standard.max_upload_bytes(),
            standard.max_draw_batches(),
        );
        let aggregate_limits =
            RenderLimits::new(1, one_command, Default::default()).with_max_world_rectangles(1);
        let result = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, aggregate_limits),
            [camera()?],
            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
            [rectangle_source(
                second,
                Vec2::ZERO,
                Vec2::ZERO,
                Vec2::ONE,
                0,
                0.0,
            )],
            [],
        );
        assert!(matches!(
            result,
            Err(ExtractionError::Scene(SceneError::BudgetExceeded {
                resource: SceneBudgetResource::Commands,
                limit: 1,
                requested: 2,
            }))
        ));
        Ok(())
    }

    #[test]
    fn line_and_aggregate_command_limits_are_distinct() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let first = entity(&mut world, generation);
        let second = entity(&mut world, generation);
        let line_limit = RenderLimits::default().with_max_world_lines(1);
        let lines = [
            line_source(first, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
            line_source(second, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
        ];
        let result = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, line_limit),
            [camera()?],
            [],
            [],
            lines,
        );
        assert!(matches!(
            result,
            Err(ExtractionError::LineLimitExceeded { limit: 1 })
        ));

        let standard = DEFAULT_WORLD_SCENE_BUDGET;
        let one_command = sim_engine::SceneBudget::new(
            1,
            standard.max_points(),
            standard.max_tessellated_vertices(),
            standard.max_retained_bytes(),
            standard.max_allocation_bytes(),
            standard.max_upload_bytes(),
            standard.max_draw_batches(),
        );
        let limits = RenderLimits::new(1, one_command, Default::default()).with_max_world_lines(1);
        let result = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
            [],
            [line_source(
                second,
                Vec2::ZERO,
                Vec2::ZERO,
                Vec2::ONE,
                0,
                0.0,
            )],
        );
        assert!(matches!(
            result,
            Err(ExtractionError::Scene(SceneError::BudgetExceeded {
                resource: SceneBudgetResource::Commands,
                limit: 1,
                requested: 2,
            }))
        ));
        Ok(())
    }

    #[test]
    fn collapsed_or_overflowed_rectangle_bounds_keep_entity_attribution()
    -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let collapsed = entity(&mut world, generation);
        let overflowed = entity(&mut world, generation);

        for source in [
            rectangle_source(
                collapsed,
                Vec2::splat(f32::MAX),
                Vec2::splat(f32::MAX),
                Vec2::ONE,
                0,
                0.0,
            ),
            rectangle_source(
                overflowed,
                Vec2::splat(f32::MAX),
                Vec2::splat(f32::MAX),
                Vec2::splat(f32::MAX),
                0,
                0.0,
            ),
        ] {
            let result = extract_frame(
                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
                [camera()?],
                [],
                [source],
                [],
            );
            assert!(matches!(
                result,
                Err(ExtractionError::InvalidResolvedRectangle { entity })
                    if entity == source.entity
            ));
        }
        Ok(())
    }

    #[test]
    fn collapsed_or_overflowed_line_endpoints_keep_entity_attribution() -> Result<(), Box<dyn Error>>
    {
        let generation = generation(1);
        let mut world = World::new();
        let collapsed = entity(&mut world, generation);
        let overflowed = entity(&mut world, generation);

        for source in [
            line_source(
                collapsed,
                Vec2::splat(f32::MAX),
                Vec2::splat(f32::MAX),
                Vec2::ONE,
                0,
                0.0,
            ),
            line_source(
                overflowed,
                Vec2::splat(f32::MAX),
                Vec2::splat(f32::MAX),
                Vec2::splat(f32::MAX),
                0,
                0.0,
            ),
        ] {
            let result = extract_frame(
                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
                [camera()?],
                [],
                [],
                [source],
            );
            assert!(matches!(
                result,
                Err(ExtractionError::InvalidResolvedLine { entity })
                    if entity == source.entity
            ));
        }
        Ok(())
    }

    #[test]
    fn foreign_generation_is_rejected() -> Result<(), Box<dyn Error>> {
        let active = generation(1);
        let stale = generation(2);
        let mut world = World::new();
        let stale_entity = entity(&mut world, stale);

        let result = extract_frame(
            ExtractionParameters::new(active, Color::BLACK, 0.0, RenderLimits::default()),
            [camera()?],
            [source(stale_entity, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
            [],
            [],
        );

        assert!(matches!(
            result,
            Err(ExtractionError::ForeignEntity { entity, expected })
                if entity == stale_entity && expected == active
        ));
        Ok(())
    }

    #[test]
    fn defensive_visual_validation_precedes_scene_publication() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let entity = entity(&mut world, generation);
        let invalid = CircleSource {
            radius: f32::NAN,
            ..source(entity, Vec2::ZERO, Vec2::ZERO, 0, 0.0)
        };

        let result = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.5, RenderLimits::default()),
            [camera()?],
            [invalid],
            [],
            [],
        );

        assert!(matches!(
            result,
            Err(ExtractionError::InvalidVisual {
                error: VisualValueError::InvalidRadius { .. },
                ..
            })
        ));
        Ok(())
    }

    #[test]
    fn defensive_line_validation_preserves_entity_attribution() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let entity = entity(&mut world, generation);

        for invalid in [
            LineSource {
                vector: Vec2::new(f32::NAN, 0.0),
                ..line_source(entity, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0)
            },
            LineSource {
                stroke_width_logical_pixels: f32::MAX,
                ..line_source(entity, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0)
            },
        ] {
            let result = extract_frame(
                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
                [camera()?],
                [],
                [],
                [invalid],
            );
            assert!(matches!(
                result,
                Err(ExtractionError::InvalidVisual {
                    entity: rejected,
                    error: VisualValueError::InvalidLineVector { .. }
                        | VisualValueError::InvalidLineWidth { .. },
                }) if rejected == entity
            ));
        }
        Ok(())
    }

    #[test]
    fn camera_cardinality_is_checked() -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let limits = RenderLimits::default();
        let missing = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
            [],
            [],
            [],
            [],
        );
        assert!(matches!(missing, Err(ExtractionError::MissingActiveCamera)));

        let multiple = extract_frame(
            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
            [camera()?, camera()?],
            [],
            [],
            [],
        );
        assert!(matches!(
            multiple,
            Err(ExtractionError::MultipleActiveCameras)
        ));

        Ok(())
    }

    #[test]
    fn reusable_storage_clears_logical_state_without_losing_fixed_record_capacity()
    -> Result<(), Box<dyn Error>> {
        let generation = generation(1);
        let mut world = World::new();
        let first = entity(&mut world, generation);
        let second = entity(&mut world, generation);
        let third = entity(&mut world, generation);
        let fourth = entity(&mut world, generation);
        let fifth = entity(&mut world, generation);
        let limits = RenderLimits::default();
        let mut storage = ExtractionBuffer::new(limits)?;

        let first_metadata = extract_frame_into(
            &mut storage,
            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [
                source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
                source(second, Vec2::ONE, Vec2::ONE, 0, 1.0),
            ],
            [
                rectangle_source(third, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 2.0),
                rectangle_source(fourth, Vec2::ONE, Vec2::ONE, Vec2::ONE, 0, 3.0),
            ],
            [line_source(
                fifth,
                Vec2::new(2.0, 4.0),
                Vec2::new(2.0, 4.0),
                Vec2::new(3.0, -1.0),
                0,
                4.0,
            )],
            [],
        )?;
        assert_eq!(first_metadata.background, Color::BLACK);
        let circle_capacity = storage.resolved_circles.capacity();
        let rectangle_capacity = storage.resolved_rectangles.capacity();
        let line_capacity = storage.resolved_lines.capacity();
        let circle_address = storage.resolved_circles.as_ptr();
        let rectangle_address = storage.resolved_rectangles.as_ptr();
        let line_address = storage.resolved_lines.as_ptr();
        let scene_address = storage.world_scene.commands().as_ptr();
        let scene_allocation = storage.world_scene.allocation_bytes();

        let moved_camera = ActiveCamera2d::new(Camera2d::new(Vec2::new(7.0, -4.0), 20.0)?);
        let second_metadata = extract_frame_into(
            &mut storage,
            ExtractionParameters::new(generation, Color::WHITE, 0.0, limits),
            [moved_camera],
            [source(first, Vec2::ONE, Vec2::ONE, 0, 0.0)],
            [],
            [],
            [],
        )?;
        assert_eq!(second_metadata.background, Color::WHITE);
        assert_eq!(second_metadata.camera.center(), Vec2::new(7.0, -4.0));
        assert_eq!(storage.resolved_circles.len(), 1);
        assert!(storage.resolved_rectangles.is_empty());
        assert!(storage.resolved_lines.is_empty());
        assert_eq!(storage.world_scene.command_count(), 1);
        assert_eq!(storage.world_scene.background(), Color::WHITE);
        assert_eq!(storage.resolved_circles.capacity(), circle_capacity);
        assert_eq!(storage.resolved_rectangles.capacity(), rectangle_capacity);
        assert_eq!(storage.resolved_lines.capacity(), line_capacity);
        assert_eq!(storage.resolved_circles.as_ptr(), circle_address);
        assert_eq!(storage.resolved_rectangles.as_ptr(), rectangle_address);
        assert_eq!(storage.resolved_lines.as_ptr(), line_address);
        assert_eq!(storage.world_scene.commands().as_ptr(), scene_address);
        assert_eq!(storage.world_scene.allocation_bytes(), scene_allocation);

        let empty_metadata = extract_frame_into(
            &mut storage,
            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [],
            [],
            [],
            [],
        )?;
        assert_eq!(empty_metadata.background, Color::BLACK);
        assert!(storage.resolved_circles.is_empty());
        assert!(storage.resolved_rectangles.is_empty());
        assert!(storage.resolved_lines.is_empty());
        assert_eq!(storage.world_scene.command_count(), 0);
        assert_eq!(storage.world_scene.statistics().accepted_commands(), 0);
        assert_eq!(storage.world_scene.background(), Color::BLACK);
        assert_eq!(storage.resolved_circles.capacity(), circle_capacity);
        assert_eq!(storage.resolved_rectangles.capacity(), rectangle_capacity);
        assert_eq!(storage.resolved_lines.capacity(), line_capacity);
        assert_eq!(storage.resolved_circles.as_ptr(), circle_address);
        assert_eq!(storage.resolved_rectangles.as_ptr(), rectangle_address);
        assert_eq!(storage.resolved_lines.as_ptr(), line_address);
        assert_eq!(storage.world_scene.commands().as_ptr(), scene_address);
        assert_eq!(storage.world_scene.allocation_bytes(), scene_allocation);
        Ok(())
    }

    #[test]
    fn invalid_line_staging_preserves_publication_and_retry_clears_partial_records()
    -> Result<(), Box<dyn Error>> {
        let first_generation = generation(1);
        let next_generation = generation(2);
        let mut world = World::new();
        let first = entity(&mut world, first_generation);
        let valid = entity(&mut world, next_generation);
        let invalid = entity(&mut world, next_generation);
        let limits = RenderLimits::default();
        let mut buffers = ExtractionBuffers::new();

        buffers.stage_world_only(
            ExtractionParameters::new(first_generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
            [],
            [],
        )?;
        assert_eq!(buffers.publish(), Some(first_generation));

        let result = buffers.stage_world_only(
            ExtractionParameters::new(next_generation, Color::WHITE, 0.0, limits),
            [camera()?],
            [],
            [],
            [
                line_source(valid, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
                line_source(
                    invalid,
                    Vec2::splat(f32::MAX),
                    Vec2::splat(f32::MAX),
                    Vec2::ONE,
                    0,
                    1.0,
                ),
            ],
        );
        assert!(matches!(
            result,
            Err(ExtractionError::InvalidResolvedLine { entity }) if entity == invalid
        ));
        let partial = buffers
            .spare
            .as_ref()
            .ok_or("failed line staging should retain its private spare")?;
        assert_eq!(partial.resolved_lines.len(), 1);
        assert_eq!(partial.resolved_lines[0].source(), valid);
        assert_eq!(partial.world_scene.command_count(), 0);

        let published = buffers
            .published()
            .ok_or("failed line staging should preserve the published frame")?;
        assert_eq!(published.world_generation(), first_generation);
        assert_eq!(published.resolved_circles().len(), 1);
        assert!(published.resolved_lines().is_empty());

        buffers.stage_world_only(
            ExtractionParameters::new(next_generation, Color::WHITE, 0.0, limits),
            [camera()?],
            [],
            [],
            [line_source(
                valid,
                Vec2::new(2.0, 3.0),
                Vec2::new(2.0, 3.0),
                Vec2::new(-1.0, 4.0),
                0,
                0.0,
            )],
        )?;
        assert_eq!(buffers.publish(), Some(next_generation));
        let published = buffers
            .published()
            .ok_or("valid line retry should publish")?;
        assert!(published.resolved_circles().is_empty());
        let [line] = published.resolved_lines() else {
            return Err("valid line retry should contain one fresh line".into());
        };
        assert_eq!(line.source(), valid);
        assert_eq!(line.from(), Vec2::new(2.0, 3.0));
        assert_eq!(line.to(), Vec2::new(1.0, 7.0));
        assert_eq!(published.world_scene().command_count(), 1);
        Ok(())
    }

    #[test]
    fn downstream_line_scene_failure_keeps_the_last_complete_snapshot() -> Result<(), Box<dyn Error>>
    {
        let first_generation = generation(1);
        let failed_generation = generation(2);
        let mut world = World::new();
        let first = entity(&mut world, first_generation);
        let failed_first = entity(&mut world, failed_generation);
        let failed_second = entity(&mut world, failed_generation);
        let defaults = RenderLimits::default();
        let scene = defaults.world_scene_budget();
        let one_draw_batch = sim_engine::SceneBudget::new(
            scene.max_commands(),
            scene.max_points(),
            scene.max_tessellated_vertices(),
            scene.max_retained_bytes(),
            scene.max_allocation_bytes(),
            scene.max_upload_bytes(),
            1,
        );
        let limits = RenderLimits::new(
            defaults.max_world_circles(),
            one_draw_batch,
            defaults.frame_limits(),
        )
        .with_max_world_rectangles(defaults.max_world_rectangles())
        .with_max_world_lines(defaults.max_world_lines());
        let mut buffers = ExtractionBuffers::new();

        buffers.stage_world_only(
            ExtractionParameters::new(first_generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
            [],
            [],
        )?;
        assert_eq!(buffers.publish(), Some(first_generation));

        let result = buffers.stage_world_only(
            ExtractionParameters::new(failed_generation, Color::WHITE, 0.0, limits),
            [camera()?],
            [],
            [],
            [
                line_source(failed_first, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
                line_source(failed_second, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 1, 0.0),
            ],
        );
        assert!(matches!(result, Err(ExtractionError::Scene(_))));
        let partial = buffers
            .spare
            .as_ref()
            .ok_or("failed Scene staging should retain its private spare")?;
        assert_eq!(partial.resolved_lines.len(), 2);
        assert_eq!(partial.world_scene.command_count(), 1);
        assert_eq!(partial.world_scene.statistics().requested_commands(), 2);
        assert_eq!(partial.world_scene.statistics().accepted_commands(), 1);
        assert_eq!(partial.world_scene.statistics().rejected_commands(), 1);
        assert_eq!(partial.world_scene.statistics().estimated_draw_batches(), 1);

        let published = buffers
            .published()
            .ok_or("failed Scene staging should preserve the published frame")?;
        assert_eq!(published.world_generation(), first_generation);
        assert_eq!(published.resolved_circles().len(), 1);
        assert!(published.resolved_lines().is_empty());
        Ok(())
    }

    #[test]
    fn failed_staging_preserves_published_frame_and_retry_has_no_partial_records()
    -> Result<(), Box<dyn Error>> {
        let first_generation = generation(1);
        let failed_generation = generation(2);
        let recovered_generation = generation(3);
        let mut world = World::new();
        let first = entity(&mut world, first_generation);
        let failed_first = entity(&mut world, failed_generation);
        let failed_second = entity(&mut world, failed_generation);
        let recovered = entity(&mut world, recovered_generation);
        let defaults = RenderLimits::default();
        let scene = defaults.world_scene_budget();
        let one_draw_batch = sim_engine::SceneBudget::new(
            scene.max_commands(),
            scene.max_points(),
            scene.max_tessellated_vertices(),
            scene.max_retained_bytes(),
            scene.max_allocation_bytes(),
            scene.max_upload_bytes(),
            1,
        );
        let limits = RenderLimits::new(
            defaults.max_world_circles(),
            one_draw_batch,
            defaults.frame_limits(),
        )
        .with_max_world_rectangles(defaults.max_world_rectangles());
        let mut buffers = ExtractionBuffers::new();

        buffers.stage_world_only(
            ExtractionParameters::new(first_generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [source(first, Vec2::ONE, Vec2::ONE, 0, 0.0)],
            [],
            [],
        )?;
        assert_eq!(buffers.publish(), Some(first_generation));

        let result = buffers.stage_world_only(
            ExtractionParameters::new(failed_generation, Color::WHITE, 0.0, limits),
            [ActiveCamera2d::new(Camera2d::new(Vec2::ONE, 20.0)?)],
            [
                source(failed_first, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
                source(
                    failed_second,
                    Vec2::splat(f32::MAX),
                    Vec2::splat(f32::MAX),
                    1,
                    1.0,
                ),
            ],
            [],
            [],
        );
        assert!(matches!(result, Err(ExtractionError::Scene(_))));
        let partial = buffers
            .spare
            .as_ref()
            .ok_or("failed staging should retain its private spare")?;
        assert_eq!(partial.resolved_circles.len(), 2);
        assert_eq!(partial.world_scene.command_count(), 1);
        assert_eq!(partial.world_scene.statistics().requested_commands(), 2);
        assert_eq!(partial.world_scene.statistics().accepted_commands(), 1);
        let published = buffers
            .published()
            .ok_or("failed staging should preserve the published frame")?;
        assert_eq!(published.world_generation(), first_generation);
        assert_eq!(published.background(), Color::BLACK);
        assert_eq!(published.camera().center(), Vec2::ZERO);
        assert_eq!(published.resolved_circles().len(), 1);
        assert_eq!(published.resolved_circles()[0].source(), first);
        assert_eq!(published.world_scene().command_count(), 1);

        buffers.stage_world_only(
            ExtractionParameters::new(failed_generation, Color::WHITE, 0.0, limits),
            [ActiveCamera2d::new(Camera2d::new(Vec2::ONE, 20.0)?)],
            [source(failed_first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
            [],
            [],
        )?;
        buffers.discard_staged();
        assert_eq!(buffers.publish(), None);
        assert_eq!(
            buffers.published().map(ExtractedFrame::world_generation),
            Some(first_generation),
            "abandoning a validated candidate must not publish its work buffer"
        );

        buffers.stage_world_only(
            ExtractionParameters::new(recovered_generation, Color::WHITE, 0.0, limits),
            [ActiveCamera2d::new(Camera2d::new(
                Vec2::new(-2.0, 3.0),
                20.0,
            )?)],
            [],
            [rectangle_source(
                recovered,
                Vec2::new(4.0, 5.0),
                Vec2::new(4.0, 5.0),
                Vec2::ONE,
                0,
                0.0,
            )],
            [],
        )?;
        assert_eq!(buffers.publish(), Some(recovered_generation));
        let published = buffers
            .published()
            .ok_or("valid retry should publish its complete frame")?;
        assert_eq!(published.world_generation(), recovered_generation);
        assert_eq!(published.background(), Color::WHITE);
        assert_eq!(published.camera().center(), Vec2::new(-2.0, 3.0));
        assert!(published.resolved_circles().is_empty());
        let [rectangle] = published.resolved_rectangles() else {
            return Err("valid retry should contain only its rectangle".into());
        };
        assert_eq!(rectangle.source(), recovered);
        assert_eq!(published.world_scene().command_count(), 1);
        assert_eq!(published.world_scene().statistics().accepted_commands(), 1);
        assert!(matches!(
            published.world_scene().commands()[0].command(),
            DrawCommand::Rect(_)
        ));
        Ok(())
    }

    #[test]
    fn successful_publications_alternate_exactly_two_warmed_buffers() -> Result<(), Box<dyn Error>>
    {
        let first_generation = generation(1);
        let second_generation = generation(2);
        let third_generation = generation(3);
        let mut world = World::new();
        let first = entity(&mut world, first_generation);
        let second = entity(&mut world, second_generation);
        let third = entity(&mut world, third_generation);
        let limits = RenderLimits::default();
        let mut buffers = ExtractionBuffers::new();

        buffers.stage_world_only(
            ExtractionParameters::new(first_generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
            [],
            [],
        )?;
        assert_eq!(buffers.publish(), Some(first_generation));
        let published = buffers.published().ok_or("first frame was not published")?;
        let first_circle_address = published.storage.resolved_circles.as_ptr();
        let first_scene_address = published.storage.world_scene.commands().as_ptr();

        buffers.stage_world_only(
            ExtractionParameters::new(second_generation, Color::WHITE, 0.0, limits),
            [camera()?],
            [source(second, Vec2::ONE, Vec2::ONE, 0, 0.0)],
            [],
            [],
        )?;
        assert_eq!(buffers.publish(), Some(second_generation));
        let published = buffers
            .published()
            .ok_or("second frame was not published")?;
        let second_circle_address = published.storage.resolved_circles.as_ptr();
        let second_scene_address = published.storage.world_scene.commands().as_ptr();
        assert_ne!(second_circle_address, first_circle_address);
        assert_ne!(second_scene_address, first_scene_address);

        buffers.stage_world_only(
            ExtractionParameters::new(third_generation, Color::BLACK, 0.0, limits),
            [camera()?],
            [source(
                third,
                Vec2::new(2.0, 3.0),
                Vec2::new(2.0, 3.0),
                0,
                0.0,
            )],
            [],
            [],
        )?;
        assert_eq!(buffers.publish(), Some(third_generation));
        let published = buffers.published().ok_or("third frame was not published")?;
        assert_eq!(
            published.storage.resolved_circles.as_ptr(),
            first_circle_address
        );
        assert_eq!(
            published.storage.world_scene.commands().as_ptr(),
            first_scene_address
        );
        assert_eq!(published.resolved_circles()[0].source(), third);
        Ok(())
    }
}