-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvf_osc.hpp
105 lines (94 loc) · 1.89 KB
/
svf_osc.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#pragma once
#include <math.h>
template <size_t SAMPLERATE, size_t OVERSAMPLING = 1> class SvfOsc
{
private:
static const int driftCorr = 10;
float_t fq = 0; // frequency
float_t f = 0; // freq increment
bool sign = true;
float_t _sin = 0.;
float_t _cos = 1.;
int driftCount = 0;
void stabilize()
{
if (_cos > 1.)
{
_cos = 1;
_sin = 0;
driftCount = 0;
}
else if (_cos < -1.)
{
_cos = -1;
_sin = 0;
driftCount = 0;
}
else if (_sin > 1.)
{
_cos = 0;
_sin = 1;
driftCount = 0;
}
else if (_sin < -1.)
{
_cos = 0;
_sin = -1;
driftCount = 0;
}
else if (driftCount >= driftCorr)
{
float_t g = 0.5 * (3 - (_cos * _cos + _sin * _sin));
_cos *= g;
_sin *= g;
driftCount = 0;
}
}
void _next()
{
if (sign)
{
_sin = _sin + f * _cos;
_cos = _cos - f * _sin;
}
else
{
_sin = _sin - f * _cos;
_cos = _cos + f * _sin;
}
stabilize();
}
void calcFreq()
{
f = std::abs(2. * M_PI * (fq / (float_t)(SAMPLERATE * OVERSAMPLING)));
}
public:
SvfOsc()
{
setFreq(1);
}
SvfOsc(float_t freq)
{
setFreq(freq);
}
void next()
{
for (size_t i = 0; i < OVERSAMPLING; i++)
{
_next();
}
}
void setFreq(float_t freq)
{
fq = freq;
calcFreq();
}
float_t sin()
{
return _sin;
}
float_t cos()
{
return _cos;
}
};