glamour 0.18.0

Strongly typed linear algebra with glam
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
//! Point types.
//!
//! Points are vectors with different and more limited semantics.
//!
//! For example, transforming a 3D point through a 4 x 4 matrix is different
//! from transforming a 3D vector through the same matrix.
//!
//! Arithmetic operators with points are also typed differently: Subtracting two
//! points yields a vector, while subtracting a vector from a point yields
//! another point.

use bytemuck::{Pod, Zeroable};
use num_traits::{ConstOne, ConstZero};

use crate::{
    Scalar, Transparent, Unit, Vector2, Vector3, Vector4, bindings::prelude::*, peel, rewrap,
    scalar::FloatScalar, unit::FloatUnit, wrap,
};
use core::ops::Mul;

/// 2D point.
///
/// Alignment: Same as the scalar.
#[cfg_attr(
    all(not(target_arch = "wasm32"), feature = "wasmtime"),
    derive(
        wasmtime::component::ComponentType,
        wasmtime::component::Lower,
        wasmtime::component::Lift
    )
)]
#[cfg_attr(
    all(not(target_arch = "wasm32"), feature = "wasmtime"),
    component(record)
)]
#[repr(C)]
#[cfg_attr(feature = "facet", derive(facet_derive::Facet))]
pub struct Point2<U: Unit = f32> {
    /// X coordinate
    pub x: U::Scalar,
    /// Y coordinate
    pub y: U::Scalar,
}

// SAFETY: `T::Scalar` is `Zeroable`, and `Point2` is `#[repr(C)]`.
unsafe impl<T: Unit> Zeroable for Point2<T> {}
// SAFETY: `T::Scalar` is `Pod`.
unsafe impl<T: Unit> Pod for Point2<T> {}
// SAFETY: This is the fundamental guarantee of this crate.
impl<T: Unit> Transparent for Point2<T> {
    type Wrapped = <T::Scalar as Scalar>::Vec2;
}

/// 3D point.
///
/// Alignment: Same as the scalar (so not 16 bytes). If you really need 16-byte
/// alignment, use [`Point4`].
#[cfg_attr(
    all(not(target_arch = "wasm32"), feature = "wasmtime"),
    derive(
        wasmtime::component::ComponentType,
        wasmtime::component::Lower,
        wasmtime::component::Lift
    )
)]
#[cfg_attr(
    all(not(target_arch = "wasm32"), feature = "wasmtime"),
    component(record)
)]
#[cfg_attr(feature = "facet", derive(facet_derive::Facet))]
#[repr(C)]
pub struct Point3<U: Unit = f32> {
    /// X coordinate
    pub x: U::Scalar,
    /// Y coordinate
    pub y: U::Scalar,
    /// Z coordinate
    pub z: U::Scalar,
}

/// SAFETY: `T::Scalar` is `Zeroable`, and `Point3` is `#[repr(C)]`.
unsafe impl<T: Unit> Zeroable for Point3<T> {}
/// SAFETY: `T::Scalar` is `Pod`.
unsafe impl<T: Unit> Pod for Point3<T> {}
impl<T: Unit> Transparent for Point3<T> {
    type Wrapped = <T::Scalar as Scalar>::Vec3;
}

/// 4D point.
///
/// Alignment: This is always 16-byte aligned. [`glam::DVec4`] is only 8-byte
/// aligned (for some reason), and integer vectors are only 4-byte aligned,
/// which means that reference-casting from those glam types to `Point4` type
/// will fail (but not the other way around).
#[cfg_attr(not(target_arch = "spirv"), repr(C))]
#[cfg_attr(
    all(not(target_arch = "wasm32"), feature = "wasmtime"),
    derive(
        wasmtime::component::ComponentType,
        wasmtime::component::Lower,
        wasmtime::component::Lift
    )
)]
#[cfg_attr(
    all(not(target_arch = "wasm32"), feature = "wasmtime"),
    component(record)
)]
pub struct Point4<U: Unit = f32> {
    /// X coordinate
    pub x: U::Scalar,
    /// Y coordinate
    pub y: U::Scalar,
    /// Z coordinate
    pub z: U::Scalar,
    /// W coordinate
    pub w: U::Scalar,
}

/// SAFETY: `T::Scalar` is `Zeroable`, and `Point4` is `#[repr(C)]`.
unsafe impl<T: Unit> Zeroable for Point4<T> {}
/// SAFETY: `T::Scalar` is `Pod`.
unsafe impl<T: Unit> Pod for Point4<T> {}
impl<T: Unit> Transparent for Point4<T> {
    type Wrapped = <T::Scalar as Scalar>::Vec4;
}

macro_rules! point_interface {
    ($base_type_name:ident, $vector_type:ident) => {
        /// Convert a vector to a point as-is.
        #[inline]
        pub fn from_vector(vec: $vector_type<T>) -> Self {
            vec.into()
        }

        /// Cast this point as-is to a vector.
        #[inline]
        pub fn to_vector(self) -> $vector_type<T> {
            self.into()
        }

        #[doc = "Reinterpret as vector."]
        #[inline]
        pub fn as_vector(&self) -> &$vector_type<T> {
            bytemuck::cast_ref(self)
        }

        #[doc = "Reinterpret as vector."]
        #[inline]
        pub fn as_vector_mut(&mut self) -> &mut $vector_type<T> {
            bytemuck::cast_mut(self)
        }

        /// Translate this point by vector.
        ///
        /// Equivalent to `self + by`.
        #[inline]
        #[must_use]
        pub fn translate(self, by: $vector_type<T>) -> Self {
            self + by
        }
    };
}

crate::impl_ops::point_ops!(Point2, Vector2);
crate::impl_ops::point_ops!(Point3, Vector3);
crate::impl_ops::point_ops!(Point4, Vector4);

impl<T: Unit> Point2<T> {
    /// New point.
    pub const fn new(x: T::Scalar, y: T::Scalar) -> Self {
        Point2 { x, y }
    }

    point_interface!(Point2, Vector2);
}

crate::impl_vectorlike::pointlike!(Point2, 2);

impl<T: Unit> Point3<T> {
    /// New point.
    pub const fn new(x: T::Scalar, y: T::Scalar, z: T::Scalar) -> Self {
        Point3 { x, y, z }
    }

    point_interface!(Point3, Vector3);
}

crate::impl_vectorlike::pointlike!(Point3, 3);

impl<T: Unit> Point4<T> {
    /// New point.
    pub const fn new(x: T::Scalar, y: T::Scalar, z: T::Scalar, w: T::Scalar) -> Self {
        Point4 { x, y, z, w }
    }

    point_interface!(Point4, Vector4);
}

crate::impl_vectorlike::pointlike!(Point4, 4);

impl<T> Point3<T>
where
    T: Unit<Scalar = f32>,
{
    /// Create from SIMD-aligned [`glam::Vec3A`].
    ///
    /// See [the design limitations](crate::docs::design#vector-overalignment)
    /// for why this is needed.
    #[inline]
    #[must_use]
    pub fn from_vec3a(vec: glam::Vec3A) -> Self {
        vec.into()
    }

    /// Convert to SIMD-aligned [`glam::Vec3A`].
    ///
    /// See [the design limitations](crate::docs::design#vector-overalignment)
    /// for why this is needed.
    #[inline]
    #[must_use]
    pub fn to_vec3a(self) -> glam::Vec3A {
        self.into()
    }
}

impl<T> Mul<Point3<T>> for glam::Quat
where
    T: Unit<Scalar = f32>,
{
    type Output = Point3<T>;

    fn mul(self, rhs: Point3<T>) -> Self::Output {
        wrap(self * peel(rhs))
    }
}

impl<T> Mul<Point3<T>> for glam::DQuat
where
    T: Unit<Scalar = f64>,
{
    type Output = Point3<T>;

    fn mul(self, rhs: Point3<T>) -> Self::Output {
        wrap(self * peel(rhs))
    }
}

impl<T: Unit> From<Vector2<T>> for Point2<T> {
    fn from(vec: Vector2<T>) -> Point2<T> {
        rewrap(vec)
    }
}

impl<T: Unit> From<Vector3<T>> for Point3<T> {
    #[inline]
    fn from(vec: Vector3<T>) -> Point3<T> {
        rewrap(vec)
    }
}

impl<T: Unit> From<Vector4<T>> for Point4<T> {
    #[inline]
    fn from(vec: Vector4<T>) -> Point4<T> {
        rewrap(vec)
    }
}

impl<T: Unit> From<Point2<T>> for Vector2<T> {
    #[inline]
    fn from(point: Point2<T>) -> Vector2<T> {
        rewrap(point)
    }
}

impl<T: Unit> From<Point3<T>> for Vector3<T> {
    #[inline]
    fn from(point: Point3<T>) -> Vector3<T> {
        rewrap(point)
    }
}

impl<T: Unit> From<Point4<T>> for Vector4<T> {
    #[inline]
    fn from(point: Point4<T>) -> Vector4<T> {
        rewrap(point)
    }
}

impl<T: Unit> core::fmt::Debug for Point2<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_struct("Point2")
            .field("x", &self.x)
            .field("y", &self.y)
            .finish()
    }
}
impl<T: Unit> core::fmt::Debug for Point3<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_struct("Point3")
            .field("x", &self.x)
            .field("y", &self.y)
            .field("z", &self.z)
            .finish()
    }
}
impl<T: Unit> core::fmt::Debug for Point4<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_struct("Point4")
            .field("x", &self.x)
            .field("y", &self.y)
            .field("z", &self.z)
            .field("w", &self.w)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use crate::point;

    use super::*;

    type Point = super::Point3<f32>;

    #[test]
    #[expect(clippy::op_ref)]
    fn ops_by_scalar_ref() {
        let a = Point::new(1.0, 2.0, 3.0);
        let b = 2.0;
        let added = a + b;
        let subtracted = a - b;
        let multiplied = a * b;

        assert_eq!(a + &b, added);
        assert_eq!(&a + b, added);
        assert_eq!(&a + &b, added);
        assert_eq!(b + &a, added);
        assert_eq!(&b + a, added);
        assert_eq!(&b + &a, added);
        assert_eq!(a - &b, subtracted);
        assert_eq!(&a - b, subtracted);
        assert_eq!(&a - &b, subtracted);
        assert_eq!(b - &a, subtracted);
        assert_eq!(&b - a, subtracted);
        assert_eq!(&b - &a, subtracted);
        assert_eq!(a * &b, multiplied);
        assert_eq!(&a * b, multiplied);
        assert_eq!(&a * &b, multiplied);
        assert_eq!(b * &a, multiplied);
        assert_eq!(&b * a, multiplied);
        assert_eq!(&b * &a, multiplied);

        let mut a2 = a;
        a2 += &b;
        assert_eq!(a2, added);
        let mut a2 = a;
        a2 -= &b;
        assert_eq!(a2, subtracted);
        let mut a2 = a;
        a2 *= &b;
        assert_eq!(a2, multiplied);
    }

    #[test]
    fn subtraction_yields_vector() {
        let p = Point::ONE;
        let q = Point::ONE;
        let v: Vector3<f32> = q - p;
        assert_eq!(v, Vector3::<f32>::ZERO);
    }

    #[test]
    fn vec3a() {
        let a: glam::Vec3A = Point::new(0.0, 1.0, 2.0).to_vec3a();
        assert_eq!(a, glam::Vec3A::new(0.0, 1.0, 2.0));
        let b = Point::from_vec3a(a);
        assert_eq!(b, Point::new(0.0, 1.0, 2.0));
    }

    #[test]
    fn rotate() {
        use crate::Angle;
        use approx::assert_abs_diff_eq;

        let v = Point3::<f32>::new(1.0, 0.0, 0.0);
        let quat = Angle::from_degrees(180.0f32).to_rotation(Vector3::Z);
        assert_abs_diff_eq!(quat * v, -v);

        let v = Point3::<f64>::new(1.0, 0.0, 0.0);
        let quat = Angle::from_degrees(180.0f64).to_rotation(Vector3::Z);
        assert_abs_diff_eq!(quat * v, -v);
    }

    #[test]
    fn from_into_vector2() {
        let mut p: Point2<f32> = point!(1.0, 2.0);
        let mut v: Vector2<f32> = p.to_vector();
        let q: Point2<f32> = Point2::from_vector(v);
        assert_eq!(p, q);
        assert_eq!(Vector2::from_point(p), v);

        let _: &Vector2<_> = p.as_vector();
        let _: &mut Vector2<_> = p.as_vector_mut();
        let _: &Point2<_> = v.as_point();
        let _: &mut Point2<_> = v.as_point_mut();
    }

    #[test]
    fn from_into_vector3() {
        let mut p: Point3<f32> = point!(1.0, 2.0, 3.0);
        let mut v: Vector3<f32> = p.to_vector();
        let q: Point3<f32> = Point3::from_vector(v);
        assert_eq!(p, q);
        assert_eq!(Vector3::from_point(p), v);

        let _: &Vector3<_> = p.as_vector();
        let _: &mut Vector3<_> = p.as_vector_mut();
        let _: &Point3<_> = v.as_point();
        let _: &mut Point3<_> = v.as_point_mut();
    }

    #[test]
    fn from_into_vector4() {
        let mut p: Point4<f32> = point!(1.0, 2.0, 3.0, 4.0);
        let mut v: Vector4<f32> = p.to_vector();
        let q: Point4<f32> = Point4::from_vector(v);
        assert_eq!(p, q);
        assert_eq!(Vector4::from_point(p), v);

        let _: &Vector4<_> = p.as_vector();
        let _: &mut Vector4<_> = p.as_vector_mut();
        let _: &Point4<_> = v.as_point();
        let _: &mut Point4<_> = v.as_point_mut();
    }

    #[test]
    fn extend() {
        let p2: Point2<f32> = point!(1.0, 2.0);
        let p3: Point3<f32> = p2.extend(3.0);
        assert_eq!(p3, point!(1.0, 2.0, 3.0));
        let p4: Point4<f32> = p3.extend(4.0);
        assert_eq!(p4, point!(1.0, 2.0, 3.0, 4.0));
    }

    #[test]
    fn manhattan_distance() {
        let a: Point3<i16> = point![1, 1, 1];
        let b: Point3<i16> = point![2, 2, 2];
        let d: u16 = a.manhattan_distance(b);
        assert_eq!(d, 3);

        let a: Point3<i16> = point![0, 0, 0];
        let b: Point3<i16> = point![i16::MAX, i16::MAX, 2];
        let d: Option<u16> = a.checked_manhattan_distance(b);
        assert_eq!(d, None);
    }

    #[test]
    fn chebyshev_distance() {
        let a: Point3<i16> = point![1, 1, 1];
        let b: Point3<i16> = point![2, 2, 3];
        let d: u16 = a.chebyshev_distance(b);
        assert_eq!(d, 2);
    }

    #[test]
    fn gaslight_coverage() {
        extern crate alloc;
        _ = alloc::format!("{:?}", Point2::<f32>::default());
        _ = alloc::format!("{:?}", Point3::<f32>::default());
        _ = alloc::format!("{:?}", Point4::<f32>::default());
    }
}