cranpose-render-pixels 0.13.0

Software renderer for Cranpose scenes and RGBA framebuffers
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
use std::{ops::Range, rc::Rc, sync::Arc};

use cranpose_render_common::{
    Brush,
    graph::{
        LayerNode, PrimitiveEntry, PrimitiveNode, PrimitivePhase, ProjectiveTransform, RenderGraph,
        RenderNode, TextPrimitiveNode,
    },
    graph_scene::RenderDiagnostics,
    hit_graph::collect_hits_from_graph,
    layer_composition::folded_layer_alpha,
    layer_shadow::{ShadowLight, layer_shadow_geometry},
    layer_transform::{apply_layer_affine_to_rect, apply_layer_to_rect, layer_uniform_scale},
    primitive_emit::{
        DrawPrimitiveSink, ImageDrawParams, PrimitiveClipSpace, ShapeDrawParams, TextDrawParams,
        draw_shape_params_for_primitive, emit_draw_primitive, resolve_clip, resolve_primitive_clip,
    },
};
use cranpose_ui::{
    LayoutBox, measure_text,
    text::{TextDecoration, TextStyle},
};
use cranpose_ui_graphics::{
    BlendMode, Color, ColorFilter, CompositingStrategy, DrawPrimitive, GraphicsLayer, LayerShape,
    Point, Rect, RenderEffect, RoundedCornerShape, TransformOrigin, whole,
};

use crate::{
    scene::{ItemCounts, PassedDown, RasterScene, Scene},
    style::{
        apply_layer_to_brush, apply_layer_to_color, compose_color_filters, scale_corner_radii,
    },
};

fn graphics_layer_supports_rigid_snap(layer: &GraphicsLayer) -> bool {
    (layer.scale - 1.0).abs() <= f32::EPSILON
        && (layer.scale_x - 1.0).abs() <= f32::EPSILON
        && (layer.scale_y - 1.0).abs() <= f32::EPSILON
        && layer.rotation_x.abs() <= f32::EPSILON
        && layer.rotation_y.abs() <= f32::EPSILON
        && layer.rotation_z.abs() <= f32::EPSILON
}

fn rigid_snap_anchor(layer_bounds: Rect, layer: &GraphicsLayer) -> Option<Point> {
    if !graphics_layer_supports_rigid_snap(layer) {
        return None;
    }
    let mapped = apply_layer_affine_to_rect(layer_bounds, layer_bounds, layer);
    Some(Point::new(mapped.x, mapped.y))
}

fn assign_snap_anchor_since(
    scene: &mut RasterScene,
    counts: ItemCounts,
    snap_anchor: Option<Point>,
) {
    let Some(snap_anchor) = snap_anchor else {
        return;
    };

    for shape in &mut scene.shapes[counts.shapes..] {
        shape.snap_anchor = Some(snap_anchor);
    }
    for image in &mut scene.images[counts.images..] {
        image.snap_anchor = Some(snap_anchor);
    }
    for text in &mut scene.texts[counts.texts..] {
        text.snap_anchor = Some(snap_anchor);
    }
    for shadow in &mut scene.shadows[counts.shadows..] {
        shadow.snap_anchor = Some(snap_anchor);
    }
}

#[derive(Clone, Copy)]
struct PrimitiveRenderContext<'a> {
    layer_bounds: RasterLayerBounds,
    node_layer: &'a GraphicsLayer,
    visual_clip: Option<Rect>,
    motion_context_animated: bool,
    content_offset_translation: bool,
    layer_snap_anchor: Option<Point>,
}

/// The alpha and colour filter content draws with: a layer's own folded
/// alpha and filter combined with those of every layer above it. No other
/// property of a layer passes to the content beneath it.
#[derive(Clone)]
struct ContentStyle {
    alpha: f32,
    color_filter: Option<ColorFilter>,
}

impl ContentStyle {
    const PLAIN: Self = Self {
        alpha: 1.0,
        color_filter: None,
    };

    /// The style of `layer`'s content beneath content drawn in `self`.
    fn under(&self, layer: &GraphicsLayer) -> Self {
        Self {
            alpha: (self.alpha * folded_layer_alpha(layer)).clamp(0.0, 1.0),
            color_filter: compose_color_filters(
                self.color_filter.as_ref(),
                layer.color_filter.as_ref(),
            ),
        }
    }
}

struct RasterTraversalContext<'a> {
    parent_transform: &'a ProjectiveTransform,
    parent_content_style: &'a ContentStyle,
    parent_visual_clip: Option<Rect>,
    inherited_translated_snap_anchor: Option<Point>,
    inherited_translated_content_context: bool,
    diagnostics: &'a RenderDiagnostics,
    /// The window's shadow light in device pixels, the space the raster
    /// scene is drawn in.
    light: ShadowLight,
    /// Whether everything above is what the walk passed down to the layer's
    /// old record in the frame before's scene.
    same_as_before: bool,
}

/// The scene the frame before built, whose items a walk copies for each
/// subtree that did not change since.
struct Reuse<'a> {
    old: &'a RasterScene,
    /// The old record of the layer the walk reaches next, while the graph
    /// keeps the shape it had.
    cursor: usize,
    /// The old records of unchanged subtrees, siblings one after another,
    /// to copy before the scene takes anything else, and the counts their
    /// items reach there: a run of them copies as one.
    pending: Option<(Range<usize>, ItemCounts)>,
}

impl Reuse<'_> {
    /// The index of `layer`'s old record, at the cursor or one subtree on,
    /// after a sibling before it went away.
    fn find(&self, layer: &LayerNode) -> Option<usize> {
        let identity = (layer.node_id, layer.wraps);
        let records = &self.old.subtrees;
        let at = records.get(self.cursor)?;
        if at.identity == identity {
            return Some(self.cursor);
        }
        records
            .get(at.end)
            .is_some_and(|next| next.identity == identity)
            .then_some(at.end)
    }

    /// Queues the copy of the subtree of the old record `index`, which ends
    /// at `end` and pushed its items up to `stop`.
    fn copy_later(&mut self, scene: &mut RasterScene, index: usize, end: usize, stop: ItemCounts) {
        match &mut self.pending {
            Some((records, pending_stop)) if records.end == index => {
                records.end = end;
                *pending_stop = stop;
            }
            _ => {
                self.flush(scene);
                self.pending = Some((index..end, stop));
            }
        }
    }

    /// Copies the queued subtrees into `scene`.
    fn flush(&mut self, scene: &mut RasterScene) {
        if let Some((records, stop)) = self.pending.take() {
            scene.copy_subtrees(self.old, records, stop);
        }
    }
}

/// Copies the subtrees `reuse` queued into `scene`, before it takes items of
/// its own.
fn flush_copies(reuse: &mut Option<Reuse<'_>>, scene: &mut RasterScene) {
    if let Some(reuse) = reuse.as_mut() {
        reuse.flush(scene);
    }
}

fn layer_contains_text_primitives(layer: &LayerNode) -> bool {
    layer.children.iter().any(|child| {
        matches!(
            child,
            RenderNode::Primitive(PrimitiveEntry {
                node: PrimitiveNode::Text(_),
                ..
            })
        )
    })
}

fn layer_contains_draw_primitives(layer: &LayerNode) -> bool {
    layer.children.iter().any(|child| {
        matches!(
            child,
            RenderNode::Primitive(PrimitiveEntry {
                node: PrimitiveNode::Draw(_),
                ..
            })
        )
    })
}

fn layer_needs_rigid_snap(layer: &LayerNode, translated_content_context: bool) -> bool {
    (translated_content_context
        && (layer_contains_draw_primitives(layer) || layer_contains_text_primitives(layer)))
        || (layer_contains_text_primitives(layer) && layer_contains_draw_primitives(layer))
}

fn is_render_effect_supported(_effect: &RenderEffect) -> bool {
    false
}

fn layer_requires_effect_fallback(layer: &GraphicsLayer) -> bool {
    layer
        .render_effect
        .as_ref()
        .is_some_and(|effect| !is_render_effect_supported(effect))
        || layer
            .backdrop_effect
            .as_ref()
            .is_some_and(|effect| !is_render_effect_supported(effect))
        || layer.compositing_strategy == CompositingStrategy::Offscreen
        || layer.blend_mode != BlendMode::SrcOver
}

fn report_unsupported_effects(layer: &GraphicsLayer, diagnostics: &RenderDiagnostics) {
    if layer_requires_effect_fallback(layer)
        && diagnostics.claim_warning_once("pixels.unsupported-layer-effect")
    {
        log::warn!(
            "Pixels renderer does not support render/backdrop effects, offscreen compositing, or non-SrcOver layer blend modes; falling back to base layer rendering"
        );
    }
}

#[derive(Clone, Copy)]
struct ShadowSample {
    expansion: f32,
    weight: f32,
}

fn blur_samples(blur_radius: f32) -> Vec<ShadowSample> {
    if blur_radius <= f32::EPSILON {
        return Vec::new();
    }

    let sample_count = (whole::ceil(blur_radius * 2.4) as usize).clamp(8, 36);
    let sigma = (blur_radius * 0.5).max(1.0);
    let mut samples = Vec::with_capacity(sample_count);
    let mut weight_sum = 0.0f32;

    for index in 0..sample_count {
        let t0 = index as f32 / sample_count as f32;
        let t1 = (index + 1) as f32 / sample_count as f32;
        let center = blur_radius * (t0 + t1) * 0.5;
        let expansion = blur_radius * t1;
        let weight = (-0.5 * (center / sigma).powi(2)).exp().max(0.0001);
        samples.push(ShadowSample { expansion, weight });
        weight_sum += weight;
    }

    if weight_sum <= f32::EPSILON {
        return vec![ShadowSample {
            expansion: blur_radius,
            weight: 1.0,
        }];
    }

    for sample in &mut samples {
        sample.weight /= weight_sum;
    }

    samples
}

fn expanded_shape_rect(shape: &crate::scene::DrawShape, expansion: f32) -> Rect {
    Rect {
        x: shape.rect.x - expansion,
        y: shape.rect.y - expansion,
        width: (shape.rect.width + expansion * 2.0).max(0.0),
        height: (shape.rect.height + expansion * 2.0).max(0.0),
    }
}

fn push_blurred_shape_samples(
    scene: &mut RasterScene,
    shape: &crate::scene::DrawShape,
    blend_mode: BlendMode,
    clip: Option<Rect>,
    blur_radius: f32,
) {
    let samples = blur_samples(blur_radius.max(1.0));
    if samples.is_empty() {
        scene.push_shape(
            shape.rect,
            shape.brush.clone(),
            shape.shape,
            clip,
            blend_mode,
        );
        return;
    }

    for sample in samples.iter().rev() {
        scene.push_shape(
            expanded_shape_rect(shape, sample.expansion),
            scale_brush_alpha(shape.brush.clone(), sample.weight),
            shape.shape,
            clip,
            blend_mode,
        );
    }
}

fn scale_color_alpha(color: Color, alpha: f32) -> Color {
    Color(
        color.r(),
        color.g(),
        color.b(),
        (color.a() * alpha).clamp(0.0, 1.0),
    )
}

fn scale_brush_alpha(brush: Brush, alpha: f32) -> Brush {
    match brush {
        Brush::Solid(color) => Brush::solid(scale_color_alpha(color, alpha)),
        Brush::LinearGradient {
            mut colors,
            stops,
            start,
            end,
            tile_mode,
        } => {
            for color in &mut colors {
                *color = scale_color_alpha(*color, alpha);
            }
            Brush::LinearGradient {
                colors,
                stops,
                start,
                end,
                tile_mode,
            }
        }
        Brush::RadialGradient {
            mut colors,
            stops,
            center,
            radius,
            tile_mode,
        } => {
            for color in &mut colors {
                *color = scale_color_alpha(*color, alpha);
            }
            Brush::RadialGradient {
                colors,
                stops,
                center,
                radius,
                tile_mode,
            }
        }
        Brush::SweepGradient {
            mut colors,
            stops,
            center,
        } => {
            for color in &mut colors {
                *color = scale_color_alpha(*color, alpha);
            }
            Brush::SweepGradient {
                colors,
                stops,
                center,
            }
        }
    }
}

fn push_layer_shadow(
    scene: &mut RasterScene,
    layer: &GraphicsLayer,
    layer_bounds: RasterLayerBounds,
    transformed_bounds: Rect,
    clip: Option<Rect>,
    light: ShadowLight,
) {
    if layer.shadow_elevation <= 0.0 {
        return;
    }
    let caster = match layer.shape {
        LayerShape::Rectangle => None,
        LayerShape::Rounded(shape) => {
            let scale = layer_uniform_scale(layer).max(0.1);
            let resolved = shape.resolve(
                layer_bounds.local_bounds.width,
                layer_bounds.local_bounds.height,
            );
            Some(RoundedCornerShape::with_radii(scale_corner_radii(
                resolved, scale,
            )))
        }
    };
    for (shadow, color) in layer_shadow_geometry(layer, transformed_bounds, caster, light).passes()
    {
        scene.push_shadow(shadow, color, clip);
    }
}

pub(crate) fn render_layout_tree(root: &LayoutBox, scene: &mut Scene) {
    let graph = cranpose_render_common::scene_builder::build_graph_from_layout_tree(root, 1.0);
    collect_hits_from_graph(&graph.root, ProjectiveTransform::identity(), scene, None);
    scene.replace_graph(graph);
}

fn resolve_text_color_without_gradient_fallback(text_style: &TextStyle, default: Color) -> Color {
    let mut color = text_style
        .span_style
        .color
        .or(match text_style.span_style.brush.as_ref() {
            Some(Brush::Solid(color)) => Some(*color),
            _ => None,
        })
        .unwrap_or(default);
    if let Some(alpha) = text_style.span_style.alpha {
        color.3 *= alpha.clamp(0.0, 1.0);
    }
    color
}

#[expect(clippy::too_many_arguments)]
fn push_text_style_draws(
    scene: &mut RasterScene,
    rect: Rect,
    text_rect: Rect,
    node_layer: &GraphicsLayer,
    text: &Rc<cranpose_ui::text::AnnotatedString>,
    text_style: &Arc<TextStyle>,
    font_size: f32,
    text_clip: Option<Rect>,
) {
    let baseline_shift_px = text_style
        .span_style
        .baseline_shift
        .filter(|shift| shift.is_specified())
        .map_or(0.0, |shift| -(shift.0 * font_size));
    let shifted_text_rect = Rect {
        x: text_rect.x,
        y: text_rect.y + baseline_shift_px,
        width: text_rect.width,
        height: text_rect.height,
    };
    let transformed_shifted_text_rect = apply_layer_to_rect(shifted_text_rect, rect, node_layer);

    if let Some(background) = text_style.span_style.background {
        let brush = apply_layer_to_brush(Brush::solid(background), node_layer);
        scene.push_shape(
            transformed_shifted_text_rect,
            brush,
            None,
            text_clip,
            BlendMode::SrcOver,
        );
    }

    let text_color =
        resolve_text_color_without_gradient_fallback(text_style, Color(1.0, 1.0, 1.0, 1.0));
    let transformed_text_color = apply_layer_to_color(text_color, node_layer);
    // The glyphs draw without the shadow and with the brush the layer
    // tints; a style with neither is shared as it is.
    let transformed_text_style =
        if text_style.span_style.shadow.is_none() && text_style.span_style.brush.is_none() {
            Arc::clone(text_style)
        } else {
            let mut style = TextStyle::clone(text_style);
            style.span_style.shadow = None;
            style.span_style.brush = text_style
                .span_style
                .brush
                .clone()
                .map(|brush| apply_layer_to_brush(brush, node_layer));
            Arc::new(style)
        };
    let text_brush = transformed_text_style
        .span_style
        .brush
        .clone()
        .unwrap_or_else(|| Brush::solid(transformed_text_color));

    if let Some(shadow) = text_style.span_style.shadow {
        let shadow_rect = Rect {
            x: shifted_text_rect.x + shadow.offset.x,
            y: shifted_text_rect.y + shadow.offset.y,
            width: shifted_text_rect.width,
            height: shifted_text_rect.height,
        };
        let transformed_shadow_rect = apply_layer_to_rect(shadow_rect, rect, node_layer);
        let transformed_shadow_color = apply_layer_to_color(shadow.color, node_layer);
        let mut shadow_text_style = TextStyle::clone(&transformed_text_style);
        shadow_text_style.span_style.brush = None;
        shadow_text_style.span_style.shadow = Some(cranpose_ui::text::Shadow {
            color: transformed_shadow_color,
            offset: Point::new(0.0, 0.0),
            blur_radius: shadow.blur_radius,
        });
        scene.push_text(
            transformed_shadow_rect,
            Rc::clone(text),
            Color::TRANSPARENT,
            Arc::new(shadow_text_style),
            font_size,
            layer_uniform_scale(node_layer),
            text_clip,
        );
    }

    scene.push_text(
        transformed_shifted_text_rect,
        Rc::clone(text),
        transformed_text_color,
        transformed_text_style,
        font_size,
        layer_uniform_scale(node_layer),
        text_clip,
    );

    push_text_decorations(
        scene,
        rect,
        shifted_text_rect,
        node_layer,
        text,
        text_style,
        &text_brush,
        text_clip,
    );
}

#[expect(clippy::too_many_arguments)]
fn push_text_decorations(
    scene: &mut RasterScene,
    rect: Rect,
    text_rect: Rect,
    content_layer: &GraphicsLayer,
    annotated_text: &cranpose_ui::text::AnnotatedString,
    global_style: &TextStyle,
    text_brush: &Brush,
    text_clip: Option<Rect>,
) {
    // A span draws a line only when its style or a span over it has one;
    // without any, measuring the spans finds nothing to draw.
    let decorated = |style: &cranpose_ui::text::SpanStyle| {
        style
            .text_decoration
            .is_some_and(|decoration| decoration != TextDecoration::NONE)
    };
    if annotated_text.is_empty()
        || !(decorated(&global_style.span_style)
            || annotated_text
                .span_styles
                .iter()
                .any(|span| decorated(&span.item)))
    {
        return;
    }

    let boundaries = annotated_text.span_boundaries();
    let text_str = annotated_text.text.as_str();

    let mut current_offset: f32 = 0.0;

    for window in boundaries.windows(2) {
        let start = window[0];
        let end = window[1];
        if start == end {
            continue;
        }

        let slice = &text_str[start..end];
        let mut merged_style = global_style.span_style.clone();
        for span in &annotated_text.span_styles {
            if span.range.start <= start && span.range.end >= end {
                merged_style = merged_style.merge(&span.item);
            }
        }

        let mut span_text_style = global_style.clone();
        span_text_style.span_style = merged_style.clone();

        let span_width = measure_text(
            &cranpose_ui::text::AnnotatedString::from(slice),
            &span_text_style,
        )
        .width
        .max(0.0);

        let Some(decoration) = merged_style.text_decoration else {
            current_offset += span_width;
            continue;
        };

        if decoration == TextDecoration::NONE || span_width <= 0.0 {
            current_offset += span_width;
            continue;
        }

        let font_size = span_text_style.resolve_font_size(14.0);
        let line_height = cranpose_ui::text::text_line_box(&span_text_style)
            .map_or_else(
                || span_text_style.resolve_line_height(14.0, font_size),
                |line_box| line_box.block_height(1),
            )
            .max(1.0);
        let thickness = (font_size * 0.06).clamp(1.0, line_height * 0.25);
        let brush = merged_style.brush.clone().unwrap_or_else(|| {
            merged_style
                .color
                .map_or_else(|| text_brush.clone(), Brush::solid)
        });

        let line_top = text_rect.y;

        if decoration.contains(TextDecoration::UNDERLINE) {
            let underline_rect = text_decoration_rect(
                text_rect.x + current_offset,
                line_top + line_height - thickness * 1.35,
                span_width,
                thickness,
            );
            let transformed = apply_layer_to_rect(underline_rect, rect, content_layer);
            scene.push_pixel_snapped_shape(
                transformed,
                brush.clone(),
                None,
                text_clip,
                BlendMode::SrcOver,
            );
        }

        if decoration.contains(TextDecoration::LINE_THROUGH) {
            let strike_rect = text_decoration_rect(
                text_rect.x + current_offset,
                line_top + line_height * 0.52 - thickness * 0.5,
                span_width,
                thickness,
            );
            let transformed = apply_layer_to_rect(strike_rect, rect, content_layer);
            scene.push_pixel_snapped_shape(transformed, brush, None, text_clip, BlendMode::SrcOver);
        }

        current_offset += span_width;
    }
}

fn text_decoration_rect(x: f32, y: f32, width: f32, thickness: f32) -> Rect {
    Rect {
        x,
        y,
        width,
        height: whole::ceil(thickness).max(1.0),
    }
}

#[cfg(test)]
use cranpose_render_common::scene_builder::expand_text_bounds_for_baseline_shift;

pub(crate) fn build_raster_scene(
    graph: &RenderGraph,
    diagnostics: &RenderDiagnostics,
    scale: f32,
) -> RasterScene {
    let mut scene = RasterScene::new();
    fill_raster_scene(&mut scene, graph, diagnostics, scale, None);
    scene
}

/// Replaces what `scene` holds with `graph` drawn at `scale`, keeping the
/// scene's storage. The items of each subtree that `previous`, the scene of
/// the frame before, holds for the same content in the same place are
/// copied from it.
pub(crate) fn fill_raster_scene(
    scene: &mut RasterScene,
    graph: &RenderGraph,
    diagnostics: &RenderDiagnostics,
    scale: f32,
    previous: Option<&RasterScene>,
) {
    scene.clear();
    let light = ShadowLight::for_window(
        graph.root.local_bounds.width * scale,
        graph.root.local_bounds.height * scale,
        scale,
        1.0,
    );
    scene.start = Some((scale, light));
    let mut reuse = previous.map(|old| Reuse {
        old,
        cursor: 0,
        pending: None,
    });
    populate_draws_from_graph(
        &graph.root,
        scene,
        &RasterTraversalContext {
            parent_transform: &ProjectiveTransform::uniform_scale(scale),
            parent_content_style: &ContentStyle::PLAIN,
            parent_visual_clip: None,
            inherited_translated_snap_anchor: None,
            inherited_translated_content_context: false,
            diagnostics,
            light,
            same_as_before: previous.is_some_and(|old| old.start == scene.start),
        },
        &mut reuse,
    );
    flush_copies(&mut reuse, scene);
}

#[derive(Clone, Copy)]
struct RasterLayerBounds {
    device_origin: Point,
    local_bounds: Rect,
}

impl RasterLayerBounds {
    fn from_transformed_bounds(transformed_bounds: Rect, local_bounds: Rect) -> Self {
        Self {
            device_origin: Point::new(transformed_bounds.x, transformed_bounds.y),
            local_bounds,
        }
    }

    fn raster_rect(self) -> Rect {
        Rect {
            x: self.device_origin.x,
            y: self.device_origin.y,
            width: self.local_bounds.width,
            height: self.local_bounds.height,
        }
    }
}

struct RasterLayerMapping {
    layer_bounds: RasterLayerBounds,
    /// Where the node's own draws and text sit: its rect, whose origin is
    /// the node's even where its layer is bounded at a coordinator away
    /// from it.
    content_bounds: RasterLayerBounds,
    transformed_bounds: Rect,
    content_style: ContentStyle,
    scale_x: f32,
    scale_y: f32,
}

impl RasterLayerMapping {
    /// The layer the node's own draws take: its content style, scaled from
    /// local to device pixels about its origin.
    fn content_layer(&self) -> GraphicsLayer {
        GraphicsLayer {
            alpha: self.content_style.alpha,
            color_filter: self.content_style.color_filter.clone(),
            scale_x: self.scale_x,
            scale_y: self.scale_y,
            transform_origin: TransformOrigin::new(0.0, 0.0),
            ..GraphicsLayer::default()
        }
    }
}

fn raster_layer_scale(transformed_bounds: Rect, local_bounds: Rect) -> (f32, f32) {
    (
        axis_scale(transformed_bounds.width, local_bounds.width).max(0.0),
        axis_scale(transformed_bounds.height, local_bounds.height).max(0.0),
    )
}

/// How far a transform stretches an axis of `local` extent to `transformed`,
/// 1 for an empty axis. An axis it keeps gives 1 without the division, which
/// a chip with no float divider pays for on every layer.
fn axis_scale(transformed: f32, local: f32) -> f32 {
    if local.abs() <= f32::EPSILON || (transformed == local && local.is_finite()) {
        1.0
    } else {
        transformed / local
    }
}

fn raster_layer_mapping(
    layer: &LayerNode,
    transform: &ProjectiveTransform,
    parent_content_style: &ContentStyle,
) -> RasterLayerMapping {
    let transformed_bounds = transform.bounds_for_rect(layer.local_bounds);
    let (scale_x, scale_y) = raster_layer_scale(transformed_bounds, layer.local_bounds);
    let content_style = parent_content_style.under(&layer.graphics_layer);
    let layer_bounds =
        RasterLayerBounds::from_transformed_bounds(transformed_bounds, layer.local_bounds);
    let node_rect = layer.node_rect();
    let content_bounds =
        RasterLayerBounds::from_transformed_bounds(transform.bounds_for_rect(node_rect), node_rect);

    RasterLayerMapping {
        layer_bounds,
        content_bounds,
        transformed_bounds,
        content_style,
        scale_x,
        scale_y,
    }
}

/// Queues `layer`'s elevation shadow, when it casts one, cut to its shadow
/// clip within `parent_visual_clip`.
fn push_layer_shadow_of(
    scene: &mut RasterScene,
    layer: &LayerNode,
    mapping: &RasterLayerMapping,
    transform: &ProjectiveTransform,
    parent_visual_clip: Option<Rect>,
    light: ShadowLight,
) {
    if layer.graphics_layer.shadow_elevation <= 0.0 {
        return;
    }
    let shadow_clip = resolve_clip(
        parent_visual_clip,
        layer
            .shadow_clip()
            .map(|clip| transform.bounds_for_rect(clip)),
    );
    let shadow_layer = GraphicsLayer {
        alpha: layer.graphics_layer.alpha,
        scale_x: mapping.scale_x,
        scale_y: mapping.scale_y,
        transform_origin: TransformOrigin::new(0.0, 0.0),
        shadow_elevation: layer.graphics_layer.shadow_elevation,
        ambient_shadow_color: layer.graphics_layer.ambient_shadow_color,
        spot_shadow_color: layer.graphics_layer.spot_shadow_color,
        shape: layer.graphics_layer.shape,
        ..GraphicsLayer::default()
    };
    push_layer_shadow(
        scene,
        &shadow_layer,
        mapping.layer_bounds,
        mapping.transformed_bounds,
        shadow_clip,
        light,
    );
}

/// Pushes the items of `layer` and its subtree, copied from the frame
/// before's scene when they did not change since, and records them for the
/// next frame.
fn populate_draws_from_graph(
    layer: &LayerNode,
    scene: &mut RasterScene,
    context: &RasterTraversalContext<'_>,
    reuse: &mut Option<Reuse<'_>>,
) {
    // The end of the layer's old record and where the old scene holds what
    // the layer passed down then.
    let mut before = None;
    if let Some(reuse) = reuse.as_mut()
        && let Some(index) = reuse.find(layer)
        && let Some(record) = reuse.old.subtrees.get(index)
    {
        // The layer's number covers its subtree, save its placement.
        if context.same_as_before
            && record.change == layer.change
            && record.transform == layer.transform_to_parent
        {
            let (end, stop) = (record.end, record.stop);
            reuse.cursor = end;
            reuse.copy_later(scene, index, end, stop);
            return;
        }
        reuse.cursor = index + 1;
        before = Some((record.end, record.passed_down));
    }
    flush_copies(reuse, scene);
    let record = scene.open_subtree(layer);
    push_layer_items(
        layer,
        scene,
        context,
        record,
        before.and_then(|(_, passed_down)| passed_down),
        reuse,
    );
    flush_copies(reuse, scene);
    scene.close_subtree(record);
    if let (Some(reuse), Some((end, _))) = (reuse.as_mut(), before) {
        reuse.cursor = end;
    }
}

/// Pushes the items of `layer` and its subtree, whose record is `record`.
/// `passed_down_before` is where the old scene holds what the layer passed
/// to its child layers in the frame before.
fn push_layer_items(
    layer: &LayerNode,
    scene: &mut RasterScene,
    context: &RasterTraversalContext<'_>,
    record: usize,
    passed_down_before: Option<usize>,
    reuse: &mut Option<Reuse<'_>>,
) {
    let diagnostics = context.diagnostics;
    let transform = layer.transform_to_parent.then(*context.parent_transform);
    let mapping = raster_layer_mapping(layer, &transform, context.parent_content_style);
    let raster_content_layer = mapping.content_layer();
    report_unsupported_effects(&layer.graphics_layer, diagnostics);

    if mapping.transformed_bounds.width <= 0.0 || mapping.transformed_bounds.height <= 0.0 {
        return;
    }

    let visual_clip = resolve_clip(
        context.parent_visual_clip,
        layer
            .visual_clip_rect()
            .map(|clip| transform.bounds_for_rect(clip)),
    );
    let effective_translated_content_context =
        context.inherited_translated_content_context || layer.translated_content_context;
    let (translated_snap_anchor, layer_snap_anchor) =
        layer_snap_anchors(layer, context, &transform, &mapping, &raster_content_layer);

    if visual_clip.is_some_and(|clip| clip.is_empty()) {
        return;
    }

    push_layer_shadow_of(
        scene,
        layer,
        &mapping,
        &transform,
        context.parent_visual_clip,
        context.light,
    );

    let primitive_context = PrimitiveRenderContext {
        layer_bounds: mapping.content_bounds,
        node_layer: &raster_content_layer,
        visual_clip,
        motion_context_animated: layer.motion_context_animated,
        content_offset_translation: effective_translated_content_context,
        layer_snap_anchor,
    };
    // Worked out at the first child layer: most layers have none.
    let mut children_same_as_before = None;
    let mut deferred_draws: Vec<&RenderNode> = Vec::new();
    for child in &layer.children {
        match child {
            RenderNode::Layer(child_layer) => {
                let same_as_before = *children_same_as_before.get_or_insert_with(|| {
                    let passed_down = PassedDown {
                        transform,
                        alpha: mapping.content_style.alpha,
                        color_filter: mapping.content_style.color_filter.clone(),
                        clip: visual_clip,
                        snap_anchor: translated_snap_anchor,
                        translated: effective_translated_content_context,
                    };
                    note_passed_down(
                        scene,
                        record,
                        passed_down,
                        context,
                        passed_down_before,
                        reuse,
                    )
                });
                populate_draws_from_graph(
                    child_layer,
                    scene,
                    &RasterTraversalContext {
                        parent_transform: &transform,
                        parent_content_style: &mapping.content_style,
                        parent_visual_clip: visual_clip,
                        inherited_translated_snap_anchor: translated_snap_anchor,
                        inherited_translated_content_context: effective_translated_content_context,
                        diagnostics,
                        light: context.light,
                        same_as_before,
                    },
                    reuse,
                );
            }
            _ if draws_after_children(child) => deferred_draws.push(child),
            _ => {
                flush_copies(reuse, scene);
                render_draw_child(scene, child, primitive_context);
            }
        }
    }

    flush_copies(reuse, scene);
    for child in deferred_draws {
        render_draw_child(scene, child, primitive_context);
    }
}

/// The snap anchor `layer`'s child layers inherit and the one its own draws
/// take.
fn layer_snap_anchors(
    layer: &LayerNode,
    context: &RasterTraversalContext<'_>,
    transform: &ProjectiveTransform,
    mapping: &RasterLayerMapping,
    content_layer: &GraphicsLayer,
) -> (Option<Point>, Option<Point>) {
    let effective_translated_content_context =
        context.inherited_translated_content_context || layer.translated_content_context;
    let allow_rigid_snap = effective_translated_content_context || !layer.motion_context_animated;
    let boundary_snap_anchor = if !context.inherited_translated_content_context
        && layer.translated_content_context
        && allow_rigid_snap
    {
        rigid_snap_anchor(
            transform.bounds_for_rect(layer.local_bounds.translate(
                layer.translated_content_offset.x,
                layer.translated_content_offset.y,
            )),
            content_layer,
        )
    } else {
        None
    };
    let translated_snap_anchor = context
        .inherited_translated_snap_anchor
        .or(boundary_snap_anchor);
    let layer_snap_anchor = translated_snap_anchor.or_else(|| {
        if allow_rigid_snap && layer_needs_rigid_snap(layer, effective_translated_content_context) {
            rigid_snap_anchor(mapping.layer_bounds.raster_rect(), content_layer)
        } else {
            None
        }
    });
    (translated_snap_anchor, layer_snap_anchor)
}

/// Notes in `record` what its layer passes down to its child layers, and
/// returns whether that is what it passed in the frame before, which the old
/// scene holds at `before`, under an unchanged walk above.
fn note_passed_down(
    scene: &mut RasterScene,
    record: usize,
    passed_down: PassedDown,
    context: &RasterTraversalContext<'_>,
    before: Option<usize>,
    reuse: &Option<Reuse<'_>>,
) -> bool {
    let same = context.same_as_before
        && before.and_then(|at| reuse.as_ref()?.old.passed_down.get(at)) == Some(&passed_down);
    scene.note_passed_down(record, passed_down);
    same
}

/// Whether `child`, a primitive or draw run, draws after the layer's child
/// layers.
fn draws_after_children(child: &RenderNode) -> bool {
    match child {
        RenderNode::Primitive(primitive) => primitive.phase == PrimitivePhase::AfterChildren,
        RenderNode::DrawRun(run) => run.phase == PrimitivePhase::AfterChildren,
        RenderNode::Layer(_) => false,
    }
}

/// Pushes the items of `child`, a primitive or draw run of a layer.
fn render_draw_child(
    scene: &mut RasterScene,
    child: &RenderNode,
    context: PrimitiveRenderContext<'_>,
) {
    match child {
        RenderNode::Primitive(primitive) => render_graph_primitive(scene, primitive, context),
        RenderNode::DrawRun(run) => render_graph_draw_run(scene, run, context),
        RenderNode::Layer(_) => {}
    }
}

fn render_graph_draw_run(
    scene: &mut RasterScene,
    run: &cranpose_render_common::graph::DrawRunNode,
    context: PrimitiveRenderContext<'_>,
) {
    let rect = context.layer_bounds.raster_rect();
    let counts_before = scene.counts();
    for primitive in run.primitives() {
        push_draw_primitive(
            &primitive,
            rect,
            context.node_layer,
            context.visual_clip,
            scene,
            None,
            context.motion_context_animated || context.content_offset_translation,
        );
    }
    assign_snap_anchor_since(scene, counts_before, context.layer_snap_anchor);
}

fn render_graph_primitive(
    scene: &mut RasterScene,
    primitive: &PrimitiveEntry,
    context: PrimitiveRenderContext<'_>,
) {
    let rect = context.layer_bounds.raster_rect();
    let counts_before = scene.counts();
    match &primitive.node {
        PrimitiveNode::Draw(draw) => {
            let effective_clip = resolve_primitive_clip(
                draw.clip,
                rect,
                context.node_layer,
                context.visual_clip,
                PrimitiveClipSpace::LayerTransformed,
            );
            if effective_clip.is_some_and(|clip| clip.is_empty()) {
                return;
            }
            push_draw_primitive(
                &draw.primitive,
                rect,
                context.node_layer,
                effective_clip,
                scene,
                None,
                context.motion_context_animated || context.content_offset_translation,
            );
        }
        PrimitiveNode::Text(text) => {
            render_graph_text(
                scene,
                text,
                context.layer_bounds,
                context.node_layer,
                context.visual_clip,
            );
        }
    }
    assign_snap_anchor_since(scene, counts_before, context.layer_snap_anchor);
}

fn render_graph_text(
    scene: &mut RasterScene,
    text: &TextPrimitiveNode,
    layer_bounds: RasterLayerBounds,
    node_layer: &GraphicsLayer,
    visual_clip: Option<Rect>,
) {
    let rect = layer_bounds.raster_rect();
    let text_rect = Rect {
        x: rect.x + text.rect.x,
        y: rect.y + text.rect.y,
        width: text.rect.width,
        height: text.rect.height,
    };
    let text_clip = resolve_primitive_clip(
        text.clip,
        rect,
        node_layer,
        visual_clip,
        PrimitiveClipSpace::LayerTransformed,
    );
    if text_clip.is_some_and(|clip| clip.is_empty()) {
        return;
    }

    push_text_style_draws(
        scene,
        rect,
        text_rect,
        node_layer,
        &text.text,
        &text.text_style,
        text.font_size,
        text_clip,
    );
}

pub(crate) fn push_draw_primitive(
    primitive: &DrawPrimitive,
    layer_bounds: Rect,
    layer: &GraphicsLayer,
    clip: Option<Rect>,
    scene: &mut RasterScene,
    blend_mode: Option<BlendMode>,
    motion_context_animated: bool,
) {
    struct SceneEmitter<'a> {
        scene: &'a mut RasterScene,
    }

    impl DrawPrimitiveSink for SceneEmitter<'_> {
        fn push_shape(&mut self, params: ShapeDrawParams) {
            self.scene.push_shape_params(params);
        }

        fn push_image(&mut self, params: ImageDrawParams) {
            self.scene.push_image_with_geometry(
                params.rect,
                params.local_rect,
                params.quad,
                params.image,
                params.alpha,
                params.color_filter,
                params.sampling,
                params.clip,
                params.src_rect,
                params.blend_mode,
            );
        }

        fn push_shadow(
            &mut self,
            shadow_primitive: &cranpose_ui_graphics::ShadowPrimitive,
            layer_bounds: Rect,
            layer: &GraphicsLayer,
            clip: Option<Rect>,
        ) {
            push_shadow_primitive(shadow_primitive, layer_bounds, layer, clip, self.scene);
        }

        fn push_text(&mut self, params: TextDrawParams) {
            self.scene.push_text(
                params.rect,
                params.text,
                params.color,
                Arc::new(params.text_style),
                params.font_size,
                params.scale,
                params.clip,
            );
        }
    }

    let mut emitter = SceneEmitter { scene };
    emit_draw_primitive(
        primitive,
        layer_bounds,
        layer,
        clip,
        &mut emitter,
        blend_mode,
        motion_context_animated,
    );
}

fn push_shadow_primitive(
    shadow_prim: &cranpose_ui_graphics::ShadowPrimitive,
    layer_bounds: Rect,
    layer: &GraphicsLayer,
    clip: Option<Rect>,
    scene: &mut RasterScene,
) {
    fn shape_pair_for_primitive(
        prim: &DrawPrimitive,
        layer_bounds: Rect,
        layer: &GraphicsLayer,
        blend_mode: BlendMode,
    ) -> Option<(crate::scene::DrawShape, BlendMode)> {
        let params = draw_shape_params_for_primitive(prim, layer_bounds, layer, None, blend_mode)?;
        let blend_mode = params.blend_mode;
        Some((crate::scene::DrawShape::of_params(params), blend_mode))
    }

    match shadow_prim {
        cranpose_ui_graphics::ShadowPrimitive::Drop {
            shape,
            cutout,
            blur_radius,
            blend_mode,
        } => {
            let Some(shape_pair) =
                shape_pair_for_primitive(shape, layer_bounds, layer, *blend_mode)
            else {
                return;
            };
            let cutout_pair = match cutout {
                Some(cutout) => {
                    let Some(pair) =
                        shape_pair_for_primitive(cutout, layer_bounds, layer, BlendMode::DstOut)
                    else {
                        return;
                    };
                    Some(pair)
                }
                None => None,
            };
            let Some(cutout_pair) = cutout_pair else {
                push_blurred_shape_samples(scene, &shape_pair.0, shape_pair.1, clip, *blur_radius);
                return;
            };
            let samples = blur_samples(blur_radius.max(1.0));
            if samples.is_empty() {
                scene.push_shape(
                    shape_pair.0.rect,
                    shape_pair.0.brush,
                    shape_pair.0.shape,
                    clip,
                    shape_pair.1,
                );
                scene.push_shape(
                    cutout_pair.0.rect,
                    cutout_pair.0.brush,
                    cutout_pair.0.shape,
                    clip,
                    cutout_pair.1,
                );
                return;
            }
            for sample in samples.iter().rev() {
                scene.push_shape(
                    expanded_shape_rect(&shape_pair.0, sample.expansion),
                    scale_brush_alpha(shape_pair.0.brush.clone(), sample.weight),
                    shape_pair.0.shape,
                    clip,
                    shape_pair.1,
                );
                scene.push_shape(
                    expanded_shape_rect(&cutout_pair.0, sample.expansion),
                    scale_brush_alpha(cutout_pair.0.brush.clone(), sample.weight),
                    cutout_pair.0.shape,
                    clip,
                    cutout_pair.1,
                );
            }
        }
        cranpose_ui_graphics::ShadowPrimitive::Inner {
            fill,
            cutout,
            blur_radius,
            blend_mode,
            clip_rect,
        } => {
            let Some(fill_pair) = shape_pair_for_primitive(fill, layer_bounds, layer, *blend_mode)
            else {
                return;
            };
            let Some(cutout_pair) =
                shape_pair_for_primitive(cutout, layer_bounds, layer, BlendMode::DstOut)
            else {
                return;
            };
            let abs_clip = Rect {
                x: clip_rect.x + layer_bounds.x,
                y: clip_rect.y + layer_bounds.y,
                width: clip_rect.width,
                height: clip_rect.height,
            };
            let transformed_clip = apply_layer_to_rect(abs_clip, layer_bounds, layer);
            let effective_clip = clip.map_or(Some(transformed_clip), |parent_clip| {
                parent_clip.intersect(transformed_clip)
            });
            let samples = blur_samples(blur_radius.max(1.0));
            if samples.is_empty() {
                scene.push_shape(
                    fill_pair.0.rect,
                    fill_pair.0.brush,
                    fill_pair.0.shape,
                    effective_clip,
                    fill_pair.1,
                );
                scene.push_shape(
                    cutout_pair.0.rect,
                    cutout_pair.0.brush,
                    cutout_pair.0.shape,
                    effective_clip,
                    cutout_pair.1,
                );
                return;
            }

            for sample in samples.iter().rev() {
                scene.push_shape(
                    expanded_shape_rect(&fill_pair.0, sample.expansion),
                    scale_brush_alpha(fill_pair.0.brush.clone(), sample.weight),
                    fill_pair.0.shape,
                    effective_clip,
                    fill_pair.1,
                );
                scene.push_shape(
                    expanded_shape_rect(&cutout_pair.0, sample.expansion),
                    scale_brush_alpha(cutout_pair.0.brush.clone(), sample.weight),
                    cutout_pair.0.shape,
                    effective_clip,
                    cutout_pair.1,
                );
            }
        }
    }
}

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