glamour 0.18.0

Strongly typed linear algebra with glam
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! Strongly typed 2D and 3D transforms.
//!
//! # Chaining transforms
//!
//!

use core::ops::Mul;
use core::{fmt::Debug, marker::PhantomData};

use approx::{AbsDiffEq, RelativeEq, UlpsEq};
use bytemuck::{Pod, Zeroable, cast};

use crate::peel;
use crate::{
    Angle, Matrix3, Matrix4, Point2, Point3, Transparent, Unit, Vector2, Vector3,
    bindings::prelude::*, scalar::FloatScalar,
};

/// 2D transform represented as a 3x3 column-major matrix.
///
/// This is a strongly typed wrapper around a [`Matrix3`], where that matrix
/// describes how to map between units.
#[repr(transparent)]
#[cfg_attr(feature = "facet", derive(facet_derive::Facet))]
pub struct Transform2<Src: Unit, Dst: Unit> {
    /// Underlying matrix.
    pub matrix: Matrix3<Src::Scalar>,
    _marker: PhantomData<Dst>,
}

/// 3D transform represented as a 4x4 column-major matrix.
///
/// This is a strongly typed wrapper around a [`Matrix4`], where that matrix
/// describes how to map between units.
#[repr(transparent)]
#[cfg_attr(feature = "facet", derive(facet_derive::Facet))]
pub struct Transform3<Src: Unit, Dst: Unit> {
    /// Underlying matrix.
    pub matrix: Matrix4<Src::Scalar>,
    _marker: PhantomData<Dst>,
}

/// The mapping operation from one unit to another through a transform.
pub trait TransformMap<T> {
    /// Result type of the transformation.
    type Output;

    /// Map `T` to `Self::Output`.
    #[must_use]
    fn map(&self, value: T) -> Self::Output;
}

impl<Src: Unit, Dst: Unit> Clone for Transform2<Src, Dst> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Src: Unit, Dst: Unit> Clone for Transform3<Src, Dst> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Src: Unit, Dst: Unit> Copy for Transform2<Src, Dst> {}
impl<Src: Unit, Dst: Unit> Copy for Transform3<Src, Dst> {}

impl<Src, Dst> Default for Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit,
{
    #[inline]
    fn default() -> Self {
        Self {
            matrix: Matrix3::default(),
            _marker: PhantomData,
        }
    }
}

impl<Src, Dst> Default for Transform3<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit,
{
    #[inline]
    fn default() -> Self {
        Self {
            matrix: Matrix4::default(),
            _marker: PhantomData,
        }
    }
}

impl<Src, Dst> Debug for Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Transform2")
            .field("matrix", &self.matrix)
            .finish()
    }
}

impl<Src, Dst> Debug for Transform3<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Transform3")
            .field("matrix", &self.matrix)
            .finish()
    }
}

impl<Src, Dst> PartialEq for Transform2<Src, Dst>
where
    Src: Unit,
    Dst: Unit,
{
    fn eq(&self, other: &Self) -> bool {
        self.matrix == other.matrix
    }
}

impl<Src, Dst> AbsDiffEq for Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    type Epsilon = <Matrix3<Src::Scalar> as AbsDiffEq>::Epsilon;

    fn default_epsilon() -> Self::Epsilon {
        <Matrix3<Src::Scalar> as AbsDiffEq>::default_epsilon()
    }

    fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
        self.matrix.abs_diff_eq(&other.matrix, epsilon)
    }
}

impl<Src, Dst> RelativeEq for Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    fn default_max_relative() -> Self::Epsilon {
        <Matrix3<Src::Scalar> as RelativeEq>::default_max_relative()
    }

    fn relative_eq(
        &self,
        other: &Self,
        epsilon: Self::Epsilon,
        max_relative: Self::Epsilon,
    ) -> bool {
        self.matrix
            .relative_eq(&other.matrix, epsilon, max_relative)
    }
}

impl<Src, Dst> UlpsEq for Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    fn default_max_ulps() -> u32 {
        <Matrix3<Src::Scalar> as UlpsEq>::default_max_ulps()
    }

    fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
        self.matrix.ulps_eq(&other.matrix, epsilon, max_ulps)
    }
}

impl<Src: Unit, Dst: Unit> PartialEq for Transform3<Src, Dst> {
    fn eq(&self, other: &Self) -> bool {
        self.matrix == other.matrix
    }
}

impl<Src, Dst> AbsDiffEq for Transform3<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit,
{
    type Epsilon = <Matrix4<Src::Scalar> as AbsDiffEq>::Epsilon;

    fn default_epsilon() -> Self::Epsilon {
        <Matrix4<Src::Scalar> as AbsDiffEq>::default_epsilon()
    }

    fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
        self.matrix.abs_diff_eq(&other.matrix, epsilon)
    }
}

impl<Src, Dst> RelativeEq for Transform3<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit,
{
    fn default_max_relative() -> Self::Epsilon {
        <Matrix4<Src::Scalar> as RelativeEq>::default_max_relative()
    }

    fn relative_eq(
        &self,
        other: &Self,
        epsilon: Self::Epsilon,
        max_relative: Self::Epsilon,
    ) -> bool {
        self.matrix
            .relative_eq(&other.matrix, epsilon, max_relative)
    }
}

impl<Src, Dst> UlpsEq for Transform3<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit,
{
    fn default_max_ulps() -> u32 {
        <Matrix4<Src::Scalar> as UlpsEq>::default_max_ulps()
    }

    fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
        self.matrix.ulps_eq(&other.matrix, epsilon, max_ulps)
    }
}

// SAFETY: These impls are safe because all members are required to be Pod by
// trait bounds in Scalar.
unsafe impl<Src: Unit, Dst: Unit> Zeroable for Transform2<Src, Dst> {}
unsafe impl<Src: Unit, Dst: Unit> Pod for Transform2<Src, Dst> {}
unsafe impl<Src: Unit, Dst: Unit> Zeroable for Transform3<Src, Dst> {}
unsafe impl<Src: Unit, Dst: Unit> Pod for Transform3<Src, Dst> {}
impl<Src: Unit, Dst: Unit> Transparent for Transform2<Src, Dst> {
    type Wrapped = Matrix3<Src::Scalar>;
}
impl<Src: Unit, Dst: Unit> Transparent for Transform3<Src, Dst> {
    type Wrapped = Matrix4<Src::Scalar>;
}

impl<Src, Dst> Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    /// Identity matrix.
    pub const IDENTITY: Self = Self {
        matrix: Matrix3::IDENTITY,
        _marker: PhantomData,
    };

    /// Create from matrix.
    #[inline]
    #[must_use]
    pub const fn from_matrix_unchecked(matrix: Matrix3<Src::Scalar>) -> Self {
        Transform2 {
            matrix,
            _marker: PhantomData,
        }
    }

    /// Create from matrix, checking if the matrix is invertible.
    #[inline]
    #[must_use]
    pub fn from_matrix(matrix: Matrix3<Src::Scalar>) -> Option<Self> {
        if matrix.is_invertible() {
            Some(Self::from_matrix_unchecked(matrix))
        } else {
            None
        }
    }

    /// Create rotation transform.
    ///
    /// #### Example
    /// ```rust
    /// # use glamour::prelude::*;
    /// # use approx::*;
    /// struct A;
    /// impl Unit for A { type Scalar = f64; }
    /// struct B;
    /// impl Unit for B { type Scalar = f64; }
    ///
    /// type Transform = Transform2<A, B>;
    ///
    /// let translate = Transform::from_angle(Angle::FRAG_PI_2);
    /// let a: Vector2<A> = Vector2 { x: 10.0, y: 20.0 };
    /// let b: Vector2<B> = translate.map(a);
    /// assert_abs_diff_eq!(b, vec2!(-20.0, 10.0), epsilon = 0.000001);
    /// ```
    #[inline]
    #[must_use]
    pub fn from_angle(angle: Angle<Src::Scalar>) -> Self {
        Self::from_matrix_unchecked(Matrix3::from_angle(Angle {
            radians: angle.radians,
        }))
    }

    /// Create scaling transform.
    ///
    /// #### Example
    /// ```rust
    /// # use glamour::prelude::*;
    /// # use approx::*;
    /// struct A;
    /// impl Unit for A { type Scalar = f32; }
    /// struct B;
    /// impl Unit for B { type Scalar = f32; }
    ///
    /// type Transform = Transform2<A, B>;
    ///
    /// let translate = Transform::from_scale(Vector2 { x: 2.0, y: 3.0 });
    /// let a: Vector2<A> = Vector2 { x: 10.0, y: 20.0 };
    /// let b: Vector2<B> = translate.map(a);
    /// assert_abs_diff_eq!(b, vec2!(20.0, 60.0));
    /// ```
    #[inline]
    #[must_use]
    pub fn from_scale(scale: Vector2<Src>) -> Self {
        Self::from_matrix_unchecked(Matrix3::from_scale(scale.to_untyped()))
    }

    /// Create translation transform.
    ///
    /// #### Example
    /// ```rust
    /// # use glamour::prelude::*;
    /// # use approx::*;
    /// struct A;
    /// impl Unit for A { type Scalar = f32; }
    /// struct B;
    /// impl Unit for B { type Scalar = f32; }
    ///
    /// type Transform = Transform2<A, B>;
    ///
    /// let translate = Transform::from_translation(Vector2 { x: 10.0, y: 20.0 });
    /// let a: Point2<A> = Point2 { x: 1.0, y: 2.0 };
    /// let b: Point2<B> = translate.map(a);
    /// assert_abs_diff_eq!(b, point!(11.0, 22.0));
    /// ```
    #[inline]
    #[must_use]
    pub fn from_translation(translation: Vector2<Src>) -> Self {
        Self::from_matrix_unchecked(Matrix3::from_translation(translation.to_untyped()))
    }

    /// Create scaling, rotation, and translation matrix.
    ///
    /// #### Example
    /// ```rust
    /// # use glamour::prelude::*;
    /// # use approx::*;
    ///
    /// type Transform = Transform2<f32, f32>;
    ///
    /// let a = Transform::from_scale_angle_translation(
    ///     (2.0, 3.0).into(),
    ///     Angle::from_degrees(90.0),
    ///     (10.0, 20.0).into(),
    /// );
    ///
    /// let b = Transform::from_scale((2.0, 3.0).into())
    ///     .then_rotate(Angle::from_degrees(90.0))
    ///     .then_translate((10.0, 20.0).into());
    ///
    /// assert_abs_diff_eq!(a, b);
    #[inline]
    #[must_use]
    pub fn from_scale_angle_translation(
        scale: Vector2<Src>,
        angle: Angle<Src::Scalar>,
        translation: Vector2<Src>,
    ) -> Self {
        Self::from_matrix_unchecked(Matrix3::from_scale_angle_translation(
            scale.to_untyped(),
            angle,
            translation.to_untyped(),
        ))
    }
}

impl<Src, Dst> TransformMap<Point2<Src>> for Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    type Output = Point2<Dst>;

    #[must_use]
    fn map(&self, value: Point2<Src>) -> Self::Output {
        Point2::from_untyped(self.matrix.transform_point(value.to_untyped()))
    }
}

impl<Src, Dst> TransformMap<Vector2<Src>> for Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    type Output = Vector2<Dst>;

    #[must_use]
    fn map(&self, value: Vector2<Src>) -> Self::Output {
        Vector2::from_untyped(self.matrix.transform_vector(value.to_untyped()))
    }
}

impl<Src, Dst> Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    /// Perform matrix multiplication such that `other`'s transformation applies
    /// after `self`.
    ///
    /// This may change the target coordinate space - that is, the resulting
    /// transform takes points and vectors from `Src` to `Dst2`.
    ///
    /// This operation is equivalent to `other.matrix * self.matrix` - that is,
    /// the multiplication order is the reverse of the order of the effects of
    /// the transformation.
    #[inline]
    #[must_use]
    pub fn then<Dst2>(self, other: Transform2<Dst, Dst2>) -> Transform2<Src, Dst2>
    where
        Dst2: Unit<Scalar = Dst::Scalar>,
    {
        Transform2::from_matrix_unchecked(other.matrix * self.matrix)
    }

    /// Shorthand for `.then(Transform2::from_angle(angle))`.
    ///
    /// This does not change the target coordinate space.
    #[inline]
    #[must_use]
    pub fn then_rotate(self, angle: Angle<Src::Scalar>) -> Self {
        self.then(Transform2::from_angle(angle))
    }

    /// Shorthand for `.then(Transform2::from_scale(scale))`.
    ///
    /// This does not change the target coordinate space.
    ///
    /// #### Example
    ///
    /// ```rust
    /// # use glamour::prelude::*;
    /// let a = Transform2::<f32, f32>::IDENTITY
    ///     .then_scale((2.0, 3.0).into());
    /// let b = Transform2::<f32, f32>::from_scale((2.0, 3.0).into());
    /// assert_eq!(a, b);
    /// ```
    #[inline]
    #[must_use]
    pub fn then_scale(self, scale: Vector2<Dst>) -> Self {
        self.then(Transform2::from_scale(scale))
    }

    /// Shorthand for `.then(Transform2::from_scale(scale))`.
    ///
    /// This does not change the target coordinate space.
    #[inline]
    #[must_use]
    pub fn then_translate(self, translation: Vector2<Dst>) -> Self {
        self.then(Transform2::from_translation(translation))
    }

    /// Invert the matrix.
    ///
    /// See [`glam::Mat3::inverse()`] and [`glam::DMat3::inverse()`].
    #[inline]
    #[must_use]
    pub fn inverse(&self) -> Transform2<Dst, Src> {
        Transform2::from_matrix_unchecked(self.matrix.inverse())
    }
}

impl<Src, Dst, Dst2> Mul<Transform2<Dst, Dst2>> for Transform2<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
    Dst2: Unit<Scalar = Src::Scalar>,
{
    type Output = Transform2<Src, Dst2>;

    #[inline]
    #[must_use]
    fn mul(self, rhs: Transform2<Dst, Dst2>) -> Self::Output {
        Transform2::from_matrix_unchecked(rhs.matrix * self.matrix)
    }
}

impl<Src, Dst, Dst2> Mul<Transform3<Dst, Dst2>> for Transform3<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
    Dst2: Unit<Scalar = Src::Scalar>,
{
    type Output = Transform3<Src, Dst2>;

    #[inline]
    #[must_use]
    fn mul(self, rhs: Transform3<Dst, Dst2>) -> Self::Output {
        Transform3::from_matrix_unchecked(rhs.matrix * self.matrix)
    }
}

impl<Src, Dst> Transform3<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    /// Identity matrix.
    pub const IDENTITY: Self = Self {
        matrix: Matrix4::IDENTITY,
        _marker: PhantomData,
    };

    /// Create from matrix.
    #[inline]
    #[must_use]
    pub const fn from_matrix_unchecked(matrix: Matrix4<Src::Scalar>) -> Self {
        Transform3 {
            matrix,
            _marker: PhantomData,
        }
    }

    /// Create from matrix, checking if the matrix is invertible.
    #[inline]
    #[must_use]
    pub fn from_matrix(matrix: Matrix4<Src::Scalar>) -> Option<Self> {
        if matrix.is_invertible() {
            Some(Self::from_matrix_unchecked(matrix))
        } else {
            None
        }
    }

    /// Perform matrix multiplication such that `other`'s transformation applies
    /// after `self`.
    ///
    /// This may change the target coordinate space - that is, the resulting
    /// transform takes points and vectors from `Src` to `Dst2`.
    ///
    /// This operation is equivalent to `other.matrix * self.matrix` - that is,
    /// the multiplication order is the reverse of the order of the effects of
    /// the transformation.
    #[inline]
    #[must_use]
    pub fn then<Dst2: Unit<Scalar = Dst::Scalar>>(
        self,
        other: Transform3<Dst, Dst2>,
    ) -> Transform3<Src, Dst2> {
        Transform3::from_matrix_unchecked(other.matrix * self.matrix)
    }

    /// Shorthand for `.then(Transform3::from_angle(angle))`.
    ///
    /// This does not change the target coordinate space.
    #[inline]
    #[must_use]
    pub fn then_rotate(self, axis: Vector3<Dst>, angle: Angle<Src::Scalar>) -> Self {
        self.then(Transform3::from_axis_angle(axis, angle))
    }

    /// Shorthand for `.then(Transform3::from_scale(scale))`.
    ///
    /// This does not change the target coordinate space.
    ///
    /// #### Example
    ///
    /// ```rust
    /// # use glamour::prelude::*;
    /// let a = Transform3::<f32, f32>::IDENTITY
    ///     .then_scale((2.0, 3.0, 4.0).into());
    /// let b = Transform3::<f32, f32>::from_scale((2.0, 3.0, 4.0).into());
    /// assert_eq!(a, b);
    /// ```
    #[inline]
    #[must_use]
    pub fn then_scale(self, scale: Vector3<Dst>) -> Self {
        self.then(Transform3::from_scale(scale))
    }

    /// Shorthand for `.then(Transform3::from_scale(scale))`.
    ///
    /// This does not change the target coordinate space.
    #[inline]
    #[must_use]
    pub fn then_translate(self, translation: Vector3<Dst>) -> Self {
        self.then(Transform3::from_translation(translation))
    }

    /// Create rotation transform.
    ///
    /// #### Example
    /// ```rust
    /// # use glamour::prelude::*;
    /// # use approx::*;
    /// struct A;
    /// impl Unit for A { type Scalar = f64; }
    /// struct B;
    /// impl Unit for B { type Scalar = f64; }
    ///
    /// type Transform = Transform3<A, B>;
    ///
    /// let translate = Transform::from_axis_angle(Vector3::Z, Angle::FRAG_PI_2);
    /// let a: Vector3<A> = Vector3 { x: 10.0, y: 20.0, z: 30.0 };
    /// let b: Vector3<B> = translate.map(a);
    /// assert_abs_diff_eq!(b, vec3!(-20.0, 10.0, 30.0), epsilon = 0.000001);
    /// ```
    #[inline]
    #[must_use]
    pub fn from_axis_angle(axis: Vector3<Src>, angle: Angle<Src::Scalar>) -> Self {
        Self::from_matrix_unchecked(Matrix4::from_axis_angle(
            axis.to_untyped(),
            Angle {
                radians: angle.radians,
            },
        ))
    }

    /// Create scaling transform.
    ///
    /// #### Example
    /// ```rust
    /// # use glamour::{Unit, prelude::*};
    /// # use approx::*;
    /// struct A;
    /// impl Unit for A { type Scalar = f32; }
    /// struct B;
    /// impl Unit for B { type Scalar = f32; }
    ///
    /// type Transform = Transform3<A, B>;
    ///
    /// let scale = Transform::from_scale(Vector3 { x: 2.0, y: 3.0, z: 1.0 });
    /// let a: Vector3<A> = Vector3 { x: 10.0, y: 20.0, z: 30.0 };
    /// let b: Vector3<B> = scale.map(a);
    /// assert_abs_diff_eq!(b, vec3!(20.0, 60.0, 30.0));
    /// ```
    #[inline]
    #[must_use]
    pub fn from_scale(scale: Vector3<Src>) -> Self {
        Self::from_matrix_unchecked(Matrix4::from_scale(scale.to_untyped()))
    }

    /// Create translation transform.
    ///
    /// #### Example
    /// ```rust
    /// # use glamour::{Unit, prelude::*};
    /// # use approx::*;
    /// struct A;
    /// impl Unit for A { type Scalar = f32; }
    /// struct B;
    /// impl Unit for B { type Scalar = f32; }
    ///
    /// type Transform = Transform3<A, B>;
    ///
    /// let translate = Transform::from_translation(Vector3 { x: 10.0, y: 20.0, z: 30.0 });
    /// let a: Point3<A> = Point3 { x: 1.0, y: 2.0, z: 30.0 };
    /// let b: Point3<B> = translate.map(a);
    /// assert_abs_diff_eq!(b, point!(11.0, 22.0, 60.0));
    /// ```
    #[inline]
    #[must_use]
    pub fn from_translation(translation: Vector3<Src>) -> Self {
        Self::from_matrix_unchecked(Matrix4::from_translation(translation.to_untyped()))
    }

    /// Create scaling, rotation, and translation matrix.
    ///
    /// Note: This internally converts `axis` and `angle` to a quaternion and
    /// calls [`glam::Mat4::from_scale_rotation_translation()`].
    ///
    /// #### Example
    /// ```rust
    /// # use glamour::{Unit, prelude::*};
    /// # use approx::*;
    ///
    /// type Transform = Transform3<f32, f32>;
    ///
    /// let a = Transform::from_scale_rotation_translation(
    ///     (2.0, 3.0, 1.0).into(),
    ///     (0.0, 0.0, 1.0).into(),
    ///     Angle::from_degrees(90.0),
    ///     (10.0, 20.0, 30.0).into(),
    /// );
    ///
    /// // While this is equivalent, it introduces a significant amount of
    /// // floating point imprecision.
    /// let b = Transform::from_scale((2.0, 3.0, 1.0).into())
    ///     .then_rotate((0.0, 0.0, 1.0).into(), Angle::from_degrees(90.0))
    ///     .then_translate((10.0, 20.0, 30.0).into());
    ///
    /// assert_abs_diff_eq!(a, b, epsilon = 0.001);
    #[inline]
    #[must_use]
    pub fn from_scale_rotation_translation(
        scale: Vector3<Src>,
        axis: Vector3<Src>,
        angle: Angle<Src::Scalar>,
        translation: Vector3<Src>,
    ) -> Self {
        let rotation = <Src::Scalar as FloatScalar>::Quat::from_axis_angle(peel(axis), peel(angle));
        Self::from_matrix_unchecked(Matrix4::from_scale_rotation_translation(
            scale.to_untyped(),
            rotation,
            translation.to_untyped(),
        ))
    }

    /// Map vector from `Src` to `Dst`.
    ///
    /// See [`glam::Mat4::transform_vector3()`] and
    /// [`glam::DMat4::transform_vector3()`].
    #[inline]
    #[must_use]
    pub fn map_vector(&self, vector: Vector3<Src>) -> Vector3<Dst> {
        cast(self.matrix.transform_vector3(vector.to_untyped()))
    }

    /// Map point from `Src` to `Dst`, including perspective correction.
    ///
    /// See [`glam::Mat4::project_point3()`] and
    /// [`glam::DMat4::project_point3()`].
    #[inline]
    #[must_use]
    pub fn map_point(&self, point: Point3<Src>) -> Point3<Dst> {
        cast(self.matrix.project_point3(point.to_untyped()))
    }

    /// Invert the matrix.
    ///
    /// See [`glam::Mat4::inverse()`] and [`glam::DMat4::inverse()`].
    #[inline]
    #[must_use]
    pub fn inverse(&self) -> Transform3<Dst, Src> {
        Transform3::from_matrix_unchecked(self.matrix.inverse())
    }
}

impl<Src, Dst> TransformMap<Point3<Src>> for Transform3<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    type Output = Point3<Dst>;

    #[must_use]
    fn map(&self, value: Point3<Src>) -> Self::Output {
        self.map_point(value)
    }
}

impl<Src, Dst> TransformMap<Vector3<Src>> for Transform3<Src, Dst>
where
    Src: Unit,
    Src::Scalar: FloatScalar,
    Dst: Unit<Scalar = Src::Scalar>,
{
    type Output = Vector3<Dst>;

    #[must_use]
    fn map(&self, value: Vector3<Src>) -> Self::Output {
        self.map_vector(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::*;

    struct TestSrc;
    impl Unit for TestSrc {
        type Scalar = f32;
    }

    struct TestDst;
    impl Unit for TestDst {
        type Scalar = f32;
    }

    struct TestDst2;
    impl Unit for TestDst2 {
        type Scalar = f32;
    }

    macro_rules! check_2d_and_3d {
        { $($test:tt)* } => {{
            {
                type Transform = Transform2<TestSrc, TestDst>;
                type Mat = Matrix3<f32>;
                type TransformInverse = Transform2<TestDst, TestSrc>;
                type VectorSrc = Vector2<TestSrc>;
                type VectorDst = Vector2<TestDst>;
                type PointSrc = Point2<TestSrc>;
                type PointDst = Point2<TestDst>;
                let _ = core::mem::size_of::<(Transform, Mat, TransformInverse, VectorSrc, VectorDst, PointSrc, PointDst)>();
                $($test)*
            }
            {
                type Transform = Transform3<TestSrc, TestDst>;
                type Mat = Matrix4<f32>;
                type TransformInverse = Transform3<TestDst, TestSrc>;
                type VectorSrc = Vector3<TestSrc>;
                type VectorDst = Vector3<TestDst>;
                type PointSrc = Point3<TestSrc>;
                type PointDst = Point3<TestDst>;
                let _ = core::mem::size_of::<(Transform, Mat, TransformInverse, VectorSrc, VectorDst, PointSrc, PointDst)>();
                $($test)*
            }
        }};
    }

    #[test]
    fn basic() {
        check_2d_and_3d! {
            let a = Transform::IDENTITY;
            let b = a;
            assert_eq!(a, b);
            assert_abs_diff_eq!(a, b);
            assert_relative_eq!(a, b);
            assert_ulps_eq!(a, b);

            let c = a.then_scale(VectorDst::splat(2.0));
            assert_ne!(a, c);
            assert_abs_diff_ne!(a, c);
            assert_relative_ne!(a, c);
            assert_ulps_ne!(a, c);
        };

        check_2d_and_3d! {
            let a = Transform::IDENTITY;
            assert_eq!(a, Transform::default());
        };
    }

    #[test]
    fn from_matrix() {
        check_2d_and_3d! {
            assert!(Transform::from_matrix(Mat::ZERO).is_none());
            assert_eq!(Transform::from_matrix(Mat::IDENTITY), Some(Transform::IDENTITY));
        };
    }

    #[test]
    fn inverse() {
        check_2d_and_3d! {
            assert!(Transform::from_matrix(Mat::zeroed()).is_none());

            let transform = Transform::from_translation(VectorSrc::splat(1.0));
            let point = PointSrc::splat(2.0);
            let point_dst: PointDst = transform.map(point);
            assert_abs_diff_eq!(point_dst, PointDst::splat(3.0));

            let inverse: TransformInverse = transform.inverse();
            let point_src = inverse.map(point_dst);
            assert_abs_diff_eq!(point_src, point);
        };
    }

    #[test]
    fn concatenation() {
        {
            let a = Transform2::<TestSrc, TestDst>::from_scale((2.0, 2.0).into());
            let b = Transform2::<TestDst, TestDst2>::from_translation((1.0, 1.0).into());
            let c: Transform2<TestSrc, TestDst2> = a * b;
            assert_eq!(
                c,
                Transform2::<TestSrc, TestDst2>::from_scale((2.0, 2.0).into())
                    .then_translate((1.0, 1.0).into())
            );
        }

        {
            let a = Transform3::<TestSrc, TestDst>::from_scale((2.0, 2.0, 2.0).into());
            let b = Transform3::<TestDst, TestDst2>::from_translation((1.0, 1.0, 1.0).into());
            let c: Transform3<TestSrc, TestDst2> = a * b;
            assert_eq!(
                c,
                Transform3::<TestSrc, TestDst2>::from_scale((2.0, 2.0, 2.0).into())
                    .then_translate((1.0, 1.0, 1.0).into())
            );
        }
    }

    #[test]
    fn gaslight_coverage() {
        fn clone_me<T: Clone>(v: &T) -> T {
            v.clone()
        }
        _ = clone_me(&Transform2::<f32, f32>::IDENTITY);
        _ = clone_me(&Transform3::<f32, f32>::IDENTITY);
    }
}