Skip to main content

skia_safe/core/
matrix.rs

1//! Holds a 3x3 matrix for transforming coordinates. This allows mapping [`Point`] and vectors
2//! with translation, scaling, skewing, rotation, and perspective.
3//!
4//! Matrix elements are in row-major order. [`Matrix`] constexpr default constructs to identity.
5//!
6//! [`Matrix`] includes a hidden variable that classifies the type of matrix to improve
7//! performance. [`Matrix`] is not thread safe unless [`Matrix::get_type()`] is called first.
8//!
9//! Example (C++): <https://fiddle.skia.org/c/@Matrix_063>
10
11use std::{
12    ops::{Index, IndexMut, Mul},
13    slice,
14};
15
16use super::scalar_;
17use crate::{Point, Point3, RSXform, Rect, Scalar, Size, Vector, prelude::*, scalar};
18use skia_bindings::{self as sb, SkMatrix};
19
20#[repr(C)]
21#[derive(Copy, Clone, Debug)]
22pub struct Matrix {
23    mat: [scalar; 9usize],
24    type_mask: u32,
25}
26
27native_transmutable!(SkMatrix, Matrix);
28
29impl PartialEq for Matrix {
30    fn eq(&self, rhs: &Self) -> bool {
31        unsafe { sb::C_SkMatrix_Equals(self.native(), rhs.native()) }
32    }
33}
34
35impl Mul for Matrix {
36    type Output = Self;
37    fn mul(self, rhs: Matrix) -> Self::Output {
38        Matrix::concat(&self, &rhs)
39    }
40}
41
42#[derive(Copy, Clone, PartialEq, Eq, Debug)]
43pub enum Member {
44    ScaleX = 0,
45    SkewX = 1,
46    TransX = 2,
47    SkewY = 3,
48    ScaleY = 4,
49    TransY = 5,
50    Persp0 = 6,
51    Persp1 = 7,
52    Persp2 = 8,
53}
54
55#[derive(Copy, Clone, PartialEq, Eq, Debug)]
56pub enum AffineMember {
57    ScaleX = 0,
58    SkewY = 1,
59    SkewX = 2,
60    ScaleY = 3,
61    TransX = 4,
62    TransY = 5,
63}
64
65impl Index<Member> for Matrix {
66    type Output = scalar;
67
68    fn index(&self, index: Member) -> &Self::Output {
69        &self[index as usize]
70    }
71}
72
73impl Index<AffineMember> for Matrix {
74    type Output = scalar;
75
76    fn index(&self, index: AffineMember) -> &Self::Output {
77        &self[index as usize]
78    }
79}
80
81impl Index<usize> for Matrix {
82    type Output = scalar;
83
84    fn index(&self, index: usize) -> &Self::Output {
85        &self.native().fMat[index]
86    }
87}
88
89impl IndexMut<Member> for Matrix {
90    fn index_mut(&mut self, index: Member) -> &mut Self::Output {
91        self.index_mut(index as usize)
92    }
93}
94
95impl IndexMut<AffineMember> for Matrix {
96    fn index_mut(&mut self, index: AffineMember) -> &mut Self::Output {
97        self.index_mut(index as usize)
98    }
99}
100
101impl IndexMut<usize> for Matrix {
102    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
103        unsafe { &mut *sb::C_SkMatrix_SubscriptMut(self.native_mut(), index) }
104    }
105}
106
107impl Default for Matrix {
108    fn default() -> Self {
109        Matrix::new()
110    }
111}
112
113impl Matrix {
114    const fn new() -> Self {
115        Self {
116            mat: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
117            type_mask: TypeMask::IDENTITY.bits() | 0x10,
118        }
119    }
120
121    #[must_use]
122    /// Sets the matrix to scale by (`sx`, `sy`). The returned matrix is:
123    ///
124    /// ```text
125    /// | sx  0  0 |
126    /// |  0 sy  0 |
127    /// |  0  0  1 |
128    /// ```
129    ///
130    /// - `sx` horizontal scale factor
131    /// - `sy` vertical scale factor
132    pub fn scale((sx, sy): (scalar, scalar)) -> Self {
133        let mut m = Self::new();
134        m.set_scale((sx, sy), None);
135        m
136    }
137
138    #[must_use]
139    /// Sets the matrix to translate by (`dx`, `dy`). The returned matrix is:
140    ///
141    /// ```text
142    /// | 1 0 dx |
143    /// | 0 1 dy |
144    /// | 0 0  1 |
145    /// ```
146    ///
147    /// - `d` translation as a vector
148    pub fn translate(d: impl Into<Vector>) -> Self {
149        let mut m = Self::new();
150        m.set_translate(d);
151        m
152    }
153
154    #[must_use]
155    pub fn scale_translate((sx, sy): (scalar, scalar), t: impl Into<Vector>) -> Self {
156        let t = t.into();
157        Self::construct(|m| unsafe { sb::C_SkMatrix_ScaleTranslate(sx, sy, t.x, t.y, m) })
158    }
159
160    #[must_use]
161    /// Sets the matrix to rotate by `deg` about a pivot point at (0, 0).
162    ///
163    /// - `deg` rotation angle in degrees (positive rotates clockwise)
164    pub fn rotate_deg(deg: scalar) -> Self {
165        let mut m = Self::new();
166        m.set_rotate(deg, None);
167        m
168    }
169
170    #[must_use]
171    pub fn rotate_deg_pivot(deg: scalar, pivot: impl Into<Point>) -> Self {
172        let mut m = Self::new();
173        m.set_rotate(deg, pivot.into());
174        m
175    }
176
177    #[must_use]
178    pub fn rotate_rad(rad: scalar) -> Self {
179        Self::rotate_deg(scalar_::radians_to_degrees(rad))
180    }
181
182    #[must_use]
183    /// Sets the matrix to skew by (`kx`, `ky`) about the pivot point (0, 0).
184    ///
185    /// - `kx` horizontal skew factor
186    /// - `ky` vertical skew factor
187    pub fn skew((kx, ky): (scalar, scalar)) -> Self {
188        let mut m = Self::new();
189        m.set_skew((kx, ky), None);
190        m
191    }
192}
193
194pub type ScaleToFit = skia_bindings::SkMatrix_ScaleToFit;
195variant_name!(ScaleToFit::Fill);
196
197impl Matrix {
198    #[deprecated(since = "0.89.0", note = "Use rect_2_rect")]
199    #[must_use]
200    pub fn rect_to_rect(
201        src: impl AsRef<Rect>,
202        dst: impl AsRef<Rect>,
203        scale_to_fit: impl Into<Option<ScaleToFit>>,
204    ) -> Option<Self> {
205        Self::rect_2_rect(src, dst, scale_to_fit.into().unwrap_or(ScaleToFit::Fill))
206    }
207
208    #[must_use]
209    #[allow(clippy::too_many_arguments)]
210    /// Sets the matrix to:
211    ///
212    /// ```text
213    /// | scaleX  skewX transX |
214    /// |  skewY scaleY transY |
215    /// |  pers0  pers1  pers2 |
216    /// ```
217    ///
218    /// - `scale_x` horizontal scale factor
219    /// - `skew_x` horizontal skew factor
220    /// - `trans_x` horizontal translation
221    /// - `skew_y` vertical skew factor
222    /// - `scale_y` vertical scale factor
223    /// - `trans_y` vertical translation
224    /// - `pers_0` input x-axis perspective factor
225    /// - `pers_1` input y-axis perspective factor
226    /// - `pers_2` perspective scale factor
227    pub fn new_all(
228        scale_x: scalar,
229        skew_x: scalar,
230        trans_x: scalar,
231        skew_y: scalar,
232        scale_y: scalar,
233        trans_y: scalar,
234        pers_0: scalar,
235        pers_1: scalar,
236        pers_2: scalar,
237    ) -> Self {
238        let mut m = Self::new();
239        m.set_all(
240            scale_x, skew_x, trans_x, skew_y, scale_y, trans_y, pers_0, pers_1, pers_2,
241        );
242        m
243    }
244}
245
246bitflags! {
247    // m85: On Windows the SkMatrix_TypeMask is defined as i32,
248    // but we stick to u32 (macOS / Linux), because there is no need to leak
249    // the platform difference to the Rust side.
250    #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
251    pub struct TypeMask: u32 {
252        const IDENTITY = sb::SkMatrix_TypeMask_kIdentity_Mask as _;
253        const TRANSLATE = sb::SkMatrix_TypeMask_kTranslate_Mask as _;
254        const SCALE = sb::SkMatrix_TypeMask_kScale_Mask as _;
255        const AFFINE = sb::SkMatrix_TypeMask_kAffine_Mask as _;
256        const PERSPECTIVE = sb::SkMatrix_TypeMask_kPerspective_Mask as _;
257    }
258}
259
260impl TypeMask {
261    const UNKNOWN: u32 = sb::SkMatrix_kUnknown_Mask as _;
262}
263
264impl Matrix {
265    /// Returns a bit field describing the transformations the matrix may perform. The bit field is
266    /// computed conservatively, so it may include false positives. For example, when
267    /// [`TypeMask::PERSPECTIVE`] is set, all other bits are set.
268    pub fn get_type(&self) -> TypeMask {
269        TypeMask::from_bits_truncate(unsafe { sb::C_SkMatrix_getType(self.native()) } as _)
270    }
271
272    /// Returns true if the matrix is identity. The identity matrix is:
273    ///
274    /// ```text
275    /// | 1 0 0 |
276    /// | 0 1 0 |
277    /// | 0 0 1 |
278    /// ```
279    pub fn is_identity(&self) -> bool {
280        self.get_type() == TypeMask::IDENTITY
281    }
282
283    /// Returns true if the matrix at most scales and translates. The matrix may be identity,
284    /// contain only scale elements, only translate elements, or both. The matrix form is:
285    ///
286    /// ```text
287    /// | scale-x    0    translate-x |
288    /// |    0    scale-y translate-y |
289    /// |    0       0         1      |
290    /// ```
291    pub fn is_scale_translate(&self) -> bool {
292        (self.get_type() & !(TypeMask::SCALE | TypeMask::TRANSLATE)).is_empty()
293    }
294
295    /// Returns true if the matrix is identity, or translates. The matrix form is:
296    ///
297    /// ```text
298    /// | 1 0 translate-x |
299    /// | 0 1 translate-y |
300    /// | 0 0      1      |
301    /// ```
302    pub fn is_translate(&self) -> bool {
303        (self.get_type() & !TypeMask::TRANSLATE).is_empty()
304    }
305
306    /// Returns true if the matrix maps a [`Rect`] to another [`Rect`]. If true, the matrix is
307    /// identity, or scales, or rotates a multiple of 90 degrees, or mirrors on axes. In all cases,
308    /// the matrix may also have translation. The matrix form is either:
309    ///
310    /// ```text
311    /// | scale-x    0    translate-x |
312    /// |    0    scale-y translate-y |
313    /// |    0       0         1      |
314    /// ```
315    ///
316    /// or
317    ///
318    /// ```text
319    /// |    0     rotate-x translate-x |
320    /// | rotate-y    0     translate-y |
321    /// |    0        0          1      |
322    /// ```
323    ///
324    /// for non-zero values of scale-x, scale-y, rotate-x, and rotate-y.
325    ///
326    /// Also called [`Self::preserves_axis_alignment()`]; use the one that provides better inline
327    /// documentation.
328    pub fn rect_stays_rect(&self) -> bool {
329        unsafe { sb::C_SkMatrix_rectStaysRect(self.native()) }
330    }
331
332    /// Returns true if the matrix maps a [`Rect`] to another [`Rect`]. If true, the matrix is
333    /// identity, or scales, or rotates a multiple of 90 degrees, or mirrors on axes. In all cases,
334    /// the matrix may also have translation. The matrix form is either:
335    ///
336    /// ```text
337    /// | scale-x    0    translate-x |
338    /// |    0    scale-y translate-y |
339    /// |    0       0         1      |
340    /// ```
341    ///
342    /// or
343    ///
344    /// ```text
345    /// |    0     rotate-x translate-x |
346    /// | rotate-y    0     translate-y |
347    /// |    0        0          1      |
348    /// ```
349    ///
350    /// for non-zero values of scale-x, scale-y, rotate-x, and rotate-y.
351    ///
352    /// Also called [`Self::rect_stays_rect()`]; use the one that provides better inline
353    /// documentation.
354    pub fn preserves_axis_alignment(&self) -> bool {
355        self.rect_stays_rect()
356    }
357
358    /// Returns true if the matrix contains perspective elements. The matrix form is:
359    ///
360    /// ```text
361    /// |       --            --              --          |
362    /// |       --            --              --          |
363    /// | perspective-x  perspective-y  perspective-scale |
364    /// ```
365    ///
366    /// where perspective-x or perspective-y is non-zero, or perspective-scale is not one. All other
367    /// elements may have any value.
368    pub fn has_perspective(&self) -> bool {
369        unsafe { sb::C_SkMatrix_hasPerspective(self.native()) }
370    }
371
372    /// Returns true if the matrix contains only translation, rotation, reflection, and uniform
373    /// scale. Returns false if the matrix contains different scales, skewing, perspective, or
374    /// degenerate forms that collapse to a line or point.
375    ///
376    /// Describes that the matrix makes rendering with and without the matrix visually alike; a
377    /// transformed circle remains a circle. Mathematically, this is referred to as similarity of a
378    /// Euclidean space, or a similarity transformation.
379    ///
380    /// Preserves right angles, keeping the arms of the angle equal lengths.
381    ///
382    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_isSimilarity>
383    pub fn is_similarity(&self) -> bool {
384        unsafe { self.native().isSimilarity(scalar::NEARLY_ZERO) }
385    }
386
387    /// Returns true if the matrix contains only translation, rotation, reflection, and scale. Scale
388    /// may differ along rotated axes. Returns false if the matrix skews, has perspective, or has
389    /// degenerate forms that collapse to a line or point.
390    ///
391    /// Preserves right angles, but does not require that the arms of the angle retain equal
392    /// lengths.
393    ///
394    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_preservesRightAngles>
395    pub fn preserves_right_angles(&self) -> bool {
396        unsafe { self.native().preservesRightAngles(scalar::NEARLY_ZERO) }
397    }
398
399    /// Returns one matrix value from a particular row/column. Asserts if the index is out of range
400    /// and `SK_DEBUG` is defined.
401    ///
402    /// - `r` matrix row to fetch
403    /// - `c` matrix column to fetch
404    pub fn rc(&self, r: usize, c: usize) -> scalar {
405        assert!(r <= 2);
406        assert!(c <= 2);
407        self[r * 3 + c]
408    }
409
410    /// Returns the scale factor multiplied by the x-axis input, contributing to the x-axis output.
411    /// With [`Self::map_points()`], scales [`Point`] along the x-axis.
412    pub fn scale_x(&self) -> scalar {
413        self[Member::ScaleX]
414    }
415
416    /// Returns the scale factor multiplied by the y-axis input, contributing to the y-axis output.
417    /// With [`Self::map_points()`], scales [`Point`] along the y-axis.
418    pub fn scale_y(&self) -> scalar {
419        self[Member::ScaleY]
420    }
421
422    /// Returns the scale factor multiplied by the x-axis input, contributing to the y-axis output.
423    /// With [`Self::map_points()`], skews [`Point`] along the y-axis. Skewing both axes can rotate
424    /// [`Point`].
425    pub fn skew_y(&self) -> scalar {
426        self[Member::SkewY]
427    }
428
429    /// Returns the scale factor multiplied by the y-axis input, contributing to the x-axis output.
430    /// With [`Self::map_points()`], skews [`Point`] along the x-axis. Skewing both axes can rotate
431    /// [`Point`].
432    pub fn skew_x(&self) -> scalar {
433        self[Member::SkewX]
434    }
435
436    /// Returns the translation contributing to the x-axis output. With [`Self::map_points()`],
437    /// moves [`Point`] along the x-axis.
438    pub fn translate_x(&self) -> scalar {
439        self[Member::TransX]
440    }
441
442    /// Returns the translation contributing to the y-axis output. With [`Self::map_points()`],
443    /// moves [`Point`] along the y-axis.
444    pub fn translate_y(&self) -> scalar {
445        self[Member::TransY]
446    }
447
448    /// Returns the factor scaling input x-axis relative to input y-axis.
449    pub fn persp_x(&self) -> scalar {
450        self[Member::Persp0]
451    }
452
453    /// Returns the factor scaling input y-axis relative to input x-axis.
454    pub fn persp_y(&self) -> scalar {
455        self[Member::Persp1]
456    }
457
458    /// Sets the horizontal scale factor.
459    ///
460    /// - `v` horizontal scale factor to store
461    pub fn set_scale_x(&mut self, v: scalar) -> &mut Self {
462        self.set(Member::ScaleX, v)
463    }
464
465    /// Sets the vertical scale factor.
466    ///
467    /// - `v` vertical scale factor to store
468    pub fn set_scale_y(&mut self, v: scalar) -> &mut Self {
469        self.set(Member::ScaleY, v)
470    }
471
472    /// Sets the vertical skew factor.
473    ///
474    /// - `v` vertical skew factor to store
475    pub fn set_skew_y(&mut self, v: scalar) -> &mut Self {
476        self.set(Member::SkewY, v)
477    }
478
479    /// Sets the horizontal skew factor.
480    ///
481    /// - `v` horizontal skew factor to store
482    pub fn set_skew_x(&mut self, v: scalar) -> &mut Self {
483        self.set(Member::SkewX, v)
484    }
485
486    /// Sets the horizontal translation.
487    ///
488    /// - `v` horizontal translation to store
489    pub fn set_translate_x(&mut self, v: scalar) -> &mut Self {
490        self.set(Member::TransX, v)
491    }
492
493    /// Sets the vertical translation.
494    ///
495    /// - `v` vertical translation to store
496    pub fn set_translate_y(&mut self, v: scalar) -> &mut Self {
497        self.set(Member::TransY, v)
498    }
499
500    /// Sets the input x-axis perspective factor, which causes [`Self::map_points()`] to vary input
501    /// x-axis values inversely proportional to input y-axis values.
502    ///
503    /// - `v` perspective factor
504    pub fn set_persp_x(&mut self, v: scalar) -> &mut Self {
505        self.set(Member::Persp0, v)
506    }
507
508    /// Sets the input y-axis perspective factor, which causes [`Self::map_points()`] to vary input
509    /// y-axis values inversely proportional to input x-axis values.
510    ///
511    /// - `v` perspective factor
512    pub fn set_persp_y(&mut self, v: scalar) -> &mut Self {
513        self.set(Member::Persp1, v)
514    }
515
516    /// Sets all values from parameters. Sets the matrix to:
517    ///
518    /// ```text
519    /// | scaleX  skewX transX |
520    /// |  skewY scaleY transY |
521    /// | persp0 persp1 persp2 |
522    /// ```
523    ///
524    /// - `scale_x` horizontal scale factor to store
525    /// - `skew_x` horizontal skew factor to store
526    /// - `trans_x` horizontal translation to store
527    /// - `skew_y` vertical skew factor to store
528    /// - `scale_y` vertical scale factor to store
529    /// - `trans_y` vertical translation to store
530    /// - `persp_0` input x-axis values perspective factor to store
531    /// - `persp_1` input y-axis values perspective factor to store
532    /// - `persp_2` perspective scale factor to store
533    #[allow(clippy::too_many_arguments)]
534    pub fn set_all(
535        &mut self,
536        scale_x: scalar,
537        skew_x: scalar,
538        trans_x: scalar,
539        skew_y: scalar,
540        scale_y: scalar,
541        trans_y: scalar,
542        persp_0: scalar,
543        persp_1: scalar,
544        persp_2: scalar,
545    ) -> &mut Self {
546        self[Member::ScaleX] = scale_x;
547        self[Member::SkewX] = skew_x;
548        self[Member::TransX] = trans_x;
549        self[Member::SkewY] = skew_y;
550        self[Member::ScaleY] = scale_y;
551        self[Member::TransY] = trans_y;
552        self[Member::Persp0] = persp_0;
553        self[Member::Persp1] = persp_1;
554        self[Member::Persp2] = persp_2;
555        self.type_mask = TypeMask::UNKNOWN;
556        self
557    }
558
559    /// Copies the nine scalar values contained by the matrix into `buffer`, in member value
560    /// ascending order: scale-x, skew-x, trans-x, skew-y, scale-y, trans-y, persp-0, persp-1,
561    /// persp-2.
562    ///
563    /// - `buffer` storage for nine scalar values
564    pub fn get_9(&self, buffer: &mut [scalar; 9]) {
565        buffer.copy_from_slice(&self.mat)
566    }
567
568    /// Sets the matrix to the nine scalar values in `buffer`, in member value ascending order:
569    /// scale-x, skew-x, trans-x, skew-y, scale-y, trans-y, persp-0, persp-1, persp-2.
570    ///
571    /// Sets the matrix to:
572    ///
573    /// ```text
574    /// | buffer[0] buffer[1] buffer[2] |
575    /// | buffer[3] buffer[4] buffer[5] |
576    /// | buffer[6] buffer[7] buffer[8] |
577    /// ```
578    ///
579    /// In the future, `set_9` followed by `get_9` may not return the same values. Since the matrix
580    /// maps non-homogeneous coordinates, scaling all nine values produces an equivalent
581    /// transformation, possibly improving precision.
582    ///
583    /// - `buffer` nine scalar values
584    pub fn set_9(&mut self, buffer: &[scalar; 9]) -> &mut Self {
585        unsafe {
586            self.native_mut().set9(buffer.as_ptr());
587        }
588        self
589    }
590
591    /// Sets the matrix to identity, which has no effect on mapped points. Sets the matrix to:
592    ///
593    /// ```text
594    /// | 1 0 0 |
595    /// | 0 1 0 |
596    /// | 0 0 1 |
597    /// ```
598    ///
599    /// Also called [`Self::set_identity()`]; use the one that provides better inline documentation.
600    pub fn reset(&mut self) -> &mut Self {
601        unsafe {
602            self.native_mut().reset();
603        }
604        self
605    }
606
607    /// Sets the matrix to identity, which has no effect on mapped points. Sets the matrix to:
608    ///
609    /// ```text
610    /// | 1 0 0 |
611    /// | 0 1 0 |
612    /// | 0 0 1 |
613    /// ```
614    ///
615    /// Also called [`Self::reset()`]; use the one that provides better inline documentation.
616    pub fn set_identity(&mut self) -> &mut Self {
617        self.reset();
618        self
619    }
620
621    /// Sets the matrix to translate by `v`.
622    ///
623    /// - `v` vector containing horizontal and vertical translation
624    pub fn set_translate(&mut self, v: impl Into<Vector>) -> &mut Self {
625        let v = v.into();
626        unsafe {
627            self.native_mut().setTranslate(v.x, v.y);
628        }
629        self
630    }
631
632    /// Sets the matrix to scale by (`sx`, `sy`), about a pivot point at `pivot`. The pivot point is
633    /// unchanged when mapped with the matrix.
634    ///
635    /// - `sx` horizontal scale factor
636    /// - `sy` vertical scale factor
637    /// - `pivot` pivot on x- and y-axes
638    pub fn set_scale(
639        &mut self,
640        (sx, sy): (scalar, scalar),
641        pivot: impl Into<Option<Point>>,
642    ) -> &mut Self {
643        let pivot = pivot.into().unwrap_or_default();
644        unsafe {
645            self.native_mut().setScale(sx, sy, pivot.x, pivot.y);
646        }
647        self
648    }
649
650    /// Sets the matrix to rotate by `degrees` about a pivot point at `pivot`. The pivot point is
651    /// unchanged when mapped with the matrix.
652    ///
653    /// Positive degrees rotates clockwise.
654    ///
655    /// - `degrees` angle of axes relative to upright axes
656    /// - `pivot` pivot on x- and y-axes
657    pub fn set_rotate(&mut self, degrees: scalar, pivot: impl Into<Option<Point>>) -> &mut Self {
658        let pivot = pivot.into().unwrap_or_default();
659        unsafe {
660            self.native_mut().setRotate(degrees, pivot.x, pivot.y);
661        }
662        self
663    }
664
665    /// Sets the matrix to rotate by `sin_value` and `cos_value`, about a pivot point at `pivot`.
666    /// The pivot point is unchanged when mapped with the matrix.
667    ///
668    /// Vector (`sin_value`, `cos_value`) describes the angle of rotation relative to (0, 1). Vector
669    /// length specifies scale.
670    ///
671    /// - `sin_value` rotation vector x-axis component
672    /// - `cos_value` rotation vector y-axis component
673    /// - `pivot` pivot on x- and y-axes
674    pub fn set_sin_cos(
675        &mut self,
676        (sin_value, cos_value): (scalar, scalar),
677        pivot: impl Into<Option<Point>>,
678    ) -> &mut Self {
679        let pivot = pivot.into().unwrap_or_default();
680        unsafe {
681            self.native_mut()
682                .setSinCos(sin_value, cos_value, pivot.x, pivot.y);
683        }
684        self
685    }
686
687    /// Sets the matrix to rotate, scale, and translate using a compressed matrix form.
688    ///
689    /// Vector (`rsxform.scos`, `rsxform.ssin`) describes the angle of rotation relative to (0, 1).
690    /// Vector length specifies scale. The mapped point is rotated and scaled by the vector, then
691    /// translated by (`rsxform.tx`, `rsxform.ty`).
692    ///
693    /// - `rsxform` compressed [`RSXform`] matrix
694    ///
695    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_setRSXform>
696    pub fn set_rsxform(&mut self, rsxform: &RSXform) -> &mut Self {
697        unsafe {
698            self.native_mut().setRSXform(rsxform.native());
699        }
700        self
701    }
702
703    /// Sets the matrix to skew by (`kx`, `ky`), about a pivot point at `pivot`. The pivot point is
704    /// unchanged when mapped with the matrix.
705    ///
706    /// - `kx` horizontal skew factor
707    /// - `ky` vertical skew factor
708    /// - `pivot` pivot on x- and y-axes
709    pub fn set_skew(
710        &mut self,
711        (kx, ky): (scalar, scalar),
712        pivot: impl Into<Option<Point>>,
713    ) -> &mut Self {
714        let pivot = pivot.into().unwrap_or_default();
715        unsafe {
716            self.native_mut().setSkew(kx, ky, pivot.x, pivot.y);
717        }
718        self
719    }
720
721    /// Sets the matrix to matrix `a` multiplied by matrix `b`. Either `a` or `b` may be this.
722    ///
723    /// Given:
724    ///
725    /// ```text
726    ///         | A B C |      | J K L |
727    ///     a = | D E F |, b = | M N O |
728    ///         | G H I |      | P Q R |
729    /// ```
730    ///
731    /// sets the matrix to:
732    ///
733    /// ```text
734    ///             | A B C |   | J K L |   | AJ+BM+CP AK+BN+CQ AL+BO+CR |
735    ///     a * b = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR |
736    ///             | G H I |   | P Q R |   | GJ+HM+IP GK+HN+IQ GL+HO+IR |
737    /// ```
738    ///
739    /// - `a` matrix on left side of multiply expression
740    /// - `b` matrix on right side of multiply expression
741    pub fn set_concat(&mut self, a: &Self, b: &Self) -> &mut Self {
742        unsafe {
743            self.native_mut().setConcat(a.native(), b.native());
744        }
745        self
746    }
747
748    /// Sets the matrix to the matrix multiplied by a matrix constructed from translation `delta`.
749    /// This can be thought of as moving the point to be mapped before applying the matrix.
750    ///
751    /// Given:
752    ///
753    /// ```text
754    ///              | A B C |               | 1 0 dx |
755    ///     Matrix = | D E F |,  T(dx, dy) = | 0 1 dy |
756    ///              | G H I |               | 0 0  1 |
757    /// ```
758    ///
759    /// sets the matrix to:
760    ///
761    /// ```text
762    ///                          | A B C | | 1 0 dx |   | A B A*dx+B*dy+C |
763    ///     Matrix * T(dx, dy) = | D E F | | 0 1 dy | = | D E D*dx+E*dy+F |
764    ///                          | G H I | | 0 0  1 |   | G H G*dx+H*dy+I |
765    /// ```
766    ///
767    /// - `delta` x- and y-axis translation before applying the matrix
768    pub fn pre_translate(&mut self, delta: impl Into<Vector>) -> &mut Self {
769        let delta = delta.into();
770        unsafe {
771            self.native_mut().preTranslate(delta.x, delta.y);
772        }
773        self
774    }
775
776    /// Sets the matrix to the matrix multiplied by a matrix constructed from scaling by (`sx`, `sy`)
777    /// about the pivot point `pivot`. This can be thought of as scaling about a pivot point before
778    /// applying the matrix.
779    ///
780    /// Given:
781    ///
782    /// ```text
783    ///              | A B C |                       | sx  0 dx |
784    ///     Matrix = | D E F |,  S(sx, sy, px, py) = |  0 sy dy |
785    ///              | G H I |                       |  0  0  1 |
786    /// ```
787    ///
788    /// where
789    ///
790    /// ```text
791    ///     dx = px - sx * px
792    ///     dy = py - sy * py
793    /// ```
794    ///
795    /// sets the matrix to:
796    ///
797    /// ```text
798    ///                                      | A B C | | sx  0 dx |   | A*sx B*sy A*dx+B*dy+C |
799    ///     Matrix * S(sx, sy, px, py) =     | D E F | |  0 sy dy | = | D*sx E*sy D*dx+E*dy+F |
800    ///                                      | G H I | |  0  0  1 |   | G*sx H*sy G*dx+H*dy+I |
801    /// ```
802    ///
803    /// - `sx` horizontal scale factor
804    /// - `sy` vertical scale factor
805    /// - `pivot` pivot on x- and y-axes
806    pub fn pre_scale(
807        &mut self,
808        (sx, sy): (scalar, scalar),
809        pivot: impl Into<Option<Point>>,
810    ) -> &mut Self {
811        let pivot = pivot.into().unwrap_or_default();
812        unsafe {
813            self.native_mut().preScale(sx, sy, pivot.x, pivot.y);
814        }
815        self
816    }
817
818    /// Sets the matrix to the matrix multiplied by a matrix constructed from rotating by `degrees`
819    /// about the pivot point `pivot`. This can be thought of as rotating about a pivot point before
820    /// applying the matrix.
821    ///
822    /// Positive degrees rotates clockwise.
823    ///
824    /// Given:
825    ///
826    /// ```text
827    ///              | A B C |                        | c -s dx |
828    ///     Matrix = | D E F |,  R(degrees, px, py) = | s  c dy |
829    ///              | G H I |                        | 0  0  1 |
830    /// ```
831    ///
832    /// where
833    ///
834    /// ```text
835    ///     c  = cos(degrees)
836    ///     s  = sin(degrees)
837    ///     dx =  s * py + (1 - c) * px
838    ///     dy = -s * px + (1 - c) * py
839    /// ```
840    ///
841    /// sets the matrix to:
842    ///
843    /// ```text
844    ///                                       | A B C | | c -s dx |   | Ac+Bs -As+Bc A*dx+B*dy+C |
845    ///     Matrix * R(degrees, px, py) =     | D E F | | s  c dy | = | Dc+Es -Ds+Ec D*dx+E*dy+F |
846    ///                                       | G H I | | 0  0  1 |   | Gc+Hs -Gs+Hc G*dx+H*dy+I |
847    /// ```
848    ///
849    /// - `degrees` angle of axes relative to upright axes
850    /// - `pivot` pivot on x- and y-axes
851    pub fn pre_rotate(&mut self, degrees: scalar, pivot: impl Into<Option<Point>>) -> &mut Self {
852        let pivot = pivot.into().unwrap_or_default();
853        unsafe {
854            self.native_mut().preRotate(degrees, pivot.x, pivot.y);
855        }
856        self
857    }
858
859    /// Sets the matrix to the matrix multiplied by a matrix constructed from skewing by (`kx`, `ky`)
860    /// about the pivot point `pivot`. This can be thought of as skewing about a pivot point before
861    /// applying the matrix.
862    ///
863    /// Given:
864    ///
865    /// ```text
866    ///              | A B C |                       |  1 kx dx |
867    ///     Matrix = | D E F |,  K(kx, ky, px, py) = | ky  1 dy |
868    ///              | G H I |                       |  0  0  1 |
869    /// ```
870    ///
871    /// where
872    ///
873    /// ```text
874    ///     dx = -kx * py
875    ///     dy = -ky * px
876    /// ```
877    ///
878    /// sets the matrix to:
879    ///
880    /// ```text
881    ///                                      | A B C | |  1 kx dx |   | A+B*ky A*kx+B A*dx+B*dy+C |
882    ///     Matrix * K(kx, ky, px, py) =     | D E F | | ky  1 dy | = | D+E*ky D*kx+E D*dx+E*dy+F |
883    ///                                      | G H I | |  0  0  1 |   | G+H*ky G*kx+H G*dx+H*dy+I |
884    /// ```
885    ///
886    /// - `kx` horizontal skew factor
887    /// - `ky` vertical skew factor
888    /// - `pivot` pivot on x- and y-axes
889    pub fn pre_skew(
890        &mut self,
891        (kx, ky): (scalar, scalar),
892        pivot: impl Into<Option<Point>>,
893    ) -> &mut Self {
894        let pivot = pivot.into().unwrap_or_default();
895        unsafe {
896            self.native_mut().preSkew(kx, ky, pivot.x, pivot.y);
897        }
898        self
899    }
900
901    /// Sets the matrix to the matrix multiplied by the matrix `other`. This can be thought of as
902    /// mapping by `other` before applying the matrix.
903    ///
904    /// Given:
905    ///
906    /// ```text
907    ///              | A B C |          | J K L |
908    ///     Matrix = | D E F |, other = | M N O |
909    ///              | G H I |          | P Q R |
910    /// ```
911    ///
912    /// sets the matrix to:
913    ///
914    /// ```text
915    ///                      | A B C |   | J K L |   | AJ+BM+CP AK+BN+CQ AL+BO+CR |
916    ///     Matrix * other = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR |
917    ///                      | G H I |   | P Q R |   | GJ+HM+IP GK+HN+IQ GL+HO+IR |
918    /// ```
919    ///
920    /// - `other` matrix on the right side of the multiply expression
921    pub fn pre_concat(&mut self, other: &Self) -> &mut Self {
922        unsafe {
923            self.native_mut().preConcat(other.native());
924        }
925        self
926    }
927
928    /// Sets the matrix to a matrix constructed from translation `delta` multiplied by the matrix.
929    /// This can be thought of as moving the point to be mapped after applying the matrix.
930    ///
931    /// Given:
932    ///
933    /// ```text
934    ///              | J K L |               | 1 0 dx |
935    ///     Matrix = | M N O |,  T(dx, dy) = | 0 1 dy |
936    ///              | P Q R |               | 0 0  1 |
937    /// ```
938    ///
939    /// sets the matrix to:
940    ///
941    /// ```text
942    ///                          | 1 0 dx | | J K L |   | J+dx*P K+dx*Q L+dx*R |
943    ///     T(dx, dy) * Matrix = | 0 1 dy | | M N O | = | M+dy*P N+dy*Q O+dy*R |
944    ///                          | 0 0  1 | | P Q R |   |      P      Q      R |
945    /// ```
946    ///
947    /// - `delta` x- and y-axis translation after applying the matrix
948    pub fn post_translate(&mut self, delta: impl Into<Vector>) -> &mut Self {
949        let delta = delta.into();
950        unsafe {
951            self.native_mut().postTranslate(delta.x, delta.y);
952        }
953        self
954    }
955
956    /// Sets the matrix to a matrix constructed from scaling by (`sx`, `sy`) about the pivot point
957    /// `pivot`, multiplied by the matrix. This can be thought of as scaling about a pivot point
958    /// after applying the matrix.
959    ///
960    /// Given:
961    ///
962    /// ```text
963    ///              | J K L |                       | sx  0 dx |
964    ///     Matrix = | M N O |,  S(sx, sy, px, py) = |  0 sy dy |
965    ///              | P Q R |                       |  0  0  1 |
966    /// ```
967    ///
968    /// where
969    ///
970    /// ```text
971    ///     dx = px - sx * px
972    ///     dy = py - sy * py
973    /// ```
974    ///
975    /// sets the matrix to:
976    ///
977    /// ```text
978    ///                                      | sx  0 dx | | J K L |   | sx*J+dx*P sx*K+dx*Q sx*L+dx*R |
979    ///     S(sx, sy, px, py) * Matrix =     |  0 sy dy | | M N O | = | sy*M+dy*P sy*N+dy*Q sy*O+dy*R |
980    ///                                      |  0  0  1 | | P Q R |   |         P         Q         R |
981    /// ```
982    ///
983    /// - `sx` horizontal scale factor
984    /// - `sy` vertical scale factor
985    /// - `pivot` pivot on x- and y-axes
986    pub fn post_scale(
987        &mut self,
988        (sx, sy): (scalar, scalar),
989        pivot: impl Into<Option<Point>>,
990    ) -> &mut Self {
991        let pivot = pivot.into().unwrap_or_default();
992        unsafe {
993            self.native_mut().postScale(sx, sy, pivot.x, pivot.y);
994        }
995        self
996    }
997
998    #[deprecated(
999        since = "0.27.0",
1000        note = "use post_scale((1.0 / x as scalar, 1.0 / y as scalar), None)"
1001    )]
1002    pub fn post_idiv(&mut self, (div_x, div_y): (i32, i32)) -> bool {
1003        if div_x == 0 || div_y == 0 {
1004            return false;
1005        }
1006        self.post_scale((1.0 / div_x as scalar, 1.0 / div_y as scalar), None);
1007        true
1008    }
1009
1010    /// Sets the matrix to a matrix constructed from rotating by `degrees` about the pivot point
1011    /// `pivot`, multiplied by the matrix. This can be thought of as rotating about a pivot point
1012    /// after applying the matrix.
1013    ///
1014    /// Positive degrees rotates clockwise.
1015    ///
1016    /// Given:
1017    ///
1018    /// ```text
1019    ///              | J K L |                        | c -s dx |
1020    ///     Matrix = | M N O |,  R(degrees, px, py) = | s  c dy |
1021    ///              | P Q R |                        | 0  0  1 |
1022    /// ```
1023    ///
1024    /// where
1025    ///
1026    /// ```text
1027    ///     c  = cos(degrees)
1028    ///     s  = sin(degrees)
1029    ///     dx =  s * py + (1 - c) * px
1030    ///     dy = -s * px + (1 - c) * py
1031    /// ```
1032    ///
1033    /// sets the matrix to:
1034    ///
1035    /// ```text
1036    ///                                       | c -s dx | | J K L |   | cJ-sM+dx*P cK-sN+dx*Q cL-sO+dx*R |
1037    ///     R(degrees, px, py) * Matrix =     | s  c dy | | M N O | = | sJ+cM+dy*P sK+cN+dy*Q sL+cO+dy*R |
1038    ///                                       | 0  0  1 | | P Q R |   |         P          Q          R |
1039    /// ```
1040    ///
1041    /// - `degrees` angle of axes relative to upright axes
1042    /// - `pivot` pivot on x- and y-axes
1043    pub fn post_rotate(&mut self, degrees: scalar, pivot: impl Into<Option<Point>>) -> &mut Self {
1044        let pivot = pivot.into().unwrap_or_default();
1045        unsafe {
1046            self.native_mut().postRotate(degrees, pivot.x, pivot.y);
1047        }
1048        self
1049    }
1050
1051    /// Sets the matrix to a matrix constructed from skewing by (`kx`, `ky`) about the pivot point
1052    /// `pivot`, multiplied by the matrix. This can be thought of as skewing about a pivot point
1053    /// after applying the matrix.
1054    ///
1055    /// Given:
1056    ///
1057    /// ```text
1058    ///              | J K L |                       |  1 kx dx |
1059    ///     Matrix = | M N O |,  K(kx, ky, px, py) = | ky  1 dy |
1060    ///              | P Q R |                       |  0  0  1 |
1061    /// ```
1062    ///
1063    /// where
1064    ///
1065    /// ```text
1066    ///     dx = -kx * py
1067    ///     dy = -ky * px
1068    /// ```
1069    ///
1070    /// sets the matrix to:
1071    ///
1072    /// ```text
1073    ///                                      | 1 kx dx | | J K L |   | J+kx*M+dx*P K+kx*N+dx*Q L+kx*O+dx*R |
1074    ///     K(kx, ky, px, py) * Matrix =     | ky  1 dy | | M N O | = | ky*J+M+dy*P ky*K+N+dy*Q ky*L+O+dy*R |
1075    ///                                      | 0  0  1 | | P Q R |   |          P           Q           R |
1076    /// ```
1077    ///
1078    /// - `kx` horizontal skew factor
1079    /// - `ky` vertical skew factor
1080    /// - `pivot` pivot on x- and y-axes
1081    pub fn post_skew(
1082        &mut self,
1083        (kx, ky): (scalar, scalar),
1084        pivot: impl Into<Option<Point>>,
1085    ) -> &mut Self {
1086        let pivot = pivot.into().unwrap_or_default();
1087        unsafe {
1088            self.native_mut().postSkew(kx, ky, pivot.x, pivot.y);
1089        }
1090        self
1091    }
1092
1093    /// Sets the matrix to the matrix `other` multiplied by the matrix. This can be thought of as
1094    /// mapping by `other` after applying the matrix.
1095    ///
1096    /// Given:
1097    ///
1098    /// ```text
1099    ///              | J K L |           | A B C |
1100    ///     Matrix = | M N O |,  other = | D E F |
1101    ///              | P Q R |           | G H I |
1102    /// ```
1103    ///
1104    /// sets the matrix to:
1105    ///
1106    /// ```text
1107    ///                      | A B C |   | J K L |   | AJ+BM+CP AK+BN+CQ AL+BO+CR |
1108    ///     other * Matrix = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR |
1109    ///                      | G H I |   | P Q R |   | GJ+HM+IP GK+HN+IQ GL+HO+IR |
1110    /// ```
1111    ///
1112    /// - `other` matrix on the left side of the multiply expression
1113    pub fn post_concat(&mut self, other: &Matrix) -> &mut Self {
1114        unsafe {
1115            self.native_mut().postConcat(other.native());
1116        }
1117        self
1118    }
1119
1120    #[deprecated(since = "0.88.0", note = "Use rect_2_rect")]
1121    pub fn from_rect_to_rect(
1122        src: impl AsRef<Rect>,
1123        dst: impl AsRef<Rect>,
1124        stf: ScaleToFit,
1125    ) -> Option<Self> {
1126        Self::rect_2_rect(src, dst, stf)
1127    }
1128
1129    /// If possible, returns a matrix that will transform the `src` rect to the `dst` rect. If `src`
1130    /// is empty, this will return `None`. If `dst` is empty, this will return the zero matrix
1131    /// (degenerate).
1132    ///
1133    /// - `src` source rectangle
1134    /// - `dst` destination rectangle
1135    /// - `stf` scale-to-fit mode, defaults to [`ScaleToFit::Fill`]
1136    pub fn rect_2_rect(
1137        src: impl AsRef<Rect>,
1138        dst: impl AsRef<Rect>,
1139        stf: impl Into<Option<ScaleToFit>>,
1140    ) -> Option<Self> {
1141        let mut m = Self::new_identity();
1142        unsafe {
1143            sb::C_SkMatrix_Rect2Rect(
1144                src.as_ref().native(),
1145                dst.as_ref().native(),
1146                stf.into().unwrap_or(ScaleToFit::Fill),
1147                m.native_mut(),
1148            )
1149        }
1150        .then_some(m)
1151    }
1152
1153    /// Returns the matrix that transforms the `src` rect to the `dst` rect, or the identity matrix
1154    /// if such a matrix does not exist (e.g. if `src` is empty).
1155    ///
1156    /// - `src` source rectangle
1157    /// - `dst` destination rectangle
1158    /// - `stf` scale-to-fit mode, defaults to [`ScaleToFit::Fill`]
1159    pub fn rect_to_rect_or_identity(
1160        src: impl AsRef<Rect>,
1161        dst: impl AsRef<Rect>,
1162        stf: impl Into<Option<ScaleToFit>>,
1163    ) -> Self {
1164        Self::rect_2_rect(src, dst, stf).unwrap_or(Matrix::new_identity())
1165    }
1166
1167    /// Computes a matrix from two polygons, such that if the matrix was applied to the `src`
1168    /// polygon, it would produce the `dst` polygon.
1169    ///
1170    /// If the size of the two spans are not equal, or if they are greater than 4, returns `None`.
1171    /// If the resulting matrix is non-invertible, returns `None`.
1172    ///
1173    /// - `src` source polygon points
1174    /// - `dst` destination polygon points
1175    ///
1176    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_setPolyToPoly>
1177    pub fn poly_to_poly(src: &[Point], dst: &[Point]) -> Option<Matrix> {
1178        let mut m = Matrix::new();
1179        m.set_poly_to_poly(src, dst).then_some(m)
1180    }
1181
1182    /// Sets the matrix to a matrix computed from two polygons, such that if the matrix was applied
1183    /// to the `src` polygon, it would produce the `dst` polygon.
1184    ///
1185    /// If the size of the two spans are not equal, or if they are greater than 4, returns `false`.
1186    /// If the resulting matrix is non-invertible, returns `false`.
1187    ///
1188    /// - `src` source polygon points
1189    /// - `dst` destination polygon points
1190    pub fn set_poly_to_poly(&mut self, src: &[Point], dst: &[Point]) -> bool {
1191        unsafe {
1192            sb::C_SkMatrix_setPolyToPoly(
1193                self.native_mut(),
1194                src.native().as_ptr(),
1195                src.len(),
1196                dst.native().as_ptr(),
1197                dst.len(),
1198            )
1199        }
1200    }
1201
1202    /// Computes a matrix from two polygons, such that if the matrix was applied to the `src`
1203    /// polygon, it would produce the `dst` polygon.
1204    ///
1205    /// If the size of the two spans are not equal, or if they are greater than 4, returns `None`.
1206    /// If the resulting matrix is non-invertible, returns `None`.
1207    ///
1208    /// - `src` source polygon points
1209    /// - `dst` destination polygon points
1210    pub fn from_poly_to_poly(src: &[Point], dst: &[Point]) -> Option<Matrix> {
1211        let mut m = Matrix::new_identity();
1212        m.set_poly_to_poly(src, dst).then_some(m)
1213    }
1214
1215    /// If this matrix is invertible, returns its inverse; otherwise, returns `None`.
1216    pub fn invert(&self) -> Option<Matrix> {
1217        let mut m = Matrix::new_identity();
1218        unsafe { sb::C_SkMatrix_invert(self.native(), m.native_mut()) }.then_some(m)
1219    }
1220
1221    /// Fills `affine` with identity values in column major order. Sets `affine` to:
1222    ///
1223    /// ```text
1224    /// | 1 0 0 |
1225    /// | 0 1 0 |
1226    /// ```
1227    ///
1228    /// Affine 3 by 2 matrices in column major order are used by OpenGL and XPS.
1229    ///
1230    /// - `affine` storage for the 3 by 2 affine matrix
1231    ///
1232    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_SetAffineIdentity>
1233    pub fn set_affine_identity(affine: &mut [scalar; 6]) {
1234        unsafe { SkMatrix::SetAffineIdentity(affine.as_mut_ptr()) }
1235    }
1236
1237    /// Fills `affine` in column major order. Sets `affine` to:
1238    ///
1239    /// ```text
1240    /// | scale-x  skew-x translate-x |
1241    /// |  skew-y scale-y translate-y |
1242    /// ```
1243    ///
1244    /// If the matrix contains perspective, returns `None` and leaves `affine` unchanged.
1245    #[must_use]
1246    pub fn to_affine(self) -> Option<[scalar; 6]> {
1247        let mut affine = [scalar::default(); 6];
1248        unsafe { self.native().asAffine(affine.as_mut_ptr()) }.then_some(affine)
1249    }
1250
1251    /// Sets the matrix to affine values, passed in column major order. Given `affine`, column, then
1252    /// row, as:
1253    ///
1254    /// ```text
1255    /// | scale-x  skew-x translate-x |
1256    /// |  skew-y scale-y translate-y |
1257    /// ```
1258    ///
1259    /// the matrix is set, row, then column, to:
1260    ///
1261    /// ```text
1262    /// | scale-x  skew-x translate-x |
1263    /// |  skew-y scale-y translate-y |
1264    /// |       0       0           1 |
1265    /// ```
1266    ///
1267    /// - `affine` 3 by 2 affine matrix
1268    pub fn set_affine(&mut self, affine: &[scalar; 6]) -> &mut Self {
1269        unsafe { self.native_mut().setAffine(affine.as_ptr()) };
1270        self
1271    }
1272
1273    /// Creates a matrix from affine values, passed in column major order. Given `affine`, column,
1274    /// then row, as:
1275    ///
1276    /// ```text
1277    /// | scale-x  skew-x translate-x |
1278    /// |  skew-y scale-y translate-y |
1279    /// ```
1280    ///
1281    /// the matrix is set, row, then column, to:
1282    ///
1283    /// ```text
1284    /// | scale-x  skew-x translate-x |
1285    /// |  skew-y scale-y translate-y |
1286    /// |       0       0           1 |
1287    /// ```
1288    ///
1289    /// - `affine` 3 by 2 affine matrix
1290    pub fn from_affine(affine: &[scalar; 6]) -> Matrix {
1291        let mut m = Matrix::new_identity();
1292        unsafe {
1293            m.native_mut().setAffine(affine.as_ptr());
1294        }
1295        m
1296    }
1297
1298    /// A matrix is categorized as 'perspective' if the bottom row is not `[0, 0, 1]`. However, for
1299    /// most uses (e.g. [`Self::map_points()`]) a bottom row of `[0, 0, X]` behaves like a
1300    /// non-perspective matrix, though it will be categorized as perspective. Calling
1301    /// `normalize_perspective()` will change the matrix such that, if its bottom row was `[0, 0, X]`,
1302    /// it will be changed to `[0, 0, 1]` by scaling the rest of the matrix by `1/X`.
1303    ///
1304    /// ```text
1305    /// | A B C |    | A/X B/X C/X |
1306    /// | D E F | -> | D/X E/X F/X |   for X != 0
1307    /// | 0 0 X |    |  0   0   1  |
1308    /// ```
1309    pub fn normalize_perspective(&mut self) {
1310        unsafe { sb::C_SkMatrix_normalizePerspective(self.native_mut()) }
1311    }
1312
1313    /// Maps the `src` point array to the `dst` point array. Points are mapped by multiplying each
1314    /// point by the matrix. Given:
1315    ///
1316    /// ```text
1317    ///              | A B C |        | x |
1318    ///     Matrix = | D E F |,  pt = | y |
1319    ///              | G H I |        | 1 |
1320    /// ```
1321    ///
1322    /// each `dst` point is computed as:
1323    ///
1324    /// ```text
1325    ///                   |A B C| |x|                               Ax+By+C   Dx+Ey+F
1326    ///     Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
1327    ///                   |G H I| |1|                               Gx+Hy+I   Gx+Hy+I
1328    /// ```
1329    ///
1330    /// `src` and `dst` may point to the same storage.
1331    ///
1332    /// - `dst` storage where the transformed points are written
1333    /// - `src` storage where the points are read from
1334    ///
1335    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_mapPoints>
1336    pub fn map_points(&self, dst: &mut [Point], src: &[Point]) {
1337        assert!(dst.len() >= src.len());
1338
1339        unsafe {
1340            sb::C_SkMatrix_mapPoints(
1341                self.native(),
1342                dst.native_mut().as_mut_ptr(),
1343                src.native().as_ptr(),
1344                src.len(),
1345            )
1346        };
1347    }
1348
1349    /// Maps the point array in place. Points are mapped by multiplying each point by the matrix.
1350    /// Given:
1351    ///
1352    /// ```text
1353    ///              | A B C |        | x |
1354    ///     Matrix = | D E F |,  pt = | y |
1355    ///              | G H I |        | 1 |
1356    /// ```
1357    ///
1358    /// each resulting point is computed as:
1359    ///
1360    /// ```text
1361    ///                   |A B C| |x|                               Ax+By+C   Dx+Ey+F
1362    ///     Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
1363    ///                   |G H I| |1|                               Gx+Hy+I   Gx+Hy+I
1364    /// ```
1365    ///
1366    /// - `pts` points to be transformed in place
1367    pub fn map_points_inplace(&self, pts: &mut [Point]) {
1368        let ptr = pts.native_mut().as_mut_ptr();
1369        unsafe { sb::C_SkMatrix_mapPoints(self.native(), ptr, ptr, pts.len()) };
1370    }
1371
1372    /// Maps the `src` point array to the `dst` point array. Points are mapped by multiplying each
1373    /// point by the matrix. Given:
1374    ///
1375    /// ```text
1376    ///              | A B C |         | x |
1377    ///     Matrix = | D E F |,  src = | y |
1378    ///              | G H I |         | z |
1379    /// ```
1380    ///
1381    /// each resulting point is computed as:
1382    ///
1383    /// ```text
1384    ///                |A B C| |x|
1385    ///     Matrix * src = |D E F| |y| = |Ax+By+Cz Dx+Ey+Fz Gx+Hy+Iz|
1386    ///                |G H I| |z|
1387    /// ```
1388    ///
1389    /// - `dst` storage where the transformed points are written
1390    /// - `src` storage where the points are read from
1391    ///
1392    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_mapHomogeneousPoints>
1393    pub fn map_homogeneous_points(&self, dst: &mut [Point3], src: &[Point3]) {
1394        assert!(dst.len() >= src.len());
1395
1396        unsafe {
1397            sb::C_SkMatrix_mapHomogeneousPoints(
1398                self.native(),
1399                dst.native_mut().as_mut_ptr(),
1400                src.native().as_ptr(),
1401                src.len(),
1402            )
1403        };
1404    }
1405
1406    /// Maps `src` point by the matrix.
1407    ///
1408    /// - `src` point to map
1409    pub fn map_homogeneous_point(&self, src: Point3) -> Point3 {
1410        let mut dst = Point3::default();
1411        self.map_homogeneous_points(slice::from_mut(&mut dst), &[src]);
1412        dst
1413    }
1414
1415    #[deprecated(since = "0.88.0", note = "use map_points_to_homogeneous()")]
1416    pub fn map_homogeneous_points_2d(&self, dst: &mut [Point3], src: &[Point]) {
1417        self.map_points_to_homogeneous(dst, src);
1418    }
1419
1420    /// Returns homogeneous points, starting with the 2D `src` points (with implied `w = 1`).
1421    ///
1422    /// - `dst` storage where the transformed points are written
1423    /// - `src` storage where the points are read from
1424    pub fn map_points_to_homogeneous(&self, dst: &mut [Point3], src: &[Point]) {
1425        assert!(dst.len() >= src.len());
1426
1427        unsafe {
1428            sb::C_SkMatrix_mapPointsToHomogeneous(
1429                self.native(),
1430                dst.native_mut().as_mut_ptr(),
1431                src.native().as_ptr(),
1432                src.len(),
1433            )
1434        };
1435    }
1436
1437    /// Returns `src` mapped to a homogeneous point.
1438    ///
1439    /// - `src` point to map
1440    pub fn map_point_to_homogeneous(&self, src: Point) -> Point3 {
1441        let mut dst = Point3::default();
1442        self.map_points_to_homogeneous(slice::from_mut(&mut dst), &[src]);
1443        dst
1444    }
1445
1446    #[deprecated(since = "0.88.0", note = "use map_point((x, y))")]
1447    pub fn map_xy(&self, x: scalar, y: scalar) -> Point {
1448        self.map_point((x, y))
1449    }
1450
1451    /// Returns the point multiplied by the matrix. Given:
1452    ///
1453    /// ```text
1454    ///              | A B C |        | x |
1455    ///     Matrix = | D E F |,  pt = | y |
1456    ///              | G H I |        | 1 |
1457    /// ```
1458    ///
1459    /// the result is computed as:
1460    ///
1461    /// ```text
1462    ///                   |A B C| |x|                               Ax+By+C   Dx+Ey+F
1463    ///     Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
1464    ///                   |G H I| |1|                               Gx+Hy+I   Gx+Hy+I
1465    /// ```
1466    ///
1467    /// - `point` point to map
1468    pub fn map_point(&self, point: impl Into<Point>) -> Point {
1469        Point::from_native_c(unsafe {
1470            sb::C_SkMatrix_mapPoint(self.native(), point.into().into_native())
1471        })
1472    }
1473
1474    /// If the caller knows the matrix has no perspective, this will inline the math, making it more
1475    /// efficient than calling [`Self::map_point()`].
1476    ///
1477    /// - `point` point to map
1478    pub fn map_point_affine(&self, point: impl Into<Point>) -> Point {
1479        Point::from_native_c(unsafe {
1480            sb::C_SkMatrix_mapPointAffine(self.native(), point.into().into_native())
1481        })
1482    }
1483
1484    /// Returns `(0, 0)` multiplied by the matrix. Given:
1485    ///
1486    /// ```text
1487    ///              | A B C |        | 0 |
1488    ///     Matrix = | D E F |,  pt = | 0 |
1489    ///              | G H I |        | 1 |
1490    /// ```
1491    ///
1492    /// the result is computed as:
1493    ///
1494    /// ```text
1495    ///                   |A B C| |0|             C    F
1496    ///     Matrix * pt = |D E F| |0| = |C F I| = -  , -
1497    ///                   |G H I| |1|             I    I
1498    /// ```
1499    pub fn map_origin(&self) -> Point {
1500        let mut x = self.translate_x();
1501        let mut y = self.translate_y();
1502        if self.has_perspective() {
1503            let mut w = self[Member::Persp2];
1504            if w != 0.0 {
1505                w = 1.0 / w;
1506            }
1507            x *= w;
1508            y *= w;
1509        }
1510        Point::new(x, y)
1511    }
1512
1513    /// Maps the `src` vector array to the `dst` vector array. Vectors are mapped by multiplying
1514    /// each vector by the matrix, treating the matrix translation as zero. Given:
1515    ///
1516    /// ```text
1517    ///              | A B 0 |         | x |
1518    ///     Matrix = | D E 0 |,  src = | y |
1519    ///              | G H I |         | 1 |
1520    /// ```
1521    ///
1522    /// each `dst` vector is computed as:
1523    ///
1524    /// ```text
1525    ///                |A B 0| |x|                            Ax+By     Dx+Ey
1526    ///     Matrix * src = |D E 0| |y| = |Ax+By Dx+Ey Gx+Hy+I| = ------- , -------
1527    ///                |G H I| |1|                           Gx+Hy+I   Gx+Hy+I
1528    /// ```
1529    ///
1530    /// `src` and `dst` may point to the same storage.
1531    ///
1532    /// - `dst` storage where the transformed vectors are written
1533    /// - `src` storage where the vectors are read from
1534    ///
1535    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_mapVectors>
1536    pub fn map_vectors(&self, dst: &mut [Vector], src: &[Vector]) {
1537        assert!(dst.len() >= src.len());
1538        unsafe {
1539            sb::C_SkMatrix_mapVectors(
1540                self.native(),
1541                dst.native_mut().as_mut_ptr(),
1542                src.native().as_ptr(),
1543                src.len(),
1544            )
1545        }
1546    }
1547
1548    /// Maps the vector array in place, multiplying each vector by the matrix, treating the matrix
1549    /// translation as zero.
1550    ///
1551    /// - `vecs` vectors to transform, and storage for the mapped vectors
1552    pub fn map_vectors_inplace(&self, vecs: &mut [Vector]) {
1553        let ptr = vecs.native_mut().as_mut_ptr();
1554        unsafe { sb::C_SkMatrix_mapVectors(self.native(), ptr, ptr, vecs.len()) }
1555    }
1556
1557    /// Returns the vector multiplied by the matrix, treating the matrix translation as zero. Given:
1558    ///
1559    /// ```text
1560    ///              | A B 0 |         | dx |
1561    ///     Matrix = | D E 0 |,  vec = | dy |
1562    ///              | G H I |         |  1 |
1563    /// ```
1564    ///
1565    /// the result vector is computed as:
1566    ///
1567    /// ```text
1568    ///                |A B 0| |dx|                                        A*dx+B*dy     D*dx+E*dy
1569    ///     Matrix * vec = |D E 0| |dy| = |A*dx+B*dy D*dx+E*dy G*dx+H*dy+I| = ----------- , -----------
1570    ///                |G H I| | 1|                                       G*dx+H*dy+I   G*dx+H*dy+I
1571    /// ```
1572    ///
1573    /// - `vec` vector to map
1574    pub fn map_vector(&self, vec: impl Into<Vector>) -> Vector {
1575        let mut vec = vec.into();
1576        self.map_vectors_inplace(slice::from_mut(&mut vec));
1577        vec
1578    }
1579
1580    /// Sets `dst` to the bounds of the `src` corners mapped by the matrix. Returns true if the
1581    /// mapped corners are the `dst` corners.
1582    ///
1583    /// The returned value is the same as calling [`Self::rect_stays_rect()`].
1584    ///
1585    /// - `src` rectangle to map
1586    ///
1587    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_mapRect>
1588    pub fn map_rect(&self, src: impl AsRef<Rect>) -> (Rect, bool) {
1589        let mut dst = Rect::default();
1590        let rect_stays_rect = unsafe {
1591            self.native()
1592                .mapRect(dst.native_mut(), src.as_ref().native())
1593        };
1594        (dst, rect_stays_rect)
1595    }
1596
1597    /// Maps the four corners of `rect` to a quad. Points are mapped by multiplying each rect corner
1598    /// by the matrix. The rect corner is processed in this order: (`rect.left`, `rect.top`),
1599    /// (`rect.right`, `rect.top`), (`rect.right`, `rect.bottom`), (`rect.left`, `rect.bottom`).
1600    ///
1601    /// `rect` may be empty: `rect.left` may be greater than or equal to `rect.right`; `rect.top` may
1602    /// be greater than or equal to `rect.bottom`.
1603    ///
1604    /// This does not perform perspective clipping (as that might result in more than 4 points, so
1605    /// results are suspect if the matrix contains perspective).
1606    ///
1607    /// - `rect` rectangle to map
1608    pub fn map_rect_to_quad(&self, rect: impl AsRef<Rect>) -> [Point; 4] {
1609        let mut quad = rect.as_ref().to_quad(None);
1610        self.map_points_inplace(quad.as_mut());
1611        quad
1612    }
1613
1614    /// Sets the result to the bounds of the `src` corners mapped by the matrix. If the matrix
1615    /// contains elements other than scale or translate, returns `None` (asserts if `SK_DEBUG` is
1616    /// defined; otherwise, results are undefined).
1617    ///
1618    /// - `src` rectangle to map
1619    ///
1620    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_mapRectScaleTranslate>
1621    pub fn map_rect_scale_translate(&self, src: impl AsRef<Rect>) -> Option<Rect> {
1622        if self.is_scale_translate() {
1623            let mut rect = Rect::default();
1624            unsafe {
1625                self.native()
1626                    .mapRectScaleTranslate(rect.native_mut(), src.as_ref().native())
1627            };
1628            Some(rect)
1629        } else {
1630            None
1631        }
1632    }
1633
1634    /// Returns the geometric mean radius of the ellipse formed by constructing a circle of size
1635    /// `radius`, and mapping the constructed circle with the matrix. The result squared is equal to
1636    /// the major axis length times the minor axis length.
1637    ///
1638    /// The result is not meaningful if the matrix contains perspective elements.
1639    ///
1640    /// - `radius` circle size to map
1641    ///
1642    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_mapRadius>
1643    pub fn map_radius(&self, radius: scalar) -> Option<scalar> {
1644        if !self.has_perspective() {
1645            Some(unsafe { self.native().mapRadius(radius) })
1646        } else {
1647            None
1648        }
1649    }
1650
1651    #[deprecated(since = "0.27.0", note = "removed without replacement")]
1652    pub fn is_fixed_step_in_x(&self) -> ! {
1653        unimplemented!("removed without replacement")
1654    }
1655
1656    #[deprecated(since = "0.27.0", note = "removed without replacement")]
1657    pub fn fixed_step_in_x(&self, _y: scalar) -> ! {
1658        unimplemented!("removed without replacement")
1659    }
1660
1661    #[deprecated(since = "0.27.0", note = "removed without replacement")]
1662    pub fn cheap_equal_to(&self, _other: &Matrix) -> ! {
1663        unimplemented!("removed without replacement")
1664    }
1665
1666    /// Writes a text representation of the matrix to standard output. Floating point values are
1667    /// written with limited precision; it may not be possible to reconstruct the original matrix
1668    /// from the output.
1669    ///
1670    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_dump>
1671    pub fn dump(&self) {
1672        unsafe { self.native().dump() }
1673    }
1674
1675    /// Returns the minimum scaling factor of the matrix by decomposing the scaling and skewing
1676    /// elements.
1677    ///
1678    /// Returns -1 if the scale factor overflows or the matrix contains perspective.
1679    ///
1680    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_getMinScale>
1681    pub fn min_scale(&self) -> scalar {
1682        unsafe { self.native().getMinScale() }
1683    }
1684
1685    /// Returns the maximum scaling factor of the matrix by decomposing the scaling and skewing
1686    /// elements.
1687    ///
1688    /// Returns -1 if the scale factor overflows or the matrix contains perspective.
1689    ///
1690    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_getMaxScale>
1691    pub fn max_scale(&self) -> scalar {
1692        unsafe { self.native().getMaxScale() }
1693    }
1694
1695    /// Sets the first element of the result to the minimum scaling factor, and the second to the
1696    /// maximum scaling factor. Scaling factors are computed by decomposing the matrix scaling and
1697    /// skewing elements.
1698    ///
1699    /// Returns a tuple of the minimum and maximum scale factors if they are found; otherwise,
1700    /// returns undefined values.
1701    #[must_use]
1702    pub fn min_max_scales(&self) -> (scalar, scalar) {
1703        let mut r: [scalar; 2] = Default::default();
1704        unsafe { self.native().getMinMaxScales(r.as_mut_ptr()) };
1705        #[allow(clippy::tuple_array_conversions)]
1706        (r[0], r[1])
1707    }
1708
1709    /// Decomposes the matrix into scale components and whatever remains. Returns `None` if the
1710    /// matrix could not be decomposed.
1711    ///
1712    /// Sets `scale` to the portion of the matrix that scales axes. Sets `remaining` to the matrix
1713    /// with scaling factored out. `remaining` may be passed as `None` to determine if the matrix
1714    /// can be decomposed without computing the remainder.
1715    ///
1716    /// Returns the scale components if they are found. The scale and `remaining` are unchanged if
1717    /// the matrix contains perspective, the scale factors are not finite, or are nearly zero.
1718    ///
1719    /// On success: `Matrix = remaining * scale`.
1720    ///
1721    /// - `remaining` matrix without scaling; may be `None`
1722    ///
1723    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_decomposeScale>
1724    pub fn decompose_scale(&self, mut remaining: Option<&mut Matrix>) -> Option<Size> {
1725        let mut size = Size::default();
1726        unsafe {
1727            self.native()
1728                .decomposeScale(size.native_mut(), remaining.native_ptr_or_null_mut())
1729        }
1730        .then_some(size)
1731    }
1732
1733    /// Returns a reference to the const identity matrix. The returned matrix is set to:
1734    ///
1735    /// ```text
1736    /// | 1 0 0 |
1737    /// | 0 1 0 |
1738    /// | 0 0 1 |
1739    /// ```
1740    ///
1741    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_I>
1742    pub fn i() -> &'static Matrix {
1743        &IDENTITY
1744    }
1745
1746    /// Returns a reference to a const matrix with invalid values. The returned matrix is set to:
1747    ///
1748    /// ```text
1749    /// | SK_ScalarMax SK_ScalarMax SK_ScalarMax |
1750    /// | SK_ScalarMax SK_ScalarMax SK_ScalarMax |
1751    /// | SK_ScalarMax SK_ScalarMax SK_ScalarMax |
1752    /// ```
1753    ///
1754    /// Example (C++): <https://fiddle.skia.org/c/@Matrix_InvalidMatrix>
1755    pub fn invalid_matrix() -> &'static Matrix {
1756        Self::from_native_ref(unsafe { &*sb::C_SkMatrix_InvalidMatrix() })
1757    }
1758
1759    /// Returns matrix `a` multiplied by matrix `b`.
1760    ///
1761    /// Given:
1762    ///
1763    /// ```text
1764    ///         | A B C |      | J K L |
1765    ///     a = | D E F |, b = | M N O |
1766    ///         | G H I |      | P Q R |
1767    /// ```
1768    ///
1769    /// the result is:
1770    ///
1771    /// ```text
1772    ///             | A B C |   | J K L |   | AJ+BM+CP AK+BN+CQ AL+BO+CR |
1773    ///     a * b = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR |
1774    ///             | G H I |   | P Q R |   | GJ+HM+IP GK+HN+IQ GL+HO+IR |
1775    /// ```
1776    ///
1777    /// - `a` matrix on the left side of the multiply expression
1778    /// - `b` matrix on the right side of the multiply expression
1779    pub fn concat(a: &Matrix, b: &Matrix) -> Matrix {
1780        let mut m = Matrix::new_identity();
1781        unsafe { m.native_mut().setConcat(a.native(), b.native()) };
1782        m
1783    }
1784
1785    /// Sets the internal cache to the unknown state. Use to force an update after repeated
1786    /// modifications to matrix element references returned by indexing.
1787    pub fn dirty_matrix_type_cache(&mut self) {
1788        self.native_mut().fTypeMask = 0x80;
1789    }
1790
1791    /// Initializes the matrix with scale and translate elements.
1792    ///
1793    /// ```text
1794    /// | sx  0 tx |
1795    /// |  0 sy ty |
1796    /// |  0  0  1 |
1797    /// ```
1798    ///
1799    /// - `s` horizontal and vertical scale factors to store
1800    /// - `t` horizontal and vertical translation to store
1801    pub fn set_scale_translate(&mut self, s: (scalar, scalar), t: impl Into<Vector>) -> &mut Self {
1802        *self = Self::scale_translate(s, t);
1803        self
1804    }
1805
1806    /// Returns true if all elements of the matrix are finite. Returns false if any element is
1807    /// infinity, or NaN.
1808    pub fn is_finite(&self) -> bool {
1809        unsafe { sb::C_SkMatrix_isFinite(self.native()) }
1810    }
1811
1812    pub const fn new_identity() -> Self {
1813        Self::new()
1814    }
1815}
1816
1817impl IndexGet for Matrix {}
1818impl IndexSet for Matrix {}
1819
1820pub const IDENTITY: Matrix = Matrix::new_identity();
1821
1822#[cfg(test)]
1823mod tests {
1824    use super::{AffineMember, Matrix, TypeMask};
1825    use crate::prelude::*;
1826
1827    #[test]
1828    fn test_get_set_trait_compilation() {
1829        let mut m = Matrix::new_identity();
1830        let _x = m.get(AffineMember::ScaleX);
1831        m.set(AffineMember::ScaleX, 1.0);
1832    }
1833
1834    #[test]
1835    #[allow(clippy::float_cmp)]
1836    fn test_tuple_to_vector() {
1837        let mut m = Matrix::new_identity();
1838        m.set_translate((10.0, 11.0));
1839        assert_eq!(10.0, m.translate_x());
1840        assert_eq!(11.0, m.translate_y());
1841    }
1842
1843    #[test]
1844    fn setting_a_matrix_component_recomputes_typemask() {
1845        let mut m = Matrix::default();
1846        assert_eq!(TypeMask::IDENTITY, m.get_type());
1847        m.set_persp_x(0.1);
1848        assert_eq!(
1849            TypeMask::TRANSLATE | TypeMask::SCALE | TypeMask::AFFINE | TypeMask::PERSPECTIVE,
1850            m.get_type()
1851        );
1852    }
1853}