incular-rendering 0.1.0

Renderer-neutral scene, canvas, display-list, and compositor APIs for Incular
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
use crate::display_list::{DisplayList, PaintCommand, SurfacePartitionId};
use crate::effects::{
    BlendMode, ColorFilter, DropShadowEffect, GaussianBlur, blur_bounds, drop_shadow_bounds,
};
use crate::geometry::{RRect, union_rect};
use crate::gradients::Brush;
use crate::paint::FillRule;
use crate::paths::{Path, ellipse_as_path, fallback_tolerance, rect_as_path, rrect_as_path};
use incular_core::finite_or_zero;
use incular_core::{Arena, ArenaId, Offset, Rect, Size, Transform};
use std::{
    any::{Any, TypeId},
    cell::RefCell,
    collections::HashMap,
    rc::Rc,
    sync::Arc,
};

/// Opaque retained compositor identity. It uses the core generational arena so
/// an ID for a removed layer can never select a later, unrelated layer.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LayerId(ArenaId);

/// Canonical opacity representation shared by widgets, retained layers, and
/// GPU lowering. Non-finite values become transparent and finite values are
/// clamped to the physically meaningful range.
#[must_use]
pub fn normalize_opacity(alpha: f32) -> f32 {
    if alpha.is_finite() {
        alpha.clamp(0., 1.)
    } else {
        0.
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CompositorDiagnostics {
    pub layers: u64,
    pub picture_layers_repainted: u64,
    pub transform_updates: u64,
    pub clip_updates: u64,
    pub layers_culled: u64,
    pub opacity_updates: u64,
    /// Leader-publication passes executed (every `flatten` and every
    /// pre-semantics republish runs one, unconditionally).
    pub leader_publish_passes: u64,
    /// Leaders successfully published across those passes (cumulative, so
    /// per-pass work is the delta over a known frame window).
    pub leaders_published: u64,
}

/// A picture placement observed while flattening. All rectangles here are in
/// logical coordinates; this is intentionally useful for CPU-side scene tests
/// and diagnostics without involving a surface or DPI scale factor.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FlattenedPicture {
    pub layer: LayerId,
    pub local_bounds: Rect,
    pub world_bounds: Rect,
    pub active_clip: Option<Rect>,
}

/// A type-erased application annotation carried by an annotated compositing
/// region. The value remains strongly typed at the API boundary: consumers
/// query it with [`LayerTree::find_annotation`] and receive only values of the
/// requested concrete type. Native platform adapters can therefore project
/// their own typed metadata without making the renderer depend on a platform
/// crate.
#[derive(Clone)]
pub struct Annotation {
    value: Rc<dyn Any>,
    type_id: TypeId,
}
impl Annotation {
    #[must_use]
    pub fn new<T: Any>(value: T) -> Self {
        Self {
            value: Rc::new(value),
            type_id: TypeId::of::<T>(),
        }
    }
    #[must_use]
    pub const fn value_type_id(&self) -> TypeId {
        self.type_id
    }
    #[must_use]
    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
        self.value.downcast_ref::<T>()
    }
    #[must_use]
    pub fn cloned<T: Any + Clone>(&self) -> Option<T> {
        self.downcast_ref::<T>().cloned()
    }
}
impl std::fmt::Debug for Annotation {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Annotation")
            .field("type_id", &self.type_id)
            .finish_non_exhaustive()
    }
}
impl PartialEq for Annotation {
    fn eq(&self, other: &Self) -> bool {
        self.type_id == other.type_id && Rc::ptr_eq(&self.value, &other.value)
    }
}

/// Normalized anchor used by leader/follower layers. `(-1, -1)` is the
/// top-left corner, `(0, 0)` the center, and `(1, 1)` the bottom-right.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct LayerAnchor {
    pub x: f32,
    pub y: f32,
}
impl LayerAnchor {
    pub const TOP_LEFT: Self = Self { x: -1., y: -1. };

    #[must_use]
    pub fn new(x: f32, y: f32) -> Self {
        Self {
            x: finite_or_zero(x),
            y: finite_or_zero(y),
        }
    }
    #[must_use]
    pub const fn along_size(self, size: Size) -> Offset {
        Offset::new(
            size.width * (self.x + 1.) * 0.5,
            size.height * (self.y + 1.) * 0.5,
        )
    }
}

/// World-space bounding box of a clip layer's shape, or `None` when the
/// shape is empty and clips everything away. Conservative for rounded
/// corners: the box covers the full rect. Pass only clip layers; any
/// other kind also reports `None` so a misuse culls rather than leaks.
fn clip_world_bounds(kind: &LayerKind, world_transform: Transform) -> Option<Rect> {
    match kind {
        LayerKind::ClipRect { rect, .. } => Some(world_transform.transform_rect_bbox(*rect)),
        LayerKind::ClipRRect { rrect, .. } => Some(world_transform.transform_rect_bbox(rrect.rect)),
        LayerKind::ClipOval { rect, .. } => Some(world_transform.transform_rect_bbox(*rect)),
        LayerKind::ClipPath { path, .. } => path
            .bounds()
            .map(|bounds| world_transform.transform_rect_bbox(bounds)),
        _ => None,
    }
}

/// What shape representations stay exact under a world transform.
/// Misclassification only costs a path fallback, never correctness: the
/// fallback path is exact for every affine map.
#[derive(Clone, Copy, Debug, PartialEq)]
enum ClipSpace {
    Translation,
    Scale { x: f32, y: f32 },
    General,
}

fn clip_space(world: Transform) -> ClipSpace {
    let [a, b, c, d, _, _] = world.to_kurbo().as_coeffs();
    if b == 0. && c == 0. {
        if a == 1. && d == 1. {
            ClipSpace::Translation
        } else {
            ClipSpace::Scale {
                x: a as f32,
                y: d as f32,
            }
        }
    } else {
        ClipSpace::General
    }
}

/// World-space point where a follower's anchor must land, resolved entirely
/// in leader space. The compositor and the widget tree share this half of
/// the projection; each side then inverts it into its own retained frame
/// (layer world vs. render parent), which is why the callers still differ.
#[must_use]
pub fn resolve_follower_target(
    leader_transform: Transform,
    leader_size: Size,
    target_anchor: LayerAnchor,
    offset: Offset,
) -> Offset {
    let target_point = leader_transform.transform_point(target_anchor.along_size(leader_size));
    let leader_origin = leader_transform.transform_point(Offset::ZERO);
    target_point + (leader_transform.transform_point(offset) - leader_origin)
}

/// World-resolved fallback path retained per clip layer. At most one
/// lives on a layer: geometry updates replace it through their own
/// update path, removal drops it with the layer, and no global map or
/// transform history exists. Tolerance is a pure function of the world,
/// so world equality implies tolerance equality.
#[derive(Clone, Debug)]
struct ResolvedClipPath {
    world: Transform,
    path: Arc<Path>,
}

#[derive(Clone, Debug)]
struct LeaderData {
    owner: PublisherIdentity,
    transform: Transform,
    size: Size,
    generation: u64,
}

/// One reachable leader layer snapshotted for the resolution pass, in
/// paint order. The snapshot carries everything publication needs so the
/// pass never holds layer borrows across recursive resolution.
struct LeaderRecord {
    id: LayerId,
    link: LayerLink,
    size: Size,
    publisher: PublisherIdentity,
    generation: u64,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum PublishState {
    InProgress,
    Published,
    Unresolvable,
}

/// Opaque publication owner minted per leader layer. A link may be shared
/// across layer trees whose arena indices overlap, so a tree-local
/// `LayerId` cannot name the publisher; instead each leader layer owns one
/// allocation whose identity is inseparable from the owner's lifetime.
/// Compare only with `same_owner`, never by detached address.
#[derive(Clone, Debug)]
pub struct PublisherIdentity(Rc<()>);
impl PublisherIdentity {
    pub(crate) fn new() -> Self {
        Self(Rc::new(()))
    }
    /// Whether both tokens name the same owning leader layer. Clones of
    /// one token always agree, including across layer trees.
    #[must_use]
    pub fn same_owner(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

/// Shared identity used to resolve a composited target and any number of
/// followers across otherwise unrelated retained subtrees.
#[derive(Clone)]
pub struct LayerLink(Rc<RefCell<Option<LeaderData>>>);
impl Default for LayerLink {
    fn default() -> Self {
        Self::new()
    }
}
impl std::fmt::Debug for LayerLink {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("LayerLink")
            .field("linked", &self.is_linked())
            .finish()
    }
}
impl PartialEq for LayerLink {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}
impl LayerLink {
    #[must_use]
    pub fn new() -> Self {
        Self(Rc::new(RefCell::new(None)))
    }
    #[must_use]
    pub fn is_linked(&self) -> bool {
        self.0.borrow().is_some()
    }
    #[must_use]
    pub fn leader_size(&self) -> Option<Size> {
        self.0.borrow().as_ref().map(|leader| leader.size)
    }
    #[must_use]
    pub fn leader_transform(&self) -> Option<Transform> {
        self.0.borrow().as_ref().map(|leader| leader.transform)
    }
    #[must_use]
    pub fn leader_generation(&self) -> u64 {
        self.0
            .borrow()
            .as_ref()
            .map_or(0, |leader| leader.generation)
    }
    /// Releases the publication only when `owner` made it. Removing or
    /// rebinding any other leader layer must not disturb the winner.
    fn clear_if_owned_by(&self, owner: &PublisherIdentity) {
        let mut state = self.0.borrow_mut();
        if state
            .as_ref()
            .is_some_and(|leader| leader.owner.same_owner(owner))
        {
            *state = None;
        }
    }
    /// Unconditional frame reset. The resolution pass republishes every live
    /// leader right after, so no reader observes the gap.
    fn clear_publication(&self) {
        *self.0.borrow_mut() = None;
    }
    fn publish(&self, owner: PublisherIdentity, transform: Transform, size: Size, generation: u64) {
        // One target per link: the first resolvable leader in paint order
        // wins. Keeping that rule deterministic is preferable to allowing
        // a later subtree to move an already published follower.
        let mut state = self.0.borrow_mut();
        if state.is_none() {
            *state = Some(LeaderData {
                owner,
                transform,
                size,
                generation,
            });
        }
    }
}

/// Annotation placement captured by the most recent layer flatten. A `None`
/// bounds value represents `sized: false`, which participates at every point
/// in the scene subject to ancestor clipping.
#[derive(Clone, Debug, PartialEq)]
pub struct FlattenedAnnotation {
    pub annotation: Annotation,
    pub world_bounds: Option<Rect>,
}

#[derive(Clone, Debug)]
pub enum LayerKind {
    Picture {
        display_list: Arc<DisplayList>,
        bounds: Rect,
    },
    Transform {
        transform: Transform,
    },
    ClipRect {
        rect: Rect,
    },
    ClipRRect {
        rrect: RRect,
    },
    ClipOval {
        rect: Rect,
    },
    ClipPath {
        path: Arc<Path>,
        fill_rule: FillRule,
    },
    Opacity {
        alpha: f32,
    },
    Blur {
        blur: GaussianBlur,
    },
    DropShadow {
        shadow: DropShadowEffect,
    },
    // Rare large payloads are boxed so every layer slot stays small.
    ColorFilter {
        filter: Box<ColorFilter>,
    },
    Blend {
        mode: BlendMode,
    },
    ShaderMask {
        shader: Box<Brush>,
        blend_mode: BlendMode,
        mask_size: Size,
        mask_transform: Box<Transform>,
    },
    BackdropFilter {
        blur: GaussianBlur,
        blend_mode: BlendMode,
        enabled: bool,
    },
    AnnotatedRegion {
        annotation: Annotation,
        sized: bool,
        size: Size,
    },
    Leader {
        link: LayerLink,
        size: Size,
        publisher: PublisherIdentity,
    },
    Follower(FollowerLayer),
}

/// Retained configuration of a layer that tracks a [`LayerLink`] leader.
#[derive(Clone, Debug, PartialEq)]
pub struct FollowerLayer {
    pub link: LayerLink,
    pub show_when_unlinked: bool,
    pub offset: Offset,
    pub target_anchor: LayerAnchor,
    pub follower_anchor: LayerAnchor,
    pub size: Size,
}

#[derive(Clone, Debug)]
struct Layer {
    kind: LayerKind,
    children: Vec<LayerId>,
    surface_partition: Option<SurfacePartitionId>,
    generation: u64,
    /// Owned fallback-path cache for clip layers. `LayerKind` describes
    /// requested behavior only; resolved state lives here so removal
    /// releases it and geometry updates invalidate it in one place.
    clip_cache: Option<Box<ResolvedClipPath>>,
}

/// Returns the current layer generation and advances the counter.
fn next_generation(counter: &mut u64) -> u64 {
    let generation = *counter;
    *counter = generation
        .checked_add(1)
        .expect("layer generation exhausted");
    generation
}

/// Renderer-independent retained layer arena. Picture display lists are owned
/// once and scene flattening only emits a transient linear command stream.
/// This deliberately has no GPU resources or offscreen textures.
pub struct LayerTree {
    layers: Arena<Layer>,
    root: Option<LayerId>,
    diagnostics: CompositorDiagnostics,
    flattened_pictures: Vec<FlattenedPicture>,
    flattened_annotations: Vec<FlattenedAnnotation>,
    next_generation: u64,
    /// Live annotated-region layers; the per-frame annotation pass is
    /// skipped entirely while there are none.
    annotation_layers: usize,
    /// Live leader layers; leader publication and its two layer walks are
    /// skipped entirely while there are none.
    leader_layers: usize,
    /// Reusable child-id stack for recursive passes, so traversals borrow
    /// the tree mutably without cloning each layer's child list.
    child_stack: Vec<LayerId>,
}
impl Default for LayerTree {
    fn default() -> Self {
        Self::new()
    }
}
impl LayerTree {
    #[must_use]
    pub fn new() -> Self {
        Self {
            layers: Arena::new(),
            root: None,
            diagnostics: CompositorDiagnostics::default(),
            flattened_pictures: Vec::new(),
            flattened_annotations: Vec::new(),
            next_generation: 1,
            annotation_layers: 0,
            leader_layers: 0,
            child_stack: Vec::new(),
        }
    }
    #[must_use]
    pub fn diagnostics(&self) -> CompositorDiagnostics {
        self.diagnostics
    }
    #[must_use]
    pub fn root(&self) -> Option<LayerId> {
        self.root
    }
    #[doc(hidden)]
    #[must_use]
    pub fn contains(&self, id: LayerId) -> bool {
        self.layers.contains(id.0)
    }
    pub fn set_root(&mut self, root: LayerId) {
        self.root = Some(root);
    }

    /// Returns the retained scene's conservative world-space visual bounds
    /// after compositor transforms, rectangular clipping, blur support, and
    /// drop-shadow support have been applied.
    ///
    /// This is renderer-independent geometry. It is useful to embedders that
    /// need to size a native host around retained content without inspecting
    /// widget types or GPU commands.
    #[must_use]
    pub fn scene_bounds(&self) -> Option<Rect> {
        self.root
            .and_then(|root| self.visual_subtree_bounds(root, Transform::IDENTITY))
    }
    pub fn create_picture(&mut self, display_list: DisplayList, bounds: Rect) -> LayerId {
        self.insert(LayerKind::Picture {
            display_list: Arc::new(display_list),
            bounds,
        })
    }
    pub fn create_transform(&mut self, transform: Transform) -> LayerId {
        self.insert(LayerKind::Transform { transform })
    }
    pub fn create_clip_rect(&mut self, rect: Rect) -> LayerId {
        self.insert(LayerKind::ClipRect { rect })
    }
    /// Creates a rounded-rectangle clip stage in local space; the world
    /// shape resolves at flatten time like [`Self::create_clip_rect`].
    pub fn create_clip_rrect(&mut self, rrect: RRect) -> LayerId {
        self.insert(LayerKind::ClipRRect { rrect })
    }
    /// Creates an oval clip stage in local space; the world shape resolves
    /// at flatten time like [`Self::create_clip_rect`].
    pub fn create_clip_oval(&mut self, rect: Rect) -> LayerId {
        self.insert(LayerKind::ClipOval { rect })
    }
    /// Creates a path clip stage in local space; the world shape resolves
    /// at flatten time like [`Self::create_clip_rect`].
    pub fn create_clip_path(&mut self, path: Arc<Path>, fill_rule: FillRule) -> LayerId {
        self.insert(LayerKind::ClipPath { path, fill_rule })
    }
    /// Creates an isolated compositor group. Alpha is normalized at the
    /// renderer-neutral boundary so every backend observes identical values.
    pub fn create_opacity(&mut self, alpha: f32) -> LayerId {
        self.insert(LayerKind::Opacity {
            alpha: normalize_opacity(alpha),
        })
    }
    /// Creates an isolated Gaussian-filtered compositor group.
    pub fn create_blur(&mut self, blur: GaussianBlur) -> LayerId {
        self.insert(LayerKind::Blur {
            blur: GaussianBlur::new(blur.sigma_x, blur.sigma_y),
        })
    }
    /// Creates an isolated arbitrary-subtree drop-shadow compositor group.
    pub fn create_drop_shadow(&mut self, shadow: DropShadowEffect) -> LayerId {
        self.insert(LayerKind::DropShadow {
            shadow: DropShadowEffect::asymmetric(
                shadow.offset,
                shadow.sigma_x,
                shadow.sigma_y,
                shadow.color,
            ),
        })
    }
    /// Creates an isolated color-matrix stage. Matrix changes are compositor
    /// updates and deliberately do not change the source generation.
    pub fn create_color_filter(&mut self, filter: ColorFilter) -> LayerId {
        self.insert(LayerKind::ColorFilter {
            filter: Box::new(filter),
        })
    }
    /// Creates a retained blend group whose source remains cached when only
    /// the discrete blend mode changes.
    pub fn create_blend(&mut self, mode: BlendMode) -> LayerId {
        self.insert(LayerKind::Blend { mode })
    }
    /// Creates an isolated shader-mask stage. The callback is evaluated by
    /// the retained widget during paint; this layer only owns the resolved,
    /// renderer-neutral shader description and its local coordinate space.
    pub fn create_shader_mask(
        &mut self,
        shader: Brush,
        blend_mode: BlendMode,
        mask_size: Size,
        mask_transform: Transform,
    ) -> LayerId {
        self.insert(LayerKind::ShaderMask {
            shader: Box::new(shader),
            blend_mode,
            mask_size,
            mask_transform: Box::new(mask_transform),
        })
    }
    /// Creates a backdrop-filter stage. Unlike [`Self::create_blur`], this
    /// stage samples the already painted destination before its child is
    /// composited.
    pub fn create_backdrop_filter(
        &mut self,
        blur: GaussianBlur,
        blend_mode: BlendMode,
        enabled: bool,
    ) -> LayerId {
        self.insert(LayerKind::BackdropFilter {
            blur: GaussianBlur::new(blur.sigma_x, blur.sigma_y),
            blend_mode,
            enabled,
        })
    }
    pub fn create_annotated_region(
        &mut self,
        annotation: Annotation,
        sized: bool,
        size: Size,
    ) -> LayerId {
        self.insert(LayerKind::AnnotatedRegion {
            annotation,
            sized,
            size,
        })
    }
    pub fn create_leader(&mut self, link: LayerLink, size: Size) -> LayerId {
        self.insert(LayerKind::Leader {
            link,
            size,
            publisher: PublisherIdentity::new(),
        })
    }
    pub fn create_follower(&mut self, follower: FollowerLayer) -> LayerId {
        self.insert(LayerKind::Follower(follower))
    }
    fn insert(&mut self, kind: LayerKind) -> LayerId {
        self.annotation_layers += usize::from(matches!(kind, LayerKind::AnnotatedRegion { .. }));
        self.leader_layers += usize::from(matches!(kind, LayerKind::Leader { .. }));
        let generation = next_generation(&mut self.next_generation);
        let id = LayerId(self.layers.insert(Layer {
            kind,
            children: Vec::new(),
            surface_partition: None,
            generation,
            clip_cache: None,
        }));
        self.diagnostics.layers += 1;
        id
    }
    pub fn remove(&mut self, id: LayerId) {
        if let Some(layer) = self.layers.remove(id.0) {
            self.annotation_layers -=
                usize::from(matches!(layer.kind, LayerKind::AnnotatedRegion { .. }));
            self.leader_layers -= usize::from(matches!(layer.kind, LayerKind::Leader { .. }));
            // A removed leader stops resolving only when it owned the
            // publication: its shared link state would otherwise outlive it
            // and followers would track a ghost. A non-owner's removal must
            // not disturb the winner.
            if let LayerKind::Leader {
                link, publisher, ..
            } = &layer.kind
            {
                link.clear_if_owned_by(publisher);
            }
            self.diagnostics.layers -= 1;
            if self.root == Some(id) {
                self.root = None;
            }
            // Children are pruned by their owners before removal in normal
            // widget unmounting; stale entries are ignored by flattening.
        }
    }
    pub fn set_children(&mut self, id: LayerId, children: Vec<LayerId>) {
        if let Some(layer) = self.layers.get_mut(id.0) {
            if layer.children == children {
                return;
            }
            layer.children = children;
            layer.generation = next_generation(&mut self.next_generation);
        }
    }

    /// Marks one retained layer subtree as detachable presentation content.
    /// The marker is renderer-neutral and does not alter layout, painting, or
    /// the retained layer topology.
    pub fn set_surface_partition(&mut self, id: LayerId, partition: Option<SurfacePartitionId>) {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return;
        };
        if layer.surface_partition == partition {
            return;
        }
        layer.surface_partition = partition;
    }

    /// Clears every detachable-surface marker. WidgetTree reapplies markers for
    /// the currently visible transient portals before flattening each frame.
    pub fn clear_surface_partitions(&mut self) {
        let ids = self
            .layers
            .iter()
            .filter_map(|(raw, layer)| layer.surface_partition.is_some().then_some(LayerId(raw)))
            .collect::<Vec<_>>();
        for id in ids {
            self.set_surface_partition(id, None);
        }
    }
    pub fn update_picture(&mut self, id: LayerId, display_list: DisplayList, bounds: Rect) {
        if let Some(layer) = self.layers.get_mut(id.0)
            && let LayerKind::Picture {
                display_list: current,
                bounds: current_bounds,
            } = &mut layer.kind
        {
            *current = Arc::new(display_list);
            *current_bounds = bounds;
            layer.generation = next_generation(&mut self.next_generation);
            self.diagnostics.picture_layers_repainted += 1;
        }
    }
    pub fn update_transform(&mut self, id: LayerId, transform: Transform) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::Transform { transform: current } = &mut layer.kind else {
            return false;
        };
        if *current == transform {
            return false;
        }
        *current = transform;
        layer.generation = next_generation(&mut self.next_generation);
        self.diagnostics.transform_updates += 1;
        true
    }
    pub fn update_clip(&mut self, id: LayerId, rect: Rect) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::ClipRect { rect: current } = &mut layer.kind else {
            return false;
        };
        if *current == rect {
            return false;
        }
        *current = rect;
        layer.clip_cache = None;
        layer.generation = next_generation(&mut self.next_generation);
        self.diagnostics.clip_updates += 1;
        true
    }
    pub fn update_clip_rrect(&mut self, id: LayerId, rrect: RRect) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::ClipRRect { rrect: current } = &mut layer.kind else {
            return false;
        };
        if *current == rrect {
            return false;
        }
        *current = rrect;
        layer.clip_cache = None;
        layer.generation = next_generation(&mut self.next_generation);
        self.diagnostics.clip_updates += 1;
        true
    }
    pub fn update_clip_oval(&mut self, id: LayerId, rect: Rect) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::ClipOval { rect: current } = &mut layer.kind else {
            return false;
        };
        if *current == rect {
            return false;
        }
        *current = rect;
        layer.clip_cache = None;
        layer.generation = next_generation(&mut self.next_generation);
        self.diagnostics.clip_updates += 1;
        true
    }
    pub fn update_clip_path(&mut self, id: LayerId, path: Arc<Path>, fill_rule: FillRule) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::ClipPath {
            path: current_path,
            fill_rule: current_rule,
        } = &mut layer.kind
        else {
            return false;
        };
        if **current_path == *path && *current_rule == fill_rule {
            return false;
        }
        *current_path = path;
        *current_rule = fill_rule;
        layer.clip_cache = None;
        layer.generation = next_generation(&mut self.next_generation);
        self.diagnostics.clip_updates += 1;
        true
    }
    /// Updates only the group alpha. This deliberately does not change the
    /// content generation, allowing a cached offscreen texture to be reused
    /// while an opacity animation is ticking.
    pub fn update_opacity(&mut self, id: LayerId, alpha: f32) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::Opacity { alpha: current } = &mut layer.kind else {
            return false;
        };
        let alpha = normalize_opacity(alpha);
        if *current == alpha {
            return false;
        }
        *current = alpha;
        self.diagnostics.opacity_updates += 1;
        true
    }
    /// Updates Gaussian parameters without changing the retained source
    /// generation. A backend recomputes only the filtered result.
    pub fn update_blur(&mut self, id: LayerId, blur: GaussianBlur) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::Blur { blur: current } = &mut layer.kind else {
            return false;
        };
        let blur = GaussianBlur::new(blur.sigma_x, blur.sigma_y);
        if *current == blur {
            return false;
        }
        *current = blur;
        true
    }
    /// Updates shadow presentation properties without changing source pixels.
    /// Sigma invalidates the filtered mask; offset/color remain composite-only
    /// in GPU backends.
    pub fn update_drop_shadow(&mut self, id: LayerId, shadow: DropShadowEffect) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::DropShadow { shadow: current } = &mut layer.kind else {
            return false;
        };
        let shadow = DropShadowEffect::asymmetric(
            shadow.offset,
            shadow.sigma_x,
            shadow.sigma_y,
            shadow.color,
        );
        if *current == shadow {
            return false;
        }
        *current = shadow;
        true
    }
    pub fn update_color_filter(&mut self, id: LayerId, filter: ColorFilter) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::ColorFilter { filter: current } = &mut layer.kind else {
            return false;
        };
        if **current == filter {
            return false;
        }
        **current = filter;
        true
    }
    pub fn update_blend(&mut self, id: LayerId, mode: BlendMode) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::Blend { mode: current } = &mut layer.kind else {
            return false;
        };
        if *current == mode {
            return false;
        }
        *current = mode;
        true
    }
    pub fn update_shader_mask(
        &mut self,
        id: LayerId,
        shader: Brush,
        blend_mode: BlendMode,
        mask_size: Size,
        mask_transform: Transform,
    ) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::ShaderMask {
            shader: current_shader,
            blend_mode: current_mode,
            mask_size: current_size,
            mask_transform: current_transform,
        } = &mut layer.kind
        else {
            return false;
        };
        if **current_shader == shader
            && *current_mode == blend_mode
            && *current_size == mask_size
            && **current_transform == mask_transform
        {
            return false;
        }
        **current_shader = shader;
        *current_mode = blend_mode;
        *current_size = mask_size;
        **current_transform = mask_transform;
        layer.generation = next_generation(&mut self.next_generation);
        true
    }
    pub fn update_shader_mask_blend(&mut self, id: LayerId, blend_mode: BlendMode) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::ShaderMask {
            blend_mode: current,
            ..
        } = &mut layer.kind
        else {
            return false;
        };
        if *current == blend_mode {
            return false;
        }
        *current = blend_mode;
        layer.generation = next_generation(&mut self.next_generation);
        true
    }
    pub fn update_backdrop_filter(
        &mut self,
        id: LayerId,
        blur: GaussianBlur,
        blend_mode: BlendMode,
        enabled: bool,
    ) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::BackdropFilter {
            blur: current_blur,
            blend_mode: current_mode,
            enabled: current_enabled,
        } = &mut layer.kind
        else {
            return false;
        };
        let blur = GaussianBlur::new(blur.sigma_x, blur.sigma_y);
        if *current_blur == blur && *current_mode == blend_mode && *current_enabled == enabled {
            return false;
        }
        *current_blur = blur;
        *current_mode = blend_mode;
        *current_enabled = enabled;
        layer.generation = next_generation(&mut self.next_generation);
        true
    }
    pub fn update_annotated_region(
        &mut self,
        id: LayerId,
        annotation: Annotation,
        sized: bool,
        size: Size,
    ) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::AnnotatedRegion {
            annotation: current_annotation,
            sized: current_sized,
            size: current_size,
        } = &mut layer.kind
        else {
            return false;
        };
        if *current_annotation == annotation && *current_sized == sized && *current_size == size {
            return false;
        }
        *current_annotation = annotation;
        *current_sized = sized;
        *current_size = size;
        layer.generation = next_generation(&mut self.next_generation);
        true
    }
    pub fn update_leader(&mut self, id: LayerId, link: LayerLink, size: Size) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::Leader {
            link: current_link,
            size: current_size,
            publisher,
        } = &mut layer.kind
        else {
            return false;
        };
        if *current_link == link && *current_size == size {
            return false;
        }
        // The rebound layer releases only its own publication; a non-owner
        // rebind must not clear the winner it never displaced.
        current_link.clear_if_owned_by(publisher);
        *current_link = link;
        *current_size = size;
        layer.generation = next_generation(&mut self.next_generation);
        true
    }
    pub fn update_leader_size(&mut self, id: LayerId, size: Size) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::Leader { size: current, .. } = &mut layer.kind else {
            return false;
        };
        if *current == size {
            return false;
        }
        *current = size;
        layer.generation = next_generation(&mut self.next_generation);
        true
    }
    pub fn update_follower(&mut self, id: LayerId, follower: FollowerLayer) -> bool {
        let Some(layer) = self.layers.get_mut(id.0) else {
            return false;
        };
        let LayerKind::Follower(current) = &mut layer.kind else {
            return false;
        };
        if *current == follower {
            return false;
        }
        *current = follower;
        layer.generation = next_generation(&mut self.next_generation);
        true
    }
    /// World-space logical bounds captured by the most recent [`Self::flatten`]
    /// call. This keeps coordinate diagnostics out of the renderer hot path.
    #[must_use]
    pub fn flattened_pictures(&self) -> &[FlattenedPicture] {
        &self.flattened_pictures
    }
    #[must_use]
    pub fn flattened_annotations(&self) -> &[FlattenedAnnotation] {
        &self.flattened_annotations
    }
    /// Returns the front-most annotation of type `T` at `point`. Annotation
    /// lookup follows layer paint order, honours ancestor clips, and treats
    /// `sized: false` regions as covering the entire clipped subtree.
    #[must_use]
    pub fn find_annotation<T: Any + Clone>(&self, point: Offset) -> Option<T> {
        self.flattened_annotations.iter().find_map(|entry| {
            let in_bounds = entry
                .world_bounds
                .is_none_or(|bounds| bounds.contains(point));
            in_bounds.then(|| entry.annotation.cloned::<T>()).flatten()
        })
    }
    #[must_use]
    pub fn find_annotations<T: Any + Clone>(&self, point: Offset) -> Vec<T> {
        self.flattened_annotations
            .iter()
            .filter_map(|entry| {
                let in_bounds = entry
                    .world_bounds
                    .is_none_or(|bounds| bounds.contains(point));
                in_bounds.then(|| entry.annotation.cloned::<T>()).flatten()
            })
            .collect()
    }
    #[must_use]
    pub fn flatten(&mut self) -> DisplayList {
        let mut out = DisplayList::new();
        self.flattened_pictures.clear();
        self.flattened_annotations.clear();
        if let Some(root) = self.root {
            // Leader publication runs as its own pass before any follower
            // resolves, so flatten order cannot strand a follower behind
            // its leader: paint, hit testing, and semantics all read the
            // same post-publication state.
            self.publish_leader_links();
            self.flatten_layer(root, Transform::IDENTITY, None, &mut out);
            if self.annotation_layers > 0 {
                self.collect_annotations(root, Transform::IDENTITY, None);
            }
        }
        out
    }
    /// Exact world-space clip command for one clip layer. Translation-only
    /// worlds keep every shape analytic; uniform scales additionally keep
    /// rounded corners analytic with scaled radii. Anything a shape cannot
    /// represent falls back to an equivalent tolerance-flattened path,
    /// which stays exact for every affine map. Culling still uses the
    /// bounding box from `clip_world_bounds`: conservative there, never
    /// the emitted shape.
    fn clip_command(&mut self, id: LayerId, kind: &LayerKind, world: Transform) -> PaintCommand {
        match kind {
            LayerKind::ClipRect { rect, .. } => match clip_space(world) {
                ClipSpace::Translation | ClipSpace::Scale { .. } => PaintCommand::PushClip {
                    rect: world.transform_rect_bbox(*rect),
                },
                ClipSpace::General => {
                    let rect = *rect;
                    PaintCommand::PushClipPath {
                        path: self.memoized_fallback_path(id, move || rect_as_path(rect), world),
                        fill_rule: FillRule::NonZero,
                    }
                }
            },
            LayerKind::ClipRRect { rrect, .. } => match clip_space(world) {
                ClipSpace::Translation => PaintCommand::PushClipRRect {
                    rrect: RRect::new(world.transform_rect_bbox(rrect.rect), rrect.radii),
                },
                // Positive uniform scales keep corners circular; anything
                // else (mirrors, nonuniform scales) would move corner
                // ownership, so those shapes fall back to a path.
                ClipSpace::Scale { x, y } if x > 0. && x == y => PaintCommand::PushClipRRect {
                    rrect: RRect::new(world.transform_rect_bbox(rrect.rect), rrect.radii.scaled(x)),
                },
                _ => {
                    let (rect, radii) = (rrect.rect, rrect.radii);
                    PaintCommand::PushClipPath {
                        path: self.memoized_fallback_path(
                            id,
                            move || rrect_as_path(rect, radii, fallback_tolerance(world)),
                            world,
                        ),
                        fill_rule: FillRule::NonZero,
                    }
                }
            },
            LayerKind::ClipOval { rect, .. } => match clip_space(world) {
                // Axis-aligned scales keep ovals exact through the box.
                ClipSpace::Translation | ClipSpace::Scale { .. } => PaintCommand::PushClipOval {
                    rect: world.transform_rect_bbox(*rect),
                },
                ClipSpace::General => {
                    let rect = *rect;
                    PaintCommand::PushClipPath {
                        path: self.memoized_fallback_path(
                            id,
                            move || ellipse_as_path(rect, fallback_tolerance(world)),
                            world,
                        ),
                        fill_rule: FillRule::NonZero,
                    }
                }
            },
            LayerKind::ClipPath {
                path, fill_rule, ..
            } => PaintCommand::PushClipPath {
                path: self.memoized_clip_path(id, path, world),
                fill_rule: *fill_rule,
            },
            _ => unreachable!("clip emitter received a non-clip layer"),
        }
    }
    /// World-resolved path for a ClipPath layer, reusing the memoized
    /// resolution while the world, path, and rule stand still. Identity
    /// worlds reuse the supplied arc directly so static clips never mint
    /// replacement identities (and backend re-tessellations) per flatten.
    fn memoized_clip_path(&mut self, id: LayerId, path: &Arc<Path>, world: Transform) -> Arc<Path> {
        if world == Transform::IDENTITY {
            return path.clone();
        }
        let owned = path.clone();
        self.memoized_fallback_path(id, move || owned.as_ref().clone(), world)
    }
    /// World-resolved fallback path shared by every clip variant that
    /// emits one. The builder runs only on a memo miss; hits reuse the
    /// retained arc, so unchanged geometry and transform keep one path
    /// identity (and one backend mesh) across flattens. Geometry updates
    /// reset the memo through their own update path, and removal drops
    /// it with the layer.
    fn memoized_fallback_path(
        &mut self,
        id: LayerId,
        build: impl FnOnce() -> Path,
        world: Transform,
    ) -> Arc<Path> {
        if let Some(layer) = self.layers.get(id.0)
            && let Some(memo) = layer.clip_cache.as_ref()
            && memo.world == world
        {
            return memo.path.clone();
        }
        let resolved = Arc::new(build().transformed(world));
        if let Some(layer) = self.layers.get_mut(id.0) {
            layer.clip_cache = Some(Box::new(ResolvedClipPath {
                world,
                path: resolved.clone(),
            }));
        }
        resolved
    }
    fn flatten_layer(
        &mut self,
        id: LayerId,
        world_transform: Transform,
        clip: Option<Rect>,
        out: &mut DisplayList,
    ) {
        let partition = self
            .layers
            .get(id.0)
            .and_then(|layer| layer.surface_partition);
        if let Some(id) = partition {
            out.push(PaintCommand::PushSurfacePartition { id });
        }
        self.flatten_layer_contents(id, world_transform, clip, out);
        if partition.is_some() {
            out.push(PaintCommand::PopSurfacePartition);
        }
    }

    /// Visits `id`'s children (back to front when `reverse`) without cloning
    /// its child list: ids are staged on a reusable stack so `visit` may
    /// recurse with the tree borrowed mutably.
    fn visit_children(
        &mut self,
        id: LayerId,
        reverse: bool,
        mut visit: impl FnMut(&mut Self, LayerId),
    ) {
        let start = self.child_stack.len();
        if let Some(layer) = self.layers.get(id.0) {
            self.child_stack.extend_from_slice(&layer.children);
        }
        let end = self.child_stack.len();
        for index in start..end {
            let child = self.child_stack[if reverse {
                start + end - 1 - index
            } else {
                index
            }];
            visit(self, child);
        }
        self.child_stack.truncate(start);
    }

    fn flatten_layer_contents(
        &mut self,
        id: LayerId,
        world_transform: Transform,
        clip: Option<Rect>,
        out: &mut DisplayList,
    ) {
        let Some(kind) = self.layers.get(id.0).map(|layer| layer.kind.clone()) else {
            return;
        };
        match kind {
            LayerKind::Picture {
                display_list,
                bounds,
            } => {
                let world = world_transform.transform_rect_bbox(bounds);
                if clip.is_some_and(|active| !active.intersects(world)) {
                    self.diagnostics.layers_culled += 1;
                    return;
                }
                self.flattened_pictures.push(FlattenedPicture {
                    layer: id,
                    local_bounds: bounds,
                    world_bounds: world,
                    active_clip: clip,
                });
                out.push(PaintCommand::PushTransform {
                    transform: world_transform,
                });
                out.extend_from(&display_list);
                out.push(PaintCommand::PopTransform);
            }
            LayerKind::Transform { transform: local } => {
                let next = world_transform.then(local);
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, next, clip, out)
                });
            }
            LayerKind::ClipRect { .. }
            | LayerKind::ClipRRect { .. }
            | LayerKind::ClipOval { .. }
            | LayerKind::ClipPath { .. } => {
                // Conservative world bounds drive culling; the emitted
                // command carries the exact shape (or its path fallback),
                // never the box.
                let Some(shape_bounds) = clip_world_bounds(&kind, world_transform) else {
                    self.diagnostics.layers_culled += 1;
                    return;
                };
                let next_clip = match clip {
                    Some(active) => active.intersection(shape_bounds),
                    None => Some(shape_bounds),
                };
                if next_clip.is_none() {
                    self.diagnostics.layers_culled += 1;
                    return;
                }
                out.push(self.clip_command(id, &kind, world_transform));
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, next_clip, out)
                });
                out.push(PaintCommand::PopClip);
            }
            LayerKind::Opacity { alpha } => {
                let bounds = self
                    .subtree_bounds(id, world_transform)
                    .unwrap_or_else(|| Rect::from_origin_size(Offset::ZERO, Size::ZERO));
                out.push(PaintCommand::PushOpacity {
                    layer: id,
                    alpha,
                    generation: self.subtree_generation(id),
                    bounds,
                });
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, clip, out)
                });
                out.push(PaintCommand::PopOpacity);
            }
            LayerKind::Blur { blur } => {
                let bounds = self
                    .subtree_bounds(id, world_transform)
                    .unwrap_or_else(|| Rect::from_origin_size(Offset::ZERO, Size::ZERO));
                out.push(PaintCommand::PushBlur {
                    layer: id,
                    blur,
                    generation: self.subtree_generation(id),
                    bounds,
                });
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, clip, out)
                });
                out.push(PaintCommand::PopEffect);
            }
            LayerKind::DropShadow { shadow } => {
                let bounds = self
                    .subtree_bounds(id, world_transform)
                    .unwrap_or_else(|| Rect::from_origin_size(Offset::ZERO, Size::ZERO));
                out.push(PaintCommand::PushDropShadow {
                    layer: id,
                    shadow,
                    generation: self.subtree_generation(id),
                    bounds,
                });
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, clip, out)
                });
                out.push(PaintCommand::PopEffect);
            }
            LayerKind::ColorFilter { filter } => {
                let bounds = self
                    .subtree_bounds(id, world_transform)
                    .unwrap_or_else(|| Rect::from_origin_size(Offset::ZERO, Size::ZERO));
                out.push(PaintCommand::PushColorFilter {
                    layer: id,
                    filter: *filter,
                    generation: self.subtree_generation(id),
                    bounds,
                });
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, clip, out)
                });
                out.push(PaintCommand::PopEffect);
            }
            LayerKind::Blend { mode } => {
                let bounds = self
                    .subtree_bounds(id, world_transform)
                    .unwrap_or_else(|| Rect::from_origin_size(Offset::ZERO, Size::ZERO));
                out.push(PaintCommand::PushBlend {
                    layer: id,
                    mode,
                    generation: self.subtree_generation(id),
                    bounds,
                });
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, clip, out)
                });
                out.push(PaintCommand::PopEffect);
            }
            LayerKind::ShaderMask {
                shader,
                blend_mode,
                mask_size,
                mask_transform,
            } => {
                let bounds = self
                    .subtree_bounds(id, world_transform)
                    .unwrap_or_else(|| Rect::from_origin_size(Offset::ZERO, Size::ZERO));
                if !bounds.size.width.is_finite()
                    || !bounds.size.height.is_finite()
                    || bounds.size.width <= 0.
                    || bounds.size.height <= 0.
                {
                    return;
                }
                out.push(PaintCommand::PushShaderMask {
                    layer: id,
                    shader: *shader,
                    blend_mode,
                    mask_size,
                    mask_transform: *mask_transform,
                    generation: self.subtree_generation(id),
                    bounds,
                });
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, clip, out)
                });
                out.push(PaintCommand::PopEffect);
            }
            LayerKind::BackdropFilter {
                blur,
                blend_mode,
                enabled,
            } => {
                if !enabled || (blur.sigma_x <= f32::EPSILON && blur.sigma_y <= f32::EPSILON) {
                    self.visit_children(id, false, |tree, child| {
                        tree.flatten_layer(child, world_transform, clip, out)
                    });
                    return;
                }
                let bounds = self
                    .subtree_bounds(id, world_transform)
                    .unwrap_or_else(|| Rect::from_origin_size(Offset::ZERO, Size::ZERO));
                out.push(PaintCommand::PushBackdropFilter {
                    layer: id,
                    blur,
                    blend_mode,
                    enabled,
                    generation: self.subtree_generation(id),
                    bounds,
                });
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, clip, out)
                });
                out.push(PaintCommand::PopEffect);
            }
            LayerKind::AnnotatedRegion { .. } => {
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, clip, out)
                });
            }
            LayerKind::Leader { .. } => {
                // Publication already ran in the dedicated pass above; the
                // flatten walk only positions children here.
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, world_transform, clip, out)
                });
            }
            LayerKind::Follower(follower) => {
                let Some(next_transform) = self.follower_transform(world_transform, &follower)
                else {
                    return;
                };
                self.visit_children(id, false, |tree, child| {
                    tree.flatten_layer(child, next_transform, clip, out)
                });
            }
        }
    }
    fn clear_link_states(&self, id: LayerId) {
        let Some(layer) = self.layers.get(id.0) else {
            return;
        };
        if let LayerKind::Leader { link, .. } = &layer.kind {
            link.clear_publication();
        }
        for child in layer.children.iter() {
            self.clear_link_states(*child);
        }
    }
    /// Republishes leader links from current layer state for readers that
    /// run before `flatten` (notably semantic collection, which the frame
    /// runs pre-paint). Same pass `flatten` runs, so follower visibility
    /// reflects this frame's layout instead of the previous paint;
    /// genuinely hidden leaders still stay unpublished. Idempotent.
    pub fn publish_leader_links(&mut self) {
        if self.leader_layers == 0 {
            return;
        }
        if let Some(root) = self.root {
            self.clear_link_states(root);
            self.publish_resolved_leaders(root);
        }
    }
    /// Publishes every reachable leader in dependency order: a leader
    /// nested under linked followers resolves through the same follower
    /// projection the flatten walk uses, so nested publications land in
    /// the resolved frame rather than the layout frame. Leaders are
    /// attempted once each in paint order with cycle-guarded recursion,
    /// so chains and cycles always terminate; the first resolvable
    /// leader per link wins and anything culled or cyclic stays
    /// unpublished for its followers to treat as unlinked.
    fn publish_resolved_leaders(&mut self, root: LayerId) {
        self.diagnostics.leader_publish_passes += 1;
        let mut parents = HashMap::new();
        let mut leaders = Vec::new();
        self.collect_publish_state(root, &mut parents, &mut leaders);
        if leaders.is_empty() {
            return;
        }
        let mut states = HashMap::new();
        let mut published = 0;
        for index in 0..leaders.len() {
            published += self.ensure_published(index, &leaders, &parents, &mut states) as u64;
        }
        self.diagnostics.leaders_published += published;
    }
    fn collect_publish_state(
        &self,
        id: LayerId,
        parents: &mut HashMap<LayerId, LayerId>,
        leaders: &mut Vec<LeaderRecord>,
    ) {
        let Some(layer) = self.layers.get(id.0) else {
            return;
        };
        if let LayerKind::Leader {
            link,
            size,
            publisher,
        } = &layer.kind
        {
            leaders.push(LeaderRecord {
                id,
                link: link.clone(),
                size: *size,
                publisher: publisher.clone(),
                generation: layer.generation,
            });
        }
        for child in layer.children.iter() {
            parents.entry(*child).or_insert(id);
            self.collect_publish_state(*child, parents, leaders);
        }
    }
    fn ensure_published(
        &self,
        index: usize,
        leaders: &[LeaderRecord],
        parents: &HashMap<LayerId, LayerId>,
        states: &mut HashMap<LayerId, PublishState>,
    ) -> bool {
        let id = leaders[index].id;
        match states.get(&id) {
            Some(PublishState::Published) => return true,
            Some(PublishState::Unresolvable) => return false,
            // A dependency cycle: the revisit reports failure so the
            // depender treats the link as currently unlinked. The outer
            // attempt still finishes and overwrites this marker with its
            // own outcome, so a leader whose only dependent is itself
            // resolves through the unlinked-follower rule below.
            Some(PublishState::InProgress) => {
                states.insert(id, PublishState::Unresolvable);
                return false;
            }
            None => {}
        }
        states.insert(id, PublishState::InProgress);
        let published = match self.leader_context(index, leaders, parents, states) {
            Some(world) => {
                let record = &leaders[index];
                record.link.publish(
                    record.publisher.clone(),
                    world,
                    record.size,
                    record.generation,
                );
                true
            }
            None => false,
        };
        states.insert(
            id,
            if published {
                PublishState::Published
            } else {
                PublishState::Unresolvable
            },
        );
        published
    }
    /// Resolves one leader's publication frame by folding its ancestor
    /// chain with the same rules the flatten walk applies: transforms
    /// compose, followers resolve through the shared projection (ensuring
    /// their links' winners first), showing-but-unlinked followers keep
    /// the parent frame, and anything the flatten walk would cull —
    /// hidden followers, emptied clips, singular inversions — resolves
    /// to nothing so the leader stays unpublished exactly where flatten
    /// would never visit it.
    fn leader_context(
        &self,
        index: usize,
        leaders: &[LeaderRecord],
        parents: &HashMap<LayerId, LayerId>,
        states: &mut HashMap<LayerId, PublishState>,
    ) -> Option<Transform> {
        let mut chain = vec![leaders[index].id];
        while let Some(parent) = chain.last().and_then(|id| parents.get(id)) {
            chain.push(*parent);
        }
        let mut world = Transform::IDENTITY;
        let mut clip: Option<Rect> = None;
        for node in chain.iter().rev() {
            let layer = self.layers.get(node.0)?;
            match &layer.kind {
                LayerKind::Transform { transform } => {
                    world = world.then(*transform);
                }
                LayerKind::Follower(follower) => {
                    let link = &follower.link;
                    if link.leader_transform().is_none() {
                        // Publish the dependency first: a nested leader
                        // waits for its ancestor follower's link, trying
                        // candidates in paint order until one publishes.
                        for dependency in 0..leaders.len() {
                            if leaders[dependency].link == *link {
                                self.ensure_published(dependency, leaders, parents, states);
                                if link.leader_transform().is_some() {
                                    break;
                                }
                            }
                        }
                    }
                    match link.leader_transform() {
                        Some(_) => {
                            world = self.follower_transform(world, follower)?;
                        }
                        None if follower.show_when_unlinked => {}
                        None => return None,
                    }
                }
                LayerKind::ClipRect { .. }
                | LayerKind::ClipRRect { .. }
                | LayerKind::ClipOval { .. }
                | LayerKind::ClipPath { .. } => {
                    let shape = clip_world_bounds(&layer.kind, world)?;
                    clip = match clip {
                        Some(active) => active.intersection(shape),
                        None => Some(shape),
                    };
                    // An emptied clip culls the subtree: flatten never
                    // visits leaders beneath it, so neither does this pass.
                    clip?;
                }
                _ => {}
            }
        }
        Some(world)
    }
    fn follower_transform(
        &self,
        world_transform: Transform,
        follower: &FollowerLayer,
    ) -> Option<Transform> {
        let FollowerLayer {
            link,
            show_when_unlinked,
            offset,
            target_anchor,
            follower_anchor,
            size,
        } = follower;
        let Some(leader_transform) = link.leader_transform() else {
            return show_when_unlinked.then_some(world_transform);
        };
        let leader_size = link.leader_size().unwrap_or(Size::ZERO);
        let desired_anchor =
            resolve_follower_target(leader_transform, leader_size, *target_anchor, *offset);
        let desired_local = world_transform.inverse_transform_point(desired_anchor)?;
        let local_delta = desired_local - follower_anchor.along_size(*size);
        Some(world_transform.then(Transform::translation(local_delta)))
    }
    fn collect_annotations(&mut self, id: LayerId, world_transform: Transform, clip: Option<Rect>) {
        let Some(kind) = self.layers.get(id.0).map(|layer| layer.kind.clone()) else {
            return;
        };
        match kind {
            LayerKind::Transform { transform } => {
                let next = world_transform.then(transform);
                self.visit_children(id, false, |tree, child| {
                    tree.collect_annotations(child, next, clip)
                });
            }
            LayerKind::ClipRect { rect, .. } => {
                let world = world_transform.transform_rect_bbox(rect);
                let next_clip = match clip {
                    Some(current) => current.intersection(world),
                    None => Some(world),
                };
                if next_clip.is_none() {
                    return;
                }
                self.visit_children(id, false, |tree, child| {
                    tree.collect_annotations(child, world_transform, next_clip)
                });
            }
            LayerKind::ClipRRect { .. }
            | LayerKind::ClipOval { .. }
            | LayerKind::ClipPath { .. } => {
                let Some(world) = clip_world_bounds(&kind, world_transform) else {
                    return;
                };
                let next_clip = match clip {
                    Some(current) => current.intersection(world),
                    None => Some(world),
                };
                if next_clip.is_none() {
                    return;
                }
                self.visit_children(id, false, |tree, child| {
                    tree.collect_annotations(child, world_transform, next_clip)
                });
            }
            LayerKind::Follower(follower) => {
                let Some(next) = self.follower_transform(world_transform, &follower) else {
                    return;
                };
                self.visit_children(id, false, |tree, child| {
                    tree.collect_annotations(child, next, clip)
                });
            }
            LayerKind::AnnotatedRegion {
                annotation,
                sized,
                size,
            } => {
                // Container layers are painted in child order, but annotation
                // lookup walks visually front-to-back. Visit children in
                // reverse order, then append this layer's own annotation.
                self.visit_children(id, true, |tree, child| {
                    tree.collect_annotations(child, world_transform, clip)
                });
                let region =
                    world_transform.transform_rect_bbox(Rect::from_origin_size(Offset::ZERO, size));
                let world_bounds = if sized {
                    match clip {
                        Some(active) => active.intersection(region),
                        None => Some(region),
                    }
                } else {
                    clip
                };
                if world_bounds
                    .is_none_or(|bounds| bounds.size.width > 0. && bounds.size.height > 0.)
                {
                    self.flattened_annotations.push(FlattenedAnnotation {
                        annotation,
                        world_bounds,
                    });
                }
            }
            LayerKind::Picture { .. }
            | LayerKind::Opacity { .. }
            | LayerKind::Blur { .. }
            | LayerKind::DropShadow { .. }
            | LayerKind::ColorFilter { .. }
            | LayerKind::Blend { .. }
            | LayerKind::ShaderMask { .. }
            | LayerKind::BackdropFilter { .. }
            | LayerKind::Leader { .. } => {
                self.visit_children(id, false, |tree, child| {
                    tree.collect_annotations(child, world_transform, clip)
                });
            }
        }
    }
    fn subtree_generation(&self, id: LayerId) -> u64 {
        let Some(layer) = self.layers.get(id.0) else {
            return 0;
        };
        let mut value = layer.generation.wrapping_mul(0x9e37_79b9_7f4a_7c15);
        for child in &layer.children {
            // An opacity layer's own alpha is intentionally excluded from
            // its cache key: changing it only changes the final composite.
            // When that layer is nested inside another isolated group,
            // however, its composite is part of the parent's pixels. Include
            // the child's alpha at this boundary so an inner fade invalidates
            // the outer group's cached texture without invalidating the
            // inner group's own content target.
            if let Some(child_layer) = self.layers.get(child.0)
                && let LayerKind::Opacity { alpha } = &child_layer.kind
            {
                value = value.rotate_left(11) ^ u64::from(alpha.to_bits());
            }
            if let Some(child_layer) = self.layers.get(child.0) {
                match &child_layer.kind {
                    LayerKind::Blur { blur } => {
                        value = value.rotate_left(13)
                            ^ u64::from(blur.sigma_x.to_bits())
                            ^ u64::from(blur.sigma_y.to_bits()).rotate_left(17);
                    }
                    LayerKind::DropShadow { shadow } => {
                        value = value.rotate_left(13)
                            ^ u64::from(shadow.offset.x.to_bits())
                            ^ u64::from(shadow.offset.y.to_bits()).rotate_left(7)
                            ^ u64::from(shadow.sigma_x.to_bits()).rotate_left(17)
                            ^ u64::from(shadow.sigma_y.to_bits()).rotate_left(23)
                            ^ u64::from(shadow.color.red)
                            ^ (u64::from(shadow.color.green) << 8)
                            ^ (u64::from(shadow.color.blue) << 16)
                            ^ (u64::from(shadow.color.alpha) << 24);
                    }
                    LayerKind::ColorFilter { filter } => {
                        for (index, bits) in filter.to_matrix().map(f32::to_bits).iter().enumerate()
                        {
                            value ^= u64::from(*bits).rotate_left((index as u32 % 31) + 1);
                        }
                    }
                    LayerKind::Blend { mode } => {
                        value = value.rotate_left(13) ^ u64::from(mode.code());
                    }
                    LayerKind::ShaderMask {
                        shader,
                        blend_mode,
                        mask_size,
                        mask_transform,
                    } => {
                        value = value.rotate_left(13)
                            ^ brush_generation(shader)
                            ^ u64::from(blend_mode.code())
                            ^ u64::from(mask_size.width.to_bits()).rotate_left(9)
                            ^ u64::from(mask_size.height.to_bits()).rotate_left(15)
                            ^ transform_generation(**mask_transform);
                    }
                    LayerKind::BackdropFilter {
                        blur,
                        blend_mode,
                        enabled,
                    } => {
                        value = value.rotate_left(13)
                            ^ u64::from(blur.sigma_x.to_bits())
                            ^ u64::from(blur.sigma_y.to_bits()).rotate_left(7)
                            ^ u64::from(blend_mode.code())
                            ^ u64::from(*enabled as u8);
                    }
                    LayerKind::AnnotatedRegion {
                        annotation: _,
                        sized,
                        size,
                    } => {
                        value = value.rotate_left(13)
                            ^ u64::from(*sized as u8)
                            ^ u64::from(size.width.to_bits()).rotate_left(9)
                            ^ u64::from(size.height.to_bits()).rotate_left(15);
                    }
                    LayerKind::Leader { link, size, .. } => {
                        value = value.rotate_left(13)
                            ^ link.leader_generation()
                            ^ u64::from(size.width.to_bits()).rotate_left(9)
                            ^ u64::from(size.height.to_bits()).rotate_left(15);
                    }
                    LayerKind::Follower(follower) => {
                        value = value.rotate_left(13)
                            ^ follower.link.leader_generation()
                            ^ u64::from(follower.show_when_unlinked as u8)
                            ^ u64::from(follower.offset.x.to_bits())
                            ^ u64::from(follower.offset.y.to_bits()).rotate_left(7)
                            ^ u64::from(follower.target_anchor.x.to_bits()).rotate_left(13)
                            ^ u64::from(follower.target_anchor.y.to_bits()).rotate_left(17)
                            ^ u64::from(follower.follower_anchor.x.to_bits()).rotate_left(21)
                            ^ u64::from(follower.follower_anchor.y.to_bits()).rotate_left(25)
                            ^ u64::from(follower.size.width.to_bits()).rotate_left(29)
                            ^ u64::from(follower.size.height.to_bits()).rotate_left(31);
                    }
                    _ => {}
                }
            }
            value = value.rotate_left(7) ^ self.subtree_generation(*child);
        }
        value
    }
    fn subtree_bounds(&self, id: LayerId, world_transform: Transform) -> Option<Rect> {
        let layer = self.layers.get(id.0)?;
        match &layer.kind {
            LayerKind::Picture { bounds, .. } => Some(world_transform.transform_rect_bbox(*bounds)),
            LayerKind::Transform { transform: local } => layer
                .children
                .iter()
                .filter_map(|child| self.subtree_bounds(*child, world_transform.then(*local)))
                .reduce(union_rect),
            LayerKind::ClipRect { rect, .. } => {
                let world = world_transform.transform_rect_bbox(*rect);
                layer
                    .children
                    .iter()
                    .filter_map(|child| self.subtree_bounds(*child, world_transform))
                    .reduce(union_rect)
                    .and_then(|bounds| bounds.intersection(world))
            }
            LayerKind::ClipRRect { .. }
            | LayerKind::ClipOval { .. }
            | LayerKind::ClipPath { .. } => {
                let world = clip_world_bounds(&layer.kind, world_transform)?;
                layer
                    .children
                    .iter()
                    .filter_map(|child| self.subtree_bounds(*child, world_transform))
                    .reduce(union_rect)
                    .and_then(|bounds| bounds.intersection(world))
            }
            LayerKind::Opacity { .. } => layer
                .children
                .iter()
                .filter_map(|child| self.subtree_bounds(*child, world_transform))
                .reduce(union_rect),
            LayerKind::Blur { .. } | LayerKind::DropShadow { .. } => layer
                .children
                .iter()
                .filter_map(|child| self.subtree_bounds(*child, world_transform))
                .reduce(union_rect),
            LayerKind::ColorFilter { .. } | LayerKind::Blend { .. } => layer
                .children
                .iter()
                .filter_map(|child| self.subtree_bounds(*child, world_transform))
                .reduce(union_rect),
            LayerKind::ShaderMask { .. }
            | LayerKind::BackdropFilter { .. }
            | LayerKind::AnnotatedRegion { .. }
            | LayerKind::Leader { .. } => layer
                .children
                .iter()
                .filter_map(|child| self.subtree_bounds(*child, world_transform))
                .reduce(union_rect),
            LayerKind::Follower(follower) => {
                let next = self.follower_transform(world_transform, follower)?;
                layer
                    .children
                    .iter()
                    .filter_map(|child| self.subtree_bounds(*child, next))
                    .reduce(union_rect)
            }
        }
    }

    fn visual_subtree_bounds(&self, id: LayerId, world_transform: Transform) -> Option<Rect> {
        let layer = self.layers.get(id.0)?;
        let child_bounds = |tree: &Self, transform: Transform| {
            layer
                .children
                .iter()
                .filter_map(|child| tree.visual_subtree_bounds(*child, transform))
                .reduce(union_rect)
        };
        match &layer.kind {
            LayerKind::Picture { bounds, .. } => Some(world_transform.transform_rect_bbox(*bounds)),
            LayerKind::Transform { transform: local } => {
                child_bounds(self, world_transform.then(*local))
            }
            LayerKind::ClipRect { rect, .. } => {
                let world = world_transform.transform_rect_bbox(*rect);
                child_bounds(self, world_transform).and_then(|bounds| bounds.intersection(world))
            }
            LayerKind::ClipRRect { .. }
            | LayerKind::ClipOval { .. }
            | LayerKind::ClipPath { .. } => {
                let world = clip_world_bounds(&layer.kind, world_transform)?;
                child_bounds(self, world_transform).and_then(|bounds| bounds.intersection(world))
            }
            LayerKind::Opacity { .. }
            | LayerKind::ColorFilter { .. }
            | LayerKind::Blend { .. }
            | LayerKind::ShaderMask { .. }
            | LayerKind::BackdropFilter { .. }
            | LayerKind::AnnotatedRegion { .. }
            | LayerKind::Leader { .. } => child_bounds(self, world_transform),
            LayerKind::Blur { blur } => child_bounds(self, world_transform)
                .map(|bounds| blur_bounds(bounds, blur.sigma_x, blur.sigma_y)),
            LayerKind::DropShadow { shadow } => child_bounds(self, world_transform).map(|bounds| {
                drop_shadow_bounds(bounds, shadow.offset, shadow.sigma_x, shadow.sigma_y)
            }),
            LayerKind::Follower(follower) => {
                let next = self.follower_transform(world_transform, follower)?;
                child_bounds(self, next)
            }
        }
    }
    #[must_use]
    pub fn debug_tree(&self) -> String {
        let mut out = String::new();
        if let Some(root) = self.root {
            self.write_debug(root, 0, &mut out);
        }
        out
    }
    fn write_debug(&self, id: LayerId, depth: usize, out: &mut String) {
        self.write_debug_at(id, None, depth, Transform::IDENTITY, None, out);
    }
    fn write_debug_at(
        &self,
        id: LayerId,
        parent: Option<LayerId>,
        depth: usize,
        world_transform: Transform,
        clip: Option<Rect>,
        out: &mut String,
    ) {
        let Some(layer) = self.layers.get(id.0) else {
            return;
        };
        let indent = "  ".repeat(depth);
        let kind = match &layer.kind {
            LayerKind::Picture { bounds, .. } => format!(
                "Picture(local_bounds={bounds:?}, world_bounds={:?}, clip={clip:?})",
                world_transform.transform_rect_bbox(*bounds)
            ),
            LayerKind::Transform { transform } => {
                format!(
                    "Transform(local={:?}, world={:?})",
                    transform,
                    world_transform.then(*transform)
                )
            }
            LayerKind::ClipRect { rect, .. } => format!(
                "ClipRect(local={rect:?}, world={:?})",
                world_transform.transform_rect_bbox(*rect)
            ),
            LayerKind::ClipRRect { rrect, .. } => format!(
                "ClipRRect(local={rrect:?}, world={:?})",
                world_transform.transform_rect_bbox(rrect.rect)
            ),
            LayerKind::ClipOval { rect, .. } => format!(
                "ClipOval(local={rect:?}, world={:?})",
                world_transform.transform_rect_bbox(*rect)
            ),
            LayerKind::ClipPath { path, .. } => format!(
                "ClipPath(local_bounds={:?}, world={:?})",
                path.bounds(),
                clip_world_bounds(&layer.kind, world_transform)
            ),
            LayerKind::Opacity { alpha } => format!(
                "Opacity(alpha={alpha:.3}, bounds={:?}, generation={})",
                self.subtree_bounds(id, world_transform),
                self.subtree_generation(id)
            ),
            LayerKind::Blur { blur } => format!(
                "Blur(sigma=({:.3},{:.3}), bounds={:?}, generation={})",
                blur.sigma_x,
                blur.sigma_y,
                self.subtree_bounds(id, world_transform),
                self.subtree_generation(id)
            ),
            LayerKind::DropShadow { shadow } => format!(
                "DropShadow(sigma=({:.3},{:.3}), offset={:?}, bounds={:?}, generation={})",
                shadow.sigma_x,
                shadow.sigma_y,
                shadow.offset,
                self.subtree_bounds(id, world_transform),
                self.subtree_generation(id)
            ),
            LayerKind::ColorFilter { filter } => format!(
                "ColorFilter(matrix={:?}, bounds={:?}, generation={})",
                filter.to_matrix(),
                self.subtree_bounds(id, world_transform),
                self.subtree_generation(id)
            ),
            LayerKind::Blend { mode } => format!(
                "Blend(mode={mode:?}, bounds={:?}, generation={})",
                self.subtree_bounds(id, world_transform),
                self.subtree_generation(id)
            ),
            LayerKind::ShaderMask {
                blend_mode,
                mask_size,
                ..
            } => format!(
                "ShaderMask(blend_mode={blend_mode:?}, mask_size={mask_size:?}, bounds={:?}, generation={})",
                self.subtree_bounds(id, world_transform),
                self.subtree_generation(id)
            ),
            LayerKind::BackdropFilter {
                blur,
                blend_mode,
                enabled,
            } => format!(
                "BackdropFilter(sigma=({:.3},{:.3}), blend_mode={blend_mode:?}, enabled={enabled}, bounds={:?}, generation={})",
                blur.sigma_x,
                blur.sigma_y,
                self.subtree_bounds(id, world_transform),
                self.subtree_generation(id)
            ),
            LayerKind::AnnotatedRegion { sized, size, .. } => format!(
                "AnnotatedRegion(sized={sized}, size={size:?}, generation={})",
                self.subtree_generation(id)
            ),
            LayerKind::Leader { link, size, .. } => format!(
                "CompositedTransformTarget(size={size:?}, linked={}, generation={})",
                link.is_linked(),
                self.subtree_generation(id)
            ),
            LayerKind::Follower(FollowerLayer {
                show_when_unlinked,
                offset,
                target_anchor,
                follower_anchor,
                ..
            }) => format!(
                "CompositedTransformFollower(show_when_unlinked={show_when_unlinked}, offset={offset:?}, target_anchor={target_anchor:?}, follower_anchor={follower_anchor:?}, bounds={:?}, generation={})",
                self.subtree_bounds(id, world_transform),
                self.subtree_generation(id)
            ),
        };
        out.push_str(&format!("{indent}{id:?} parent={parent:?} {kind}\n"));
        let (next_translation, next_clip) = match &layer.kind {
            LayerKind::Picture { .. } => (world_transform, clip),
            LayerKind::Transform { transform: local } => (world_transform.then(*local), clip),
            LayerKind::ClipRect { rect, .. } => {
                let world = world_transform.transform_rect_bbox(*rect);
                (
                    world_transform,
                    Some(clip.map_or(world, |old| old.intersection(world).unwrap_or(world))),
                )
            }
            LayerKind::ClipRRect { .. }
            | LayerKind::ClipOval { .. }
            | LayerKind::ClipPath { .. } => {
                // An empty path keeps the incoming clip: this dump never
                // culls, it only narrows what children report.
                let narrowed = clip_world_bounds(&layer.kind, world_transform).map(|world| {
                    clip.map_or(world, |old| old.intersection(world).unwrap_or(world))
                });
                (world_transform, narrowed.or(clip))
            }
            LayerKind::Opacity { .. } => (world_transform, clip),
            LayerKind::Blur { .. } | LayerKind::DropShadow { .. } => (world_transform, clip),
            LayerKind::ColorFilter { .. } | LayerKind::Blend { .. } => (world_transform, clip),
            LayerKind::ShaderMask { .. }
            | LayerKind::BackdropFilter { .. }
            | LayerKind::AnnotatedRegion { .. }
            | LayerKind::Leader { .. } => (world_transform, clip),
            LayerKind::Follower(follower) => (
                self.follower_transform(world_transform, follower)
                    .unwrap_or(world_transform),
                clip,
            ),
        };
        for child in &layer.children {
            self.write_debug_at(
                *child,
                Some(id),
                depth + 1,
                next_translation,
                next_clip,
                out,
            );
        }
    }
}

fn brush_generation(brush: &Brush) -> u64 {
    match brush {
        Brush::Solid(color) => {
            u64::from(color.red)
                | (u64::from(color.green) << 8)
                | (u64::from(color.blue) << 16)
                | (u64::from(color.alpha) << 24)
        }
        Brush::LinearGradient(gradient) => {
            gradient.stops.id().get()
                ^ u64::from(gradient.start.x.to_bits()).rotate_left(7)
                ^ u64::from(gradient.start.y.to_bits()).rotate_left(13)
                ^ u64::from(gradient.end.x.to_bits()).rotate_left(19)
                ^ u64::from(gradient.end.y.to_bits()).rotate_left(23)
        }
        Brush::RadialGradient(gradient) => {
            gradient.stops.id().get()
                ^ u64::from(gradient.center.x.to_bits()).rotate_left(7)
                ^ u64::from(gradient.center.y.to_bits()).rotate_left(13)
                ^ u64::from(gradient.radius.to_bits()).rotate_left(19)
        }
        Brush::SweepGradient(gradient) => {
            gradient.stops.id().get()
                ^ u64::from(gradient.center.x.to_bits()).rotate_left(7)
                ^ u64::from(gradient.center.y.to_bits()).rotate_left(13)
                ^ u64::from(gradient.start_angle.to_bits()).rotate_left(19)
        }
    }
}

fn transform_generation(transform: Transform) -> u64 {
    transform
        .to_kurbo()
        .as_coeffs()
        .iter()
        .enumerate()
        .fold(0, |value, (index, coefficient)| {
            value ^ coefficient.to_bits().rotate_left((index as u32 * 9) % 63)
        })
}