sim-engine 0.2.0

A validated high-performance visualization engine for simulations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
use std::{
    error::Error,
    fmt,
    mem::size_of,
    panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};

use crate::{
    Color, Interpolate, LogicalPixels, LogicalScreenPosition, LogicalScreenVector, Rect, Vec2,
    WorldLength,
};

pub(crate) const CIRCLE_SEGMENTS: usize = 64;
pub(crate) const ROUND_CAP_SEGMENTS: usize = 16;
pub(crate) const CORNER_SEGMENTS: usize = 12;
pub(crate) const TESSELLATED_VERTEX_BYTES: usize = 20 * size_of::<f32>();
const MAX_DASH_ELEMENTS: usize = 8;
const MAX_MITER_LIMIT: f32 = 1_000.0;
const MIN_STROKE_TURN_SINE: f64 = 0.000_1;
/// Maximum visible dash pieces one command may request from tessellation.
pub const MAX_STROKE_DASH_SUBSEGMENTS: usize = 1_000_000;

/// Primitive category attached to structured scene validation errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScenePrimitive {
    /// Circle geometry or style.
    Circle,
    /// Rectangle geometry or style.
    Rect,
    /// Single line geometry or stroke.
    Line,
    /// Connected polyline geometry or stroke.
    Polyline,
}

/// Work category constrained by a [`SceneBudget`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SceneBudgetResource {
    /// Accepted scene commands.
    Commands,
    /// Points retained by polyline commands.
    Points,
    /// Conservative upper bound for generated triangle-list vertices.
    TessellatedVertices,
    /// Command payload bytes retained by the scene.
    RetainedBytes,
    /// Committed command-vector and owned polyline allocation bytes.
    AllocationBytes,
    /// Bytes uploaded for generated scene vertices.
    UploadBytes,
    /// Draw batches caused by ordering and clip changes.
    DrawBatches,
}

/// Explicit upper bounds for engine-owned ordinary-scene work.
///
/// Limits may be zero to construct a background-only scene. Retained bytes
/// count logical command values and owned polyline storage. Allocation bytes
/// additionally bound committed spare command-vector capacity; allocator
/// bookkeeping and transactional replacement overlap are excluded. Vertex and
/// upload limits use the renderer's conservative
/// triangle-list estimate, which is checked again after tessellation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SceneBudget {
    max_commands: usize,
    max_points: usize,
    max_tessellated_vertices: usize,
    max_retained_bytes: usize,
    max_allocation_bytes: usize,
    max_upload_bytes: usize,
    max_draw_batches: usize,
}

impl SceneBudget {
    /// Builds a complete budget for ordinary scene construction and rendering.
    pub const fn new(
        max_commands: usize,
        max_points: usize,
        max_tessellated_vertices: usize,
        max_retained_bytes: usize,
        max_allocation_bytes: usize,
        max_upload_bytes: usize,
        max_draw_batches: usize,
    ) -> Self {
        Self {
            max_commands,
            max_points,
            max_tessellated_vertices,
            max_retained_bytes,
            max_allocation_bytes,
            max_upload_bytes,
            max_draw_batches,
        }
    }

    /// Returns the maximum accepted command count.
    pub const fn max_commands(self) -> usize {
        self.max_commands
    }

    /// Returns the maximum retained polyline point count.
    pub const fn max_points(self) -> usize {
        self.max_points
    }

    /// Returns the maximum conservatively estimated vertex count.
    pub const fn max_tessellated_vertices(self) -> usize {
        self.max_tessellated_vertices
    }

    /// Returns the maximum retained command payload bytes.
    pub const fn max_retained_bytes(self) -> usize {
        self.max_retained_bytes
    }

    /// Returns the maximum committed command and polyline allocation bytes.
    pub const fn max_allocation_bytes(self) -> usize {
        self.max_allocation_bytes
    }

    /// Returns the maximum generated vertex upload bytes.
    pub const fn max_upload_bytes(self) -> usize {
        self.max_upload_bytes
    }

    /// Returns the maximum draw-batch count.
    pub const fn max_draw_batches(self) -> usize {
        self.max_draw_batches
    }
}

/// Construction and conservative rendering work accumulated by a scene.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SceneStatistics {
    requested_commands: usize,
    accepted_commands: usize,
    rejected_commands: usize,
    requested_by_primitive: PrimitiveCommandCounts,
    accepted_by_primitive: PrimitiveCommandCounts,
    rejected_by_primitive: PrimitiveCommandCounts,
    retained_points: usize,
    estimated_tessellated_vertices: usize,
    retained_bytes: usize,
    estimated_upload_bytes: usize,
    estimated_draw_batches: usize,
}

impl SceneStatistics {
    /// Returns all insertion attempts, including invalid and over-budget work.
    pub const fn requested_commands(self) -> usize {
        self.requested_commands
    }

    /// Returns commands currently retained by the scene.
    pub const fn accepted_commands(self) -> usize {
        self.accepted_commands
    }

    /// Returns insertion attempts rejected by validation, budget, or allocation.
    pub const fn rejected_commands(self) -> usize {
        self.rejected_commands
    }

    /// Returns insertion attempts grouped by primitive category.
    pub const fn requested_by_primitive(self) -> PrimitiveCommandCounts {
        self.requested_by_primitive
    }

    /// Returns currently retained commands grouped by primitive category.
    pub const fn accepted_by_primitive(self) -> PrimitiveCommandCounts {
        self.accepted_by_primitive
    }

    /// Returns rejected insertion attempts grouped by primitive category.
    pub const fn rejected_by_primitive(self) -> PrimitiveCommandCounts {
        self.rejected_by_primitive
    }

    /// Returns points retained by accepted polyline commands.
    pub const fn retained_points(self) -> usize {
        self.retained_points
    }

    /// Returns the conservative upper bound for tessellated vertices.
    pub const fn estimated_tessellated_vertices(self) -> usize {
        self.estimated_tessellated_vertices
    }

    /// Returns tracked command and owned polyline payload bytes.
    pub const fn retained_bytes(self) -> usize {
        self.retained_bytes
    }

    /// Returns estimated bytes uploaded for generated vertices.
    pub const fn estimated_upload_bytes(self) -> usize {
        self.estimated_upload_bytes
    }

    /// Returns the conservative draw-batch upper bound.
    pub const fn estimated_draw_batches(self) -> usize {
        self.estimated_draw_batches
    }

    fn with_command(mut self, command: &DrawCommand) -> Self {
        let vertices = command.estimated_tessellated_vertices();
        self.accepted_commands = self.accepted_commands.saturating_add(1);
        self.accepted_by_primitive.increment(command.primitive());
        self.retained_points = self
            .retained_points
            .saturating_add(command.retained_point_count());
        self.estimated_tessellated_vertices =
            self.estimated_tessellated_vertices.saturating_add(vertices);
        self.retained_bytes = self.retained_bytes.saturating_add(command.retained_bytes());
        self.estimated_upload_bytes = self
            .estimated_upload_bytes
            .saturating_add(vertices.saturating_mul(TESSELLATED_VERTEX_BYTES));
        self.estimated_draw_batches = self.estimated_draw_batches.saturating_add(1);
        self
    }
}

/// Command counters grouped by ordinary 2D primitive category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PrimitiveCommandCounts {
    circles: usize,
    rectangles: usize,
    lines: usize,
    polylines: usize,
}

impl PrimitiveCommandCounts {
    /// Returns circle command count.
    pub const fn circles(self) -> usize {
        self.circles
    }

    /// Returns rectangle command count.
    pub const fn rectangles(self) -> usize {
        self.rectangles
    }

    /// Returns single-line command count.
    pub const fn lines(self) -> usize {
        self.lines
    }

    /// Returns connected-polyline command count.
    pub const fn polylines(self) -> usize {
        self.polylines
    }

    /// Returns all primitive commands represented by these counters.
    pub const fn total(self) -> usize {
        self.circles
            .saturating_add(self.rectangles)
            .saturating_add(self.lines)
            .saturating_add(self.polylines)
    }

    pub(crate) fn increment(&mut self, primitive: ScenePrimitive) {
        match primitive {
            ScenePrimitive::Circle => self.circles = self.circles.saturating_add(1),
            ScenePrimitive::Rect => self.rectangles = self.rectangles.saturating_add(1),
            ScenePrimitive::Line => self.lines = self.lines.saturating_add(1),
            ScenePrimitive::Polyline => self.polylines = self.polylines.saturating_add(1),
        }
    }

    pub(crate) fn adding(mut self, other: Self) -> Self {
        self.circles = self.circles.saturating_add(other.circles);
        self.rectangles = self.rectangles.saturating_add(other.rectangles);
        self.lines = self.lines.saturating_add(other.lines);
        self.polylines = self.polylines.saturating_add(other.polylines);
        self
    }
}

/// Reason a command or temporary scene state was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SceneError {
    /// Clear color is non-finite or outside normalized RGBA.
    InvalidBackground,
    /// Primitive coordinates contain NaN or infinity.
    NonFiniteGeometry(ScenePrimitive),
    /// Radius, size, corner radius, or stroke width is outside its valid range.
    InvalidDimension(ScenePrimitive),
    /// A line segment, or at least one consecutive polyline segment, is not drawable.
    DegenerateGeometry(ScenePrimitive),
    /// Consecutive polyline segments form a numerically ambiguous continuation or reversal.
    ///
    /// An almost-collinear change of direction cannot select a stable shader
    /// join branch; a retraced centerline also has no interior-disjoint
    /// alpha-blended representation. `vertex_index` identifies the path point.
    DegenerateStrokeTurn {
        /// Primitive containing the ambiguous turn.
        primitive: ScenePrimitive,
        /// Zero-based index of the shared turn point.
        vertex_index: usize,
    },
    /// Shape has no fill, stroke, or shadow.
    MissingStyle(ScenePrimitive),
    /// Fill color or gradient configuration is invalid.
    InvalidFill(ScenePrimitive),
    /// Stroke width or color is invalid.
    InvalidStroke(ScenePrimitive),
    /// A dash pattern would expand into more retained triangle pieces than its
    /// explicit per-command limit.
    StrokeExpansionLimitExceeded {
        /// Primitive whose stroke exceeded the limit.
        primitive: ScenePrimitive,
        /// Configured maximum number of emitted visible subsegments.
        limit: usize,
        /// Minimum visible-subsegment count that proved the limit was exceeded.
        required: usize,
    },
    /// Dash/gap boundaries collapse at the source path's `f32` coordinate scale.
    UnrepresentableStrokePattern(ScenePrimitive),
    /// Shadow offset, spread, or color is invalid.
    InvalidShadow(ScenePrimitive),
    /// Active logical screen clip is non-finite or empty.
    InvalidScreenClip,
    /// Pseudo-depth must be finite.
    NonFiniteDepth,
    /// An accepted command would exceed an explicit scene work limit.
    BudgetExceeded {
        /// Work category whose limit was exceeded.
        resource: SceneBudgetResource,
        /// Configured maximum for the category.
        limit: usize,
        /// Total category usage that the command requested.
        requested: usize,
    },
    /// Engine-owned command storage could not be reserved without mutation.
    AllocationFailed {
        /// Conservative byte estimate associated with the failed reservation.
        ///
        /// Depending on the transactional path, this can describe one
        /// command's retained payload or the total replacement/staging
        /// allocation that could not be reserved. It is diagnostic context,
        /// not a delta suitable for allocator accounting.
        requested_bytes: usize,
    },
}

impl fmt::Display for SceneError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "scene command rejected: {self:?}")
    }
}

impl Error for SceneError {}

/// Ordered list of visual draw commands for a single frame.
///
/// A scene contains renderable primitives only. It does not own simulation
/// entities, domain rules, or time stepping.
#[derive(Debug)]
pub struct Scene {
    background: Color,
    /// Commands stored in draw order.
    commands: Vec<SceneCommand>,
    owned_payload_bytes: usize,
    next_order: u64,
    current_screen_clip: Option<ScreenClipRect>,
    current_depth: f32,
    budget: Option<SceneBudget>,
    statistics: SceneStatistics,
}

impl Clone for Scene {
    fn clone(&self) -> Self {
        let commands = self.commands.clone();
        let owned_payload_bytes = commands
            .iter()
            .map(|command| command.command.owned_allocation_bytes())
            .fold(0usize, usize::saturating_add);
        let mut statistics = self.statistics;
        statistics.retained_bytes = commands
            .len()
            .saturating_mul(size_of::<SceneCommand>())
            .saturating_add(owned_payload_bytes);
        Self {
            background: self.background,
            commands,
            owned_payload_bytes,
            next_order: self.next_order,
            current_screen_clip: self.current_screen_clip,
            current_depth: self.current_depth,
            budget: self.budget,
            statistics,
        }
    }
}

impl Scene {
    /// Creates an empty scene with a normalized linear-RGBA background color.
    ///
    /// This compatibility constructor is intentionally unbounded. Production
    /// hosts handling externally sized visual state should prefer
    /// [`Scene::with_budget`].
    pub fn new(background: Color) -> Result<Self, SceneError> {
        Self::create(background, None)
    }

    /// Creates an empty scene with explicit construction and rendering limits.
    pub fn with_budget(background: Color, budget: SceneBudget) -> Result<Self, SceneError> {
        Self::create(background, Some(budget))
    }

    fn create(background: Color, budget: Option<SceneBudget>) -> Result<Self, SceneError> {
        if !background.is_normalized() {
            return Err(SceneError::InvalidBackground);
        }
        Ok(Self {
            background,
            commands: Vec::new(),
            owned_payload_bytes: 0,
            next_order: 0,
            current_screen_clip: None,
            current_depth: 0.0,
            budget,
            statistics: SceneStatistics::default(),
        })
    }

    /// Returns the normalized clear color used before drawing commands.
    pub fn background(&self) -> Color {
        self.background
    }

    /// Replaces the clear color used before drawing commands.
    pub fn set_background(&mut self, background: Color) -> Result<(), SceneError> {
        if !background.is_normalized() {
            return Err(SceneError::InvalidBackground);
        }
        self.background = background;
        Ok(())
    }

    /// Removes all draw commands and active clipping without changing the background color.
    pub fn clear(&mut self) {
        self.commands.clear();
        self.owned_payload_bytes = 0;
        self.next_order = 0;
        self.current_screen_clip = None;
        self.current_depth = 0.0;
        self.statistics = SceneStatistics::default();
    }

    /// Returns accepted commands in stable layer and insertion order.
    pub fn commands(&self) -> &[SceneCommand] {
        &self.commands
    }

    /// Returns the number of accepted render commands.
    pub fn command_count(&self) -> usize {
        self.commands.len()
    }

    /// Returns CPU allocation bytes currently owned by command and polyline storage.
    ///
    /// Unlike [`SceneStatistics::retained_bytes`], which is the budgeted payload
    /// of accepted commands, this includes spare `Vec` capacity retained for
    /// reuse after insertion or [`Scene::clear`]. Allocator bookkeeping is not
    /// included.
    pub fn allocation_bytes(&self) -> usize {
        self.commands
            .capacity()
            .saturating_mul(size_of::<SceneCommand>())
            .saturating_add(self.owned_payload_bytes)
    }

    pub(crate) fn preflight_command_storage(
        &self,
        additional_commands: usize,
        additional_owned_bytes: usize,
    ) -> Result<(), SceneError> {
        let Some(budget) = self.budget else {
            return Ok(());
        };
        let retained_bytes = self
            .statistics
            .retained_bytes
            .saturating_add(additional_commands.saturating_mul(size_of::<SceneCommand>()))
            .saturating_add(additional_owned_bytes);
        if retained_bytes > budget.max_retained_bytes {
            return Err(SceneError::BudgetExceeded {
                resource: SceneBudgetResource::RetainedBytes,
                limit: budget.max_retained_bytes,
                requested: retained_bytes,
            });
        }
        let required_len = self.commands.len().saturating_add(additional_commands);
        let owned_payload_bytes = self
            .owned_payload_bytes
            .saturating_add(additional_owned_bytes);
        let capacity = if required_len <= self.commands.capacity() {
            self.commands.capacity()
        } else {
            budgeted_command_capacity(
                budget,
                self.commands.capacity(),
                required_len,
                owned_payload_bytes,
            )?
        };
        validate_scene_allocation_budget(budget, capacity, owned_payload_bytes)
    }

    /// Returns the explicit work budget, or `None` for an unbounded scene.
    pub const fn budget(&self) -> Option<SceneBudget> {
        self.budget
    }

    /// Returns requested, accepted, rejected, and estimated scene work.
    pub const fn statistics(&self) -> SceneStatistics {
        self.statistics
    }

    pub(crate) const fn current_screen_clip(&self) -> Option<ScreenClipRect> {
        self.current_screen_clip
    }

    /// Replaces the screen-space clipping rectangle captured by new commands.
    ///
    /// The rectangle uses logical screen pixels with the origin at the top-left
    /// of the render surface. Existing commands keep the clip they captured when
    /// they were appended. `None` disables clipping for subsequent commands.
    /// The previous clip is returned so callers can restore explicit drawing
    /// state without tracking it separately. Invalid clips are rejected here,
    /// before they can affect a later command insertion.
    pub fn set_screen_clip(
        &mut self,
        screen_clip: Option<ScreenClipRect>,
    ) -> Result<Option<ScreenClipRect>, SceneError> {
        if screen_clip.is_some_and(|clip| !clip.is_valid()) {
            return Err(SceneError::InvalidScreenClip);
        }
        Ok(std::mem::replace(
            &mut self.current_screen_clip,
            screen_clip,
        ))
    }

    /// Appends commands from `draw` using a temporary screen-space clip.
    ///
    /// The rectangle uses logical screen pixels. Nested clips are intersected,
    /// so inner drawing cannot escape an outer clip. The previous clip is
    /// restored after `draw` returns.
    pub fn with_screen_clip<R>(
        &mut self,
        screen_clip: ScreenClipRect,
        draw: impl FnOnce(&mut Self) -> R,
    ) -> Result<R, SceneError> {
        if !screen_clip.is_valid() {
            return Err(SceneError::InvalidScreenClip);
        }
        let previous = self.current_screen_clip;
        let combined = match previous {
            Some(outer) => outer.intersection(screen_clip)?,
            None => screen_clip,
        };
        if !combined.is_valid() {
            return Err(SceneError::InvalidScreenClip);
        }
        self.current_screen_clip = Some(combined);
        let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
        self.current_screen_clip = previous;
        match result {
            Ok(result) => Ok(result),
            Err(payload) => resume_unwind(payload),
        }
    }

    /// Replaces the pseudo-depth captured by subsequently appended commands.
    ///
    /// Depth is measured in caller-defined units and converted through
    /// [`crate::Projection2d::depth_scale`]. It affects projection only, not draw
    /// order. Non-finite values return `false` and leave the current depth unchanged.
    pub fn set_depth(&mut self, depth: f32) -> bool {
        self.try_set_depth(depth).is_ok()
    }

    /// Replaces pseudo-depth and reports why invalid input was rejected.
    pub fn try_set_depth(&mut self, depth: f32) -> Result<(), SceneError> {
        if !depth.is_finite() {
            return Err(SceneError::NonFiniteDepth);
        }
        self.current_depth = depth;
        Ok(())
    }

    /// Appends commands with a temporary pseudo-depth value.
    ///
    /// The previous depth is restored after `draw` returns or unwinds. Non-finite
    /// depth returns an error without calling `draw`.
    pub fn with_depth<R>(
        &mut self,
        depth: f32,
        draw: impl FnOnce(&mut Self) -> R,
    ) -> Result<R, SceneError> {
        if !depth.is_finite() {
            return Err(SceneError::NonFiniteDepth);
        }

        let previous = self.current_depth;
        self.current_depth = depth;
        let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
        self.current_depth = previous;
        match result {
            Ok(result) => Ok(result),
            Err(payload) => resume_unwind(payload),
        }
    }

    /// Appends a valid command to the default layer.
    ///
    /// Returns `false` without changing commands, ordering, or retained
    /// allocation when the primitive is invalid. Requested/rejected diagnostic
    /// counters still advance for the attempted command.
    pub fn push(&mut self, command: DrawCommand) -> bool {
        self.try_push(command).is_ok()
    }

    /// Appends a command to the default layer with structured rejection diagnostics.
    pub fn try_push(&mut self, command: DrawCommand) -> Result<(), SceneError> {
        self.try_push_to_layer(Layer::DEFAULT, command)
    }

    /// Appends a command to a layer.
    ///
    /// Lower layer values are drawn first. Commands on the same layer preserve
    /// insertion order.
    /// Returns `false` without changing commands, ordering, or retained
    /// allocation when `command` is invalid. Requested/rejected diagnostic
    /// counters still advance for the attempted command.
    pub fn push_to_layer(&mut self, layer: Layer, command: DrawCommand) -> bool {
        self.try_push_to_layer(layer, command).is_ok()
    }

    /// Appends a command to a layer with structured rejection diagnostics.
    pub fn try_push_to_layer(
        &mut self,
        layer: Layer,
        command: DrawCommand,
    ) -> Result<(), SceneError> {
        let primitive = command.primitive();
        self.statistics.requested_commands = self.statistics.requested_commands.saturating_add(1);
        self.statistics.requested_by_primitive.increment(primitive);
        let result = self.try_push_to_layer_inner(layer, command);
        if result.is_err() {
            self.statistics.rejected_commands = self.statistics.rejected_commands.saturating_add(1);
            self.statistics.rejected_by_primitive.increment(primitive);
        }
        result
    }

    /// Atomically appends many commands and orders the combined scene once.
    ///
    /// This is the bounded high-volume construction path for adversarial or
    /// frequently alternating layers. Validation and budget accounting happen
    /// before the existing command list is changed. On failure, no command from
    /// the batch is retained; request and rejection diagnostics still advance.
    /// The resulting order is stable by layer and by batch insertion order.
    pub fn try_extend_to_layers(
        &mut self,
        commands: impl IntoIterator<Item = (Layer, DrawCommand)>,
    ) -> Result<(), SceneError> {
        let mut staged = Vec::new();
        let mut requested = self.statistics;
        let mut attempted = 0usize;
        let mut attempted_by_primitive = PrimitiveCommandCounts::default();
        let mut next_order = self.next_order;
        let existing_owned_payload_bytes = self.owned_payload_bytes;
        let mut staged_owned_payload_bytes = 0usize;

        for (layer, command) in commands {
            let primitive = command.primitive();
            attempted = attempted.saturating_add(1);
            attempted_by_primitive.increment(primitive);
            requested.requested_commands = requested.requested_commands.saturating_add(1);
            requested.requested_by_primitive.increment(primitive);
            if let Err(error) = command.validate() {
                self.record_batch_rejection(attempted, attempted_by_primitive);
                return Err(error);
            }
            if self
                .current_screen_clip
                .is_some_and(|screen_clip| !screen_clip.is_valid())
            {
                self.record_batch_rejection(attempted, attempted_by_primitive);
                return Err(SceneError::InvalidScreenClip);
            }

            requested = requested.with_command(&command);
            if let Some(budget) = self.budget
                && let Err(error) = validate_scene_budget(budget, requested)
            {
                self.record_batch_rejection(attempted, attempted_by_primitive);
                return Err(error);
            }
            let command_owned_payload_bytes = command.owned_allocation_bytes();
            let prospective_owned_payload_bytes = existing_owned_payload_bytes
                .saturating_add(staged_owned_payload_bytes)
                .saturating_add(command_owned_payload_bytes);
            if let Some(budget) = self.budget {
                let required_total = self
                    .commands
                    .len()
                    .saturating_add(staged.len())
                    .saturating_add(1);
                let final_capacity = if required_total <= self.commands.capacity() {
                    self.commands.capacity()
                } else {
                    match budgeted_command_capacity(
                        budget,
                        self.commands.capacity(),
                        required_total,
                        prospective_owned_payload_bytes,
                    ) {
                        Ok(capacity) => capacity,
                        Err(error) => {
                            self.record_batch_rejection(attempted, attempted_by_primitive);
                            return Err(error);
                        }
                    }
                };
                if let Err(error) = validate_scene_allocation_budget(
                    budget,
                    final_capacity,
                    prospective_owned_payload_bytes,
                ) {
                    self.record_batch_rejection(attempted, attempted_by_primitive);
                    return Err(error);
                }

                if staged.len() == staged.capacity() {
                    let staging_capacity = match budgeted_command_capacity(
                        budget,
                        staged.capacity(),
                        staged.len().saturating_add(1),
                        prospective_owned_payload_bytes,
                    ) {
                        Ok(capacity) => capacity,
                        Err(error) => {
                            self.record_batch_rejection(attempted, attempted_by_primitive);
                            return Err(error);
                        }
                    };
                    let mut replacement = Vec::new();
                    if replacement.try_reserve_exact(staging_capacity).is_err() {
                        self.record_batch_rejection(attempted, attempted_by_primitive);
                        return Err(SceneError::AllocationFailed {
                            requested_bytes: scene_allocation_bytes(
                                staging_capacity,
                                prospective_owned_payload_bytes,
                            ),
                        });
                    }
                    if let Err(error) = validate_scene_allocation_budget(
                        budget,
                        replacement.capacity(),
                        prospective_owned_payload_bytes,
                    ) {
                        self.record_batch_rejection(attempted, attempted_by_primitive);
                        return Err(error);
                    }
                    replacement.append(&mut staged);
                    staged = replacement;
                } else if let Err(error) = validate_scene_allocation_budget(
                    budget,
                    staged.capacity(),
                    prospective_owned_payload_bytes,
                ) {
                    self.record_batch_rejection(attempted, attempted_by_primitive);
                    return Err(error);
                }
            } else if staged.try_reserve(1).is_err() {
                self.record_batch_rejection(attempted, attempted_by_primitive);
                return Err(SceneError::AllocationFailed {
                    requested_bytes: command.retained_bytes(),
                });
            }
            staged.push(SceneCommand {
                layer,
                order: next_order,
                depth: self.current_depth,
                screen_clip: self.current_screen_clip,
                command,
            });
            staged_owned_payload_bytes =
                staged_owned_payload_bytes.saturating_add(command_owned_payload_bytes);
            next_order = next_order.saturating_add(1);
        }

        if staged.is_empty() {
            return Ok(());
        }
        let total = self.commands.len().saturating_add(staged.len());
        let owned_payload_bytes =
            existing_owned_payload_bytes.saturating_add(staged_owned_payload_bytes);
        let requested_capacity = if let Some(budget) = self.budget {
            if total <= self.commands.capacity() {
                self.commands.capacity()
            } else {
                match budgeted_command_capacity(
                    budget,
                    self.commands.capacity(),
                    total,
                    owned_payload_bytes,
                ) {
                    Ok(capacity) => capacity,
                    Err(error) => {
                        self.record_batch_rejection(attempted, attempted_by_primitive);
                        return Err(error);
                    }
                }
            }
        } else {
            total
        };
        if staged.capacity() < requested_capacity
            && staged
                .try_reserve_exact(requested_capacity.saturating_sub(staged.len()))
                .is_err()
        {
            self.record_batch_rejection(attempted, attempted_by_primitive);
            return Err(SceneError::AllocationFailed {
                requested_bytes: scene_allocation_bytes(requested_capacity, owned_payload_bytes),
            });
        }
        if let Some(budget) = self.budget
            && let Err(error) =
                validate_scene_allocation_budget(budget, staged.capacity(), owned_payload_bytes)
        {
            self.record_batch_rejection(attempted, attempted_by_primitive);
            return Err(error);
        }
        staged.append(&mut self.commands);
        staged.sort_unstable_by_key(|command| (command.layer, command.order));
        self.commands = staged;
        self.owned_payload_bytes = owned_payload_bytes;
        self.next_order = next_order;
        self.statistics = requested;
        Ok(())
    }

    fn record_batch_rejection(
        &mut self,
        command_count: usize,
        by_primitive: PrimitiveCommandCounts,
    ) {
        self.statistics.requested_commands = self
            .statistics
            .requested_commands
            .saturating_add(command_count);
        self.statistics.rejected_commands = self
            .statistics
            .rejected_commands
            .saturating_add(command_count);
        self.statistics.requested_by_primitive =
            self.statistics.requested_by_primitive.adding(by_primitive);
        self.statistics.rejected_by_primitive =
            self.statistics.rejected_by_primitive.adding(by_primitive);
    }

    pub(crate) fn record_external_rejection(&mut self, primitive: ScenePrimitive) {
        let mut counts = PrimitiveCommandCounts::default();
        counts.increment(primitive);
        self.record_batch_rejection(1, counts);
    }

    fn try_push_to_layer_inner(
        &mut self,
        layer: Layer,
        command: DrawCommand,
    ) -> Result<(), SceneError> {
        command.validate()?;
        if self
            .current_screen_clip
            .is_some_and(|screen_clip| !screen_clip.is_valid())
        {
            return Err(SceneError::InvalidScreenClip);
        }

        let command_retained_bytes = command.retained_bytes();
        let owned_payload_bytes = self
            .owned_payload_bytes
            .saturating_add(command.owned_allocation_bytes());
        let requested = self.statistics.with_command(&command);
        if let Some(budget) = self.budget {
            validate_scene_budget(budget, requested)?;
        }

        let replacement = if self.commands.len() == self.commands.capacity() {
            if let Some(budget) = self.budget {
                let required_len = self.commands.len().saturating_add(1);
                let capacity = budgeted_command_capacity(
                    budget,
                    self.commands.capacity(),
                    required_len,
                    owned_payload_bytes,
                )?;
                let mut replacement = Vec::new();
                replacement.try_reserve_exact(capacity).map_err(|_| {
                    SceneError::AllocationFailed {
                        requested_bytes: scene_allocation_bytes(capacity, owned_payload_bytes),
                    }
                })?;
                validate_scene_allocation_budget(
                    budget,
                    replacement.capacity(),
                    owned_payload_bytes,
                )?;
                Some(replacement)
            } else {
                self.commands
                    .try_reserve(1)
                    .map_err(|_| SceneError::AllocationFailed {
                        requested_bytes: command_retained_bytes,
                    })?;
                None
            }
        } else {
            if let Some(budget) = self.budget {
                validate_scene_allocation_budget(
                    budget,
                    self.commands.capacity(),
                    owned_payload_bytes,
                )?;
            }
            None
        };

        if let Some(mut replacement) = replacement {
            replacement.append(&mut self.commands);
            self.commands = replacement;
        }

        let order = self.next_order;
        let scene_command = SceneCommand {
            layer,
            order,
            depth: self.current_depth,
            screen_clip: self.current_screen_clip,
            command,
        };
        let position = self.commands.partition_point(|existing| {
            existing.layer < scene_command.layer
                || (existing.layer == scene_command.layer && existing.order <= scene_command.order)
        });
        self.commands.insert(position, scene_command);
        self.owned_payload_bytes = owned_payload_bytes;
        self.next_order = self.next_order.saturating_add(1);
        self.statistics = requested;
        Ok(())
    }

    /// Appends a circle in world coordinates.
    ///
    /// `radius` is in world units. Returns `false` for non-positive or non-finite
    /// radius, non-finite center, or invalid style values.
    pub fn circle(&mut self, center: Vec2, radius: f32, style: ShapeStyle) -> bool {
        self.try_circle(center, radius, style).is_ok()
    }

    /// Appends a circle and returns a structured validation error on rejection.
    pub fn try_circle(
        &mut self,
        center: Vec2,
        radius: f32,
        style: ShapeStyle,
    ) -> Result<(), SceneError> {
        self.try_circle_on_layer(Layer::DEFAULT, center, radius, style)
    }

    /// Appends a circle in world coordinates to a layer.
    ///
    /// `radius` is in world units. Returns `false` for non-positive or non-finite
    /// radius, non-finite center, or invalid style values.
    pub fn circle_on_layer(
        &mut self,
        layer: Layer,
        center: Vec2,
        radius: f32,
        style: ShapeStyle,
    ) -> bool {
        self.try_circle_on_layer(layer, center, radius, style)
            .is_ok()
    }

    /// Appends a circle to a layer with structured rejection diagnostics.
    pub fn try_circle_on_layer(
        &mut self,
        layer: Layer,
        center: Vec2,
        radius: f32,
        style: ShapeStyle,
    ) -> Result<(), SceneError> {
        self.try_push_to_layer(
            layer,
            DrawCommand::Circle(Circle {
                center,
                radius,
                style,
            }),
        )
    }

    /// Appends an axis-aligned rectangle in world coordinates.
    ///
    /// `corner_radius` is in world units and renderers clamp it to half the
    /// rectangle size. Invalid bounds, negative radius, and invalid styles return
    /// `false` without adding a command.
    pub fn rect(&mut self, rect: Rect, corner_radius: f32, style: ShapeStyle) -> bool {
        self.try_rect(rect, corner_radius, style).is_ok()
    }

    /// Appends a rectangle and returns a structured validation error on rejection.
    pub fn try_rect(
        &mut self,
        rect: Rect,
        corner_radius: f32,
        style: ShapeStyle,
    ) -> Result<(), SceneError> {
        self.try_rect_on_layer(Layer::DEFAULT, rect, corner_radius, style)
    }

    /// Appends an axis-aligned rectangle in world coordinates to a layer.
    ///
    /// `corner_radius` is in world units and renderers clamp it to half the
    /// rectangle size. Invalid bounds, negative radius, and invalid styles return
    /// `false` without adding a command.
    pub fn rect_on_layer(
        &mut self,
        layer: Layer,
        rect: Rect,
        corner_radius: f32,
        style: ShapeStyle,
    ) -> bool {
        self.try_rect_on_layer(layer, rect, corner_radius, style)
            .is_ok()
    }

    /// Appends a rectangle to a layer with structured rejection diagnostics.
    pub fn try_rect_on_layer(
        &mut self,
        layer: Layer,
        rect: Rect,
        corner_radius: f32,
        style: ShapeStyle,
    ) -> Result<(), SceneError> {
        self.try_push_to_layer(
            layer,
            DrawCommand::Rect(RectShape {
                rect,
                corner_radius,
                style,
            }),
        )
    }

    /// Appends a stroked line between world-space points.
    ///
    /// `width` is in logical screen pixels so line thickness stays readable while the
    /// camera zooms. Degenerate geometry and invalid width or color return
    /// `false`.
    pub fn line(&mut self, from: Vec2, to: Vec2, width: f32, color: Color) -> bool {
        self.try_line(from, to, width, color).is_ok()
    }

    /// Appends a line and returns a structured validation error on rejection.
    pub fn try_line(
        &mut self,
        from: Vec2,
        to: Vec2,
        width: f32,
        color: Color,
    ) -> Result<(), SceneError> {
        self.try_styled_line(from, to, StrokeStyle2d::new(width, color))
    }

    /// Appends a stroked line between world-space points to a layer.
    ///
    /// `width` is in logical screen pixels so line thickness stays readable while the
    /// camera zooms. Degenerate geometry and invalid width or color return
    /// `false`.
    pub fn line_on_layer(
        &mut self,
        layer: Layer,
        from: Vec2,
        to: Vec2,
        width: f32,
        color: Color,
    ) -> bool {
        self.try_line_on_layer(layer, from, to, width, color)
            .is_ok()
    }

    /// Appends a line to a layer with structured rejection diagnostics.
    pub fn try_line_on_layer(
        &mut self,
        layer: Layer,
        from: Vec2,
        to: Vec2,
        width: f32,
        color: Color,
    ) -> Result<(), SceneError> {
        self.try_styled_line_on_layer(layer, from, to, StrokeStyle2d::new(width, color))
    }

    /// Appends a line with explicit width units, caps, joins, dashes, and markers.
    pub fn styled_line(&mut self, from: Vec2, to: Vec2, style: StrokeStyle2d) -> bool {
        self.try_styled_line(from, to, style).is_ok()
    }

    /// Appends an explicitly styled line with structured rejection diagnostics.
    pub fn try_styled_line(
        &mut self,
        from: Vec2,
        to: Vec2,
        style: StrokeStyle2d,
    ) -> Result<(), SceneError> {
        self.try_styled_line_on_layer(Layer::DEFAULT, from, to, style)
    }

    /// Appends an explicitly styled line to a shared draw layer.
    pub fn styled_line_on_layer(
        &mut self,
        layer: Layer,
        from: Vec2,
        to: Vec2,
        style: StrokeStyle2d,
    ) -> bool {
        self.try_styled_line_on_layer(layer, from, to, style)
            .is_ok()
    }

    /// Appends an explicitly styled line to a layer with structured rejection.
    pub fn try_styled_line_on_layer(
        &mut self,
        layer: Layer,
        from: Vec2,
        to: Vec2,
        style: StrokeStyle2d,
    ) -> Result<(), SceneError> {
        self.try_push_to_layer(layer, DrawCommand::Line(Line { from, to, style }))
    }

    /// Appends connected stroked segments through world-space points.
    ///
    /// `width` is in logical screen pixels. Empty, single-point, non-finite,
    /// repeated-adjacent, or numerically ambiguous turn input returns `false`
    /// without adding a command; every consecutive segment must be drawable.
    pub fn polyline(&mut self, points: Vec<Vec2>, width: f32, color: Color) -> bool {
        self.try_polyline(points, width, color).is_ok()
    }

    /// Appends a polyline and returns a structured validation error on rejection.
    pub fn try_polyline(
        &mut self,
        points: Vec<Vec2>,
        width: f32,
        color: Color,
    ) -> Result<(), SceneError> {
        self.try_styled_polyline(points, StrokeStyle2d::new(width, color))
    }

    /// Appends connected stroked segments through world-space points to a layer.
    ///
    /// `width` is in logical screen pixels. Empty, single-point, non-finite,
    /// repeated-adjacent, or numerically ambiguous turn input returns `false`
    /// without adding a command; every consecutive segment must be drawable.
    pub fn polyline_on_layer(
        &mut self,
        layer: Layer,
        points: Vec<Vec2>,
        width: f32,
        color: Color,
    ) -> bool {
        self.try_polyline_on_layer(layer, points, width, color)
            .is_ok()
    }

    /// Appends a polyline to a layer with structured rejection diagnostics.
    pub fn try_polyline_on_layer(
        &mut self,
        layer: Layer,
        points: Vec<Vec2>,
        width: f32,
        color: Color,
    ) -> Result<(), SceneError> {
        self.try_styled_polyline_on_layer(layer, points, StrokeStyle2d::new(width, color))
    }

    /// Appends a connected path with explicit width, caps, joins, dashes, and markers.
    pub fn styled_polyline(&mut self, points: Vec<Vec2>, style: StrokeStyle2d) -> bool {
        self.try_styled_polyline(points, style).is_ok()
    }

    /// Appends an explicitly styled path with structured rejection diagnostics.
    pub fn try_styled_polyline(
        &mut self,
        points: Vec<Vec2>,
        style: StrokeStyle2d,
    ) -> Result<(), SceneError> {
        self.try_styled_polyline_on_layer(Layer::DEFAULT, points, style)
    }

    /// Appends an explicitly styled path to a shared draw layer.
    pub fn styled_polyline_on_layer(
        &mut self,
        layer: Layer,
        points: Vec<Vec2>,
        style: StrokeStyle2d,
    ) -> bool {
        self.try_styled_polyline_on_layer(layer, points, style)
            .is_ok()
    }

    /// Appends an explicitly styled path to a layer with structured rejection.
    pub fn try_styled_polyline_on_layer(
        &mut self,
        layer: Layer,
        points: Vec<Vec2>,
        style: StrokeStyle2d,
    ) -> Result<(), SceneError> {
        self.try_push_to_layer(layer, DrawCommand::Polyline(Polyline { points, style }))
    }
}

/// Draw layer used to order scene commands.
///
/// Lower values are drawn first. Higher values appear above lower layers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Layer {
    order: i32,
}

impl Layer {
    /// Default layer used by convenience drawing methods.
    pub const DEFAULT: Self = Self::new(0);
    /// Conventional layer for background guides or grids.
    pub const BACKGROUND: Self = Self::new(-100);
    /// Conventional layer for foreground annotations or overlays.
    pub const FOREGROUND: Self = Self::new(100);

    /// Builds a layer from an order value.
    pub const fn new(order: i32) -> Self {
        Self { order }
    }

    /// Returns the order value used for sorting.
    pub const fn order(self) -> i32 {
        self.order
    }
}

/// Axis-aligned clipping rectangle in logical screen pixels.
///
/// The coordinate origin is the top-left of the render surface and positive y
/// points downward. Constructors reject empty and non-finite bounds.
/// Renderers clamp valid clips to the target viewport.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScreenClipRect {
    rect: Rect,
}

impl ScreenClipRect {
    /// Builds a non-empty clip from two corners in logical screen pixels.
    pub fn new(min: LogicalScreenPosition, max: LogicalScreenPosition) -> Result<Self, SceneError> {
        Self::from_rect(Rect::new(min.to_vec2(), max.to_vec2()))
    }

    /// Builds a clip from its top-left corner and size in logical screen pixels.
    ///
    /// Negative size components are accepted and normalized before validation.
    pub fn from_min_size(
        min: LogicalScreenPosition,
        size: LogicalScreenVector,
    ) -> Result<Self, SceneError> {
        Self::from_rect(Rect::from_min_size(min.to_vec2(), size.to_vec2()))
    }

    fn from_rect(rect: Rect) -> Result<Self, SceneError> {
        let clip = Self { rect };
        clip.is_valid()
            .then_some(clip)
            .ok_or(SceneError::InvalidScreenClip)
    }

    #[cfg(feature = "wgpu")]
    pub(crate) fn rect(self) -> Rect {
        self.rect
    }

    /// Returns the normalized top-left corner in logical screen pixels.
    pub fn min(self) -> LogicalScreenPosition {
        LogicalScreenPosition::from_vec2(self.rect.normalized().min)
    }

    /// Returns the normalized bottom-right corner in logical screen pixels.
    pub fn max(self) -> LogicalScreenPosition {
        LogicalScreenPosition::from_vec2(self.rect.normalized().max)
    }

    /// Returns the overlap between two screen-space clips.
    ///
    /// Disjoint inputs return [`SceneError::InvalidScreenClip`].
    pub fn intersection(self, other: Self) -> Result<Self, SceneError> {
        let first = self.rect.normalized();
        let second = other.rect.normalized();
        let min = Vec2::new(first.min.x.max(second.min.x), first.min.y.max(second.min.y));
        let max = Vec2::new(first.max.x.min(second.max.x), first.max.y.min(second.max.y));

        Self::new(
            LogicalScreenPosition::from_vec2(min),
            LogicalScreenPosition::from_vec2(Vec2::new(max.x.max(min.x), max.y.max(min.y))),
        )
    }

    fn is_valid(self) -> bool {
        if !self.rect.min.is_finite() || !self.rect.max.is_finite() {
            return false;
        }

        let rect = self.rect.normalized();
        rect.width() > 0.0 && rect.height() > 0.0
    }
}

/// Draw command with layer and stable insertion order metadata.
#[derive(Debug, Clone)]
pub struct SceneCommand {
    /// Layer used to sort commands before rendering.
    layer: Layer,
    /// Monotonic insertion order within the scene.
    order: u64,
    /// Caller-defined pseudo-depth used by camera projection.
    depth: f32,
    /// Optional clipping rectangle in logical screen pixels.
    screen_clip: Option<ScreenClipRect>,
    /// Visual primitive to render.
    command: DrawCommand,
}

impl SceneCommand {
    /// Returns the layer used for stable scene ordering.
    pub fn layer(&self) -> Layer {
        self.layer
    }

    /// Returns the insertion order assigned by the scene.
    pub fn order(&self) -> u64 {
        self.order
    }

    /// Returns caller-defined pseudo-depth captured by this command.
    ///
    /// Depth affects camera projection only. Commands on one layer retain their
    /// insertion order regardless of depth.
    pub fn depth(&self) -> f32 {
        self.depth
    }

    /// Returns the optional clip captured when the command was appended.
    pub fn screen_clip(&self) -> Option<ScreenClipRect> {
        self.screen_clip
    }

    /// Returns the visual primitive stored by this command.
    pub fn command(&self) -> &DrawCommand {
        &self.command
    }
}

/// Renderable primitive command.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DrawCommand {
    /// Filled and/or stroked circle.
    Circle(Circle),
    /// Filled and/or stroked rectangle.
    Rect(RectShape),
    /// Single stroked segment.
    Line(Line),
    /// Connected stroked segments.
    Polyline(Polyline),
}

impl DrawCommand {
    /// Returns the primitive category used by diagnostics and budgets.
    pub const fn primitive(&self) -> ScenePrimitive {
        match self {
            Self::Circle(_) => ScenePrimitive::Circle,
            Self::Rect(_) => ScenePrimitive::Rect,
            Self::Line(_) => ScenePrimitive::Line,
            Self::Polyline(_) => ScenePrimitive::Polyline,
        }
    }

    /// Builds and validates a circle command for batch insertion.
    pub fn circle(center: Vec2, radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
        let command = Self::Circle(Circle {
            center,
            radius,
            style,
        });
        command.validate()?;
        Ok(command)
    }

    /// Builds and validates a rectangle command for batch insertion.
    pub fn rect(rect: Rect, corner_radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
        let command = Self::Rect(RectShape {
            rect,
            corner_radius,
            style,
        });
        command.validate()?;
        Ok(command)
    }

    /// Builds and validates a single line command for batch insertion.
    pub fn line(from: Vec2, to: Vec2, width: f32, color: Color) -> Result<Self, SceneError> {
        Self::styled_line(from, to, StrokeStyle2d::new(width, color))
    }

    /// Builds and validates an explicitly styled line command.
    pub fn styled_line(from: Vec2, to: Vec2, style: StrokeStyle2d) -> Result<Self, SceneError> {
        let command = Self::Line(Line { from, to, style });
        command.validate()?;
        Ok(command)
    }

    /// Builds and validates a connected polyline command for batch insertion.
    pub fn polyline(points: Vec<Vec2>, width: f32, color: Color) -> Result<Self, SceneError> {
        Self::styled_polyline(points, StrokeStyle2d::new(width, color))
    }

    /// Builds and validates an explicitly styled polyline command.
    pub fn styled_polyline(points: Vec<Vec2>, style: StrokeStyle2d) -> Result<Self, SceneError> {
        let command = Self::Polyline(Polyline { points, style });
        command.validate()?;
        Ok(command)
    }

    fn validate(&self) -> Result<(), SceneError> {
        match self {
            Self::Circle(circle) => {
                if !circle.center.is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
                }
                if !circle.radius.is_finite() || circle.radius <= 0.0 {
                    return Err(SceneError::InvalidDimension(ScenePrimitive::Circle));
                }
                if !(circle.center + Vec2::splat(circle.radius)).is_finite()
                    || !(circle.center - Vec2::splat(circle.radius)).is_finite()
                {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
                }
                circle.style.validate(ScenePrimitive::Circle)
            }
            Self::Rect(rectangle) => {
                let rect = rectangle.rect.normalized();
                if !rect.min.is_finite() || !rect.max.is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
                }
                let width = rect.width();
                let height = rect.height();
                if !width.is_finite() || !height.is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
                }
                if width <= 0.0
                    || height <= 0.0
                    || !rectangle.corner_radius.is_finite()
                    || rectangle.corner_radius < 0.0
                {
                    return Err(SceneError::InvalidDimension(ScenePrimitive::Rect));
                }
                rectangle.style.validate(ScenePrimitive::Rect)
            }
            Self::Line(line) => {
                if !line.from.is_finite() || !line.to.is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
                }
                if !(line.to - line.from).is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
                }
                if !drawable_segment(line.from, line.to) {
                    return Err(SceneError::DegenerateGeometry(ScenePrimitive::Line));
                }
                if !line.style.is_valid() {
                    return Err(SceneError::InvalidStroke(ScenePrimitive::Line));
                }
                validate_stroke_path(&[line.from, line.to], line.style, ScenePrimitive::Line)?;
                Ok(())
            }
            Self::Polyline(polyline) => {
                validate_styled_polyline(polyline.points.iter().copied(), polyline.style)?;
                Ok(())
            }
        }
    }

    fn retained_point_count(&self) -> usize {
        match self {
            Self::Polyline(polyline) => polyline.points.len(),
            Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
        }
    }

    fn retained_bytes(&self) -> usize {
        size_of::<SceneCommand>().saturating_add(self.owned_allocation_bytes())
    }

    fn owned_allocation_bytes(&self) -> usize {
        match self {
            Self::Polyline(polyline) => {
                polyline.points.capacity().saturating_mul(size_of::<Vec2>())
            }
            Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
        }
    }

    fn estimated_tessellated_vertices(&self) -> usize {
        match self {
            Self::Circle(circle) => {
                let fill_vertices = CIRCLE_SEGMENTS * 3;
                let stroke_vertices = CIRCLE_SEGMENTS * 6;
                let style = circle.style;
                usize::from(style.fill.is_some()) * fill_vertices
                    + usize::from(style.stroke.is_some()) * stroke_vertices
                    + style.shadow.map_or(0, |shadow| {
                        fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
                    })
            }
            Self::Rect(rectangle) => {
                let rect = rectangle.rect.normalized();
                let radius = rectangle
                    .corner_radius
                    .max(0.0)
                    .min(rect.width().abs() * 0.5)
                    .min(rect.height().abs() * 0.5);
                let boundary_segments = if radius <= 0.0 {
                    4
                } else {
                    4 * (CORNER_SEGMENTS + 1)
                };
                let fill_vertices = boundary_segments * 3;
                let stroke_vertices = boundary_segments * 6;
                let style = rectangle.style;
                usize::from(style.fill.is_some()) * fill_vertices
                    + usize::from(style.stroke.is_some()) * stroke_vertices
                    + style.shadow.map_or(0, |shadow| {
                        fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
                    })
            }
            Self::Line(line) => estimate_stroke_vertices(&[line.from, line.to], line.style),
            Self::Polyline(polyline) => estimate_stroke_vertices(&polyline.points, polyline.style),
        }
    }
}

fn validate_stroke_path(
    points: &[Vec2],
    style: StrokeStyle2d,
    primitive: ScenePrimitive,
) -> Result<(), SceneError> {
    validate_stroke_path_iter(points.iter().copied(), style, primitive)
}

fn validate_stroke_path_iter<I>(
    points: I,
    style: StrokeStyle2d,
    primitive: ScenePrimitive,
) -> Result<(), SceneError>
where
    I: Iterator<Item = Vec2> + Clone,
{
    let maximum_offset = f64::from(style.stroke.width) * 0.5 * f64::from(style.miter_limit);
    if !maximum_offset.is_finite() || maximum_offset > f64::from(f32::MAX) {
        return Err(SceneError::InvalidStroke(primitive));
    }
    if style.width_mode == StrokeWidthMode2d::WorldUnits {
        let extent = Vec2::splat(maximum_offset as f32);
        if points
            .clone()
            .any(|point| !(point + extent).is_finite() || !(point - extent).is_finite())
        {
            return Err(SceneError::NonFiniteGeometry(primitive));
        }
    }
    if let Some(dash) = style.dash {
        let required = dash_subsegment_count_iter(points, dash, Some(dash.max_subsegments))
            .ok_or(SceneError::UnrepresentableStrokePattern(primitive))?;
        if required > dash.max_subsegments {
            return Err(SceneError::StrokeExpansionLimitExceeded {
                primitive,
                limit: dash.max_subsegments,
                required,
            });
        }
    }
    Ok(())
}

/// Validates caller-owned polyline coordinates without allocating or copying them.
///
/// Screen-space adapters use this before reserving their converted point buffer,
/// so an invalid leading point or segment cannot force work proportional to the
/// rest of a caller-sized slice.
pub(crate) fn validate_polyline_geometry<I>(points: I) -> Result<(), SceneError>
where
    I: Iterator<Item = Vec2> + Clone,
{
    let primitive = ScenePrimitive::Polyline;
    if !points.clone().all(|point| point.is_finite()) {
        return Err(SceneError::NonFiniteGeometry(primitive));
    }

    let mut deltas = points.clone();
    let Some(mut previous) = deltas.next() else {
        return Err(SceneError::DegenerateGeometry(primitive));
    };
    let mut segment_count = 0usize;
    for point in deltas {
        let delta = point - previous;
        if !delta.is_finite() {
            return Err(SceneError::NonFiniteGeometry(primitive));
        }
        previous = point;
        segment_count = segment_count.saturating_add(1);
    }
    if segment_count == 0 {
        return Err(SceneError::DegenerateGeometry(primitive));
    }

    let mut segments = points.clone();
    let mut previous = segments
        .next()
        .expect("a non-empty path was established above");
    for point in segments {
        if !drawable_segment(previous, point) {
            return Err(SceneError::DegenerateGeometry(primitive));
        }
        previous = point;
    }

    let mut turns = points;
    let mut first = turns
        .next()
        .expect("a drawable segment was established above");
    let mut second = turns
        .next()
        .expect("a drawable segment was established above");
    for (index, third) in turns.enumerate() {
        let incoming = second - first;
        let outgoing = third - second;
        let cross = f64::from(incoming.x) * f64::from(outgoing.y)
            - f64::from(incoming.y) * f64::from(outgoing.x);
        let dot = f64::from(incoming.x) * f64::from(outgoing.x)
            + f64::from(incoming.y) * f64::from(outgoing.y);
        let direction_product = f64::from(incoming.x).hypot(f64::from(incoming.y))
            * f64::from(outgoing.x).hypot(f64::from(outgoing.y));
        let normalized_cross = cross / direction_product;
        if normalized_cross.abs() <= MIN_STROKE_TURN_SINE && (dot < 0.0 || normalized_cross != 0.0)
        {
            return Err(SceneError::DegenerateStrokeTurn {
                primitive,
                vertex_index: index + 1,
            });
        }
        first = second;
        second = third;
    }
    Ok(())
}

/// Validates a complete styled polyline without taking ownership of its points.
pub(crate) fn validate_styled_polyline<I>(points: I, style: StrokeStyle2d) -> Result<(), SceneError>
where
    I: Iterator<Item = Vec2> + Clone,
{
    validate_polyline_geometry(points.clone())?;
    if !style.is_valid() {
        return Err(SceneError::InvalidStroke(ScenePrimitive::Polyline));
    }
    validate_stroke_path_iter(points, style, ScenePrimitive::Polyline)
}

fn estimate_stroke_vertices(points: &[Vec2], style: StrokeStyle2d) -> usize {
    let segment_count = points
        .windows(2)
        .filter(|pair| drawable_segment(pair[0], pair[1]))
        .count();
    if segment_count == 0 {
        return 0;
    }
    let body_count = style.dash.map_or(segment_count, |dash| {
        dash_subsegment_count(points, dash, None)
            .expect("accepted dash paths have representable subsegments")
    });
    // A visible dash may continue across every geometric vertex. Counting all
    // possible joins is conservative without expanding the pattern twice.
    let join_count = segment_count.saturating_sub(1);
    let cap_count = if style.dash.is_some() {
        body_count.saturating_mul(2)
    } else {
        2
    };
    let cap_vertices = match style.cap {
        StrokeCap2d::Round => cap_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
        StrokeCap2d::Butt | StrokeCap2d::Square => 0,
    };
    let join_vertices = match style.join {
        StrokeJoin2d::Bevel => join_count.saturating_mul(6),
        StrokeJoin2d::Miter => join_count.saturating_mul(12),
        // Logical round joins carry one candidate fan for each possible screen
        // orientation; the shader collapses the inactive fan to zero area.
        StrokeJoin2d::Round if style.width_mode == StrokeWidthMode2d::LogicalPixels => {
            join_count.saturating_mul(ROUND_CAP_SEGMENTS * 6)
        }
        StrokeJoin2d::Round => join_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
    };
    let marker_vertices = (usize::from(style.start_marker.is_some())
        + usize::from(style.end_marker.is_some()))
    .saturating_mul(3);
    body_count
        .saturating_mul(6)
        .saturating_add(cap_vertices)
        .saturating_add(join_vertices)
        .saturating_add(marker_vertices)
}

fn dash_subsegment_count(
    points: &[Vec2],
    dash: StrokeDashPattern2d,
    stop_after: Option<usize>,
) -> Option<usize> {
    dash_subsegment_count_iter(points.iter().copied(), dash, stop_after)
}

fn dash_subsegment_count_iter<I>(
    points: I,
    dash: StrokeDashPattern2d,
    stop_after: Option<usize>,
) -> Option<usize>
where
    I: Iterator<Item = Vec2>,
{
    let lengths = dash.lengths();
    let total: f64 = lengths.iter().map(|length| f64::from(*length)).sum();
    let mut phase = f64::from(dash.phase).rem_euclid(total);
    let mut pattern_index = 0usize;
    while phase >= f64::from(lengths[pattern_index]) {
        phase -= f64::from(lengths[pattern_index]);
        pattern_index = (pattern_index + 1) % lengths.len();
    }
    let mut pattern_remaining = f64::from(lengths[pattern_index]) - phase;
    let mut count = 0usize;

    let mut points = points;
    let mut previous = points.next()?;
    for point in points {
        let delta = point - previous;
        let segment_length = f64::from(delta.x).hypot(f64::from(delta.y));
        let mut segment_remaining = segment_length;
        while segment_remaining > 0.0 {
            let consumed = segment_remaining.min(pattern_remaining);
            if pattern_index.is_multiple_of(2) && consumed > 0.0 {
                count = count.saturating_add(1);
                if stop_after.is_some_and(|limit| count > limit) {
                    return Some(count);
                }
            }
            let next_remaining = segment_remaining - consumed;
            if next_remaining >= segment_remaining {
                return None;
            }
            let amount_start = 1.0 - segment_remaining / segment_length;
            let amount_end = 1.0 - next_remaining / segment_length;
            if dash_segment_point(previous, point, amount_start)
                == dash_segment_point(previous, point, amount_end)
            {
                return None;
            }
            segment_remaining = next_remaining;
            pattern_remaining -= consumed;
            if pattern_remaining <= 0.0 {
                pattern_index = (pattern_index + 1) % lengths.len();
                pattern_remaining = f64::from(lengths[pattern_index]);
            }
        }
        previous = point;
    }
    Some(count)
}

fn dash_segment_point(from: Vec2, to: Vec2, amount: f64) -> Vec2 {
    Vec2::new(
        (f64::from(from.x) * (1.0 - amount) + f64::from(to.x) * amount) as f32,
        (f64::from(from.y) * (1.0 - amount) + f64::from(to.y) * amount) as f32,
    )
}

fn validate_scene_budget(
    budget: SceneBudget,
    requested: SceneStatistics,
) -> Result<(), SceneError> {
    let limits = [
        (
            SceneBudgetResource::Commands,
            budget.max_commands,
            requested.accepted_commands,
        ),
        (
            SceneBudgetResource::Points,
            budget.max_points,
            requested.retained_points,
        ),
        (
            SceneBudgetResource::TessellatedVertices,
            budget.max_tessellated_vertices,
            requested.estimated_tessellated_vertices,
        ),
        (
            SceneBudgetResource::RetainedBytes,
            budget.max_retained_bytes,
            requested.retained_bytes,
        ),
        // Actual allocation capacity is validated transactionally at the
        // insertion boundary, once the prospective Vec capacity is known.
        (
            SceneBudgetResource::UploadBytes,
            budget.max_upload_bytes,
            requested.estimated_upload_bytes,
        ),
        (
            SceneBudgetResource::DrawBatches,
            budget.max_draw_batches,
            requested.estimated_draw_batches,
        ),
    ];
    for (resource, limit, requested) in limits {
        if requested > limit {
            return Err(SceneError::BudgetExceeded {
                resource,
                limit,
                requested,
            });
        }
    }
    Ok(())
}

fn scene_allocation_bytes(command_capacity: usize, owned_payload_bytes: usize) -> usize {
    command_capacity
        .saturating_mul(size_of::<SceneCommand>())
        .saturating_add(owned_payload_bytes)
}

fn validate_scene_allocation_budget(
    budget: SceneBudget,
    command_capacity: usize,
    owned_payload_bytes: usize,
) -> Result<(), SceneError> {
    let requested = scene_allocation_bytes(command_capacity, owned_payload_bytes);
    if requested > budget.max_allocation_bytes {
        return Err(SceneError::BudgetExceeded {
            resource: SceneBudgetResource::AllocationBytes,
            limit: budget.max_allocation_bytes,
            requested,
        });
    }
    Ok(())
}

fn budgeted_command_capacity(
    budget: SceneBudget,
    current_capacity: usize,
    required_len: usize,
    owned_payload_bytes: usize,
) -> Result<usize, SceneError> {
    let available = budget
        .max_allocation_bytes
        .saturating_sub(owned_payload_bytes);
    let maximum_capacity = available / size_of::<SceneCommand>();
    if required_len > maximum_capacity {
        return Err(SceneError::BudgetExceeded {
            resource: SceneBudgetResource::AllocationBytes,
            limit: budget.max_allocation_bytes,
            requested: scene_allocation_bytes(required_len, owned_payload_bytes),
        });
    }
    Ok(current_capacity
        .max(1)
        .saturating_mul(2)
        .max(required_len)
        .min(maximum_capacity))
}

fn drawable_segment(from: Vec2, to: Vec2) -> bool {
    let delta = to - from;
    delta.is_finite() && (delta.x != 0.0 || delta.y != 0.0)
}

/// Circle primitive in world coordinates.
#[derive(Debug, Clone)]
pub struct Circle {
    center: Vec2,
    radius: f32,
    style: ShapeStyle,
}

impl Circle {
    /// Returns the center in world coordinates.
    pub const fn center(&self) -> Vec2 {
        self.center
    }
    /// Returns the radius in world units.
    pub const fn radius(&self) -> f32 {
        self.radius
    }
    /// Returns fill, stroke, and shadow styling.
    pub const fn style(&self) -> ShapeStyle {
        self.style
    }
}

/// Axis-aligned rectangle primitive in world coordinates.
#[derive(Debug, Clone)]
pub struct RectShape {
    rect: Rect,
    corner_radius: f32,
    style: ShapeStyle,
}

impl RectShape {
    /// Returns rectangle bounds in world coordinates.
    pub const fn rect(&self) -> Rect {
        self.rect
    }
    /// Returns corner radius in world units.
    pub const fn corner_radius(&self) -> f32 {
        self.corner_radius
    }
    /// Returns fill, stroke, and shadow styling.
    pub const fn style(&self) -> ShapeStyle {
        self.style
    }
}

/// Stroked line primitive in world coordinates.
#[derive(Debug, Clone)]
pub struct Line {
    from: Vec2,
    to: Vec2,
    style: StrokeStyle2d,
}

impl Line {
    /// Returns the start point in world coordinates.
    pub const fn from(&self) -> Vec2 {
        self.from
    }
    /// Returns the end point in world coordinates.
    pub const fn to(&self) -> Vec2 {
        self.to
    }
    /// Returns color and scalar width; inspect [`Self::stroke_style`] for units.
    pub const fn stroke(&self) -> Stroke {
        self.style.stroke
    }
    /// Returns the complete cap, join, dash, marker, and width-mode style.
    pub const fn stroke_style(&self) -> StrokeStyle2d {
        self.style
    }
}

/// Connected line-strip primitive in world coordinates.
#[derive(Debug, Clone)]
pub struct Polyline {
    points: Vec<Vec2>,
    style: StrokeStyle2d,
}

impl Polyline {
    /// Returns connected points in world coordinates.
    pub fn points(&self) -> &[Vec2] {
        &self.points
    }
    /// Returns color and scalar width; inspect [`Self::stroke_style`] for units.
    pub const fn stroke(&self) -> Stroke {
        self.style.stroke
    }
    /// Returns the complete cap, join, dash, marker, and width-mode style.
    pub const fn stroke_style(&self) -> StrokeStyle2d {
        self.style
    }
}

/// Coordinate space used by a line or polyline stroke width.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeWidthMode2d {
    /// Width remains constant in logical screen pixels while the camera zooms.
    LogicalPixels,
    /// Width is measured in the same world units as the path coordinates.
    WorldUnits,
}

/// Presentation used at an open line or dash endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeCap2d {
    /// Stop exactly at the endpoint.
    Butt,
    /// Extend by half the stroke width beyond the endpoint.
    Square,
    /// Add a semicircular endpoint.
    Round,
}

/// Presentation used where two visible polyline segments meet.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeJoin2d {
    /// Connect the two segment corners directly.
    Bevel,
    /// Fill the corner with a circular join.
    Round,
    /// Extend corner edges to their intersection, bounded by the style's
    /// miter limit and falling back to a bevel beyond it.
    Miter,
}

/// Fixed-size, allocation-free dash pattern in source path-coordinate units.
///
/// Values alternate visible and hidden lengths, beginning with a visible
/// length. The element count must be even and at most eight. `phase` advances
/// into the repeating pattern in the same path units. `max_subsegments` is a
/// hard limit on visible pieces generated for one command.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeDashPattern2d {
    lengths: [f32; MAX_DASH_ELEMENTS],
    length_count: u8,
    phase: f32,
    max_subsegments: usize,
}

impl StrokeDashPattern2d {
    /// Builds a bounded alternating visible/hidden dash pattern.
    pub fn new(
        lengths: &[f32],
        phase: f32,
        max_subsegments: usize,
    ) -> Result<Self, StrokeStyleError> {
        if lengths.len() < 2
            || lengths.len() > MAX_DASH_ELEMENTS
            || !lengths.len().is_multiple_of(2)
        {
            return Err(StrokeStyleError::InvalidDashElementCount);
        }
        if lengths
            .iter()
            .any(|length| !length.is_finite() || *length <= 0.0)
        {
            return Err(StrokeStyleError::InvalidDashLength);
        }
        if !phase.is_finite() {
            return Err(StrokeStyleError::InvalidDashPhase);
        }
        if max_subsegments == 0 || max_subsegments > MAX_STROKE_DASH_SUBSEGMENTS {
            return Err(StrokeStyleError::InvalidDashExpansionLimit);
        }
        let mut stored = [0.0; MAX_DASH_ELEMENTS];
        stored[..lengths.len()].copy_from_slice(lengths);
        Ok(Self {
            lengths: stored,
            length_count: lengths.len() as u8,
            phase,
            max_subsegments,
        })
    }

    /// Returns the alternating visible/hidden lengths in path units.
    pub fn lengths(&self) -> &[f32] {
        &self.lengths[..usize::from(self.length_count)]
    }

    /// Returns the repeating-pattern phase in path units.
    pub const fn phase(self) -> f32 {
        self.phase
    }

    /// Returns the hard visible-subsegment expansion limit.
    pub const fn max_subsegments(self) -> usize {
        self.max_subsegments
    }
}

/// Reusable arrow marker definition for a line endpoint.
///
/// Marker dimensions are logical pixels even when the line body uses a world
/// width, keeping scientific annotations readable under camera zoom. A marked
/// endpoint ignores the ordinary cap: the body ends with a butt boundary at
/// the path endpoint, which is also the marker base. The filled triangle grows
/// outward from the path, so markers remain interior-disjoint from arbitrarily
/// short, dashed, or camera-scaled terminal segments.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeMarker2d {
    length: LogicalPixels,
    width: LogicalPixels,
}

impl StrokeMarker2d {
    /// Builds a filled triangular arrow marker.
    pub const fn arrow(length: LogicalPixels, width: LogicalPixels) -> Self {
        Self { length, width }
    }

    /// Returns marker length along the endpoint tangent.
    pub const fn length(self) -> LogicalPixels {
        self.length
    }

    /// Returns full marker width perpendicular to the endpoint tangent.
    pub const fn width(self) -> LogicalPixels {
        self.width
    }
}

/// Complete bounded styling for open 2D lines and polylines.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeStyle2d {
    stroke: Stroke,
    width_mode: StrokeWidthMode2d,
    cap: StrokeCap2d,
    join: StrokeJoin2d,
    miter_limit: f32,
    dash: Option<StrokeDashPattern2d>,
    start_marker: Option<StrokeMarker2d>,
    end_marker: Option<StrokeMarker2d>,
}

impl StrokeStyle2d {
    /// Builds the legacy logical-pixel round-cap joined-strip style.
    pub const fn new(width: f32, color: Color) -> Self {
        Self {
            stroke: Stroke::new(width, color),
            width_mode: StrokeWidthMode2d::LogicalPixels,
            cap: StrokeCap2d::Round,
            join: StrokeJoin2d::Miter,
            miter_limit: MAX_MITER_LIMIT,
            dash: None,
            start_marker: None,
            end_marker: None,
        }
    }

    /// Builds a validated logical-pixel-width style.
    pub const fn logical(width: LogicalPixels, color: Color) -> Self {
        Self::new(width.get(), color)
    }

    /// Builds a validated world-unit-width style.
    pub const fn world(width: WorldLength, color: Color) -> Self {
        let mut style = Self::new(width.get(), color);
        style.width_mode = StrokeWidthMode2d::WorldUnits;
        style
    }

    /// Selects the open endpoint presentation.
    pub const fn with_cap(mut self, cap: StrokeCap2d) -> Self {
        self.cap = cap;
        self
    }

    /// Selects the connected-segment presentation.
    pub const fn with_join(mut self, join: StrokeJoin2d) -> Self {
        self.join = join;
        self
    }

    /// Sets the miter-length multiple in `1.0..=1000.0`.
    pub fn with_miter_limit(mut self, limit: f32) -> Result<Self, StrokeStyleError> {
        if !limit.is_finite() || !(1.0..=MAX_MITER_LIMIT).contains(&limit) {
            return Err(StrokeStyleError::InvalidMiterLimit);
        }
        self.miter_limit = limit;
        Ok(self)
    }

    /// Applies an allocation-free bounded dash pattern.
    pub const fn with_dash_pattern(mut self, dash: StrokeDashPattern2d) -> Self {
        self.dash = Some(dash);
        self
    }

    /// Adds an outward-pointing triangular marker based at the first path point.
    pub const fn with_start_marker(mut self, marker: StrokeMarker2d) -> Self {
        self.start_marker = Some(marker);
        self
    }

    /// Adds an outward-pointing triangular marker based at the last path point.
    pub const fn with_end_marker(mut self, marker: StrokeMarker2d) -> Self {
        self.end_marker = Some(marker);
        self
    }

    /// Returns color and scalar width.
    pub const fn stroke(self) -> Stroke {
        self.stroke
    }

    /// Returns whether width is logical-screen or world-space.
    pub const fn width_mode(self) -> StrokeWidthMode2d {
        self.width_mode
    }

    /// Returns endpoint presentation.
    pub const fn cap(self) -> StrokeCap2d {
        self.cap
    }

    /// Returns connected-segment presentation.
    pub const fn join(self) -> StrokeJoin2d {
        self.join
    }

    /// Returns the bounded miter multiple.
    pub const fn miter_limit(self) -> f32 {
        self.miter_limit
    }

    /// Returns the optional bounded dash pattern.
    pub const fn dash_pattern(self) -> Option<StrokeDashPattern2d> {
        self.dash
    }

    /// Returns the optional first-endpoint marker.
    pub const fn start_marker(self) -> Option<StrokeMarker2d> {
        self.start_marker
    }

    /// Returns the optional last-endpoint marker.
    pub const fn end_marker(self) -> Option<StrokeMarker2d> {
        self.end_marker
    }

    fn is_valid(self) -> bool {
        self.stroke.is_valid()
            && self.miter_limit.is_finite()
            && (1.0..=MAX_MITER_LIMIT).contains(&self.miter_limit)
    }
}

/// Invalid bounded line-style configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeStyleError {
    /// Dash patterns require an even count from two through eight.
    InvalidDashElementCount,
    /// Every dash and gap length must be positive and finite.
    InvalidDashLength,
    /// Dash phase must be finite.
    InvalidDashPhase,
    /// Dash expansion limit must be in `1..=1_000_000`.
    InvalidDashExpansionLimit,
    /// Miter limit must be finite and in `1.0..=1000.0`.
    InvalidMiterLimit,
}

impl fmt::Display for StrokeStyleError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "invalid bounded 2D stroke style: {self:?}")
    }
}

impl Error for StrokeStyleError {}

/// Fill, stroke, and shadow styling for solid primitives.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ShapeStyle {
    fill: Option<Fill>,
    stroke: Option<Stroke>,
    shadow: Option<Shadow>,
}

impl ShapeStyle {
    /// Builds explicit fill, stroke, and shadow choices.
    pub const fn new(fill: Option<Fill>, stroke: Option<Stroke>, shadow: Option<Shadow>) -> Self {
        Self {
            fill,
            stroke,
            shadow,
        }
    }

    /// Returns fill paint, if any.
    pub const fn fill(self) -> Option<Fill> {
        self.fill
    }
    /// Returns outline stroke, if any.
    pub const fn stroke(self) -> Option<Stroke> {
        self.stroke
    }
    /// Returns shadow styling, if any.
    pub const fn shadow(self) -> Option<Shadow> {
        self.shadow
    }
    /// Creates a style with fill color only.
    pub fn filled(color: Color) -> Self {
        Self::filled_with(Fill::Solid(color))
    }

    /// Creates a style with fill paint only.
    pub fn filled_with(fill: Fill) -> Self {
        Self {
            fill: Some(fill),
            stroke: None,
            shadow: None,
        }
    }

    /// Creates a style with stroke only.
    ///
    /// `width` is in logical screen pixels.
    pub fn stroked(width: f32, color: Color) -> Self {
        Self {
            fill: None,
            stroke: Some(Stroke { width, color }),
            shadow: None,
        }
    }

    /// Creates a style with both fill and stroke.
    ///
    /// `stroke_width` is in logical screen pixels.
    pub fn fill_stroke(fill: Color, stroke_width: f32, stroke: Color) -> Self {
        Self::fill_stroke_with(Fill::Solid(fill), stroke_width, stroke)
    }

    /// Creates a style with both fill paint and stroke.
    ///
    /// `stroke_width` is in logical screen pixels.
    pub fn fill_stroke_with(fill: Fill, stroke_width: f32, stroke: Color) -> Self {
        Self {
            fill: Some(fill),
            stroke: Some(Stroke {
                width: stroke_width,
                color: stroke,
            }),
            shadow: None,
        }
    }

    /// Adds a shadow to the style.
    pub fn with_shadow(mut self, shadow: Shadow) -> Self {
        self.shadow = Some(shadow);
        self
    }

    fn validate(self, primitive: ScenePrimitive) -> Result<(), SceneError> {
        if self.fill.is_none() && self.stroke.is_none() && self.shadow.is_none() {
            return Err(SceneError::MissingStyle(primitive));
        }
        if self.fill.is_some_and(|fill| !fill.is_valid()) {
            return Err(SceneError::InvalidFill(primitive));
        }
        if self.stroke.is_some_and(|stroke| !stroke.is_valid()) {
            return Err(SceneError::InvalidStroke(primitive));
        }
        if self.shadow.is_some_and(|shadow| !shadow.is_valid()) {
            return Err(SceneError::InvalidShadow(primitive));
        }
        Ok(())
    }
}

/// Paint used to fill a shape.
///
/// Gradient coordinates are in world units. Renderers may approximate gradients
/// per vertex until a more advanced shader path exists.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Fill {
    /// Single color over the whole shape.
    Solid(Color),
    /// Color interpolation along a world-space axis.
    LinearGradient(LinearGradient),
    /// Color interpolation outward from a world-space center.
    RadialGradient(RadialGradient),
}

impl Fill {
    /// Returns the color at a world-space point.
    ///
    /// Degenerate gradients fall back to their end color rather than producing
    /// NaN.
    pub fn color_at(self, world: Vec2) -> Color {
        self.color_at_with_offset(world, Vec2::ZERO)
    }

    pub(crate) fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
        match self {
            Self::Solid(color) => color,
            Self::LinearGradient(gradient) => {
                gradient.color_at_with_offset(world_base, world_offset)
            }
            Self::RadialGradient(gradient) => {
                gradient.color_at_with_offset(world_base, world_offset)
            }
        }
    }

    fn is_valid(self) -> bool {
        match self {
            Self::Solid(color) => color.is_normalized(),
            Self::LinearGradient(gradient) => gradient.is_valid(),
            Self::RadialGradient(gradient) => gradient.is_valid(),
        }
    }
}

impl From<Color> for Fill {
    fn from(color: Color) -> Self {
        Self::Solid(color)
    }
}

/// Linear color gradient in world coordinates.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinearGradient {
    start: Vec2,
    end: Vec2,
    start_color: Color,
    end_color: Color,
}

impl LinearGradient {
    /// Builds a linear gradient between two world-space points.
    pub fn new(start: Vec2, end: Vec2, start_color: Color, end_color: Color) -> Self {
        Self {
            start,
            end,
            start_color,
            end_color,
        }
    }

    /// Returns the world-space gradient start.
    pub const fn start(self) -> Vec2 {
        self.start
    }
    /// Returns the world-space gradient end.
    pub const fn end(self) -> Vec2 {
        self.end
    }
    /// Returns the color at the start.
    pub const fn start_color(self) -> Color {
        self.start_color
    }
    /// Returns the color at the end.
    pub const fn end_color(self) -> Color {
        self.end_color
    }

    /// Samples the gradient at a world-space point.
    pub fn color_at(self, world: Vec2) -> Color {
        self.color_at_with_offset(world, Vec2::ZERO)
    }

    fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
        if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
            return self.end_color.clamp();
        }

        let axis_x = f64::from(self.end.x) - f64::from(self.start.x);
        let axis_y = f64::from(self.end.y) - f64::from(self.start.y);
        let relative_x =
            f64::from(world_base.x) - f64::from(self.start.x) + f64::from(world_offset.x);
        let relative_y =
            f64::from(world_base.y) - f64::from(self.start.y) + f64::from(world_offset.y);
        let axis_length_squared = axis_x * axis_x + axis_y * axis_y;
        let amount = ((relative_x * axis_x + relative_y * axis_y) / axis_length_squared)
            .clamp(0.0, 1.0) as f32;
        self.start_color.interpolate(self.end_color, amount)
    }

    fn is_valid(self) -> bool {
        self.start.is_finite()
            && self.end.is_finite()
            && self.start_color.is_normalized()
            && self.end_color.is_normalized()
            && self.start != self.end
    }
}

/// Radial color gradient in world coordinates.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RadialGradient {
    /// Center point in world coordinates.
    center: Vec2,
    /// Radius where `inner_color` is reached, in world units.
    inner_radius: f32,
    /// Radius where `outer_color` is reached, in world units.
    outer_radius: f32,
    /// Color at or inside `inner_radius`.
    inner_color: Color,
    /// Color at or outside `outer_radius`.
    outer_color: Color,
}

impl RadialGradient {
    /// Builds a radial gradient in world coordinates.
    ///
    /// Reversed finite radii are normalized together with their colors so the
    /// color attached to each radius remains stable.
    pub fn new(
        center: Vec2,
        inner_radius: f32,
        outer_radius: f32,
        inner_color: Color,
        outer_color: Color,
    ) -> Self {
        if inner_radius.is_finite() && outer_radius.is_finite() && inner_radius > outer_radius {
            Self {
                center,
                inner_radius: outer_radius,
                outer_radius: inner_radius,
                inner_color: outer_color,
                outer_color: inner_color,
            }
        } else {
            Self {
                center,
                inner_radius,
                outer_radius,
                inner_color,
                outer_color,
            }
        }
    }

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

    /// Returns the inner radius in world units.
    pub const fn inner_radius(self) -> f32 {
        self.inner_radius
    }

    /// Returns the outer radius in world units.
    pub const fn outer_radius(self) -> f32 {
        self.outer_radius
    }

    /// Returns the inner linear color.
    pub const fn inner_color(self) -> Color {
        self.inner_color
    }

    /// Returns the outer linear color.
    pub const fn outer_color(self) -> Color {
        self.outer_color
    }

    /// Samples the gradient at a world-space point.
    pub fn color_at(self, world: Vec2) -> Color {
        self.color_at_with_offset(world, Vec2::ZERO)
    }

    fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
        if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
            return self.outer_color.clamp();
        }

        let radius_range = self.outer_radius - self.inner_radius;
        if radius_range == 0.0 {
            return self.outer_color;
        }

        let horizontal =
            f64::from(world_base.x) - f64::from(self.center.x) + f64::from(world_offset.x);
        let vertical =
            f64::from(world_base.y) - f64::from(self.center.y) + f64::from(world_offset.y);
        let distance = horizontal.hypot(vertical);
        let amount = ((distance - f64::from(self.inner_radius)) / f64::from(radius_range))
            .clamp(0.0, 1.0) as f32;
        self.inner_color.interpolate(self.outer_color, amount)
    }

    fn is_valid(self) -> bool {
        self.center.is_finite()
            && self.inner_radius.is_finite()
            && self.outer_radius.is_finite()
            && self.inner_radius >= 0.0
            && self.outer_radius >= self.inner_radius
            && self.inner_color.is_normalized()
            && self.outer_color.is_normalized()
    }
}

/// Stroke color and width for lines and shape outlines.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Stroke {
    width: f32,
    color: Color,
}

impl Stroke {
    /// Builds a stroke used by shape outlines and legacy logical-width lines.
    ///
    /// [`StrokeStyle2d::world`] reuses the same scalar/color value while making
    /// the width's coordinate space explicit on the containing style.
    pub const fn new(width: f32, color: Color) -> Self {
        Self { width, color }
    }
    /// Returns scalar width in the coordinate space selected by its owner.
    pub const fn width(self) -> f32 {
        self.width
    }
    /// Returns the stroke color.
    pub const fn color(self) -> Color {
        self.color
    }
    fn is_valid(self) -> bool {
        self.width.is_finite() && self.width > 0.0 && self.color.is_normalized()
    }
}

/// Simple screen-space shadow used by the first renderer slice.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Shadow {
    offset: LogicalScreenVector,
    spread: f32,
    color: Color,
}

impl Shadow {
    /// Builds a shadow from logical screen-space offset, spread, and color.
    pub fn new(offset: LogicalScreenVector, spread: f32, color: Color) -> Self {
        Self {
            offset,
            spread,
            color,
        }
    }

    /// Returns the logical-pixel shadow offset.
    pub const fn offset(self) -> LogicalScreenVector {
        self.offset
    }
    /// Returns extra logical-pixel spread.
    pub const fn spread(self) -> f32 {
        self.spread
    }
    /// Returns the shadow color.
    pub const fn color(self) -> Color {
        self.color
    }

    fn is_valid(self) -> bool {
        self.offset.is_finite()
            && self.spread.is_finite()
            && self.spread >= 0.0
            && (self.spread * 2.0).is_finite()
            && self.color.is_normalized()
    }
}

#[cfg(test)]
mod tests {
    use std::panic::{AssertUnwindSafe, catch_unwind};

    use super::MAX_STROKE_DASH_SUBSEGMENTS;
    use crate::{
        Color, DrawCommand, Fill, Layer, LinearGradient, LogicalScreenPosition,
        LogicalScreenVector, RadialGradient, Rect, Scene, SceneBudget, SceneBudgetResource,
        SceneCommand, SceneError, ScenePrimitive, ScreenClipRect, ShapeStyle, StrokeCap2d,
        StrokeDashPattern2d, StrokeJoin2d, StrokeMarker2d, StrokeStyle2d, StrokeStyleError, Vec2,
    };
    use crate::{LogicalPixels, WorldLength};

    const UNLIMITED: usize = usize::MAX;

    const fn budget_for(
        commands: usize,
        points: usize,
        vertices: usize,
        retained_bytes: usize,
        upload_bytes: usize,
        batches: usize,
    ) -> SceneBudget {
        SceneBudget::new(
            commands,
            points,
            vertices,
            retained_bytes,
            UNLIMITED,
            upload_bytes,
            batches,
        )
    }

    #[test]
    fn scene_collects_visual_commands_only() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));

        assert_eq!(scene.commands.len(), 1);
    }

    #[test]
    fn scene_keeps_commands_sorted_by_layer() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        scene.circle_on_layer(
            Layer::FOREGROUND,
            Vec2::ZERO,
            10.0,
            ShapeStyle::filled(Color::WHITE),
        );
        scene.line_on_layer(Layer::BACKGROUND, Vec2::ZERO, Vec2::X, 1.0, Color::WHITE);

        assert!(matches!(scene.commands[0].command, DrawCommand::Line(_)));
        assert!(matches!(scene.commands[1].command, DrawCommand::Circle(_)));
    }

    #[test]
    fn scene_budget_rejection_is_atomic_and_counted() {
        let budget = budget_for(1, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED);
        let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
        scene
            .try_circle(Vec2::new(1.0, 2.0), 3.0, ShapeStyle::filled(Color::WHITE))
            .unwrap();

        let before_order = scene.commands()[0].order();
        let result = scene.try_circle(Vec2::new(4.0, 5.0), 6.0, ShapeStyle::filled(Color::WHITE));

        assert_eq!(
            result,
            Err(SceneError::BudgetExceeded {
                resource: SceneBudgetResource::Commands,
                limit: 1,
                requested: 2,
            })
        );
        assert_eq!(scene.command_count(), 1);
        assert_eq!(scene.commands()[0].order(), before_order);
        assert_eq!(scene.statistics().requested_commands(), 2);
        assert_eq!(scene.statistics().accepted_commands(), 1);
        assert_eq!(scene.statistics().rejected_commands(), 1);
    }

    #[test]
    fn scene_budget_enforces_every_resource_at_insertion() {
        let mut reference = Scene::new(Color::BLACK).unwrap();
        reference
            .try_polyline(
                vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1.0)],
                2.0,
                Color::WHITE,
            )
            .unwrap();
        let usage = reference.statistics();
        let cases = [
            (
                SceneBudgetResource::Points,
                budget_for(
                    UNLIMITED,
                    usage.retained_points() - 1,
                    UNLIMITED,
                    UNLIMITED,
                    UNLIMITED,
                    UNLIMITED,
                ),
                usage.retained_points(),
            ),
            (
                SceneBudgetResource::TessellatedVertices,
                budget_for(
                    UNLIMITED,
                    UNLIMITED,
                    usage.estimated_tessellated_vertices() - 1,
                    UNLIMITED,
                    UNLIMITED,
                    UNLIMITED,
                ),
                usage.estimated_tessellated_vertices(),
            ),
            (
                SceneBudgetResource::RetainedBytes,
                budget_for(
                    UNLIMITED,
                    UNLIMITED,
                    UNLIMITED,
                    usage.retained_bytes() - 1,
                    UNLIMITED,
                    UNLIMITED,
                ),
                usage.retained_bytes(),
            ),
            (
                SceneBudgetResource::UploadBytes,
                budget_for(
                    UNLIMITED,
                    UNLIMITED,
                    UNLIMITED,
                    UNLIMITED,
                    usage.estimated_upload_bytes() - 1,
                    UNLIMITED,
                ),
                usage.estimated_upload_bytes(),
            ),
            (
                SceneBudgetResource::DrawBatches,
                budget_for(
                    UNLIMITED,
                    UNLIMITED,
                    UNLIMITED,
                    UNLIMITED,
                    UNLIMITED,
                    usage.estimated_draw_batches() - 1,
                ),
                usage.estimated_draw_batches(),
            ),
        ];

        for (resource, budget, requested) in cases {
            let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
            let result = scene.try_polyline(
                vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1.0)],
                2.0,
                Color::WHITE,
            );
            assert_eq!(
                result,
                Err(SceneError::BudgetExceeded {
                    resource,
                    limit: requested - 1,
                    requested,
                })
            );
            assert_eq!(scene.command_count(), 0);
            assert_eq!(scene.statistics().accepted_commands(), 0);
            assert_eq!(scene.statistics().rejected_commands(), 1);
        }
    }

    #[test]
    fn exact_scene_budget_is_accepted_and_clear_preserves_limits() {
        let mut reference = Scene::new(Color::BLACK).unwrap();
        reference
            .try_line(Vec2::ZERO, Vec2::X, 2.0, Color::WHITE)
            .unwrap();
        let usage = reference.statistics();
        let budget = budget_for(
            usage.accepted_commands(),
            usage.retained_points(),
            usage.estimated_tessellated_vertices(),
            usage.retained_bytes(),
            usage.estimated_upload_bytes(),
            usage.estimated_draw_batches(),
        );
        let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();

        scene
            .try_line(Vec2::ZERO, Vec2::X, 2.0, Color::WHITE)
            .unwrap();
        assert_eq!(scene.statistics(), usage);
        scene.clear();

        assert_eq!(scene.budget(), Some(budget));
        assert_eq!(scene.statistics(), Default::default());
        assert_eq!(scene.command_count(), 0);
    }

    #[test]
    fn scene_allocation_budget_bounds_spare_command_capacity_atomically() {
        let command_bytes = size_of::<SceneCommand>();
        let too_small = SceneBudget::new(
            1,
            UNLIMITED,
            UNLIMITED,
            command_bytes,
            command_bytes - 1,
            UNLIMITED,
            UNLIMITED,
        );
        let mut rejected = Scene::with_budget(Color::BLACK, too_small).unwrap();
        let error = rejected
            .try_circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE))
            .unwrap_err();
        assert!(matches!(
            error,
            SceneError::BudgetExceeded {
                resource: SceneBudgetResource::AllocationBytes,
                limit,
                requested,
            } if limit == command_bytes - 1 && requested >= command_bytes
        ));
        assert_eq!(rejected.command_count(), 0);
        assert_eq!(rejected.allocation_bytes(), 0);

        let bounded = SceneBudget::new(
            4,
            UNLIMITED,
            UNLIMITED,
            4 * command_bytes,
            4 * command_bytes,
            UNLIMITED,
            UNLIMITED,
        );
        let mut scene = Scene::with_budget(Color::BLACK, bounded).unwrap();
        scene
            .try_circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE))
            .unwrap();
        assert!(scene.allocation_bytes() <= bounded.max_allocation_bytes());
        scene.clear();
        assert!(scene.allocation_bytes() <= bounded.max_allocation_bytes());
    }

    #[test]
    fn batch_allocation_budget_rejects_before_consuming_unbounded_input() {
        let budget = SceneBudget::new(
            usize::MAX,
            UNLIMITED,
            UNLIMITED,
            UNLIMITED,
            1,
            UNLIMITED,
            UNLIMITED,
        );
        let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
        let consumed = std::cell::Cell::new(0usize);
        let command =
            DrawCommand::circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)).unwrap();
        let commands = std::iter::from_fn(|| {
            consumed.set(consumed.get().saturating_add(1));
            Some((Layer::DEFAULT, command.clone()))
        });

        assert!(matches!(
            scene.try_extend_to_layers(commands),
            Err(SceneError::BudgetExceeded {
                resource: SceneBudgetResource::AllocationBytes,
                limit: 1,
                ..
            })
        ));
        assert_eq!(consumed.get(), 1);
        assert_eq!(scene.command_count(), 0);
        assert_eq!(scene.allocation_bytes(), 0);
    }

    #[test]
    fn batch_insertion_sorts_once_and_is_atomic_on_budget_failure() {
        let budget = budget_for(4, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED);
        let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
        scene
            .try_extend_to_layers([
                (
                    Layer::FOREGROUND,
                    DrawCommand::circle(Vec2::new(1.0, 0.0), 1.0, ShapeStyle::filled(Color::WHITE))
                        .unwrap(),
                ),
                (
                    Layer::BACKGROUND,
                    DrawCommand::line(Vec2::ZERO, Vec2::X, 1.0, Color::WHITE).unwrap(),
                ),
                (
                    Layer::FOREGROUND,
                    DrawCommand::circle(Vec2::new(2.0, 0.0), 1.0, ShapeStyle::filled(Color::WHITE))
                        .unwrap(),
                ),
            ])
            .unwrap();

        assert_eq!(scene.command_count(), 3);
        assert_eq!(scene.commands()[0].layer(), Layer::BACKGROUND);
        assert_eq!(scene.commands()[1].order(), 0);
        assert_eq!(scene.commands()[2].order(), 2);

        let result = scene.try_extend_to_layers([
            (
                Layer::DEFAULT,
                DrawCommand::circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)).unwrap(),
            ),
            (
                Layer::DEFAULT,
                DrawCommand::circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE)).unwrap(),
            ),
        ]);
        assert_eq!(
            result,
            Err(SceneError::BudgetExceeded {
                resource: SceneBudgetResource::Commands,
                limit: 4,
                requested: 5,
            })
        );
        assert_eq!(scene.command_count(), 3);
        assert_eq!(scene.statistics().requested_commands(), 5);
        assert_eq!(scene.statistics().accepted_commands(), 3);
        assert_eq!(scene.statistics().rejected_commands(), 2);
    }

    #[test]
    fn linear_gradient_samples_along_axis() {
        let gradient = LinearGradient::new(Vec2::ZERO, Vec2::X, Color::BLACK, Color::WHITE);

        let sampled = Fill::LinearGradient(gradient).color_at(Vec2::new(0.5, 4.0));

        assert!((sampled.red() - 0.5).abs() < 0.001);
        assert!((sampled.green() - 0.5).abs() < 0.001);
        assert!((sampled.blue() - 0.5).abs() < 0.001);
    }

    #[test]
    fn extreme_gradients_sample_without_f32_overflow() {
        let gradient = LinearGradient::new(
            Vec2::new(-f32::MAX, 0.0),
            Vec2::new(f32::MAX, 0.0),
            Color::BLACK,
            Color::WHITE,
        );
        let mut scene = Scene::new(Color::BLACK).unwrap();

        assert!(
            scene
                .try_circle(
                    Vec2::ZERO,
                    1.0,
                    ShapeStyle::filled_with(Fill::LinearGradient(gradient)),
                )
                .is_ok()
        );
        assert_eq!(
            gradient.color_at(Vec2::ZERO),
            Color::rgba(0.5, 0.5, 0.5, 1.0)
        );

        let radial = RadialGradient::new(
            Vec2::splat(f32::MAX),
            0.0,
            f32::MAX,
            Color::BLACK,
            Color::WHITE,
        );
        assert_eq!(radial.color_at(Vec2::splat(-f32::MAX)), Color::WHITE);
    }

    #[test]
    fn overflowing_circle_and_shadow_are_rejected_at_scene_boundary() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        assert_eq!(
            scene.try_circle(
                Vec2::splat(f32::MAX),
                f32::MAX,
                ShapeStyle::filled(Color::WHITE),
            ),
            Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle))
        );
        assert_eq!(
            scene.try_circle(
                Vec2::ZERO,
                1.0,
                ShapeStyle::filled(Color::WHITE).with_shadow(super::Shadow::new(
                    LogicalScreenVector::new(0.0, 0.0),
                    f32::MAX,
                    Color::WHITE,
                )),
            ),
            Err(SceneError::InvalidShadow(ScenePrimitive::Circle))
        );
        assert_eq!(
            scene.try_line(
                Vec2::new(-f32::MAX, 0.0),
                Vec2::new(f32::MAX, 0.0),
                1.0,
                Color::WHITE,
            ),
            Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line))
        );
        assert_eq!(
            scene.try_rect(
                Rect::new(Vec2::new(-f32::MAX, 0.0), Vec2::new(f32::MAX, 1.0),),
                0.0,
                ShapeStyle::filled(Color::WHITE),
            ),
            Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect))
        );
    }

    #[test]
    fn commands_capture_temporary_screen_clip() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        let outer = ScreenClipRect::from_min_size(
            LogicalScreenPosition::new(10.0, 20.0),
            LogicalScreenVector::new(100.0, 80.0),
        )
        .unwrap();
        let inner = ScreenClipRect::from_min_size(
            LogicalScreenPosition::new(50.0, 0.0),
            LogicalScreenVector::new(100.0, 50.0),
        )
        .unwrap();

        scene
            .with_screen_clip(outer, |scene| {
                scene
                    .with_screen_clip(inner, |scene| {
                        scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
                    })
                    .unwrap();
            })
            .unwrap();
        scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));

        assert_eq!(
            scene.commands[0].screen_clip,
            Some(
                ScreenClipRect::new(
                    LogicalScreenPosition::new(50.0, 20.0),
                    LogicalScreenPosition::new(110.0, 50.0),
                )
                .unwrap(),
            )
        );
        assert_eq!(scene.commands[1].screen_clip, None);
    }

    #[test]
    fn scene_rejects_invalid_primitives_before_ordering() {
        let mut scene = Scene::new(Color::BLACK).unwrap();

        assert!(!scene.circle(Vec2::ZERO, -1.0, ShapeStyle::filled(Color::WHITE)));
        assert!(!scene.line(Vec2::ZERO, Vec2::X, f32::NAN, Color::WHITE));
        assert!(!scene.polyline(vec![Vec2::ZERO], 1.0, Color::WHITE));
        assert_eq!(scene.command_count(), 0);

        assert!(scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)));
        assert_eq!(scene.commands()[0].order(), 0);
    }

    #[test]
    fn bounded_stroke_configuration_rejects_invalid_patterns_and_miters() {
        assert_eq!(
            StrokeDashPattern2d::new(&[1.0], 0.0, 4),
            Err(StrokeStyleError::InvalidDashElementCount)
        );
        assert_eq!(
            StrokeDashPattern2d::new(&[1.0, 0.0], 0.0, 4),
            Err(StrokeStyleError::InvalidDashLength)
        );
        assert_eq!(
            StrokeDashPattern2d::new(&[1.0, 1.0], f32::NAN, 4),
            Err(StrokeStyleError::InvalidDashPhase)
        );
        assert_eq!(
            StrokeDashPattern2d::new(&[1.0, 1.0], 0.0, 0),
            Err(StrokeStyleError::InvalidDashExpansionLimit)
        );
        assert_eq!(
            StrokeDashPattern2d::new(&[1.0, 1.0], 0.0, MAX_STROKE_DASH_SUBSEGMENTS + 1,),
            Err(StrokeStyleError::InvalidDashExpansionLimit)
        );
        assert_eq!(
            StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE)
                .with_miter_limit(0.5),
            Err(StrokeStyleError::InvalidMiterLimit)
        );
    }

    #[test]
    fn dash_boundaries_must_be_representable_at_the_source_coordinate_scale() {
        let dash =
            StrokeDashPattern2d::new(&[f32::MIN_POSITIVE, f32::MIN_POSITIVE], 0.0, 8).unwrap();
        let style = StrokeStyle2d::logical(LogicalPixels::new(1.0).unwrap(), Color::WHITE)
            .with_dash_pattern(dash);

        assert!(matches!(
            DrawCommand::styled_line(Vec2::ZERO, Vec2::new(f32::MAX, 0.0), style),
            Err(SceneError::UnrepresentableStrokePattern(
                ScenePrimitive::Line,
            ))
        ));
    }

    #[test]
    fn dash_expansion_is_rejected_atomically_at_the_scene_boundary() {
        let dash = StrokeDashPattern2d::new(&[2.0, 2.0], 0.0, 2).unwrap();
        let style = StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE)
            .with_cap(StrokeCap2d::Butt)
            .with_dash_pattern(dash);
        let mut scene = Scene::new(Color::BLACK).unwrap();

        assert_eq!(
            scene.try_styled_line(Vec2::ZERO, Vec2::new(10.0, 0.0), style),
            Err(SceneError::StrokeExpansionLimitExceeded {
                primitive: ScenePrimitive::Line,
                limit: 2,
                required: 3,
            })
        );
        assert_eq!(scene.command_count(), 0);
        assert_eq!(scene.statistics().requested_commands(), 1);
        assert_eq!(scene.statistics().rejected_commands(), 1);
    }

    #[test]
    fn scene_statistics_group_requested_accepted_and_rejected_primitives() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        scene
            .try_circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE))
            .unwrap();
        assert_eq!(
            scene.try_line(Vec2::ZERO, Vec2::ZERO, 1.0, Color::WHITE),
            Err(SceneError::DegenerateGeometry(ScenePrimitive::Line))
        );
        scene
            .try_polyline(vec![Vec2::ZERO, Vec2::X], 1.0, Color::WHITE)
            .unwrap();

        let statistics = scene.statistics();
        assert_eq!(statistics.requested_by_primitive().circles(), 1);
        assert_eq!(statistics.requested_by_primitive().lines(), 1);
        assert_eq!(statistics.requested_by_primitive().polylines(), 1);
        assert_eq!(statistics.requested_by_primitive().total(), 3);
        assert_eq!(statistics.accepted_by_primitive().circles(), 1);
        assert_eq!(statistics.accepted_by_primitive().polylines(), 1);
        assert_eq!(statistics.accepted_by_primitive().total(), 2);
        assert_eq!(statistics.rejected_by_primitive().lines(), 1);
        assert_eq!(statistics.rejected_by_primitive().total(), 1);
    }

    #[test]
    fn rich_stroke_values_are_reusable_and_world_overflow_is_rejected() {
        let marker = StrokeMarker2d::arrow(
            LogicalPixels::new(8.0).unwrap(),
            LogicalPixels::new(6.0).unwrap(),
        );
        let style = StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE)
            .with_cap(StrokeCap2d::Square)
            .with_join(StrokeJoin2d::Bevel)
            .with_start_marker(marker)
            .with_end_marker(marker);
        let command =
            DrawCommand::styled_polyline(vec![Vec2::ZERO, Vec2::X, Vec2::new(2.0, 1.0)], style)
                .unwrap();
        assert_eq!(command.estimated_tessellated_vertices(), 24);

        let unsafe_world = StrokeStyle2d::world(WorldLength::new(f32::MAX).unwrap(), Color::WHITE);
        assert!(matches!(
            DrawCommand::styled_line(Vec2::ZERO, Vec2::X, unsafe_world),
            Err(SceneError::InvalidStroke(ScenePrimitive::Line))
        ));

        let unsafe_logical =
            StrokeStyle2d::logical(LogicalPixels::new(f32::MAX).unwrap(), Color::WHITE);
        assert!(matches!(
            DrawCommand::styled_line(Vec2::ZERO, Vec2::X, unsafe_logical),
            Err(SceneError::InvalidStroke(ScenePrimitive::Line))
        ));
    }

    #[test]
    fn polyline_rejects_zero_segments_and_numerically_ambiguous_turns() {
        let style = StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE);
        assert!(matches!(
            DrawCommand::styled_polyline(vec![Vec2::ZERO, Vec2::ZERO, Vec2::X], style),
            Err(SceneError::DegenerateGeometry(ScenePrimitive::Polyline))
        ));
        assert!(matches!(
            DrawCommand::styled_polyline(vec![Vec2::ZERO, Vec2::X, Vec2::ZERO], style),
            Err(SceneError::DegenerateStrokeTurn {
                primitive: ScenePrimitive::Polyline,
                vertex_index: 1,
            })
        ));
        assert!(matches!(
            DrawCommand::styled_polyline(
                vec![Vec2::ZERO, Vec2::X, Vec2::new(0.0, 0.000_000_1)],
                style,
            ),
            Err(SceneError::DegenerateStrokeTurn {
                primitive: ScenePrimitive::Polyline,
                vertex_index: 1,
            })
        ));
        assert!(matches!(
            DrawCommand::styled_polyline(
                vec![Vec2::ZERO, Vec2::X, Vec2::new(2.0, 0.000_05)],
                style,
            ),
            Err(SceneError::DegenerateStrokeTurn {
                primitive: ScenePrimitive::Polyline,
                vertex_index: 1,
            })
        ));
    }

    #[test]
    fn background_and_clip_are_validated_when_created() {
        assert!(matches!(
            Scene::new(Color::rgba(f32::NAN, 0.0, 0.0, 1.0)),
            Err(SceneError::InvalidBackground)
        ));
        assert!(matches!(
            Scene::new(Color::rgb(1.01, 0.0, 0.0)),
            Err(SceneError::InvalidBackground)
        ));
        assert_eq!(
            ScreenClipRect::new(
                LogicalScreenPosition::new(0.0, 0.0),
                LogicalScreenPosition::new(0.0, 10.0),
            ),
            Err(SceneError::InvalidScreenClip)
        );
        assert_eq!(
            ScreenClipRect::new(
                LogicalScreenPosition::new(f32::NAN, 0.0),
                LogicalScreenPosition::new(10.0, 10.0),
            ),
            Err(SceneError::InvalidScreenClip)
        );
    }

    #[test]
    fn render_bound_scene_colors_must_be_normalized() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        assert_eq!(
            scene.try_circle(
                Vec2::ZERO,
                1.0,
                ShapeStyle::filled(Color::rgb(2.0, 0.0, 0.0)),
            ),
            Err(SceneError::InvalidFill(ScenePrimitive::Circle))
        );
        assert_eq!(
            scene.try_line(Vec2::ZERO, Vec2::X, 1.0, Color::rgba(0.0, 0.0, 0.0, -0.01),),
            Err(SceneError::InvalidStroke(ScenePrimitive::Line))
        );
        assert_eq!(scene.command_count(), 0);
    }

    #[test]
    fn depth_does_not_reorder_commands_within_a_layer() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        scene
            .with_depth(4.0, |scene| {
                scene.circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE));
            })
            .unwrap();
        scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE));

        assert_eq!(scene.commands()[0].depth(), 4.0);
        assert_eq!(scene.commands()[1].depth(), 0.0);
    }

    #[test]
    fn allocation_bytes_preserve_spare_command_capacity_after_clear() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        scene
            .try_polyline(
                vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1.0)],
                1.0,
                Color::WHITE,
            )
            .unwrap();
        let allocated = scene.allocation_bytes();
        assert!(allocated >= size_of::<SceneCommand>() + 3 * size_of::<Vec2>());
        scene.clear();
        assert_eq!(scene.statistics().retained_bytes(), 0);
        assert_eq!(
            scene.allocation_bytes(),
            scene.commands.capacity() * size_of::<SceneCommand>()
        );
        assert!(scene.allocation_bytes() > 0);
    }

    #[test]
    fn clone_recomputes_capacity_based_polyline_accounting() {
        let mut points = Vec::with_capacity(1_024);
        points.extend([Vec2::ZERO, Vec2::X]);
        let mut scene = Scene::new(Color::BLACK).unwrap();
        scene.try_polyline(points, 1.0, Color::WHITE).unwrap();

        let cloned = scene.clone();
        let actual_owned = cloned
            .commands
            .iter()
            .map(|command| command.command.owned_allocation_bytes())
            .fold(0usize, usize::saturating_add);
        assert_eq!(cloned.owned_payload_bytes, actual_owned);
        assert_eq!(
            cloned.statistics.retained_bytes(),
            cloned
                .commands
                .len()
                .saturating_mul(size_of::<SceneCommand>())
                .saturating_add(actual_owned)
        );
        assert_eq!(
            cloned.allocation_bytes(),
            cloned
                .commands
                .capacity()
                .saturating_mul(size_of::<SceneCommand>())
                .saturating_add(actual_owned)
        );
    }

    #[test]
    fn structured_scene_errors_preserve_rejection_reason() {
        let mut scene = Scene::new(Color::BLACK).unwrap();

        assert_eq!(
            scene.try_circle(Vec2::ZERO, -1.0, ShapeStyle::filled(Color::WHITE)),
            Err(SceneError::InvalidDimension(ScenePrimitive::Circle))
        );
        assert_eq!(
            scene.try_line(Vec2::ZERO, Vec2::ZERO, 1.0, Color::WHITE),
            Err(SceneError::DegenerateGeometry(ScenePrimitive::Line))
        );
        assert_eq!(
            scene.try_circle(
                Vec2::ZERO,
                1.0,
                ShapeStyle {
                    fill: None,
                    stroke: None,
                    shadow: None,
                },
            ),
            Err(SceneError::MissingStyle(ScenePrimitive::Circle))
        );
        assert_eq!(scene.command_count(), 0);
    }

    #[test]
    fn commands_capture_depth_and_restore_it_after_unwind() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        let panic_result = catch_unwind(AssertUnwindSafe(|| {
            let _ = scene.with_depth(4.5, |scene| {
                scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE));
                panic!("intentional depth unwind");
            });
        }));
        assert!(panic_result.is_err());

        scene.circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE));

        assert_eq!(scene.commands()[0].depth(), 4.5);
        assert_eq!(scene.commands()[1].depth(), 0.0);
        assert_eq!(
            scene.with_depth(f32::NAN, |_| {}),
            Err(SceneError::NonFiniteDepth)
        );
    }

    #[test]
    fn gradients_sanitize_invalid_and_reversed_configuration() {
        let invalid_linear = LinearGradient::new(
            Vec2::new(f32::NAN, 0.0),
            Vec2::X,
            Color::BLACK,
            Color::WHITE,
        );
        assert_eq!(invalid_linear.color_at(Vec2::ZERO), Color::WHITE);

        let reversed = RadialGradient::new(Vec2::ZERO, 10.0, 5.0, Color::WHITE, Color::BLACK);
        assert_eq!(reversed.inner_radius(), 5.0);
        assert_eq!(reversed.outer_radius(), 10.0);
        assert_eq!(reversed.color_at(Vec2::ZERO), Color::BLACK);
    }

    #[test]
    fn tiny_nonzero_radial_range_preserves_both_color_endpoints() {
        let gradient =
            RadialGradient::new(Vec2::ZERO, 0.0, 0.000_000_01, Color::BLACK, Color::WHITE);

        assert_eq!(gradient.color_at(Vec2::ZERO), Color::BLACK);
        assert_eq!(
            gradient.color_at(Vec2::new(0.000_000_01, 0.0)),
            Color::WHITE
        );
    }

    #[test]
    fn temporary_screen_clip_restores_state_after_unwind() {
        let mut scene = Scene::new(Color::BLACK).unwrap();
        let clip = ScreenClipRect::from_min_size(
            LogicalScreenPosition::new(0.0, 0.0),
            LogicalScreenVector::new(100.0, 100.0),
        )
        .unwrap();

        let panic_result = catch_unwind(AssertUnwindSafe(|| {
            let _ = scene.with_screen_clip(clip, |_| panic!("intentional test panic"));
        }));
        assert!(panic_result.is_err());

        assert!(scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)));
        assert_eq!(scene.commands()[0].screen_clip(), None);
    }
}