1 //
2 // Copyright (c) 2008-2017 the Urho3D project.
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21 //
22 
23 #pragma once
24 
25 #ifdef _MSC_VER
26 #pragma warning(push)
27 #pragma warning(disable:4244) // Conversion from 'double' to 'float'
28 #pragma warning(disable:4702) // unreachable code
29 #endif
30 
31 #include "../Math/Random.h"
32 
33 #include <cstdlib>
34 #include <cmath>
35 #include <limits>
36 
37 namespace Urho3D
38 {
39 
40 #undef M_PI
41 static const float M_PI = 3.14159265358979323846264338327950288f;
42 static const float M_HALF_PI = M_PI * 0.5f;
43 static const int M_MIN_INT = 0x80000000;
44 static const int M_MAX_INT = 0x7fffffff;
45 static const unsigned M_MIN_UNSIGNED = 0x00000000;
46 static const unsigned M_MAX_UNSIGNED = 0xffffffff;
47 
48 static const float M_EPSILON = 0.000001f;
49 static const float M_LARGE_EPSILON = 0.00005f;
50 static const float M_MIN_NEARCLIP = 0.01f;
51 static const float M_MAX_FOV = 160.0f;
52 static const float M_LARGE_VALUE = 100000000.0f;
53 static const float M_INFINITY = (float)HUGE_VAL;
54 static const float M_DEGTORAD = M_PI / 180.0f;
55 static const float M_DEGTORAD_2 = M_PI / 360.0f;    // M_DEGTORAD / 2.f
56 static const float M_RADTODEG = 1.0f / M_DEGTORAD;
57 
58 /// Intersection test result.
59 enum Intersection
60 {
61     OUTSIDE,
62     INTERSECTS,
63     INSIDE
64 };
65 
66 /// Check whether two floating point values are equal within accuracy.
67 template <class T>
Equals(T lhs,T rhs)68 inline bool Equals(T lhs, T rhs) { return lhs + std::numeric_limits<T>::epsilon() >= rhs && lhs - std::numeric_limits<T>::epsilon() <= rhs; }
69 
70 /// Linear interpolation between two values.
71 template <class T, class U>
Lerp(T lhs,T rhs,U t)72 inline T Lerp(T lhs, T rhs, U t) { return lhs * (1.0 - t) + rhs * t; }
73 
74 /// Inverse linear interpolation between two values.
75 template <class T>
InverseLerp(T lhs,T rhs,T x)76 inline T InverseLerp(T lhs, T rhs, T x) { return (x - lhs) / (rhs - lhs); }
77 
78 /// Return the smaller of two values.
79 template <class T, class U>
Min(T lhs,U rhs)80 inline T Min(T lhs, U rhs) { return lhs < rhs ? lhs : rhs; }
81 
82 /// Return the larger of two values.
83 template <class T, class U>
Max(T lhs,U rhs)84 inline T Max(T lhs, U rhs) { return lhs > rhs ? lhs : rhs; }
85 
86 /// Return absolute value of a value
87 template <class T>
Abs(T value)88 inline T Abs(T value) { return value >= 0.0 ? value : -value; }
89 
90 /// Return the sign of a float (-1, 0 or 1.)
91 template <class T>
Sign(T value)92 inline T Sign(T value) { return value > 0.0 ? 1.0 : (value < 0.0 ? -1.0 : 0.0); }
93 
94 /// Return a representation of the specified floating-point value as a single format bit layout.
FloatToRawIntBits(float value)95 inline unsigned FloatToRawIntBits(float value)
96 {
97     unsigned u = *((unsigned*)&value);
98     return u;
99 }
100 
101 /// Check whether a floating point value is NaN.
102 /// Use a workaround for GCC, see https://github.com/urho3d/Urho3D/issues/655
103 #ifndef __GNUC__
IsNaN(float value)104 inline bool IsNaN(float value) { return value != value; }
105 #else
106 
IsNaN(float value)107 inline bool IsNaN(float value)
108 {
109     unsigned u = FloatToRawIntBits(value);
110     return (u & 0x7fffffff) > 0x7f800000;
111 }
112 
113 #endif
114 
115 /// Clamp a number to a range.
116 template <class T>
Clamp(T value,T min,T max)117 inline T Clamp(T value, T min, T max)
118 {
119     if (value < min)
120         return min;
121     else if (value > max)
122         return max;
123     else
124         return value;
125 }
126 
127 /// Smoothly damp between values.
128 template <class T>
SmoothStep(T lhs,T rhs,T t)129 inline T SmoothStep(T lhs, T rhs, T t)
130 {
131     t = Clamp((t - lhs) / (rhs - lhs), T(0.0), T(1.0)); // Saturate t
132     return t * t * (3.0 - 2.0 * t);
133 }
134 
135 /// Return sine of an angle in degrees.
Sin(T angle)136 template <class T> inline T Sin(T angle) { return sin(angle * M_DEGTORAD); }
137 
138 /// Return cosine of an angle in degrees.
Cos(T angle)139 template <class T> inline T Cos(T angle) { return cos(angle * M_DEGTORAD); }
140 
141 /// Return tangent of an angle in degrees.
Tan(T angle)142 template <class T> inline T Tan(T angle) { return tan(angle * M_DEGTORAD); }
143 
144 /// Return arc sine in degrees.
Asin(T x)145 template <class T> inline T Asin(T x) { return M_RADTODEG * asin(Clamp(x, T(-1.0), T(1.0))); }
146 
147 /// Return arc cosine in degrees.
Acos(T x)148 template <class T> inline T Acos(T x) { return M_RADTODEG * acos(Clamp(x, T(-1.0), T(1.0))); }
149 
150 /// Return arc tangent in degrees.
Atan(T x)151 template <class T> inline T Atan(T x) { return M_RADTODEG * atan(x); }
152 
153 /// Return arc tangent of y/x in degrees.
Atan2(T y,T x)154 template <class T> inline T Atan2(T y, T x) { return M_RADTODEG * atan2(y, x); }
155 
156 /// Return X in power Y.
Pow(T x,T y)157 template <class T> T Pow(T x, T y) { return pow(x, y); }
158 
159 /// Return natural logarithm of X.
Ln(T x)160 template <class T> T Ln(T x) { return log(x); }
161 
162 /// Return square root of X.
Sqrt(T x)163 template <class T> T Sqrt(T x) { return sqrt(x); }
164 
165 /// Return floating-point remainder of X/Y.
Mod(T x,T y)166 template <class T> T Mod(T x, T y) { return fmod(x, y); }
167 
168 /// Return fractional part of passed value in range [0, 1).
Fract(T value)169 template <class T> T Fract(T value) { return value - floor(value); }
170 
171 /// Round value down.
Floor(T x)172 template <class T> T Floor(T x) { return floor(x); }
173 
174 /// Round value down. Returns integer value.
FloorToInt(T x)175 template <class T> int FloorToInt(T x) { return static_cast<int>(floor(x)); }
176 
177 /// Round value to nearest integer.
Round(T x)178 template <class T> T Round(T x) { return floor(x + T(0.5)); }
179 
180 /// Round value to nearest integer.
RoundToInt(T x)181 template <class T> int RoundToInt(T x) { return static_cast<int>(floor(x + T(0.5))); }
182 
183 /// Round value up.
Ceil(T x)184 template <class T> T Ceil(T x) { return ceil(x); }
185 
186 /// Round value up.
CeilToInt(T x)187 template <class T> int CeilToInt(T x) { return static_cast<int>(ceil(x)); }
188 
189 /// Check whether an unsigned integer is a power of two.
IsPowerOfTwo(unsigned value)190 inline bool IsPowerOfTwo(unsigned value)
191 {
192     return !(value & (value - 1));
193 }
194 
195 /// Round up to next power of two.
NextPowerOfTwo(unsigned value)196 inline unsigned NextPowerOfTwo(unsigned value)
197 {
198     // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
199     --value;
200     value |= value >> 1;
201     value |= value >> 2;
202     value |= value >> 4;
203     value |= value >> 8;
204     value |= value >> 16;
205     return ++value;
206 }
207 
208 /// Return log base two or the MSB position of the given value.
LogBaseTwo(unsigned value)209 inline unsigned LogBaseTwo(unsigned value)
210 {
211     // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
212     unsigned ret = 0;
213     while (value >>= 1)     // Unroll for more speed...
214         ++ret;
215     return ret;
216 }
217 
218 /// Count the number of set bits in a mask.
CountSetBits(unsigned value)219 inline unsigned CountSetBits(unsigned value)
220 {
221     // Brian Kernighan's method
222     unsigned count = 0;
223     for (count = 0; value; count++)
224         value &= value - 1;
225     return count;
226 }
227 
228 /// Update a hash with the given 8-bit value using the SDBM algorithm.
SDBMHash(unsigned hash,unsigned char c)229 inline unsigned SDBMHash(unsigned hash, unsigned char c) { return c + (hash << 6) + (hash << 16) - hash; }
230 
231 /// Return a random float between 0.0 (inclusive) and 1.0 (exclusive.)
Random()232 inline float Random() { return Rand() / 32768.0f; }
233 
234 /// Return a random float between 0.0 and range, inclusive from both ends.
Random(float range)235 inline float Random(float range) { return Rand() * range / 32767.0f; }
236 
237 /// Return a random float between min and max, inclusive from both ends.
Random(float min,float max)238 inline float Random(float min, float max) { return Rand() * (max - min) / 32767.0f + min; }
239 
240 /// Return a random integer between 0 and range - 1.
Random(int range)241 inline int Random(int range) { return (int)(Random() * range); }
242 
243 /// Return a random integer between min and max - 1.
Random(int min,int max)244 inline int Random(int min, int max) { float range = (float)(max - min); return (int)(Random() * range) + min; }
245 
246 /// Return a random normal distributed number with the given mean value and variance.
RandomNormal(float meanValue,float variance)247 inline float RandomNormal(float meanValue, float variance) { return RandStandardNormal() * sqrtf(variance) + meanValue; }
248 
249 /// Convert float to half float. From https://gist.github.com/martinkallman/5049614
FloatToHalf(float value)250 inline unsigned short FloatToHalf(float value)
251 {
252     unsigned inu = FloatToRawIntBits(value);
253     unsigned t1 = inu & 0x7fffffff;         // Non-sign bits
254     unsigned t2 = inu & 0x80000000;         // Sign bit
255     unsigned t3 = inu & 0x7f800000;         // Exponent
256 
257     t1 >>= 13;                              // Align mantissa on MSB
258     t2 >>= 16;                              // Shift sign bit into position
259 
260     t1 -= 0x1c000;                          // Adjust bias
261 
262     t1 = (t3 < 0x38800000) ? 0 : t1;        // Flush-to-zero
263     t1 = (t3 > 0x47000000) ? 0x7bff : t1;   // Clamp-to-max
264     t1 = (t3 == 0 ? 0 : t1);                // Denormals-as-zero
265 
266     t1 |= t2;                               // Re-insert sign bit
267 
268     return (unsigned short)t1;
269 }
270 
271 /// Convert half float to float. From https://gist.github.com/martinkallman/5049614
HalfToFloat(unsigned short value)272 inline float HalfToFloat(unsigned short value)
273 {
274     unsigned t1 = value & 0x7fff;           // Non-sign bits
275     unsigned t2 = value & 0x8000;           // Sign bit
276     unsigned t3 = value & 0x7c00;           // Exponent
277 
278     t1 <<= 13;                              // Align mantissa on MSB
279     t2 <<= 16;                              // Shift sign bit into position
280 
281     t1 += 0x38000000;                       // Adjust bias
282 
283     t1 = (t3 == 0 ? 0 : t1);                // Denormals-as-zero
284 
285     t1 |= t2;                               // Re-insert sign bit
286 
287     float out;
288     *((unsigned*)&out) = t1;
289     return out;
290 }
291 
292 /// Calculate both sine and cosine, with angle in degrees.
293 URHO3D_API void SinCos(float angle, float& sin, float& cos);
294 
295 }
296 
297 #ifdef _MSC_VER
298 #pragma warning(pop)
299 #endif
300