Skip to main content

waft_embedder/scene/
placement.rs

1//! Where a frame puts one composition layer, with everything the containers above it do to it:
2//! Flutter's `EmbeddedViewParams` and its `MutatorsStack`. A scene's slices hand a host one for
3//! each layer the scene places, and a layer places its sublayers by them too, in its buffer's
4//! pixels.
5//!
6//! A host applies what its compositor can and reads the rest through the summaries here: a
7//! compositor that only moves and clips rectangles reads [`Placement::bounds`],
8//! [`Placement::scale`] and [`Placement::visible_bounds`]. The invariant a later editor must
9//! keep: the mutators are what the containers above the layer do, outermost first, and nothing a
10//! host can work out from them is stored beside them.
11
12use crate::geometry::{Matrix4, RRect, Rect};
13use crate::painting::Path;
14
15/// Where one frame puts one composition layer: what a host compares to tell a frame worth
16/// presenting from one it already shows.
17#[derive(Clone, Debug, PartialEq)]
18pub struct Placement {
19    /// The layer's rectangle, in the coordinates the transforms among `mutators` lead to.
20    pub rect: Rect,
21    /// What the containers above the layer do to it, the outermost first: Flutter's
22    /// `MutatorsStack`. A view's scene begins with its root transform, which takes the
23    /// framework's logical pixels to the view's physical ones.
24    pub mutators: Vec<Mutator>,
25}
26
27/// One thing a container above a composition layer does to it: Flutter's `Mutator`. Each is in the
28/// coordinates the transforms before it lead to.
29#[derive(Clone, Debug, PartialEq)]
30pub enum Mutator {
31    Transform(Matrix4),
32    /// Nothing of the layer shows outside the rectangle.
33    ClipRect(Rect),
34    /// Nothing of the layer shows outside the rounded rectangle.
35    ClipRRect(RRect),
36    /// Nothing of the layer shows outside the path, filled by its fill type.
37    ClipPath(Path),
38    /// The layer shows at this alpha, out of 255.
39    Opacity(u8),
40}
41
42impl Placement {
43    /// Every transform above the layer in one: Flutter's `transformMatrix`, which takes `rect`'s
44    /// coordinates to the view's pixels.
45    pub fn transform(&self) -> Matrix4 {
46        self.mutators
47            .iter()
48            .fold(Matrix4::IDENTITY, |transform, mutator| match mutator {
49                Mutator::Transform(matrix) => transform.then(matrix),
50                _ => transform,
51            })
52    }
53
54    /// Every opacity above the layer multiplied, from 0 to 1.
55    pub fn opacity(&self) -> f64 {
56        self.mutators
57            .iter()
58            .fold(1.0, |opacity, mutator| match mutator {
59                Mutator::Opacity(alpha) => opacity * f64::from(*alpha) / 255.0,
60                _ => opacity,
61            })
62    }
63
64    /// How many of the view's pixels one unit of the layer's own coordinates spans along its
65    /// own horizontal: the scale of every transform above it, the root's device pixel ratio
66    /// among them. A producer draws its buffers at the device pixel ratio, so a host shows a
67    /// buffer at `scale / device_pixel_ratio` of its size.
68    pub fn scale(&self) -> f64 {
69        let m = self.transform().to_flutter_array();
70        f64::from(m[0]).hypot(f64::from(m[1]))
71    }
72
73    /// The box around the layer under every transform above it, in the view's pixels.
74    pub fn bounds(&self) -> Rect {
75        bounds_under(&self.transform(), self.rect)
76    }
77
78    /// [`bounds`](Self::bounds) cut down to the bounds of every clip above the layer: what a
79    /// compositor that clips by rectangles alone shows of it. An empty rectangle on the clip's
80    /// nearest edge when nothing shows.
81    pub fn visible_bounds(&self) -> Rect {
82        let mut transform = Matrix4::IDENTITY;
83        let mut visible = self.bounds();
84        for mutator in &self.mutators {
85            let clip_bounds = match mutator {
86                Mutator::Transform(matrix) => {
87                    transform = transform.then(matrix);
88                    continue;
89                }
90                Mutator::ClipRect(rect) => *rect,
91                Mutator::ClipRRect(rrect) => rrect.outer_rect(),
92                Mutator::ClipPath(path) => path.get_bounds(),
93                Mutator::Opacity(_) => continue,
94            };
95            visible = visible_part_of(visible, bounds_under(&transform, clip_bounds));
96        }
97        visible
98    }
99}
100
101/// The box around `rect` under `transform`.
102fn bounds_under(transform: &Matrix4, rect: Rect) -> Rect {
103    rect_of(transform.map_rect(&rect.into()))
104}
105
106fn rect_of(rect: crate::valo::Rect) -> Rect {
107    Rect::from_ltwh(
108        f64::from(rect.x),
109        f64::from(rect.y),
110        f64::from(rect.width),
111        f64::from(rect.height),
112    )
113}
114
115/// What of `rect` lies inside `clip`; an empty rectangle on `clip`'s nearest edge when nothing
116/// does.
117fn visible_part_of(rect: Rect, clip: Rect) -> Rect {
118    let overlap = rect.intersect(clip);
119    Rect::from_ltrb(
120        overlap.left,
121        overlap.top,
122        overlap.right.max(overlap.left),
123        overlap.bottom.max(overlap.top),
124    )
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use crate::painting::{Path, PathBuilder};
131
132    fn placement(rect: Rect, mutators: Vec<Mutator>) -> Placement {
133        Placement { rect, mutators }
134    }
135
136    /// A page at half its size on a display of two pixels a point: each unit of the page's own
137    /// spans one of the view's pixels, so a buffer drawn at two pixels a point shows at half its
138    /// size.
139    #[test]
140    fn a_placement_carries_the_scale_and_the_bounds_of_every_transform_above_it() {
141        let page = placement(
142            Rect::from_ltwh(0.0, 0.0, 390.0, 844.0),
143            vec![
144                Mutator::Transform(Matrix4::scale(2.0, 2.0)),
145                Mutator::Transform(Matrix4::translation(10.0, 20.0)),
146                Mutator::Transform(Matrix4::scale(0.5, 0.5)),
147            ],
148        );
149        assert_eq!(page.scale(), 1.0);
150        assert_eq!(page.bounds(), Rect::from_ltwh(20.0, 40.0, 390.0, 844.0));
151        assert_eq!(page.visible_bounds(), page.bounds(), "nothing clips it");
152    }
153
154    #[test]
155    fn a_turned_layer_is_bounded_by_the_box_around_it() {
156        let turned = placement(
157            Rect::from_ltwh(0.0, 0.0, 10.0, 10.0),
158            vec![Mutator::Transform(Matrix4::rotation(
159                std::f32::consts::FRAC_PI_4,
160            ))],
161        );
162        let bounds = turned.bounds();
163        let half_diagonal = 50f64.sqrt();
164        assert!((bounds.left + half_diagonal).abs() < 1e-4, "{bounds:?}");
165        assert!((bounds.right - half_diagonal).abs() < 1e-4, "{bounds:?}");
166        assert!((turned.scale() - 1.0).abs() < 1e-6);
167    }
168
169    #[test]
170    fn what_shows_is_cut_by_the_bounds_of_every_clip_under_its_own_transform() {
171        let path = {
172            let mut path = PathBuilder::new();
173            path.rrect(Rect::from_ltwh(0.0, 0.0, 200.0, 20.0).into(), 4.0);
174            Path::new(path.build())
175        };
176        let clipped = placement(
177            Rect::from_ltwh(-5.0, -5.0, 300.0, 300.0),
178            vec![
179                Mutator::Transform(Matrix4::scale(2.0, 2.0)),
180                Mutator::ClipRect(Rect::from_ltwh(0.0, 0.0, 100.0, 50.0)),
181                Mutator::Transform(Matrix4::translation(10.0, 10.0)),
182                Mutator::ClipPath(path),
183            ],
184        );
185        assert_eq!(clipped.bounds(), Rect::from_ltwh(10.0, 10.0, 600.0, 600.0));
186        // The path's bounds, (10, 10) to (210, 30), cut by the rectangle's, (0, 0) to (100, 50),
187        // at two pixels to a unit.
188        assert_eq!(
189            clipped.visible_bounds(),
190            Rect::from_ltrb(20.0, 20.0, 200.0, 60.0)
191        );
192    }
193
194    #[test]
195    fn a_layer_outside_its_clip_shows_nothing() {
196        let outside = placement(
197            Rect::from_ltwh(200.0, 0.0, 50.0, 50.0),
198            vec![Mutator::ClipRect(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0))],
199        );
200        assert!(outside.visible_bounds().is_empty());
201    }
202
203    #[test]
204    fn opacities_multiply() {
205        let faded = placement(
206            Rect::from_ltwh(0.0, 0.0, 1.0, 1.0),
207            vec![
208                Mutator::Opacity(51),
209                Mutator::Opacity(255),
210                Mutator::Opacity(51),
211            ],
212        );
213        assert!((faded.opacity() - 0.04).abs() < 1e-9, "{}", faded.opacity());
214        assert_eq!(placement(Rect::ZERO, Vec::new()).opacity(), 1.0);
215    }
216}