glamx 0.2.0

Extensions for glam: Pose2, Pose3, Rot2, and matrix utilities.
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
//! 3D pose types for rigid body transformations.

use crate::rot3::{DRot3, Rot3};
use core::ops::{Mul, MulAssign};

/// Macro to generate a 3D pose type for a specific scalar type.
macro_rules! impl_pose3 {
    ($Pose3:ident, $Rot3:ident, $Real:ty, $Vec3:ty, $Mat4: ty $(, $Padding: ty, $bytemuck: ident)?) => {
        #[doc = concat!("A 3D pose (rotation + translation), representing a rigid body transformation (", stringify!($Real), " precision).")]
        #[derive(Copy, Clone, Debug, PartialEq)]
        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
        #[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
        $(#[cfg_attr(feature = "bytemuck", derive($bytemuck::Pod, $bytemuck::Zeroable))])*
        #[repr(C)]
        pub struct $Pose3 {
            /// The rotational part of the pose.
            pub rotation: $Rot3,
            /// The translational part of the pose.
            pub translation: $Vec3,
            $(
            /// Explicit padding for compatibility with bytemuck and targets like spirv.
            ///
            /// Can have any value as it is never read from or written to.
            pub padding: $Padding,
            )*
        }

        impl $Pose3 {
            /// The identity pose (no rotation, no translation).
            pub const IDENTITY: Self = Self {
                rotation: $Rot3::IDENTITY,
                translation: <$Vec3>::ZERO,
                $(padding: 0 as $Padding,)*
            };

            /// Creates the identity pose.
            #[inline]
            pub fn identity() -> Self {
                Self::IDENTITY
            }

            /// Creates a pose from a translation vector.
            #[inline]
            pub fn from_translation(translation: $Vec3) -> Self {
                Self {
                    rotation: $Rot3::IDENTITY,
                    translation,
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Creates a pose from translation components.
            #[inline]
            pub fn translation(x: $Real, y: $Real, z: $Real) -> Self {
                Self::from_translation(<$Vec3>::new(x, y, z))
            }

            /// Creates a pose from a rotation.
            #[inline]
            pub fn from_rotation(rotation: $Rot3) -> Self {
                Self {
                    rotation,
                    translation: <$Vec3>::ZERO,
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Creates a pose from translation and rotation parts.
            #[inline]
            pub fn from_parts(translation: $Vec3, rotation: $Rot3) -> Self {
                Self {
                    rotation,
                    translation,
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Creates a pose from translation and axis-angle rotation.
            #[inline]
            pub fn new(translation: $Vec3, axisangle: $Vec3) -> Self {
                let rotation = $Rot3::from_scaled_axis(axisangle.into());
                Self {
                    rotation,
                    translation,
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Creates a pose from axis-angle rotation only (no translation).
            #[inline]
            pub fn rotation(axisangle: $Vec3) -> Self {
                Self {
                    rotation: $Rot3::from_scaled_axis(axisangle.into()),
                    translation: <$Vec3>::ZERO,
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Prepends a translation to this pose (applies translation in local frame).
            #[inline]
            pub fn prepend_translation(self, translation: $Vec3) -> Self {
                Self {
                    rotation: self.rotation,
                    translation: self.translation + self.rotation * translation,
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Appends a translation to this pose (applies translation in world frame).
            #[inline]
            pub fn append_translation(self, translation: $Vec3) -> Self {
                Self {
                    rotation: self.rotation,
                    translation: self.translation + translation,
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Returns the inverse of this pose.
            #[inline]
            pub fn inverse(&self) -> Self {
                let inv_rot = self.rotation.inverse();
                Self {
                    rotation: inv_rot,
                    translation: inv_rot * (-self.translation),
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Computes `self.inverse() * rhs`.
            #[inline]
            pub fn inv_mul(&self, rhs: &Self) -> Self {
                let inv_rot1 = self.rotation.inverse();
                let tr_12 = rhs.translation - self.translation;
                $Pose3 {
                    translation: inv_rot1 * tr_12,
                    rotation: inv_rot1 * rhs.rotation,
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Transforms a 3D point by this pose.
            ///
            /// This applies both the rotation and translation.
            #[inline]
            pub fn transform_point(&self, p: $Vec3) -> $Vec3 {
                self.rotation * p + self.translation
            }

            /// Transforms a 3D vector by this pose.
            ///
            /// This applies only the rotation (ignores translation).
            #[inline]
            pub fn transform_vector(&self, v: $Vec3) -> $Vec3 {
                self.rotation * v
            }

            /// Transforms a point by the inverse of this pose.
            #[inline]
            pub fn inverse_transform_point(&self, p: $Vec3) -> $Vec3 {
                self.rotation.inverse() * (p - self.translation)
            }

            /// Transforms a vector by the inverse of this pose.
            #[inline]
            pub fn inverse_transform_vector(&self, v: $Vec3) -> $Vec3 {
                self.rotation.inverse() * v
            }

            /// Linearly interpolates between two poses.
            ///
            /// Uses spherical linear interpolation for the rotation part.
            #[inline]
            pub fn lerp(&self, other: &Self, t: $Real) -> Self {
                Self {
                    rotation: self.rotation.slerp(other.rotation, t),
                    translation: self.translation.lerp(other.translation, t),
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Returns `true` if, and only if, all elements are finite.
            #[inline]
            pub fn is_finite(&self) -> bool {
                self.rotation.is_finite() && self.translation.is_finite()
            }

            /// Returns `true` if any element is `NaN`.
            #[inline]
            pub fn is_nan(&self) -> bool {
                self.rotation.is_nan() || self.translation.is_nan()
            }

            /// Converts this pose to a homogeneous 4x4 matrix.
            #[inline]
            pub fn to_mat4(&self) -> $Mat4 {
                <$Mat4>::from_rotation_translation(self.rotation, self.translation.into())
            }

            /// Creates a pose from a homogeneous 4x4 matrix.
            ///
            /// The matrix is assumed to represent a rigid body transformation
            /// (rotation + translation only, no scaling or shearing).
            #[inline]
            pub fn from_mat4(mat: $Mat4) -> Self {
                let (_, rotation, translation) = mat.to_scale_rotation_translation();
                Self {
                    rotation,
                    translation: translation.into(),
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Builds a right-handed look-at view matrix.
            ///
            /// It maps the view direction target - eye to the negative z axis to and the eye to the
            /// origin. This conforms to the common notion of right-handed camera look-at view matrix from the computer graphics community, i.e. the camera is assumed to look toward its local -z axis.
            ///
            /// # Arguments
            /// - `eye`: The eye position.
            /// - `target`: The target position.
            /// - `up`: A vector approximately aligned with required the vertical axis. The only
            ///   requirement of this parameter is to not be collinear to target - eye.
            #[inline]
            pub fn look_at_rh(eye: $Vec3, target: $Vec3, up: $Vec3) -> $Pose3 {
                let rotation = <$Rot3>::look_at_rh(eye.into(), target.into(), up.into());
                let translation = rotation * (-eye);

                $Pose3 {
                    rotation,
                    translation,
                    $(padding: 0 as $Padding,)*
                }
            }

            /// Creates a pose that corresponds to the local frame of an observer standing at the
            /// point eye and looking toward target.
            ///
            /// It maps the `z` axis to the view direction target - eye and the origin to the eye.
            ///
            /// # Arguments
            /// - `eye`: The observer position.
            /// - `target`: The target position.
            /// - `up`: Vertical direction. The only requirement of this parameter is to not be
            ///   collinear to eye - at. Non-collinearity is not checked.
            #[inline]
            pub fn face_towards(eye: $Vec3, target: $Vec3, up: $Vec3) -> $Pose3 {
                $Pose3 {
                    rotation: <$Rot3>::look_at_lh(eye.into(), target.into(), up.into()).inverse(),
                    translation: eye,
                    $(padding: 0 as $Padding,)*
                }
            }
        }

        // Pose3 * Pose3
        impl Mul<$Pose3> for $Pose3 {
            type Output = Self;

            #[inline]
            fn mul(self, rhs: Self) -> Self::Output {
                Self {
                    rotation: self.rotation * rhs.rotation,
                    translation: self.translation + self.rotation * rhs.translation,
                    $(padding: 0 as $Padding,)*
                }
            }
        }

        impl MulAssign<$Pose3> for $Pose3 {
            #[inline]
            fn mul_assign(&mut self, rhs: Self) {
                *self = *self * rhs;
            }
        }

        // Pose3 * Vec3 (transform point - applies rotation and translation)
        impl Mul<$Vec3> for $Pose3 {
            type Output = $Vec3;

            #[inline]
            fn mul(self, rhs: $Vec3) -> Self::Output {
                self.transform_point(rhs)
            }
        }

        impl Mul<$Vec3> for &$Pose3 {
            type Output = $Vec3;

            #[inline]
            fn mul(self, rhs: $Vec3) -> Self::Output {
                self.transform_point(rhs)
            }
        }

        impl Mul<&$Vec3> for $Pose3 {
            type Output = $Vec3;

            #[inline]
            fn mul(self, rhs: &$Vec3) -> Self::Output {
                self.transform_point(*rhs)
            }
        }

        // &Pose3 * &Pose3
        impl Mul<&$Pose3> for &$Pose3 {
            type Output = $Pose3;

            #[inline]
            fn mul(self, rhs: &$Pose3) -> Self::Output {
                *self * *rhs
            }
        }

        // Pose3 * &Pose3
        impl Mul<&$Pose3> for $Pose3 {
            type Output = $Pose3;

            #[inline]
            fn mul(self, rhs: &$Pose3) -> Self::Output {
                self * *rhs
            }
        }

        // &Pose3 * Pose3
        impl Mul<$Pose3> for &$Pose3 {
            type Output = $Pose3;

            #[inline]
            fn mul(self, rhs: $Pose3) -> Self::Output {
                *self * rhs
            }
        }

        impl Default for $Pose3 {
            fn default() -> Self {
                Self::IDENTITY
            }
        }

        impl Mul<$Pose3> for $Rot3 {
            type Output = $Pose3;

            #[inline]
            fn mul(self, rhs: $Pose3) -> Self::Output {
                $Pose3 {
                    translation: self * rhs.translation,
                    rotation: self * rhs.rotation,
                    $(padding: 0 as $Padding,)*
                }
            }
        }

        impl Mul<$Rot3> for $Pose3 {
            type Output = $Pose3;

            #[inline]
            fn mul(self, rhs: $Rot3) -> Self::Output {
                $Pose3 {
                    translation: self.translation,
                    rotation: self.rotation * rhs,
                    $(padding: 0 as $Padding,)*
                }
            }
        }

        impl MulAssign<$Rot3> for $Pose3 {
            #[inline]
            fn mul_assign(&mut self, rhs: $Rot3) {
                *self = *self * rhs;
            }
        }

        impl From<$Rot3> for $Pose3 {
            #[inline]
            fn from(rotation: $Rot3) -> Self {
                Self::from_rotation(rotation)
            }
        }

        #[cfg(feature = "approx")]
        impl approx::AbsDiffEq for $Pose3 {
            type Epsilon = $Real;

            fn default_epsilon() -> Self::Epsilon {
                <$Real>::EPSILON
            }

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

        #[cfg(feature = "approx")]
        impl approx::RelativeEq for $Pose3 {
            fn default_max_relative() -> Self::Epsilon {
                <$Real>::EPSILON
            }

            fn relative_eq(
                &self,
                other: &Self,
                epsilon: Self::Epsilon,
                max_relative: Self::Epsilon,
            ) -> bool {
                self.rotation.abs_diff_eq(other.rotation, epsilon.max(max_relative))
                    && self.translation.abs_diff_eq(other.translation, epsilon.max(max_relative))
            }
        }
    };
}

impl_pose3!(Pose3, Rot3, f32, glam::Vec3, glam::Mat4, u32, bytemuck);
impl_pose3!(Pose3A, Rot3, f32, glam::Vec3A, glam::Mat4);
impl_pose3!(DPose3, DRot3, f64, glam::DVec3, glam::DMat4);

// f32 <-> f64 conversions
impl From<Pose3> for DPose3 {
    #[inline]
    fn from(p: Pose3) -> Self {
        Self {
            rotation: p.rotation.as_dquat(),
            translation: p.translation.as_dvec3(),
        }
    }
}

impl From<DPose3> for Pose3 {
    #[inline]
    fn from(p: DPose3) -> Self {
        Self {
            rotation: p.rotation.as_quat(),
            translation: p.translation.as_vec3(),
            padding: 0,
        }
    }
}

impl From<Pose3A> for DPose3 {
    #[inline]
    fn from(p: Pose3A) -> Self {
        Self {
            rotation: p.rotation.as_dquat(),
            translation: p.translation.as_dvec3(),
        }
    }
}

impl From<DPose3> for Pose3A {
    #[inline]
    fn from(p: DPose3) -> Self {
        Self {
            rotation: p.rotation.as_quat(),
            translation: p.translation.as_vec3a(),
        }
    }
}

// Pose3 <-> Pose3A conversions
impl From<Pose3> for Pose3A {
    #[inline]
    fn from(p: Pose3) -> Self {
        Self {
            rotation: p.rotation,
            translation: p.translation.into(),
        }
    }
}

impl From<Pose3A> for Pose3 {
    #[inline]
    fn from(p: Pose3A) -> Self {
        Self {
            rotation: p.rotation,
            translation: p.translation.into(),
            padding: 0,
        }
    }
}

// Nalgebra conversions
#[cfg(feature = "nalgebra")]
mod nalgebra_conv {
    use super::*;

    impl From<Pose3> for nalgebra::Isometry3<f32> {
        fn from(p: Pose3) -> Self {
            nalgebra::Isometry3 {
                translation: p.translation.into(),
                rotation: p.rotation.into(),
            }
        }
    }

    impl From<nalgebra::Isometry3<f32>> for Pose3 {
        fn from(iso: nalgebra::Isometry3<f32>) -> Self {
            Self {
                rotation: glam::Quat::from_xyzw(
                    iso.rotation.i,
                    iso.rotation.j,
                    iso.rotation.k,
                    iso.rotation.w,
                ),
                translation: glam::Vec3::new(
                    iso.translation.x,
                    iso.translation.y,
                    iso.translation.z,
                ),
                padding: 0,
            }
        }
    }

    impl From<DPose3> for nalgebra::Isometry3<f64> {
        fn from(p: DPose3) -> Self {
            nalgebra::Isometry3 {
                translation: p.translation.into(),
                rotation: p.rotation.into(),
            }
        }
    }

    impl From<nalgebra::Isometry3<f64>> for DPose3 {
        fn from(iso: nalgebra::Isometry3<f64>) -> Self {
            Self {
                rotation: iso.rotation.into(),
                translation: iso.translation.into(),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use core::f32::consts::PI;

    #[test]
    fn test_pose3_identity() {
        let p = Pose3::IDENTITY;
        assert_eq!(p.rotation, Rot3::IDENTITY);
        assert_eq!(p.translation, glam::Vec3::ZERO);
        assert!(p.is_finite());
    }

    #[test]
    fn test_pose3_from_translation() {
        let t = glam::Vec3::new(1.0, 2.0, 3.0);
        let p = Pose3::from_translation(t);
        assert_eq!(p.translation, t);
        assert_eq!(p.rotation, Rot3::IDENTITY);
    }

    #[test]
    fn test_pose3_from_rotation_translation() {
        let t = glam::Vec3::new(1.0, 2.0, 3.0);
        let r = Rot3::from_rotation_z(PI / 4.0);
        let p = Pose3::from_parts(t, r);
        assert_eq!(p.translation, t);
        assert_eq!(p.rotation, r);
    }

    #[test]
    fn test_pose3_transform_point() {
        let axisangle = glam::Vec3::new(0.0, 0.0, PI / 2.0);
        let p = Pose3::new(glam::Vec3::new(1.0, 0.0, 0.0), axisangle);
        let point = glam::Vec3::new(1.0, 0.0, 0.0);
        let result = p.transform_point(point);
        assert_relative_eq!(result.x, 1.0, epsilon = 1e-6);
        assert_relative_eq!(result.y, 1.0, epsilon = 1e-6);
        assert_relative_eq!(result.z, 0.0, epsilon = 1e-6);
        // Operator should also work
        let result2 = p * point;
        assert_relative_eq!(result2.x, 1.0, epsilon = 1e-6);
        assert_relative_eq!(result2.y, 1.0, epsilon = 1e-6);
        assert_relative_eq!(result2.z, 0.0, epsilon = 1e-6);
    }

    #[test]
    fn test_pose3_transform_vector() {
        let axisangle = glam::Vec3::new(0.0, 0.0, PI / 2.0);
        let p = Pose3::new(glam::Vec3::new(100.0, 200.0, 300.0), axisangle);
        let vector = glam::Vec3::new(1.0, 0.0, 0.0);
        // Vector transformation ignores translation
        let result = p.transform_vector(vector);
        assert_relative_eq!(result.x, 0.0, epsilon = 1e-6);
        assert_relative_eq!(result.y, 1.0, epsilon = 1e-6);
        assert_relative_eq!(result.z, 0.0, epsilon = 1e-6);
    }

    #[test]
    fn test_pose3_inverse() {
        let axisangle = glam::Vec3::new(0.1, 0.2, 0.3);
        let p = Pose3::new(axisangle, glam::Vec3::new(1.0, 2.0, 3.0));
        let inv = p.inverse();
        let identity = p * inv;
        assert_relative_eq!(identity.rotation, Rot3::IDENTITY, epsilon = 1e-6);
        assert_relative_eq!(identity.translation.x, 0.0, epsilon = 1e-6);
        assert_relative_eq!(identity.translation.y, 0.0, epsilon = 1e-6);
        assert_relative_eq!(identity.translation.z, 0.0, epsilon = 1e-6);
    }

    #[test]
    fn test_pose3_to_from_mat4() {
        let axisangle = glam::Vec3::new(0.1, 0.2, 0.3);
        let p = Pose3::new(axisangle, glam::Vec3::new(1.0, 2.0, 3.0));
        let m = p.to_mat4();
        let p2 = Pose3::from_mat4(m);
        assert_relative_eq!(p.rotation.x, p2.rotation.x, epsilon = 1e-5);
        assert_relative_eq!(p.rotation.y, p2.rotation.y, epsilon = 1e-5);
        assert_relative_eq!(p.rotation.z, p2.rotation.z, epsilon = 1e-5);
        assert_relative_eq!(p.rotation.w, p2.rotation.w, epsilon = 1e-5);
        assert_relative_eq!(p.translation.x, p2.translation.x, epsilon = 1e-6);
        assert_relative_eq!(p.translation.y, p2.translation.y, epsilon = 1e-6);
        assert_relative_eq!(p.translation.z, p2.translation.z, epsilon = 1e-6);
    }

    #[test]
    fn test_dpose3_new() {
        let axisangle = glam::DVec3::new(0.1, 0.2, 0.3);
        let p = DPose3::new(glam::DVec3::new(1.0, 2.0, 3.0), axisangle);
        assert_relative_eq!(p.translation.x, 1.0, epsilon = 1e-10);
        assert_relative_eq!(p.translation.y, 2.0, epsilon = 1e-10);
        assert_relative_eq!(p.translation.z, 3.0, epsilon = 1e-10);
    }
}