MathDefs.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. //
  2. // Copyright (c) 2008-2020 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. /// \file
  23. #pragma once
  24. #ifdef _MSC_VER
  25. #pragma warning(push)
  26. #pragma warning(disable:4244) // Conversion from 'double' to 'float'
  27. #pragma warning(disable:4702) // unreachable code
  28. #endif
  29. #include "../Math/Random.h"
  30. #include <cstdlib>
  31. #include <cmath>
  32. #include <limits>
  33. #include <type_traits>
  34. namespace Urho3D
  35. {
  36. #undef M_PI
  37. static const float M_PI = 3.14159265358979323846264338327950288f;
  38. static const float M_HALF_PI = M_PI * 0.5f;
  39. static const int M_MIN_INT = 0x80000000;
  40. static const int M_MAX_INT = 0x7fffffff;
  41. static const unsigned M_MIN_UNSIGNED = 0x00000000;
  42. static const unsigned M_MAX_UNSIGNED = 0xffffffff;
  43. static const float M_EPSILON = 0.000001f;
  44. static const float M_LARGE_EPSILON = 0.00005f;
  45. static const float M_MIN_NEARCLIP = 0.01f;
  46. static const float M_MAX_FOV = 160.0f;
  47. static const float M_LARGE_VALUE = 100000000.0f;
  48. static const float M_INFINITY = (float)HUGE_VAL;
  49. static const float M_DEGTORAD = M_PI / 180.0f;
  50. static const float M_DEGTORAD_2 = M_PI / 360.0f; // M_DEGTORAD / 2.f
  51. static const float M_RADTODEG = 1.0f / M_DEGTORAD;
  52. /// Intersection test result.
  53. enum Intersection
  54. {
  55. OUTSIDE,
  56. INTERSECTS,
  57. INSIDE
  58. };
  59. /// Check whether two floating point values are equal within accuracy.
  60. /// @specialization{float}
  61. template <class T>
  62. inline bool Equals(T lhs, T rhs) { return lhs + std::numeric_limits<T>::epsilon() >= rhs && lhs - std::numeric_limits<T>::epsilon() <= rhs; }
  63. /// Linear interpolation between two values.
  64. /// @specialization{float,float}
  65. template <class T, class U>
  66. inline T Lerp(T lhs, T rhs, U t) { return lhs * (1.0 - t) + rhs * t; }
  67. /// Inverse linear interpolation between two values.
  68. /// @specialization{float}
  69. template <class T>
  70. inline T InverseLerp(T lhs, T rhs, T x) { return (x - lhs) / (rhs - lhs); }
  71. /// Return the smaller of two values.
  72. /// @specialization{float,float} @specialization{int,int}
  73. template <class T, class U>
  74. inline T Min(T lhs, U rhs) { return lhs < rhs ? lhs : rhs; }
  75. /// Return the larger of two values.
  76. /// @specialization{float,float} @specialization{int,int}
  77. template <class T, class U>
  78. inline T Max(T lhs, U rhs) { return lhs > rhs ? lhs : rhs; }
  79. /// Return absolute value of a value.
  80. /// @specialization{float}
  81. template <class T>
  82. inline T Abs(T value) { return value >= 0.0 ? value : -value; }
  83. /// Return the sign of a float (-1, 0 or 1).
  84. /// @specialization{float}
  85. template <class T>
  86. inline T Sign(T value) { return value > 0.0 ? 1.0 : (value < 0.0 ? -1.0 : 0.0); }
  87. /// Convert degrees to radians.
  88. template <class T>
  89. inline T ToRadians(const T degrees) { return M_DEGTORAD * degrees; }
  90. /// Convert radians to degrees.
  91. template <class T>
  92. inline T ToDegrees(const T radians) { return M_RADTODEG * radians; }
  93. /// Return a representation of the specified floating-point value as a single format bit layout.
  94. inline unsigned FloatToRawIntBits(float value)
  95. {
  96. unsigned u = *((unsigned*)&value);
  97. return u;
  98. }
  99. /// Check whether a floating point value is NaN.
  100. /// @specialization{float} @specialization{double}
  101. template <class T> inline bool IsNaN(T value) { return std::isnan(value); }
  102. /// Check whether a floating point value is positive or negative infinity.
  103. template <class T> inline bool IsInf(T value) { return std::isinf(value); }
  104. /// Clamp a number to a range.
  105. /// @specialization{float} @specialization{int}
  106. template <class T>
  107. inline T Clamp(T value, T min, T max)
  108. {
  109. if (value < min)
  110. return min;
  111. else if (value > max)
  112. return max;
  113. else
  114. return value;
  115. }
  116. /// Smoothly damp between values.
  117. /// @specialization{float}
  118. template <class T>
  119. inline T SmoothStep(T lhs, T rhs, T t)
  120. {
  121. t = Clamp((t - lhs) / (rhs - lhs), T(0.0), T(1.0)); // Saturate t
  122. return t * t * (3.0 - 2.0 * t);
  123. }
  124. /// Return sine of an angle in degrees.
  125. /// @specialization{float}
  126. template <class T> inline T Sin(T angle) { return sin(angle * M_DEGTORAD); }
  127. /// Return cosine of an angle in degrees.
  128. /// @specialization{float}
  129. template <class T> inline T Cos(T angle) { return cos(angle * M_DEGTORAD); }
  130. /// Return tangent of an angle in degrees.
  131. /// @specialization{float}
  132. template <class T> inline T Tan(T angle) { return tan(angle * M_DEGTORAD); }
  133. /// Return arc sine in degrees.
  134. /// @specialization{float}
  135. template <class T> inline T Asin(T x) { return M_RADTODEG * asin(Clamp(x, T(-1.0), T(1.0))); }
  136. /// Return arc cosine in degrees.
  137. /// @specialization{float}
  138. template <class T> inline T Acos(T x) { return M_RADTODEG * acos(Clamp(x, T(-1.0), T(1.0))); }
  139. /// Return arc tangent in degrees.
  140. /// @specialization{float}
  141. template <class T> inline T Atan(T x) { return M_RADTODEG * atan(x); }
  142. /// Return arc tangent of y/x in degrees.
  143. /// @specialization{float}
  144. template <class T> inline T Atan2(T y, T x) { return M_RADTODEG * atan2(y, x); }
  145. /// Return X in power Y.
  146. /// @specialization{float}
  147. template <class T> inline T Pow(T x, T y) { return pow(x, y); }
  148. /// Return natural logarithm of X.
  149. /// @specialization{float}
  150. template <class T> inline T Ln(T x) { return log(x); }
  151. /// Return square root of X.
  152. /// @specialization{float}
  153. template <class T> inline T Sqrt(T x) { return sqrt(x); }
  154. /// Return remainder of X/Y for float values.
  155. template <class T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
  156. inline T Mod(T x, T y) { return fmod(x, y); }
  157. /// Return remainder of X/Y for integer values.
  158. template <class T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
  159. inline T Mod(T x, T y) { return x % y; }
  160. /// Return always positive remainder of X/Y.
  161. template <class T>
  162. inline T AbsMod(T x, T y)
  163. {
  164. const T result = Mod(x, y);
  165. return result < 0 ? result + y : result;
  166. }
  167. /// Return fractional part of passed value in range [0, 1).
  168. /// @specialization{float}
  169. template <class T> inline T Fract(T value) { return value - floor(value); }
  170. /// Round value down.
  171. /// @specialization{float}
  172. template <class T> inline T Floor(T x) { return floor(x); }
  173. /// Round value down. Returns integer value.
  174. /// @specialization{float}
  175. template <class T> inline int FloorToInt(T x) { return static_cast<int>(floor(x)); }
  176. /// Round value to nearest integer.
  177. /// @specialization{float}
  178. template <class T> inline T Round(T x) { return round(x); }
  179. /// Compute average value of the range.
  180. template <class Iterator> inline auto Average(Iterator begin, Iterator end) -> typename std::decay<decltype(*begin)>::type
  181. {
  182. using T = typename std::decay<decltype(*begin)>::type;
  183. T average{};
  184. unsigned size{};
  185. for (Iterator it = begin; it != end; ++it)
  186. {
  187. average += *it;
  188. ++size;
  189. }
  190. return size != 0 ? average / size : average;
  191. }
  192. /// Round value to nearest integer.
  193. /// @specialization{float}
  194. template <class T> inline int RoundToInt(T x) { return static_cast<int>(round(x)); }
  195. /// Round value to nearest multiple.
  196. template <class T> inline T RoundToNearestMultiple(T x, T multiple)
  197. {
  198. T mag = Abs(x);
  199. multiple = Abs(multiple);
  200. T remainder = Mod(mag, multiple);
  201. if (remainder >= multiple / 2)
  202. return (FloorToInt<T>(mag / multiple) * multiple + multiple) * Sign(x);
  203. else
  204. return (FloorToInt<T>(mag / multiple) * multiple) * Sign(x);
  205. }
  206. /// Round value up.
  207. /// @specialization{float}
  208. template <class T> inline T Ceil(T x) { return ceil(x); }
  209. /// Round value up.
  210. /// @specialization{float}
  211. template <class T> inline int CeilToInt(T x) { return static_cast<int>(ceil(x)); }
  212. /// Check whether an unsigned integer is a power of two.
  213. inline bool IsPowerOfTwo(unsigned value)
  214. {
  215. return !(value & (value - 1)) && value;
  216. }
  217. /// Round up to next power of two.
  218. inline unsigned NextPowerOfTwo(unsigned value)
  219. {
  220. // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
  221. --value;
  222. value |= value >> 1u;
  223. value |= value >> 2u;
  224. value |= value >> 4u;
  225. value |= value >> 8u;
  226. value |= value >> 16u;
  227. return ++value;
  228. }
  229. /// Round up or down to the closest power of two.
  230. inline unsigned ClosestPowerOfTwo(unsigned value)
  231. {
  232. const unsigned next = NextPowerOfTwo(value);
  233. const unsigned prev = next >> 1u;
  234. return (value - prev) > (next - value) ? next : prev;
  235. }
  236. /// Return log base two or the MSB position of the given value.
  237. inline unsigned LogBaseTwo(unsigned value)
  238. {
  239. // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
  240. unsigned ret = 0;
  241. while (value >>= 1) // Unroll for more speed...
  242. ++ret;
  243. return ret;
  244. }
  245. /// Count the number of set bits in a mask.
  246. inline unsigned CountSetBits(unsigned value)
  247. {
  248. // Brian Kernighan's method
  249. unsigned count = 0;
  250. for (count = 0; value; count++)
  251. value &= value - 1;
  252. return count;
  253. }
  254. /// Update a hash with the given 8-bit value using the SDBM algorithm.
  255. inline constexpr unsigned SDBMHash(unsigned hash, unsigned char c) { return c + (hash << 6u) + (hash << 16u) - hash; }
  256. /// Return a random float between 0.0 (inclusive) and 1.0 (exclusive).
  257. inline float Random() { return Rand() / 32768.0f; }
  258. /// Return a random float between 0.0 and range, inclusive from both ends.
  259. inline float Random(float range) { return Rand() * range / 32767.0f; }
  260. /// Return a random float between min and max, inclusive from both ends.
  261. inline float Random(float min, float max) { return Rand() * (max - min) / 32767.0f + min; }
  262. /// Return a random integer between 0 and range - 1.
  263. /// @alias{RandomInt}
  264. inline int Random(int range) { return (int)(Random() * range); }
  265. /// Return a random integer between min and max - 1.
  266. /// @alias{RandomInt}
  267. inline int Random(int min, int max) { auto range = (float)(max - min); return (int)(Random() * range) + min; }
  268. /// Return a random normal distributed number with the given mean value and variance.
  269. inline float RandomNormal(float meanValue, float variance) { return RandStandardNormal() * sqrtf(variance) + meanValue; }
  270. /// Convert float to half float. From https://gist.github.com/martinkallman/5049614
  271. inline unsigned short FloatToHalf(float value)
  272. {
  273. unsigned inu = FloatToRawIntBits(value);
  274. unsigned t1 = inu & 0x7fffffffu; // Non-sign bits
  275. unsigned t2 = inu & 0x80000000u; // Sign bit
  276. unsigned t3 = inu & 0x7f800000u; // Exponent
  277. t1 >>= 13; // Align mantissa on MSB
  278. t2 >>= 16; // Shift sign bit into position
  279. t1 -= 0x1c000; // Adjust bias
  280. t1 = (t3 < 0x38800000) ? 0 : t1; // Flush-to-zero
  281. t1 = (t3 > 0x47000000) ? 0x7bff : t1; // Clamp-to-max
  282. t1 = (t3 == 0 ? 0 : t1); // Denormals-as-zero
  283. t1 |= t2; // Re-insert sign bit
  284. return (unsigned short)t1;
  285. }
  286. /// Convert half float to float. From https://gist.github.com/martinkallman/5049614
  287. inline float HalfToFloat(unsigned short value)
  288. {
  289. unsigned t1 = value & 0x7fffu; // Non-sign bits
  290. unsigned t2 = value & 0x8000u; // Sign bit
  291. unsigned t3 = value & 0x7c00u; // Exponent
  292. t1 <<= 13; // Align mantissa on MSB
  293. t2 <<= 16; // Shift sign bit into position
  294. t1 += 0x38000000; // Adjust bias
  295. t1 = (t3 == 0 ? 0 : t1); // Denormals-as-zero
  296. t1 |= t2; // Re-insert sign bit
  297. float out;
  298. *((unsigned*)&out) = t1;
  299. return out;
  300. }
  301. /// Calculate both sine and cosine, with angle in degrees.
  302. URHO3D_API void SinCos(float angle, float& sin, float& cos);
  303. }
  304. #ifdef _MSC_VER
  305. #pragma warning(pop)
  306. #endif