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.

477 lines
17KB

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