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.

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