quickgui 0.1.5

A damage-driven, GPU-accelerated desktop GUI foundation
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
//! Compositing layers: offscreen group textures, subtree filters, backdrops, and blend modes.
//!
//! Everything an element can declare that cannot be expressed as one more instanced primitive —
//! a non-translational transform, a subtree blur or drop shadow, a backdrop effect, a non-normal
//! blend mode — makes that element a *compositing group*. [`Scene`] records the group, keeps its
//! descendants' paint layers inside it, and places one composite primitive in the parent layer at
//! the group's own cross-primitive paint order.
//!
//! This module owns the pass sequencing that turns those records into GPU work, and both the
//! window renderer (`gpu.rs`) and the headless visual-test renderer (`offscreen.rs`) drive the
//! same code, so a screenshot test exercises the production path.
//!
//! ## Why group textures are window-sized
//!
//! Text is prepared by Glyphon at absolute window coordinates and its vertex buffers are built
//! before any pass begins; the instanced shape, image, SVG, path, and custom-shader renderers
//! likewise bake one window-sized projection into a shared uniform. Allocating a group texture at
//! the group's own bounds would need every one of those renderers to learn a per-layer origin.
//! Allocating at the window's physical size instead lets a group be rendered with the unmodified
//! per-frame preparation — text included, so text rotates with its parent — at the cost of memory,
//! which [`MAX_LAYER_TEXTURE_BYTES`] bounds with honest degradation once the bound is reached.

use std::{
    collections::HashMap,
    sync::{Arc, Weak},
};

use wgpu::{
    BindGroup, BlendComponent, BlendFactor, BlendOperation, BlendState, ColorTargetState,
    ColorWrites, CommandEncoder, Device, Extent3d, FragmentState, LoadOp, MultisampleState,
    Operations, PipelineCompilationOptions, PrimitiveState, Queue, RenderPass,
    RenderPassColorAttachment, RenderPassDescriptor, RenderPipeline, RenderPipelineDescriptor,
    ShaderStages, Texture, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages,
    TextureView, TextureViewDescriptor, VertexState,
};

use crate::{
    BlendMode, Color as UiColor, ColorMatrix, Corners, MAX_LAYER_TEXTURE_BYTES, Rect, Scene,
    ScenePlane, Transform2D,
    custom_shader_renderer::CustomShaderRenderer,
    image_renderer::ImageRenderer,
    path_renderer::PathRenderer,
    scene::{BLUR_MARGIN_SIGMAS, PaintGroup, PaintLayer, PrimitiveRef},
    svg_renderer::SvgRenderer,
};

use super::{RendererError, ShapeRenderer, TextSystem};

/// Largest number of Gaussian taps evaluated per direction and per axis.
///
/// A wider support is approximated by striding the taps, so the cost of the largest accepted
/// [`MAX_BLUR_RADIUS`](crate::MAX_BLUR_RADIUS) stays bounded at any scale factor.
const MAX_BLUR_TAPS: f32 = 48.0;

/// Composite draws recorded per frame: a backdrop, a drop shadow, and the group itself for each
/// group, plus headroom.
const MAX_COMPOSITE_DRAWS: usize = 4 * crate::MAX_LAYERS_PER_FRAME;
/// Blur passes recorded per frame: two axes each for the group blur and the backdrop blur.
const MAX_BLUR_DRAWS: usize = 4 * crate::MAX_LAYERS_PER_FRAME;

const COMPOSITE_UNIFORM_STRIDE: u64 = 256;
const BLUR_UNIFORM_STRIDE: u64 = 256;
const MAX_CACHED_LAYER_COMMAND_BYTES: usize = 32 * 1024 * 1024;

/// Per-frame compositing telemetry surfaced through [`RenderStats`](crate::RenderStats).
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct CompositeStats {
    /// Groups composited from their own offscreen texture this frame.
    pub layers: usize,
    /// Offscreen group passes recorded this frame.
    pub layer_passes: usize,
    /// Group textures whose unchanged content was reused without recording a group pass.
    pub reused_layers: usize,
    /// Separable blur passes recorded this frame.
    pub blur_passes: usize,
    /// Bytes of offscreen texture retained by this window after eviction.
    pub layer_texture_bytes: u64,
    /// Declared layer effects painted without their effect because a bound was reached.
    pub skipped_layer_effects: usize,
}

/// The immutable per-frame description of the target being rendered.
#[derive(Clone, Copy, Debug)]
pub(crate) struct CompositeFrame {
    pub width: u32,
    pub height: u32,
    pub scale: f32,
    pub format: TextureFormat,
    /// Whether the target texture can be copied from, which destination-reading effects need.
    pub target_copyable: bool,
    /// Restrict rendering to one plane, as the window renderer does around a native view.
    pub plane: Option<ScenePlane>,
}

/// Borrowed references to every primitive renderer that participates in a pass.
pub(crate) struct SceneRenderers<'a> {
    pub shapes: &'a ShapeRenderer,
    pub path: Option<&'a PathRenderer>,
    pub custom_shader: Option<&'a CustomShaderRenderer>,
    pub image: Option<&'a ImageRenderer>,
    pub svg: Option<&'a SvgRenderer>,
    pub text: &'a TextSystem,
}

impl<'a> SceneRenderers<'a> {
    fn draw(
        &'a self,
        pass: &mut RenderPass<'a>,
        layer: usize,
        order: u32,
    ) -> Result<(), RendererError> {
        self.shapes.render_order(pass, layer, order);
        if let Some(path) = self.path {
            path.render_order(pass, layer, order);
        }
        if let Some(custom_shader) = self.custom_shader {
            custom_shader.render_order(pass, layer, order);
        }
        if let Some(image) = self.image {
            image.render_order(pass, layer, order);
        }
        if let Some(svg) = self.svg {
            svg.render_order(pass, layer, order);
        }
        self.text.render_order(pass, layer, order)
    }
}

/// One recorded unit of work inside a target's pass sequence.
#[derive(Clone, Copy, Debug)]
enum Step {
    /// Draw every primitive of one paint layer at one cross-primitive order.
    Draw { layer: usize, order: u32 },
    /// End the current pass, copy the target, and blur the copy. Destination-reading effects
    /// (backdrop filters and every blend mode but `normal` and `screen`) need this first.
    Capture { blur: Option<usize> },
    /// Draw one composite quad.
    Composite { draw: usize },
}

/// Identity of one retained offscreen texture.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum LayerTextureKey {
    /// The rendered content of a group.
    Content(u16),
    /// The blurred content of a group.
    Blurred(u16),
    /// Shared scratch: 0 the blur ping-pong, 1 the destination copy, 2 the blurred copy.
    Scratch(u8),
}

struct LayerTexture {
    key: LayerTextureKey,
    width: u32,
    height: u32,
    format: TextureFormat,
    texture: Arc<Texture>,
    view: Arc<TextureView>,
    last_used: u64,
    generation: u64,
}

impl LayerTexture {
    fn bytes(&self) -> u64 {
        u64::from(self.width) * u64::from(self.height) * 4
    }
}

/// A bounded, least-recently-used pool of window-sized offscreen textures.
struct LayerTextureCache {
    textures: Vec<LayerTexture>,
    frame: u64,
    bytes: u64,
    generation: u64,
    byte_limit: u64,
}

impl Default for LayerTextureCache {
    fn default() -> Self {
        Self {
            textures: Vec::new(),
            frame: 0,
            bytes: 0,
            generation: 0,
            byte_limit: MAX_LAYER_TEXTURE_BYTES,
        }
    }
}

impl LayerTextureCache {
    fn generation(&self, key: LayerTextureKey) -> u64 {
        self.textures
            .iter()
            .find(|texture| texture.key == key)
            .map_or(0, |texture| texture.generation)
    }
    fn begin_frame(&mut self) {
        self.frame = self.frame.wrapping_add(1);
    }

    /// Reuse or allocate the texture for `key`, or return `None` when the bound forbids it.
    fn acquire(
        &mut self,
        device: &Device,
        key: LayerTextureKey,
        width: u32,
        height: u32,
        format: TextureFormat,
    ) -> Option<(Arc<Texture>, Arc<TextureView>)> {
        let frame = self.frame;
        if let Some(existing) = self.textures.iter_mut().find(|texture| {
            texture.key == key
                && texture.width == width
                && texture.height == height
                && texture.format == format
        }) {
            existing.last_used = frame;
            return Some((existing.texture.clone(), existing.view.clone()));
        }
        // Repurpose a same-shaped texture this frame has not claimed before allocating.
        if let Some(reusable) = self.textures.iter_mut().find(|texture| {
            texture.last_used != frame
                && texture.width == width
                && texture.height == height
                && texture.format == format
        }) {
            self.generation = self.generation.wrapping_add(1);
            reusable.generation = self.generation;
            reusable.key = key;
            reusable.last_used = frame;
            return Some((reusable.texture.clone(), reusable.view.clone()));
        }

        let bytes = u64::from(width) * u64::from(height) * 4;
        if bytes > self.byte_limit {
            return None;
        }
        while self.bytes + bytes > self.byte_limit {
            let victim = self
                .textures
                .iter()
                .enumerate()
                .filter(|(_, texture)| texture.last_used != frame)
                .min_by_key(|(_, texture)| texture.last_used)
                .map(|(index, _)| index)?;
            self.bytes -= self.textures[victim].bytes();
            self.textures.remove(victim);
        }

        let texture = Arc::new(device.create_texture(&TextureDescriptor {
            label: Some("quickgui compositing layer"),
            size: Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: TextureDimension::D2,
            format,
            usage: TextureUsages::RENDER_ATTACHMENT
                | TextureUsages::TEXTURE_BINDING
                | TextureUsages::COPY_SRC
                | TextureUsages::COPY_DST,
            view_formats: &[],
        }));
        let view = Arc::new(texture.create_view(&TextureViewDescriptor::default()));
        self.bytes += bytes;
        self.generation = self.generation.wrapping_add(1);
        self.textures.push(LayerTexture {
            key,
            width,
            height,
            format,
            texture: texture.clone(),
            view: view.clone(),
            last_used: frame,
            generation: self.generation,
        });
        Some((texture, view))
    }
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct CompositeUniform {
    inverse: [f32; 4],
    inverse_translation: [f32; 2],
    source_size: [f32; 2],
    quad: [f32; 4],
    clip: [f32; 4],
    mask: [f32; 4],
    corners: [f32; 4],
    matrix_r: [f32; 4],
    matrix_g: [f32; 4],
    matrix_b: [f32; 4],
    matrix_a: [f32; 4],
    matrix_offset: [f32; 4],
    tint: [f32; 4],
    params: [f32; 4],
    viewport: [f32; 2],
    _padding: [f32; 2],
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct BlurUniform {
    params: [f32; 4],
    source: [f32; 4],
    viewport: [f32; 2],
    _padding: [f32; 2],
}

/// How a composite draw combines with what is already in the target.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CompositeBlend {
    /// Premultiplied source-over.
    Over,
    /// Exact separable `screen`, which needs no destination copy.
    Screen,
    /// The shader already produced the final color from a captured destination.
    Replace,
}

impl CompositeBlend {
    fn index(self) -> usize {
        match self {
            Self::Over => 0,
            Self::Screen => 1,
            Self::Replace => 2,
        }
    }

    fn state(self) -> BlendState {
        match self {
            Self::Over => BlendState::PREMULTIPLIED_ALPHA_BLENDING,
            // `screen` is exactly Cs + Cb(1 - Cs) in premultiplied form.
            Self::Screen => BlendState {
                color: BlendComponent {
                    src_factor: BlendFactor::One,
                    dst_factor: BlendFactor::OneMinusSrc,
                    operation: BlendOperation::Add,
                },
                alpha: BlendComponent {
                    src_factor: BlendFactor::One,
                    dst_factor: BlendFactor::OneMinusSrcAlpha,
                    operation: BlendOperation::Add,
                },
            },
            Self::Replace => BlendState::REPLACE,
        }
    }
}

/// One recorded composite draw.
struct CompositeDraw {
    bind_group: BindGroup,
    offset: u32,
    blend: CompositeBlend,
}

/// One recorded separable blur pass.
struct BlurDraw {
    bind_group: BindGroup,
    offset: u32,
    target: Arc<TextureView>,
}

/// The textures one group claimed for this frame.
struct GroupTextures {
    /// The group's own content texture; absent when the effect was dropped for a bound.
    content: Option<Arc<TextureView>>,
    content_texture: Option<Arc<Texture>>,
    /// The blurred copy of that content, when a subtree blur or drop shadow was declared.
    blurred: Option<Arc<TextureView>>,
    /// The blur ping-pong scratch shared with every other group.
    scratch: Option<Arc<TextureView>>,
}

/// A group's finished plan for this frame.
struct GroupPlan {
    id: u16,
    content: Option<Arc<TextureView>>,
    content_texture: Option<Arc<Texture>>,
    /// Blur passes replayed straight after the group's own pass.
    blurs: Vec<usize>,
    /// Steps replayed into the group's own pass.
    steps: Vec<Step>,
    /// Steps the parent replays where the group's composite belongs.
    composite: Vec<Step>,
    /// Whether the effect was dropped and the subtree paints directly into its parent.
    inlined: bool,
}

#[derive(Clone)]
struct GroupContent {
    layers: Vec<Arc<PaintLayer>>,
    children: Vec<(PaintGroup, GroupContent)>,
}

impl GroupContent {
    fn allocated_bytes(&self) -> usize {
        self.layers.capacity() * size_of::<Arc<PaintLayer>>()
            + self
                .layers
                .iter()
                .map(|layer| layer.allocated_bytes())
                .sum::<usize>()
            + self.children.capacity() * size_of::<(PaintGroup, GroupContent)>()
            + self
                .children
                .iter()
                .map(|(group, content)| {
                    group.layers.capacity() * size_of::<usize>() + content.allocated_bytes()
                })
                .sum::<usize>()
    }

    fn of(scene: &Scene, group: &PaintGroup) -> Self {
        Self {
            layers: group
                .layers
                .iter()
                .map(|index| scene.paint_layers()[*index].clone())
                .collect(),
            children: scene
                .groups()
                .iter()
                .filter(|child| child.parent == group.id)
                .map(|child| (child.clone(), Self::of(scene, child)))
                .collect(),
        }
    }

    fn matches(&self, other: &Self) -> bool {
        self.layers.len() == other.layers.len()
            && self.children.len() == other.children.len()
            && self
                .layers
                .iter()
                .zip(&other.layers)
                .all(|(a, b)| a.same_commands(b))
            && self
                .children
                .iter()
                .zip(&other.children)
                .all(|((a, ac), (b, bc))| {
                    a.id == b.id
                        && a.bounds == b.bounds
                        && a.clip == b.clip
                        && a.effects == b.effects
                        && a.opacity == b.opacity
                        && ac.matches(bc)
                })
    }
}

struct CachedGroup {
    content: GroupContent,
    texture: Weak<Texture>,
    blurred: Option<Weak<TextureView>>,
    scale: f32,
    sigma: f32,
    descendant_effects: Vec<(u16, bool)>,
    content_generation: u64,
    blur_generation: u64,
}

struct GroupReuse {
    content: GroupContent,
    pixels: bool,
    blur: bool,
    sigma: f32,
    descendant_effects: Vec<(u16, bool)>,
}

/// Immutable device objects, created lazily on the first frame that declares a layer effect.
struct CompositePipelines {
    format: TextureFormat,
    composite_layout: wgpu::BindGroupLayout,
    blur_layout: wgpu::BindGroupLayout,
    composite: [RenderPipeline; 3],
    blur: RenderPipeline,
    sampler: wgpu::Sampler,
    composite_uniforms: wgpu::Buffer,
    blur_uniforms: wgpu::Buffer,
}

/// Owns every compositing resource for one window or headless target.
#[derive(Default)]
pub(crate) struct Compositor {
    pipelines: Option<CompositePipelines>,
    cache: LayerTextureCache,
    content_cache: HashMap<u16, CachedGroup>,
}

impl Compositor {
    /// Whether this compositor has ever allocated anything. A window that never declares a layer
    /// effect keeps this `true` and pays nothing per frame.
    #[cfg(test)]
    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
    pub(crate) fn is_idle(&self) -> bool {
        self.pipelines.is_none() && self.cache.textures.is_empty()
    }

    #[cfg(test)]
    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
    pub(crate) fn retained_bytes(&self) -> u64 {
        self.cache.bytes
    }

    fn ensure_pipelines(&mut self, device: &Device, format: TextureFormat) {
        if self
            .pipelines
            .as_ref()
            .is_none_or(|pipelines| pipelines.format != format)
        {
            self.pipelines = Some(CompositePipelines::new(device, format));
        }
    }

    /// Render one scene into `target_view`, compositing every declared layer effect.
    ///
    /// The zero-group path is exactly the historical single-pass loop: no texture allocated, no
    /// pipeline compiled, no extra pass recorded.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn render_scene(
        &mut self,
        device: &Device,
        queue: &Queue,
        encoder: &mut CommandEncoder,
        scene: &Scene,
        renderers: &SceneRenderers<'_>,
        target_view: &TextureView,
        target_texture: Option<&Texture>,
        clear: Option<UiColor>,
        frame: CompositeFrame,
    ) -> Result<CompositeStats, RendererError> {
        let plane = frame.plane;
        let root_layers: Vec<usize> = scene
            .paint_layers()
            .iter()
            .enumerate()
            .filter(|(_, layer)| {
                layer.key().group == 0 && plane.is_none_or(|plane| layer.key().plane == plane)
            })
            .map(|(index, _)| index)
            .collect();
        let groups: Vec<&PaintGroup> = scene
            .groups()
            .iter()
            .filter(|group| plane.is_none_or(|plane| group.plane == plane))
            .collect();

        let mut stats = CompositeStats {
            skipped_layer_effects: scene.skipped_groups(),
            layer_texture_bytes: self.cache.bytes,
            ..Default::default()
        };

        if groups.is_empty() {
            self.content_cache
                .retain(|id, _| scene.groups().iter().any(|group| group.id == *id));
            let mut pass = begin_pass(encoder, target_view, clear, "quickgui scene pass");
            for layer in root_layers {
                for order in 0..=scene.paint_layers()[layer].max_order() {
                    renderers.draw(&mut pass, layer, order)?;
                }
            }
            return Ok(stats);
        }

        // Phase 1: claim textures, deepest group first, under the retained-byte bound. The
        // separable blur's ping-pong is shared by every group, because each pair of axis passes
        // completes before the next begins.
        self.cache.begin_frame();
        let blur_scratch = if groups.iter().any(|group| {
            group.effects.blur > 0.0
                || group.effects.backdrop_blur > 0.0
                || group
                    .effects
                    .drop_shadow
                    .is_some_and(|shadow| shadow.sigma() > 0.0)
        }) {
            self.scratch(device, 0, frame).map(|(_, view)| view)
        } else {
            None
        };
        let mut textures: Vec<GroupTextures> = Vec::with_capacity(groups.len());
        for group in groups.iter().rev() {
            textures.push(self.claim_textures(device, group, blur_scratch.as_ref(), frame));
        }
        let capture = self.scratch(device, 1, frame);
        let capture_blur = if groups.iter().any(|group| group.effects.backdrop_blur > 0.0) {
            self.scratch(device, 2, frame)
        } else {
            None
        };
        stats.layer_texture_bytes = self.cache.bytes;

        self.content_cache
            .retain(|id, _| scene.groups().iter().any(|group| group.id == *id));
        let mut reuse: Vec<_> = groups
            .iter()
            .rev()
            .zip(&textures)
            .map(|(group, claimed)| {
                let content = GroupContent::of(scene, group);
                let previous = self.content_cache.get(&group.id);
                let pixels = previous.is_some_and(|previous| {
                    previous.scale == frame.scale
                        && previous.content_generation
                            == self.cache.generation(LayerTextureKey::Content(group.id))
                        && previous
                            .texture
                            .upgrade()
                            .zip(claimed.content_texture.as_ref())
                            .is_some_and(|(old, current)| Arc::ptr_eq(&old, current))
                        && previous.content.matches(&content)
                });
                let sigma = group.effects.blur.max(
                    group
                        .effects
                        .drop_shadow
                        .map_or(0.0, |shadow| shadow.sigma()),
                );
                let blur = pixels
                    && previous.is_some_and(|previous| {
                        previous.sigma == sigma
                            && previous.blur_generation
                                == self.cache.generation(LayerTextureKey::Blurred(group.id))
                            && previous
                                .blurred
                                .as_ref()
                                .and_then(Weak::upgrade)
                                .zip(claimed.blurred.as_ref())
                                .is_some_and(|(old, current)| Arc::ptr_eq(&old, current))
                    });
                GroupReuse {
                    content,
                    pixels,
                    blur,
                    sigma,
                    descendant_effects: Vec::new(),
                }
            })
            .collect();

        // Phase 2: build every draw and the ordered step lists.
        self.ensure_pipelines(device, frame.format);
        let pipelines = self
            .pipelines
            .as_ref()
            .expect("the compositor pipelines were just created");
        let mut composite_draws: Vec<CompositeDraw> = Vec::new();
        let mut blur_draws: Vec<BlurDraw> = Vec::new();
        let mut composite_uniforms: Vec<CompositeUniform> = Vec::new();
        let mut blur_uniforms: Vec<BlurUniform> = Vec::new();
        let mut plans: Vec<GroupPlan> = Vec::new();

        for ((group, claimed), reuse) in groups.iter().rev().zip(textures.iter()).zip(&mut reuse) {
            let plan = plan_group(
                device,
                pipelines,
                scene,
                group,
                claimed,
                frame,
                capture.as_ref().map(|(_, view)| view),
                capture_blur.as_ref().map(|(_, view)| view),
                blur_scratch.as_ref(),
                &plans,
                &mut composite_draws,
                &mut blur_draws,
                &mut composite_uniforms,
                &mut blur_uniforms,
            );
            // Texture pressure or per-frame draw limits can inline a child that previously had
            // an effect (and vice versa), even when its declaration is unchanged.
            reuse.descendant_effects = plans.iter().map(|plan| (plan.id, plan.inlined)).collect();
            reuse.pixels &= self
                .content_cache
                .get(&group.id)
                .is_some_and(|previous| previous.descendant_effects == reuse.descendant_effects);
            reuse.blur &= reuse.pixels;
            if plan.inlined {
                stats.skipped_layer_effects += 1;
            } else {
                stats.layers += 1;
                if reuse.pixels {
                    stats.reused_layers += 1;
                } else {
                    stats.layer_passes += 1;
                }
            }
            plans.push(plan);
        }
        plans.reverse();
        let root_steps = build_steps(scene, &root_layers, &plans);
        stats.blur_passes = blur_draws.len()
            - plans
                .iter()
                .rev()
                .zip(&reuse)
                .filter(|(_, reuse)| reuse.blur)
                .map(|(plan, _)| plan.blurs.len())
                .sum::<usize>();

        // Base and overlay planes can be encoded before one queue submission. Queue writes are
        // executed before that submission, so each plane needs distinct uniform addresses.
        let overlay = u64::from(frame.plane == Some(ScenePlane::Overlay));
        let composite_offset = overlay * COMPOSITE_UNIFORM_STRIDE * MAX_COMPOSITE_DRAWS as u64;
        let blur_offset = overlay * BLUR_UNIFORM_STRIDE * MAX_BLUR_DRAWS as u64;
        for draw in &mut composite_draws {
            draw.offset += composite_offset as u32;
        }
        for draw in &mut blur_draws {
            draw.offset += blur_offset as u32;
        }
        queue.write_buffer(
            &pipelines.composite_uniforms,
            composite_offset,
            &pack_uniforms(&composite_uniforms, COMPOSITE_UNIFORM_STRIDE),
        );
        queue.write_buffer(
            &pipelines.blur_uniforms,
            blur_offset,
            &pack_uniforms(&blur_uniforms, BLUR_UNIFORM_STRIDE),
        );

        // Phase 3: record group passes deepest first, then the target's own pass.
        for (plan, reuse) in plans.iter().rev().zip(&reuse) {
            let Some(content) = plan.content.clone() else {
                continue;
            };
            if !reuse.pixels {
                record_target(
                    encoder,
                    renderers,
                    &plan.steps,
                    &composite_draws,
                    &blur_draws,
                    pipelines,
                    &content,
                    plan.content_texture.as_deref(),
                    capture.as_ref().map(|(texture, _)| texture.as_ref()),
                    Some(UiColor::TRANSPARENT),
                    frame,
                    "quickgui layer pass",
                )?;
            }
            for blur in plan.blurs.iter().filter(|_| !reuse.blur) {
                let draw = &blur_draws[*blur];
                let mut pass = begin_pass(encoder, &draw.target, None, "quickgui layer blur");
                pass.set_pipeline(&pipelines.blur);
                pass.set_bind_group(0, &draw.bind_group, &[draw.offset]);
                pass.draw(0..6, 0..1);
            }
        }

        record_target(
            encoder,
            renderers,
            &root_steps,
            &composite_draws,
            &blur_draws,
            pipelines,
            target_view,
            target_texture,
            capture.as_ref().map(|(texture, _)| texture.as_ref()),
            clear,
            frame,
            "quickgui scene pass",
        )?;

        for (((group, claimed), reuse), plan) in groups
            .iter()
            .rev()
            .zip(&textures)
            .zip(reuse)
            .zip(plans.iter().rev())
        {
            self.content_cache.remove(&group.id);
            let retained_bytes: usize = self
                .content_cache
                .values()
                .map(|entry| entry.content.allocated_bytes())
                .sum();
            if !plan.inlined
                && retained_bytes + reuse.content.allocated_bytes()
                    <= MAX_CACHED_LAYER_COMMAND_BYTES
                && let Some(texture) = &claimed.content_texture
            {
                self.content_cache.insert(
                    group.id,
                    CachedGroup {
                        content: reuse.content,
                        texture: Arc::downgrade(texture),
                        blurred: claimed.blurred.as_ref().map(Arc::downgrade),
                        scale: frame.scale,
                        sigma: reuse.sigma,
                        descendant_effects: reuse.descendant_effects,
                        content_generation: self
                            .cache
                            .generation(LayerTextureKey::Content(group.id)),
                        blur_generation: self.cache.generation(LayerTextureKey::Blurred(group.id)),
                    },
                );
            } else {
                self.content_cache.remove(&group.id);
            }
        }

        Ok(stats)
    }

    fn scratch(
        &mut self,
        device: &Device,
        slot: u8,
        frame: CompositeFrame,
    ) -> Option<(Arc<Texture>, Arc<TextureView>)> {
        self.cache.acquire(
            device,
            LayerTextureKey::Scratch(slot),
            frame.width,
            frame.height,
            frame.format,
        )
    }

    fn claim_textures(
        &mut self,
        device: &Device,
        group: &PaintGroup,
        blur_scratch: Option<&Arc<TextureView>>,
        frame: CompositeFrame,
    ) -> GroupTextures {
        let dropped = GroupTextures {
            content: None,
            content_texture: None,
            blurred: None,
            scratch: None,
        };
        if group.effects.reads_destination() && !frame.target_copyable {
            // This surface cannot be read back, so the effect cannot be honored.
            return dropped;
        }
        let Some((content_texture, content)) = self.cache.acquire(
            device,
            LayerTextureKey::Content(group.id),
            frame.width,
            frame.height,
            frame.format,
        ) else {
            return dropped;
        };
        let needs_blur =
            group.effects.blur > 0.0 || group.effects.drop_shadow.is_some_and(|s| s.sigma() > 0.0);
        if !needs_blur {
            return GroupTextures {
                content: Some(content),
                content_texture: Some(content_texture),
                blurred: None,
                scratch: None,
            };
        }
        let scratch = blur_scratch.cloned();
        let blurred = self
            .cache
            .acquire(
                device,
                LayerTextureKey::Blurred(group.id),
                frame.width,
                frame.height,
                frame.format,
            )
            .map(|(_, view)| view);
        match (scratch, blurred) {
            (Some(scratch), Some(blurred)) => GroupTextures {
                content: Some(content),
                content_texture: Some(content_texture),
                blurred: Some(blurred),
                scratch: Some(scratch),
            },
            // Without room for the convolution the group would paint unblurred, which is a
            // different picture rather than a cheaper one. Drop the effect instead.
            _ => dropped,
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn plan_group(
    device: &Device,
    pipelines: &CompositePipelines,
    scene: &Scene,
    group: &PaintGroup,
    claimed: &GroupTextures,
    frame: CompositeFrame,
    capture: Option<&Arc<TextureView>>,
    capture_blur: Option<&Arc<TextureView>>,
    blur_scratch: Option<&Arc<TextureView>>,
    planned: &[GroupPlan],
    composite_draws: &mut Vec<CompositeDraw>,
    blur_draws: &mut Vec<BlurDraw>,
    composite_uniforms: &mut Vec<CompositeUniform>,
    blur_uniforms: &mut Vec<BlurUniform>,
) -> GroupPlan {
    let dropped = |steps: Vec<Step>| GroupPlan {
        id: group.id,
        content: None,
        content_texture: None,
        blurs: Vec::new(),
        steps: Vec::new(),
        composite: steps,
        inlined: true,
    };
    let inline_steps = || build_steps(scene, &group.layers, planned);
    let Some(content) = claimed.content.clone() else {
        return dropped(inline_steps());
    };
    if composite_draws.len() + 3 > MAX_COMPOSITE_DRAWS || blur_draws.len() + 4 > MAX_BLUR_DRAWS {
        return dropped(inline_steps());
    }
    let effects = group.effects;
    let reads_destination = effects.reads_destination();
    if reads_destination && capture.is_none() {
        return dropped(inline_steps());
    }
    if effects.backdrop_blur > 0.0 && (capture_blur.is_none() || blur_scratch.is_none()) {
        return dropped(inline_steps());
    }

    // The group's transform, expressed in physical pixels.
    let scale = frame.scale;
    let transform = physical_transform(effects.transform, scale);
    let Some(inverse) = transform.inverse() else {
        return dropped(inline_steps());
    };
    let source_size = [frame.width as f32, frame.height as f32];
    let clip = physical_rect(group.clip, scale, frame);
    let mask = physical_rect(group.bounds_box(), scale, frame);
    let matrix = effects.color_matrix;

    let mut blurs = Vec::new();
    if let (Some(blurred), Some(scratch)) = (&claimed.blurred, &claimed.scratch) {
        // One pair of passes serves both the subtree blur and the drop shadow; the wider of the
        // two standard deviations wins.
        let sigma = effects
            .blur
            .max(effects.drop_shadow.map_or(0.0, |shadow| shadow.sigma()))
            * scale;
        blurs.push(push_blur(
            device,
            pipelines,
            blur_draws,
            blur_uniforms,
            &content,
            scratch.clone(),
            [1.0, 0.0],
            sigma,
            frame,
        ));
        blurs.push(push_blur(
            device,
            pipelines,
            blur_draws,
            blur_uniforms,
            scratch,
            blurred.clone(),
            [0.0, 1.0],
            sigma,
            frame,
        ));
    }

    let mut composite = Vec::new();
    if reads_destination {
        let capture = capture.expect("a destination-reading group holds a capture texture");
        let blur = if effects.backdrop_blur > 0.0 {
            let target = capture_blur.expect("a blurred backdrop holds its own texture");
            let scratch = blur_scratch
                .cloned()
                .expect("a blurred backdrop holds the shared ping-pong");
            // Horizontal into the ping-pong, vertical into the blurred capture.
            let horizontal = push_blur(
                device,
                pipelines,
                blur_draws,
                blur_uniforms,
                capture,
                scratch.clone(),
                [1.0, 0.0],
                effects.backdrop_blur * scale,
                frame,
            );
            let _ = push_blur(
                device,
                pipelines,
                blur_draws,
                blur_uniforms,
                &scratch,
                target.clone(),
                [0.0, 1.0],
                effects.backdrop_blur * scale,
                frame,
            );
            Some(horizontal)
        } else {
            None
        };
        composite.push(Step::Capture { blur });

        if effects.has_backdrop() {
            let source = if effects.backdrop_blur > 0.0 {
                capture_blur.expect("a blurred backdrop holds its own texture")
            } else {
                capture
            };
            // The backdrop is filtered in the element's own coordinate system, so it travels
            // through the same transform and is masked by the element's rounded rectangle.
            let quad = transform.transform_rect(physical_rect(group.bounds_box(), scale, frame));
            composite.push(push_composite(
                device,
                pipelines,
                composite_draws,
                composite_uniforms,
                CompositeParameters {
                    source,
                    destination: capture,
                    inverse,
                    source_size,
                    quad,
                    clip,
                    mask: Some((mask, effects.backdrop_corners, scale)),
                    matrix: effects.backdrop_matrix,
                    tint: None,
                    opacity: group.opacity,
                    blend: BlendMode::Normal,
                    frame,
                },
            ));
        }
    }

    let composited = claimed.blurred.as_ref().filter(|_| effects.blur > 0.0);
    // A drop shadow with no blur is the subtree's own silhouette, offset and tinted.
    let shadow_source = claimed.blurred.as_ref().unwrap_or(&content);
    if let Some(shadow) = effects.drop_shadow {
        let source = shadow_source;
        let offset = Transform2D::translate(shadow.offset.x * scale, shadow.offset.y * scale);
        let shadow_transform = offset.then(transform);
        if let Some(shadow_inverse) = shadow_transform.inverse() {
            let quad =
                shadow_transform.transform_rect(physical_rect(group.bounds_box(), scale, frame));
            composite.push(push_composite(
                device,
                pipelines,
                composite_draws,
                composite_uniforms,
                CompositeParameters {
                    source,
                    destination: capture.unwrap_or(&content),
                    inverse: shadow_inverse,
                    source_size,
                    quad,
                    clip,
                    mask: None,
                    matrix: ColorMatrix::IDENTITY,
                    tint: Some(shadow.color),
                    opacity: group.opacity,
                    blend: BlendMode::Normal,
                    frame,
                },
            ));
        }
    }

    let source = composited.unwrap_or(&content);
    let quad = transform.transform_rect(physical_rect(group.bounds_box(), scale, frame));
    composite.push(push_composite(
        device,
        pipelines,
        composite_draws,
        composite_uniforms,
        CompositeParameters {
            source,
            destination: capture.unwrap_or(&content),
            inverse,
            source_size,
            quad,
            clip,
            mask: None,
            matrix,
            tint: None,
            opacity: group.opacity,
            blend: effects.blend,
            frame,
        },
    ));

    GroupPlan {
        id: group.id,
        content: Some(content),
        content_texture: claimed.content_texture.clone(),
        blurs,
        steps: build_steps(scene, &group.layers, planned),
        composite,
        inlined: false,
    }
}

struct CompositeParameters<'a> {
    source: &'a TextureView,
    destination: &'a TextureView,
    inverse: Transform2D,
    source_size: [f32; 2],
    quad: Rect,
    clip: Rect,
    mask: Option<(Rect, Corners, f32)>,
    matrix: ColorMatrix,
    tint: Option<UiColor>,
    opacity: f32,
    blend: BlendMode,
    frame: CompositeFrame,
}

fn push_composite(
    device: &Device,
    pipelines: &CompositePipelines,
    draws: &mut Vec<CompositeDraw>,
    uniforms: &mut Vec<CompositeUniform>,
    parameters: CompositeParameters<'_>,
) -> Step {
    let matrix = parameters.matrix.as_array();
    let (mask, corners) = match parameters.mask {
        Some((rect, corners, scale)) => (
            [rect.x, rect.y, rect.width, rect.height],
            [
                corners.top_left * scale,
                corners.top_right * scale,
                corners.bottom_right * scale,
                corners.bottom_left * scale,
            ],
        ),
        None => ([0.0; 4], [0.0; 4]),
    };
    let tint = match parameters.tint {
        Some(color) => [
            color.r * color.a,
            color.g * color.a,
            color.b * color.a,
            color.a,
        ],
        None => [0.0, 0.0, 0.0, -1.0],
    };
    let reads_destination = parameters.blend.reads_destination();
    let blend = if reads_destination {
        CompositeBlend::Replace
    } else if parameters.blend == BlendMode::Screen {
        CompositeBlend::Screen
    } else {
        CompositeBlend::Over
    };
    let offset = (uniforms.len() as u64 * COMPOSITE_UNIFORM_STRIDE) as u32;
    uniforms.push(CompositeUniform {
        inverse: [
            parameters.inverse.a,
            parameters.inverse.b,
            parameters.inverse.c,
            parameters.inverse.d,
        ],
        inverse_translation: [parameters.inverse.tx, parameters.inverse.ty],
        source_size: parameters.source_size,
        quad: [
            parameters.quad.x,
            parameters.quad.y,
            parameters.quad.width,
            parameters.quad.height,
        ],
        clip: [
            parameters.clip.x,
            parameters.clip.y,
            parameters.clip.right(),
            parameters.clip.bottom(),
        ],
        mask,
        corners,
        matrix_r: [matrix[0], matrix[1], matrix[2], matrix[3]],
        matrix_g: [matrix[5], matrix[6], matrix[7], matrix[8]],
        matrix_b: [matrix[10], matrix[11], matrix[12], matrix[13]],
        matrix_a: [matrix[15], matrix[16], matrix[17], matrix[18]],
        matrix_offset: [matrix[4], matrix[9], matrix[14], matrix[19]],
        tint,
        params: [
            parameters.opacity.clamp(0.0, 1.0),
            parameters.blend.code() as f32,
            if reads_destination { 1.0 } else { 0.0 },
            if parameters.matrix.is_identity() {
                0.0
            } else {
                1.0
            },
        ],
        viewport: [
            parameters.frame.width as f32,
            parameters.frame.height as f32,
        ],
        _padding: [0.0; 2],
    });
    let bind_group =
        pipelines.composite_bind_group(device, parameters.source, parameters.destination);
    let draw = draws.len();
    draws.push(CompositeDraw {
        bind_group,
        offset,
        blend,
    });
    Step::Composite { draw }
}

#[allow(clippy::too_many_arguments)]
fn push_blur(
    device: &Device,
    pipelines: &CompositePipelines,
    draws: &mut Vec<BlurDraw>,
    uniforms: &mut Vec<BlurUniform>,
    source: &TextureView,
    target: Arc<TextureView>,
    direction: [f32; 2],
    sigma: f32,
    frame: CompositeFrame,
) -> usize {
    let sigma = sigma.max(1.0e-3);
    let support = (sigma * BLUR_MARGIN_SIGMAS).ceil().max(1.0);
    let step = (support / MAX_BLUR_TAPS).ceil().max(1.0);
    let taps = (support / step).ceil().min(MAX_BLUR_TAPS);
    let offset = (uniforms.len() as u64 * BLUR_UNIFORM_STRIDE) as u32;
    uniforms.push(BlurUniform {
        params: [direction[0], direction[1], taps, step],
        source: [
            1.0 / (sigma * sigma),
            frame.width as f32,
            frame.height as f32,
            0.0,
        ],
        viewport: [frame.width as f32, frame.height as f32],
        _padding: [0.0; 2],
    });
    let bind_group = pipelines.blur_bind_group(device, source);
    let index = draws.len();
    draws.push(BlurDraw {
        bind_group,
        offset,
        target,
    });
    index
}

/// Flatten one target's layers into the ordered step list its passes replay.
fn build_steps(scene: &Scene, layers: &[usize], planned: &[GroupPlan]) -> Vec<Step> {
    let mut steps = Vec::new();
    for layer_index in layers {
        let layer = &scene.paint_layers()[*layer_index];
        if layer.paint().is_empty() {
            continue;
        }
        for order in 0..=layer.max_order() {
            steps.push(Step::Draw {
                layer: *layer_index,
                order,
            });
            for item in layer.paint() {
                if item.order != order {
                    continue;
                }
                let PrimitiveRef::Group(slot) = item.primitive else {
                    continue;
                };
                let Some(reference) = layer.groups().get(slot) else {
                    continue;
                };
                if let Some(plan) = planned.iter().find(|plan| plan.id == reference.group) {
                    steps.extend_from_slice(&plan.composite);
                }
            }
        }
    }
    steps
}

fn physical_transform(transform: Transform2D, scale: f32) -> Transform2D {
    Transform2D::new(
        transform.a,
        transform.b,
        transform.c,
        transform.d,
        transform.tx * scale,
        transform.ty * scale,
    )
}

fn physical_rect(rect: Rect, scale: f32, frame: CompositeFrame) -> Rect {
    let left = (rect.x * scale).max(0.0);
    let top = (rect.y * scale).max(0.0);
    let right = (rect.right() * scale).min(frame.width as f32);
    let bottom = (rect.bottom() * scale).min(frame.height as f32);
    Rect::new(left, top, (right - left).max(0.0), (bottom - top).max(0.0))
}

fn begin_pass<'encoder>(
    encoder: &'encoder mut CommandEncoder,
    view: &TextureView,
    clear: Option<UiColor>,
    label: &'static str,
) -> RenderPass<'encoder> {
    encoder.begin_render_pass(&RenderPassDescriptor {
        label: Some(label),
        color_attachments: &[Some(RenderPassColorAttachment {
            view,
            depth_slice: None,
            resolve_target: None,
            ops: Operations {
                load: match clear {
                    Some(color) => {
                        let [r, g, b, a] = color.premultiplied_srgba();
                        LoadOp::Clear(wgpu::Color {
                            r: f64::from(r),
                            g: f64::from(g),
                            b: f64::from(b),
                            a: f64::from(a),
                        })
                    }
                    None => LoadOp::Load,
                },
                store: wgpu::StoreOp::Store,
            },
        })],
        depth_stencil_attachment: None,
        timestamp_writes: None,
        occlusion_query_set: None,
        multiview_mask: None,
    })
}

/// Replay one target's steps, splitting the pass wherever a step needs the destination copied.
#[allow(clippy::too_many_arguments)]
fn record_target<'a>(
    encoder: &mut CommandEncoder,
    renderers: &'a SceneRenderers<'a>,
    steps: &[Step],
    composite_draws: &'a [CompositeDraw],
    blur_draws: &'a [BlurDraw],
    pipelines: &'a CompositePipelines,
    target_view: &TextureView,
    target_texture: Option<&Texture>,
    capture_texture: Option<&Texture>,
    clear: Option<UiColor>,
    frame: CompositeFrame,
    label: &'static str,
) -> Result<(), RendererError> {
    let mut load = clear;
    let mut index = 0;
    let mut opened = false;
    while index <= steps.len() {
        let mut end = index;
        while end < steps.len() && !matches!(steps[end], Step::Capture { .. }) {
            end += 1;
        }
        if index < end || !opened {
            let mut pass = begin_pass(encoder, target_view, load, label);
            for step in &steps[index..end] {
                match *step {
                    Step::Draw { layer, order } => renderers.draw(&mut pass, layer, order)?,
                    Step::Composite { draw } => {
                        let draw = &composite_draws[draw];
                        pass.set_pipeline(&pipelines.composite[draw.blend.index()]);
                        pass.set_bind_group(0, &draw.bind_group, &[draw.offset]);
                        pass.draw(0..6, 0..1);
                    }
                    Step::Capture { .. } => unreachable!("captures end the segment"),
                }
            }
            load = None;
            opened = true;
        }
        if end >= steps.len() {
            break;
        }
        let Step::Capture { blur } = steps[end] else {
            unreachable!("the segment ended on a capture")
        };
        if let (Some(target), Some(capture)) = (target_texture, capture_texture) {
            copy_target(encoder, target, capture, frame);
        }
        if let Some(blur) = blur {
            for draw in &blur_draws[blur..(blur + 2).min(blur_draws.len())] {
                let mut pass = begin_pass(encoder, &draw.target, None, "quickgui backdrop blur");
                pass.set_pipeline(&pipelines.blur);
                pass.set_bind_group(0, &draw.bind_group, &[draw.offset]);
                pass.draw(0..6, 0..1);
            }
        }
        index = end + 1;
    }
    Ok(())
}

/// Copy the whole target into the shared capture texture so a destination-reading effect can
/// sample what is already painted behind it.
fn copy_target(
    encoder: &mut CommandEncoder,
    target: &Texture,
    capture: &Texture,
    frame: CompositeFrame,
) {
    encoder.copy_texture_to_texture(
        wgpu::TexelCopyTextureInfo {
            texture: target,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        wgpu::TexelCopyTextureInfo {
            texture: capture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        Extent3d {
            width: frame.width,
            height: frame.height,
            depth_or_array_layers: 1,
        },
    );
}

fn pack_uniforms<T: bytemuck::Pod>(values: &[T], stride: u64) -> Vec<u8> {
    let stride = stride as usize;
    let mut packed = vec![0_u8; stride * values.len().max(1)];
    for (index, value) in values.iter().enumerate() {
        let bytes = bytemuck::bytes_of(value);
        packed[index * stride..index * stride + bytes.len()].copy_from_slice(bytes);
    }
    packed
}

impl CompositePipelines {
    fn new(device: &Device, format: TextureFormat) -> Self {
        let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("quickgui composite shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../composite.wgsl").into()),
        });
        let composite_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("quickgui composite bind group layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: wgpu::BufferSize::new(
                            std::mem::size_of::<CompositeUniform>() as u64,
                        ),
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });
        let blur_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("quickgui blur bind group layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: wgpu::BufferSize::new(
                            std::mem::size_of::<BlurUniform>() as u64
                        ),
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });
        let composite_pipeline_layout =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("quickgui composite pipeline layout"),
                bind_group_layouts: &[Some(&composite_layout)],
                immediate_size: 0,
            });
        let blur_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("quickgui blur pipeline layout"),
            bind_group_layouts: &[Some(&blur_layout)],
            immediate_size: 0,
        });
        let make_composite = |blend: CompositeBlend| {
            device.create_render_pipeline(&RenderPipelineDescriptor {
                label: Some("quickgui composite pipeline"),
                layout: Some(&composite_pipeline_layout),
                vertex: VertexState {
                    module: &module,
                    entry_point: Some("composite_vertex"),
                    buffers: &[],
                    compilation_options: PipelineCompilationOptions::default(),
                },
                fragment: Some(FragmentState {
                    module: &module,
                    entry_point: Some("composite_fragment"),
                    targets: &[Some(ColorTargetState {
                        format,
                        blend: Some(blend.state()),
                        write_mask: ColorWrites::ALL,
                    })],
                    compilation_options: PipelineCompilationOptions::default(),
                }),
                primitive: PrimitiveState::default(),
                depth_stencil: None,
                multisample: MultisampleState::default(),
                multiview_mask: None,
                cache: None,
            })
        };
        let composite = [
            make_composite(CompositeBlend::Over),
            make_composite(CompositeBlend::Screen),
            make_composite(CompositeBlend::Replace),
        ];
        let blur = device.create_render_pipeline(&RenderPipelineDescriptor {
            label: Some("quickgui blur pipeline"),
            layout: Some(&blur_pipeline_layout),
            vertex: VertexState {
                module: &module,
                entry_point: Some("blur_vertex"),
                buffers: &[],
                compilation_options: PipelineCompilationOptions::default(),
            },
            fragment: Some(FragmentState {
                module: &module,
                entry_point: Some("blur_fragment"),
                targets: &[Some(ColorTargetState {
                    format,
                    blend: Some(BlendState::REPLACE),
                    write_mask: ColorWrites::ALL,
                })],
                compilation_options: PipelineCompilationOptions::default(),
            }),
            primitive: PrimitiveState::default(),
            depth_stencil: None,
            multisample: MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("quickgui composite sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });
        let composite_uniforms = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("quickgui composite uniforms"),
            size: 2 * COMPOSITE_UNIFORM_STRIDE * MAX_COMPOSITE_DRAWS as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let blur_uniforms = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("quickgui blur uniforms"),
            size: 2 * BLUR_UNIFORM_STRIDE * MAX_BLUR_DRAWS as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        Self {
            format,
            composite_layout,
            blur_layout,
            composite,
            blur,
            sampler,
            composite_uniforms,
            blur_uniforms,
        }
    }

    fn composite_bind_group(
        &self,
        device: &Device,
        source: &TextureView,
        destination: &TextureView,
    ) -> BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("quickgui composite bind group"),
            layout: &self.composite_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: &self.composite_uniforms,
                        offset: 0,
                        size: wgpu::BufferSize::new(std::mem::size_of::<CompositeUniform>() as u64),
                    }),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(source),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::TextureView(destination),
                },
            ],
        })
    }

    fn blur_bind_group(&self, device: &Device, source: &TextureView) -> BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("quickgui blur bind group"),
            layout: &self.blur_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: &self.blur_uniforms,
                        offset: 0,
                        size: wgpu::BufferSize::new(std::mem::size_of::<BlurUniform>() as u64),
                    }),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(source),
                },
            ],
        })
    }
}

/// The untransformed box a group's composite covers, grown by its effect margin.
impl PaintGroup {
    pub(crate) fn bounds_box(&self) -> Rect {
        let margin = self.effects.margin();
        Rect::new(
            self.bounds.x - margin,
            self.bounds.y - margin,
            self.bounds.width + margin * 2.0,
            self.bounds.height + margin * 2.0,
        )
    }
}

#[cfg(all(test, target_os = "macos"))]
mod cache_tests {
    use super::*;
    use crate::renderer::OffscreenRenderer;
    use crate::{Assets, PerformanceProfile};

    #[test]
    fn texture_budget_and_generations_survive_repurposing() {
        let fonts = crate::renderer::create_shared_font_system(&Assets::default(), &[]).unwrap();
        let renderer =
            pollster::block_on(OffscreenRenderer::new(PerformanceProfile::Balanced, fonts))
                .unwrap();
        let (device, _) = renderer.gpu();
        let mut cache = LayerTextureCache {
            byte_limit: 16 * 16 * 4,
            ..Default::default()
        };
        let format = TextureFormat::Rgba8Unorm;
        cache.begin_frame();
        let (original, _) = cache
            .acquire(device, LayerTextureKey::Content(1), 16, 16, format)
            .unwrap();
        let generation = cache.generation(LayerTextureKey::Content(1));
        assert!(
            cache
                .acquire(device, LayerTextureKey::Content(2), 16, 16, format)
                .is_none()
        );
        assert!(cache.bytes <= cache.byte_limit);
        cache.begin_frame();
        let (scratch, _) = cache
            .acquire(device, LayerTextureKey::Scratch(0), 16, 16, format)
            .unwrap();
        assert!(Arc::ptr_eq(&original, &scratch));
        assert_ne!(generation, cache.generation(LayerTextureKey::Scratch(0)));
        cache.begin_frame();
        let (reclaimed, _) = cache
            .acquire(device, LayerTextureKey::Content(1), 16, 16, format)
            .unwrap();
        assert!(Arc::ptr_eq(&original, &reclaimed));
        assert_ne!(
            generation,
            cache.generation(LayerTextureKey::Content(1)),
            "pointer identity cannot validate reused pixels"
        );
        cache.begin_frame();
        let (resized, _) = cache
            .acquire(device, LayerTextureKey::Content(1), 8, 8, format)
            .unwrap();
        assert!(!Arc::ptr_eq(&original, &resized));
        assert_eq!(cache.bytes, 8 * 8 * 4);
        assert!(
            cache
                .acquire(device, LayerTextureKey::Content(3), 32, 32, format)
                .is_none()
        );
    }
}