affn 0.6.0

Affine geometry primitives: strongly-typed coordinate systems, reference frames, and centers for scientific computing.
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
//! # XYZ: Shared Storage for Cartesian Types
//!
//! This module provides the internal `XYZ<T>` type, a thin `#[repr(transparent)]`
//! wrapper around `nalgebra::Vector3<T>`.
//!
//! ## Purpose
//!
//! `XYZ<T>` centralizes all component-wise mathematical operations in one place:
//! - Addition, subtraction, scaling
//! - Dot product, magnitude, normalization
//!
//! The semantic types (`Position`, `Vector`, `Direction`) are thin wrappers over
//! `XYZ<T>` with `PhantomData` markers for center, frame, and unit information.
//! This eliminates code duplication while maintaining zero-cost abstractions.
//!
//! ## Design Notes
//!
//! - Uses `#[repr(transparent)]` for zero-cost ABI compatibility with `Vector3<T>`
//! - All operations are `#[inline]` for optimal performance
//! - Generic over the component type `T` (typically `f64` or `Quantity<U>`)

use nalgebra::Vector3;
use std::ops::{Add, Mul, Neg, Sub};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Internal shared storage for 3D Cartesian coordinates.
///
/// This is a thin wrapper around `nalgebra::Vector3<T>` that provides
/// centralized implementations of component-wise operations.
///
/// # Type Parameter
/// - `T`: The component type (e.g., `f64`, `Quantity<U>`)
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
    feature = "serde",
    serde(bound(
        serialize = "T: Serialize + Clone + PartialEq + std::fmt::Debug + 'static",
        deserialize = "T: Deserialize<'de> + Clone + PartialEq + std::fmt::Debug + 'static"
    ))
)]
#[repr(transparent)]
pub struct XYZ<T>(pub(crate) Vector3<T>);

// =============================================================================
// Constructors
// =============================================================================

impl<T> XYZ<T> {
    /// Creates a new XYZ from individual components.
    #[inline]
    pub const fn new(x: T, y: T, z: T) -> Self {
        Self(Vector3::new(x, y, z))
    }

    /// Creates an XYZ from a nalgebra Vector3.
    #[inline]
    pub const fn from_vec3(vec: Vector3<T>) -> Self {
        Self(vec)
    }

    /// Returns the underlying nalgebra Vector3.
    #[inline]
    pub const fn as_vec3(&self) -> &Vector3<T> {
        &self.0
    }

    /// Consumes self and returns the underlying Vector3.
    #[inline]
    pub fn into_vec3(self) -> Vector3<T> {
        self.0
    }
}

// =============================================================================
// Component Access
// =============================================================================

impl<T: Copy> XYZ<T> {
    /// Returns the x-component.
    #[inline]
    pub fn x(&self) -> T {
        self.0[0]
    }

    /// Returns the y-component.
    #[inline]
    pub fn y(&self) -> T {
        self.0[1]
    }

    /// Returns the z-component.
    #[inline]
    pub fn z(&self) -> T {
        self.0[2]
    }

    /// Returns components as a tuple.
    #[inline]
    pub fn components(&self) -> (T, T, T) {
        (self.x(), self.y(), self.z())
    }
}

// =============================================================================
// Arithmetic Operations for f64 components
// =============================================================================

impl XYZ<f64> {
    /// The zero vector.
    pub const ZERO: Self = Self::new(0.0, 0.0, 0.0);

    /// Computes the Euclidean magnitude (length) of the vector.
    #[inline]
    pub fn magnitude(&self) -> f64 {
        self.0.magnitude()
    }

    /// Computes the squared magnitude (avoids sqrt).
    #[inline]
    pub fn magnitude_squared(&self) -> f64 {
        self.0.magnitude_squared()
    }

    /// Computes the dot product with another vector.
    #[inline]
    pub fn dot(&self, other: &Self) -> f64 {
        self.0.dot(&other.0)
    }

    /// Computes the cross product with another vector.
    #[inline]
    pub fn cross(&self, other: &Self) -> Self {
        Self(self.0.cross(&other.0))
    }

    /// Returns a normalized (unit length) version, or None if magnitude is zero.
    #[inline]
    pub fn try_normalize(&self) -> Option<Self> {
        let mag = self.magnitude();
        if mag.abs() < f64::EPSILON {
            None
        } else {
            Some(Self(self.0 / mag))
        }
    }

    /// Returns a normalized version, assuming non-zero magnitude.
    ///
    /// # Safety
    /// Caller must ensure the vector is non-zero.
    #[inline]
    pub fn normalize_unchecked(&self) -> Self {
        Self(self.0.normalize())
    }

    /// Scales the vector by a scalar factor.
    #[inline]
    pub fn scale(&self, factor: f64) -> Self {
        Self(self.0 * factor)
    }

    /// Component-wise addition.
    #[inline]
    pub fn add(&self, other: &Self) -> Self {
        Self(self.0 + other.0)
    }

    /// Component-wise subtraction.
    #[inline]
    pub fn sub(&self, other: &Self) -> Self {
        Self(self.0 - other.0)
    }

    /// Negates all components.
    #[inline]
    pub fn neg(&self) -> Self {
        Self(-self.0)
    }
}

// =============================================================================
// Operator Implementations for XYZ<f64>
// =============================================================================

impl Add for XYZ<f64> {
    type Output = Self;

    #[inline]
    fn add(self, other: Self) -> Self::Output {
        Self(self.0 + other.0)
    }
}

impl Sub for XYZ<f64> {
    type Output = Self;

    #[inline]
    fn sub(self, other: Self) -> Self::Output {
        Self(self.0 - other.0)
    }
}

impl Neg for XYZ<f64> {
    type Output = Self;

    #[inline]
    fn neg(self) -> Self::Output {
        Self(-self.0)
    }
}

impl Mul<f64> for XYZ<f64> {
    type Output = Self;

    #[inline]
    fn mul(self, scalar: f64) -> Self::Output {
        Self(self.0 * scalar)
    }
}

impl Mul<XYZ<f64>> for f64 {
    type Output = XYZ<f64>;

    #[inline]
    fn mul(self, xyz: XYZ<f64>) -> Self::Output {
        XYZ(xyz.0 * self)
    }
}

// =============================================================================
// Quantity-aware operations
// =============================================================================

use qtty::{Quantity, Unit};

impl<U: Unit> XYZ<Quantity<U>> {
    /// The zero vector for this unit type.
    pub const ZERO: Self = Self::new(
        Quantity::<U>::new(0.0),
        Quantity::<U>::new(0.0),
        Quantity::<U>::new(0.0),
    );

    /// Computes the Euclidean magnitude in the same unit.
    #[inline]
    pub fn magnitude(&self) -> Quantity<U> {
        let mag = Vector3::new(self.0[0].value(), self.0[1].value(), self.0[2].value()).magnitude();
        Quantity::new(mag)
    }

    /// Computes the squared magnitude as a raw `f64`.
    ///
    /// Returns the dimensionless squared magnitude `|v|²` by extracting raw
    /// component values before squaring. This intentionally returns `f64`
    /// rather than `Quantity<U²>` to avoid requiring a squared-unit type
    /// in the dependency tree. Use [`magnitude`](Self::magnitude) if you
    /// need the result with a unit.
    #[inline]
    pub fn magnitude_squared(&self) -> f64 {
        let x = self.0[0].value();
        let y = self.0[1].value();
        let z = self.0[2].value();
        x * x + y * y + z * z
    }

    /// Extracts raw f64 values as an XYZ<f64>.
    #[inline]
    pub fn to_raw(&self) -> XYZ<f64> {
        XYZ::new(self.0[0].value(), self.0[1].value(), self.0[2].value())
    }

    /// Creates from raw f64 values.
    #[inline]
    pub fn from_raw(raw: XYZ<f64>) -> Self {
        Self::new(
            Quantity::new(raw.x()),
            Quantity::new(raw.y()),
            Quantity::new(raw.z()),
        )
    }

    /// Component-wise addition.
    #[inline]
    pub fn add(&self, other: &Self) -> Self {
        Self(self.0 + other.0)
    }

    /// Component-wise subtraction.
    #[inline]
    pub fn sub(&self, other: &Self) -> Self {
        Self(self.0 - other.0)
    }
}

impl<U: Unit> Add for XYZ<Quantity<U>> {
    type Output = Self;

    #[inline]
    fn add(self, other: Self) -> Self::Output {
        Self(self.0 + other.0)
    }
}

impl<U: Unit> Sub for XYZ<Quantity<U>> {
    type Output = Self;

    #[inline]
    fn sub(self, other: Self) -> Self::Output {
        Self(self.0 - other.0)
    }
}

impl<U: Unit> Neg for XYZ<Quantity<U>> {
    type Output = Self;

    #[inline]
    fn neg(self) -> Self::Output {
        Self::new(-self.0[0], -self.0[1], -self.0[2])
    }
}

// =============================================================================
// Default Implementation
// =============================================================================

impl<T: Default> Default for XYZ<T> {
    fn default() -> Self {
        Self(Vector3::new(T::default(), T::default(), T::default()))
    }
}

// =============================================================================
// Display
// =============================================================================

impl<T: std::fmt::Display + Copy> std::fmt::Display for XYZ<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "(")?;
        std::fmt::Display::fmt(&self.x(), f)?;
        write!(f, ", ")?;
        std::fmt::Display::fmt(&self.y(), f)?;
        write!(f, ", ")?;
        std::fmt::Display::fmt(&self.z(), f)?;
        write!(f, ")")
    }
}

impl<T: std::fmt::LowerExp + Copy> std::fmt::LowerExp for XYZ<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "(")?;
        std::fmt::LowerExp::fmt(&self.x(), f)?;
        write!(f, ", ")?;
        std::fmt::LowerExp::fmt(&self.y(), f)?;
        write!(f, ", ")?;
        std::fmt::LowerExp::fmt(&self.z(), f)?;
        write!(f, ")")
    }
}

impl<T: std::fmt::UpperExp + Copy> std::fmt::UpperExp for XYZ<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "(")?;
        std::fmt::UpperExp::fmt(&self.x(), f)?;
        write!(f, ", ")?;
        std::fmt::UpperExp::fmt(&self.y(), f)?;
        write!(f, ", ")?;
        std::fmt::UpperExp::fmt(&self.z(), f)?;
        write!(f, ")")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use qtty::{Meter, Quantity, M};

    #[test]
    fn test_xyz_basic_ops() {
        let a = XYZ::new(1.0, 2.0, 3.0);
        let b = XYZ::new(4.0, 5.0, 6.0);

        // Addition
        let sum = a + b;
        assert!((sum.x() - 5.0).abs() < f64::EPSILON);
        assert!((sum.y() - 7.0).abs() < f64::EPSILON);
        assert!((sum.z() - 9.0).abs() < f64::EPSILON);

        // Subtraction
        let diff = b - a;
        assert!((diff.x() - 3.0).abs() < f64::EPSILON);
        assert!((diff.y() - 3.0).abs() < f64::EPSILON);
        assert!((diff.z() - 3.0).abs() < f64::EPSILON);

        // Scaling
        let scaled = a.scale(2.0);
        assert!((scaled.x() - 2.0).abs() < f64::EPSILON);
        assert!((scaled.y() - 4.0).abs() < f64::EPSILON);
        assert!((scaled.z() - 6.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_xyz_magnitude_and_normalize() {
        let v = XYZ::new(3.0, 4.0, 0.0);
        assert!((v.magnitude() - 5.0).abs() < f64::EPSILON);

        let n = v.try_normalize().unwrap();
        assert!((n.magnitude() - 1.0).abs() < f64::EPSILON);
        assert!((n.x() - 0.6).abs() < f64::EPSILON);
        assert!((n.y() - 0.8).abs() < f64::EPSILON);
    }

    #[test]
    fn test_xyz_dot_and_cross() {
        let a = XYZ::new(1.0, 0.0, 0.0);
        let b = XYZ::new(0.0, 1.0, 0.0);

        // Dot product of perpendicular vectors
        assert!(a.dot(&b).abs() < f64::EPSILON);

        // Cross product
        let c = a.cross(&b);
        assert!((c.x()).abs() < f64::EPSILON);
        assert!((c.y()).abs() < f64::EPSILON);
        assert!((c.z() - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_xyz_zero_normalize() {
        let zero = XYZ::<f64>::ZERO;
        assert!(zero.try_normalize().is_none());
    }

    #[test]
    fn test_xyz_quantity_ops() {
        let a = XYZ::new(3.0 * M, 4.0 * M, 0.0 * M);
        let b = XYZ::new(1.0 * M, 2.0 * M, 3.0 * M);

        let sum = a + b;
        assert!((sum.x().value() - 4.0).abs() < f64::EPSILON);
        assert!((sum.y().value() - 6.0).abs() < f64::EPSILON);

        let diff = a - b;
        assert!((diff.x().value() - 2.0).abs() < f64::EPSILON);
        assert!((diff.y().value() - 2.0).abs() < f64::EPSILON);

        let mag = a.magnitude();
        assert!((mag.value() - 5.0).abs() < f64::EPSILON);
        let mag_sq = a.magnitude_squared();
        assert!((mag_sq - 25.0).abs() < f64::EPSILON);

        let raw = a.to_raw();
        assert!((raw.x() - 3.0).abs() < f64::EPSILON);
        let back = XYZ::<Quantity<Meter>>::from_raw(raw);
        assert!((back.y().value() - 4.0).abs() < f64::EPSILON);

        let neg = -b;
        assert!((neg.z().value() + 3.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_xyz_vec3_roundtrip() {
        let vec3: nalgebra::Vector3<f64> = nalgebra::Vector3::new(1.0, 2.0, 3.0);
        let xyz: XYZ<f64> = XYZ::from_vec3(vec3);
        assert!((xyz.x() - 1.0).abs() < f64::EPSILON);

        let as_vec3 = xyz.as_vec3();
        assert!((as_vec3[2] - 3.0).abs() < f64::EPSILON);

        let into_vec3 = xyz.into_vec3();
        assert!((into_vec3[1] - 2.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_xyz_f64_helpers_and_traits() {
        let a = XYZ::new(1.0, -2.0, 3.5);
        let b = XYZ::new(-4.0, 5.0, 6.0);

        let mag_sq = a.magnitude_squared();
        assert!((mag_sq - (1.0 + 4.0 + 12.25)).abs() < f64::EPSILON);

        let sum = XYZ::<f64>::add(&a, &b);
        assert!((sum.x() + 3.0).abs() < f64::EPSILON);
        assert!((sum.y() - 3.0).abs() < f64::EPSILON);
        assert!((sum.z() - 9.5).abs() < f64::EPSILON);

        let diff = XYZ::<f64>::sub(&a, &b);
        assert!((diff.x() - 5.0).abs() < f64::EPSILON);
        assert!((diff.y() + 7.0).abs() < f64::EPSILON);
        assert!((diff.z() - -2.5).abs() < f64::EPSILON);

        let (x, y, z) = a.components();
        assert!((x - 1.0).abs() < f64::EPSILON);
        assert!((y + 2.0).abs() < f64::EPSILON);
        assert!((z - 3.5).abs() < f64::EPSILON);

        let default_xyz: XYZ<f64> = Default::default();
        assert!((default_xyz.x()).abs() < f64::EPSILON);
        assert!((default_xyz.y()).abs() < f64::EPSILON);
        assert!((default_xyz.z()).abs() < f64::EPSILON);

        let display = a.to_string();
        assert_eq!(display, "(1, -2, 3.5)");

        let display_prec = format!("{:.2}", a);
        assert_eq!(display_prec, "(1.00, -2.00, 3.50)");

        let display_exp = format!("{:.2e}", a);
        assert_eq!(display_exp, "(1.00e0, -2.00e0, 3.50e0)");

        let neg = -a;
        assert!((neg.x() + 1.0).abs() < f64::EPSILON);
        assert!((neg.y() - 2.0).abs() < f64::EPSILON);
        assert!((neg.z() + 3.5).abs() < f64::EPSILON);

        let scaled = a * 2.0;
        assert!((scaled.x() - 2.0).abs() < f64::EPSILON);
        let scaled2 = 2.0 * a;
        assert!((scaled2.y() + 4.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_xyz_quantity_helpers() {
        let a = XYZ::new(1.0 * M, 2.0 * M, 3.0 * M);
        let b = XYZ::new(-1.0 * M, 0.5 * M, 4.0 * M);

        let sum = XYZ::<Quantity<Meter>>::add(&a, &b);
        assert!((sum.x().value()).abs() < f64::EPSILON);
        assert!((sum.y().value() - 2.5).abs() < f64::EPSILON);

        let diff = XYZ::<Quantity<Meter>>::sub(&a, &b);
        assert!((diff.x().value() - 2.0).abs() < f64::EPSILON);
        assert!((diff.z().value() - -1.0).abs() < f64::EPSILON);
    }
}