frust-engine 0.5.2

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

use frust_engine::filters::blur::{
    FILTER_ATLAS_PADDING, FILTER_SIZE_BYTES, FilterInstanceData, GpuFilterData, GpuGaussianBlur,
    LinearKernel, MAX_KERNEL_SIZE, MAX_TAPS_PER_SIDE, blur_passes, edge_mode, filter_type,
    pack_u16_pair,
};
use frust_engine::filters::drop_shadow::{GpuDropShadow, drop_shadow_passes};
use frust_engine::filters::{
    FilterPassKind, LayerFilter, MAX_BLUR_SIGMA, SERVED_EDGE_MODE, ServedFilter, device_blur_sigma,
    push_filter_layer, served_blur, served_drop_shadow, served_filter,
};
use frust_engine::gpu::pipelines::{
    EnginePipeline, EngineShaders, INTERMEDIATE_FORMAT, warm_up_descs,
};
use frust_engine::gpu::shader_src::{FILTER, FILTER_NAME};
use frust_engine::gpu::targets::{INTERMEDIATE_USAGE, IntermediateTargets};
use frust_engine::renderer::{FilterPassPlan, FilterResources};
use frust_engine::schedule::{PageConfig, PageParity, Round, RoundOp, RoundTarget, Schedule};
use frust_engine::{EngineDraw, EngineError};
use frust_gpu::{DownlevelProfile, PipelineCache, ShaderLibrary, TierCaps};
use kurbo::Affine;
use peniko::color::{AlphaColor, Srgb};
use vello_common::color::palette::css::RED;
use vello_common::filter::drop_shadow::DropShadow;
use vello_common::filter::gaussian_blur::{
    GaussianBlur, compute_gaussian_kernel, plan_decimated_blur,
};
use vello_common::filter_effects::{EdgeMode, Filter, FilterPrimitive};
use vello_common::geometry::SizeU16;
use vello_common::paint::Paint;
use vello_common::peniko::BlendMode;
use vello_common::record::{CommandRecorder, LayerProps};
use vello_common::strip::Strip;
use vello_common::tile::Tile;
use wgpu::naga;

/// Viewport every recording is built against. Deliberately not square, so an
/// axis swapped somewhere in page or pass sizing cannot pass by symmetry.
const VIEWPORT: (u16, u16) = (256, 192);

/// The three standard deviations this file pins, spanning the decimation
/// plan's whole range: none, some, and the deepest a page-sized layer reaches.
const SIGMAS: [f32; 3] = [2.0, 8.0, 32.0];

fn caps() -> TierCaps {
    TierCaps::fake(DownlevelProfile::Full)
}

fn recorder() -> CommandRecorder<EngineDraw> {
    CommandRecorder::new(VIEWPORT.0, VIEWPORT.1)
}

/// A layer composited source-over at `opacity`, with no mask and no layer clip
/// path.
fn layer(opacity: f32) -> LayerProps {
    LayerProps {
        blend_mode: BlendMode::default(),
        opacity,
        mask: None,
        clip_path: None,
    }
}

/// Strips covering `width` pixels of the tile row holding `y`, starting at `x`.
fn strips(x: u16, y: u16, width: u16) -> Vec<Strip> {
    vec![
        Strip::new(x, y, 0, false),
        Strip::sentinel(y, u32::from(width) * u32::from(Tile::HEIGHT)),
    ]
}

/// Records one draw covering `width` pixels of the tile row holding `y`.
fn draw(recorder: &mut CommandRecorder<EngineDraw>, x: u16, y: u16, width: u16) {
    let strips = strips(x, y, width);
    let depth = u32::try_from(recorder.draws.len()).expect("a test records a handful of draws");
    recorder.push_draw(
        EngineDraw::new(Paint::from(RED), depth, 0..strips.len()),
        &strips,
    );
}

/// A recording of one blurred layer under the surface, holding one draw.
fn blurred_layer(sigma: f32, opacity: f32) -> CommandRecorder<EngineDraw> {
    let mut recorder = recorder();
    push_filter_layer(
        &mut recorder,
        layer(opacity),
        LayerFilter::Blur { sigma },
        Affine::IDENTITY,
    )
    .expect("a finite σ under the ceiling records");
    draw(&mut recorder, 64, 64, 32);
    recorder.pop_layer();
    recorder
}

/// A recording of one shadowed layer under the surface, holding one draw.
fn drop_shadow_layer(
    offset: (f32, f32),
    sigma: f32,
    color: AlphaColor<Srgb>,
    opacity: f32,
) -> CommandRecorder<EngineDraw> {
    let mut recorder = recorder();
    push_filter_layer(
        &mut recorder,
        layer(opacity),
        LayerFilter::DropShadow {
            offset,
            sigma,
            color,
        },
        Affine::IDENTITY,
    )
    .expect("a finite offset and σ under the ceiling records");
    draw(&mut recorder, 64, 64, 32);
    recorder.pop_layer();
    recorder
}

/// A `vello_common` drop shadow built the way [`served_drop_shadow`] hands one
/// back: through `PreparedFilter::new`, so its decimation plan and kernel are
/// the reference's own rather than re-derived.
fn shadow(offset: (f32, f32), sigma: f32, color: AlphaColor<Srgb>) -> DropShadow {
    let filter = Filter::from_primitive(FilterPrimitive::DropShadowOnly {
        dx: offset.0,
        dy: offset.1,
        std_deviation: sigma,
        color,
        edge_mode: EdgeMode::default(),
    });
    match vello_common::filter::PreparedFilter::new(&filter, &Affine::IDENTITY) {
        vello_common::filter::PreparedFilter::DropShadow(shadow) => shadow,
        other => panic!("a `DropShadowOnly` primitive must prepare as a drop shadow: {other:?}"),
    }
}

fn schedule(recorder: &CommandRecorder<EngineDraw>) -> Vec<Round> {
    Schedule::build(recorder, &caps(), &PageConfig::default())
        .expect("a blurred layer under the surface schedules")
}

fn escalation(recorder: &CommandRecorder<EngineDraw>) -> String {
    match Schedule::build(recorder, &caps(), &PageConfig::default()) {
        Err(EngineError::SchedulerEscalation { reason }) => reason,
        other => panic!("expected an escalation, got {other:?}"),
    }
}

// -----------------------------------------------------------------------------
// The kernel, and its bilinear form
// -----------------------------------------------------------------------------

/// The decimation plan is the CPU rasterizer's, not a second one: the blur this
/// tier renders at a given σ halves the same number of times and convolves with
/// the same discrete weights, which is the whole reason the two tiers can be
/// compared pixel for pixel at all.
#[test]
fn every_sigma_plans_the_shared_kernel_rather_than_one_of_this_tiers_own() {
    for sigma in SIGMAS {
        let blur = GaussianBlur::new(sigma, EdgeMode::default());
        let (n_decimations, kernel, kernel_size) = plan_decimated_blur(sigma);

        assert_eq!(blur.n_decimations, n_decimations, "σ {sigma}");
        assert_eq!(blur.kernel_size, kernel_size, "σ {sigma}");
        assert_eq!(blur.kernel, kernel, "σ {sigma}");
        assert!(
            usize::from(kernel_size) <= MAX_KERNEL_SIZE,
            "σ {sigma} planned a kernel of {kernel_size}, past the {MAX_KERNEL_SIZE} the \
             decimation plan is supposed to bound it to"
        );
    }
}

/// Decimation is what keeps the kernel bounded, so a larger σ has to buy its
/// blur with halvings rather than with taps.
#[test]
fn a_larger_sigma_costs_decimations_rather_than_a_wider_kernel() {
    let decimations: Vec<usize> = SIGMAS
        .iter()
        .map(|sigma| plan_decimated_blur(*sigma).0)
        .collect();

    assert_eq!(decimations, vec![0, 2, 4], "σ 2 / 8 / 32");
}

/// The merged bilinear taps have to describe the same Gaussian the discrete
/// kernel does. Each merged tap stands for two adjacent discrete ones, and its
/// fractional offset is what says how its weight divides between them — so
/// splitting it back apart must reproduce the kernel it came from.
#[test]
fn the_bilinear_kernel_splits_back_into_the_discrete_one() {
    for sigma in SIGMAS {
        let (kernel, kernel_size) = compute_gaussian_kernel(plan_remaining_sigma(sigma));
        let linear = LinearKernel::new(&kernel, kernel_size);
        let radius = usize::from(kernel_size) / 2;

        assert_eq!(
            linear.center_weight, kernel[radius],
            "σ {sigma}: the centre tap is not merged with anything"
        );

        for tap in 0..usize::from(linear.n_taps) {
            let merged = linear.weights[tap];
            let offset = linear.offsets[tap];
            let low = 2 * tap + 1;

            // A tap merging two neighbours divides its weight by how far its
            // sample sits between them; a leftover single tap sits on a whole
            // texel and takes all of it.
            let high_share = merged * (offset - low as f32);
            let low_share = merged - high_share;

            assert!(
                (low_share - kernel[radius + low]).abs() < 1e-6,
                "σ {sigma}, tap {tap}: low share {low_share} != {}",
                kernel[radius + low]
            );
            let high = kernel.get(radius + low + 1).copied().unwrap_or(0.0);
            assert!(
                (high_share - high).abs() < 1e-6,
                "σ {sigma}, tap {tap}: high share {high_share} != {high}"
            );
        }
    }
}

/// A convolution that did not sum to one would darken or brighten what it
/// blurred, which is the failure the normalization exists to prevent — and the
/// merge has to preserve it, since every tap is applied on both sides.
#[test]
fn the_bilinear_kernel_still_sums_to_one() {
    for sigma in SIGMAS {
        let blur = GaussianBlur::new(sigma, EdgeMode::default());
        let linear = LinearKernel::new(&blur.kernel, blur.kernel_size);
        let sum: f32 = linear.center_weight
            + 2.0
                * linear
                    .weights
                    .iter()
                    .take(usize::from(linear.n_taps))
                    .sum::<f32>();

        assert!((sum - 1.0).abs() < 1e-5, "σ {sigma} summed to {sum}");
    }
}

/// The shader reads the tap weights and offsets as one `vec3<f32>` each, which
/// is only enough because the decimation plan bounds the kernel.
#[test]
fn no_kernel_the_plan_produces_needs_more_taps_than_the_shader_reads() {
    for sigma in [0.0, 0.1, 0.5, 1.0, 2.0, 8.0, 32.0, 1024.0, MAX_BLUR_SIGMA] {
        let blur = GaussianBlur::new(sigma, EdgeMode::default());
        let linear = LinearKernel::new(&blur.kernel, blur.kernel_size);

        assert!(
            usize::from(linear.n_taps) <= MAX_TAPS_PER_SIDE,
            "σ {sigma} merged into {} taps, past the {MAX_TAPS_PER_SIDE} the shader reads",
            linear.n_taps
        );
    }
}

/// A σ of zero is a valid identity blur rather than a refusal or a panic: the
/// plan hands back a one-tap kernel, and one tap at full weight copies.
#[test]
fn a_zero_sigma_is_an_identity_kernel_rather_than_a_refusal() {
    let blur = GaussianBlur::new(0.0, EdgeMode::default());
    let linear = LinearKernel::new(&blur.kernel, blur.kernel_size);

    assert_eq!(blur.kernel_size, 1);
    assert_eq!(linear.n_taps, 0);
    assert!((linear.center_weight - 1.0).abs() < 1e-6);
}

/// The σ that reaches the kernel after the decimations have taken their share.
fn plan_remaining_sigma(sigma: f32) -> f32 {
    let mut variance = sigma * sigma;
    while variance > 4.0 {
        variance = (variance - 1.5) * 0.25;
    }
    variance.sqrt()
}

// -----------------------------------------------------------------------------
// The layouts the shader reads
// -----------------------------------------------------------------------------

/// The law the type erasure rests on: every filter's parameter block is one
/// size, so a filter's own block is addressed by a plain texel multiple.
#[test]
fn every_filter_parameter_block_is_one_size() {
    assert_eq!(FILTER_SIZE_BYTES, 48);
    assert_eq!(size_of::<GpuFilterData>(), FILTER_SIZE_BYTES);
    assert_eq!(size_of::<GpuGaussianBlur>(), FILTER_SIZE_BYTES);
    assert_eq!(size_of::<GpuDropShadow>(), FILTER_SIZE_BYTES);
    assert_eq!(align_of::<GpuFilterData>(), 16);
    assert_eq!(align_of::<GpuGaussianBlur>(), 16);
    assert_eq!(align_of::<GpuDropShadow>(), 16);
    assert_eq!(GpuFilterData::SIZE_TEXELS, 3);
}

/// A drop shadow's parameter block survives the round trip through the
/// type-erased form, and packs its kernel at the same offsets a blur's own
/// does — the reason its blur passes read through the exact accessors a plain
/// blur's do, unmodified.
#[test]
fn a_drop_shadows_parameter_block_round_trips_through_the_erased_form() {
    for (offset, sigma) in [((0.0, 0.0), 2.0), ((3.0, -4.0), 8.0), ((-12.0, 20.0), 32.0)] {
        let shadow_value = shadow(offset, sigma, RED);
        let packed = GpuDropShadow::from(&shadow_value);
        let erased = GpuFilterData::from(packed);

        assert_eq!(
            erased.filter_type(),
            filter_type::DROP_SHADOW,
            "{offset:?} σ {sigma}"
        );
        assert_eq!(
            erased.n_decimations(),
            shadow_value.n_decimations,
            "{offset:?} σ {sigma}"
        );
        assert_eq!(
            bytemuck::cast::<GpuFilterData, GpuDropShadow>(erased),
            packed,
            "{offset:?} σ {sigma}"
        );
        assert_eq!(packed.dx, offset.0, "{offset:?} σ {sigma}");
        assert_eq!(packed.dy, offset.1, "{offset:?} σ {sigma}");
        assert_eq!(
            packed.color,
            RED.premultiply().to_rgba8().to_u32(),
            "{offset:?} σ {sigma}"
        );

        let linear = LinearKernel::new(&shadow_value.kernel, shadow_value.kernel_size);
        assert_eq!(
            packed.center_weight, linear.center_weight,
            "{offset:?} σ {sigma}"
        );
        assert_eq!(
            (packed.header >> 11) & 0x3,
            u32::from(linear.n_taps),
            "{offset:?} σ {sigma}"
        );
    }
}

/// This engine never composites a filter layer's original content back over
/// its shadow (see `frust_engine::filters::drop_shadow`'s own doc), so a
/// shadow-only block never sets the bit a future `composite_original` shape
/// would read.
#[test]
fn a_drop_shadows_header_never_sets_the_composite_bit() {
    for sigma in [0.0, 2.0, 8.0, 32.0, MAX_BLUR_SIGMA] {
        let packed = GpuDropShadow::from(&shadow((3.0, -4.0), sigma, RED));
        assert_eq!(packed.header & (1 << 13), 0, "σ {sigma}");
    }
}

/// The padding a filter layer reserves is half a kernel, because that is how
/// far a tap can reach past the region it filters — the bound that lets every
/// kernel skip its bounds checks.
#[test]
fn the_filter_padding_is_half_the_widest_kernel() {
    assert_eq!(FILTER_ATLAS_PADDING, (MAX_KERNEL_SIZE / 2) as u16);
    assert_eq!(FILTER_ATLAS_PADDING, 6);
}

/// A blur's parameter block survives the round trip through the type-erased
/// form, and the header it packs is what the fragment stage unpacks.
#[test]
fn a_blurs_parameter_block_round_trips_through_the_erased_form() {
    for sigma in SIGMAS {
        let blur = GaussianBlur::new(sigma, EdgeMode::default());
        let packed = GpuGaussianBlur::from(&blur);
        let erased = GpuFilterData::from(packed);

        assert_eq!(
            erased.filter_type(),
            filter_type::GAUSSIAN_BLUR,
            "σ {sigma}"
        );
        assert_eq!(erased.n_decimations(), blur.n_decimations, "σ {sigma}");
        assert_eq!(
            bytemuck::cast::<GpuFilterData, GpuGaussianBlur>(erased),
            packed,
            "σ {sigma}"
        );

        let linear = LinearKernel::new(&blur.kernel, blur.kernel_size);
        assert_eq!((packed.header >> 5) & 0x3, edge_mode::NONE, "σ {sigma}");
        assert_eq!(
            (packed.header >> 11) & 0x3,
            u32::from(linear.n_taps),
            "σ {sigma}"
        );
    }
}

/// Bit 13 belongs to the drop shadow that lands next; the blur's own fields
/// must not have grown into it at any σ the plan produces.
#[test]
fn a_blurs_header_leaves_the_drop_shadows_bit_alone() {
    for sigma in [0.0, 2.0, 8.0, 32.0, MAX_BLUR_SIGMA] {
        let packed = GpuGaussianBlur::from(&GaussianBlur::new(sigma, EdgeMode::default()));
        assert_eq!(packed.header & (1 << 13), 0, "σ {sigma}");
    }
}

/// The instance layout the vertex stage reads is the one the host packs.
#[test]
fn the_filter_instance_matches_its_shader_layout() {
    let module = validate(FILTER_NAME, FILTER);

    assert_eq!(
        struct_span(&module, "FilterInstanceData") as usize,
        size_of::<FilterInstanceData>(),
        "the shader's `FilterInstanceData` must stay byte-identical to the Rust one"
    );
    assert_eq!(size_of::<FilterInstanceData>(), 32);
}

/// An instance carries the step's own extents, the page it writes into, and the
/// layer's unscaled extent — which is what bounds the transparent border a
/// decimated pass overdraws.
#[test]
fn an_instance_carries_its_steps_extents_and_the_pages_it_addresses() {
    let blur = GaussianBlur::new(8.0, EdgeMode::default());
    let original = SizeU16::from_wh(96, 64);
    let steps = blur_passes(&blur, original);
    let first = steps.first().expect("a blur costs at least one pass");

    let instance = FilterInstanceData::new(first, 3, (0, 0), (0, 0), SizeU16::new(512), original);

    assert_eq!(instance.filter_data_offset, 3);
    assert_eq!(instance.filter_pass_kind, first.kind.code());
    assert_eq!(
        instance.source_size,
        pack_u16_pair(first.source.width(), first.source.height())
    );
    assert_eq!(
        instance.dest_size,
        pack_u16_pair(first.dest.width(), first.dest.height())
    );
    assert_eq!(instance.dest_texture_size, pack_u16_pair(512, 512));
    assert_eq!(instance.original_size, pack_u16_pair(96, 64));
}

/// The pass numbering is the reference renderer's, kept so the kinds this
/// engine does not serve can be added without renumbering the wire format.
#[test]
fn the_pass_kinds_keep_the_reference_numbering() {
    assert_eq!(FilterPassKind::Copy.code(), 0);
    assert_eq!(FilterPassKind::Offset.code(), 2);
    assert_eq!(FilterPassKind::Downscale.code(), 3);
    assert_eq!(FilterPassKind::BlurH.code(), 4);
    assert_eq!(FilterPassKind::BlurV.code(), 5);
    assert_eq!(FilterPassKind::Upscale.code(), 6);
    assert_eq!(FilterPassKind::Colorize.code(), 8);
}

// -----------------------------------------------------------------------------
// The shader sources
// -----------------------------------------------------------------------------

/// The filter program compiles the way a `wgpu::Device` would compile it — no
/// GPU, no adapter, and a failure surfaces here rather than as a
/// pipeline-creation error at run time.
#[test]
fn the_filter_module_parses_and_validates() {
    validate(FILTER_NAME, FILTER);
}

/// Assembled the way every engine module is: the binding-free helper prelude,
/// then the blur kernels, then the drop-shadow kernels, then the entry-point
/// module. No prelude declares a binding, so the module's derived bind-group
/// layout is its own.
#[test]
fn the_filter_module_is_its_preludes_followed_by_its_own_source() {
    let helpers = include_str!("../shaders/helpers.wgsl");
    let kernels = include_str!("../shaders/filters_blur.wgsl");
    let shadow_kernels = include_str!("../shaders/filters_drop_shadow.wgsl");
    let entry = include_str!("../shaders/filter.wgsl");

    assert_eq!(FILTER, format!("{helpers}{kernels}{shadow_kernels}{entry}"));

    for (name, source) in [
        ("helpers", helpers),
        ("filters_blur", kernels),
        ("filters_drop_shadow", shadow_kernels),
    ] {
        let declaration = source
            .lines()
            .find(|line| !line.trim_start().starts_with("//") && line.contains("@group"));
        assert!(
            declaration.is_none(),
            "{name} is prepended to every module that uses it, so a binding of its own would \
             change their derived bind-group layouts: {declaration:?}"
        );
    }
}

/// Every bilinear sample the blur kernels take goes through the one helper
/// that bounds a tap against the region it is filtering.
///
/// The origin invariant — *every tap outside the filtered region reads
/// transparent* — is a property of `sample_region_bilinear` alone, so a kernel
/// that sampled the source texture directly would escape it silently: it would
/// look right everywhere but at a region flush against its page's origin, which
/// is the one place a host test cannot reach and the one place a full-screen
/// backdrop blur puts it. Counting the call sites is what keeps the invariant
/// a property of the module rather than of the three kernels that happen to
/// hold it today.
#[test]
fn every_bilinear_sample_goes_through_the_region_bounded_helper() {
    let kernels = include_str!("../shaders/filters_blur.wgsl");

    let code: Vec<&str> = kernels
        .lines()
        .filter(|line| !line.trim_start().starts_with("//"))
        .collect();
    let samples = code
        .iter()
        .filter(|line| line.contains("textureSampleLevel("))
        .count();
    assert_eq!(
        samples, 1,
        "the blur kernels take exactly one bilinear sample, inside \
         `sample_region_bilinear`; every other kernel calls that helper"
    );

    assert!(
        kernels.contains("fn sample_region_bilinear("),
        "the helper the count above is about has to be the one this module declares"
    );

    // And no other prelude of the filter module samples at all: the drop
    // shadow's own passes read whole texels through `textureLoad`, bounds-
    // checked the same way.
    for (name, source) in [
        ("helpers", include_str!("../shaders/helpers.wgsl")),
        (
            "filters_drop_shadow",
            include_str!("../shaders/filters_drop_shadow.wgsl"),
        ),
        ("filter", include_str!("../shaders/filter.wgsl")),
    ] {
        assert!(
            !source.contains("textureSampleLevel("),
            "{name} samples bilinearly outside `sample_region_bilinear`"
        );
    }
}

/// The constants the host and the shader both spell out have to agree; a
/// comment saying "keep in sync" is not a mechanism.
#[test]
fn the_shader_constants_match_the_host_ones() {
    let entry = include_str!("../shaders/filter.wgsl");
    let kernels = include_str!("../shaders/filters_blur.wgsl");

    assert_shader_const(
        entry,
        "FILTER_ATLAS_PADDING",
        u32::from(FILTER_ATLAS_PADDING),
    );
    assert_shader_const(entry, "FILTER_SIZE_BYTES", FILTER_SIZE_BYTES as u32);
    assert_shader_const(kernels, "MAX_TAPS_PER_SIDE", MAX_TAPS_PER_SIDE as u32);

    for kind in [
        FilterPassKind::Copy,
        FilterPassKind::Offset,
        FilterPassKind::Downscale,
        FilterPassKind::BlurH,
        FilterPassKind::BlurV,
        FilterPassKind::Upscale,
        FilterPassKind::Colorize,
    ] {
        let name = match kind {
            FilterPassKind::Copy => "PASS_COPY",
            FilterPassKind::Offset => "PASS_OFFSET",
            FilterPassKind::Downscale => "PASS_DOWNSCALE",
            FilterPassKind::BlurH => "PASS_BLUR_H",
            FilterPassKind::BlurV => "PASS_BLUR_V",
            FilterPassKind::Upscale => "PASS_UPSCALE",
            FilterPassKind::Colorize => "PASS_COLORIZE",
        };
        assert_shader_const(entry, name, kind.code());
    }
}

/// The value the WGSL declares for `name`, as a `u32`.
fn assert_shader_const(source: &str, name: &str, expected: u32) {
    let needle = format!("const {name}: u32 = ");
    let line = source
        .lines()
        .find(|line| line.trim_start().starts_with(&needle))
        .unwrap_or_else(|| panic!("the shader declares no `{name}`"));
    let value = line
        .trim_start()
        .trim_start_matches(&needle)
        .trim_end()
        .trim_end_matches(';')
        .trim_end_matches('u');

    assert_eq!(
        value.parse::<u32>().ok(),
        Some(expected),
        "the shader's `{name}` is `{value}`, the host's is `{expected}`"
    );
}

/// Parses and validates `src` the way a `wgpu::Device` would.
fn validate(name: &str, src: &str) -> naga::Module {
    let module = naga::front::wgsl::parse_str(src)
        .unwrap_or_else(|err| panic!("{name} failed to parse: {err:?}"));
    naga::valid::Validator::new(
        naga::valid::ValidationFlags::all(),
        naga::valid::Capabilities::empty(),
    )
    .validate(&module)
    .unwrap_or_else(|err| panic!("{name} failed validation: {err:?}"));
    module
}

/// The byte size naga computed for the struct named `name`.
fn struct_span(module: &naga::Module, name: &str) -> u32 {
    module
        .types
        .iter()
        .find_map(|(_, ty)| match (&ty.name, &ty.inner) {
            (Some(ty_name), naga::TypeInner::Struct { span, .. }) if ty_name == name => Some(*span),
            _ => None,
        })
        .unwrap_or_else(|| panic!("the module declares no struct named {name}"))
}

// -----------------------------------------------------------------------------
// The pass sequence
// -----------------------------------------------------------------------------

/// A blur is `n` halvings, one horizontal and one vertical convolution at the
/// decimated resolution, then `n` doublings back — the reference's own
/// sequence, and the reason a large σ costs passes rather than taps.
#[test]
fn a_blur_is_its_decimations_a_convolution_and_the_way_back() {
    let expectations: [(f32, Vec<FilterPassKind>); 3] = [
        (2.0, vec![FilterPassKind::BlurH, FilterPassKind::BlurV]),
        (
            8.0,
            vec![
                FilterPassKind::Downscale,
                FilterPassKind::Downscale,
                FilterPassKind::BlurH,
                FilterPassKind::BlurV,
                FilterPassKind::Upscale,
                FilterPassKind::Upscale,
            ],
        ),
        (
            32.0,
            vec![
                FilterPassKind::Downscale,
                FilterPassKind::Downscale,
                FilterPassKind::Downscale,
                FilterPassKind::Downscale,
                FilterPassKind::BlurH,
                FilterPassKind::BlurV,
                FilterPassKind::Upscale,
                FilterPassKind::Upscale,
                FilterPassKind::Upscale,
                FilterPassKind::Upscale,
            ],
        ),
    ];

    for (sigma, expected) in expectations {
        let blur = GaussianBlur::new(sigma, EdgeMode::default());
        let kinds: Vec<FilterPassKind> = blur_passes(&blur, SizeU16::from_wh(96, 64))
            .iter()
            .map(|step| step.kind)
            .collect();

        assert_eq!(kinds, expected, "σ {sigma}");
    }
}

/// Each pass writes the page it did not read, so an odd-length sequence would
/// leave the result in the scratch page rather than the one the parent
/// composites. A blur's is always even, which is why it never needs the copy
/// the reference's `ensure_result_in_original` would append.
#[test]
fn a_blurs_pass_sequence_is_always_even_and_never_needs_a_closing_copy() {
    for sigma in [0.0, 0.5, 2.0, 8.0, 32.0, 512.0, MAX_BLUR_SIGMA] {
        let blur = GaussianBlur::new(sigma, EdgeMode::default());
        let steps = blur_passes(&blur, SizeU16::from_wh(96, 64));

        assert_eq!(steps.len(), 2 * blur.n_decimations + 2, "σ {sigma}");
        assert!(steps.len().is_multiple_of(2), "σ {sigma}");
        assert!(
            !steps.iter().any(|step| step.kind == FilterPassKind::Copy),
            "σ {sigma} planned a closing copy it should not have needed"
        );
    }
}

/// A step's destination is the next step's source, and the extents halve and
/// double back to exactly the layer's own — an off-by-one on an odd axis would
/// composite a filtered image one texel short of the page it was rendered at.
#[test]
fn the_extents_halve_and_double_back_to_the_layers_own() {
    // Odd on both axes, which is where the halving's rounding shows.
    let size = SizeU16::from_wh(97, 63);
    let blur = GaussianBlur::new(8.0, EdgeMode::default());
    let steps = blur_passes(&blur, size);

    assert_eq!(
        steps.first().map(|step| step.source),
        Some(size),
        "the first pass reads the layer at its own extent"
    );
    assert_eq!(
        steps.last().map(|step| step.dest),
        Some(size),
        "the last pass writes the layer back at its own extent"
    );

    for pair in steps.windows(2) {
        assert_eq!(
            pair[0].dest, pair[1].source,
            "a pass reads exactly what the pass before it wrote: {pair:?}"
        );
    }

    let decimated = SizeU16::from_wh(25, 16);
    for step in &steps {
        if step.kind == FilterPassKind::BlurH || step.kind == FilterPassKind::BlurV {
            assert_eq!(step.source, decimated);
            assert_eq!(step.dest, decimated);
        }
    }
}

/// A convolution neither grows nor shrinks what it reads; only the rescaling
/// passes change extent.
#[test]
fn only_the_rescaling_passes_change_extent() {
    let blur = GaussianBlur::new(32.0, EdgeMode::default());

    for step in blur_passes(&blur, SizeU16::from_wh(96, 64)) {
        match step.kind {
            FilterPassKind::Downscale => {
                assert_eq!(step.dest.width(), step.source.width().div_ceil(2));
                assert_eq!(step.dest.height(), step.source.height().div_ceil(2));
            }
            FilterPassKind::Upscale => {
                assert!(step.dest.width() > step.source.width());
                assert!(step.dest.height() > step.source.height());
            }
            FilterPassKind::BlurH | FilterPassKind::BlurV | FilterPassKind::Copy => {
                assert_eq!(step.source, step.dest);
            }
            FilterPassKind::Offset | FilterPassKind::Colorize => {
                unreachable!("a blur's own sequence never emits an offset or colourize pass")
            }
        }
    }
}

// -----------------------------------------------------------------------------
// The drop shadow's own passes
// -----------------------------------------------------------------------------

/// A shadow is the offset, exactly the blur sequence its own kernel plans, and
/// the colourize, in that order — the reference's own drop-shadow plan
/// narrowed to the shadow-only shape.
#[test]
fn a_drop_shadow_is_the_offset_the_blur_and_the_colorize() {
    for (offset, sigma) in [((0.0, 0.0), 2.0), ((3.0, -4.0), 8.0), ((12.0, 20.0), 32.0)] {
        let shadow_value = shadow(offset, sigma, RED);
        let blur = GaussianBlur::new(sigma, EdgeMode::default());
        let size = SizeU16::from_wh(96, 64);

        let steps = drop_shadow_passes(&shadow_value, size);
        let (first, rest) = steps
            .split_first()
            .expect("a shadow costs at least one pass");
        let (last, middle) = rest
            .split_last()
            .expect("a shadow costs at least two passes");

        assert_eq!(first.kind, FilterPassKind::Offset, "{offset:?} σ {sigma}");
        assert_eq!(first.source, size, "{offset:?} σ {sigma}");
        assert_eq!(first.dest, size, "{offset:?} σ {sigma}");

        assert_eq!(last.kind, FilterPassKind::Colorize, "{offset:?} σ {sigma}");
        assert_eq!(last.source, size, "{offset:?} σ {sigma}");
        assert_eq!(last.dest, size, "{offset:?} σ {sigma}");

        let blur_kinds: Vec<FilterPassKind> = middle.iter().map(|step| step.kind).collect();
        let expected_kinds: Vec<FilterPassKind> = blur_passes(&blur, size)
            .iter()
            .map(|step| step.kind)
            .collect();
        assert_eq!(blur_kinds, expected_kinds, "{offset:?} σ {sigma}");
    }
}

/// Offset and colourize add exactly two passes to the blur's own always-even
/// sequence, so a drop shadow's sequence never needs the closing copy
/// [`drop_shadow_passes`] would append if it ever went odd.
#[test]
fn a_drop_shadows_pass_sequence_is_always_even_and_never_needs_a_closing_copy() {
    for sigma in [0.0, 0.5, 2.0, 8.0, 32.0, 512.0, MAX_BLUR_SIGMA] {
        let shadow_value = shadow((3.0, -4.0), sigma, RED);
        let steps = drop_shadow_passes(&shadow_value, SizeU16::from_wh(96, 64));

        assert_eq!(steps.len(), 2 * shadow_value.n_decimations + 4, "σ {sigma}");
        assert!(steps.len().is_multiple_of(2), "σ {sigma}");
        assert!(
            !steps.iter().any(|step| step.kind == FilterPassKind::Copy),
            "σ {sigma} planned a closing copy it should not have needed"
        );
    }
}

// -----------------------------------------------------------------------------
// Recording a filter layer
// -----------------------------------------------------------------------------

/// The blur's whole point at the recording level: the layer's bounds grow by
/// the distance the blur paints past its contents, so the page it is rendered
/// into is large enough to hold the halo rather than clipping it.
#[test]
fn a_blurred_layers_bounds_grow_by_the_blurs_own_spread() {
    let plain = {
        let mut recorder = recorder();
        recorder.push_layer(layer(0.5), None);
        draw(&mut recorder, 64, 64, 32);
        recorder.pop_layer();
        recorder
    };
    let plain_bbox = plain.layers[0].bbox;

    for sigma in SIGMAS {
        let blurred = blurred_layer(sigma, 0.5);
        let bbox = blurred.layers[0].bbox;
        // 3σ each side, snapped up to the tile grid; the low edges are clamped
        // at the viewport origin rather than going negative.
        let spread = (3.0 * sigma).ceil() as u16;

        assert!(
            bbox.width() >= plain_bbox.width() + spread,
            "σ {sigma}: {bbox:?} did not grow past {plain_bbox:?} by 3σ"
        );
        assert!(
            bbox.height() >= plain_bbox.height() + spread,
            "σ {sigma}: {bbox:?} did not grow past {plain_bbox:?} by 3σ"
        );
    }
}

/// A σ that is not a standard deviation is refused where it is recorded, and
/// refused without opening a layer no `pop_layer` would balance.
#[test]
fn a_sigma_that_is_not_a_standard_deviation_is_refused_at_the_recorder() {
    for sigma in [f32::NAN, f32::INFINITY, -1.0, MAX_BLUR_SIGMA + 1.0] {
        let mut recorder = recorder();
        let refusal = push_filter_layer(
            &mut recorder,
            layer(0.5),
            LayerFilter::Blur { sigma },
            Affine::IDENTITY,
        );

        assert!(
            matches!(refusal, Err(EngineError::InvalidGeometry)),
            "σ {sigma} recorded as {refusal:?}"
        );
        assert!(
            recorder.layers.is_empty(),
            "σ {sigma} opened a layer despite being refused"
        );
    }
}

/// The transform is what scales σ into device space, so a transform that is not
/// finite is refused on the same terms the compiler already refuses one on.
#[test]
fn a_non_finite_transform_is_refused_at_the_recorder() {
    let mut recorder = recorder();
    let refusal = push_filter_layer(
        &mut recorder,
        layer(0.5),
        LayerFilter::Blur { sigma: 8.0 },
        Affine::translate((f64::NAN, 0.0)),
    );

    assert!(matches!(refusal, Err(EngineError::InvalidTransform)));
    assert!(recorder.layers.is_empty());
}

/// σ is a user-space quantity; the transform in force when the layer is opened
/// is what turns it into the device-space spread the page is sized from.
#[test]
fn the_transform_scales_the_blur_into_device_space() {
    let mut scaled = recorder();
    push_filter_layer(
        &mut scaled,
        layer(0.5),
        LayerFilter::Blur { sigma: 8.0 },
        Affine::scale(2.0),
    )
    .expect("a finite transform records");
    draw(&mut scaled, 64, 64, 32);
    scaled.pop_layer();

    let unscaled = blurred_layer(8.0, 0.5);

    assert!(
        scaled.layers[0].bbox.width() > unscaled.layers[0].bbox.width(),
        "a 2x transform must widen the blurred layer's bounds"
    );
}

/// A shadow's bounds grow by its own offset on top of the blur's 3σ spread —
/// the reference's own filter expansion for `DropShadowOnly`
/// (`vello_common::filter_effects::FilterPrimitive::filter_expansion`), which
/// this engine takes as given rather than re-deriving (see
/// [`LayerFilter::filter_data`]).
#[test]
fn a_shadowed_layers_bounds_grow_by_the_blurs_spread_and_the_shadows_own_offset() {
    let plain = {
        let mut recorder = recorder();
        recorder.push_layer(layer(0.5), None);
        draw(&mut recorder, 64, 64, 32);
        recorder.pop_layer();
        recorder
    };
    let plain_bbox = plain.layers[0].bbox;

    let unshifted = drop_shadow_layer((0.0, 0.0), 8.0, RED, 0.5);
    let shifted = drop_shadow_layer((40.0, 0.0), 8.0, RED, 0.5);

    assert!(
        unshifted.layers[0].bbox.width() >= plain_bbox.width(),
        "a shadow's blur alone must still grow the layer: {:?}",
        unshifted.layers[0].bbox
    );
    assert!(
        shifted.layers[0].bbox.width() > unshifted.layers[0].bbox.width(),
        "an offset shadow must grow its layer past an unshifted one of the same σ: {:?} vs {:?}",
        shifted.layers[0].bbox,
        unshifted.layers[0].bbox
    );
}

/// A σ or an offset that is not finite is refused where it is recorded, on the
/// same terms [`LayerFilter::Blur`] is, and refused without opening a layer no
/// `pop_layer` would balance.
#[test]
fn a_drop_shadow_with_a_non_finite_sigma_or_offset_is_refused_at_the_recorder() {
    let cases: [(f32, f32, f32); 5] = [
        (f32::NAN, 0.0, 0.0),
        (8.0, f32::NAN, 0.0),
        (8.0, 0.0, f32::NAN),
        (8.0, f32::INFINITY, 0.0),
        (MAX_BLUR_SIGMA + 1.0, 0.0, 0.0),
    ];

    for (sigma, dx, dy) in cases {
        let mut recorder = recorder();
        let refusal = push_filter_layer(
            &mut recorder,
            layer(0.5),
            LayerFilter::DropShadow {
                offset: (dx, dy),
                sigma,
                color: RED,
            },
            Affine::IDENTITY,
        );

        assert!(
            matches!(refusal, Err(EngineError::InvalidGeometry)),
            "σ {sigma}, offset ({dx}, {dy}) recorded as {refusal:?}"
        );
        assert!(
            recorder.layers.is_empty(),
            "σ {sigma}, offset ({dx}, {dy}) opened a layer despite being refused"
        );
    }
}

// -----------------------------------------------------------------------------
// The rounds a filter layer costs
// -----------------------------------------------------------------------------

/// `served_drop_shadow` is what `Schedule::build` (and the renderer's own
/// `filter_block`) reads a recorded shadow-only drop shadow back through; it
/// has to hand back the same parameters [`LayerFilter::DropShadow`] recorded.
#[test]
fn served_drop_shadow_reads_back_what_was_recorded() {
    let recording = drop_shadow_layer((3.0, -4.0), 8.0, RED, 0.5);
    let kind = &recording.layers[0].kind;

    let served = served_drop_shadow(0, kind).expect("a recorded shadow-only drop shadow serves");
    assert_eq!(served.dx, 3.0);
    assert_eq!(served.dy, -4.0);
    assert_eq!(served.color, RED);
    assert!(
        !served.composite_original,
        "this engine never serves the compositing shape"
    );
}

/// The frame path's own entry point plans a blur rather than refusing it, and
/// it is the only entry point there is.
///
/// While the renderer had no filter pipeline, `Schedule::build` refused every
/// filter and a second `build_with_filters` planned them, so the frame path
/// could not reach a round nothing could execute. The renderer runs them now,
/// and one call plans them for every caller — this is the case that would fail
/// if the refusing arm ever came back without the pipeline going with it.
#[test]
fn the_frame_paths_own_entry_point_plans_a_blur() {
    let rounds = Schedule::build(&blurred_layer(8.0, 0.5), &caps(), &PageConfig::default())
        .expect("the one entry point plans a blur");

    assert!(rounds.iter().any(|round| round.filter_pass().is_some()));
}

/// The shape the whole feature is for: the layer's contents into one page, one
/// round per filter pass alternating between the two, and the surface's own
/// round compositing whatever the last pass wrote.
#[test]
fn a_blurred_layer_costs_its_contents_its_passes_and_the_composite() {
    let blur = GaussianBlur::new(8.0, EdgeMode::default());
    let passes = blur_passes(&blur, SizeU16::from_wh(1, 1)).len();
    let rounds = schedule(&blurred_layer(8.0, 0.5));

    assert_eq!(
        rounds.len(),
        passes + 2,
        "one round for the contents, one per pass, and the surface's own: {rounds:#?}"
    );

    let contents = &rounds[0];
    assert!(contents.filter_pass().is_none());
    assert_eq!(contents.draw_count(), 1);
    let contents_page = contents.page().expect("the contents render into a page");
    assert!(!contents_page.continued, "the layer's first round clears");

    let mut source = contents_page.parity;
    for round in &rounds[1..rounds.len() - 1] {
        let pass = round.filter_pass().expect("a filter round runs a pass");
        let page = round.page().expect("a filter pass writes a page");

        assert!(round.ops.is_empty(), "a filter round draws nothing");
        assert_eq!(pass.layer, 0);
        assert_eq!(pass.source, source, "a pass reads the page before it wrote");
        assert_eq!(
            page.parity,
            source.opposite(),
            "a pass writes the group it did not read"
        );
        assert!(
            !page.continued,
            "a filter round clears, so what surrounds the region it writes is transparent"
        );
        assert_eq!(page.size, contents_page.size, "both pages are one size");
        assert_eq!(page.bounds, contents_page.bounds);

        source = page.parity;
    }

    let root = rounds.last().expect("a frame always has a root round");
    assert!(matches!(root.target, RoundTarget::Root));
    let composite = root
        .composites()
        .next()
        .expect("the surface composites the filtered layer");
    assert_eq!(
        composite.parity, contents_page.parity,
        "an even sequence leaves the result in the page the contents were rendered into"
    );
    assert_eq!(composite.opacity, 0.5);
}

/// Both groups are the filter layer's for the length of its sequence, and the
/// scratch one goes back to the pool as the last pass ends rather than being
/// held to the composite.
#[test]
fn the_scratch_page_goes_back_at_the_last_pass_and_the_result_at_the_composite() {
    let rounds = schedule(&blurred_layer(8.0, 0.5));
    let result = rounds[0]
        .page()
        .expect("the contents render into a page")
        .parity;

    let filter_rounds: Vec<&Round> = rounds
        .iter()
        .filter(|round| round.filter_pass().is_some())
        .collect();
    let (last, earlier) = filter_rounds
        .split_last()
        .expect("a blur costs at least one pass");

    for round in earlier {
        assert!(
            round.released.is_empty(),
            "both pages are live until the last pass: {round:#?}"
        );
    }
    assert_eq!(
        last.released,
        vec![result.opposite()],
        "the last pass hands the scratch group back"
    );

    let root = rounds.last().expect("a frame always has a root round");
    assert_eq!(
        root.released,
        vec![result],
        "the composite hands the result's group back"
    );
}

/// A blurred layer at full opacity still costs its passes: filtering a layer's
/// contents is not what drawing them into the parent does, so the inlining a
/// plain opaque layer gets does not apply.
#[test]
fn a_blurred_layer_at_full_opacity_is_still_isolated() {
    let rounds = schedule(&blurred_layer(8.0, 1.0));

    assert!(rounds.len() > 1, "an opaque blurred layer was inlined away");
    assert!(rounds.iter().any(|round| round.filter_pass().is_some()));
}

/// A layer at zero opacity contributes nothing whatever it filters, and a
/// filtered layer covering no pixel is not worth a page or a pass either.
#[test]
fn a_blurred_layer_that_contributes_nothing_costs_no_pass() {
    let transparent = schedule(&blurred_layer(8.0, 0.0));
    assert_eq!(transparent.len(), 1, "{transparent:#?}");
    assert!(
        transparent
            .iter()
            .all(|round| round.filter_pass().is_none())
    );

    let mut empty = recorder();
    push_filter_layer(
        &mut empty,
        layer(0.5),
        LayerFilter::Blur { sigma: 8.0 },
        Affine::IDENTITY,
    )
    .expect("a finite σ records");
    empty.pop_layer();
    let rounds = schedule(&empty);

    assert_eq!(rounds.len(), 1, "{rounds:#?}");
    assert!(rounds.iter().all(|round| round.filter_pass().is_none()));
}

/// A larger σ costs more passes and so more rounds, which is the price
/// decimation trades a bounded kernel for.
#[test]
fn a_larger_sigma_costs_more_rounds() {
    let counts: Vec<usize> = SIGMAS
        .iter()
        .map(|sigma| schedule(&blurred_layer(*sigma, 0.5)).len())
        .collect();

    assert_eq!(counts, vec![4, 8, 12], "σ 2 / 8 / 32");
}

/// A filter layer takes the group its own depth names for its contents, exactly
/// as an opacity layer does, and the other for its passes.
#[test]
fn a_filter_layer_takes_its_depths_group_for_its_contents() {
    let rounds = schedule(&blurred_layer(2.0, 0.5));
    let contents = rounds[0].page().expect("the contents render into a page");

    assert_eq!(contents.depth, 1);
    assert_eq!(contents.parity, PageParity::from_depth(1));
}

/// A blurred layer beside an opacity layer is served: the sibling's page comes
/// back when the surface's round is cut, and the filter takes both groups.
#[test]
fn a_blurred_layer_beside_an_opacity_layer_is_served_by_cutting_the_surfaces_round() {
    let mut recorder = recorder();
    recorder.push_layer(layer(0.5), None);
    draw(&mut recorder, 16, 16, 16);
    recorder.pop_layer();
    push_filter_layer(
        &mut recorder,
        layer(0.5),
        LayerFilter::Blur { sigma: 2.0 },
        Affine::IDENTITY,
    )
    .expect("a finite σ records");
    draw(&mut recorder, 96, 96, 16);
    recorder.pop_layer();

    let rounds = schedule(&recorder);
    let filter_rounds = rounds
        .iter()
        .filter(|round| round.filter_pass().is_some())
        .count();

    assert_eq!(filter_rounds, 2, "{rounds:#?}");
    // The sibling's composite was emitted early, in a cut round of the
    // surface's own, so its page was back in the pool before the filter's
    // passes needed it.
    assert!(
        rounds
            .iter()
            .filter(|round| matches!(round.target, RoundTarget::Root))
            .count()
            > 1,
        "the surface's round had to be cut to hand the second group back: {rounds:#?}"
    );
    assert_eq!(
        rounds
            .iter()
            .flat_map(|round| round.ops.iter())
            .filter(|op| matches!(op, RoundOp::Composite(_)))
            .count(),
        2
    );
}

/// The shape a shadow costs, on the same terms a blur's own does: the layer's
/// contents into one page, one round per pass of `drop_shadow_passes`
/// alternating between the two, and the surface's own round compositing
/// whatever the last pass wrote.
#[test]
fn a_shadowed_layer_costs_its_contents_its_passes_and_the_composite() {
    let shadow_value = shadow((3.0, -4.0), 8.0, RED);
    let passes = drop_shadow_passes(&shadow_value, SizeU16::from_wh(1, 1)).len();
    let rounds = schedule(&drop_shadow_layer((3.0, -4.0), 8.0, RED, 0.5));

    assert_eq!(
        rounds.len(),
        passes + 2,
        "one round for the contents, one per pass, and the surface's own: {rounds:#?}"
    );

    let contents = &rounds[0];
    assert!(contents.filter_pass().is_none());
    let contents_page = contents.page().expect("the contents render into a page");

    let mut source = contents_page.parity;
    for round in &rounds[1..rounds.len() - 1] {
        let pass = round.filter_pass().expect("a filter round runs a pass");
        let page = round.page().expect("a filter pass writes a page");
        assert_eq!(pass.source, source, "a pass reads the page before it wrote");
        assert_eq!(
            page.parity,
            source.opposite(),
            "a pass writes the group it did not read"
        );
        source = page.parity;
    }

    let root = rounds.last().expect("a frame always has a root round");
    let composite = root
        .composites()
        .next()
        .expect("the surface composites the shadowed layer");
    assert_eq!(
        composite.parity, contents_page.parity,
        "an even sequence leaves the result in the page the contents were rendered into"
    );
}

// -----------------------------------------------------------------------------
// What is refused
// -----------------------------------------------------------------------------

/// Only the blur and the shadow-only drop shadow graduate. Every other filter
/// a recording can carry is refused by name.
#[test]
fn every_filter_but_the_blur_or_drop_shadow_is_still_refused_by_name() {
    let mut recorder = recorder();
    let flood = Filter::from_primitive(FilterPrimitive::Flood { color: RED });
    recorder.push_layer(
        layer(0.5),
        Some(vello_common::filter::FilterData::new(
            flood,
            Affine::IDENTITY,
        )),
    );
    draw(&mut recorder, 64, 64, 32);
    recorder.pop_layer();

    let reason = escalation(&recorder);
    assert!(
        reason.contains("Gaussian blur"),
        "the reason has to say what the engine does serve: {reason}"
    );
}

/// The reference's other drop-shadow shape — the one that composites the
/// layer's own unfiltered content back over the shadow — is refused by name
/// too: this engine serves only `DropShadowOnly`, never `DropShadow` (see
/// `frust_engine::filters::drop_shadow`'s own doc for why).
#[test]
fn a_drop_shadow_that_composites_the_original_is_refused_by_name() {
    let mut recorder = recorder();
    let compositing = Filter::from_primitive(FilterPrimitive::DropShadow {
        dx: 3.0,
        dy: -4.0,
        std_deviation: 8.0,
        color: RED,
        edge_mode: EdgeMode::default(),
    });
    recorder.push_layer(
        layer(0.5),
        Some(vello_common::filter::FilterData::new(
            compositing,
            Affine::IDENTITY,
        )),
    );
    draw(&mut recorder, 64, 64, 32);
    recorder.pop_layer();

    let reason = escalation(&recorder);
    assert!(
        reason.contains("shadow-only"),
        "the reason has to name what this engine actually serves: {reason}"
    );
}

/// The one dispatch three sites share answers with the filter the recording
/// actually carries, rather than each site trying a blur and then a drop
/// shadow in a pair of its own.
#[test]
fn the_shared_kind_dispatch_names_the_filter_the_recording_carries() {
    let blurred = blurred_layer(8.0, 0.5);
    assert!(
        matches!(
            served_filter(0, &blurred.layers[0].kind),
            Ok(ServedFilter::Blur(_))
        ),
        "a recorded Gaussian blur is dispatched as one"
    );

    let shadowed = drop_shadow_layer((3.0, -4.0), 8.0, RED, 0.5);
    assert!(
        matches!(
            served_filter(0, &shadowed.layers[0].kind),
            Ok(ServedFilter::DropShadow(_))
        ),
        "a recorded shadow-only drop shadow is dispatched as one"
    );

    // And a layer that carries no filter at all is refused rather than
    // dispatched to either arm.
    let mut plain = recorder();
    plain.push_layer(layer(0.5), None);
    draw(&mut plain, 64, 64, 32);
    plain.pop_layer();
    assert!(served_filter(0, &plain.layers[0].kind).is_err());
}

/// A refusal names the recorded primitive's *own* fault.
///
/// The three sites used to try a blur and then a drop shadow, so a blur with a
/// σ the engine does not serve was reported as "not a shadow-only drop shadow"
/// — the second attempt's complaint about the first attempt's filter. The
/// shared dispatch keys on the primitive first, so the reason names the σ.
#[test]
fn a_served_filters_own_fault_is_what_the_refusal_names() {
    let mut recorder = recorder();
    let hostile = Filter::from_primitive(FilterPrimitive::GaussianBlur {
        std_deviation: MAX_BLUR_SIGMA * 2.0,
        edge_mode: EdgeMode::None,
    });
    recorder.push_layer(
        layer(0.5),
        Some(vello_common::filter::FilterData::new(
            hostile,
            Affine::IDENTITY,
        )),
    );
    draw(&mut recorder, 64, 64, 32);
    recorder.pop_layer();

    let reason = escalation(&recorder);
    assert!(
        reason.contains('σ') && reason.contains("Gaussian blur"),
        "the reason has to name the blur's own σ, not the drop shadow it also is not: {reason}"
    );
}

/// Every edge mode but the one the kernels implement is refused by name.
///
/// `Wrap` and `Mirror` would have to address the region's opposite or
/// reflected texels and `Duplicate` its edge ones, while every kernel here
/// reads transparent black outside the region unconditionally — which is
/// `EdgeMode::None` and nothing else. Rendering one of the other three as
/// `None` and calling it that filter is the silent-wrong-pixels answer this
/// tier does not give.
#[test]
fn an_edge_mode_the_kernels_do_not_implement_is_refused_by_name() {
    for mode in [EdgeMode::Duplicate, EdgeMode::Wrap, EdgeMode::Mirror] {
        for (what, filter) in [
            (
                "blur",
                Filter::from_primitive(FilterPrimitive::GaussianBlur {
                    std_deviation: 8.0,
                    edge_mode: mode,
                }),
            ),
            (
                "drop shadow",
                Filter::from_primitive(FilterPrimitive::DropShadowOnly {
                    dx: 3.0,
                    dy: -4.0,
                    std_deviation: 8.0,
                    color: RED,
                    edge_mode: mode,
                }),
            ),
        ] {
            let mut recorder = recorder();
            recorder.push_layer(
                layer(0.5),
                Some(vello_common::filter::FilterData::new(
                    filter,
                    Affine::IDENTITY,
                )),
            );
            draw(&mut recorder, 64, 64, 32);
            recorder.pop_layer();

            let reason = escalation(&recorder);
            assert!(
                reason.contains(&format!("{mode:?}")),
                "a {what} with edge mode {mode:?} has to be refused by that mode's own name: \
                 {reason}"
            );
        }
    }

    // And the mode the engine does serve is not caught by the same gate.
    assert_eq!(
        SERVED_EDGE_MODE,
        EdgeMode::None,
        "the kernels read transparent black outside the region, which is `EdgeMode::None`"
    );
    assert!(served_filter(0, &blurred_layer(8.0, 0.5).layers[0].kind).is_ok());
}

// -----------------------------------------------------------------------------
// The device-space σ gate
// -----------------------------------------------------------------------------

/// A hand-built recording carrying `filter` under `transform`, the shape a
/// recording the engine's own recorder never produced can still take (E17).
///
/// Two things are deliberate about how the hostile transform gets in.
///
/// It is written onto a `FilterData` built under the identity rather than
/// passed to `FilterData::new`, because that constructor snaps the filter's own
/// expansion under the transform and `debug_assert!`s that the result contains
/// the origin — a NaN coefficient trips the assertion there, upstream of any
/// gate this engine owns. And the layer is left empty, because `pop_layer`
/// expands a *non-empty* filter layer's bbox and snaps it, where
/// `vello_common`'s `RectU16::snap_to_tile_coordinates` unwraps a
/// `checked_next_multiple_of` that a saturated expansion overflows.
///
/// Neither is what this gate is about, and neither is reachable through
/// [`push_filter_layer`], which refuses both shapes before recording anything.
/// What is left is exactly the E17 case: a recorded `kind` the engine's own
/// recorder never produced, which is all [`served_filter`] reads.
fn recorded_filter(filter: Filter, transform: Affine) -> CommandRecorder<EngineDraw> {
    let mut filter_data = vello_common::filter::FilterData::new(filter, Affine::IDENTITY);
    filter_data.transform = transform;

    let mut recorder = recorder();
    recorder.push_layer(layer(0.5), Some(filter_data));
    recorder.pop_layer();
    recorder
}

/// A blur of `sigma` recorded under `transform`, with nothing else in the way.
fn recorded_blur(sigma: f32, transform: Affine) -> CommandRecorder<EngineDraw> {
    recorded_filter(
        Filter::from_primitive(FilterPrimitive::GaussianBlur {
            std_deviation: sigma,
            edge_mode: SERVED_EDGE_MODE,
        }),
        transform,
    )
}

/// The σ this engine bounds is the *device-space* one, and it is computed the
/// way `vello_common` computes it.
///
/// The gate would be worthless if the two drifted: `PreparedFilter::new` scales
/// σ by `transform_blur_params` before handing it to the planner, so a bound
/// taken over any other quantity would bound something the planner never sees.
/// That function is `pub(crate)` upstream, so this pins the recomputation
/// against the prepared blur's own `std_deviation` rather than against a
/// second copy of the formula.
#[test]
fn the_device_space_sigma_is_the_one_the_reference_prepares_with() {
    for (sigma, transform) in [
        (8.0_f32, Affine::IDENTITY),
        (8.0, Affine::scale(2.0)),
        (8.0, Affine::scale(0.25)),
        (32.0, Affine::scale_non_uniform(3.0, 1.0)),
        (2.0, Affine::rotate(0.7) * Affine::scale(5.0)),
        (8.0, Affine::translate((40.0, -12.0))),
    ] {
        let recording = recorded_blur(sigma, transform);
        let served = served_blur(0, &recording.layers[0].kind)
            .expect("a σ and a transform inside the ceiling serve");

        assert_eq!(
            served.std_deviation,
            device_blur_sigma(sigma, transform),
            "σ {sigma} under {transform:?}: the engine's own device-space σ must be the one \
             `PreparedFilter::new` prepared with"
        );
    }
}

/// A transform coefficient that is not finite is refused before the planner
/// ever sees the σ it would scale.
///
/// This is the hang, stated as a refusal: `transform_blur_params` would carry
/// an infinite coefficient into `plan_decimated_blur`, whose
/// `while remaining_variance > 4.0 { (v - 1.5) * 0.25 }` never leaves an
/// infinite variance. The case is deliberately written so the planner is never
/// invoked with the hostile value at all — a test that reproduced the hang by
/// calling it would not complete.
#[test]
fn a_non_finite_transform_coefficient_is_refused_before_the_planner_sees_it() {
    for coeffs in [
        [f64::INFINITY, 0.0, 0.0, 1.0, 0.0, 0.0],
        [1.0, f64::INFINITY, 0.0, 1.0, 0.0, 0.0],
        [1.0, 0.0, f64::NEG_INFINITY, 1.0, 0.0, 0.0],
        [1.0, 0.0, 0.0, f64::NAN, 0.0, 0.0],
    ] {
        let transform = Affine::new(coeffs);
        // A σ well inside the recorded bound, so the *transform* is the only
        // thing this case can be refused for.
        let recording = recorded_blur(8.0, transform);

        let refusal = served_filter(0, &recording.layers[0].kind)
            .expect_err("a non-finite transform coefficient is refused");
        assert!(
            refusal.contains("non-finite transform"),
            "the reason has to name the transform: {refusal}"
        );

        // And the whole frame is skipped rather than scheduled — the refusal
        // reaches the frame path, not just the gate.
        assert!(escalation(&recording).contains("non-finite transform"));
    }
}

/// A finite transform that scales a served σ past the ceiling is refused too.
///
/// The recorded σ alone is not the quantity that reaches the planner: a σ of 8
/// under a 10⁶ scale is a device-space σ of 8×10⁶, which plans tens of
/// decimations rather than the four the bound leaves room for.
#[test]
fn a_finite_transform_that_scales_sigma_past_the_ceiling_is_refused() {
    let transform = Affine::scale(1.0e6);
    let recording = recorded_blur(8.0, transform);

    let refusal = served_filter(0, &recording.layers[0].kind)
        .expect_err("a device-space σ past the ceiling is refused");
    assert!(
        refusal.contains("device-space σ"),
        "the reason has to name the scaled σ rather than the recorded one: {refusal}"
    );
    assert!(escalation(&recording).contains("device-space σ"));

    // The recorder refuses it on the same terms, so a caller going through the
    // engine's own entry point never records it in the first place.
    let mut recorder = recorder();
    assert!(matches!(
        push_filter_layer(
            &mut recorder,
            layer(0.5),
            LayerFilter::Blur { sigma: 8.0 },
            transform,
        ),
        Err(EngineError::InvalidGeometry)
    ));
    assert!(recorder.layers.is_empty());
}

/// The bound is inclusive, and it is taken at the exact boundary rather than
/// near it.
///
/// A device-space σ of exactly [`MAX_BLUR_SIGMA`] serves; the next σ the same
/// transform scales past it does not. Both halves matter: a gate that refused
/// the boundary would shrink the served set, and one that admitted anything
/// past it would leave the planner reachable.
#[test]
fn the_device_space_sigma_bound_is_inclusive_and_exact_at_its_boundary() {
    let transform = Affine::scale(2.0);
    let at_boundary = MAX_BLUR_SIGMA / 2.0;
    assert_eq!(
        device_blur_sigma(at_boundary, transform),
        MAX_BLUR_SIGMA,
        "the case has to sit on the boundary exactly, not near it"
    );

    let served = served_blur(0, &recorded_blur(at_boundary, transform).layers[0].kind)
        .expect("a device-space σ of exactly the ceiling is served");
    assert_eq!(served.std_deviation, MAX_BLUR_SIGMA);

    let past = f32::from_bits(at_boundary.to_bits() + 1);
    assert!(
        device_blur_sigma(past, transform) > MAX_BLUR_SIGMA,
        "the next representable σ has to cross the boundary"
    );
    assert!(
        served_filter(0, &recorded_blur(past, transform).layers[0].kind).is_err(),
        "one ulp past the boundary is refused"
    );

    // The recorded-σ half of the same bound, unchanged: an identity transform
    // leaves the two spaces equal, so `MAX_BLUR_SIGMA` itself still serves.
    assert!(
        served_filter(
            0,
            &recorded_blur(MAX_BLUR_SIGMA, Affine::IDENTITY).layers[0].kind
        )
        .is_ok()
    );
}

/// A drop shadow's own blur is held to the same device-space bound.
#[test]
fn a_drop_shadows_sigma_is_bounded_in_device_space_too() {
    let hostile = |transform| {
        recorded_filter(
            Filter::from_primitive(FilterPrimitive::DropShadowOnly {
                dx: 3.0,
                dy: -4.0,
                std_deviation: 8.0,
                color: RED,
                edge_mode: SERVED_EDGE_MODE,
            }),
            transform,
        )
    };

    assert!(served_filter(0, &hostile(Affine::IDENTITY).layers[0].kind).is_ok());
    assert!(served_filter(0, &hostile(Affine::scale(1.0e6)).layers[0].kind).is_err());
    assert!(
        served_filter(
            0,
            &hostile(Affine::new([f64::INFINITY, 0.0, 0.0, 1.0, 0.0, 0.0])).layers[0].kind
        )
        .is_err()
    );
}

/// A filter layer inside another layer is refused rather than rendered from
/// bounds that would clip it: `vello_common` places one in its parent by
/// undoing a source shift the reference renderer applies to a filter layer's
/// contents and this engine's compiler does not.
#[test]
fn a_filter_layer_inside_another_layer_is_refused() {
    for outer in [0.5, 1.0] {
        let mut recorder = recorder();
        recorder.push_layer(layer(outer), None);
        push_filter_layer(
            &mut recorder,
            layer(0.5),
            LayerFilter::Blur { sigma: 8.0 },
            Affine::IDENTITY,
        )
        .expect("a finite σ records");
        draw(&mut recorder, 64, 64, 32);
        recorder.pop_layer();
        recorder.pop_layer();

        let reason = escalation(&recorder);
        assert!(
            reason.contains("recorded inside another layer"),
            "outer opacity {outer}: {reason}"
        );
    }
}

/// The padding overflow the reference guards: a blur grows its layer past what
/// a page can be sized to, and the frame is refused rather than clipped to the
/// ceiling — and never panicked (E17), however far past the ceiling it lands.
///
/// A filter layer's page is sized by [`frust_engine::schedule::filter_page_size`]
/// (wired into `Schedule::build` since this test's own boundary was pinned),
/// which checks the PADDED request against two ceilings rather than one: this
/// case's bbox alone already clears the pool's configured `max_page_size`, so
/// once padded it is refused as [`EngineError::IntermediateTextureLimitReached`]
/// — the adapter could still serve it, but this pool's own budget will not —
/// rather than [`EngineError::IntermediateTextureTooLarge`], which is reserved
/// for a request past the ADAPTER's own ceiling (see the sibling test below,
/// which drives a σ large enough to cross that one too).
#[test]
fn a_blur_that_grows_its_layer_past_a_page_is_refused_rather_than_clipped() {
    let config = PageConfig {
        min_page_size: 512,
        max_page_size: 1024,
    };

    // Small enough contents that only the blur's own spread pushes the layer
    // past the ceiling.
    let mut recorder = recorder();
    push_filter_layer(
        &mut recorder,
        layer(0.5),
        LayerFilter::Blur { sigma: 400.0 },
        Affine::IDENTITY,
    )
    .expect("a finite σ under the ceiling records");
    draw(&mut recorder, 64, 64, 32);
    recorder.pop_layer();

    assert!(
        recorder.layers[0].bbox.width() > 1024,
        "the blur has to be what pushes the layer past the ceiling: {:?}",
        recorder.layers[0].bbox
    );
    assert!(matches!(
        Schedule::build(&recorder, &caps(), &config),
        Err(EngineError::IntermediateTextureLimitReached)
    ));
}

/// The refusal is a return value at every σ the recorder accepts, including the
/// largest — a blur is never a panic, whatever it is asked for.
///
/// Both refusal shapes are accepted here: `filter_page_size`'s padded request
/// can cross either ceiling depending how far the σ pushes it (see the two
/// tests above), and this sweep exists to pin "never a panic", not which of
/// the two named errors a given σ lands on.
#[test]
fn no_sigma_the_recorder_accepts_panics_the_scheduler() {
    let config = PageConfig {
        min_page_size: 512,
        max_page_size: 1024,
    };

    for sigma in [0.0, 0.5, 2.0, 8.0, 32.0, 400.0, 4000.0, MAX_BLUR_SIGMA] {
        let mut recorder = recorder();
        push_filter_layer(
            &mut recorder,
            layer(0.5),
            LayerFilter::Blur { sigma },
            Affine::IDENTITY,
        )
        .expect("every σ here is finite and inside the ceiling");
        draw(&mut recorder, 64, 64, 32);
        recorder.pop_layer();

        match Schedule::build(&recorder, &caps(), &config) {
            Ok(rounds) => assert!(!rounds.is_empty(), "σ {sigma}"),
            Err(
                EngineError::IntermediateTextureTooLarge
                | EngineError::IntermediateTextureLimitReached,
            ) => {}
            Err(other) => panic!("σ {sigma} refused unexpectedly: {other:?}"),
        }
    }
}

/// A blurred layer with a non-default blend, a mask or a layer clip path is
/// refused on the properties themselves, before the filter is ever considered —
/// the filter round changes nothing about what a layer's own properties can be.
#[test]
fn a_blurred_layer_with_a_blend_mode_is_refused_on_the_blend() {
    use vello_common::peniko::{Compose, Mix};

    let mut recorder = recorder();
    let props = LayerProps {
        blend_mode: BlendMode::new(Mix::Multiply, Compose::SrcOver),
        opacity: 0.5,
        mask: None,
        clip_path: None,
    };
    push_filter_layer(
        &mut recorder,
        props,
        LayerFilter::Blur { sigma: 8.0 },
        Affine::IDENTITY,
    )
    .expect("a finite σ records");
    draw(&mut recorder, 64, 64, 32);
    recorder.pop_layer();

    let reason = escalation(&recorder);
    assert!(reason.contains("blend mode"), "{reason}");
}

// -----------------------------------------------------------------------------
// On real hardware
// -----------------------------------------------------------------------------
//
// Everything above is a decision over plain values. Below is the other half:
// the ported WGSL, the pipeline derived from it, the filter-data texture, the
// engine's one sampler and the instance packing, all exercised on a real
// adapter — the first time any of them runs at all.
//
// The pass sequence is driven through `FilterResources`, which is exactly what
// `EngineRenderer::record_frame` drives, over two pages of this file's own
// rather than two the scheduler named. See this file's header for why that
// stops short of `EngineRenderer::encode` and what it therefore does not claim.

/// Extent of both pages every hardware case renders between.
///
/// A power of two so a page read-back's `bytes_per_row` needs no padding, and
/// larger than [`FILTER_REGION`] on both axes, exactly as a pooled page is — the
/// pool quantizes a request up to its own 256-texel keys and never sizes a page
/// to the layer. The slack is not cosmetic: it is the room a decimated pass's
/// own `FILTER_ATLAS_PADDING`-wide overdraw is written into.
const FILTER_PAGE: u32 = 512;

/// The filter layer's own extent inside those pages, at the page origin exactly
/// as the scheduler places one.
///
/// Deliberately not square, and its width is a multiple of 64 so the source
/// upload's `bytes_per_row` is already `COPY_BYTES_PER_ROW_ALIGNMENT`-aligned.
const FILTER_REGION: (u32, u32) = (448, 384);

/// The opaque rectangle the blur is measured on, inset inside
/// [`FILTER_REGION`] on every side.
///
/// The 160-texel margin is what lets the deepest plan σ 32 produces spread
/// without reaching either low edge: each halving takes it to roughly half
/// (160 → 79 → 39 → 19 → 9), the coarsest convolution's widest tap is
/// `MAX_KERNEL_SIZE / 2` = 6, and each doubling back restores it faster than
/// the reconstruction spreads ink into it. That keeps this case an
/// interior-only comparison, which is what makes the tolerances below a
/// rounding budget rather than an edge-behaviour one.
///
/// It is no longer what makes the comparison *sound*. A tap past the region's
/// low edge used to be clamped to the region's own edge texel, so the case
/// depended on that texel being transparent at every level of the pyramid; the
/// kernels now bound their taps against the region and read transparent black
/// outside it either way. [`FILTER_RECT_AT_ORIGIN`] is the case that measures
/// that directly, with no margin at all.
const FILTER_RECT: (u32, u32, u32, u32) = (160, 160, 128, 64);

/// The opaque rectangle the *origin* case is measured on: flush against the
/// region's own low edges, with no transparent margin on either.
///
/// The shape a full-screen backdrop blur takes — a filter layer whose expanded
/// bounds were cut off at device zero, so the 3σ margin the expansion would
/// have added on the near side is simply not there and the region's first row
/// and column are the layer's own opaque content.
const FILTER_RECT_AT_ORIGIN: (u32, u32, u32, u32) = (0, 0, 128, 64);

/// Bytes one page texel occupies at `INTERMEDIATE_FORMAT`.
const PAGE_TEXEL_BYTES: u32 = 4;

/// Serializes every case in this binary that creates a GPU device, for the
/// reason `atlas_render.rs` and `encode_contract.rs` both document: each builds
/// a `wgpu::Device` of its own, and a driver that serializes device teardown on
/// a process-global mutex deadlocks when two tear down at once. Poison is
/// ignored deliberately — one case's failure must not cascade into its
/// siblings.
static RENDER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

fn render_lock() -> std::sync::MutexGuard<'static, ()> {
    RENDER_LOCK
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// Blocks on `future` by polling it to completion.
///
/// wgpu's native adapter and device requests resolve without an executor
/// driving them, so a bare poll loop is enough; this crate has no async runtime
/// of its own and these cases are the only callers.
fn block_on<F: std::future::Future>(future: F) -> F::Output {
    use std::task::{Context, Poll, Waker};

    let waker = Waker::noop();
    let mut cx = Context::from_waker(waker);
    let mut future = std::pin::pin!(future);
    loop {
        match future.as_mut().poll(&mut cx) {
            Poll::Ready(value) => return value,
            Poll::Pending => std::thread::yield_now(),
        }
    }
}

/// Pops a validation error scope, pumping the device until the pop resolves.
fn drain_error_scope(device: &wgpu::Device, scope: wgpu::ErrorScopeGuard) -> Option<wgpu::Error> {
    use std::task::{Context, Poll, Waker};

    let waker = Waker::noop();
    let mut cx = Context::from_waker(waker);
    let mut future = std::pin::pin!(scope.pop());
    loop {
        match future.as_mut().poll(&mut cx) {
            Poll::Ready(error) => return error,
            Poll::Pending => {
                let _ = device.poll(wgpu::PollType::wait_indefinitely());
            }
        }
    }
}

/// A device plus the capabilities probed off the adapter it came from.
fn gpu() -> (wgpu::Device, wgpu::Queue, TierCaps) {
    block_on(async {
        let instance =
            wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
        // The environment-aware initializer, so `WGPU_ADAPTER_NAME` picks the
        // GPU on a multi-adapter host instead of the run silently landing on
        // whichever one enumerates first.
        let adapter = wgpu::util::initialize_adapter_from_env_or_default(&instance, None)
            .await
            .expect("no compatible GPU adapter");
        println!("frust-engine filter adapter: {:?}", adapter.get_info());
        let caps = TierCaps::probe(&adapter);
        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("frust-engine filter test device"),
                required_features: wgpu::Features::empty(),
                required_limits: frust_gpu::test_device_limits(&adapter, &caps),
                ..Default::default()
            })
            .await
            .expect("failed to create the device");
        (device, queue, caps)
    })
}

/// One case's device, filter pipeline, filter resources and page pair.
struct FilterHarness {
    device: wgpu::Device,
    queue: wgpu::Queue,
    caps: TierCaps,
    pipeline: wgpu::RenderPipeline,
    filters: FilterResources,
    /// The two pooled pages a filter sequence ping-pongs between, standing in
    /// for the two the scheduler's parity groups would hand out.
    pages: [Page; 2],
    /// Kept alive so the pipeline's shader module outlives the passes.
    _cache: PipelineCache,
}

/// One page: a texture with the exact usage
/// [`frust_engine::gpu::targets::INTERMEDIATE_USAGE`] gives a pooled one.
struct Page {
    texture: wgpu::Texture,
    view: wgpu::TextureView,
}

impl FilterHarness {
    fn new() -> Self {
        let (device, queue, caps) = gpu();

        let mut library = ShaderLibrary::new();
        let shaders = EngineShaders::register(&mut library, &device);
        let mut cache = PipelineCache::new(std::sync::Arc::new(library), None);
        // The very description the warm-up list carries, so this is the same
        // pipeline object a real renderer would have compiled before its first
        // frame — the format argument is ignored by the filter variant.
        let desc = EnginePipeline::Filter.desc(&shaders, wgpu::TextureFormat::Bgra8Unorm);
        assert!(
            warm_up_descs(&shaders, wgpu::TextureFormat::Bgra8Unorm).contains(&desc),
            "the filter description must be one the warm-up list already covers"
        );
        let pipeline = cache.get_or_create(&device, &desc).clone();

        let pages = [page(&device, "a"), page(&device, "b")];
        let filters = FilterResources::new(&device);

        Self {
            device,
            queue,
            caps,
            pipeline,
            filters,
            pages,
            _cache: cache,
        }
    }

    /// Uploads `image` into page 0 at its origin, where the scheduler puts a
    /// filter layer's own contents.
    fn upload_source(&self, image: &Image) {
        self.queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &self.pages[0].texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &image.to_rgba8(),
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(image.width as u32 * PAGE_TEXEL_BYTES),
                rows_per_image: Some(image.height as u32),
            },
            wgpu::Extent3d {
                width: image.width as u32,
                height: image.height as u32,
                depth_or_array_layers: 1,
            },
        );
    }

    /// Runs every pass of a blur's `steps` in one encoder, answering which page
    /// holds the result. A thin wrapper over [`Self::run_block`] for the
    /// blur-only callers this harness has always had.
    fn run(&mut self, blur: &GaussianBlur, steps: &[frust_engine::filters::FilterStep]) -> usize {
        self.run_block(GpuFilterData::from(GpuGaussianBlur::from(blur)), steps)
    }

    /// Runs every pass of `steps` against parameter block `block` in one
    /// encoder, answering which page holds the result.
    ///
    /// The ping-pong the scheduler plans, with page indices standing in for its
    /// parity groups: pass `i` reads the page pass `i - 1` wrote and writes the
    /// other, and the first reads the contents page. Generic over the block
    /// itself — a blur's and a drop shadow's alike are just erased 48-byte
    /// records by the time they reach here.
    fn run_block(
        &mut self,
        block: GpuFilterData,
        steps: &[frust_engine::filters::FilterStep],
    ) -> usize {
        let passes = u32::try_from(steps.len()).expect("a filter costs a handful of passes");
        self.filters
            .prepare(&self.device, &self.queue, &self.pipeline, &[block], passes);

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("frust-engine filter test"),
            });

        let mut source = 0_usize;
        for (index, step) in steps.iter().enumerate() {
            let dest = 1 - source;
            let instance = u32::try_from(index).expect("a blur costs a handful of passes");
            self.filters.write_instance(
                &self.queue,
                instance,
                &FilterInstanceData::new(
                    step,
                    0,
                    (0, 0),
                    (0, 0),
                    SizeU16::from_wh(FILTER_PAGE as u16, FILTER_PAGE as u16),
                    SizeU16::from_wh(FILTER_REGION.0 as u16, FILTER_REGION.1 as u16),
                ),
            );
            self.filters.record_pass(
                &self.device,
                &mut encoder,
                &FilterPassPlan {
                    label: "frust-engine filter test pass",
                    pipeline: &self.pipeline,
                    dest: &self.pages[dest].view,
                    source: &self.pages[source].view,
                    instance,
                },
            );
            source = dest;
        }

        self.queue.submit([encoder.finish()]);
        source
    }

    /// One page's texels as an [`Image`] of [`FILTER_REGION`]'s extent.
    fn read_region(&self, page: usize) -> Image {
        let bytes_per_row = (FILTER_PAGE * PAGE_TEXEL_BYTES).next_multiple_of(256);
        let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("frust-engine filter readback"),
            size: u64::from(bytes_per_row) * u64::from(FILTER_PAGE),
            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("frust-engine filter readback copy"),
            });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &self.pages[page].texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(bytes_per_row),
                    rows_per_image: Some(FILTER_PAGE),
                },
            },
            wgpu::Extent3d {
                width: FILTER_PAGE,
                height: FILTER_PAGE,
                depth_or_array_layers: 1,
            },
        );
        self.queue.submit([encoder.finish()]);

        let slice = buffer.slice(..);
        let (tx, rx) = std::sync::mpsc::channel();
        slice.map_async(wgpu::MapMode::Read, move |result| {
            let _ = tx.send(result);
        });
        self.device
            .poll(wgpu::PollType::wait_indefinitely())
            .expect("the readback poll must succeed");
        rx.recv()
            .expect("the readback channel must stay open")
            .expect("the readback buffer must map");

        let mapped = slice
            .get_mapped_range()
            .expect("the mapped readback range must be readable");
        let stride = bytes_per_row as usize;
        let mut image = Image::new(FILTER_REGION.0 as usize, FILTER_REGION.1 as usize);
        for y in 0..image.height {
            for x in 0..image.width {
                let at = y * stride + x * PAGE_TEXEL_BYTES as usize;
                image.data[y * image.width + x] = [
                    f32::from(mapped[at]),
                    f32::from(mapped[at + 1]),
                    f32::from(mapped[at + 2]),
                    f32::from(mapped[at + 3]),
                ];
            }
        }
        drop(mapped);
        buffer.unmap();
        image
    }
}

/// One page texture, with the pool's own format and usage plus `COPY_DST`.
///
/// The extra usage is the one place these pages differ from a pooled one, and
/// it is the test harness rather than the filter: a real contents page is
/// *rendered* into by a strip pass, and this file seeds it with an upload
/// instead so the source is an exact set of texels rather than a rasterization
/// the comparison would then have to model.
fn page(device: &wgpu::Device, label: &str) -> Page {
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some(label),
        size: wgpu::Extent3d {
            width: FILTER_PAGE,
            height: FILTER_PAGE,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: INTERMEDIATE_FORMAT,
        usage: INTERMEDIATE_USAGE | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    Page { texture, view }
}

/// A premultiplied RGBA image in 0..=255 floats — the space both the GPU pages
/// and the CPU reference work in, so a comparison is a subtraction.
#[derive(Clone)]
struct Image {
    width: usize,
    height: usize,
    data: Vec<[f32; 4]>,
}

impl Image {
    fn new(width: usize, height: usize) -> Self {
        Self {
            width,
            height,
            data: vec![[0.0; 4]; width * height],
        }
    }

    /// Transparent everywhere but `rect`, which is opaque `color`.
    fn with_rect(width: usize, height: usize, rect: (u32, u32, u32, u32), color: [f32; 4]) -> Self {
        let mut image = Self::new(width, height);
        for y in rect.1 as usize..(rect.1 + rect.3) as usize {
            for x in rect.0 as usize..(rect.0 + rect.2) as usize {
                image.data[y * width + x] = color;
            }
        }
        image
    }

    /// The texel at `(x, y)`, or transparent black outside — `EdgeMode::None`,
    /// which is the mode every filter this engine serves is prepared with.
    fn sample(&self, x: i64, y: i64) -> [f32; 4] {
        if x < 0 || y < 0 || x >= self.width as i64 || y >= self.height as i64 {
            return [0.0; 4];
        }
        self.data[y as usize * self.width + x as usize]
    }

    /// Tightly packed RGBA8 bytes, for a texture upload.
    fn to_rgba8(&self) -> Vec<u8> {
        self.data
            .iter()
            .flat_map(|texel| texel.map(|c| c.clamp(0.0, 255.0).round() as u8))
            .collect()
    }

    /// Rounds every channel to the byte a pass would have stored.
    ///
    /// Applied once per *pass*, which is where this reference follows the GPU
    /// rather than the CPU rasterizer. Both store their intermediates in eight
    /// bits per channel — an `Rgba8Unorm` page here, a `PremulRgba8` pixmap
    /// there — but the rasterizer runs each rescaling step as two separable
    /// passes and rounds between them, while the shader collapses the two axes
    /// into one pass and rounds once. The kernel is identical either way (four
    /// bilinear samples reproduce `[1,3,3,1]/8` on both axes exactly); only the
    /// rounding schedule differs, and the schedule modelled here is the one the
    /// texels being compared actually went through.
    fn quantize(mut self) -> Self {
        for texel in &mut self.data {
            for channel in texel {
                *channel = channel.clamp(0.0, 255.0).round();
            }
        }
        self
    }

    /// The `(x, y)` of the largest per-channel difference from `other` inside
    /// the window `margin` texels in from every edge, and its size.
    fn worst_diff(&self, other: &Self, margin: usize) -> (f32, usize, usize) {
        let mut worst = (0.0_f32, 0_usize, 0_usize);
        for y in margin..self.height.saturating_sub(margin) {
            for x in margin..self.width.saturating_sub(margin) {
                let mine = self.data[y * self.width + x];
                let theirs = other.data[y * other.width + x];
                for channel in 0..4 {
                    let diff = (mine[channel] - theirs[channel]).abs();
                    if diff > worst.0 {
                        worst = (diff, x, y);
                    }
                }
            }
        }
        worst
    }

    /// The mean per-channel difference from `other` over the same window.
    fn mean_diff(&self, other: &Self, margin: usize) -> f32 {
        let mut total = 0.0_f64;
        let mut count = 0_u64;
        for y in margin..self.height.saturating_sub(margin) {
            for x in margin..self.width.saturating_sub(margin) {
                let mine = self.data[y * self.width + x];
                let theirs = other.data[y * other.width + x];
                for channel in 0..4 {
                    total += f64::from((mine[channel] - theirs[channel]).abs());
                    count += 1;
                }
            }
        }
        if count == 0 {
            return 0.0;
        }
        (total / count as f64) as f32
    }
}

/// The reference blur: `vello_common`'s own decimation plan and discrete
/// kernel, applied exactly the way the CPU rasterizer applies them.
///
/// Not a second implementation of the *kernel* — `blur.kernel` and
/// `blur.n_decimations` come straight out of
/// `vello_common::filter::gaussian_blur`, which is the whole point of the
/// comparison. What is reproduced here is the pyramid the rasterizer walks:
/// `n` decimations by the separable `[1,3,3,1]/8` binomial filter, one
/// horizontal and one vertical convolution at the coarsest level, then `n`
/// phase-aligned doublings back, with transparent black past every edge and a
/// round to bytes after each pass.
fn cpu_blur(source: &Image, blur: &GaussianBlur) -> Image {
    let mut image = source.clone();
    let mut stack: Vec<(usize, usize)> = Vec::new();

    for _ in 0..blur.n_decimations {
        stack.push((image.width, image.height));
        image = downscale(&image);
    }

    let kernel = &blur.kernel[..usize::from(blur.kernel_size)];
    image = convolve(&image, kernel, Axis::X);
    image = convolve(&image, kernel, Axis::Y);

    while let Some(target) = stack.pop() {
        image = upscale(&image, target);
    }

    image
}

/// Which axis a separable pass runs along.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Axis {
    X,
    Y,
}

/// One separable convolution pass along `axis`.
fn convolve(source: &Image, kernel: &[f32], axis: Axis) -> Image {
    let radius = (kernel.len() / 2) as i64;
    let mut out = Image::new(source.width, source.height);

    for y in 0..source.height {
        for x in 0..source.width {
            let mut rgba = [0.0_f32; 4];
            for (j, weight) in kernel.iter().enumerate() {
                let offset = j as i64 - radius;
                let texel = match axis {
                    Axis::X => source.sample(x as i64 + offset, y as i64),
                    Axis::Y => source.sample(x as i64, y as i64 + offset),
                };
                for channel in 0..4 {
                    rgba[channel] += texel[channel] * weight;
                }
            }
            out.data[y * out.width + x] = rgba;
        }
    }

    out.quantize()
}

/// One 2x decimation: the `[1,3,3,1]/8` binomial filter along each axis, over
/// the taps `[2k - 1, 2k, 2k + 1, 2k + 2]`.
///
/// Both axes inside one [`Image::quantize`], because the shader's four bilinear
/// samples do the same — see that method for why the reference follows the
/// shader's rounding schedule rather than the rasterizer's.
fn downscale(source: &Image) -> Image {
    let dst_width = source.width.div_ceil(2);
    let dst_height = source.height.div_ceil(2);

    let mut horizontal = Image::new(dst_width, source.height);
    for y in 0..source.height {
        for x in 0..dst_width {
            let base = 2 * x as i64;
            horizontal.data[y * dst_width + x] = binomial(
                source.sample(base - 1, y as i64),
                source.sample(base, y as i64),
                source.sample(base + 1, y as i64),
                source.sample(base + 2, y as i64),
            );
        }
    }

    let mut out = Image::new(dst_width, dst_height);
    for x in 0..dst_width {
        for y in 0..dst_height {
            let base = 2 * y as i64;
            out.data[y * dst_width + x] = binomial(
                horizontal.sample(x as i64, base - 1),
                horizontal.sample(x as i64, base),
                horizontal.sample(x as i64, base + 1),
                horizontal.sample(x as i64, base + 2),
            );
        }
    }
    out.quantize()
}

/// One 2x reconstruction, cropped back to the extent the matching decimation
/// consumed: the phase-aligned `[0.75, 0.25]` interpolation the decimation's
/// half-texel offset calls for.
///
/// Both axes inside one [`Image::quantize`], for the same reason
/// [`downscale`] is: the shader reconstructs with a single bilinear sample.
fn upscale(source: &Image, target: (usize, usize)) -> Image {
    let mut horizontal = Image::new(source.width * 2, source.height);
    for y in 0..source.height {
        for x in 0..source.width {
            let centre = source.sample(x as i64, y as i64);
            let low = interpolate(source.sample(x as i64 - 1, y as i64), centre);
            let high = interpolate(source.sample(x as i64 + 1, y as i64), centre);
            horizontal.data[y * horizontal.width + 2 * x] = low;
            horizontal.data[y * horizontal.width + 2 * x + 1] = high;
        }
    }

    let mut doubled = Image::new(horizontal.width, source.height * 2);
    for x in 0..doubled.width {
        for y in 0..source.height {
            let centre = horizontal.sample(x as i64, y as i64);
            let low = interpolate(horizontal.sample(x as i64, y as i64 - 1), centre);
            let high = interpolate(horizontal.sample(x as i64, y as i64 + 1), centre);
            doubled.data[2 * y * doubled.width + x] = low;
            doubled.data[(2 * y + 1) * doubled.width + x] = high;
        }
    }
    let doubled = doubled.quantize();

    let mut out = Image::new(target.0, target.1);
    for y in 0..target.1 {
        for x in 0..target.0 {
            out.data[y * target.0 + x] = doubled.sample(x as i64, y as i64);
        }
    }
    out
}

/// `(a + 3b + 3c + d) / 8`.
fn binomial(a: [f32; 4], b: [f32; 4], c: [f32; 4], d: [f32; 4]) -> [f32; 4] {
    let mut out = [0.0_f32; 4];
    for channel in 0..4 {
        out[channel] = (a[channel] + 3.0 * b[channel] + 3.0 * c[channel] + d[channel]) / 8.0;
    }
    out
}

/// `0.25 * neighbour + 0.75 * centre`.
fn interpolate(neighbour: [f32; 4], centre: [f32; 4]) -> [f32; 4] {
    let mut out = [0.0_f32; 4];
    for channel in 0..4 {
        out[channel] = 0.25 * neighbour[channel] + 0.75 * centre[channel];
    }
    out
}

/// The reference drop shadow: [`cpu_blur`]'s own pyramid, run over a shifted
/// copy of the source, then recoloured into the shadow's own premultiplied
/// colour — the host-side mirror of the sequence
/// `drop_shadow_passes` plans (offset, the blur, colourize), built from the
/// same `vello_common::filter::drop_shadow::DropShadow` kernel and decimation
/// plan every other reference in this file uses.
fn cpu_drop_shadow(source: &Image, shadow: &DropShadow) -> Image {
    let shifted = shift_image(source, shadow.dx, shadow.dy);
    let blur = GaussianBlur {
        std_deviation: shadow.std_deviation,
        n_decimations: shadow.n_decimations,
        kernel: shadow.kernel,
        kernel_size: shadow.kernel_size,
        edge_mode: shadow.edge_mode,
    };
    let blurred = cpu_blur(&shifted, &blur);
    colorize(&blurred, shadow.color)
}

/// Shift `source` by `(dx, dy)`, rounded to the nearest whole texel the same
/// way the WGSL offset pass does (`floor(x + 0.5)`, ties away from zero,
/// rather than `round()`'s ties-to-even) — transparent black past every edge,
/// exactly [`Image::sample`]'s own `EdgeMode::None`.
fn shift_image(source: &Image, dx: f32, dy: f32) -> Image {
    let shift_x = (dx + 0.5).floor() as i64;
    let shift_y = (dy + 0.5).floor() as i64;
    let mut out = Image::new(source.width, source.height);
    for y in 0..source.height {
        for x in 0..source.width {
            out.data[y * source.width + x] = source.sample(x as i64 - shift_x, y as i64 - shift_y);
        }
    }
    out
}

/// Recolour every texel of `source` into `color`'s own premultiplied value,
/// scaled by the texel's own alpha — the mask's own colour is discarded, as
/// `colorize_drop_shadow` discards it on the GPU. Quantized once, the same
/// per-pass 8-bit rounding budget every other pass in this pyramid pays.
fn colorize(source: &Image, color: AlphaColor<Srgb>) -> Image {
    let premultiplied = color.premultiply().to_rgba8();
    let channels = [
        f32::from(premultiplied.r),
        f32::from(premultiplied.g),
        f32::from(premultiplied.b),
        f32::from(premultiplied.a),
    ];

    let mut out = Image::new(source.width, source.height);
    for (dest, texel) in out.data.iter_mut().zip(source.data.iter()) {
        let alpha = texel[3] / 255.0;
        for channel in 0..4 {
            dest[channel] = channels[channel] * alpha;
        }
    }
    out.quantize()
}

/// The claim the whole card exists for: at σ 2, 8 and 32 the ported WGSL
/// produces the same blur on a real GPU that `vello_common`'s own kernel and
/// decimation plan produce on the CPU.
///
/// Three σ so all three shapes of the plan are covered — no decimation at all,
/// two levels, and the four the plan tops out at — which is also every pass kind
/// the shader implements bar the closing copy a blur never needs.
///
/// The tolerance is a *quantization* budget, not a correctness one. Both tiers
/// round to eight bits per channel after every pass of the pyramid and a deep
/// plan is ten passes, so the two walk apart by an LSB at a time; what would
/// show up as a real disagreement — a kernel read at the wrong offset, an axis
/// swapped, a tap merged wrong, a pass reading the page it wrote — moves texels
/// by tens or empties the region entirely, and neither is inside any budget.
#[test]
#[ignore = "requires a GPU (Vulkan/Metal); run with `cargo test -p frust-engine --test filters -- --ignored`"]
fn a_blur_on_the_gpu_matches_the_shared_kernel_on_the_cpu() {
    let _guard = render_lock();
    let mut harness = FilterHarness::new();
    let scope = harness
        .device
        .push_error_scope(wgpu::ErrorFilter::Validation);

    let source = Image::with_rect(
        FILTER_REGION.0 as usize,
        FILTER_REGION.1 as usize,
        FILTER_RECT,
        // Premultiplied opaque red: every channel is exercised, and an opaque
        // source is what makes an alpha that is not blurred with the colour
        // show up as a difference rather than as a coincidence.
        [255.0, 0.0, 0.0, 255.0],
    );

    for sigma in SIGMAS {
        let blur = GaussianBlur::new(sigma, EdgeMode::default());
        let steps = blur_passes(
            &blur,
            SizeU16::from_wh(FILTER_REGION.0 as u16, FILTER_REGION.1 as u16),
        );

        harness.upload_source(&source);
        let result = harness.run(&blur, &steps);
        let gpu = harness.read_region(result);
        let cpu = cpu_blur(&source, &blur);

        // The whole region, with no border excluded — see [`FILTER_RECT`] for
        // why the inset makes that sound.
        let (worst, x, y) = gpu.worst_diff(&cpu, 0);
        let mean = gpu.mean_diff(&cpu, 0);
        println!(
            "σ {sigma}: {} passes, worst per-channel diff {worst} at ({x}, {y}), mean {mean}",
            steps.len()
        );

        assert!(
            worst <= GPU_CPU_TOLERANCE,
            "σ {sigma}: the GPU blur differs from the shared kernel's own by {worst} at ({x}, {y}), \
             past the {GPU_CPU_TOLERANCE} eight-bit-rounding budget"
        );
        assert!(
            mean <= GPU_CPU_MEAN_TOLERANCE,
            "σ {sigma}: mean per-channel difference {mean} past {GPU_CPU_MEAN_TOLERANCE}"
        );

        // A blur that produced nothing at all would satisfy any tolerance
        // against a reference that also produced nothing, so three properties
        // of the output are asserted directly, none of them derived from the
        // reference.
        //
        // It paints outside the rectangle that produced it…
        let outside = gpu.sample(
            i64::from(FILTER_RECT.0) - 2,
            i64::from(FILTER_RECT.1 + FILTER_RECT.3 / 2),
        );
        assert!(
            outside[3] > 0.0,
            "σ {sigma}: nothing was painted outside the source rectangle — the pass produced no \
             texels at all: {outside:?}"
        );

        // …its middle is still the brightest thing in the region, and still
        // substantially inked. Not "nearly opaque": at σ 32 the 3σ spread is
        // wider than the rectangle is tall, so a correct blur really does thin
        // its own middle out — which is the point of running the deepest plan.
        let centre = gpu.sample(
            i64::from(FILTER_RECT.0 + FILTER_RECT.2 / 2),
            i64::from(FILTER_RECT.1 + FILTER_RECT.3 / 2),
        );
        assert!(
            centre[3] > 64.0,
            "σ {sigma}: the rectangle's own middle should stay the region's brightest texel by a \
             wide margin: {centre:?}"
        );
        assert!(
            gpu.data.iter().all(|texel| texel[3] <= centre[3]),
            "σ {sigma}: some texel outranks the rectangle's own middle, so the blur is not \
             centred where its source was"
        );

        // …and it blurs every channel alike. The source is premultiplied opaque
        // red, so red equals alpha at every texel a correct convolution
        // produces, and green and blue stay zero — a kernel applied per channel
        // with a mismatched weight, or an alpha left unfiltered, shows up here
        // whatever the reference says.
        assert!(
            gpu.data
                .iter()
                .all(|texel| texel[0] == texel[3] && texel[1] == 0.0 && texel[2] == 0.0),
            "σ {sigma}: premultiplied opaque red must stay red-equals-alpha through every pass"
        );

        // Coverage is conserved: a normalized kernel neither creates nor
        // destroys alpha, and the region is wide enough to hold the whole 3σ
        // spread, so the blurred total must match the rectangle's own to within
        // the pyramid's eight-bit rounding.
        let painted: f64 = gpu.data.iter().map(|texel| f64::from(texel[3])).sum();
        let source_total: f64 = source.data.iter().map(|texel| f64::from(texel[3])).sum();
        let drift = (painted - source_total).abs() / source_total;
        println!("σ {sigma}: coverage drift {drift}");
        assert!(
            drift <= COVERAGE_DRIFT_TOLERANCE,
            "σ {sigma}: the blur moved {drift} of the layer's total coverage, past the \
             {COVERAGE_DRIFT_TOLERANCE} eight-bit-rounding budget — a normalized kernel conserves it"
        );
    }

    let error = drain_error_scope(&harness.device, scope);
    assert!(error.is_none(), "the filter passes raised {error:?}");
}

/// The largest per-channel difference the eight-bit rounding of a ten-pass
/// pyramid is allowed to accumulate.
///
/// Measured on the pinned T400 runner (NVIDIA 610.43.03, Vulkan), not guessed:
/// worst 1 at σ 2, 2 at σ 8 and 2 at σ 32. Two LSBs of headroom over the
/// deepest plan's measured worst, which is room for another driver's own
/// bilinear-weight precision without room for a wrong kernel.
const GPU_CPU_TOLERANCE: f32 = 4.0;

/// The mean per-channel difference over the same region.
///
/// Measured on the same runner: 0.00006 at σ 2, 0.033 at σ 8, 0.098 at σ 32 —
/// three orders of magnitude under the worst case, because a rounding
/// disagreement is a rare texel rather than a bias.
const GPU_CPU_MEAN_TOLERANCE: f32 = 0.3;

/// The fraction of the layer's total coverage a blur is allowed to gain or
/// lose.
///
/// A normalized kernel conserves it exactly; eight-bit rounding does not, and
/// each level of the pyramid rounds again. Measured on the same runner:
/// 0.00001 at σ 2, 0.0035 at σ 8, 0.0137 at σ 32 — the deepest plan loses the
/// most because it rounds ten times.
const COVERAGE_DRIFT_TOLERANCE: f64 = 0.02;

/// A σ of zero is an identity kernel, so the sequence has to hand the layer
/// back unchanged rather than blank, doubled or shifted.
///
/// The negative control for the case above: it is the one input whose expected
/// output is known without a reference implementation at all, so a shader that
/// sampled at a constant offset, or a pass that read the page it was writing,
/// fails here with nothing to hide behind.
#[test]
#[ignore = "requires a GPU (Vulkan/Metal); run with `cargo test -p frust-engine --test filters -- --ignored`"]
fn a_zero_sigma_blur_returns_the_layer_unchanged_on_the_gpu() {
    let _guard = render_lock();
    let mut harness = FilterHarness::new();
    let scope = harness
        .device
        .push_error_scope(wgpu::ErrorFilter::Validation);

    let source = Image::with_rect(
        FILTER_REGION.0 as usize,
        FILTER_REGION.1 as usize,
        FILTER_RECT,
        [255.0, 0.0, 0.0, 255.0],
    );
    let blur = GaussianBlur::new(0.0, EdgeMode::default());
    let steps = blur_passes(
        &blur,
        SizeU16::from_wh(FILTER_REGION.0 as u16, FILTER_REGION.1 as u16),
    );
    assert_eq!(steps.len(), 2, "an undecimated blur is one pass per axis");

    harness.upload_source(&source);
    let result = harness.run(&blur, &steps);
    let gpu = harness.read_region(result);

    let (worst, x, y) = gpu.worst_diff(&source, 0);
    println!("σ 0: worst per-channel diff {worst} at ({x}, {y})");
    assert!(
        worst <= 1.0,
        "an identity kernel must return the layer it was handed, but ({x}, {y}) moved by {worst}"
    );

    let error = drain_error_scope(&harness.device, scope);
    assert!(error.is_none(), "the filter passes raised {error:?}");
}

/// Every pass of the sequence writes real texels, not just the last one.
///
/// A sequence whose middle passes silently did nothing would still end with a
/// plausible image at σ 2 (two passes, both of them the ones that matter), so
/// the decimated plan is the one to check: after the two halvings of σ 8 the
/// region really is a quarter of the texels on each axis, and the padding
/// border the quad overdraws around it really is transparent.
#[test]
#[ignore = "requires a GPU (Vulkan/Metal); run with `cargo test -p frust-engine --test filters -- --ignored`"]
fn a_decimated_pass_writes_its_own_extent_and_clears_the_border_around_it() {
    let _guard = render_lock();
    let mut harness = FilterHarness::new();
    let scope = harness
        .device
        .push_error_scope(wgpu::ErrorFilter::Validation);

    let source = Image::with_rect(
        FILTER_REGION.0 as usize,
        FILTER_REGION.1 as usize,
        FILTER_RECT,
        [255.0, 0.0, 0.0, 255.0],
    );
    let blur = GaussianBlur::new(8.0, EdgeMode::default());
    let all = blur_passes(
        &blur,
        SizeU16::from_wh(FILTER_REGION.0 as u16, FILTER_REGION.1 as u16),
    );
    // Just the two decimations, so the page that is read back is the one the
    // second halving wrote rather than the one the way back up restored.
    let downscales: Vec<frust_engine::filters::FilterStep> = all
        .iter()
        .take_while(|step| step.kind == FilterPassKind::Downscale)
        .copied()
        .collect();
    assert_eq!(downscales.len(), 2, "σ 8 halves twice");

    harness.upload_source(&source);
    let result = harness.run(&blur, &downscales);
    let page = harness.read_region(result);

    let decimated = downscales[1].dest;
    assert_eq!(
        (decimated.width(), decimated.height()),
        (112, 96),
        "448 x 384 halved twice"
    );

    // Ink inside the decimated region…
    let inked = page.sample(
        i64::from(decimated.width()) / 2,
        i64::from(decimated.height()) / 2,
    );
    assert!(
        inked[3] > 200.0,
        "the decimated region's own middle should still be very nearly opaque: {inked:?}"
    );

    // …and nothing at all past the padding border the quad overdraws. A pass
    // that wrote its *source* extent instead of its destination one would leave
    // the previous level's ink out here.
    let padding = i64::from(FILTER_ATLAS_PADDING);
    for offset in 0..8 {
        let beyond = i64::from(decimated.width()) + padding + offset;
        let texel = page.sample(beyond, i64::from(decimated.height()) / 2);
        assert_eq!(
            texel, [0.0; 4],
            "texel ({beyond}, mid) is past the region and its padding, so it must be transparent"
        );
    }

    let error = drain_error_scope(&harness.device, scope);
    assert!(error.is_none(), "the filter passes raised {error:?}");
}

/// The oversized-layer case on the real device path: a blur that grows its
/// layer past what this adapter's own pool will allocate is refused as a value,
/// and nothing is allocated and no device error is raised on the way.
///
/// The host cases above make the same claim against `TierCaps::fake`; this one
/// makes it against the adapter's real `max_texture_dimension_2d` and a real
/// `wgpu::Device`, which is where "refused" and "the driver refused it for us"
/// would finally read differently.
#[test]
#[ignore = "requires a GPU (Vulkan/Metal); run with `cargo test -p frust-engine --test filters -- --ignored`"]
fn an_oversized_filter_layer_is_refused_by_the_real_pool_rather_than_the_driver() {
    let _guard = render_lock();
    let harness = FilterHarness::new();
    let scope = harness
        .device
        .push_error_scope(wgpu::ErrorFilter::Validation);

    let config = PageConfig::default();
    // The DEVICE ceiling, not the pool's own configured budget: a filter
    // layer's page is sized by `filter_page_size` since this test's own
    // boundary was pinned, which checks the padded request against both
    // ceilings separately (see that function's doc) — this test's claim is
    // specifically about the adapter's own `max_texture_dimension_2d`, so the
    // σ below has to cross THAT one, not merely the pool's configured
    // `max_page_size` (a σ that only crosses the latter is `pages.rs`'s own
    // host-level `a_filter_layer_inside_the_device_ceiling_but_past_the_pool_
    // budget_is_limit_reached`, not this device-level claim).
    let device_ceiling = frust_engine::gpu::targets::max_texture_size(&harness.caps);

    // A σ whose 3σ spread on every side is past the adapter's own device
    // ceiling, over contents small enough that only the blur can have done
    // it.
    let sigma = (device_ceiling as f32) / 2.0;
    let mut recorder = recorder();
    push_filter_layer(
        &mut recorder,
        layer(0.5),
        LayerFilter::Blur { sigma },
        Affine::IDENTITY,
    )
    .expect("a σ under the ceiling records");
    draw(&mut recorder, 64, 64, 32);
    recorder.pop_layer();

    assert!(
        u32::from(recorder.layers[0].bbox.width()) > device_ceiling,
        "the blur has to be what pushes the layer past this adapter's device ceiling: {:?}",
        recorder.layers[0].bbox
    );
    assert!(
        matches!(
            Schedule::build(&recorder, &harness.caps, &config),
            Err(EngineError::IntermediateTextureTooLarge)
        ),
        "a filter layer past the adapter's own device ceiling is refused rather than clipped \
         onto it"
    );

    // And the pool the frame path would have asked answers the same way,
    // without touching the device.
    let mut targets = IntermediateTargets::new(&harness.caps);
    let max = targets.max_texture_size();
    let before = targets.stats().created;
    let refused = targets.acquire(&harness.device, max + 1, 64, "oversized filter page");
    assert!(refused.is_too_large());
    assert_eq!(
        targets.stats().created,
        before,
        "a refused request must allocate nothing on a real device either"
    );

    let error = drain_error_scope(&harness.device, scope);
    assert!(
        error.is_none(),
        "refusing an oversized filter layer raised {error:?}"
    );
}

// -----------------------------------------------------------------------------
// On real hardware: the drop shadow
// -----------------------------------------------------------------------------
//
// The same claim the blur cases above make, run over `drop_shadow_passes`'
// sequence instead: the offset and colourize this file's own
// `filters_drop_shadow.wgsl` prelude adds, plus the blur passes a shadow reuses
// unmodified, driven through the identical `FilterHarness` and compared
// against a CPU reference built from the same `vello_common::filter::gaussian_blur`
// kernel `cpu_blur` already uses, wrapped in [`shift_image`]/[`colorize`].

/// The offset every drop-shadow GPU case shifts its shadow by.
///
/// Small enough that even σ 32's own 3σ ≈ 96px spread, plus this shift, stays
/// inside [`FILTER_RECT`]'s ~160px margin from [`FILTER_REGION`]'s edge on
/// every side (see those constants' own docs) — the same margin that keeps the
/// plain blur cases an interior-only comparison.
const DROP_SHADOW_OFFSET: (f32, f32) = (16.0, -12.0);

/// The shadow's own colour: opaque blue, deliberately not [`FILTER_RECT`]'s
/// opaque red — a colorize pass that let the source's own colour leak
/// through, or one that ran before the blur rather than after, shows up as a
/// colour disagreement rather than only a shape one.
const DROP_SHADOW_COLOR: AlphaColor<Srgb> = AlphaColor::new([0.0, 0.0, 1.0, 1.0]);

/// The claim this half of the card exists for: at σ 2, 8 and 32 the ported
/// offset and colourize passes, run around the same blur pyramid the plain
/// blur cases already proved, produce the same shadow on a real GPU that
/// `vello_common`'s own kernel, decimation plan and drop-shadow colour packing
/// produce on the CPU.
///
/// The tolerance is the blur's own quantization budget plus the one extra
/// 8-bit rounding the colourize pass pays (see [`DROP_SHADOW_GPU_CPU_TOLERANCE`]).
#[test]
#[ignore = "requires a GPU (Vulkan/Metal); run with `cargo test -p frust-engine --test filters -- --ignored`"]
fn a_drop_shadow_on_the_gpu_matches_the_shared_kernel_on_the_cpu() {
    let _guard = render_lock();
    let mut harness = FilterHarness::new();
    let scope = harness
        .device
        .push_error_scope(wgpu::ErrorFilter::Validation);

    let source = Image::with_rect(
        FILTER_REGION.0 as usize,
        FILTER_REGION.1 as usize,
        FILTER_RECT,
        [255.0, 0.0, 0.0, 255.0],
    );

    for sigma in SIGMAS {
        let shadow_value = shadow(DROP_SHADOW_OFFSET, sigma, DROP_SHADOW_COLOR);
        let steps = drop_shadow_passes(
            &shadow_value,
            SizeU16::from_wh(FILTER_REGION.0 as u16, FILTER_REGION.1 as u16),
        );

        harness.upload_source(&source);
        let block = GpuFilterData::from(GpuDropShadow::from(&shadow_value));
        let result = harness.run_block(block, &steps);
        let gpu = harness.read_region(result);
        let cpu = cpu_drop_shadow(&source, &shadow_value);

        let (worst, x, y) = gpu.worst_diff(&cpu, 0);
        let mean = gpu.mean_diff(&cpu, 0);
        println!(
            "drop shadow σ {sigma}: {} passes, worst per-channel diff {worst} at ({x}, {y}), mean {mean}",
            steps.len()
        );

        assert!(
            worst <= DROP_SHADOW_GPU_CPU_TOLERANCE,
            "σ {sigma}: the GPU drop shadow differs from the shared kernel's own by {worst} at \
             ({x}, {y}), past the {DROP_SHADOW_GPU_CPU_TOLERANCE} eight-bit-rounding budget"
        );
        assert!(
            mean <= DROP_SHADOW_GPU_CPU_MEAN_TOLERANCE,
            "σ {sigma}: mean per-channel difference {mean} past {DROP_SHADOW_GPU_CPU_MEAN_TOLERANCE}"
        );

        // The shadow is inked at its own shifted centre...
        let shifted_x = i64::from(FILTER_RECT.0 as u16 + FILTER_RECT.2 as u16 / 2)
            + DROP_SHADOW_OFFSET.0.round() as i64;
        let shifted_y = i64::from(FILTER_RECT.1 as u16 + FILTER_RECT.3 as u16 / 2)
            + DROP_SHADOW_OFFSET.1.round() as i64;
        let centre = gpu.sample(shifted_x, shifted_y);
        assert!(
            centre[3] > 64.0,
            "σ {sigma}: the shadow's own shifted middle should be substantially inked: {centre:?}"
        );

        // ...and every texel of it is blue, never red: the source's own
        // colour must never reach a colorized shadow, wherever the blur or
        // the offset placed it.
        assert!(
            gpu.data.iter().all(|texel| texel[0] <= 1.0),
            "σ {sigma}: a shadow texel carries red, so the source's own colour leaked through \
             the colourize pass"
        );
    }

    let error = drain_error_scope(&harness.device, scope);
    assert!(error.is_none(), "the drop-shadow passes raised {error:?}");
}

/// The largest per-channel difference the eight-bit rounding of a drop
/// shadow's pyramid is allowed to accumulate.
///
/// Measured on the pinned T400 runner (NVIDIA 610.43.03, Vulkan), not
/// guessed: worst 1 at σ 2, 2 at σ 8 and 2 at σ 32 — identical to
/// [`GPU_CPU_TOLERANCE`]'s own blur-only measurement, so the offset and
/// colourize passes this file adds cost the pyramid no extra rounding this
/// budget has to account for. Kept as its own named constant rather than
/// reusing [`GPU_CPU_TOLERANCE`] directly: the two are equal by measurement,
/// not by any shared reasoning that would make a future drift in one an
/// error in the other.
const DROP_SHADOW_GPU_CPU_TOLERANCE: f32 = 4.0;

/// The mean per-channel difference over the same region.
///
/// Measured on the same runner: 0.00006 at σ 2, 0.033 at σ 8, 0.082 at σ 32 —
/// on the same order as [`GPU_CPU_MEAN_TOLERANCE`]'s own blur-only
/// measurement.
const DROP_SHADOW_GPU_CPU_MEAN_TOLERANCE: f32 = 0.3;

/// σ 0 at offset 0 is an identity blur and a no-op shift, so the sequence has
/// to hand back the source's own shape, recoloured — neither blank, shifted
/// nor still the source's own colour.
///
/// The negative control for the case above, on the same terms the blur's own
/// zero-σ case is: the one input whose expected output is knowable without a
/// pyramid at all, so a shader that shifted at a constant offset regardless of
/// the parameter block, or a colourize pass that ran before the blur instead
/// of after, fails here with nothing to hide behind.
#[test]
#[ignore = "requires a GPU (Vulkan/Metal); run with `cargo test -p frust-engine --test filters -- --ignored`"]
fn a_zero_sigma_zero_offset_drop_shadow_recolors_the_sources_own_shape_on_the_gpu() {
    let _guard = render_lock();
    let mut harness = FilterHarness::new();
    let scope = harness
        .device
        .push_error_scope(wgpu::ErrorFilter::Validation);

    let source = Image::with_rect(
        FILTER_REGION.0 as usize,
        FILTER_REGION.1 as usize,
        FILTER_RECT,
        [255.0, 0.0, 0.0, 255.0],
    );
    let shadow_value = shadow((0.0, 0.0), 0.0, DROP_SHADOW_COLOR);
    let steps = drop_shadow_passes(
        &shadow_value,
        SizeU16::from_wh(FILTER_REGION.0 as u16, FILTER_REGION.1 as u16),
    );
    assert_eq!(
        steps.len(),
        4,
        "an unshifted, undecimated shadow is one offset, one pass per blur axis, and one colourize"
    );

    harness.upload_source(&source);
    let block = GpuFilterData::from(GpuDropShadow::from(&shadow_value));
    let result = harness.run_block(block, &steps);
    let gpu = harness.read_region(result);
    let expected = colorize(&source, DROP_SHADOW_COLOR);

    let (worst, x, y) = gpu.worst_diff(&expected, 0);
    println!("drop shadow σ 0, offset 0: worst per-channel diff {worst} at ({x}, {y})");
    assert!(
        worst <= 1.0,
        "an identity blur at zero offset must recolour the source's own shape unchanged, but \
         ({x}, {y}) moved by {worst}"
    );

    let error = drain_error_scope(&harness.device, scope);
    assert!(error.is_none(), "the drop-shadow passes raised {error:?}");
}

// -----------------------------------------------------------------------------
// On real hardware: the origin invariant
// -----------------------------------------------------------------------------

/// The Major this card exists for, measured at the origin: a filter layer whose
/// region is flush against its page's own low edges still reads transparent
/// past its near edge.
///
/// Every other hardware case in this file leaves [`FILTER_RECT`]'s 160-texel
/// margin between the ink and the region's low edges, so the sampler's
/// `ClampToEdge` behaviour there replicates a *transparent* texel and no
/// disagreement can show. That is not the shape a full-screen backdrop blur
/// takes: the layer's expanded bounds are cut off at device zero, the 3σ margin
/// on the near side is simply absent, and the region's first row and column are
/// the layer's own opaque content ([`FILTER_RECT_AT_ORIGIN`]). Replicating
/// those into the taps that reach past them smears the blur along both low
/// edges, brightening them towards the unblurred source instead of fading them
/// out.
///
/// Two independent claims, because the reference could in principle be wrong
/// in the same direction:
///
/// - the whole region matches [`cpu_blur`] — whose [`Image::sample`] is
///   `EdgeMode::None`, transparent past every edge — inside the same
///   eight-bit-rounding budget the inset cases are measured at; and
/// - the region's own edge column is *substantially dimmer* than its interior,
///   which is what losing half the kernel's neighbourhood means and what edge
///   replication would have hidden. No reference is consulted for that half.
///
/// Measured on the pinned T400 runner (NVIDIA 610.43.03, Vulkan): worst
/// per-channel diff 1 at σ 2, 2 at σ 8 and 3 at σ 32, means 0.00003 / 0.020 /
/// 0.046 — the same order as the inset cases' own, inside the same budget.
/// Edge-column alpha against the interior's runs 153 vs 255, 82 vs 255 and 30
/// vs 161. With the region bound removed from `sample_region_bilinear` the same
/// case fails at σ 2 by 163 at (0, 0) while every inset case above stays at its
/// recorded numbers to the digit — which is both the negative control for this
/// case and the evidence that the bound changes nothing in the interior.
#[test]
#[ignore = "requires a GPU (Vulkan/Metal); run with `cargo test -p frust-engine --test filters -- --ignored`"]
fn a_blur_at_the_regions_own_origin_still_reads_transparent_past_its_near_edge() {
    let _guard = render_lock();
    let mut harness = FilterHarness::new();
    let scope = harness
        .device
        .push_error_scope(wgpu::ErrorFilter::Validation);

    let source = Image::with_rect(
        FILTER_REGION.0 as usize,
        FILTER_REGION.1 as usize,
        FILTER_RECT_AT_ORIGIN,
        [255.0, 0.0, 0.0, 255.0],
    );

    for sigma in SIGMAS {
        let blur = GaussianBlur::new(sigma, SERVED_EDGE_MODE);
        let steps = blur_passes(
            &blur,
            SizeU16::from_wh(FILTER_REGION.0 as u16, FILTER_REGION.1 as u16),
        );

        harness.upload_source(&source);
        let result = harness.run(&blur, &steps);
        let gpu = harness.read_region(result);
        let cpu = cpu_blur(&source, &blur);

        let (worst, x, y) = gpu.worst_diff(&cpu, 0);
        let mean = gpu.mean_diff(&cpu, 0);
        println!(
            "origin σ {sigma}: {} passes, worst per-channel diff {worst} at ({x}, {y}), mean {mean}",
            steps.len()
        );
        assert!(
            worst <= GPU_CPU_TOLERANCE,
            "σ {sigma}: a blur at the region's own origin differs from `EdgeMode::None` by \
             {worst} at ({x}, {y}), past the {GPU_CPU_TOLERANCE} eight-bit-rounding budget — a \
             tap past the near edge read the region's own content instead of transparent black"
        );
        assert!(
            mean <= GPU_CPU_MEAN_TOLERANCE,
            "σ {sigma}: mean per-channel difference {mean} past {GPU_CPU_MEAN_TOLERANCE}"
        );

        // The reference-free half. The rectangle is 128 wide and 64 tall at the
        // origin, so at σ 2, 8 and 32 alike its own middle row (y = 32) is more
        // than 3σ from the far edges on the axis being measured while column 0
        // sits exactly on the near one.
        let interior_x = i64::from(FILTER_RECT_AT_ORIGIN.2) / 2;
        let middle_y = i64::from(FILTER_RECT_AT_ORIGIN.3) / 2;
        let edge = gpu.sample(0, middle_y);
        let interior = gpu.sample(interior_x, middle_y);

        println!(
            "origin σ {sigma}: edge alpha {} vs interior {}",
            edge[3], interior[3]
        );
        assert!(
            interior[3] > 32.0,
            "σ {sigma}: the interior has to be inked for the comparison below to mean anything: \
             {interior:?}"
        );
        // Half the kernel's weight falls outside the region at the edge, so the
        // edge texel is about half the interior's. Edge replication would put it
        // at essentially the whole of it; three quarters separates the two
        // without pinning a Gaussian's exact half-integral.
        assert!(
            edge[3] < 0.75 * interior[3],
            "σ {sigma}: the region's own edge column is {} against an interior of {}, which is \
             what replicating the edge texel into the taps past it looks like — the near-side \
             taps must read transparent black",
            edge[3],
            interior[3]
        );
    }

    let error = drain_error_scope(&harness.device, scope);
    assert!(error.is_none(), "the filter passes raised {error:?}");
}