Audio plugin host https://kx.studio/carla
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.

juce_MathsFunctions.h 22KB

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