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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
// Copyright 2019 The Al_Jabr Developers. For a full listing of authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
//! A generic linear algebra library for computer graphics.
//!
//! `al_jabr` is roughly compatibly with [cgmath](https://github.com/rustgd/cgmath)
//! and is intended to provide a small set of lightweight linear algebra
//! operations typically useful in interactive computer graphics.
//!
//! `al_jabr` is n-dimensional, meaning that its data structures support an
//! arbitrary number of elements. If you wish to create a five-dimensional rigid
//! body simulation, `al_jabr` can help you.
//!
//! ## Getting started
//!
//! All of `al_jabr`'s types are exported in the root of the crate, so importing
//! them all is as easy as adding the following to the top of your source file:
//!
//! ```
//! use al_jabr::*;
//! ```
//!
//! After that, you can begin using `al_jabr`.
//!
//! ### Vector
//!
//! [Vectors](Vector) can be constructed from arrays of any type and size.
//! Under the hood, a Vector is a one-dimensional [Matrix]. Use the [vector!]
//! macro to easily construct a vector:
//!
//! ```
//! # use al_jabr::*;
//! let a = vector![ 0u32, 1, 2, 3 ];
//! assert_eq!(
//!     a,
//!     Vector::<u32, 4>::from([ 0u32, 1, 2, 3 ])
//! );
//! ```
//!
//! [Add], [Sub], and [Neg] will be properly implemented for any `Vector<Scalar,
//! N>` for any respective implementation of such operations for `Scalar`.
//! Operations are only implemented for vectors of equal sizes.
//!
//! ```
//! # use al_jabr::*;
//! let b = vector![ 0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, ];
//! let c = vector![ 1.0f32, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ] * 0.5;
//! assert_eq!(
//!     b + c,
//!     vector![ 0.5f32, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5 ]
//! );
//! ```
//!
//! If the scalar type implements [Mul] as well, then the Vector will be an
//! [InnerSpace] and have the [dot](InnerSpace::dot) product defined for it,
//! as well as the ability to find the squared distance between two vectors
//! (implements [MetricSpace]) and  the squared magnitude of a vector. If the
//! scalar type is a real number then the  distance between two vectors and
//! the magnitude of a vector can be found in addition:
//!
//! ```rust
//! # use al_jabr::*;
//! let a = vector!(1i32, 1);
//! let b = vector!(5i32, 5);
//! assert_eq!(a.distance2(b), 32);       // distance method not implemented.
//! assert_eq!((b - a).magnitude2(), 32); // magnitude method not implemented.
//!
//! let a = vector!(1.0f32, 1.0);
//! let b = vector!(5.0f32, 5.0);
//! const close: f32 = 5.65685424949;
//! assert_eq!(a.distance(b), close);       // distance is implemented.
//! assert_eq!((b - a).magnitude(), close); // magnitude is implemented.
//!
//! // Vector normalization is also supported for floating point scalars.
//! assert_eq!(
//!     vector!(0.0f32, 20.0, 0.0)
//!         .normalize(),
//!     vector!(0.0f32, 1.0, 0.0)
//! );
//! ```
//!
//! ### Matrix
//!
//! [Matrices](Matrix) can be created from an array of arrays of any size
//! and scalar type. Matrices are column-major and constructing a matrix from a
//! raw array reflects that. The [matrix!] macro can be used to construct a
//! matrix in row-major order:
//!
//! ```
//! # use al_jabr::*;
//! let a = Matrix::<f32, 3, 3>::from([
//!     [1.0, 0.0, 0.0],
//!     [0.0, 1.0, 0.0],
//!     [0.0, 0.0, 1.0],
//! ]);
//!
//! let b: Matrix::<i32, 3, 3> = matrix![
//!     [ 0, -3, 5 ],
//!     [ 6, 1, -4 ],
//!     [ 2, 3, -2 ]
//! ];
//! ```
//!
//! All operations performed on matrices produce fixed-size outputs. For
//! example, taking the [transpose](Matrix::transpose) of a non-square matrix
//! will produce a matrix with the width and height swapped:
//!
//! ```
//! # use al_jabr::*;
//! assert_eq!(
//!     Matrix::<i32, 1, 2>::from([ [ 1 ], [ 2 ] ])
//!         .transpose(),
//!     Matrix::<i32, 2, 1>::from([ [ 1, 2 ] ])
//! );
//! ```
//!
//! As with Vectors, if the underlying scalar type supports the appropriate
//! operations, a matrix will implement element-wise [Add] and [Sub] for
//! matrices of equal size:
//!
//! ```
//! # use al_jabr::*;
//! let a = matrix!([1_u32]);
//! let b = matrix!([2_u32]);
//! let c = matrix!([3_u32]);
//! assert_eq!(a + b, c);
//! ```
//!
//! And this is true for any type that implements [Add], so therefore the
//! following is possible as well:
//!
//! ```
//! # use al_jabr::*;
//! let a = matrix!([matrix!([1_u32])]);
//! let b = matrix!([matrix!([2_u32])]);
//! let c = matrix!([matrix!([3_u32])]);
//! assert_eq!(a + b, c);
//! ```
//!
//! For a given type `T`, if `T: Clone` and `Vector<T, _>` is an [InnerSpace],
//! then multiplication is defined for `Matrix<T, N, M> * Matrix<T, M, P>`. The
//! result is a `Matrix<T, N, P>`:
//!
//! ```rust
//! # use al_jabr::*;
//! let a: Matrix::<i32, 3, 3> = matrix![
//!     [ 0, -3, 5 ],
//!     [ 6, 1, -4 ],
//!     [ 2, 3, -2 ],
//! ];
//! let b: Matrix::<i32, 3, 3> = matrix![
//!     [ -1, 0, -3 ],
//!     [  4, 5,  1 ],
//!     [  2, 6, -2 ],
//! ];
//! let c: Matrix::<i32, 3, 3> = matrix![
//!     [  -2,  15, -13 ],
//!     [ -10, -19,  -9 ],
//!     [   6,   3,   1 ],
//! ];
//! assert_eq!(
//!     a * b,
//!     c
//! );
//! ```

use core::{
    cmp::PartialOrd,
    fmt,
    hash::{Hash, Hasher},
    iter::{FromIterator, Product},
    marker::PhantomData,
    mem::{self, transmute_copy, MaybeUninit},
    ops::{
        Add, AddAssign, Deref, DerefMut, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub,
        SubAssign,
    },
};

#[cfg(feature = "rand")]
use rand::{
    distributions::{Distribution, Standard},
    Rng,
};

#[cfg(feature = "serde")]
use serde::{
    de::{Error, SeqAccess, Visitor},
    ser::SerializeTuple,
    Deserialize, Deserializer, Serialize, Serializer,
};

mod array;
mod matrix;
mod point;
mod rotation;
pub mod row_view;
mod vector;

pub use array::*;
pub use matrix::*;
pub use point::*;
pub use rotation::*;
use row_view::*;
pub use vector::*;

/// Defines the additive identity for `Self`.
pub trait Zero {
    /// Returns the additive identity of `Self`.
    fn zero() -> Self;

    /// Returns true if the value is the additive identity.
    fn is_zero(&self) -> bool;
}

macro_rules! impl_zero {
    // Default $zero to '0' if not provided.
    (
        $type:ty
    ) => {
        impl_zero! { $type, 0 }
    };
    // Main impl.
    (
        $type:ty,
        $zero:expr
    ) => {
        impl Zero for $type {
            fn zero() -> Self {
                $zero
            }

            fn is_zero(&self) -> bool {
                *self == $zero
            }
        }
    };
}

impl_zero! { bool, false }
impl_zero! { f32, 0.0 }
impl_zero! { f64, 0.0 }
impl_zero! { i8 }
impl_zero! { i16 }
impl_zero! { i32 }
impl_zero! { i64 }
impl_zero! { i128 }
impl_zero! { isize }
impl_zero! { u8 }
impl_zero! { u16 }
impl_zero! { u32 }
impl_zero! { u64 }
impl_zero! { u128 }
impl_zero! { usize }

/// Defines the multiplicative identity element for `Self`.
///
/// For Matrices, `one` is an alias for the unit matrix.
pub trait One {
    /// Returns the multiplicative identity for `Self`.
    fn one() -> Self;

    /// Returns true if the value is the multiplicative identity.
    fn is_one(&self) -> bool;
}

macro_rules! impl_one {
    // Default $one to '1' if not provided.
    (
        $type:ty
    ) => {
        impl_one! { $type, 1 }
    };
    // Main impl.
    (
        $type:ty,
        $one:expr
    ) => {
        impl One for $type {
            fn one() -> Self {
                $one
            }

            fn is_one(&self) -> bool {
                *self == $one
            }
        }
    };
}

impl_one! { bool, true }
impl_one! { f32, 1.0 }
impl_one! { f64, 1.0 }
impl_one! { i8 }
impl_one! { i16 }
impl_one! { i32 }
impl_one! { i64 }
impl_one! { i128 }
impl_one! { isize }
impl_one! { u8 }
impl_one! { u16 }
impl_one! { u32 }
impl_one! { u64 }
impl_one! { u128 }
impl_one! { usize }

/// Values that are [real numbers](https://en.wikipedia.org/wiki/Real_number#Axiomatic_approach).
pub trait Real
where
    Self: Sized,
    Self: Add<Output = Self>,
    Self: Sub<Output = Self>,
    Self: Mul<Output = Self>,
    Self: Div<Output = Self>,
    Self: Neg<Output = Self>,
    Self: PartialOrd + PartialEq,
{
    fn sqrt(self) -> Self;

    fn mul2(self) -> Self;

    fn div2(self) -> Self;

    fn abs(self) -> Self;

    /// Returns the sine of the angle.
    fn sin(self) -> Self;

    /// Returns the cosine of the angle.
    fn cos(self) -> Self;

    /// Returns the tangent of the angle.
    fn tan(self) -> Self;

    /// Returns the arcsine of the angle.
    fn asin(self) -> Self;

    /// Returns the arccos of the angle.
    fn acos(self) -> Self;

    /// Returns the four quadrant arctangent of `self` and `x` in radians.
    fn atan2(self, x: Self) -> Self;

    /// Returns the sine and the cosine of the angle.
    fn sin_cos(self) -> (Self, Self);
}

impl Real for f32 {
    fn sqrt(self) -> Self {
        self.sqrt()
    }

    fn mul2(self) -> Self {
        2.0 * self
    }

    fn div2(self) -> Self {
        self / 2.0
    }

    fn abs(self) -> Self {
        self.abs()
    }

    fn sin(self) -> Self {
        self.sin()
    }

    fn cos(self) -> Self {
        self.cos()
    }

    fn asin(self) -> Self {
        self.asin()
    }

    fn acos(self) -> Self {
        self.acos()
    }

    fn tan(self) -> Self {
        self.tan()
    }

    fn atan2(self, x: Self) -> Self {
        self.atan2(x)
    }

    fn sin_cos(self) -> (Self, Self) {
        (self.sin(), self.cos())
    }
}

impl Real for f64 {
    fn sqrt(self) -> Self {
        self.sqrt()
    }

    fn mul2(self) -> Self {
        2.0 * self
    }

    fn div2(self) -> Self {
        self / 2.0
    }

    fn abs(self) -> Self {
        self.abs()
    }

    fn sin(self) -> Self {
        self.sin()
    }

    fn cos(self) -> Self {
        self.cos()
    }

    fn asin(self) -> Self {
        self.asin()
    }

    fn acos(self) -> Self {
        self.acos()
    }

    fn tan(self) -> Self {
        self.tan()
    }

    fn atan2(self, x: Self) -> Self {
        self.atan2(x)
    }

    fn sin_cos(self) -> (Self, Self) {
        (self.sin(), self.cos())
    }
}

/// Vectors that can be added together and multiplied by scalars form a
/// `VectorSpace`.
///
/// If a [Vector] implements [Add] and [Sub] and its scalar implements [Mul] and
/// [Div], then that vector is part of a `VectorSpace`.
pub trait VectorSpace
where
    Self: Sized + Clone + Zero,
    Self: Add<Self, Output = Self>,
    Self: Sub<Self, Output = Self>,
    Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>,
    Self: Div<<Self as VectorSpace>::Scalar, Output = Self>,
{
    // I only need Div, but I felt like I had to add them all...
    type Scalar: Add<Self::Scalar, Output = Self::Scalar>
        + Sub<Self::Scalar, Output = Self::Scalar>
        + Mul<Self::Scalar, Output = Self::Scalar>
        + Div<Self::Scalar, Output = Self::Scalar>;

    /// Linear interpolate between the two vectors with a weight of `t`.
    fn lerp(self, other: Self, t: Self::Scalar) -> Self {
        self.clone() + ((other - self) * t)
    }
}

/// A type with a distance function between two values.
pub trait MetricSpace: Sized {
    type Metric;

    /// Returns the distance squared between the two values.
    fn distance2(self, other: Self) -> Self::Metric;
}

/// A [MetricSpace] where the metric is a real number.
pub trait RealMetricSpace: MetricSpace
where
    Self::Metric: Real,
{
    /// Returns the distance between the two values.
    fn distance(self, other: Self) -> Self::Metric {
        self.distance2(other).sqrt()
    }
}

impl<T> RealMetricSpace for T
where
    T: MetricSpace,
    <T as MetricSpace>::Metric: Real,
{
}

/// Vector spaces that have an inner (also known as "dot") product.
pub trait InnerSpace: VectorSpace
where
    Self: Clone,
    Self: MetricSpace<Metric = <Self as VectorSpace>::Scalar>,
{
    /// Return the inner (also known as "dot") product.
    fn dot(self, other: Self) -> Self::Scalar;

    /// Returns the squared length of the value.
    fn magnitude2(self) -> Self::Scalar {
        self.clone().dot(self)
    }

    /// Returns the [reflection](https://en.wikipedia.org/wiki/Reflection_(mathematics))
    /// of the current vector with respect to the given surface normal. The
    /// surface normal must be of length 1 for the return value to be
    /// correct. The current vector is interpreted as pointing toward the
    /// surface, and does not need to be normalized.
    fn reflect(self, surface_normal: Self) -> Self {
        let a = surface_normal.clone() * self.clone().dot(surface_normal);
        self - (a.clone() + a)
    }
}

/// Defines an [InnerSpace] where the Scalar is a real number. Automatically
/// implemented.
pub trait RealInnerSpace: InnerSpace
where
    Self: Clone,
    Self: MetricSpace<Metric = <Self as VectorSpace>::Scalar>,
    <Self as VectorSpace>::Scalar: Real,
{
    /// Returns the length of the vector.
    fn magnitude(self) -> Self::Scalar {
        self.clone().dot(self).sqrt()
    }

    /// Returns a vector with the same direction and a magnitude of `1`.
    fn normalize(self) -> Self
    where
        Self::Scalar: One,
    {
        self.normalize_to(<Self::Scalar as One>::one())
    }

    /// Returns a vector with the same direction and a given magnitude.
    fn normalize_to(self, magnitude: Self::Scalar) -> Self {
        self.clone() * (magnitude / self.magnitude())
    }

    /// Returns the
    /// [vector projection](https://en.wikipedia.org/wiki/Vector_projection)
    /// of the current inner space projected onto the supplied argument.
    fn project_on(self, other: Self) -> Self {
        other.clone() * (self.dot(other.clone()) / other.magnitude2())
    }
}

impl<T> RealInnerSpace for T
where
    T: InnerSpace,
    <T as VectorSpace>::Scalar: Real,
{
}

/// An object with a magnitude of one
#[derive(Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(transparent)]
pub struct Unit<T>(T);

impl<T> Unit<T> {
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for Unit<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Unit<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> Unit<T>
where
    T: RealInnerSpace + VectorSpace,
    T::Scalar: Real + One,
{
    /// Construct a new unit object, normalizing the input in the process
    pub fn new_normalize(obj: T) -> Self {
        Unit(obj.normalize())
    }
}

impl<T> Unit<T>
where
    T: RealInnerSpace + VectorSpace + Neg<Output = T>,
    T::Scalar: Real + Zero + One + Clone,
{
    /// Perform a normalized linear interpolation between self and rhs
    pub fn nlerp(self, mut rhs: Self, amount: T::Scalar) -> Self {
        if self.0.clone().dot(rhs.0.clone()) < T::Scalar::zero() {
            rhs.0 = -rhs.0;
        }
        Self::new_normalize(self.0 * (T::Scalar::one() - amount.clone()) + rhs.0 * amount)
    }

    /// Perform a spherical linear interpolation between self and rhs
    pub fn slerp(self, mut rhs: Self, amount: T::Scalar) -> Self {
        let mut dot = self.0.clone().dot(rhs.0.clone());

        if dot.clone() < T::Scalar::zero() {
            rhs.0 = -rhs.0;
            dot = -dot;
        }

        if dot.clone() >= T::Scalar::one() {
            return self;
        }

        let theta = dot.acos();
        let scale_lhs = (theta.clone() * (T::Scalar::one() - amount.clone())).sin();
        let scale_rhs = (theta * amount).sin();

        Self::new_normalize(self.0 * scale_lhs + rhs.0 * scale_rhs)
    }
}

/// Convert a object to a unit object
pub trait IntoUnit: Sized {
    fn into_unit(self) -> Unit<Self>;
}

impl<T> IntoUnit for T
where
    T: RealInnerSpace + VectorSpace,
    T::Scalar: Real + One,
{
    fn into_unit(self) -> Unit<Self> {
        Unit::new_normalize(self)
    }
}

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

    type Vector1<T> = Vector<T, 1>;

    /*
    #[test]
    fn test_permutation() {
        let p1 = Permutation::unit();
        let p2 = Permutation([0usize, 1, 2]);
        let p3 = Permutation([1usize, 2, 0]);
        let v = vector!(1.0f64, 2.0, 3.0);
        assert_eq!(p1, p2);
        assert_eq!(v, p3 * (p3 * (p3 * v)));
    }

    #[test]
    fn permutation_parity() {
        let p1 = Permutation::<4>::unit();
        let p2 = Permutation([3usize, 1, 2, 0]);
        let p3 = Permutation([2usize, 3, 1, 0]);
        assert!(!p1.odd_parity());
        assert!(p2.odd_parity());
        assert!(p3.odd_parity());
    }
    */

    #[test]
    fn vec_zero() {
        let a = Vector3::<u32>::zero();
        assert_eq!(a, vector![0, 0, 0]);
    }

    #[test]
    fn vec_index() {
        let a = Vector1::<u32>::from([0]);
        assert_eq!(*a.x(), 0_u32);
        let mut b = Vector2::<u32>::from([1, 2]);
        *b.y_mut() += 3;
        assert_eq!(*b.y(), 5);
    }

    #[test]
    fn vec_eq() {
        let a = Vector1::<u32>::from([0]);
        let b = Vector1::<u32>::from([1]);
        let c = Vector1::<u32>::from([0]);
        let d = [[0u32]];
        assert_ne!(a, b);
        assert_eq!(a, c);
        assert_eq!(a, &d);
    }

    #[test]
    fn vec_addition() {
        let a = Vector1::<u32>::from([0]);
        let b = Vector1::<u32>::from([1]);
        let c = Vector1::<u32>::from([2]);
        assert_eq!(a + b, b);
        assert_eq!(b + b, c);
        // We shouldn't need to have to test more dimensions, but we shall test
        // one more.
        let a = Vector2::<u32>::from([0, 1]);
        let b = Vector2::<u32>::from([1, 2]);
        let c = Vector2::<u32>::from([1, 3]);
        let d = Vector2::<u32>::from([2, 5]);
        assert_eq!(a + b, c);
        assert_eq!(b + c, d);
        let mut c = Vector2::<u32>::from([1, 3]);
        let d = Vector2::<u32>::from([2, 5]);
        c += d;
        let e = Vector2::<u32>::from([3, 8]);
        assert_eq!(c, e);
    }

    #[test]
    fn vec_subtraction() {
        let mut a = Vector1::<u32>::from([3]);
        let b = Vector1::<u32>::from([1]);
        let c = Vector1::<u32>::from([2]);
        assert_eq!(a - c, b);
        a -= b;
        assert_eq!(a, c);
    }

    #[test]
    fn vec_negation() {
        let a = Vector4::<i32>::from([1, 2, 3, 4]);
        let b = Vector4::<i32>::from([-1, -2, -3, -4]);
        assert_eq!(-a, b);
    }

    #[test]
    fn vec_scale() {
        let a = Vector4::<f32>::from([2.0, 4.0, 2.0, 4.0]);
        let b = Vector4::<f32>::from([4.0, 8.0, 4.0, 8.0]);
        let c = Vector4::<f32>::from([1.0, 2.0, 1.0, 2.0]);
        assert_eq!(a * 2.0, b);
        assert_eq!(a / 2.0, c);
    }

    #[test]
    fn vec_cross() {
        let a = vector!(1isize, 2isize, 3isize);
        let b = vector!(4isize, 5isize, 6isize);
        let r = vector!(-3isize, 6isize, -3isize);
        assert_eq!(a.cross(b), r);
    }

    #[test]
    fn vec_distance() {
        let a = Vector1::<f32>::from([0.0]);
        let b = Vector1::<f32>::from([1.0]);
        assert_eq!(a.distance2(b), 1.0);
        let a = Vector1::<f32>::from([0.0]);
        let b = Vector1::<f32>::from([2.0]);
        assert_eq!(a.distance2(b), 4.0);
        assert_eq!(a.distance(b), 2.0);
        let a = Vector2::<f32>::from([0.0, 0.0]);
        let b = Vector2::<f32>::from([1.0, 1.0]);
        assert_eq!(a.distance2(b), 2.0);
    }

    #[test]
    fn vec_normalize() {
        let a = vector!(5.0);
        assert_eq!(a.magnitude(), 5.0);
        let a_norm = a.normalize();
        assert_eq!(a_norm, vector!(1.0));
    }

    #[test]
    fn vec_transpose() {
        let v = vector!(1i32, 2, 3, 4);
        let m = Matrix::<i32, 1, 4>::from([[1i32], [2], [3], [4]]);
        assert_eq!(v.transpose(), m);
    }

    #[test]
    fn from_fn() {
        let indices: Vector<usize, 10> = vector!(0usize, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        assert_eq!(Vector::<usize, 10>::from_fn(|i| i), indices);
    }

    #[test]
    fn decompose() {
        let a = matrix![[-1.0f64, 1.0], [2.0, 1.0]];
        let b = vector!(5.0f64, 2.0);
        let lu = a.lu().unwrap();

        assert_eq!(a * lu.solve(b), b);
    }

    #[test]
    fn vec_map() {
        let int = vector!(1i32, 0, 1, 1, 0, 1, 1, 0, 0, 0);
        let boolean = vector!(true, false, true, true, false, true, true, false, false, false);
        assert_eq!(int.map(|i| i != 0), boolean);
    }

    #[test]
    fn vec_from_iter() {
        let v = vec![1i32, 2, 3, 4];
        let vec = Vector::<i32, 4>::from_iter(v);
        assert_eq!(vec, vector![1i32, 2, 3, 4])
    }

    /*
    #[test]
    fn vec_into_iter() {
        let v = vector!(1i32, 2, 3, 4);
        let vec: Vec<_> = v.into_iter().collect();
        assert_eq!(vec, vec![1i32, 2, 3, 4])
    }
    */

    #[test]
    fn vec_indexed_map() {
        let boolean = vector!(true, false, true, true, false, true, true, false, false, false);
        let indices = vector!(0usize, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        assert_eq!(boolean.indexed_map(|i, _| i), indices);
    }

    // Does not compile.
    /*
    #[test]
    fn vec_first() {
        let a = Vector2::<i32>::from([ 1, 2 ]);
        let b = Vector3::<i32>::from([ 1, 2, 3 ]);
        let c = b.first::<2_usize>();
        assert_eq!(a, c);
    }
     */

    #[test]
    fn vec_linear_interpolate() {
        let v1 = vector!(0.0, 0.0, 0.0);
        let v2 = vector!(1.0, 2.0, 3.0);
        assert_eq!(v1.lerp(v2, 0.5), vector!(0.5, 1.0, 1.5));
    }

    #[test]
    fn mat_identity() {
        let unit = matrix![[1u32, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1],];
        assert_eq!(Matrix::<u32, 4, 4>::one(), unit);
    }

    #[test]
    fn mat_negation() {
        let neg_unit = matrix![
            [-1i32, 0, 0, 0],
            [0, -1, 0, 0],
            [0, 0, -1, 0],
            [0, 0, 0, -1],
        ];
        assert_eq!(-Matrix::<i32, 4, 4>::one(), neg_unit);
    }

    #[test]
    fn mat_add() {
        let a = matrix![[matrix![[1u32]]]];
        let b = matrix![[matrix![[10u32]]]];
        let c = matrix![[matrix![[11u32]]]];
        assert_eq!(a + b, c);
    }

    #[test]
    fn mat_scalar_mult() {
        let a = Matrix::<f32, 2, 2>::from([[0.0, 1.0], [0.0, 2.0]]);
        let b = Matrix::<f32, 2, 2>::from([[0.0, 2.0], [0.0, 4.0]]);
        assert_eq!(a * 2.0, b);
    }

    #[test]
    fn mat_mult() {
        let a = Matrix::<f32, 2, 2>::from([[0.0, 0.0], [1.0, 0.0]]);
        let b = Matrix::<f32, 2, 2>::from([[0.0, 1.0], [0.0, 0.0]]);
        assert_eq!(a * b, matrix![[1.0, 0.0], [0.0, 0.0],]);
        assert_eq!(b * a, matrix![[0.0, 0.0], [0.0, 1.0],]);
        // Basic example:
        let a: Matrix<usize, 1, 1> = matrix![[1]];
        let b: Matrix<usize, 1, 1> = matrix![[2]];
        let c: Matrix<usize, 1, 1> = matrix![[2]];
        assert_eq!(a * b, c);
        // Removing the type signature here caused the compiler to crash.
        // Since then I've been wary.
        let a = Matrix::<f32, 3, 3>::from([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
        let b = a;
        let c = a * b;
        assert_eq!(
            c,
            matrix![[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0],]
        );
        // Here is another random example I found online.
        let a: Matrix<i32, 3, 3> = matrix![[0, -3, 5], [6, 1, -4], [2, 3, -2],];
        let b: Matrix<i32, 3, 3> = matrix![[-1, 0, -3], [4, 5, 1], [2, 6, -2]];
        let c: Matrix<i32, 3, 3> = matrix![[-2, 15, -13], [-10, -19, -9], [6, 3, 1]];
        assert_eq!(a * b, c);
    }

    #[test]
    fn mat_index() {
        let m: Matrix<i32, 2, 2> = matrix![[0, 2], [1, 3],];
        assert_eq!(m[(0, 0)], 0);
        assert_eq!(m[0][0], 0);
        assert_eq!(m[(1, 0)], 1);
        assert_eq!(m[0][1], 1);
        assert_eq!(m[(0, 1)], 2);
        assert_eq!(m[1][0], 2);
        assert_eq!(m[(1, 1)], 3);
        assert_eq!(m[1][1], 3);
    }

    #[test]
    fn mat_transpose() {
        assert_eq!(
            Matrix::<i32, 1, 2>::from([[1], [2]]).transpose(),
            Matrix::<i32, 2, 1>::from([[1, 2]])
        );
        assert_eq!(
            matrix![[1, 2], [3, 4],].transpose(),
            matrix![[1, 3], [2, 4],]
        );
    }

    #[test]
    fn square_matrix() {
        let a: Matrix<i32, 3, 3> = matrix![[5, 0, 0], [0, 8, 12], [0, 0, 16],];
        let diag: Vector<i32, 3> = vector!(5, 8, 16);
        assert_eq!(a.diagonal(), diag);
    }

    #[test]
    fn readme_code() {
        let a = vector!(0u32, 1, 2, 3);
        assert_eq!(a, Vector::<u32, 4>::from([0u32, 1, 2, 3]));

        let b = Vector::<f32, 7>::from([0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
        let c = Vector::<f32, 7>::from([1.0f32, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) * 0.5;
        assert_eq!(
            b + c,
            Vector::<f32, 7>::from([0.5f32, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5])
        );

        let a = vector!(1i32, 1);
        let b = vector!(5i32, 5);
        assert_eq!(a.distance2(b), 32); // distance method not implemented.
        assert_eq!((b - a).magnitude2(), 32); // magnitude method not implemented.

        let a = vector!(1.0f32, 1.0);
        let b = vector!(5.0f32, 5.0);
        const CLOSE: f32 = 5.656854;
        assert_eq!(a.distance(b), CLOSE); // distance is implemented.
        assert_eq!((b - a).magnitude(), CLOSE); // magnitude is implemented.

        // Vector normalization is also supported for floating point scalars.
        assert_eq!(
            vector!(0.0f32, 20.0, 0.0).normalize(),
            vector!(0.0f32, 1.0, 0.0)
        );

        let _a = Matrix::<f32, 3, 3>::from([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
        let _b: Matrix<i32, 3, 3> = matrix![[0, -3, 5], [6, 1, -4], [2, 3, -2]];

        assert_eq!(
            matrix![[1i32, 0, 0,], [0, 2, 0], [0, 0, 3],].diagonal(),
            vector!(1i32, 2, 3)
        );

        assert_eq!(
            matrix![[1i32, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]].diagonal(),
            vector!(1i32, 2, 3, 4)
        );
    }

    #[test]
    fn mat_map() {
        let int = matrix![[1i32, 0], [1, 1], [0, 1], [1, 0], [0, 0]];
        let boolean = matrix![
            [true, false],
            [true, true],
            [false, true],
            [true, false],
            [false, false]
        ];
        assert_eq!(int.map(|i| i != 0), boolean);
    }

    #[test]
    fn mat_from_iter() {
        let v = vec![1i32, 2, 3, 4];
        let mat = Matrix::<i32, 2, 2>::from_iter(v);
        assert_eq!(mat, matrix![[1i32, 2], [3, 4]].transpose())
    }

    #[test]
    fn mat_invert() {
        assert!(Matrix2::<f64>::one().invert().unwrap() == Matrix2::<f64>::one());

        // Example taken from cgmath:

        let a: Matrix2<f64> = matrix![[1.0f64, 2.0f64], [3.0f64, 4.0f64],];
        let identity: Matrix2<f64> = Matrix2::<f64>::one();
        assert!(abs_diff_eq!(
            a.invert().unwrap(),
            matrix![[-2.0f64, 1.0f64], [1.5f64, -0.5f64]]
        ));

        assert!(abs_diff_eq!(
            a.invert().unwrap() * a,
            identity,
            epsilon = 0.1
        ));
        assert!(abs_diff_eq!(a * a.invert().unwrap(), identity));
        assert!(matrix![[0.0f64, 2.0f64], [0.0f64, 5.0f64]]
            .invert()
            .is_none());
    }

    #[test]
    fn mat_determinant() {
        assert_eq!(Matrix2::<f64>::one().determinant(), f64::one());
        /*
        assert_eq!(
            matrix![[3.0f64, 8.0f64], [4.0f64, 6.0f64]].invert().unwrap(),
            matrix![[3.0f64, 8.0f64], [4.0f64, 6.0f64]]
        );
        */
        assert_eq!(
            matrix![[3.0f64, 8.0f64], [4.0f64, 6.0f64]].determinant(),
            -14.0f64
        );
        assert_eq!(
            matrix![[-2.0f64, 1.0f64], [1.5f64, -0.5f64]].determinant(),
            -0.5f64
        );
        assert_eq!(
            matrix![[6.0f64, 1.0, 1.0], [4.0, -2.0, 5.0], [2.0, 8.0, 7.0]].determinant(),
            -306.0f64
        );
    }

    #[test]
    fn mat_swap() {
        let mut m = matrix![[1.0, 2.0], [3.0, 4.0]];
        m.swap_columns(0, 1);
        assert_eq!(m, matrix![[2.0, 1.0], [4.0, 3.0]]);
        let mut m = matrix![[1.0, 2.0], [3.0, 4.0]];
        m.swap_rows(0, 1);
        assert_eq!(m, matrix![[3.0, 4.0], [1.0, 2.0]]);
        let mut m = matrix![[1.0, 2.0], [3.0, 4.0]];
        m.swap_columns(0, 0);
        assert_eq!(m, matrix![[1.0, 2.0], [3.0, 4.0]]);
        m.swap_rows(0, 0);
        assert_eq!(m, matrix![[1.0, 2.0], [3.0, 4.0]]);
    }

    #[test]
    fn vec_macro_constructor() {
        let v: Vector<f32, 0> = vector![];
        assert!(v[0].is_empty());

        let v = vector![1];
        assert_eq!(1, *v.x());

        let v = vector![1, 2, 3, 4, 5, 6, 7, 8, 9, 10,];
        for i in 0..10 {
            assert_eq!(i + 1, v[0][i]);
        }
    }

    #[test]
    fn mat_macro_constructor() {
        let m: Matrix<f32, 0, 0> = matrix![];
        assert!(m.is_empty());

        let m = matrix![[1]];
        assert_eq!(1, m[0][0]);

        let m = matrix![[1, 2], [3, 4], [5, 6],];
        assert_eq!(m, Matrix::<u32, 3, 2>::from([[1, 3, 5], [2, 4, 6]]));
    }

    #[test]
    fn vec_swizzle() {
        let v: Vector<f32, 1> = Vector::<f32, 1>::from([1.0]);
        assert_eq!(1.0, *v.x());

        let v: Vector<f32, 2> = Vector::<f32, 2>::from([1.0, 2.0]);
        assert_eq!(1.0, *v.x());
        assert_eq!(2.0, *v.y());

        let v: Vector<f32, 3> = Vector::<f32, 3>::from([1.0, 2.0, 3.0]);
        assert_eq!(1.0, *v.x());
        assert_eq!(2.0, *v.y());
        assert_eq!(3.0, *v.z());

        let v: Vector<f32, 4> = Vector::<f32, 4>::from([1.0, 2.0, 3.0, 4.0]);
        assert_eq!(1.0, *v.x());
        assert_eq!(2.0, *v.y());
        assert_eq!(3.0, *v.z());
        assert_eq!(4.0, *v.w());

        let v: Vector<f32, 5> = Vector::<f32, 5>::from([1.0, 2.0, 3.0, 4.0, 5.0]);
        assert_eq!(1.0, *v.x());
        assert_eq!(2.0, *v.y());
        assert_eq!(3.0, *v.z());
        assert_eq!(4.0, *v.w());
    }

    #[test]
    fn vec_reflect() {
        // Incident straight on to the surface.
        let v = vector!(1, 0);
        let n = vector!(-1, 0);
        let r = v.reflect(n);
        assert_eq!(r, vector!(-1, 0));

        // Incident at 45 degree angle to the surface.
        let v = vector!(1, 1);
        let n = vector!(-1, 0);
        let r = v.reflect(n);
        assert_eq!(r, vector!(-1, 1));
    }

    #[test]
    fn rotation() {
        let rot = Orthonormal::<f32, 3>::from(Euler {
            x: 0.0,
            y: 0.0,
            z: core::f32::consts::FRAC_PI_2,
        });
        assert_eq!(*rot.rotate_vector(vector![1.0f32, 0.0, 0.0]).y(), 1.0);
        let v = vector![1.0f32, 0.0, 0.0];
        let q1 = Quaternion::from(Euler {
            x: 0.0,
            y: 0.0,
            z: core::f32::consts::FRAC_PI_2,
        });
        assert_eq!(*q1.rotate_vector(v).normalize().y(), 1.0);
    }
}

#[cfg(all(feature = "mint", test))]
mod mint_tests {
    use super::*;

    #[test]
    fn point2_roundtrip() {
        let alj1 = point![1, 2];
        let mint: mint::Point2<u32> = alj1.into();
        let alj2: Point<u32, 2> = mint.into();
        assert_eq!(alj1, alj2);
    }

    #[test]
    fn point3_roundtrip() {
        let alj1 = point![1, 2, 3];
        let mint: mint::Point3<u32> = alj1.into();
        let alj2: Point<u32, 3> = mint.into();
        assert_eq!(alj1, alj2);
    }

    #[test]
    fn vector2_roundtrip() {
        let alj1 = vector![1, 2];
        let mint: mint::Vector2<u32> = alj1.into();
        let alj2: Vector<u32, 2> = mint.into();
        assert_eq!(alj1, alj2);
    }

    #[test]
    fn vector3_roundtrip() {
        let alj1 = vector![1, 2, 3];
        let mint: mint::Vector3<u32> = alj1.into();
        let alj2: Vector<u32, 3> = mint.into();
        assert_eq!(alj1, alj2);
    }

    #[test]
    fn vector4_roundtrip() {
        let alj1 = vector![1, 2, 3, 4];
        let mint: mint::Vector4<u32> = alj1.into();
        let alj2: Vector<u32, 4> = mint.into();
        assert_eq!(alj1, alj2);
    }

    #[test]
    fn quaternion_roundtrip() {
        let alj1 = Quaternion::new(1, 2, 3, 4);
        let mint: mint::Quaternion<u32> = alj1.into();
        let alj2: Quaternion<u32> = mint.into();
        assert_eq!(alj1, alj2);
    }

    #[test]
    fn matrix2x2_roundtrip() {
        let alj1 = matrix![[1, 2], [3, 4]];
        let mint_col: mint::ColumnMatrix2<u32> = alj1.into();
        let mint_row: mint::RowMatrix2<u32> = alj1.into();
        let alj2: Matrix<u32, 2, 2> = mint_col.into();
        let alj3: Matrix<u32, 2, 2> = mint_row.into();
        assert_eq!(alj1, alj2);
        assert_eq!(alj1, alj3);
    }

    #[test]
    fn matrix3x2_roundtrip() {
        let alj1 = matrix![[1, 2], [3, 4], [5, 6]];
        let mint_col: mint::ColumnMatrix3x2<u32> = alj1.into();
        let mint_row: mint::RowMatrix3x2<u32> = alj1.into();
        let alj2: Matrix<u32, 3, 2> = mint_col.into();
        let alj3: Matrix<u32, 3, 2> = mint_row.into();
        assert_eq!(alj1, alj2);
        assert_eq!(alj1, alj3);
    }

    #[test]
    fn matrix3x4_roundtrip() {
        let alj1 = matrix![[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
        let mint_col: mint::ColumnMatrix3x4<u32> = alj1.into();
        let mint_row: mint::RowMatrix3x4<u32> = alj1.into();
        let alj2: Matrix<u32, 3, 4> = mint_col.into();
        let alj3: Matrix<u32, 3, 4> = mint_row.into();
        assert_eq!(alj1, alj2);
        assert_eq!(alj1, alj3);
    }
}