Skip to main content

waft_painting/
matrix_utils.rs

1//! Flutter counterpart: `painting/matrix_utils.dart`.
2
3use std::any::Any;
4use std::fmt;
5
6use waft_embedder::{Matrix4, Offset, Rect};
7use waft_foundation::{
8    DiagnosticLevel, DiagnosticsJsonMap, DiagnosticsNode, DiagnosticsProperty,
9    DiagnosticsSerializationDelegate, DiagnosticsTreeStyle, IntoPropertyName,
10    TextTreeConfiguration, TextTreeRenderer, debug_format_double,
11};
12
13/// Returns the transform as an [`Offset`] if it is only a 2D translation.
14pub fn get_as_translation(transform: Matrix4) -> Option<Offset> {
15    let m = transform.to_flutter_array();
16    if m[0] == 1.0
17        && m[1] == 0.0
18        && m[2] == 0.0
19        && m[3] == 0.0
20        && m[4] == 0.0
21        && m[5] == 1.0
22        && m[6] == 0.0
23        && m[7] == 0.0
24        && m[8] == 0.0
25        && m[9] == 0.0
26        && m[10] == 1.0
27        && m[11] == 0.0
28        && m[14] == 0.0
29        && m[15] == 1.0
30    {
31        Some(Offset::new(m[12] as f64, m[13] as f64))
32    } else {
33        None
34    }
35}
36
37/// Returns a uniform 2D scale if the matrix is only that scale.
38pub fn get_as_scale(transform: Matrix4) -> Option<f64> {
39    let m = transform.to_flutter_array();
40    if m[0] == m[5]
41        && m[1] == 0.0
42        && m[2] == 0.0
43        && m[3] == 0.0
44        && m[4] == 0.0
45        && m[6] == 0.0
46        && m[7] == 0.0
47        && m[8] == 0.0
48        && m[9] == 0.0
49        && m[10] == 1.0
50        && m[11] == 0.0
51        && m[12] == 0.0
52        && m[13] == 0.0
53        && m[14] == 0.0
54        && m[15] == 1.0
55    {
56        Some(m[0] as f64)
57    } else {
58        None
59    }
60}
61
62/// Flutter `MatrixUtils.transformPoint`.
63pub fn transform_point(transform: &Matrix4, point: Offset) -> Offset {
64    let storage = transform.to_flutter_array();
65    let x = point.dx();
66    let y = point.dy();
67    let rx = storage[0] as f64 * x + storage[4] as f64 * y + storage[12] as f64;
68    let ry = storage[1] as f64 * x + storage[5] as f64 * y + storage[13] as f64;
69    let rw = storage[3] as f64 * x + storage[7] as f64 * y + storage[15] as f64;
70    if rw == 1.0 {
71        Offset::new(rx, ry)
72    } else {
73        Offset::new(rx / rw, ry / rw)
74    }
75}
76
77/// Flutter `MatrixUtils.transformRect`: the bounding box of the four
78/// transformed corners. Flutter's translation/scale/affine fast paths are
79/// skipped; they compute the same numbers.
80pub fn transform_rect(transform: &Matrix4, rect: Rect) -> Rect {
81    let mut left = f64::INFINITY;
82    let mut top = f64::INFINITY;
83    let mut right = f64::NEG_INFINITY;
84    let mut bottom = f64::NEG_INFINITY;
85    for corner in [
86        Offset::new(rect.left, rect.top),
87        Offset::new(rect.right, rect.top),
88        Offset::new(rect.left, rect.bottom),
89        Offset::new(rect.right, rect.bottom),
90    ] {
91        let mapped = transform_point(transform, corner);
92        left = left.min(mapped.dx());
93        top = top.min(mapped.dy());
94        right = right.max(mapped.dx());
95        bottom = bottom.max(mapped.dy());
96    }
97    Rect::from_ltrb(left, top, right, bottom)
98}
99
100/// Flutter `MatrixUtils.inverseTransformRect`.
101pub fn inverse_transform_rect(transform: Matrix4, rect: Rect) -> Rect {
102    if transform == Matrix4::IDENTITY {
103        return rect;
104    }
105    let inverted = transform
106        .invert()
107        .unwrap_or_else(|| Matrix4::from_flutter_array(&[0.0; 16]));
108    transform_rect(&inverted, rect)
109}
110
111/// Flutter `debugDescribeTransform`: the transform's rows, one string each, for
112/// diagnostics such as Flutter's `TransformProperty`.
113///
114/// The matrix is column-major as Dart's `storage` is, so `entry(row, column)`
115/// reads index `column * 4 + row`.
116pub fn debug_describe_transform(transform: Option<Matrix4>) -> Vec<String> {
117    let Some(transform) = transform else {
118        return vec!["null".to_string()];
119    };
120    let storage = transform.to_flutter_array();
121    (0..4)
122        .map(|row| {
123            let entries: Vec<String> = (0..4)
124                .map(|column| debug_format_double(Some(storage[column * 4 + row] as f64)))
125                .collect();
126            format!("[{row}] {}", entries.join(","))
127        })
128        .collect()
129}
130
131/// Returns a matrix that transforms every point to `offset`.
132pub fn force_to_point(offset: Offset) -> Matrix4 {
133    let mut storage = [0.0; 16];
134    // Matrix4 is column-major.
135    // The first two columns (indices 0, 1, 4, 5) are zero, so x and y are ignored.
136    storage[10] = 1.0; // Row 2, Column 2: z' = z
137    storage[12] = offset.dx() as f32; // Row 0, Column 3: x' = offset.dx
138    storage[13] = offset.dy() as f32; // Row 1, Column 3: y' = offset.dy
139    storage[15] = 1.0; // Row 3, Column 3: w' = w
140    Matrix4::from_flutter_array(&storage)
141}
142
143/// Property which handles [`Matrix4`] that represent transforms.
144pub struct TransformProperty {
145    inner: DiagnosticsProperty<String>,
146    matrix: Option<Matrix4>,
147}
148
149impl TransformProperty {
150    /// Create a diagnostics property for [`Matrix4`] objects; `None` is Dart's null.
151    pub fn new(
152        name: impl IntoPropertyName,
153        value: impl Into<Option<Matrix4>>,
154    ) -> TransformProperty {
155        let name = name.into_property_name();
156        let matrix = value.into();
157        TransformProperty {
158            inner: DiagnosticsProperty::<String>::new(
159                name,
160                matrix.map(|matrix| debug_describe_transform(Some(matrix)).join("\n")),
161            ),
162            matrix,
163        }
164    }
165
166    /// Dart `TransformProperty(defaultValue:)`: shown only when the transform differs from it.
167    pub fn default_value(mut self, default_value: Option<Matrix4>) -> Self {
168        self.inner = self.inner.default_value(
169            default_value.map(|matrix| debug_describe_transform(Some(matrix)).join("\n")),
170        );
171        self
172    }
173
174    /// Dart `TransformProperty(level:)`.
175    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
176        self.inner = self.inner.with_level(level);
177        self
178    }
179
180    /// Dart's `TransformProperty.valueToString`.
181    pub fn value_to_string(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
182        if parent_configuration.is_some_and(|config| !config.line_break_properties) {
183            let values: Vec<String> = debug_describe_transform(self.matrix)
184                .into_iter()
185                .map(|row| {
186                    row.split_once(' ')
187                        .expect("a row has an index")
188                        .1
189                        .to_string()
190                })
191                .collect();
192            return format!("[{}]", values.join("; "));
193        }
194        debug_describe_transform(self.matrix).join("\n")
195    }
196}
197
198impl DiagnosticsNode for TransformProperty {
199    /// Dart's `TransformProperty`, which adds nothing to its property's JSON.
200    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
201        self.inner.to_json_map(delegate)
202    }
203
204    fn name(&self) -> Option<&str> {
205        self.inner.name()
206    }
207
208    fn value(&self) -> Option<&dyn Any> {
209        self.matrix.as_ref().map(|matrix| matrix as &dyn Any)
210    }
211
212    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
213        self.value_to_string(parent_configuration)
214    }
215
216    fn show_separator(&self) -> bool {
217        self.inner.show_separator()
218    }
219
220    fn level(&self) -> DiagnosticLevel {
221        self.inner.level()
222    }
223
224    fn show_name(&self) -> bool {
225        self.inner.show_name()
226    }
227
228    fn line_prefix(&self) -> Option<&str> {
229        self.inner.line_prefix()
230    }
231
232    fn style(&self) -> Option<DiagnosticsTreeStyle> {
233        self.inner.style()
234    }
235
236    fn allow_wrap(&self) -> bool {
237        self.inner.allow_wrap()
238    }
239
240    fn allow_name_wrap(&self) -> bool {
241        self.inner.allow_name_wrap()
242    }
243
244    fn to_string_deep_with(
245        &self,
246        prefix_line_one: &str,
247        prefix_other_lines: Option<&str>,
248        parent_configuration: Option<&TextTreeConfiguration>,
249        min_level: DiagnosticLevel,
250        wrap_width: usize,
251    ) -> String {
252        TextTreeRenderer::new()
253            .min_level(min_level)
254            .wrap_width(wrap_width)
255            .render_with(
256                self,
257                prefix_line_one,
258                prefix_other_lines,
259                parent_configuration,
260            )
261    }
262}
263
264impl fmt::Display for TransformProperty {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    // 'forceToPoint'
275    #[test]
276    fn force_to_point_maps_every_point_to_the_offset() {
277        let forced_offset = Offset::new(20.0, -30.0);
278        let forced_transform = force_to_point(forced_offset);
279
280        assert_eq!(
281            transform_point(&forced_transform, forced_offset),
282            forced_offset
283        );
284
285        assert_eq!(
286            transform_point(&forced_transform, Offset::ZERO),
287            forced_offset
288        );
289
290        assert_eq!(
291            transform_point(&forced_transform, Offset::new(1.0, 1.0)),
292            forced_offset
293        );
294
295        assert_eq!(
296            transform_point(&forced_transform, Offset::new(-1.0, -1.0)),
297            forced_offset
298        );
299
300        assert_eq!(
301            transform_point(&forced_transform, Offset::new(-20.0, 30.0)),
302            forced_offset
303        );
304
305        assert_eq!(
306            transform_point(&forced_transform, Offset::new(-1.2344, 1422434.23)),
307            forced_offset
308        );
309    }
310
311    #[test]
312    fn identity_leaves_a_rect_alone() {
313        let rect = Rect::from_ltwh(3.0, 5.0, 10.0, 20.0);
314        assert_eq!(transform_rect(&Matrix4::IDENTITY, rect), rect);
315        assert_eq!(get_as_translation(Matrix4::IDENTITY), Some(Offset::ZERO));
316        assert_eq!(get_as_scale(Matrix4::IDENTITY), Some(1.0));
317    }
318
319    /// `matrix_utils.dart`'s `debugDescribeTransform`: one string per row, and `null` for none.
320    #[test]
321    fn debug_describe_transform_lists_the_rows_of_the_matrix() {
322        let rows = debug_describe_transform(Some(Matrix4::IDENTITY));
323        assert_eq!(
324            rows,
325            [
326                "[0] 1.0,0.0,0.0,0.0",
327                "[1] 0.0,1.0,0.0,0.0",
328                "[2] 0.0,0.0,1.0,0.0",
329                "[3] 0.0,0.0,0.0,1.0",
330            ]
331        );
332        assert_eq!(debug_describe_transform(None), ["null"]);
333    }
334
335    #[test]
336    fn translation_shifts_points_and_rects() {
337        let transform = Matrix4::translation(7.0, -2.0);
338        assert_eq!(get_as_translation(transform), Some(Offset::new(7.0, -2.0)));
339        assert_eq!(
340            transform_point(&transform, Offset::new(1.0, 1.0)),
341            Offset::new(8.0, -1.0)
342        );
343        assert_eq!(
344            transform_rect(&transform, Rect::from_ltwh(0.0, 0.0, 4.0, 4.0)),
345            Rect::from_ltwh(7.0, -2.0, 4.0, 4.0)
346        );
347    }
348
349    #[test]
350    fn scale_grows_the_bounding_box_from_the_origin() {
351        let transform = Matrix4::scale(2.0, 3.0);
352        assert_eq!(get_as_scale(transform), None);
353        assert_eq!(
354            transform_rect(&transform, Rect::from_ltwh(1.0, 1.0, 2.0, 2.0)),
355            Rect::from_ltrb(2.0, 3.0, 6.0, 9.0)
356        );
357        assert_eq!(get_as_scale(Matrix4::scale(2.0, 2.0)), Some(2.0));
358    }
359}