You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

70 lines
1.9 KiB

/* PolyBLEP oscillator inspired by: https://www.metafunction.co.uk/post/all-about-digital-oscillators-part-2-blits-bleps
* Further info about BLEP at: https://pbat.ch/sndkit/blep/
*/
#include <math.h>
#define PIx2 (2 * M_PI)
class Oscillator {
public:
enum Mode { MODE_SINE, MODE_SAW, MODE_SQUARE };
Mode mode;
float phase;
float phaseStep;
float value;
Oscillator();
float polyBlep(float t) {
double dt = phaseStep / PIx2;
// t-t^2/2 +1/2
// 0 < t <= 1
// discontinuities between 0 & 1
if (t < dt) {
t /= dt;
return t + t - t * t - 1.0;
}
// t^2/2 +t +1/2
// -1 <= t <= 0
// discontinuities between -1 & 0
else if (t > 1.0 - dt) {
t = (t - 1.0) / dt;
return t * t + t + t + 1.0;
}
// no discontinuities
// 0 otherwise
else return 0.0;
}
// This class provides a band-limited oscillator
float tick() {
float t = phase / PIx2; // Define half phase
if (mode == MODE_SINE) {
value = sin(phase); // No harmonics in sine so no aliasing!! No Poly BLEPs needed!
} else if (mode == MODE_SAW) {
value = (2.0 * phase / PIx2) - 1.0; // Render naive waveshape
value -= polyBlep(t); // Layer output of Poly BLEP on top
} else if (mode == MODE_SQUARE) {
if (phase < M_PI) {
value = 1.0; // Flip
} else {
value = -1.0; // Flop
}
value += polyBlep(t); // Layer output of Poly BLEP on top (flip)
value -= polyBlep(fmod(t + 0.5, 1.0)); // Layer output of Poly BLEP on top (flop)
}
phase += phaseStep;
if(phase >= PIx2) {
phase -= PIx2;
}
return value; // Output
}
};