tonewheel/plugin/generator.cpp

95 lines
2.7 KiB
C++

/*
tonewheel organ plugin
Copyright 2025 Gordon JC Pearce <gordonjcp@gjcp.net>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "generator.hpp"
#include <math.h>
#include <string.h>
#include <cstdio>
#include "DistrhoPluginInfo.h"
// globals set when the plugin is activated
// sample rate or buffer size may actually change!
extern double sampleRate;
extern uint32_t bufferSize;
Generator::Generator() {
}
Generator::~Generator() {
}
void Generator::activate() {
// create a sine table
for (uint16_t i = 0; i < 256; i++) {
sine[i] = sin((float)i / 128.0 * 3.14159);
}
// create the phase increments for each semitone
for (uint8_t i = 0; i < 12; i++) {
phase[i] = 0;
uint32_t f;
f = (1 << 30) * (32.703 * powf(2, 0.083334 * i) / sampleRate);
omega[i] = f;
}
}
void Generator::run(float *output, uint32_t frames) {
Voice *v;
uint32_t i;
uint8_t k, p;
uint32_t d = 0;
memset(output, 0, frames * sizeof(float));
// for every frame of the output...
for (i = 0; i < frames; i++) {
// loop over all twelve semitones adding on the phase increment
// these are 32-bit unsigned values and will wrap
for (p = 0; p < 12; p++) {
phase[p] += omega[p];
}
// loop over all the voices, calculating what they need
for (k = 0; k < NUM_VOICES; k++) {
v = &voices[k];
// you'd loop over all the stops in the register here
// 8' stop
d = (phase[v->semi] >> (24 - v->oct)) & 0xff;
// convert to a sine and scale it by 0.25, which would want to be your drawbar amount
output[i] += .25 * (sine[d] * v->gate);
// mutation stops are a fifth up
d = (phase[(v->semi + 7) % 12] >> (22 - v->oct)) & 0xff;
output[i] += .25 * (sine[d] * v->gate);
}
}
}
void Voice::startNote(uint8_t key) {
// start a new note
semi = key % 12, oct = (key / 12);
gate = 1;
}
void Voice::stopNote() {
gate = 0;
}