mirui 0.24.0

A lightweight, no_std ECS-driven UI framework for embedded, desktop, and WebAssembly
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
use crate::types::{Color, Fixed, Point, Rect, Transform, Viewport};

use super::canvas::Canvas;
use super::command::DrawCommand;
use super::path::Path;
use super::renderer::Renderer;
use super::texture::Texture;

#[cfg(feature = "perf")]
pub mod perf;
#[cfg(feature = "perf")]
pub use perf::{PerfCtx, quad_perf};

mod blit_dispatch;
mod blit_fast;
pub mod blur;
mod label;
pub mod mix;
mod path;
mod quad;
mod quad_aa;
mod rect_fill;
mod rect_stroke;
mod transformed;
use quad::{blit_quad, fill_rect_quad, stroke_rect_quad};
use transformed::{blit_transformed, fill_rect_transformed, offset_point, offset_rect};

pub use crate::draw::texture::AlphaMode;

pub struct SwRenderer<'a> {
    pub target: Texture<'a>,
    pub viewport: Viewport,
    #[cfg(feature = "perf")]
    pub perf: Option<PerfCtx>,
}

impl<'a> SwRenderer<'a> {
    pub fn new(target: Texture<'a>) -> Self {
        let w = target.width;
        let h = target.height;
        Self {
            target,
            viewport: Viewport::new(w, h, Fixed::ONE),
            #[cfg(feature = "perf")]
            perf: None,
        }
    }

    /// Sets the destination buffer's alpha mode. `Opaque` (the
    /// default) writes `dst.a = 255` on every pixel — correct for
    /// framebuffer output. `Blend` accumulates `dst.a` via
    /// non-premultiplied source-over so a sampler reading the
    /// buffer's alpha channel sees a correct silhouette; intended
    /// for offscreen buffers feeding effect widgets that read the
    /// alpha channel.
    pub fn with_alpha_mode(mut self, mode: AlphaMode) -> Self {
        self.target.alpha_mode = mode;
        self
    }
}

impl<'a> SwRenderer<'a> {
    /// Each `DrawCommand` arm is `#[inline(never)]` so `Renderer::draw`
    /// stays small enough to fit ESP32-C3's 16 KiB ICache. Letting LLVM
    /// inline the full dispatch chain produced a 20 KiB monolith that
    /// guaranteed cache miss every frame.
    #[inline(never)]
    fn draw_transformed(&mut self, cmd: &DrawCommand, clip: &Rect, tf: &Transform) {
        let vp = self.viewport.as_transform();
        let phys_tf = vp.compose(tf);
        let phys_clip = self.viewport.rect_to_physical(*clip);
        match cmd {
            DrawCommand::Fill {
                area, color, opa, ..
            } => {
                fill_rect_transformed(&mut self.target, *area, phys_clip, &phys_tf, color, *opa);
            }
            DrawCommand::Blit {
                pos, size, texture, ..
            } => {
                let src_rect = Rect::new(0, 0, texture.width, texture.height);
                let dst = Rect {
                    x: pos.x,
                    y: pos.y,
                    w: size.x,
                    h: size.y,
                };
                blit_transformed(
                    &mut self.target,
                    texture,
                    &src_rect,
                    dst,
                    phys_clip,
                    &phys_tf,
                );
            }
            _ => unimplemented!(
                "sw backend: {:?} under non-axis-aligned transform not yet supported",
                core::mem::discriminant(cmd)
            ),
        }
    }
}

impl<'a> Canvas for SwRenderer<'a> {
    fn fill_path(&mut self, path: &Path, clip: &Rect, color: &Color, opa: u8) {
        self.fill_path_inner(path, clip, color, opa);
    }

    fn stroke_path(&mut self, path: &Path, clip: &Rect, width: Fixed, color: &Color, opa: u8) {
        self.stroke_path_inner(path, clip, width, color, opa);
    }

    fn fill_rect(&mut self, area: &Rect, clip: &Rect, color: &Color, radius: Fixed, opa: u8) {
        self.fill_rect_inner(area, clip, color, radius, opa);
    }

    fn stroke_rect(
        &mut self,
        area: &Rect,
        clip: &Rect,
        width: Fixed,
        color: &Color,
        radius: Fixed,
        opa: u8,
    ) {
        self.stroke_rect_inner(area, clip, width, color, radius, opa);
    }

    fn blit(&mut self, src: &Texture, src_rect: &Rect, dst: Point, dst_size: Point, clip: &Rect) {
        self.blit_inner(src, src_rect, dst, dst_size, clip);
    }

    fn clear(&mut self, area: &Rect, color: &Color) {
        let phys_area = self.viewport.rect_to_physical(*area);
        let screen = Rect::new(0, 0, self.target.width, self.target.height);
        let Some(draw_area) = phys_area.intersect(&screen) else {
            return;
        };
        let (px_x0, px_y0, px_x1, px_y1) = draw_area.pixel_bounds();
        for py in px_y0..px_y1 {
            for px in px_x0..px_x1 {
                self.target.set_pixel(px, py, color);
            }
        }
    }

    fn draw_label(&mut self, pos: &Point, text: &[u8], clip: &Rect, color: &Color, opa: u8) {
        self.draw_label_inner(pos, text, clip, color, opa);
    }

    fn flush(&mut self) {}
}

impl SwRenderer<'_> {
    #[inline(never)]
    fn dispatch_fill_quad(
        &mut self,
        q: &[Point; 4],
        area: &Rect,
        color: &Color,
        radius: Fixed,
        opa: u8,
        clip: &Rect,
    ) {
        #[cfg(feature = "perf")]
        let t0 = quad_perf::now();
        let phys_clip = self.viewport.rect_to_physical(*clip);
        let phys_q = [
            self.viewport.point_to_physical(q[0]),
            self.viewport.point_to_physical(q[1]),
            self.viewport.point_to_physical(q[2]),
            self.viewport.point_to_physical(q[3]),
        ];
        let s = self.viewport.scale();
        fill_rect_quad(
            &mut self.target,
            &phys_q,
            phys_clip,
            color,
            radius * s,
            area.w * s,
            area.h * s,
            opa,
        );
        #[cfg(feature = "perf")]
        quad_perf::add_fill(quad_perf::now().wrapping_sub(t0));
    }

    #[inline(never)]
    fn dispatch_blit_quad(&mut self, q: &[Point; 4], texture: &Texture, clip: &Rect) {
        #[cfg(feature = "perf")]
        let t0 = quad_perf::now();
        let phys_clip = self.viewport.rect_to_physical(*clip);
        let phys_q = [
            self.viewport.point_to_physical(q[0]),
            self.viewport.point_to_physical(q[1]),
            self.viewport.point_to_physical(q[2]),
            self.viewport.point_to_physical(q[3]),
        ];
        blit_quad(&mut self.target, texture, &phys_q, phys_clip);
        #[cfg(feature = "perf")]
        quad_perf::add_blit(quad_perf::now().wrapping_sub(t0));
    }

    #[inline(never)]
    fn dispatch_border_quad(
        &mut self,
        q: &[Point; 4],
        color: &Color,
        width: Fixed,
        radius: Fixed,
        opa: u8,
        clip: &Rect,
    ) {
        let phys_clip = self.viewport.rect_to_physical(*clip);
        let phys_q = [
            self.viewport.point_to_physical(q[0]),
            self.viewport.point_to_physical(q[1]),
            self.viewport.point_to_physical(q[2]),
            self.viewport.point_to_physical(q[3]),
        ];
        let s = self.viewport.scale();
        stroke_rect_quad(
            &mut self.target,
            &phys_q,
            phys_clip,
            color,
            width * s,
            radius * s,
            opa,
        );
    }

    #[inline(never)]
    #[allow(clippy::too_many_arguments)]
    fn dispatch_fill(
        &mut self,
        area: &Rect,
        color: &Color,
        radius: Fixed,
        opa: u8,
        tx: Fixed,
        ty: Fixed,
        clip: &Rect,
    ) {
        #[cfg(feature = "perf")]
        let t0 = self.perf.as_ref().map(|p| (p.clock)());
        let area = offset_rect(area, tx, ty);
        self.fill_rect(&area, clip, color, radius, opa);
        #[cfg(feature = "perf")]
        if let (Some(t0), Some(p)) = (t0, self.perf.as_mut()) {
            p.fill += (p.clock)() - t0;
            p.count_fill += 1;
        }
    }

    #[inline(never)]
    #[allow(clippy::too_many_arguments)]
    fn dispatch_border(
        &mut self,
        area: &Rect,
        color: &Color,
        width: Fixed,
        radius: Fixed,
        opa: u8,
        tx: Fixed,
        ty: Fixed,
        clip: &Rect,
    ) {
        #[cfg(feature = "perf")]
        let t0 = self.perf.as_ref().map(|p| (p.clock)());
        let area = offset_rect(area, tx, ty);
        self.stroke_rect(&area, clip, width, color, radius, opa);
        #[cfg(feature = "perf")]
        if let (Some(t0), Some(p)) = (t0, self.perf.as_mut()) {
            p.stroke += (p.clock)() - t0;
            p.count_stroke += 1;
        }
    }

    #[inline(never)]
    fn dispatch_blit(
        &mut self,
        pos: &Point,
        size: Point,
        texture: &Texture,
        tx: Fixed,
        ty: Fixed,
        clip: &Rect,
    ) {
        #[cfg(feature = "perf")]
        let t0 = self.perf.as_ref().map(|p| (p.clock)());
        let src_rect = Rect::new(0, 0, texture.width, texture.height);
        let pos = offset_point(pos, tx, ty);
        self.blit(texture, &src_rect, pos, size, clip);
        #[cfg(feature = "perf")]
        if let (Some(t0), Some(p)) = (t0, self.perf.as_mut()) {
            p.blit += (p.clock)() - t0;
            p.count_blit += 1;
        }
    }

    #[inline(never)]
    #[allow(clippy::too_many_arguments)]
    fn dispatch_label(
        &mut self,
        pos: &Point,
        text: &[u8],
        color: &Color,
        opa: u8,
        tx: Fixed,
        ty: Fixed,
        clip: &Rect,
    ) {
        #[cfg(feature = "perf")]
        let t0 = self.perf.as_ref().map(|p| (p.clock)());
        let pos = offset_point(pos, tx, ty);
        self.draw_label(&pos, text, clip, color, opa);
        #[cfg(feature = "perf")]
        if let (Some(t0), Some(p)) = (t0, self.perf.as_mut()) {
            p.label += (p.clock)() - t0;
            p.count_label += 1;
        }
    }

    #[inline(never)]
    #[allow(clippy::too_many_arguments)]
    fn dispatch_line(
        &mut self,
        p1: &Point,
        p2: &Point,
        color: &Color,
        width: Fixed,
        opa: u8,
        tx: Fixed,
        ty: Fixed,
        clip: &Rect,
    ) {
        #[cfg(feature = "perf")]
        let t0 = self.perf.as_ref().map(|p| (p.clock)());
        let p1 = offset_point(p1, tx, ty);
        let p2 = offset_point(p2, tx, ty);
        self.draw_line(p1, p2, clip, width, color, opa);
        #[cfg(feature = "perf")]
        if let (Some(t0), Some(p)) = (t0, self.perf.as_mut()) {
            p.stroke += (p.clock)() - t0;
            p.count_stroke += 1;
        }
    }

    #[inline(never)]
    #[allow(clippy::too_many_arguments)]
    fn dispatch_arc(
        &mut self,
        center: &Point,
        radius: Fixed,
        start_angle: Fixed,
        end_angle: Fixed,
        color: &Color,
        width: Fixed,
        opa: u8,
        tx: Fixed,
        ty: Fixed,
        clip: &Rect,
    ) {
        #[cfg(feature = "perf")]
        let t0 = self.perf.as_ref().map(|p| (p.clock)());
        let center = offset_point(center, tx, ty);
        self.draw_arc(
            center,
            radius,
            start_angle,
            end_angle,
            clip,
            width,
            color,
            opa,
        );
        #[cfg(feature = "perf")]
        if let (Some(t0), Some(p)) = (t0, self.perf.as_mut()) {
            p.stroke += (p.clock)() - t0;
            p.count_stroke += 1;
        }
    }
}

impl Renderer for SwRenderer<'_> {
    fn draw(&mut self, cmd: &DrawCommand, clip: &Rect) {
        use crate::types::TransformClass;

        // Quad fast paths short-circuit before the translate/transform branch.
        if let DrawCommand::Fill {
            area,
            quad: Some(q),
            color,
            opa,
            radius,
            ..
        } = cmd
        {
            crate::trace_span!("sw.fill_quad");
            self.dispatch_fill_quad(q, area, color, *radius, *opa, clip);
            return;
        }
        if let DrawCommand::Blit {
            quad: Some(q),
            texture,
            ..
        } = cmd
        {
            crate::trace_span!("sw.blit_quad");
            self.dispatch_blit_quad(q, texture, clip);
            return;
        }
        if let DrawCommand::Border {
            quad: Some(q),
            color,
            width,
            radius,
            opa,
            ..
        } = cmd
        {
            crate::trace_span!("sw.border_quad");
            self.dispatch_border_quad(q, color, *width, *radius, *opa, clip);
            return;
        }

        let tf = cmd.transform();
        let class = tf.classify();
        if !matches!(class, TransformClass::Identity | TransformClass::Translate) {
            crate::trace_span!("sw.transformed");
            self.draw_transformed(cmd, clip, &tf);
            return;
        }
        let (tx, ty) = match class {
            TransformClass::Identity => (Fixed::ZERO, Fixed::ZERO),
            TransformClass::Translate => (tf.tx, tf.ty),
            _ => unreachable!(),
        };
        match cmd {
            DrawCommand::Fill {
                area,
                color,
                radius,
                opa,
                ..
            } => {
                crate::trace_span!("sw.fill");
                self.dispatch_fill(area, color, *radius, *opa, tx, ty, clip);
            }
            DrawCommand::Border {
                area,
                color,
                width,
                radius,
                opa,
                ..
            } => {
                crate::trace_span!("sw.border");
                self.dispatch_border(area, color, *width, *radius, *opa, tx, ty, clip);
            }
            DrawCommand::Blit {
                pos, size, texture, ..
            } => {
                crate::trace_span!("sw.blit");
                self.dispatch_blit(pos, *size, texture, tx, ty, clip);
            }
            DrawCommand::Label {
                pos,
                text,
                color,
                opa,
                ..
            } => {
                crate::trace_span!("sw.label");
                self.dispatch_label(pos, text, color, *opa, tx, ty, clip);
            }
            DrawCommand::Line {
                p1,
                p2,
                color,
                width,
                opa,
                ..
            } => {
                crate::trace_span!("sw.line");
                self.dispatch_line(p1, p2, color, *width, *opa, tx, ty, clip);
            }
            DrawCommand::Arc {
                center,
                radius,
                start_angle,
                end_angle,
                color,
                width,
                opa,
                ..
            } => {
                crate::trace_span!("sw.arc");
                self.dispatch_arc(
                    center,
                    *radius,
                    *start_angle,
                    *end_angle,
                    color,
                    *width,
                    *opa,
                    tx,
                    ty,
                    clip,
                );
            }
            DrawCommand::FillPath {
                path, color, opa, ..
            } => {
                crate::trace_span!("sw.fill_path");
                if tx == Fixed::ZERO && ty == Fixed::ZERO {
                    self.fill_path_inner(path, clip, color, *opa);
                } else {
                    let translated = translate_path(path, tx, ty);
                    self.fill_path_inner(&translated, clip, color, *opa);
                }
            }
        }
    }

    fn flush(&mut self) {
        Canvas::flush(self);
    }

    fn supports_offscreen(&self) -> bool {
        true
    }

    fn offscreen_format(&self) -> Option<crate::draw::texture::ColorFormat> {
        Some(self.target.format)
    }

    fn sample_target_region(&self, src: &Rect) -> Option<crate::draw::texture::Texture<'static>> {
        let (sx0, sy0, sx1, sy1) = self.viewport.rect_to_physical_pixel_bounds(*src);
        let w = (sx1 - sx0).max(1) as u16;
        let h = (sy1 - sy0).max(1) as u16;
        let mut tex = crate::draw::texture::Texture::owned(w, h, self.target.format);
        self.read_target_region(src, &mut tex);
        Some(tex)
    }

    fn modify_target_region(
        &mut self,
        src: &Rect,
        f: &mut dyn FnMut(&mut crate::draw::texture::Texture),
    ) -> bool {
        use crate::draw::texture::{TexBuf, Texture};
        let (sx0, sy0, sx1, sy1) = self.viewport.rect_to_physical_pixel_bounds(*src);
        let target_w = self.target.width as i32;
        let target_h = self.target.height as i32;
        let cx0 = sx0.max(0);
        let cy0 = sy0.max(0);
        let cx1 = sx1.min(target_w);
        let cy1 = sy1.min(target_h);
        if cx1 <= cx0 || cy1 <= cy0 {
            return false;
        }
        let bpp = self.target.format.bytes_per_pixel();
        let target_stride = self.target.stride;
        let off_start = cy0 as usize * target_stride + cx0 as usize * bpp;
        // `(row_h - 1) * stride + row_w * bpp` so the slice ends at
        // the rect's last pixel, not the last full stride row — the
        // gap past `width` per row is shared with neighbouring
        // entities and must stay outside our borrow.
        let row_w = (cx1 - cx0) as u16;
        let row_h = (cy1 - cy0) as u16;
        let view_bytes = (row_h as usize - 1) * target_stride + row_w as usize * bpp;
        let buf = &mut self.target.buf.as_mut_slice()[off_start..off_start + view_bytes];
        let mut view = Texture {
            buf: TexBuf::Mut(buf),
            width: row_w,
            height: row_h,
            format: self.target.format,
            stride: target_stride,
            alpha_mode: self.target.alpha_mode,
        };
        f(&mut view);
        true
    }

    fn supports_scroll_blit(&self) -> bool {
        true
    }

    fn scroll_target_region(&mut self, area: &Rect, dx: Fixed, dy: Fixed) {
        // Sub-pixel deltas truncate toward zero; the caller is expected
        // to keep the residue and re-submit it next frame. Truncation
        // (not floor) keeps the residue's sign matching the original
        // delta so a `-0.5` shift doesn't bounce to `-1` here and leave
        // a `+0.5` residue.
        let (px0, py0, px1, py1) = self.viewport.rect_to_physical_pixel_bounds(*area);
        let target_w = self.target.width as i32;
        let target_h = self.target.height as i32;
        let scale = self.viewport.scale();
        let dx_phys = (dx * scale).trunc_to_int();
        let dy_phys = (dy * scale).trunc_to_int();
        if dx_phys == 0 && dy_phys == 0 {
            return;
        }

        let sx0 = px0.max(0);
        let sy0 = py0.max(0);
        let sx1 = px1.min(target_w);
        let sy1 = py1.min(target_h);
        if sx1 <= sx0 || sy1 <= sy0 {
            return;
        }

        let bpp = self.target.format.bytes_per_pixel();
        let stride = self.target.stride;
        let buf = self.target.buf.as_mut_slice();

        // Pick row order so a source row is never clobbered before it
        // is read: top-down for dy < 0, bottom-up otherwise.
        let row_iter: alloc::vec::Vec<i32> = if dy_phys >= 0 {
            (sy0..sy1).rev().collect()
        } else {
            (sy0..sy1).collect()
        };

        for src_y in row_iter {
            let dst_y = src_y + dy_phys;
            if dst_y < sy0 || dst_y >= sy1 {
                continue;
            }
            if dx_phys == 0 {
                let src_off = src_y as usize * stride + sx0 as usize * bpp;
                let dst_off = dst_y as usize * stride + sx0 as usize * bpp;
                let row_bytes = (sx1 - sx0) as usize * bpp;
                buf.copy_within(src_off..src_off + row_bytes, dst_off);
                continue;
            }
            let dst_x0 = (sx0 + dx_phys).max(sx0);
            let dst_x1 = (sx1 + dx_phys).min(sx1);
            if dst_x1 <= dst_x0 {
                continue;
            }
            let src_x0 = dst_x0 - dx_phys;
            let copy_w = (dst_x1 - dst_x0) as usize * bpp;
            let src_off = src_y as usize * stride + src_x0 as usize * bpp;
            let dst_off = dst_y as usize * stride + dst_x0 as usize * bpp;
            // `copy_within` is memmove, so within a row overlap is
            // safe; the row_iter direction handles cross-row aliasing.
            buf.copy_within(src_off..src_off + copy_w, dst_off);
        }
    }

    fn read_target_region(&self, src: &Rect, dst: &mut crate::draw::texture::Texture) {
        // Caller may pass a logical-sized dst; clipping to the
        // overlap avoids stretched top-left samples on HiDPI.
        let (sx0, sy0, sx1, sy1) = self.viewport.rect_to_physical_pixel_bounds(*src);
        let target_w = self.target.width as i32;
        let target_h = self.target.height as i32;
        let copy_w = ((sx1 - sx0).min(dst.width as i32)).max(0);
        let copy_h = ((sy1 - sy0).min(dst.height as i32)).max(0);
        if copy_w == 0 || copy_h == 0 {
            return;
        }

        // Same-format fast path: row-wise byte memcpy. Both callers
        // (`try_draw_offscreen` pre-seed, `sample_target_region`)
        // allocate dst at the target's format, so this normally hits.
        if self.target.format == dst.format {
            let bpp = dst.format.bytes_per_pixel();
            let target_buf = self.target.buf.as_slice();
            let dst_buf = dst.buf.as_mut_slice();
            let target_stride = self.target.stride;
            let dst_stride = dst.stride;
            for dy in 0..copy_h as usize {
                let phys_y = sy0 + dy as i32;
                if phys_y < 0 || phys_y >= target_h {
                    continue;
                }
                let src_x_start = sx0.max(0);
                let src_x_end = (sx0 + copy_w).min(target_w);
                if src_x_end <= src_x_start {
                    continue;
                }
                let dst_x_start = (src_x_start - sx0) as usize;
                let row_bytes = (src_x_end - src_x_start) as usize * bpp;
                let src_row_off = phys_y as usize * target_stride + src_x_start as usize * bpp;
                let dst_row_off = dy * dst_stride + dst_x_start * bpp;
                dst_buf[dst_row_off..dst_row_off + row_bytes]
                    .copy_from_slice(&target_buf[src_row_off..src_row_off + row_bytes]);
            }
            return;
        }

        for dy in 0..copy_h {
            for dx in 0..copy_w {
                let phys_x = sx0 + dx;
                let phys_y = sy0 + dy;
                if phys_x < 0 || phys_y < 0 || phys_x >= target_w || phys_y >= target_h {
                    continue;
                }
                let px = self.target.get_pixel(phys_x, phys_y);
                dst.set_pixel(dx, dy, &px);
            }
        }
    }
}

fn translate_path(path: &Path, tx: Fixed, ty: Fixed) -> Path {
    use super::path::PathCmd;
    let cmds = path
        .cmds
        .iter()
        .map(|c| match c {
            PathCmd::MoveTo(p) => PathCmd::MoveTo(Point {
                x: p.x + tx,
                y: p.y + ty,
            }),
            PathCmd::LineTo(p) => PathCmd::LineTo(Point {
                x: p.x + tx,
                y: p.y + ty,
            }),
            PathCmd::QuadTo { ctrl, end } => PathCmd::QuadTo {
                ctrl: Point {
                    x: ctrl.x + tx,
                    y: ctrl.y + ty,
                },
                end: Point {
                    x: end.x + tx,
                    y: end.y + ty,
                },
            },
            PathCmd::CubicTo { ctrl1, ctrl2, end } => PathCmd::CubicTo {
                ctrl1: Point {
                    x: ctrl1.x + tx,
                    y: ctrl1.y + ty,
                },
                ctrl2: Point {
                    x: ctrl2.x + tx,
                    y: ctrl2.y + ty,
                },
                end: Point {
                    x: end.x + tx,
                    y: end.y + ty,
                },
            },
            PathCmd::Close => PathCmd::Close,
        })
        .collect();
    Path { cmds }
}

#[cfg(test)]
mod tests {
    use super::blit_fast::{blit_1to1_fast, blit_2to2_fast, blit_dda, blit_generic_slow};
    use super::*;
    use crate::draw::texture::ColorFormat;
    use alloc::vec;

    /// Blit dst origin at a negative x — common when an OffscreenRender
    /// entity's WidgetTransform translates the buffer off the left
    /// edge — must not write to wrong target rows. Pre-fix, blit_inner
    /// passed `dx0=-N` straight to the path that did `dx0 as usize * 4`
    /// for the row offset, wrapping into a far positive byte index and
    /// scribbling the source texture into a different row of the
    /// target.
    #[test]
    fn blit_at_negative_x_does_not_wrap_into_wrong_rows() {
        let mut tgt_buf = vec![0u8; 64 * 64 * 4];
        let tgt_tex = Texture::new(&mut tgt_buf, 64, 64, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tgt_tex);

        let mut src_buf = vec![0u8; 32 * 32 * 4];
        for px in src_buf.chunks_exact_mut(4) {
            px[0] = 200;
            px[1] = 100;
            px[2] = 50;
            px[3] = 255;
        }
        let src_tex = Texture::new(&mut src_buf, 32, 32, ColorFormat::RGBA8888);
        let src_rect = Rect::new(0, 0, 32, 32);

        let dst = Point::new(Fixed::from_int(-24), Fixed::from_int(8));
        let dst_size = Point::new(Fixed::from_int(32), Fixed::from_int(32));
        let clip = Rect {
            x: Fixed::from_int(-24),
            y: Fixed::from_int(0),
            w: Fixed::from_int(80),
            h: Fixed::from_int(64),
        };
        backend.blit(&src_tex, &src_rect, dst, dst_size, &clip);

        for y in 8..40 {
            for x in 0..8 {
                let p = backend.target.get_pixel(x, y);
                assert_eq!(
                    (p.r, p.g, p.b),
                    (200, 100, 50),
                    "visible pixel ({},{}) should be source colour",
                    x,
                    y
                );
            }
        }
        // Anywhere outside the visible band must stay zeroed; the
        // pre-fix bug wrote source colour into row 8 columns ~40-64
        // because dx0=-24 cast to usize wrapped the row offset.
        for y in 0..64 {
            for x in 0..64 {
                let in_visible = (8..40).contains(&y) && x < 8;
                if in_visible {
                    continue;
                }
                let p = backend.target.get_pixel(x, y);
                assert_eq!(
                    (p.r, p.g, p.b, p.a),
                    (0, 0, 0, 0),
                    "out-of-visible pixel ({},{}) was written",
                    x,
                    y
                );
            }
        }
    }

    /// Same negative-x guard as the RGBA8888 case but exercising the
    /// RGB565Swapped → RGB565Swapped fast path, which has its own
    /// `dx0 as usize * 2` byte-offset arithmetic.
    #[test]
    fn blit_at_negative_x_rgb565_swapped_does_not_wrap() {
        let mut tgt_buf = vec![0u8; 64 * 64 * 2];
        let tgt_tex = Texture::new(&mut tgt_buf, 64, 64, ColorFormat::RGB565Swapped);
        let mut backend = SwRenderer::new(tgt_tex);

        let mut src_buf = vec![0u8; 32 * 32 * 2];
        for px in src_buf.chunks_exact_mut(2) {
            // RGB565Swapped: hi byte first. Pack red = 0xF800,
            // wire bytes [0xF8, 0x00].
            px[0] = 0xF8;
            px[1] = 0x00;
        }
        let src_tex = Texture::new(&mut src_buf, 32, 32, ColorFormat::RGB565Swapped);
        let src_rect = Rect::new(0, 0, 32, 32);

        let dst = Point::new(Fixed::from_int(-24), Fixed::from_int(8));
        let dst_size = Point::new(Fixed::from_int(32), Fixed::from_int(32));
        let clip = Rect {
            x: Fixed::from_int(-24),
            y: Fixed::from_int(0),
            w: Fixed::from_int(80),
            h: Fixed::from_int(64),
        };
        backend.blit(&src_tex, &src_rect, dst, dst_size, &clip);

        for y in 8..40 {
            for x in 0..8 {
                let p = backend.target.get_pixel(x, y);
                assert_eq!(p.r, 248, "visible pixel ({},{}) should be red", x, y);
            }
        }
        for y in 0..64 {
            for x in 0..64 {
                let in_visible = (8..40).contains(&y) && x < 8;
                if in_visible {
                    continue;
                }
                let off = (y as usize * 64 + x as usize) * 2;
                assert_eq!(
                    (
                        backend.target.buf.as_slice()[off],
                        backend.target.buf.as_slice()[off + 1]
                    ),
                    (0, 0),
                    "out-of-visible pixel ({},{}) was written",
                    x,
                    y
                );
            }
        }
    }

    #[test]
    fn fill_rect_basic() {
        let mut buf = vec![0u8; 16 * 16 * 4];
        let tex = Texture::new(&mut buf, 16, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let rect = Rect::new(2, 2, 4, 4);
        let clip = Rect::new(0, 0, 16, 16);
        backend.fill_rect(&rect, &clip, &Color::rgb(255, 0, 0), Fixed::ZERO, 255);

        let c = backend.target.get_pixel(3, 3);
        assert_eq!(c.r, 255);
        assert_eq!(c.g, 0);
        assert_eq!(c.b, 0);

        let c = backend.target.get_pixel(0, 0);
        assert_eq!(c.r, 0);
    }

    #[test]
    fn clear_fills_area() {
        let mut buf = vec![0u8; 8 * 8 * 4];
        let tex = Texture::new(&mut buf, 8, 8, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        backend.clear(&Rect::new(0, 0, 8, 8), &Color::rgb(50, 100, 150));

        let c = backend.target.get_pixel(4, 4);
        assert_eq!(c.r, 50);
        assert_eq!(c.g, 100);
        assert_eq!(c.b, 150);
    }

    #[test]
    fn fill_path_rect_matches_fill_rect() {
        // A rectangular Path should produce the same interior pixels as fill_rect.
        let mut buf = vec![0u8; 16 * 16 * 4];
        let tex = Texture::new(&mut buf, 16, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let path = super::super::path::Path::rect(
            Fixed::from_int(2),
            Fixed::from_int(2),
            Fixed::from_int(8),
            Fixed::from_int(8),
        );
        let clip = Rect::new(0, 0, 16, 16);
        backend.fill_path(&path, &clip, &Color::rgb(0, 0, 255), 255);

        let c = backend.target.get_pixel(5, 5);
        assert_eq!(c.b, 255);
        assert_eq!(c.r, 0);
        let c = backend.target.get_pixel(0, 0);
        assert_eq!(c.b, 0);
    }

    #[test]
    fn fill_path_empty_is_noop() {
        let mut buf = vec![0u8; 4 * 4 * 4];
        let tex = Texture::new(&mut buf, 4, 4, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let path = super::super::path::Path::new();
        let clip = Rect::new(0, 0, 4, 4);
        backend.fill_path(&path, &clip, &Color::rgb(255, 255, 255), 255);

        for y in 0..4 {
            for x in 0..4 {
                assert_eq!(backend.target.get_pixel(x, y).r, 0);
            }
        }
    }

    #[test]
    fn fill_path_zero_opa_is_noop() {
        let mut buf = vec![0u8; 4 * 4 * 4];
        let tex = Texture::new(&mut buf, 4, 4, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let path = super::super::path::Path::rect(
            Fixed::ZERO,
            Fixed::ZERO,
            Fixed::from_int(4),
            Fixed::from_int(4),
        );
        let clip = Rect::new(0, 0, 4, 4);
        backend.fill_path(&path, &clip, &Color::rgb(255, 0, 0), 0);

        assert_eq!(backend.target.get_pixel(2, 2).r, 0);
    }

    #[test]
    fn fill_path_triangle_interior_vs_exterior() {
        // Right triangle with vertices (0,0), (10,0), (0,10). Probe interior
        // point (2,2) vs exterior point (8,8).
        let mut buf = vec![0u8; 16 * 16 * 4];
        let tex = Texture::new(&mut buf, 16, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let mut path = super::super::path::Path::new();
        path.move_to(Point {
            x: Fixed::ZERO,
            y: Fixed::ZERO,
        })
        .line_to(Point {
            x: Fixed::from_int(10),
            y: Fixed::ZERO,
        })
        .line_to(Point {
            x: Fixed::ZERO,
            y: Fixed::from_int(10),
        })
        .close();

        let clip = Rect::new(0, 0, 16, 16);
        backend.fill_path(&path, &clip, &Color::rgb(0, 200, 0), 255);

        assert_eq!(backend.target.get_pixel(2, 2).g, 200);
        assert_eq!(backend.target.get_pixel(8, 8).g, 0);
    }

    #[test]
    fn draw_label_is_reachable_via_trait() {
        // Exercises the trait dispatch path rather than the glyph pixels —
        // just verifies the method exists on Canvas and writes something.
        let mut buf = vec![0u8; 32 * 16 * 4];
        let tex = Texture::new(&mut buf, 32, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let pos = Point {
            x: Fixed::from_int(1),
            y: Fixed::from_int(1),
        };
        let clip = Rect::new(0, 0, 32, 16);
        Canvas::draw_label(&mut backend, &pos, b"A", &clip, &Color::rgb(255, 0, 0), 255);

        let mut found = false;
        for y in 0..16 {
            for x in 0..32 {
                if backend.target.get_pixel(x, y).r > 0 {
                    found = true;
                    break;
                }
            }
        }
        assert!(found, "expected at least one red pixel from glyph");
    }

    #[test]
    fn stroke_path_line_colors_interior_and_skips_far_pixels() {
        // Horizontal line from (2,8) to (14,8), width=2. Interior pixels
        // around y=8 should be colored; pixels several rows away must not.
        let mut buf = vec![0u8; 16 * 16 * 4];
        let tex = Texture::new(&mut buf, 16, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let mut path = super::super::path::Path::new();
        path.move_to(Point {
            x: Fixed::from_int(2),
            y: Fixed::from_int(8),
        })
        .line_to(Point {
            x: Fixed::from_int(14),
            y: Fixed::from_int(8),
        });

        let clip = Rect::new(0, 0, 16, 16);
        backend.stroke_path(
            &path,
            &clip,
            Fixed::from_int(2),
            &Color::rgb(255, 0, 0),
            255,
        );

        assert!(backend.target.get_pixel(8, 8).r > 0);
        assert_eq!(backend.target.get_pixel(8, 0).r, 0);
        assert_eq!(backend.target.get_pixel(8, 15).r, 0);
    }

    #[test]
    fn renderer_dispatches_line_command() {
        use crate::draw::renderer::Renderer;
        let mut buf = vec![0u8; 16 * 16 * 4];
        let tex = Texture::new(&mut buf, 16, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let cmd = DrawCommand::Line {
            p1: Point {
                x: Fixed::from_int(2),
                y: Fixed::from_int(8),
            },
            p2: Point {
                x: Fixed::from_int(14),
                y: Fixed::from_int(8),
            },
            transform: crate::types::Transform::IDENTITY,
            color: Color::rgb(255, 0, 0),
            width: Fixed::from_int(2),
            opa: 255,
        };
        let clip = Rect::new(0, 0, 16, 16);
        Renderer::draw(&mut backend, &cmd, &clip);

        assert!(backend.target.get_pixel(8, 8).r > 0);
    }

    #[test]
    fn renderer_dispatches_arc_command() {
        use crate::draw::renderer::Renderer;
        let mut buf = vec![0u8; 32 * 32 * 4];
        let tex = Texture::new(&mut buf, 32, 32, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let cmd = DrawCommand::Arc {
            center: Point {
                x: Fixed::from_int(16),
                y: Fixed::from_int(16),
            },
            transform: crate::types::Transform::IDENTITY,
            radius: Fixed::from_int(10),
            start_angle: Fixed::from_int(0),
            end_angle: Fixed::from_int(90),
            color: Color::rgb(0, 255, 0),
            width: Fixed::from_int(2),
            opa: 255,
        };
        let clip = Rect::new(0, 0, 32, 32);
        Renderer::draw(&mut backend, &cmd, &clip);

        let hit = backend.target.get_pixel(26, 16).g > 0 || backend.target.get_pixel(25, 16).g > 0;
        assert!(hit);
    }

    #[test]
    fn draw_line_default_impl_strokes_pixels() {
        // Exercises Canvas::draw_line's default trait impl → stroke_path.
        let mut buf = vec![0u8; 16 * 16 * 4];
        let tex = Texture::new(&mut buf, 16, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let p1 = Point {
            x: Fixed::from_int(2),
            y: Fixed::from_int(8),
        };
        let p2 = Point {
            x: Fixed::from_int(14),
            y: Fixed::from_int(8),
        };
        let clip = Rect::new(0, 0, 16, 16);
        backend.draw_line(
            p1,
            p2,
            &clip,
            Fixed::from_int(2),
            &Color::rgb(255, 0, 0),
            255,
        );

        assert!(backend.target.get_pixel(8, 8).r > 0);
    }

    #[test]
    fn draw_arc_default_impl_strokes_pixels() {
        let mut buf = vec![0u8; 32 * 32 * 4];
        let tex = Texture::new(&mut buf, 32, 32, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let center = Point {
            x: Fixed::from_int(16),
            y: Fixed::from_int(16),
        };
        let clip = Rect::new(0, 0, 32, 32);
        backend.draw_arc(
            center,
            Fixed::from_int(10),
            Fixed::from_int(0),
            Fixed::from_int(90),
            &clip,
            Fixed::from_int(2),
            &Color::rgb(0, 255, 0),
            255,
        );

        // The 0°→90° arc runs from (+radius, 0) to (0, +radius) relative to
        // center. Sample a point on the arc and verify green is present.
        assert!(backend.target.get_pixel(26, 16).g > 0 || backend.target.get_pixel(25, 16).g > 0);
    }

    #[test]
    fn stroke_path_zero_width_is_noop() {
        let mut buf = vec![0u8; 8 * 8 * 4];
        let tex = Texture::new(&mut buf, 8, 8, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        let mut path = super::super::path::Path::new();
        path.move_to(Point {
            x: Fixed::ZERO,
            y: Fixed::ZERO,
        })
        .line_to(Point {
            x: Fixed::from_int(8),
            y: Fixed::ZERO,
        });

        let clip = Rect::new(0, 0, 8, 8);
        backend.stroke_path(&path, &clip, Fixed::ZERO, &Color::rgb(255, 0, 0), 255);

        for y in 0..8 {
            for x in 0..8 {
                assert_eq!(backend.target.get_pixel(x, y).r, 0);
            }
        }
    }

    #[test]
    fn painter_fill_rect_with_backend() {
        use crate::draw::painter::Painter;

        let mut buf = vec![0u8; 16 * 16 * 4];
        let tex = Texture::new(&mut buf, 16, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);

        {
            let mut painter = Painter::new(&mut backend);
            let rect = Rect::new(1, 1, 6, 6);
            let clip = Rect::new(0, 0, 16, 16);
            painter.fill_rect(&rect, &clip, &Color::rgb(0, 255, 0), Fixed::ZERO, 255);
        }

        let c = backend.target.get_pixel(3, 3);
        assert_eq!(c.r, 0);
        assert_eq!(c.g, 255);
        assert_eq!(c.b, 0);
    }

    #[test]
    fn painter_forwards_path_and_stroke_methods() {
        use crate::draw::painter::Painter;
        use crate::draw::path::Path;

        let mut buf = vec![0u8; 32 * 32 * 4];
        let tex = Texture::new(&mut buf, 32, 32, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);
        let clip = Rect::new(0, 0, 32, 32);

        {
            let mut painter = Painter::new(&mut backend);
            let path = Path::rect(
                Fixed::from_int(4),
                Fixed::from_int(4),
                Fixed::from_int(10),
                Fixed::from_int(10),
            );
            painter.fill_path(&path, &clip, &Color::rgb(255, 0, 0), 255);

            painter.draw_line(
                Point {
                    x: Fixed::from_int(20),
                    y: Fixed::from_int(20),
                },
                Point {
                    x: Fixed::from_int(28),
                    y: Fixed::from_int(28),
                },
                &clip,
                Fixed::from_int(2),
                &Color::rgb(0, 255, 0),
                255,
            );

            painter.draw_arc(
                Point {
                    x: Fixed::from_int(24),
                    y: Fixed::from_int(8),
                },
                Fixed::from_int(4),
                Fixed::from_int(0),
                Fixed::from_int(90),
                &clip,
                Fixed::from_int(2),
                &Color::rgb(0, 0, 255),
                255,
            );
        }

        assert_eq!(backend.target.get_pixel(8, 8).r, 255);
        assert!(backend.target.get_pixel(24, 24).g > 0);
        assert!(
            backend.target.get_pixel(28, 8).b > 0
                || backend.target.get_pixel(27, 8).b > 0
                || backend.target.get_pixel(28, 9).b > 0,
        );
    }

    #[test]
    fn painter_draw_text_forwards_to_backend() {
        use crate::draw::painter::Painter;

        let mut buf = vec![0u8; 32 * 16 * 4];
        let tex = Texture::new(&mut buf, 32, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);
        let clip = Rect::new(0, 0, 32, 16);

        {
            let mut painter = Painter::new(&mut backend);
            painter.draw_text(
                &Point {
                    x: Fixed::from_int(1),
                    y: Fixed::from_int(1),
                },
                b"B",
                &clip,
                &Color::rgb(200, 100, 50),
                255,
            );
        }

        let mut found = false;
        for y in 0..16 {
            for x in 0..32 {
                if backend.target.get_pixel(x, y).r > 0 {
                    found = true;
                    break;
                }
            }
        }
        assert!(found);
    }

    /// DDA and the divide-based slow path must land on the same src
    /// sample for every dst pixel. Drive both on the same 4×4 → 7×5
    /// non-integer scale and compare dst byte-for-byte.
    #[test]
    fn blit_dda_matches_generic_slow() {
        // Src: 4×4 ARGB with a distinct per-pixel red value so we can
        // tell which src pixel each dst pixel sampled.
        let mut src_buf = vec![0u8; 4 * 4 * 4];
        for y in 0..4 {
            for x in 0..4 {
                let i = (y * 4 + x) * 4;
                src_buf[i] = (y * 4 + x) as u8 * 16 + 1;
                src_buf[i + 3] = 255;
            }
        }
        let src = Texture::new(&mut src_buf, 4, 4, ColorFormat::RGBA8888);

        // Dst: 8×6, draw 7×5 blit at (0,0). Two identical dst buffers.
        let mut dst_a = vec![0u8; 8 * 6 * 4];
        let mut dst_b = vec![0u8; 8 * 6 * 4];

        {
            let mut tex_a = Texture::new(&mut dst_a, 8, 6, ColorFormat::RGBA8888);
            blit_generic_slow(&mut tex_a, &src, 0, 0, 4, 4, 0, 0, 7, 5, 0, 0, 8, 6);
        }
        {
            let mut tex_b = Texture::new(&mut dst_b, 8, 6, ColorFormat::RGBA8888);
            blit_dda(&mut tex_b, &src, 0, 0, 4, 4, 0, 0, 7, 5, 0, 0, 8, 6);
        }

        assert_eq!(dst_a, dst_b, "dda sampling diverged from divide path");
    }

    /// 1× fast path should match the slow path exactly on α==0 and
    /// α==255 pixels, and within ±1 per channel on partial-α blends
    /// (slow path uses Fixed map_range, fast path uses integer
    /// `(src * a + dst * (255 - a)) / 255` — the two differ by at
    /// most one LSB per channel).
    #[test]
    fn blit_1to1_matches_generic_for_argb_to_argb() {
        let mut src_buf = vec![0u8; 4 * 4 * 4];
        for i in 0..16 {
            src_buf[i * 4] = 30 + i as u8;
            src_buf[i * 4 + 1] = 60 + i as u8;
            src_buf[i * 4 + 2] = 90 + i as u8;
            src_buf[i * 4 + 3] = match i {
                0 => 0,
                3 | 7 => 128,
                _ => 255,
            };
        }
        let src = Texture::new(&mut src_buf, 4, 4, ColorFormat::RGBA8888);

        let mut dst_a = vec![0u8; 6 * 6 * 4];
        for (i, byte) in dst_a.iter_mut().enumerate() {
            *byte = (i * 3) as u8;
        }
        let mut dst_b = dst_a.clone();

        {
            let mut tex = Texture::new(&mut dst_a, 6, 6, ColorFormat::RGBA8888);
            blit_generic_slow(&mut tex, &src, 0, 0, 4, 4, 1, 1, 4, 4, 0, 0, 6, 6);
        }
        {
            let mut tex = Texture::new(&mut dst_b, 6, 6, ColorFormat::RGBA8888);
            blit_1to1_fast(&mut tex, &src, 0, 0, 4, 4, 1, 1, 0, 0, 6, 6);
        }
        for (i, (&a, &b)) in dst_a.iter().zip(dst_b.iter()).enumerate() {
            assert!(
                (a as i32 - b as i32).abs() <= 1,
                "byte {} diverged by more than 1: slow={} fast={}",
                i,
                a,
                b
            );
        }
    }

    #[test]
    fn blit_1to1_matches_generic_for_argb_to_565sw() {
        let mut src_buf = vec![0u8; 4 * 4 * 4];
        for i in 0..16 {
            src_buf[i * 4] = 30 + i as u8 * 5;
            src_buf[i * 4 + 1] = 40 + i as u8 * 3;
            src_buf[i * 4 + 2] = 50 + i as u8 * 7;
            src_buf[i * 4 + 3] = if i == 0 { 0 } else { 255 };
        }
        let src = Texture::new(&mut src_buf, 4, 4, ColorFormat::RGBA8888);

        let mut dst_a = vec![0u8; 6 * 6 * 2];
        for i in 0..dst_a.len() {
            dst_a[i] = (i * 5) as u8;
        }
        let mut dst_b = dst_a.clone();

        {
            let mut tex = Texture::new(&mut dst_a, 6, 6, ColorFormat::RGB565Swapped);
            blit_generic_slow(&mut tex, &src, 0, 0, 4, 4, 1, 1, 4, 4, 0, 0, 6, 6);
        }
        {
            let mut tex = Texture::new(&mut dst_b, 6, 6, ColorFormat::RGB565Swapped);
            blit_1to1_fast(&mut tex, &src, 0, 0, 4, 4, 1, 1, 0, 0, 6, 6);
        }
        assert_eq!(dst_a, dst_b);
    }

    /// 2× integer-scale fast path must produce the same 2×2 block
    /// pattern as the slow DDA path for each source pixel. Check
    /// 565sw→565sw (pure copy) for exact parity.
    #[test]
    fn blit_2to2_565sw_matches_dda() {
        let mut src_buf = vec![0u8; 3 * 3 * 2];
        for i in 0..9 {
            src_buf[i * 2] = 0x12 + i as u8;
            src_buf[i * 2 + 1] = 0x34 + i as u8;
        }
        let src = Texture::new(&mut src_buf, 3, 3, ColorFormat::RGB565Swapped);

        let mut dst_a = vec![0u8; 10 * 10 * 2];
        let mut dst_b = vec![0u8; 10 * 10 * 2];
        {
            let mut tex = Texture::new(&mut dst_a, 10, 10, ColorFormat::RGB565Swapped);
            blit_dda(&mut tex, &src, 0, 0, 3, 3, 1, 1, 6, 6, 0, 0, 10, 10);
        }
        {
            let mut tex = Texture::new(&mut dst_b, 10, 10, ColorFormat::RGB565Swapped);
            blit_2to2_fast(&mut tex, &src, 0, 0, 3, 3, 1, 1, 0, 0, 10, 10);
        }
        assert_eq!(dst_a, dst_b);
    }

    /// 2× clip that lands on odd boundaries triggers the fast path's
    /// DDA fallback; verify the fallback still produces correct output.
    #[test]
    fn blit_2to2_odd_clip_falls_back_cleanly() {
        let mut src_buf = vec![0u8; 2 * 2 * 2];
        src_buf[0] = 0xAA;
        src_buf[1] = 0xBB;
        let src = Texture::new(&mut src_buf, 2, 2, ColorFormat::RGB565Swapped);

        let mut dst = vec![0u8; 6 * 6 * 2];
        let mut tex = Texture::new(&mut dst, 6, 6, ColorFormat::RGB565Swapped);
        // Clip starts at odd x=1: fast path 2×2 alignment broken → DDA fallback.
        blit_2to2_fast(&mut tex, &src, 0, 0, 2, 2, 0, 0, 1, 0, 6, 6);
        // Should not panic; column 0 stays zero, column 1+ has pixels.
        assert_eq!(dst[0], 0);
        assert_eq!(dst[1], 0);
        assert_ne!(dst[2], 0);
    }

    #[test]
    fn fill_rect_transformed_90deg_rotation() {
        let mut buf = vec![0u8; 16 * 16 * 4];
        let mut dst = Texture::new(&mut buf, 16, 16, ColorFormat::RGBA8888);
        let rect = Rect::new(6, 6, 4, 4);
        let cx = rect.x + rect.w / Fixed::from_int(2);
        let cy = rect.y + rect.h / Fixed::from_int(2);
        let tf = Transform::translate(cx, cy)
            .compose(&Transform::rotate_deg(Fixed::from_int(90)))
            .compose(&Transform::translate(Fixed::ZERO - cx, Fixed::ZERO - cy));
        let red = Color::rgb(255, 0, 0);
        fill_rect_transformed(&mut dst, rect, Rect::new(0, 0, 16, 16), &tf, &red, 255);

        let mut painted = 0;
        for y in 0..16 {
            for x in 0..16 {
                if dst.get_pixel(x, y).r == 255 {
                    painted += 1;
                }
            }
        }
        assert!(
            (12..=20).contains(&painted),
            "expected ~16 painted pixels, got {}",
            painted
        );
    }

    #[test]
    fn renderer_transformed_fill_uses_logical_area_under_hidpi() {
        let mut buf = vec![0u8; 64 * 64 * 4];
        let tex = Texture::new(&mut buf, 64, 64, ColorFormat::RGBA8888);
        let mut renderer = SwRenderer::new(tex);
        renderer.viewport = Viewport::new(32, 32, Fixed::from_int(2));

        renderer.draw(
            &DrawCommand::Fill {
                area: Rect::new(4, 4, 8, 8),
                transform: Transform::scale(Fixed::from_int(2), Fixed::from_int(2)),
                quad: None,
                color: Color::rgb(255, 0, 0),
                radius: Fixed::ZERO,
                opa: 255,
            },
            &Rect::new(0, 0, 32, 32),
        );

        assert_eq!(renderer.target.get_pixel(20, 20).r, 255);
        assert_eq!(renderer.target.get_pixel(10, 10).r, 0);
        assert_eq!(renderer.target.get_pixel(50, 50).r, 0);
    }

    #[test]
    fn blit_1to1_with_clip_restricted() {
        let mut src_buf = vec![0u8; 4 * 4 * 4];
        for i in 0..16 {
            src_buf[i * 4] = 100 + i as u8;
            src_buf[i * 4 + 3] = 255;
        }
        let src = Texture::new(&mut src_buf, 4, 4, ColorFormat::RGBA8888);

        let mut dst_a = vec![0u8; 8 * 8 * 4];
        let mut dst_b = vec![0u8; 8 * 8 * 4];

        // Clip covers only the right half of the blit rect.
        {
            let mut tex = Texture::new(&mut dst_a, 8, 8, ColorFormat::RGBA8888);
            blit_generic_slow(&mut tex, &src, 0, 0, 4, 4, 1, 1, 4, 4, 3, 0, 8, 8);
        }
        {
            let mut tex = Texture::new(&mut dst_b, 8, 8, ColorFormat::RGBA8888);
            blit_1to1_fast(&mut tex, &src, 0, 0, 4, 4, 1, 1, 3, 0, 8, 8);
        }
        assert_eq!(dst_a, dst_b);
    }

    /// Clip partially covering the dst rect must still produce the
    /// same output as the divide-based slow path (every pixel outside
    /// the clip untouched, every pixel inside matching src sampling).
    #[test]
    fn blit_dda_with_partial_clip() {
        let mut src_buf = vec![0u8; 4 * 4 * 4];
        for i in 0..16 {
            src_buf[i * 4] = (i * 16 + 1) as u8;
            src_buf[i * 4 + 3] = 255;
        }
        let src = Texture::new(&mut src_buf, 4, 4, ColorFormat::RGBA8888);

        let mut dst_a = vec![0u8; 10 * 10 * 4];
        let mut dst_b = vec![0u8; 10 * 10 * 4];
        // Clip covers columns 2..7 only.
        {
            let mut tex_a = Texture::new(&mut dst_a, 10, 10, ColorFormat::RGBA8888);
            blit_generic_slow(&mut tex_a, &src, 0, 0, 4, 4, 1, 1, 8, 8, 2, 0, 7, 10);
        }
        {
            let mut tex_b = Texture::new(&mut dst_b, 10, 10, ColorFormat::RGBA8888);
            blit_dda(&mut tex_b, &src, 0, 0, 4, 4, 1, 1, 8, 8, 2, 0, 7, 10);
        }
        assert_eq!(dst_a, dst_b);
    }

    #[test]
    fn sw_renderer_supports_offscreen() {
        let mut buf = vec![0u8; 4 * 4 * 4];
        let tex = Texture::new(&mut buf, 4, 4, ColorFormat::RGBA8888);
        let backend = SwRenderer::new(tex);
        assert!(Renderer::supports_offscreen(&backend));
    }

    /// View `stride` must equal the framebuffer's so writing every
    /// pixel of the borrowed view hits exactly the rect's pixels in
    /// the underlying buffer.
    #[test]
    fn modify_target_region_writes_exact_rect() {
        let mut buf = vec![0u8; 16 * 16 * 4];
        let tex = Texture::new(&mut buf, 16, 16, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);
        let rect = Rect::new(
            Fixed::from_int(4),
            Fixed::from_int(4),
            Fixed::from_int(6),
            Fixed::from_int(5),
        );
        let ran = backend.modify_target_region(&rect, &mut |view| {
            assert_eq!(view.width, 6);
            assert_eq!(view.height, 5);
            assert_eq!(view.stride, 16 * 4);
            for y in 0..view.height as i32 {
                for x in 0..view.width as i32 {
                    view.set_pixel(x, y, &Color::rgb(255, 128, 64));
                }
            }
        });
        assert!(ran);

        let target = &backend.target;
        for py in 0..16i32 {
            for px in 0..16i32 {
                let p = target.get_pixel(px, py);
                let in_rect = (4..10).contains(&px) && (4..9).contains(&py);
                if in_rect {
                    assert_eq!((p.r, p.g, p.b), (255, 128, 64), "in-rect ({px},{py})");
                } else {
                    assert_eq!((p.r, p.g, p.b), (0, 0, 0), "outside-rect ({px},{py})");
                }
            }
        }
    }

    #[test]
    fn scroll_target_region_shift_up_moves_rows_correctly() {
        let mut buf = vec![0u8; 8 * 8 * 4];
        // Per-row red gradient (Y * 30) so each row is distinguishable.
        for y in 0..8 {
            for x in 0..8 {
                let off = (y * 8 + x) * 4;
                buf[off] = (y * 30) as u8;
                buf[off + 3] = 255;
            }
        }
        let tex = Texture::new(&mut buf, 8, 8, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);
        let area = Rect::new(
            Fixed::ZERO,
            Fixed::ZERO,
            Fixed::from_int(8),
            Fixed::from_int(8),
        );
        backend.scroll_target_region(&area, Fixed::ZERO, Fixed::from_int(-2));

        // Rows 0..6 should now hold pre-scroll rows 2..8; rows 6, 7
        // are the bottom strip the caller is meant to repaint, so
        // their post-shift contents are unspecified and not checked.
        for y in 0..6 {
            let src_y_before = y + 2;
            let p = backend.target.get_pixel(0, y);
            assert_eq!(
                p.r,
                (src_y_before * 30) as u8,
                "row {y} should hold pre-scroll row {src_y_before}",
            );
        }
    }

    #[test]
    fn scroll_target_region_shift_down_moves_rows_correctly() {
        let mut buf = vec![0u8; 8 * 8 * 4];
        for y in 0..8 {
            for x in 0..8 {
                let off = (y * 8 + x) * 4;
                buf[off] = (y * 30) as u8;
                buf[off + 3] = 255;
            }
        }
        let tex = Texture::new(&mut buf, 8, 8, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);
        let area = Rect::new(
            Fixed::ZERO,
            Fixed::ZERO,
            Fixed::from_int(8),
            Fixed::from_int(8),
        );
        backend.scroll_target_region(&area, Fixed::ZERO, Fixed::from_int(2));

        for y in 2..8 {
            let src_y_before = y - 2;
            let p = backend.target.get_pixel(0, y);
            assert_eq!(
                p.r,
                (src_y_before * 30) as u8,
                "row {y} should hold pre-scroll row {src_y_before}",
            );
        }
    }

    /// Sub-pixel dy truncates to zero physical pixels and is a no-op;
    /// caller is expected to keep and re-submit the residue.
    #[test]
    fn scroll_target_region_sub_pixel_dy_is_noop() {
        let mut buf = vec![1u8; 4 * 4 * 4];
        let tex = Texture::new(&mut buf, 4, 4, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);
        let area = Rect::new(
            Fixed::ZERO,
            Fixed::ZERO,
            Fixed::from_int(4),
            Fixed::from_int(4),
        );
        let half = Fixed::from_int(1) / Fixed::from_int(2);
        backend.scroll_target_region(&area, Fixed::ZERO, half);
        for px in backend.target.buf.as_slice() {
            assert_eq!(*px, 1);
        }
    }

    /// Negative sub-pixel dy must truncate toward zero (no-op), not
    /// floor (which would emit a 1-pixel shift). The residue lives
    /// in the caller's `ScrollDelta`; if the renderer floored, a
    /// `-0.5` shift would clobber a row of pixels and leave the
    /// caller with a `+0.5` residue that cancels the next `-0.5`.
    #[test]
    fn scroll_target_region_negative_sub_pixel_dy_is_noop() {
        // Stripe the buf per-row so a 1-row shift would be visible.
        let mut buf = vec![0u8; 4 * 4 * 4];
        for y in 0..4 {
            for x in 0..4 {
                let off = (y * 4 + x) * 4;
                buf[off] = (y * 50) as u8;
                buf[off + 3] = 255;
            }
        }
        let snapshot = buf.clone();
        let tex = Texture::new(&mut buf, 4, 4, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);
        let area = Rect::new(
            Fixed::ZERO,
            Fixed::ZERO,
            Fixed::from_int(4),
            Fixed::from_int(4),
        );
        let neg_half = Fixed::ZERO - (Fixed::from_int(1) / Fixed::from_int(2));
        backend.scroll_target_region(&area, Fixed::ZERO, neg_half);
        assert_eq!(
            backend.target.buf.as_slice(),
            snapshot.as_slice(),
            "negative sub-pixel dy must not modify the buffer"
        );
    }

    #[test]
    fn scroll_target_region_shift_left_moves_columns_correctly() {
        let mut buf = vec![0u8; 8 * 8 * 4];
        for y in 0..8 {
            for x in 0..8 {
                let off = (y * 8 + x) * 4;
                buf[off] = (x * 30) as u8;
                buf[off + 3] = 255;
            }
        }
        let tex = Texture::new(&mut buf, 8, 8, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);
        let area = Rect::new(
            Fixed::ZERO,
            Fixed::ZERO,
            Fixed::from_int(8),
            Fixed::from_int(8),
        );
        backend.scroll_target_region(&area, Fixed::from_int(-2), Fixed::ZERO);

        for x in 0..6 {
            let src_x_before = x + 2;
            let p = backend.target.get_pixel(x, 3);
            assert_eq!(
                p.r,
                (src_x_before * 30) as u8,
                "col {x} should hold pre-scroll col {src_x_before}",
            );
        }
    }

    #[test]
    fn scroll_target_region_shift_right_moves_columns_correctly() {
        let mut buf = vec![0u8; 8 * 8 * 4];
        for y in 0..8 {
            for x in 0..8 {
                let off = (y * 8 + x) * 4;
                buf[off] = (x * 30) as u8;
                buf[off + 3] = 255;
            }
        }
        let tex = Texture::new(&mut buf, 8, 8, ColorFormat::RGBA8888);
        let mut backend = SwRenderer::new(tex);
        let area = Rect::new(
            Fixed::ZERO,
            Fixed::ZERO,
            Fixed::from_int(8),
            Fixed::from_int(8),
        );
        backend.scroll_target_region(&area, Fixed::from_int(2), Fixed::ZERO);

        for x in 2..8 {
            let src_x_before = x - 2;
            let p = backend.target.get_pixel(x, 3);
            assert_eq!(
                p.r,
                (src_x_before * 30) as u8,
                "col {x} should hold pre-scroll col {src_x_before}",
            );
        }
    }

    #[test]
    fn opaque_mode_writes_full_alpha() {
        // Default mode (Opaque): every blend-pixel write must leave
        // dst.a = 255 regardless of source alpha. Regression guard
        // for the framebuffer path post-AlphaMode introduction.
        let mut buf = std::vec![0u8; 4 * 4];
        let mut tex = Texture::new(&mut buf, 2, 2, ColorFormat::RGBA8888);
        tex.blend_pixel_int(0, 0, &Color::rgba(255, 0, 0, 100), 100);
        tex.blend_pixel_int(1, 0, &Color::rgba(0, 255, 0, 200), 200);
        assert_eq!(tex.get_pixel(0, 0).a, 255, "opaque mode: dst.a always 255");
        assert_eq!(tex.get_pixel(1, 0).a, 255, "opaque mode: dst.a always 255");
    }

    #[test]
    fn blend_alpha_accumulates_on_clear_transparent() {
        // Blend mode + transparent dst (a=0): a single fill of partial
        // alpha must leave dst.a = src.a, not 255.
        let mut buf = std::vec![0u8; 4 * 4];
        let mut tex = Texture::new(&mut buf, 2, 2, ColorFormat::RGBA8888);
        tex.alpha_mode = AlphaMode::Blend;
        tex.blend_pixel_int(0, 0, &Color::rgba(255, 0, 0, 128), 128);
        let p = tex.get_pixel(0, 0);
        assert_eq!(
            p.a, 128,
            "blend mode + transparent dst: dst.a should equal src.a, got {}",
            p.a,
        );
    }

    #[test]
    fn blend_alpha_blends_when_dst_partial() {
        // Two overlapping fills in Blend mode must compose alpha via
        //   out.a = src.a + dst.a * (255 − src.a) / 255
        // First fill leaves dst.a = 100; second fill src.a = 100 over
        // that should give roughly 100 + 100 × 155 / 255 = 161.
        let mut buf = std::vec![0u8; 4 * 4];
        let mut tex = Texture::new(&mut buf, 2, 2, ColorFormat::RGBA8888);
        tex.alpha_mode = AlphaMode::Blend;
        tex.blend_pixel_int(0, 0, &Color::rgba(255, 0, 0, 100), 100);
        tex.blend_pixel_int(0, 0, &Color::rgba(0, 0, 255, 100), 100);
        let p = tex.get_pixel(0, 0);
        // ±2 tolerance for u8 rounding in two-step source-over.
        let expected = 100 + (100 * 155) / 255;
        assert!(
            (p.a as i32 - expected as i32).abs() <= 2,
            "blend mode source-over: expected ~{expected}, got {}",
            p.a,
        );
    }

    #[test]
    fn blend_a_eq_255_writes_full_alpha_in_blend_mode() {
        // Source-over identity at a=255: fully opaque source covers
        // dst, so dst.a = 255 even in Blend mode. Pins the
        // short-circuit behaviour for the common case.
        let mut buf = std::vec![0u8; 4 * 4];
        let mut tex = Texture::new(&mut buf, 2, 2, ColorFormat::RGBA8888);
        tex.alpha_mode = AlphaMode::Blend;
        tex.blend_pixel_int(0, 0, &Color::rgba(255, 0, 0, 255), 255);
        assert_eq!(tex.get_pixel(0, 0).a, 255);
    }
}