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.

489 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. wassert (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. // if these are in the wrong order, results are unpredictable..
  137. CARLA_SAFE_ASSERT_RETURN(lowerLimit <= upperLimit, lowerLimit);
  138. return (valueToConstrain < lowerLimit) ? lowerLimit
  139. : ((upperLimit < valueToConstrain) ? upperLimit
  140. : valueToConstrain);
  141. }
  142. /** Returns true if a value is at least zero, and also below a specified upper limit.
  143. This is basically a quicker way to write:
  144. @code valueToTest >= 0 && valueToTest < upperLimit
  145. @endcode
  146. */
  147. template <typename Type>
  148. bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  149. {
  150. // makes no sense to call this if the upper limit is itself below zero..
  151. CARLA_SAFE_ASSERT_RETURN(Type() <= upperLimit, false);
  152. return Type() <= valueToTest && valueToTest < upperLimit;
  153. }
  154. template <>
  155. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  156. {
  157. // makes no sense to call this if the upper limit is itself below zero..
  158. CARLA_SAFE_ASSERT_RETURN(upperLimit >= 0, false);
  159. return static_cast<unsigned int> (valueToTest) < static_cast<unsigned int> (upperLimit);
  160. }
  161. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  162. This is basically a quicker way to write:
  163. @code valueToTest >= 0 && valueToTest <= upperLimit
  164. @endcode
  165. */
  166. template <typename Type>
  167. bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  168. {
  169. // makes no sense to call this if the upper limit is itself below zero..
  170. CARLA_SAFE_ASSERT_RETURN(Type() <= upperLimit, false);
  171. return Type() <= valueToTest && valueToTest <= upperLimit;
  172. }
  173. template <>
  174. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  175. {
  176. // makes no sense to call this if the upper limit is itself below zero..
  177. CARLA_SAFE_ASSERT_RETURN(upperLimit >= 0, false);
  178. return static_cast<unsigned int> (valueToTest) <= static_cast<unsigned int> (upperLimit);
  179. }
  180. //==============================================================================
  181. /** Handy function to swap two values. */
  182. template <typename Type>
  183. void swapVariables (Type& variable1, Type& variable2)
  184. {
  185. std::swap (variable1, variable2);
  186. }
  187. /** Handy function for avoiding unused variables warning. */
  188. template <typename Type1>
  189. void ignoreUnused (const Type1&) noexcept {}
  190. template <typename Type1, typename Type2>
  191. void ignoreUnused (const Type1&, const Type2&) noexcept {}
  192. template <typename Type1, typename Type2, typename Type3>
  193. void ignoreUnused (const Type1&, const Type2&, const Type3&) noexcept {}
  194. template <typename Type1, typename Type2, typename Type3, typename Type4>
  195. void ignoreUnused (const Type1&, const Type2&, const Type3&, const Type4&) noexcept {}
  196. /** Handy function for getting the number of elements in a simple const C array.
  197. E.g.
  198. @code
  199. static size_t myArray[] = { 1, 2, 3 };
  200. size_t numElements = numElementsInArray (myArray) // returns 3
  201. @endcode
  202. */
  203. template <typename Type, size_t N>
  204. size_t numElementsInArray (Type (&array)[N])
  205. {
  206. ignoreUnused (array);
  207. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  208. return N;
  209. }
  210. //==============================================================================
  211. // Some useful maths functions that aren't always present with all compilers and build settings.
  212. /** Using water_hypot is easier than dealing with the different types of hypot function
  213. that are provided by the various platforms and compilers. */
  214. template <typename Type>
  215. Type water_hypot (Type a, Type b) noexcept
  216. {
  217. return static_cast<Type> (hypot (a, b));
  218. }
  219. template <>
  220. inline float water_hypot (float a, float b) noexcept
  221. {
  222. return hypotf (a, b);
  223. }
  224. /** 64-bit abs function. */
  225. inline int64 abs64 (const int64 n) noexcept
  226. {
  227. return (n >= 0) ? n : -n;
  228. }
  229. //==============================================================================
  230. /** A predefined value for Pi, at double-precision.
  231. @see float_Pi
  232. */
  233. const double double_Pi = 3.1415926535897932384626433832795;
  234. /** A predefined value for Pi, at single-precision.
  235. @see double_Pi
  236. */
  237. const float float_Pi = 3.14159265358979323846f;
  238. /** Converts an angle in degrees to radians. */
  239. inline float degreesToRadians (float degrees) noexcept { return degrees * (float_Pi / 180.0f); }
  240. /** Converts an angle in degrees to radians. */
  241. inline double degreesToRadians (double degrees) noexcept { return degrees * (double_Pi / 180.0); }
  242. /** Converts an angle in radians to degrees. */
  243. inline float radiansToDegrees (float radians) noexcept { return radians * (180.0f / float_Pi); }
  244. /** Converts an angle in radians to degrees. */
  245. inline double radiansToDegrees (double radians) noexcept { return radians * (180.0 / double_Pi); }
  246. //==============================================================================
  247. /** The isfinite() method seems to vary between platforms, so this is a
  248. platform-independent function for it.
  249. */
  250. template <typename NumericType>
  251. bool water_isfinite (NumericType) noexcept
  252. {
  253. return true; // Integer types are always finite
  254. }
  255. template <>
  256. inline bool water_isfinite (float value) noexcept
  257. {
  258. return std::isfinite (value);
  259. }
  260. template <>
  261. inline bool water_isfinite (double value) noexcept
  262. {
  263. return std::isfinite (value);
  264. }
  265. //==============================================================================
  266. /** Fast floating-point-to-integer conversion.
  267. This is faster than using the normal c++ cast to convert a float to an int, and
  268. it will round the value to the nearest integer, rather than rounding it down
  269. like the normal cast does.
  270. Note that this routine gets its speed at the expense of some accuracy, and when
  271. rounding values whose floating point component is exactly 0.5, odd numbers and
  272. even numbers will be rounded up or down differently.
  273. */
  274. template <typename FloatType>
  275. int roundToInt (const FloatType value) noexcept
  276. {
  277. union { int asInt[2]; double asDouble; } n;
  278. n.asDouble = ((double) value) + 6755399441055744.0;
  279. #if defined(__BIG_ENDIAN__) || (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
  280. return n.asInt [1];
  281. #else
  282. return n.asInt [0];
  283. #endif
  284. }
  285. inline int roundToInt (int value) noexcept
  286. {
  287. return value;
  288. }
  289. /** Fast floating-point-to-integer conversion.
  290. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  291. fine for values above zero, but negative numbers are rounded the wrong way.
  292. */
  293. inline int roundToIntAccurate (double value) noexcept
  294. {
  295. return roundToInt (value + 1.5e-8);
  296. }
  297. /** Fast floating-point-to-integer conversion.
  298. This is faster than using the normal c++ cast to convert a double to an int, and
  299. it will round the value to the nearest integer, rather than rounding it down
  300. like the normal cast does.
  301. Note that this routine gets its speed at the expense of some accuracy, and when
  302. rounding values whose floating point component is exactly 0.5, odd numbers and
  303. even numbers will be rounded up or down differently. For a more accurate conversion,
  304. see roundDoubleToIntAccurate().
  305. */
  306. inline int roundDoubleToInt (double value) noexcept
  307. {
  308. return roundToInt (value);
  309. }
  310. /** Fast floating-point-to-integer conversion.
  311. This is faster than using the normal c++ cast to convert a float to an int, and
  312. it will round the value to the nearest integer, rather than rounding it down
  313. like the normal cast does.
  314. Note that this routine gets its speed at the expense of some accuracy, and when
  315. rounding values whose floating point component is exactly 0.5, odd numbers and
  316. even numbers will be rounded up or down differently.
  317. */
  318. inline int roundFloatToInt (float value) noexcept
  319. {
  320. return roundToInt (value);
  321. }
  322. //==============================================================================
  323. /** Returns true if the specified integer is a power-of-two. */
  324. template <typename IntegerType>
  325. bool isPowerOfTwo (IntegerType value)
  326. {
  327. return (value & (value - 1)) == 0;
  328. }
  329. /** Returns the smallest power-of-two which is equal to or greater than the given integer. */
  330. inline int nextPowerOfTwo (int n) noexcept
  331. {
  332. --n;
  333. n |= (n >> 1);
  334. n |= (n >> 2);
  335. n |= (n >> 4);
  336. n |= (n >> 8);
  337. n |= (n >> 16);
  338. return n + 1;
  339. }
  340. /** Returns the index of the highest set bit in a (non-zero) number.
  341. So for n=3 this would return 1, for n=7 it returns 2, etc.
  342. An input value of 0 is illegal!
  343. */
  344. int findHighestSetBit (uint32 n) noexcept;
  345. /** Returns the number of bits in a 32-bit integer. */
  346. inline int countNumberOfBits (uint32 n) noexcept
  347. {
  348. n -= ((n >> 1) & 0x55555555);
  349. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  350. n = (((n >> 4) + n) & 0x0f0f0f0f);
  351. n += (n >> 8);
  352. n += (n >> 16);
  353. return (int) (n & 0x3f);
  354. }
  355. /** Returns the number of bits in a 64-bit integer. */
  356. inline int countNumberOfBits (uint64 n) noexcept
  357. {
  358. return countNumberOfBits ((uint32) n) + countNumberOfBits ((uint32) (n >> 32));
  359. }
  360. /** Performs a modulo operation, but can cope with the dividend being negative.
  361. The divisor must be greater than zero.
  362. */
  363. template <typename IntegerType>
  364. IntegerType negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
  365. {
  366. wassert (divisor > 0);
  367. dividend %= divisor;
  368. return (dividend < 0) ? (dividend + divisor) : dividend;
  369. }
  370. /** Returns the square of its argument. */
  371. template <typename NumericType>
  372. NumericType square (NumericType n) noexcept
  373. {
  374. return n * n;
  375. }
  376. //==============================================================================
  377. /** Writes a number of bits into a memory 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 value would be written
  380. into bits 2-8 of targetBuffer[1], and the upper 5 bits of value into bits 0-5 of targetBuffer[2].
  381. @see readLittleEndianBitsInBuffer
  382. */
  383. void writeLittleEndianBitsInBuffer (void* targetBuffer, uint32 startBit, uint32 numBits, uint32 value) noexcept;
  384. /** Reads a number of bits from a buffer at a given bit index.
  385. The buffer is treated as a sequence of 8-bit bytes, and the value is encoded in little-endian order,
  386. so for example if startBit = 10, and numBits = 11 then the lower 6 bits of the result would be read
  387. from bits 2-8 of sourceBuffer[1], and the upper 5 bits of the result from bits 0-5 of sourceBuffer[2].
  388. @see writeLittleEndianBitsInBuffer
  389. */
  390. uint32 readLittleEndianBitsInBuffer (const void* sourceBuffer, uint32 startBit, uint32 numBits) noexcept;
  391. //==============================================================================
  392. }
  393. #endif // WATER_MATHSFUNCTIONS_H_INCLUDED