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
//! Rotations matrices.

#![allow(missing_docs)]

use std::ops::{Mul, Neg, Index};
use rand::{Rand, Rng};
use num::{Zero, One};
use traits::geometry::{Rotate, Rotation, AbsoluteRotate, RotationMatrix, RotationTo, Transform,
                       ToHomogeneous, Norm, Cross};
use traits::structure::{Cast, Dim, Row, Col, BaseFloat, BaseNum, Eye, Diag};
use traits::operations::{Absolute, Inv, Transpose, ApproxEq};
use structs::vec::{Vec1, Vec2, Vec3, Vec4};
use structs::pnt::{Pnt2, Pnt3, Pnt4};
use structs::mat::{Mat2, Mat3, Mat4, Mat5};
#[cfg(feature="arbitrary")]
use quickcheck::{Arbitrary, Gen};


/// Two dimensional rotation matrix.
#[repr(C)]
#[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Hash, Copy)]
pub struct Rot2<N> {
    submat: Mat2<N>
}

impl<N: Clone + BaseFloat + Neg<Output = N>> Rot2<N> {
    /// Builds a 2 dimensional rotation matrix from an angle in radian.
    pub fn new(angle: Vec1<N>) -> Rot2<N> {
        let (sia, coa) = angle.x.sin_cos();

        Rot2 {
            submat: Mat2::new(coa.clone(), -sia, sia, coa)
        }
    }
}

impl<N: BaseFloat + Clone> Rotation<Vec1<N>> for Rot2<N> {
    #[inline]
    fn rotation(&self) -> Vec1<N> {
        Vec1::new((-self.submat.m12).atan2(self.submat.m11.clone()))
    }

    #[inline]
    fn inv_rotation(&self) -> Vec1<N> {
        -self.rotation()
    }

    #[inline]
    fn append_rotation_mut(&mut self, rot: &Vec1<N>) {
        *self = Rotation::append_rotation(self, rot)
    }

    #[inline]
    fn append_rotation(&self, rot: &Vec1<N>) -> Rot2<N> {
        Rot2::new(rot.clone()) * *self
    }

    #[inline]
    fn prepend_rotation_mut(&mut self, rot: &Vec1<N>) {
        *self = Rotation::prepend_rotation(self, rot)
    }

    #[inline]
    fn prepend_rotation(&self, rot: &Vec1<N>) -> Rot2<N> {
        *self * Rot2::new(rot.clone())
    }

    #[inline]
    fn set_rotation(&mut self, rot: Vec1<N>) {
        *self = Rot2::new(rot)
    }
}

impl<N: BaseFloat> RotationTo for Rot2<N> {
    type AngleType = N;
    type DeltaRotationType = Rot2<N>;

    #[inline]
    fn angle_to(&self, other: &Self) -> N {
        self.rotation_to(other).rotation().norm()
    }

    #[inline]
    fn rotation_to(&self, other: &Self) -> Rot2<N> {
        *other * ::inv(self).unwrap()
    }
}

impl<N: Rand + BaseFloat> Rand for Rot2<N> {
    #[inline]
    fn rand<R: Rng>(rng: &mut R) -> Rot2<N> {
        Rot2::new(rng.gen())
    }
}

impl<N: BaseFloat> AbsoluteRotate<Vec2<N>> for Rot2<N> {
    #[inline]
    fn absolute_rotate(&self, v: &Vec2<N>) -> Vec2<N> {
        // the matrix is skew-symetric, so we dont need to compute the absolute value of every
        // component.
        let m11 = ::abs(&self.submat.m11);
        let m12 = ::abs(&self.submat.m12);
        let m22 = ::abs(&self.submat.m22);

        Vec2::new(m11 * v.x + m12 * v.y, m12 * v.x + m22 * v.y)
    }
}

#[cfg(feature="arbitrary")]
impl<N: Arbitrary + Clone + BaseFloat + Neg<Output = N>> Arbitrary for Rot2<N> {
    fn arbitrary<G: Gen>(g: &mut G) -> Rot2<N> {
        Rot2::new(Arbitrary::arbitrary(g))
    }
}


/*
 * 3d rotation
 */
/// Three dimensional rotation matrix.
#[repr(C)]
#[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Hash, Copy)]
pub struct Rot3<N> {
    submat: Mat3<N>
}


impl<N: Clone + BaseFloat> Rot3<N> {
    /// Builds a 3 dimensional rotation matrix from an axis and an angle.
    ///
    /// # Arguments
    ///   * `axisangle` - A vector representing the rotation. Its magnitude is the amount of rotation
    ///   in radian. Its direction is the axis of rotation.
    pub fn new(axisangle: Vec3<N>) -> Rot3<N> {
        if ::is_zero(&Norm::sqnorm(&axisangle)) {
            ::one()
        }
        else {
            let mut axis   = axisangle;
            let angle      = axis.normalize_mut();
            let _1: N      = ::one();
            let ux         = axis.x.clone();
            let uy         = axis.y.clone();
            let uz         = axis.z.clone();
            let sqx        = ux * ux;
            let sqy        = uy * uy;
            let sqz        = uz * uz;
            let (sin, cos) = angle.sin_cos();
            let one_m_cos  = _1 - cos;

            Rot3 {
                submat: Mat3::new(
                            (sqx + (_1 - sqx) * cos),
                            (ux * uy * one_m_cos - uz * sin),
                            (ux * uz * one_m_cos + uy * sin),

                            (ux * uy * one_m_cos + uz * sin),
                            (sqy + (_1 - sqy) * cos),
                            (uy * uz * one_m_cos - ux * sin),

                            (ux * uz * one_m_cos - uy * sin),
                            (uy * uz * one_m_cos + ux * sin),
                            (sqz + (_1 - sqz) * cos))
            }
        }
    }

    /// Builds a rotation matrix from an orthogonal matrix.
    ///
    /// This is unsafe because the orthogonality of `mat` is not checked.
    pub unsafe fn new_with_mat(mat: Mat3<N>) -> Rot3<N> {
        Rot3 {
            submat: mat
        }
    }

    /// Creates a new rotation from Euler angles.
    ///
    /// The primitive rotations are applied in order: 1 roll − 2 pitch − 3 yaw.
    pub fn new_with_euler_angles(roll: N, pitch: N, yaw: N) -> Rot3<N> {
        let (sr, cr) = roll.sin_cos();
        let (sp, cp) = pitch.sin_cos();
        let (sy, cy) = yaw.sin_cos();

        unsafe {
            Rot3::new_with_mat(
                Mat3::new(
                    cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr,
                    sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr,
                    -sp,     cp * sr,                cp * cr
                )
            )
        }
    }
}

impl<N: Clone + BaseFloat> Rot3<N> {
    /// Reorient this matrix such that its local `x` axis points to a given point. Note that the
    /// usually known `look_at` function does the same thing but with the `z` axis. See `look_at_z`
    /// for that.
    ///
    /// # Arguments
    ///   * at - The point to look at. It is also the direction the matrix `x` axis will be aligned
    ///   with
    ///   * up - Vector pointing `up`. The only requirement of this parameter is to not be colinear
    ///   with `at`. Non-colinearity is not checked.
    pub fn look_at(&mut self, at: &Vec3<N>, up: &Vec3<N>) {
        let xaxis = Norm::normalize(at);
        let zaxis = Norm::normalize(&Cross::cross(up, &xaxis));
        let yaxis = Cross::cross(&zaxis, &xaxis);

        self.submat = Mat3::new(
            xaxis.x.clone(), yaxis.x.clone(), zaxis.x.clone(),
            xaxis.y.clone(), yaxis.y.clone(), zaxis.y.clone(),
            xaxis.z        , yaxis.z        , zaxis.z)
    }

    /// Reorient this matrix such that its local `z` axis points to a given point.
    ///
    /// # Arguments
    ///   * at - The look direction, that is, direction the matrix `y` axis will be aligned with
    ///   * up - Vector pointing `up`. The only requirement of this parameter is to not be colinear
    ///   with `at`. Non-colinearity is not checked.
    pub fn look_at_z(&mut self, at: &Vec3<N>, up: &Vec3<N>) {
        let zaxis = Norm::normalize(at);
        let xaxis = Norm::normalize(&Cross::cross(up, &zaxis));
        let yaxis = Cross::cross(&zaxis, &xaxis);

        self.submat = Mat3::new(
            xaxis.x.clone(), yaxis.x.clone(), zaxis.x.clone(),
            xaxis.y.clone(), yaxis.y.clone(), zaxis.y.clone(),
            xaxis.z        , yaxis.z        , zaxis.z)
    }
}

impl<N: Clone + BaseFloat + Cast<f64>>
Rotation<Vec3<N>> for Rot3<N> {
    #[inline]
    fn rotation(&self) -> Vec3<N> {
        let angle = ((self.submat.m11 + self.submat.m22 + self.submat.m33 - ::one()) / Cast::from(2.0)).acos();

        if angle != angle {
            // FIXME: handle that correctly
            ::zero()
        }
        else if ::is_zero(&angle) {
            ::zero()
        }
        else {
            let m32_m23 = self.submat.m32 - self.submat.m23;
            let m13_m31 = self.submat.m13 - self.submat.m31;
            let m21_m12 = self.submat.m21 - self.submat.m12;

            let denom = (m32_m23 * m32_m23 + m13_m31 * m13_m31 + m21_m12 * m21_m12).sqrt();

            if ::is_zero(&denom) {
                // XXX: handle that properly
                // panic!("Internal error: singularity.")
                ::zero()
            }
            else {
                let a_d = angle / denom;

                Vec3::new(m32_m23 * a_d, m13_m31 * a_d, m21_m12 * a_d)
            }
        }
    }

    #[inline]
    fn inv_rotation(&self) -> Vec3<N> {
        -self.rotation()
    }


    #[inline]
    fn append_rotation_mut(&mut self, rot: &Vec3<N>) {
        *self = Rotation::append_rotation(self, rot)
    }

    #[inline]
    fn append_rotation(&self, axisangle: &Vec3<N>) -> Rot3<N> {
        Rot3::new(axisangle.clone()) * *self
    }

    #[inline]
    fn prepend_rotation_mut(&mut self, rot: &Vec3<N>) {
        *self = Rotation::prepend_rotation(self, rot)
    }

    #[inline]
    fn prepend_rotation(&self, axisangle: &Vec3<N>) -> Rot3<N> {
        *self * Rot3::new(axisangle.clone())
    }

    #[inline]
    fn set_rotation(&mut self, axisangle: Vec3<N>) {
        *self = Rot3::new(axisangle)
    }
}

impl<N: BaseFloat> RotationTo for Rot3<N> {
    type AngleType = N;
    type DeltaRotationType = Rot3<N>;

    #[inline]
    fn angle_to(&self, other: &Self) -> N {
        // FIXME: refactor to avoid the normalization of the rotation axisangle vector.
        self.rotation_to(other).rotation().norm()
    }

    #[inline]
    fn rotation_to(&self, other: &Self) -> Rot3<N> {
        *other * ::inv(self).unwrap()
    }
}

impl<N: Clone + Rand + BaseFloat> Rand for Rot3<N> {
    #[inline]
    fn rand<R: Rng>(rng: &mut R) -> Rot3<N> {
        Rot3::new(rng.gen())
    }
}

impl<N: BaseFloat> AbsoluteRotate<Vec3<N>> for Rot3<N> {
    #[inline]
    fn absolute_rotate(&self, v: &Vec3<N>) -> Vec3<N> {
        Vec3::new(
            ::abs(&self.submat.m11) * v.x + ::abs(&self.submat.m12) * v.y + ::abs(&self.submat.m13) * v.z,
            ::abs(&self.submat.m21) * v.x + ::abs(&self.submat.m22) * v.y + ::abs(&self.submat.m23) * v.z,
            ::abs(&self.submat.m31) * v.x + ::abs(&self.submat.m32) * v.y + ::abs(&self.submat.m33) * v.z)
    }
}

#[cfg(feature="arbitrary")]
impl<N: Arbitrary + Clone + BaseFloat> Arbitrary for Rot3<N> {
    fn arbitrary<G: Gen>(g: &mut G) -> Rot3<N> {
        Rot3::new(Arbitrary::arbitrary(g))
    }
}


/// Four dimensional rotation matrix.
#[repr(C)]
#[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Hash, Copy)]
pub struct Rot4<N> {
    submat: Mat4<N>
}

// impl<N> Rot4<N> {
//     pub fn new(left_iso: Quat<N>, right_iso: Quat<N>) -> Rot4<N> {
//         assert!(left_iso.is_unit());
//         assert!(right_iso.is_unright);
//
//         let mat_left_iso = Mat4::new(
//             left_iso.x, -left_iso.y, -left_iso.z, -left_iso.w,
//             left_iso.y,  left_iso.x, -left_iso.w,  left_iso.z,
//             left_iso.z,  left_iso.w,  left_iso.x, -left_iso.y,
//             left_iso.w, -left_iso.z,  left_iso.y,  left_iso.x);
//         let mat_right_iso = Mat4::new(
//             right_iso.x, -right_iso.y, -right_iso.z, -right_iso.w,
//             right_iso.y,  right_iso.x,  right_iso.w, -right_iso.z,
//             right_iso.z, -right_iso.w,  right_iso.x,  right_iso.y,
//             right_iso.w,  right_iso.z, -right_iso.y,  right_iso.x);
//
//         Rot4 {
//             submat: mat_left_iso * mat_right_iso
//         }
//     }
// }

impl<N: BaseFloat> AbsoluteRotate<Vec4<N>> for Rot4<N> {
    #[inline]
    fn absolute_rotate(&self, v: &Vec4<N>) -> Vec4<N> {
        Vec4::new(
            ::abs(&self.submat.m11) * v.x + ::abs(&self.submat.m12) * v.y +
            ::abs(&self.submat.m13) * v.z + ::abs(&self.submat.m14) * v.w,

            ::abs(&self.submat.m21) * v.x + ::abs(&self.submat.m22) * v.y +
            ::abs(&self.submat.m23) * v.z + ::abs(&self.submat.m24) * v.w,

            ::abs(&self.submat.m31) * v.x + ::abs(&self.submat.m32) * v.y +
            ::abs(&self.submat.m33) * v.z + ::abs(&self.submat.m34) * v.w,

            ::abs(&self.submat.m41) * v.x + ::abs(&self.submat.m42) * v.y +
            ::abs(&self.submat.m43) * v.z + ::abs(&self.submat.m44) * v.w)
    }
}

impl<N: BaseFloat + Clone>
Rotation<Vec4<N>> for Rot4<N> {
    #[inline]
    fn rotation(&self) -> Vec4<N> {
        panic!("Not yet implemented")
    }

    #[inline]
    fn inv_rotation(&self) -> Vec4<N> {
        panic!("Not yet implemented")
    }

    #[inline]
    fn append_rotation_mut(&mut self, _: &Vec4<N>) {
        panic!("Not yet implemented")
    }

    #[inline]
    fn append_rotation(&self, _: &Vec4<N>) -> Rot4<N> {
        panic!("Not yet implemented")
    }

    #[inline]
    fn prepend_rotation_mut(&mut self, _: &Vec4<N>) {
        panic!("Not yet implemented")
    }

    #[inline]
    fn prepend_rotation(&self, _: &Vec4<N>) -> Rot4<N> {
        panic!("Not yet implemented")
    }

    #[inline]
    fn set_rotation(&mut self, _: Vec4<N>) {
        panic!("Not yet implemented")
    }
}


/*
 * Common implementations.
 */

submat_impl!(Rot2, Mat2);
rotate_impl!(Rot2, Vec2, Pnt2);
transform_impl!(Rot2, Vec2, Pnt2);
dim_impl!(Rot2, 2);
rot_mul_rot_impl!(Rot2);
rot_mul_vec_impl!(Rot2, Vec2);
vec_mul_rot_impl!(Rot2, Vec2);
rot_mul_pnt_impl!(Rot2, Pnt2);
pnt_mul_rot_impl!(Rot2, Pnt2);
one_impl!(Rot2);
eye_impl!(Rot2);
rotation_matrix_impl!(Rot2, Vec2, Vec1);
col_impl!(Rot2, Vec2);
row_impl!(Rot2, Vec2);
index_impl!(Rot2);
absolute_impl!(Rot2, Mat2);
to_homogeneous_impl!(Rot2, Mat3);
inv_impl!(Rot2);
transpose_impl!(Rot2);
approx_eq_impl!(Rot2);
diag_impl!(Rot2, Vec2);

submat_impl!(Rot3, Mat3);
rotate_impl!(Rot3, Vec3, Pnt3);
transform_impl!(Rot3, Vec3, Pnt3);
dim_impl!(Rot3, 3);
rot_mul_rot_impl!(Rot3);
rot_mul_vec_impl!(Rot3, Vec3);
vec_mul_rot_impl!(Rot3, Vec3);
rot_mul_pnt_impl!(Rot3, Pnt3);
pnt_mul_rot_impl!(Rot3, Pnt3);
one_impl!(Rot3);
eye_impl!(Rot3);
rotation_matrix_impl!(Rot3, Vec3, Vec3);
col_impl!(Rot3, Vec3);
row_impl!(Rot3, Vec3);
index_impl!(Rot3);
absolute_impl!(Rot3, Mat3);
to_homogeneous_impl!(Rot3, Mat4);
inv_impl!(Rot3);
transpose_impl!(Rot3);
approx_eq_impl!(Rot3);
diag_impl!(Rot3, Vec3);

submat_impl!(Rot4, Mat4);
rotate_impl!(Rot4, Vec4, Pnt4);
transform_impl!(Rot4, Vec4, Pnt4);
dim_impl!(Rot4, 4);
rot_mul_rot_impl!(Rot4);
rot_mul_vec_impl!(Rot4, Vec4);
vec_mul_rot_impl!(Rot4, Vec4);
rot_mul_pnt_impl!(Rot4, Pnt4);
pnt_mul_rot_impl!(Rot4, Pnt4);
one_impl!(Rot4);
eye_impl!(Rot4);
rotation_matrix_impl!(Rot4, Vec4, Vec4);
col_impl!(Rot4, Vec4);
row_impl!(Rot4, Vec4);
index_impl!(Rot4);
absolute_impl!(Rot4, Mat4);
to_homogeneous_impl!(Rot4, Mat5);
inv_impl!(Rot4);
transpose_impl!(Rot4);
approx_eq_impl!(Rot4);
diag_impl!(Rot4, Vec4);