/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values that are related to transformations. use crate::derives::*; use crate::typed_om::{ KeywordValue, MatrixComponent, NumericValue, PerspectiveComponent, PerspectiveValue, RotateComponent, ScaleComponent, SkewComponent, ToTyped, TransformComponent, TranslateComponent, TypedValue, }; use crate::values::computed::length::Length as ComputedLength; use crate::values::computed::length::LengthPercentage as ComputedLengthPercentage; use crate::values::computed::transform::Matrix3D as ComputedMatrix3D; use crate::values::specified::angle::Angle as SpecifiedAngle; use crate::values::specified::length::Length as SpecifiedLength; use crate::values::specified::length::LengthPercentage as SpecifiedLengthPercentage; use crate::values::specified::number::Number as SpecifiedNumber; use crate::values::{CSSFloat, computed}; use crate::{One, Zero, ZeroNoPercent}; use euclid::default::{Rect, Transform3D}; use std::fmt::{self, Write}; use std::ops::Neg; use style_traits::{CssString, CssWriter, ToCss}; use thin_vec::ThinVec; /// A generic 2D transformation matrix. #[allow(missing_docs)] #[derive( Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[css(comma, function = "matrix")] #[repr(C)] pub struct GenericMatrix { pub a: T, pub b: T, pub c: T, pub d: T, pub e: T, pub f: T, } pub use self::GenericMatrix as Matrix; #[allow(missing_docs)] #[rustfmt::skip] #[derive( Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[css(comma, function = "matrix3d")] #[repr(C)] pub struct GenericMatrix3D { pub m11: T, pub m12: T, pub m13: T, pub m14: T, pub m21: T, pub m22: T, pub m23: T, pub m24: T, pub m31: T, pub m32: T, pub m33: T, pub m34: T, pub m41: T, pub m42: T, pub m43: T, pub m44: T, } pub use self::GenericMatrix3D as Matrix3D; #[rustfmt::skip] impl TryFrom> for Transform3D { type Error = (); #[inline] fn try_from(m: Matrix) -> Result { Ok(Transform3D::new( m.a.to_f64()?, m.b.to_f64()?, 0.0, 0.0, m.c.to_f64()?, m.d.to_f64()?, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, m.e.to_f64()?, m.f.to_f64()?, 0.0, 1.0, )) } } #[rustfmt::skip] impl TryFrom> for Transform3D { type Error = (); #[inline] fn try_from(m: Matrix3D) -> Result { Ok(Transform3D::new( m.m11.to_f64()?, m.m12.to_f64()?, m.m13.to_f64()?, m.m14.to_f64()?, m.m21.to_f64()?, m.m22.to_f64()?, m.m23.to_f64()?, m.m24.to_f64()?, m.m31.to_f64()?, m.m32.to_f64()?, m.m33.to_f64()?, m.m34.to_f64()?, m.m41.to_f64()?, m.m42.to_f64()?, m.m43.to_f64()?, m.m44.to_f64()?, )) } } /// A generic transform origin. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, ToTyped, )] #[repr(C)] #[typed(todo_derive_fields)] pub struct GenericTransformOrigin { /// The horizontal origin. pub horizontal: H, /// The vertical origin. pub vertical: V, /// The depth. pub depth: Depth, } pub use self::GenericTransformOrigin as TransformOrigin; impl TransformOrigin { /// Returns a new transform origin. pub fn new(horizontal: H, vertical: V, depth: D) -> Self { Self { horizontal, vertical, depth, } } } fn is_same(x: &N, y: &N) -> bool { x == y } /// A value for the `perspective()` transform function, which is either a /// non-negative `` or `none`. #[derive( Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, ToTyped, )] #[repr(C, u8)] pub enum GenericPerspectiveFunction { /// `none` None, /// A ``. Length(L), } impl GenericPerspectiveFunction { /// Returns `f32::INFINITY` or the result of a function on the length value. pub fn infinity_or(&self, f: impl FnOnce(&L) -> f32) -> f32 { match *self { Self::None => f32::INFINITY, Self::Length(ref l) => f(l), } } } pub use self::GenericPerspectiveFunction as PerspectiveFunction; #[derive( Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] /// A single operation in the list of a `transform` value pub enum GenericTransformOperation where Angle: Zero, LengthPercentage: Zero + ZeroNoPercent, Number: PartialEq, { /// Represents a 2D 2x3 matrix. Matrix(GenericMatrix), /// Represents a 3D 4x4 matrix. Matrix3D(GenericMatrix3D), /// A 2D skew. /// /// If the second angle is not provided it is assumed zero. /// /// Syntax can be skew(angle) or skew(angle, angle) #[css(comma, function)] Skew(Angle, #[css(skip_if = "Zero::is_zero")] Angle), /// skewX(angle) #[css(function = "skewX")] SkewX(Angle), /// skewY(angle) #[css(function = "skewY")] SkewY(Angle), /// translate(x, y) or translate(x) #[css(comma, function)] Translate( LengthPercentage, #[css(skip_if = "ZeroNoPercent::is_zero_no_percent")] LengthPercentage, ), /// translateX(x) #[css(function = "translateX")] TranslateX(LengthPercentage), /// translateY(y) #[css(function = "translateY")] TranslateY(LengthPercentage), /// translateZ(z) #[css(function = "translateZ")] TranslateZ(Length), /// translate3d(x, y, z) #[css(comma, function = "translate3d")] Translate3D(LengthPercentage, LengthPercentage, Length), /// A 2D scaling factor. /// /// Syntax can be scale(factor) or scale(factor, factor) #[css(comma, function)] Scale(Number, #[css(contextual_skip_if = "is_same")] Number), /// scaleX(factor) #[css(function = "scaleX")] ScaleX(Number), /// scaleY(factor) #[css(function = "scaleY")] ScaleY(Number), /// scaleZ(factor) #[css(function = "scaleZ")] ScaleZ(Number), /// scale3D(factorX, factorY, factorZ) #[css(comma, function = "scale3d")] Scale3D(Number, Number, Number), /// Describes a 2D Rotation. /// /// In a 3D scene `rotate(angle)` is equivalent to `rotateZ(angle)`. #[css(function)] Rotate(Angle), /// Rotation in 3D space around the x-axis. #[css(function = "rotateX")] RotateX(Angle), /// Rotation in 3D space around the y-axis. #[css(function = "rotateY")] RotateY(Angle), /// Rotation in 3D space around the z-axis. #[css(function = "rotateZ")] RotateZ(Angle), /// Rotation in 3D space. /// /// Generalization of rotateX, rotateY and rotateZ. #[css(comma, function = "rotate3d")] Rotate3D(Number, Number, Number, Angle), /// Specifies a perspective projection matrix. /// /// Part of CSS Transform Module Level 2 and defined at /// [ยง 13.1. 3D Transform Function](https://drafts.csswg.org/css-transforms-2/#funcdef-perspective). /// /// The value must be greater than or equal to zero. #[css(function)] Perspective(GenericPerspectiveFunction), /// A intermediate type for interpolation of mismatched transform lists. #[allow(missing_docs)] #[css(comma, function = "interpolatematrix")] InterpolateMatrix { from_list: GenericTransform< GenericTransformOperation, >, to_list: GenericTransform< GenericTransformOperation, >, progress: computed::Percentage, }, /// A intermediate type for accumulation of mismatched transform lists. #[allow(missing_docs)] #[css(comma, function = "accumulatematrix")] AccumulateMatrix { from_list: GenericTransform< GenericTransformOperation, >, to_list: GenericTransform< GenericTransformOperation, >, count: Integer, }, } pub use self::GenericTransformOperation as TransformOperation; /// Converts a transform operation into a transform component. pub trait ToTransformComponent { /// Attempt to convert `self` into a transform component. /// /// Implementations append the resulting component to `dest`. Returning /// `Err(())` indicates that the transform operation cannot currently be /// represented as a transform component. fn to_transform_component(&self, _dest: &mut ThinVec) -> Result<(), ()>; } impl ToTransformComponent for TransformOperation where Angle: Zero + ToTyped, Number: PartialEq + ToFloat + ToTyped, Length: ToTyped, LengthPercentage: Zero + ToTyped + ZeroNoPercent, { fn to_transform_component(&self, dest: &mut ThinVec) -> Result<(), ()> { use self::TransformOperation::*; // https://drafts.css-houdini.org/css-typed-om-1/#reify-a-transform-function let component = match *self { Matrix(ref m) => TransformComponent::Matrix(MatrixComponent { #[rustfmt::skip] matrix: ComputedMatrix3D { m11: m.a.to_f32()?, m12: m.b.to_f32()?, m13: 0.0, m14: 0.0, m21: m.c.to_f32()?, m22: m.d.to_f32()?, m23: 0.0, m24: 0.0, m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, m41: m.e.to_f32()?, m42: m.f.to_f32()?, m43: 0.0, m44: 1.0, }, is_2d: true, }), Matrix3D(ref m) => TransformComponent::Matrix(MatrixComponent { #[rustfmt::skip] matrix: ComputedMatrix3D { m11: m.m11.to_f32()?, m12: m.m12.to_f32()?, m13: m.m13.to_f32()?, m14: m.m14.to_f32()?, m21: m.m21.to_f32()?, m22: m.m22.to_f32()?, m23: m.m23.to_f32()?, m24: m.m24.to_f32()?, m31: m.m31.to_f32()?, m32: m.m32.to_f32()?, m33: m.m33.to_f32()?, m34: m.m34.to_f32()?, m41: m.m41.to_f32()?, m42: m.m42.to_f32()?, m43: m.m43.to_f32()?, m44: m.m44.to_f32()?, }, is_2d: false, }), Skew(ref theta_x, ref theta_y) => TransformComponent::Skew(SkewComponent { ax: theta_x.to_numeric_value().ok_or(())?, ay: theta_y.to_numeric_value().ok_or(())?, }), SkewX(ref theta) => TransformComponent::SkewX(theta.to_numeric_value().ok_or(())?), SkewY(ref theta) => TransformComponent::SkewY(theta.to_numeric_value().ok_or(())?), Translate(ref tx, ref ty) => TransformComponent::Translate(TranslateComponent { x: tx.to_numeric_value().ok_or(())?, y: ty.to_numeric_value().ok_or(())?, z: NumericValue::zero_px(), is_2d: true, }), TranslateX(ref t) => TransformComponent::Translate(TranslateComponent { x: t.to_numeric_value().ok_or(())?, y: NumericValue::zero_px(), z: NumericValue::zero_px(), is_2d: true, }), TranslateY(ref t) => TransformComponent::Translate(TranslateComponent { x: NumericValue::zero_px(), y: t.to_numeric_value().ok_or(())?, z: NumericValue::zero_px(), is_2d: true, }), TranslateZ(ref t) => TransformComponent::Translate(TranslateComponent { x: NumericValue::zero_px(), y: NumericValue::zero_px(), z: t.to_numeric_value().ok_or(())?, is_2d: false, }), Translate3D(ref tx, ref ty, ref tz) => { TransformComponent::Translate(TranslateComponent { x: tx.to_numeric_value().ok_or(())?, y: ty.to_numeric_value().ok_or(())?, z: tz.to_numeric_value().ok_or(())?, is_2d: false, }) }, Scale(ref sx, ref sy) => TransformComponent::Scale(ScaleComponent { x: sx.to_numeric_value().ok_or(())?, y: sy.to_numeric_value().ok_or(())?, z: NumericValue::one(), is_2d: true, }), ScaleX(ref s) => TransformComponent::Scale(ScaleComponent { x: s.to_numeric_value().ok_or(())?, y: NumericValue::one(), z: NumericValue::one(), is_2d: true, }), ScaleY(ref s) => TransformComponent::Scale(ScaleComponent { x: NumericValue::one(), y: s.to_numeric_value().ok_or(())?, z: NumericValue::one(), is_2d: true, }), ScaleZ(ref s) => TransformComponent::Scale(ScaleComponent { x: NumericValue::one(), y: NumericValue::one(), z: s.to_numeric_value().ok_or(())?, is_2d: false, }), Scale3D(ref sx, ref sy, ref sz) => TransformComponent::Scale(ScaleComponent { x: sx.to_numeric_value().ok_or(())?, y: sy.to_numeric_value().ok_or(())?, z: sz.to_numeric_value().ok_or(())?, is_2d: false, }), Rotate(ref theta) => TransformComponent::Rotate(RotateComponent { angle: theta.to_numeric_value().ok_or(())?, x: NumericValue::zero(), y: NumericValue::zero(), z: NumericValue::one(), is_2d: true, }), RotateX(ref theta) => TransformComponent::Rotate(RotateComponent { angle: theta.to_numeric_value().ok_or(())?, x: NumericValue::one(), y: NumericValue::zero(), z: NumericValue::zero(), is_2d: false, }), RotateY(ref theta) => TransformComponent::Rotate(RotateComponent { angle: theta.to_numeric_value().ok_or(())?, x: NumericValue::zero(), y: NumericValue::one(), z: NumericValue::zero(), is_2d: false, }), RotateZ(ref theta) => TransformComponent::Rotate(RotateComponent { angle: theta.to_numeric_value().ok_or(())?, x: NumericValue::zero(), y: NumericValue::zero(), z: NumericValue::one(), is_2d: false, }), Rotate3D(ref ax, ref ay, ref az, ref theta) => { TransformComponent::Rotate(RotateComponent { angle: theta.to_numeric_value().ok_or(())?, x: ax.to_numeric_value().ok_or(())?, y: ay.to_numeric_value().ok_or(())?, z: az.to_numeric_value().ok_or(())?, is_2d: false, }) }, Perspective(ref p) => { let length = match p.to_typed_value().ok_or(())? { TypedValue::Numeric(value) => PerspectiveValue::Numeric(value), TypedValue::Keyword(value) => PerspectiveValue::Keyword(value), _ => return Err(()), }; TransformComponent::Perspective(PerspectiveComponent { length }) }, _ => return Err(()), }; dest.push(component); Ok(()) } } #[derive( Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C)] /// A value of the `transform` property pub struct GenericTransform(#[css(if_empty = "none", iterable)] pub crate::OwnedSlice); pub use self::GenericTransform as Transform; impl ToTyped for Transform { fn to_typed(&self, dest: &mut ThinVec) -> Result<(), ()> { if self.0.is_empty() { dest.push(TypedValue::Keyword(KeywordValue(CssString::from("none")))); return Ok(()); } // https://drafts.css-houdini.org/css-typed-om-1/#reify-a-transform-list let mut values = ThinVec::new(); let ops: &[T] = &self.0; for item in ops { item.to_transform_component(&mut values)?; } dest.push(TypedValue::Transform(values)); Ok(()) } } impl TransformOperation where Angle: Zero, LengthPercentage: Zero + ZeroNoPercent, Number: PartialEq, { /// Check if it is any rotate function. pub fn is_rotate(&self) -> bool { use self::TransformOperation::*; matches!( *self, Rotate(..) | Rotate3D(..) | RotateX(..) | RotateY(..) | RotateZ(..) ) } /// Check if it is any translate function pub fn is_translate(&self) -> bool { use self::TransformOperation::*; match *self { Translate(..) | Translate3D(..) | TranslateX(..) | TranslateY(..) | TranslateZ(..) => { true }, _ => false, } } /// Check if it is any scale function pub fn is_scale(&self) -> bool { use self::TransformOperation::*; match *self { Scale(..) | Scale3D(..) | ScaleX(..) | ScaleY(..) | ScaleZ(..) => true, _ => false, } } } /// Convert a length type into the absolute lengths. pub trait ToAbsoluteLength { /// Returns the absolute length as pixel value. fn to_pixel_length(&self, containing_len: Option) -> Result; } impl ToAbsoluteLength for SpecifiedLength { // This returns Err(()) if there is any relative length or percentage. We use this when // parsing a transform list of DOMMatrix because we want to return a DOM Exception // if there is relative length. #[inline] fn to_pixel_length(&self, _containing_len: Option) -> Result { self.to_computed_pixel_length_without_context() } } impl ToAbsoluteLength for SpecifiedLengthPercentage { // This returns Err(()) if there is any relative length or percentage. We use this when // parsing a transform list of DOMMatrix because we want to return a DOM Exception // if there is relative length. #[inline] fn to_pixel_length(&self, _containing_len: Option) -> Result { use self::SpecifiedLengthPercentage::*; match *self { Length(len) => len.to_computed_pixel_length_without_context(), Calc(ref calc) => calc.to_computed_pixel_length_without_context(), Percentage(..) => Err(()), } } } impl ToAbsoluteLength for ComputedLength { #[inline] fn to_pixel_length(&self, _containing_len: Option) -> Result { Ok(self.px()) } } impl ToAbsoluteLength for ComputedLengthPercentage { #[inline] fn to_pixel_length(&self, containing_len: Option) -> Result { Ok(self .maybe_percentage_relative_to(containing_len) .ok_or(())? .px()) } } /// Support the conversion to a 3d matrix. pub trait ToMatrix { /// Check if it is a 3d transform function. fn is_3d(&self) -> bool; /// Return the equivalent 3d matrix. fn to_3d_matrix( &self, reference_box: Option<&Rect>, ) -> Result, ()>; } /// A little helper to deal with both specified and computed angles. pub trait ToRadians { /// Return the radians value as a 64-bit floating point value. fn radians64(&self) -> Result; } impl ToRadians for computed::angle::Angle { #[inline] fn radians64(&self) -> Result { Ok(computed::angle::Angle::radians64(self)) } } impl ToRadians for SpecifiedAngle { #[inline] fn radians64(&self) -> Result { let degrees = self.degrees().ok_or(())?; Ok(computed::angle::Angle::from_degrees(degrees).radians64()) } } /// Convert a number type into a float. pub trait ToFloat { /// Return the number as an f32, or Err(()) if the conversion is not possible. fn to_f32(&self) -> Result; /// Return the number as an f64, or Err(()) if the conversion is not possible. fn to_f64(&self) -> Result; } impl ToFloat for SpecifiedNumber { #[inline] fn to_f32(&self) -> Result { self.resolve().ok_or(()) } #[inline] fn to_f64(&self) -> Result { self.resolve().map(|v| v as f64).ok_or(()) } } impl ToFloat for computed::Number { #[inline] fn to_f32(&self) -> Result { Ok(*self) } #[inline] fn to_f64(&self) -> Result { Ok(*self as f64) } } impl ToMatrix for TransformOperation where Angle: Zero + ToRadians + Clone, Number: PartialEq + Clone + ToFloat + ToFloat, Length: ToAbsoluteLength, LoP: Zero + ToAbsoluteLength + ZeroNoPercent, { #[inline] fn is_3d(&self) -> bool { use self::TransformOperation::*; match *self { Translate3D(..) | TranslateZ(..) | Rotate3D(..) | RotateX(..) | RotateY(..) | RotateZ(..) | Scale3D(..) | ScaleZ(..) | Perspective(..) | Matrix3D(..) => true, _ => false, } } /// If |reference_box| is None, we will drop the percent part from translate because /// we cannot resolve it without the layout info, for computed TransformOperation. /// However, for specified TransformOperation, we will return Err(()) if there is any relative /// lengths because the only caller, DOMMatrix, doesn't accept relative lengths. #[inline] fn to_3d_matrix( &self, reference_box: Option<&Rect>, ) -> Result, ()> { use self::TransformOperation::*; let reference_width = reference_box.map(|v| v.size.width); let reference_height = reference_box.map(|v| v.size.height); let matrix = match *self { Rotate3D(ref ax, ref ay, ref az, ref theta) => { let theta = theta.radians64()?; let (ax, ay, az, theta) = get_normalized_vector_and_angle( ax.to_f32()?, ay.to_f32()?, az.to_f32()?, theta, ); Transform3D::rotation( ax as f64, ay as f64, az as f64, euclid::Angle::radians(theta), ) }, RotateX(ref theta) => { let theta = euclid::Angle::radians(theta.radians64()?); Transform3D::rotation(1., 0., 0., theta) }, RotateY(ref theta) => { let theta = euclid::Angle::radians(theta.radians64()?); Transform3D::rotation(0., 1., 0., theta) }, RotateZ(ref theta) | Rotate(ref theta) => { let theta = euclid::Angle::radians(theta.radians64()?); Transform3D::rotation(0., 0., 1., theta) }, Perspective(ref p) => { let px = match p { PerspectiveFunction::None => f32::INFINITY, PerspectiveFunction::Length(p) => p.to_pixel_length(None)?, }; create_perspective_matrix(px).cast() }, Scale3D(ref sx, ref sy, ref sz) => { Transform3D::scale(sx.to_f64()?, sy.to_f64()?, sz.to_f64()?) }, Scale(ref sx, ref sy) => Transform3D::scale(sx.to_f64()?, sy.to_f64()?, 1.), ScaleX(ref s) => Transform3D::scale(s.to_f64()?, 1., 1.), ScaleY(ref s) => Transform3D::scale(1., s.to_f64()?, 1.), ScaleZ(ref s) => Transform3D::scale(1., 1., s.to_f64()?), Translate3D(ref tx, ref ty, ref tz) => { let tx = tx.to_pixel_length(reference_width)? as f64; let ty = ty.to_pixel_length(reference_height)? as f64; Transform3D::translation(tx, ty, tz.to_pixel_length(None)? as f64) }, Translate(ref tx, ref ty) => { let tx = tx.to_pixel_length(reference_width)? as f64; let ty = ty.to_pixel_length(reference_height)? as f64; Transform3D::translation(tx, ty, 0.) }, TranslateX(ref t) => { let t = t.to_pixel_length(reference_width)? as f64; Transform3D::translation(t, 0., 0.) }, TranslateY(ref t) => { let t = t.to_pixel_length(reference_height)? as f64; Transform3D::translation(0., t, 0.) }, TranslateZ(ref z) => Transform3D::translation(0., 0., z.to_pixel_length(None)? as f64), Skew(ref theta_x, ref theta_y) => Transform3D::skew( euclid::Angle::radians(theta_x.radians64()?), euclid::Angle::radians(theta_y.radians64()?), ), SkewX(ref theta) => Transform3D::skew( euclid::Angle::radians(theta.radians64()?), euclid::Angle::radians(0.), ), SkewY(ref theta) => Transform3D::skew( euclid::Angle::radians(0.), euclid::Angle::radians(theta.radians64()?), ), Matrix3D(ref m) => m.clone().try_into()?, Matrix(ref m) => m.clone().try_into()?, InterpolateMatrix { .. } | AccumulateMatrix { .. } => { // TODO: Convert InterpolateMatrix/AccumulateMatrix into a valid Transform3D by // the reference box and do interpolation on these two Transform3D matrices. // Both Gecko and Servo don't support this for computing distance, and Servo // doesn't support animations on InterpolateMatrix/AccumulateMatrix, so // return an identity matrix. // Note: DOMMatrix doesn't go into this arm. Transform3D::identity() }, }; Ok(matrix) } } impl Transform { /// `none` pub fn none() -> Self { Transform(Default::default()) } } impl Transform { /// Return the equivalent 3d matrix of this transform list. /// /// We return a pair: the first one is the transform matrix, and the second one /// indicates if there is any 3d transform function in this transform list. #[rustfmt::skip] pub fn to_transform_3d_matrix( &self, reference_box: Option<&Rect> ) -> Result<(Transform3D, bool), ()> { Self::components_to_transform_3d_matrix(&self.0, reference_box) } /// Converts a series of components to a 3d matrix. #[rustfmt::skip] pub fn components_to_transform_3d_matrix( ops: &[T], reference_box: Option<&Rect>, ) -> Result<(Transform3D, bool), ()> { let cast_3d_transform = |m: Transform3D| -> Transform3D { let cast = |v: f64| v.min(f32::MAX as f64).max(f32::MIN as f64) as f32; Transform3D::new( cast(m.m11), cast(m.m12), cast(m.m13), cast(m.m14), cast(m.m21), cast(m.m22), cast(m.m23), cast(m.m24), cast(m.m31), cast(m.m32), cast(m.m33), cast(m.m34), cast(m.m41), cast(m.m42), cast(m.m43), cast(m.m44), ) }; let (m, is_3d) = Self::components_to_transform_3d_matrix_f64(ops, reference_box)?; Ok((cast_3d_transform(m), is_3d)) } /// Same as Transform::to_transform_3d_matrix but a f64 version. pub fn to_transform_3d_matrix_f64( &self, reference_box: Option<&Rect>, ) -> Result<(Transform3D, bool), ()> { Self::components_to_transform_3d_matrix_f64(&self.0, reference_box) } /// Same as Transform::components_to_transform_3d_matrix but a f64 version. fn components_to_transform_3d_matrix_f64( ops: &[T], reference_box: Option<&Rect>, ) -> Result<(Transform3D, bool), ()> { // We intentionally use Transform3D during computation to avoid // error propagation because using f32 to compute triangle functions // (e.g. in rotation()) is not accurate enough. In Gecko, we also use // "double" to compute the triangle functions. Therefore, let's use // Transform3D during matrix computation and cast it into f32 in // the end. let mut transform = Transform3D::::identity(); let mut contain_3d = false; for operation in ops { let matrix = operation.to_3d_matrix(reference_box)?; contain_3d = contain_3d || operation.is_3d(); transform = matrix.then(&transform); } Ok((transform, contain_3d)) } } /// Return the transform matrix from a perspective length. #[inline] pub fn create_perspective_matrix(d: CSSFloat) -> Transform3D { if d.is_finite() { Transform3D::perspective(d.max(1.)) } else { Transform3D::identity() } } /// Return the normalized direction vector and its angle for Rotate3D. pub fn get_normalized_vector_and_angle( x: CSSFloat, y: CSSFloat, z: CSSFloat, angle: T, ) -> (CSSFloat, CSSFloat, CSSFloat, T) { use crate::values::computed::transform::DirectionVector; use euclid::approxeq::ApproxEq; let vector = DirectionVector::new(x, y, z); if vector.square_length().approx_eq(&f32::zero()) { // https://www.w3.org/TR/css-transforms-1/#funcdef-rotate3d // A direction vector that cannot be normalized, such as [0, 0, 0], will cause the // rotation to not be applied, so we use identity matrix (i.e. rotate3d(0, 0, 1, 0)). (0., 0., 1., T::zero()) } else { let vector = vector.robust_normalize(); (vector.x, vector.y, vector.z, angle) } } #[derive( Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToResolvedValue, ToShmem, ToTyped, )] #[repr(C, u8)] #[typed(todo_derive_fields)] /// A value of the `Rotate` property /// /// pub enum GenericRotate { /// 'none' None, /// '' Rotate(Angle), /// '{3} ' Rotate3D(Number, Number, Number, Angle), } pub use self::GenericRotate as Rotate; /// A trait to check if the current 3D vector is parallel to the DirectionVector. /// This is especially for serialization on Rotate. pub trait IsParallelTo { /// Returns true if this is parallel to the vector. fn is_parallel_to(&self, vector: &computed::transform::DirectionVector) -> bool; } impl ToCss for Rotate where Number: Clone + PartialOrd + ToCss + Zero, Angle: Clone + Neg + ToCss + Zero, (Number, Number, Number): IsParallelTo, { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where W: fmt::Write, { use crate::values::computed::transform::DirectionVector; match *self { Rotate::None => dest.write_str("none"), Rotate::Rotate(ref angle) => angle.to_css(dest), Rotate::Rotate3D(ref x, ref y, ref z, ref angle) => { // If the axis is parallel with the x or y axes, it must serialize as the // appropriate keyword. If a rotation about the z axis (that is, in 2D) is // specified, the property must serialize as just an . // // Note that if the axis is parallel to x/y/z but pointing in the opposite // direction, we need to negate the angle to maintain the correct meaning. // // https://drafts.csswg.org/css-transforms-2/#individual-transform-serialization let v = (x.clone(), y.clone(), z.clone()); let (axis, angle) = if v.0.is_zero() && v.1.is_zero() && v.2.is_zero() { // The zero length vector is parallel to every other vector, so // is_parallel_to() returns true for it. However, it is definitely different // from x axis, y axis, or z axis, and it's meaningless to perform a rotation // using that direction vector. So we *have* to serialize it using that same // vector - we can't simplify to some theoretically parallel axis-aligned // vector. (None, angle.clone()) } else if v.is_parallel_to(&DirectionVector::new(1., 0., 0.)) { ( Some("x "), if v.0 < Number::zero() { -angle.clone() } else { angle.clone() }, ) } else if v.is_parallel_to(&DirectionVector::new(0., 1., 0.)) { ( Some("y "), if v.1 < Number::zero() { -angle.clone() } else { angle.clone() }, ) } else if v.is_parallel_to(&DirectionVector::new(0., 0., 1.)) { // When we're parallel to the z-axis, we can just serialize the angle. let angle = if v.2 < Number::zero() { -angle.clone() } else { angle.clone() }; return angle.to_css(dest); } else { (None, angle.clone()) }; match axis { Some(a) => dest.write_str(a)?, None => { x.to_css(dest)?; dest.write_char(' ')?; y.to_css(dest)?; dest.write_char(' ')?; z.to_css(dest)?; dest.write_char(' ')?; }, } angle.to_css(dest) }, } } } #[derive( Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToResolvedValue, ToShmem, ToTyped, )] #[repr(C, u8)] /// A value of the `Scale` property /// /// pub enum GenericScale { /// 'none' None, /// '{1,3}' Scale(Number, Number, Number), } pub use self::GenericScale as Scale; impl ToCss for Scale where Number: ToCss + PartialEq + Clone + ToFloat, { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where W: fmt::Write, { match *self { Scale::None => dest.write_str("none"), Scale::Scale(ref x, ref y, ref z) => { x.to_css(dest)?; let serialize_z = z.to_f32() != Ok(1.0); if serialize_z || x != y { dest.write_char(' ')?; y.to_css(dest)?; } if serialize_z { dest.write_char(' ')?; z.to_css(dest)?; } Ok(()) }, } } } #[inline] fn y_axis_and_z_axis_are_zero( _: &LengthPercentage, y: &LengthPercentage, z: &Length, ) -> bool { y.is_zero_no_percent() && z.is_zero() } #[derive( Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, ToTyped, )] #[repr(C, u8)] /// A value of the `translate` property /// /// https://drafts.csswg.org/css-transforms-2/#individual-transform-serialization: /// /// If a 2d translation is specified, the property must serialize with only one /// or two values (per usual, if the second value is 0px, the default, it must /// be omitted when serializing; however if 0% is the second value, it is included). /// /// If a 3d translation is specified and the value can be expressed as 2d, we treat as 2d and /// serialize accoringly. Otherwise, we serialize all three values. /// https://github.com/w3c/csswg-drafts/issues/3305 /// /// pub enum GenericTranslate where LengthPercentage: Zero + ZeroNoPercent, Length: Zero, { /// 'none' None, /// [ ? ]? Translate( LengthPercentage, #[css(contextual_skip_if = "y_axis_and_z_axis_are_zero")] LengthPercentage, #[css(skip_if = "Zero::is_zero")] Length, ), } pub use self::GenericTranslate as Translate; #[allow(missing_docs)] #[derive( Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, ToResolvedValue, ToShmem, ToTyped, )] #[repr(u8)] pub enum TransformStyle { Flat, #[css(keyword = "preserve-3d")] Preserve3d, }