1 /*
2 * utils.h
3 * DIN Is Noise is copyright (c) 2006-2021 Jagannathan Sampath
4 * For more information, please visit http://dinisnoise.org/
5 */
6 
7 #ifndef _UTILS
8 #define _UTILS
9 
10 #define SIGN(x) ((x) < 0 ? -1 : (x) > 0)
11 
12 #include "log.h"
13 #include <cmath>
14 
15 using namespace std;
16 
transfer(const T & v,const T & a,const T & b,const T & c,const T & d)17 template <typename T> T transfer (const T& v, const T& a, const T& b, const T& c, const T& d) {
18   if (a != b) {
19     T q = (v - a) / (b - a);
20     T tv = c + q * (d - c);
21     return tv;
22   }
23   return 0;
24 }
25 
inrange(const T & min,const T & val,const T & max)26 template <typename T> inline bool inrange (const T& min, const T& val, const T& max) {
27   return ((val >= min) && (val <= max));
28 }
29 
clamp(const T & lo,T & val,const T & hi)30 template<typename T> inline int clamp (const T& lo, T& val, const T& hi) {
31   // ensures lo <= val <= hi
32   if (val < lo) {
33     val = lo;
34     return -1;
35   } else if (val > hi) {
36     val = hi;
37     return 1;
38   }
39   return 0;
40 }
41 
wrap(const T & lo,T & val,const T & hi)42 template<typename T> inline T& wrap (const T& lo, T& val, const T& hi) {
43   // val stays between lo and hi but wraps
44   if (val < lo) val = hi; else if (val > hi) val = lo;
45   return val;
46 }
47 
bounce(T low,T & val,T high,T reb)48 template<typename T> inline int bounce (T low, T& val, T high, T reb) {
49 	// val stays between lo and hi but rebounds
50 	if (val < low) {
51 		val += reb;
52 		return bounce (low, val, high, reb); // can still exceed high
53 	} else if (val > high) {
54 		val -= reb;
55 		return bounce (low, val, high, reb); // can still go below low
56 	}
57 	return 1;
58 }
59 
60 template <typename T> int equals (T a, T b, T e = 0.0001f) {
61 	return (abs(a-b) <= e);
62 }
63 
sign(T t)64 template <typename T> int sign (T t) {
65   return ( (t > T(0)) - (t < T(0)) );
66 }
67 
68 struct item_op {
69 	virtual int operator()(int) const = 0;
70 };
71 
72 struct sel : item_op {
operatorsel73 	int operator()(int) const { return 1;}
74 };
75 
76 struct desel : item_op {
operatordesel77 	int operator()(int) const { return 0;}
78 };
79 
80 struct togg : item_op {
operatortogg81 	int operator()(int i) const { return !i;}
82 };
83 
84 void multiply (float* out, float* mul, int n); // multiply n muls with n outs; store in out
85 void multiply (float* out, int n, float d); // multiply n outs with d; store in out
86 void fill (float* buf, float s, float e, int n); // fill buf with values interpolated from s to e
87 void tween (float* buf1, float* buf2, int n, float amount); // interpolate buf2 -> buf1 by amount; store in buf1
88 void tween (float* buf1, float* buf2, int n, float* pamount); // interpolate buf2 -> buf1 by amount array; store in buf1
89 
90 #endif
91