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
//! Generic angles.

use approx::{AbsDiffEq, RelativeEq, UlpsEq};
use bytemuck::{Pod, Zeroable};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign};

use crate::{
    bindings::Quat, peel, scalar::FloatScalar, traits::marker::PodValue, Scalar, Transparent, Unit,
    Vector3,
};

/// Angle in radians.
#[repr(transparent)]
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
#[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 Angle<U: Scalar = f32> {
    /// Angle in radians.
    pub radians: U,
}
unsafe impl<T: Scalar> Zeroable for Angle<T> {}
unsafe impl<T: Scalar> Pod for Angle<T> {}
unsafe impl<T: Scalar> Transparent for Angle<T> {
    type Wrapped = T;
}

/// Strongly typed angle constants.
///
/// These allow common constants used as angles to be strongly typed (so it's
/// possible to write `Angle::<f32>::PI` instead of
/// `Angle::radians(core::f32::PI)`).
///
/// Note that this is also the most convenient way to get these constants in a
/// `const` context. Since [`Angle`][crate::Angle] is a generic type, the
/// [`Angle::from_radians()`](crate::Angle::from_radians) constructor cannot be
/// invoked in a const context. This is also why [`num_traits::FloatConst`] is
/// not good enough.
pub trait AngleConsts {
    /// π
    const PI: Self;

    /// τ = 2π
    const TAU: Self;

    /// 1.0 / π
    const FRAG_1_PI: Self;
    /// 2.0 / π
    const FRAG_2_PI: Self;

    /// π / 2.0
    const FRAG_PI_2: Self;
    /// π / 3.0
    const FRAG_PI_3: Self;
    /// π / 4.0
    const FRAG_PI_4: Self;
    /// π / 6.0
    const FRAG_PI_6: Self;
    /// π / 8.0
    const FRAG_PI_8: Self;
}

macro_rules! impl_float_angle_consts {
    ($float:ident) => {
        impl AngleConsts for $float {
            const PI: Self = core::$float::consts::PI;
            const TAU: Self = Self::PI + Self::PI;

            const FRAG_1_PI: Self = 1.0 / Self::PI;
            const FRAG_2_PI: Self = 2.0 / Self::PI;
            const FRAG_PI_2: Self = Self::PI / 2.0;
            const FRAG_PI_3: Self = Self::PI / 3.0;
            const FRAG_PI_4: Self = Self::PI / 4.0;
            const FRAG_PI_6: Self = Self::PI / 6.0;
            const FRAG_PI_8: Self = Self::PI / 8.0;
        }
    };
}

impl_float_angle_consts!(f32);
impl_float_angle_consts!(f64);

macro_rules! forward_to_float_as_angle {
    (
        $(#[$attr:meta])?
        fn $f:ident(self $(, $args:ident: $args_ty:ty)*) -> Angle<Self>) => {
        $(#[$attr])?
        #[must_use]
        #[inline]
        fn $f(self, $($args: $args_ty),*) -> Angle<Self> {
            Angle::from_radians(<Self as num_traits::Float>::$f(self $($args),*))
        }
    };
}

/// Convenience trait to create strongly typed angles from floats.
pub trait FloatAngleExt: FloatScalar + AngleConsts + PodValue {
    forward_to_float_as_angle!(
        #[doc = "asin()"]
        fn asin(self) -> Angle<Self>
    );
    forward_to_float_as_angle!(
        #[doc = "acos()"]
        fn acos(self) -> Angle<Self>);
    forward_to_float_as_angle!(
        #[doc = "atan()"]
        fn atan(self) -> Angle<Self>
    );
}

impl FloatAngleExt for f32 {}
impl FloatAngleExt for f64 {}

impl<T: Scalar + AngleConsts> core::fmt::Debug for Angle<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        use core::fmt::Write;
        f.write_str("Angle(")?;
        let r = self.radians;
        if r == T::PI {
            f.write_char('π')?;
        } else if r == T::TAU {
            f.write_str("2π")?;
        } else if r == T::FRAG_1_PI {
            f.write_str("1/π")?;
        } else if r == T::FRAG_2_PI {
            f.write_str("2/π")?;
        } else if r == T::FRAG_PI_2 {
            f.write_str("π/2")?;
        } else if r == T::FRAG_PI_3 {
            f.write_str("π/3")?;
        } else if r == T::FRAG_PI_4 {
            f.write_str("π/4")?;
        } else if r == T::FRAG_PI_6 {
            f.write_str("π/6")?;
        } else if r == T::FRAG_PI_8 {
            f.write_str("π/8")?;
        } else {
            write!(f, "{r:0.5}")?;
        }
        f.write_char(')')
    }
}

impl<T> Unit for Angle<T>
where
    T: Scalar + AngleConsts,
{
    type Scalar = T;
}

impl<T: Scalar> AbsDiffEq for Angle<T> {
    type Epsilon = T::Epsilon;

    #[inline]
    fn default_epsilon() -> Self::Epsilon {
        T::default_epsilon()
    }

    #[inline]
    fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
        self.radians.abs_diff_eq(&other.radians, epsilon)
    }

    #[inline]
    fn abs_diff_ne(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
        self.radians.abs_diff_ne(&other.radians, epsilon)
    }
}

impl<T: FloatScalar> UlpsEq for Angle<T> {
    #[inline]
    fn default_max_ulps() -> u32 {
        T::default_max_ulps()
    }

    #[inline]
    fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
        self.radians.ulps_eq(&other.radians, epsilon, max_ulps)
    }

    #[inline]
    fn ulps_ne(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
        self.radians.ulps_ne(&other.radians, epsilon, max_ulps)
    }
}

impl<T: FloatScalar> RelativeEq for Angle<T> {
    #[inline]
    fn default_max_relative() -> Self::Epsilon {
        T::default_max_relative()
    }

    #[inline]
    fn relative_eq(
        &self,
        other: &Self,
        epsilon: Self::Epsilon,
        max_relative: Self::Epsilon,
    ) -> bool {
        self.radians
            .relative_eq(&other.radians, epsilon, max_relative)
    }

    #[inline]
    fn relative_ne(
        &self,
        other: &Self,
        epsilon: Self::Epsilon,
        max_relative: Self::Epsilon,
    ) -> bool {
        self.radians
            .relative_ne(&other.radians, epsilon, max_relative)
    }
}

macro_rules! forward_to_unit {
    (
        $(#[$attr:meta])?
        fn $f:ident(self $(, $args:ident: $args_ty:ty)*) -> $ret:ty) => {
        $(#[$attr])*
        #[must_use]
        #[inline]
        pub fn $f(self, $($args: $args_ty),*) -> $ret {
            self.radians.$f($($args),*)
        }
    };
}

macro_rules! forward_to_unit_as_self {
    (
        $(#[$attr:meta])?
        fn $f:ident(self $(, $args:ident: $args_ty:ty)*) -> Self) => {
        $(#[$attr])*
        #[must_use]
        #[inline]
        pub fn $f(self,  $($args: $args_ty),*) -> Angle<T> {
            Angle::from_radians(self.radians.$f($($args.radians),*))
        }
    };
}

impl<T: FloatScalar> Angle<T> {
    /// Angle from radians.
    #[inline]
    #[must_use]
    pub const fn new(radians: T) -> Self {
        Angle { radians }
    }

    /// Angle from radians.
    #[inline]
    #[must_use]
    pub const fn from_radians(radians: T) -> Self {
        Angle::new(radians)
    }

    /// Angle from degrees.
    ///
    /// Will be converted to radians internally.
    #[inline]
    #[must_use]
    pub fn from_degrees(degrees: T) -> Self {
        Self::from_radians(degrees.to_radians())
    }

    /// Get this angle in radians.
    #[inline]
    #[must_use]
    pub const fn to_radians(self) -> T {
        self.radians
    }

    forward_to_unit!(
        #[doc = "See [num_traits::Float::to_degrees()]"]
        fn to_degrees(self) -> T);
    forward_to_unit!(
        #[doc = "See [num_traits::Float::sin()]."]
        fn sin(self) -> T);
    forward_to_unit!(
        #[doc = "See [num_traits::Float::cos()]."]
        fn cos(self) -> T);
    forward_to_unit!(
        #[doc = "See [num_traits::Float::tan()]."]
        fn tan(self) -> T);
    forward_to_unit!(
        #[doc = "See [num_traits::Float::sin_cos()]."]
        fn sin_cos(self) -> (T, T));

    forward_to_unit_as_self!(
        #[doc = "See [num_traits::Float::min()]."]
        fn min(self, other: Self) -> Self);
    forward_to_unit_as_self!(
        #[doc = "See [num_traits::Float::max()]."]
        fn max(self, other: Self) -> Self);
}

impl<T: FloatScalar + AngleConsts> Angle<T> {
    /// 2π
    pub const CIRCLE: Self = Self::TAU;
    /// π
    pub const HALF_CIRCLE: Self = Self::PI;
    /// π/2
    pub const QUARTER_CIRCLE: Self = Self::FRAG_PI_2;
}

impl<T: Scalar> From<T> for Angle<T> {
    fn from(radians: T) -> Self {
        Angle { radians }
    }
}

macro_rules! forward_op_scalar {
    ($trait_name:ident, $op:ident) => {
        impl<T: FloatScalar> $trait_name<T> for Angle<T> {
            type Output = Self;

            fn $op(self, rhs: T) -> Self {
                Angle {
                    radians: self.radians.$op(rhs),
                }
            }
        }
    };
}

macro_rules! forward_op_scalar_assign {
    ($trait_name:ident, $op:ident) => {
        impl<T: FloatScalar> $trait_name<T> for Angle<T> {
            fn $op(&mut self, rhs: T) {
                self.radians.$op(rhs);
            }
        }
    };
}

macro_rules! forward_op_self {
    ($trait_name:ident, $op:ident) => {
        impl<T: FloatScalar> $trait_name for Angle<T> {
            type Output = Self;

            fn $op(self, rhs: Self) -> Self {
                Angle {
                    radians: self.radians.$op(rhs.radians),
                }
            }
        }
    };
}

macro_rules! forward_op_self_assign {
    ($trait_name:ident, $op:ident) => {
        impl<T: FloatScalar> $trait_name for Angle<T> {
            fn $op(&mut self, rhs: Self) {
                self.radians.$op(rhs.radians);
            }
        }
    };
}

forward_op_scalar!(Mul, mul);
forward_op_scalar!(Div, div);
forward_op_scalar!(Rem, rem);
forward_op_scalar_assign!(MulAssign, mul_assign);
forward_op_scalar_assign!(DivAssign, div_assign);
forward_op_scalar_assign!(RemAssign, rem_assign);

forward_op_self!(Add, add);
forward_op_self!(Sub, sub);
forward_op_self!(Rem, rem);
forward_op_self_assign!(AddAssign, add_assign);
forward_op_self_assign!(SubAssign, sub_assign);
forward_op_self_assign!(RemAssign, rem_assign);

impl<T: Scalar> Div<Angle<T>> for Angle<T> {
    type Output = T;

    fn div(self, rhs: Angle<T>) -> Self::Output {
        self.radians / rhs.radians
    }
}

impl<T: FloatScalar + AngleConsts> AngleConsts for Angle<T> {
    const PI: Self = Angle { radians: T::PI };
    const TAU: Self = Angle { radians: T::TAU };

    const FRAG_1_PI: Self = Angle {
        radians: T::FRAG_1_PI,
    };
    const FRAG_2_PI: Self = Angle {
        radians: T::FRAG_2_PI,
    };
    const FRAG_PI_2: Self = Angle {
        radians: T::FRAG_PI_2,
    };
    const FRAG_PI_3: Self = Angle {
        radians: T::FRAG_PI_3,
    };
    const FRAG_PI_4: Self = Angle {
        radians: T::FRAG_PI_4,
    };
    const FRAG_PI_6: Self = Angle {
        radians: T::FRAG_PI_6,
    };
    const FRAG_PI_8: Self = Angle {
        radians: T::FRAG_PI_8,
    };
}

impl<T: FloatScalar> Angle<T> {
    /// Create quaternion from this angle and an axis vector.
    #[inline]
    #[must_use]
    pub fn to_rotation(self, axis: Vector3<T>) -> T::Quat {
        <T::Quat as Quat<T>>::from_axis_angle(peel(axis), self.radians)
    }
}

#[cfg(test)]
mod tests {
    use approx::{
        assert_abs_diff_eq, assert_abs_diff_ne, assert_relative_eq, assert_relative_ne,
        assert_ulps_eq, assert_ulps_ne,
    };

    use crate::{peel_mut, peel_ref};

    use super::*;

    type Angle = super::Angle<f32>;

    #[test]
    fn forward_to_float() {
        use super::FloatAngleExt;
        let s: Angle = FloatAngleExt::asin(1.0f32);
        let c: Angle = FloatAngleExt::acos(1.0f32);
        let t: Angle = FloatAngleExt::atan(1.0f32);
        assert_eq!(s.to_radians(), f32::asin(1.0f32));
        assert_eq!(c.to_radians(), f32::acos(1.0f32));
        assert_eq!(t.to_radians(), f32::atan(1.0f32));

        assert_eq!(Angle::PI.clone(), Angle::PI);
        assert_eq!(Angle::default(), Angle::from_radians(0.0));
        assert!(Angle::PI >= Angle::default());
    }

    #[test]
    fn min_max() {
        assert_eq!(
            Angle::from_radians(1.0).max(Angle::from_radians(2.0)),
            Angle::from_radians(2.0)
        );
        assert_eq!(
            Angle::from_radians(1.0).min(Angle::from_radians(2.0)),
            Angle::from_radians(1.0)
        );
    }

    #[test]
    fn approx_comparison() {
        assert_eq!(Angle::PI, Angle::from_radians(f32::PI));
        assert_ne!(Angle::PI, Angle::CIRCLE);

        assert_abs_diff_eq!(Angle::PI, Angle::PI);
        assert_relative_eq!(Angle::PI, Angle::PI);
        assert_ulps_eq!(Angle::PI, Angle::PI);
        assert_abs_diff_ne!(Angle::PI, Angle::CIRCLE);
        assert_relative_ne!(Angle::PI, Angle::CIRCLE);
        assert_ulps_ne!(Angle::PI, Angle::CIRCLE);
    }

    #[test]
    fn angle_arithmetic() {
        let a = Angle::from_radians(1.0);
        let b = Angle::from_radians(-0.5);
        assert_abs_diff_eq!(a + b, Angle::from_radians(0.5));
        assert_abs_diff_eq!(a * 2.0, Angle::from_radians(2.0));
        assert_abs_diff_eq!(a / 2.0, Angle::from_radians(0.5));
        assert_abs_diff_eq!(a / b, -2.0);

        let mut a = Angle::from_radians(1.0);
        a += Angle::from_radians(2.0);
        assert_eq!(a, Angle::from_radians(3.0));
        a -= Angle::from_radians(4.0);
        assert_eq!(a, Angle::from_radians(-1.0));
        let mut a = Angle::from_radians(3.0);
        a %= Angle::from_radians(2.0);
        assert_eq!(a, Angle::from_radians(1.0));
        a *= 2.0;
        assert_eq!(a, Angle::from_radians(2.0));
        a /= 2.0;
        assert_eq!(a, Angle::from_radians(1.0));
    }

    #[test]
    fn angle_degrees() {
        let circle = Angle::CIRCLE;
        assert_abs_diff_eq!(circle, Angle::from_degrees(360.0));
        assert_ulps_eq!(circle, Angle::from_degrees(360.0));
        assert_relative_eq!(circle, Angle::from_degrees(360.0));

        let quarter_circle = Angle::FRAG_PI_2;
        assert_abs_diff_eq!(quarter_circle, Angle::from_degrees(90.0));
        assert_ulps_eq!(quarter_circle, Angle::from_degrees(90.0));
        assert_relative_eq!(quarter_circle, Angle::from_degrees(90.0));
        assert_eq!(Angle::from_degrees(90.0).to_degrees(), 90.0);
    }

    #[test]
    fn angle_cast() {
        let mut a = Angle::CIRCLE;
        let _: &f32 = peel_ref(&a);
        let _: &mut f32 = peel_mut(&mut a);
        let _: f32 = peel(a);
        let _: f32 = a.to_radians();
        let _: Angle = 1.0.into();
    }

    #[test]
    fn to_rotation() {
        let angle = Angle::HALF_CIRCLE;
        let quat = angle.to_rotation(Vector3::Z);
        assert_abs_diff_eq!(quat, glam::Quat::from_axis_angle(glam::Vec3::Z, f32::PI));
        let v = quat * Vector3::<f32>::X;
        assert_abs_diff_eq!(v, -Vector3::X);
    }
}