cranpose-render-pixels 0.22.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
use std::{ops::Range, rc::Rc, sync::Arc};

use cranpose_core::NodeId;
use cranpose_render_common::{
    Brush,
    graph::{
        InlineNode, LayerNode, PrimitiveEntry, PrimitiveNode, ProjectiveTransform, RenderGraph,
        RenderNode, TextPrimitiveNode, for_each_in_draw_order,
    },
    graph_scene::RenderDiagnostics,
    hit_graph::collect_hits_from_graph,
    layer_composition::folded_layer_alpha,
    layer_shadow::ShadowLight,
    layer_transform::{apply_layer_affine_to_rect, apply_layer_to_rect, layer_uniform_scale},
    primitive_emit::resolve_clip,
    text_decoration::{visit_text_backgrounds, visit_text_lines},
    text_raster::GlyphInk,
};
use cranpose_ui::{LayoutBox, text::TextStyle};
use cranpose_ui_graphics::{
    BlendMode, Color, ColorFilter, GraphicsLayer, Point, Rect, RenderEffect, TransformOrigin,
};

use crate::{
    draw::TextRaster,
    scene::{ItemCounts, PassedDown, RasterScene, Scene, Subtree, TextDraw},
    style::{apply_layer_to_brush, apply_layer_to_color, compose_color_filters},
    surface::{SurfacePlacement, rasterize_surface, scales_and_moves},
};

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))
}

#[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 fonts and glyphs a surface's text is drawn with.
    text: &'a TextRaster,
    /// Whether the layer is the one whose surface the walk draws: it draws
    /// its items straight into the surface, and its parent drew its shadow.
    surface_root: bool,
    /// Whether the walk lies in a scene's space, whose scene draws the
    /// mesh surfaces and 3D transforms there, as its eye sees them.
    in_space: 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 the old record of the node with `identity`, at the
    /// cursor or one subtree on, after a sibling before it went away.
    fn find(&self, identity: (Option<NodeId>, Option<NodeId>)) -> Option<usize> {
        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 contains_text_primitives(nodes: &[RenderNode]) -> bool {
    nodes.iter().any(|child| {
        matches!(
            child,
            RenderNode::Primitive(PrimitiveEntry {
                node: PrimitiveNode::Text(_),
                ..
            })
        )
    })
}

fn contains_draw_primitives(nodes: &[RenderNode]) -> bool {
    nodes.iter().any(|child| {
        matches!(
            child,
            RenderNode::Primitive(PrimitiveEntry {
                node: PrimitiveNode::Draw(_),
                ..
            })
        )
    })
}

fn content_needs_rigid_snap(nodes: &[RenderNode], translated_content_context: bool) -> bool {
    (translated_content_context
        && (contains_draw_primitives(nodes) || contains_text_primitives(nodes)))
        || (contains_text_primitives(nodes) && contains_draw_primitives(nodes))
}

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.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 or non-SrcOver layer blend modes; falling back to base layer rendering"
        );
    }
}

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
}

// Where a text node draws: the bounds and transform of its layer, its box
// before the transform and its clip.
#[derive(Clone, Copy)]
struct TextPlacement<'a> {
    bounds: Rect,
    text_rect: Rect,
    layer: &'a GraphicsLayer,
    clip: Option<Rect>,
}

fn push_text_style_draws(
    scene: &mut RasterScene,
    node: &TextPrimitiveNode,
    placement: TextPlacement<'_>,
) {
    let (rect, node_layer, text_clip) = (placement.bounds, placement.layer, placement.clip);
    let (text, text_style, layout) = (&node.text, &node.text_style, &node.layout);
    let text_rect = placement.text_rect;
    let transformed_text_rect = apply_layer_to_rect(text_rect, rect, node_layer);
    // A line or a box of the text, in layout pixels, where the node draws it.
    let placed = |part: Rect| {
        apply_layer_to_rect(part.translate(text_rect.x, text_rect.y), rect, node_layer)
    };

    visit_text_backgrounds(layout, text.as_ref().into(), text_style, |part, brush| {
        scene.push_shape(
            placed(part),
            apply_layer_to_brush(brush.clone(), node_layer),
            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)
        };

    if let Some(shadow) = text_style.span_style.shadow {
        let shadow_rect = text_rect.translate(shadow.offset.x, shadow.offset.y);
        let mut shadow_text_style = TextStyle::clone(&transformed_text_style);
        shadow_text_style.span_style.shadow = Some(cranpose_ui::text::Shadow {
            color: apply_layer_to_color(shadow.color, node_layer),
            offset: Point::new(0.0, 0.0),
            blur_radius: shadow.blur_radius,
        });
        scene.push_text(TextDraw {
            rect: apply_layer_to_rect(shadow_rect, rect, node_layer),
            snap_anchor: None,
            text: Rc::clone(text),
            layout: layout.clone(),
            color: Color::TRANSPARENT,
            text_style: Arc::new(shadow_text_style),
            font_size: node.font_size,
            scale: layer_uniform_scale(node_layer),
            ink: GlyphInk::Hidden,
            clip: text_clip,
        });
    }

    scene.push_text(TextDraw {
        rect: transformed_text_rect,
        snap_anchor: None,
        text: Rc::clone(text),
        layout: layout.clone(),
        color: transformed_text_color,
        text_style: transformed_text_style,
        font_size: node.font_size,
        scale: layer_uniform_scale(node_layer),
        ink: GlyphInk::Painted,
        clip: text_clip,
    });

    visit_text_lines(
        layout,
        text.as_ref().into(),
        text_style,
        text_color,
        |part, brush| {
            scene.push_pixel_snapped_shape(
                placed(part),
                apply_layer_to_brush(brush.clone(), node_layer),
                None,
                text_clip,
                BlendMode::SrcOver,
            );
        },
    );
}

pub(crate) fn build_raster_scene(
    graph: &RenderGraph,
    diagnostics: &RenderDiagnostics,
    scale: f32,
    text: &TextRaster,
) -> RasterScene {
    let mut scene = RasterScene::new();
    fill_raster_scene(&mut scene, graph, diagnostics, scale, None, text);
    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.
mod draw_child;
mod in_place;
mod layer_shadow;
mod space;

#[cfg(test)]
pub(crate) use draw_child::push_draw_primitive;
use draw_child::render_draw_child;
pub(crate) use in_place::{InPlaceUpdate, UpdatedReach};
use layer_shadow::push_layer_shadow;
use space::{push_seen_surfaces, seen_surfaces};

/// The shadow light of a scene `graph` gives at `scale`.
fn scene_light(graph: &RenderGraph, scale: f32) -> ShadowLight {
    ShadowLight::for_window(
        graph.root.local_bounds.width * scale,
        graph.root.local_bounds.height * scale,
        scale,
        1.0,
    )
}

pub(crate) fn fill_raster_scene(
    scene: &mut RasterScene,
    graph: &RenderGraph,
    diagnostics: &RenderDiagnostics,
    scale: f32,
    previous: Option<&RasterScene>,
    text: &TextRaster,
) {
    scene.clear();
    let light = scene_light(graph, scale);
    scene.start = Some((scale, light));
    let mut reuse = previous.map(|old| Reuse {
        old,
        cursor: 0,
        pending: None,
    });
    populate_draws_from_graph(
        Subtree::Layer(&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),
            text,
            surface_root: false,
            in_space: false,
        },
        &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,
}

/// The layer of content drawn at alpha one with no colour filter and at
/// scale one, which most layers' content takes.
const PLAIN_CONTENT_LAYER: GraphicsLayer = GraphicsLayer {
    transform_origin: TransformOrigin::new(0.0, 0.0),
    ..GraphicsLayer::DEFAULT
};

impl RasterLayerMapping {
    /// Whether the node's own draws take [`PLAIN_CONTENT_LAYER`], so need no
    /// [`Self::content_layer`] built.
    fn draws_plain(&self) -> bool {
        self.content_style.alpha == 1.0
            && self.content_style.color_filter.is_none()
            && self.scale_x == 1.0
            && self.scale_y == 1.0
    }

    /// 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 layer_raster_mapping(
    layer: &LayerNode,
    transform: &ProjectiveTransform,
    parent_content_style: &ContentStyle,
) -> RasterLayerMapping {
    // A draw group's layer copies the paint of the node whose draws it
    // holds, which reaches it here already.
    let content_style = if layer.draw_phase.is_some() {
        parent_content_style.clone()
    } else {
        parent_content_style.under(&layer.graphics_layer)
    };
    let bounds = layer.local_bounds;
    // A node's rect that differs from its layer's bounds in some bit maps on
    // its own: a zero of another sign maps to other bits.
    let node_rect = layer.node_rect();
    let same = |a: f32, b: f32| a.to_bits() == b.to_bits();
    let content_bounds = (!(same(node_rect.x, bounds.x)
        && same(node_rect.y, bounds.y)
        && same(node_rect.width, bounds.width)
        && same(node_rect.height, bounds.height)))
    .then(|| {
        RasterLayerBounds::from_transformed_bounds(transform.bounds_for_rect(node_rect), node_rect)
    });
    raster_layer_mapping(bounds, content_bounds, transform, content_style)
}

// `content_bounds` is `None` where the node's draws map as its layer does,
// as an inline node's do.
fn raster_layer_mapping(
    local_bounds: Rect,
    content_bounds: Option<RasterLayerBounds>,
    transform: &ProjectiveTransform,
    content_style: ContentStyle,
) -> RasterLayerMapping {
    let transformed_bounds = transform.bounds_for_rect(local_bounds);
    let (scale_x, scale_y) = raster_layer_scale(transformed_bounds, local_bounds);
    let layer_bounds = RasterLayerBounds::from_transformed_bounds(transformed_bounds, local_bounds);

    RasterLayerMapping {
        layer_bounds,
        content_bounds: content_bounds.unwrap_or(layer_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`.
// Out of line, as are the surface and a text's draw: inlined, their locals
// would take room on the stack at every layer nesting level of the walk,
// which recurses through `push_layer_items`. A child's other draws stay
// inline: out of line, the ESP32-S3 demo waited longer for their code.
#[inline(never)]
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(
    subtree: Subtree<'_>,
    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(subtree.identity())
        && 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 == subtree.change()
            && record.transform == subtree.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(subtree);
    match subtree {
        Subtree::Layer(layer) => push_layer_items(
            layer,
            scene,
            context,
            record,
            before.and_then(|(_, passed_down)| passed_down),
            reuse,
        ),
        Subtree::Inline(inline) => push_inline_items(inline, scene, context),
    }
    flush_copies(reuse, scene);
    scene.close_subtree(record);
    if let (Some(reuse), Some((end, _))) = (reuse.as_mut(), before) {
        reuse.cursor = end;
    }
}

/// Draws `layer` and its subtree into a surface of its own and queues the
/// surface's pixels, placed by `transform`, the layer's map to device
/// pixels.
#[inline(never)]
fn push_layer_surface(
    layer: &LayerNode,
    scene: &mut RasterScene,
    context: &RasterTraversalContext<'_>,
    transform: &ProjectiveTransform,
) {
    let Some(placement) = SurfacePlacement::of(layer.local_bounds, transform) else {
        return;
    };
    // The walk below places the layer by its own transform first.
    let Some(parent_transform) = layer
        .transform_to_parent
        .inverse()
        .map(|inverse| inverse.then(placement.to_surface))
    else {
        return;
    };
    // The surface takes the alpha as it lands, so its items overlap as
    // they would in the layer's own buffer and a mask keeps its alpha.
    let content_style = ContentStyle {
        alpha: 1.0,
        color_filter: context.parent_content_style.color_filter.clone(),
    };
    let mut items = RasterScene::new();
    let record = items.open_subtree(Subtree::Layer(layer));
    push_layer_items(
        layer,
        &mut items,
        &RasterTraversalContext {
            parent_transform: &parent_transform,
            parent_content_style: &content_style,
            parent_visual_clip: Some(Rect {
                x: 0.0,
                y: 0.0,
                width: placement.width as f32,
                height: placement.height as f32,
            }),
            inherited_translated_snap_anchor: None,
            inherited_translated_content_context: false,
            diagnostics: context.diagnostics,
            light: context.light,
            same_as_before: false,
            text: context.text,
            surface_root: true,
            in_space: context.in_space,
        },
        record,
        None,
        &mut None,
    );
    items.close_subtree(record);
    if let Some(image) = rasterize_surface(
        &items,
        placement.width,
        placement.height,
        context.diagnostics,
        context.text,
    ) {
        scene.push_surface_image(
            image,
            placement.rect,
            placement.to_device,
            context.parent_visual_clip,
            context.parent_content_style.alpha,
        );
    }
}

/// 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 = layer_raster_mapping(layer, &transform, context.parent_content_style);
    let styled_content_layer;
    let raster_content_layer = if mapping.draws_plain() {
        &PLAIN_CONTENT_LAYER
    } else {
        styled_content_layer = mapping.content_layer();
        &styled_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;
    }

    // A surface's layer casts its shadow where its parent draws the surface.
    if !context.surface_root {
        push_layer_shadow_of(
            scene,
            layer,
            &mapping,
            &transform,
            context.parent_visual_clip,
            context.light,
        );
        if layer.isolation.explicit_offscreen || !scales_and_moves(&transform) {
            push_layer_surface(layer, scene, context, &transform);
            return;
        }
    }

    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,
    };
    // A scene draws the surfaces its eye sees in its own space where its
    // first child in 3D comes, far ones first: this renderer keeps no depth
    // between them, and draws a scene behind a doorway flat on its surface.
    let (mut seen, in_space) = layer_space(layer, &transform, context.in_space);
    // Worked out at the first child layer: most layers have none.
    let mut children_same_as_before = None;
    let mut push_child =
        |child: &RenderNode, scene: &mut RasterScene, reuse: &mut Option<Reuse<'_>>| {
            let Some(subtree) = Subtree::of_child(child) else {
                flush_copies(reuse, scene);
                return render_draw_child(scene, child, primitive_context);
            };
            if let Subtree::Layer(child_layer) = subtree {
                if let Some(surfaces) = seen.take_if(|_| child_layer.has_space()) {
                    flush_copies(reuse, scene);
                    push_seen_surfaces(
                        surfaces,
                        scene,
                        context,
                        (&mapping.content_style, visual_clip),
                    );
                }
                if drawn_by_its_scene(child_layer, in_space) {
                    return;
                }
            }
            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(
                subtree,
                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,
                    text: context.text,
                    surface_root: false,
                    in_space,
                },
                reuse,
            );
        };
    for_each_in_draw_order(&layer.children, |child| push_child(child, scene, reuse));
}

// Pushes the content of `inline`, a node drawn in its parent's layer,
// placed as the walk of its parent's children, `context`, places a child
// layer that only moves.
fn push_inline_items(
    inline: &InlineNode,
    scene: &mut RasterScene,
    context: &RasterTraversalContext<'_>,
) {
    let transform = inline.transform_to_parent().then(*context.parent_transform);
    let node_rect = inline.node_rect();
    let content_style = context.parent_content_style.under(&GraphicsLayer::DEFAULT);
    let mapping = raster_layer_mapping(node_rect, None, &transform, content_style);
    if mapping.transformed_bounds.width <= 0.0 || mapping.transformed_bounds.height <= 0.0 {
        return;
    }
    let styled_content_layer;
    let raster_content_layer = if mapping.draws_plain() {
        &PLAIN_CONTENT_LAYER
    } else {
        styled_content_layer = mapping.content_layer();
        &styled_content_layer
    };
    let translated = context.inherited_translated_content_context;
    let layer_snap_anchor = context.inherited_translated_snap_anchor.or_else(|| {
        ((translated || !inline.motion_context_animated)
            && content_needs_rigid_snap(&inline.content, translated))
        .then(|| rigid_snap_anchor(mapping.layer_bounds.raster_rect(), raster_content_layer))
        .flatten()
    });
    let primitive_context = PrimitiveRenderContext {
        layer_bounds: mapping.content_bounds,
        node_layer: raster_content_layer,
        visual_clip: context.parent_visual_clip,
        motion_context_animated: inline.motion_context_animated,
        content_offset_translation: translated,
        layer_snap_anchor,
    };
    for_each_in_draw_order(&inline.content, |child| {
        render_draw_child(scene, child, primitive_context);
    });
}

/// The surfaces `layer` draws for the eye of the scene it shows, if it shows
/// one (see [`seen_surfaces`]), and whether its children lie in a scene's
/// space, given whether `layer` does.
fn layer_space<'a>(
    layer: &'a LayerNode,
    transform: &ProjectiveTransform,
    in_space: bool,
) -> (Option<Vec<(&'a LayerNode, ProjectiveTransform)>>, bool) {
    if layer.graphics_layer.space.is_none() {
        return (None, in_space);
    }
    let seen = seen_surfaces(layer, transform);
    let in_space = in_space || seen.is_some();
    (seen, in_space)
}

/// Whether a scene draws `layer` from its eye's view: so it does for a layer
/// in 3D that lies in a scene's space, as `in_space` says, and shows no scene
/// of its own. Such layers draw where the scene's first child in 3D comes.
fn drawn_by_its_scene(layer: &LayerNode, in_space: bool) -> bool {
    in_space
        && layer.graphics_layer.space.is_some()
        && cranpose_render_common::space::scene_of(layer).is_none()
}

/// 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
            && content_needs_rigid_snap(&layer.children, 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
}

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