cvmath 0.0.8

Computer Graphics Vector Math Library
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
/*!
Angles.
*/
use super::*;

/// Angle in radians.
#[derive(Copy, Clone, Default, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct Angle<T> {
	pub radians: T,
}

/// Angle constructor.
#[allow(non_snake_case)]
#[inline]
pub const fn Angle<T>(radians: T) -> Angle<T> {
	Angle { radians }
}

impl<T: Zero> Zero for Angle<T> {
	const ZERO: Angle<T> = Angle { radians: T::ZERO };
}

impl<T: Float> Angle<T> {
	/// Constructs a new angle from radians.
	#[inline]
	pub const fn new(radians: T) -> Angle<T> {
		Angle { radians }
	}

	/// Constructs a new angle from degrees.
	#[inline]
	pub fn deg(degrees: T) -> Angle<T> {
		let radians = degrees * (T::TAU / T::THREE_SIXTY);
		Angle { radians }
	}

	/// Constant 360° angle or 2π radians.
	pub const TAU: Angle<T> = Angle(T::TAU);
	/// Constant 180° angle or π radians.
	pub const PI: Angle<T> = Angle(T::PI);
	#[doc(hidden)]
	pub const TURN: Angle<T> = Angle(T::TAU);
	#[doc(hidden)]
	pub const HALF: Angle<T> = Angle(T::PI);
	/// Constant 90° angle or π/2 radians.
	pub const QUARTER: Angle<T> = Angle(T::FRAC_PI_2);
	/// Constant 0° angle or 0 radians.
	pub const ZERO: Angle<T> = Angle(T::ZERO);

	/// Normalizes the angle to range -180°, 180° or -π rad, π rad.
	#[inline]
	pub fn norm(self) -> Self {
		let div = self.radians / T::TAU;
		Angle(self.radians - div.round() * T::TAU)
	}

	/// Normalizes the angle to range 0°, 360° or 0 rad, 2π rad.
	#[inline]
	pub fn norm_abs(self) -> Self {
		let div = self.radians / T::TAU;
		Angle(self.radians - div.floor() * T::TAU)
	}

	/// Absolute value of the angle.
	#[inline]
	pub fn abs(self) -> Self {
		Angle(self.radians.abs())
	}

	/// Sine.
	#[inline]
	pub fn sin(self) -> T {
		self.radians.sin()
	}
	/// Cosine.
	#[inline]
	pub fn cos(self) -> T {
		self.radians.cos()
	}
	/// Tangent.
	#[inline]
	pub fn tan(self) -> T {
		self.radians.tan()
	}
	/// Sine and cosine.
	#[inline]
	pub fn sin_cos(self) -> (T, T) {
		self.radians.sin_cos()
	}

	/// Converts the angle to a normalized 2D vector.
	#[inline]
	pub fn vec2(self) -> Vec2<T> {
		let (s, c) = self.sin_cos();
		Vec2(c, s)
	}
	/// Converts the angle to polar coordinates.
	#[inline]
	pub fn polar(self, radius: T) -> Polar<T> {
		Polar { radius, theta: self }
	}

	#[inline]
	pub fn asin(sin: T) -> Self {
		Angle(sin.asin())
	}
	#[inline]
	pub fn acos(cos: T) -> Self {
		Angle(cos.acos())
	}
	#[inline]
	pub fn atan(tan: T) -> Self {
		Angle(tan.atan())
	}
	#[inline]
	pub fn atan2(y: T, x: T) -> Self {
		Angle(y.atan2(x))
	}

	/// Linear interpolation between the angles, prefers the shorter path.
	#[inline]
	pub fn lerp_shortest(self, target: Self, t: T) -> Self {
		self + (target - self).norm() * t
	}

	/// Converts to degrees.
	#[inline]
	pub fn to_deg(self) -> T {
		self.radians * (T::THREE_SIXTY / T::TAU)
	}
	/// Casts the angle to another type.
	#[inline]
	pub fn cast<U>(self) -> Angle<U> where T: CastTo<U> {
		Angle(self.radians.cast_to())
	}
}

impl<T: Extrema> Extrema for Angle<T> {
	#[inline]
	fn min(self, rhs: Angle<T>) -> Angle<T> {
		Angle(self.radians.min(rhs.radians))
	}
	#[inline]
	fn max(self, rhs: Angle<T>) -> Angle<T> {
		Angle(self.radians.max(rhs.radians))
	}
	#[inline]
	fn min_max(self, rhs: Angle<T>) -> (Angle<T>, Angle<T>) {
		let (min, max) = self.radians.min_max(rhs.radians);
		(Angle(min), Angle(max))
	}
}

impl<T: Extrema> Angle<T> {
	/// Returns the smaller of two angles.
	#[inline]
	pub fn min(self, rhs: Angle<T>) -> Angle<T> {
		Angle(self.radians.min(rhs.radians))
	}
	/// Returns the larger of two angles.
	#[inline]
	pub fn max(self, rhs: Angle<T>) -> Angle<T> {
		Angle(self.radians.max(rhs.radians))
	}
	/// Returns angles in order: (smaller, larger).
	#[inline]
	pub fn min_max(self, rhs: Angle<T>) -> (Angle<T>, Angle<T>) {
		let (min, max) = self.radians.min_max(rhs.radians);
		(Angle(min), Angle(max))
	}
	/// Clamps the angle to the [min, max] range.
	#[inline]
	pub fn clamp(self, min: Angle<T>, max: Angle<T>) -> Angle<T> {
		Angle(self.radians.clamp(min.radians, max.radians))
	}
}

specialized_type!(Angle, Anglef, f32, radians);
specialized_type!(Angle, Angled, f64, radians);

//----------------------------------------------------------------
// Conversions

impl<T> AsRef<T> for Angle<T> {
	#[inline]
	fn as_ref(&self) -> &T {
		&self.radians
	}
}
impl<T> AsMut<T> for Angle<T> {
	#[inline]
	fn as_mut(&mut self) -> &mut T {
		&mut self.radians
	}
}

//----------------------------------------------------------------
// Operators

impl<T: ops::Add<Output = T>> ops::Add<Angle<T>> for Angle<T> {
	type Output = Angle<T>;
	#[inline]
	fn add(self, rhs: Angle<T>) -> Angle<T> {
		Angle(self.radians + rhs.radians)
	}
}
impl<T: ops::Sub<Output = T>> ops::Sub<Angle<T>> for Angle<T> {
	type Output = Angle<T>;
	#[inline]
	fn sub(self, rhs: Angle<T>) -> Angle<T> {
		Angle(self.radians - rhs.radians)
	}
}
impl<T: ops::Neg<Output = T>> ops::Neg for Angle<T> {
	type Output = Angle<T>;
	#[inline]
	fn neg(self) -> Angle<T> {
		Angle(-self.radians)
	}
}

impl<T: ops::Mul<Output = T>> ops::Mul<T> for Angle<T> {
	type Output = Angle<T>;
	#[inline]
	fn mul(self, rhs: T) -> Angle<T> {
		Angle(self.radians * rhs)
	}
}
impl<T: ops::Div<Output = T>> ops::Div<T> for Angle<T> {
	type Output = Angle<T>;
	#[inline]
	fn div(self, rhs: T) -> Angle<T> {
		Angle(self.radians / rhs)
	}
}
impl<T: ops::Div<Output = T>> ops::Div<Angle<T>> for Angle<T> {
	type Output = T;
	#[inline]
	fn div(self, rhs: Angle<T>) -> T {
		self.radians / rhs.radians
	}
}

impl<T: ops::AddAssign> ops::AddAssign for Angle<T> {
	#[inline]
	fn add_assign(&mut self, rhs: Angle<T>) {
		self.radians += rhs.radians;
	}
}
impl<T: ops::SubAssign> ops::SubAssign for Angle<T> {
	#[inline]
	fn sub_assign(&mut self, rhs: Angle<T>) {
		self.radians -= rhs.radians;
	}
}

impl<T: Float> Lerp for Angle<T> {
	type T = T;

	#[inline]
	fn lerp(self, other: Self, t: T) -> Self {
		self + (other - self) * t
	}
}

//----------------------------------------------------------------
// Random

#[cfg(feature = "urandom")]
impl<T: Float + urandom::distr::SampleUniform> urandom::Distribution<Angle<T>> for urandom::distr::StandardUniform {
	#[inline]
	fn sample<R: urandom::Rng + ?Sized>(&self, rand: &mut urandom::Random<R>) -> Angle<T> {
		let rad = rand.sample(&urandom::distr::Uniform::new(T::ZERO, T::TAU));
		Angle(rad)
	}
}

//----------------------------------------------------------------
// Formatting

macro_rules! fmt {
	($fmt:path) => {
		impl<T: $fmt + Float> $fmt for Angle<T> {
			fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
				<T as $fmt>::fmt(&self.to_deg(), f)?;
				f.write_str("°")
			}
		}
	};
}

fmt!(fmt::Display);
fmt!(fmt::Debug);
fmt!(fmt::UpperExp);
fmt!(fmt::LowerExp);

//----------------------------------------------------------------
// Parsing

impl<T: Float + FromStr> FromStr for Angle<T> {
	type Err = T::Err;
	fn from_str(s: &str) -> Result<Angle<T>, T::Err> {
		let (s, degrees) = if let Some(s) = s.strip_suffix("°").or_else(|| s.strip_suffix("deg")) {
			(s.trim_ascii_end(), true)
		}
		else if let Some(s) = s.strip_suffix("rad") {
			(s.trim_ascii_end(), false)
		}
		else {
			(s, false)
		};
		let value = T::from_str(s)?;
		Ok(if degrees { Angle::deg(value) } else { Angle(value) })
	}
}

//----------------------------------------------------------------

#[cfg(feature = "serde")]
impl<T: serde::Serialize + 'static> serde::Serialize for Angle<T> {
	fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
		// Pseudo specialization for f32 and f64
		if let Some(&float) = (&self.radians as &dyn std::any::Any).downcast_ref::<f32>() {
			float.to_degrees().serialize(serializer)
		}
		else if let Some(&double) = (&self.radians as &dyn std::any::Any).downcast_ref::<f64>() {
			double.to_degrees().serialize(serializer)
		}
		else {
			self.radians.serialize(serializer)
		}
	}
}

#[cfg(feature = "serde")]
impl<'de, T: serde::Deserialize<'de> + 'static> serde::Deserialize<'de> for Angle<T> {
	fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Angle<T>, D::Error> {
		// Pseudo specialization for f32 and f64
		let mut value = T::deserialize(deserializer)?;
		if let Some(float) = (&mut value as &mut dyn std::any::Any).downcast_mut::<f32>() {
			*float = float.to_radians();
		}
		else if let Some(double) = (&mut value as &mut dyn std::any::Any).downcast_mut::<f64>() {
			*double = double.to_radians();
		}
		Ok(Angle(value))
	}
}

//----------------------------------------------------------------

#[cfg(test)]
mod tests {
	use super::*;

	fn deg<T: Float>(degrees: T) -> Angle<T> {
		Angle::deg(degrees)
	}

	#[track_caller]
	fn assert_eq<T: Float>(a: Angle<T>, b: Angle<T>) {
		assert_eq!(format!("{:.4}", a), format!("{:.4}", b), "angles not equal: {} != {}", a, b);
	}

	#[test]
	fn normalize() {
		assert_eq(deg(179.0), deg(-181.0).norm());
		assert_eq(deg(-179.0), deg(181.0).norm());
		assert_eq(deg(0.125), deg(360.125).norm());
		assert_eq(deg(180.0), deg(-180.0).norm());
		assert_eq(deg(-180.0), deg(180.0).norm());
	}

	#[test]
	fn normalize_abs() {
		assert_eq(deg(179.0), deg(-181.0).norm_abs());
		assert_eq(deg(181.0), deg(181.0).norm_abs());
		assert_eq(deg(1.0), deg(361.0).norm_abs());
		assert_eq(deg(180.0), deg(-180.0).norm_abs());
		assert_eq(deg(359.0), deg(359.0).norm_abs());
	}

	#[test]
	fn lerps() {
		assert_eq(deg(45.0), deg(0.0).lerp_shortest(deg(90.0), 0.5));
		assert_eq(deg(-90.0), deg(0.0).lerp_shortest(deg(180.0), 0.5));
		assert_eq(deg(0.0), deg(0.0).lerp_shortest(deg(360.0), 0.5));
	}

	#[test]
	fn formatting() {
		assert_eq!("12°", format!("{:.0}", deg(12.1f32)));
		assert_eq!(" 12.0°", format!("{:>5.1}", deg(12.0)));
	}

	#[test]
	fn parse() {
		assert_eq!(Angle::<f32>::TAU, "360°".parse().unwrap());
		assert_eq!(Angle(1.5f32), "1.5 rad".parse().unwrap());
		assert_eq!(Angle(2.5f64), "2.5".parse().unwrap());
		assert_eq!(deg(180f32), "180°".parse().unwrap());
		assert_eq!(deg(90f32), "90deg".parse().unwrap());
	}
}