euclid/
transform3d.rs

1// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10#![allow(clippy::just_underscores_and_digits)]
11
12use super::{Angle, UnknownUnit};
13use crate::approxeq::ApproxEq;
14use crate::box2d::Box2D;
15use crate::box3d::Box3D;
16use crate::homogen::HomogeneousVector;
17use crate::num::{One, Zero};
18use crate::point::{point2, point3, Point2D, Point3D};
19use crate::rect::Rect;
20use crate::scale::Scale;
21use crate::transform2d::Transform2D;
22use crate::trig::Trig;
23use crate::vector::{vec2, vec3, Vector2D, Vector3D};
24use crate::ScaleOffset2D;
25
26use core::cmp::{Eq, PartialEq};
27use core::fmt;
28use core::hash::Hash;
29use core::marker::PhantomData;
30use core::ops::{Add, Div, Mul, Neg, Sub};
31
32#[cfg(feature = "bytemuck")]
33use bytemuck::{Pod, Zeroable};
34#[cfg(feature = "malloc_size_of")]
35use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
36#[cfg(feature = "mint")]
37use mint;
38use num_traits::{NumCast, Signed};
39#[cfg(feature = "serde")]
40use serde::{Deserialize, Serialize};
41
42/// A 3d transform stored as a column-major 4 by 4 matrix.
43///
44/// Transforms can be parametrized over the source and destination units, to describe a
45/// transformation from a space to another.
46/// For example, `Transform3D<f32, WorldSpace, ScreenSpace>::transform_point3d`
47/// takes a `Point3D<f32, WorldSpace>` and returns a `Point3D<f32, ScreenSpace>`.
48///
49/// Transforms expose a set of convenience methods for pre- and post-transformations.
50/// Pre-transformations (`pre_*` methods) correspond to adding an operation that is
51/// applied before the rest of the transformation, while post-transformations (`then_*`
52/// methods) add an operation that is applied after.
53///
54/// When translating `Transform3D` into general matrix representations, consider that the
55/// representation follows the column major notation with column vectors.
56///
57/// ```text
58///  |x'|   | m11 m12 m13 m14 |   |x|
59///  |y'|   | m21 m22 m23 m24 |   |y|
60///  |z'| = | m31 m32 m33 m34 | x |y|
61///  |w |   | m41 m42 m43 m44 |   |1|
62/// ```
63///
64/// The translation terms are `m41`, `m42` and `m43`.
65#[repr(C)]
66#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
67#[cfg_attr(
68    feature = "serde",
69    serde(bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>"))
70)]
71#[rustfmt::skip]
72pub struct Transform3D<T, Src, Dst> {
73    pub m11: T, pub m12: T, pub m13: T, pub m14: T,
74    pub m21: T, pub m22: T, pub m23: T, pub m24: T,
75    pub m31: T, pub m32: T, pub m33: T, pub m34: T,
76    pub m41: T, pub m42: T, pub m43: T, pub m44: T,
77    #[doc(hidden)]
78    pub _unit: PhantomData<(Src, Dst)>,
79}
80
81#[cfg(feature = "arbitrary")]
82impl<'a, T, Src, Dst> arbitrary::Arbitrary<'a> for Transform3D<T, Src, Dst>
83where
84    T: arbitrary::Arbitrary<'a>,
85{
86    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
87        let (m11, m12, m13, m14) = arbitrary::Arbitrary::arbitrary(u)?;
88        let (m21, m22, m23, m24) = arbitrary::Arbitrary::arbitrary(u)?;
89        let (m31, m32, m33, m34) = arbitrary::Arbitrary::arbitrary(u)?;
90        let (m41, m42, m43, m44) = arbitrary::Arbitrary::arbitrary(u)?;
91
92        Ok(Transform3D {
93            m11,
94            m12,
95            m13,
96            m14,
97            m21,
98            m22,
99            m23,
100            m24,
101            m31,
102            m32,
103            m33,
104            m34,
105            m41,
106            m42,
107            m43,
108            m44,
109            _unit: PhantomData,
110        })
111    }
112}
113
114#[cfg(feature = "bytemuck")]
115unsafe impl<T: Zeroable, Src, Dst> Zeroable for Transform3D<T, Src, Dst> {}
116
117#[cfg(feature = "bytemuck")]
118unsafe impl<T: Pod, Src: 'static, Dst: 'static> Pod for Transform3D<T, Src, Dst> {}
119
120#[cfg(feature = "malloc_size_of")]
121impl<T: MallocSizeOf, Src, Dst> MallocSizeOf for Transform3D<T, Src, Dst> {
122    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
123        self.m11.size_of(ops)
124            + self.m12.size_of(ops)
125            + self.m13.size_of(ops)
126            + self.m14.size_of(ops)
127            + self.m21.size_of(ops)
128            + self.m22.size_of(ops)
129            + self.m23.size_of(ops)
130            + self.m24.size_of(ops)
131            + self.m31.size_of(ops)
132            + self.m32.size_of(ops)
133            + self.m33.size_of(ops)
134            + self.m34.size_of(ops)
135            + self.m41.size_of(ops)
136            + self.m42.size_of(ops)
137            + self.m43.size_of(ops)
138            + self.m44.size_of(ops)
139    }
140}
141
142impl<T: Copy, Src, Dst> Copy for Transform3D<T, Src, Dst> {}
143
144impl<T: Clone, Src, Dst> Clone for Transform3D<T, Src, Dst> {
145    fn clone(&self) -> Self {
146        Transform3D {
147            m11: self.m11.clone(),
148            m12: self.m12.clone(),
149            m13: self.m13.clone(),
150            m14: self.m14.clone(),
151            m21: self.m21.clone(),
152            m22: self.m22.clone(),
153            m23: self.m23.clone(),
154            m24: self.m24.clone(),
155            m31: self.m31.clone(),
156            m32: self.m32.clone(),
157            m33: self.m33.clone(),
158            m34: self.m34.clone(),
159            m41: self.m41.clone(),
160            m42: self.m42.clone(),
161            m43: self.m43.clone(),
162            m44: self.m44.clone(),
163            _unit: PhantomData,
164        }
165    }
166}
167
168impl<T, Src, Dst> Eq for Transform3D<T, Src, Dst> where T: Eq {}
169
170impl<T, Src, Dst> PartialEq for Transform3D<T, Src, Dst>
171where
172    T: PartialEq,
173{
174    fn eq(&self, other: &Self) -> bool {
175        self.m11 == other.m11
176            && self.m12 == other.m12
177            && self.m13 == other.m13
178            && self.m14 == other.m14
179            && self.m21 == other.m21
180            && self.m22 == other.m22
181            && self.m23 == other.m23
182            && self.m24 == other.m24
183            && self.m31 == other.m31
184            && self.m32 == other.m32
185            && self.m33 == other.m33
186            && self.m34 == other.m34
187            && self.m41 == other.m41
188            && self.m42 == other.m42
189            && self.m43 == other.m43
190            && self.m44 == other.m44
191    }
192}
193
194impl<T, Src, Dst> Hash for Transform3D<T, Src, Dst>
195where
196    T: Hash,
197{
198    fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
199        self.m11.hash(h);
200        self.m12.hash(h);
201        self.m13.hash(h);
202        self.m14.hash(h);
203        self.m21.hash(h);
204        self.m22.hash(h);
205        self.m23.hash(h);
206        self.m24.hash(h);
207        self.m31.hash(h);
208        self.m32.hash(h);
209        self.m33.hash(h);
210        self.m34.hash(h);
211        self.m41.hash(h);
212        self.m42.hash(h);
213        self.m43.hash(h);
214        self.m44.hash(h);
215    }
216}
217
218impl<T, Src, Dst> Transform3D<T, Src, Dst> {
219    /// Create a transform specifying all of it's component as a 4 by 4 matrix.
220    ///
221    /// Components are specified following column-major-column-vector matrix notation.
222    /// For example, the translation terms m41, m42, m43 are the 13rd, 14th and 15th parameters.
223    ///
224    /// ```
225    /// use euclid::default::Transform3D;
226    /// let tx = 1.0;
227    /// let ty = 2.0;
228    /// let tz = 3.0;
229    /// let translation = Transform3D::new(
230    ///   1.0, 0.0, 0.0, 0.0,
231    ///   0.0, 1.0, 0.0, 0.0,
232    ///   0.0, 0.0, 1.0, 0.0,
233    ///   tx,  ty,  tz,  1.0,
234    /// );
235    /// ```
236    #[inline]
237    #[allow(clippy::too_many_arguments)]
238    #[rustfmt::skip]
239    pub const fn new(
240        m11: T, m12: T, m13: T, m14: T,
241        m21: T, m22: T, m23: T, m24: T,
242        m31: T, m32: T, m33: T, m34: T,
243        m41: T, m42: T, m43: T, m44: T,
244    ) -> Self {
245        Transform3D {
246            m11, m12, m13, m14,
247            m21, m22, m23, m24,
248            m31, m32, m33, m34,
249            m41, m42, m43, m44,
250            _unit: PhantomData,
251        }
252    }
253
254    /// Create a transform representing a 2d transformation from the components
255    /// of a 2 by 3 matrix transformation.
256    ///
257    /// Components follow the column-major-column-vector notation (m41 and m42
258    /// representing the translation terms).
259    ///
260    /// ```text
261    /// m11  m12   0   0
262    /// m21  m22   0   0
263    ///   0    0   1   0
264    /// m41  m42   0   1
265    /// ```
266    #[inline]
267    #[rustfmt::skip]
268    pub fn new_2d(m11: T, m12: T, m21: T, m22: T, m41: T, m42: T) -> Self
269    where
270        T: Zero + One,
271    {
272        let _0 = || T::zero();
273        let _1 = || T::one();
274
275        Self::new(
276            m11,  m12,  _0(), _0(),
277            m21,  m22,  _0(), _0(),
278            _0(), _0(), _1(), _0(),
279            m41,  m42,  _0(), _1()
280       )
281    }
282
283    /// Returns `true` if this transform can be represented with a `Transform2D`.
284    ///
285    /// See <https://drafts.csswg.org/css-transforms/#2d-transform>
286    #[inline]
287    pub fn is_2d(&self) -> bool
288    where
289        T: Zero + One + PartialEq,
290    {
291        let (_0, _1): (T, T) = (Zero::zero(), One::one());
292        self.m31 == _0
293            && self.m32 == _0
294            && self.m13 == _0
295            && self.m23 == _0
296            && self.m43 == _0
297            && self.m14 == _0
298            && self.m24 == _0
299            && self.m34 == _0
300            && self.m33 == _1
301            && self.m44 == _1
302    }
303}
304
305impl<T: Copy, Src, Dst> Transform3D<T, Src, Dst> {
306    /// Returns an array containing this transform's terms.
307    ///
308    /// The terms are laid out in the same order as they are
309    /// specified in `Transform3D::new`, that is following the
310    /// column-major-column-vector matrix notation.
311    ///
312    /// For example the translation terms are found on the
313    /// 13th, 14th and 15th slots of the array.
314    #[inline]
315    #[rustfmt::skip]
316    pub fn to_array(&self) -> [T; 16] {
317        [
318            self.m11, self.m12, self.m13, self.m14,
319            self.m21, self.m22, self.m23, self.m24,
320            self.m31, self.m32, self.m33, self.m34,
321            self.m41, self.m42, self.m43, self.m44
322        ]
323    }
324
325    /// Returns an array containing this transform's terms transposed.
326    ///
327    /// The terms are laid out in transposed order from the same order of
328    /// `Transform3D::new` and `Transform3D::to_array`, that is following
329    /// the row-major-column-vector matrix notation.
330    ///
331    /// For example the translation terms are found at indices 3, 7 and 11
332    /// of the array.
333    #[inline]
334    #[rustfmt::skip]
335    pub fn to_array_transposed(&self) -> [T; 16] {
336        [
337            self.m11, self.m21, self.m31, self.m41,
338            self.m12, self.m22, self.m32, self.m42,
339            self.m13, self.m23, self.m33, self.m43,
340            self.m14, self.m24, self.m34, self.m44
341        ]
342    }
343
344    /// Equivalent to `to_array` with elements packed four at a time
345    /// in an array of arrays.
346    #[inline]
347    #[rustfmt::skip]
348    pub fn to_arrays(&self) -> [[T; 4]; 4] {
349        [
350            [self.m11, self.m12, self.m13, self.m14],
351            [self.m21, self.m22, self.m23, self.m24],
352            [self.m31, self.m32, self.m33, self.m34],
353            [self.m41, self.m42, self.m43, self.m44],
354        ]
355    }
356
357    /// Equivalent to `to_array_transposed` with elements packed
358    /// four at a time in an array of arrays.
359    #[inline]
360    #[rustfmt::skip]
361    pub fn to_arrays_transposed(&self) -> [[T; 4]; 4] {
362        [
363            [self.m11, self.m21, self.m31, self.m41],
364            [self.m12, self.m22, self.m32, self.m42],
365            [self.m13, self.m23, self.m33, self.m43],
366            [self.m14, self.m24, self.m34, self.m44],
367        ]
368    }
369
370    /// Create a transform providing its components via an array
371    /// of 16 elements instead of as individual parameters.
372    ///
373    /// The order of the components corresponds to the
374    /// column-major-column-vector matrix notation (the same order
375    /// as `Transform3D::new`).
376    #[inline]
377    #[rustfmt::skip]
378    pub fn from_array(array: [T; 16]) -> Self {
379        Self::new(
380            array[0],  array[1],  array[2],  array[3],
381            array[4],  array[5],  array[6],  array[7],
382            array[8],  array[9],  array[10], array[11],
383            array[12], array[13], array[14], array[15],
384        )
385    }
386
387    /// Equivalent to `from_array` with elements packed four at a time
388    /// in an array of arrays.
389    ///
390    /// The order of the components corresponds to the
391    /// column-major-column-vector matrix notation (the same order
392    /// as `Transform3D::new`).
393    #[inline]
394    #[rustfmt::skip]
395    pub fn from_arrays(array: [[T; 4]; 4]) -> Self {
396        Self::new(
397            array[0][0], array[0][1], array[0][2], array[0][3],
398            array[1][0], array[1][1], array[1][2], array[1][3],
399            array[2][0], array[2][1], array[2][2], array[2][3],
400            array[3][0], array[3][1], array[3][2], array[3][3],
401        )
402    }
403
404    /// Tag a unitless value with units.
405    #[inline]
406    #[rustfmt::skip]
407    pub fn from_untyped(m: &Transform3D<T, UnknownUnit, UnknownUnit>) -> Self {
408        Transform3D::new(
409            m.m11, m.m12, m.m13, m.m14,
410            m.m21, m.m22, m.m23, m.m24,
411            m.m31, m.m32, m.m33, m.m34,
412            m.m41, m.m42, m.m43, m.m44,
413        )
414    }
415
416    /// Drop the units, preserving only the numeric value.
417    #[inline]
418    #[rustfmt::skip]
419    pub fn to_untyped(&self) -> Transform3D<T, UnknownUnit, UnknownUnit> {
420        Transform3D::new(
421            self.m11, self.m12, self.m13, self.m14,
422            self.m21, self.m22, self.m23, self.m24,
423            self.m31, self.m32, self.m33, self.m34,
424            self.m41, self.m42, self.m43, self.m44,
425        )
426    }
427
428    /// Returns the same transform with a different source unit.
429    #[inline]
430    #[rustfmt::skip]
431    pub fn with_source<NewSrc>(&self) -> Transform3D<T, NewSrc, Dst> {
432        Transform3D::new(
433            self.m11, self.m12, self.m13, self.m14,
434            self.m21, self.m22, self.m23, self.m24,
435            self.m31, self.m32, self.m33, self.m34,
436            self.m41, self.m42, self.m43, self.m44,
437        )
438    }
439
440    /// Returns the same transform with a different destination unit.
441    #[inline]
442    #[rustfmt::skip]
443    pub fn with_destination<NewDst>(&self) -> Transform3D<T, Src, NewDst> {
444        Transform3D::new(
445            self.m11, self.m12, self.m13, self.m14,
446            self.m21, self.m22, self.m23, self.m24,
447            self.m31, self.m32, self.m33, self.m34,
448            self.m41, self.m42, self.m43, self.m44,
449        )
450    }
451
452    /// Create a 2D transform picking the relevant terms from this transform.
453    ///
454    /// This method assumes that self represents a 2d transformation, callers
455    /// should check that [`is_2d`] returns `true` beforehand.
456    ///
457    /// [`is_2d`]: Self::is_2d
458    pub fn to_2d(&self) -> Transform2D<T, Src, Dst> {
459        Transform2D::new(self.m11, self.m12, self.m21, self.m22, self.m41, self.m42)
460    }
461
462    /// Returns true if self can be represented as a 2d scale+offset
463    /// transform, using `T`'s default epsilon value.
464    pub fn is_scale_offset_2d(&self) -> bool
465    where
466        T: Signed + PartialOrd + ApproxEq<T>,
467    {
468        self.is_scale_offset_2d_eps(T::approx_epsilon())
469    }
470
471    /// Returns true if self can be represented as a 2d scale+offset
472    /// transform.
473    pub fn is_scale_offset_2d_eps(&self, epsilon: T) -> bool
474    where
475        T: Signed + PartialOrd,
476    {
477        (self.m12.abs() < epsilon)
478            & (self.m13.abs() < epsilon)
479            & (self.m14.abs() < epsilon)
480            & (self.m21.abs() < epsilon)
481            & (self.m23.abs() < epsilon)
482            & (self.m24.abs() < epsilon)
483            & (self.m31.abs() < epsilon)
484            & (self.m32.abs() < epsilon)
485            & ((self.m33 - T::one()).abs() < epsilon)
486            & (self.m34.abs() < epsilon)
487            & (self.m43.abs() < epsilon)
488            & ((self.m44 - T::one()).abs() < epsilon)
489    }
490
491    /// Creates a 2D scale+offset transform from the current transform.
492    ///
493    /// This method assumes that self can be represented as a 2d scale+offset
494    /// transformation, callers should check that [`is_scale_offset_2d`] or
495    /// [`is_scale_offset_2d_eps`] returns `true` beforehand.
496    pub fn to_scale_offset2d(&self) -> Option<ScaleOffset2D<T, Src, Dst>>
497    where
498        T: Signed + One + PartialOrd,
499    {
500        Some(ScaleOffset2D {
501            sx: self.m11,
502            sy: self.m22,
503            tx: self.m41,
504            ty: self.m42,
505            _unit: PhantomData,
506        })
507    }
508}
509
510impl<T, Src, Dst> Transform3D<T, Src, Dst>
511where
512    T: Zero + One,
513{
514    /// Creates an identity matrix:
515    ///
516    /// ```text
517    /// 1 0 0 0
518    /// 0 1 0 0
519    /// 0 0 1 0
520    /// 0 0 0 1
521    /// ```
522    #[inline]
523    pub fn identity() -> Self {
524        Self::translation(T::zero(), T::zero(), T::zero())
525    }
526
527    /// Intentional not public, because it checks for exact equivalence
528    /// while most consumers will probably want some sort of approximate
529    /// equivalence to deal with floating-point errors.
530    #[inline]
531    fn is_identity(&self) -> bool
532    where
533        T: PartialEq,
534    {
535        *self == Self::identity()
536    }
537
538    /// Create a 2d skew transform.
539    ///
540    /// See <https://drafts.csswg.org/css-transforms/#funcdef-skew>
541    #[rustfmt::skip]
542    pub fn skew(alpha: Angle<T>, beta: Angle<T>) -> Self
543    where
544        T: Trig,
545    {
546        let _0 = || T::zero();
547        let _1 = || T::one();
548        let (sx, sy) = (beta.radians.tan(), alpha.radians.tan());
549
550        Self::new(
551            _1(), sx,   _0(), _0(),
552            sy,   _1(), _0(), _0(),
553            _0(), _0(), _1(), _0(),
554            _0(), _0(), _0(), _1(),
555        )
556    }
557
558    /// Create a simple perspective transform, projecting to the plane `z = -d`.
559    ///
560    /// ```text
561    /// 1   0   0   0
562    /// 0   1   0   0
563    /// 0   0   1 -1/d
564    /// 0   0   0   1
565    /// ```
566    ///
567    /// See <https://drafts.csswg.org/css-transforms-2/#PerspectiveDefined>.
568    pub fn perspective(d: T) -> Self
569    where
570        T: Neg<Output = T> + Div<Output = T>,
571    {
572        let _0 = || T::zero();
573        let _1 = || T::one();
574
575        Self::new(
576            _1(),
577            _0(),
578            _0(),
579            _0(),
580            _0(),
581            _1(),
582            _0(),
583            _0(),
584            _0(),
585            _0(),
586            _1(),
587            -_1() / d,
588            _0(),
589            _0(),
590            _0(),
591            _1(),
592        )
593    }
594}
595
596/// Methods for combining generic transformations
597impl<T, Src, Dst> Transform3D<T, Src, Dst>
598where
599    T: Copy + Add<Output = T> + Mul<Output = T>,
600{
601    /// Returns the multiplication of the two matrices such that mat's transformation
602    /// applies after self's transformation.
603    ///
604    /// Assuming row vectors, this is equivalent to self * mat
605    #[must_use]
606    #[rustfmt::skip]
607    pub fn then<NewDst>(&self, other: &Transform3D<T, Dst, NewDst>) -> Transform3D<T, Src, NewDst> {
608        Transform3D::new(
609            self.m11 * other.m11  +  self.m12 * other.m21  +  self.m13 * other.m31  +  self.m14 * other.m41,
610            self.m11 * other.m12  +  self.m12 * other.m22  +  self.m13 * other.m32  +  self.m14 * other.m42,
611            self.m11 * other.m13  +  self.m12 * other.m23  +  self.m13 * other.m33  +  self.m14 * other.m43,
612            self.m11 * other.m14  +  self.m12 * other.m24  +  self.m13 * other.m34  +  self.m14 * other.m44,
613
614            self.m21 * other.m11  +  self.m22 * other.m21  +  self.m23 * other.m31  +  self.m24 * other.m41,
615            self.m21 * other.m12  +  self.m22 * other.m22  +  self.m23 * other.m32  +  self.m24 * other.m42,
616            self.m21 * other.m13  +  self.m22 * other.m23  +  self.m23 * other.m33  +  self.m24 * other.m43,
617            self.m21 * other.m14  +  self.m22 * other.m24  +  self.m23 * other.m34  +  self.m24 * other.m44,
618
619            self.m31 * other.m11  +  self.m32 * other.m21  +  self.m33 * other.m31  +  self.m34 * other.m41,
620            self.m31 * other.m12  +  self.m32 * other.m22  +  self.m33 * other.m32  +  self.m34 * other.m42,
621            self.m31 * other.m13  +  self.m32 * other.m23  +  self.m33 * other.m33  +  self.m34 * other.m43,
622            self.m31 * other.m14  +  self.m32 * other.m24  +  self.m33 * other.m34  +  self.m34 * other.m44,
623
624            self.m41 * other.m11  +  self.m42 * other.m21  +  self.m43 * other.m31  +  self.m44 * other.m41,
625            self.m41 * other.m12  +  self.m42 * other.m22  +  self.m43 * other.m32  +  self.m44 * other.m42,
626            self.m41 * other.m13  +  self.m42 * other.m23  +  self.m43 * other.m33  +  self.m44 * other.m43,
627            self.m41 * other.m14  +  self.m42 * other.m24  +  self.m43 * other.m34  +  self.m44 * other.m44,
628        )
629    }
630}
631
632/// Methods for creating and combining translation transformations
633impl<T, Src, Dst> Transform3D<T, Src, Dst>
634where
635    T: Zero + One,
636{
637    /// Create a 3d translation transform:
638    ///
639    /// ```text
640    /// 1 0 0 0
641    /// 0 1 0 0
642    /// 0 0 1 0
643    /// x y z 1
644    /// ```
645    #[inline]
646    #[rustfmt::skip]
647    pub fn translation(x: T, y: T, z: T) -> Self {
648        let _0 = || T::zero();
649        let _1 = || T::one();
650
651        Self::new(
652            _1(), _0(), _0(), _0(),
653            _0(), _1(), _0(), _0(),
654            _0(), _0(), _1(), _0(),
655             x,    y,    z,   _1(),
656        )
657    }
658
659    /// Returns a transform with a translation applied before self's transformation.
660    #[must_use]
661    pub fn pre_translate(&self, v: Vector3D<T, Src>) -> Self
662    where
663        T: Copy + Add<Output = T> + Mul<Output = T>,
664    {
665        Transform3D::translation(v.x, v.y, v.z).then(self)
666    }
667
668    /// Returns a transform with a translation applied after self's transformation.
669    #[must_use]
670    pub fn then_translate(&self, v: Vector3D<T, Dst>) -> Self
671    where
672        T: Copy + Add<Output = T> + Mul<Output = T>,
673    {
674        self.then(&Transform3D::translation(v.x, v.y, v.z))
675    }
676}
677
678/// Methods for creating and combining rotation transformations
679impl<T, Src, Dst> Transform3D<T, Src, Dst>
680where
681    T: Copy
682        + Add<Output = T>
683        + Sub<Output = T>
684        + Mul<Output = T>
685        + Div<Output = T>
686        + Zero
687        + One
688        + Trig,
689{
690    /// Create a 3d rotation transform from an angle / axis.
691    /// The supplied axis must be normalized.
692    #[rustfmt::skip]
693    pub fn rotation(x: T, y: T, z: T, theta: Angle<T>) -> Self {
694        let (_0, _1): (T, T) = (Zero::zero(), One::one());
695        let _2 = _1 + _1;
696
697        let xx = x * x;
698        let yy = y * y;
699        let zz = z * z;
700
701        let half_theta = theta.get() / _2;
702        let sc = half_theta.sin() * half_theta.cos();
703        let sq = half_theta.sin() * half_theta.sin();
704
705        Transform3D::new(
706            _1 - _2 * (yy + zz) * sq,
707            _2 * (x * y * sq + z * sc),
708            _2 * (x * z * sq - y * sc),
709            _0,
710
711
712            _2 * (x * y * sq - z * sc),
713            _1 - _2 * (xx + zz) * sq,
714            _2 * (y * z * sq + x * sc),
715            _0,
716
717            _2 * (x * z * sq + y * sc),
718            _2 * (y * z * sq - x * sc),
719            _1 - _2 * (xx + yy) * sq,
720            _0,
721
722            _0,
723            _0,
724            _0,
725            _1
726        )
727    }
728
729    /// Returns a transform with a rotation applied after self's transformation.
730    #[must_use]
731    pub fn then_rotate(&self, x: T, y: T, z: T, theta: Angle<T>) -> Self {
732        self.then(&Transform3D::rotation(x, y, z, theta))
733    }
734
735    /// Returns a transform with a rotation applied before self's transformation.
736    #[must_use]
737    pub fn pre_rotate(&self, x: T, y: T, z: T, theta: Angle<T>) -> Self {
738        Transform3D::rotation(x, y, z, theta).then(self)
739    }
740}
741
742/// Methods for creating and combining scale transformations
743impl<T, Src, Dst> Transform3D<T, Src, Dst>
744where
745    T: Zero + One,
746{
747    /// Create a 3d scale transform:
748    ///
749    /// ```text
750    /// x 0 0 0
751    /// 0 y 0 0
752    /// 0 0 z 0
753    /// 0 0 0 1
754    /// ```
755    #[inline]
756    #[rustfmt::skip]
757    pub fn scale(x: T, y: T, z: T) -> Self {
758        let _0 = || T::zero();
759        let _1 = || T::one();
760
761        Self::new(
762             x,   _0(), _0(), _0(),
763            _0(),  y,   _0(), _0(),
764            _0(), _0(),  z,   _0(),
765            _0(), _0(), _0(), _1(),
766        )
767    }
768
769    /// Returns a transform with a scale applied before self's transformation.
770    #[must_use]
771    #[rustfmt::skip]
772    pub fn pre_scale(&self, x: T, y: T, z: T) -> Self
773    where
774        T: Copy + Add<Output = T> + Mul<Output = T>,
775    {
776        Transform3D::new(
777            self.m11 * x, self.m12 * x, self.m13 * x, self.m14 * x,
778            self.m21 * y, self.m22 * y, self.m23 * y, self.m24 * y,
779            self.m31 * z, self.m32 * z, self.m33 * z, self.m34 * z,
780            self.m41    , self.m42,     self.m43,     self.m44
781        )
782    }
783
784    /// Returns a transform with a scale applied after self's transformation.
785    #[must_use]
786    pub fn then_scale(&self, x: T, y: T, z: T) -> Self
787    where
788        T: Copy + Add<Output = T> + Mul<Output = T>,
789    {
790        self.then(&Transform3D::scale(x, y, z))
791    }
792}
793
794/// Methods for apply transformations to objects
795impl<T, Src, Dst> Transform3D<T, Src, Dst>
796where
797    T: Copy + Add<Output = T> + Mul<Output = T>,
798{
799    /// Returns the homogeneous vector corresponding to the transformed 2d point.
800    ///
801    /// The input point must be use the unit Src, and the returned point has the unit Dst.
802    #[inline]
803    #[rustfmt::skip]
804    pub fn transform_point2d_homogeneous(
805        &self, p: Point2D<T, Src>
806    ) -> HomogeneousVector<T, Dst> {
807        let x = p.x * self.m11 + p.y * self.m21 + self.m41;
808        let y = p.x * self.m12 + p.y * self.m22 + self.m42;
809        let z = p.x * self.m13 + p.y * self.m23 + self.m43;
810        let w = p.x * self.m14 + p.y * self.m24 + self.m44;
811
812        HomogeneousVector::new(x, y, z, w)
813    }
814
815    /// Returns the given 2d point transformed by this transform, if the transform makes sense,
816    /// or `None` otherwise.
817    ///
818    /// The input point must be use the unit Src, and the returned point has the unit Dst.
819    #[inline]
820    pub fn transform_point2d(&self, p: Point2D<T, Src>) -> Option<Point2D<T, Dst>>
821    where
822        T: Div<Output = T> + Zero + PartialOrd,
823    {
824        //Note: could use `transform_point2d_homogeneous()` but it would waste the calculus of `z`
825        let w = p.x * self.m14 + p.y * self.m24 + self.m44;
826        if w > T::zero() {
827            let x = p.x * self.m11 + p.y * self.m21 + self.m41;
828            let y = p.x * self.m12 + p.y * self.m22 + self.m42;
829
830            Some(Point2D::new(x / w, y / w))
831        } else {
832            None
833        }
834    }
835
836    /// Returns the given 2d vector transformed by this matrix.
837    ///
838    /// The input point must be use the unit Src, and the returned point has the unit Dst.
839    #[inline]
840    pub fn transform_vector2d(&self, v: Vector2D<T, Src>) -> Vector2D<T, Dst> {
841        vec2(
842            v.x * self.m11 + v.y * self.m21,
843            v.x * self.m12 + v.y * self.m22,
844        )
845    }
846
847    /// Returns the homogeneous vector corresponding to the transformed 3d point.
848    ///
849    /// The input point must be use the unit Src, and the returned point has the unit Dst.
850    #[inline]
851    pub fn transform_point3d_homogeneous(&self, p: Point3D<T, Src>) -> HomogeneousVector<T, Dst> {
852        let x = p.x * self.m11 + p.y * self.m21 + p.z * self.m31 + self.m41;
853        let y = p.x * self.m12 + p.y * self.m22 + p.z * self.m32 + self.m42;
854        let z = p.x * self.m13 + p.y * self.m23 + p.z * self.m33 + self.m43;
855        let w = p.x * self.m14 + p.y * self.m24 + p.z * self.m34 + self.m44;
856
857        HomogeneousVector::new(x, y, z, w)
858    }
859
860    /// Returns the given 3d point transformed by this transform, if the transform makes sense,
861    /// or `None` otherwise.
862    ///
863    /// The input point must be use the unit Src, and the returned point has the unit Dst.
864    #[inline]
865    pub fn transform_point3d(&self, p: Point3D<T, Src>) -> Option<Point3D<T, Dst>>
866    where
867        T: Div<Output = T> + Zero + PartialOrd,
868    {
869        self.transform_point3d_homogeneous(p).to_point3d()
870    }
871
872    /// Returns the given 3d vector transformed by this matrix.
873    ///
874    /// The input point must be use the unit Src, and the returned point has the unit Dst.
875    #[inline]
876    pub fn transform_vector3d(&self, v: Vector3D<T, Src>) -> Vector3D<T, Dst> {
877        vec3(
878            v.x * self.m11 + v.y * self.m21 + v.z * self.m31,
879            v.x * self.m12 + v.y * self.m22 + v.z * self.m32,
880            v.x * self.m13 + v.y * self.m23 + v.z * self.m33,
881        )
882    }
883
884    /// Returns a rectangle that encompasses the result of transforming the given rectangle by this
885    /// transform, if the transform makes sense for it, or `None` otherwise.
886    pub fn outer_transformed_rect(&self, rect: &Rect<T, Src>) -> Option<Rect<T, Dst>>
887    where
888        T: Sub<Output = T> + Div<Output = T> + Zero + PartialOrd,
889    {
890        let min = rect.min();
891        let max = rect.max();
892        Some(Rect::from_points(&[
893            self.transform_point2d(min)?,
894            self.transform_point2d(max)?,
895            self.transform_point2d(point2(max.x, min.y))?,
896            self.transform_point2d(point2(min.x, max.y))?,
897        ]))
898    }
899
900    /// Returns a 2d box that encompasses the result of transforming the given box by this
901    /// transform, if the transform makes sense for it, or `None` otherwise.
902    pub fn outer_transformed_box2d(&self, b: &Box2D<T, Src>) -> Option<Box2D<T, Dst>>
903    where
904        T: Sub<Output = T> + Div<Output = T> + Zero + PartialOrd,
905    {
906        Some(Box2D::from_points(&[
907            self.transform_point2d(b.min)?,
908            self.transform_point2d(b.max)?,
909            self.transform_point2d(point2(b.max.x, b.min.y))?,
910            self.transform_point2d(point2(b.min.x, b.max.y))?,
911        ]))
912    }
913
914    /// Returns a 3d box that encompasses the result of transforming the given box by this
915    /// transform, if the transform makes sense for it, or `None` otherwise.
916    pub fn outer_transformed_box3d(&self, b: &Box3D<T, Src>) -> Option<Box3D<T, Dst>>
917    where
918        T: Sub<Output = T> + Div<Output = T> + Zero + PartialOrd,
919    {
920        Some(Box3D::from_points(&[
921            self.transform_point3d(point3(b.min.x, b.min.y, b.min.z))?,
922            self.transform_point3d(point3(b.min.x, b.min.y, b.max.z))?,
923            self.transform_point3d(point3(b.min.x, b.max.y, b.min.z))?,
924            self.transform_point3d(point3(b.min.x, b.max.y, b.max.z))?,
925            self.transform_point3d(point3(b.max.x, b.min.y, b.min.z))?,
926            self.transform_point3d(point3(b.max.x, b.min.y, b.max.z))?,
927            self.transform_point3d(point3(b.max.x, b.max.y, b.min.z))?,
928            self.transform_point3d(point3(b.max.x, b.max.y, b.max.z))?,
929        ]))
930    }
931}
932
933impl<T, Src, Dst> Transform3D<T, Src, Dst>
934where
935    T: Copy
936        + Add<T, Output = T>
937        + Sub<T, Output = T>
938        + Mul<T, Output = T>
939        + Div<T, Output = T>
940        + Neg<Output = T>
941        + PartialOrd
942        + One
943        + Zero,
944{
945    /// Create an orthogonal projection transform.
946    #[rustfmt::skip]
947    pub fn ortho(left: T, right: T,
948                 bottom: T, top: T,
949                 near: T, far: T) -> Self {
950        let tx = -((right + left) / (right - left));
951        let ty = -((top + bottom) / (top - bottom));
952        let tz = -((far + near) / (far - near));
953
954        let (_0, _1): (T, T) = (Zero::zero(), One::one());
955        let _2 = _1 + _1;
956        Transform3D::new(
957            _2 / (right - left), _0                 , _0                , _0,
958            _0                 , _2 / (top - bottom), _0                , _0,
959            _0                 , _0                 , -_2 / (far - near), _0,
960            tx                 , ty                 , tz                , _1
961        )
962    }
963
964    /// Check whether shapes on the XY plane with Z pointing towards the
965    /// screen transformed by this matrix would be facing back.
966    #[rustfmt::skip]
967    pub fn is_backface_visible(&self) -> bool {
968        // inverse().m33 < 0;
969        let det = self.determinant();
970        let m33 = self.m12 * self.m24 * self.m41 - self.m14 * self.m22 * self.m41 +
971                  self.m14 * self.m21 * self.m42 - self.m11 * self.m24 * self.m42 -
972                  self.m12 * self.m21 * self.m44 + self.m11 * self.m22 * self.m44;
973        let _0: T = Zero::zero();
974        (m33 * det) < _0
975    }
976
977    /// Returns whether it is possible to compute the inverse transform.
978    #[inline]
979    pub fn is_invertible(&self) -> bool {
980        self.determinant() != Zero::zero()
981    }
982
983    /// Returns the inverse transform if possible.
984    pub fn inverse(&self) -> Option<Transform3D<T, Dst, Src>> {
985        let det = self.determinant();
986
987        if det == Zero::zero() {
988            return None;
989        }
990
991        // todo(gw): this could be made faster by special casing
992        // for simpler transform types.
993        #[rustfmt::skip]
994        let m = Transform3D::new(
995            self.m23*self.m34*self.m42 - self.m24*self.m33*self.m42 +
996            self.m24*self.m32*self.m43 - self.m22*self.m34*self.m43 -
997            self.m23*self.m32*self.m44 + self.m22*self.m33*self.m44,
998
999            self.m14*self.m33*self.m42 - self.m13*self.m34*self.m42 -
1000            self.m14*self.m32*self.m43 + self.m12*self.m34*self.m43 +
1001            self.m13*self.m32*self.m44 - self.m12*self.m33*self.m44,
1002
1003            self.m13*self.m24*self.m42 - self.m14*self.m23*self.m42 +
1004            self.m14*self.m22*self.m43 - self.m12*self.m24*self.m43 -
1005            self.m13*self.m22*self.m44 + self.m12*self.m23*self.m44,
1006
1007            self.m14*self.m23*self.m32 - self.m13*self.m24*self.m32 -
1008            self.m14*self.m22*self.m33 + self.m12*self.m24*self.m33 +
1009            self.m13*self.m22*self.m34 - self.m12*self.m23*self.m34,
1010
1011            self.m24*self.m33*self.m41 - self.m23*self.m34*self.m41 -
1012            self.m24*self.m31*self.m43 + self.m21*self.m34*self.m43 +
1013            self.m23*self.m31*self.m44 - self.m21*self.m33*self.m44,
1014
1015            self.m13*self.m34*self.m41 - self.m14*self.m33*self.m41 +
1016            self.m14*self.m31*self.m43 - self.m11*self.m34*self.m43 -
1017            self.m13*self.m31*self.m44 + self.m11*self.m33*self.m44,
1018
1019            self.m14*self.m23*self.m41 - self.m13*self.m24*self.m41 -
1020            self.m14*self.m21*self.m43 + self.m11*self.m24*self.m43 +
1021            self.m13*self.m21*self.m44 - self.m11*self.m23*self.m44,
1022
1023            self.m13*self.m24*self.m31 - self.m14*self.m23*self.m31 +
1024            self.m14*self.m21*self.m33 - self.m11*self.m24*self.m33 -
1025            self.m13*self.m21*self.m34 + self.m11*self.m23*self.m34,
1026
1027            self.m22*self.m34*self.m41 - self.m24*self.m32*self.m41 +
1028            self.m24*self.m31*self.m42 - self.m21*self.m34*self.m42 -
1029            self.m22*self.m31*self.m44 + self.m21*self.m32*self.m44,
1030
1031            self.m14*self.m32*self.m41 - self.m12*self.m34*self.m41 -
1032            self.m14*self.m31*self.m42 + self.m11*self.m34*self.m42 +
1033            self.m12*self.m31*self.m44 - self.m11*self.m32*self.m44,
1034
1035            self.m12*self.m24*self.m41 - self.m14*self.m22*self.m41 +
1036            self.m14*self.m21*self.m42 - self.m11*self.m24*self.m42 -
1037            self.m12*self.m21*self.m44 + self.m11*self.m22*self.m44,
1038
1039            self.m14*self.m22*self.m31 - self.m12*self.m24*self.m31 -
1040            self.m14*self.m21*self.m32 + self.m11*self.m24*self.m32 +
1041            self.m12*self.m21*self.m34 - self.m11*self.m22*self.m34,
1042
1043            self.m23*self.m32*self.m41 - self.m22*self.m33*self.m41 -
1044            self.m23*self.m31*self.m42 + self.m21*self.m33*self.m42 +
1045            self.m22*self.m31*self.m43 - self.m21*self.m32*self.m43,
1046
1047            self.m12*self.m33*self.m41 - self.m13*self.m32*self.m41 +
1048            self.m13*self.m31*self.m42 - self.m11*self.m33*self.m42 -
1049            self.m12*self.m31*self.m43 + self.m11*self.m32*self.m43,
1050
1051            self.m13*self.m22*self.m41 - self.m12*self.m23*self.m41 -
1052            self.m13*self.m21*self.m42 + self.m11*self.m23*self.m42 +
1053            self.m12*self.m21*self.m43 - self.m11*self.m22*self.m43,
1054
1055            self.m12*self.m23*self.m31 - self.m13*self.m22*self.m31 +
1056            self.m13*self.m21*self.m32 - self.m11*self.m23*self.m32 -
1057            self.m12*self.m21*self.m33 + self.m11*self.m22*self.m33
1058        );
1059
1060        let _1: T = One::one();
1061        Some(m.mul_s(_1 / det))
1062    }
1063
1064    /// Compute the determinant of the transform.
1065    #[rustfmt::skip]
1066    pub fn determinant(&self) -> T {
1067        self.m14 * self.m23 * self.m32 * self.m41 -
1068        self.m13 * self.m24 * self.m32 * self.m41 -
1069        self.m14 * self.m22 * self.m33 * self.m41 +
1070        self.m12 * self.m24 * self.m33 * self.m41 +
1071        self.m13 * self.m22 * self.m34 * self.m41 -
1072        self.m12 * self.m23 * self.m34 * self.m41 -
1073        self.m14 * self.m23 * self.m31 * self.m42 +
1074        self.m13 * self.m24 * self.m31 * self.m42 +
1075        self.m14 * self.m21 * self.m33 * self.m42 -
1076        self.m11 * self.m24 * self.m33 * self.m42 -
1077        self.m13 * self.m21 * self.m34 * self.m42 +
1078        self.m11 * self.m23 * self.m34 * self.m42 +
1079        self.m14 * self.m22 * self.m31 * self.m43 -
1080        self.m12 * self.m24 * self.m31 * self.m43 -
1081        self.m14 * self.m21 * self.m32 * self.m43 +
1082        self.m11 * self.m24 * self.m32 * self.m43 +
1083        self.m12 * self.m21 * self.m34 * self.m43 -
1084        self.m11 * self.m22 * self.m34 * self.m43 -
1085        self.m13 * self.m22 * self.m31 * self.m44 +
1086        self.m12 * self.m23 * self.m31 * self.m44 +
1087        self.m13 * self.m21 * self.m32 * self.m44 -
1088        self.m11 * self.m23 * self.m32 * self.m44 -
1089        self.m12 * self.m21 * self.m33 * self.m44 +
1090        self.m11 * self.m22 * self.m33 * self.m44
1091    }
1092
1093    /// Multiplies all of the transform's component by a scalar and returns the result.
1094    #[must_use]
1095    #[rustfmt::skip]
1096    pub fn mul_s(&self, x: T) -> Self {
1097        Transform3D::new(
1098            self.m11 * x, self.m12 * x, self.m13 * x, self.m14 * x,
1099            self.m21 * x, self.m22 * x, self.m23 * x, self.m24 * x,
1100            self.m31 * x, self.m32 * x, self.m33 * x, self.m34 * x,
1101            self.m41 * x, self.m42 * x, self.m43 * x, self.m44 * x
1102        )
1103    }
1104
1105    /// Convenience function to create a scale transform from a `Scale`.
1106    pub fn from_scale(scale: Scale<T, Src, Dst>) -> Self {
1107        Transform3D::scale(scale.get(), scale.get(), scale.get())
1108    }
1109}
1110
1111impl<T, Src, Dst> Transform3D<T, Src, Dst>
1112where
1113    T: Copy + Mul<Output = T> + Div<Output = T> + Zero + One + PartialEq,
1114{
1115    /// Returns a projection of this transform in 2d space.
1116    pub fn project_to_2d(&self) -> Self {
1117        let (_0, _1): (T, T) = (Zero::zero(), One::one());
1118
1119        let mut result = self.clone();
1120
1121        result.m31 = _0;
1122        result.m32 = _0;
1123        result.m13 = _0;
1124        result.m23 = _0;
1125        result.m33 = _1;
1126        result.m43 = _0;
1127        result.m34 = _0;
1128
1129        // Try to normalize perspective when possible to convert to a 2d matrix.
1130        // Some matrices, such as those derived from perspective transforms, can
1131        // modify m44 from 1, while leaving the rest of the fourth column
1132        // (m14, m24) at 0. In this case, after resetting the third row and
1133        // third column above, the value of m44 functions only to scale the
1134        // coordinate transform divide by W. The matrix can be converted to
1135        // a true 2D matrix by normalizing out the scaling effect of m44 on
1136        // the remaining components ahead of time.
1137        if self.m14 == _0 && self.m24 == _0 && self.m44 != _0 && self.m44 != _1 {
1138            let scale = _1 / self.m44;
1139            result.m11 = result.m11 * scale;
1140            result.m12 = result.m12 * scale;
1141            result.m21 = result.m21 * scale;
1142            result.m22 = result.m22 * scale;
1143            result.m41 = result.m41 * scale;
1144            result.m42 = result.m42 * scale;
1145            result.m44 = _1;
1146        }
1147
1148        result
1149    }
1150}
1151
1152impl<T: NumCast + Copy, Src, Dst> Transform3D<T, Src, Dst> {
1153    /// Cast from one numeric representation to another, preserving the units.
1154    #[inline]
1155    pub fn cast<NewT: NumCast>(&self) -> Transform3D<NewT, Src, Dst> {
1156        self.try_cast().unwrap()
1157    }
1158
1159    /// Fallible cast from one numeric representation to another, preserving the units.
1160    #[rustfmt::skip]
1161    pub fn try_cast<NewT: NumCast>(&self) -> Option<Transform3D<NewT, Src, Dst>> {
1162        match (NumCast::from(self.m11), NumCast::from(self.m12),
1163               NumCast::from(self.m13), NumCast::from(self.m14),
1164               NumCast::from(self.m21), NumCast::from(self.m22),
1165               NumCast::from(self.m23), NumCast::from(self.m24),
1166               NumCast::from(self.m31), NumCast::from(self.m32),
1167               NumCast::from(self.m33), NumCast::from(self.m34),
1168               NumCast::from(self.m41), NumCast::from(self.m42),
1169               NumCast::from(self.m43), NumCast::from(self.m44)) {
1170            (Some(m11), Some(m12), Some(m13), Some(m14),
1171             Some(m21), Some(m22), Some(m23), Some(m24),
1172             Some(m31), Some(m32), Some(m33), Some(m34),
1173             Some(m41), Some(m42), Some(m43), Some(m44)) => {
1174                Some(Transform3D::new(m11, m12, m13, m14,
1175                                      m21, m22, m23, m24,
1176                                      m31, m32, m33, m34,
1177                                      m41, m42, m43, m44))
1178            },
1179            _ => None
1180        }
1181    }
1182}
1183
1184impl<T: ApproxEq<T>, Src, Dst> Transform3D<T, Src, Dst> {
1185    /// Returns `true` if this transform is approximately equal to the other one, using
1186    /// `T`'s default epsilon value.
1187    ///
1188    /// The same as [`ApproxEq::approx_eq`] but available without importing trait.
1189    #[inline]
1190    pub fn approx_eq(&self, other: &Self) -> bool {
1191        <Self as ApproxEq<T>>::approx_eq(self, other)
1192    }
1193
1194    /// Returns `true` if this transform is approximately equal to the other one, using
1195    /// a provided epsilon value.
1196    ///
1197    /// The same as [`ApproxEq::approx_eq_eps`] but available without importing trait.
1198    #[inline]
1199    pub fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool {
1200        <Self as ApproxEq<T>>::approx_eq_eps(self, other, eps)
1201    }
1202}
1203
1204impl<T: ApproxEq<T>, Src, Dst> ApproxEq<T> for Transform3D<T, Src, Dst> {
1205    #[inline]
1206    fn approx_epsilon() -> T {
1207        T::approx_epsilon()
1208    }
1209
1210    #[rustfmt::skip]
1211    fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool {
1212        self.m11.approx_eq_eps(&other.m11, eps) && self.m12.approx_eq_eps(&other.m12, eps) &&
1213        self.m13.approx_eq_eps(&other.m13, eps) && self.m14.approx_eq_eps(&other.m14, eps) &&
1214        self.m21.approx_eq_eps(&other.m21, eps) && self.m22.approx_eq_eps(&other.m22, eps) &&
1215        self.m23.approx_eq_eps(&other.m23, eps) && self.m24.approx_eq_eps(&other.m24, eps) &&
1216        self.m31.approx_eq_eps(&other.m31, eps) && self.m32.approx_eq_eps(&other.m32, eps) &&
1217        self.m33.approx_eq_eps(&other.m33, eps) && self.m34.approx_eq_eps(&other.m34, eps) &&
1218        self.m41.approx_eq_eps(&other.m41, eps) && self.m42.approx_eq_eps(&other.m42, eps) &&
1219        self.m43.approx_eq_eps(&other.m43, eps) && self.m44.approx_eq_eps(&other.m44, eps)
1220    }
1221}
1222
1223impl<T, Src, Dst> Default for Transform3D<T, Src, Dst>
1224where
1225    T: Zero + One,
1226{
1227    /// Returns the [identity transform](Self::identity).
1228    fn default() -> Self {
1229        Self::identity()
1230    }
1231}
1232
1233impl<T, Src, Dst> fmt::Debug for Transform3D<T, Src, Dst>
1234where
1235    T: Copy + fmt::Debug + PartialEq + One + Zero,
1236{
1237    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1238        if self.is_identity() {
1239            write!(f, "[I]")
1240        } else {
1241            self.to_array().fmt(f)
1242        }
1243    }
1244}
1245
1246#[cfg(feature = "mint")]
1247impl<T, Src, Dst> From<mint::RowMatrix4<T>> for Transform3D<T, Src, Dst> {
1248    #[rustfmt::skip]
1249    fn from(m: mint::RowMatrix4<T>) -> Self {
1250        Transform3D {
1251            m11: m.x.x, m12: m.x.y, m13: m.x.z, m14: m.x.w,
1252            m21: m.y.x, m22: m.y.y, m23: m.y.z, m24: m.y.w,
1253            m31: m.z.x, m32: m.z.y, m33: m.z.z, m34: m.z.w,
1254            m41: m.w.x, m42: m.w.y, m43: m.w.z, m44: m.w.w,
1255            _unit: PhantomData,
1256        }
1257    }
1258}
1259#[cfg(feature = "mint")]
1260impl<T, Src, Dst> From<Transform3D<T, Src, Dst>> for mint::RowMatrix4<T> {
1261    #[rustfmt::skip]
1262    fn from(t: Transform3D<T, Src, Dst>) -> Self {
1263        mint::RowMatrix4 {
1264            x: mint::Vector4 { x: t.m11, y: t.m12, z: t.m13, w: t.m14 },
1265            y: mint::Vector4 { x: t.m21, y: t.m22, z: t.m23, w: t.m24 },
1266            z: mint::Vector4 { x: t.m31, y: t.m32, z: t.m33, w: t.m34 },
1267            w: mint::Vector4 { x: t.m41, y: t.m42, z: t.m43, w: t.m44 },
1268        }
1269    }
1270}
1271
1272impl<T: Copy + Zero + One, Src, Dst> From<Transform2D<T, Src, Dst>> for Transform3D<T, Src, Dst> {
1273    fn from(t: Transform2D<T, Src, Dst>) -> Self {
1274        t.to_3d()
1275    }
1276}
1277
1278impl<T: Copy + Zero + One, Src, Dst> From<Scale<T, Src, Dst>> for Transform3D<T, Src, Dst> {
1279    fn from(s: Scale<T, Src, Dst>) -> Self {
1280        Transform3D::scale(s.get(), s.get(), s.get())
1281    }
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286    use super::*;
1287    use crate::approxeq::ApproxEq;
1288    use crate::default;
1289    use crate::{point2, point3};
1290
1291    use core::f32::consts::{FRAC_PI_2, PI};
1292
1293    type Mf32 = default::Transform3D<f32>;
1294
1295    // For convenience.
1296    fn rad(v: f32) -> Angle<f32> {
1297        Angle::radians(v)
1298    }
1299
1300    #[test]
1301    pub fn test_translation() {
1302        let t1 = Mf32::translation(1.0, 2.0, 3.0);
1303        let t2 = Mf32::identity().pre_translate(vec3(1.0, 2.0, 3.0));
1304        let t3 = Mf32::identity().then_translate(vec3(1.0, 2.0, 3.0));
1305        assert_eq!(t1, t2);
1306        assert_eq!(t1, t3);
1307
1308        assert_eq!(
1309            t1.transform_point3d(point3(1.0, 1.0, 1.0)),
1310            Some(point3(2.0, 3.0, 4.0))
1311        );
1312        assert_eq!(
1313            t1.transform_point2d(point2(1.0, 1.0)),
1314            Some(point2(2.0, 3.0))
1315        );
1316
1317        assert_eq!(t1.then(&t1), Mf32::translation(2.0, 4.0, 6.0));
1318
1319        assert!(!t1.is_2d());
1320        assert_eq!(
1321            Mf32::translation(1.0, 2.0, 3.0).to_2d(),
1322            Transform2D::translation(1.0, 2.0)
1323        );
1324    }
1325
1326    #[test]
1327    pub fn test_rotation() {
1328        let r1 = Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1329        let r2 = Mf32::identity().pre_rotate(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1330        let r3 = Mf32::identity().then_rotate(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1331        assert_eq!(r1, r2);
1332        assert_eq!(r1, r3);
1333
1334        assert!(r1
1335            .transform_point3d(point3(1.0, 2.0, 3.0))
1336            .unwrap()
1337            .approx_eq(&point3(-2.0, 1.0, 3.0)));
1338        assert!(r1
1339            .transform_point2d(point2(1.0, 2.0))
1340            .unwrap()
1341            .approx_eq(&point2(-2.0, 1.0)));
1342
1343        assert!(r1
1344            .then(&r1)
1345            .approx_eq(&Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2 * 2.0))));
1346
1347        assert!(r1.is_2d());
1348        assert!(r1.to_2d().approx_eq(&Transform2D::rotation(rad(FRAC_PI_2))));
1349    }
1350
1351    #[test]
1352    pub fn test_scale() {
1353        let s1 = Mf32::scale(2.0, 3.0, 4.0);
1354        let s2 = Mf32::identity().pre_scale(2.0, 3.0, 4.0);
1355        let s3 = Mf32::identity().then_scale(2.0, 3.0, 4.0);
1356        assert_eq!(s1, s2);
1357        assert_eq!(s1, s3);
1358
1359        assert!(s1
1360            .transform_point3d(point3(2.0, 2.0, 2.0))
1361            .unwrap()
1362            .approx_eq(&point3(4.0, 6.0, 8.0)));
1363        assert!(s1
1364            .transform_point2d(point2(2.0, 2.0))
1365            .unwrap()
1366            .approx_eq(&point2(4.0, 6.0)));
1367
1368        assert_eq!(s1.then(&s1), Mf32::scale(4.0, 9.0, 16.0));
1369
1370        assert!(!s1.is_2d());
1371        assert_eq!(
1372            Mf32::scale(2.0, 3.0, 0.0).to_2d(),
1373            Transform2D::scale(2.0, 3.0)
1374        );
1375    }
1376
1377    #[test]
1378    pub fn test_pre_then_scale() {
1379        let m = Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2)).then_translate(vec3(6.0, 7.0, 8.0));
1380        let s = Mf32::scale(2.0, 3.0, 4.0);
1381        assert_eq!(m.then(&s), m.then_scale(2.0, 3.0, 4.0));
1382    }
1383
1384    #[test]
1385    #[rustfmt::skip]
1386    pub fn test_ortho() {
1387        let (left, right, bottom, top) = (0.0f32, 1.0f32, 0.1f32, 1.0f32);
1388        let (near, far) = (-1.0f32, 1.0f32);
1389        let result = Mf32::ortho(left, right, bottom, top, near, far);
1390        let expected = Mf32::new(
1391             2.0,  0.0,         0.0, 0.0,
1392             0.0,  2.22222222,  0.0, 0.0,
1393             0.0,  0.0,        -1.0, 0.0,
1394            -1.0, -1.22222222, -0.0, 1.0
1395        );
1396        assert!(result.approx_eq(&expected));
1397    }
1398
1399    #[test]
1400    pub fn test_is_2d() {
1401        assert!(Mf32::identity().is_2d());
1402        assert!(Mf32::rotation(0.0, 0.0, 1.0, rad(0.7854)).is_2d());
1403        assert!(!Mf32::rotation(0.0, 1.0, 0.0, rad(0.7854)).is_2d());
1404    }
1405
1406    #[test]
1407    #[rustfmt::skip]
1408    pub fn test_new_2d() {
1409        let m1 = Mf32::new_2d(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
1410        let m2 = Mf32::new(
1411            1.0, 2.0, 0.0, 0.0,
1412            3.0, 4.0, 0.0, 0.0,
1413            0.0, 0.0, 1.0, 0.0,
1414            5.0, 6.0, 0.0, 1.0
1415        );
1416        assert_eq!(m1, m2);
1417    }
1418
1419    #[test]
1420    pub fn test_inverse_simple() {
1421        let m1 = Mf32::identity();
1422        let m2 = m1.inverse().unwrap();
1423        assert!(m1.approx_eq(&m2));
1424    }
1425
1426    #[test]
1427    pub fn test_inverse_scale() {
1428        let m1 = Mf32::scale(1.5, 0.3, 2.1);
1429        let m2 = m1.inverse().unwrap();
1430        assert!(m1.then(&m2).approx_eq(&Mf32::identity()));
1431        assert!(m2.then(&m1).approx_eq(&Mf32::identity()));
1432    }
1433
1434    #[test]
1435    pub fn test_inverse_translate() {
1436        let m1 = Mf32::translation(-132.0, 0.3, 493.0);
1437        let m2 = m1.inverse().unwrap();
1438        assert!(m1.then(&m2).approx_eq(&Mf32::identity()));
1439        assert!(m2.then(&m1).approx_eq(&Mf32::identity()));
1440    }
1441
1442    #[test]
1443    pub fn test_inverse_rotate() {
1444        let m1 = Mf32::rotation(0.0, 1.0, 0.0, rad(1.57));
1445        let m2 = m1.inverse().unwrap();
1446        assert!(m1.then(&m2).approx_eq(&Mf32::identity()));
1447        assert!(m2.then(&m1).approx_eq(&Mf32::identity()));
1448    }
1449
1450    #[test]
1451    pub fn test_inverse_transform_point_2d() {
1452        let m1 = Mf32::translation(100.0, 200.0, 0.0);
1453        let m2 = m1.inverse().unwrap();
1454        assert!(m1.then(&m2).approx_eq(&Mf32::identity()));
1455        assert!(m2.then(&m1).approx_eq(&Mf32::identity()));
1456
1457        let p1 = point2(1000.0, 2000.0);
1458        let p2 = m1.transform_point2d(p1);
1459        assert_eq!(p2, Some(point2(1100.0, 2200.0)));
1460
1461        let p3 = m2.transform_point2d(p2.unwrap());
1462        assert_eq!(p3, Some(p1));
1463    }
1464
1465    #[test]
1466    fn test_inverse_none() {
1467        assert!(Mf32::scale(2.0, 0.0, 2.0).inverse().is_none());
1468        assert!(Mf32::scale(2.0, 2.0, 2.0).inverse().is_some());
1469    }
1470
1471    #[test]
1472    pub fn test_pre_post() {
1473        let m1 = default::Transform3D::identity()
1474            .then_scale(1.0, 2.0, 3.0)
1475            .then_translate(vec3(1.0, 2.0, 3.0));
1476        let m2 = default::Transform3D::identity()
1477            .pre_translate(vec3(1.0, 2.0, 3.0))
1478            .pre_scale(1.0, 2.0, 3.0);
1479        assert!(m1.approx_eq(&m2));
1480
1481        let r = Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1482        let t = Mf32::translation(2.0, 3.0, 0.0);
1483
1484        let a = point3(1.0, 1.0, 1.0);
1485
1486        assert!(r
1487            .then(&t)
1488            .transform_point3d(a)
1489            .unwrap()
1490            .approx_eq(&point3(1.0, 4.0, 1.0)));
1491        assert!(t
1492            .then(&r)
1493            .transform_point3d(a)
1494            .unwrap()
1495            .approx_eq(&point3(-4.0, 3.0, 1.0)));
1496        assert!(t.then(&r).transform_point3d(a).unwrap().approx_eq(
1497            &r.transform_point3d(t.transform_point3d(a).unwrap())
1498                .unwrap()
1499        ));
1500    }
1501
1502    #[test]
1503    fn test_size_of() {
1504        use core::mem::size_of;
1505        assert_eq!(
1506            size_of::<default::Transform3D<f32>>(),
1507            16 * size_of::<f32>()
1508        );
1509        assert_eq!(
1510            size_of::<default::Transform3D<f64>>(),
1511            16 * size_of::<f64>()
1512        );
1513    }
1514
1515    #[test]
1516    #[rustfmt::skip]
1517    pub fn test_transform_associativity() {
1518        let m1 = Mf32::new(3.0, 2.0, 1.5, 1.0,
1519                           0.0, 4.5, -1.0, -4.0,
1520                           0.0, 3.5, 2.5, 40.0,
1521                           0.0, 3.0, 0.0, 1.0);
1522        let m2 = Mf32::new(1.0, -1.0, 3.0, 0.0,
1523                           -1.0, 0.5, 0.0, 2.0,
1524                           1.5, -2.0, 6.0, 0.0,
1525                           -2.5, 6.0, 1.0, 1.0);
1526
1527        let p = point3(1.0, 3.0, 5.0);
1528        let p1 = m1.then(&m2).transform_point3d(p).unwrap();
1529        let p2 = m2.transform_point3d(m1.transform_point3d(p).unwrap()).unwrap();
1530        assert!(p1.approx_eq(&p2));
1531    }
1532
1533    #[test]
1534    pub fn test_is_identity() {
1535        let m1 = default::Transform3D::identity();
1536        assert!(m1.is_identity());
1537        let m2 = m1.then_translate(vec3(0.1, 0.0, 0.0));
1538        assert!(!m2.is_identity());
1539    }
1540
1541    #[test]
1542    pub fn test_transform_vector() {
1543        // Translation does not apply to vectors.
1544        let m = Mf32::translation(1.0, 2.0, 3.0);
1545        let v1 = vec3(10.0, -10.0, 3.0);
1546        assert_eq!(v1, m.transform_vector3d(v1));
1547        // While it does apply to points.
1548        assert_ne!(Some(v1.to_point()), m.transform_point3d(v1.to_point()));
1549
1550        // same thing with 2d vectors/points
1551        let v2 = vec2(10.0, -5.0);
1552        assert_eq!(v2, m.transform_vector2d(v2));
1553        assert_ne!(Some(v2.to_point()), m.transform_point2d(v2.to_point()));
1554    }
1555
1556    #[test]
1557    pub fn test_is_backface_visible() {
1558        // backface is not visible for rotate-x 0 degree.
1559        let r1 = Mf32::rotation(1.0, 0.0, 0.0, rad(0.0));
1560        assert!(!r1.is_backface_visible());
1561        // backface is not visible for rotate-x 45 degree.
1562        let r1 = Mf32::rotation(1.0, 0.0, 0.0, rad(PI * 0.25));
1563        assert!(!r1.is_backface_visible());
1564        // backface is visible for rotate-x 180 degree.
1565        let r1 = Mf32::rotation(1.0, 0.0, 0.0, rad(PI));
1566        assert!(r1.is_backface_visible());
1567        // backface is visible for rotate-x 225 degree.
1568        let r1 = Mf32::rotation(1.0, 0.0, 0.0, rad(PI * 1.25));
1569        assert!(r1.is_backface_visible());
1570        // backface is not visible for non-inverseable matrix
1571        let r1 = Mf32::scale(2.0, 0.0, 2.0);
1572        assert!(!r1.is_backface_visible());
1573    }
1574
1575    #[test]
1576    pub fn test_homogeneous() {
1577        #[rustfmt::skip]
1578        let m = Mf32::new(
1579            1.0, 2.0, 0.5, 5.0,
1580            3.0, 4.0, 0.25, 6.0,
1581            0.5, -1.0, 1.0, -1.0,
1582            -1.0, 1.0, -1.0, 2.0,
1583        );
1584        assert_eq!(
1585            m.transform_point2d_homogeneous(point2(1.0, 2.0)),
1586            HomogeneousVector::new(6.0, 11.0, 0.0, 19.0),
1587        );
1588        assert_eq!(
1589            m.transform_point3d_homogeneous(point3(1.0, 2.0, 4.0)),
1590            HomogeneousVector::new(8.0, 7.0, 4.0, 15.0),
1591        );
1592    }
1593
1594    #[test]
1595    pub fn test_perspective_division() {
1596        let p = point2(1.0, 2.0);
1597        let mut m = Mf32::identity();
1598        assert!(m.transform_point2d(p).is_some());
1599        m.m44 = 0.0;
1600        assert_eq!(None, m.transform_point2d(p));
1601        m.m44 = 1.0;
1602        m.m24 = -1.0;
1603        assert_eq!(None, m.transform_point2d(p));
1604    }
1605
1606    #[cfg(feature = "mint")]
1607    #[test]
1608    pub fn test_mint() {
1609        let m1 = Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1610        let mm: mint::RowMatrix4<_> = m1.into();
1611        let m2 = Mf32::from(mm);
1612
1613        assert_eq!(m1, m2);
1614    }
1615}