cranpose-liquid 0.9.38

Glass controls, themes and motion for Cranpose apps
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
//! The Liquid Glass material: Gaussian backdrop frost followed by wcKSRD
//! refraction applied to a composable's own bounds through
//! [`LiquidModifierExt::glass_effect`] — the analogue of SwiftUI's
//! `.glassEffect(_:in:)`.

use std::{cell::RefCell, sync::OnceLock};

use cranpose_ui::{Modifier, current_density};
use cranpose_ui_graphics::{
    Color, GLASS_ACTIVITY_UNIFORM, GLASS_ADAPTIVE_FROST_UNIFORM, GLASS_ADAPTIVE_TONE_UNIFORM,
    GLASS_BLUR_RADIUS_UNIFORM, GLASS_DISPERSION_UNIFORM, GLASS_EDGE_REFRACTION_REACH_UNIFORM,
    GLASS_EDGE_RETURN_DEPTH_UNIFORM, GLASS_EDGE_SPECTRUM_UNIFORM, GLASS_EFFECT_DENSITY_UNIFORM,
    GLASS_FACE_LIGHTING_OFF_UNIFORM, GLASS_FACE_RESPONSE_UNIFORM, GLASS_FOLD_DEPTH_UNIFORM,
    GLASS_INNER_SHADOW_UNIFORM, GLASS_KEY_FILL_UNIFORM, GLASS_LAYER_CLIPPED_UNIFORM,
    GLASS_LAYERED_RETURN_UNIFORM, GLASS_LIGHT_DIRECTION_UNIFORM, GLASS_MENISCUS_ABSORPTION_UNIFORM,
    GLASS_OPTICAL_PROJECTION_UNIFORM, GLASS_OPTICAL_ZOOM_ANCHOR_UNIFORM,
    GLASS_OPTICAL_ZOOM_UNIFORM, GLASS_PHYSICAL_REFRACTION_DEPTH_ENABLED_UNIFORM,
    GLASS_PHYSICAL_REFRACTION_DEPTH_UNIFORM, GLASS_REFRACTION_CURVE_UNIFORM,
    GLASS_REFRACTION_MODE_UNIFORM, GLASS_RESTING_EDGE_SHARPNESS_UNIFORM,
    GLASS_RESTING_TINT_UNIFORM, GLASS_TOUCH_RADIUS_UNIFORM, GLASS_TRANSMISSION_REFRACTION_UNIFORM,
    GraphicsLayer, LIQUID_GLASS_WGSL, LayerShape, PlaceholderShape, Rect, RenderEffect,
    RoundedCornerShape, RuntimeShader, TileMode, liquid_glass_placeholder,
    liquid_glass_runtime_effect, specialize_liquid_glass,
};

use crate::{appearance::GlassTintAmount, theme::LiquidColors};

/// Sets the ambient glass light return direction (screen space, need not be
/// normalized — the shader normalizes). Feed device attitude here.
pub fn set_glass_light_direction(direction: (f32, f32)) {
    crate::thread_state::with(|state| state.glass_light_return.set(direction));
}

/// The current ambient glass light return direction.
pub fn glass_light_direction() -> (f32, f32) {
    crate::thread_state::with(|state| state.glass_light_return.get())
}

const CAPSULE_CLIP_RADIUS: f32 = 1.0e6;

const CAPSULE_SHADER_RADIUS: f32 = -1.0;

const WCKSRD_OPTICAL_BLUR_RADIUS_PX: f32 = 2.0;

/// The shape of a glass element (also its clip and shadow shape).
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum LiquidShape {
    /// A pill: corner radius follows the smaller half-extent.
    #[default]
    Capsule,
    /// Rounded rectangle with the radius in dp.
    RoundedRect(f32),
    /// A circle (capsule of a square node).
    Circle,
}

impl LiquidShape {
    /// The clip shape handed to the graphics layer.
    pub fn clip_shape(&self) -> RoundedCornerShape {
        match self {
            LiquidShape::Capsule | LiquidShape::Circle => {
                RoundedCornerShape::uniform(CAPSULE_CLIP_RADIUS)
            }
            LiquidShape::RoundedRect(radius) => RoundedCornerShape::uniform(*radius),
        }
    }

    /// The layer shape (clip + shadow geometry).
    pub fn layer_shape(&self) -> LayerShape {
        LayerShape::Rounded(self.clip_shape())
    }

    fn shader_radius_px(&self, density: f32) -> f32 {
        match self {
            LiquidShape::Capsule | LiquidShape::Circle => CAPSULE_SHADER_RADIUS,
            LiquidShape::RoundedRect(radius) => radius * density,
        }
    }

    /// The corner radius in dp, the largest one making a capsule.
    fn radius_dp(&self) -> f32 {
        match self {
            LiquidShape::Capsule | LiquidShape::Circle => f32::MAX,
            LiquidShape::RoundedRect(radius) => *radius,
        }
    }
}

/// Material variant, mirroring SwiftUI's `.regular` / `.clear` glass, plus
/// the interactive lens.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum GlassVariant {
    /// Frosted: strong backdrop blur, vibrancy boost, scheme-adaptive lift.
    #[default]
    Regular,
    /// Transparent: minimal blur, mild vibrancy — for media-rich backdrops.
    Clear,
    /// The interactive magnifying bubble (drag lenses, flying selection):
    /// no frost, no tone shift, a full-element dome and pronounced rainbow
    /// dispersion at the rim.
    Lens,
}

/// The projection used to transmit the captured backdrop through glass.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum GlassRefraction {
    /// A radial projection toward the optical axis.
    #[default]
    Radial,
    /// A projection perpendicular to the nearest surface edge.
    Surface {
        /// Maximum inward sample displacement in dp, independent of its falloff depth.
        reach_dp: f32,
    },
    /// Successive outward and inward sample displacements with circular falloff profiles.
    /// The return amplitude is 17.5/9 times the outward amplitude. Its default depth
    /// is 7/36 of the outer profile; [`GlassDynamics::edge_return_depth_dp`] overrides it.
    EdgeLens {
        /// Outward warp amplitude in dp; refraction depth sets its falloff height.
        reach_dp: f32,
    },
    /// An outward backdrop warp followed by the material's inward surface warp.
    /// Both coordinate maps are composed before sampling, avoiding an intermediate image.
    /// Amplitudes and depths are absolute; activity controls the resting fill separately.
    LayeredSurface {
        /// Outward backdrop amplitude in dp; refraction depth sets its falloff height.
        reach_dp: f32,
        /// Inward surface amplitude in dp.
        return_reach_dp: f32,
        /// Inward surface falloff height in dp.
        return_depth_dp: f32,
    },
}

impl GlassRefraction {
    fn shader_parameters(self) -> (f32, f32) {
        match self {
            Self::Radial => (0.0, 0.0),
            Self::Surface { reach_dp } => (1.0, finite_nonnegative(reach_dp)),
            Self::EdgeLens { reach_dp } => (2.0, finite_nonnegative(reach_dp)),
            Self::LayeredSurface { reach_dp, .. } => (3.0, finite_nonnegative(reach_dp)),
        }
    }
}

fn finite_nonnegative(reach_dp: f32) -> f32 {
    if reach_dp.is_finite() {
        reach_dp.max(0.0)
    } else {
        0.0
    }
}

/// Shadow owned by a glass surface. Morphing glass evaluates the same live
/// SDF for this shadow; clipped static glass forwards the values to the layer
/// shadow primitive.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassShadow {
    pub color: Color,
    pub radius: f32,
    pub offset_y: f32,
    pub spread: f32,
}

impl GlassShadow {
    pub fn new(color: Color, radius: f32, offset_y: f32, spread: f32) -> Self {
        Self {
            color,
            radius: radius.max(0.0),
            offset_y,
            spread,
        }
    }

    fn uniforms(self) -> Option<[f32; 8]> {
        let values = [
            self.color.r(),
            self.color.g(),
            self.color.b(),
            self.color.a(),
            self.radius,
            self.offset_y,
            self.spread,
            1.0,
        ];
        (values.iter().all(|value| value.is_finite())
            && self.radius >= 0.0
            && (0.0..=1.0).contains(&self.color.a()))
        .then_some(values)
    }
}

/// Per-frame motion inputs for an interactive glass element, read lazily at
/// scene-build time (no recomposition per frame).
#[derive(Clone, Debug, PartialEq, Default)]
pub struct GlassDynamics {
    /// Uses a global color transfer and a white blurred contact light in place of touch glow.
    pub contact_lighting: bool,
    /// Per-frame source mapping. Layered surfaces use this to animate the backdrop
    /// and material independently of the opaque resting fill.
    pub refraction: Option<GlassRefraction>,
    /// Per-frame shadow of the persistent surface, independent of optical activity.
    pub shadow: Option<GlassShadow>,
    /// A shadow cast by the surface contour instead of its filled silhouette.
    /// The second value is the contour stroke width in dp; the shadow radius
    /// is its Gaussian standard deviation. Nonfinite or nonpositive widths disable it.
    pub ring_shadow: Option<(GlassShadow, f32)>,
    /// Independent inner return depth for an edge lens, in dp. Zero removes its depth.
    /// Nonfinite or negative values preserve the material's default depth ratio.
    pub edge_return_depth_dp: Option<f32>,
    /// Horizontal and vertical projection of the complete glass field about its primary center.
    /// Refraction, lighting and all scene shapes share the projection. Missing, nonfinite or
    /// nonpositive scales resolve to identity. This does not magnify the underlying backdrop.
    pub optical_projection: Option<(f32, f32)>,
    /// Continuous optical presence. `None` preserves the resolved material;
    /// `Some(0)` is an exact backdrop identity while retaining the same node,
    /// SDF, and pointer ride path.
    pub activity: Option<f32>,
    /// Base tint of the same persistent SDF surface at zero optical activity.
    /// Its alpha cross-fades out as the refractive material rises.
    pub resting_tint: Option<Color>,
    /// Extra specular intensity (0 = spec default; e.g. press boost).
    pub highlight_boost: f32,
    /// Per-frame saturation added to the resolved material. Interactive
    /// surfaces use this to raise chroma without changing their base tint.
    pub saturation_boost: f32,
    /// Optional per-frame multiplier for the material tint alpha. Values
    /// below one clear a resting wash; values above one densify a raised tint.
    pub tint_alpha_multiplier: Option<f32>,
    /// Blends a plain translucent tint into this material's tint, including its
    /// luminance-dependent transmission. The fraction is zero at the supplied
    /// tint and one at the material tint; refraction and lighting stay active.
    pub tint_crossfade: Option<(Color, f32)>,
    /// Shape morph: when set, the glass geometry is these node-local rects
    /// instead of the node cover — the shapeshift channel.
    pub morph: Option<GlassMorph>,
    /// Touch glow: `(x_dp, y_dp, intensity)` in node-local dp. A pressed
    /// surface concentrates saturation and a soft light in a radial
    /// gradient under the finger (never a flat recolor).
    pub touch: Option<(f32, f32, f32)>,
    /// Radius of the touch glow in dp; absent, nonpositive and nonfinite values use 58 dp.
    pub touch_radius_dp: Option<f32>,
    /// Dome press depth: how squashed the interactive dome is. At 1 the
    /// pressed dome refracts deep and vivid (wide rim band, strong
    /// chromatic split — the reference toggle's gray-hold rainbow); toward
    /// 0 the released bead relaxes shallow and its split fades with it
    /// (the reference's thin settled ring). `None` = 1.
    pub press_depth: Option<f32>,
}

impl GlassDynamics {
    fn projection(&self) -> (f32, f32) {
        self.optical_projection
            .filter(|(x, y)| x.is_finite() && y.is_finite() && *x > 0.0 && *y > 0.0)
            .unwrap_or((1.0, 1.0))
    }

    /// The universal touched-up state (user-directed law): a pressed
    /// liquid surface comes closer to the user while its OWN colors go
    /// HDR-bright and saturated, with a radial glow following the finger.
    /// Never a repaint with alternate colors — the boosts amplify whatever
    /// the surface already is. `press` is 0..1; `finger` is node-local dp
    /// (falls back to `center`, the surface's own heart).
    pub fn touched_up(
        mut self,
        press: f32,
        finger: Option<(f32, f32)>,
        center: (f32, f32),
    ) -> Self {
        let press = press.clamp(0.0, 1.0);
        if press <= 0.0 {
            return self;
        }
        self.highlight_boost += 0.85 * press;
        self.saturation_boost += 0.45 * press;
        let (fx, fy) = finger.unwrap_or(center);
        let carried = self.touch.map_or(0.0, |(_, _, i)| i);
        self.touch = Some((fx, fy, (carried + press).clamp(0.0, 1.0)));
        self
    }
}

fn foreground_is_dark(foreground: Color) -> bool {
    let foreground_luma =
        0.2126 * foreground.r() + 0.7152 * foreground.g() + 0.0722 * foreground.b();
    foreground_luma < 0.5
}

/// The tint a glass shows: `tint`, or, while it crossfades from a previous
/// tint, the two mixed by the crossfade's progress.
fn shown_tint(tint: Color, crossfade: Option<(Color, f32)>) -> Color {
    let Some((previous, progress)) = crossfade.filter(|(_, progress)| progress.is_finite()) else {
        return tint;
    };
    let progress = progress.clamp(0.0, 1.0);
    let mix = |from: f32, to: f32| from + (to - from) * progress;
    Color(
        mix(previous.0, tint.0),
        mix(previous.1, tint.1),
        mix(previous.2, tint.2),
        mix(previous.3, tint.3),
    )
}

fn boost_tint_saturation(tint: Color, boost: f32) -> Color {
    if boost.abs() <= f32::EPSILON {
        return tint;
    }
    let luma = 0.2126 * tint.r() + 0.7152 * tint.g() + 0.0722 * tint.b();
    let saturation = (1.0 + boost).max(0.0);
    Color::rgba(
        (luma + (tint.r() - luma) * saturation).clamp(0.0, 1.0),
        (luma + (tint.g() - luma) * saturation).clamp(0.0, 1.0),
        (luma + (tint.b() - luma) * saturation).clamp(0.0, 1.0),
        tint.a(),
    )
}

pub(crate) fn neutral_surface_tint(foreground: Color, light_alpha: f32, dark_alpha: f32) -> Color {
    if foreground_is_dark(foreground) {
        Color::BLACK.with_alpha(light_alpha.clamp(0.0, 1.0))
    } else {
        Color::WHITE.with_alpha(dark_alpha.clamp(0.0, 1.0))
    }
}

/// A liquid shapeshift frame: the primary shape plus any number of nearby
/// glass shapes, ALL smooth-unioned into one field — liquid glass glues to
/// whatever glass it passes near (a growing menu necks with a neighboring
/// button, the drag lens merges with the search circle). Up to
/// [`GlassMorph::MAX_SHAPES`] extra shapes; an angular wobble makes the
/// mid-flight field bubble like a droplet. All geometry is node-local dp:
/// `(center_x, center_y, width, height, corner_radius)`; radius sentinel
/// `-1` means capsule; `-2` means SUBTRACT capsule — the shape carves a
/// smooth hole in the field (the growing menu leaves its anchor button
/// crisp on top until it swallows it).
#[derive(Clone, Debug, PartialEq, Default)]
pub struct GlassMorph {
    /// The glass node's own size in dp. The shader receives all morph
    /// geometry in dp and derives px-per-dp from the renderer-injected node
    /// pixel rect divided by this — geometry then lands correctly at ANY
    /// render scale (live window density, robot captures at 1.0, fractional
    /// desktop scales). The authoring widget always knows its node size.
    pub node_size: (f32, f32),
    pub primary: (f32, f32, f32, f32, f32),
    /// Nearby glass shapes participating in the field.
    pub shapes: Vec<(f32, f32, f32, f32, f32)>,
    /// Smooth-union glue radius (dp): shapes within it neck together.
    pub glue: f32,
    /// Wobble amplitude (dp) and phase (radians).
    pub wobble_amplitude: f32,
    pub wobble_phase: f32,
    /// Viscous leading-edge bulge: while the shape travels or inflates, its
    /// side facing `bulge_direction` (radians, math convention) swells like a
    /// pulled droplet. Amplitude in dp, usually driven by morph velocity.
    pub bulge_amplitude: f32,
    pub bulge_direction: f32,
    /// Blends the primary rounded-rectangle field toward an ellipse. This is
    /// used by expanding droplets whose broad phase has continuous curvature
    /// rather than the straight sides of a capsule.
    pub ellipse_blend: f32,
    /// Smooths the primary capsule's straight-to-arc joins over this distance in dp.
    /// A positive value replaces its corner radius with the maximum capsule radius.
    /// The span is capped by half the difference between the primary side lengths.
    /// Zero or a nonfinite value preserves the primary outline.
    pub capsule_smoothing_dp: f32,
    /// Area-preserving affine strain applied to the primary shape. Extra
    /// scene shapes remain fixed so nearby glass can join the travelling
    /// droplet without being dragged through its local deformation.
    pub deformation: Option<GlassDeformation>,
    /// Offset (dp) of the optical-zoom axis from the primary SDF center. A
    /// leaning droplet's silhouette shifts toward its travel side while its
    /// curvature apex stays over the content it rides; anchoring the
    /// magnification there keeps the face filled by that content instead of
    /// pulling in whatever lies beyond it.
    pub zoom_anchor: (f32, f32),
}

/// A normalized motion axis and reciprocal scales for incompressible glass.
/// Construction derives the cross-axis scale, so callers cannot describe a
/// deformation that changes the bubble's area.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassDeformation {
    axis: (f32, f32),
    along: f32,
}

impl GlassDeformation {
    pub fn incompressible(axis: (f32, f32), along: f32) -> Self {
        let length = (axis.0 * axis.0 + axis.1 * axis.1).sqrt();
        let axis = if length > f32::EPSILON {
            (axis.0 / length, axis.1 / length)
        } else {
            (1.0, 0.0)
        };
        Self {
            axis,
            along: along.max(f32::EPSILON),
        }
    }

    pub fn axis(self) -> (f32, f32) {
        self.axis
    }

    pub fn along(self) -> f32 {
        self.along
    }

    pub fn across(self) -> f32 {
        1.0 / self.along
    }
}

impl GlassMorph {
    /// Shader budget for extra scene shapes.
    pub const MAX_SHAPES: usize = 8;
}

/// Reflection of opposing lights across a narrow band around the surface contour.
/// The reflected environment is brightest along the light axis and darkest between the lights.
/// Nonfinite fields or nonpositive height or spread disable this treatment.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassContourHighlight {
    /// Width of the reflecting band in dp.
    pub height_dp: f32,
    /// Signed distance of the band's outer edge; negative values extend outside the surface.
    pub offset_dp: f32,
    /// Reflected-light opacity, clamped to zero through one.
    pub amount: f32,
    /// Additive brightness of the reflected environment.
    pub color_bias: f32,
    /// Direction of the first light in screen-space radians; the second is opposite.
    pub angle_radians: f32,
    /// Angular extent of each light in radians.
    pub spread_radians: f32,
}

impl GlassContourHighlight {
    fn uniforms(self) -> Option<[f32; 6]> {
        let values = [
            self.height_dp,
            self.offset_dp,
            self.amount,
            self.color_bias,
            self.angle_radians,
            self.spread_radians,
        ];
        (values.iter().all(|value| value.is_finite())
            && self.height_dp > 0.0
            && self.spread_radians > 0.0)
            .then_some(values)
    }
}

/// Backdrop-dependent reflections from opposing lights, with a sharp rim and a softer inward lobe.
/// Invalid dimensions or nonfinite fields disable the reflection.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassSpecularHighlight {
    /// Width of the sharp reflection in dp.
    pub height_dp: f32,
    /// Direction of the first light in screen-space radians; the second is opposite.
    pub angle_radians: f32,
    /// Angular extent of each sharp reflection, in radians.
    pub spread_radians: f32,
    /// Exponent of the angular response; must be positive.
    pub curvature: f32,
    /// Opacity of the diffuse reflection, clamped to zero through one.
    pub diffuse_amount: f32,
    /// Inward extent of the diffuse reflection, in dp.
    pub diffuse_height_dp: f32,
    /// Angular extent of each diffuse reflection, in radians.
    pub diffuse_spread_radians: f32,
    /// Gain applied to the transmitted surface's chroma in the reflected color.
    pub saturation: f32,
    /// Gain applied to the transmitted surface's luminance in the reflected color.
    pub luma_gain: f32,
    /// Additive brightness of the reflected color.
    pub color_bias: f32,
}

impl GlassSpecularHighlight {
    fn uniforms(self) -> Option<[f32; 10]> {
        let values = [
            self.height_dp,
            self.angle_radians,
            self.spread_radians,
            self.curvature,
            self.diffuse_amount,
            self.diffuse_height_dp,
            self.diffuse_spread_radians,
            self.saturation,
            self.luma_gain,
            self.color_bias,
        ];
        (values.iter().all(|value| value.is_finite())
            && self.height_dp > 0.0
            && self.spread_radians > 0.0
            && self.curvature > 0.0
            && self.diffuse_height_dp > 0.0
            && self.diffuse_spread_radians > 0.0)
            .then_some(values)
    }
}

/// Opposing edge lights whose color responds to the backdrop.
/// Nonfinite fields or nonpositive height or curvature disable this treatment.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassKeyFill {
    /// Inward extent of the highlight, in dp.
    pub height_dp: f32,
    /// Linear reduction in brightness across the highlight's inward extent.
    pub curvature: f32,
    /// Direction of the first light in screen-space radians; the second is opposite.
    pub angle_radians: f32,
    /// Gain applied to the backdrop's chroma in the reflected color.
    pub saturation: f32,
    /// Gain applied to the backdrop's luminance in the reflected color.
    pub luma_gain: f32,
    /// Additive contribution to each reflected color channel.
    pub offset: f32,
    /// Whether the highlight width follows the surface transform or stays fixed on screen.
    pub scale_with_surface: bool,
}

impl GlassKeyFill {
    fn uniforms(self) -> Option<[f32; 7]> {
        let values = [
            self.height_dp,
            self.curvature,
            self.angle_radians,
            self.saturation,
            self.luma_gain,
            self.offset,
            f32::from(self.scale_with_surface),
        ];
        (values.iter().all(|value| value.is_finite())
            && self.height_dp > 0.0
            && self.curvature > 0.0)
            .then_some(values)
    }
}

/// Seven-tap RGB spectrum for an edge lens. Distances follow the surface transform.
/// Nonfinite values, negative extents, or opacities outside zero to one are ignored.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassSpectrum {
    /// Angle θ in radians. For outward normal (x, y), the sampling direction is
    /// (y cosθ + x sinθ, (x cosθ − y sinθ) × vertical_scale).
    pub angle_radians: f32,
    /// Signed spacing between adjacent taps, in dp; negative values reverse the colors.
    pub step_dp: f32,
    /// Scale of the vertical component of the sampling direction.
    pub vertical_scale: f32,
    /// Spectral opacity at the silhouette edge.
    pub opacity_near: f32,
    /// Spectral opacity at and beyond the fade depth.
    pub opacity_far: f32,
    /// Inward distance in dp over which opacity interpolates linearly.
    pub fade_depth_dp: f32,
    /// Inward distance in dp beyond which the spectrum disappears.
    pub extent_dp: f32,
}

impl GlassSpectrum {
    fn uniforms(self) -> Option<[f32; 8]> {
        let values = [
            self.angle_radians,
            self.step_dp,
            self.vertical_scale,
            self.opacity_near,
            self.opacity_far,
            self.fade_depth_dp,
            self.extent_dp,
            1.0,
        ];
        (values.iter().all(|value| value.is_finite())
            && self.vertical_scale >= 0.0
            && (0.0..=1.0).contains(&self.opacity_near)
            && (0.0..=1.0).contains(&self.opacity_far)
            && self.fade_depth_dp >= 0.0
            && self.extent_dp >= 0.0)
            .then_some(values)
    }

    fn capture_reach(self) -> f32 {
        self.step_dp.abs() * 3.0 * self.vertical_scale.max(1.0)
    }
}

/// Face attenuation before edge lighting, followed by additive illumination.
/// Edge lenses attenuate the inner refraction image before chromatic sampling.
/// Invalid or nonfinite parameters disable the response.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassFaceResponse {
    /// Interior color gain, from zero to one.
    pub gain: f32,
    /// Screen-space depth in dp where attenuation starts.
    pub start_dp: f32,
    /// Screen-space depth in dp where attenuation reaches its interior gain.
    /// Equal start and end apply the gain uniformly.
    pub end_dp: f32,
    /// Light added to each color channel inside the silhouette after edge lighting.
    pub illumination: f32,
}

impl GlassFaceResponse {
    fn uniforms(self) -> Option<[f32; 4]> {
        let values = [
            1.0 - self.gain,
            self.start_dp,
            self.end_dp,
            self.illumination,
        ];
        (values.iter().all(|value| value.is_finite())
            && (0.0..=1.0).contains(&self.gain)
            && self.start_dp >= 0.0
            && self.end_dp >= self.start_dp)
            .then_some(values)
    }
}

/// A fixed luminance transfer with an independent chroma gain.
/// Luminance `y` becomes `black + (white - black) * y - (1 - max_luminance) * y²`;
/// chroma is scaled by `saturation` and the combined RGB is clamped to zero–one.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassFaceTone {
    /// Black input's output, from zero to one.
    pub black: f32,
    /// White endpoint before quadratic highlight compression; greater than black.
    pub white: f32,
    /// Chroma gain independent of the luminance transfer; finite and nonnegative.
    pub saturation: f32,
    /// Highlight compression endpoint, from zero to one. One disables compression.
    pub max_luminance: f32,
}

impl GlassFaceTone {
    fn uniforms(self) -> Option<[f32; 5]> {
        let values = [
            self.black,
            self.white,
            self.saturation,
            self.max_luminance,
            1.0,
        ];
        (values.iter().all(|value| value.is_finite())
            && (0.0..=1.0).contains(&self.black)
            && self.white > self.black
            && self.saturation >= 0.0
            && (0.0..=1.0).contains(&self.max_luminance))
        .then_some(values)
    }
}

/// Builder describing a glass material. Resolved against the theme at the
/// composition site, then evaluated per frame for density and dynamics.
#[derive(Clone, Debug, PartialEq)]
pub struct Glass {
    /// Optional fixed face transfer, replacing adaptive tone, saturation, contrast and lift.
    pub face_tone: Option<GlassFaceTone>,
    pub variant: GlassVariant,
    pub shape: LiquidShape,
    /// Tint over the refracted backdrop; defaults to the theme's glass tint.
    pub tint: Option<Color>,
    /// Minimum transmitted luminance for a colored tint. `None` uses alpha tinting.
    pub tint_transmission: Option<f32>,
    /// Optional sharp/blurred pane blend, separate from the color tint.
    pub tint_amount: Option<GlassTintAmount>,
    /// Diffuse pane kernel reach in dp; its Gaussian standard deviation is half this value.
    pub pane_blur_radius: f32,
    /// Backdrop blur radius in dp (defaults per variant).
    pub blur_radius: Option<f32>,
    /// Radius in dp and opacity of the blurred backdrop mixed with an edge lens’s outer warp.
    pub backdrop_blur: Option<(f32, f32)>,
    /// Saturation boost (defaults per variant).
    pub saturation: Option<f32>,
    /// wcKSRD refraction depth as a fraction of the shape inradius. Regular
    /// frosted surfaces default to zero so their backdrop stays motion-stable;
    /// interactive lenses opt into optical displacement explicitly.
    pub refraction_depth: f32,
    /// Optional physical wcKSRD refraction depth in dp. When present, this
    /// keeps the optical band equally deep across surfaces with different
    /// inradii instead of scaling it from each surface's height.
    pub refraction_depth_dp: Option<f32>,
    /// Backdrop projection model.
    pub refraction: GlassRefraction,
    /// Normalized wcKSRD ray-return exponent.
    pub refraction_curve: f32,
    /// Normalized wcKSRD spectral ray separation.
    pub dispersion: f32,
    /// Optional directional spectrum for the edge-lens projection.
    pub edge_spectrum: Option<GlassSpectrum>,
    /// Fraction of the wcKSRD displacement applied to the transmitted
    /// backdrop. Regular frosted surfaces default to zero. The mirrored
    /// meniscus follows its own optical path.
    pub transmission_refraction: f32,
    /// Energy removed from the transmitted ray at the meniscus. Reflection
    /// and spectral return follow independent paths.
    pub meniscus_absorption: f32,
    /// Depth of the rim fold band in dp: the raised lens rim replays its
    /// interior mirrored toward the edge (a pure displacement). Zero
    /// disables the fold.
    pub fold_depth: f32,
    /// Uniform face magnification of a riding lens (1.0 = no zoom).
    /// The selected refraction model controls the surrounding rim band.
    pub optical_zoom: f32,
    /// Meniscus rim reflectivity multiplier (1.0 = the reference toggle's
    /// visible rim line; near 0 = the segmented lens's invisible body).
    pub rim_reflection: f32,
    /// Optical ink recolor: the lens recolors dark transmitted ink toward
    /// this color at the given strength (the reference tab bubble's
    /// color-mask act). None = off.
    pub ink_recolor: Option<(Color, f32)>,
    /// Specular rim intensity.
    pub highlight: f32,
    /// Whether the face receives the material's diffuse directional illumination.
    pub face_lighting: bool,
    /// Replaces dome lighting with a pair of opposing edge lights.
    pub key_fill: Option<GlassKeyFill>,
    /// Contour reflection applied before the foreground's spectral dispersion.
    pub contour_highlight: Option<GlassContourHighlight>,
    /// Directional rim reflection applied above the transmitted and tinted surface.
    pub specular_highlight: Option<GlassSpecularHighlight>,
    /// Attenuation and illumination applied around the edge-light pass.
    pub face_response: Option<GlassFaceResponse>,
    /// Inset shadow on the transmitted face, covered by the chromatic foreground.
    pub inner_shadow: Option<GlassShadow>,
    /// Screen-lift override (brightening toward white; negative darkens).
    /// Defaults per variant.
    pub lift: Option<f32>,
    /// Tone-compression override around the shader's mid pivot (<1 pulls
    /// every backdrop toward mid-luminance — the reference dark menu reads
    /// bright magenta over deep purple AND dim gray over white through one
    /// law). Defaults per variant.
    pub contrast: Option<f32>,
    /// Drop shadow below the glass.
    pub shadow: bool,
    /// Per-surface shadow override.
    pub shadow_style: Option<GlassShadow>,
    /// Clip the layer to `shape`. Morphing glass disables this — coverage
    /// comes entirely from the shader's SDF.
    pub clip: bool,
    /// Foreground color whose contrast the frost must protect. `None` uses
    /// the theme label color.
    pub foreground: Option<Color>,
    /// Strength of backdrop+foreground frost adaptation.
    pub adaptive_frost: f32,
    /// Adapts the face transfer curve to the mean captured backdrop brightness.
    /// Foreground polarity selects the preferred light or dark treatment.
    pub adaptive_tone: bool,
    /// Resting edge sharpness, from a soft eight-dp fade at zero to pixel antialiasing at one.
    pub resting_edge_sharpness: f32,
}

impl Glass {
    /// A motion-stable frosted surface without optical displacement.
    pub fn regular() -> Self {
        Self {
            variant: GlassVariant::Regular,
            face_tone: None,
            shape: LiquidShape::Capsule,
            tint: None,
            tint_transmission: None,
            tint_amount: None,
            pane_blur_radius: 8.0,
            blur_radius: None,
            backdrop_blur: None,
            saturation: None,
            refraction_depth: 0.0,
            refraction_depth_dp: None,
            refraction: GlassRefraction::Radial,
            refraction_curve: 0.25,
            dispersion: 0.0,
            edge_spectrum: None,
            transmission_refraction: 0.0,
            meniscus_absorption: 1.0,
            fold_depth: 0.0,
            optical_zoom: 1.0,
            rim_reflection: 1.0,
            ink_recolor: None,
            highlight: 0.9,
            face_lighting: true,
            key_fill: None,
            contour_highlight: None,
            specular_highlight: None,
            face_response: None,
            inner_shadow: None,
            lift: None,
            contrast: None,
            shadow: true,
            shadow_style: None,
            clip: true,
            foreground: None,
            adaptive_frost: 0.65,
            adaptive_tone: false,
            resting_edge_sharpness: 0.0,
        }
    }

    pub fn clear() -> Self {
        Self {
            variant: GlassVariant::Clear,
            ..Self::regular()
        }
    }

    /// An interactive glass lens with a radial projection and spectral rim.
    /// [`Self::edge_refraction`] selects an outward rim around a uniformly magnified face.
    pub fn lens() -> Self {
        Self {
            variant: GlassVariant::Lens,
            tint: Some(Color::rgba(1.0, 1.0, 1.0, 0.07)),
            refraction_depth: 0.34,
            refraction_curve: 1.0,
            dispersion: 0.30,
            transmission_refraction: 1.0,
            highlight: 1.15,
            adaptive_frost: 0.0,
            ..Self::regular()
        }
    }

    /// Enables or disables diffuse face illumination without changing the specular rim.
    pub fn face_lighting(mut self, enabled: bool) -> Self {
        self.face_lighting = enabled;
        self
    }

    /// Sets the resting edge sharpness from zero (eight-dp fade) to one (pixel antialiasing).
    /// Out-of-range values are clamped; nonfinite values preserve the soft default.
    pub fn resting_edge_sharpness(mut self, sharpness: f32) -> Self {
        self.resting_edge_sharpness = sharpness;
        self
    }

    /// Uses opposing edge lights with a backdrop-dependent reflected color.
    /// [`Self::highlight`] controls their opacity.
    pub fn key_fill(mut self, lighting: GlassKeyFill) -> Self {
        self.key_fill = Some(lighting);
        self
    }

    /// Sets the face attenuation and illumination around the edge-light pass.
    pub fn face_response(mut self, response: GlassFaceResponse) -> Self {
        self.face_response = Some(response);
        self
    }

    /// Adds an inset shadow with a Gaussian falloff from the live surface outline.
    /// The chromatic foreground covers this shadow without refracting it.
    /// Nonfinite values, negative radii, and opacity outside zero to one disable it.
    pub fn inner_shadow(mut self, shadow: GlassShadow) -> Self {
        self.inner_shadow = shadow.uniforms().map(|_| shadow);
        self
    }

    pub fn shape(mut self, shape: LiquidShape) -> Self {
        self.shape = shape;
        self
    }

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

    /// Colors transmitted light while retaining the backdrop's luminance structure.
    pub fn transmission_tint(mut self, tint: Color, black: f32) -> Self {
        if black.is_finite() {
            self.tint = Some(tint);
            self.tint_transmission = Some(black.clamp(0.0, 1.0));
        }
        self
    }

    pub fn blur_radius(mut self, radius_dp: f32) -> Self {
        self.blur_radius = Some(radius_dp);
        self
    }

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

    pub fn refraction_depth(mut self, fraction: f32) -> Self {
        self.refraction_depth = fraction.clamp(0.0, 2.0);
        self.refraction_depth_dp = None;
        self
    }

    /// Uses a density-stable physical refraction depth instead of a fraction
    /// of the live shape inradius.
    pub fn refraction_depth_dp(mut self, depth_dp: f32) -> Self {
        self.refraction_depth_dp = Some(depth_dp.max(0.0));
        self
    }

    /// Selects a circular depth profile along the surface normal, preserving
    /// tangential background coordinates along straight edges. `reach_dp` sets the inward
    /// displacement independently of depth; both remain fixed under surface scaling.
    /// Negative and nonfinite reach values become zero.
    pub fn surface_refraction(mut self, reach_dp: f32) -> Self {
        self.refraction = GlassRefraction::Surface {
            reach_dp: finite_nonnegative(reach_dp),
        };
        self
    }

    /// Overrides the edge lens's spectrum; radial and surface projections use `dispersion`.
    /// Invalid profiles are ignored. The signed spacing supports continuous color reversal.
    pub fn edge_spectrum(mut self, spectrum: GlassSpectrum) -> Self {
        self.edge_spectrum = spectrum.uniforms().map(|_| spectrum);
        self
    }

    /// Selects a rim that enters inward, crests outward and returns smoothly to the face.
    /// `reach_dp` controls its maximum outward displacement; negative and nonfinite values become zero.
    /// Its inward return uses the amplitude and depth ratios in [`GlassRefraction::EdgeLens`].
    pub fn edge_refraction(mut self, reach_dp: f32) -> Self {
        self.refraction = GlassRefraction::EdgeLens {
            reach_dp: finite_nonnegative(reach_dp),
        };
        self
    }

    pub fn refraction_curve(mut self, curve: f32) -> Self {
        self.refraction_curve = curve.clamp(0.05, 1.0);
        self
    }

    pub fn dispersion(mut self, strength: f32) -> Self {
        self.dispersion = strength.clamp(0.0, 1.0);
        self
    }

    pub fn transmission_refraction(mut self, strength: f32) -> Self {
        self.transmission_refraction = strength.clamp(0.0, 1.0);
        self
    }

    pub fn meniscus_absorption(mut self, strength: f32) -> Self {
        self.meniscus_absorption = strength.clamp(0.0, 1.0);
        self
    }

    /// Sets the rim fold band depth in dp (zero disables the fold).
    pub fn fold_depth(mut self, depth_dp: f32) -> Self {
        self.fold_depth = depth_dp.max(0.0);
        self
    }

    /// Sets the uniform face magnification of a riding lens (1.0 = none).
    pub fn optical_zoom(mut self, zoom: f32) -> Self {
        self.optical_zoom = zoom.max(1.0);
        self
    }

    /// Sets the meniscus rim reflectivity (1.0 = full reference line).
    pub fn rim_reflection(mut self, reflectivity: f32) -> Self {
        self.rim_reflection = reflectivity.clamp(0.0, 2.0);
        self
    }

    /// The lens recolors dark transmitted ink toward `color` at `strength`
    /// (0..1) — the reference bubble's color-mask act as a material optic.
    pub fn ink_recolor(mut self, color: Color, strength: f32) -> Self {
        self.ink_recolor = Some((color, strength.clamp(0.0, 1.0)));
        self
    }

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

    /// Overrides the screen-lift (how hard the glass brightens what it
    /// shows; the bar lens uses a near-zero lift to stay transmissive).
    pub fn lift(mut self, lift: f32) -> Self {
        self.lift = Some(lift);
        self
    }

    /// Overrides the tone compression around the shader's mid pivot
    /// (values below one pull every backdrop toward mid-luminance).
    pub fn contrast(mut self, contrast: f32) -> Self {
        self.contrast = Some(contrast.max(0.05));
        self
    }

    pub fn adaptive_frost(mut self, foreground: Color, strength: f32) -> Self {
        self.foreground = Some(foreground);
        self.adaptive_frost = strength.clamp(0.0, 1.0);
        self
    }

    /// Uses the captured backdrop's mean brightness to adapt the face transfer curve.
    /// This replaces local frost adaptation, saturation, contrast, lift and
    /// the key/fill color response. Tint and edge-light geometry still apply.
    /// The foreground chooses the preferred polarity, with dark treatment over black
    /// backgrounds and light treatment over white backgrounds.
    pub fn adaptive_tone(mut self, foreground: Color) -> Self {
        self.face_tone = None;
        self.foreground = Some(foreground);
        self.adaptive_tone = true;
        self.adaptive_frost = 0.0;
        self
    }

    /// Uses a fixed face transfer without reading a mean-backdrop texture.
    /// Invalid parameters disable the fixed transfer.
    pub fn face_tone(mut self, tone: GlassFaceTone) -> Self {
        self.face_tone = tone.uniforms().map(|_| tone);
        self.adaptive_tone = false;
        self.adaptive_frost = 0.0;
        self
    }

    pub fn shadow(mut self, shadow: bool) -> Self {
        self.shadow = shadow;
        self
    }

    pub fn shadow_style(mut self, shadow: GlassShadow) -> Self {
        self.shadow_style = Some(shadow);
        self
    }

    /// Disables the layer clip: the shader's SDF coverage is the only shape
    /// (required while morphing across geometry the clip can't follow).
    pub fn no_clip(mut self) -> Self {
        self.clip = false;
        self
    }

    /// Uses a sharp/blurred backdrop blend controlled by the tint percentage.
    /// This replaces the whole-backdrop blur for this material.
    pub fn tint_amount(mut self, amount: GlassTintAmount) -> Self {
        self.tint_amount = Some(amount);
        self
    }

    /// Sets the diffuse pane's kernel reach, independently of its sharp transmitted image.
    pub fn pane_blur_radius(mut self, radius: f32) -> Self {
        if radius.is_finite() && radius >= 0.0 {
            self.pane_blur_radius = radius;
        }
        self
    }

    /// Crossfades the edge lens’s outer warp with a fixed-radius blurred backdrop.
    /// Radius uses the renderer's Gaussian convention: twice the standard deviation, in dp.
    /// Nonfinite values disable the blend; finite radius is nonnegative and opacity is clamped to 0–1.
    pub fn backdrop_blur(mut self, radius_dp: f32, opacity: f32) -> Self {
        self.backdrop_blur = (radius_dp.is_finite() && opacity.is_finite())
            .then_some((radius_dp.max(0.0), opacity.clamp(0.0, 1.0)));
        self
    }

    fn default_blur_radius(&self) -> f32 {
        match self.variant {
            GlassVariant::Regular => 8.0,
            GlassVariant::Clear => 3.0,
            GlassVariant::Lens => 0.0,
        }
    }

    fn default_saturation(&self) -> f32 {
        match self.variant {
            GlassVariant::Regular => 1.5,
            GlassVariant::Clear => 1.25,
            GlassVariant::Lens => 1.0,
        }
    }

    /// The backdrop effect this material produces for a node at `density`
    /// under `dynamics`, resolved against `colors`: the render effect the
    /// glass modifiers install, for a layer built without them.
    pub fn backdrop_effect(
        &self,
        colors: &LiquidColors,
        density: f32,
        dynamics: GlassDynamics,
    ) -> RenderEffect {
        self.resolve(colors).backdrop_effect(density, dynamics)
    }

    fn preferred_foreground(&self, colors: &LiquidColors) -> Color {
        self.foreground
            .filter(|color| {
                [color.r(), color.g(), color.b(), color.a()]
                    .iter()
                    .all(|value| value.is_finite())
            })
            .unwrap_or(colors.label)
    }

    pub(crate) fn resolve(&self, colors: &LiquidColors) -> ResolvedGlass {
        let lift = self.lift.unwrap_or(match (self.variant, colors.is_dark) {
            (GlassVariant::Regular, false) => 0.42,
            (GlassVariant::Regular, true) => -0.38,
            (GlassVariant::Clear, false) => 0.12,
            (GlassVariant::Clear, true) => -0.12,
            (GlassVariant::Lens, false) => 0.10,
            (GlassVariant::Lens, true) => -0.08,
        });
        let foreground = self.preferred_foreground(colors);
        let shadow = self.shadow_style.unwrap_or_else(|| {
            GlassShadow::new(
                Color::BLACK.with_alpha(match (self.variant, colors.is_dark) {
                    (GlassVariant::Lens, false) => 0.14,
                    (GlassVariant::Lens, true) => 0.28,
                    (_, false) => 0.16,
                    (_, true) => 0.5,
                }),
                if self.variant == GlassVariant::Lens {
                    10.0
                } else {
                    22.0
                },
                if self.variant == GlassVariant::Lens {
                    3.0
                } else {
                    8.0
                },
                if self.variant == GlassVariant::Lens {
                    -6.0
                } else {
                    -2.0
                },
            )
        });
        ResolvedGlass {
            face_tone: self.face_tone,
            shape: self.shape,
            tint: self.tint.unwrap_or(colors.glass_tint),
            tint_transmission: self.tint_transmission,
            tint_amount: self.tint_amount,
            pane_blur_radius: self.pane_blur_radius,
            backdrop_blur: self.backdrop_blur,
            blur_radius_dp: self
                .blur_radius
                .unwrap_or_else(|| self.default_blur_radius()),
            saturation: self.saturation.unwrap_or_else(|| self.default_saturation()),
            refraction_depth: self.refraction_depth,
            refraction_depth_dp: self.refraction_depth_dp,
            refraction: self.refraction,
            refraction_curve: self.refraction_curve,
            dispersion: self.dispersion,
            edge_spectrum: self.edge_spectrum,
            transmission_refraction: self.transmission_refraction,
            meniscus_absorption: self.meniscus_absorption,
            fold_depth: self.fold_depth,
            optical_zoom: self.optical_zoom,
            rim_reflection: self.rim_reflection,
            ink_recolor: self.ink_recolor,
            highlight: self.highlight,
            face_lighting: self.face_lighting,
            key_fill: self.key_fill,
            contour_highlight: self.contour_highlight,
            specular_highlight: self.specular_highlight,
            face_response: self.face_response,
            inner_shadow: self.inner_shadow,
            lift,
            contrast: self.contrast.unwrap_or(match self.variant {
                GlassVariant::Lens => 1.0,
                _ => 1.03,
            }),
            shadow: self.shadow,
            clip: self.clip,
            foreground_luma: 0.2126 * foreground.r()
                + 0.7152 * foreground.g()
                + 0.0722 * foreground.b(),
            adaptive_frost: self.adaptive_frost,
            adaptive_tone: self.adaptive_tone,
            resting_edge_sharpness: finite_nonnegative(self.resting_edge_sharpness).min(1.0),
            rim_style: if self.variant == GlassVariant::Lens {
                1.0
            } else {
                0.0
            },
            shadow_color: shadow.color,
            shadow_radius: shadow.radius,
            shadow_offset_y: shadow.offset_y,
            shadow_spread: shadow.spread,
        }
    }
}

impl Default for Glass {
    fn default() -> Self {
        Self::regular()
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ResolvedGlass {
    specular_highlight: Option<GlassSpecularHighlight>,
    face_tone: Option<GlassFaceTone>,
    resting_edge_sharpness: f32,
    pub shape: LiquidShape,
    pub tint: Color,
    tint_transmission: Option<f32>,
    tint_amount: Option<GlassTintAmount>,
    pane_blur_radius: f32,
    backdrop_blur: Option<(f32, f32)>,
    pub blur_radius_dp: f32,
    pub saturation: f32,
    pub refraction_depth: f32,
    pub refraction_depth_dp: Option<f32>,
    pub refraction: GlassRefraction,
    pub refraction_curve: f32,
    pub dispersion: f32,
    pub edge_spectrum: Option<GlassSpectrum>,
    pub transmission_refraction: f32,
    pub meniscus_absorption: f32,
    pub fold_depth: f32,
    pub optical_zoom: f32,
    pub rim_reflection: f32,
    pub ink_recolor: Option<(Color, f32)>,
    pub highlight: f32,
    pub face_lighting: bool,
    pub key_fill: Option<GlassKeyFill>,
    /// Contour reflection applied before the foreground's spectral dispersion.
    pub contour_highlight: Option<GlassContourHighlight>,
    /// Attenuation and illumination applied around the edge-light pass.
    pub face_response: Option<GlassFaceResponse>,
    pub lift: f32,
    /// Inset shadow on the transmitted face, covered by the chromatic foreground.
    pub inner_shadow: Option<GlassShadow>,
    pub contrast: f32,
    pub shadow: bool,
    pub clip: bool,
    pub rim_style: f32,
    pub foreground_luma: f32,
    pub adaptive_frost: f32,
    pub adaptive_tone: bool,
    pub shadow_color: Color,
    pub shadow_radius: f32,
    pub shadow_offset_y: f32,
    pub shadow_spread: f32,
}

fn set_edge_return_depth(shader: &mut RuntimeShader, depth: Option<f32>) {
    if let Some(depth) = depth.filter(|depth| depth.is_finite() && *depth >= 0.0) {
        shader.set_float2(GLASS_EDGE_RETURN_DEPTH_UNIFORM, depth, 1.0);
    }
}

impl ResolvedGlass {
    /// The rounded rectangle a placeholder fills while this glass compiles:
    /// around its morph's shapes, or the whole node in its shape.
    fn placeholder_shape(&self, morph: Option<&GlassMorph>) -> PlaceholderShape {
        let Some(morph) = morph else {
            return PlaceholderShape {
                bounds: Rect {
                    x: 0.0,
                    y: 0.0,
                    width: 1.0,
                    height: 1.0,
                },
                corner_radius: self.shape.radius_dp(),
            };
        };
        let (node_width, node_height) = morph.node_size;
        let (node_width, node_height) =
            (node_width.max(f32::EPSILON), node_height.max(f32::EPSILON));
        // A radius of -2 subtracts its shape: it carves a hole in the field.
        let added = morph.shapes.iter().filter(|&&(.., radius)| radius > -1.5);
        let (left, top, right, bottom) = std::iter::once(&morph.primary).chain(added).fold(
            (f32::MAX, f32::MAX, f32::MIN, f32::MIN),
            |(left, top, right, bottom), &(center_x, center_y, width, height, _)| {
                (
                    left.min(center_x - width * 0.5),
                    top.min(center_y - height * 0.5),
                    right.max(center_x + width * 0.5),
                    bottom.max(center_y + height * 0.5),
                )
            },
        );
        // A negative radius is the shader's capsule.
        let (.., radius) = morph.primary;
        PlaceholderShape {
            bounds: Rect {
                x: left / node_width,
                y: top / node_height,
                width: (right - left) / node_width,
                height: (bottom - top) / node_height,
            },
            corner_radius: if radius < 0.0 { f32::MAX } else { radius },
        }
    }

    /// The same glass as a flat surface, for a person who asked the system
    /// for less transparency: the surface color with no blur, no refraction
    /// and no spectrum, the shape and the shadow as they were.
    pub(crate) fn without_transparency(mut self, colors: &LiquidColors) -> Self {
        self.tint = colors.surface;
        self.tint_transmission = None;
        self.tint_amount = None;
        self.backdrop_blur = None;
        self.face_tone = None;
        self.contour_highlight = None;
        self.specular_highlight = None;
        self.adaptive_tone = false;
        self.blur_radius_dp = 0.0;
        self.saturation = 1.0;
        self.refraction_depth = 0.0;
        self.refraction_depth_dp = None;
        self.dispersion = 0.0;
        self.edge_spectrum = None;
        self.transmission_refraction = 0.0;
        self.meniscus_absorption = 0.0;
        self.rim_reflection = 0.0;
        self.adaptive_frost = 0.0;
        self
    }

    fn clips_in_shader(&self) -> bool {
        self.key_fill.and_then(GlassKeyFill::uniforms).is_some()
    }
    pub(crate) fn backdrop_effect(&self, density: f32, dynamics: GlassDynamics) -> RenderEffect {
        self.runtime_effect(density, &dynamics, false)
    }

    fn blur_radii(&self, density: f32, activity: f32, content_mask: bool) -> (f32, f32) {
        if content_mask || self.tint_amount.is_some() {
            return (0.0, 0.0);
        }
        let radius = self.blur_radius_dp * density * activity;
        if radius > WCKSRD_OPTICAL_BLUR_RADIUS_PX {
            (0.0, radius)
        } else {
            (radius, 0.0)
        }
    }

    fn runtime_effect(
        &self,
        density: f32,
        dynamics: &GlassDynamics,
        content_mask: bool,
    ) -> RenderEffect {
        self.runtime_effect_with_content(density, dynamics, content_mask, false)
    }

    fn set_refraction_uniforms(
        &self,
        shader: &mut RuntimeShader,
        dynamics: &GlassDynamics,
        activity: f32,
    ) -> (f32, f32, f32) {
        let press_depth = dynamics.press_depth.unwrap_or(1.0).clamp(0.0, 1.0);
        shader.set_float(9, self.refraction_depth * activity * press_depth);
        let refraction = dynamics.refraction.unwrap_or(self.refraction);
        let (refraction_mode, refraction_reach) = refraction.shader_parameters();
        let refraction_weight = if matches!(refraction, GlassRefraction::LayeredSurface { .. }) {
            1.0
        } else {
            activity * press_depth
        };
        shader.set_float(GLASS_REFRACTION_MODE_UNIFORM, refraction_mode);
        if let GlassRefraction::LayeredSurface {
            return_reach_dp,
            return_depth_dp,
            ..
        } = refraction
        {
            shader.set_float2(
                GLASS_LAYERED_RETURN_UNIFORM,
                finite_nonnegative(return_reach_dp),
                finite_nonnegative(return_depth_dp),
            );
        }
        set_edge_return_depth(shader, dynamics.edge_return_depth_dp);
        shader.set_float(
            GLASS_EDGE_REFRACTION_REACH_UNIFORM,
            refraction_reach * refraction_weight,
        );
        shader.set_float(
            GLASS_PHYSICAL_REFRACTION_DEPTH_UNIFORM,
            self.refraction_depth_dp.unwrap_or(0.0) * refraction_weight,
        );
        shader.set_float(
            GLASS_PHYSICAL_REFRACTION_DEPTH_ENABLED_UNIFORM,
            if self.refraction_depth_dp.is_some() {
                1.0
            } else {
                0.0
            },
        );
        shader.set_float(
            GLASS_REFRACTION_CURVE_UNIFORM,
            self.refraction_curve * activity,
        );
        shader.set_float(
            GLASS_DISPERSION_UNIFORM,
            self.dispersion * activity * press_depth,
        );
        let spectrum_reach = self.set_spectrum_uniforms(shader);
        shader.set_float(
            GLASS_TRANSMISSION_REFRACTION_UNIFORM,
            self.transmission_refraction * if refraction_mode > 2.5 { 1.0 } else { activity },
        );
        shader.set_float(
            GLASS_MENISCUS_ABSORPTION_UNIFORM,
            self.meniscus_absorption * press_depth,
        );
        shader.set_float(
            GLASS_FOLD_DEPTH_UNIFORM,
            self.fold_depth.max(0.0) * press_depth,
        );
        (refraction_mode, refraction_reach, spectrum_reach)
    }

    fn set_shadow_uniforms(
        &self,
        shader: &mut RuntimeShader,
        dynamics: &GlassDynamics,
        activity: f32,
    ) -> (f32, f32) {
        let dynamic_shadow = !self.clip && self.shadow;
        let shadow = dynamics
            .shadow
            .filter(|shadow| shadow.uniforms().is_some())
            .unwrap_or_else(|| {
                GlassShadow::new(
                    self.shadow_color
                        .with_alpha(self.shadow_color.a() * 0.55 * activity),
                    self.shadow_radius,
                    self.shadow_offset_y,
                    self.shadow_spread,
                )
            });
        shader.set_float(
            102,
            if dynamic_shadow {
                shadow.color.a()
            } else {
                0.0
            },
        );
        shader.set_float(103, shadow.radius);
        shader.set_float(104, shadow.offset_y);
        shader.set_float(105, shadow.spread);
        shader.set_float4(
            cranpose_ui_graphics::GLASS_SHADOW_COLOR_UNIFORM,
            shadow.color.r(),
            shadow.color.g(),
            shadow.color.b(),
            0.0,
        );
        let ring_shadow = dynamics.ring_shadow.filter(|(ring, width)| {
            ring.color.a() > 0.0 && ring.uniforms().is_some() && width.is_finite() && *width > 0.0
        });
        if let Some((ring, width)) = ring_shadow {
            shader.set_float4(
                cranpose_ui_graphics::GLASS_RING_SHADOW_UNIFORM,
                ring.color.r(),
                ring.color.g(),
                ring.color.b(),
                ring.color.a(),
            );
            shader.set_float4(
                cranpose_ui_graphics::GLASS_RING_SHADOW_UNIFORM + 4,
                ring.radius,
                ring.offset_y,
                width,
                1.0,
            );
            shader.set_float(
                cranpose_ui_graphics::GLASS_RING_SHADOW_UNIFORM + 8,
                ring.spread,
            );
        }
        let ring_reach = ring_shadow.map_or(0.0, |(ring, width)| {
            3.0 * ring.radius + ring.offset_y.abs() + width * 0.5 + ring.spread.abs()
        });
        let contour_reach = self
            .contour_highlight
            .and_then(GlassContourHighlight::uniforms)
            .filter(|values| values[2] > 0.0 && activity > 0.0)
            .map_or(0.0, |values| (-values[1]).max(0.0));
        let visible_shadow = dynamic_shadow && shadow.color.a() > 0.0;
        let shadow_reach = if visible_shadow {
            shadow.radius + shadow.offset_y.abs() + shadow.spread.max(0.0)
        } else {
            0.0
        }
        .max(ring_reach)
        .max(contour_reach);
        // The drop shadow falls outside the node: without this reach the
        // compositor cuts it at the node's rectangle.
        shader.set_output_padding(shadow_reach);
        let offset = if visible_shadow || ring_shadow.is_some() {
            shadow
                .offset_y
                .abs()
                .max(ring_shadow.map_or(0.0, |(ring, _)| ring.offset_y.abs()))
        } else {
            0.0
        };
        (shadow_reach, offset)
    }

    fn runtime_effect_with_content(
        &self,
        density: f32,
        dynamics: &GlassDynamics,
        content_mask: bool,
        separate_content: bool,
    ) -> RenderEffect {
        let density = density.max(f32::EPSILON);
        let activity = dynamics
            .activity
            .filter(|value| value.is_finite())
            .unwrap_or(1.0)
            .clamp(0.0, 1.0);
        static SHADER: OnceLock<RuntimeShader> = OnceLock::new();
        let mut shader = SHADER
            .get_or_init(|| {
                let mut shader = RuntimeShader::new(LIQUID_GLASS_WGSL);
                shader.set_float(GLASS_ACTIVITY_UNIFORM, 1.0);
                shader.set_float2(GLASS_OPTICAL_ZOOM_ANCHOR_UNIFORM, 0.0, 0.0);
                specialize_liquid_glass(&mut shader);
                shader
            })
            .clone();
        if let Some(morph) = dynamics.morph.as_ref() {
            set_morph_uniforms(&mut shader, morph, activity);
        } else {
            shader.set_float2(0, 0.0, 0.0);
            shader.set_float(6, self.shape.shader_radius_px(density));
        }
        let projection = dynamics.projection();
        shader.set_float2(GLASS_OPTICAL_PROJECTION_UNIFORM, projection.0, projection.1);
        let (refraction_mode, refraction_reach, spectrum_reach) =
            self.set_refraction_uniforms(&mut shader, dynamics, activity);
        shader.set_float(
            GLASS_OPTICAL_ZOOM_UNIFORM,
            1.0 + (self.optical_zoom - 1.0).max(0.0) * activity,
        );
        let zoom_anchor = dynamics
            .morph
            .as_ref()
            .map_or((0.0, 0.0), |morph| morph.zoom_anchor);
        shader.set_float2(
            GLASS_OPTICAL_ZOOM_ANCHOR_UNIFORM,
            zoom_anchor.0,
            zoom_anchor.1,
        );
        shader.set_float(121, self.rim_reflection.max(0.001));
        let (ink_color, ink_strength) = self
            .ink_recolor
            .map_or((Color::TRANSPARENT, 0.0), |(color, strength)| {
                (color, strength * activity)
            });
        shader.set_float(124, ink_color.r());
        shader.set_float(125, ink_color.g());
        shader.set_float(126, ink_color.b());
        shader.set_float(127, ink_strength);
        let (light_x, light_y) = glass_light_direction();
        shader.set_float(GLASS_LIGHT_DIRECTION_UNIFORM, light_x);
        shader.set_float(GLASS_LIGHT_DIRECTION_UNIFORM + 1, light_y);
        self.set_lighting_uniforms(&mut shader, dynamics);
        shader.set_float(GLASS_EFFECT_DENSITY_UNIFORM, density);
        shader.set_float(
            11,
            (self.highlight + dynamics.highlight_boost).clamp(0.0, 2.0) * activity,
        );
        let dynamic_tint = boost_tint_saturation(self.tint, dynamics.saturation_boost);
        let dynamic_tint_alpha = (dynamic_tint.a()
            * dynamics
                .tint_alpha_multiplier
                .unwrap_or(1.0)
                .clamp(0.0, 2.0)
            * activity)
            .clamp(0.0, 1.0);
        shader.set_float4(
            14,
            dynamic_tint.r(),
            dynamic_tint.g(),
            dynamic_tint.b(),
            dynamic_tint_alpha,
        );
        if let Some((color, progress)) = dynamics.tint_crossfade.filter(|(_, p)| p.is_finite()) {
            let index = cranpose_ui_graphics::liquid_glass::GLASS_TINT_CROSSFADE_UNIFORM;
            shader.set_float(index, 1.0 + progress.clamp(0.0, 1.0));
            shader.set_float4(index + 1, color.r(), color.g(), color.b(), color.a());
        }
        let saturation = (self.saturation + dynamics.saturation_boost).max(0.0);
        shader.set_float(18, 1.0 + (saturation - 1.0) * activity);
        shader.set_float(20, self.lift * activity);
        shader.set_float(21, 0.5 * activity);
        shader.set_float2(22, 0.0, 1.0);
        shader.set_float(24, 1.0 + (self.contrast - 1.0) * activity);
        shader.set_float(28, self.rim_style * activity);
        let (wcksrd_blur_radius, gaussian_blur_radius) =
            self.blur_radii(density, activity, content_mask);
        shader.set_float(GLASS_BLUR_RADIUS_UNIFORM, wcksrd_blur_radius);
        shader.set_float(GLASS_ACTIVITY_UNIFORM, activity);
        shader.set_float(
            GLASS_RESTING_EDGE_SHARPNESS_UNIFORM,
            self.resting_edge_sharpness,
        );
        let resting_tint = dynamics.resting_tint.unwrap_or(Color::TRANSPARENT);
        shader.set_float4(
            GLASS_RESTING_TINT_UNIFORM,
            resting_tint.r(),
            resting_tint.g(),
            resting_tint.b(),
            resting_tint.a(),
        );
        shader.set_float(112, if content_mask { 1.0 } else { 0.0 });
        shader.set_float(GLASS_ADAPTIVE_FROST_UNIFORM, self.adaptive_frost * activity);
        shader.set_float(97, self.foreground_luma);
        shader.set_float(GLASS_ADAPTIVE_TONE_UNIFORM, f32::from(self.adaptive_tone));
        self.set_backdrop_uniforms(&mut shader, density, content_mask);
        shader.set_float(
            cranpose_ui_graphics::GLASS_FOREGROUND_CONTENT_UNIFORM,
            f32::from(separate_content),
        );
        let (shadow_reach, shadow_offset) = if content_mask {
            (0.0, 0.0)
        } else {
            self.set_shadow_uniforms(&mut shader, dynamics, activity)
        };
        let morph_pad = dynamics.morph.as_ref().map_or(0.0, |morph| {
            let (px, py, pw, ph, _) = morph.primary;
            let (left, top) = (px - pw * 0.5, py - ph * 0.5);
            let (right, bottom) = (px + pw * 0.5, py + ph * 0.5);
            let mut shape_reach = 0.0f32;
            for (sx, sy, sw, sh, _) in &morph.shapes {
                let reach_x = ((sx + sw * 0.5) - right)
                    .max(left - (sx - sw * 0.5))
                    .max(0.0);
                let reach_y = ((sy + sh * 0.5) - bottom)
                    .max(top - (sy - sh * 0.5))
                    .max(0.0);
                shape_reach = shape_reach.max(reach_x.max(reach_y));
            }
            let glue_pad = if morph.shapes.is_empty() {
                0.0
            } else {
                morph.glue * 2.0
            };
            morph.wobble_amplitude * 2.0 + morph.bulge_amplitude + shape_reach + glue_pad
        });
        shader.set_input_padding(if content_mask {
            0.0
        } else {
            (self.input_padding()
                + if refraction_mode > 2.5 {
                    refraction_reach + spectrum_reach
                } else if refraction_mode >= 1.5 {
                    refraction_reach * (26.5 / 9.0) + spectrum_reach
                } else {
                    refraction_reach
                }
                + morph_pad
                + wcksrd_blur_radius / density)
                * projection.0.max(projection.1).max(1.0)
        });
        if let Some(morph) = dynamics.morph.as_ref() {
            let support =
                morph_output_support(morph, activity, morph_pad, shadow_reach, shadow_offset);
            let (cx, cy, _, _, _) = morph.primary;
            let support = Rect {
                x: cx + (support.x - cx) * projection.0,
                y: cy + (support.y - cy) * projection.1,
                width: support.width * projection.0,
                height: support.height * projection.1,
            };
            let (node_w, node_h) = morph.node_size;
            let overhang = (-support.x)
                .max(-support.y)
                .max(support.x + support.width - node_w)
                .max(support.y + support.height - node_h)
                .max(0.0);
            shader.set_output_padding((morph_pad + shadow_reach + 4.0).max(overhang));
            shader.set_output_support(Some(support));
        }

        shader.set_placeholder(Some(liquid_glass_placeholder(
            shown_tint(
                Color(
                    dynamic_tint.r(),
                    dynamic_tint.g(),
                    dynamic_tint.b(),
                    dynamic_tint_alpha,
                ),
                dynamics.tint_crossfade,
            ),
            Some(self.placeholder_shape(dynamics.morph.as_ref())),
        )));
        let optical_effect = liquid_glass_runtime_effect(shader);
        if gaussian_blur_radius > f32::EPSILON {
            RenderEffect::blur_with_edge_treatment(gaussian_blur_radius, TileMode::Mirror)
                .then(optical_effect)
        } else {
            optical_effect
        }
    }

    fn set_backdrop_uniforms(&self, shader: &mut RuntimeShader, density: f32, content_mask: bool) {
        if let Some(values) = self.face_tone.and_then(GlassFaceTone::uniforms) {
            for (index, value) in values.into_iter().enumerate() {
                shader.set_float(cranpose_ui_graphics::GLASS_FACE_TONE_UNIFORM + index, value);
            }
        }
        if let Some(amount) = self.tint_amount {
            shader.set_float(
                cranpose_ui_graphics::GLASS_PANE_BLEND_UNIFORM,
                self.pane_blur_radius * density,
            );
            shader.set_float(
                cranpose_ui_graphics::GLASS_PANE_BLEND_UNIFORM + 1,
                amount.percent() / 100.0,
            );
        }
        if !content_mask && let Some((radius, opacity)) = self.backdrop_blur {
            shader.set_float2(
                cranpose_ui_graphics::GLASS_BACKDROP_BLUR_UNIFORM,
                radius * density,
                opacity,
            );
        }
    }

    fn set_spectrum_uniforms(&self, shader: &mut RuntimeShader) -> f32 {
        let spectrum = self
            .edge_spectrum
            .and_then(|spectrum| spectrum.uniforms().map(|values| (spectrum, values)));
        if let Some((spectrum, values)) = spectrum {
            for (index, value) in values.into_iter().enumerate() {
                shader.set_float(GLASS_EDGE_SPECTRUM_UNIFORM + index, value);
            }
            spectrum.capture_reach()
        } else {
            40.787 * self.dispersion
        }
    }

    fn set_lighting_uniforms(&self, shader: &mut RuntimeShader, dynamics: &GlassDynamics) {
        if let Some(values) = self
            .specular_highlight
            .and_then(GlassSpecularHighlight::uniforms)
        {
            for (index, value) in values.into_iter().enumerate() {
                shader.set_float(
                    cranpose_ui_graphics::GLASS_SPECULAR_HIGHLIGHT_UNIFORM + index,
                    value,
                );
            }
        }
        shader.set_float(
            cranpose_ui_graphics::GLASS_CONTACT_LIGHT_UNIFORM,
            f32::from(dynamics.contact_lighting),
        );
        if let Some(black) = self.tint_transmission.filter(|value| value.is_finite()) {
            shader.set_float2(
                cranpose_ui_graphics::GLASS_TINT_TRANSMISSION_UNIFORM,
                black.clamp(0.0, 1.0),
                1.0,
            );
        }
        let (touch_x, touch_y, touch_intensity) = dynamics.touch.unwrap_or((0.0, 0.0, 0.0));
        shader.set_float(118, touch_x);
        shader.set_float(119, touch_y);
        shader.set_float(120, touch_intensity.clamp(0.0, 1.0));
        shader.set_float(
            GLASS_FACE_LIGHTING_OFF_UNIFORM,
            f32::from(!self.face_lighting),
        );
        shader.set_float(
            GLASS_TOUCH_RADIUS_UNIFORM,
            dynamics
                .touch_radius_dp
                .filter(|radius| radius.is_finite() && *radius > 0.0)
                .unwrap_or(58.0),
        );
        shader.set_float(
            GLASS_LAYER_CLIPPED_UNIFORM,
            f32::from(self.clip && !self.clips_in_shader()),
        );
        if let Some(values) = self.key_fill.and_then(GlassKeyFill::uniforms) {
            for (index, value) in values.into_iter().enumerate() {
                shader.set_float(GLASS_KEY_FILL_UNIFORM + index, value);
            }
        }
        if let Some(values) = self.face_response.and_then(GlassFaceResponse::uniforms) {
            for (index, value) in values.into_iter().enumerate() {
                shader.set_float(GLASS_FACE_RESPONSE_UNIFORM + index, value);
            }
        }
        if let Some(values) = self
            .contour_highlight
            .and_then(GlassContourHighlight::uniforms)
        {
            for (index, value) in values.into_iter().enumerate() {
                shader.set_float(
                    cranpose_ui_graphics::GLASS_CONTOUR_HIGHLIGHT_UNIFORM + index,
                    value,
                );
            }
        }
        if let Some(values) = self.inner_shadow.and_then(GlassShadow::uniforms) {
            for (index, value) in values.into_iter().enumerate() {
                shader.set_float(GLASS_INNER_SHADOW_UNIFORM + index, value);
            }
        }
    }

    fn input_padding(&self) -> f32 {
        2.0
    }
}

/// Modifier extension installing the Liquid Glass material.
pub trait LiquidModifierExt {
    /// Applies the glass material to this composable's bounds: backdrop blur +
    /// lens shader, clipped to `glass.shape`, with a soft drop shadow.
    ///
    /// Must be called in composable context (the material resolves theme
    /// colors at the call site).
    fn glass_effect(self, glass: Glass) -> Modifier;

    /// [`glass_effect`](Self::glass_effect) with per-frame motion inputs; the
    /// closure is read at scene-build time, so animating tilt or highlight
    /// does not recompose.
    fn glass_effect_with(
        self,
        glass: Glass,
        dynamics: impl Fn() -> GlassDynamics + 'static,
    ) -> Modifier;
}

impl LiquidModifierExt for Modifier {
    fn glass_effect(self, glass: Glass) -> Modifier {
        self.glass_effect_with(glass, GlassDynamics::default)
    }

    fn glass_effect_with(
        self,
        glass: Glass,
        dynamics: impl Fn() -> GlassDynamics + 'static,
    ) -> Modifier {
        let colors = crate::theme::liquid_colors();
        let options = cranpose_services::local_accessibility_options().current();
        let resolved = if options.reduce_transparency {
            glass.resolve(&colors).without_transparency(&colors)
        } else {
            glass.resolve(&colors)
        };
        let shape = resolved.shape;

        let mut modifier = self;
        if resolved.shadow && resolved.clip {
            let shadow_color = resolved.shadow_color;
            let (radius, offset_y, spread) = (
                resolved.shadow_radius,
                resolved.shadow_offset_y,
                resolved.shadow_spread,
            );
            modifier = modifier.drop_shadow(shape.layer_shape(), move |scope| {
                scope.radius = radius;
                scope.spread = spread;
                scope.offset.y = offset_y;
                scope.color = shadow_color;
                scope.cutout = true;
            });
        }

        let layer = cached_glass_layer(resolved);
        modifier.graphics_layer(move || layer(current_density(), dynamics()))
    }
}

struct CachedGlassLayer<T> {
    density: u32,
    light: [u32; 2],
    dynamics: GlassDynamics,
    value: T,
}

fn cached_glass_layer(resolved: ResolvedGlass) -> impl Fn(f32, GlassDynamics) -> GraphicsLayer {
    cached_glass_layers(resolved, false, std::convert::identity)
}

pub(crate) fn cached_glass_content_layers(
    resolved: ResolvedGlass,
) -> impl Fn(f32, GlassDynamics) -> [GraphicsLayer; 2] {
    cached_glass_layers(resolved, true, |mut layer| {
        let Some(RenderEffect::Chain { first, second }) = layer.backdrop_effect.take() else {
            panic!("content layers require a sequential edge lens");
        };
        layer.backdrop_effect = Some((*second).clone());
        [
            GraphicsLayer {
                backdrop_effect: Some((*first).clone()),
                ..Default::default()
            },
            layer,
        ]
    })
}

fn cached_glass_layers<T: Clone>(
    resolved: ResolvedGlass,
    separate_content: bool,
    assemble: impl Fn(GraphicsLayer) -> T,
) -> impl Fn(f32, GlassDynamics) -> T {
    let cached = RefCell::new(None::<CachedGlassLayer<T>>);
    move |density, dynamics| {
        let direction = glass_light_direction();
        let light = [direction.0, direction.1].map(f32::to_bits);
        let mut cached = cached.borrow_mut();
        if let Some(previous) = &*cached
            && previous.density == density.to_bits()
            && previous.light == light
            && glass_dynamics_match(&previous.dynamics, &dynamics)
        {
            return previous.value.clone();
        }
        let render_effect = ((!resolved.clip && dynamics.morph.is_some())
            || (resolved.clip && resolved.clips_in_shader()))
        .then(|| resolved.runtime_effect(density, &dynamics, true));
        let layer = GraphicsLayer {
            backdrop_effect: Some(resolved.runtime_effect_with_content(
                density,
                &dynamics,
                false,
                separate_content,
            )),
            render_effect,
            shape: resolved.shape.layer_shape(),
            clip: resolved.clip && !resolved.clips_in_shader(),
            ..Default::default()
        };
        let value = assemble(layer);
        *cached = Some(CachedGlassLayer {
            density: density.to_bits(),
            light,
            dynamics,
            value: value.clone(),
        });
        value
    }
}

fn glass_dynamics_match(a: &GlassDynamics, b: &GlassDynamics) -> bool {
    let bits = |d: &GlassDynamics| {
        let GlassDynamics {
            contact_lighting,
            refraction,
            shadow,
            ring_shadow,
            edge_return_depth_dp,
            optical_projection,
            activity,
            resting_tint,
            highlight_boost,
            saturation_boost,
            tint_alpha_multiplier,
            tint_crossfade,
            morph: _,
            touch,
            touch_radius_dp,
            press_depth,
        } = d;
        (
            (
                *contact_lighting,
                ring_shadow.map(|(ring, width)| (shadow_bits(ring), width.to_bits())),
                tint_crossfade.map(|(Color(r, g, b, a), p)| [r, g, b, a, p].map(f32::to_bits)),
            ),
            refraction.map(|refraction| {
                match refraction {
                    GlassRefraction::Radial => [0.0, 0.0, 0.0, 0.0],
                    GlassRefraction::Surface { reach_dp } => [1.0, reach_dp, 0.0, 0.0],
                    GlassRefraction::EdgeLens { reach_dp } => [2.0, reach_dp, 0.0, 0.0],
                    GlassRefraction::LayeredSurface {
                        reach_dp,
                        return_reach_dp,
                        return_depth_dp,
                    } => [3.0, reach_dp, return_reach_dp, return_depth_dp],
                }
                .map(f32::to_bits)
            }),
            shadow.map(shadow_bits),
            edge_return_depth_dp.map(f32::to_bits),
            optical_projection.map(|(x, y)| [x, y].map(f32::to_bits)),
            activity.map(f32::to_bits),
            resting_tint.map(|Color(r, g, b, a)| [r, g, b, a].map(f32::to_bits)),
            [*highlight_boost, *saturation_boost].map(f32::to_bits),
            tint_alpha_multiplier.map(f32::to_bits),
            touch.map(|(x, y, strength)| [x, y, strength].map(f32::to_bits)),
            press_depth.map(f32::to_bits),
            touch_radius_dp.map(f32::to_bits),
        )
    };
    bits(a) == bits(b)
        && match (&a.morph, &b.morph) {
            (None, None) => true,
            (Some(a), Some(b)) => glass_morphs_match(a, b),
            _ => false,
        }
}

fn shadow_bits(shadow: GlassShadow) -> [u32; 7] {
    [
        shadow.color.r(),
        shadow.color.g(),
        shadow.color.b(),
        shadow.color.a(),
        shadow.radius,
        shadow.offset_y,
        shadow.spread,
    ]
    .map(f32::to_bits)
}

fn glass_morphs_match(a: &GlassMorph, b: &GlassMorph) -> bool {
    let shape_bits =
        |&(x, y, w, h, r): &(f32, f32, f32, f32, f32)| [x, y, w, h, r].map(f32::to_bits);
    let bits = |m: &GlassMorph| {
        let GlassMorph {
            node_size,
            primary,
            shapes: _,
            glue,
            wobble_amplitude,
            wobble_phase,
            bulge_amplitude,
            bulge_direction,
            ellipse_blend,
            capsule_smoothing_dp,
            deformation,
            zoom_anchor,
        } = m;
        (
            [
                node_size.0,
                node_size.1,
                *glue,
                *wobble_amplitude,
                *wobble_phase,
                *bulge_amplitude,
                *bulge_direction,
                *ellipse_blend,
                *capsule_smoothing_dp,
                zoom_anchor.0,
                zoom_anchor.1,
            ]
            .map(f32::to_bits),
            shape_bits(primary),
            deformation
                .map(|GlassDeformation { axis, along }| [axis.0, axis.1, along].map(f32::to_bits)),
        )
    };
    bits(a) == bits(b)
        && a.shapes
            .iter()
            .map(shape_bits)
            .eq(b.shapes.iter().map(shape_bits))
}

fn morph_output_support(
    morph: &GlassMorph,
    activity: f32,
    morph_pad: f32,
    shadow_reach: f32,
    shadow_offset: f32,
) -> Rect {
    let (px, py, pw, ph, _) = morph.primary;
    let (along, (ax, ay)) = morph.deformation.map_or((1.0, (1.0, 0.0)), |deformation| {
        (
            1.0 + (deformation.along() - 1.0) * activity,
            deformation.axis(),
        )
    });
    let across = 1.0 / along;
    let smallest_strain = along.min(across);
    let reach = (morph_pad + shadow_reach + 4.0) / smallest_strain;
    let rows = [
        (
            (along * ax * ax + across * ay * ay).abs(),
            ((along - across) * ax * ay).abs(),
        ),
        (
            ((along - across) * ax * ay).abs(),
            (along * ay * ay + across * ax * ax).abs(),
        ),
    ];
    let half = (pw * 0.5 + reach, ph * 0.5 + reach);
    let extent_x = rows[0].0 * half.0 + rows[0].1 * half.1;
    let extent_y = rows[1].0 * half.0 + rows[1].1 * half.1;
    let (mut left, mut top) = (px - extent_x, py - extent_y);
    let (mut right, mut bottom) = (px + extent_x, py + extent_y);
    for (sx, sy, sw, sh, _) in &morph.shapes {
        left = left.min(sx - sw * 0.5 - reach);
        top = top.min(sy - sh * 0.5 - reach);
        right = right.max(sx + sw * 0.5 + reach);
        bottom = bottom.max(sy + sh * 0.5 + reach);
    }
    Rect {
        x: left,
        y: top - shadow_offset,
        width: right - left,
        height: bottom - top + 2.0 * shadow_offset,
    }
}

fn set_morph_uniforms(shader: &mut RuntimeShader, morph: &GlassMorph, activity: f32) {
    let (node_w, node_h) = morph.node_size;
    let (cx, cy, w, h, radius) = morph.primary;
    shader.set_float2(0, node_w.max(1.0), node_h.max(1.0));
    shader.set_float2(2, cx, cy);
    shader.set_float2(4, w, h);
    shader.set_float(6, radius);
    let count = morph.shapes.len().min(GlassMorph::MAX_SHAPES);
    shader.set_float(30, count as f32);
    for (index, (sx, sy, sw, sh, sr)) in morph.shapes.iter().take(count).enumerate() {
        let base = 36 + index * 5;
        shader.set_float(base, *sx);
        shader.set_float(base + 1, *sy);
        shader.set_float(base + 2, *sw);
        shader.set_float(base + 3, *sh);
        shader.set_float(base + 4, *sr);
    }
    shader.set_float(31, morph.glue);
    shader.set_float(32, morph.wobble_amplitude * activity);
    shader.set_float(33, morph.wobble_phase);
    shader.set_float(26, morph.bulge_amplitude * activity);
    shader.set_float(27, morph.bulge_direction);
    shader.set_float(110, morph.ellipse_blend.clamp(0.0, 1.0) * activity);
    shader.set_float(
        cranpose_ui_graphics::liquid_glass::GLASS_CAPSULE_SMOOTHING_UNIFORM,
        if morph.capsule_smoothing_dp.is_finite() {
            morph.capsule_smoothing_dp.max(0.0) * activity
        } else {
            0.0
        },
    );
    if let Some(deformation) = morph.deformation {
        let axis = deformation.axis();
        let along = 1.0 + (deformation.along() - 1.0) * activity;
        shader.set_float2(106, axis.0, axis.1);
        shader.set_float(108, along);
        shader.set_float(109, 1.0 / along);
    } else {
        shader.set_float2(106, 1.0, 0.0);
        shader.set_float2(108, 1.0, 1.0);
    }
}

#[cfg(test)]
#[path = "tests/material_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "tests/material_transparency_tests.rs"]
mod transparency_tests;