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.

375 lines
12KB

  1. /*
  2. The filter DSP code has been derived from
  3. Miller Puckette's code hosted at
  4. https://github.com/ddiakopoulos/MoogLadders/blob/master/src/RKSimulationModel.h
  5. which is licensed for use under the following terms (MIT license):
  6. Copyright (c) 2015, Miller Puckette. All rights reserved.
  7. Redistribution and use in source and binary forms, with or without
  8. modification, are permitted provided that the following conditions are met:
  9. * Redistributions of source code must retain the above copyright notice, this
  10. list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above copyright notice,
  12. this list of conditions and the following disclaimer in the documentation
  13. and/or other materials provided with the distribution.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  18. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  20. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  21. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  22. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  23. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #include "FrozenWasteland.hpp"
  26. #include "dsp/digital.hpp"
  27. #include "dsp/decimator.hpp"
  28. #include "dsp/filter.hpp"
  29. namespace rack_plugin_FrozenWasteland {
  30. // The clipping function of a transistor pair is approximately tanh(x)
  31. // TODO: Put this in a lookup table. 5th order approx doesn't seem to cut it
  32. inline float clip(float x) {
  33. return tanhf(x);
  34. }
  35. template <int OVERSAMPLE, int QUALITY>
  36. struct VoltageControlledOscillator {
  37. float phase = 0.0;
  38. float freq;
  39. float pw = 0.5;
  40. float pitch;
  41. Decimator<OVERSAMPLE, QUALITY> sqrDecimator;
  42. RCFilter sqrFilter;
  43. float sqrBuffer[OVERSAMPLE] = {};
  44. void setPitch(float pitchKnob, float pitchCv) {
  45. // Compute frequency
  46. pitch = pitchKnob;
  47. pitch = roundf(pitch);
  48. pitch += pitchCv;
  49. // Note C3
  50. freq = 261.626 * powf(2.0, pitch / 12.0);
  51. }
  52. void setPulseWidth(float pulseWidth) {
  53. const float pwMin = 0.01;
  54. pw = clamp(pulseWidth, pwMin, 1.0f - pwMin);
  55. }
  56. void process(float deltaTime) {
  57. // Advance phase
  58. float deltaPhase = clamp(freq * deltaTime, 1e-6f, 0.5f);
  59. sqrFilter.setCutoff(40.0 * deltaTime);
  60. for (int i = 0; i < OVERSAMPLE; i++) {
  61. sqrBuffer[i] = (phase < pw) ? 1.f : -1.f;
  62. // Advance phase
  63. phase += deltaPhase / OVERSAMPLE;
  64. phase = eucmod(phase, 1.0f);
  65. }
  66. }
  67. float sqr() {
  68. return sqrDecimator.process(sqrBuffer);
  69. }
  70. float light() {
  71. return sinf(2*M_PI * phase);
  72. }
  73. };
  74. struct PhaseComparator {
  75. bool clock = false;
  76. bool data = false;
  77. bool nandGate1 = false;
  78. bool nandGate2 = false;
  79. bool nandGate3 = false;
  80. bool nandGate4 = false;
  81. void setClock(float clockInput) {
  82. clock = clockInput >= 0;
  83. }
  84. void setData(float dataInput) {
  85. data = dataInput >= 0;
  86. }
  87. float XORoutput() {
  88. return (clock ^ data) ? 5.0 : -5.0;
  89. }
  90. float FlipFlopOutput() {
  91. bool invertedData = !data;
  92. nandGate1 = !(data && clock);
  93. nandGate2 = !(clock && invertedData);
  94. nandGate3 = !(nandGate1 && nandGate4);
  95. nandGate4 = !(nandGate3 && nandGate2);
  96. return nandGate3 ? 5.0 : -5.0;
  97. }
  98. };
  99. struct LadderFilter {
  100. float cutoff = 1000.0;
  101. float resonance = 0.0;
  102. float state[4] = {};
  103. void calculateDerivatives(float input, float *dstate, const float *state) {
  104. float cutoff2Pi = 2*M_PI * cutoff;
  105. float satstate0 = clip(state[0]);
  106. float satstate1 = clip(state[1]);
  107. float satstate2 = clip(state[2]);
  108. dstate[0] = cutoff2Pi * (clip(input - resonance * state[3]) - satstate0);
  109. dstate[1] = cutoff2Pi * (satstate0 - satstate1);
  110. dstate[2] = cutoff2Pi * (satstate1 - satstate2);
  111. dstate[3] = cutoff2Pi * (satstate2 - clip(state[3]));
  112. }
  113. void process(float input, float dt) {
  114. float deriv1[4], deriv2[4], deriv3[4], deriv4[4], tempState[4];
  115. calculateDerivatives(input, deriv1, state);
  116. for (int i = 0; i < 4; i++)
  117. tempState[i] = state[i] + 0.5 * dt * deriv1[i];
  118. calculateDerivatives(input, deriv2, tempState);
  119. for (int i = 0; i < 4; i++)
  120. tempState[i] = state[i] + 0.5 * dt * deriv2[i];
  121. calculateDerivatives(input, deriv3, tempState);
  122. for (int i = 0; i < 4; i++)
  123. tempState[i] = state[i] + dt * deriv3[i];
  124. calculateDerivatives(input, deriv4, tempState);
  125. for (int i = 0; i < 4; i++)
  126. state[i] += (1.0 / 6.0) * dt * (deriv1[i] + 2.0 * deriv2[i] + 2.0 * deriv3[i] + deriv4[i]);
  127. }
  128. void reset() {
  129. for (int i = 0; i < 4; i++) {
  130. state[i] = 0.0;
  131. }
  132. }
  133. };
  134. struct PhasedLockedLoop : Module {
  135. enum ParamIds {
  136. VCO_FREQ_PARAM,
  137. VCO_PW_PARAM,
  138. VCO_PWCV_PARAM,
  139. LPF_FREQ_PARAM,
  140. COMPARATOR_TYPE_PARAM,
  141. NUM_PARAMS
  142. };
  143. enum InputIds {
  144. VCO_CV_INPUT,
  145. VCO_PW_INPUT,
  146. PHASE_COMPARATOR_INPUT,
  147. SIGNAL_INPUT,
  148. LPF_FREQ_INPUT,
  149. NUM_INPUTS
  150. };
  151. enum OutputIds {
  152. SQUARE_OUTPUT,
  153. COMPARATOR_OUTPUT,
  154. LPF_OUTPUT,
  155. NUM_OUTPUTS
  156. };
  157. enum LightIds {
  158. PHASE_LOCKED_LIGHT,
  159. XOR_COMPARATOR_LIGHT,
  160. FLIP_FLOP_COMPARATOR_LIGHT,
  161. NUM_LIGHTS
  162. };
  163. enum ComparatorTypes {
  164. XOR_COMPARATOR,
  165. FLIP_FLOP_COMARATOR
  166. };
  167. VoltageControlledOscillator<16,16> oscillator;
  168. PhaseComparator comparator;
  169. LadderFilter filter;
  170. SchmittTrigger modeTrigger;
  171. float filterOutput = 0;
  172. int currentComparatorType = XOR_COMPARATOR;
  173. PhasedLockedLoop() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {}
  174. void step() override;
  175. json_t *toJson() override {
  176. json_t *rootJ = json_object();
  177. json_object_set_new(rootJ, "comparatorType", json_integer((int) currentComparatorType));
  178. return rootJ;
  179. }
  180. void fromJson(json_t *rootJ) override {
  181. json_t *sumJ = json_object_get(rootJ, "comparatorType");
  182. if (sumJ)
  183. currentComparatorType = json_integer_value(sumJ);
  184. }
  185. // For more advanced Module features, read Rack's engine.hpp header file
  186. // - toJson, fromJson: serialization of internal data
  187. // - onSampleRateChange: event triggered by a change of sample rate
  188. // - onReset, onRandomize, onCreate, onDelete: implements special behavior when user clicks these from the context menu
  189. };
  190. void PhasedLockedLoop::step() {
  191. // Modes
  192. if (modeTrigger.process(params[COMPARATOR_TYPE_PARAM].value)) {
  193. currentComparatorType = (currentComparatorType + 1) % 2; //only 2...for now!!!
  194. }
  195. lights[XOR_COMPARATOR_LIGHT].value = currentComparatorType == XOR_COMPARATOR ? 1.0 : 0.0;
  196. lights[FLIP_FLOP_COMPARATOR_LIGHT].value = currentComparatorType == FLIP_FLOP_COMARATOR ? 1.0 : 0.0;
  197. float pitchCv;
  198. if (inputs[VCO_CV_INPUT].active) {
  199. pitchCv = 12.0 * inputs[VCO_CV_INPUT].value;
  200. } else {
  201. pitchCv = 12.0 * filterOutput;
  202. }
  203. float pulseWidth = params[VCO_PW_PARAM].value;
  204. if(inputs[VCO_PW_INPUT].active) {
  205. pulseWidth += inputs[VCO_PW_INPUT].value * (params[VCO_PWCV_PARAM].value / 10.0);
  206. }
  207. //pitchCv = 0.0;// Test
  208. oscillator.setPitch(params[VCO_FREQ_PARAM].value, pitchCv);
  209. oscillator.setPulseWidth(pulseWidth);
  210. oscillator.process(1.0 / engineGetSampleRate());
  211. float squareOutput = 5.0 * oscillator.sqr(); //Used a lot :)
  212. outputs[SQUARE_OUTPUT].value = squareOutput;
  213. //normally use internally genrated square wave, unless the input is being used
  214. float phaseComparatorData; //
  215. if(inputs[PHASE_COMPARATOR_INPUT].active) {
  216. phaseComparatorData = inputs[PHASE_COMPARATOR_INPUT].value;
  217. } else {
  218. phaseComparatorData = squareOutput;
  219. }
  220. comparator.setData(phaseComparatorData);
  221. //This is what we compare either the internal square wave, or alternate input too
  222. if(inputs[SIGNAL_INPUT].active) {
  223. comparator.setClock(inputs[SIGNAL_INPUT].value);
  224. }
  225. float comparatorOutput;
  226. switch (currentComparatorType) {
  227. case XOR_COMPARATOR :
  228. comparatorOutput = comparator.XORoutput();
  229. break;
  230. case FLIP_FLOP_COMARATOR :
  231. comparatorOutput = comparator.FlipFlopOutput();
  232. break;
  233. default:
  234. comparatorOutput = comparator.XORoutput();
  235. break;
  236. }
  237. outputs[COMPARATOR_OUTPUT].value = comparatorOutput;
  238. lights[PHASE_LOCKED_LIGHT].value = ((comparatorOutput >= 0.0 && phaseComparatorData >= 0.0) || (comparatorOutput < 0.0 && phaseComparatorData < 0.0));
  239. //feed comparator into the filter
  240. float filterInput = comparatorOutput / 5.0;
  241. // Set cutoff frequency
  242. float cutoffExp = params[LPF_FREQ_PARAM].value;
  243. if (inputs[LPF_FREQ_INPUT].active) {
  244. cutoffExp += (inputs[LPF_FREQ_INPUT].value / 5);
  245. }
  246. cutoffExp = clamp(cutoffExp, 0.0f, 1.0f);
  247. const float minCutoff = 15.0;
  248. const float maxCutoff = 8400.0;
  249. filter.cutoff = minCutoff * powf(maxCutoff / minCutoff, cutoffExp);
  250. // Push a sample to the state filter
  251. filter.process(filterInput, 1.0/engineGetSampleRate());
  252. // Set outputs
  253. filterOutput = 5.0 * filter.state[3];
  254. outputs[LPF_OUTPUT].value = filterOutput;
  255. }
  256. struct PhasedLockedLoopWidget : ModuleWidget {
  257. PhasedLockedLoopWidget(PhasedLockedLoop *module);
  258. };
  259. PhasedLockedLoopWidget::PhasedLockedLoopWidget(PhasedLockedLoop *module) : ModuleWidget(module) {
  260. box.size = Vec(15*10, RACK_GRID_HEIGHT);
  261. {
  262. SVGPanel *panel = new SVGPanel();
  263. panel->box.size = box.size;
  264. panel->setBackground(SVG::load(assetPlugin(plugin, "res/PhasedLockedLoop.svg")));
  265. addChild(panel);
  266. }
  267. addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH-12, 0)));
  268. addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH + 12, 0)));
  269. addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH-12, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  270. addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH + 12, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  271. addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(100, 44), module, PhasedLockedLoop::VCO_FREQ_PARAM, -54.0, 54.0, 0.0));
  272. addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(85, 78), module, PhasedLockedLoop::VCO_PW_PARAM, 0, 1, 0.5));
  273. addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(118, 78), module, PhasedLockedLoop::VCO_PWCV_PARAM, 0, 1, 0));
  274. addParam(ParamWidget::create<RoundBlackKnob>(Vec(97, 305), module, PhasedLockedLoop::LPF_FREQ_PARAM, 0, 1, 0.5));
  275. addParam(ParamWidget::create<CKD6>(Vec(18, 202), module, PhasedLockedLoop::COMPARATOR_TYPE_PARAM, 0.0, 1.0, 0.0));
  276. addInput(Port::create<PJ301MPort>(Vec(8, 30), Port::INPUT, module, PhasedLockedLoop::VCO_CV_INPUT));
  277. addInput(Port::create<PJ301MPort>(Vec(8, 62), Port::INPUT, module, PhasedLockedLoop::VCO_PW_INPUT));
  278. addInput(Port::create<PJ301MPort>(Vec(8, 135), Port::INPUT, module, PhasedLockedLoop::PHASE_COMPARATOR_INPUT));
  279. addInput(Port::create<PJ301MPort>(Vec(8, 165), Port::INPUT, module, PhasedLockedLoop::SIGNAL_INPUT));
  280. addInput(Port::create<PJ301MPort>(Vec(8, 289), Port::INPUT, module, PhasedLockedLoop::LPF_FREQ_INPUT));
  281. addOutput(Port::create<PJ301MPort>(Vec(8, 94), Port::OUTPUT, module, PhasedLockedLoop::SQUARE_OUTPUT));
  282. addOutput(Port::create<PJ301MPort>(Vec(8, 239), Port::OUTPUT, module, PhasedLockedLoop::COMPARATOR_OUTPUT));
  283. addOutput(Port::create<PJ301MPort>(Vec(8, 319), Port::OUTPUT, module, PhasedLockedLoop::LPF_OUTPUT));
  284. addChild(ModuleLightWidget::create<LargeLight<BlueLight>>(Vec(112, 155), module, PhasedLockedLoop::PHASE_LOCKED_LIGHT));
  285. addChild(ModuleLightWidget::create<SmallLight<BlueLight>>(Vec(62, 201), module, PhasedLockedLoop::XOR_COMPARATOR_LIGHT));
  286. addChild(ModuleLightWidget::create<SmallLight<BlueLight>>(Vec(62, 217), module, PhasedLockedLoop::FLIP_FLOP_COMPARATOR_LIGHT));
  287. }
  288. } // namespace rack_plugin_FrozenWasteland
  289. using namespace rack_plugin_FrozenWasteland;
  290. RACK_PLUGIN_MODEL_INIT(FrozenWasteland, PhasedLockedLoop) {
  291. Model *modelPhasedLockedLoop = Model::create<PhasedLockedLoop, PhasedLockedLoopWidget>("Frozen Wasteland", "PhasedLockedLoop", "Phased Locked Loop", OSCILLATOR_TAG);
  292. return modelPhasedLockedLoop;
  293. }