rust_widgets 2.9.2

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

//! WGPU renderer implementation.
use super::commands::WgpuDrawCommand;
use super::raster::{align_to, rasterize_draw_commands_rgba8};
use super::shaders::ShaderModule;
use super::types::Rgba8;
use crate::render::gpu::{GpuCapability, GpuRenderer};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::mpsc;
use std::time::Duration;

/// Upper bound on a single blocking GPU readback.
///
/// The readback is synchronous by design: every entry point returns owned pixels. Before this
/// bound existed, `device.poll` waited forever, so a lost device or a stuck submission hung the
/// caller instead of reporting an error (G-63).
const GPU_READBACK_TIMEOUT: Duration = Duration::from_secs(10);

/// One persistent colour-uniform arena shared by every draw of one call.
///
/// WebGPU requires a dynamic uniform offset to be a multiple of the device's
/// `min_uniform_buffer_offset_alignment` (256 on the common backends, but a
/// device may report more), so each rectangle's 16-byte colour is padded to a
/// stride read from the device rather than assumed. One buffer and one bind
/// group serve the whole call instead of one of each per rectangle (REND-02).
struct UniformArena {
    buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    capacity: u64,
    /// Dynamic-offset stride: the device's `min_uniform_buffer_offset_alignment`,
    /// raised to hold the 16-byte colour, so every offset stays legal on any backend.
    ///
    /// Only the per-rectangle path reads this; an instanced run carries colour in its instance
    /// records instead.
    stride: u64,
}

/// The offscreen render target for one `(width, height)`.
struct TargetCache {
    width: u32,
    height: u32,
    texture: wgpu::Texture,
    view: wgpu::TextureView,
}

/// A grow-only vertex buffer reused across calls.
///
/// The same cache holds both the per-rectangle vertex positions and the instanced quad records:
/// both uses are `VERTEX`-usage buffers written once per call, and sharing one grow-only
/// allocation is what keeps an instanced run from allocating once per quad.
struct VertexCache {
    buffer: wgpu::Buffer,
    capacity: u64,
}

/// A grow-only readback buffer reused across calls.
struct ReadbackCache {
    buffer: wgpu::Buffer,
    size: u64,
}

/// The two ping-pong targets and per-direction bind groups of the blur pass.
///
/// The pass reads a texture and writes one that is not also bound as its attachment, so two
/// textures are required. Both are `RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_*`: the first is
/// uploaded into and read back from, the second is only ever the horizontal pass's target. Cached
/// per `(width, height)` and rebuilt when the size changes (REND-02's reuse rule).
struct BlurTargets {
    width: u32,
    height: u32,
    source: wgpu::Texture,
    source_view: wgpu::TextureView,
    scratch_view: wgpu::TextureView,
    horizontal: wgpu::BindGroup,
    vertical: wgpu::BindGroup,
    horizontal_params: wgpu::Buffer,
    vertical_params: wgpu::Buffer,
}

/// The model-view-projection uniform used by the instanced quad pipeline.
///
/// One matrix serves a whole call, so this is not a dynamic-offset arena. The 64-byte size is
/// `mat4x4f`'s uniform footprint.
struct TransformedUniform {
    buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
}

/// The colour-and-depth pair the `3d` mesh pipeline renders into.
///
/// The view owns its texture, so the texture handle itself does not need to be stored. Cached per
/// `(width, height)` like the other targets (REND-02) and rebuilt when the size changes.
#[cfg(feature = "3d")]
struct DepthTarget {
    width: u32,
    height: u32,
    view: wgpu::TextureView,
}

/// Creates a 64-byte matrix uniform and the bind group that exposes it at group 0, binding 0.
///
/// Both the instanced quad pipeline and the mesh pipeline use one matrix per call rather than a
/// dynamic-offset arena, so this is the one shape their resources share. The 64-byte size is
/// `mat4x4f`'s uniform footprint.
fn create_matrix_uniform(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    label: &str,
) -> TransformedUniform {
    let buffer_label = format!("{label}_ubo");
    let bind_group_label = format!("{label}_bind_group");
    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some(buffer_label.as_str()),
        size: 64,
        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });
    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some(bind_group_label.as_str()),
        layout,
        entries: &[wgpu::BindGroupEntry {
            binding: 0,
            resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                buffer: &buffer,
                offset: 0,
                size: wgpu::BufferSize::new(64),
            }),
        }],
    });
    TransformedUniform { buffer, bind_group }
}

/// Device resources a renderer keeps across calls.
///
/// # Why this exists (REND-02)
///
/// Every entry point used to allocate its uniform buffer, bind group, vertex
/// buffer, offscreen texture and full-frame readback buffer per call. Those
/// allocations are not free — a `fill_rect` batch of 40 rectangles created 40
/// uniform buffers and 40 bind groups — and the per-call texture made the GPU
/// treat every call as a new render target. This cache keeps one of each, grown
/// on demand and overwritten with `write_buffer`, because the API is called at
/// frame rate by a host that renders offscreen. The data is fully rewritten on
/// every call, so no stale content can leak between calls.
///
/// `RefCell` rather than `&mut self`: the public entry points take `&self` (and
/// `GpuRenderer` calls them that way), so the cache is the only interior-mutable
/// piece. It is not `Sync`, and the renderer is not shared across threads.
#[derive(Default)]
struct RenderCache {
    uniform: Option<UniformArena>,
    target: Option<TargetCache>,
    upload_target: Option<TargetCache>,
    vertices: Option<VertexCache>,
    readback: Option<ReadbackCache>,
    /// Ping-pong targets and bind groups for the separable blur pass.
    blur: Option<BlurTargets>,
    /// Mvp uniform and bind group for the instanced quad pipeline.
    transformed_uniform: Option<TransformedUniform>,
    /// The `Depth32Float` attachment for mesh draws.
    #[cfg(feature = "3d")]
    depth_target: Option<DepthTarget>,
    /// Mvp uniform and bind group for the mesh pipeline.
    #[cfg(feature = "3d")]
    mesh_uniform: Option<TransformedUniform>,
    /// Grow-only index buffer for mesh draws.
    #[cfg(feature = "3d")]
    mesh_indices: Option<VertexCache>,
}

// Retain headroom without exceeding the device limit; buffers remain grow-only.
fn grown_buffer_capacity(current: u64, needed: u64, limit: u64) -> u64 {
    let grown = current.saturating_add(current / 2).max(needed).max(4);
    let rounded = grown.checked_add(65_535).map(|size| size / 65_536 * 65_536).unwrap_or(limit);
    rounded.min(limit).max(needed.max(4))
}

impl RenderCache {
    /// The dynamic-offset stride for the colour arena: the device's
    /// `min_uniform_buffer_offset_alignment`, raised to hold the 16-byte colour
    /// and rounded back up to a legal multiple. A hard-coded 256 would make every
    /// draw a validation error on a device that reports 512.
    fn uniform_stride(device: &wgpu::Device) -> u64 {
        let alignment = device.limits().min_uniform_buffer_offset_alignment as u64;
        alignment.max(16).next_multiple_of(alignment.max(1))
    }

    /// Ensures the colour arena can hold `slots` colours.
    fn ensure_uniform(
        &mut self,
        device: &wgpu::Device,
        layout: &wgpu::BindGroupLayout,
        slots: usize,
    ) -> Result<(), String> {
        let stride = Self::uniform_stride(device);
        let needed = stride
            .checked_mul(slots.max(1) as u64)
            .ok_or_else(|| format!("{slots} colour slots overflow the uniform buffer size"))?;
        let needs_new = self.uniform.as_ref().map(|arena| arena.capacity < needed).unwrap_or(true);
        if needs_new {
            if needed > device.limits().max_buffer_size {
                return Err(format!("{needed} uniform bytes exceed the device buffer limit"));
            }
            let capacity = grown_buffer_capacity(
                self.uniform.as_ref().map_or(0, |arena| arena.capacity),
                needed,
                device.limits().max_buffer_size,
            );
            let buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("rect_color_ubo"),
                size: capacity,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("rect_bind_group"),
                layout,
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: &buffer,
                        offset: 0,
                        size: wgpu::BufferSize::new(16),
                    }),
                }],
            });
            self.uniform = Some(UniformArena { buffer, bind_group, capacity, stride });
        }
        Ok(())
    }

    /// Ensures the offscreen target matches `width × height`.
    fn ensure_target(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        let matches = self
            .target
            .as_ref()
            .map(|target| target.width == width && target.height == height)
            .unwrap_or(false);
        if !matches {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("wgpu_offscreen_target"),
                size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8Unorm,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.target = Some(TargetCache { width, height, texture, view });
        }
    }

    /// Ensures the upload-side texture matches `width × height`.
    ///
    /// Separate from [`Self::ensure_target`] because this one is writable
    /// (`COPY_DST`): `queue.write_texture` uploads the caller's bytes into it before the copy
    /// back, which a render-attachment-only texture cannot accept.
    fn ensure_upload_target(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        let matches = self
            .upload_target
            .as_ref()
            .map(|target| target.width == width && target.height == height)
            .unwrap_or(false);
        if !matches {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("rw_wgpu_offscreen_texture"),
                size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8Unorm,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::COPY_SRC
                    | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.upload_target = Some(TargetCache { width, height, texture, view });
        }
    }

    /// Ensures the vertex buffer can hold `bytes`.
    fn ensure_vertices(&mut self, device: &wgpu::Device, bytes: u64) {
        let needs_new = self.vertices.as_ref().map(|cache| cache.capacity < bytes).unwrap_or(true);
        if needs_new {
            let capacity = grown_buffer_capacity(
                self.vertices.as_ref().map_or(0, |cache| cache.capacity),
                bytes,
                device.limits().max_buffer_size,
            );
            let buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("rect_vertex_buffer"),
                size: capacity,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            self.vertices = Some(VertexCache { buffer, capacity });
        }
    }

    /// Ensures the readback buffer can hold `size` bytes.
    fn ensure_readback(&mut self, device: &wgpu::Device, size: u64) {
        let needs_new = self.readback.as_ref().map(|cache| cache.size < size).unwrap_or(true);
        if needs_new {
            let capacity = grown_buffer_capacity(
                self.readback.as_ref().map_or(0, |cache| cache.size),
                size,
                device.limits().max_buffer_size,
            );
            let buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("wgpu_readback"),
                size: capacity,
                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
                mapped_at_creation: false,
            });
            self.readback = Some(ReadbackCache { buffer, size: capacity });
        }
    }

    /// Ensures the blur ping-pong targets and both directional bind groups match `width × height`.
    fn ensure_blur_targets(
        &mut self,
        device: &wgpu::Device,
        layout: &wgpu::BindGroupLayout,
        width: u32,
        height: u32,
    ) {
        let matches = self
            .blur
            .as_ref()
            .map(|targets| targets.width == width && targets.height == height)
            .unwrap_or(false);
        if matches {
            return;
        }
        let make_texture = |label: &str| {
            device.create_texture(&wgpu::TextureDescriptor {
                label: Some(label),
                size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8Unorm,
                usage: wgpu::TextureUsages::TEXTURE_BINDING
                    | wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::COPY_SRC
                    | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            })
        };
        let source = make_texture("wgpu_blur_source");
        let scratch = make_texture("wgpu_blur_scratch");
        let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
        let scratch_view = scratch.create_view(&wgpu::TextureViewDescriptor::default());
        let make_params = |label: &str| {
            device.create_buffer(&wgpu::BufferDescriptor {
                label: Some(label),
                size: 16,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            })
        };
        let horizontal_params = make_params("wgpu_blur_horizontal_params");
        let vertical_params = make_params("wgpu_blur_vertical_params");
        let make_bind_group = |label: &str, view: &wgpu::TextureView, buffer: &wgpu::Buffer| {
            device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some(label),
                layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureView(view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                            buffer,
                            offset: 0,
                            size: wgpu::BufferSize::new(16),
                        }),
                    },
                ],
            })
        };
        let horizontal = make_bind_group("wgpu_blur_horizontal", &source_view, &horizontal_params);
        let vertical = make_bind_group("wgpu_blur_vertical", &scratch_view, &vertical_params);
        self.blur = Some(BlurTargets {
            width,
            height,
            source,
            source_view,
            scratch_view,
            horizontal,
            vertical,
            horizontal_params,
            vertical_params,
        });
    }

    /// Ensures the instanced-quad mvp uniform and its bind group exist.
    ///
    /// The buffer never grows: every call writes one 64-byte matrix. It is created once per
    /// renderer, matching the rest of this cache (REND-02).
    fn ensure_transformed_uniform(
        &mut self,
        device: &wgpu::Device,
        layout: &wgpu::BindGroupLayout,
    ) {
        if self.transformed_uniform.is_some() {
            return;
        }
        self.transformed_uniform = Some(create_matrix_uniform(device, layout, "transformed_mvp"));
    }

    /// Ensures the mesh mvp uniform and its bind group exist.
    ///
    /// Separate from [`Self::ensure_transformed_uniform`] so a 2D transformed draw and a mesh draw
    /// never race for the same 64-byte buffer within one frame.
    #[cfg(feature = "3d")]
    fn ensure_mesh_uniform(&mut self, device: &wgpu::Device, layout: &wgpu::BindGroupLayout) {
        if self.mesh_uniform.is_some() {
            return;
        }
        self.mesh_uniform = Some(create_matrix_uniform(device, layout, "mesh_mvp"));
    }

    /// Ensures the `Depth32Float` attachment matches `(width, height)`.
    #[cfg(feature = "3d")]
    fn ensure_depth_target(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        let matches = self
            .depth_target
            .as_ref()
            .map(|target| target.width == width && target.height == height)
            .unwrap_or(false);
        if matches {
            return;
        }
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("mesh_depth_texture"),
            size: wgpu::Extent3d {
                width: width.max(1),
                height: height.max(1),
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Depth32Float,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        self.depth_target = Some(DepthTarget { width, height, view });
    }

    /// Ensures the mesh index buffer holds at least `bytes`.
    #[cfg(feature = "3d")]
    fn ensure_mesh_indices(&mut self, device: &wgpu::Device, bytes: u64) {
        if self.mesh_indices.as_ref().map(|cache| cache.capacity >= bytes).unwrap_or(false) {
            return;
        }
        let capacity = bytes.max(256).next_power_of_two();
        let buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("mesh_indices"),
            size: capacity,
            usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        self.mesh_indices = Some(VertexCache { buffer, capacity });
    }
}

/// Byte length of an RGBA8 image of `width × height` pixels.
///
/// Computed in `usize` with checked multiplication: in `u32` the product wraps
/// (e.g. 65536×16384 = 2^32), which would hand the GPU a buffer one byte long for
/// a 1 GiB image. Returns an explicit error on overflow, a zero dimension, or a
/// size beyond the largest supported framebuffer (N-S-66).
fn rgba_buffer_len(width: u32, height: u32) -> Result<usize, String> {
    if width == 0 || height == 0 {
        return Err(format!("width/height must be > 0, got {width}x{height}"));
    }
    let pixels = (width as usize)
        .checked_mul(height as usize)
        .ok_or_else(|| format!("image {width}x{height} pixel count overflows usize"))?;
    let bytes = pixels
        .checked_mul(4)
        .ok_or_else(|| format!("image {width}x{height} RGBA size overflows usize"))?;
    if bytes > u32::MAX as usize {
        return Err(format!(
            "image {width}x{height} needs {bytes} bytes, which exceeds the largest supported \
             framebuffer ({} bytes)",
            u32::MAX
        ));
    }
    Ok(bytes)
}

/// Bytes per row of an RGBA8 image, aligned to WebGPU's copy requirement.
fn padded_row_bytes(width: u32) -> Result<u32, String> {
    let unpadded = width
        .checked_mul(4)
        .ok_or_else(|| format!("row byte width for {width} pixels overflows u32"))?;
    Ok(align_to(unpadded, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT))
}

/// Total bytes of a padded RGBA8 readback buffer.
fn readback_frame_bytes(width: u32, height: u32) -> Result<u64, String> {
    let padded = padded_row_bytes(width)?;
    (padded as u64)
        .checked_mul(height as u64)
        .ok_or_else(|| format!("readback buffer for {width}x{height} overflows u64"))
}

/// Composites `tint` over every pixel of a straight-RGBA frame.
///
/// `weight` scales the tint's alpha, so a tint colour with `a = 200` at weight `0.5`
/// contributes half of its own opacity. A non-finite weight is ignored rather than clamped:
/// `f32::clamp` propagates `NaN`, and a `NaN` here would poison every channel of the frame.
fn tint_blurred_frame(frame: &mut [u8], tint: Rgba8, weight: f32) {
    if !weight.is_finite() {
        return;
    }
    let weight = weight.clamp(0.0, 1.0);
    let tint_alpha = (tint.a as f32 / 255.0) * weight;
    if tint_alpha <= 0.0 {
        return;
    }
    let tint_rgb = [tint.r as f32 / 255.0, tint.g as f32 / 255.0, tint.b as f32 / 255.0];
    for pixel in frame.as_chunks_mut::<4>().0 {
        let dst_alpha = pixel[3] as f32 / 255.0;
        let out_alpha = tint_alpha + dst_alpha * (1.0 - tint_alpha);
        if out_alpha <= f32::EPSILON {
            pixel.fill(0);
            continue;
        }
        for channel in 0..3 {
            let dst = pixel[channel] as f32 / 255.0;
            let blended =
                (tint_rgb[channel] * tint_alpha + dst * dst_alpha * (1.0 - tint_alpha)) / out_alpha;
            pixel[channel] = (blended * 255.0).round().clamp(0.0, 255.0) as u8;
        }
        pixel[3] = (out_alpha * 255.0).round().clamp(0.0, 255.0) as u8;
    }
}

/// Packs a row-major [`crate::render::math3d::Mat4`] as the column-major bytes WGSL expects.
///
/// WGSL's `mat4x4f` uniform layout is column-major, while the maths module stores rows to
/// match the affine matrix's natural reading order. Transposing here is what keeps the two
/// conventions from being silently swapped — the failure mode would be a transposed transform
/// that still compiles and still draws *something*.
#[cfg(feature = "3d")]
#[allow(clippy::needless_range_loop)] // row and column index the source row-major matrix.
fn mvp_column_major_bytes(m: &crate::render::math3d::Mat4) -> [u8; 64] {
    let mut bytes = [0u8; 64];
    for column in 0..4 {
        for row in 0..4 {
            let value = m.m[row * 4 + column];
            let start = (column * 4 + row) * 4;
            bytes[start..start + 4].copy_from_slice(&value.to_le_bytes());
        }
    }
    bytes
}

/// Bytes of one instanced quad record: two `vec4f` corner pairs and one `vec4f` colour.
///
/// Kept as a named constant because the vertex-buffer stride, the writer and the chunk offsets
/// must agree exactly; a mismatch is a pipeline validation error rather than a silent misread.
const INSTANCE_BYTES: usize = 48;

/// Upper bound on the instances submitted by one instanced draw.
///
/// A longer run is streamed in cap-sized chunks from the same grow-only buffer. The chunks are
/// drawn in order, so splitting never reorders the run and never allocates per quad.
const MAX_INSTANCES_PER_DRAW: usize = 4096;

/// Column-major bytes of the pixel-to-clip matrix for a `width × height` target.
///
/// `x` maps `0..width` to `-1..1` and `y` maps `0..height` to `1..-1`, matching the renderer's
/// top-left origin. These are the bytes `Mat4::from_affine(ortho)` produces, written directly so
/// the 2D rectangle path can use the instanced pipeline without the `3d` feature's maths module.
fn ortho_mvp_bytes(width: u32, height: u32) -> [u8; 64] {
    let w = width as f32;
    let h = height as f32;
    // Column-major: scale x, flip and scale y, keep z, then translate to the clip-space corner.
    let values =
        [2.0 / w, 0.0, 0.0, 0.0, 0.0, -2.0 / h, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0];
    let mut bytes = [0u8; 64];
    for (index, value) in values.iter().enumerate() {
        bytes[index * 4..index * 4 + 4].copy_from_slice(&value.to_le_bytes());
    }
    bytes
}

/// Packs a run of quads into the 48-byte-per-instance layout described on
/// [`super::shaders::FILL_RECT_VS_TRANSFORMED`].
///
/// Each record is the four corners in perimeter order, then straight RGBA with every channel
/// clamped to `0.0..=1.0`. Returns an explicit error rather than wrapping if the run is too
/// large to address, so a hostile count cannot produce a short buffer.
fn instanced_quad_bytes(quads: &[([crate::core::Point; 4], [f64; 4])]) -> Result<Vec<u8>, String> {
    let capacity = quads
        .len()
        .checked_mul(INSTANCE_BYTES)
        .ok_or_else(|| format!("{} quads overflow the instance buffer size", quads.len()))?;
    let mut bytes = Vec::with_capacity(capacity);
    for (corners, colour) in quads {
        for point in corners {
            bytes.extend_from_slice(&(point.x as f32).to_le_bytes());
            bytes.extend_from_slice(&(point.y as f32).to_le_bytes());
        }
        for channel in colour {
            bytes.extend_from_slice(&((*channel).clamp(0.0, 1.0) as f32).to_le_bytes());
        }
    }
    Ok(bytes)
}

/// Packs a mesh's vertices into the 32-byte interleaved layout [`super::shaders::MESH3D_VS`] reads.
///
/// Each record is the position as `(x, y, z, 1)` followed by straight RGBA, all little-endian
/// `f32`. The stride, the shader's attribute offsets and this writer must agree exactly; a
/// mismatch is a pipeline validation error rather than a silent misread.
#[cfg(feature = "3d")]
fn mesh_vertex_bytes(mesh: &crate::render::mesh3d::Mesh3D) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(mesh.vertices().len() * 32);
    for vertex in mesh.vertices() {
        for value in [vertex.position.x, vertex.position.y, vertex.position.z, 1.0] {
            bytes.extend_from_slice(&value.to_le_bytes());
        }
        for channel in [vertex.color.r, vertex.color.g, vertex.color.b, vertex.color.a] {
            bytes.extend_from_slice(&((channel as f32) / 255.0).to_le_bytes());
        }
    }
    bytes
}

/// Packs a mesh's indices as little-endian `u32`, matching `IndexFormat::Uint32`.
#[cfg(feature = "3d")]
fn mesh_index_bytes(mesh: &crate::render::mesh3d::Mesh3D) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(mesh.indices().len() * 4);
    for index in mesh.indices() {
        bytes.extend_from_slice(&index.to_le_bytes());
    }
    bytes
}

/// Lightweight GPU renderer context backed by `wgpu`.
pub struct WgpuRenderer {
    device: wgpu::Device,
    queue: wgpu::Queue,
    clear_pipeline: wgpu::RenderPipeline,
    /// The 2D per-rectangle pipeline. Used only for the single-rectangle case; a longer run goes
    /// through the instanced quad pipeline instead (G-64).
    rect_pipeline: wgpu::RenderPipeline,
    /// The separable-blur pipeline: one full-screen triangle, no vertex buffer, two directional
    /// passes. A 2D effect, so it is compiled in every build rather than behind `3d`.
    blur_pipeline: wgpu::RenderPipeline,
    bind_group_layout: wgpu::BindGroupLayout,
    /// Bind group layout of the blur pass: a non-filterable input texture and a 16-byte uniform
    /// (`direction`, `radius`).
    blur_bind_group_layout: wgpu::BindGroupLayout,
    /// Instanced quad pipeline. It renders a whole run of rectangles (and, with `3d`, arbitrary
    /// transformed quads) in `MAX_INSTANCES_PER_DRAW`-sized draws (G-64).
    transformed_pipeline: wgpu::RenderPipeline,
    /// The vertex-stage layout that carries the mvp matrix (group 0 of the instanced pipeline).
    transformed_bind_group_layout: wgpu::BindGroupLayout,
    /// Depth-tested triangle pipeline for mesh draws (`3d` only).
    #[cfg(feature = "3d")]
    mesh_pipeline: wgpu::RenderPipeline,
    /// Cached shader module pipeline references (BLUE11 R5.2).
    shader_cache: HashMap<String, wgpu::ShaderModule>,
    /// Device resources reused across calls (REND-02).
    cache: RefCell<RenderCache>,
}
impl WgpuRenderer {
    /// Create a new renderer by requesting a default GPU adapter and logical device.
    pub fn new() -> Result<Self, String> {
        pollster::block_on(Self::new_async())
    }
    async fn new_async() -> Result<Self, String> {
        // Build the instance from the whole degradation ladder so a host with no
        // primary driver can still reach the GL (OpenGL ES) rung, and report
        // which tier we landed on rather than failing outright.
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: crate::gpu::backend_ladder::instance_backends(),
            flags: wgpu::InstanceFlags::default(),
            memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
            backend_options: wgpu::BackendOptions::default(),
            display: None,
        });
        let (adapter, tier) = crate::gpu::backend_ladder::select_adapter_with_gl_fallback(
            &instance,
            wgpu::PowerPreference::HighPerformance,
            None,
        )
        .await
        .ok_or_else(|| {
            // Distinguish "this host has no GPU backend at all" from "you pinned
            // a backend this host cannot provide". The second case is a user
            // error worth naming, not a mystery to debug.
            match crate::gpu::backend_ladder::backends_from_env() {
                Some(pinned) => format!(
                    "wgpu adapter request failed: WGPU_BACKEND pinned {pinned:?}, \
                     which this host does not provide"
                ),
                None => "wgpu adapter request failed on every backend tier".to_string(),
            }
        })?;

        let adapter_info = adapter.get_info();
        if tier.is_degraded() {
            // Surface the degradation once, at start-up, so a slow session is
            // explainable instead of mysterious.
            log::warn!(
                "[wgpu] using degraded backend tier: {} ({:?}, adapter '{}')",
                tier.label(),
                adapter_info.backend,
                adapter_info.name,
            );
        } else {
            log::info!(
                "[wgpu] using {} backend ({:?}, adapter '{}')",
                tier.label(),
                adapter_info.backend,
                adapter_info.name,
            );
        }

        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("rw_wgpu_device"),
                required_features: wgpu::Features::empty(),
                required_limits: wgpu::Limits::default(),
                memory_hints: wgpu::MemoryHints::Performance,
                experimental_features: wgpu::ExperimentalFeatures::disabled(),
                trace: wgpu::Trace::Off,
            })
            .await
            .map_err(|error| {
                format!(
                    "the GPU device could not be requested: {error}; the adapter may have been \
                     lost or the requested limits unsupported"
                )
            })?;
        // ── Create shader modules ──
        let clear_vs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("clear_vs"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::FULLSCREEN_QUAD_VS.into()),
        });
        let clear_fs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("clear_fs"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::CLEAR_FS.into()),
        });
        let rect_vs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("rect_vs"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::FILL_RECT_VS.into()),
        });
        let rect_fs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("rect_fs"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::FILL_RECT_FS.into()),
        });
        let transformed_vs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("rect_vs_transformed"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::FILL_RECT_VS_TRANSFORMED.into()),
        });
        let instanced_fs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("rect_fs_instanced"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::FILL_RECT_INSTANCED_FS.into()),
        });
        #[cfg(feature = "3d")]
        let mesh_vs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("mesh3d_vs"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::MESH3D_VS.into()),
        });
        #[cfg(feature = "3d")]
        let mesh_fs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("mesh3d_fs"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::MESH3D_FS.into()),
        });
        let blur_vs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("blur_vs"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::BLUR_VS.into()),
        });
        let blur_fs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("blur_fs"),
            source: wgpu::ShaderSource::Wgsl(super::shaders::BLUR_FS.into()),
        });

        // Create bind group layout for uniform color (shared between clear and rect pipelines)
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("uniform_color_bind_group_layout"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: true,
                    min_binding_size: Some(wgpu::BufferSize::new(16).unwrap()),
                },
                count: None,
            }],
        });

        // The matrix lives in its own group because the instanced fragment stage takes its
        // colour per instance rather than from a group-0 uniform. With group 0 free, the
        // instanced pipeline binds the matrix at group 0 directly.
        let transformed_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("transformed_mvp_bind_group_layout"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: Some(wgpu::BufferSize::new(64).unwrap()),
                    },
                    count: None,
                }],
            });

        // ── Create clear pipeline (full-screen triangle, no vertex buffer) ──
        let clear_pipeline_layout =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("clear_pipeline_layout"),
                bind_group_layouts: &[Some(&bind_group_layout)],
                immediate_size: 0,
            });
        let clear_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("clear_pipeline"),
            layout: Some(&clear_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &clear_vs_module,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &clear_fs_module,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    blend: Some(wgpu::BlendState::REPLACE),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: Some(wgpu::Face::Back),
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview_mask: None,
            cache: None,
        });

        // ── Create rect pipeline (vertex buffer for quad positions) ──
        let rect_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("rect_pipeline_layout"),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });

        // Vertex buffer layout: one vec2f per vertex at location 0
        let rect_vertex_buffer_layout = wgpu::VertexBufferLayout {
            array_stride: 8, // 2 * f32 = 8 bytes
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &[wgpu::VertexAttribute {
                format: wgpu::VertexFormat::Float32x2,
                offset: 0,
                shader_location: 0,
            }],
        };

        let rect_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("rect_pipeline"),
            layout: Some(&rect_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &rect_vs_module,
                entry_point: Some("vs_main"),
                buffers: &[Some(rect_vertex_buffer_layout)],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &rect_fs_module,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    blend: Some(wgpu::BlendState::REPLACE),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Cw,
                cull_mode: Some(wgpu::Face::Back),
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview_mask: None,
            cache: None,
        });

        // ── Create the separable blur pipeline ──
        //
        // The input is read with `textureLoad`, so its sample type is non-filterable and no
        // sampler is bound. One draw call per direction filters the whole target; the two
        // bind groups differ only in the uniform that names the axis and in which texture is
        // the source.
        let blur_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("blur_bind_group_layout"),
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Texture {
                            sample_type: wgpu::TextureSampleType::Float { filterable: false },
                            view_dimension: wgpu::TextureViewDimension::D2,
                            multisampled: false,
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: false,
                            min_binding_size: Some(wgpu::BufferSize::new(16).unwrap()),
                        },
                        count: None,
                    },
                ],
            });
        let blur_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("blur_pipeline_layout"),
            bind_group_layouts: &[Some(&blur_bind_group_layout)],
            immediate_size: 0,
        });
        let blur_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("blur_pipeline"),
            layout: Some(&blur_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &blur_vs_module,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &blur_fs_module,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    blend: Some(wgpu::BlendState::REPLACE),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview_mask: None,
            cache: None,
        });

        // ── Create the instanced quad pipeline ──
        //
        // One instance carries the four corners and the colour, so a whole run of quads is a
        // single draw (`0..6` vertices, `0..N` instances). Culling is disabled because a
        // negative scale reverses the winding order, which is a valid mirror rather than a
        // reason to drop the quad. No depth attachment is added: this is a 2D affine composed
        // with an orthographic matrix, not a depth-tested 3D scene. The 2D rectangle path uses it
        // for every run longer than one rectangle (G-64).
        let transformed_pipeline = {
            let transformed_pipeline_layout =
                device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                    label: Some("rect_transformed_pipeline_layout"),
                    bind_group_layouts: &[Some(&transformed_bind_group_layout)],
                    immediate_size: 0,
                });
            // Locations 0/1 are the four corners as two vectors; location 2 is the colour.
            let instance_buffer_layout = wgpu::VertexBufferLayout {
                array_stride: INSTANCE_BYTES as u64,
                step_mode: wgpu::VertexStepMode::Instance,
                attributes: &[
                    wgpu::VertexAttribute {
                        format: wgpu::VertexFormat::Float32x4,
                        offset: 0,
                        shader_location: 0,
                    },
                    wgpu::VertexAttribute {
                        format: wgpu::VertexFormat::Float32x4,
                        offset: 16,
                        shader_location: 1,
                    },
                    wgpu::VertexAttribute {
                        format: wgpu::VertexFormat::Float32x4,
                        offset: 32,
                        shader_location: 2,
                    },
                ],
            };
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("rect_instanced_pipeline"),
                layout: Some(&transformed_pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &transformed_vs_module,
                    entry_point: Some("vs_main"),
                    buffers: &[Some(instance_buffer_layout)],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &instanced_fs_module,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: wgpu::TextureFormat::Rgba8Unorm,
                        blend: Some(wgpu::BlendState::REPLACE),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    strip_index_format: None,
                    front_face: wgpu::FrontFace::Cw,
                    cull_mode: None,
                    unclipped_depth: false,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    conservative: false,
                },
                depth_stencil: None,
                multisample: wgpu::MultisampleState {
                    count: 1,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview_mask: None,
                cache: None,
            })
        };

        // ── Create the depth-tested `3d` mesh pipeline ──
        //
        // One vertex buffer, one index buffer, one mvp uniform. Culling is disabled to match the
        // software rasteriser's documented policy: the depth test, not the winding order, decides
        // what is visible. Depth is `Depth32Float`, cleared to `1.0` per pass and compared with
        // `Less`, because every matrix this pipeline receives has already been remapped to the
        // `0..=1` range WebGPU expects.
        #[cfg(feature = "3d")]
        let mesh_pipeline = {
            let mesh_pipeline_layout =
                device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                    label: Some("mesh_pipeline_layout"),
                    bind_group_layouts: &[Some(&transformed_bind_group_layout)],
                    immediate_size: 0,
                });
            // 32-byte stride: position `(x, y, z, 1)` then colour.
            let vertex_buffer_layout = wgpu::VertexBufferLayout {
                array_stride: 32,
                step_mode: wgpu::VertexStepMode::Vertex,
                attributes: &[
                    wgpu::VertexAttribute {
                        format: wgpu::VertexFormat::Float32x4,
                        offset: 0,
                        shader_location: 0,
                    },
                    wgpu::VertexAttribute {
                        format: wgpu::VertexFormat::Float32x4,
                        offset: 16,
                        shader_location: 1,
                    },
                ],
            };
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("mesh_pipeline"),
                layout: Some(&mesh_pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &mesh_vs_module,
                    entry_point: Some("vs_main"),
                    buffers: &[Some(vertex_buffer_layout)],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &mesh_fs_module,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: wgpu::TextureFormat::Rgba8Unorm,
                        blend: Some(wgpu::BlendState::REPLACE),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    strip_index_format: None,
                    front_face: wgpu::FrontFace::Ccw,
                    cull_mode: None,
                    unclipped_depth: false,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    conservative: false,
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: wgpu::TextureFormat::Depth32Float,
                    depth_write_enabled: Some(true),
                    depth_compare: Some(wgpu::CompareFunction::Less),
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: 1,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview_mask: None,
                cache: None,
            })
        };

        let mut shader_cache = HashMap::new();
        shader_cache.insert("clear_vs".to_string(), clear_vs_module);
        shader_cache.insert("clear_fs".to_string(), clear_fs_module);
        shader_cache.insert("rect_vs".to_string(), rect_vs_module);
        shader_cache.insert("rect_fs".to_string(), rect_fs_module);
        shader_cache.insert("blur_vs".to_string(), blur_vs_module);
        shader_cache.insert("blur_fs".to_string(), blur_fs_module);
        shader_cache.insert("rect_vs_transformed".to_string(), transformed_vs_module);
        shader_cache.insert("rect_fs_instanced".to_string(), instanced_fs_module);
        #[cfg(feature = "3d")]
        shader_cache.insert("mesh3d_vs".to_string(), mesh_vs_module);
        #[cfg(feature = "3d")]
        shader_cache.insert("mesh3d_fs".to_string(), mesh_fs_module);

        Ok(Self {
            device,
            queue,
            clear_pipeline,
            rect_pipeline,
            blur_pipeline,
            bind_group_layout,
            blur_bind_group_layout,
            transformed_pipeline,
            transformed_bind_group_layout,
            #[cfg(feature = "3d")]
            mesh_pipeline,
            shader_cache,
            cache: RefCell::new(RenderCache::default()),
        })
    }
    /// Render one offscreen RGBA frame by clearing a texture with the given color and read pixels back.
    ///
    /// A solid clear needs no GPU work, so this fills the buffer on the CPU and returns it
    /// directly. The previous implementation routed the same fill through a texture upload and a
    /// blocking readback, which could only reproduce the bytes it was given (G-66).
    pub fn render_clear_rgba8(
        &self,
        width: u32,
        height: u32,
        color: [f64; 4],
    ) -> Result<Vec<u8>, String> {
        rasterize_draw_commands_rgba8(
            width,
            height,
            &[WgpuDrawCommand::Clear {
                color: Rgba8 {
                    r: (color[0].clamp(0.0, 1.0) * 255.0) as u8,
                    g: (color[1].clamp(0.0, 1.0) * 255.0) as u8,
                    b: (color[2].clamp(0.0, 1.0) * 255.0) as u8,
                    a: (color[3].clamp(0.0, 1.0) * 255.0) as u8,
                },
            }],
        )
    }
    /// Render a clear frame using the GPU pipeline with a WGSL shader.
    /// Uses a full-screen triangle and a uniform buffer for the clear color.
    pub fn render_clear_gpu(
        &self,
        width: u32,
        height: u32,
        color: [f64; 4],
    ) -> Result<Vec<u8>, String> {
        // Validate dimensions before touching the GPU: a zero-sized texture is
        // not a valid render target and an overflowing byte count must not be
        // truncated (N-S-66).
        let expected_len = rgba_buffer_len(width, height)?;
        let mut colour_bytes = [0u8; 16];
        for (channel, value) in color.iter().enumerate() {
            let clamped = value.clamp(0.0, 1.0) as f32;
            colour_bytes[channel * 4..channel * 4 + 4].copy_from_slice(&clamped.to_le_bytes());
        }
        let frame_bytes = readback_frame_bytes(width, height)?;

        // One cached uniform arena, target and readback buffer for every call, rather than a new
        // set of GPU resources per call (REND-02).
        let mut cache = self.cache.borrow_mut();
        cache.ensure_uniform(&self.device, &self.bind_group_layout, 1)?;
        cache.ensure_target(&self.device, width, height);
        cache.ensure_readback(&self.device, frame_bytes);
        let uniform = cache.uniform.as_ref().expect("the arena was just ensured");
        let target = cache.target.as_ref().expect("the target was just ensured");
        let readback = cache.readback.as_ref().expect("the readback was just ensured");

        self.queue.write_buffer(&uniform.buffer, 0, &colour_bytes);

        // Encode render pass with full-screen triangle
        let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("gpu_clear_encoder"),
        });
        {
            let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("gpu_clear_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &target.view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            rp.set_pipeline(&self.clear_pipeline);
            rp.set_bind_group(0, &uniform.bind_group, &[0]);
            rp.draw(0..3, 0..1); // 3 vertices for full-screen triangle
        }

        let padded_bytes_per_row = padded_row_bytes(width)?;
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &target.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback.buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(padded_bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
        );

        self.queue.submit(Some(encoder.finish()));
        self.read_back(&readback.buffer, width, height, expected_len)
    }
    /// Render filled rectangles using the GPU pipeline with vertex buffer shaders.
    ///
    /// Each rect is defined as `(x, y, width, height, [r, g, b, a])` where:
    /// - `(x, y)` is the top-left corner in pixel coordinates
    /// - `(width, height)` is the rectangle size in pixels
    /// - `color` is an RGBA float array with values in `[0.0, 1.0]`
    ///
    /// A single rectangle goes through the `FILL_RECT_VS`/`FILL_RECT_FS` pipeline, which selects
    /// its colour from a per-rect uniform. A longer run is expanded to quads and drawn in
    /// `MAX_INSTANCES_PER_DRAW`-sized instanced draws, which produces the same picture with a
    /// draw count that no longer grows with the run (G-64).
    /// Encodes the fill-rect pass into the cached target and submits it.
    ///
    /// Split out from [`Self::render_fill_rect_gpu`] so a compositor can use the rendered
    /// texture directly (REND-02) instead of paying for a full `copy_texture_to_buffer` and a
    /// blocking map. The readback buffer is deliberately **not** ensured here.
    fn encode_fill_rects(
        &self,
        width: u32,
        height: u32,
        rects: &[(i32, i32, u32, u32, [f64; 4])],
    ) -> Result<(), String> {
        // A single rectangle is already one draw, and the per-rect pipeline avoids the matrix
        // uniform upload for that common case. Two or more are packed into instance records and
        // drawn in `MAX_INSTANCES_PER_DRAW`-sized chunks, so the draw count no longer grows with
        // the run (G-64). Chunk order preserves painter order.
        if rects.len() <= 1 {
            self.encode_fill_rects_per_rect(width, height, rects)
        } else {
            self.encode_fill_rects_instanced(width, height, rects)
        }
    }

    /// The single-rectangle path: two triangles and one draw, with the colour selected by a
    /// dynamic uniform offset.
    ///
    /// A run of more than one rectangle takes the instanced path below instead, which is what
    /// keeps the draw count bounded (G-64).
    fn encode_fill_rects_per_rect(
        &self,
        width: u32,
        height: u32,
        rects: &[(i32, i32, u32, u32, [f64; 4])],
    ) -> Result<(), String> {
        let w = width as f32;
        let h = height as f32;

        // Generate transformed vertex positions in NDC and one clamped colour per rect.
        // Both are built directly as bytes: the previous `Vec<f32>` + `flat_map().collect()`
        // pair allocated twice per call for data that is written once (REND-02).
        let mut vertex_bytes: Vec<u8> = Vec::with_capacity(rects.len() * 48);
        let mut colours: Vec<[f32; 4]> = Vec::with_capacity(rects.len());

        for &(x, y, rw, rh, color) in rects {
            // Convert pixel coordinates to NDC: [-1, 1]
            // WebGPU/wgpu NDC: y = +1 maps to top of viewport, y = -1 to bottom
            // (OpenGL convention, not Vulkan).
            let x0 = (x as f32 / w) * 2.0 - 1.0;
            let y0 = 1.0 - (y as f32 / h) * 2.0;
            let x1 = ((x.saturating_add(rw as i32)) as f32 / w) * 2.0 - 1.0;
            let y1 = 1.0 - ((y.saturating_add(rh as i32)) as f32 / h) * 2.0;

            // Two triangles: bottom-left, bottom-right, top-left, then bottom-right, top-right, top-left
            for value in [x0, y0, x1, y0, x0, y1, x1, y0, x1, y1, x0, y1] {
                vertex_bytes.extend_from_slice(&value.to_le_bytes());
            }

            colours.push([
                color[0].clamp(0.0, 1.0) as f32,
                color[1].clamp(0.0, 1.0) as f32,
                color[2].clamp(0.0, 1.0) as f32,
                color[3].clamp(0.0, 1.0) as f32,
            ]);
        }

        // Cached resources for the whole call: one colour arena, one bind group, one vertex
        // buffer and one target (REND-02).
        let mut cache = self.cache.borrow_mut();
        cache.ensure_uniform(&self.device, &self.bind_group_layout, colours.len())?;
        cache.ensure_target(&self.device, width, height);
        cache.ensure_vertices(&self.device, vertex_bytes.len() as u64);
        let uniform = cache.uniform.as_ref().expect("the arena was just ensured");
        let target = cache.target.as_ref().expect("the target was just ensured");
        let vertices = cache.vertices.as_ref().expect("the vertices were just ensured");
        let stride = uniform.stride as usize;

        // One upload for every colour, laid out at the dynamic-offset stride.
        let mut uniform_bytes = vec![0u8; stride * colours.len()];
        for (slot, colour) in colours.iter().enumerate() {
            let start = slot * stride;
            for (channel, value) in colour.iter().enumerate() {
                uniform_bytes[start + channel * 4..start + channel * 4 + 4]
                    .copy_from_slice(&value.to_le_bytes());
            }
        }
        self.queue.write_buffer(&uniform.buffer, 0, &uniform_bytes);
        self.queue.write_buffer(&vertices.buffer, 0, &vertex_bytes);

        let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("gpu_rect_encoder"),
        });
        {
            let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("gpu_rect_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &target.view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            rp.set_pipeline(&self.rect_pipeline);
            rp.set_vertex_buffer(0, vertices.buffer.slice(..vertex_bytes.len() as u64));

            for index in 0..colours.len() {
                let offset = (index * stride) as u32;
                rp.set_bind_group(0, &uniform.bind_group, &[offset]);
                let start = (index * 6) as u32;
                let end = ((index + 1) * 6) as u32;
                rp.draw(start..end, 0..1);
            }
        }

        self.queue.submit(Some(encoder.finish()));
        Ok(())
    }

    /// The batched path: turns every rectangle into a quad and renders the whole run as an
    /// instanced draw through the quad pipeline.
    ///
    /// The identity affine composed with the orthographic pixel-to-clip matrix is exactly the
    /// matrix [`ortho_mvp_bytes`] writes, so the geometry is identical to the per-rect path; only
    /// the draw count changes (G-64).
    fn encode_fill_rects_instanced(
        &self,
        width: u32,
        height: u32,
        rects: &[(i32, i32, u32, u32, [f64; 4])],
    ) -> Result<(), String> {
        let mut quads: Vec<([crate::core::Point; 4], [f64; 4])> = Vec::with_capacity(rects.len());
        for &(x, y, rw, rh, colour) in rects {
            // Saturating addition mirrors the 2D path's treatment of an extreme width/height.
            let x1 = x.saturating_add(rw as i32);
            let y1 = y.saturating_add(rh as i32);
            quads.push((
                [
                    crate::core::Point::new(x, y),
                    crate::core::Point::new(x1, y),
                    crate::core::Point::new(x1, y1),
                    crate::core::Point::new(x, y1),
                ],
                colour,
            ));
        }
        let mvp_bytes = ortho_mvp_bytes(width, height);
        self.encode_instances(width, height, &mvp_bytes, &quads)
    }

    /// Renders a run of quads into the cached target with instanced draws.
    ///
    /// `mvp_bytes` is the column-major model-view-projection matrix every instance is multiplied
    /// by. All instance records are written once into the grow-only buffer and the run is drawn in
    /// `MAX_INSTANCES_PER_DRAW`-sized chunks. Each chunk reads its own slice of that one upload,
    /// so no chunk overwrites another and no quad allocates a buffer. Chunks are submitted in
    /// order, which is what keeps overlapping quads in painter order.
    ///
    /// The target is cleared to transparent first, so an empty run is a transparent frame rather
    /// than stale pixels from a previous call.
    fn encode_instances(
        &self,
        width: u32,
        height: u32,
        mvp_bytes: &[u8; 64],
        quads: &[([crate::core::Point; 4], [f64; 4])],
    ) -> Result<(), String> {
        let instance_bytes = instanced_quad_bytes(quads)?;

        // Cached resources for the whole call: one grow-only instance buffer, one target and
        // one mvp uniform (REND-02).
        let mut cache = self.cache.borrow_mut();
        cache.ensure_target(&self.device, width, height);
        cache.ensure_vertices(&self.device, instance_bytes.len() as u64);
        cache.ensure_transformed_uniform(&self.device, &self.transformed_bind_group_layout);
        let target = cache.target.as_ref().expect("the target was just ensured");
        let instances = cache.vertices.as_ref().expect("the instance buffer was just ensured");
        let transformed = cache.transformed_uniform.as_ref().expect("the mvp was just ensured");

        self.queue.write_buffer(&transformed.buffer, 0, mvp_bytes);
        if !instance_bytes.is_empty() {
            self.queue.write_buffer(&instances.buffer, 0, &instance_bytes);
        }

        let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("gpu_quads_encoder"),
        });
        {
            let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("gpu_quads_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &target.view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            rp.set_pipeline(&self.transformed_pipeline);
            rp.set_bind_group(0, &transformed.bind_group, &[]);
            for (chunk_index, chunk) in quads.chunks(MAX_INSTANCES_PER_DRAW).enumerate() {
                let start = chunk_index * MAX_INSTANCES_PER_DRAW * INSTANCE_BYTES;
                let end = start + chunk.len() * INSTANCE_BYTES;
                rp.set_vertex_buffer(0, instances.buffer.slice(start as u64..end as u64));
                rp.draw(0..6, 0..chunk.len() as u32);
            }
        }

        self.queue.submit(Some(encoder.finish()));
        Ok(())
    }

    /// Renders a run of quads through an arbitrary affine transform (`3d` feature).
    ///
    /// The affine is applied to the local corners before the orthographic pixel-to-clip matrix,
    /// matching the software `FillQuad` path.
    #[cfg(feature = "3d")]
    fn encode_quads_instanced(
        &self,
        width: u32,
        height: u32,
        affine: &crate::render::math3d::Mat3,
        quads: &[([crate::core::Point; 4], [f64; 4])],
    ) -> Result<(), String> {
        let w = width as f32;
        let h = height as f32;
        let ortho = crate::render::math3d::Mat3::scaling(2.0 / w, -2.0 / h)
            .then(&crate::render::math3d::Mat3::translation(-1.0, 1.0));
        let mvp = affine.then(&ortho);
        let mvp_bytes = mvp_column_major_bytes(&crate::render::math3d::Mat4::from_affine(mvp));
        self.encode_instances(width, height, &mvp_bytes, quads)
    }

    /// Renders filled rectangles into the cached target and hands the **view** to `f`.
    ///
    /// This is the texture/view frame path REND-02 asked for: a caller that composites the
    /// result on the GPU never pays for `copy_texture_to_buffer` or a blocking `map_async`.
    /// [`Self::render_fill_rect_gpu`] remains for callers that genuinely need pixels (tests,
    /// screenshots, a host with no GPU compositor).
    pub fn with_fill_rect_texture<R>(
        &self,
        width: u32,
        height: u32,
        rects: &[(i32, i32, u32, u32, [f64; 4])],
        f: impl FnOnce(&wgpu::TextureView) -> R,
    ) -> Result<R, String> {
        rgba_buffer_len(width, height)?;
        if rects.is_empty() {
            return Err("with_fill_rect_texture needs at least one rectangle".to_string());
        }
        self.encode_fill_rects(width, height, rects)?;
        let cache = self.cache.borrow();
        let target = cache.target.as_ref().ok_or_else(|| "render target missing".to_string())?;
        Ok(f(&target.view))
    }

    /// Render filled rectangles using the GPU pipeline with vertex buffer shaders.
    ///
    /// Each rect is defined as `(x, y, width, height, [r, g, b, a])` where:
    /// - `(x, y)` is the top-left corner in pixel coordinates
    /// - `(width, height)` is the rectangle size in pixels
    /// - `color` is an RGBA float array with values in `[0.0, 1.0]`
    ///
    /// Uses the WGSL vertex shader (`FILL_RECT_VS`) with a vertex buffer and the
    /// fragment shader (`FILL_RECT_FS`) with a per-rect uniform colour for a single rectangle.
    /// A longer run is drawn as instanced quad batches through the matrix pipeline (G-64).
    pub fn render_fill_rect_gpu(
        &self,
        width: u32,
        height: u32,
        rects: &[(i32, i32, u32, u32, [f64; 4])],
    ) -> Result<Vec<u8>, String> {
        // Reject zero/overflowing dimensions up front so the empty-rects fast
        // path cannot allocate a wrapped-around buffer either (N-S-66).
        let expected_len = rgba_buffer_len(width, height)?;
        if rects.is_empty() {
            return Ok(vec![0u8; expected_len]);
        }

        self.encode_fill_rects(width, height, rects)?;

        let frame_bytes = readback_frame_bytes(width, height)?;
        let padded_bytes_per_row = padded_row_bytes(width)?;
        let mut cache = self.cache.borrow_mut();
        cache.ensure_readback(&self.device, frame_bytes);
        let target = cache.target.as_ref().expect("the target was just ensured");
        let readback = cache.readback.as_ref().expect("the readback was just ensured");

        let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("gpu_rect_readback"),
        });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &target.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback.buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(padded_bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
        );
        self.queue.submit(Some(encoder.finish()));
        self.read_back(&readback.buffer, width, height, expected_len)
    }

    /// Renders arbitrary quadrilaterals through the instanced `3d` matrix pipeline.
    ///
    /// Each quad is a `([Point; 4], [r, g, b, a])` pair. The four corners are **local logical
    /// pixels** in perimeter order; `affine` is applied to them in the vertex stage, and the
    /// renderer composes that with an orthographic pixel-to-clip matrix. The result is the same
    /// geometry the software backend draws for
    /// [`crate::render::RenderCommand::FillQuad`], which is what lets a 45-degree rotated
    /// rectangle agree across the two paths.
    ///
    /// The whole run is one upload and, below the per-draw cap, one instanced draw; a longer run
    /// streams in order from the same buffer. Culling is disabled so a mirrored (negative-scale)
    /// transform still draws. There is no depth attachment: this path is a 2D affine, and scene
    /// layers keep their existing painter's-order responsibility for control-level occlusion.
    #[cfg(feature = "3d")]
    pub fn render_fill_quads_gpu(
        &self,
        width: u32,
        height: u32,
        affine: &crate::render::math3d::Mat3,
        quads: &[([crate::core::Point; 4], [f64; 4])],
    ) -> Result<Vec<u8>, String> {
        let expected_len = rgba_buffer_len(width, height)?;
        if quads.is_empty() {
            return Ok(vec![0u8; expected_len]);
        }

        self.encode_quads_instanced(width, height, affine, quads)?;

        let frame_bytes = readback_frame_bytes(width, height)?;
        let padded_bytes_per_row = padded_row_bytes(width)?;
        let mut cache = self.cache.borrow_mut();
        cache.ensure_readback(&self.device, frame_bytes);
        let target = cache.target.as_ref().expect("the target was just ensured");
        let readback = cache.readback.as_ref().expect("the readback was just ensured");

        let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("gpu_quads_readback"),
        });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &target.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback.buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(padded_bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
        );
        self.queue.submit(Some(encoder.finish()));
        self.read_back(&readback.buffer, width, height, expected_len)
    }

    /// Renders an indexed triangle mesh through the depth-tested `3d` pipeline.
    ///
    /// `model` places the mesh, `camera` supplies the projection and `viewport` selects the part of
    /// the `width × height` target the camera looks through. The composition is
    /// `model × view-projection × viewport-matrix`, the same one
    /// [`crate::render::mesh3d::project_mesh`] uses, so the GPU and software pictures describe the
    /// same geometry.
    ///
    /// The pass clears colour to transparent and depth to `1.0`, then runs one indexed draw with a
    /// `Depth32Float` attachment compared by `Less`. No triangle is culled: the depth test decides
    /// visibility, matching the documented software policy. The target is read back and returned as
    /// tightly packed RGBA8.
    ///
    /// An empty mesh or an empty viewport returns a transparent frame rather than an error, so a
    /// caller may drop a mesh without special-casing the render call.
    #[cfg(feature = "3d")]
    pub fn render_mesh_3d_gpu(
        &self,
        width: u32,
        height: u32,
        mesh: &crate::render::mesh3d::Mesh3D,
        model: &crate::render::math3d::Mat4,
        camera: &crate::render::mesh3d::Camera,
        viewport: crate::core::Rect,
    ) -> Result<Vec<u8>, String> {
        let expected_len = rgba_buffer_len(width, height)?;
        if mesh.triangle_count() == 0 || viewport.width == 0 || viewport.height == 0 {
            return Ok(vec![0u8; expected_len]);
        }

        let aspect = viewport.width as f32 / viewport.height as f32;
        let mvp = model.then(&camera.view_projection(aspect)).then(
            &crate::render::mesh3d::viewport_matrix(
                viewport,
                crate::core::Size::new(width, height),
            ),
        );
        let mvp_bytes = mvp_column_major_bytes(&mvp);
        let vertex_bytes = mesh_vertex_bytes(mesh);
        let index_bytes = mesh_index_bytes(mesh);
        let index_count = mesh.indices().len() as u32;
        if index_count == 0 {
            return Ok(vec![0u8; expected_len]);
        }

        let mut cache = self.cache.borrow_mut();
        cache.ensure_target(&self.device, width, height);
        cache.ensure_depth_target(&self.device, width, height);
        cache.ensure_vertices(&self.device, vertex_bytes.len() as u64);
        cache.ensure_mesh_indices(&self.device, index_bytes.len() as u64);
        cache.ensure_mesh_uniform(&self.device, &self.transformed_bind_group_layout);
        let target = cache.target.as_ref().ok_or_else(|| "render target missing".to_string())?;
        let depth =
            cache.depth_target.as_ref().ok_or_else(|| "depth target missing".to_string())?;
        let vertices =
            cache.vertices.as_ref().ok_or_else(|| "vertex buffer missing".to_string())?;
        let indices =
            cache.mesh_indices.as_ref().ok_or_else(|| "index buffer missing".to_string())?;
        let uniform =
            cache.mesh_uniform.as_ref().ok_or_else(|| "mvp uniform missing".to_string())?;

        self.queue.write_buffer(&uniform.buffer, 0, &mvp_bytes);
        self.queue.write_buffer(&vertices.buffer, 0, &vertex_bytes);
        self.queue.write_buffer(&indices.buffer, 0, &index_bytes);

        let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("gpu_mesh_encoder"),
        });
        {
            let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("gpu_mesh_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &target.view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: &depth.view,
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Clear(1.0),
                        store: wgpu::StoreOp::Store,
                    }),
                    stencil_ops: None,
                }),
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            rp.set_pipeline(&self.mesh_pipeline);
            rp.set_bind_group(0, &uniform.bind_group, &[]);
            rp.set_vertex_buffer(0, vertices.buffer.slice(..vertex_bytes.len() as u64));
            rp.set_index_buffer(
                indices.buffer.slice(..index_bytes.len() as u64),
                wgpu::IndexFormat::Uint32,
            );
            rp.draw_indexed(0..index_count, 0, 0..1);
        }
        drop(cache);
        self.queue.submit(Some(encoder.finish()));
        self.read_target(width, height, expected_len, "gpu_mesh_readback")
    }

    /// Copies the cached render target into a tight RGBA8 buffer.
    ///
    /// The target must already hold the picture; this helper only arranges the copy and the blocking
    /// read. Kept separate so an entry point that renders through a new pipeline does not repeat the
    /// row-padding arithmetic.
    #[cfg(feature = "3d")]
    fn read_target(
        &self,
        width: u32,
        height: u32,
        expected_len: usize,
        label: &str,
    ) -> Result<Vec<u8>, String> {
        let frame_bytes = readback_frame_bytes(width, height)?;
        let padded_bytes_per_row = padded_row_bytes(width)?;
        let mut cache = self.cache.borrow_mut();
        cache.ensure_readback(&self.device, frame_bytes);
        let target = cache.target.as_ref().ok_or_else(|| "render target missing".to_string())?;
        let readback =
            cache.readback.as_ref().ok_or_else(|| "readback buffer missing".to_string())?;
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(label) });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &target.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback.buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(padded_bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
        );
        self.queue.submit(Some(encoder.finish()));
        self.read_back(&readback.buffer, width, height, expected_len)
    }

    /// Maps a readback buffer, copies its rows into a tight RGBA8 image and unmaps it.
    ///
    /// The buffer belongs to [`RenderCache`], so it must be unmapped before it can be reused:
    /// leaving it mapped made the next `map_async` fail silently, which is why this is one
    /// helper rather than a copy in every entry point.
    ///
    /// The wait is bounded by [`GPU_READBACK_TIMEOUT`]; on expiry the pending mapping is
    /// cancelled with `unmap` and an error is returned, so a lost device reports a failure
    /// instead of hanging the process (G-63).
    fn read_back(
        &self,
        buffer: &wgpu::Buffer,
        width: u32,
        height: u32,
        expected_len: usize,
    ) -> Result<Vec<u8>, String> {
        let unpadded = width
            .checked_mul(4)
            .ok_or_else(|| format!("row byte width for {width} pixels overflows u32"))?
            as usize;
        let padded = padded_row_bytes(width)? as usize;
        let buffer_slice = buffer.slice(..(padded * height as usize) as u64);
        let (sender, receiver) = mpsc::channel();
        buffer_slice.map_async(
            wgpu::MapMode::Read,
            move |result: Result<(), wgpu::BufferAsyncError>| {
                let _ = sender.send(result);
            },
        );
        if let Err(error) = self.device.poll(wgpu::PollType::Wait {
            submission_index: None,
            timeout: Some(GPU_READBACK_TIMEOUT),
        }) {
            // Cancel the still-pending mapping so the cached buffer is usable next call.
            buffer.unmap();
            return Err(format!(
                "GPU readback did not complete within {GPU_READBACK_TIMEOUT:?}: {error}"
            ));
        }
        let map_result = match receiver.recv_timeout(GPU_READBACK_TIMEOUT) {
            Ok(result) => result,
            Err(error) => {
                buffer.unmap();
                return Err(format!(
                    "GPU map callback did not arrive within {GPU_READBACK_TIMEOUT:?}: {error}"
                ));
            }
        };
        if let Err(error) = map_result {
            buffer.unmap();
            return Err(format!("GPU buffer could not be mapped for CPU readback: {error:?}"));
        }
        let mapped = match buffer_slice.get_mapped_range() {
            Ok(mapped) => mapped,
            Err(error) => {
                buffer.unmap();
                return Err(format!("mapped GPU buffer range could not be read back: {error:?}"));
            }
        };

        // Copy row by row, stripping padding.
        let mut pixels = vec![0u8; expected_len];
        for row in 0..height as usize {
            let src_start = row * padded;
            let dst_start = row * unpadded;
            pixels[dst_start..dst_start + unpadded]
                .copy_from_slice(&mapped[src_start..src_start + unpadded]);
        }
        drop(mapped);
        buffer.unmap();
        Ok(pixels)
    }
    /// Render stroked (outlined) rectangles using the GPU pipeline.
    /// Each stroke rect is decomposed into 4 thin filled rectangles
    /// (top, bottom, left, right edges) and rendered via the existing FillRect pipeline.
    #[allow(clippy::type_complexity)]
    pub fn render_stroke_rect_gpu(
        &self,
        width: u32,
        height: u32,
        rects: &[((i32, i32, u32, u32, u32), [f64; 4])],
    ) -> Result<Vec<u8>, String> {
        // Validate dimensions before any allocation (N-S-66).
        let expected_len = rgba_buffer_len(width, height)?;
        if rects.is_empty() {
            return Ok(vec![0u8; expected_len]);
        }

        // Decompose each stroke rect into 4 fill rects
        let mut fill_rects: Vec<((i32, i32, u32, u32), [f64; 4])> =
            Vec::with_capacity(rects.len() * 4);

        for &((x, y, rw, rh, sw), color) in rects {
            let sw_i = sw as i32;
            // Top edge
            fill_rects.push(((x, y, rw, sw), color));
            // Bottom edge
            fill_rects.push(((x, y + rh as i32 - sw_i, rw, sw), color));
            // Left edge (excludes corners already covered by top/bottom)
            let inner_h = rh.saturating_sub(sw * 2);
            if inner_h > 0 {
                fill_rects.push(((x, y + sw_i, sw, inner_h), color));
            }
            // Right edge
            if inner_h > 0 {
                fill_rects.push(((x + rw as i32 - sw_i, y + sw_i, sw, inner_h), color));
            }
        }

        // Convert fill_rects (without stroke_width) back to the (i32, i32, u32, u32, [f64; 4]) format
        let rect_input: Vec<(i32, i32, u32, u32, [f64; 4])> =
            fill_rects.into_iter().map(|((x, y, w, h), color)| (x, y, w, h, color)).collect();
        self.render_fill_rect_gpu(width, height, &rect_input)
    }

    /// Render lines using the GPU pipeline.
    /// Each line is approximated as a thin filled rectangle.
    /// Horizontal/vertical-aligned lines are rendered accurately;
    /// diagonal lines are approximated as axis-aligned thin rects.
    #[allow(clippy::type_complexity)]
    pub fn render_draw_line_gpu(
        &self,
        width: u32,
        height: u32,
        lines: &[((i32, i32, i32, i32, u32), [f64; 4])],
    ) -> Result<Vec<u8>, String> {
        // Validate dimensions before any allocation (N-S-66).
        let expected_len = rgba_buffer_len(width, height)?;
        if lines.is_empty() {
            return Ok(vec![0u8; expected_len]);
        }

        let mut fill_rects: Vec<(i32, i32, u32, u32, [f64; 4])> = Vec::with_capacity(lines.len());

        for &((x1, y1, x2, y2, lw), color) in lines {
            let lw_i = lw as i32;
            let dx = (x2 - x1).abs();
            let dy = (y2 - y1).abs();

            if dx >= dy {
                // More horizontal: render as horizontal thin rect
                let min_x = x1.min(x2);
                let line_len = dx.max(1) as u32;
                fill_rects.push((min_x, y1 - lw_i / 2, line_len, lw, color));
            } else {
                // More vertical: render as vertical thin rect
                let min_y = y1.min(y2);
                let line_len = dy.max(1) as u32;
                fill_rects.push((x1 - lw_i / 2, min_y, lw, line_len, color));
            }
        }

        self.render_fill_rect_gpu(width, height, &fill_rects)
    }

    /// Render filled circles using the GPU pipeline.
    /// Each circle is approximated as vertical strips (thin rectangles).
    /// The more strips, the smoother the circle.
    #[allow(clippy::type_complexity)]
    pub fn render_fill_circle_gpu(
        &self,
        width: u32,
        height: u32,
        circles: &[((i32, i32, u32), [f64; 4])], // ((cx, cy, radius), color)
    ) -> Result<Vec<u8>, String> {
        // Validate dimensions before any allocation (N-S-66).
        let expected_len = rgba_buffer_len(width, height)?;
        if circles.is_empty() {
            return Ok(vec![0u8; expected_len]);
        }

        let mut fill_rects: Vec<(i32, i32, u32, u32, [f64; 4])> = Vec::new();

        for &((cx, cy, radius), color) in circles {
            let r = radius as i32;
            // Use vertical strips to approximate the circle
            // Each strip is 1 pixel wide
            for dx in -r..=r {
                let half_height = ((r * r - dx * dx) as f64).sqrt() as i32;
                let x = cx + dx;
                let y1 = cy - half_height;
                let strip_height = (half_height * 2) as u32;
                if strip_height > 0 {
                    fill_rects.push((x, y1, 1, strip_height, color));
                }
            }
        }

        // Convert to the format expected by render_fill_rect_gpu
        let rects: Vec<(i32, i32, u32, u32, [f64; 4])> = fill_rects;
        self.render_fill_rect_gpu(width, height, &rects)
    }

    /// Render command list with deterministic ordering and clipping.
    ///
    /// # Cost (G-63)
    ///
    /// The command list is rasterised on the CPU and the finished frame is then uploaded to a
    /// texture and read back, so the GPU only performs a copy. The round trip makes this slower
    /// than returning [`rasterize_draw_commands_rgba8`] directly; it is kept because it is the
    /// placeholder for the planned on-GPU rasterisation (see the module documentation).
    pub fn render_draw_commands_rgba8(
        &self,
        width: u32,
        height: u32,
        commands: &[WgpuDrawCommand],
    ) -> Result<Vec<u8>, String> {
        let pixels = rasterize_draw_commands_rgba8(width, height, commands)?;
        self.upload_and_readback_rgba8(width, height, &pixels)
    }
    /// Applies a separable Gaussian blur to an RGBA8 image on the GPU.
    ///
    /// # Why two passes
    ///
    /// A Gaussian kernel is separable: blurring rows and then columns costs `O(radius)` per pixel
    /// instead of `O(radius²)`. Each pass is one full-screen draw through [`super::shaders::BLUR_FS`],
    /// ping-ponging between two cached textures. The input is uploaded once, the result read back
    /// once, and every intermediate stage stays on the GPU.
    ///
    /// `radius` is the Gaussian's 2-sigma point, matching [`crate::render::RenderCommand::Blur`], and is clamped
    /// to the same 100-pixel ceiling the software path uses. A zero radius is an identity and
    /// returns the input bytes unchanged (no GPU round trip).
    ///
    /// This is the hardware path the backdrop-blur layer uses. It is a 2D effect, so it is compiled
    /// in every build rather than behind the `3d` feature.
    pub fn render_blur_rgba8(
        &self,
        width: u32,
        height: u32,
        rgba8: &[u8],
        radius: u32,
    ) -> Result<Vec<u8>, String> {
        let expected_len = rgba_buffer_len(width, height)?;
        if rgba8.len() != expected_len {
            return Err(format!(
                "rgba8 input is {} bytes but a {width}x{height} image needs {expected_len} bytes",
                rgba8.len(),
            ));
        }
        let radius = radius.min(100);
        if radius == 0 {
            return Ok(rgba8.to_vec());
        }
        let padded_bytes_per_row = padded_row_bytes(width)?;
        let output_buffer_size = readback_frame_bytes(width, height)?;
        let mut cache = self.cache.borrow_mut();
        cache.ensure_blur_targets(&self.device, &self.blur_bind_group_layout, width, height);
        cache.ensure_readback(&self.device, output_buffer_size);
        let targets = cache.blur.as_ref().expect("the blur targets were just ensured");
        let readback = cache.readback.as_ref().expect("the readback was just ensured");

        self.queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &targets.source,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba8,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(width * 4),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
        );
        let write_params = |buffer: &wgpu::Buffer, direction: [f32; 2]| {
            let mut bytes = [0u8; 16];
            bytes[0..4].copy_from_slice(&direction[0].to_ne_bytes());
            bytes[4..8].copy_from_slice(&direction[1].to_ne_bytes());
            bytes[8..12].copy_from_slice(&(radius as f32).to_ne_bytes());
            self.queue.write_buffer(buffer, 0, &bytes);
        };
        write_params(&targets.horizontal_params, [1.0, 0.0]);
        write_params(&targets.vertical_params, [0.0, 1.0]);

        let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("wgpu_blur_encoder"),
        });
        let mut blur_pass = |view: &wgpu::TextureView, group: &wgpu::BindGroup, label: &str| {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some(label),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_pipeline(&self.blur_pipeline);
            pass.set_bind_group(0, group, &[]);
            pass.draw(0..3, 0..1);
        };
        blur_pass(&targets.scratch_view, &targets.horizontal, "wgpu_blur_horizontal");
        blur_pass(&targets.source_view, &targets.vertical, "wgpu_blur_vertical");

        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &targets.source,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback.buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(padded_bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
        );
        self.queue.submit(Some(encoder.finish()));
        self.read_back(&readback.buffer, width, height, expected_len)
    }

    /// Applies one backdrop-blur pass to a frame that has already been composed.
    ///
    /// # Where the pass runs
    ///
    /// The existing offscreen target is the pass's storage: the frame is uploaded into it
    /// and read back before the blur, so the caller hands over the pixels the GPU actually
    /// produced rather than a CPU-side copy of what it meant to draw. This renderer's
    /// pipeline set has no blur shader (only the fill, image, text, rounded-rect and circle
    /// programs ship), so the convolution itself runs through the existing software blur —
    /// the same three-box Gaussian approximation every other blur in the crate uses. Adding a
    /// WGSL program for one effect would be a new pipeline to keep in step with this one for
    /// no picture difference, so the offscreen round trip is the GPU half and the kernel is
    /// shared.
    ///
    /// `radius` is the Gaussian's 2-sigma point, matching [`crate::render::RenderCommand::Blur`]. The
    /// tint, when present, is applied afterwards so it sits on the blurred backdrop, as it does in
    /// the software layer composition.
    ///
    /// The frame is uploaded straight into the blur source texture and only the final result is
    /// read back. An earlier form uploaded and read the backdrop first and then uploaded it again
    /// for the blur, paying two round trips for one result (G-65). A zero radius is an identity
    /// and returns the validated input bytes with no GPU work at all.
    pub fn render_backdrop_blur_rgba8(
        &self,
        width: u32,
        height: u32,
        backdrop: &[u8],
        radius: u32,
        tint: Option<(Rgba8, f32)>,
    ) -> Result<Vec<u8>, String> {
        let mut frame = self.render_blur_rgba8(width, height, backdrop, radius)?;
        if let Some((tint, weight)) = tint {
            tint_blurred_frame(&mut frame, tint, weight);
        }
        Ok(frame)
    }

    /// Upload a full RGBA8 frame to GPU texture and read it back deterministically.
    pub fn upload_rgba8_and_readback(
        &self,
        width: u32,
        height: u32,
        rgba8: &[u8],
    ) -> Result<Vec<u8>, String> {
        // Zero dimensions have no GPU texture representation and must be an
        // explicit error, not a zero-sized texture that silently succeeds
        // (N-S-66).
        if width == 0 || height == 0 {
            return Err(format!("width/height must be > 0, got {width}x{height}"));
        }
        // Compute the expected byte length with checked wide-type arithmetic: in
        // `u32` the product wraps (65536×16384 = 2^32), so this both reports
        // overflow and validates the input length against the real size (N-S-66).
        let expected_len = rgba_buffer_len(width, height)?;
        if rgba8.len() != expected_len {
            return Err(format!(
                "rgba8 input is {} bytes but a {width}x{height} image needs {expected_len} bytes",
                rgba8.len(),
            ));
        }
        let padded_bytes_per_row = padded_row_bytes(width)?;
        let output_buffer_size = readback_frame_bytes(width, height)?;

        // Cached upload texture and readback buffer (REND-02). Both are fully overwritten by this
        // call — `write_texture` covers the whole extent — so no previous frame can leak through.
        let mut cache = self.cache.borrow_mut();
        cache.ensure_upload_target(&self.device, width, height);
        cache.ensure_readback(&self.device, output_buffer_size);
        let target = cache.upload_target.as_ref().expect("the upload target was just ensured");
        let readback = cache.readback.as_ref().expect("the readback was just ensured");

        self.queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &target.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba8,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(width * 4),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
        );
        let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("rw_wgpu_encoder"),
        });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &target.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback.buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(padded_bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
        );
        self.queue.submit(Some(encoder.finish()));
        self.read_back(&readback.buffer, width, height, expected_len)
    }
    fn upload_and_readback_rgba8(
        &self,
        width: u32,
        height: u32,
        rgba8: &[u8],
    ) -> Result<Vec<u8>, String> {
        self.upload_rgba8_and_readback(width, height, rgba8)
    }

    /// Get the shader module enum for integration (BLUE11 R5.2).
    pub fn shader_modules(&self) -> Vec<ShaderModule> {
        vec![
            ShaderModule::FillRect,
            ShaderModule::DrawImage,
            ShaderModule::DrawText,
            ShaderModule::FillRoundedRect,
            ShaderModule::FillCircle,
        ]
    }

    /// Return a reference to the cached wgpu `ShaderModule` for the given module name.
    pub fn get_shader_module(&self, name: &str) -> Option<&wgpu::ShaderModule> {
        self.shader_cache.get(name)
    }
}

impl GpuRenderer for WgpuRenderer {
    fn initialize(&mut self) -> Result<(), String> {
        // Device and queue are already initialized in `new()`, so this is a no-op.
        Ok(())
    }

    fn capabilities(&self) -> &[GpuCapability] {
        &[GpuCapability::Basic2D, GpuCapability::Texture]
    }

    fn has_capability(&self, capability: GpuCapability) -> bool {
        matches!(capability, GpuCapability::Basic2D | GpuCapability::Texture)
    }

    fn render_frame(&mut self) -> Result<(), String> {
        // # Why this is an error and not a silent `Ok` (D09-GPU-01)
        //
        // This renderer exposes GPU draw entry points (`render_fill_rect_gpu`,
        // `render_draw_commands_rgba8`, …) that rasterise offscreen, but it has no swapchain or
        // present path: there is no way to put a frame on a window from here. Returning `Ok(())`
        // while drawing nothing is the same kind of untruth as reporting a GPU-accelerated scene
        // backend that only round-trips through the CPU — it tells the caller a frame was
        // presented when none was. Offscreen work belongs to the `render_*_rgba8` methods; a
        // real frame loop must be added before this can succeed.
        Err("WgpuRenderer has no present/swapchain path; render offscreen with the \
             render_*_rgba8 methods instead"
            .to_string())
    }

    fn memory_usage(&self) -> u64 {
        // No reliable GPU-memory query is available through the current wgpu backend.
        0
    }

    fn vendor_info(&self) -> &str {
        // Vendor/device info is available from `wgpu::Adapter::get_info()`, but we do not
        // store the adapter after construction. This will be plumbed in a follow-up.
        "wgpu (WGPU)"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    /// A renderer on this host, or `None` when no adapter can be reached.
    ///
    /// The GPU tests are real: they submit work and read the pixels back. A host with no
    /// adapter cannot answer them, so they report the skip rather than failing — the same
    /// contract the platform code uses for an unavailable capability.
    fn renderer() -> Option<WgpuRenderer> {
        match WgpuRenderer::new() {
            Ok(renderer) => Some(renderer),
            Err(error) => {
                eprintln!("skipping GPU test: no wgpu adapter available ({error})");
                None
            }
        }
    }

    fn pixel(pixels: &[u8], width: u32, x: u32, y: u32) -> [u8; 4] {
        let start = ((y * width + x) * 4) as usize;
        [pixels[start], pixels[start + 1], pixels[start + 2], pixels[start + 3]]
    }

    /// G-213: the enum's pipeline table and the shader cache the renderer registers must agree.
    ///
    /// Every member that names a pipeline key must have that key in the cache, and the cache's
    /// key set is asserted exactly, so adding a shader without wiring it into a pipeline — or
    /// deleting one — fails here instead of drifting silently.
    #[test]
    fn shader_module_registry_matches_pipelines() {
        let Some(renderer) = renderer() else { return };

        let mut expected = vec![
            "clear_vs",
            "clear_fs",
            "rect_vs",
            "rect_fs",
            "blur_vs",
            "blur_fs",
            "rect_vs_transformed",
            "rect_fs_instanced",
        ];
        #[cfg(feature = "3d")]
        expected.extend(["mesh3d_vs", "mesh3d_fs"]);
        let mut registered: Vec<&str> = renderer.shader_cache.keys().map(String::as_str).collect();
        expected.sort_unstable();
        registered.sort_unstable();
        assert_eq!(
            registered, expected,
            "the registered shader cache drifted from the pipeline table; wire or remove the \
             entry and update the table in this test"
        );

        for module in renderer.shader_modules() {
            if let Some(key) = module.pipeline_cache_key() {
                assert!(
                    renderer.get_shader_module(key).is_some(),
                    "{module:?} advertises pipeline key {key:?}, but no such module is \
                     registered"
                );
            }
        }
    }

    /// Growth is geometric and block-rounded, so a frame that needs a few more bytes reuses the
    /// existing buffer instead of recreating it at the exact size (G-09).
    #[test]
    fn buffer_growth_leaves_headroom_and_respects_the_limit() {
        assert_eq!(grown_buffer_capacity(0, 1, u64::MAX), 65_536);
        let first = grown_buffer_capacity(0, 100 * 1024, u64::MAX);
        assert!(first >= 100 * 1024);
        assert_eq!(first % 65_536, 0, "capacities are whole 64 KiB blocks");

        // A small increase must not force a new allocation.
        let grown = grown_buffer_capacity(first, first + 16, u64::MAX);
        assert!(grown > first, "growth is geometric, not exact-size");
        assert_eq!(grown, first + first / 2, "the next step is 1.5x before rounding");

        // The device limit caps the rounded capacity; the caller rejects a request that cannot
        // fit at all before calling this.
        assert_eq!(grown_buffer_capacity(0, 3, 4), 4);
    }

    /// The texture/view path renders without asking for pixels back (REND-02).
    #[test]
    fn texture_path_renders_a_view_without_readback() {
        let Some(renderer) = renderer() else { return };
        let rects = [(0, 0, 4, 4, [1.0, 0.0, 0.0, 1.0])];
        let seen = renderer
            .with_fill_rect_texture(4, 4, &rects, |_view| true)
            .expect("the texture path must render");
        assert!(seen, "the closure receives the rendered view");
    }

    /// A clear must fill every pixel with the requested colour.
    #[test]
    fn clear_writes_the_requested_colour_across_the_frame() {
        let Some(renderer) = renderer() else { return };
        let pixels =
            renderer.render_clear_gpu(4, 3, [1.0, 0.0, 0.0, 1.0]).expect("the clear must render");
        assert_eq!(pixels.len(), 4 * 3 * 4);
        for y in 0..3 {
            for x in 0..4 {
                assert_eq!(pixel(&pixels, 4, x, y), [255, 0, 0, 255]);
            }
        }
    }

    /// Two rectangles must each land in their own corner — and the second call through the
    /// cached buffers must produce exactly the same picture as the first (REND-02's reuse path).
    #[test]
    fn fill_rect_reuses_its_buffers_without_changing_the_picture() {
        let Some(renderer) = renderer() else { return };
        let rects = [(0, 0, 4, 4, [1.0, 0.0, 0.0, 1.0]), (4, 4, 4, 4, [0.0, 0.0, 1.0, 1.0])];
        let first = renderer.render_fill_rect_gpu(8, 8, &rects).expect("first fill");
        let second = renderer.render_fill_rect_gpu(8, 8, &rects).expect("second fill");
        assert_eq!(first, second, "cached resources must reproduce the same frame");
        assert_eq!(pixel(&first, 8, 0, 0), [255, 0, 0, 255]);
        assert_eq!(pixel(&first, 8, 3, 3), [255, 0, 0, 255]);
        assert_eq!(pixel(&first, 8, 4, 4), [0, 0, 255, 255]);
        assert_eq!(pixel(&first, 8, 7, 7), [0, 0, 255, 255]);
        assert_eq!(pixel(&first, 8, 7, 0), [0, 0, 0, 0]);
    }

    /// A larger run must still place every rectangle's colour on its own pixels.
    ///
    /// Three rectangles now take the instanced batched path (G-64), so this is the guard that the
    /// batching change did not collapse or reorder their colours.
    #[test]
    fn a_larger_run_renders_every_colour() {
        let Some(renderer) = renderer() else { return };
        let one = [(0, 0, 4, 2, [1.0, 0.0, 0.0, 1.0])];
        renderer.render_fill_rect_gpu(4, 2, &one).expect("one rect");
        let three = [
            (0, 0, 1, 1, [1.0, 0.0, 0.0, 1.0]),
            (1, 0, 1, 1, [0.0, 1.0, 0.0, 1.0]),
            (2, 0, 1, 1, [0.0, 0.0, 1.0, 1.0]),
        ];
        let pixels = renderer.render_fill_rect_gpu(4, 2, &three).expect("three rects");
        assert_eq!(pixel(&pixels, 4, 0, 0), [255, 0, 0, 255]);
        assert_eq!(pixel(&pixels, 4, 1, 0), [0, 255, 0, 255]);
        assert_eq!(pixel(&pixels, 4, 2, 0), [0, 0, 255, 255]);
    }

    /// An upload must round-trip the exact bytes it was given.
    #[test]
    fn upload_round_trips_the_given_pixels() {
        let Some(renderer) = renderer() else { return };
        let input: Vec<u8> = (0..(4 * 4 * 4) as u8).collect();
        let output =
            renderer.upload_rgba8_and_readback(4, 4, &input).expect("the upload must round-trip");
        assert_eq!(output, input);
        // A second call reuses the cached upload texture and readback buffer.
        assert_eq!(renderer.upload_rgba8_and_readback(4, 4, &input).expect("second upload"), input);
    }

    #[cfg(feature = "3d")]
    #[test]
    fn fill_quads_empty_is_transparent() {
        let Some(renderer) = renderer() else { return };
        let pixels = renderer
            .render_fill_quads_gpu(8, 8, &crate::render::math3d::Mat3::IDENTITY, &[])
            .expect("an empty quad batch must produce a frame");
        assert_eq!(pixels.len(), 8 * 8 * 4);
        assert!(pixels.iter().all(|&byte| byte == 0));
    }

    /// A rectangle rotated by 45 degrees must land on the same pixels through the matrix
    /// pipeline as it does through the software polygon fill.
    ///
    /// The comparison deliberately samples the interior and the hidden corners rather than the
    /// edge pixels: both rasterisers are hard-edged but use different fill rules, so exact
    /// agreement on a sloped boundary is not something either path promises.
    #[cfg(feature = "3d")]
    #[test]
    fn a_45_degree_rotated_rect_agrees_with_the_software_path() {
        use crate::core::{Color, Point};
        use crate::render::math3d::Mat3;
        use crate::render::SoftwareSurface;

        let Some(renderer) = renderer() else { return };
        let affine = Mat3::translation(-16.0, -16.0)
            .then(&Mat3::rotation(core::f32::consts::FRAC_PI_4))
            .then(&Mat3::translation(16.0, 16.0));
        let local = [Point::new(8, 8), Point::new(24, 8), Point::new(24, 24), Point::new(8, 24)];

        let gpu = renderer
            .render_fill_quads_gpu(32, 32, &affine, &[(local, [1.0, 0.0, 0.0, 1.0])])
            .expect("the matrix pipeline must render");

        let mapped = local.map(|point| affine.map_point(point));
        let mut surface = SoftwareSurface::new(crate::core::Size::new(32, 32), 1.0);
        surface.begin_frame(Color::TRANSPARENT);
        surface.draw_path(&mapped[..], true, Color::RED, true, 0);
        surface.end_frame();
        let software = surface.frame_rgba();

        for (x, y, what) in [
            (16, 16, "centre"),
            (10, 16, "left interior"),
            (22, 16, "right interior"),
            (16, 10, "top interior"),
            (16, 22, "bottom interior"),
        ] {
            assert_eq!(
                pixel(software, 32, x, y),
                pixel(&gpu, 32, x, y),
                "{what} must agree between the software and matrix paths"
            );
        }
        for (x, y) in [(0, 0), (31, 0), (0, 31), (31, 31)] {
            assert_eq!(
                pixel(software, 32, x, y),
                pixel(&gpu, 32, x, y),
                "a corner outside the rotated square must remain transparent in both paths"
            );
        }
    }

    /// Builds an axis-aligned quad in perimeter order, matching the corner order the instanced
    /// shader expands into two triangles.
    #[cfg(feature = "3d")]
    fn quad_rect(x: i32, y: i32, x1: i32, y1: i32) -> [crate::core::Point; 4] {
        [
            crate::core::Point::new(x, y),
            crate::core::Point::new(x1, y),
            crate::core::Point::new(x1, y1),
            crate::core::Point::new(x, y1),
        ]
    }

    /// Converts a `Color` to the `0.0..=1.0` tuple the GPU entry points take.
    #[cfg(feature = "3d")]
    fn gpu_colour(color: crate::core::Color) -> [f64; 4] {
        [
            color.r as f64 / 255.0,
            color.g as f64 / 255.0,
            color.b as f64 / 255.0,
            color.a as f64 / 255.0,
        ]
    }

    /// An instanced run of axis-aligned quads must produce exactly the software picture at the
    /// sampled pixels, including overlapping quads, whose later instances paint over earlier
    /// ones.
    ///
    /// The samples are interiors rather than edges: the software scanline fill and the GPU both
    /// cover a shape's interior identically, but their boundary conventions differ, so an edge
    /// pixel is not a fair pixel-for-pixel comparison for either path.
    #[cfg(feature = "3d")]
    #[test]
    fn instanced_run_matches_the_software_reference() {
        use crate::core::{Color, Point};
        use crate::render::math3d::Mat3;
        use crate::render::SoftwareSurface;

        let Some(renderer) = renderer() else { return };
        let run = [
            (quad_rect(2, 2, 10, 10), Color::RED),
            (quad_rect(8, 2, 16, 10), Color::GREEN),
            (quad_rect(2, 8, 10, 16), Color::BLUE),
            (quad_rect(8, 8, 16, 16), Color::YELLOW),
        ];
        let quads: Vec<([Point; 4], [f64; 4])> =
            run.iter().map(|(corners, colour)| (*corners, gpu_colour(*colour))).collect();

        let gpu = renderer
            .render_fill_quads_gpu(18, 18, &Mat3::IDENTITY, &quads)
            .expect("the instanced run must render");

        let mut surface = SoftwareSurface::new(crate::core::Size::new(18, 18), 1.0);
        surface.begin_frame(Color::TRANSPARENT);
        for (corners, colour) in run {
            surface.draw_path(&corners, true, colour, true, 0);
        }
        surface.end_frame();
        let software = surface.frame_rgba();

        // One sample per quad, one per pair overlap, and one where all four overlap. The
        // expected colour is the last quad in `run` that covers the point, so this also proves
        // the instanced draw preserved painter order.
        for (x, y, expected) in [
            (4, 4, Color::RED),
            (12, 4, Color::GREEN),
            (4, 12, Color::BLUE),
            (12, 12, Color::YELLOW),
            (9, 4, Color::GREEN),
            (4, 9, Color::BLUE),
            (12, 9, Color::YELLOW),
            (9, 12, Color::YELLOW),
            (9, 9, Color::YELLOW),
        ] {
            assert_eq!(
                pixel(&gpu, 18, x, y),
                pixel(&software, 18, x, y),
                "pixel ({x}, {y}) must match the software reference"
            );
            assert_eq!(
                pixel(&gpu, 18, x, y),
                [expected.r, expected.g, expected.b, expected.a],
                "pixel ({x}, {y}) must show the last quad in the run that covers it"
            );
        }
    }

    /// An empty instanced run must produce a transparent frame, not stale pixels.
    #[cfg(feature = "3d")]
    #[test]
    fn instanced_empty_run_is_transparent() {
        let Some(renderer) = renderer() else { return };
        let pixels = renderer
            .render_fill_quads_gpu(8, 8, &crate::render::math3d::Mat3::IDENTITY, &[])
            .expect("an empty instanced run must produce a frame");
        assert_eq!(pixels.len(), 8 * 8 * 4);
        assert!(pixels.iter().all(|&byte| byte == 0));
    }

    /// A run longer than the per-draw cap must stream across chunks without reordering: the
    /// lone instance in the second chunk must read its own record, not the first chunk's.
    #[cfg(feature = "3d")]
    #[test]
    fn an_over_cap_instanced_run_streams_every_chunk_in_order() {
        let Some(renderer) = renderer() else { return };
        // Quads are 2x1 so no pixel centre lies on the shared triangle edge; 1024 of them fit
        // in one row, and the extra instance lands on the next row.
        let per_row = 1024u32;
        let total = MAX_INSTANCES_PER_DRAW + 1;
        let width = per_row * 2;
        let height = (total as u32).div_ceil(per_row);
        let mut quads = Vec::with_capacity(total);
        for index in 0..total {
            let x = ((index as u32 % per_row) * 2) as i32;
            let y = (index as u32 / per_row) as i32;
            let colour =
                if index + 1 == total { [0.0, 0.0, 1.0, 1.0] } else { [1.0, 0.0, 0.0, 1.0] };
            quads.push((quad_rect(x, y, x + 2, y + 1), colour));
        }
        let pixels = renderer
            .render_fill_quads_gpu(width, height, &crate::render::math3d::Mat3::IDENTITY, &quads)
            .expect("an over-cap run must render");

        let sample = |index: usize| -> [u8; 4] {
            let x = (index as u32 % per_row) * 2;
            let y = index as u32 / per_row;
            pixel(&pixels, width, x, y)
        };
        let last = total - 1;
        assert_eq!(sample(last), [0, 0, 255, 255], "the second chunk must draw its own quad");
        assert_eq!(sample(last - 1), [255, 0, 0, 255], "the first chunk's last quad must draw");
        assert_eq!(sample(0), [255, 0, 0, 255], "the first chunk's first quad must draw");
    }

    /// A run of 45-degree rotated quads must land on the same interior pixels through the
    /// instanced matrix pipeline as it does through the software polygon fill.
    ///
    /// The comparison samples each square's mapped centre and the frame corners rather than a
    /// sloped boundary: the two rasterisers are hard-edged but use different fill rules, so
    /// exact agreement on an edge is not something either path promises.
    #[cfg(feature = "3d")]
    #[test]
    fn a_45_degree_instanced_run_agrees_with_the_software_path() {
        use crate::core::{Color, Point};
        use crate::render::math3d::Mat3;
        use crate::render::SoftwareSurface;

        let Some(renderer) = renderer() else { return };
        let affine = Mat3::translation(-16.0, -16.0)
            .then(&Mat3::rotation(core::f32::consts::FRAC_PI_4))
            .then(&Mat3::translation(16.0, 16.0));
        let run = [
            (quad_rect(6, 6, 14, 14), Color::RED),
            (quad_rect(18, 6, 26, 14), Color::GREEN),
            (quad_rect(6, 18, 14, 26), Color::BLUE),
        ];
        let quads: Vec<([Point; 4], [f64; 4])> =
            run.iter().map(|(corners, colour)| (*corners, gpu_colour(*colour))).collect();

        let gpu = renderer
            .render_fill_quads_gpu(32, 32, &affine, &quads)
            .expect("the instanced matrix pipeline must render");

        let mut surface = SoftwareSurface::new(crate::core::Size::new(32, 32), 1.0);
        surface.begin_frame(Color::TRANSPARENT);
        for (corners, colour) in run {
            let mapped = corners.map(|point| affine.map_point(point));
            surface.draw_path(&mapped, true, colour, true, 0);
        }
        surface.end_frame();
        let software = surface.frame_rgba();

        for ((corners, _colour), what) in run.iter().zip(["top-left", "top-right", "bottom-left"]) {
            let centre = affine.map_point(Point::new(
                (corners[0].x + corners[2].x) / 2,
                (corners[0].y + corners[2].y) / 2,
            ));
            let (x, y) = (centre.x as u32, centre.y as u32);
            assert_eq!(
                pixel(software, 32, x, y),
                pixel(&gpu, 32, x, y),
                "the {what} square centre must agree between the software and instanced paths"
            );
        }
        for (x, y) in [(0, 0), (31, 0), (0, 31), (31, 31)] {
            assert_eq!(
                pixel(software, 32, x, y),
                pixel(&gpu, 32, x, y),
                "a corner outside the rotated run must remain transparent in both paths"
            );
        }
    }

    /// A zero radius is the identity, and it must not even touch the GPU.
    #[test]
    fn a_zero_radius_blur_returns_the_input() {
        let Some(renderer) = renderer() else { return };
        let input = vec![9u8; 4 * 4 * 4];
        let output = renderer.render_blur_rgba8(4, 4, &input, 0).expect("identity blur");
        assert_eq!(output, input);
    }

    /// A uniform field is a fixed point of a normalised blur kernel.
    ///
    /// This is the property a separable GPU pass is most likely to break with a bad weight or an
    /// edge clamp: a field of one colour must stay that colour, because every tap reads the same
    /// value and the weights sum to one.
    #[test]
    fn a_uniform_field_survives_the_gpu_blur() {
        let Some(renderer) = renderer() else { return };
        let input: Vec<u8> = (0..8 * 8).flat_map(|_| [100u8, 150, 200, 255]).collect();
        let output = renderer.render_blur_rgba8(8, 8, &input, 3).expect("the blur pass runs");
        for y in 0..8 {
            for x in 0..8 {
                let seen = pixel(&output, 8, x, y);
                for channel in 0..4 {
                    assert!(
                        seen[channel].abs_diff(input[channel]) <= 1,
                        "a uniform field must stay uniform at ({x},{y}), got {seen:?}"
                    );
                }
            }
        }
    }

    /// A blur moves colour across a hard edge and stays symmetric about it.
    ///
    /// The left half is red and the right half blue. After the blur the pixels either side of the
    /// seam must both contain some of each colour, and their values must mirror: the kernel is
    /// symmetric, so sampling one pixel left of the seam and one right of it must produce the same
    /// two-colour mixture.
    #[test]
    fn the_gpu_blur_spreads_an_edge_symmetrically() {
        let Some(renderer) = renderer() else { return };
        let width = 16u32;
        let height = 4u32;
        let mut input = vec![0u8; (width * height * 4) as usize];
        for y in 0..height {
            for x in 0..width {
                let offset = ((y * width + x) * 4) as usize;
                if x < width / 2 {
                    input[offset..offset + 4].copy_from_slice(&[255, 0, 0, 255]);
                } else {
                    input[offset..offset + 4].copy_from_slice(&[0, 0, 255, 255]);
                }
            }
        }
        let output = renderer.render_blur_rgba8(width, height, &input, 4).expect("the blur runs");
        let left = pixel(&output, width, width / 2 - 1, 2);
        let right = pixel(&output, width, width / 2, 2);
        assert!(left[2] > 0, "blue must bleed left of the seam: {left:?}");
        assert!(right[0] > 0, "red must bleed right of the seam: {right:?}");
        // Symmetry about the seam swaps the two colours, so the red/blue channels mirror each
        // other rather than matching channel for channel.
        assert!(
            left[0].abs_diff(right[2]) <= 2 && left[2].abs_diff(right[0]) <= 2,
            "the two sides of a symmetric edge must mirror: {left:?} vs {right:?}"
        );
    }

    /// The depth-tested mesh path draws the near face of a cube and leaves the background clear.
    ///
    /// This runs only on a host with an adapter; on a headless host it compiles and skips, which is
    /// what keeps the pipeline type-checked without making the suite GPU-dependent.
    #[cfg(feature = "3d")]
    #[test]
    fn the_gpu_mesh_pipeline_draws_a_cube_through_a_depth_attachment() {
        use crate::render::math3d::Mat4;
        use crate::render::mesh3d::{Camera, Mesh3D, Vec3};

        let Some(renderer) = renderer() else { return };
        let mesh = Mesh3D::cube(Vec3::ZERO, 2.0, [crate::core::Color::RED; 6]);
        let camera = Camera::new(Vec3::new(3.0, 2.0, 6.0), Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0));
        let pixels = renderer
            .render_mesh_3d_gpu(
                64,
                64,
                &mesh,
                &Mat4::IDENTITY,
                &camera,
                crate::core::Rect::new(0, 0, 64, 64),
            )
            .expect("the mesh pipeline runs");
        assert_eq!(pixels.len(), 64 * 64 * 4);
        let painted = pixels.chunks_exact(4).filter(|pixel| pixel[3] > 0).count();
        assert!(painted > 100, "the cube must cover part of the target, got {painted} pixels");
    }
}