forked from thunderox/triceratops-old-version-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lfo.cpp
executable file
·116 lines (100 loc) · 2.26 KB
/
lfo.cpp
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
106
107
108
109
110
111
112
113
114
115
116
//============================================================================
/**
Implementation file for LFO.hpp
@author Remy Muller
@date 20030822
*/
//============================================================================
#include <cmath>
#include "lfo.h"
const std::string LFO::waveNames[] = {"triangle", "sinus", "sawtooth", "square", "exponent"};
LFO::LFO(float samplerate)
: samplerate(samplerate),
phase(0),
inc(0)
{
setWaveform(LFO::sinus);
setRate(1.0f); //1Hz
}
static const float k1Div24lowerBits = 1.0f/(float)(1<<24);
float LFO::tick()
{
// the 8 MSB are the index in the table in the range 0-255
int i = phase >> 24;
// and the 24 LSB are the fractionnal part
float frac = (phase & 0x00FFFFFF) * k1Div24lowerBits;
// increment the phase for the next tick
phase += inc; // the phase overflow itself
return table[i]*(1.0f-frac) + table[i+1]*frac; // linear interpolation
}
void LFO::setRate(float rate)
{
/** the rate in Hz is converted to a phase increment with the following formula
\f[ inc = (256*rate/samplerate) * 2^24 \f] */
inc = (unsigned int)((256.0f * rate / samplerate) * (float)(1<<24));
}
void LFO::setWaveform(waveform_t index)
{
switch(index)
{
case sinus:
{
double pi = 4.0 * atan(1.0);
int i;
for(i=0;i<=256;i++)
table[i] = sin(2.0f*pi*(i/256.0f));
break;
}
case triangle:
{
int i;
for(i=0;i<64;i++)
{
table[i] = i / 64.0f;
table[i+64] = (64-i) / 64.0f;
table[i+128] = - i / 64.0f;
table[i+192] = - (64-i) / 64.0f;
}
table[256] = 0.0f;
break;
}
case sawtooth:
{
int i;
for(i=0;i<256;i++)
{
table[i] = 2.0f*(i/255.0f) - 1.0f;
}
table[256] = -1.0f;
break;
}
case square:
{
int i;
for(i=0;i<128;i++)
{
table[i] = 1.0f;
table[i+128] = -1.0f;
}
table[256] = 1.0f;
break;
}
case exponent:
{
/* symetric exponent similar to triangle */
int i;
float e = (float)exp(1.0f);
for(i=0;i<128;i++)
{
table[i] = 2.0f * ((exp(i/128.0f) - 1.0f) / (e - 1.0f)) - 1.0f ;
table[i+128] = 2.0f * ((exp((128-i)/128.0f) - 1.0f) / (e - 1.0f)) - 1.0f ;
}
table[256] = -1.0f;
break;
}
default:
{
break;
}
}
}