gpui-fast 0.1.20

gpui: GPUI with gpui-fast rendering and layout optimizations
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
// Modified by Longbridge for gpui-fast.
//! Putting a finished scene in drawing order without moving its primitives
//! more than once or allocating, and scene helpers for tests: a finished scene
//! described as text, to compare two frames by, and forgetting the orderings
//! the bounds tree replays.

use crate::{
    DrawOrder, MonochromeSprite, PaintSurface, PaintedPath, PolychromeSprite, Quad, Scene, Shadow,
    SubpixelSprite, Underline,
};
use std::mem;

/// Room to sort a scene's primitives in, kept from one frame to the next so
/// that a frame does not allocate megabytes to put what it drew in order.
#[derive(Default)]
pub(crate) struct SortScratch {
    permutation: Permutation,
    shadows: Vec<Shadow>,
    quads: Vec<Quad>,
    paths: Vec<PaintedPath>,
    underlines: Vec<Underline>,
    monochrome_sprites: Vec<MonochromeSprite>,
    subpixel_sprites: Vec<SubpixelSprite>,
    polychrome_sprites: Vec<PolychromeSprite>,
    surfaces: Vec<PaintSurface>,
}

/// The order to gather a kind of primitive in, and what working it out takes.
#[derive(Default)]
struct Permutation {
    /// The index of the primitive to put at each place.
    order: Vec<u32>,
    /// For each draw order, how many primitives have it, and then where the
    /// next of them goes.
    counts: Vec<u32>,
    /// Draw orders packed with indices, when they are too spread out to count.
    keys: Vec<u64>,
    /// Sprites' draw orders, textures and tiles packed with indices.
    wide_keys: Vec<u128>,
}

/// How much wider than the number of primitives their draw orders may spread
/// before [`sort_by_draw_order`] sorts them rather than counting them, so that
/// the counts are never much longer than the primitives.
const MAX_ORDERS_PER_PRIMITIVE: usize = 4;

/// Puts `items` in draw order, keeping the order they came in among those of
/// one draw order, as a stable sort does.
///
/// A primitive's draw order is one past the greatest among the primitives
/// before it that it overlaps, or its layer's, so a scene of thousands of
/// primitives has a few dozen of them. They are counted rather than compared:
/// one pass counts how many primitives have each order, the next puts each
/// where its order's run is up to. Orders spread wider than
/// [`MAX_ORDERS_PER_PRIMITIVE`] allows are sorted as packed keys instead. A
/// scene with no primitive out of order is left as it is.
fn sort_by_draw_order<T: Clone>(
    items: &mut Vec<T>,
    permutation: &mut Permutation,
    gathered: &mut Vec<T>,
    draw_order: impl Fn(&T) -> DrawOrder,
) {
    if items.len() < 2 {
        return;
    }
    let mut max = 0;
    let mut sorted = true;
    let mut previous = 0;
    for item in items.iter() {
        let order = draw_order(item);
        sorted &= order >= previous;
        previous = order;
        max = max.max(order);
    }
    if sorted {
        return;
    }
    let Permutation {
        order,
        counts,
        keys,
        ..
    } = permutation;
    if max as usize > items.len() * MAX_ORDERS_PER_PRIMITIVE {
        keys.clear();
        keys.extend(
            items
                .iter()
                .enumerate()
                .map(|(index, item)| (u64::from(draw_order(item)) << 32) | index as u64),
        );
        keys.sort_unstable();
        order.clear();
        order.extend(keys.iter().map(|&key| key as u32));
    } else {
        counts.clear();
        counts.resize(max as usize + 1, 0);
        for item in items.iter() {
            counts[draw_order(item) as usize] += 1;
        }
        let mut start = 0;
        for count in counts.iter_mut() {
            let primitives = *count;
            *count = start;
            start += primitives;
        }
        order.clear();
        order.resize(items.len(), 0);
        for (index, item) in items.iter().enumerate() {
            let next = &mut counts[draw_order(item) as usize];
            order[*next as usize] = index as u32;
            *next += 1;
        }
    }
    gather(items, order, gathered);
}

/// Puts sprites in draw order, those of one draw order grouped by the atlas
/// texture they come from and then by tile, keeping the order they came in
/// among sprites of one tile, as a stable sort does.
///
/// The draw order, texture, tile and index of each sprite are packed into one
/// integer, so the sort compares integers lying next to each other rather
/// than reaching into a sprite for its key on every comparison. Sprites
/// already in that order are left as they are.
fn sort_sprites<T: Clone>(
    items: &mut Vec<T>,
    permutation: &mut Permutation,
    gathered: &mut Vec<T>,
    key: impl Fn(&T) -> (DrawOrder, u32, u32),
) {
    if items.len() < 2 {
        return;
    }
    let Permutation {
        order, wide_keys, ..
    } = permutation;
    wide_keys.clear();
    wide_keys.extend(items.iter().enumerate().map(|(index, item)| {
        let (draw_order, texture, tile) = key(item);
        (u128::from(draw_order) << 96)
            | (u128::from(texture) << 64)
            | (u128::from(tile) << 32)
            | index as u128
    }));
    if wide_keys.is_sorted() {
        return;
    }
    wide_keys.sort_unstable();
    order.clear();
    order.extend(wide_keys.iter().map(|&key| key as u32));
    gather(items, order, gathered);
}

/// Puts the item at `order[i]` at place `i`.
///
/// Sorting indices and then gathering once moves each item a single time,
/// where sorting the items themselves moves them as often as the sort needs
/// to compare them — and these items are 112 to 168 bytes each.
fn gather<T: Clone>(items: &mut Vec<T>, order: &[u32], gathered: &mut Vec<T>) {
    gathered.clear();
    gathered.extend(order.iter().map(|&index| items[index as usize].clone()));
    mem::swap(items, gathered);
}

impl Scene {
    /// Forgets the orderings recorded for replaying, so the next frame orders
    /// every primitive from scratch.
    #[cfg(test)]
    pub(crate) fn forget_orderings(&mut self) {
        self.primitive_bounds.forget();
    }

    /// Everything this finished scene draws, in drawing order, as text two
    /// scenes can be compared by: each primitive with its bounds, clip, colours
    /// and ordering, and each layer's bounds. Atlas tiles are left out, since
    /// two windows need not place the same glyph in the same tile.
    #[cfg(test)]
    pub(crate) fn describe(&self) -> Vec<String> {
        let mut lines = Vec::new();
        for operation in &self.paint_operations {
            match operation {
                crate::PaintOperation::StartLayer(bounds) => {
                    lines.push(format!("layer {bounds:?}"))
                }
                crate::PaintOperation::EndLayer => lines.push("end layer".into()),
                crate::PaintOperation::FastRoundedClip(clip) => {
                    lines.push(format!("rounded clip {clip:?}"))
                }
                crate::PaintOperation::Primitive(..) => {}
            }
        }
        lines.extend(self.shadows.iter().map(|shadow| format!("{shadow:?}")));
        lines.extend(self.quads.iter().map(|quad| format!("{quad:?}")));
        lines.extend(
            self.underlines
                .iter()
                .map(|underline| format!("{underline:?}")),
        );
        lines.extend(self.monochrome_sprites.iter().map(|sprite| {
            format!(
                "monochrome sprite {} {:?} {:?} {:?}",
                sprite.order, sprite.bounds, sprite.content_mask, sprite.color
            )
        }));
        lines.extend(self.subpixel_sprites.iter().map(|sprite| {
            format!(
                "subpixel sprite {} {:?} {:?} {:?}",
                sprite.order, sprite.bounds, sprite.content_mask, sprite.color
            )
        }));
        lines.extend(self.polychrome_sprites.iter().map(|sprite| {
            format!(
                "polychrome sprite {} {:?} {:?}",
                sprite.order, sprite.bounds, sprite.content_mask
            )
        }));
        lines.extend(
            self.paths
                .iter()
                .map(|path| format!("path {} {:?}", path.order, path.bounds)),
        );
        lines
    }
}

/// What [`Scene::finish`] does: puts every primitive in drawing order.
/// Sprites of one order are grouped by the atlas texture they come from:
/// a batch draws from one texture, and tile ids, which each texture
/// numbers from zero, would interleave them.
#[inline]
pub(crate) fn sort_in_drawing_order(scene: &mut Scene) {
    crate::fast::rounded_clip_scene::compile(scene);
    let scratch = &mut scene.sort_scratch;
    macro_rules! sort {
        ($field:ident, $order:expr) => {
            sort_by_draw_order(
                &mut scene.$field,
                &mut scratch.permutation,
                &mut scratch.$field,
                $order,
            )
        };
    }
    macro_rules! sort_sprites {
        ($field:ident) => {
            sort_sprites(
                &mut scene.$field,
                &mut scratch.permutation,
                &mut scratch.$field,
                |sprite| {
                    (
                        sprite.order,
                        sprite.tile.texture_id.index,
                        sprite.tile.tile_id.0,
                    )
                },
            )
        };
    }
    sort!(shadows, |shadow: &Shadow| shadow.order);
    sort!(quads, |quad: &Quad| quad.order);
    sort!(paths, |path: &PaintedPath| path.order);
    sort!(underlines, |underline: &Underline| underline.order);
    sort_sprites!(monochrome_sprites);
    sort_sprites!(subpixel_sprites);
    sort_sprites!(polychrome_sprites);
    sort!(surfaces, |surface: &PaintSurface| surface.order);
}

#[cfg(test)]
mod tests {
    #[test]
    fn replaying_a_layer_in_one_pass_inserts_what_painting_it_did() {
        use crate::scene::{PaintOperation, Primitive, Quad, Scene};
        use crate::{Bounds, ContentMask, ScaledPixels, point, size};
        let rect = |x: f32, y: f32, w: f32, h: f32| Bounds {
            origin: point(ScaledPixels(x), ScaledPixels(y)),
            size: size(ScaledPixels(w), ScaledPixels(h)),
        };
        let quad = |bounds: Bounds<ScaledPixels>, mask: Bounds<ScaledPixels>| Quad {
            bounds,
            content_mask: ContentMask { bounds: mask },
            ..Default::default()
        };
        let all = rect(0., 0., 1000., 1000.);
        let mut painted = Scene::default();
        painted.insert_primitive(quad(rect(0., 0., 100., 100.), all));
        painted.push_layer(rect(10., 10., 50., 20.));
        painted.insert_primitive(quad(rect(10., 10., 20., 20.), all));
        painted.insert_primitive(quad(rect(20., 10., 20., 20.), all));
        // Clipped away: left out of the layer's bounds and batches.
        painted.insert_primitive(quad(rect(500., 500., 20., 20.), rect(0., 0., 1., 1.)));
        painted.insert_primitive(quad(rect(40., 10., 20., 20.), all));
        painted.pop_layer();
        painted.push_layer(rect(0., 0., 0., 0.));
        painted.pop_layer();
        painted.insert_primitive(quad(rect(30., 15., 10., 10.), all));
        painted.push_layer(rect(0., 0., 300., 300.));
        painted.push_layer(rect(0., 0., 300., 300.)); // nested: the general path
        painted.insert_primitive(quad(rect(25., 25., 200., 200.), all));
        painted.pop_layer();
        painted.pop_layer();

        let mut replayed = Scene::default();
        replayed.replay(0..painted.len(), &painted);

        let quads = |scene: &Scene| {
            scene
                .quads
                .iter()
                .map(|quad| (quad.bounds, quad.order))
                .collect::<Vec<_>>()
        };
        assert_eq!(quads(&replayed), quads(&painted));
        let operations = |scene: &Scene| {
            scene
                .paint_operations
                .iter()
                .map(|operation| match operation {
                    PaintOperation::Primitive(Primitive::Quad(quad)) => {
                        format!("quad {:?} {}", quad.bounds, quad.order)
                    }
                    PaintOperation::StartLayer(bounds) => format!("start {bounds:?}"),
                    PaintOperation::EndLayer => "end".to_string(),
                    _ => "other".to_string(),
                })
                .collect::<Vec<_>>()
        };
        assert_eq!(operations(&replayed), operations(&painted));
    }

    use super::{MAX_ORDERS_PER_PRIMITIVE, Permutation, sort_by_draw_order, sort_sprites};
    use crate::DrawOrder;
    use rand::{Rng as _, SeedableRng as _, rngs::StdRng};

    /// A primitive as the sorts see it, and where it was before them.
    #[derive(Clone, Copy, PartialEq, Debug)]
    struct Item {
        order: DrawOrder,
        texture: u32,
        tile: u32,
        painted: usize,
    }

    /// Random primitives with draw orders below `orders`, from few textures
    /// and tiles so that many share them.
    fn items(rng: &mut StdRng, len: usize, orders: DrawOrder) -> Vec<Item> {
        (0..len)
            .map(|painted| Item {
                order: rng.random_range(0..orders),
                texture: rng.random_range(0..3),
                tile: rng.random_range(0..8),
                painted,
            })
            .collect()
    }

    /// Lengths and order spreads covering no items, one, orders already in
    /// order, orders counted, and orders spread too wide to count.
    fn cases(rng: &mut StdRng) -> Vec<Vec<Item>> {
        let mut cases = vec![Vec::new(), items(rng, 1, 5)];
        for _ in 0..200 {
            let len = rng.random_range(2..300);
            let spread = match rng.random_range(0..4) {
                0 => 1,
                1 => rng.random_range(2..30),
                2 => (len * MAX_ORDERS_PER_PRIMITIVE + 1) as DrawOrder,
                _ => rng.random_range(len * MAX_ORDERS_PER_PRIMITIVE + 2..100_000) as DrawOrder,
            };
            let mut case = items(rng, len, spread);
            // The greatest order is the one that decides how they are sorted.
            let greatest = rng.random_range(0..len);
            case[greatest].order = spread - 1;
            if rng.random_ratio(1, 5) {
                case.sort_by_key(|item| item.order);
            }
            cases.push(case);
        }
        cases
    }

    #[test]
    fn draw_order_sort_is_a_stable_sort_by_draw_order() {
        let mut rng = StdRng::seed_from_u64(7);
        let mut permutation = Permutation::default();
        let mut gathered = Vec::new();
        for case in cases(&mut rng) {
            let mut expected = case.clone();
            expected.sort_by_key(|item| item.order);
            let mut sorted = case.clone();
            sort_by_draw_order(&mut sorted, &mut permutation, &mut gathered, |item| {
                item.order
            });
            assert_eq!(sorted, expected, "sorting {case:?}");
        }
    }

    #[test]
    fn draw_order_sort_counts_orders_unless_they_spread_too_wide() {
        let mut rng = StdRng::seed_from_u64(13);
        let mut gathered = Vec::new();
        let (mut counted, mut packed) = (0, 0);
        for mut case in cases(&mut rng) {
            let mut permutation = Permutation::default();
            let in_order = case.is_sorted_by_key(|item| item.order);
            let greatest = case.iter().map(|item| item.order).max().unwrap_or(0) as usize;
            sort_by_draw_order(&mut case, &mut permutation, &mut gathered, |item| {
                item.order
            });
            let (counts, keys) = (permutation.counts.len(), permutation.keys.len());
            if in_order {
                assert_eq!((counts, keys), (0, 0), "sorting what is in order");
            } else if greatest > case.len() * MAX_ORDERS_PER_PRIMITIVE {
                assert_eq!((counts, keys), (0, case.len()), "orders up to {greatest}");
                packed += 1;
            } else {
                assert_eq!((counts, keys), (greatest + 1, 0), "orders up to {greatest}");
                counted += 1;
            }
        }
        assert!(
            counted > 0 && packed > 0,
            "{counted} counted, {packed} packed"
        );
    }

    #[test]
    fn draw_order_sort_counts_orders_up_to_the_widest_spread_it_allows() {
        let mut permutation = Permutation::default();
        let mut gathered = Vec::new();
        let item = |order, painted| Item {
            order,
            texture: 0,
            tile: 0,
            painted,
        };
        let widest = (2 * MAX_ORDERS_PER_PRIMITIVE) as DrawOrder;
        let mut sorted = vec![item(widest, 0), item(0, 1)];
        sort_by_draw_order(&mut sorted, &mut permutation, &mut gathered, |item| {
            item.order
        });
        assert_eq!(sorted, [item(0, 1), item(widest, 0)]);
        assert_eq!(permutation.counts.len(), widest as usize + 1);

        let mut sorted = vec![item(widest + 1, 0), item(0, 1)];
        sort_by_draw_order(&mut sorted, &mut permutation, &mut gathered, |item| {
            item.order
        });
        assert_eq!(sorted, [item(0, 1), item(widest + 1, 0)]);
        assert_eq!(permutation.keys.len(), 2);
    }

    #[test]
    fn sprite_sort_is_a_stable_sort_by_order_texture_and_tile() {
        let mut rng = StdRng::seed_from_u64(11);
        let mut permutation = Permutation::default();
        let mut gathered = Vec::new();
        for case in cases(&mut rng) {
            let mut expected = case.clone();
            expected.sort_by_key(|item| (item.order, item.texture, item.tile));
            let mut sorted = case.clone();
            sort_sprites(&mut sorted, &mut permutation, &mut gathered, |item| {
                (item.order, item.texture, item.tile)
            });
            assert_eq!(sorted, expected, "sorting {case:?}");
            sort_sprites(&mut sorted, &mut permutation, &mut gathered, |item| {
                (item.order, item.texture, item.tile)
            });
            assert_eq!(sorted, expected, "sorting {case:?} again");
        }
    }

    #[test]
    fn sprite_sort_keeps_every_bit_of_its_keys() {
        let mut permutation = Permutation::default();
        let mut gathered = Vec::new();
        let item = |order, texture, tile, painted| Item {
            order,
            texture,
            tile,
            painted,
        };
        let mut sorted = vec![
            item(u32::MAX, 0, 0, 0),
            item(0, u32::MAX, 0, 1),
            item(0, 0, u32::MAX, 2),
            item(0, 0, 0, 3),
        ];
        sort_sprites(&mut sorted, &mut permutation, &mut gathered, |item| {
            (item.order, item.texture, item.tile)
        });
        let painted: Vec<usize> = sorted.iter().map(|item| item.painted).collect();
        assert_eq!(painted, [3, 2, 1, 0]);
    }
}

/// What a platform's partial redraw compares a painted path by: its draw
/// order and a key that changes when the pixels it paints may change (its
/// binned tiles, shared while the path keeps its shape and place, and its
/// paint).
pub fn painted_path_key(path: &PaintedPath) -> (DrawOrder, u64) {
    use std::hash::{Hash as _, Hasher as _};
    let mut hasher = collections::FxHasher::default();
    (std::rc::Rc::as_ptr(&path.tiles) as usize).hash(&mut hasher);
    for value in [
        path.bounds.origin.x.0,
        path.bounds.origin.y.0,
        path.bounds.size.width.0,
        path.bounds.size.height.0,
    ] {
        value.to_bits().hash(&mut hasher);
    }
    format!("{:?}", path.paint.color).hash(&mut hasher);
    (path.paint.even_odd == true.into()).hash(&mut hasher);
    (path.order, hasher.finish())
}

/// Sets the draw order of `primitive`, as the scene keeps it in its paint
/// operations: upstream assigns orders only to the primitives it batches,
/// while `fast::layers` reads them from the paint operations (baking a
/// layer's background, ordering its tiles).
pub(crate) fn set_draw_order(primitive: &mut crate::scene::Primitive, order: DrawOrder) {
    use crate::scene::Primitive;
    match primitive {
        Primitive::Shadow(p) => p.order = order,
        Primitive::Quad(p) => p.order = order,
        Primitive::Path(p) => p.order = order,
        Primitive::Underline(p) => p.order = order,
        Primitive::MonochromeSprite(p) => p.order = order,
        Primitive::SubpixelSprite(p) => p.order = order,
        Primitive::PolychromeSprite(p) => p.order = order,
        Primitive::Surface(p) => p.order = order,
        Primitive::NativeView(p) => p.order = order,
    }
}

/// Starts collecting the pieces upstream's `Window::insert_quad` splits a
/// quad into, to insert them together at [`end_quad_pieces`].
pub(crate) fn begin_quad_pieces(scene: &mut Scene) {
    scene.fast_quad_pieces = Some(smallvec::SmallVec::new());
}

pub(crate) fn end_quad_pieces(scene: &mut Scene) {
    if let Some(pieces) = scene.fast_quad_pieces.take() {
        insert_quad_pieces(scene, &pieces);
    }
}

/// Keeps `primitive` as a piece while pieces are collected, or hands it back.
pub(crate) fn quad_piece(
    scene: &mut Scene,
    primitive: crate::scene::Primitive,
) -> Option<crate::scene::Primitive> {
    match (&mut scene.fast_quad_pieces, primitive) {
        (Some(pieces), crate::scene::Primitive::Quad(quad)) => {
            pieces.push(quad);
            None
        }
        (_, primitive) => Some(primitive),
    }
}

/// Inserts the pieces a quad was split into (upstream's `Window::insert_quad`
/// splits a bordered or rounded quad into its interior and four strips).
///
/// The pieces don't overlap, so they can share one place in the drawing
/// order: the one the quad as a whole would get. That is one insert into the
/// bounds tree instead of five, and the same insert from one frame to the
/// next, which the tree replays. Inside a layer the pieces already share the
/// layer's place, so they are inserted as they are.
pub(crate) fn insert_quad_pieces(scene: &mut Scene, pieces: &[Quad]) {
    if pieces.len() < 2 || !scene.fast_top_level() {
        for piece in pieces {
            scene.insert_primitive(*piece);
        }
        return;
    }
    let pieces: smallvec::SmallVec<[_; 5]> = pieces
        .iter()
        .map(|piece| (*piece, quad_clipped_bounds(piece)))
        .collect();
    insert_bounded_pieces(scene, &pieces);
}

/// A quad's bounds clipped to its content mask (quads have no transformation),
/// without building a `Primitive` around it.
#[inline]
fn quad_clipped_bounds(quad: &Quad) -> crate::Bounds<crate::ScaledPixels> {
    quad.bounds.intersect(&quad.content_mask.bounds)
}

/// [`insert_quad_pieces`] with each piece's clipped bounds worked out once.
fn insert_bounded_pieces(scene: &mut Scene, pieces: &[(Quad, crate::Bounds<crate::ScaledPixels>)]) {
    if pieces.len() < 2 || !scene.fast_top_level() {
        for (piece, _) in pieces {
            scene.insert_primitive(*piece);
        }
        return;
    }
    let mut union = None::<crate::Bounds<crate::ScaledPixels>>;
    for (_, bounds) in pieces {
        if !bounds.is_empty() {
            union = Some(match union {
                Some(union) => union.join(bounds),
                None => *bounds,
            });
        }
    }
    let Some(union) = union else {
        return;
    };
    let order = scene.primitive_bounds.insert(union);
    for (piece, bounds) in pieces {
        if bounds.is_empty() {
            continue;
        }
        scene.fast_push_quad(*piece, order);
    }
}

/// Consecutive quads being replayed that can be inserted as the pieces of
/// one, see [`insert_quad_pieces`]: they have the same bounds (a split quad's
/// pieces keep the bounds of the whole) and don't overlap.
#[derive(Default)]
pub(crate) struct QuadRun {
    pieces: smallvec::SmallVec<[(Quad, crate::Bounds<crate::ScaledPixels>); 5]>,
}

impl QuadRun {
    pub(crate) fn push(&mut self, scene: &mut Scene, quad: Quad) {
        let bounds = quad_clipped_bounds(&quad);
        if let Some((first, _)) = self.pieces.first()
            && (first.bounds != quad.bounds
                || self
                    .pieces
                    .iter()
                    .any(|(_, piece)| piece.intersects(&bounds)))
        {
            self.flush(scene);
        }
        self.pieces.push((quad, bounds));
    }

    pub(crate) fn flush(&mut self, scene: &mut Scene) {
        if !self.pieces.is_empty() {
            insert_bounded_pieces(scene, &self.pieces);
            self.pieces.clear();
        }
    }
}

/// Replays a top-level layer of the previous scene (`operations` starts at its
/// `StartLayer`) the way painting it would insert it: one place in the drawing
/// order for the union of what it painted, in one pass instead of collecting
/// it as a pending layer. Gives up (`None`) on nested layers, rounded clips and
/// native views, which the general path handles; otherwise returns how many
/// operations it replayed.
pub(crate) fn replay_flat_layer(
    scene: &mut Scene,
    operations: &[crate::scene::PaintOperation],
) -> Option<usize> {
    use crate::scene::{PaintOperation, Primitive};
    let PaintOperation::StartLayer(layer_bounds) = operations.first()? else {
        return None;
    };
    let mut union = None::<crate::Bounds<crate::ScaledPixels>>;
    let mut end = None;
    // What painting clipped away, which is rare.
    let mut clipped_away = smallvec::SmallVec::<[usize; 4]>::new();
    for (index, operation) in operations.iter().enumerate().skip(1) {
        match operation {
            PaintOperation::Primitive(Primitive::NativeView(_)) => return None,
            PaintOperation::Primitive(primitive) => {
                let bounds = primitive.clipped_bounds();
                if bounds.is_empty() {
                    clipped_away.push(index);
                } else {
                    union = Some(match union {
                        Some(union) => union.join(&bounds),
                        None => bounds,
                    });
                }
            }
            PaintOperation::EndLayer => {
                end = Some(index);
                break;
            }
            PaintOperation::StartLayer(_) | PaintOperation::FastRoundedClip(_) => return None,
        }
    }
    let end = end?;
    scene
        .paint_operations
        .push(PaintOperation::StartLayer(*layer_bounds));
    if let Some(union) = union {
        let order = scene.primitive_bounds.insert(union);
        for (index, operation) in operations[..end].iter().enumerate().skip(1) {
            if let PaintOperation::Primitive(primitive) = operation
                && !clipped_away.contains(&index)
            {
                scene.fast_push_painted(primitive, order);
            }
        }
    }
    scene.paint_operations.push(PaintOperation::EndLayer);
    Some(end + 1)
}