u-geometry 0.1.0

Domain-agnostic computational geometry: primitives, polygons, NFP, collision detection, spatial indexing.
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
//! Rigid transformations for 2D and 3D.
//!
//! Built on nalgebra's `Isometry2`/`Isometry3` for numerical correctness.
//! Provides a simpler API for common transform operations.

use crate::primitives::{Point2, Point3};
use nalgebra::{
    Isometry2, Isometry3, Point2 as NaPoint2, Point3 as NaPoint3, UnitQuaternion,
    Vector2 as NaVector2, Vector3 as NaVector3,
};

/// A 2D rigid transformation (rotation + translation).
///
/// Internally uses nalgebra `Isometry2` for correct composition
/// and inversion. The representation stores translation (tx, ty)
/// and rotation angle in radians.
///
/// # Example
///
/// ```
/// use u_geometry::transform::Transform2D;
/// use std::f64::consts::PI;
///
/// let t = Transform2D::new(10.0, 20.0, PI / 2.0);
/// let (x, y) = t.apply(1.0, 0.0);
/// assert!((x - 10.0).abs() < 1e-10);
/// assert!((y - 21.0).abs() < 1e-10);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Transform2D {
    /// Translation x.
    pub tx: f64,
    /// Translation y.
    pub ty: f64,
    /// Rotation angle in radians.
    pub angle: f64,
}

impl Transform2D {
    /// Identity transform (no rotation, no translation).
    pub fn identity() -> Self {
        Self {
            tx: 0.0,
            ty: 0.0,
            angle: 0.0,
        }
    }

    /// Creates a translation-only transform.
    pub fn translation(tx: f64, ty: f64) -> Self {
        Self { tx, ty, angle: 0.0 }
    }

    /// Creates a rotation-only transform (about the origin).
    pub fn rotation(angle: f64) -> Self {
        Self {
            tx: 0.0,
            ty: 0.0,
            angle,
        }
    }

    /// Creates a transform with translation and rotation.
    pub fn new(tx: f64, ty: f64, angle: f64) -> Self {
        Self { tx, ty, angle }
    }

    /// Converts to a nalgebra `Isometry2`.
    #[inline]
    pub fn to_isometry(&self) -> Isometry2<f64> {
        Isometry2::new(NaVector2::new(self.tx, self.ty), self.angle)
    }

    /// Creates from a nalgebra `Isometry2`.
    pub fn from_isometry(iso: &Isometry2<f64>) -> Self {
        Self {
            tx: iso.translation.x,
            ty: iso.translation.y,
            angle: iso.rotation.angle(),
        }
    }

    /// Applies this transform to a point.
    #[inline]
    pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {
        let iso = self.to_isometry();
        let p = iso.transform_point(&NaPoint2::new(x, y));
        (p.x, p.y)
    }

    /// Applies this transform to a `Point2`.
    #[inline]
    pub fn apply_point(&self, p: &Point2) -> Point2 {
        let (x, y) = self.apply(p.x, p.y);
        Point2::new(x, y)
    }

    /// Transforms a slice of points.
    pub fn apply_points(&self, points: &[(f64, f64)]) -> Vec<(f64, f64)> {
        let iso = self.to_isometry();
        points
            .iter()
            .map(|(x, y)| {
                let p = iso.transform_point(&NaPoint2::new(*x, *y));
                (p.x, p.y)
            })
            .collect()
    }

    /// Composes two transforms: applies `self` first, then `other`.
    pub fn then(&self, other: &Self) -> Self {
        let iso1 = self.to_isometry();
        let iso2 = other.to_isometry();
        Self::from_isometry(&(iso1 * iso2))
    }

    /// Returns the inverse transform.
    pub fn inverse(&self) -> Self {
        Self::from_isometry(&self.to_isometry().inverse())
    }

    /// Whether this is approximately an identity transform.
    pub fn is_identity(&self, epsilon: f64) -> bool {
        self.tx.abs() < epsilon && self.ty.abs() < epsilon && self.angle.abs() < epsilon
    }
}

impl Default for Transform2D {
    fn default() -> Self {
        Self::identity()
    }
}

/// A 3D rigid transformation (rotation + translation).
///
/// Internally uses nalgebra `Isometry3` with quaternion rotation
/// for gimbal-lock-free composition and inversion.
/// The representation stores translation (tx, ty, tz) and
/// Euler angles (roll, pitch, yaw) in radians for human readability.
///
/// # Euler Angle Convention
/// - Roll (rx): rotation about X axis
/// - Pitch (ry): rotation about Y axis
/// - Yaw (rz): rotation about Z axis
///
/// Composition order: Rz * Ry * Rx (extrinsic rotations)
///
/// # Reference
/// Diebel (2006), "Representing Attitude: Euler Angles, Unit Quaternions, and Rotation Vectors"
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Transform3D {
    /// Translation x.
    pub tx: f64,
    /// Translation y.
    pub ty: f64,
    /// Translation z.
    pub tz: f64,
    /// Roll (rotation about X axis) in radians.
    pub rx: f64,
    /// Pitch (rotation about Y axis) in radians.
    pub ry: f64,
    /// Yaw (rotation about Z axis) in radians.
    pub rz: f64,
}

impl Transform3D {
    /// Identity transform.
    pub fn identity() -> Self {
        Self {
            tx: 0.0,
            ty: 0.0,
            tz: 0.0,
            rx: 0.0,
            ry: 0.0,
            rz: 0.0,
        }
    }

    /// Creates a translation-only transform.
    pub fn translation(tx: f64, ty: f64, tz: f64) -> Self {
        Self {
            tx,
            ty,
            tz,
            rx: 0.0,
            ry: 0.0,
            rz: 0.0,
        }
    }

    /// Creates a transform with translation and Euler angles.
    pub fn new(tx: f64, ty: f64, tz: f64, rx: f64, ry: f64, rz: f64) -> Self {
        Self {
            tx,
            ty,
            tz,
            rx,
            ry,
            rz,
        }
    }

    /// Converts to a nalgebra `Isometry3`.
    ///
    /// Uses the Euler angle convention: Rz * Ry * Rx.
    #[inline]
    pub fn to_isometry(&self) -> Isometry3<f64> {
        let rotation = UnitQuaternion::from_euler_angles(self.rx, self.ry, self.rz);
        Isometry3::from_parts(NaVector3::new(self.tx, self.ty, self.tz).into(), rotation)
    }

    /// Creates from a nalgebra `Isometry3`.
    pub fn from_isometry(iso: &Isometry3<f64>) -> Self {
        let (rx, ry, rz) = iso.rotation.euler_angles();
        Self {
            tx: iso.translation.x,
            ty: iso.translation.y,
            tz: iso.translation.z,
            rx,
            ry,
            rz,
        }
    }

    /// Applies this transform to coordinates.
    #[inline]
    pub fn apply(&self, x: f64, y: f64, z: f64) -> (f64, f64, f64) {
        let iso = self.to_isometry();
        let p = iso.transform_point(&NaPoint3::new(x, y, z));
        (p.x, p.y, p.z)
    }

    /// Applies this transform to a `Point3`.
    #[inline]
    pub fn apply_point(&self, p: &Point3) -> Point3 {
        let (x, y, z) = self.apply(p.x, p.y, p.z);
        Point3::new(x, y, z)
    }

    /// Transforms a slice of points.
    pub fn apply_points(&self, points: &[Point3]) -> Vec<Point3> {
        let iso = self.to_isometry();
        points
            .iter()
            .map(|p| {
                let tp = iso.transform_point(&NaPoint3::new(p.x, p.y, p.z));
                Point3::new(tp.x, tp.y, tp.z)
            })
            .collect()
    }

    /// Composes two transforms: applies `self` first, then `other`.
    pub fn then(&self, other: &Self) -> Self {
        let iso1 = self.to_isometry();
        let iso2 = other.to_isometry();
        Self::from_isometry(&(iso1 * iso2))
    }

    /// Returns the inverse transform.
    pub fn inverse(&self) -> Self {
        Self::from_isometry(&self.to_isometry().inverse())
    }

    /// Whether this is approximately an identity transform.
    pub fn is_identity(&self, epsilon: f64) -> bool {
        self.tx.abs() < epsilon
            && self.ty.abs() < epsilon
            && self.tz.abs() < epsilon
            && self.rx.abs() < epsilon
            && self.ry.abs() < epsilon
            && self.rz.abs() < epsilon
    }
}

impl Default for Transform3D {
    fn default() -> Self {
        Self::identity()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::f64::consts::PI;

    #[test]
    fn test_identity() {
        let t = Transform2D::identity();
        let (x, y) = t.apply(1.0, 2.0);
        assert!((x - 1.0).abs() < 1e-10);
        assert!((y - 2.0).abs() < 1e-10);
    }

    #[test]
    fn test_translation() {
        let t = Transform2D::translation(10.0, 20.0);
        let (x, y) = t.apply(1.0, 2.0);
        assert!((x - 11.0).abs() < 1e-10);
        assert!((y - 22.0).abs() < 1e-10);
    }

    #[test]
    fn test_rotation_90() {
        let t = Transform2D::rotation(PI / 2.0);
        let (x, y) = t.apply(1.0, 0.0);
        assert!((x - 0.0).abs() < 1e-10);
        assert!((y - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_rotation_180() {
        let t = Transform2D::rotation(PI);
        let (x, y) = t.apply(1.0, 0.0);
        assert!((x - (-1.0)).abs() < 1e-10);
        assert!((y - 0.0).abs() < 1e-10);
    }

    #[test]
    fn test_compose() {
        let t1 = Transform2D::translation(10.0, 0.0);
        let t2 = Transform2D::translation(0.0, 20.0);
        let composed = t1.then(&t2);
        let (x, y) = composed.apply(0.0, 0.0);
        assert!((x - 10.0).abs() < 1e-10);
        assert!((y - 20.0).abs() < 1e-10);
    }

    #[test]
    fn test_inverse() {
        let t = Transform2D::new(10.0, 20.0, PI / 4.0);
        let inv = t.inverse();
        let composed = t.then(&inv);
        assert!(composed.is_identity(1e-10));
    }

    #[test]
    fn test_apply_point() {
        let t = Transform2D::translation(5.0, 3.0);
        let p = Point2::new(1.0, 2.0);
        let q = t.apply_point(&p);
        assert!((q.x - 6.0).abs() < 1e-10);
        assert!((q.y - 5.0).abs() < 1e-10);
    }

    #[test]
    fn test_apply_points() {
        let t = Transform2D::translation(1.0, 1.0);
        let points = vec![(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)];
        let transformed = t.apply_points(&points);
        assert!((transformed[0].0 - 1.0).abs() < 1e-10);
        assert!((transformed[0].1 - 1.0).abs() < 1e-10);
        assert!((transformed[1].0 - 2.0).abs() < 1e-10);
        assert!((transformed[2].1 - 2.0).abs() < 1e-10);
    }

    #[test]
    fn test_default_is_identity() {
        let t = Transform2D::default();
        assert!(t.is_identity(1e-15));
    }

    // ======================== 3D Transform Tests ========================

    #[test]
    fn test_3d_identity() {
        let t = Transform3D::identity();
        let (x, y, z) = t.apply(1.0, 2.0, 3.0);
        assert!((x - 1.0).abs() < 1e-10);
        assert!((y - 2.0).abs() < 1e-10);
        assert!((z - 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_3d_translation() {
        let t = Transform3D::translation(10.0, 20.0, 30.0);
        let (x, y, z) = t.apply(1.0, 2.0, 3.0);
        assert!((x - 11.0).abs() < 1e-10);
        assert!((y - 22.0).abs() < 1e-10);
        assert!((z - 33.0).abs() < 1e-10);
    }

    #[test]
    fn test_3d_rotation_z_90() {
        // Rotate 90 degrees about Z: (1,0,0) → (0,1,0)
        let t = Transform3D::new(0.0, 0.0, 0.0, 0.0, 0.0, PI / 2.0);
        let (x, y, z) = t.apply(1.0, 0.0, 0.0);
        assert!((x - 0.0).abs() < 1e-10);
        assert!((y - 1.0).abs() < 1e-10);
        assert!((z - 0.0).abs() < 1e-10);
    }

    #[test]
    fn test_3d_rotation_x_90() {
        // Rotate 90 degrees about X: (0,1,0) → (0,0,1)
        let t = Transform3D::new(0.0, 0.0, 0.0, PI / 2.0, 0.0, 0.0);
        let (x, y, z) = t.apply(0.0, 1.0, 0.0);
        assert!((x - 0.0).abs() < 1e-10);
        assert!((y - 0.0).abs() < 1e-10);
        assert!((z - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_3d_rotation_y_90() {
        // Rotate 90 degrees about Y: (0,0,1) → (1,0,0)
        let t = Transform3D::new(0.0, 0.0, 0.0, 0.0, PI / 2.0, 0.0);
        let (x, y, z) = t.apply(0.0, 0.0, 1.0);
        assert!((x - 1.0).abs() < 1e-10);
        assert!((y - 0.0).abs() < 1e-10);
        assert!((z - 0.0).abs() < 1e-10);
    }

    #[test]
    fn test_3d_compose() {
        let t1 = Transform3D::translation(10.0, 0.0, 0.0);
        let t2 = Transform3D::translation(0.0, 20.0, 0.0);
        let composed = t1.then(&t2);
        let (x, y, z) = composed.apply(0.0, 0.0, 0.0);
        assert!((x - 10.0).abs() < 1e-10);
        assert!((y - 20.0).abs() < 1e-10);
        assert!((z - 0.0).abs() < 1e-10);
    }

    #[test]
    fn test_3d_inverse() {
        let t = Transform3D::new(10.0, 20.0, 30.0, PI / 4.0, PI / 6.0, PI / 3.0);
        let inv = t.inverse();
        let composed = t.then(&inv);
        assert!(composed.is_identity(1e-10));
    }

    #[test]
    fn test_3d_apply_point() {
        let t = Transform3D::translation(5.0, 3.0, 1.0);
        let p = Point3::new(1.0, 2.0, 3.0);
        let q = t.apply_point(&p);
        assert!((q.x - 6.0).abs() < 1e-10);
        assert!((q.y - 5.0).abs() < 1e-10);
        assert!((q.z - 4.0).abs() < 1e-10);
    }

    #[test]
    fn test_3d_apply_points() {
        let t = Transform3D::translation(1.0, 1.0, 1.0);
        let points = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
        ];
        let transformed = t.apply_points(&points);
        assert!((transformed[0].x - 1.0).abs() < 1e-10);
        assert!((transformed[1].x - 2.0).abs() < 1e-10);
        assert!((transformed[2].y - 2.0).abs() < 1e-10);
    }

    #[test]
    fn test_3d_default_is_identity() {
        let t = Transform3D::default();
        assert!(t.is_identity(1e-15));
    }

    // ======================== Serde Tests ========================

    #[cfg(feature = "serde")]
    mod serde_tests {
        use super::*;

        #[test]
        fn test_transform2d_roundtrip() {
            let t = Transform2D::new(10.0, 20.0, std::f64::consts::PI / 4.0);
            let json = serde_json::to_string(&t).unwrap();
            let t2: Transform2D = serde_json::from_str(&json).unwrap();
            assert_eq!(t, t2);
        }

        #[test]
        fn test_transform3d_roundtrip() {
            let t = Transform3D::new(1.0, 2.0, 3.0, 0.1, 0.2, 0.3);
            let json = serde_json::to_string(&t).unwrap();
            let t2: Transform3D = serde_json::from_str(&json).unwrap();
            assert_eq!(t, t2);
        }
    }
}