To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.
root / CollidoscopeApp / include / EnvASR.h @ 0:02467299402e
History | View | Annotate | Download (1.56 KB)
| 1 | 0:02467299402e | f | #pragma once
|
|---|---|---|---|
| 2 | |||
| 3 | namespace collidoscope {
|
||
| 4 | |||
| 5 | template <typename T> |
||
| 6 | class EnvASR |
||
| 7 | {
|
||
| 8 | public:
|
||
| 9 | |||
| 10 | enum class State {
|
||
| 11 | eAttack, |
||
| 12 | eSustain, |
||
| 13 | eRelease, |
||
| 14 | eIdle // before attack after release
|
||
| 15 | }; |
||
| 16 | |||
| 17 | EnvASR( T sustainLevel, T attackTime, T releaseTime, std::size_t sampleRate ) : |
||
| 18 | mSustainLevel( sustainLevel ), |
||
| 19 | mState( State::eIdle ), |
||
| 20 | mValue( 0 )
|
||
| 21 | |||
| 22 | {
|
||
| 23 | if ( attackTime <= 0 ) |
||
| 24 | attackTime = T( 0.001 ); |
||
| 25 | |||
| 26 | if ( releaseTime <= 0 ) |
||
| 27 | releaseTime = T( 0.001 ); |
||
| 28 | |||
| 29 | mAttackRate = T( 1.0 ) / (attackTime * sampleRate); |
||
| 30 | mReleaseRate = T( 1.0 ) / (releaseTime * sampleRate); |
||
| 31 | } |
||
| 32 | |||
| 33 | T tick() |
||
| 34 | {
|
||
| 35 | |||
| 36 | switch ( mState )
|
||
| 37 | {
|
||
| 38 | |||
| 39 | case State::eIdle: {
|
||
| 40 | mValue = 0;
|
||
| 41 | }; |
||
| 42 | break;
|
||
| 43 | |||
| 44 | case State::eAttack: {
|
||
| 45 | mValue += mAttackRate; |
||
| 46 | if ( mValue >= mSustainLevel ){
|
||
| 47 | mValue = mSustainLevel; |
||
| 48 | mState = State::eSustain; |
||
| 49 | } |
||
| 50 | }; |
||
| 51 | break;
|
||
| 52 | |||
| 53 | case State::eRelease:
|
||
| 54 | mValue -= mReleaseRate; |
||
| 55 | if ( mValue <= 0 ){ |
||
| 56 | mValue = 0;
|
||
| 57 | mState = State::eIdle; |
||
| 58 | } |
||
| 59 | break;
|
||
| 60 | default:
|
||
| 61 | break;
|
||
| 62 | } |
||
| 63 | |||
| 64 | return mValue;
|
||
| 65 | |||
| 66 | } |
||
| 67 | |||
| 68 | State getState() const
|
||
| 69 | {
|
||
| 70 | return mState;
|
||
| 71 | } |
||
| 72 | |||
| 73 | void setState( State state )
|
||
| 74 | {
|
||
| 75 | mState = state; |
||
| 76 | } |
||
| 77 | |||
| 78 | private:
|
||
| 79 | T mSustainLevel; |
||
| 80 | T mAttackRate; |
||
| 81 | T mReleaseRate; |
||
| 82 | |||
| 83 | // output
|
||
| 84 | T mValue; |
||
| 85 | |||
| 86 | State mState; |
||
| 87 | |||
| 88 | }; |
||
| 89 | |||
| 90 | |||
| 91 | } |