The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

508 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  19. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  20. //==============================================================================
  21. /*
  22. This file sets up some handy mathematical typdefs and functions.
  23. */
  24. //==============================================================================
  25. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  26. /** A platform-independent 8-bit signed integer type. */
  27. typedef signed char int8;
  28. /** A platform-independent 8-bit unsigned integer type. */
  29. typedef unsigned char uint8;
  30. /** A platform-independent 16-bit signed integer type. */
  31. typedef signed short int16;
  32. /** A platform-independent 16-bit unsigned integer type. */
  33. typedef unsigned short uint16;
  34. /** A platform-independent 32-bit signed integer type. */
  35. typedef signed int int32;
  36. /** A platform-independent 32-bit unsigned integer type. */
  37. typedef unsigned int uint32;
  38. #if JUCE_MSVC
  39. /** A platform-independent 64-bit integer type. */
  40. typedef __int64 int64;
  41. /** A platform-independent 64-bit unsigned integer type. */
  42. typedef unsigned __int64 uint64;
  43. /** A platform-independent macro for writing 64-bit literals, needed because
  44. different compilers have different syntaxes for this.
  45. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  46. GCC, or 0x1000000000 for MSVC.
  47. */
  48. #define literal64bit(longLiteral) ((__int64) longLiteral)
  49. #else
  50. /** A platform-independent 64-bit integer type. */
  51. typedef long long int64;
  52. /** A platform-independent 64-bit unsigned integer type. */
  53. typedef unsigned long long uint64;
  54. /** A platform-independent macro for writing 64-bit literals, needed because
  55. different compilers have different syntaxes for this.
  56. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  57. GCC, or 0x1000000000 for MSVC.
  58. */
  59. #define literal64bit(longLiteral) (longLiteral##LL)
  60. #endif
  61. #if JUCE_64BIT
  62. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  63. typedef int64 pointer_sized_int;
  64. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  65. typedef uint64 pointer_sized_uint;
  66. #elif JUCE_MSVC
  67. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  68. typedef _W64 int pointer_sized_int;
  69. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  70. typedef _W64 unsigned int pointer_sized_uint;
  71. #else
  72. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  73. typedef int pointer_sized_int;
  74. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  75. typedef unsigned int pointer_sized_uint;
  76. #endif
  77. #if JUCE_MSVC
  78. typedef pointer_sized_int ssize_t;
  79. #endif
  80. //==============================================================================
  81. // Some indispensible min/max functions
  82. /** Returns the larger of two values. */
  83. template <typename Type>
  84. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  85. /** Returns the larger of three values. */
  86. template <typename Type>
  87. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  88. /** Returns the larger of four values. */
  89. template <typename Type>
  90. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  91. /** Returns the smaller of two values. */
  92. template <typename Type>
  93. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  94. /** Returns the smaller of three values. */
  95. template <typename Type>
  96. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  97. /** Returns the smaller of four values. */
  98. template <typename Type>
  99. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  100. /** Scans an array of values, returning the minimum value that it contains. */
  101. template <typename Type>
  102. const Type findMinimum (const Type* data, int numValues)
  103. {
  104. if (numValues <= 0)
  105. return Type();
  106. Type result (*data++);
  107. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  108. {
  109. const Type& v = *data++;
  110. if (v < result) result = v;
  111. }
  112. return result;
  113. }
  114. /** Scans an array of values, returning the maximum value that it contains. */
  115. template <typename Type>
  116. const Type findMaximum (const Type* values, int numValues)
  117. {
  118. if (numValues <= 0)
  119. return Type();
  120. Type result (*values++);
  121. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  122. {
  123. const Type& v = *values++;
  124. if (result < v) result = v;
  125. }
  126. return result;
  127. }
  128. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  129. template <typename Type>
  130. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  131. {
  132. if (numValues <= 0)
  133. {
  134. lowest = Type();
  135. highest = Type();
  136. }
  137. else
  138. {
  139. Type mn (*values++);
  140. Type mx (mn);
  141. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  142. {
  143. const Type& v = *values++;
  144. if (mx < v) mx = v;
  145. if (v < mn) mn = v;
  146. }
  147. lowest = mn;
  148. highest = mx;
  149. }
  150. }
  151. //==============================================================================
  152. /** Constrains a value to keep it within a given range.
  153. This will check that the specified value lies between the lower and upper bounds
  154. specified, and if not, will return the nearest value that would be in-range. Effectively,
  155. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  156. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  157. the results will be unpredictable.
  158. @param lowerLimit the minimum value to return
  159. @param upperLimit the maximum value to return
  160. @param valueToConstrain the value to try to return
  161. @returns the closest value to valueToConstrain which lies between lowerLimit
  162. and upperLimit (inclusive)
  163. @see jlimit0To, jmin, jmax
  164. */
  165. template <typename Type>
  166. inline Type jlimit (const Type lowerLimit,
  167. const Type upperLimit,
  168. const Type valueToConstrain) noexcept
  169. {
  170. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  171. return (valueToConstrain < lowerLimit) ? lowerLimit
  172. : ((upperLimit < valueToConstrain) ? upperLimit
  173. : valueToConstrain);
  174. }
  175. /** Returns true if a value is at least zero, and also below a specified upper limit.
  176. This is basically a quicker way to write:
  177. @code valueToTest >= 0 && valueToTest < upperLimit
  178. @endcode
  179. */
  180. template <typename Type>
  181. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  182. {
  183. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  184. return Type() <= valueToTest && valueToTest < upperLimit;
  185. }
  186. template <>
  187. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  188. {
  189. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  190. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  191. }
  192. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  193. This is basically a quicker way to write:
  194. @code valueToTest >= 0 && valueToTest <= upperLimit
  195. @endcode
  196. */
  197. template <typename Type>
  198. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  199. {
  200. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  201. return Type() <= valueToTest && valueToTest <= upperLimit;
  202. }
  203. template <>
  204. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  205. {
  206. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  207. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  208. }
  209. //==============================================================================
  210. /** Handy function to swap two values. */
  211. template <typename Type>
  212. inline void swapVariables (Type& variable1, Type& variable2)
  213. {
  214. std::swap (variable1, variable2);
  215. }
  216. /** Handy function for getting the number of elements in a simple const C array.
  217. E.g.
  218. @code
  219. static int myArray[] = { 1, 2, 3 };
  220. int numElements = numElementsInArray (myArray) // returns 3
  221. @endcode
  222. */
  223. template <typename Type, int N>
  224. inline int numElementsInArray (Type (&array)[N])
  225. {
  226. (void) array; // (required to avoid a spurious warning in MS compilers)
  227. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  228. return N;
  229. }
  230. //==============================================================================
  231. // Some useful maths functions that aren't always present with all compilers and build settings.
  232. /** Using juce_hypot is easier than dealing with the different types of hypot function
  233. that are provided by the various platforms and compilers. */
  234. template <typename Type>
  235. inline Type juce_hypot (Type a, Type b) noexcept
  236. {
  237. #if JUCE_MSVC
  238. return static_cast <Type> (_hypot (a, b));
  239. #else
  240. return static_cast <Type> (hypot (a, b));
  241. #endif
  242. }
  243. /** 64-bit abs function. */
  244. inline int64 abs64 (const int64 n) noexcept
  245. {
  246. return (n >= 0) ? n : -n;
  247. }
  248. //==============================================================================
  249. /** A predefined value for Pi, at double-precision.
  250. @see float_Pi
  251. */
  252. const double double_Pi = 3.1415926535897932384626433832795;
  253. /** A predefined value for Pi, at sngle-precision.
  254. @see double_Pi
  255. */
  256. const float float_Pi = 3.14159265358979323846f;
  257. //==============================================================================
  258. /** The isfinite() method seems to vary between platforms, so this is a
  259. platform-independent function for it.
  260. */
  261. template <typename FloatingPointType>
  262. inline bool juce_isfinite (FloatingPointType value)
  263. {
  264. #if JUCE_WINDOWS
  265. return _finite (value);
  266. #elif JUCE_ANDROID
  267. return isfinite (value);
  268. #else
  269. return std::isfinite (value);
  270. #endif
  271. }
  272. //==============================================================================
  273. #if JUCE_MSVC
  274. #pragma optimize ("t", off)
  275. #pragma float_control (precise, on, push)
  276. #endif
  277. /** Fast floating-point-to-integer conversion.
  278. This is faster than using the normal c++ cast to convert a float to an int, and
  279. it will round the value to the nearest integer, rather than rounding it down
  280. like the normal cast does.
  281. Note that this routine gets its speed at the expense of some accuracy, and when
  282. rounding values whose floating point component is exactly 0.5, odd numbers and
  283. even numbers will be rounded up or down differently.
  284. */
  285. template <typename FloatType>
  286. inline int roundToInt (const FloatType value) noexcept
  287. {
  288. union { int asInt[2]; double asDouble; } n;
  289. n.asDouble = ((double) value) + 6755399441055744.0;
  290. #if JUCE_BIG_ENDIAN
  291. return n.asInt [1];
  292. #else
  293. return n.asInt [0];
  294. #endif
  295. }
  296. #if JUCE_MSVC
  297. #pragma float_control (pop)
  298. #pragma optimize ("", on) // resets optimisations to the project defaults
  299. #endif
  300. /** Fast floating-point-to-integer conversion.
  301. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  302. fine for values above zero, but negative numbers are rounded the wrong way.
  303. */
  304. inline int roundToIntAccurate (const double value) noexcept
  305. {
  306. return roundToInt (value + 1.5e-8);
  307. }
  308. /** Fast floating-point-to-integer conversion.
  309. This is faster than using the normal c++ cast to convert a double to an int, and
  310. it will round the value to the nearest integer, rather than rounding it down
  311. like the normal cast does.
  312. Note that this routine gets its speed at the expense of some accuracy, and when
  313. rounding values whose floating point component is exactly 0.5, odd numbers and
  314. even numbers will be rounded up or down differently. For a more accurate conversion,
  315. see roundDoubleToIntAccurate().
  316. */
  317. inline int roundDoubleToInt (const double value) noexcept
  318. {
  319. return roundToInt (value);
  320. }
  321. /** Fast floating-point-to-integer conversion.
  322. This is faster than using the normal c++ cast to convert a float to an int, and
  323. it will round the value to the nearest integer, rather than rounding it down
  324. like the normal cast does.
  325. Note that this routine gets its speed at the expense of some accuracy, and when
  326. rounding values whose floating point component is exactly 0.5, odd numbers and
  327. even numbers will be rounded up or down differently.
  328. */
  329. inline int roundFloatToInt (const float value) noexcept
  330. {
  331. return roundToInt (value);
  332. }
  333. //==============================================================================
  334. /** Returns true if the specified integer is a power-of-two.
  335. */
  336. template <typename IntegerType>
  337. bool isPowerOfTwo (IntegerType value)
  338. {
  339. return (value & (value - 1)) == 0;
  340. }
  341. /** Returns the smallest power-of-two which is equal to or greater than the given integer.
  342. */
  343. inline int nextPowerOfTwo (int n) noexcept
  344. {
  345. --n;
  346. n |= (n >> 1);
  347. n |= (n >> 2);
  348. n |= (n >> 4);
  349. n |= (n >> 8);
  350. n |= (n >> 16);
  351. return n + 1;
  352. }
  353. /** Performs a modulo operation, but can cope with the dividend being negative.
  354. The divisor must be greater than zero.
  355. */
  356. template <typename IntegerType>
  357. int negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
  358. {
  359. jassert (divisor > 0);
  360. dividend %= divisor;
  361. return (dividend < 0) ? (dividend + divisor) : dividend;
  362. }
  363. //==============================================================================
  364. #if (JUCE_INTEL && JUCE_32BIT) || defined (DOXYGEN)
  365. /** This macro can be applied to a float variable to check whether it contains a denormalised
  366. value, and to normalise it if necessary.
  367. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  368. */
  369. #define JUCE_UNDENORMALISE(x) x += 1.0f; x -= 1.0f;
  370. #else
  371. #define JUCE_UNDENORMALISE(x)
  372. #endif
  373. //==============================================================================
  374. /** This namespace contains a few template classes for helping work out class type variations.
  375. */
  376. namespace TypeHelpers
  377. {
  378. #if JUCE_VC8_OR_EARLIER
  379. #define PARAMETER_TYPE(type) const type&
  380. #else
  381. /** The ParameterType struct is used to find the best type to use when passing some kind
  382. of object as a parameter.
  383. Of course, this is only likely to be useful in certain esoteric template situations.
  384. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  385. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  386. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  387. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  388. pass-by-value, but passing objects as a const reference, to avoid copying.
  389. */
  390. template <typename Type> struct ParameterType { typedef const Type& type; };
  391. #if ! DOXYGEN
  392. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  393. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  394. template <> struct ParameterType <char> { typedef char type; };
  395. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  396. template <> struct ParameterType <short> { typedef short type; };
  397. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  398. template <> struct ParameterType <int> { typedef int type; };
  399. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  400. template <> struct ParameterType <long> { typedef long type; };
  401. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  402. template <> struct ParameterType <int64> { typedef int64 type; };
  403. template <> struct ParameterType <uint64> { typedef uint64 type; };
  404. template <> struct ParameterType <bool> { typedef bool type; };
  405. template <> struct ParameterType <float> { typedef float type; };
  406. template <> struct ParameterType <double> { typedef double type; };
  407. #endif
  408. /** A helpful macro to simplify the use of the ParameterType template.
  409. @see ParameterType
  410. */
  411. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  412. #endif
  413. /** These templates are designed to take a type, and if it's a double, they return a double
  414. type; for anything else, they return a float type.
  415. */
  416. template <typename Type> struct SmallestFloatType { typedef float type; };
  417. template <> struct SmallestFloatType <double> { typedef double type; };
  418. }
  419. //==============================================================================
  420. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__