blinc_core 0.5.1

Blinc core runtime - reactive signals, state machines, and event dispatch
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
//! Draw Context - Unified Rendering API
//!
//! The `DrawContext` trait provides a unified interface for all drawing operations
//! in the BLINC canvas architecture. It adapts to the current layer type, providing
//! appropriate operations for 2D UI, 2D canvas drawing, and 3D scenes.
//!
//! # Design Philosophy
//!
//! Rather than having separate APIs for different rendering contexts, DrawContext
//! provides a single interface that:
//!
//! - Maintains transform, clip, and opacity stacks
//! - Supports 2D path-based drawing (fill, stroke, text)
//! - Supports 3D scene operations (meshes, lights, cameras)
//! - Enables dimension bridging (billboards, 3D viewports)
//! - Records commands for deferred GPU execution
//!
//! # Example
//!
//! ```ignore
//! fn paint(ctx: &mut dyn DrawContext) {
//!     // Transform stack
//!     ctx.push_transform(Transform::translate(10.0, 20.0));
//!
//!     // Draw a rounded rectangle
//!     ctx.fill_rect(Rect::new(0.0, 0.0, 100.0, 50.0), 8.0.into(), Color::BLUE);
//!
//!     // Draw text
//!     ctx.draw_text("Hello", Point::new(10.0, 30.0), &TextStyle::default());
//!
//!     ctx.pop_transform();
//! }
//! ```

use crate::layer::{
    Affine2D, BillboardFacing, BlendMode, Brush, Camera, ClipShape, Color, CornerRadius,
    CubemapData, Environment, LayerId, Light, Mat4, ParticleSystemData, Point, Rect, Sdf3DViewport,
    Shadow, Size, Vec2,
};

// ─────────────────────────────────────────────────────────────────────────────
// Transform Types
// ─────────────────────────────────────────────────────────────────────────────

/// Unified transform that can represent 2D or 3D transformations
#[derive(Clone, Debug)]
pub enum Transform {
    /// 2D affine transformation
    Affine2D(Affine2D),
    /// 3D matrix transformation
    Mat4(Mat4),
}

impl Transform {
    /// Create a 2D translation
    pub fn translate(x: f32, y: f32) -> Self {
        Transform::Affine2D(Affine2D::translation(x, y))
    }

    /// Create a 2D scale around the origin (0, 0)
    ///
    /// Note: This scales around the top-left corner. For centered scaling,
    /// use `scale_centered()` instead.
    pub fn scale(sx: f32, sy: f32) -> Self {
        Transform::Affine2D(Affine2D::scale(sx, sy))
    }

    /// Create a 2D scale centered around a specific point
    ///
    /// This creates a transform that:
    /// 1. Translates the center point to the origin
    /// 2. Applies the scale
    /// 3. Translates back
    ///
    /// This results in scaling that appears to grow/shrink from the center point.
    pub fn scale_centered(sx: f32, sy: f32, center_x: f32, center_y: f32) -> Self {
        // Combined transform: translate(cx, cy) * scale(sx, sy) * translate(-cx, -cy)
        // This can be computed directly in the affine matrix:
        // tx = cx * (1 - sx)
        // ty = cy * (1 - sy)
        let tx = center_x * (1.0 - sx);
        let ty = center_y * (1.0 - sy);
        Transform::Affine2D(Affine2D {
            elements: [sx, 0.0, 0.0, sy, tx, ty],
        })
    }

    /// Create a 2D rotation around the origin (0, 0)
    ///
    /// Note: This rotates around the top-left corner. For centered rotation,
    /// use `rotate_centered()` instead.
    pub fn rotate(angle: f32) -> Self {
        Transform::Affine2D(Affine2D::rotation(angle))
    }

    /// Create a 2D rotation centered around a specific point
    ///
    /// This creates a transform that:
    /// 1. Translates the center point to the origin
    /// 2. Applies the rotation
    /// 3. Translates back
    pub fn rotate_centered(angle: f32, center_x: f32, center_y: f32) -> Self {
        // Combined transform: translate(cx, cy) * rotate(angle) * translate(-cx, -cy)
        let c = angle.cos();
        let s = angle.sin();
        // tx = cx - cx*cos + cy*sin
        // ty = cy - cx*sin - cy*cos
        let tx = center_x - center_x * c + center_y * s;
        let ty = center_y - center_x * s - center_y * c;
        Transform::Affine2D(Affine2D {
            elements: [c, s, -s, c, tx, ty],
        })
    }

    /// Create a 3D translation
    pub fn translate_3d(x: f32, y: f32, z: f32) -> Self {
        Transform::Mat4(Mat4::translation(x, y, z))
    }

    /// Create a 3D scale
    pub fn scale_3d(x: f32, y: f32, z: f32) -> Self {
        Transform::Mat4(Mat4::scale(x, y, z))
    }

    /// Create identity transform
    pub fn identity() -> Self {
        Transform::Affine2D(Affine2D::IDENTITY)
    }

    /// Check if this is a 2D transform
    pub fn is_2d(&self) -> bool {
        matches!(self, Transform::Affine2D(_))
    }

    /// Check if this is a 3D transform
    pub fn is_3d(&self) -> bool {
        matches!(self, Transform::Mat4(_))
    }
}

impl Default for Transform {
    fn default() -> Self {
        Transform::identity()
    }
}

impl From<Affine2D> for Transform {
    fn from(t: Affine2D) -> Self {
        Transform::Affine2D(t)
    }
}

impl From<Mat4> for Transform {
    fn from(t: Mat4) -> Self {
        Transform::Mat4(t)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Stroke Configuration
// ─────────────────────────────────────────────────────────────────────────────

/// Line cap style
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineCap {
    /// Flat cap at the endpoint
    #[default]
    Butt,
    /// Rounded cap extending past the endpoint
    Round,
    /// Square cap extending past the endpoint
    Square,
}

/// Line join style
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineJoin {
    /// Miter join (sharp corner)
    #[default]
    Miter,
    /// Round join
    Round,
    /// Bevel join (flat corner)
    Bevel,
}

/// Stroke style configuration
#[derive(Clone, Debug)]
pub struct Stroke {
    /// Line width
    pub width: f32,
    /// Line cap style
    pub cap: LineCap,
    /// Line join style
    pub join: LineJoin,
    /// Miter limit (for Miter joins)
    pub miter_limit: f32,
    /// Dash pattern (empty for solid line)
    pub dash: Vec<f32>,
    /// Dash offset
    pub dash_offset: f32,
}

impl Default for Stroke {
    fn default() -> Self {
        Self {
            width: 1.0,
            cap: LineCap::Butt,
            join: LineJoin::Miter,
            miter_limit: 4.0,
            dash: Vec::new(),
            dash_offset: 0.0,
        }
    }
}

impl Stroke {
    /// Create a new stroke with the given width
    pub fn new(width: f32) -> Self {
        Self {
            width,
            ..Default::default()
        }
    }

    /// Set line cap style
    pub fn with_cap(mut self, cap: LineCap) -> Self {
        self.cap = cap;
        self
    }

    /// Set line join style
    pub fn with_join(mut self, join: LineJoin) -> Self {
        self.join = join;
        self
    }

    /// Set dash pattern
    pub fn with_dash(mut self, pattern: Vec<f32>, offset: f32) -> Self {
        self.dash = pattern;
        self.dash_offset = offset;
        self
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Text Configuration
// ─────────────────────────────────────────────────────────────────────────────

/// Text alignment
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextAlign {
    #[default]
    Left,
    Center,
    Right,
}

/// Text baseline
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextBaseline {
    Top,
    Middle,
    #[default]
    Alphabetic,
    Bottom,
}

/// Font weight
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FontWeight {
    Thin,
    Light,
    #[default]
    Regular,
    Medium,
    Bold,
    Black,
}

/// Text style configuration
#[derive(Clone, Debug)]
pub struct TextStyle {
    /// Font family name
    pub family: String,
    /// Font size in pixels
    pub size: f32,
    /// Font weight
    pub weight: FontWeight,
    /// Text color
    pub color: Color,
    /// Text alignment
    pub align: TextAlign,
    /// Text baseline
    pub baseline: TextBaseline,
    /// Letter spacing adjustment
    pub letter_spacing: f32,
    /// Line height multiplier
    pub line_height: f32,
}

impl Default for TextStyle {
    fn default() -> Self {
        Self {
            family: "system-ui".to_string(),
            size: 14.0,
            weight: FontWeight::Regular,
            color: Color::BLACK,
            align: TextAlign::Left,
            baseline: TextBaseline::Alphabetic,
            letter_spacing: 0.0,
            line_height: 1.2,
        }
    }
}

impl TextStyle {
    /// Create a new text style with font size
    pub fn new(size: f32) -> Self {
        Self {
            size,
            ..Default::default()
        }
    }

    /// Set text color
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    /// Set font weight
    pub fn with_weight(mut self, weight: FontWeight) -> Self {
        self.weight = weight;
        self
    }

    /// Set font family
    pub fn with_family(mut self, family: impl Into<String>) -> Self {
        self.family = family.into();
        self
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Path Types
// ─────────────────────────────────────────────────────────────────────────────

/// Path command for building vector paths
#[derive(Clone, Debug)]
pub enum PathCommand {
    /// Move to a point
    MoveTo(Point),
    /// Line to a point
    LineTo(Point),
    /// Quadratic Bézier curve
    QuadTo { control: Point, end: Point },
    /// Cubic Bézier curve
    CubicTo {
        control1: Point,
        control2: Point,
        end: Point,
    },
    /// Arc to a point
    ArcTo {
        radii: Vec2,
        rotation: f32,
        large_arc: bool,
        sweep: bool,
        end: Point,
    },
    /// Close the current subpath
    Close,
}

/// A vector path
#[derive(Clone, Debug, Default)]
pub struct Path {
    commands: Vec<PathCommand>,
}

impl Path {
    /// Create a new empty path
    pub fn new() -> Self {
        Self {
            commands: Vec::new(),
        }
    }

    /// Create a path from a vector of commands
    pub fn from_commands(commands: Vec<PathCommand>) -> Self {
        Self { commands }
    }

    /// Move to a point
    pub fn move_to(mut self, x: f32, y: f32) -> Self {
        self.commands.push(PathCommand::MoveTo(Point::new(x, y)));
        self
    }

    /// Line to a point
    pub fn line_to(mut self, x: f32, y: f32) -> Self {
        self.commands.push(PathCommand::LineTo(Point::new(x, y)));
        self
    }

    /// Quadratic Bézier curve
    pub fn quad_to(mut self, cx: f32, cy: f32, x: f32, y: f32) -> Self {
        self.commands.push(PathCommand::QuadTo {
            control: Point::new(cx, cy),
            end: Point::new(x, y),
        });
        self
    }

    /// Cubic Bézier curve
    pub fn cubic_to(mut self, cx1: f32, cy1: f32, cx2: f32, cy2: f32, x: f32, y: f32) -> Self {
        self.commands.push(PathCommand::CubicTo {
            control1: Point::new(cx1, cy1),
            control2: Point::new(cx2, cy2),
            end: Point::new(x, y),
        });
        self
    }

    /// Close the path
    pub fn close(mut self) -> Self {
        self.commands.push(PathCommand::Close);
        self
    }

    /// SVG Arc to a point
    ///
    /// - `radii`: The x and y radii of the ellipse
    /// - `rotation`: Rotation angle of the ellipse in radians
    /// - `large_arc`: If true, use the larger arc (> 180 degrees)
    /// - `sweep`: If true, draw clockwise; if false, counter-clockwise
    /// - `x`, `y`: End point of the arc
    pub fn arc_to(
        mut self,
        radii: Vec2,
        rotation: f32,
        large_arc: bool,
        sweep: bool,
        x: f32,
        y: f32,
    ) -> Self {
        self.commands.push(PathCommand::ArcTo {
            radii,
            rotation,
            large_arc,
            sweep,
            end: Point::new(x, y),
        });
        self
    }

    /// Create a rectangle path
    pub fn rect(rect: Rect) -> Self {
        Self::new()
            .move_to(rect.x(), rect.y())
            .line_to(rect.x() + rect.width(), rect.y())
            .line_to(rect.x() + rect.width(), rect.y() + rect.height())
            .line_to(rect.x(), rect.y() + rect.height())
            .close()
    }

    /// Create a circle path
    pub fn circle(center: Point, radius: f32) -> Self {
        // Approximate circle with 4 cubic Bézier curves
        let k = 0.552_284_8; // Magic number for cubic Bézier circle approximation
        let r = radius;
        let cx = center.x;
        let cy = center.y;

        Self::new()
            .move_to(cx + r, cy)
            .cubic_to(cx + r, cy + r * k, cx + r * k, cy + r, cx, cy + r)
            .cubic_to(cx - r * k, cy + r, cx - r, cy + r * k, cx - r, cy)
            .cubic_to(cx - r, cy - r * k, cx - r * k, cy - r, cx, cy - r)
            .cubic_to(cx + r * k, cy - r, cx + r, cy - r * k, cx + r, cy)
            .close()
    }

    /// Create a line path
    pub fn line(from: Point, to: Point) -> Self {
        Self::new().move_to(from.x, from.y).line_to(to.x, to.y)
    }

    /// Get the path commands
    pub fn commands(&self) -> &[PathCommand] {
        &self.commands
    }

    /// Check if the path is empty
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    /// Calculate the bounding rectangle of this path
    pub fn bounds(&self) -> Rect {
        if self.commands.is_empty() {
            return Rect::ZERO;
        }

        let mut min_x = f32::INFINITY;
        let mut min_y = f32::INFINITY;
        let mut max_x = f32::NEG_INFINITY;
        let mut max_y = f32::NEG_INFINITY;

        for cmd in &self.commands {
            match cmd {
                PathCommand::MoveTo(p) | PathCommand::LineTo(p) => {
                    min_x = min_x.min(p.x);
                    min_y = min_y.min(p.y);
                    max_x = max_x.max(p.x);
                    max_y = max_y.max(p.y);
                }
                PathCommand::QuadTo { control, end } => {
                    min_x = min_x.min(control.x).min(end.x);
                    min_y = min_y.min(control.y).min(end.y);
                    max_x = max_x.max(control.x).max(end.x);
                    max_y = max_y.max(control.y).max(end.y);
                }
                PathCommand::CubicTo {
                    control1,
                    control2,
                    end,
                } => {
                    min_x = min_x.min(control1.x).min(control2.x).min(end.x);
                    min_y = min_y.min(control1.y).min(control2.y).min(end.y);
                    max_x = max_x.max(control1.x).max(control2.x).max(end.x);
                    max_y = max_y.max(control1.y).max(control2.y).max(end.y);
                }
                PathCommand::ArcTo { end, radii, .. } => {
                    // Conservative bounds: include endpoint and radii extent
                    min_x = min_x.min(end.x).min(end.x - radii.x);
                    min_y = min_y.min(end.y).min(end.y - radii.y);
                    max_x = max_x.max(end.x).max(end.x + radii.x);
                    max_y = max_y.max(end.y).max(end.y + radii.y);
                }
                PathCommand::Close => {}
            }
        }

        if min_x.is_finite() && min_y.is_finite() && max_x.is_finite() && max_y.is_finite() {
            Rect::new(min_x, min_y, max_x - min_x, max_y - min_y)
        } else {
            Rect::ZERO
        }
    }

    /// Create a rounded rectangle path
    pub fn rounded_rect(rect: Rect, corner_radius: impl Into<CornerRadius>) -> Self {
        let r = corner_radius.into();
        let x = rect.x();
        let y = rect.y();
        let w = rect.width();
        let h = rect.height();

        // Clamp radii to half the minimum dimension
        let max_r = (w.min(h) / 2.0).max(0.0);
        let tl = r.top_left.min(max_r);
        let tr = r.top_right.min(max_r);
        let br = r.bottom_right.min(max_r);
        let bl = r.bottom_left.min(max_r);

        // Magic number for cubic Bézier circle approximation
        let k = 0.552_284_8;

        let mut path = Self::new().move_to(x + tl, y);

        // Top edge
        path = path.line_to(x + w - tr, y);
        if tr > 0.0 {
            path = path.cubic_to(
                x + w - tr * (1.0 - k),
                y,
                x + w,
                y + tr * (1.0 - k),
                x + w,
                y + tr,
            );
        }

        // Right edge
        path = path.line_to(x + w, y + h - br);
        if br > 0.0 {
            path = path.cubic_to(
                x + w,
                y + h - br * (1.0 - k),
                x + w - br * (1.0 - k),
                y + h,
                x + w - br,
                y + h,
            );
        }

        // Bottom edge
        path = path.line_to(x + bl, y + h);
        if bl > 0.0 {
            path = path.cubic_to(
                x + bl * (1.0 - k),
                y + h,
                x,
                y + h - bl * (1.0 - k),
                x,
                y + h - bl,
            );
        }

        // Left edge
        path = path.line_to(x, y + tl);
        if tl > 0.0 {
            path = path.cubic_to(x, y + tl * (1.0 - k), x + tl * (1.0 - k), y, x + tl, y);
        }

        path.close()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Image Types
// ─────────────────────────────────────────────────────────────────────────────

/// Handle to a loaded image
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageId(pub u64);

/// Image rendering options
#[derive(Clone, Debug, Default)]
pub struct ImageOptions {
    /// Source rectangle within the image (None = entire image)
    pub source_rect: Option<Rect>,
    /// Tint color (white = no tint)
    pub tint: Option<Color>,
    /// Opacity (1.0 = fully opaque)
    pub opacity: f32,
}

impl ImageOptions {
    pub fn new() -> Self {
        Self {
            source_rect: None,
            tint: None,
            opacity: 1.0,
        }
    }

    pub fn with_tint(mut self, color: Color) -> Self {
        self.tint = Some(color);
        self
    }

    pub fn with_opacity(mut self, opacity: f32) -> Self {
        self.opacity = opacity;
        self
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// 3D Types
// ─────────────────────────────────────────────────────────────────────────────

/// Handle to a loaded mesh (for cached/registered meshes)
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MeshId(pub u64);

/// Handle to a material (for cached/registered materials)
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MaterialId(pub u64);

/// Mesh instance for instanced rendering
#[derive(Clone, Debug)]
pub struct MeshInstance {
    pub transform: Mat4,
    pub material: Option<MaterialId>,
}

// ─────────────────────────────────────────────────────────────────────────────
// Generic Mesh Data — users convert from glTF/OBJ/FBX/custom formats
// ─────────────────────────────────────────────────────────────────────────────

/// A single vertex with position, normal, UV, and color
#[derive(Clone, Copy, Debug, Default)]
#[repr(C)]
pub struct Vertex {
    pub position: [f32; 3],
    pub normal: [f32; 3],
    pub uv: [f32; 2],
    pub color: [f32; 4],
    /// Tangent vector for normal mapping (xyz = direction, w = handedness ±1)
    pub tangent: [f32; 4],
    /// Joint indices for skeletal animation (up to 4 influences per vertex)
    pub joints: [u32; 4],
    /// Joint weights for skeletal animation (should sum to 1.0)
    pub weights: [f32; 4],
}

impl Vertex {
    pub fn new(pos: [f32; 3]) -> Self {
        Self {
            position: pos,
            normal: [0.0, 1.0, 0.0],
            uv: [0.0, 0.0],
            color: [1.0, 1.0, 1.0, 1.0],
            tangent: [1.0, 0.0, 0.0, 1.0],
            joints: [0; 4],
            weights: [1.0, 0.0, 0.0, 0.0],
        }
    }

    pub fn with_normal(mut self, n: [f32; 3]) -> Self {
        self.normal = n;
        self
    }
    pub fn with_uv(mut self, uv: [f32; 2]) -> Self {
        self.uv = uv;
        self
    }
    pub fn with_color(mut self, c: [f32; 4]) -> Self {
        self.color = c;
        self
    }
    pub fn with_tangent(mut self, t: [f32; 4]) -> Self {
        self.tangent = t;
        self
    }
    pub fn with_joints(mut self, joints: [u32; 4], weights: [f32; 4]) -> Self {
        self.joints = joints;
        self.weights = weights;
        self
    }
}

/// Generic mesh data — the interchange format for 3D geometry.
///
/// Users convert from any source format (glTF, OBJ, FBX, procedural)
/// into this struct, then pass it to `DrawContext::draw_mesh_data()`.
///
/// # Example
///
/// ```ignore
/// // Triangle
/// let mesh = MeshData {
///     vertices: vec![
///         Vertex::new([-0.5, -0.5, 0.0]).with_color([1.0, 0.0, 0.0, 1.0]),
///         Vertex::new([ 0.5, -0.5, 0.0]).with_color([0.0, 1.0, 0.0, 1.0]),
///         Vertex::new([ 0.0,  0.5, 0.0]).with_color([0.0, 0.0, 1.0, 1.0]),
///     ],
///     indices: vec![0, 1, 2],
///     material: Material::default(),
/// };
/// ctx.draw_mesh_data(&mesh, Mat4::IDENTITY);
/// ```
#[derive(Clone, Debug)]
pub struct MeshData {
    pub vertices: Vec<Vertex>,
    pub indices: Vec<u32>,
    pub material: Material,
    /// Optional skinning data for skeletal animation.
    /// When provided, the GPU applies bone transforms to each vertex
    /// based on joint indices and weights.
    pub skin: Option<SkinningData>,
}

/// PBR material for mesh rendering.
///
/// Follows the glTF 2.0 metallic-roughness workflow. Scalar factors
/// (`base_color`, `metallic`, `roughness`, `emissive`) are multiplied
/// by their optional textures when those textures are present; when a
/// texture is `None` the scalar acts alone, which means a caller can
/// leave every texture unset and still get a valid flat-shaded material.
#[derive(Clone, Debug)]
pub struct Material {
    /// Base color (RGBA). Multiplied against `base_color_texture` when
    /// that texture is present.
    pub base_color: [f32; 4],
    /// Metallic factor. Multiplied against the `.b` channel of
    /// `metallic_roughness_texture` when present. glTF convention:
    /// `0.0` = dielectric, `1.0` = pure metal.
    pub metallic: f32,
    /// Roughness factor. Multiplied against the `.g` channel of
    /// `metallic_roughness_texture` when present. `0.0` = mirror,
    /// `1.0` = perfectly diffuse.
    pub roughness: f32,
    /// Emissive color (RGB, linear). Multiplied against
    /// `emissive_texture` when present.
    pub emissive: [f32; 3],
    /// Base color texture (sRGB RGBA pixels, decoded per-fragment).
    /// `None` = use `base_color` alone.
    pub base_color_texture: Option<TextureData>,
    /// Normal map (tangent-space normals encoded as RGB in `[0,1]`,
    /// shader unpacks to `[-1,1]`).
    pub normal_map: Option<TextureData>,
    /// Normal map strength. `0.0` = flat, `1.0` = full effect.
    pub normal_scale: f32,
    /// Metallic/roughness texture. glTF convention: metallic in `.b`,
    /// roughness in `.g`. The shader multiplies these per-texel by the
    /// scalar `metallic` / `roughness` factors above.
    pub metallic_roughness_texture: Option<TextureData>,
    /// Emissive texture (sRGB RGB). Multiplied per-texel by
    /// `emissive`. Used for glowing HUD elements, lights, screens —
    /// anything the mesh emits light from regardless of incident
    /// illumination.
    pub emissive_texture: Option<TextureData>,
    /// Ambient occlusion texture (grayscale). The `.r` channel
    /// attenuates the ambient + indirect diffuse terms to simulate
    /// crevice self-shadowing without running a full ray query.
    pub occlusion_texture: Option<TextureData>,
    /// Occlusion strength. `0.0` = no AO, `1.0` = full AO from the
    /// texture. Matches the glTF `occlusionTexture.strength` semantic.
    pub occlusion_strength: f32,
    /// Displacement / height map (grayscale). Drives parallax
    /// occlusion mapping in the shader.
    pub displacement_map: Option<TextureData>,
    /// Displacement scale in world units.
    pub displacement_scale: f32,
    /// Whether the material is unlit (ignore lighting).
    pub unlit: bool,
    /// Alpha mode.
    pub alpha_mode: AlphaMode,
    /// Whether this mesh receives shadows from other meshes.
    pub receives_shadows: bool,
    /// Whether this mesh casts shadows onto other meshes.
    pub casts_shadows: bool,
}

impl Default for Material {
    fn default() -> Self {
        Self {
            base_color: [1.0, 1.0, 1.0, 1.0],
            metallic: 0.0,
            roughness: 0.5,
            emissive: [0.0, 0.0, 0.0],
            base_color_texture: None,
            normal_map: None,
            normal_scale: 1.0,
            metallic_roughness_texture: None,
            emissive_texture: None,
            occlusion_texture: None,
            occlusion_strength: 1.0,
            displacement_map: None,
            displacement_scale: 0.05,
            unlit: false,
            alpha_mode: AlphaMode::Opaque,
            receives_shadows: true,
            casts_shadows: true,
        }
    }
}

/// Texture data for materials
#[derive(Clone, Debug)]
pub struct TextureData {
    pub rgba: Vec<u8>,
    pub width: u32,
    pub height: u32,
}

/// Alpha blending mode
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AlphaMode {
    #[default]
    Opaque,
    Blend,
    Mask,
}

// ─────────────────────────────────────────────────────────────────────────────
// Skeletal Animation
// ─────────────────────────────────────────────────────────────────────────────

/// A bone in a skeletal hierarchy.
///
/// Users construct bones from glTF skins, FBX skeletons, etc.
/// The `inverse_bind_matrix` transforms from mesh space to bone-local space.
#[derive(Clone, Debug)]
pub struct Bone {
    /// Human-readable name (e.g., "LeftUpperArm")
    pub name: String,
    /// Index of parent bone, or None for the root
    pub parent: Option<usize>,
    /// Inverse bind matrix — transforms mesh-space positions into this bone's local space
    pub inverse_bind_matrix: [f32; 16],
}

/// Skeletal hierarchy (bind pose).
///
/// The bone list defines the hierarchy and rest pose.
/// Users animate by computing per-frame joint matrices and passing
/// them via `SkinningData`.
#[derive(Clone, Debug)]
pub struct Skeleton {
    pub bones: Vec<Bone>,
}

/// Per-frame skinning data sent to the GPU.
///
/// Each joint matrix is the product of the bone's current world transform
/// and its inverse bind matrix: `joint_matrix[i] = world_transform[i] * inverse_bind[i]`.
///
/// Maximum 256 joints. Vertices reference these via `Vertex::joints` indices.
#[derive(Clone, Debug)]
pub struct SkinningData {
    /// Joint matrices — one per bone, max 256.
    /// Each is a column-major 4x4 matrix.
    pub joint_matrices: Vec<[f32; 16]>,
}

// ─────────────────────────────────────────────────────────────────────────────
// Layer Effects
// ─────────────────────────────────────────────────────────────────────────────

/// Post-processing effect quality levels
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BlurQuality {
    /// Single-pass box blur (fastest, lowest quality)
    Low,
    /// Two-pass separable Gaussian (balanced)
    #[default]
    Medium,
    /// Multi-pass Kawase blur (slowest, highest quality)
    High,
}

/// Post-processing effects that can be applied to layers
#[derive(Clone, Debug, PartialEq)]
pub enum LayerEffect {
    /// Gaussian blur effect
    Blur {
        /// Blur radius in pixels
        radius: f32,
        /// Quality level (affects performance and visual quality)
        quality: BlurQuality,
    },
    /// Drop shadow effect (rendered behind the layer)
    DropShadow {
        /// Horizontal offset
        offset_x: f32,
        /// Vertical offset
        offset_y: f32,
        /// Blur radius
        blur: f32,
        /// Spread radius (positive expands, negative contracts)
        spread: f32,
        /// Shadow color
        color: Color,
    },
    /// Outer glow effect
    Glow {
        /// Glow color
        color: Color,
        /// Blur softness (higher = softer edges)
        blur: f32,
        /// Glow range (how far the glow extends from the element)
        range: f32,
        /// Glow opacity (0.0 to 1.0)
        opacity: f32,
    },
    /// Color matrix transformation (4x5 matrix for RGBA + offset)
    ColorMatrix {
        /// 4x5 color transformation matrix stored row-major:
        /// `[R_new]` = `[m0  m1  m2  m3  m4 ]` * `[R]`
        /// `[G_new]` = `[m5  m6  m7  m8  m9 ]` * `[G]`
        /// `[B_new]` = `[m10 m11 m12 m13 m14]` * `[B]`
        /// `[A_new]` = `[m15 m16 m17 m18 m19]` * `[A]`
        ///                                       `[1]`
        matrix: [f32; 20],
    },
    /// Mask image effect (multiplies layer alpha by mask luminance/alpha)
    MaskImage {
        /// Image URL or path
        image_url: String,
        /// Mask sizing mode
        mask_mode: MaskMode,
    },
}

/// How a mask image is interpreted
#[derive(Clone, Debug, PartialEq, Default)]
pub enum MaskMode {
    /// Use the alpha channel of the mask image
    #[default]
    Alpha,
    /// Use the luminance of the mask image as alpha
    Luminance,
}

/// CSS mask-image value
#[derive(Clone, Debug)]
pub enum MaskImage {
    /// URL to an image file
    Url(String),
    /// Gradient mask (reuses the existing Gradient type)
    Gradient(crate::layer::Gradient),
}

impl LayerEffect {
    /// Create a blur effect with default quality
    pub fn blur(radius: f32) -> Self {
        Self::Blur {
            radius,
            quality: BlurQuality::default(),
        }
    }

    /// Create a blur effect with specified quality
    pub fn blur_with_quality(radius: f32, quality: BlurQuality) -> Self {
        Self::Blur { radius, quality }
    }

    /// Create a drop shadow effect
    pub fn drop_shadow(offset_x: f32, offset_y: f32, blur: f32, color: Color) -> Self {
        Self::DropShadow {
            offset_x,
            offset_y,
            blur,
            spread: 0.0,
            color,
        }
    }

    /// Create a glow effect
    ///
    /// ## Parameters
    /// - `color`: Glow color
    /// - `blur`: Blur softness (higher = softer edges), typically 4-24
    /// - `range`: How far the glow extends from the element, typically 0-20
    /// - `opacity`: Glow visibility (0.0 to 1.0)
    pub fn glow(color: Color, blur: f32, range: f32, opacity: f32) -> Self {
        Self::Glow {
            color,
            blur,
            range,
            opacity,
        }
    }

    /// Create an identity color matrix (no change)
    pub fn color_matrix_identity() -> Self {
        Self::ColorMatrix {
            matrix: [
                1.0, 0.0, 0.0, 0.0, 0.0, // R
                0.0, 1.0, 0.0, 0.0, 0.0, // G
                0.0, 0.0, 1.0, 0.0, 0.0, // B
                0.0, 0.0, 0.0, 1.0, 0.0, // A
            ],
        }
    }

    /// Create a grayscale color matrix
    pub fn grayscale() -> Self {
        Self::ColorMatrix {
            matrix: [
                0.299, 0.587, 0.114, 0.0, 0.0, // R = 0.299R + 0.587G + 0.114B
                0.299, 0.587, 0.114, 0.0, 0.0, // G = same
                0.299, 0.587, 0.114, 0.0, 0.0, // B = same
                0.0, 0.0, 0.0, 1.0, 0.0, // A = A
            ],
        }
    }

    /// Create a sepia color matrix
    pub fn sepia() -> Self {
        Self::ColorMatrix {
            matrix: [
                0.393, 0.769, 0.189, 0.0, 0.0, // R
                0.349, 0.686, 0.168, 0.0, 0.0, // G
                0.272, 0.534, 0.131, 0.0, 0.0, // B
                0.0, 0.0, 0.0, 1.0, 0.0, // A
            ],
        }
    }

    /// Create a brightness adjustment matrix
    pub fn brightness(factor: f32) -> Self {
        Self::ColorMatrix {
            matrix: [
                factor, 0.0, 0.0, 0.0, 0.0, // R
                0.0, factor, 0.0, 0.0, 0.0, // G
                0.0, 0.0, factor, 0.0, 0.0, // B
                0.0, 0.0, 0.0, 1.0, 0.0, // A
            ],
        }
    }

    /// Create a contrast adjustment matrix
    pub fn contrast(factor: f32) -> Self {
        let offset = 0.5 * (1.0 - factor);
        Self::ColorMatrix {
            matrix: [
                factor, 0.0, 0.0, 0.0, offset, // R
                0.0, factor, 0.0, 0.0, offset, // G
                0.0, 0.0, factor, 0.0, offset, // B
                0.0, 0.0, 0.0, 1.0, 0.0, // A
            ],
        }
    }

    /// Create a saturation adjustment matrix
    pub fn saturation(factor: f32) -> Self {
        let inv = 1.0 - factor;
        let r = 0.299 * inv;
        let g = 0.587 * inv;
        let b = 0.114 * inv;
        Self::ColorMatrix {
            matrix: [
                r + factor,
                g,
                b,
                0.0,
                0.0, // R
                r,
                g + factor,
                b,
                0.0,
                0.0, // G
                r,
                g,
                b + factor,
                0.0,
                0.0, // B
                0.0,
                0.0,
                0.0,
                1.0,
                0.0, // A
            ],
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Layer Configuration
// ─────────────────────────────────────────────────────────────────────────────

/// 3D perspective transform parameters for layer-based compositing.
/// When a container has CSS rotate-x/rotate-y, its entire subtree (including text)
/// is rendered flat to a layer texture, then the layer is composited with perspective
/// distortion applied to the blit quad.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Transform3DParams {
    pub sin_rx: f32,
    pub cos_rx: f32,
    pub sin_ry: f32,
    pub cos_ry: f32,
    /// Perspective distance in physical pixels (already DPI-scaled)
    pub perspective_d: f32,
}

/// Configuration for offscreen layers
#[derive(Clone, Debug, Default)]
pub struct LayerConfig {
    /// Layer ID (optional)
    pub id: Option<LayerId>,
    /// Layer position in viewport coordinates (for proper compositing)
    pub position: Option<crate::Point>,
    /// Layer size (None = inherit from parent)
    pub size: Option<Size>,
    /// Blend mode with parent
    pub blend_mode: BlendMode,
    /// Opacity
    pub opacity: f32,
    /// Enable depth buffer
    pub depth: bool,
    /// Post-processing effects to apply when layer is composited
    pub effects: Vec<LayerEffect>,
    /// 3D perspective transform for layer compositing (rotate-x/rotate-y on containers)
    pub transform_3d: Option<Transform3DParams>,
}

impl LayerConfig {
    /// Create a new layer config with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the layer ID
    pub fn id(mut self, id: LayerId) -> Self {
        self.id = Some(id);
        self
    }

    /// Set the layer size
    pub fn size(mut self, size: Size) -> Self {
        self.size = Some(size);
        self
    }

    /// Set the layer position in viewport coordinates
    pub fn position(mut self, position: crate::Point) -> Self {
        self.position = Some(position);
        self
    }

    /// Set the blend mode
    pub fn blend_mode(mut self, mode: BlendMode) -> Self {
        self.blend_mode = mode;
        self
    }

    /// Set the opacity
    pub fn opacity(mut self, opacity: f32) -> Self {
        self.opacity = opacity;
        self
    }

    /// Enable depth buffer
    pub fn with_depth(mut self) -> Self {
        self.depth = true;
        self
    }

    /// Add a post-processing effect
    pub fn effect(mut self, effect: LayerEffect) -> Self {
        self.effects.push(effect);
        self
    }

    /// Add a blur effect
    pub fn blur(self, radius: f32) -> Self {
        self.effect(LayerEffect::blur(radius))
    }

    /// Add a drop shadow effect
    pub fn drop_shadow(self, offset_x: f32, offset_y: f32, blur: f32, color: Color) -> Self {
        self.effect(LayerEffect::drop_shadow(offset_x, offset_y, blur, color))
    }

    /// Add a glow effect
    ///
    /// ## Parameters
    /// - `color`: Glow color
    /// - `blur`: Blur softness (higher = softer edges), typically 4-24
    /// - `range`: How far the glow extends from the element, typically 0-20
    /// - `opacity`: Glow visibility (0.0 to 1.0)
    pub fn glow(self, color: Color, blur: f32, range: f32, opacity: f32) -> Self {
        self.effect(LayerEffect::glow(color, blur, range, opacity))
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// SDF Builder
// ─────────────────────────────────────────────────────────────────────────────

/// Shape ID returned by SDF operations
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ShapeId(pub u32);

/// Builder for SDF (Signed Distance Field) shapes
///
/// This provides an optimized path for rendering UI primitives using GPU SDF shaders.
/// Operations here are batched and rendered very efficiently.
pub trait SdfBuilder {
    // ─────────────────────────────────────────────────────────────────────────
    // Primitives
    // ─────────────────────────────────────────────────────────────────────────

    /// Create a rectangle with optional corner radius
    fn rect(&mut self, rect: Rect, corner_radius: CornerRadius) -> ShapeId;

    /// Create a circle
    fn circle(&mut self, center: Point, radius: f32) -> ShapeId;

    /// Create an ellipse
    fn ellipse(&mut self, center: Point, radii: Vec2) -> ShapeId;

    /// Create a line segment
    fn line(&mut self, from: Point, to: Point, width: f32) -> ShapeId;

    /// Create an arc
    fn arc(&mut self, center: Point, radius: f32, start: f32, end: f32, width: f32) -> ShapeId;

    /// Create a quadratic Bézier curve (has closed-form SDF)
    fn quad_bezier(&mut self, p0: Point, p1: Point, p2: Point, width: f32) -> ShapeId;

    // ─────────────────────────────────────────────────────────────────────────
    // Boolean Operations
    // ─────────────────────────────────────────────────────────────────────────

    /// Union of two shapes
    fn union(&mut self, a: ShapeId, b: ShapeId) -> ShapeId;

    /// Subtract b from a
    fn subtract(&mut self, a: ShapeId, b: ShapeId) -> ShapeId;

    /// Intersect two shapes
    fn intersect(&mut self, a: ShapeId, b: ShapeId) -> ShapeId;

    /// Smooth union with blend radius
    fn smooth_union(&mut self, a: ShapeId, b: ShapeId, radius: f32) -> ShapeId;

    /// Smooth subtract with blend radius
    fn smooth_subtract(&mut self, a: ShapeId, b: ShapeId, radius: f32) -> ShapeId;

    /// Smooth intersect with blend radius
    fn smooth_intersect(&mut self, a: ShapeId, b: ShapeId, radius: f32) -> ShapeId;

    // ─────────────────────────────────────────────────────────────────────────
    // Modifiers
    // ─────────────────────────────────────────────────────────────────────────

    /// Round the corners of a shape
    fn round(&mut self, shape: ShapeId, radius: f32) -> ShapeId;

    /// Create an outline of a shape
    fn outline(&mut self, shape: ShapeId, width: f32) -> ShapeId;

    /// Offset a shape (positive = expand, negative = shrink)
    fn offset(&mut self, shape: ShapeId, distance: f32) -> ShapeId;

    // ─────────────────────────────────────────────────────────────────────────
    // Rendering
    // ─────────────────────────────────────────────────────────────────────────

    /// Fill a shape with a brush
    fn fill(&mut self, shape: ShapeId, brush: Brush);

    /// Stroke a shape
    fn stroke(&mut self, shape: ShapeId, stroke: &Stroke, brush: Brush);

    /// Add a shadow to a shape
    fn shadow(&mut self, shape: ShapeId, shadow: Shadow);
}

// ─────────────────────────────────────────────────────────────────────────────
// Draw Context Trait
// ─────────────────────────────────────────────────────────────────────────────

/// Unified drawing context that adapts to the current layer type
///
/// This is the primary interface for all drawing operations in BLINC. It provides:
///
/// - Transform, clip, and opacity stacks
/// - 2D drawing operations (fill, stroke, text, images)
/// - SDF primitive operations (optimized for UI)
/// - 3D scene operations (meshes, lights, cameras)
/// - Dimension bridging (billboards, 3D viewports)
/// - Layer management
pub trait DrawContext {
    // ─────────────────────────────────────────────────────────────────────────
    // Transform Stack
    // ─────────────────────────────────────────────────────────────────────────

    /// Push a transform onto the stack
    fn push_transform(&mut self, transform: Transform);

    /// Pop the top transform from the stack
    fn pop_transform(&mut self);

    /// Get the current combined transform
    fn current_transform(&self) -> Transform;

    // ─────────────────────────────────────────────────────────────────────────
    // State Stack
    // ─────────────────────────────────────────────────────────────────────────

    /// Push a clip shape onto the stack
    fn push_clip(&mut self, shape: ClipShape);

    /// Pop the top clip from the stack
    fn pop_clip(&mut self);

    /// Push an opacity value (multiplied with parent)
    fn push_opacity(&mut self, opacity: f32);

    /// Pop the top opacity from the stack
    fn pop_opacity(&mut self);

    /// Push a blend mode
    fn push_blend_mode(&mut self, mode: BlendMode);

    /// Pop the top blend mode from the stack
    fn pop_blend_mode(&mut self);

    /// Set whether we're rendering to the foreground layer (after glass)
    ///
    /// When true, primitives should be rendered on top of glass elements.
    /// Default is false (background layer). This is used by the three-pass
    /// rendering system to separate background and foreground primitives.
    fn set_foreground_layer(&mut self, _is_foreground: bool) {
        // Default implementation does nothing (for contexts that don't support layering)
    }

    /// Set the current z-layer for rendering
    ///
    /// Z-layers are used to interleave primitive and text rendering for proper
    /// Stack z-ordering. Each Stack child increments the z-layer, ensuring that
    /// all content (primitives + text) within that child renders together.
    fn set_z_layer(&mut self, _layer: u32) {
        // Default implementation does nothing
    }

    /// Get the current z-layer
    fn z_layer(&self) -> u32 {
        0
    }

    // ─────────────────────────────────────────────────────────────────────────
    // 3D Transform (per-element, transient)
    // ─────────────────────────────────────────────────────────────────────────

    /// Set 3D rotation and perspective for the current element
    fn set_3d_transform(&mut self, _rx_rad: f32, _ry_rad: f32, _perspective_d: f32) {}

    /// Set 3D shape parameters for the current element
    fn set_3d_shape(&mut self, _shape_type: f32, _depth: f32, _ambient: f32, _specular: f32) {}

    /// Set 3D light parameters for the current element
    fn set_3d_light(&mut self, _direction: [f32; 3], _intensity: f32) {}

    /// Set translate-z offset for 3D elements (positive = toward viewer)
    fn set_3d_translate_z(&mut self, _z: f32) {}

    /// Set group shape descriptors for compound 3D rendering
    /// Each shape is 16 floats: [offset(4), params(4), half_ext(4), color(4)]
    fn set_3d_group_raw(&mut self, _shapes: &[[f32; 16]]) {}

    /// Reset 3D transient state to defaults
    fn clear_3d(&mut self) {}

    /// Set CSS filter parameters for the current element
    #[allow(clippy::too_many_arguments)]
    fn set_css_filter(
        &mut self,
        _grayscale: f32,
        _invert: f32,
        _sepia: f32,
        _hue_rotate_deg: f32,
        _brightness: f32,
        _contrast: f32,
        _saturate: f32,
    ) {
    }

    /// Reset CSS filter state to identity
    fn clear_css_filter(&mut self) {}

    /// Set mask gradient parameters for the current element
    /// params: linear=(x1,y1,x2,y2), radial=(cx,cy,r,0) in pixel coords
    /// info: [mask_type, start_alpha, end_alpha, 0] where mask_type: 0=none, 1=linear, 2=radial
    fn set_mask_gradient(&mut self, _params: [f32; 4], _info: [f32; 4]) {}

    /// Clear mask gradient state
    fn clear_mask_gradient(&mut self) {}

    /// Set corner shape (superellipse n parameter) for the current element.
    /// Values: [top_left, top_right, bottom_right, bottom_left].
    /// n=1.0 = round (default), n=0.0 = bevel, n=2.0 = squircle, n=-1.0 = scoop.
    fn set_corner_shape(&mut self, _shape: [f32; 4]) {}

    /// Clear corner shape to default (round, n=1.0)
    fn clear_corner_shape(&mut self) {}

    /// Set overflow fade distances for the next push_clip.
    /// Values: [top, right, bottom, left] in CSS pixels.
    fn set_overflow_fade(&mut self, _fade: [f32; 4]) {}

    /// Clear pending overflow fade
    fn clear_overflow_fade(&mut self) {}

    // ─────────────────────────────────────────────────────────────────────────
    // 2D Drawing Operations
    // ─────────────────────────────────────────────────────────────────────────

    /// Fill a path with a brush
    fn fill_path(&mut self, path: &Path, brush: Brush);

    /// Stroke a path
    fn stroke_path(&mut self, path: &Path, stroke: &Stroke, brush: Brush);

    /// Fill a rectangle (convenience method)
    fn fill_rect(&mut self, rect: Rect, corner_radius: CornerRadius, brush: Brush);

    /// Fill a notched rect using the SDF pipeline.
    ///
    /// A notch is a rounded rect with:
    /// - Optional per-corner concave curves (indicated by the `corner_types`
    ///   slot: 0.0 = sharp/convex, 1.0 = concave).
    /// - Optional top and/or bottom edge modifier — scoop (1), bulge (2),
    ///   v-cut (3), or v-peak (4) — described by the `top_mod` / `bottom_mod`
    ///   tuples as `(type, width, height_or_depth, corner_radius)`. Pass
    ///   `(0, 0, 0, 0)` for no modifier on a given edge.
    ///
    /// All geometry is evaluated per-pixel in the SDF fragment shader so
    /// notches inherit the main pipeline's antialiasing, clip/layer
    /// composition, transform stack, and border/shadow support — no CPU
    /// path tessellation and no dependency on the separate tessellated-
    /// path pipeline (which had portability issues on some WebGPU
    /// implementations).
    ///
    /// The default implementation falls back to `fill_rect` so non-GPU
    /// renderers (hit-testing, headless unit tests, etc.) don't have to
    /// reimplement the full SDF composition.
    ///
    /// # Parameters
    /// - `rect` — outer bounds in layout coordinates.
    /// - `corner_radii` — per-corner radii (top-left, top-right,
    ///   bottom-right, bottom-left). Magnitude only; sign is ignored.
    /// - `corner_types` — per-corner type flags in the same order
    ///   (0.0 = sharp or convex, 1.0 = concave).
    /// - `top_mod` — top edge modifier `(type, width, height, corner_radius)`.
    /// - `bottom_mod` — bottom edge modifier, same layout as `top_mod`.
    /// - `border` — optional `(width, color)` to stroke the notch with.
    /// - `shadow` — optional drop shadow.
    /// - `brush` — fill brush.
    #[allow(clippy::too_many_arguments)]
    fn fill_notch(
        &mut self,
        rect: Rect,
        corner_radii: [f32; 4],
        corner_types: [f32; 4],
        top_mod: [f32; 4],
        bottom_mod: [f32; 4],
        border: Option<(f32, Color)>,
        shadow: Option<Shadow>,
        brush: Brush,
    ) {
        // Default: drop every notch feature and draw a plain rounded rect.
        // The sign-less max() keeps concave radii from bleeding a rect
        // larger than the caller's bounds on fallback backends.
        let _ = (corner_types, top_mod, bottom_mod);
        let cr = CornerRadius {
            top_left: corner_radii[0].max(0.0),
            top_right: corner_radii[1].max(0.0),
            bottom_right: corner_radii[2].max(0.0),
            bottom_left: corner_radii[3].max(0.0),
        };
        if let Some(sh) = shadow {
            self.draw_shadow(rect, cr, sh);
        }
        self.fill_rect(rect, cr, brush);
        if let Some((width, color)) = border {
            if width > 0.0 {
                self.stroke_rect(rect, cr, &Stroke::new(width), Brush::Solid(color));
            }
        }
    }

    /// Fill a rectangle with per-side borders (all same color)
    /// Border format: [top, right, bottom, left]
    /// Default implementation draws fill then strokes with max border width
    fn fill_rect_with_per_side_border(
        &mut self,
        rect: Rect,
        corner_radius: CornerRadius,
        brush: Brush,
        border_widths: [f32; 4],
        border_color: Color,
    ) {
        // Default: draw fill then stroke (suboptimal but works)
        self.fill_rect(rect, corner_radius, brush);
        let max_border = border_widths.iter().cloned().fold(0.0f32, |a, b| a.max(b));
        if max_border > 0.0 {
            let stroke = Stroke::new(max_border);
            self.stroke_rect(rect, corner_radius, &stroke, Brush::Solid(border_color));
        }
    }

    /// Stroke a rectangle (convenience method)
    fn stroke_rect(
        &mut self,
        rect: Rect,
        corner_radius: CornerRadius,
        stroke: &Stroke,
        brush: Brush,
    );

    /// Fill a circle (convenience method)
    fn fill_circle(&mut self, center: Point, radius: f32, brush: Brush);

    /// Stroke a circle (convenience method)
    fn stroke_circle(&mut self, center: Point, radius: f32, stroke: &Stroke, brush: Brush);

    /// Draw text at a position
    fn draw_text(&mut self, text: &str, origin: Point, style: &TextStyle);

    /// Draw an image
    fn draw_image(&mut self, image: ImageId, rect: Rect, options: &ImageOptions);

    /// Draw raw RGBA pixel data directly to the target.
    ///
    /// Uploads the pixel data as a GPU texture and renders it to the
    /// destination rect. Use for video frames, camera preview, or
    /// any dynamically-generated image data.
    ///
    /// # Arguments
    /// * `data` — RGBA pixel data (4 bytes per pixel)
    /// * `width` — Image width in pixels
    /// * `height` — Image height in pixels
    /// * `dest` — Destination rectangle in layout coordinates
    fn draw_rgba_pixels(&mut self, _data: &[u8], _width: u32, _height: u32, _dest: Rect) {
        // Default no-op — GPU implementations override
    }

    /// Draw a drop shadow (renders outside the shape)
    fn draw_shadow(&mut self, rect: Rect, corner_radius: CornerRadius, shadow: Shadow);

    /// Draw an inner shadow (renders inside the shape, like CSS inset box-shadow)
    fn draw_inner_shadow(&mut self, rect: Rect, corner_radius: CornerRadius, shadow: Shadow);

    /// Draw a circle drop shadow with radially symmetric blur
    fn draw_circle_shadow(&mut self, center: Point, radius: f32, shadow: Shadow);

    /// Draw a circle inner shadow (renders inside the circle)
    fn draw_circle_inner_shadow(&mut self, center: Point, radius: f32, shadow: Shadow);

    /// Build SDF shapes using the optimized SDF pipeline
    ///
    /// This is the most efficient way to render UI primitives:
    /// ```ignore
    /// ctx.sdf_build(|sdf| {
    ///     let rect = sdf.rect(bounds, 8.0.into());
    ///     sdf.shadow(rect, Shadow::new(0.0, 4.0, 10.0, Color::BLACK.with_alpha(0.2)));
    ///     sdf.fill(rect, Color::WHITE.into());
    /// });
    /// ```
    fn sdf_build(&mut self, f: &mut dyn FnMut(&mut dyn SdfBuilder));

    // ─────────────────────────────────────────────────────────────────────────
    // 3D Drawing Operations
    // ─────────────────────────────────────────────────────────────────────────

    /// Set the camera for 3D rendering
    fn set_camera(&mut self, camera: &Camera);

    /// Set the logical bounds of the 3D viewport region. Called by
    /// `SceneKit3D::element` before `draw_mesh_data` so the paint
    /// context can compute the physical-pixel viewport rect from the
    /// current transform stack + these bounds, clipping the mesh to
    /// the canvas element rather than the full frame.
    fn set_3d_viewport_bounds(&mut self, _width: f32, _height: f32) {}

    /// Draw a mesh with a material (using cached mesh/material handles)
    fn draw_mesh(&mut self, mesh: MeshId, material: MaterialId, transform: Mat4);

    /// Draw instanced meshes (using cached mesh handle)
    fn draw_mesh_instanced(&mut self, mesh: MeshId, instances: &[MeshInstance]);

    /// Draw mesh data directly (no registration needed).
    ///
    /// Users convert from any format (glTF, OBJ, FBX, procedural) into
    /// `MeshData`, then pass it here. The GPU implementation handles
    /// vertex/index buffer upload and rendering.
    ///
    /// ```ignore
    /// let mesh = Arc::new(MeshData {
    ///     vertices: vec![Vertex::new([-0.5, -0.5, 0.0]), ...],
    ///     indices: vec![0, 1, 2],
    ///     material: Material::default(),
    /// });
    /// ctx.draw_mesh_data(mesh.clone(), Mat4::IDENTITY);
    /// ```
    fn draw_mesh_data(&mut self, _mesh: std::sync::Arc<MeshData>, _transform: Mat4) {
        // Default no-op — GPU implementations override
    }

    /// Add a light to the scene
    fn add_light(&mut self, light: Light);

    /// Set the environment (skybox, IBL)
    fn set_environment(&mut self, env: &Environment);

    /// Provide a pre-generated cubemap for IBL reflections.
    ///
    /// The GPU implementation uploads the face/mip data to the environment
    /// cubemap texture. Scenes that don't call this get a neutral gray
    /// fallback.
    fn set_environment_cubemap(&mut self, _data: std::sync::Arc<CubemapData>) {}

    // ─────────────────────────────────────────────────────────────────────────
    // Dimension Bridging
    // ─────────────────────────────────────────────────────────────────────────

    /// Embed 2D content in the current 3D context as a billboard
    fn billboard_draw(
        &mut self,
        size: Size,
        transform: Mat4,
        facing: BillboardFacing,
        f: &mut dyn FnMut(&mut dyn DrawContext),
    );

    /// Embed a 3D viewport in the current 2D context
    fn viewport_3d_draw(
        &mut self,
        rect: Rect,
        camera: &Camera,
        f: &mut dyn FnMut(&mut dyn DrawContext),
    );

    /// Draw an SDF 3D viewport using GPU raymarching
    ///
    /// This renders a procedural 3D scene defined by signed distance functions.
    /// The shader WGSL code should contain a `map_scene(p: vec3<f32>) -> f32` function
    /// that defines the SDF scene, and a `get_material(p: vec3<f32>) -> SdfMaterial`
    /// function for materials.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use blinc_3d::sdf::{SdfScene, SdfCodegen};
    /// use blinc_core::{DrawContext, Sdf3DViewport, Rect};
    ///
    /// // Build an SDF scene
    /// let scene = SdfScene::new()
    ///     .sphere(1.0)
    ///     .translate(0.0, 1.0, 0.0);
    ///
    /// // Generate shader and create viewport
    /// let mut viewport = Sdf3DViewport::default();
    /// viewport.shader_wgsl = SdfCodegen::generate_full_shader(&scene);
    ///
    /// // Render the viewport
    /// ctx.draw_sdf_viewport(Rect::new(0.0, 0.0, 800.0, 600.0), &viewport);
    /// ```
    fn draw_sdf_viewport(&mut self, _rect: Rect, _viewport: &Sdf3DViewport) {
        // Default implementation does nothing
        // GPU implementations override this to add SDF viewports to the render batch
    }

    /// Draw GPU-accelerated particles
    ///
    /// This renders a particle system using GPU compute and instanced rendering.
    /// The particle simulation and rendering happens entirely on the GPU for
    /// maximum performance.
    ///
    /// # Arguments
    ///
    /// * `rect` - The viewport rectangle to render particles in
    /// * `particle_data` - The particle system configuration and state
    ///
    /// # Example
    ///
    /// ```ignore
    /// use blinc_core::{DrawContext, ParticleSystemData, Rect};
    ///
    /// // Create particle system data
    /// let particles = ParticleSystemData {
    ///     emitter_position: Vec3::new(0.0, 0.0, 0.0),
    ///     emission_rate: 100.0,
    ///     ..Default::default()
    /// };
    ///
    /// // Render the particles
    /// ctx.draw_particles(Rect::new(0.0, 0.0, 800.0, 600.0), &particles);
    /// ```
    fn draw_particles(&mut self, _rect: Rect, _particle_data: &ParticleSystemData) {
        // Default implementation does nothing
        // GPU implementations override this to render particles
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Layer Management
    // ─────────────────────────────────────────────────────────────────────────

    /// Begin an offscreen layer
    fn push_layer(&mut self, config: LayerConfig);

    /// End the current offscreen layer
    fn pop_layer(&mut self);

    /// Sample from a named layer's output
    fn sample_layer(&mut self, id: LayerId, source_rect: Rect, dest_rect: Rect);

    // ─────────────────────────────────────────────────────────────────────────
    // State Queries
    // ─────────────────────────────────────────────────────────────────────────

    /// Get the current viewport size
    fn viewport_size(&self) -> Size;

    /// Check if we're in a 3D context
    fn is_3d_context(&self) -> bool;

    /// Get the current opacity
    fn current_opacity(&self) -> f32;

    /// Get the current blend mode
    fn current_blend_mode(&self) -> BlendMode;
}

/// Extension trait for DrawContext that provides ergonomic generic methods
///
/// These methods are implemented on concrete types and provide convenient
/// APIs using `impl Into<Brush>` for colors and brushes.
pub trait DrawContextExt: DrawContext {
    /// Fill a path with a color or brush
    fn fill<B: Into<Brush>>(&mut self, path: &Path, brush: B) {
        self.fill_path(path, brush.into());
    }

    /// Stroke a path with a color or brush
    fn stroke<B: Into<Brush>>(&mut self, path: &Path, stroke: &Stroke, brush: B) {
        self.stroke_path(path, stroke, brush.into());
    }

    /// Fill a rectangle with a color or brush
    fn fill_rounded_rect<B: Into<Brush>>(
        &mut self,
        rect: Rect,
        corner_radius: CornerRadius,
        brush: B,
    ) {
        self.fill_rect(rect, corner_radius, brush.into());
    }

    /// Build SDF shapes with a closure (convenience wrapper)
    fn sdf<F: FnMut(&mut dyn SdfBuilder)>(&mut self, mut f: F) {
        self.sdf_build(&mut f);
    }

    /// Embed 2D content as a billboard (convenience wrapper)
    fn billboard<F: FnMut(&mut dyn DrawContext)>(
        &mut self,
        size: Size,
        transform: Mat4,
        facing: BillboardFacing,
        mut f: F,
    ) {
        self.billboard_draw(size, transform, facing, &mut f);
    }

    /// Embed a 3D viewport (convenience wrapper)
    fn viewport_3d<F: FnMut(&mut dyn DrawContext)>(
        &mut self,
        rect: Rect,
        camera: &Camera,
        mut f: F,
    ) {
        self.viewport_3d_draw(rect, camera, &mut f);
    }
}

// Blanket implementation for all DrawContext implementers
impl<T: DrawContext + ?Sized> DrawContextExt for T {}

// ─────────────────────────────────────────────────────────────────────────────
// Recording Draw Context
// ─────────────────────────────────────────────────────────────────────────────

/// A draw command that can be recorded and replayed
#[derive(Clone, Debug)]
pub enum DrawCommand {
    // State
    PushTransform(Transform),
    PopTransform,
    PushClip(ClipShape),
    PopClip,
    PushOpacity(f32),
    PopOpacity,
    PushBlendMode(BlendMode),
    PopBlendMode,

    // 2D Drawing
    FillPath {
        path: Path,
        brush: Brush,
    },
    StrokePath {
        path: Path,
        stroke: Stroke,
        brush: Brush,
    },
    FillRect {
        rect: Rect,
        corner_radius: CornerRadius,
        brush: Brush,
    },
    StrokeRect {
        rect: Rect,
        corner_radius: CornerRadius,
        stroke: Stroke,
        brush: Brush,
    },
    FillCircle {
        center: Point,
        radius: f32,
        brush: Brush,
    },
    StrokeCircle {
        center: Point,
        radius: f32,
        stroke: Stroke,
        brush: Brush,
    },
    DrawText {
        text: String,
        origin: Point,
        style: TextStyle,
    },
    DrawImage {
        image: ImageId,
        rect: Rect,
        options: ImageOptions,
    },
    DrawShadow {
        rect: Rect,
        corner_radius: CornerRadius,
        shadow: Shadow,
    },
    DrawInnerShadow {
        rect: Rect,
        corner_radius: CornerRadius,
        shadow: Shadow,
    },
    DrawCircleShadow {
        center: Point,
        radius: f32,
        shadow: Shadow,
    },
    DrawCircleInnerShadow {
        center: Point,
        radius: f32,
        shadow: Shadow,
    },

    // 3D
    SetCamera(Camera),
    DrawMesh {
        mesh: MeshId,
        material: MaterialId,
        transform: Mat4,
    },
    DrawMeshInstanced {
        mesh: MeshId,
        instances: Vec<MeshInstance>,
    },
    AddLight(Light),
    SetEnvironment(Environment),

    // Layer
    PushLayer(LayerConfig),
    PopLayer,
    SampleLayer {
        id: LayerId,
        source_rect: Rect,
        dest_rect: Rect,
    },
}

/// A draw context that records commands for later execution
#[derive(Debug, Default)]
pub struct RecordingContext {
    commands: Vec<DrawCommand>,
    transform_stack: Vec<Transform>,
    opacity_stack: Vec<f32>,
    blend_mode_stack: Vec<BlendMode>,
    viewport: Size,
    is_3d: bool,
}

impl RecordingContext {
    /// Create a new recording context
    pub fn new(viewport: Size) -> Self {
        Self {
            commands: Vec::new(),
            transform_stack: vec![Transform::identity()],
            opacity_stack: vec![1.0],
            blend_mode_stack: vec![BlendMode::Normal],
            viewport,
            is_3d: false,
        }
    }

    /// Get the recorded commands
    pub fn commands(&self) -> &[DrawCommand] {
        &self.commands
    }

    /// Take the recorded commands
    pub fn take_commands(&mut self) -> Vec<DrawCommand> {
        std::mem::take(&mut self.commands)
    }

    /// Clear all recorded commands
    pub fn clear(&mut self) {
        self.commands.clear();
        self.transform_stack = vec![Transform::identity()];
        self.opacity_stack = vec![1.0];
        self.blend_mode_stack = vec![BlendMode::Normal];
    }
}

impl DrawContext for RecordingContext {
    fn push_transform(&mut self, transform: Transform) {
        self.commands
            .push(DrawCommand::PushTransform(transform.clone()));
        self.transform_stack.push(transform);
    }

    fn pop_transform(&mut self) {
        self.commands.push(DrawCommand::PopTransform);
        if self.transform_stack.len() > 1 {
            self.transform_stack.pop();
        }
    }

    fn current_transform(&self) -> Transform {
        self.transform_stack.last().cloned().unwrap_or_default()
    }

    fn push_clip(&mut self, shape: ClipShape) {
        self.commands.push(DrawCommand::PushClip(shape));
    }

    fn pop_clip(&mut self) {
        self.commands.push(DrawCommand::PopClip);
    }

    fn push_opacity(&mut self, opacity: f32) {
        self.commands.push(DrawCommand::PushOpacity(opacity));
        let current = *self.opacity_stack.last().unwrap_or(&1.0);
        self.opacity_stack.push(current * opacity);
    }

    fn pop_opacity(&mut self) {
        self.commands.push(DrawCommand::PopOpacity);
        if self.opacity_stack.len() > 1 {
            self.opacity_stack.pop();
        }
    }

    fn push_blend_mode(&mut self, mode: BlendMode) {
        self.commands.push(DrawCommand::PushBlendMode(mode));
        self.blend_mode_stack.push(mode);
    }

    fn pop_blend_mode(&mut self) {
        self.commands.push(DrawCommand::PopBlendMode);
        if self.blend_mode_stack.len() > 1 {
            self.blend_mode_stack.pop();
        }
    }

    fn fill_path(&mut self, path: &Path, brush: Brush) {
        self.commands.push(DrawCommand::FillPath {
            path: path.clone(),
            brush,
        });
    }

    fn stroke_path(&mut self, path: &Path, stroke: &Stroke, brush: Brush) {
        self.commands.push(DrawCommand::StrokePath {
            path: path.clone(),
            stroke: stroke.clone(),
            brush,
        });
    }

    fn fill_rect(&mut self, rect: Rect, corner_radius: CornerRadius, brush: Brush) {
        self.commands.push(DrawCommand::FillRect {
            rect,
            corner_radius,
            brush,
        });
    }

    fn stroke_rect(
        &mut self,
        rect: Rect,
        corner_radius: CornerRadius,
        stroke: &Stroke,
        brush: Brush,
    ) {
        self.commands.push(DrawCommand::StrokeRect {
            rect,
            corner_radius,
            stroke: stroke.clone(),
            brush,
        });
    }

    fn fill_circle(&mut self, center: Point, radius: f32, brush: Brush) {
        self.commands.push(DrawCommand::FillCircle {
            center,
            radius,
            brush,
        });
    }

    fn stroke_circle(&mut self, center: Point, radius: f32, stroke: &Stroke, brush: Brush) {
        self.commands.push(DrawCommand::StrokeCircle {
            center,
            radius,
            stroke: stroke.clone(),
            brush,
        });
    }

    fn draw_text(&mut self, text: &str, origin: Point, style: &TextStyle) {
        self.commands.push(DrawCommand::DrawText {
            text: text.to_string(),
            origin,
            style: style.clone(),
        });
    }

    fn draw_image(&mut self, image: ImageId, rect: Rect, options: &ImageOptions) {
        self.commands.push(DrawCommand::DrawImage {
            image,
            rect,
            options: options.clone(),
        });
    }

    fn draw_shadow(&mut self, rect: Rect, corner_radius: CornerRadius, shadow: Shadow) {
        self.commands.push(DrawCommand::DrawShadow {
            rect,
            corner_radius,
            shadow,
        });
    }

    fn draw_inner_shadow(&mut self, rect: Rect, corner_radius: CornerRadius, shadow: Shadow) {
        self.commands.push(DrawCommand::DrawInnerShadow {
            rect,
            corner_radius,
            shadow,
        });
    }

    fn draw_circle_shadow(&mut self, center: Point, radius: f32, shadow: Shadow) {
        self.commands.push(DrawCommand::DrawCircleShadow {
            center,
            radius,
            shadow,
        });
    }

    fn draw_circle_inner_shadow(&mut self, center: Point, radius: f32, shadow: Shadow) {
        self.commands.push(DrawCommand::DrawCircleInnerShadow {
            center,
            radius,
            shadow,
        });
    }

    fn sdf_build(&mut self, f: &mut dyn FnMut(&mut dyn SdfBuilder)) {
        let mut builder = RecordingSdfBuilder::new();
        f(&mut builder);

        // Process shadows first (they render behind fills)
        for (shape_id, shadow) in &builder.shadows {
            if let Some(shape) = builder.shapes.get(shape_id.0 as usize) {
                match shape {
                    SdfShape::Rect {
                        rect,
                        corner_radius,
                    } => {
                        self.draw_shadow(*rect, *corner_radius, *shadow);
                    }
                    SdfShape::Circle { center, radius } => {
                        // Use proper circle shadow for radially symmetric blur
                        self.draw_circle_shadow(*center, *radius, *shadow);
                    }
                    SdfShape::Ellipse { center, radii } => {
                        let rect =
                            Rect::from_center(*center, Size::new(radii.x * 2.0, radii.y * 2.0));
                        // Use smaller radius for corner approximation
                        self.draw_shadow(rect, radii.x.min(radii.y).into(), *shadow);
                    }
                    _ => {
                        // Complex shapes: use bounding box approximation
                    }
                }
            }
        }

        // Process fills
        for (shape_id, brush) in builder.fills {
            if let Some(shape) = builder.shapes.get(shape_id.0 as usize) {
                match shape {
                    SdfShape::Rect {
                        rect,
                        corner_radius,
                    } => {
                        self.fill_rect(*rect, *corner_radius, brush);
                    }
                    SdfShape::Circle { center, radius } => {
                        self.fill_circle(*center, *radius, brush);
                    }
                    SdfShape::Ellipse { center, radii } => {
                        // Ellipse as a path (approximated with bezier curves)
                        let path = Path::circle(*center, radii.x); // Simplified: use as circle
                        self.fill_path(&path, brush);
                    }
                    SdfShape::Line { from, to, width } => {
                        // Line as a stroked path
                        let path = Path::line(*from, *to);
                        self.stroke_path(&path, &Stroke::new(*width), brush);
                    }
                    _ => {
                        // Complex SDF shapes need GPU-side evaluation
                    }
                }
            }
        }

        // Process strokes
        for (shape_id, stroke, brush) in builder.strokes {
            if let Some(shape) = builder.shapes.get(shape_id.0 as usize) {
                match shape {
                    SdfShape::Rect {
                        rect,
                        corner_radius,
                    } => {
                        self.stroke_rect(*rect, *corner_radius, &stroke, brush);
                    }
                    SdfShape::Circle { center, radius } => {
                        self.stroke_circle(*center, *radius, &stroke, brush);
                    }
                    SdfShape::Ellipse { center, radii } => {
                        let path = Path::circle(*center, radii.x); // Simplified
                        self.stroke_path(&path, &stroke, brush);
                    }
                    SdfShape::Line { from, to, .. } => {
                        let path = Path::line(*from, *to);
                        self.stroke_path(&path, &stroke, brush);
                    }
                    _ => {
                        // Complex SDF shapes need GPU-side evaluation
                    }
                }
            }
        }
    }

    fn set_camera(&mut self, camera: &Camera) {
        self.commands.push(DrawCommand::SetCamera(camera.clone()));
        self.is_3d = true;
    }

    fn draw_mesh(&mut self, mesh: MeshId, material: MaterialId, transform: Mat4) {
        self.commands.push(DrawCommand::DrawMesh {
            mesh,
            material,
            transform,
        });
    }

    fn draw_mesh_instanced(&mut self, mesh: MeshId, instances: &[MeshInstance]) {
        self.commands.push(DrawCommand::DrawMeshInstanced {
            mesh,
            instances: instances.to_vec(),
        });
    }

    fn add_light(&mut self, light: Light) {
        self.commands.push(DrawCommand::AddLight(light));
    }

    fn set_environment(&mut self, env: &Environment) {
        self.commands.push(DrawCommand::SetEnvironment(env.clone()));
    }

    fn billboard_draw(
        &mut self,
        _size: Size,
        _transform: Mat4,
        _facing: BillboardFacing,
        f: &mut dyn FnMut(&mut dyn DrawContext),
    ) {
        // Create a sub-context for the billboard content
        let mut sub_ctx = RecordingContext::new(self.viewport);
        f(&mut sub_ctx);
        // In a real implementation, this would record the billboard as a nested layer
        self.commands.extend(sub_ctx.commands);
    }

    fn viewport_3d_draw(
        &mut self,
        _rect: Rect,
        camera: &Camera,
        f: &mut dyn FnMut(&mut dyn DrawContext),
    ) {
        // Set up 3D context
        let was_3d = self.is_3d;
        self.set_camera(camera);

        // Execute 3D drawing
        f(self);

        // Restore 2D context
        self.is_3d = was_3d;
    }

    fn push_layer(&mut self, config: LayerConfig) {
        self.commands.push(DrawCommand::PushLayer(config));
    }

    fn pop_layer(&mut self) {
        self.commands.push(DrawCommand::PopLayer);
    }

    fn sample_layer(&mut self, id: LayerId, source_rect: Rect, dest_rect: Rect) {
        self.commands.push(DrawCommand::SampleLayer {
            id,
            source_rect,
            dest_rect,
        });
    }

    fn viewport_size(&self) -> Size {
        self.viewport
    }

    fn is_3d_context(&self) -> bool {
        self.is_3d
    }

    fn current_opacity(&self) -> f32 {
        *self.opacity_stack.last().unwrap_or(&1.0)
    }

    fn current_blend_mode(&self) -> BlendMode {
        self.blend_mode_stack
            .last()
            .copied()
            .unwrap_or(BlendMode::Normal)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Recording SDF Builder
// ─────────────────────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
enum SdfShape {
    Rect {
        rect: Rect,
        corner_radius: CornerRadius,
    },
    Circle {
        center: Point,
        radius: f32,
    },
    Ellipse {
        center: Point,
        radii: Vec2,
    },
    Line {
        from: Point,
        to: Point,
        width: f32,
    },
    Arc {
        center: Point,
        radius: f32,
        start: f32,
        end: f32,
        width: f32,
    },
    QuadBezier {
        p0: Point,
        p1: Point,
        p2: Point,
        width: f32,
    },
    Union {
        a: ShapeId,
        b: ShapeId,
    },
    Subtract {
        a: ShapeId,
        b: ShapeId,
    },
    Intersect {
        a: ShapeId,
        b: ShapeId,
    },
    SmoothUnion {
        a: ShapeId,
        b: ShapeId,
        radius: f32,
    },
    SmoothSubtract {
        a: ShapeId,
        b: ShapeId,
        radius: f32,
    },
    SmoothIntersect {
        a: ShapeId,
        b: ShapeId,
        radius: f32,
    },
    Round {
        shape: ShapeId,
        radius: f32,
    },
    Outline {
        shape: ShapeId,
        width: f32,
    },
    Offset {
        shape: ShapeId,
        distance: f32,
    },
}

struct RecordingSdfBuilder {
    shapes: Vec<SdfShape>,
    fills: Vec<(ShapeId, Brush)>,
    strokes: Vec<(ShapeId, Stroke, Brush)>,
    shadows: Vec<(ShapeId, Shadow)>,
}

impl RecordingSdfBuilder {
    fn new() -> Self {
        Self {
            shapes: Vec::new(),
            fills: Vec::new(),
            strokes: Vec::new(),
            shadows: Vec::new(),
        }
    }

    fn add_shape(&mut self, shape: SdfShape) -> ShapeId {
        let id = ShapeId(self.shapes.len() as u32);
        self.shapes.push(shape);
        id
    }
}

impl SdfBuilder for RecordingSdfBuilder {
    fn rect(&mut self, rect: Rect, corner_radius: CornerRadius) -> ShapeId {
        self.add_shape(SdfShape::Rect {
            rect,
            corner_radius,
        })
    }

    fn circle(&mut self, center: Point, radius: f32) -> ShapeId {
        self.add_shape(SdfShape::Circle { center, radius })
    }

    fn ellipse(&mut self, center: Point, radii: Vec2) -> ShapeId {
        self.add_shape(SdfShape::Ellipse { center, radii })
    }

    fn line(&mut self, from: Point, to: Point, width: f32) -> ShapeId {
        self.add_shape(SdfShape::Line { from, to, width })
    }

    fn arc(&mut self, center: Point, radius: f32, start: f32, end: f32, width: f32) -> ShapeId {
        self.add_shape(SdfShape::Arc {
            center,
            radius,
            start,
            end,
            width,
        })
    }

    fn quad_bezier(&mut self, p0: Point, p1: Point, p2: Point, width: f32) -> ShapeId {
        self.add_shape(SdfShape::QuadBezier { p0, p1, p2, width })
    }

    fn union(&mut self, a: ShapeId, b: ShapeId) -> ShapeId {
        self.add_shape(SdfShape::Union { a, b })
    }

    fn subtract(&mut self, a: ShapeId, b: ShapeId) -> ShapeId {
        self.add_shape(SdfShape::Subtract { a, b })
    }

    fn intersect(&mut self, a: ShapeId, b: ShapeId) -> ShapeId {
        self.add_shape(SdfShape::Intersect { a, b })
    }

    fn smooth_union(&mut self, a: ShapeId, b: ShapeId, radius: f32) -> ShapeId {
        self.add_shape(SdfShape::SmoothUnion { a, b, radius })
    }

    fn smooth_subtract(&mut self, a: ShapeId, b: ShapeId, radius: f32) -> ShapeId {
        self.add_shape(SdfShape::SmoothSubtract { a, b, radius })
    }

    fn smooth_intersect(&mut self, a: ShapeId, b: ShapeId, radius: f32) -> ShapeId {
        self.add_shape(SdfShape::SmoothIntersect { a, b, radius })
    }

    fn round(&mut self, shape: ShapeId, radius: f32) -> ShapeId {
        self.add_shape(SdfShape::Round { shape, radius })
    }

    fn outline(&mut self, shape: ShapeId, width: f32) -> ShapeId {
        self.add_shape(SdfShape::Outline { shape, width })
    }

    fn offset(&mut self, shape: ShapeId, distance: f32) -> ShapeId {
        self.add_shape(SdfShape::Offset { shape, distance })
    }

    fn fill(&mut self, shape: ShapeId, brush: Brush) {
        self.fills.push((shape, brush));
    }

    fn stroke(&mut self, shape: ShapeId, stroke: &Stroke, brush: Brush) {
        self.strokes.push((shape, stroke.clone(), brush));
    }

    fn shadow(&mut self, shape: ShapeId, shadow: Shadow) {
        self.shadows.push((shape, shadow));
    }
}

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

    #[test]
    fn test_recording_context() {
        let mut ctx = RecordingContext::new(Size::new(800.0, 600.0));

        ctx.push_transform(Transform::translate(10.0, 20.0));
        ctx.fill_rect(
            Rect::new(0.0, 0.0, 100.0, 50.0),
            8.0.into(),
            Color::BLUE.into(),
        );
        ctx.draw_text("Hello", Point::new(10.0, 30.0), &TextStyle::default());
        ctx.pop_transform();

        assert_eq!(ctx.commands().len(), 4);
    }

    #[test]
    fn test_path_builder() {
        let path = Path::new()
            .move_to(0.0, 0.0)
            .line_to(100.0, 0.0)
            .line_to(100.0, 100.0)
            .line_to(0.0, 100.0)
            .close();

        assert_eq!(path.commands().len(), 5);
    }

    #[test]
    fn test_path_shortcuts() {
        let rect = Path::rect(Rect::new(0.0, 0.0, 100.0, 50.0));
        assert_eq!(rect.commands().len(), 5); // move + 3 lines + close

        let circle = Path::circle(Point::new(50.0, 50.0), 25.0);
        assert!(!circle.is_empty());
    }

    #[test]
    fn test_transform_stack() {
        let mut ctx = RecordingContext::new(Size::new(800.0, 600.0));

        assert!(ctx.current_transform().is_2d());

        ctx.push_transform(Transform::translate(10.0, 20.0));
        ctx.push_transform(Transform::scale(2.0, 2.0));

        ctx.pop_transform();
        ctx.pop_transform();

        // Should not panic when popping past the root
        ctx.pop_transform();
    }

    #[test]
    fn test_opacity_stack() {
        let mut ctx = RecordingContext::new(Size::new(800.0, 600.0));

        assert_eq!(ctx.current_opacity(), 1.0);

        ctx.push_opacity(0.5);
        assert_eq!(ctx.current_opacity(), 0.5);

        ctx.push_opacity(0.5);
        assert_eq!(ctx.current_opacity(), 0.25); // 0.5 * 0.5

        ctx.pop_opacity();
        assert_eq!(ctx.current_opacity(), 0.5);
    }

    #[test]
    fn test_sdf_builder() {
        let mut ctx = RecordingContext::new(Size::new(800.0, 600.0));

        ctx.sdf(|sdf| {
            let rect = sdf.rect(Rect::new(0.0, 0.0, 100.0, 50.0), 8.0.into());
            sdf.fill(rect, Color::BLUE.into());

            let circle = sdf.circle(Point::new(50.0, 50.0), 25.0);
            sdf.fill(circle, Color::RED.into());
        });

        // Should have recorded the fills as rect/circle commands
        assert!(!ctx.commands().is_empty());
    }

    #[test]
    fn test_stroke_configuration() {
        let stroke = Stroke::new(2.0)
            .with_cap(LineCap::Round)
            .with_join(LineJoin::Bevel)
            .with_dash(vec![5.0, 3.0], 0.0);

        assert_eq!(stroke.width, 2.0);
        assert_eq!(stroke.cap, LineCap::Round);
        assert_eq!(stroke.join, LineJoin::Bevel);
        assert_eq!(stroke.dash.len(), 2);
    }

    #[test]
    fn test_text_style() {
        let style = TextStyle::new(16.0)
            .with_color(Color::WHITE)
            .with_weight(FontWeight::Bold)
            .with_family("Arial");

        assert_eq!(style.size, 16.0);
        assert_eq!(style.weight, FontWeight::Bold);
        assert_eq!(style.family, "Arial");
    }

    #[test]
    fn test_draw_context_ext() {
        let mut ctx = RecordingContext::new(Size::new(800.0, 600.0));

        // Test the extension trait methods
        let path = Path::rect(Rect::new(0.0, 0.0, 100.0, 50.0));
        ctx.fill(&path, Color::BLUE);
        ctx.fill_rounded_rect(Rect::new(10.0, 10.0, 80.0, 30.0), 4.0.into(), Color::RED);

        assert_eq!(ctx.commands().len(), 2);
    }
}