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
pub use cgmath;
pub use self::cgmath::num_traits::{self, Bounded, Float, NumCast, One, Zero};
pub use self::cgmath::prelude;
pub use self::cgmath::{
Basis2, Basis3, Decomposed, Deg, Euler, Matrix2, Matrix3, Matrix4, Ortho, Perspective,
PerspectiveFov, Quaternion, Rad,
};
pub use self::cgmath::{
Angle, Array, BaseFloat, BaseNum, ElementWise, EuclideanSpace, InnerSpace, Matrix, MetricSpace,
Rotation, Rotation2, Rotation3, SquareMatrix, Transform, Transform2, Transform3, VectorSpace,
};
use std::ops::Add;
pub fn map_range<X, Y>(val: X, in_min: X, in_max: X, out_min: Y, out_max: Y) -> Y
where
X: NumCast,
Y: NumCast,
{
macro_rules! unwrap_or_panic {
($result:expr, $arg:expr) => {
$result.unwrap_or_else(|| panic!("[map_range] failed to cast {} arg to `f64`"))
};
}
let val_f: f64 = unwrap_or_panic!(NumCast::from(val), "first");
let in_min_f: f64 = unwrap_or_panic!(NumCast::from(in_min), "second");
let in_max_f: f64 = unwrap_or_panic!(NumCast::from(in_max), "third");
let out_min_f: f64 = unwrap_or_panic!(NumCast::from(out_min), "fourth");
let out_max_f: f64 = unwrap_or_panic!(NumCast::from(out_max), "fifth");
NumCast::from((val_f - in_min_f) / (in_max_f - in_min_f) * (out_max_f - out_min_f) + out_min_f)
.unwrap_or_else(|| panic!("[map_range] failed to cast result to target type"))
}
pub fn partial_max<T>(a: T, b: T) -> T
where
T: PartialOrd,
{
if a >= b {
a
} else {
b
}
}
pub fn partial_min<T>(a: T, b: T) -> T
where
T: PartialOrd,
{
if a <= b {
a
} else {
b
}
}
pub fn clamp<T>(n: T, start: T, end: T) -> T
where
T: PartialOrd,
{
if start <= end {
if n < start {
start
} else if n > end {
end
} else {
n
}
} else {
if n < end {
end
} else if n > start {
start
} else {
n
}
}
}
pub fn two<S>() -> S
where
S: Add<Output = S> + One,
{
S::one() + S::one()
}
#[inline]
pub fn fmod<F>(numer: F, denom: F) -> F
where
F: Float,
{
let rquot: F = (numer / denom).floor();
numer - rquot * denom
}
pub fn deg_to_rad<S>(deg: S) -> S
where
S: BaseFloat,
{
Rad::from(Deg(deg)).0
}
pub fn rad_to_deg<S>(rad: S) -> S
where
S: BaseFloat,
{
Deg::from(Rad(rad)).0
}
pub fn turns_to_rad<S>(turns: S) -> S
where
S: BaseFloat,
{
turns * NumCast::from(2.0 * ::std::f64::consts::PI).unwrap()
}
pub fn rad_to_turns<S>(rad: S) -> S
where
S: BaseFloat,
{
rad / NumCast::from(2.0 * ::std::f64::consts::PI).unwrap()
}