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
use std::ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
use nalgebra::{
    SimdRealField, UnitQuaternion, Vector3, Quaternion, convert, RealField, zero, one, Point3,
    Matrix4, Matrix3, Rotation3,
};
use num_traits::{Zero, One};
#[cfg(feature="serde_derive")]
use serde_derive::{Serialize, Deserialize};

#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde_derive", derive(Serialize, Deserialize))]
pub struct Dual<T> {
    pub r: T,
    pub d: T,
}

impl<T> Add for Dual<T>
where T: Add<Output = T>
{
    type Output = Dual<T>;
    fn add(self, rhs: Dual<T>) -> Dual<T> {
        Dual { r: self.r + rhs.r, d: self.d + rhs.d}
    }
}

impl<T> AddAssign for Dual<T>
where T: Add<Output = T> + Copy
{
    fn add_assign(&mut self, rhs: Dual<T>) {
        *self = *self + rhs
    }
}

impl<T> Sub for Dual<T>
where T: Sub<Output = T>
{
    type Output = Self;
    fn sub(self, other: Self) -> Self {
        Dual{ r: self.r - other.r, d: self.d - other.d }
    }
}

impl<T> SubAssign for Dual<T>
where T: Sub<Output = T> + Copy
{
    fn sub_assign(&mut self, rhs: Dual<T>) {
        *self = *self - rhs
    }
}

impl<T> Mul for Dual<T>
where T: Add<Output = T> + Mul<Output = T> + Copy
{
    type Output = Dual<T>;
    fn mul(self, rhs: Dual<T>) -> Dual<T> {
        Dual {
            r: self.r * rhs.r,
            d: self.r * rhs.d + rhs.r * self.d
        }
    }
}

impl<T> MulAssign for Dual<T>
where T: Add<Output = T> + Mul<Output = T> + Copy
{
    fn mul_assign(&mut self, rhs: Dual<T>) {
        *self = *self * rhs
    }
}

impl<T> Mul<T> for Dual<T>
where T: Mul<Output = T> + Copy
{
    type Output = Dual<T>;
    fn mul(self, rhs: T) -> Dual<T> {
        Dual {
            r: self.r * rhs,
            d: rhs * self.d
        }
    }
}

impl<T> MulAssign<T> for Dual<T>
where T: Mul<Output = T> + Copy
{
    fn mul_assign(&mut self, rhs: T) {
        *self = *self * rhs
    }
}

impl<T> Div for Dual<T>
where T: Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Copy
{
    type Output = Dual<T>;
    fn div(self, rhs: Dual<T>) -> Dual<T>
    {
        Dual {
            r: self.r / rhs.r,
            d: (rhs.r * self.d - self.r * rhs.d) / (rhs.r * rhs.r)
        }
    }
}

impl<T> DivAssign for Dual<T>
where T: Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Copy
{
    fn div_assign(&mut self, rhs: Dual<T>) {
        *self = *self / rhs
    }
}

impl<T> Div<T> for Dual<T>
where T: Mul<Output = T> + Div<Output = T> + Copy
{
    type Output = Dual<T>;
    fn div(self, rhs: T) -> Dual<T> {
        Dual {
            r: self.r / rhs,
            d: (rhs * self.d) / (rhs * rhs)
        }
    }
}

impl<T> DivAssign<T> for Dual<T>
where T: Mul<Output = T> + Div<Output = T> + Copy
{
    fn div_assign(&mut self, rhs: T) {
        *self = *self / rhs
    }
}

impl<T> Dual<T> {
    pub fn new(r: T, d: T) -> Dual<T> {
        Dual { r, d }
    }
}

impl<T> Dual<T>
where T: RealField
{
    pub fn sqrt(&self) -> Dual<T> {
        let r = self.r.sqrt();
        Dual {
            r,
            d: self.d * convert(0.5) / r,
        }
    }
}

pub type DualQuaternion<T> = Dual<Quaternion<T>>;

impl<T> DualQuaternion<T>
where
    T: SimdRealField + Mul<Output = T> + Div<Output = T> + Copy,
    T::Element: SimdRealField
{
    #[inline]
    pub fn rigid_transformation(q: UnitQuaternion<T>, t: Vector3<T>) -> DualQuaternion<T> {
        Dual { r: *q, d: Quaternion::from_imag(t).half() * *q }
    }

    #[inline]
    pub fn from_real(v: T) -> DualQuaternion<T> {
        Dual{ r: Quaternion::from_real(v), d: zero() }
    }

    #[inline]
    pub fn conjugate(&self) -> DualQuaternion<T> {
        Dual{ r: self.r.conjugate(), d: self.d.conjugate() }
    }

    #[inline]
    pub fn norm_squared(&self) -> Dual<T> {
        Dual { r: self.r.norm_squared(), d: convert::<_,T>(2.) * self.r.dot(&self.d) }
    }

    #[inline]
    pub fn norm(&self) -> Dual<T> {
        Dual { r: self.r.norm(), d: (convert::<_,T>(2.) * self.r.dot(&self.d)).simd_sqrt() }
    }

    #[inline]
    pub fn magnitude(&self) -> Dual<T> {
        self.norm()
    }

    // #[inline]
    // pub fn dot(&self, other: &Self) -> T {
    //     self.r.dot(&other.r)
    // }

    #[inline]
    pub fn normalize(&self) -> DualQuaternion<T> {
        let norm = self.r.norm();
        Dual { r: self.r / norm, d: self.d / norm }
    }

    #[inline]
    pub fn squared(&self) -> DualQuaternion<T> {
        *self * *self
    }

    // #[inline]
    // pub fn scale(self) -> T {
    //     T::one() / self.r.norm_squared()
    // }

    // #[inline]
    // pub fn ln(self) -> DualQuaternion<T> {
    //     let d = (self.r.conjugate() * self.d) * self.scale();
    //     Self::new(self.r.ln(), d)
    // }

    // #[inline]
    // pub fn log(self, base: Self) -> Self {
    //     self.ln() / base.ln()
    // }

    // #[inline]
    // pub fn exp(&self) -> DualQuaternion<T> {
    //     let r = self.r.exp();
    //     Self::new(r, r * self.d)
    // }

    // #[inline]
    // pub fn slerp(&self, other: &DualQuaternion<T>, t: T) -> DualQuaternion<T> {
    //     (*other * self.conjugate()).pow(t) * *self
    // }

    // pub fn inverse(&self) -> Option<DualQuaternion<T>> {
    //     let n = self.r.norm_squared();
    //     if n != convert(0.) {
    //         Some(self.conjugate() * (convert::<_,T>(1.) / n))
    //     }else{
    //         None
    //     }
    // }

    #[inline]
    pub fn rotation(&self) -> UnitQuaternion<T> {
        UnitQuaternion::new_normalize(self.r)
    }

    #[inline]
    pub fn translation(self) -> Vector3<T> {
        let two = convert::<_,T>(2.);
        let normalized = self.normalize();
        let vr = normalized.r.vector();
        let vd = normalized.d.vector();
        (vd * normalized.r.w - vr * normalized.d.w + vr.cross(&vd)) * two
    }

    #[inline]
    pub fn transform(&self, v: &Point3<T>) -> Point3<T> {
        let two = convert::<_,T>(2.);
        let normalized = self.normalize();

        let vr = normalized.r.vector();
        let vd = normalized.d.vector();
        let trans = (vd * normalized.r.w - vr * normalized.d.w + vr.cross(&vd)) * two;
        UnitQuaternion::new_unchecked(normalized.r) * v + trans
    }

    #[inline]
    pub fn transform_normal(&self, n: &Vector3<T>) -> Vector3<T>{
        UnitQuaternion::from_quaternion(self.r) * n
    }

    pub fn transform_position_and_normal(&self, p: &Point3<T>, n: &Vector3<T>) -> (Point3<T>, Vector3<T>)
    {
        let two = convert::<_,T>(2.);
        let normalized = self.normalize();

        let vr = normalized.r.vector();
        let vd = normalized.d.vector();
        let trans = (vd * normalized.r.w - vr * normalized.d.w + vr.cross(&vd)) * two;
        let rot = UnitQuaternion::new_unchecked(normalized.r);
        let pp = rot * p + trans;
        let np = rot * n;
        (pp, np)
    }
}

impl<N: SimdRealField> Zero for DualQuaternion<N>
where N::Element: SimdRealField
{
    #[inline]
    fn zero() -> Self {
        Self::new(Quaternion::zero(), Quaternion::zero())
    }

    #[inline]
    fn is_zero(&self) -> bool {
        self.r.is_zero() && self.d.is_zero()
    }
}

impl<N: SimdRealField> One for DualQuaternion<N>
where N::Element: SimdRealField
{
    #[inline]
    fn one() -> Self {
        Self::new(one(), zero())
    }
}

impl<N: SimdRealField> Mul<N> for DualQuaternion<N>
where N::Element: SimdRealField
{
    type Output = Self;

    #[inline]
    fn mul(self, other: N) -> Self {
        Dual{ r: self.r * other, d: self.d * other }
    }
}

impl<N: SimdRealField> MulAssign<N> for DualQuaternion<N>
where N::Element: SimdRealField
{
    #[inline]
    fn mul_assign(&mut self, other: N) {
        *self = *self * other
    }
}

// impl<T: SimdRealField> Div for DualQuaternion<T> {
//     type Output = DualQuaternion<T>;
//     fn div(self, rhs: DualQuaternion<T>) -> DualQuaternion<T>
//     {
//         Dual {
//             r: self.r.right_div(&rhs.r).unwrap(),
//             d: (rhs.r * self.d - self.r * rhs.d) * (rhs.r * rhs.r).try_inverse().unwrap(),
//         }
//     }
// }

impl<N: SimdRealField> Div<N> for DualQuaternion<N>
where N::Element: SimdRealField
{
    type Output = Self;

    #[inline]
    fn div(self, other: N) -> Self {
        Dual{ r: self.r / other, d: self.d / other }
    }
}

impl<N: SimdRealField> DivAssign<N> for DualQuaternion<N>
where N::Element: SimdRealField
{
    #[inline]
    fn div_assign(&mut self, other: N) {
        *self = *self / other
    }
}

impl<N: RealField> From<Matrix4<N>> for DualQuaternion<N> {
    fn from(matrix: Matrix4<N>) -> Self {
        let t = matrix.column(3).xyz();
        let rot = Matrix3::from_columns(&[
            matrix.column(0).xyz(),
            matrix.column(1).xyz(),
            matrix.column(2).xyz(),
        ]);
        let rot = Rotation3::from_matrix(&rot);
        let q = UnitQuaternion::from_rotation_matrix(&rot);
        DualQuaternion::rigid_transformation(q, t)
    }
}

#[test]
fn test() {
    use nalgebra::{Translation3, Isometry3};

    let v = Point3::new(1., 0., 0.);
    let q = DualQuaternion::rigid_transformation(
        UnitQuaternion::identity(),
        Vector3::new(2., 0., 0.)
    );
    let t = q.transform(&v);
    assert_eq!(t, Point3::new(3., 0., 0.));


    let v = Point3::new(1., 0., 0.);
    let q = DualQuaternion::rigid_transformation(
        UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 90f64.to_radians()),
        Vector3::new(0., 0., 0.)
    );
    let t1 = q.transform(&v);
    let t2 = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 90f64.to_radians()) * v;
    assert_eq!(t1, t2);


    let v = Point3::new(1., 0., 0.);
    let q = DualQuaternion::rigid_transformation(
        UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 90f64.to_radians()),
        Vector3::new(2., 0., 0.)
    );
    let t1 = q.transform(&v);
    let r = Isometry3::from_parts(
        Translation3::new(2., 0., 0.),
        UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 90f64.to_radians())
    );
    let t2 = r.transform_point(&v);
    assert_eq!(t1, t2);
}