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.

631 lines
24KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. #pragma once
  18. //==============================================================================
  19. /*
  20. This file sets up some handy mathematical typdefs and functions.
  21. */
  22. //==============================================================================
  23. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  24. /** A platform-independent 8-bit signed integer type. */
  25. typedef signed char int8;
  26. /** A platform-independent 8-bit unsigned integer type. */
  27. typedef unsigned char uint8;
  28. /** A platform-independent 16-bit signed integer type. */
  29. typedef signed short int16;
  30. /** A platform-independent 16-bit unsigned integer type. */
  31. typedef unsigned short uint16;
  32. /** A platform-independent 32-bit signed integer type. */
  33. typedef signed int int32;
  34. /** A platform-independent 32-bit unsigned integer type. */
  35. typedef unsigned int uint32;
  36. #if JUCE_MSVC
  37. /** A platform-independent 64-bit integer type. */
  38. typedef __int64 int64;
  39. /** A platform-independent 64-bit unsigned integer type. */
  40. typedef unsigned __int64 uint64;
  41. #else
  42. /** A platform-independent 64-bit integer type. */
  43. typedef long long int64;
  44. /** A platform-independent 64-bit unsigned integer type. */
  45. typedef unsigned long long uint64;
  46. #endif
  47. #ifndef DOXYGEN
  48. /** A macro for creating 64-bit literals.
  49. Historically, this was needed to support portability with MSVC6, and is kept here
  50. so that old code will still compile, but nowadays every compiler will support the
  51. LL and ULL suffixes, so you should use those in preference to this macro.
  52. */
  53. #define literal64bit(longLiteral) (longLiteral##LL)
  54. #endif
  55. #if JUCE_64BIT
  56. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  57. typedef int64 pointer_sized_int;
  58. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  59. typedef uint64 pointer_sized_uint;
  60. #elif JUCE_MSVC
  61. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  62. typedef _W64 int pointer_sized_int;
  63. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  64. typedef _W64 unsigned int pointer_sized_uint;
  65. #else
  66. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  67. typedef int pointer_sized_int;
  68. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  69. typedef unsigned int pointer_sized_uint;
  70. #endif
  71. #if JUCE_WINDOWS && ! JUCE_MINGW
  72. typedef pointer_sized_int ssize_t;
  73. #endif
  74. //==============================================================================
  75. // Some indispensable min/max functions
  76. /** Returns the larger of two values. */
  77. template <typename Type>
  78. Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  79. /** Returns the larger of three values. */
  80. template <typename Type>
  81. Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  82. /** Returns the larger of four values. */
  83. template <typename Type>
  84. Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  85. /** Returns the smaller of two values. */
  86. template <typename Type>
  87. Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  88. /** Returns the smaller of three values. */
  89. template <typename Type>
  90. Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  91. /** Returns the smaller of four values. */
  92. template <typename Type>
  93. Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  94. /** Remaps a normalised value (between 0 and 1) to a target range.
  95. This effectively returns (targetRangeMin + value0To1 * (targetRangeMax - targetRangeMin)).
  96. */
  97. template <typename Type>
  98. Type jmap (Type value0To1, Type targetRangeMin, Type targetRangeMax)
  99. {
  100. return targetRangeMin + value0To1 * (targetRangeMax - targetRangeMin);
  101. }
  102. /** Remaps a value from a source range to a target range. */
  103. template <typename Type>
  104. Type jmap (Type sourceValue, Type sourceRangeMin, Type sourceRangeMax, Type targetRangeMin, Type targetRangeMax)
  105. {
  106. jassert (sourceRangeMax != sourceRangeMin); // mapping from a range of zero will produce NaN!
  107. return targetRangeMin + ((targetRangeMax - targetRangeMin) * (sourceValue - sourceRangeMin)) / (sourceRangeMax - sourceRangeMin);
  108. }
  109. /** Scans an array of values, returning the minimum value that it contains. */
  110. template <typename Type>
  111. Type findMinimum (const Type* data, int numValues)
  112. {
  113. if (numValues <= 0)
  114. return Type();
  115. Type result (*data++);
  116. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  117. {
  118. const Type& v = *data++;
  119. if (v < result) result = v;
  120. }
  121. return result;
  122. }
  123. /** Scans an array of values, returning the maximum value that it contains. */
  124. template <typename Type>
  125. Type findMaximum (const Type* values, int numValues)
  126. {
  127. if (numValues <= 0)
  128. return Type();
  129. Type result (*values++);
  130. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  131. {
  132. const Type& v = *values++;
  133. if (result < v) result = v;
  134. }
  135. return result;
  136. }
  137. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  138. template <typename Type>
  139. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  140. {
  141. if (numValues <= 0)
  142. {
  143. lowest = Type();
  144. highest = Type();
  145. }
  146. else
  147. {
  148. Type mn (*values++);
  149. Type mx (mn);
  150. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  151. {
  152. const Type& v = *values++;
  153. if (mx < v) mx = v;
  154. if (v < mn) mn = v;
  155. }
  156. lowest = mn;
  157. highest = mx;
  158. }
  159. }
  160. //==============================================================================
  161. /** Constrains a value to keep it within a given range.
  162. This will check that the specified value lies between the lower and upper bounds
  163. specified, and if not, will return the nearest value that would be in-range. Effectively,
  164. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  165. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  166. the results will be unpredictable.
  167. @param lowerLimit the minimum value to return
  168. @param upperLimit the maximum value to return
  169. @param valueToConstrain the value to try to return
  170. @returns the closest value to valueToConstrain which lies between lowerLimit
  171. and upperLimit (inclusive)
  172. @see jmin, jmax, jmap
  173. */
  174. template <typename Type>
  175. Type jlimit (const Type lowerLimit,
  176. const Type upperLimit,
  177. const Type valueToConstrain) noexcept
  178. {
  179. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  180. return (valueToConstrain < lowerLimit) ? lowerLimit
  181. : ((upperLimit < valueToConstrain) ? upperLimit
  182. : valueToConstrain);
  183. }
  184. /** Returns true if a value is at least zero, and also below a specified upper limit.
  185. This is basically a quicker way to write:
  186. @code valueToTest >= 0 && valueToTest < upperLimit
  187. @endcode
  188. */
  189. template <typename Type>
  190. bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  191. {
  192. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  193. return Type() <= valueToTest && valueToTest < upperLimit;
  194. }
  195. template <>
  196. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  197. {
  198. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  199. return static_cast<unsigned int> (valueToTest) < static_cast<unsigned int> (upperLimit);
  200. }
  201. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  202. This is basically a quicker way to write:
  203. @code valueToTest >= 0 && valueToTest <= upperLimit
  204. @endcode
  205. */
  206. template <typename Type>
  207. bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  208. {
  209. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  210. return Type() <= valueToTest && valueToTest <= upperLimit;
  211. }
  212. template <>
  213. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  214. {
  215. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  216. return static_cast<unsigned int> (valueToTest) <= static_cast<unsigned int> (upperLimit);
  217. }
  218. //==============================================================================
  219. /** Handy function to swap two values. */
  220. template <typename Type>
  221. void swapVariables (Type& variable1, Type& variable2)
  222. {
  223. std::swap (variable1, variable2);
  224. }
  225. /** Handy function for avoiding unused variables warning. */
  226. template <typename Type1>
  227. void ignoreUnused (const Type1&) noexcept {}
  228. template <typename Type1, typename Type2>
  229. void ignoreUnused (const Type1&, const Type2&) noexcept {}
  230. template <typename Type1, typename Type2, typename Type3>
  231. void ignoreUnused (const Type1&, const Type2&, const Type3&) noexcept {}
  232. template <typename Type1, typename Type2, typename Type3, typename Type4>
  233. void ignoreUnused (const Type1&, const Type2&, const Type3&, const Type4&) noexcept {}
  234. /** Handy function for getting the number of elements in a simple const C array.
  235. E.g.
  236. @code
  237. static int myArray[] = { 1, 2, 3 };
  238. int numElements = numElementsInArray (myArray) // returns 3
  239. @endcode
  240. */
  241. template <typename Type, int N>
  242. int numElementsInArray (Type (&array)[N])
  243. {
  244. ignoreUnused (array);
  245. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  246. return N;
  247. }
  248. //==============================================================================
  249. // Some useful maths functions that aren't always present with all compilers and build settings.
  250. /** Using juce_hypot is easier than dealing with the different types of hypot function
  251. that are provided by the various platforms and compilers. */
  252. template <typename Type>
  253. Type juce_hypot (Type a, Type b) noexcept
  254. {
  255. #if JUCE_MSVC
  256. return static_cast<Type> (_hypot (a, b));
  257. #else
  258. return static_cast<Type> (hypot (a, b));
  259. #endif
  260. }
  261. #ifndef DOXYGEN
  262. template <>
  263. inline float juce_hypot (float a, float b) noexcept
  264. {
  265. #if JUCE_MSVC
  266. return _hypotf (a, b);
  267. #else
  268. return hypotf (a, b);
  269. #endif
  270. }
  271. #endif
  272. /** 64-bit abs function. */
  273. inline int64 abs64 (const int64 n) noexcept
  274. {
  275. return (n >= 0) ? n : -n;
  276. }
  277. #if JUCE_MSVC && ! defined (DOXYGEN) // The MSVC libraries omit these functions for some reason...
  278. template<typename Type> Type asinh (Type x) { return std::log (x + std::sqrt (x * x + (Type) 1)); }
  279. template<typename Type> Type acosh (Type x) { return std::log (x + std::sqrt (x * x - (Type) 1)); }
  280. template<typename Type> Type atanh (Type x) { return (std::log (x + (Type) 1) - std::log (((Type) 1) - x)) / (Type) 2; }
  281. #endif
  282. //==============================================================================
  283. /** A predefined value for Pi, at double-precision.
  284. @see float_Pi
  285. */
  286. const double double_Pi = 3.1415926535897932384626433832795;
  287. /** A predefined value for Pi, at single-precision.
  288. @see double_Pi
  289. */
  290. const float float_Pi = 3.14159265358979323846f;
  291. /** Converts an angle in degrees to radians. */
  292. inline float degreesToRadians (float degrees) noexcept { return degrees * (float_Pi / 180.0f); }
  293. /** Converts an angle in degrees to radians. */
  294. inline double degreesToRadians (double degrees) noexcept { return degrees * (double_Pi / 180.0); }
  295. /** Converts an angle in radians to degrees. */
  296. inline float radiansToDegrees (float radians) noexcept { return radians * (180.0f / float_Pi); }
  297. /** Converts an angle in radians to degrees. */
  298. inline double radiansToDegrees (double radians) noexcept { return radians * (180.0 / double_Pi); }
  299. //==============================================================================
  300. /** The isfinite() method seems to vary between platforms, so this is a
  301. platform-independent function for it.
  302. */
  303. template <typename NumericType>
  304. bool juce_isfinite (NumericType) noexcept
  305. {
  306. return true; // Integer types are always finite
  307. }
  308. template <>
  309. inline bool juce_isfinite (float value) noexcept
  310. {
  311. #if JUCE_WINDOWS && ! JUCE_MINGW
  312. return _finite (value) != 0;
  313. #else
  314. return std::isfinite (value);
  315. #endif
  316. }
  317. template <>
  318. inline bool juce_isfinite (double value) noexcept
  319. {
  320. #if JUCE_WINDOWS && ! JUCE_MINGW
  321. return _finite (value) != 0;
  322. #else
  323. return std::isfinite (value);
  324. #endif
  325. }
  326. //==============================================================================
  327. #if JUCE_MSVC
  328. #pragma optimize ("t", off)
  329. #ifndef __INTEL_COMPILER
  330. #pragma float_control (precise, on, push)
  331. #endif
  332. #endif
  333. /** Fast floating-point-to-integer conversion.
  334. This is faster than using the normal c++ cast to convert a float to an int, and
  335. it will round the value to the nearest integer, rather than rounding it down
  336. like the normal cast does.
  337. Note that this routine gets its speed at the expense of some accuracy, and when
  338. rounding values whose floating point component is exactly 0.5, odd numbers and
  339. even numbers will be rounded up or down differently.
  340. */
  341. template <typename FloatType>
  342. int roundToInt (const FloatType value) noexcept
  343. {
  344. #ifdef __INTEL_COMPILER
  345. #pragma float_control (precise, on, push)
  346. #endif
  347. union { int asInt[2]; double asDouble; } n;
  348. n.asDouble = ((double) value) + 6755399441055744.0;
  349. #if JUCE_BIG_ENDIAN
  350. return n.asInt [1];
  351. #else
  352. return n.asInt [0];
  353. #endif
  354. }
  355. inline int roundToInt (int value) noexcept
  356. {
  357. return value;
  358. }
  359. #if JUCE_MSVC
  360. #ifndef __INTEL_COMPILER
  361. #pragma float_control (pop)
  362. #endif
  363. #pragma optimize ("", on) // resets optimisations to the project defaults
  364. #endif
  365. /** Fast floating-point-to-integer conversion.
  366. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  367. fine for values above zero, but negative numbers are rounded the wrong way.
  368. */
  369. inline int roundToIntAccurate (double value) noexcept
  370. {
  371. #ifdef __INTEL_COMPILER
  372. #pragma float_control (pop)
  373. #endif
  374. return roundToInt (value + 1.5e-8);
  375. }
  376. /** Fast floating-point-to-integer conversion.
  377. This is faster than using the normal c++ cast to convert a double to an int, and
  378. it will round the value to the nearest integer, rather than rounding it down
  379. like the normal cast does.
  380. Note that this routine gets its speed at the expense of some accuracy, and when
  381. rounding values whose floating point component is exactly 0.5, odd numbers and
  382. even numbers will be rounded up or down differently. For a more accurate conversion,
  383. see roundDoubleToIntAccurate().
  384. */
  385. inline int roundDoubleToInt (double value) noexcept
  386. {
  387. return roundToInt (value);
  388. }
  389. /** Fast floating-point-to-integer conversion.
  390. This is faster than using the normal c++ cast to convert a float to an int, and
  391. it will round the value to the nearest integer, rather than rounding it down
  392. like the normal cast does.
  393. Note that this routine gets its speed at the expense of some accuracy, and when
  394. rounding values whose floating point component is exactly 0.5, odd numbers and
  395. even numbers will be rounded up or down differently.
  396. */
  397. inline int roundFloatToInt (float value) noexcept
  398. {
  399. return roundToInt (value);
  400. }
  401. //==============================================================================
  402. /** Returns true if the specified integer is a power-of-two. */
  403. template <typename IntegerType>
  404. bool isPowerOfTwo (IntegerType value)
  405. {
  406. return (value & (value - 1)) == 0;
  407. }
  408. /** Returns the smallest power-of-two which is equal to or greater than the given integer. */
  409. inline int nextPowerOfTwo (int n) noexcept
  410. {
  411. --n;
  412. n |= (n >> 1);
  413. n |= (n >> 2);
  414. n |= (n >> 4);
  415. n |= (n >> 8);
  416. n |= (n >> 16);
  417. return n + 1;
  418. }
  419. /** Returns the index of the highest set bit in a (non-zero) number.
  420. So for n=3 this would return 1, for n=7 it returns 2, etc.
  421. An input value of 0 is illegal!
  422. */
  423. int findHighestSetBit (uint32 n) noexcept;
  424. /** Returns the number of bits in a 32-bit integer. */
  425. inline int countNumberOfBits (uint32 n) noexcept
  426. {
  427. n -= ((n >> 1) & 0x55555555);
  428. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  429. n = (((n >> 4) + n) & 0x0f0f0f0f);
  430. n += (n >> 8);
  431. n += (n >> 16);
  432. return (int) (n & 0x3f);
  433. }
  434. /** Returns the number of bits in a 64-bit integer. */
  435. inline int countNumberOfBits (uint64 n) noexcept
  436. {
  437. return countNumberOfBits ((uint32) n) + countNumberOfBits ((uint32) (n >> 32));
  438. }
  439. /** Performs a modulo operation, but can cope with the dividend being negative.
  440. The divisor must be greater than zero.
  441. */
  442. template <typename IntegerType>
  443. IntegerType negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
  444. {
  445. jassert (divisor > 0);
  446. dividend %= divisor;
  447. return (dividend < 0) ? (dividend + divisor) : dividend;
  448. }
  449. /** Returns the square of its argument. */
  450. template <typename NumericType>
  451. NumericType square (NumericType n) noexcept
  452. {
  453. return n * n;
  454. }
  455. //==============================================================================
  456. /** Writes a number of bits into a memory buffer at a given bit index.
  457. The buffer is treated as a sequence of 8-bit bytes, and the value is encoded in little-endian order,
  458. so for example if startBit = 10, and numBits = 11 then the lower 6 bits of the value would be written
  459. into bits 2-8 of targetBuffer[1], and the upper 5 bits of value into bits 0-5 of targetBuffer[2].
  460. @see readLittleEndianBitsInBuffer
  461. */
  462. void writeLittleEndianBitsInBuffer (void* targetBuffer, uint32 startBit, uint32 numBits, uint32 value) noexcept;
  463. /** Reads a number of bits from a buffer at a given bit index.
  464. The buffer is treated as a sequence of 8-bit bytes, and the value is encoded in little-endian order,
  465. so for example if startBit = 10, and numBits = 11 then the lower 6 bits of the result would be read
  466. from bits 2-8 of sourceBuffer[1], and the upper 5 bits of the result from bits 0-5 of sourceBuffer[2].
  467. @see writeLittleEndianBitsInBuffer
  468. */
  469. uint32 readLittleEndianBitsInBuffer (const void* sourceBuffer, uint32 startBit, uint32 numBits) noexcept;
  470. //==============================================================================
  471. #if JUCE_INTEL || defined (DOXYGEN)
  472. /** This macro can be applied to a float variable to check whether it contains a denormalised
  473. value, and to normalise it if necessary.
  474. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  475. */
  476. #define JUCE_UNDENORMALISE(x) { (x) += 0.1f; (x) -= 0.1f; }
  477. #else
  478. #define JUCE_UNDENORMALISE(x)
  479. #endif
  480. //==============================================================================
  481. /** This namespace contains a few template classes for helping work out class type variations.
  482. */
  483. namespace TypeHelpers
  484. {
  485. /** The ParameterType struct is used to find the best type to use when passing some kind
  486. of object as a parameter.
  487. Of course, this is only likely to be useful in certain esoteric template situations.
  488. E.g. "myFunction (typename TypeHelpers::ParameterType<int>::type, typename TypeHelpers::ParameterType<MyObject>::type)"
  489. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  490. pass-by-value, but passing objects as a const reference, to avoid copying.
  491. */
  492. template <typename Type> struct ParameterType { typedef const Type& type; };
  493. #if ! DOXYGEN
  494. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  495. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  496. template <> struct ParameterType <char> { typedef char type; };
  497. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  498. template <> struct ParameterType <short> { typedef short type; };
  499. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  500. template <> struct ParameterType <int> { typedef int type; };
  501. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  502. template <> struct ParameterType <long> { typedef long type; };
  503. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  504. template <> struct ParameterType <int64> { typedef int64 type; };
  505. template <> struct ParameterType <uint64> { typedef uint64 type; };
  506. template <> struct ParameterType <bool> { typedef bool type; };
  507. template <> struct ParameterType <float> { typedef float type; };
  508. template <> struct ParameterType <double> { typedef double type; };
  509. #endif
  510. /** These templates are designed to take a type, and if it's a double, they return a double
  511. type; for anything else, they return a float type.
  512. */
  513. template <typename Type> struct SmallestFloatType { typedef float type; };
  514. template <> struct SmallestFloatType <double> { typedef double type; };
  515. /** These templates are designed to take an integer type, and return an unsigned int
  516. version with the same size.
  517. */
  518. template <int bytes> struct UnsignedTypeWithSize {};
  519. template <> struct UnsignedTypeWithSize<1> { typedef uint8 type; };
  520. template <> struct UnsignedTypeWithSize<2> { typedef uint16 type; };
  521. template <> struct UnsignedTypeWithSize<4> { typedef uint32 type; };
  522. template <> struct UnsignedTypeWithSize<8> { typedef uint64 type; };
  523. }
  524. //==============================================================================