-
Notifications
You must be signed in to change notification settings - Fork 0
/
AdsrEnvelope.cpp
121 lines (108 loc) · 2.3 KB
/
AdsrEnvelope.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
117
118
119
120
121
#include "AdsrEnvelope.h"
AdsrEnvelope::AdsrEnvelope() : cycleAttackDecay(false),
endReached(true), sustain(0), stage(0),
stages({EnvelopeStage(true), EnvelopeStage(true), EnvelopeStage(false), EnvelopeStage(true)})
{
}
AdsrEnvelope::~AdsrEnvelope()
{
}
void AdsrEnvelope::setAttack(int samples)
{
stages[0].setLength(samples);
}
void AdsrEnvelope::setDecay(int samples)
{
stages[1].setLength(samples);
}
void AdsrEnvelope::setSustain(float level)
{
sustain = level;
}
void AdsrEnvelope::setRelease(int samples)
{
if (samples < 40)
samples = 40; // to smoothen the clicking sound when using minimal release
stages[3].setLength(samples);
}
void AdsrEnvelope::calculateNext()
{
if (endReached)
{
return;
}
EnvelopeStage *current = &stages[stage];
if (current->hasNext())
{
current->calcuateNext();
float ratio = current->getRatio();
switch (stage)
{
case 0:
envelope = ratio;
break;
case 1:
envelope = 1 - (1 - sustain) * ratio;
break;
case 2:
envelope = sustain;
break;
case 3:
envelope = releaseLevel * (1 - ratio);
break;
default:
break;
}
}
else if (stage < 3)
{
// If cycling A-D-S-A-D-S... at the end of decay stage, trigger attack again
if (cycleAttackDecay && stage == 1)
triggerStage(0);
else
triggerStage(stage + 1);
calculateNext();
}
else
{
// release ended
envelope = 0;
endReached = true;
}
}
bool AdsrEnvelope::ended()
{
return endReached;
}
void AdsrEnvelope::trigger()
{
endReached = false;
triggerStage(0);
}
void AdsrEnvelope::triggerStage(int stage)
{
this->stage = stage;
stages[stage].reset();
}
void AdsrEnvelope::release()
{
if (stage < 3)
{
releaseLevel = envelope;
releaseStage = stage;
triggerStage(3);
}
}
int AdsrEnvelope::getStage()
{
return stage;
}
float AdsrEnvelope::getRatio(int xStage)
{
xStage = xStage == -1 ? stage : xStage;
return stages[xStage].getRatio();
}
float AdsrEnvelope::getEnvelope()
{
return envelope;
}