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.

527 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 && ! JUCE_VC6
  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 minimum 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. #if ! JUCE_VC6
  187. template <>
  188. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  189. {
  190. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  191. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  192. }
  193. #endif
  194. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  195. This is basically a quicker way to write:
  196. @code valueToTest >= 0 && valueToTest <= upperLimit
  197. @endcode
  198. */
  199. template <typename Type>
  200. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  201. {
  202. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  203. return Type() <= valueToTest && valueToTest <= upperLimit;
  204. }
  205. #if ! JUCE_VC6
  206. template <>
  207. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  208. {
  209. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  210. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  211. }
  212. #endif
  213. //==============================================================================
  214. /** Handy function to swap two values. */
  215. template <typename Type>
  216. inline void swapVariables (Type& variable1, Type& variable2)
  217. {
  218. std::swap (variable1, variable2);
  219. }
  220. #if JUCE_VC6
  221. #define numElementsInArray(X) (sizeof((X)) / sizeof(0[X]))
  222. #else
  223. /** Handy function for getting the number of elements in a simple const C array.
  224. E.g.
  225. @code
  226. static int myArray[] = { 1, 2, 3 };
  227. int numElements = numElementsInArray (myArray) // returns 3
  228. @endcode
  229. */
  230. template <typename Type, int N>
  231. inline int numElementsInArray (Type (&array)[N])
  232. {
  233. (void) array; // (required to avoid a spurious warning in MS compilers)
  234. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  235. return N;
  236. }
  237. #endif
  238. //==============================================================================
  239. // Some useful maths functions that aren't always present with all compilers and build settings.
  240. /** Using juce_hypot is easier than dealing with the different types of hypot function
  241. that are provided by the various platforms and compilers. */
  242. template <typename Type>
  243. inline Type juce_hypot (Type a, Type b) noexcept
  244. {
  245. #if JUCE_WINDOWS
  246. return static_cast <Type> (_hypot (a, b));
  247. #else
  248. return static_cast <Type> (hypot (a, b));
  249. #endif
  250. }
  251. /** 64-bit abs function. */
  252. inline int64 abs64 (const int64 n) noexcept
  253. {
  254. return (n >= 0) ? n : -n;
  255. }
  256. /** This templated negate function will negate pointers as well as integers */
  257. template <typename Type>
  258. inline Type juce_negate (Type n) noexcept
  259. {
  260. return sizeof (Type) == 1 ? (Type) -(signed char) n
  261. : (sizeof (Type) == 2 ? (Type) -(short) n
  262. : (sizeof (Type) == 4 ? (Type) -(int) n
  263. : ((Type) -(int64) n)));
  264. }
  265. /** This templated negate function will negate pointers as well as integers */
  266. template <typename Type>
  267. inline Type* juce_negate (Type* n) noexcept
  268. {
  269. return (Type*) -(pointer_sized_int) n;
  270. }
  271. //==============================================================================
  272. /** A predefined value for Pi, at double-precision.
  273. @see float_Pi
  274. */
  275. const double double_Pi = 3.1415926535897932384626433832795;
  276. /** A predefined value for Pi, at sngle-precision.
  277. @see double_Pi
  278. */
  279. const float float_Pi = 3.14159265358979323846f;
  280. //==============================================================================
  281. /** The isfinite() method seems to vary between platforms, so this is a
  282. platform-independent function for it.
  283. */
  284. template <typename FloatingPointType>
  285. inline bool juce_isfinite (FloatingPointType value)
  286. {
  287. #if JUCE_WINDOWS
  288. return _finite (value);
  289. #elif JUCE_ANDROID
  290. return isfinite (value);
  291. #else
  292. return std::isfinite (value);
  293. #endif
  294. }
  295. //==============================================================================
  296. #if JUCE_MSVC
  297. #pragma optimize ("t", off)
  298. #pragma float_control (precise, on, push)
  299. #endif
  300. /** Fast floating-point-to-integer conversion.
  301. This is faster than using the normal c++ cast to convert a float to an int, and
  302. it will round the value to the nearest integer, rather than rounding it down
  303. like the normal cast does.
  304. Note that this routine gets its speed at the expense of some accuracy, and when
  305. rounding values whose floating point component is exactly 0.5, odd numbers and
  306. even numbers will be rounded up or down differently.
  307. */
  308. template <typename FloatType>
  309. inline int roundToInt (const FloatType value) noexcept
  310. {
  311. union { int asInt[2]; double asDouble; } n;
  312. n.asDouble = ((double) value) + 6755399441055744.0;
  313. #if JUCE_BIG_ENDIAN
  314. return n.asInt [1];
  315. #else
  316. return n.asInt [0];
  317. #endif
  318. }
  319. #if JUCE_MSVC
  320. #pragma float_control (pop)
  321. #pragma optimize ("", on) // resets optimisations to the project defaults
  322. #endif
  323. /** Fast floating-point-to-integer conversion.
  324. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  325. fine for values above zero, but negative numbers are rounded the wrong way.
  326. */
  327. inline int roundToIntAccurate (const double value) noexcept
  328. {
  329. return roundToInt (value + 1.5e-8);
  330. }
  331. /** Fast floating-point-to-integer conversion.
  332. This is faster than using the normal c++ cast to convert a double to an int, and
  333. it will round the value to the nearest integer, rather than rounding it down
  334. like the normal cast does.
  335. Note that this routine gets its speed at the expense of some accuracy, and when
  336. rounding values whose floating point component is exactly 0.5, odd numbers and
  337. even numbers will be rounded up or down differently. For a more accurate conversion,
  338. see roundDoubleToIntAccurate().
  339. */
  340. inline int roundDoubleToInt (const double value) noexcept
  341. {
  342. return roundToInt (value);
  343. }
  344. /** Fast floating-point-to-integer conversion.
  345. This is faster than using the normal c++ cast to convert a float to an int, and
  346. it will round the value to the nearest integer, rather than rounding it down
  347. like the normal cast does.
  348. Note that this routine gets its speed at the expense of some accuracy, and when
  349. rounding values whose floating point component is exactly 0.5, odd numbers and
  350. even numbers will be rounded up or down differently.
  351. */
  352. inline int roundFloatToInt (const float value) noexcept
  353. {
  354. return roundToInt (value);
  355. }
  356. //==============================================================================
  357. /** Returns true if the specified integer is a power-of-two.
  358. */
  359. template <typename IntegerType>
  360. bool isPowerOfTwo (IntegerType value)
  361. {
  362. return (value & (value - 1)) == 0;
  363. }
  364. /** Returns the next power-of-two which is equal to or greater than the given integer.
  365. */
  366. inline int nextPowerOfTwo (int n)
  367. {
  368. --n;
  369. n |= (n >> 1);
  370. n |= (n >> 2);
  371. n |= (n >> 4);
  372. n |= (n >> 8);
  373. n |= (n >> 16);
  374. return n + 1;
  375. }
  376. /** Performs a modulo operation, but can cope with the dividend being negative.
  377. The divisor must be greater than zero.
  378. */
  379. template <typename IntegerType>
  380. int negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
  381. {
  382. jassert (divisor > 0);
  383. dividend %= divisor;
  384. return (dividend < 0) ? (dividend + divisor) : dividend;
  385. }
  386. //==============================================================================
  387. #if (JUCE_INTEL && JUCE_32BIT) || defined (DOXYGEN)
  388. /** This macro can be applied to a float variable to check whether it contains a denormalised
  389. value, and to normalise it if necessary.
  390. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  391. */
  392. #define JUCE_UNDENORMALISE(x) x += 1.0f; x -= 1.0f;
  393. #else
  394. #define JUCE_UNDENORMALISE(x)
  395. #endif
  396. //==============================================================================
  397. /** This namespace contains a few template classes for helping work out class type variations.
  398. */
  399. namespace TypeHelpers
  400. {
  401. #if JUCE_VC8_OR_EARLIER
  402. #define PARAMETER_TYPE(type) const type&
  403. #else
  404. /** The ParameterType struct is used to find the best type to use when passing some kind
  405. of object as a parameter.
  406. Of course, this is only likely to be useful in certain esoteric template situations.
  407. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  408. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  409. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  410. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  411. pass-by-value, but passing objects as a const reference, to avoid copying.
  412. */
  413. template <typename Type> struct ParameterType { typedef const Type& type; };
  414. #if ! DOXYGEN
  415. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  416. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  417. template <> struct ParameterType <char> { typedef char type; };
  418. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  419. template <> struct ParameterType <short> { typedef short type; };
  420. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  421. template <> struct ParameterType <int> { typedef int type; };
  422. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  423. template <> struct ParameterType <long> { typedef long type; };
  424. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  425. template <> struct ParameterType <int64> { typedef int64 type; };
  426. template <> struct ParameterType <uint64> { typedef uint64 type; };
  427. template <> struct ParameterType <bool> { typedef bool type; };
  428. template <> struct ParameterType <float> { typedef float type; };
  429. template <> struct ParameterType <double> { typedef double type; };
  430. #endif
  431. /** A helpful macro to simplify the use of the ParameterType template.
  432. @see ParameterType
  433. */
  434. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  435. #endif
  436. }
  437. //==============================================================================
  438. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__