text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ChannelBuffer.cpp
Created: 10 Oct 2017 8:53:51pm
Author: Ryan Challinor
==============================================================================
*/
#include "ChannelBuffer.h"
ChannelBuffer::ChannelBuffer(int bufferSize)
{
mNumChannels = kMaxNumChannels;
mOwnsBuffers = true;
Setup(bufferSize);
}
ChannelBuffer::ChannelBuffer(float* data, int bufferSize)
{
//intended as a temporary holder for passing raw data to methods that want a ChannelBuffer
mNumChannels = 1;
mOwnsBuffers = false;
mBuffers = new float*[1];
mBuffers[0] = data;
mBufferSize = bufferSize;
}
ChannelBuffer::~ChannelBuffer()
{
if (mOwnsBuffers)
{
for (int i = 0; i < mNumChannels; ++i)
delete[] mBuffers[i];
}
delete[] mBuffers;
}
void ChannelBuffer::Setup(int bufferSize)
{
mBuffers = new float*[mNumChannels];
mBufferSize = bufferSize;
for (int i = 0; i < mNumChannels; ++i)
mBuffers[i] = nullptr;
Clear();
}
float* ChannelBuffer::GetChannel(int channel)
{
if (channel >= mActiveChannels)
ofLog() << "error: requesting a higher channel index than we have active";
float* ret = mBuffers[MIN(channel, mActiveChannels - 1)];
if (ret == nullptr)
{
assert(mOwnsBuffers);
ret = new float[BufferSize()];
::Clear(ret, BufferSize());
mBuffers[MIN(channel, mActiveChannels - 1)] = ret;
}
return ret;
}
void ChannelBuffer::Clear() const
{
for (int i = 0; i < mNumChannels; ++i)
{
if (mBuffers[i] != nullptr)
::Clear(mBuffers[i], BufferSize());
}
}
void ChannelBuffer::SetMaxAllowedChannels(int channels)
{
float** newBuffers = new float*[channels];
for (int i = 0; i < channels; ++i)
{
if (i < mNumChannels)
newBuffers[i] = mBuffers[i];
else
newBuffers[i] = nullptr;
}
for (int i = channels; i < mNumChannels; ++i)
delete[] mBuffers[i];
delete[] mBuffers;
mBuffers = newBuffers;
mNumChannels = channels;
if (mActiveChannels > channels)
mActiveChannels = channels;
}
void ChannelBuffer::CopyFrom(ChannelBuffer* src, int length /*= -1*/, int startOffset /*= 0*/)
{
if (length == -1)
length = mBufferSize;
assert(length <= mBufferSize);
assert(length + startOffset <= src->mBufferSize);
mActiveChannels = src->mActiveChannels;
for (int i = 0; i < mActiveChannels; ++i)
{
if (src->mBuffers[i])
{
if (mBuffers[i] == nullptr)
{
assert(mOwnsBuffers);
mBuffers[i] = new float[mBufferSize];
::Clear(mBuffers[i], mBufferSize);
}
BufferCopy(mBuffers[i], src->mBuffers[i] + startOffset, length);
}
else
{
delete mBuffers[i];
mBuffers[i] = nullptr;
}
}
}
void ChannelBuffer::SetChannelPointer(float* data, int channel, bool deleteOldData)
{
if (deleteOldData)
delete[] mBuffers[channel];
mBuffers[channel] = data;
}
void ChannelBuffer::Resize(int bufferSize)
{
assert(mOwnsBuffers);
for (int i = 0; i < mNumChannels; ++i)
delete[] mBuffers[i];
delete[] mBuffers;
Setup(bufferSize);
}
namespace
{
const int kSaveStateRev = 1;
}
void ChannelBuffer::Save(FileStreamOut& out, int writeLength)
{
out << kSaveStateRev;
out << writeLength;
out << mActiveChannels;
for (int i = 0; i < mActiveChannels; ++i)
{
bool hasBuffer = mBuffers[i] != nullptr;
out << hasBuffer;
if (hasBuffer)
out.Write(mBuffers[i], writeLength);
}
}
void ChannelBuffer::Load(FileStreamIn& in, int& readLength, LoadMode loadMode)
{
int rev;
in >> rev;
LoadStateValidate(rev <= kSaveStateRev);
in >> readLength;
if (loadMode == LoadMode::kSetBufferSize)
Setup(readLength);
else if (loadMode == LoadMode::kRequireExactBufferSize)
assert(readLength == mBufferSize);
else
assert(readLength <= mBufferSize);
in >> mActiveChannels;
for (int i = 0; i < mActiveChannels; ++i)
{
bool hasBuffer = true;
if (rev >= 1)
in >> hasBuffer;
if (hasBuffer)
in.Read(GetChannel(i), readLength);
}
}
``` | /content/code_sandbox/Source/ChannelBuffer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,212 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// VelocityStepSequencer.h
// Bespoke
//
// Created by Ryan Challinor on 4/14/14.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Transport.h"
#include "Checkbox.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "Slider.h"
#include "MidiController.h"
#define VSS_MAX_STEPS 8
#define VSS_RANGE 127
class VelocityStepSequencer : public IDrawableModule, public ITimeListener, public NoteEffectBase, public IButtonListener, public IDropdownListener, public IIntSliderListener, public IFloatSliderListener, public MidiDeviceListener
{
public:
VelocityStepSequencer();
~VelocityStepSequencer();
static IDrawableModule* Create() { return new VelocityStepSequencer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetMidiController(std::string name);
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//ITimeListener
void OnTimeEvent(double time) override;
//MidiDeviceListener
void OnMidiNote(MidiNote& note) override;
void OnMidiControl(MidiControl& control) override;
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 160;
height = 160;
}
int mVels[VSS_MAX_STEPS]{};
IntSlider* mVelSliders[VSS_MAX_STEPS]{};
NoteInterval mInterval{ NoteInterval::kInterval_16n };
int mArpIndex{ -1 };
DropdownList* mIntervalSelector{ nullptr };
bool mResetOnDownbeat{ true };
Checkbox* mResetOnDownbeatCheckbox{ nullptr };
int mCurrentVelocity{ 80 };
int mLength{ VSS_MAX_STEPS };
IntSlider* mLengthSlider{ nullptr };
MidiController* mController{ nullptr };
TransportListenerInfo* mTransportListenerInfo{ nullptr };
};
``` | /content/code_sandbox/Source/VelocityStepSequencer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 766 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// FollowingSong.cpp
// Bespoke
//
// Created by Ryan Challinor on 10/15/14.
//
//
#include "FollowingSong.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "Transport.h"
#include "Scale.h"
#include "IAudioReceiver.h"
FollowingSong::FollowingSong()
{
}
void FollowingSong::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mMuteCheckbox = new Checkbox(this, "mute", 200, 4, &mMute);
}
FollowingSong::~FollowingSong()
{
}
void FollowingSong::LoadSample(const char* file)
{
mLoadingSong = true;
mLoadSongMutex.lock();
mSample.Read(file);
mLoadSongMutex.unlock();
mLoadingSong = false;
}
void FollowingSong::SetPlaybackInfo(bool play, int position, float speed, float volume)
{
mPlay = play;
mSample.SetRate(speed);
mSample.SetPlayPosition(position);
mVolume = volume;
}
void FollowingSong::Process(double time)
{
PROFILER(FollowingSong);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
ComputeSliders(0);
int bufferSize = target->GetBuffer()->BufferSize();
float* out = target->GetBuffer()->GetChannel(0);
assert(bufferSize == gBufferSize);
float volSq = mVolume * mVolume * .5f;
if (!mLoadingSong && mPlay)
{
mLoadSongMutex.lock();
gWorkChannelBuffer.SetNumActiveChannels(1);
if (mSample.ConsumeData(time, &gWorkChannelBuffer, bufferSize, true))
{
for (int i = 0; i < bufferSize; ++i)
{
float sample = gWorkChannelBuffer.GetChannel(0)[i] * volSq;
if (mMute)
sample = 0;
out[i] += sample;
GetVizBuffer()->Write(sample, 0);
}
}
else
{
GetVizBuffer()->WriteChunk(gZeroBuffer, bufferSize, 0);
}
mLoadSongMutex.unlock();
}
else
{
GetVizBuffer()->WriteChunk(gZeroBuffer, bufferSize, 0);
}
}
void FollowingSong::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mMuteCheckbox->Draw();
ofPushMatrix();
ofTranslate(10, 20);
DrawTextNormal(mSample.Name(), 100, -10);
DrawAudioBuffer(540, 100, mSample.Data(), 0, mSample.LengthInSamples() / mSample.GetSampleRateRatio(), mSample.GetPlayPosition());
ofPopMatrix();
ofPushStyle();
float w, h;
GetDimensions(w, h);
ofFill();
ofSetColor(255, 255, 255, 50);
float beatWidth = w / 4;
ofRect(int(TheTransport->GetMeasurePos(gTime) * 4) * beatWidth, 0, beatWidth, h);
ofPopStyle();
}
void FollowingSong::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void FollowingSong::ButtonClicked(ClickButton* button, double time)
{
}
void FollowingSong::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void FollowingSong::RadioButtonUpdated(RadioButton* list, int oldVal, double time)
{
}
void FollowingSong::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void FollowingSong::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void FollowingSong::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void FollowingSong::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/FollowingSong.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 964 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// FilterViz.h
// Bespoke
//
// Created by Ryan Challinor on 12/24/14.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "DropdownList.h"
#include "Slider.h"
#include "ClickButton.h"
#include "IAudioEffect.h"
#define FILTER_VIZ_BINS 1024
class FilterViz : public IDrawableModule, public IDropdownListener, public IFloatSliderListener, public IButtonListener
{
public:
FilterViz();
~FilterViz();
static IDrawableModule* Create() { return new FilterViz(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IDrawableModule
void Poll() override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
bool IsEnabled() const override { return true; }
private:
void GraphFilter();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 300;
height = 200;
}
float* mImpulseBuffer{ nullptr };
float* mFFTOutReal{ nullptr };
float* mFFTOutImag{ nullptr };
bool mNeedUpdate{ true };
std::vector<IAudioEffect*> mFilters;
};
``` | /content/code_sandbox/Source/FilterViz.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 460 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Ramper.h
// Bespoke
//
// Created by Ryan Challinor on 5/19/16.
//
//
#pragma once
#include "IDrawableModule.h"
#include "ClickButton.h"
#include "Checkbox.h"
#include "Transport.h"
#include "DropdownList.h"
#include "Slider.h"
#include "IPulseReceiver.h"
class PatchCableSource;
class Ramper : public IDrawableModule, public IDropdownListener, public IAudioPoller, public IButtonListener, public IFloatSliderListener, public IPulseReceiver
{
public:
Ramper();
~Ramper();
static IDrawableModule* Create() { return new Ramper(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return true; }
void CreateUIControls() override;
void Init() override;
//IDrawableModule
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IAudioPoller
void OnTransportAdvanced(float amount) override;
//IPulseReceiver
void OnPulse(double time, float velocity, int flags) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override {}
void ButtonClicked(ClickButton* button, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
void MouseReleased() override;
void Go(double time);
std::array<IUIControl*, 16> mUIControls{ nullptr };
NoteInterval mLength{ NoteInterval::kInterval_1n };
DropdownList* mLengthSelector{ nullptr };
PatchCableSource* mControlCable{ nullptr };
ClickButton* mTriggerButton{ nullptr };
FloatSlider* mTargetValueSlider{ nullptr };
float mTargetValue{ 0 };
float mStartMeasure{ 0 };
float mStartValue{ 0 };
bool mRamping{ false };
};
``` | /content/code_sandbox/Source/Ramper.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 667 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// JumpBlender.h
// modularSynth
//
// Created by Ryan Challinor on 11/1/13.
//
//
#pragma once
#include "Ramp.h"
#define JUMP_BLEND_SAMPLES 100
class JumpBlender
{
public:
JumpBlender();
void CaptureForJump(int pos, const float* sampleSource, int sourceLength, int samplesIn);
float Process(float sample, int samplesIn);
private:
bool mBlending{ false };
Ramp mRamp;
float mSamples[JUMP_BLEND_SAMPLES]{};
int mBlendSample{ 0 };
};
``` | /content/code_sandbox/Source/JumpBlender.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 225 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ChaosEngine.cpp
// modularSynth
//
// Created by Ryan Challinor on 11/18/13.
//
//
#include "ChaosEngine.h"
#include "ModularSynth.h"
#include "SynthGlobals.h"
#include "Scale.h"
#include "Transport.h"
#include "Profiler.h"
ChaosEngine* TheChaosEngine = nullptr;
ChaosEngine::ChaosEngine()
{
assert(TheChaosEngine == nullptr);
TheChaosEngine = this;
mChordProgression.push_back(ProgressionChord(0));
}
void ChaosEngine::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mChaosButton = new ClickButton(this, "CHAOS", 10, 110);
mTotalChaosCheckbox = new Checkbox(this, "total chaos", 10, 130, &mTotalChaos);
mSectionDropdown = new RadioButton(this, "section", 10, 450, &mSectionIdx, kRadioHorizontal);
mSongDropdown = new DropdownList(this, "song", 200, 4, &mSongIdx);
mReadSongsButton = new ClickButton(this, "read", 350, 4);
mPlayChordCheckbox = new Checkbox(this, "play chord", 400, 4, &mPlayChord);
mProgressCheckbox = new Checkbox(this, "progress", 500, 4, &mProgress);
mDegreeSlider = new IntSlider(this, "degree", 400, 24, 80, 15, &mDegree, 0, 6);
mRootNoteList = new DropdownList(this, "rootnote", 490, 24, &mInputChord.mRootPitch);
mChordTypeList = new DropdownList(this, "chord type", 530, 24, (int*)(&mInputChord.mType));
mAddChordButton = new ClickButton(this, "add", 550, 60);
mRemoveChordButton = new ClickButton(this, "remove", 550, 80);
mSetProgressionButton = new ClickButton(this, "set", 550, 110);
mChordProgressionSlider = new IntSlider(this, "progression", 400, 450, 100, 15, &mChordProgressionIdx, 0, 0);
mRandomProgressionButton = new ClickButton(this, "r progression", 510, 450);
mInversionSlider = new IntSlider(this, "inversion", 500, 40, 80, 15, &mInputChord.mInversion, 0, 2);
mHideBeatCheckbox = new Checkbox(this, "hide beat", 112, 4, &mHideBeat);
mRootNoteList->AddLabel("A", 9);
mRootNoteList->AddLabel("A#", 10);
mRootNoteList->AddLabel("B", 11);
mRootNoteList->AddLabel("C", 0);
mRootNoteList->AddLabel("C#", 1);
mRootNoteList->AddLabel("D", 2);
mRootNoteList->AddLabel("D#", 3);
mRootNoteList->AddLabel("E", 4);
mRootNoteList->AddLabel("F", 5);
mRootNoteList->AddLabel("F#", 6);
mRootNoteList->AddLabel("G", 7);
mRootNoteList->AddLabel("G#", 8);
mChordTypeList->AddLabel("maj ", kChord_Maj);
mChordTypeList->AddLabel("min ", kChord_Min);
mChordTypeList->AddLabel("aug ", kChord_Aug);
mChordTypeList->AddLabel("dim ", kChord_Dim);
}
ChaosEngine::~ChaosEngine()
{
assert(TheChaosEngine == this || TheChaosEngine == nullptr);
TheChaosEngine = nullptr;
}
void ChaosEngine::Init()
{
IDrawableModule::Init();
ReadSongs();
}
void ChaosEngine::Poll()
{
double chaosTimeLeft = mChaosArrivalTime - gTime;
if (chaosTimeLeft > 0)
{
if (chaosTimeLeft > ofRandom(-1000, 3000))
{
if (mTotalChaos)
TheTransport->SetTimeSignature(gRandom() % 8 + 2, (int)powf(2, gRandom() % 3 + 2));
TheScale->SetRoot(gRandom() % TheScale->GetPitchesPerOctave());
TheScale->SetRandomSeptatonicScale();
float bias = ofRandom(0, 1);
bias *= bias;
TheTransport->SetTempo(ofMap(bias, 0.0f, 1.0f, 55.0f, 170.0f));
}
}
}
void ChaosEngine::AudioUpdate()
{
PROFILER(ChaosEngine);
int measure = TheTransport->GetMeasure(gTime);
int beat = int(TheTransport->GetMeasurePos(gTime) * TheTransport->GetTimeSigTop());
if (beat != mLastAudioUpdateBeat && mBeatsLeftToChordChange != -1)
{
--mBeatsLeftToChordChange;
}
if (mProgress && (measure != mLastAudioUpdateMeasure || mBeatsLeftToChordChange == 0))
{
if (mRestarting)
{
mRestarting = false;
}
else
{
mChordProgressionIdx = (mChordProgressionIdx + 1) % mChordProgression.size();
UpdateProgression(beat);
}
}
mLastAudioUpdateMeasure = measure;
mLastAudioUpdateBeat = beat;
}
void ChaosEngine::UpdateProgression(int beat)
{
mProgressionMutex.lock();
if (mChordProgressionIdx < 0 || mChordProgressionIdx >= mChordProgression.size())
{
mProgressionMutex.unlock();
return;
}
if (mSongIdx != -1 || mChordProgression.size() > 1)
TheScale->SetScaleDegree(mChordProgression[mChordProgressionIdx].mDegree);
TheScale->SetAccidentals(mChordProgression[mChordProgressionIdx].mAccidentals);
if (mChordProgression[mChordProgressionIdx].mBeatLength != -1)
mBeatsLeftToChordChange = mChordProgression[mChordProgressionIdx].mBeatLength;
else
mBeatsLeftToChordChange = TheTransport->GetTimeSigTop() - beat;
mProgressionMutex.unlock();
mNoteOutput.Flush(NextBufferTime(false));
if (mPlayChord)
{
std::vector<int> pitches = GetCurrentChordPitches();
for (int i = 0; i < pitches.size(); ++i)
{
PlayNoteOutput(gTime, pitches[i], 127, -1);
}
}
}
std::vector<int> ChaosEngine::GetCurrentChordPitches()
{
ProgressionChord chord(0);
if (mChordProgressionIdx != -1)
chord = mChordProgression[mChordProgressionIdx];
int degree = TheScale->GetScaleDegree();
std::vector<int> tones;
tones.push_back(0 + degree);
tones.push_back(2 + degree);
tones.push_back(4 + degree);
std::vector<int> pitches;
for (int i = 0; i < tones.size(); ++i)
{
int tone = tones[i];
if (i >= tones.size() - chord.mInversion)
tone -= 7;
pitches.push_back(TheScale->GetPitchFromTone(tone) + 48);
}
return pitches;
}
void ChaosEngine::DrawModule()
{
ofSetColor(255, 255, 255);
ofPushStyle();
float fBeat = TheTransport->GetMeasurePos(gTime) * TheTransport->GetTimeSigTop() + 1;
int beat = int(fBeat);
if (!mHideBeat)
{
float w, h;
GetDimensions(w, h);
ofFill();
float beatLeft = 1 - (fBeat - beat);
ofSetColor(255, 255, 255, 100 * beatLeft);
float beatWidth = w / TheTransport->GetTimeSigTop();
ofRect((beat - 1) * beatWidth, 0, beatWidth, h);
ofPopStyle();
}
if (Minimized() || IsVisible() == false)
return;
mChaosButton->Draw();
mTotalChaosCheckbox->Draw();
mSectionDropdown->Draw();
mSongDropdown->Draw();
mReadSongsButton->Draw();
mPlayChordCheckbox->Draw();
mProgressCheckbox->Draw();
mDegreeSlider->Draw();
mRootNoteList->Draw();
mChordTypeList->Draw();
mAddChordButton->Draw();
mRemoveChordButton->Draw();
mSetProgressionButton->Draw();
mChordProgressionSlider->Draw();
mRandomProgressionButton->Draw();
mInversionSlider->Draw();
mHideBeatCheckbox->Draw();
DrawTextNormal(mInputChord.Name(true, true), 400, 51);
for (int i = 0; i < mInputChords.size(); ++i)
{
int degree;
std::vector<Accidental> accidentals;
TheScale->GetChordDegreeAndAccidentals(mInputChords[i], degree, accidentals);
std::string accidentalList;
for (int j = 0; j < accidentals.size(); ++j)
accidentalList += ofToString(accidentals[j].mPitch) + (accidentals[j].mDirection == 1 ? "#" : "b") + " ";
DrawTextNormal(mInputChords[i].Name(true, true), 400, 75 + i * 15);
}
if (!mHideBeat)
gFont.DrawString(ofToString(beat), 42, 10, 50);
gFont.DrawString(ofToString(TheTransport->GetTimeSigTop()) + "/" + ofToString(TheTransport->GetTimeSigBottom()), 40, 90, 50);
gFont.DrawString(ofToString(TheTransport->GetTempo(), 0) + "bpm", 420, 230, 50);
gFont.DrawString(NoteName(TheScale->ScaleRoot()) + " " + TheScale->GetType(), 40, 10, 100);
DrawKeyboard(10, 150);
DrawGuitar(10, 285);
ofPushStyle();
ofFill();
for (int i = 0; i < mChordProgression.size(); ++i)
{
if (i == mChordProgressionIdx)
ofSetColor(255, 255, 255);
else
ofSetColor(150, 150, 150);
int x = 10 + 290 * (i / 6);
int y = 500 + 35 * (i % 6);
ScalePitches scale;
scale.SetRoot(TheScale->ScaleRoot());
scale.SetScaleType(TheScale->GetType());
scale.SetAccidentals(mChordProgression[i].mAccidentals);
Chord displayChord;
displayChord.SetFromDegreeAndScale(mChordProgression[i].mDegree, scale);
displayChord.mInversion = mChordProgression[i].mInversion;
gFont.DrawString(displayChord.Name(true, false, &scale), 46, x, y);
std::string accidentalList;
for (int j = 0; j < mChordProgression[i].mAccidentals.size(); ++j)
accidentalList += ofToString(mChordProgression[i].mAccidentals[j].mPitch) + (mChordProgression[i].mAccidentals[j].mDirection == 1 ? "#" : "b") + "\n";
DrawTextNormal(accidentalList, x + 180, y - 18);
int numBeats = mChordProgression[i].mBeatLength;
if (numBeats == -1)
numBeats = TheTransport->GetTimeSigTop();
for (int j = 0; j < numBeats; ++j)
{
if (i < mChordProgressionIdx ||
(i == mChordProgressionIdx && j <= numBeats - mBeatsLeftToChordChange))
ofSetColor(255, 255, 255);
else
ofSetColor(150, 150, 150);
ofRect(x + 210 + j * 15, y - 25, 13, 25);
}
}
ofPopStyle();
}
void ChaosEngine::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (right)
return;
if (y > 470)
{
y -= 470;
x -= 10;
int xSlot = x / 290;
int ySlot = y / 35;
int idx = ySlot + xSlot * 6;
if (idx < mChordProgression.size())
{
if (IsKeyHeld('x') && mChordProgression.size() > 1)
{
mProgressionMutex.lock();
mChordProgression.erase(mChordProgression.begin() + idx);
mChordProgressionSlider->SetExtents(0, (int)mChordProgression.size() - 1);
mProgressionMutex.unlock();
}
else
{
mChordProgressionIdx = idx;
UpdateProgression(0);
}
}
}
}
ofRectangle ChaosEngine::GetKeyboardKeyRect(int pitch, bool& isBlackKey)
{
const float kbWidth = 200;
const float kbHeight = 100;
int offset = pitch / TheScale->GetPitchesPerOctave() * (kbWidth - kbWidth / 8);
pitch %= 12;
if ((pitch <= 4 && pitch % 2 == 0) || (pitch >= 5 && pitch % 2 == 1)) //white key
{
int whiteKey = (pitch + 1) / 2;
isBlackKey = false;
return ofRectangle(offset + whiteKey * kbWidth / 8, 0, kbWidth / 8, kbHeight);
}
else //black key
{
int blackKey = pitch / 2;
isBlackKey = true;
return ofRectangle(offset + blackKey * kbWidth / 8 + kbWidth / 16 + kbWidth / 8 * .1f, 0, kbWidth / 8 * .8f, kbHeight / 2);
}
}
void ChaosEngine::DrawKeyboard(float x, float y)
{
ofPushStyle();
ofPushMatrix();
ofTranslate(x, y);
const int kNumKeys = 41;
//white keys
for (int pass = 0; pass < 2; ++pass)
{
for (int i = 0; i < kNumKeys; ++i)
{
bool isBlackKey;
ofRectangle key = GetKeyboardKeyRect(i, isBlackKey);
if ((pass == 0 && !isBlackKey) || (pass == 1 && isBlackKey))
{
SetPitchColor(i + 12);
ofFill();
ofRect(key);
ofSetColor(0, 0, 0);
ofNoFill();
ofRect(key);
}
}
}
ofPushStyle();
ofFill();
ofSetColor(255, 255, 255);
ofSetLineWidth(2);
std::vector<int> chord = GetCurrentChordPitches();
sort(chord.begin(), chord.end());
ofVec2f lastNoteConnector;
for (int j = 0; j < chord.size(); ++j)
{
bool isBlackKey;
int pitch = chord[j] - 36;
if (pitch < kNumKeys)
{
ofRectangle key = GetKeyboardKeyRect(pitch, isBlackKey);
key.height /= 3;
key.y += key.height * 2;
ofRect(key);
if (IsChordRoot(pitch))
{
ofPushStyle();
ofSetColor(0, 0, 0);
ofCircle(key.x + key.width / 2, key.y + key.height / 2, 5);
ofPopStyle();
}
if (j > 0)
ofLine(lastNoteConnector.x, lastNoteConnector.y, key.x, key.y + key.height / 2);
lastNoteConnector.set(key.x + key.width, key.y + key.height / 2);
}
}
ofPopStyle();
ofPopMatrix();
ofPopStyle();
}
void ChaosEngine::DrawGuitar(float x, float y)
{
ofPushStyle();
ofPushMatrix();
ofTranslate(x, y);
const float gtWidth = 570;
const float gtHeight = 150;
const int numStrings = 6;
const int numFrets = 13;
const float fretWidth = gtWidth / numFrets;
ofSetCircleResolution(10);
ofFill();
ofSetColor(0, 0, 0);
ofRect(fretWidth, 0, gtWidth - fretWidth, gtHeight);
ofSetLineWidth(3);
for (int fret = 1; fret < numFrets; ++fret)
{
float fretX = fret * fretWidth;
ofSetColor(200, 200, 200);
ofLine(fretX, 0, fretX, gtHeight);
if (fret == 3 || fret == 5 || fret == 7 || fret == 9 || fret == 15 || fret == 17 || fret == 19 || fret == 21)
{
ofSetColor(255, 255, 255);
ofCircle(fretX + fretWidth / 2, gtHeight / 2, 5);
}
if (fret == 12)
{
ofSetColor(255, 255, 255);
ofCircle(fretX + fretWidth / 2, gtHeight * .3f, 5);
ofCircle(fretX + fretWidth / 2, gtHeight * .7f, 5);
}
}
ofSetLineWidth(1);
for (int string = 0; string < numStrings; ++string)
{
float stringY = gtHeight - string * gtHeight / (numStrings - 1);
ofSetColor(255, 255, 255);
ofLine(0, stringY, gtWidth, stringY);
}
ofSetLineWidth(2);
for (int string = 0; string < numStrings; ++string)
{
float stringY = gtHeight - string * gtHeight / (numStrings - 1);
for (int fret = 0; fret < numFrets; ++fret)
{
float fretX = fret * fretWidth;
int pitch = 16 + fret + string * 5; //16 to get to E-1
if (string >= 5)
pitch -= 1;
if (TheScale->IsInScale(pitch))
{
SetPitchColor(pitch);
if (fret == 0)
ofNoFill();
else
ofFill();
ofCircle(fretX + fretWidth / 2, stringY, 9);
if (IsChordRoot(pitch))
{
ofNoFill();
ofSetColor(255, 255, 255);
ofCircle(fretX + fretWidth / 2, stringY, 10);
}
}
}
}
ofPopMatrix();
ofPopStyle();
}
void ChaosEngine::SetPitchColor(int pitch)
{
if (TheScale->IsRoot(pitch))
{
ofSetColor(0, 255, 0);
}
else if (TheScale->IsInPentatonic(pitch))
{
ofSetColor(255, 128, 0);
}
else if (TheScale->IsInScale(pitch))
{
ofSetColor(180, 80, 0);
}
else
{
ofSetColor(50, 50, 50);
}
}
bool ChaosEngine::IsChordRoot(int pitch)
{
if (mChordProgression.size() <= 1) //no chords
return false;
return TheScale->IsInScale(pitch) &&
(TheScale->GetToneFromPitch(pitch) % 7 == (TheScale->GetScaleDegree() + 7) % 7);
}
void ChaosEngine::ReadSongs()
{
mSongDropdown->Clear();
mSongDropdown->AddLabel("none", -1);
ofxJSONElement root;
bool loaded = root.open(ofToDataPath("songs.json"));
assert(loaded);
const ofxJSONElement& songs = root["songs"];
mSongs.resize(songs.size());
//TODO(Ryan) this is broken. but is it worth reviving?
/*for (int i=0; i<songs.size(); ++i)
{
const ofxJSONElement& song = songs[i];
mSongs[i].mName = song["name"].asString();
mSongs[i].mTempo = song["tempo"].asDouble();
mSongs[i].mTimeSigTop = song["timesig"][0u].asInt();
mSongs[i].mTimeSigBottom = song["timesig"][1u].asInt();
std::string scaleRootName = song["scaleroot"].asString();
int j;
for (j=0; j<12; ++j)
{
if (scaleRootName == NoteName(j))
{
mSongs[i].mScaleRoot = j;
break;
}
}
assert(j != 12);
mSongs[i].mScaleType = song["scaletype"].asString();
ScalePitches scale;
scale.SetRoot(mSongs[i].mScaleRoot);
scale.SetScaleType(mSongs[i].mScaleType);
const ofxJSONElement& sections = song["sections"];
mSongs[i].mSections.resize(sections.size());
for (j=0; j<sections.size(); ++j)
{
const ofxJSONElement& section = sections[j];
mSongs[i].mSections[j].mName = section["name"].asString();
mSongs[i].mSections[j].mChords.clear();
for (int k=0; k<section["chords"].size(); ++k)
{
const ofxJSONElement& chordInfo = section["chords"][k];
mSongs[i].mSections[j].mChords.push_back(ProgressionChord(chordInfo,scale));
}
}
}*/
for (int i = 0; i < mSongs.size(); ++i)
mSongDropdown->AddLabel(mSongs[i].mName.c_str(), i);
}
void ChaosEngine::GenerateRandomProgression()
{
mProgressionMutex.lock();
std::vector<Accidental> none;
TheScale->SetAccidentals(none);
mChordProgression.clear();
int length = (gRandom() % 3) + 3;
mChordProgression.push_back(ProgressionChord(0));
int beatsPerBar = TheTransport->GetTimeSigTop();
int beatsLeft = beatsPerBar;
for (int i = 1; i < length;)
{
int degree = (gRandom() % 6) + 1;
Chord chord;
int rootPitch = TheScale->GetPitchFromTone(degree);
if (ofRandom(1) < .5f && (degree == 3 || degree == 4)) //chance we do a non-diatonic
chord = Chord(rootPitch, (gRandom() % 2) ? kChord_Maj : kChord_Min);
else
chord.SetFromDegreeAndScale(degree, TheScale->GetScalePitches());
std::vector<Accidental> accidentals;
TheScale->GetChordDegreeAndAccidentals(chord, degree, accidentals);
int beats = beatsLeft;
if (ofRandom(1) < .2f) //small chance we do less than a bar
beats = (gRandom() % beatsLeft) + 1;
ProgressionChord progressionChord(degree, accidentals, beats);
const ProgressionChord& lastChord = mChordProgression[mChordProgression.size() - 1];
if (progressionChord.SameChord(lastChord)) //two in a row
continue;
progressionChord.mInversion = gRandom() % 3;
mChordProgression.push_back(progressionChord);
beatsLeft -= beats;
if (beatsLeft == 0)
{
beatsLeft = beatsPerBar;
++i;
}
}
mChordProgressionSlider->SetExtents(0, (int)mChordProgression.size() - 1);
mProgressionMutex.unlock();
}
ChaosEngine::ProgressionChord::ProgressionChord(const ofxJSONElement& chordInfo, ScalePitches scale)
{
if (chordInfo.isArray())
{
if (chordInfo[0u].isInt())
{
mDegree = chordInfo[0u].asInt();
mBeatLength = chordInfo[1u].asInt();
}
else
{
scale.GetChordDegreeAndAccidentals(chordInfo[0u].asString(), mDegree, mAccidentals);
mBeatLength = chordInfo[1u].asInt();
if (chordInfo[2u].isNull())
mInversion = 0;
else
mInversion = chordInfo[2u].asInt();
}
}
else
{
if (chordInfo.isInt())
mDegree = chordInfo.asInt();
else
scale.GetChordDegreeAndAccidentals(chordInfo.asString(), mDegree, mAccidentals);
mBeatLength = -1;
mInversion = 0;
}
}
void ChaosEngine::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mSongDropdown)
{
mProgressionMutex.lock();
if (mSongIdx == -1)
{
mChordProgression.clear();
mChordProgression.push_back(0);
mSectionDropdown->Clear();
}
else
{
const Song& song = mSongs[mSongIdx];
TheTransport->SetTimeSignature(song.mTimeSigTop, song.mTimeSigBottom);
TheTransport->SetTempo(song.mTempo);
TheScale->SetRoot(song.mScaleRoot);
TheScale->SetScaleType(song.mScaleType);
mChordProgression = song.mSections[0].mChords;
mSectionDropdown->Clear();
for (int i = 0; i < song.mSections.size(); ++i)
{
mSectionDropdown->AddLabel(song.mSections[i].mName.c_str(), i);
}
mChordProgressionIdx = -1;
mBeatsLeftToChordChange = -1;
mSectionIdx = 0;
}
mChordProgressionSlider->SetExtents(0, (int)mChordProgression.size() - 1);
mProgressionMutex.unlock();
}
if (list == mRootNoteList || list == mChordTypeList)
{
mDegree = TheScale->GetToneFromPitch(mInputChord.mRootPitch);
}
}
void ChaosEngine::ButtonClicked(ClickButton* button, double time)
{
if (button == mChaosButton)
{
mChaosArrivalTime = time + ofRandom(2000, 3000);
}
if (button == mReadSongsButton)
{
ReadSongs();
}
if (button == mAddChordButton)
{
mInputChords.push_back(mInputChord);
}
if (button == mRemoveChordButton)
{
if (mInputChords.size())
mInputChords.pop_back();
}
if (button == mSetProgressionButton)
{
mProgressionMutex.lock();
mChordProgression.clear();
for (int i = 0; i < mInputChords.size(); ++i)
{
int degree;
std::vector<Accidental> accidentals;
TheScale->GetChordDegreeAndAccidentals(mInputChords[i], degree, accidentals);
ProgressionChord chord = ProgressionChord(degree, accidentals);
chord.mInversion = mInputChords[i].mInversion;
mChordProgression.push_back(chord);
}
mProgressionMutex.unlock();
mChordProgressionSlider->SetExtents(0, (int)mChordProgression.size() - 1);
}
if (button == mRandomProgressionButton)
{
GenerateRandomProgression();
}
}
void ChaosEngine::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void ChaosEngine::RadioButtonUpdated(RadioButton* list, int oldVal, double time)
{
if (list == mSectionDropdown)
{
if (mSongIdx == -1 || mSectionIdx >= mSongs[mSongIdx].mSections.size())
return;
mProgressionMutex.lock();
mChordProgression = mSongs[mSongIdx].mSections[mSectionIdx].mChords;
mChordProgressionIdx = -1;
mProgressionMutex.unlock();
mChordProgressionSlider->SetExtents(0, (int)mChordProgression.size() - 1);
}
}
void ChaosEngine::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mDegreeSlider)
{
mInputChord.SetFromDegreeAndScale(mDegree, TheScale->GetScalePitches());
}
if (slider == mChordProgressionSlider)
{
mChordProgressionIdx = ofClamp(mChordProgressionIdx, 0, mChordProgression.size() - 1);
if (mProgress)
mChordProgressionIdx -= 1; //make us progress to this one on the next downbeat
else
UpdateProgression(0); //or go immediately there
}
}
void ChaosEngine::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void ChaosEngine::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/ChaosEngine.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 6,950 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Neighborhooder.h
// modularSynth
//
// Created by Ryan Challinor on 3/10/13.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
class Neighborhooder : public NoteEffectBase, public IDrawableModule, public IIntSliderListener
{
public:
Neighborhooder();
static IDrawableModule* Create() { return new Neighborhooder(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 120;
height = 38;
}
int mMinPitch{ 55 };
int mPitchRange{ 16 };
IntSlider* mMinSlider{ nullptr };
IntSlider* mRangeSlider{ nullptr };
};
``` | /content/code_sandbox/Source/Neighborhooder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 453 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
UnstablePressure.cpp
Created: 2 Mar 2021 7:49:00pm
Author: Ryan Challinor
==============================================================================
*/
#include "UnstablePressure.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
UnstablePressure::UnstablePressure()
{
for (int voice = 0; voice < kNumVoices; ++voice)
mModulation.GetPressure(voice)->CreateBuffer();
}
void UnstablePressure::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
UnstablePressure::~UnstablePressure()
{
TheTransport->RemoveAudioPoller(this);
}
void UnstablePressure::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK(3, 40, 140);
FLOATSLIDER(mAmountSlider, "amount", &mPerlin.mPerlinAmount, 0, 1);
FLOATSLIDER(mWarbleSlider, "warble", &mPerlin.mPerlinWarble, 0, 1);
FLOATSLIDER(mNoiseSlider, "noise", &mPerlin.mPerlinNoise, 0, 1);
ENDUIBLOCK(mWidth, mHeight);
mWarbleSlider->SetMode(FloatSlider::kSquare);
mNoiseSlider->SetMode(FloatSlider::kSquare);
}
void UnstablePressure::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
ofPushStyle();
ofRectangle rect(3, 3, mWidth - 6, 34);
const int kGridSize = 30;
ofFill();
for (int col = 0; col < kGridSize; ++col)
{
float x = rect.x + col * (rect.width / kGridSize);
float y = rect.y;
float val = mPerlin.GetValue(gTime, x / rect.width * 10, 0) * ofClamp(mPerlin.mPerlinAmount * 5, 0, 1);
ofSetColor(val * 255, 0, val * 255);
ofRect(x, y, (rect.width / kGridSize) + .5f, rect.height + .5f, 0);
}
ofNoFill();
ofSetColor(0, 255, 0, 90);
for (int voice = 0; voice < kNumVoices; ++voice)
{
if (mIsVoiceUsed[voice])
{
ofBeginShape();
for (int i = 0; i < gBufferSize; ++i)
{
float sample = ofClamp(mModulation.GetPressure(voice)->GetBufferValue(i), -1, 1);
ofVertex((i * rect.width) / gBufferSize + rect.x, rect.y + (1 - sample) * rect.height);
}
ofEndShape();
}
}
ofPopStyle();
mAmountSlider->Draw();
mWarbleSlider->Draw();
mNoiseSlider->Draw();
}
void UnstablePressure::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled)
{
if (voiceIdx == -1)
{
if (velocity > 0)
{
bool foundVoice = false;
for (size_t i = 0; i < mIsVoiceUsed.size(); ++i)
{
int voiceToCheck = (i + mVoiceRoundRobin) % kNumVoices;
if (mIsVoiceUsed[voiceToCheck] == false)
{
voiceIdx = voiceToCheck;
mVoiceRoundRobin = (mVoiceRoundRobin + 1) % kNumVoices;
foundVoice = true;
break;
}
}
if (!foundVoice)
{
voiceIdx = mVoiceRoundRobin;
mVoiceRoundRobin = (mVoiceRoundRobin + 1) % kNumVoices;
}
}
else
{
voiceIdx = mPitchToVoice[pitch];
}
}
if (voiceIdx < 0 || voiceIdx >= kNumVoices)
voiceIdx = 0;
mIsVoiceUsed[voiceIdx] = velocity > 0;
mPitchToVoice[pitch] = (velocity > 0) ? voiceIdx : -1;
mModulation.GetPressure(voiceIdx)->AppendTo(modulation.pressure);
modulation.pressure = mModulation.GetPressure(voiceIdx);
}
FillModulationBuffer(time, voiceIdx);
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void UnstablePressure::OnTransportAdvanced(float amount)
{
ComputeSliders(0);
for (int voice = 0; voice < kNumVoices; ++voice)
{
if (mIsVoiceUsed[voice])
FillModulationBuffer(gTime, voice);
}
}
void UnstablePressure::FillModulationBuffer(double time, int voiceIdx)
{
for (int i = 0; i < gBufferSize; ++i)
gWorkBuffer[i] = ofMap(mPerlin.GetValue(time + i * gInvSampleRateMs, (time + i * gInvSampleRateMs) / 1000, voiceIdx), 0, 1, 0, mPerlin.mPerlinAmount);
mModulation.GetPressure(voiceIdx)->FillBuffer(gWorkBuffer);
}
void UnstablePressure::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void UnstablePressure::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
if (!mEnabled)
{
for (size_t i = 0; i < mIsVoiceUsed.size(); ++i)
mIsVoiceUsed[i] = false;
}
}
}
void UnstablePressure::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void UnstablePressure::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/UnstablePressure.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,447 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// MidiController.h
// modularSynth
//
// Created by Ryan Challinor on 1/14/13.
//
//
#pragma once
#include <iostream>
#include "MidiDevice.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "ClickButton.h"
#include "DropdownList.h"
#include "RadioButton.h"
#include "ofxJSONElement.h"
#include "Transport.h"
#include "TextEntry.h"
#include "ModulationChain.h"
#include "INoteSource.h"
#define MIDI_PITCH_BEND_CONTROL_NUM 999
#define MIDI_PAGE_WIDTH 1000
#define MAX_MIDI_PAGES 10
enum MidiMessageType
{
kMidiMessage_Note,
kMidiMessage_Control,
kMidiMessage_Program,
kMidiMessage_PitchBend
};
enum ControlType
{
kControlType_Slider,
kControlType_SetValue,
kControlType_Toggle,
kControlType_Direct,
kControlType_SetValueOnRelease,
kControlType_Default
};
enum SpecialControlBinding
{
kSpecialBinding_None,
kSpecialBinding_Hover,
kSpecialBinding_HotBind0,
kSpecialBinding_HotBind1,
kSpecialBinding_HotBind2,
kSpecialBinding_HotBind3,
kSpecialBinding_HotBind4,
kSpecialBinding_HotBind5,
kSpecialBinding_HotBind6,
kSpecialBinding_HotBind7,
kSpecialBinding_HotBind8,
kSpecialBinding_HotBind9
};
enum class ChannelFilter
{
kAny,
k1,
k2,
k3,
k4,
k5,
k6,
k7,
k8,
k9,
k10,
k11,
k12,
k13,
k14,
k15,
k16
};
namespace Json
{
class Value;
}
class Monome;
class MidiController;
class GridControlTarget;
class INonstandardController;
class ScriptModule;
struct UIControlConnection
{
UIControlConnection(MidiController* owner)
: mUIOwner(owner)
{}
~UIControlConnection();
IUIControl* GetUIControl()
{
if (mSpecialBinding == kSpecialBinding_None)
return mUIControl;
else if (mSpecialBinding == kSpecialBinding_Hover)
return gHoveredUIControl;
int index = mSpecialBinding - kSpecialBinding_HotBind0;
assert(index >= 0 && index <= 9);
return gHotBindUIControl[index];
}
UIControlConnection* MakeCopy()
{
UIControlConnection* connection = new UIControlConnection(mUIOwner);
connection->mMessageType = mMessageType;
connection->mControl = mControl;
connection->SetUIControl(mUIControl);
connection->mType = mType;
connection->mValue = mValue;
connection->mLastControlValue = mLastControlValue;
connection->mMidiOnValue = mMidiOnValue;
connection->mMidiOffValue = mMidiOffValue;
connection->mScaleOutput = mScaleOutput;
connection->mBlink = mBlink;
connection->mIncrementAmount = mIncrementAmount;
connection->mTwoWay = mTwoWay;
connection->mFeedbackControl = mFeedbackControl;
connection->mSpecialBinding = mSpecialBinding;
connection->mChannel = mChannel;
connection->mPage = mPage;
connection->mPageless = mPageless;
connection->m14BitMode = m14BitMode;
return connection;
}
void SetNext(UIControlConnection* next);
void SetUIControl(IUIControl* control);
void SetUIControl(std::string path);
void CreateUIControls(int index);
void Poll();
void PreDraw();
void DrawList(int index);
void DrawLayout();
void SetShowing(bool enabled);
bool PostRepatch(PatchCableSource* cableSource, bool fromUserClick);
int mControl{ -1 };
IUIControl* mUIControl{ nullptr };
ControlType mType{ ControlType::kControlType_Slider };
MidiMessageType mMessageType{ MidiMessageType::kMidiMessage_Control };
float mValue{ 0 };
int mMidiOnValue{ 127 };
int mMidiOffValue{ 0 };
bool mScaleOutput{ false };
bool mBlink{ false };
float mIncrementAmount{ 0 };
bool mTwoWay{ true };
int mFeedbackControl{ -1 };
SpecialControlBinding mSpecialBinding{ SpecialControlBinding::kSpecialBinding_None };
int mChannel{ -1 };
int mPage{ 0 };
bool mPageless{ false };
std::string mShouldRetryForUIControlAt{ "" };
bool m14BitMode{ false };
static bool sDrawCables;
//state
int mLastControlValue{ -1 };
std::string mLastDisplayValue{ "" };
double mLastActivityTime{ -9999 };
MidiController* mUIOwner{ nullptr };
//editor controls
DropdownList* mMessageTypeDropdown{ nullptr };
TextEntry* mControlEntry{ nullptr };
DropdownList* mChannelDropdown{ nullptr };
TextEntry* mUIControlPathEntry{ nullptr };
char mUIControlPathInput[MAX_TEXTENTRY_LENGTH]{};
DropdownList* mControlTypeDropdown{ nullptr };
TextEntry* mValueEntry{ nullptr };
TextEntry* mMidiOffEntry{ nullptr };
TextEntry* mMidiOnEntry{ nullptr };
Checkbox* mScaleOutputCheckbox{ nullptr };
Checkbox* mBlinkCheckbox{ nullptr };
Checkbox* m14BitModeCheckbox{ nullptr };
TextEntry* mIncrementalEntry{ nullptr };
Checkbox* mTwoWayCheckbox{ nullptr };
DropdownList* mFeedbackDropdown{ nullptr };
Checkbox* mPagelessCheckbox{ nullptr };
ClickButton* mRemoveButton{ nullptr };
ClickButton* mCopyButton{ nullptr };
std::list<IUIControl*> mEditorControls;
};
enum ControlDrawType
{
kDrawType_Button,
kDrawType_Knob,
kDrawType_Slider
};
struct ControlLayoutElement
{
ControlLayoutElement()
{}
void Setup(MidiController* owner, MidiMessageType type, int control, ControlDrawType drawType, float incrementAmount, bool is14Bit, int offVal, int onVal, bool scaleOutput, ControlType connectionType, float x, float y, float w, float h);
bool mActive{ false };
MidiMessageType mType{ MidiMessageType::kMidiMessage_Control };
int mControl{ 0 };
ofVec2f mPosition;
ofVec2f mDimensions;
ControlDrawType mDrawType{ ControlDrawType::kDrawType_Slider };
float mIncrementAmount{ 0 };
int mOffVal{ 0 };
int mOnVal{ 127 };
bool mScaleOutput{ true };
bool m14BitMode{ false };
ControlType mConnectionType{ ControlType::kControlType_Slider };
PatchCableSource* mControlCable{ nullptr };
float mLastValue{ 0 };
float mLastActivityTime{ -9999 };
};
struct GridLayout
{
GridLayout()
{}
int mRows{ 1 };
int mCols{ 8 };
ofVec2f mPosition;
ofVec2f mDimensions;
MidiMessageType mType{ kMidiMessage_Note };
std::vector<int> mControls;
std::vector<int> mColors;
PatchCableSource* mGridCable{ nullptr };
GridControlTarget* mGridControlTarget[MAX_MIDI_PAGES]{};
};
#define NUM_LAYOUT_CONTROLS 128 + 128 + 128 + 1 + 1 //128 notes, 128 ccs, 128 program change, 1 pitch bend, 1 dummy
class MidiController : public MidiDeviceListener, public IDrawableModule, public IButtonListener, public IDropdownListener, public IRadioButtonListener, public IAudioPoller, public ITextEntryListener, public INoteSource, public IKeyboardFocusListener
{
public:
MidiController();
~MidiController();
static IDrawableModule* Create() { return new MidiController(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void AddControlConnection(const ofxJSONElement& connection);
UIControlConnection* AddControlConnection(MidiMessageType messageType, int control, int channel, IUIControl* uicontrol, int page = -1);
void UseNegativeEdge(bool use) { mUseNegativeEdge = use; }
void AddListener(MidiDeviceListener* listener, int page);
void RemoveListener(MidiDeviceListener* listener);
void AddScriptListener(ScriptModule* script);
int GetPage() const { return mControllerPage; }
bool IsInputConnected(bool immediate);
std::string GetDeviceIn() const { return mDeviceIn; }
std::string GetDeviceOut() const { return mDeviceOut; }
UIControlConnection* GetConnectionForControl(MidiMessageType messageType, int control);
UIControlConnection* GetConnectionForCableSource(const PatchCableSource* source);
void ResyncControllerState();
void SetVelocityMult(float mult) { mVelocityMult = mult; }
void SetUseChannelAsVoice(bool use) { mUseChannelAsVoice = use; }
void SetNoteOffset(int offset) { mNoteOffset = offset; }
void SetPitchBendRange(float range) { mPitchBendRange = range; }
void SendNote(int page, int pitch, int velocity, bool forceNoteOn = false, int channel = -1);
void SendCC(int page, int ctl, int value, int channel = -1);
void SendProgramChange(int page, int program, int channel = -1);
void SendPitchBend(int page, int bend, int channel = -1);
void SendData(int page, unsigned char a, unsigned char b, unsigned char c);
void SendSysEx(int page, std::string data);
INonstandardController* GetNonstandardController() { return mNonstandardController; }
static std::vector<std::string> GetAvailableInputDevices();
static std::vector<std::string> GetAvailableOutputDevices();
//IDrawableModule
void Poll() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void Exit() override;
void KeyReleased(int key) override;
//MidiDeviceListener
void OnMidiNote(MidiNote& note) override;
void OnMidiControl(MidiControl& control) override;
void OnMidiPressure(MidiPressure& pressure) override;
void OnMidiProgramChange(MidiProgramChange& program) override;
void OnMidiPitchBend(MidiPitchBend& pitchBend) override;
void OnMidi(const juce::MidiMessage& message) override;
void OnTransportAdvanced(float amount) override;
//IKeyboardFocusListener
void OnKeyPressed(int key, bool isRepeat) override;
bool ShouldConsumeKey(int key) override;
bool CanTakeFocus() override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void DropdownClicked(DropdownList* list) override;
void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override;
void TextEntryActivated(TextEntry* entry) override;
void TextEntryComplete(TextEntry* entry) override;
void PreRepatch(PatchCableSource* cableSource) override;
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
void OnCableGrabbed(PatchCableSource* cableSource) override;
void SendControllerInfoString(int control, int type, std::string str);
bool ShouldSendControllerInfoStrings() const { return mShouldSendControllerInfoStrings; }
ControlLayoutElement& GetLayoutControl(int control, MidiMessageType type);
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
virtual void SaveLayout(ofxJSONElement& moduleInfo) override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
static std::string GetDefaultTooltip(MidiMessageType type, int control);
static double sLastConnectedActivityTime;
static IUIControl* sLastActivityUIControl;
static double sLastBoundControlTime;
static IUIControl* sLastBoundUIControl;
bool IsEnabled() const override { return mEnabled; }
private:
enum MappingDisplayMode
{
kHide,
kList,
kLayout
};
//IDrawableModule
void DrawModule() override;
void DrawModuleUnclipped() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
void ConnectDevice();
void MidiReceived(MidiMessageType messageType, int control, float scaledValue, int rawValue, int channel);
void RemoveConnection(int control, MidiMessageType messageType, int channel, int page);
int GetNumConnectionsOnPage(int page);
void SetEntirePageToZero(int page);
void BuildControllerList();
void HighlightPageControls(int page);
void OnDeviceChanged();
int GetLayoutControlIndexForCable(PatchCableSource* cable) const;
int GetLayoutControlIndexForMidi(MidiMessageType type, int control) const;
std::string GetLayoutTooltip(int controlIndex);
void UpdateControllerIndex();
void LoadControllerLayout(std::string filename);
bool JustBoundControl() const { return gTime - sLastBoundControlTime < 500; }
const std::string kDefaultLayout = "default";
float mVelocityMult{ 1 };
bool mUseChannelAsVoice{ false };
float mCurrentPitchBend{ 0 };
int mNoteOffset{ 0 };
float mPitchBendRange{ 2 };
int mModwheelCC{ 1 }; // or 74 in Multidimensional Polyphonic Expression (MPE) spec
float mModWheelOffset{ 0 };
float mPressureOffset{ 0 };
Modulations mModulation{ true };
std::string mDeviceIn;
std::string mDeviceOut;
int mOutChannel{ 1 };
MidiDevice mDevice;
double mInitialConnectionTime{ 0 };
ofxJSONElement mConnectionsJson;
std::list<UIControlConnection*> mConnections;
bool mSendCCOutput{ false };
bool mUseNegativeEdge{ false }; // for midi toggle, accept on or off as a button press
bool mSlidersDefaultToIncremental{ false };
bool mBindMode{ false };
Checkbox* mBindCheckbox{ nullptr };
bool mTwoWay{ true };
bool mSendTwoWayOnChange{ true };
bool mResendFeedbackOnRelease{ false };
ClickButton* mAddConnectionButton{ nullptr };
std::list<MidiNote> mQueuedNotes;
std::list<MidiControl> mQueuedControls;
std::list<MidiProgramChange> mQueuedProgramChanges;
std::list<MidiPitchBend> mQueuedPitchBends;
DropdownList* mControllerList{ nullptr };
Checkbox* mDrawCablesCheckbox{ nullptr };
MappingDisplayMode mMappingDisplayMode{ MappingDisplayMode::kHide };
RadioButton* mMappingDisplayModeSelector{ nullptr };
int mLayoutFileIndex{ 0 };
DropdownList* mLayoutFileDropdown{ nullptr };
int mOscInPort{ 8000 };
TextEntry* mOscInPortEntry{ nullptr };
int mMonomeDeviceIndex{ -1 };
DropdownList* mMonomeDeviceDropdown{ nullptr };
bool mShouldSendControllerInfoStrings{ false };
int mControllerIndex{ -1 };
double mLastActivityTime{ -9999 };
bool mLastActivityBound{ false };
bool mShowActivityUIOverlay{ true };
bool mBlink{ false };
int mControllerPage{ 0 };
DropdownList* mPageSelector{ nullptr };
std::vector<std::list<MidiDeviceListener*> > mListeners;
std::vector<ScriptModule*> mScriptListeners;
bool mPrintInput{ false };
std::string mLastInput;
INonstandardController* mNonstandardController{ nullptr };
bool mIsConnected{ false };
bool mHasCreatedConnectionUIControls{ false };
float mReconnectWaitTimer{ 0 };
ChannelFilter mChannelFilter{ ChannelFilter::kAny };
std::string mLastLoadedLayoutFile;
ofxJSONElement mLayoutData;
std::string mLayoutLoadError;
std::array<ControlLayoutElement, NUM_LAYOUT_CONTROLS> mLayoutControls;
int mHighlightedLayoutElement{ -1 };
int mHoveredLayoutElement{ -1 };
int mLayoutWidth{ 0 };
int mLayoutHeight{ 0 };
std::vector<GridLayout*> mGrids;
ofMutex mQueuedMessageMutex;
};
``` | /content/code_sandbox/Source/MidiController.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,923 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// LooperRecorder.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/9/12.
//
//
#include "LooperRecorder.h"
#include "Looper.h"
#include "SynthGlobals.h"
#include "Transport.h"
#include "Scale.h"
#include "Stutter.h"
#include "ModularSynth.h"
#include "ChaosEngine.h"
#include "Profiler.h"
#include "PatchCableSource.h"
#include "UIControlMacros.h"
LooperRecorder::LooperRecorder()
: IAudioProcessor(gBufferSize)
, mRecordBuffer(MAX_BUFFER_SIZE)
, mWriteBuffer(gBufferSize)
{
mQuietInputRamp.SetValue(1);
}
namespace
{
const float kBufferSegmentWidth = 30;
const float kBufferHeight = 50;
}
void LooperRecorder::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mCommit1BarButton = new ClickButton(this, "1", 3 + kBufferSegmentWidth * 3, 3);
mCommit2BarsButton = new ClickButton(this, "2", 3 + kBufferSegmentWidth * 2, 3);
mCommit4BarsButton = new ClickButton(this, "4", 3 + kBufferSegmentWidth, 3);
mCommit8BarsButton = new ClickButton(this, "8", 3, 3);
float width, height;
UIBLOCK(kBufferSegmentWidth * 4 + 6, 3, 60);
DROPDOWN(mNumBarsSelector, "length", &mNumBars, 50);
BUTTON(mDoubleTempoButton, "2xtempo");
BUTTON(mHalfTempoButton, ".5tempo");
//BUTTON(mShiftMeasureButton, "shift"); UIBLOCK_SHIFTUP(); UIBLOCK_SHIFTX(30);
//BUTTON(mHalfShiftButton, "half"); UIBLOCK_NEWLINE();
//BUTTON(mShiftDownbeatButton, "downbeat");
UIBLOCK_SHIFTDOWN();
UIBLOCK_SHIFTDOWN();
INTSLIDER(mNextCommitTargetSlider, "target", &mNextCommitTargetIndex, 0, 3);
CHECKBOX(mAutoAdvanceThroughLoopersCheckbox, "auto-advance", &mAutoAdvanceThroughLoopers);
UIBLOCK_NEWCOLUMN();
UIBLOCK_PUSHSLIDERWIDTH(80);
DROPDOWN(mModeSelector, "mode", ((int*)(&mRecorderMode)), 60);
BUTTON(mClearOverdubButton, "clear");
CHECKBOX(mFreeRecordingCheckbox, "free rec", &mFreeRecording);
BUTTON(mCancelFreeRecordButton, "cancel free rec");
ENDUIBLOCK(width, height);
mWidth = MAX(mWidth, width);
mHeight = MAX(mHeight, height);
UIBLOCK(3, kBufferHeight + 6);
BUTTON(mOrigSpeedButton, "orig speed");
BUTTON(mSnapPitchButton, "snap to pitch");
BUTTON(mResampleButton, "resample");
BUTTON(mResampAndSetButton, "resample & set key");
UIBLOCK_PUSHSLIDERWIDTH(120);
FLOATSLIDER(mLatencyFixMsSlider, "latency fix ms", &mLatencyFixMs, 0, 200);
ENDUIBLOCK(width, height);
mWidth = MAX(mWidth, width);
mHeight = MAX(mHeight, height);
UIBLOCK(kBufferSegmentWidth * 4 + 110, kBufferHeight + 22);
for (int i = 0; i < (int)mWriteForLooperCheckbox.size(); ++i)
{
CHECKBOX(mWriteForLooperCheckbox[i], ("write" + ofToString(i)).c_str(), &mWriteForLooper[i]);
}
ENDUIBLOCK(width, height);
width += 12;
mWidth = MAX(mWidth, width);
mNumBarsSelector->AddLabel(" 1 ", 1);
mNumBarsSelector->AddLabel(" 2 ", 2);
mNumBarsSelector->AddLabel(" 3 ", 3);
mNumBarsSelector->AddLabel(" 4 ", 4);
mNumBarsSelector->AddLabel(" 6 ", 6);
mNumBarsSelector->AddLabel(" 8 ", 8);
mNumBarsSelector->AddLabel("12 ", 12);
mModeSelector->AddLabel("record", kRecorderMode_Record);
mModeSelector->AddLabel("overdub", kRecorderMode_Overdub);
mModeSelector->AddLabel("loop", kRecorderMode_Loop);
mCommit1BarButton->SetDisplayText(false);
mCommit1BarButton->SetDimensions(kBufferSegmentWidth, kBufferHeight);
mCommit2BarsButton->SetDisplayText(false);
mCommit2BarsButton->SetDimensions(kBufferSegmentWidth * 2, kBufferHeight);
mCommit4BarsButton->SetDisplayText(false);
mCommit4BarsButton->SetDimensions(kBufferSegmentWidth * 3, kBufferHeight);
mCommit8BarsButton->SetDisplayText(false);
mCommit8BarsButton->SetDimensions(kBufferSegmentWidth * 4, kBufferHeight);
for (int i = 0; i < kMaxLoopers; ++i)
{
mLooperPatchCables[i] = new PatchCableSource(this, kConnectionType_Special);
mLooperPatchCables[i]->AddTypeFilter("looper");
ofRectangle rect = mWriteForLooperCheckbox[i]->GetRect(K(local));
mLooperPatchCables[i]->SetManualPosition(rect.getMaxX() + 5, rect.getCenter().y);
mLooperPatchCables[i]->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight);
ofColor color = mLooperPatchCables[i]->GetColor();
color.a *= .3f;
mLooperPatchCables[i]->SetColor(color);
AddPatchCableSource(mLooperPatchCables[i]);
}
}
LooperRecorder::~LooperRecorder()
{
}
void LooperRecorder::Init()
{
IDrawableModule::Init();
mBaseTempo = TheTransport->GetTempo();
}
void LooperRecorder::Process(double time)
{
PROFILER(LooperRecorder);
IAudioReceiver* target = GetTarget();
if (target == nullptr)
return;
SyncBuffers();
if (!mEnabled)
{
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize());
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch);
}
GetBuffer()->Reset();
return;
}
ComputeSliders(0);
mWriteBuffer.SetNumActiveChannels(GetBuffer()->NumActiveChannels());
mRecordBuffer.SetNumChannels(GetBuffer()->NumActiveChannels());
int bufferSize = GetBuffer()->BufferSize();
if (mCommitToLooper)
{
SyncLoopLengths();
mCommitToLooper->SetNumBars(mNumBars);
mCommitToLooper->Commit(&mRecordBuffer, false, mLatencyFixMs);
mRecorderMode = kRecorderMode_Record;
if (mTemporarilySilenceAfterCommit)
{
mQuietInputRamp.Start(time, 0, time + 10);
mUnquietInputTime = time + 1000; //no input for 1 second
}
mCommitToLooper = nullptr;
}
if (mUnquietInputTime != -1 && time >= mUnquietInputTime)
{
mQuietInputRamp.Start(time, 1, time + 10);
mUnquietInputTime = -1;
}
UpdateSpeed();
bool acceptInput = (mRecorderMode == kRecorderMode_Record || mRecorderMode == kRecorderMode_Overdub);
bool loop = (mRecorderMode == kRecorderMode_Loop || mRecorderMode == kRecorderMode_Overdub);
for (int i = 0; i < bufferSize; ++i)
{
if (acceptInput)
{
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
GetBuffer()->GetChannel(ch)[i] *= mQuietInputRamp.Value(time);
mWriteBuffer.GetChannel(ch)[i] = GetBuffer()->GetChannel(ch)[i];
}
time += gInvSampleRateMs;
}
else
{
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
mWriteBuffer.GetChannel(ch)[i] = 0;
}
}
if (loop)
{
int delaySamps = TheTransport->GetDuration(kInterval_1n) * GetNumBars() / gInvSampleRateMs;
delaySamps = MIN(delaySamps, MAX_BUFFER_SIZE - 1);
for (int i = 0; i < bufferSize; ++i)
{
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
float sample = mRecordBuffer.GetSample(delaySamps - i, ch);
mWriteBuffer.GetChannel(ch)[i] += sample;
GetBuffer()->GetChannel(ch)[i] += sample;
}
}
}
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
mRecordBuffer.WriteChunk(mWriteBuffer.GetChannel(ch), bufferSize, ch);
Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), bufferSize);
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), bufferSize, ch);
}
GetBuffer()->Reset();
}
void LooperRecorder::DrawCircleHash(ofVec2f center, float progress, float width, float innerRadius, float outerRadius)
{
ofSetLineWidth(width);
float sinTheta = sin(progress * TWO_PI);
float cosTheta = cos(progress * TWO_PI);
ofLine(innerRadius * sinTheta + center.x, innerRadius * -cosTheta + center.y,
outerRadius * sinTheta + center.x, outerRadius * -cosTheta + center.y);
}
void LooperRecorder::GetModuleDimensions(float& width, float& height)
{
width = mWidth;
height = MAX(mHeight, mWriteForLooperCheckbox[mNumLoopers - 1]->GetRect(K(local)).getMaxY() + 3);
}
void LooperRecorder::PreRepatch(PatchCableSource* cableSource)
{
for (int i = 0; i < mLooperPatchCables.size(); ++i)
{
if (cableSource == mLooperPatchCables[i])
{
Looper* looper = nullptr;
if (i < mLoopers.size())
looper = mLoopers[i];
if (looper)
looper->SetRecorder(nullptr);
}
}
}
void LooperRecorder::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
for (int i = 0; i < mLoopers.size(); ++i)
{
if (cableSource == mLooperPatchCables[i])
{
mLoopers[i] = dynamic_cast<Looper*>(mLooperPatchCables[i]->GetTarget());
if (mLoopers[i])
mLoopers[i]->SetRecorder(this);
}
}
}
void LooperRecorder::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
for (int i = 0; i < kMaxLoopers; ++i)
{
mWriteForLooperCheckbox[i]->SetShowing(i < mNumLoopers);
mLooperPatchCables[i]->SetShowing(i < mNumLoopers);
}
ofPushStyle();
ofFill();
ofColor color = GetColor(kModuleCategory_Audio);
ofSetColor(color.r, color.g, color.b, 50);
float x = kBufferSegmentWidth * 4 + 3;
float y = 70;
float w, h;
GetModuleDimensions(w, h);
ofRect(x, y, w - x - 3, h - y - 3);
ofPopStyle();
DrawTextNormal("loopers:", kBufferSegmentWidth * 4 + 6, 82);
if (mNextCommitTargetIndex < (int)mLooperPatchCables.size())
{
ofPushStyle();
ofSetColor(255, 255, 255);
ofVec2f cablePos = mLooperPatchCables[mNextCommitTargetIndex]->GetPosition();
cablePos -= GetPosition();
ofCircle(cablePos.x, cablePos.y, 5);
ofPopStyle();
}
mResampleButton->Draw();
mResampAndSetButton->Draw();
mDoubleTempoButton->Draw();
mHalfTempoButton->Draw();
//mShiftMeasureButton->Draw();
//mHalfShiftButton->Draw();
//mShiftDownbeatButton->Draw();
mModeSelector->Draw();
mClearOverdubButton->Draw();
mNumBarsSelector->Draw();
mOrigSpeedButton->Draw();
mSnapPitchButton->Draw();
mFreeRecordingCheckbox->Draw();
mCancelFreeRecordButton->Draw();
mLatencyFixMsSlider->Draw();
mNextCommitTargetSlider->Draw();
mAutoAdvanceThroughLoopersCheckbox->Draw();
for (int i = 0; i < (int)mWriteForLooperCheckbox.size(); ++i)
mWriteForLooperCheckbox[i]->Draw();
if (mSpeed != 1)
{
float rootPitch = AdjustedRootForSpeed();
int pitch = int(rootPitch + .5f);
int cents = (rootPitch - pitch) * 100;
std::string speed = "speed " + ofToString(mSpeed, 2) + ", ";
std::string detune = NoteName(pitch);
if (cents > 0)
detune += " +" + ofToString(cents) + " cents";
if (cents < 0)
detune += " -" + ofToString(-cents) + " cents";
DrawTextNormal(speed + detune, 100, 80);
}
if (mCommit1BarButton == gHoveredUIControl)
mCommit1BarButton->Draw();
if (mCommit2BarsButton == gHoveredUIControl)
mCommit2BarsButton->Draw();
if (mCommit4BarsButton == gHoveredUIControl)
mCommit4BarsButton->Draw();
if (mCommit8BarsButton == gHoveredUIControl)
mCommit8BarsButton->Draw();
ofPushStyle();
int sampsPerBar = abs(int(TheTransport->MsPerBar() / 1000 * gSampleRate));
for (int i = 0; i < 4; ++i) //segments
{
int bars = 1;
int barOffset = 0;
if (i == 1)
{
barOffset = 1;
}
if (i == 2)
{
bars = 2;
barOffset = 2;
}
if (i == 3)
{
bars = 4;
barOffset = 4;
}
mRecordBuffer.Draw(3 + (3 - i) * kBufferSegmentWidth, 3, kBufferSegmentWidth, kBufferHeight, sampsPerBar * bars, -1, sampsPerBar * barOffset);
}
ofSetColor(0, 0, 0, 20);
for (int i = 1; i < 4; ++i)
{
const float bx = 3 + i * kBufferSegmentWidth;
ofLine(bx, 3, bx, 3 + kBufferHeight);
}
ofPopStyle();
/*ofPushStyle();
ofVec2f center(48,28);
float radius = 25;
ofSetColor(255,255,255,100*gModuleDrawAlpha);
DrawCircleHash(center, (TheTransport->GetMeasurePos(gTime) + TheTransport->GetMeasure(gTime) % 8) / 8, 1, radius * .9f, radius);
DrawCircleHash(center, (TheTransport->GetMeasurePos(gTime) + TheTransport->GetMeasure(gTime) % mNumBars) / mNumBars, 3, radius * .7f, radius);
for (int i=0; i<mNumBars; ++i)
DrawCircleHash(center, float(i)/mNumBars, 1, radius * .8f, radius);
ofPopStyle();*/
if (mDrawDebug)
mRecordBuffer.Draw(0, 162, 800, 100);
}
void LooperRecorder::RemoveLooper(Looper* looper)
{
for (int i = 0; i < mLoopers.size(); ++i)
{
if (mLoopers[i] == looper)
mLoopers[i] = nullptr;
}
}
float LooperRecorder::AdjustedRootForSpeed()
{
float rootFreq = TheScale->PitchToFreq(TheScale->ScaleRoot() + 24);
rootFreq *= mSpeed;
return TheScale->FreqToPitch(rootFreq);
}
void LooperRecorder::SnapToClosestPitch()
{
float currentPitch = AdjustedRootForSpeed();
float desiredPitch = int(currentPitch + .5f);
float currentFreq = TheScale->PitchToFreq(currentPitch);
float desiredFreq = TheScale->PitchToFreq(desiredPitch);
TheTransport->SetTempo(TheTransport->GetTempo() * desiredFreq / currentFreq);
}
void LooperRecorder::Resample(bool setKey)
{
if (setKey)
{
SnapToClosestPitch();
TheScale->SetRoot(int(AdjustedRootForSpeed() + .5f));
}
SyncLoopLengths();
}
void LooperRecorder::UpdateSpeed()
{
float newSpeed = TheTransport->GetTempo() / mBaseTempo;
if (mSpeed != newSpeed)
{
mSpeed = newSpeed;
if (mSpeed == 0)
mSpeed = .001f;
}
}
void LooperRecorder::SyncLoopLengths()
{
if (mSpeed <= 0) //avoid crashing
return;
for (int i = 0; i < mLoopers.size(); ++i)
{
if (mLoopers[i])
{
if (mSpeed != 1)
mLoopers[i]->ResampleForSpeed(mLoopers[i]->GetPlaybackSpeed());
mLoopers[i]->RecalcLoopLength();
}
}
mBaseTempo = TheTransport->GetTempo();
}
void LooperRecorder::Commit(Looper* looper)
{
mCommitToLooper = looper;
}
void LooperRecorder::RequestMerge(Looper* looper)
{
if (mMergeSource == nullptr)
{
mMergeSource = looper;
}
else if (mMergeSource == looper)
{
mMergeSource = nullptr;
}
else
{
looper->MergeIn(mMergeSource);
mMergeSource = nullptr;
}
}
void LooperRecorder::RequestSwap(Looper* looper)
{
if (mSwapSource == nullptr)
{
mSwapSource = looper;
}
else if (mSwapSource == looper)
{
mSwapSource = nullptr;
}
else
{
looper->SwapBuffers(mSwapSource);
mSwapSource = nullptr;
}
}
void LooperRecorder::RequestCopy(Looper* looper)
{
if (mCopySource == nullptr)
{
mCopySource = looper;
}
else if (mCopySource == looper)
{
mCopySource = nullptr;
}
else
{
looper->CopyBuffer(mCopySource);
mCopySource = nullptr;
}
}
void LooperRecorder::ResetSpeed()
{
mBaseTempo = TheTransport->GetTempo();
}
void LooperRecorder::StartFreeRecord(double time)
{
if (mFreeRecording)
return;
mFreeRecording = true;
mStartFreeRecordTime = time;
}
void LooperRecorder::EndFreeRecord(double time)
{
if (!mFreeRecording)
return;
float recordedTime = time - mStartFreeRecordTime;
int beats = mNumBars * TheTransport->GetTimeSigTop();
float minutes = recordedTime / 1000.0f / 60.0f;
TheTransport->SetTempo(beats / minutes);
TheTransport->SetDownbeat();
mRecorderMode = kRecorderMode_Loop;
mFreeRecording = false;
}
void LooperRecorder::CancelFreeRecord()
{
mFreeRecording = false;
mStartFreeRecordTime = 0;
}
bool LooperRecorder::OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue)
{
if (type == kMidiMessage_Note)
{
if (controlIndex >= 36 && controlIndex <= 99 && midiValue > 0)
{
int gridIndex = controlIndex - 36;
int x = gridIndex % 8;
int y = 7 - gridIndex / 8;
if (y == 0)
{
switch (x)
{
case 0: mCommit8BarsButton->SetValue(1, gTime); break;
case 1: mCommit4BarsButton->SetValue(1, gTime); break;
case 2: mCommit2BarsButton->SetValue(1, gTime); break;
case 3: mCommit1BarButton->SetValue(1, gTime); break;
default: break;
}
}
else if (y == 1)
{
if (x < mLoopers.size())
mNextCommitTargetIndex = x;
}
else if (y - 2 < mLoopers.size())
{
int looperIndex = y - 2;
if (mLoopers[looperIndex] != nullptr)
{
if (x == 0)
push2->SetDisplayModule(mLoopers[looperIndex]);
if (x == 1)
mLoopers[looperIndex]->SetMute(gTime, !mLoopers[looperIndex]->GetMute());
}
}
return true;
}
}
return false;
}
void LooperRecorder::UpdatePush2Leds(Push2Control* push2)
{
for (int x = 0; x < 8; ++x)
{
for (int y = 0; y < 8; ++y)
{
int pushColor = 0;
if (y == 0)
{
switch (x)
{
case 0: pushColor = mCommit8BarsButton->GetValue() > 0 ? 125 : 33; break;
case 1: pushColor = mCommit4BarsButton->GetValue() > 0 ? 125 : 33; break;
case 2: pushColor = mCommit2BarsButton->GetValue() > 0 ? 125 : 33; break;
case 3: pushColor = mCommit1BarButton->GetValue() > 0 ? 125 : 33; break;
default: break;
}
}
else if (y == 1)
{
if (x < mLoopers.size())
pushColor = (x == mNextCommitTargetIndex) ? 126 : 86;
}
else if (y - 2 < mLoopers.size())
{
int looperIndex = y - 2;
if (mLoopers[looperIndex] != nullptr)
{
if (x == 0)
pushColor = (push2->GetDisplayModule() == mLoopers[looperIndex]) ? 125 : 33;
if (x == 1)
pushColor = mLoopers[looperIndex]->GetMute() ? 127 : 68;
}
}
push2->SetLed(kMidiMessage_Note, x + (7 - y) * 8 + 36, pushColor);
}
}
}
void LooperRecorder::ButtonClicked(ClickButton* button, double time)
{
if (button == mResampleButton)
SyncLoopLengths();
if (button == mResampAndSetButton)
{
SnapToClosestPitch();
TheScale->SetRoot(int(AdjustedRootForSpeed() + .5f));
SyncLoopLengths();
}
if (button == mDoubleTempoButton)
{
for (int i = 0; i < mLoopers.size(); ++i)
{
if (mLoopers[i])
mLoopers[i]->DoubleNumBars();
}
TheTransport->SetTempo(TheTransport->GetTempo() * 2);
mBaseTempo = TheTransport->GetTempo();
float pos = TheTransport->GetMeasurePos(time) + (TheTransport->GetMeasure(time) % 8);
int count = TheTransport->GetMeasure(time) - int(pos);
pos *= 2;
count += int(pos);
pos -= int(pos);
TheTransport->SetMeasureTime(count + pos);
for (int i = 0; i < mLoopers.size(); ++i)
{
if (mLoopers[i])
mLoopers[i]->ResampleForSpeed(1);
}
}
if (button == mHalfTempoButton)
{
for (int i = 0; i < mLoopers.size(); ++i)
{
if (mLoopers[i])
mLoopers[i]->HalveNumBars();
}
TheTransport->SetTempo(TheTransport->GetTempo() / 2);
mBaseTempo = TheTransport->GetTempo();
float pos = TheTransport->GetMeasurePos(time) + (TheTransport->GetMeasure(time) % 8);
int count = TheTransport->GetMeasure(time) - int(pos);
pos /= 2;
count += int(pos);
pos -= int(pos);
TheTransport->SetMeasureTime(count + pos);
for (int i = 0; i < mLoopers.size(); ++i)
{
if (mLoopers[i])
mLoopers[i]->ResampleForSpeed(1);
}
}
if (button == mShiftMeasureButton)
{
for (int i = 0; i < mLoopers.size(); ++i)
{
if (mLoopers[i])
mLoopers[i]->ShiftMeasure();
}
int newMeasure = TheTransport->GetMeasure(time) - 1;
if (newMeasure < 0)
newMeasure = 7;
TheTransport->SetMeasure(newMeasure);
}
if (button == mHalfShiftButton)
{
for (int i = 0; i < mLoopers.size(); ++i)
{
if (mLoopers[i])
mLoopers[i]->HalfShift();
}
int newMeasure = int(TheTransport->GetMeasure(time) + TheTransport->GetMeasurePos(time) - .5f);
if (newMeasure < 0)
newMeasure = 7;
float newMeasurePos = FloatWrap(TheTransport->GetMeasurePos(time) - .5f, 1);
TheTransport->SetMeasureTime(newMeasure + newMeasurePos);
}
if (button == mShiftDownbeatButton)
{
TheTransport->SetMeasure(TheTransport->GetMeasure(time) / 8 * 8); //align to 8 bars
TheTransport->SetDownbeat();
for (int i = 0; i < mLoopers.size(); ++i)
{
if (mLoopers[i])
mLoopers[i]->ShiftDownbeat();
}
if (TheChaosEngine)
TheChaosEngine->RestartProgression();
}
if (button == mClearOverdubButton)
mRecordBuffer.ClearBuffer();
if (button == mOrigSpeedButton)
{
TheTransport->SetTempo(mBaseTempo);
}
if (button == mSnapPitchButton)
SnapToClosestPitch();
if (button == mCancelFreeRecordButton)
CancelFreeRecord();
if (button == mCommit1BarButton ||
button == mCommit2BarsButton ||
button == mCommit4BarsButton ||
button == mCommit8BarsButton)
{
int numBars = 1;
if (button == mCommit1BarButton)
numBars = 1;
if (button == mCommit2BarsButton)
numBars = 2;
if (button == mCommit4BarsButton)
numBars = 4;
if (button == mCommit8BarsButton)
numBars = 8;
mNumBars = numBars;
if (mNextCommitTargetIndex < (int)mLoopers.size())
Commit(mLoopers[mNextCommitTargetIndex]);
if (mAutoAdvanceThroughLoopers)
{
for (int i = 0; i < (int)mLoopers.size(); ++i)
{
mNextCommitTargetIndex = (mNextCommitTargetIndex + 1) % mLoopers.size();
if (mLoopers[mNextCommitTargetIndex] != nullptr)
break;
}
}
}
}
void LooperRecorder::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mFreeRecordingCheckbox)
{
bool freeRec = mFreeRecording;
mFreeRecording = !mFreeRecording; //flip back so these methods won't be ignored
if (freeRec)
StartFreeRecord(time);
else
EndFreeRecord(time);
}
for (int i = 0; i < (int)mWriteForLooperCheckbox.size(); ++i)
{
if (checkbox == mWriteForLooperCheckbox[i])
{
if (mWriteForLooper[i])
{
bool isWriteInProgress = false;
for (int j = 0; j < mNumLoopers; ++j)
{
if (j != i && mWriteForLooper[j])
isWriteInProgress = true;
}
if (isWriteInProgress)
{
// cancel all
for (int j = 0; j < mNumLoopers; ++j)
mWriteForLooper[j] = false;
}
else
{
mStartRecordMeasureTime[i] = TheTransport->GetMeasureTime(gTime);
}
}
else
{
double currentMeasureTime = TheTransport->GetMeasureTime(gTime);
double lengthInMeasures = currentMeasureTime - mStartRecordMeasureTime[i];
int numBars = 1;
if (lengthInMeasures < 1.5f)
numBars = 1;
else if (lengthInMeasures < 3.0f)
numBars = 2;
else if (lengthInMeasures < 6.0f)
numBars = 4;
else
numBars = 8;
mNumBars = numBars;
Commit(mLoopers[i]);
}
}
}
}
void LooperRecorder::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void LooperRecorder::RadioButtonUpdated(RadioButton* radio, int oldVal, double time)
{
}
void LooperRecorder::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mNumBarsSelector)
{
mNumBars = MAX(1, mNumBars);
}
}
void LooperRecorder::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void LooperRecorder::Poll()
{
}
void LooperRecorder::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadInt("num_loopers", moduleInfo, 4, 1, kMaxLoopers);
mModuleSaveData.LoadBool("temp_silence_after_commit", moduleInfo, false);
SetUpFromSaveData();
}
void LooperRecorder::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
mNumLoopers = mModuleSaveData.GetInt("num_loopers");
mTemporarilySilenceAfterCommit = mModuleSaveData.GetBool("temp_silence_after_commit");
}
void LooperRecorder::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mBaseTempo;
out << mSpeed;
mRecordBuffer.SaveState(out);
}
void LooperRecorder::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
in >> mBaseTempo;
in >> mSpeed;
mRecordBuffer.LoadState(in);
}
``` | /content/code_sandbox/Source/LooperRecorder.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 7,332 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteRangeFilter.h
Created: 29 Jan 2020 9:18:39pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Slider.h"
class NoteRangeFilter : public NoteEffectBase, public IDrawableModule, public IIntSliderListener
{
public:
NoteRangeFilter();
static IDrawableModule* Create() { return new NoteRangeFilter(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
float mWidth{ 200 };
float mHeight{ 20 };
int mMinPitch{ 24 };
IntSlider* mMinPitchSlider{ nullptr };
int mMaxPitch{ 36 };
IntSlider* mMaxPitchSlider{ nullptr };
bool mWrap{ false };
Checkbox* mWrapCheckbox{ nullptr };
};
``` | /content/code_sandbox/Source/NoteRangeFilter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 500 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// MacroSlider.h
// Bespoke
//
// Created by Ryan Challinor on 12/19/15.
//
//
#pragma once
#include "IDrawableModule.h"
#include "Slider.h"
#include "IModulator.h"
class PatchCableSource;
class IUIControl;
class MacroSlider : public IDrawableModule, public IFloatSliderListener
{
public:
MacroSlider();
virtual ~MacroSlider();
static IDrawableModule* Create() { return new MacroSlider(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
float GetValue() const { return mValue; }
FloatSlider* GetSlider() { return mSlider; }
void SetOutputTarget(int index, IUIControl* target);
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
const static int kMappingSpacing = 32;
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 110;
height = 25 + (int)mMappings.size() * kMappingSpacing;
}
struct Mapping : public IModulator
{
Mapping(MacroSlider* owner, int index);
~Mapping();
void CreateUIControls();
void UpdateControl();
void Draw();
PatchCableSource* GetCableSource() const { return mTargetCable; }
//IModulator
virtual float Value(int samplesIn = 0) override;
virtual bool Active() const override { return mOwner->IsEnabled(); }
MacroSlider* mOwner{ nullptr };
int mIndex{ 0 };
};
FloatSlider* mSlider{ nullptr };
float mValue{ 0 };
std::vector<Mapping*> mMappings;
};
``` | /content/code_sandbox/Source/MacroSlider.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 611 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
IModulator.h
Created: 16 Nov 2017 9:59:15pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "Slider.h"
#include "IPollable.h"
class PatchCableSource;
class IModulator : public IPollable
{
public:
IModulator();
virtual ~IModulator();
virtual float Value(int samplesIn = 0) = 0;
virtual bool Active() const = 0;
virtual bool CanAdjustRange() const { return true; }
virtual bool InitializeWithZeroRange() const { return false; }
float& GetMin() { return mTargets[0].mSliderTarget ? mTargets[0].mSliderTarget->GetModulatorMin() : mDummyMin; }
float& GetMax() { return mTargets[0].mSliderTarget ? mTargets[0].mSliderTarget->GetModulatorMax() : mDummyMax; }
void OnModulatorRepatch();
void Poll() override;
float GetRecentChange() const;
void OnRemovedFrom(IUIControl* control);
int GetNumTargets() const;
protected:
void InitializeRange(float currentValue, float min, float max, FloatSlider::Mode sliderMode);
FloatSlider* GetSliderTarget() const { return mTargets[0].mSliderTarget; }
float mDummyMin{ 0 };
float mDummyMax{ 1 };
struct Target
{
FloatSlider* mSliderTarget{ nullptr };
IUIControl* mUIControlTarget{ nullptr };
bool RequiresManualPolling() { return mUIControlTarget != nullptr && mSliderTarget == nullptr; }
};
PatchCableSource* mTargetCable{ nullptr };
FloatSlider* mMinSlider{ nullptr };
FloatSlider* mMaxSlider{ nullptr };
std::array<Target, 10> mTargets;
float mLastPollValue{ 0 };
float mSmoothedValue{ 0 };
};
``` | /content/code_sandbox/Source/IModulator.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 529 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// DebugAudioSource.h
// Bespoke
//
// Created by Ryan Challinor on 7/1/14.
//
//
#pragma once
#include <iostream>
#include "IAudioSource.h"
#include "EnvOscillator.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Slider.h"
class DebugAudioSource : public IAudioSource, public IDrawableModule, public IFloatSliderListener
{
public:
DebugAudioSource();
~DebugAudioSource();
static IDrawableModule* Create() { return new DebugAudioSource(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void CheckboxUpdated(Checkbox* checkbox, double time) override {}
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 80;
height = 60;
}
};
``` | /content/code_sandbox/Source/DebugAudioSource.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 413 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// SynthGlobals.h
// modularSynth
//
// Created by Ryan Challinor on 11/22/12.
//
//
#pragma once
#if __clang__
#pragma clang diagnostic ignored "-Wreorder"
#endif
#include "Xoshiro256ss.h"
#include "OpenFrameworksPort.h"
#include <map>
#include <list>
#include <vector>
#include <algorithm>
#include <array>
#include <cctype>
#include <random>
#include <float.h>
//#define BESPOKE_DEBUG_ALLOCATIONS
#ifdef BESPOKE_DEBUG_ALLOCATIONS
void* operator new(std::size_t size, const char* file, int line) throw(std::bad_alloc);
void* operator new[](std::size_t size, const char* file, int line) throw(std::bad_alloc);
#define DEBUG_NEW new (__FILE__, __LINE__)
#else
#define DEBUG_NEW new
#endif
#define new DEBUG_NEW
#define BESPOKE_SUPPRESS_NIGHTLY_LABEL 0
#if !defined(__PRETTY_FUNCTION__) && !defined(__GNUC__)
#define __PRETTY_FUNCTION__ __FUNCSIG__
#endif
#define MAX_BUFFER_SIZE 30 * gSampleRate
#define MAX_TEXTENTRY_LENGTH 1024
#ifndef M_PI
#define M_PI PI
#endif
#define FPI 3.14159265358979323846f
#define FTWO_PI 6.28318530717958647693f
#define USE_VECTOR_OPS
//bool labeling technique that I stole from Ableton
#define K(x) true
#define L(x, y) y
//avoid "unused variable" warnings
#define UNUSED(x) ((void)x)
class IUIControl;
class IDrawableModule;
class RollingBuffer;
class ChannelBuffer;
typedef std::map<std::string, int> EnumMap;
const int kWorkBufferSize = 1024 * 8; //larger than the audio buffer size would ever be (even oversampled)
const int kNumVoices = 16;
extern int gSampleRate;
extern int gBufferSize;
extern double gTwoPiOverSampleRate;
extern double gSampleRateMs;
extern double gInvSampleRateMs;
extern double gBufferSizeMs;
extern double gNyquistLimit;
extern bool gPrintMidiInput;
extern double gTime;
extern IUIControl* gBindToUIControl;
extern RetinaTrueTypeFont gFont;
extern RetinaTrueTypeFont gFontBold;
extern RetinaTrueTypeFont gFontFixedWidth;
extern float gModuleDrawAlpha;
extern float gNullBuffer[kWorkBufferSize];
extern float gZeroBuffer[kWorkBufferSize];
extern float gWorkBuffer[kWorkBufferSize]; //scratch buffer for doing work in
extern ChannelBuffer gWorkChannelBuffer;
extern IDrawableModule* gHoveredModule;
extern IUIControl* gHoveredUIControl;
extern IUIControl* gHotBindUIControl[10];
extern float gControlTactileFeedback;
extern float gDrawScale;
extern bool gShowDevModules;
extern float gCornerRoundness;
extern std::random_device gRandomDevice;
extern bespoke::core::Xoshiro256ss gRandom;
extern std::uniform_real_distribution<float> gRandom01;
extern std::uniform_real_distribution<float> gRandomBipolarDist;
enum OscillatorType
{
kOsc_Sin,
kOsc_Square,
kOsc_Tri,
kOsc_Saw,
kOsc_NegSaw,
kOsc_Random,
kOsc_Drunk,
kOsc_Perlin
};
enum KeyModifiers
{
kModifier_None = 0,
kModifier_Shift = 1,
kModifier_Alt = 2,
kModifier_Control = 4,
kModifier_Command = 8
};
class LoadingJSONException : public std::exception
{
};
class UnknownModuleException : public std::exception
{
public:
UnknownModuleException(std::string searchName)
: mSearchName(searchName)
{}
~UnknownModuleException() throw() {}
std::string mSearchName;
};
class UnknownEffectTypeException : public std::exception
{
};
class BadUIControlPathException : public std::exception
{
};
class UnknownUIControlException : public std::exception
{
};
class WrongModuleTypeException : public std::exception
{
};
class LoadStateException : public std::exception
{
};
void SynthInit();
void LoadGlobalResources();
void SetGlobalSampleRateAndBufferSize(int rate, int size);
std::string GetBuildInfoString();
void DrawAudioBuffer(float width, float height, ChannelBuffer* buffer, float start, float end, float pos, float vol = 1, ofColor color = ofColor::black, int wraparoundFrom = -1, int wraparoundTo = 0);
void DrawAudioBuffer(float width, float height, const float* buffer, float start, float end, float pos, float vol = 1, ofColor color = ofColor::black, int wraparoundFrom = -1, int wraparoundTo = 0, int bufferSize = -1);
void Add(float* buff1, const float* buff2, int bufferSize);
void Subtract(float* buff1, const float* buff2, int bufferSize);
void Mult(float* buff, float val, int bufferSize);
void Mult(float* buff1, const float* buff2, int bufferSize);
void Clear(float* buffer, int bufferSize);
void BufferCopy(float* dst, const float* src, int bufferSize);
std::string NoteName(int pitch, bool flat = false, bool includeOctave = false);
int PitchFromNoteName(std::string noteName);
float Interp(float a, float start, float end);
double GetPhaseInc(float freq);
float FloatWrap(float num, float space);
double DoubleWrap(double num, float space);
void DrawTextNormal(std::string text, int x, int y, float size = 13);
void DrawTextRightJustify(std::string text, int x, int y, float size = 13);
void DrawTextBold(std::string text, int x, int y, float size = 13);
float GetStringWidth(std::string text, float size = 13);
void AssertIfDenormal(float input);
float GetInterpolatedSample(double offset, const float* buffer, int bufferSize);
float GetInterpolatedSample(double offset, ChannelBuffer* buffer, int bufferSize, float channelBlend);
void WriteInterpolatedSample(double offset, float* buffer, int bufferSize, float sample);
std::string GetRomanNumeralForDegree(int degree);
void UpdateTarget(IDrawableModule* module);
void DrawLissajous(RollingBuffer* buffer, float x, float y, float w, float h, float r = .2f, float g = .7f, float b = .2f);
void StringCopy(char* dest, const char* source, int destLength);
int GetKeyModifiers();
bool IsKeyHeld(int key, int modifiers = kModifier_None);
int KeyToLower(int key);
float EaseIn(float start, float end, float a);
float EaseOut(float start, float end, float a);
float Bias(float value, float bias);
float Pow2(float in);
void PrintCallstack();
bool IsInUnitBox(ofVec2f pos);
std::string GetUniqueName(std::string name, std::vector<IDrawableModule*> existing);
std::string GetUniqueName(std::string name, std::vector<std::string> existing);
void SetMemoryTrackingEnabled(bool enabled);
void DumpUnfreedMemory();
float DistSqToLine(ofVec2f point, ofVec2f a, ofVec2f b);
uint32_t JenkinsHash(const char* key);
void LoadStateValidate(bool assertion);
float GetLeftPanGain(float pan);
float GetRightPanGain(float pan);
void DrawFallbackText(const char* text, float posX, float posY);
bool EvaluateExpression(std::string expression, float currentValue, float& output);
double NextBufferTime(bool includeLookahead);
bool IsAudioThread();
inline static float RandomSample()
{
return gRandomBipolarDist(gRandom);
}
inline static int DeterministicRandom(int seed, int index)
{
uint64_t x = seed + ((uint64_t)index << 32);
x = (x ^ (x >> 30)) * (0xbf58476d1ce4e5b9);
x = (x ^ (x >> 27)) * (0x94d049bb133111eb);
x = x ^ (x >> 31);
return (int)x;
}
inline static std::string GetPathSeparator()
{
#if BESPOKE_WINDOWS
return "\\";
#else
return "/";
#endif
}
#ifndef assert
#define assert Assert
inline static void Assert(bool condition)
{
if (condition == false)
{
ofLog() << "assertion failed";
throw new exception();
}
}
#endif
template <class T>
void RemoveFromVector(T element, std::vector<T>& vec, bool fail = false)
{
auto toRemove = std::find(vec.begin(), vec.end(), element);
if (fail && toRemove == vec.end())
assert(false);
if (toRemove != vec.end())
vec.erase(toRemove);
}
template <class T>
bool VectorContains(T element, const std::vector<T>& vec)
{
return std::find(vec.begin(), vec.end(), element) != vec.end();
}
template <class T>
bool ListContains(T element, const std::list<T>& lis)
{
return std::find(lis.begin(), lis.end(), element) != lis.end();
}
struct Vec2i
{
Vec2i()
: x(0)
, y(0)
{}
Vec2i(int _x, int _y)
: x(_x)
, y(_y)
{}
int x;
int y;
};
class ofLog
{
public:
ofLog()
: mSendToBespokeConsole(true)
{}
~ofLog();
template <class T>
ofLog& operator<<(const T& value)
{
mMessage += ofToString(value);
return *this;
}
ofLog& operator!()
{
mSendToBespokeConsole = false;
return *this;
}
private:
std::string mMessage;
bool mSendToBespokeConsole;
};
``` | /content/code_sandbox/Source/SynthGlobals.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,284 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Muter.h
// modularSynth
//
// Created by Ryan Challinor on 3/26/13.
//
//
#pragma once
#include <iostream>
#include "IAudioEffect.h"
#include "Checkbox.h"
#include "Ramp.h"
#include "Slider.h"
class Muter : public IAudioEffect, public IFloatSliderListener
{
public:
Muter();
virtual ~Muter();
static IAudioEffect* Create() { return new Muter(); }
void CreateUIControls() override;
//IAudioEffect
void ProcessAudio(double time, ChannelBuffer* buffer) override;
void SetEnabled(bool enabled) override {}
std::string GetType() override { return "muter"; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 80;
h = 38;
}
bool mPass{ false };
Checkbox* mPassCheckbox{ nullptr };
Ramp mRamp;
float mRampTimeMs{ 3 };
FloatSlider* mRampTimeSlider{ nullptr };
};
``` | /content/code_sandbox/Source/Muter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 389 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ClickButton.h
// modularSynth
//
// Created by Ryan Challinor on 12/4/12.
//
//
#pragma once
#include "IPulseReceiver.h"
#include "IUIControl.h"
class ClickButton;
class IButtonListener
{
public:
virtual ~IButtonListener() {}
virtual void ButtonClicked(ClickButton* button, double time) = 0;
};
enum class ButtonDisplayStyle
{
kText,
kNoLabel,
kPlay,
kPause,
kStop,
kGrabSample,
kSampleIcon,
kFolderIcon,
kArrowRight,
kArrowLeft,
kPlus,
kMinus,
kHamburger
};
class ClickButton : public IUIControl, public IPulseReceiver
{
public:
ClickButton(IButtonListener* owner, const char* label, int x, int y, ButtonDisplayStyle displayStyle = ButtonDisplayStyle::kText);
ClickButton(IButtonListener* owner, const char* label, IUIControl* anchor, AnchorDirection anchorDirection, ButtonDisplayStyle displayStyle = ButtonDisplayStyle::kText);
void SetLabel(const char* label);
void UpdateWidth();
void Render() override;
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
void SetDisplayText(bool display) { mDisplayStyle = ButtonDisplayStyle::kNoLabel; }
void SetDisplayStyle(ButtonDisplayStyle style) { mDisplayStyle = style; }
void SetDimensions(float width, float height)
{
mWidth = width;
mHeight = height;
}
//IUIControl
void SetFromMidiCC(float slider, double time, bool setViaModulator) override;
void SetValue(float value, double time, bool forceUpdate = false) override;
float GetValue() const override { return GetMidiValue(); }
float GetMidiValue() const override;
std::string GetDisplayValue(float val) const override;
int GetNumValues() override { return 2; }
void Increment(float amount) override;
void GetDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void SaveState(FileStreamOut& out) override {}
void LoadState(FileStreamIn& in, bool shouldSetValue) override {}
bool IsSliderControl() override { return false; }
bool IsButtonControl() override { return true; }
bool CanBeTargetedBy(PatchCableSource* source) const override;
//IPulseReceiver
void OnPulse(double time, float velocity, int flags) override;
protected:
~ClickButton(); //protected so that it can't be created on the stack
private:
void DoClick(double time);
bool ButtonLit() const;
void OnClicked(float x, float y, bool right) override;
float mWidth{ 20 };
float mHeight{ 15 };
double mClickTime{ -9999 };
IButtonListener* mOwner{ nullptr };
ButtonDisplayStyle mDisplayStyle{ ButtonDisplayStyle::kText };
};
``` | /content/code_sandbox/Source/ClickButton.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 755 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// PitchShifter.cpp
// Bespoke
//
// Created by Ryan Challinor on 3/21/15.
//
//
#include "PitchShifter.h"
#include "SynthGlobals.h"
#include "Profiler.h"
#include <cstring>
PitchShifter::PitchShifter(int fftBins)
: mFFTBins(fftBins)
, mFFT(mFFTBins)
, mRollingInputBuffer(mFFTBins)
, mRollingOutputBuffer(mFFTBins)
, mFFTData(mFFTBins, mFFTBins / 2 + 1)
{
// Generate a window with a single raised cosine from N/4 to 3N/4
mWindower = new float[mFFTBins];
for (int i = 0; i < mFFTBins; ++i)
mWindower[i] = -.5 * cos(FTWO_PI * i / mFFTBins) + .5;
mLastPhase = new float[mFFTBins / 2 + 1];
mSumPhase = new float[mFFTBins / 2 + 1];
mAnalysisMag = new float[mFFTBins];
mAnalysisFreq = new float[mFFTBins];
mSynthesisMag = new float[mFFTBins];
mSynthesisFreq = new float[mFFTBins];
}
PitchShifter::~PitchShifter()
{
delete[] mLastPhase;
delete[] mSumPhase;
delete[] mWindower;
delete[] mAnalysisMag;
delete[] mAnalysisFreq;
delete[] mSynthesisMag;
delete[] mSynthesisFreq;
}
#define MY_PITCHSHIFTER 0
#if MY_PITCHSHIFTER
void PitchShifter::Process(float* buffer, int bufferSize)
{
PROFILER(PitchShifter);
const int osamp = mOversampling;
const int stepSize = mFFTBins / osamp;
const double expct = 2. * M_PI * (double)stepSize / (double)mFFTBins;
const double freqPerBin = gSampleRate / (double)mFFTBins;
mLatency = mFFTBins - stepSize;
mRollingInputBuffer.WriteChunk(buffer, bufferSize, 0);
//copy rolling input buffer into working buffer and window it
mRollingInputBuffer.ReadChunk(mFFTData.mTimeDomain, mFFTBins, latency);
Mult(mFFTData.mTimeDomain, mWindower, mFFTBins);
mFFT.Forward(mFFTData.mTimeDomain,
mFFTData.mRealValues,
mFFTData.mImaginaryValues);
const int fftFrameSize2 = mFFTBins / 2;
// this is the analysis step
for (int k = 0; k <= fftFrameSize2; k++)
{
// de-interlace FFT buffer
float real = mFFTData.mRealValues[k];
float imag = mFFTData.mImaginaryValues[k];
// compute magnitude and phase
double mag = 2. * sqrt(real * real + imag * imag);
double phase = atan2(imag, real);
// compute phase difference
double diff = phase - mLastPhase[k];
mLastPhase[k] = phase;
// subtract expected phase difference
diff -= (double)k * expct;
// map delta phase into +/- Pi interval
long qpd = diff / M_PI;
if (qpd >= 0)
qpd += qpd & 1;
else
qpd -= qpd & 1;
diff -= M_PI * (double)qpd;
// get deviation from bin frequency from the +/- Pi interval
double deviation = osamp * diff / (2. * M_PI);
// compute the k-th partials' true frequency
double freq = (double)k * freqPerBin + deviation * freqPerBin;
// store magnitude and true frequency in analysis arrays
mAnalysisMag[k] = mag;
mAnalysisFreq[k] = freq;
}
// this does the actual pitch shifting
memset(mSynthesisMag, 0, mFFTBins * sizeof(float));
memset(mSynthesisFreq, 0, mFFTBins * sizeof(float));
for (int k = 0; k <= fftFrameSize2; k++)
{
int index = k * mRatio;
if (index <= fftFrameSize2)
{
mSynthesisMag[index] += mAnalysisMag[k];
mSynthesisFreq[index] = mAnalysisFreq[k] * mRatio;
}
}
// this is the synthesis step
for (int k = 0; k <= fftFrameSize2; k++)
{
// get magnitude and true frequency from synthesis arrays
double mag = mSynthesisMag[k];
double tmp = mSynthesisFreq[k];
// subtract bin mid frequency
tmp -= (double)k * freqPerBin;
// get bin deviation from freq deviation
tmp /= freqPerBin;
// take osamp into account
tmp = 2. * M_PI * tmp / osamp;
// add the overlap phase advance back in
tmp += (double)k * expct;
// accumulate delta phase to get bin phase
mSumPhase[k] += tmp;
double phase = mSumPhase[k];
// get real and imag part and re-interleave
mFFTData.mRealValues[k + 1] = mag * cos(phase);
mFFTData.mImaginaryValues[k + 1] = mag * sin(phase);
}
mFFT.Inverse(mFFTData.mRealValues,
mFFTData.mImaginaryValues,
mFFTData.mTimeDomain);
for (int i = 0; i < bufferSize; ++i)
mRollingOutputBuffer.Write(0);
//copy rolling input buffer into working buffer and window it
for (int i = 0; i < mFFTBins; ++i)
mRollingOutputBuffer.Accum(mFFTBins - i, mFFTData.mTimeDomain[i] * mWindower[i] * .0001f);
for (int i = 0; i < bufferSize; ++i)
buffer[i] = mRollingOutputBuffer.GetSample(latency - i);
}
#else
void smbFft(float* fftBuffer, long fftFrameSize, long sign)
/*
FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse)
Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the
time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes
and returns the cosine and sine parts in an interleaved manner, ie.
fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize
must be a power of 2. It expects a complex input signal (see footnote 2),
ie. when working with 'common' audio signals our input signal has to be
passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform
of the frequencies of interest is in fftBuffer[0...fftFrameSize].
*/
{
float wr, wi, arg, *p1, *p2, temp;
float tr, ti, ur, ui, *p1r, *p1i, *p2r, *p2i;
long i, bitm, j, le, le2, k;
for (i = 2; i < 2 * fftFrameSize - 2; i += 2)
{
for (bitm = 2, j = 0; bitm < 2 * fftFrameSize; bitm <<= 1)
{
if (i & bitm)
j++;
j <<= 1;
}
if (i < j)
{
p1 = fftBuffer + i;
p2 = fftBuffer + j;
temp = *p1;
*(p1++) = *p2;
*(p2++) = temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
}
for (k = 0, le = 2; k < (long)(log(fftFrameSize) / log(2.) + .5); k++)
{
le <<= 1;
le2 = le >> 1;
ur = 1.0;
ui = 0.0;
arg = M_PI / (le2 >> 1);
wr = cos(arg);
wi = sign * sin(arg);
for (j = 0; j < le2; j += 2)
{
p1r = fftBuffer + j;
p1i = p1r + 1;
p2r = p1r + le2;
p2i = p2r + 1;
for (i = j; i < 2 * fftFrameSize; i += le)
{
tr = *p2r * ur - *p2i * ui;
ti = *p2r * ui + *p2i * ur;
*p2r = *p1r - tr;
*p2i = *p1i - ti;
*p1r += tr;
*p1i += ti;
p1r += le;
p1i += le;
p2r += le;
p2i += le;
}
tr = ur * wr - ui * wi;
ui = ur * wi + ui * wr;
ur = tr;
}
}
}
/****************************************************************************
*
* NAME: smbPitchShift.cpp
* VERSION: 1.2
* HOME URL: path_to_url
* KNOWN BUGS: none
*
* SYNOPSIS: Routine for doing pitch shifting while maintaining
* duration using the Short Time Fourier Transform.
*
* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5
* (one octave down) and 2. (one octave up). A value of exactly 1 does not change
* the pitch. numSampsToProcess tells the routine how many samples in indata[0...
* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...
* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the
* data in-place). fftFrameSize defines the FFT frame size used for the
* processing. Typical values are 1024, 2048 and 4096. It may be any value <=
* MAX_FRAME_LENGTH but it MUST be a power of 2. osamp is the STFT
* oversampling factor which also determines the overlap between adjacent STFT
* frames. It should at least be 4 for moderate scaling ratios. A value of 32 is
* recommended for best quality. sampleRate takes the sample rate for the signal
* in unit Hz, ie. 44100 for 44.1 kHz audio. The data passed to the routine in
* indata[] should be in the range [-1.0, 1.0), which is also the output range
* for the data, make sure you scale the data accordingly (for 16bit signed integers
* you would have to divide (and multiply) by 32768).
*
* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
*
*
* Permission to use, copy, modify, distribute and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice and this license appear in all source copies.
* THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF
* ANY KIND. See path_to_url for more information.
*
*****************************************************************************/
void PitchShifter::Process(float* buffer, int bufferSize)
{
PROFILER(PitchShifter);
const int fftFrameSize = mFFTBins;
const int sampleRate = gSampleRate;
const int osamp = mOversampling;
const int numSampsToProcess = bufferSize;
float* indata = buffer;
float* outdata = buffer;
const float pitchShift = mRatio;
double magn, phase, tmp, window, real, imag;
double freqPerBin, expct;
long i, k, qpd, index, inFifoLatency, stepSize, fftFrameSize2;
/* set up some handy variables */
fftFrameSize2 = fftFrameSize / 2;
stepSize = fftFrameSize / osamp;
freqPerBin = sampleRate / (double)fftFrameSize;
expct = 2. * M_PI * (double)stepSize / (double)fftFrameSize;
inFifoLatency = fftFrameSize - stepSize;
if (gRover == false)
gRover = inFifoLatency;
mLatency = inFifoLatency;
/* initialize our static arrays */
if (gInit == false)
{
memset(gInFIFO, 0, MAX_FRAME_LENGTH * sizeof(float));
memset(gOutFIFO, 0, MAX_FRAME_LENGTH * sizeof(float));
memset(gFFTworksp, 0, 2 * MAX_FRAME_LENGTH * sizeof(float));
memset(gLastPhase, 0, (MAX_FRAME_LENGTH / 2 + 1) * sizeof(float));
memset(gSumPhase, 0, (MAX_FRAME_LENGTH / 2 + 1) * sizeof(float));
memset(gOutputAccum, 0, 2 * MAX_FRAME_LENGTH * sizeof(float));
memset(gAnaFreq, 0, MAX_FRAME_LENGTH * sizeof(float));
memset(gAnaMagn, 0, MAX_FRAME_LENGTH * sizeof(float));
gInit = true;
}
/* main processing loop */
for (i = 0; i < numSampsToProcess; i++)
{
/* As long as we have not yet collected enough data just read in */
gInFIFO[gRover] = indata[i];
outdata[i] = gOutFIFO[gRover - inFifoLatency];
gRover++;
/* now we have enough data for processing */
if (gRover >= fftFrameSize)
{
gRover = inFifoLatency;
/* do windowing and re,im interleave */
for (k = 0; k < fftFrameSize; k++)
{
window = -.5 * cos(2. * M_PI * (double)k / (double)fftFrameSize) + .5;
gFFTworksp[2 * k] = gInFIFO[k] * window;
gFFTworksp[2 * k + 1] = 0.;
}
/* ***************** ANALYSIS ******************* */
/* do transform */
smbFft(gFFTworksp, fftFrameSize, -1);
/* this is the analysis step */
for (k = 0; k <= fftFrameSize2; k++)
{
/* de-interlace FFT buffer */
real = gFFTworksp[2 * k];
imag = gFFTworksp[2 * k + 1];
/* compute magnitude and phase */
magn = 2. * sqrt(real * real + imag * imag);
phase = atan2(imag, real);
/* compute phase difference */
tmp = phase - gLastPhase[k];
gLastPhase[k] = phase;
/* subtract expected phase difference */
tmp -= (double)k * expct;
/* map delta phase into +/- Pi interval */
qpd = tmp / M_PI;
if (qpd >= 0)
qpd += qpd & 1;
else
qpd -= qpd & 1;
tmp -= M_PI * (double)qpd;
/* get deviation from bin frequency from the +/- Pi interval */
tmp = osamp * tmp / (2. * M_PI);
/* compute the k-th partials' true frequency */
tmp = (double)k * freqPerBin + tmp * freqPerBin;
/* store magnitude and true frequency in analysis arrays */
gAnaMagn[k] = magn;
gAnaFreq[k] = tmp;
}
/* ***************** PROCESSING ******************* */
/* this does the actual pitch shifting */
memset(gSynMagn, 0, fftFrameSize * sizeof(float));
memset(gSynFreq, 0, fftFrameSize * sizeof(float));
for (k = 0; k <= fftFrameSize2; k++)
{
index = k * pitchShift;
if (index <= fftFrameSize2)
{
gSynMagn[index] += gAnaMagn[k];
gSynFreq[index] = gAnaFreq[k] * pitchShift;
}
}
/* ***************** SYNTHESIS ******************* */
/* this is the synthesis step */
for (k = 0; k <= fftFrameSize2; k++)
{
/* get magnitude and true frequency from synthesis arrays */
magn = gSynMagn[k];
tmp = gSynFreq[k];
/* subtract bin mid frequency */
tmp -= (double)k * freqPerBin;
/* get bin deviation from freq deviation */
tmp /= freqPerBin;
/* take osamp into account */
tmp = 2. * M_PI * tmp / osamp;
/* add the overlap phase advance back in */
tmp += (double)k * expct;
/* accumulate delta phase to get bin phase */
gSumPhase[k] += tmp;
phase = gSumPhase[k];
/* get real and imag part and re-interleave */
gFFTworksp[2 * k] = magn * cos(phase);
gFFTworksp[2 * k + 1] = magn * sin(phase);
}
/* zero negative frequencies */
for (k = fftFrameSize + 2; k < 2 * fftFrameSize; k++)
gFFTworksp[k] = 0.;
/* do inverse transform */
smbFft(gFFTworksp, fftFrameSize, 1);
/* do windowing and add to output accumulator */
for (k = 0; k < fftFrameSize; k++)
{
window = -.5 * cos(2. * M_PI * (double)k / (double)fftFrameSize) + .5;
gOutputAccum[k] += 2. * window * gFFTworksp[2 * k] / (fftFrameSize2 * osamp);
}
for (k = 0; k < stepSize; k++)
gOutFIFO[k] = gOutputAccum[k];
/* shift accumulator */
memmove(gOutputAccum, gOutputAccum + stepSize, fftFrameSize * sizeof(float));
/* move input FIFO */
for (k = 0; k < inFifoLatency; k++)
gInFIFO[k] = gInFIFO[k + stepSize];
}
}
}
#endif
``` | /content/code_sandbox/Source/PitchShifter.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 4,293 |
```objective-c
#pragma once
enum class QwertyToPitchMappingMode
{
Ableton,
Fruity
};
struct QwertyToPitchResponse
{
public:
int mPitch{ -1 };
int mOctaveShift{ 0 };
};
class QwertyToPitchMapping
{
public:
static QwertyToPitchResponse GetPitchForComputerKey(int key);
};
``` | /content/code_sandbox/Source/QwertyToPitchMapping.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 83 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Vocoder.h
// modularSynth
//
// Created by Ryan Challinor on 4/17/13.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "FFT.h"
#include "Slider.h"
#include "GateEffect.h"
#include "BiquadFilterEffect.h"
#include "VocoderCarrierInput.h"
#define VOCODER_WINDOW_SIZE 1024
#define FFT_FREQDOMAIN_SIZE VOCODER_WINDOW_SIZE / 2 + 1
class Vocoder : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public VocoderBase, public IIntSliderListener
{
public:
Vocoder();
virtual ~Vocoder();
static IDrawableModule* Create() { return new Vocoder(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void SetCarrierBuffer(float* carrier, int bufferSize) override;
//IAudioProcessor
InputMode GetInputMode() override { return kInputMode_Mono; }
//IAudioSource
void Process(double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 235;
h = 170;
}
FFTData mFFTData{ VOCODER_WINDOW_SIZE, FFT_FREQDOMAIN_SIZE };
float* mWindower{ nullptr };
::FFT mFFT{ VOCODER_WINDOW_SIZE };
RollingBuffer mRollingInputBuffer{ VOCODER_WINDOW_SIZE };
RollingBuffer mRollingOutputBuffer{ VOCODER_WINDOW_SIZE };
float* mCarrierInputBuffer{ nullptr };
RollingBuffer mRollingCarrierBuffer{ VOCODER_WINDOW_SIZE };
FFTData mCarrierFFTData{ VOCODER_WINDOW_SIZE, FFT_FREQDOMAIN_SIZE };
float mInputPreamp{ 1 };
float mCarrierPreamp{ 1 };
float mVolume{ 1 };
FloatSlider* mInputSlider{ nullptr };
FloatSlider* mCarrierSlider{ nullptr };
FloatSlider* mVolumeSlider{ nullptr };
float mDryWet{ 1 };
FloatSlider* mDryWetSlider{ nullptr };
float mFricativeThresh{ .07 };
FloatSlider* mFricativeSlider{ nullptr };
bool mFricDetected{ false };
float mWhisper{ 0 };
FloatSlider* mWhisperSlider{ nullptr };
float mPhaseOffset{ 0 };
FloatSlider* mPhaseOffsetSlider{ nullptr };
int mCut{ 1 };
IntSlider* mCutSlider{ nullptr };
GateEffect mGate;
bool mCarrierDataSet{ false };
};
``` | /content/code_sandbox/Source/Vocoder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 819 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// DotSequencer.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/27/23.
//
//
#include "DotSequencer.h"
#include "SynthGlobals.h"
#include "UIControlMacros.h"
#include "FileStream.h"
#include "Scale.h"
DotSequencer::DotSequencer()
{
}
void DotSequencer::Init()
{
IDrawableModule::Init();
mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), true);
TheTransport->AddAudioPoller(this);
}
void DotSequencer::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 40);
UIBLOCK_SHIFTRIGHT();
INTSLIDER(mColsSlider, "cols", &mCols, 1, 64);
UIBLOCK_SHIFTRIGHT();
INTSLIDER(mRowsSlider, "rows", &mRows, 1, 64);
UIBLOCK_SHIFTRIGHT();
DROPDOWN(mNoteModeSelector, "notemode", (int*)(&mNoteMode), 80);
UIBLOCK_NEWLINE();
INTSLIDER(mOctaveSlider, "octave", &mOctave, 0, 8);
UIBLOCK_SHIFTRIGHT();
INTSLIDER(mRowOffsetSlider, "row offset", &mRowOffset, -12, 12);
UIBLOCK_SHIFTRIGHT();
BUTTON(mClearButton, "clear");
UIBLOCK_SHIFTRIGHT();
BUTTON(mDoubleButton, "double");
UIBLOCK_NEWLINE();
UIBLOCK_SHIFTX(40);
UIBLOCK_SHIFTY(25);
UICONTROL_CUSTOM(mDotGrid, new DotGrid(UICONTROL_BASICS("dotgrid"), 210, 210, mCols, mRows));
ENDUIBLOCK(mWidth, mHeight);
AddUIControl(mDotGrid);
mDotGrid->SetMajorColSize(4);
mIntervalSelector->AddLabel("4", kInterval_4);
mIntervalSelector->AddLabel("3", kInterval_3);
mIntervalSelector->AddLabel("2", kInterval_2);
mIntervalSelector->AddLabel("1n", kInterval_1n);
mIntervalSelector->AddLabel("2n", kInterval_2n);
mIntervalSelector->AddLabel("4n", kInterval_4n);
mIntervalSelector->AddLabel("4nt", kInterval_4nt);
mIntervalSelector->AddLabel("8n", kInterval_8n);
mIntervalSelector->AddLabel("8nt", kInterval_8nt);
mIntervalSelector->AddLabel("16n", kInterval_16n);
mIntervalSelector->AddLabel("16nt", kInterval_16nt);
mIntervalSelector->AddLabel("32n", kInterval_32n);
mIntervalSelector->AddLabel("64n", kInterval_64n);
mNoteModeSelector->AddLabel("scale", (int)NoteMode::Scale);
mNoteModeSelector->AddLabel("chromatic", (int)NoteMode::Chromatic);
Resize(mWidth, mHeight);
}
DotSequencer::~DotSequencer()
{
TheTransport->RemoveListener(this);
TheTransport->RemoveAudioPoller(this);
}
void DotSequencer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
ofPushStyle();
ofSetLineWidth(mDotGrid->GetDotSize() * .25f);
float ysize = mHeight / mDotGrid->GetRows();
for (int i = 0; i < mDotGrid->GetRows(); ++i)
{
ofVec2f pos = mDotGrid->GetCellPosition(0, i - 1) + mDotGrid->GetPosition(true);
ofVec2f lineAcrossStart(pos.x + 5, pos.y - ysize * .5f + 2);
ofVec2f lineAcrossEnd(pos.x + mDotGrid->GetWidth() - 10, pos.y - ysize * .5f + 2);
if (RowToPitch(i) % TheScale->GetPitchesPerOctave() == TheScale->ScaleRoot() % TheScale->GetPitchesPerOctave())
{
ofSetColor(0, 255, 0, gModuleDrawAlpha * .05f);
ofLine(lineAcrossStart, lineAcrossEnd);
ofSetColor(0, 255, 0, gModuleDrawAlpha * .8f);
}
else if (TheScale->GetPitchesPerOctave() == 12 && RowToPitch(i) % TheScale->GetPitchesPerOctave() == (TheScale->ScaleRoot() + 7) % TheScale->GetPitchesPerOctave())
{
ofSetColor(200, 150, 0, gModuleDrawAlpha * .05f);
ofLine(lineAcrossStart, lineAcrossEnd);
ofSetColor(200, 150, 0, gModuleDrawAlpha * .8f);
}
else if (mNoteMode == NoteMode::Chromatic && TheScale->IsInScale(RowToPitch(i)))
{
ofSetColor(175, 100, 0, gModuleDrawAlpha * .05f);
ofLine(lineAcrossStart, lineAcrossEnd);
ofSetColor(175, 100, 0, gModuleDrawAlpha * .8f);
}
else
{
ofSetColor(128, 128, 128, gModuleDrawAlpha * .8f);
}
float scale = std::min(mDotGrid->IClickable::GetDimensions().y / mDotGrid->GetRows() - 2, 10.0f);
DrawTextRightJustify(NoteName(RowToPitch(i), false, true) + "(" + ofToString(RowToPitch(i)) + ")", pos.x - 3, pos.y - ysize * .5f + (scale / 2), scale);
}
ofPopStyle();
mIntervalSelector->Draw();
mNoteModeSelector->Draw();
mClearButton->Draw();
mOctaveSlider->Draw();
mColsSlider->Draw();
mRowsSlider->Draw();
mRowOffsetSlider->Draw();
mDoubleButton->Draw();
mDotGrid->Draw();
}
void DotSequencer::OnTimeEvent(double time)
{
if (mHasExternalPulseSource)
return;
OnStep(time, 1, 0);
}
void DotSequencer::OnStep(double time, float velocity, int flags)
{
if (mEnabled)
{
mStepIdx = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo, mDotGrid->GetCols());
mDotGrid->SetHighlightCol(time, mStepIdx);
for (int row = 0; row < mDotGrid->GetRows(); ++row)
{
const DotGrid::DotData& data = mDotGrid->GetDataAt(mStepIdx, row);
if (data.mOn)
{
int pitch = RowToPitch(row);
if (pitch >= 0 && pitch < 128)
{
bool played = false;
for (int i = 0; i < (int)mPlayingDots.size(); ++i)
{
if (!played && mPlayingDots[i].mPitch == -1)
{
mPlayingDots[i].mPitch = pitch;
mPlayingDots[i].mRow = row;
mPlayingDots[i].mCol = mStepIdx;
mPlayingDots[i].mPlayedTime = time;
played = true;
}
else if (mPlayingDots[i].mPitch == pitch)
{
mNoteOutput.PlayNote(time, pitch, 0); //note off any colliding pitches
mPlayingDots[i].mPitch = -1;
}
}
mNoteOutput.PlayNote(time, pitch, std::max(int(data.mVelocity * 127), 1));
mDotGrid->OnPlayed(time, mStepIdx, row);
}
}
}
}
}
void DotSequencer::OnTransportAdvanced(float amount)
{
for (int i = 0; i < (int)mPlayingDots.size(); ++i)
{
if (mPlayingDots[i].mPitch != -1)
{
const DotGrid::DotData& data = mDotGrid->GetDataAt(mPlayingDots[i].mCol, mPlayingDots[i].mRow);
double noteOffTime = -1;
if (data.mOn == false || mStepIdx < mPlayingDots[i].mCol)
{
noteOffTime = NextBufferTime(!K(includeLookahead));
}
else
{
double noteEnd = mPlayingDots[i].mPlayedTime + TheTransport->GetDuration(mInterval) * std::max(.5f, data.mLength);
if (noteEnd < NextBufferTime(K(includeLookahead)))
noteOffTime = noteEnd;
}
if (noteOffTime != -1)
{
mNoteOutput.PlayNote(noteOffTime, mPlayingDots[i].mPitch, 0);
mPlayingDots[i].mPitch = -1;
}
}
}
if (mShouldStopAllNotes)
{
for (int i = 0; i < (int)mPlayingDots.size(); ++i)
{
if (mPlayingDots[i].mPitch != -1)
{
mNoteOutput.PlayNote(NextBufferTime(!K(includeLookahead)), mPlayingDots[i].mPitch, 0);
mPlayingDots[i].mPitch = -1;
}
}
mShouldStopAllNotes = false;
}
}
int DotSequencer::RowToPitch(int row) const
{
row += mRowOffset;
int numTonesInScale = TheScale->NumTonesInScale();
switch (mNoteMode)
{
case NoteMode::Scale:
return TheScale->GetPitchFromTone(row + mOctave * numTonesInScale + TheScale->GetScaleDegree());
case NoteMode::Chromatic:
return row + mOctave * TheScale->GetPitchesPerOctave();
}
return row;
}
bool DotSequencer::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll)
{
mDotGrid->NotifyMouseScrolled(x, y, scrollX, scrollY, isSmoothScroll, isInvertedScroll);
return false;
}
void DotSequencer::Resize(float w, float h)
{
mWidth = w;
mHeight = h;
ofVec2f gridPos = mDotGrid->GetPosition(K(local));
mDotGrid->SetDimensions(w - 8 - gridPos.x, h - 5 - gridPos.y);
}
void DotSequencer::GetModuleDimensions(float& width, float& height)
{
width = mWidth;
height = mHeight;
}
void DotSequencer::ButtonClicked(ClickButton* button, double time)
{
if (button == mClearButton)
mDotGrid->Clear();
if (button == mDoubleButton)
{
if (mCols * 2 <= mDotGrid->GetMaxColumns())
{
mCols *= 2;
mDotGrid->SetGrid(mCols, mRows);
for (int col = 0; col < mCols / 2; ++col)
{
for (int row = 0; row < mRows; ++row)
mDotGrid->CopyDot(DotGrid::DotPosition(col, row), DotGrid::DotPosition(col + mCols / 2, row));
}
}
}
}
void DotSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mIntervalSelector)
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
transportListenerInfo->mInterval = mInterval;
if (Transport::IsTripletInterval(mInterval))
mDotGrid->SetMajorColSize(3);
else
mDotGrid->SetMajorColSize(4);
}
}
void DotSequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mColsSlider || slider == mRowsSlider)
mDotGrid->SetGrid(mCols, mRows);
}
void DotSequencer::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
if (!mEnabled)
mShouldStopAllNotes = true;
}
}
void DotSequencer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void DotSequencer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
void DotSequencer::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << (int)mInterval;
out << mHasExternalPulseSource;
out << mWidth;
out << mHeight;
mDotGrid->SaveState(out);
}
void DotSequencer::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
int interval;
in >> interval;
mInterval = (NoteInterval)interval;
in >> mHasExternalPulseSource;
in >> mWidth;
in >> mHeight;
Resize(mWidth, mHeight);
mDotGrid->LoadState(in);
}
``` | /content/code_sandbox/Source/DotSequencer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,139 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// NoteFlusher.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/23/14.
//
//
#include "NoteFlusher.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
NoteFlusher::NoteFlusher()
{
}
void NoteFlusher::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mFlushButton = new ClickButton(this, "flush", 5, 2);
}
void NoteFlusher::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mFlushButton->Draw();
}
void NoteFlusher::ButtonClicked(ClickButton* button, double time)
{
if (button == mFlushButton)
{
mNoteOutput.Flush(time);
for (int i = 0; i < 127; ++i)
mNoteOutput.PlayNote(time, i, 0);
}
}
void NoteFlusher::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteFlusher::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteFlusher.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 361 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
MPESmoother.cpp
Created: 4 Aug 2021 9:45:26pm
Author: Ryan Challinor
==============================================================================
*/
#include "MPESmoother.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
MPESmoother::MPESmoother()
{
}
MPESmoother::~MPESmoother()
{
TheTransport->RemoveAudioPoller(this);
}
void MPESmoother::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
void MPESmoother::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK(110);
FLOATSLIDER(mPitchSmoothSlider, "pitch", &mPitchSmooth, 0, 1);
FLOATSLIDER(mPressureSmoothSlider, "pressure", &mPressureSmooth, 0, 1);
FLOATSLIDER(mModWheelSmoothSlider, "modwheel", &mModWheelSmooth, 0, 1);
ENDUIBLOCK(mWidth, mHeight);
mPitchSmoothSlider->SetMode(FloatSlider::kSquare);
mPressureSmoothSlider->SetMode(FloatSlider::kSquare);
mModWheelSmoothSlider->SetMode(FloatSlider::kSquare);
}
void MPESmoother::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mPitchSmoothSlider->Draw();
mPressureSmoothSlider->Draw();
mModWheelSmoothSlider->Draw();
}
void MPESmoother::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled && voiceIdx >= 0 && voiceIdx < kNumVoices)
{
mModulationInput[voiceIdx].pitchBend = modulation.pitchBend;
if (velocity > 0 && modulation.pitchBend != nullptr)
mModulationOutput[voiceIdx].mPitchBend.SetValue(modulation.pitchBend->GetValue(0));
modulation.pitchBend = &mModulationOutput[voiceIdx].mPitchBend;
mModulationInput[voiceIdx].pressure = modulation.pressure;
if (velocity > 0 && modulation.pressure != nullptr)
mModulationOutput[voiceIdx].mPressure.SetValue(modulation.pressure->GetValue(0));
modulation.pressure = &mModulationOutput[voiceIdx].mPressure;
mModulationInput[voiceIdx].modWheel = modulation.modWheel;
if (velocity > 0 && modulation.modWheel != nullptr)
mModulationOutput[voiceIdx].mModWheel.SetValue(modulation.modWheel->GetValue(0));
modulation.modWheel = &mModulationOutput[voiceIdx].mModWheel;
}
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void MPESmoother::OnTransportAdvanced(float amount)
{
const float kSmoothTime = 100;
for (int i = 0; i < kNumVoices; ++i)
{
if (mModulationInput[i].pitchBend != nullptr)
mModulationOutput[i].mPitchBend.RampValue(gTime, mModulationOutput[i].mPitchBend.GetValue(0), mModulationInput[i].pitchBend->GetValue(0), (amount * TheTransport->MsPerBar() * (mPitchSmooth * kSmoothTime)));
if (mModulationInput[i].pressure != nullptr)
mModulationOutput[i].mPressure.RampValue(gTime, mModulationOutput[i].mPressure.GetValue(0), mModulationInput[i].pressure->GetValue(0), (amount * TheTransport->MsPerBar() * (mPressureSmooth * kSmoothTime)));
if (mModulationInput[i].modWheel != nullptr)
mModulationOutput[i].mModWheel.RampValue(gTime, mModulationOutput[i].mModWheel.GetValue(0), mModulationInput[i].modWheel->GetValue(0), (amount * TheTransport->MsPerBar() * (mModWheelSmooth * kSmoothTime)));
}
}
void MPESmoother::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void MPESmoother::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void MPESmoother::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void MPESmoother::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/MPESmoother.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,097 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// PerformanceTimer.h
// Bespoke
//
// Created by Ryan Challinor on 3/26/15.
//
//
#pragma once
#include "OpenFrameworksPort.h"
class PerformanceTimer;
class TimerInstance
{
public:
TimerInstance(std::string name, PerformanceTimer& manager);
~TimerInstance();
private:
long mTimerStart;
std::string mName;
PerformanceTimer& mManager;
};
class PerformanceTimer
{
public:
void RecordCost(std::string name, long cost);
void PrintCosts();
private:
struct Cost
{
Cost(std::string name, long cost)
: mName(name)
, mCost(cost)
{}
std::string mName;
long mCost;
};
static bool SortCosts(const PerformanceTimer::Cost& a, const PerformanceTimer::Cost& b);
std::vector<Cost> mCostTable;
};
``` | /content/code_sandbox/Source/PerformanceTimer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 289 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// NoteTable.cpp
// modularSynth
//
// Created by Ryan Challinor on 11/1/21
//
//
#include "NoteTable.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
#include "PatchCableSource.h"
#include "MathUtils.h"
NoteTable::NoteTable()
{
for (size_t i = 0; i < mLastColumnPlayTime.size(); ++i)
mLastColumnPlayTime[i] = -1;
for (size_t i = 0; i < mPitchPlayTimes.size(); ++i)
mPitchPlayTimes[i] = -1;
for (size_t i = 0; i < mQueuedPitches.size(); ++i)
mQueuedPitches[i] = false;
}
void NoteTable::CreateUIControls()
{
IDrawableModule::CreateUIControls();
float width, height;
UIBLOCK(140);
INTSLIDER(mLengthSlider, "length", &mLength, 1, kMaxLength);
UIBLOCK_SHIFTRIGHT();
INTSLIDER(mOctaveSlider, "octave", &mOctave, 0, 7);
UIBLOCK_SHIFTRIGHT();
DROPDOWN(mNoteModeSelector, "notemode", (int*)(&mNoteMode), 80);
UIBLOCK_NEWLINE();
BUTTON(mRandomizePitchButton, "random pitch");
UIBLOCK_SHIFTRIGHT();
FLOATSLIDER_DIGITS(mRandomizePitchChanceSlider, "rand pitch chance", &mRandomizePitchChance, 0, 1, 2);
UIBLOCK_SHIFTRIGHT();
FLOATSLIDER_DIGITS(mRandomizePitchRangeSlider, "rand pitch range", &mRandomizePitchRange, 0, 1, 2);
UIBLOCK_NEWLINE();
BUTTON(mClearButton, "clear");
UIBLOCK_SHIFTRIGHT();
UICONTROL_CUSTOM(mGridControlTarget, new GridControlTarget(UICONTROL_BASICS("grid")));
UIBLOCK_SHIFTRIGHT();
INTSLIDER(mGridControlOffsetXSlider, "x offset", &mGridControlOffsetX, 0, 16);
UIBLOCK_SHIFTRIGHT();
INTSLIDER(mGridControlOffsetYSlider, "y offset", &mGridControlOffsetY, 0, 16);
ENDUIBLOCK(width, height);
mGrid = new UIGrid("uigrid", 5, height + 18, width - 10, 110, mLength, mNoteRange, this);
mNoteModeSelector->AddLabel("scale", kNoteMode_Scale);
mNoteModeSelector->AddLabel("chromatic", kNoteMode_Chromatic);
mNoteModeSelector->AddLabel("pentatonic", kNoteMode_Pentatonic);
mNoteModeSelector->AddLabel("5ths", kNoteMode_Fifths);
mGrid->SetFlip(true);
mGrid->SetListener(this);
for (int i = 0; i < kMaxLength; ++i)
{
mColumnCables[i] = new AdditionalNoteCable();
mColumnCables[i]->SetPatchCableSource(new PatchCableSource(this, kConnectionType_Note));
mColumnCables[i]->GetPatchCableSource()->SetOverrideCableDir(ofVec2f(0, 1), PatchCableSource::Side::kBottom);
AddPatchCableSource(mColumnCables[i]->GetPatchCableSource());
}
}
NoteTable::~NoteTable()
{
}
void NoteTable::Init()
{
IDrawableModule::Init();
}
void NoteTable::Poll()
{
UpdateGridControllerLights(false);
}
void NoteTable::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
ofSetColor(255, 255, 255, gModuleDrawAlpha);
mGridControlOffsetXSlider->SetShowing((mGridControlTarget->GetGridController() != nullptr && mLength > mGridControlTarget->GetGridController()->NumCols()) || mPush2GridDisplayMode == Push2GridDisplayMode::GridView);
mGridControlOffsetYSlider->SetShowing((mGridControlTarget->GetGridController() != nullptr && mNoteRange > mGridControlTarget->GetGridController()->NumRows()) || mPush2GridDisplayMode == Push2GridDisplayMode::GridView);
mLengthSlider->Draw();
mOctaveSlider->Draw();
mNoteModeSelector->Draw();
mRandomizePitchButton->Draw();
mClearButton->Draw();
mGridControlTarget->Draw();
mGridControlOffsetXSlider->Draw();
mGridControlOffsetYSlider->Draw();
mRandomizePitchChanceSlider->Draw();
mRandomizePitchRangeSlider->Draw();
mGrid->Draw();
ofPushStyle();
ofSetColor(128, 128, 128, gModuleDrawAlpha * .8f);
for (int i = 0; i < mGrid->GetCols(); ++i)
{
ofVec2f pos = mGrid->GetCellPosition(i, mGrid->GetRows() - 1) + mGrid->GetPosition(true);
DrawTextNormal(ofToString(i), pos.x + 1, pos.y - 7);
}
for (int i = 0; i < mGrid->GetRows(); ++i)
{
ofVec2f pos = mGrid->GetCellPosition(0, i - 1) + mGrid->GetPosition(true);
float scale = MIN(mGrid->IClickable::GetDimensions().y / mGrid->GetRows() - 2, 18);
DrawTextNormal(NoteName(RowToPitch(i), false, true) + "(" + ofToString(RowToPitch(i)) + ")", pos.x + 4, pos.y - (scale / 8), scale);
}
ofPopStyle();
if (mGridControlTarget->GetGridController() || mPush2GridDisplayMode == Push2GridDisplayMode::GridView)
{
int controllerCols = 8;
int controllerRows = 8;
if (mGridControlTarget->GetGridController() != nullptr)
{
controllerCols = mGridControlTarget->GetGridController()->NumCols();
controllerRows = mGridControlTarget->GetGridController()->NumRows();
}
ofPushStyle();
ofNoFill();
ofSetLineWidth(4);
ofSetColor(255, 0, 0, 50);
float squareh = float(mGrid->GetHeight()) / mNoteRange;
float squarew = float(mGrid->GetWidth()) / mLength;
ofRectangle gridRect = mGrid->GetRect(K(local));
ofRect(gridRect.x + squarew * mGridControlOffsetX,
gridRect.y + gridRect.height - squareh * (mGridControlOffsetY + controllerRows),
squarew * controllerCols,
squareh * controllerRows);
ofPopStyle();
}
ofPushStyle();
ofFill();
float gridX, gridY, gridW, gridH;
mGrid->GetPosition(gridX, gridY, true);
gridW = mGrid->GetWidth();
gridH = mGrid->GetHeight();
float boxHeight = float(gridH) / mNoteRange;
for (int i = 0; i < mNoteRange; ++i)
{
if (RowToPitch(i) % TheScale->GetPitchesPerOctave() == TheScale->ScaleRoot() % TheScale->GetPitchesPerOctave())
ofSetColor(0, 255, 0, 80);
else if (TheScale->GetPitchesPerOctave() == 12 && RowToPitch(i) % TheScale->GetPitchesPerOctave() == (TheScale->ScaleRoot() + 7) % TheScale->GetPitchesPerOctave())
ofSetColor(200, 150, 0, 80);
else if (mNoteMode == kNoteMode_Chromatic && TheScale->IsInScale(RowToPitch(i)))
ofSetColor(100, 75, 0, 80);
else
continue;
float y = gridY + gridH - i * boxHeight;
ofRect(gridX, y - boxHeight, gridW, boxHeight);
}
for (int i = 0; i < mGrid->GetCols(); ++i)
{
const float kPlayHighlightDurationMs = 250;
if (mLastColumnPlayTime[i] != -1)
{
float fade = ofClamp(1 - (gTime - mLastColumnPlayTime[i]) / kPlayHighlightDurationMs, 0, 1);
ofPushStyle();
ofFill();
ofSetColor(ofColor::white, ofLerp(20, 80, fade));
ofRect(mGrid->GetPosition(true).x + mGrid->GetWidth() / mLength * i, mGrid->GetPosition(true).y, mGrid->GetWidth() / mLength, mGrid->GetHeight());
ofNoFill();
ofSetLineWidth(3 * fade);
for (int row = 0; row < mGrid->GetRows(); ++row)
{
if (mGrid->GetVal(i, row) > 0)
{
ofVec2f pos = mGrid->GetCellPosition(i, row) + mGrid->GetPosition(true);
float xsize = float(mGrid->GetWidth()) / mGrid->GetCols();
float ysize = float(mGrid->GetHeight()) / mGrid->GetRows();
ofSetColor(ofColor::white, fade * 255);
ofRect(pos.x, pos.y, xsize, ysize);
}
}
ofPopStyle();
}
}
float moduleWidth, moduleHeight;
GetModuleDimensions(moduleWidth, moduleHeight);
for (int i = 0; i < kMaxLength; ++i)
{
if (i < mLength && mShowColumnCables)
{
ofVec2f pos = mGrid->GetCellPosition(i, 0) + mGrid->GetPosition(true);
pos.x += mGrid->GetWidth() / float(mLength) * .5f;
pos.y = moduleHeight - 7;
mColumnCables[i]->GetPatchCableSource()->SetManualPosition(pos.x, pos.y);
mColumnCables[i]->GetPatchCableSource()->SetEnabled(true);
}
else
{
mColumnCables[i]->GetPatchCableSource()->SetEnabled(false);
}
}
ofPopStyle();
}
void NoteTable::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
mGrid->TestClick(x, y, right);
}
void NoteTable::MouseReleased()
{
IDrawableModule::MouseReleased();
mGrid->MouseReleased();
}
bool NoteTable::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mGrid->NotifyMouseMoved(x, y);
return false;
}
void NoteTable::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mNoteOutput.Flush(time);
}
void NoteTable::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue)
{
}
int NoteTable::RowToPitch(int row)
{
row += mRowOffset;
int numPitchesInScale = TheScale->NumTonesInScale();
switch (mNoteMode)
{
case kNoteMode_Scale:
return TheScale->GetPitchFromTone(row + mOctave * numPitchesInScale + TheScale->GetScaleDegree());
case kNoteMode_Chromatic:
return row + mOctave * TheScale->GetPitchesPerOctave();
case kNoteMode_Pentatonic:
{
bool isMinor = TheScale->IsInScale(TheScale->ScaleRoot() + 3);
const int minorPentatonic[5] = { 0, 3, 5, 7, 10 };
const int majorPentatonic[5] = { 0, 2, 4, 7, 9 };
if (isMinor)
return TheScale->ScaleRoot() + (row / 5 + mOctave) * TheScale->GetPitchesPerOctave() + minorPentatonic[row % 5];
else
return TheScale->ScaleRoot() + (row / 5 + mOctave) * TheScale->GetPitchesPerOctave() + majorPentatonic[row % 5];
}
case kNoteMode_Fifths:
{
int oct = (row / 2) * numPitchesInScale;
bool isFifth = row % 2 == 1;
int fifths = oct;
if (isFifth)
fifths += 4;
return TheScale->GetPitchFromTone(fifths + mOctave * numPitchesInScale + TheScale->GetScaleDegree());
}
}
return row;
}
int NoteTable::PitchToRow(int pitch)
{
for (int i = 0; i < mGrid->GetRows(); ++i)
{
if (pitch == RowToPitch(i))
return i;
}
return -1;
}
float NoteTable::ExtraWidth() const
{
return 10;
}
float NoteTable::ExtraHeight() const
{
float height = 77;
if (mShowColumnCables)
height += 22;
return height;
}
void NoteTable::GetModuleDimensions(float& width, float& height)
{
width = mGrid->GetWidth() + ExtraWidth();
height = mGrid->GetHeight() + ExtraHeight();
}
void NoteTable::Resize(float w, float h)
{
mGrid->SetDimensions(MAX(w - ExtraWidth(), 210), MAX(h - ExtraHeight(), 80));
}
void NoteTable::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if ((mEnabled || velocity == 0) && pitch < kMaxLength)
PlayColumn(time, pitch, velocity, voiceIdx, modulation);
}
void NoteTable::PlayColumn(double time, int column, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (velocity == 0)
{
mLastColumnPlayTime[column] = -1;
for (int i = 0; i < 128; ++i)
{
if (mLastColumnNoteOnPitches[column][i])
{
PlayNoteOutput(time, i, 0, voiceIdx, modulation);
mColumnCables[column]->PlayNoteOutput(time, i, 0, voiceIdx, modulation);
mLastColumnNoteOnPitches[column][i] = false;
}
}
}
else
{
mLastColumnPlayTime[column] = time;
for (int row = 0; row < mGrid->GetRows(); ++row)
{
int outputPitch = RowToPitch(row);
if (mQueuedPitches[outputPitch])
{
mGrid->SetVal(column, row, 1);
mQueuedPitches[outputPitch] = false;
}
if (mGrid->GetVal(column, row) == 0)
continue;
PlayNoteOutput(time, outputPitch, velocity, voiceIdx, modulation);
mColumnCables[column]->PlayNoteOutput(time, outputPitch, velocity, voiceIdx, modulation);
mLastColumnNoteOnPitches[column][outputPitch] = true;
mPitchPlayTimes[outputPitch] = time;
}
}
}
void NoteTable::UpdateGridControllerLights(bool force)
{
if (mGridControlTarget->GetGridController())
{
for (int x = 0; x < mGridControlTarget->GetGridController()->NumCols(); ++x)
{
for (int y = 0; y < mGridControlTarget->GetGridController()->NumRows(); ++y)
{
int column = x + mGridControlOffsetX;
int row = y - mGridControlOffsetY;
GridColor color = GridColor::kGridColorOff;
if (column < mLength)
{
if (mGrid->GetVal(column, row) > 0)
{
if (mLastColumnPlayTime[column] + 80 > gTime)
color = GridColor::kGridColor3Bright;
else
color = GridColor::kGridColor1Bright;
}
}
mGridControlTarget->GetGridController()->SetLight(x, y, color, force);
}
}
}
}
void NoteTable::OnControllerPageSelected()
{
UpdateGridControllerLights(true);
}
void NoteTable::OnGridButton(int x, int y, float velocity, IGridController* grid)
{
int col = x + mGridControlOffsetX;
int row = y - mGridControlOffsetY;
if (grid == mGridControlTarget->GetGridController() && col >= 0 && col < mLength && velocity > 0)
{
mGrid->SetVal(col, row, mGrid->GetVal(col, row) > 0 ? 0 : 1);
UpdateGridControllerLights(false);
}
}
void NoteTable::ButtonClicked(ClickButton* button, double time)
{
if (button == mRandomizePitchButton)
RandomizePitches(GetKeyModifiers() & kModifier_Shift);
if (button == mClearButton)
mGrid->Clear();
}
void NoteTable::RandomizePitches(bool fifths)
{
if (fifths)
{
for (int i = 0; i < mLength; ++i)
{
if (ofRandom(1) <= mRandomizePitchChance)
{
switch (gRandom() % 5)
{
default:
SetColumnRow(i, 0);
break;
case 1:
SetColumnRow(i, 4);
break;
case 2:
SetColumnRow(i, 7);
break;
case 3:
SetColumnRow(i, 11);
break;
case 4:
SetColumnRow(i, 14);
break;
}
}
}
}
else
{
for (int i = 0; i < mLength; ++i)
{
if (ofRandom(1) <= mRandomizePitchChance)
{
int row = ofRandom(0, mNoteRange);
for (int j = 0; j < mNoteRange; ++j)
{
if (mGrid->GetVal(i, j) > 0)
row = j;
}
float minValue = MAX(0, row - mNoteRange * mRandomizePitchRange);
float maxValue = MIN(mNoteRange, row + mNoteRange * mRandomizePitchRange);
if (minValue != maxValue)
SetColumnRow(i, ofClamp(int(ofRandom(minValue, maxValue) + .5f), 0, mNoteRange - 1));
}
}
}
}
void NoteTable::SetColumnRow(int column, int row)
{
for (int i = 0; i < mNoteRange; ++i)
mGrid->SetVal(column, i, i == row ? 1 : 0, false);
}
void NoteTable::GetPush2Layout(int& sequenceRows, int& pitchCols, int& pitchRows)
{
sequenceRows = (mLength - 1) / 8 + 1;
if (mNoteMode == kNoteMode_Scale && TheScale->NumTonesInScale() == 7)
pitchCols = 7;
else
pitchCols = 8;
pitchRows = (mNoteRange - 1) / pitchCols + 1;
}
bool NoteTable::OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue)
{
if (mPush2GridDisplayMode == Push2GridDisplayMode::PerStep)
{
int sequenceRows, pitchCols, pitchRows;
GetPush2Layout(sequenceRows, pitchCols, pitchRows);
if (type == kMidiMessage_Note)
{
if (controlIndex >= 36 && controlIndex <= 99)
{
int gridIndex = controlIndex - 36;
int x = gridIndex % 8;
int y = 7 - gridIndex / 8;
if (y < sequenceRows)
{
int index = x + y * 8;
if (midiValue > 0)
mPush2HeldStep = index;
else if (index == mPush2HeldStep)
mPush2HeldStep = -1;
}
else if (y < sequenceRows + pitchRows)
{
if (midiValue > 0)
{
int index = x + (pitchRows - 1 - (y - sequenceRows)) * pitchCols;
if (index < 0 || index >= mNoteRange)
{
//out of range, do nothing
}
else if (mPush2HeldStep != -1)
{
mGrid->SetVal(mPush2HeldStep, index, mGrid->GetVal(mPush2HeldStep, index) > 0 ? 0 : 1);
}
else
{
//I'm not liking this "queued pitch" behavior, let's disable it for now
//mQueuedPitches[RowToPitch(index)] = true;
}
}
}
return true;
}
}
}
else if (mPush2GridDisplayMode == Push2GridDisplayMode::GridView)
{
if (type == kMidiMessage_Note)
{
int gridIndex = controlIndex - 36;
int x = gridIndex % 8;
int y = gridIndex / 8;
int col = x + mGridControlOffsetX;
int row = y + mGridControlOffsetY;
if (gridIndex >= 0 && gridIndex < 64 &&
col >= 0 && col < mLength &&
row >= 0 && row < mNoteRange)
{
if (midiValue > 0)
{
mPush2HeldStep = col;
mGrid->SetVal(mPush2HeldStep, row, mGrid->GetVal(mPush2HeldStep, row) > 0 ? 0 : 1);
}
else
{
mPush2HeldStep = -1;
}
}
return true;
}
}
if (type == kMidiMessage_Control)
{
if (controlIndex == push2->GetGridControllerOption1Control())
{
if (midiValue > 0)
{
if (mPush2GridDisplayMode == Push2GridDisplayMode::PerStep)
mPush2GridDisplayMode = Push2GridDisplayMode::GridView;
else
mPush2GridDisplayMode = Push2GridDisplayMode::PerStep;
}
return true;
}
}
return false;
}
void NoteTable::UpdatePush2Leds(Push2Control* push2)
{
int sequenceRows, pitchCols, pitchRows;
GetPush2Layout(sequenceRows, pitchCols, pitchRows);
for (int x = 0; x < 8; ++x)
{
for (int y = 0; y < 8; ++y)
{
int pushColor = 0;
if (mPush2GridDisplayMode == Push2GridDisplayMode::PerStep)
{
if (y < sequenceRows)
{
int index = x + y * 8;
if (index >= mLength)
pushColor = 0;
else if (index == mPush2HeldStep)
pushColor = 125;
else if (mLastColumnPlayTime[index] != -1)
pushColor = 101;
else
pushColor = 93;
}
else if (y < sequenceRows + pitchRows)
{
int index = x + (pitchRows - 1 - (y - sequenceRows)) * pitchCols;
int pitch = RowToPitch(index);
if (x >= pitchCols || index >= mNoteRange)
pushColor = 0;
else if (mPush2HeldStep != -1 && mGrid->GetVal(mPush2HeldStep, index) > 0)
pushColor = 127;
else if (mPush2HeldStep == -1 && mNoteOutput.GetNotes()[pitch])
pushColor = gTime - mPitchPlayTimes[pitch] < 100 ? 127 : 2;
else if (mQueuedPitches[pitch])
pushColor = 126;
else if (TheScale->IsRoot(pitch))
pushColor = 69;
else if (TheScale->IsInPentatonic(pitch))
pushColor = 77;
else
pushColor = 78;
}
}
else if (mPush2GridDisplayMode == Push2GridDisplayMode::GridView)
{
int column = x + mGridControlOffsetX;
int row = (7 - y) + mGridControlOffsetY;
if (column >= 0 && column < mLength && row >= 0 && row < mNoteRange)
{
bool isHighlightCol = mLastColumnPlayTime[column] != -1;
int pitch = RowToPitch(row);
if (isHighlightCol && mPush2HeldStep == -1 && mNoteOutput.GetNotes()[pitch])
pushColor = gTime - mPitchPlayTimes[pitch] < 100 ? 127 : 2;
else if (mGrid->GetVal(column, row) > 0)
pushColor = 125;
else if (mQueuedPitches[pitch])
pushColor = 126;
else if (isHighlightCol)
pushColor = 83;
else if (TheScale->IsRoot(pitch))
pushColor = 69;
else if (TheScale->IsInPentatonic(pitch))
pushColor = 77;
else
pushColor = 78;
/*bool isHighlightCol = mLastColumnPlayTime[column] != -1;
int pitch = RowToPitch(row);
if (TheScale->IsRoot(pitch))
pushColor = 69;
else if (TheScale->IsInPentatonic(pitch))
pushColor = 77;
else
pushColor = 78;
if (isHighlightCol)
pushColor = 83;
if (mTones[column] == 8 - 1 - row && mVels[column] > 0)
{
if (column == mPush2HeldStep)
pushColor = 127;
else if (isHighlightCol)
pushColor = 126;
else
pushColor = mNoteLengths[column] == 1 ? 125 : 95;
}*/
}
}
push2->SetLed(kMidiMessage_Note, x + (7 - y) * 8 + 36, pushColor);
}
}
push2->SetLed(kMidiMessage_Control, push2->GetGridControllerOption1Control(), 127);
}
void NoteTable::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mNoteModeSelector)
{
if (mNoteMode != oldVal)
mRowOffset = 0;
}
}
void NoteTable::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mLengthSlider)
{
mLength = MIN(mLength, kMaxLength);
if (mLength > oldVal)
{
//slice the loop into the nearest power of 2 and loop new steps from there
int oldLengthPow2 = std::max(1, MathUtils::HighestPow2(oldVal));
for (int i = oldVal; i < mLength; ++i)
{
int loopedFrom = i % oldLengthPow2;
for (int row = 0; row < mGrid->GetRows(); ++row)
mGrid->SetVal(i, row, mGrid->GetVal(loopedFrom, row));
}
}
mGrid->SetGrid(mLength, mNoteRange);
if (mGridControlTarget->GetGridController())
{
int maxXOffset = mLength - mGridControlTarget->GetGridController()->NumCols();
if (maxXOffset >= 0)
mGridControlOffsetXSlider->SetExtents(0, maxXOffset);
int maxYOffset = mNoteRange - mGridControlTarget->GetGridController()->NumRows();
if (maxYOffset >= 0)
mGridControlOffsetYSlider->SetExtents(0, maxYOffset);
mGridControlOffsetX = MAX(MIN(mGridControlOffsetX, maxXOffset), 0);
mGridControlOffsetY = MAX(MIN(mGridControlOffsetY, maxYOffset), 0);
}
}
if (slider == mGridControlOffsetXSlider || slider == mGridControlOffsetYSlider)
UpdateGridControllerLights(false);
}
void NoteTable::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void NoteTable::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadInt("gridrows", moduleInfo, 15, 1, 127, K(isTextField));
mModuleSaveData.LoadBool("columncables", moduleInfo, false);
SetUpFromSaveData();
}
void NoteTable::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mNoteRange = mModuleSaveData.GetInt("gridrows");
mShowColumnCables = mModuleSaveData.GetBool("columncables");
mGrid->SetGrid(mLength, mNoteRange);
}
void NoteTable::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mGrid->SaveState(out);
out << mGrid->GetWidth();
out << mGrid->GetHeight();
}
void NoteTable::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
mGrid->LoadState(in);
GridUpdated(mGrid, 0, 0, 0, 0);
if (rev >= 3)
{
float width, height;
in >> width;
in >> height;
mGrid->SetDimensions(width, height);
}
}
``` | /content/code_sandbox/Source/NoteTable.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 6,893 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// MidiClockIn.cpp
// Bespoke
//
// Created by Ryan Challinor on 1/1/22.
//
//
#include "MidiClockIn.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
#include "Transport.h"
MidiClockIn::MidiClockIn()
: mDevice(this)
{
mTempoHistory.fill(0);
}
MidiClockIn::~MidiClockIn()
{
}
void MidiClockIn::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK(3, 3, 120);
DROPDOWN(mDeviceList, "device", &mDeviceIndex, 120);
DROPDOWN(mTempoRoundModeList, "rounding", ((int*)&mTempoRoundMode), 50);
FLOATSLIDER(mStartOffsetMsSlider, "start offset ms", &mStartOffsetMs, -300, 300);
INTSLIDER(mSmoothAmountSlider, "smoothing", &mSmoothAmount, 1, (int)mTempoHistory.size());
ENDUIBLOCK(mWidth, mHeight);
mTempoRoundModeList->DrawLabel(true);
mTempoRoundModeList->AddLabel("none", (int)TempoRoundMode::kNone);
mTempoRoundModeList->AddLabel("1", (int)TempoRoundMode::kWhole);
mTempoRoundModeList->AddLabel(".5", (int)TempoRoundMode::kHalf);
mTempoRoundModeList->AddLabel(".25", (int)TempoRoundMode::kQuarter);
mTempoRoundModeList->AddLabel(".1", (int)TempoRoundMode::kTenth);
mHeight += 20;
}
void MidiClockIn::Init()
{
IDrawableModule::Init();
InitDevice();
}
void MidiClockIn::InitDevice()
{
BuildDeviceList();
const std::vector<std::string>& devices = mDevice.GetPortList(true);
for (int i = 0; i < devices.size(); ++i)
{
if (strcmp(devices[i].c_str(), mDevice.Name()) == 0)
mDeviceIndex = i;
}
}
float MidiClockIn::GetRoundedTempo()
{
float avgTempo = 0;
int temposToCount = std::min((int)mTempoHistory.size(), mSmoothAmount);
for (int i = 0; i < temposToCount; ++i)
avgTempo += mTempoHistory[(mTempoIdx - 1 - i + (int)mTempoHistory.size()) % (int)mTempoHistory.size()];
avgTempo /= temposToCount;
switch (mTempoRoundMode)
{
case TempoRoundMode::kNone:
return avgTempo;
case TempoRoundMode::kWhole:
return round(avgTempo);
case TempoRoundMode::kHalf:
return round(avgTempo * 2) / 2;
case TempoRoundMode::kQuarter:
return round(avgTempo * 4) / 4;
case TempoRoundMode::kTenth:
return round(avgTempo * 10) / 10;
}
return avgTempo;
}
void MidiClockIn::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mDeviceList->Draw();
mTempoRoundModeList->Draw();
mStartOffsetMsSlider->Draw();
mSmoothAmountSlider->Draw();
DrawTextNormal("tempo: " + ofToString(GetRoundedTempo()), 4, mHeight - 5);
}
void MidiClockIn::DrawModuleUnclipped()
{
if (mDrawDebug)
DrawTextNormal(mDebugDisplayText, 0, mHeight + 20);
}
void MidiClockIn::BuildDeviceList()
{
mDeviceList->Clear();
const std::vector<std::string>& devices = mDevice.GetPortList(true);
for (int i = 0; i < devices.size(); ++i)
mDeviceList->AddLabel(devices[i].c_str(), i);
}
void MidiClockIn::OnMidi(const juce::MidiMessage& message)
{
const int kDebugMaxLineCount = 40;
if (message.isMidiClock() || message.isSongPositionPointer())
{
const int kMinRequiredPulseCount = 48;
double time = message.getTimeStamp();
if (mDrawDebug)
AddDebugLine("midi clock " + ofToString(time, 3), kDebugMaxLineCount);
if (mReceivedPulseCount == 0)
{
double currentTempoDeltaSeconds = 1.0 / (TheTransport->GetTempo() / 60 * 24);
mDelayLockedLoop.reset(time, currentTempoDeltaSeconds, 1);
mDelayLockedLoop.setParams(gBufferSize, gSampleRate);
}
else
{
mDelayLockedLoop.update(time);
}
if (mReceivedPulseCount >= kMinRequiredPulseCount && time - mLastTimestamp > .001f)
{
double deltaSeconds = mDelayLockedLoop.timeDiff();
double pulsesPerSecond = 1 / deltaSeconds;
double beatsPerSecond = pulsesPerSecond / 24;
double instantTempo = beatsPerSecond * 60;
if (instantTempo > 20 && instantTempo < 999)
{
if (mTempoIdx == -1)
mTempoHistory.fill(instantTempo);
else
mTempoHistory[mTempoIdx] = instantTempo;
mTempoIdx = (mTempoIdx + 1) % mTempoHistory.size();
if (mEnabled)
TheTransport->SetTempo(GetRoundedTempo());
}
if (mDrawDebug)
AddDebugLine(" deltaSeconds=" + ofToString(deltaSeconds, 6) + " instantTempo=" + ofToString(instantTempo, 2) + " rounded tempo:" + ofToString(GetRoundedTempo(), 1), kDebugMaxLineCount);
mLastTimestamp = time;
}
++mReceivedPulseCount;
}
if (message.isMidiStart())
{
if (mDrawDebug)
AddDebugLine("midi start", kDebugMaxLineCount);
if (mObeyClockStartStop)
{
mTempoIdx = -1;
mReceivedPulseCount = 0;
if (TheSynth->IsAudioPaused())
{
TheSynth->SetAudioPaused(false);
TheTransport->Reset();
}
}
}
if (message.isMidiStop())
{
if (mDrawDebug)
AddDebugLine("midi stop", kDebugMaxLineCount);
if (mObeyClockStartStop)
TheSynth->SetAudioPaused(true);
}
if (message.isMidiContinue())
{
if (mDrawDebug)
AddDebugLine("midi continue", kDebugMaxLineCount);
if (mObeyClockStartStop)
{
mTempoIdx = -1;
mReceivedPulseCount = 0;
TheSynth->SetAudioPaused(false);
}
}
if (message.isSongPositionPointer())
{
if (mDrawDebug)
AddDebugLine("midi position pointer " + ofToString(message.getSongPositionPointerMidiBeat()), kDebugMaxLineCount);
if (mEnabled)
TheTransport->SetMeasureTime(message.getSongPositionPointerMidiBeat() / TheTransport->GetTimeSigTop() + mStartOffsetMs / TheTransport->MsPerBar());
}
if (message.isQuarterFrame())
{
if (mDrawDebug)
AddDebugLine("midi quarter frame " + ofToString(message.getQuarterFrameValue()) + " " + ofToString(message.getQuarterFrameSequenceNumber()), kDebugMaxLineCount);
}
}
void MidiClockIn::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mDeviceList)
{
mDevice.ConnectInput(mDeviceIndex);
}
}
void MidiClockIn::DropdownClicked(DropdownList* list)
{
BuildDeviceList();
}
void MidiClockIn::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadBool("obey_clock_start_stop", moduleInfo, true);
SetUpFromSaveData();
}
void MidiClockIn::SetUpFromSaveData()
{
mObeyClockStartStop = mModuleSaveData.GetBool("obey_clock_start_stop");
}
``` | /content/code_sandbox/Source/MidiClockIn.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,978 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// DotGrid.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/27/23.
//
//
#include "DotGrid.h"
#include "SynthGlobals.h"
#include "FileStream.h"
#include "IDrawableModule.h"
#include "PatchCableSource.h"
#include "Snapshots.h"
#include <cstring>
DotGrid::DotGrid(IClickable* parent, std::string name, int x, int y, int w, int h, int cols, int rows)
: mWidth(w)
, mHeight(h)
{
SetName(name.c_str());
SetPosition(x, y);
SetGrid(cols, rows);
Clear();
SetParent(parent);
//dynamic_cast<IDrawableModule*>(parent)->AddUIGrid(this);
}
DotGrid::~DotGrid()
{
}
void DotGrid::Init(int x, int y, int w, int h, int cols, int rows, IClickable* parent)
{
mWidth = w;
mHeight = h;
SetPosition(x, y);
SetGrid(cols, rows);
Clear();
SetParent(parent);
}
void DotGrid::DrawGridCircle(int col, int row, float radiusPercent) const
{
float xsize = float(mWidth) / mCols;
float ysize = float(mHeight) / mRows;
ofCircle(GetX(col) + xsize * .5f, GetY(row) + ysize * .5f, GetDotSize() * .5f * radiusPercent);
}
float DotGrid::GetDotSize() const
{
float xsize = float(mWidth) / mCols;
float ysize = float(mHeight) / mRows;
return std::min(xsize, ysize);
}
void DotGrid::Render()
{
ofPushMatrix();
ofTranslate(mX, mY);
ofPushStyle();
ofSetLineWidth(.5f);
float w, h;
GetDimensions(w, h);
float xsize = float(mWidth) / mCols;
float ysize = float(mHeight) / mRows;
if (GetHighlightCol(gTime) != -1)
{
ofFill();
ofSetColor(255, 255, 255, gModuleDrawAlpha * .2f);
ofRect(GetX(GetHighlightCol(gTime)), 0, xsize, mHeight);
}
ofNoFill();
int superMajor = mMajorCol * 4;
int superDuperMajor = mMajorCol * 16;
for (int j = 0; j < mRows; ++j)
{
for (int i = 0; i < mCols; ++i)
{
if (mMajorCol > 0)
{
if (mCols > superDuperMajor && i % superDuperMajor == 0)
ofSetColor(255, 255, 200, gModuleDrawAlpha);
else if (mCols > superMajor && i % superMajor == 0)
ofSetColor(255, 255, 100, gModuleDrawAlpha);
else if (mCols > mMajorCol && i % mMajorCol == 0)
ofSetColor(255, 200, 100, gModuleDrawAlpha);
else
ofSetColor(100, 100, 100, gModuleDrawAlpha);
}
else
{
ofSetColor(100, 100, 100, gModuleDrawAlpha);
}
DrawGridCircle(i, j, .3f);
}
}
for (int j = 0; j < mRows; ++j)
{
for (int i = 0; i < mCols; ++i)
{
DotData& data = mData[GetDataIndex(i, j)];
if (data.mOn)
{
float bump = ofClamp((data.mLastPlayTime + 250.0f - gTime) / 250.0f, 0, 1);
float radius = ofLerp(.65f, 1.0f, bump);
//white outer ring
ofFill();
ofSetColor(255, 255, 255);
DrawGridCircle(i, j, radius);
//line + center circle
ofSetColor(255 * data.mVelocity, 255 * data.mVelocity, 255 * data.mVelocity, gModuleDrawAlpha);
ofPushStyle();
ofSetLineWidth(GetDotSize() * radius * .23f);
ofLine(GetX(i) + xsize * .5f, GetY(j) + ysize * .5f, GetX(i) + xsize * .5f + xsize * data.mLength, GetY(j) + ysize * .5f);
ofPopStyle();
DrawGridCircle(i, j, radius * .9f);
}
if (mCurrentHover.mCol == i && mCurrentHover.mRow == j && gHoveredUIControl == nullptr)
{
if (mClick)
{
if (mDragBehavior == DragBehavior::Velocity)
{
DotData& currentHoverData = mData[GetDataIndex(mCurrentHover.mCol, mCurrentHover.mRow)];
ofSetColor(0, 255, 0);
DrawTextNormal(ofToString(currentHoverData.mVelocity, 2), GetX(i), GetY(j), 8.0f);
}
}
else
{
ofFill();
ofSetColor(180, 180, 0, 160);
DrawGridCircle(i, j, .8f);
}
}
}
}
ofPopStyle();
ofPopMatrix();
}
float DotGrid::GetX(int col) const
{
float xsize = float(mWidth) / mCols;
return (col)*xsize;
}
float DotGrid::GetY(int row) const
{
float ysize = float(mHeight) / mRows;
return mHeight - (row + 1) * ysize;
}
DotGrid::DotPosition DotGrid::GetGridCellAt(float x, float y, bool clamp /*= true*/)
{
y = (mHeight - 1) - y; //flip
float xsize = float(mWidth) / mCols;
float ysize = float(mHeight) / mRows;
int col = x / xsize;
int row = y / ysize;
if (clamp)
{
col = ofClamp(col, 0, mCols - 1);
row = ofClamp(row, 0, mRows - 1);
}
return DotPosition(col, row);
}
ofVec2f DotGrid::GetCellPosition(int col, int row)
{
return ofVec2f(GetX(col), GetY(row));
}
bool DotGrid::CanBeTargetedBy(PatchCableSource* source) const
{
return source->GetConnectionType() == kConnectionType_UIControl && dynamic_cast<Snapshots*>(source->GetOwner()) != nullptr;
}
void DotGrid::OnClicked(float x, float y, bool right)
{
if (right)
return;
mClick = true;
DotPosition cell = GetGridCellAt(x, y);
int dataIndex = GetDataIndex(cell.mCol, cell.mRow);
if (mData[dataIndex].mOn)
{
mMouseReleaseCanClear = true;
}
else
{
mData[dataIndex].mOn = true;
mData[dataIndex].mVelocity = 1;
mData[dataIndex].mLength = 0;
mMouseReleaseCanClear = false;
}
mDragBehavior = DragBehavior::Pending;
mHoldCell = cell;
mLastDragPosition.set(x, y);
}
void DotGrid::MouseReleased()
{
mClick = false;
if (mMouseReleaseCanClear && !TheSynth->MouseMovedSignificantlySincePressed() && mHoldCell.IsValid())
{
int dataIndex = GetDataIndex(mHoldCell.mCol, mHoldCell.mRow);
mData[dataIndex].mOn = false;
}
mHoldCell.Clear();
mMouseReleaseCanClear = false;
}
bool DotGrid::MouseMoved(float x, float y)
{
bool isMouseOver = (x >= 0 && x < mWidth && y >= 0 && y < mHeight);
if (mClick)
{
if (mHoldCell.IsValid())
{
if (mDragBehavior == DragBehavior::Pending)
{
if (std::abs(x - mLastDragPosition.x) < 2 && std::abs(y - mLastDragPosition.y) < 2)
mDragBehavior = DragBehavior::Pending;
else if (std::abs(x - mLastDragPosition.x) > std::abs(y - mLastDragPosition.y))
mDragBehavior = DragBehavior::Length;
else
mDragBehavior = DragBehavior::Velocity;
}
if (mDragBehavior == DragBehavior::Length)
{
DotPosition cell = GetGridCellAt(x, y, !K(clamp));
int newLength = std::max(cell.mCol - mHoldCell.mCol, 0);
int dataIndex = GetDataIndex(mHoldCell.mCol, mHoldCell.mRow);
mData[dataIndex].mLength = newLength;
}
if (mDragBehavior == DragBehavior::Velocity)
{
int dataIndex = GetDataIndex(mHoldCell.mCol, mHoldCell.mRow);
mData[dataIndex].mVelocity = std::clamp(mData[dataIndex].mVelocity - (y - mLastDragPosition.y) * .01f, 0.0f, 1.0f);
}
}
mLastDragPosition.set(x, y);
}
else
{
DotPosition cell = GetGridCellAt(x, y, K(clamp));
if (isMouseOver)
mCurrentHover = cell;
else
mCurrentHover.Clear();
}
return false;
}
bool DotGrid::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll)
{
bool isMouseOver = (x >= 0 && x < mWidth && y >= 0 && y < mHeight);
if (isMouseOver && mCurrentHover.IsValid())
{
DotData& data = mData[GetDataIndex(mCurrentHover.mCol, mCurrentHover.mRow)];
if (data.mOn)
data.mLength = std::max(data.mLength + scrollY * .1f, 0.0f);
}
return false;
}
void DotGrid::KeyPressed(int key, bool repeat)
{
if (key == OF_KEY_UP || key == OF_KEY_DOWN || key == OF_KEY_RIGHT || key == OF_KEY_LEFT)
{
if (mCurrentHover.IsValid())
{
DotData& data = mData[GetDataIndex(mCurrentHover.mCol, mCurrentHover.mRow)];
if (data.mOn)
{
int dirX = 0;
int dirY = 0;
if (key == OF_KEY_RIGHT)
dirX = 1;
if (key == OF_KEY_LEFT)
dirX = -1;
if (key == OF_KEY_UP)
dirY = 1;
if (key == OF_KEY_DOWN)
dirY = -1;
DotPosition newPos(mCurrentHover.mCol + dirX, mCurrentHover.mRow + dirY);
if (newPos.mCol >= 0 && newPos.mCol < mCols && newPos.mRow >= 0 && newPos.mRow < mRows)
{
mData[GetDataIndex(newPos.mCol, newPos.mRow)] = data;
data.mOn = false;
mCurrentHover = newPos;
}
}
}
}
}
void DotGrid::SetGrid(int cols, int rows)
{
cols = ofClamp(cols, 0, kMaxCols);
rows = ofClamp(rows, 0, kMaxRows);
mRows = rows;
mCols = cols;
}
const DotGrid::DotData& DotGrid::GetDataAt(int col, int row) const
{
col = ofClamp(col, 0, kMaxCols - 1);
row = ofClamp(row, 0, kMaxRows - 1);
return mData[GetDataIndex(col, row)];
}
void DotGrid::OnPlayed(double time, int col, int row)
{
if (IsValidPosition(DotPosition(col, row)))
mData[GetDataIndex(col, row)].mLastPlayTime = time;
}
void DotGrid::Clear()
{
for (auto& data : mData)
data.mOn = false;
}
bool DotGrid::IsValidPosition(DotPosition pos) const
{
return pos.mCol >= 0 && pos.mCol < kMaxCols && pos.mRow >= 0 && pos.mRow < kMaxRows;
}
void DotGrid::CopyDot(DotPosition from, DotPosition to)
{
if (IsValidPosition(from) && IsValidPosition(to))
mData[GetDataIndex(to.mCol, to.mRow)] = mData[GetDataIndex(from.mCol, from.mRow)];
}
void DotGrid::SetHighlightCol(double time, int col)
{
mHighlightColBuffer[mNextHighlightColPointer].time = time;
mHighlightColBuffer[mNextHighlightColPointer].col = col;
mNextHighlightColPointer = (mNextHighlightColPointer + 1) % mHighlightColBuffer.size();
}
int DotGrid::GetHighlightCol(double time) const
{
int ret = -1;
double latestTime = -1;
for (size_t i = 0; i < mHighlightColBuffer.size(); ++i)
{
if (mHighlightColBuffer[i].time <= time && mHighlightColBuffer[i].time > latestTime)
{
ret = mHighlightColBuffer[i].col;
latestTime = mHighlightColBuffer[i].time;
}
}
return ret;
}
namespace
{
const int kSaveStateRev = 0;
}
void DotGrid::SaveState(FileStreamOut& out)
{
out << kSaveStateRev;
out << mCols;
out << mRows;
for (int col = 0; col < mCols; ++col)
{
for (int row = 0; row < mRows; ++row)
{
out << mData[GetDataIndex(col, row)].mOn;
out << mData[GetDataIndex(col, row)].mVelocity;
out << mData[GetDataIndex(col, row)].mLength;
}
}
}
void DotGrid::LoadState(FileStreamIn& in, bool shouldSetValue)
{
int rev;
in >> rev;
LoadStateValidate(rev <= kSaveStateRev);
in >> mCols;
in >> mRows;
for (int col = 0; col < mCols; ++col)
{
for (int row = 0; row < mRows; ++row)
{
int dataIndex = GetDataIndex(col, row);
in >> mData[dataIndex].mOn;
in >> mData[dataIndex].mVelocity;
in >> mData[dataIndex].mLength;
}
}
}
``` | /content/code_sandbox/Source/DotGrid.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,366 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
VelocityToCV.h
Created: 28 Nov 2017 9:43:58pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "INoteReceiver.h"
#include "IModulator.h"
#include "Slider.h"
#include "Checkbox.h"
class PatchCableSource;
class VelocityToCV : public IDrawableModule, public INoteReceiver, public IModulator, public IFloatSliderListener
{
public:
VelocityToCV();
virtual ~VelocityToCV();
static IDrawableModule* Create() { return new VelocityToCV(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IModulator
virtual float Value(int samplesIn = 0) override;
virtual bool Active() const override { return mEnabled; }
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 106;
height = 17 * 3 + 2;
}
int mVelocity{ 0 };
bool mPassZero{ false };
Checkbox* mPassZeroCheckbox{ nullptr };
};
``` | /content/code_sandbox/Source/VelocityToCV.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 560 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Monome.h
// modularSynth
//
// Created by Ryan Challinor on 2/22/14.
//
//
#pragma once
#include "MidiDevice.h"
#include "INonstandardController.h"
#include "juce_osc/juce_osc.h"
#define HOST "127.0.0.1"
#define SERIAL_OSC_PORT 12002
#define NUM_MONOME_BUTTONS 128
class DropdownList;
class Monome : public INonstandardController,
private juce::OSCReceiver,
private juce::OSCReceiver::Listener<juce::OSCReceiver::MessageLoopCallback>
{
public:
Monome(MidiDeviceListener* listener);
~Monome();
void Poll() override;
bool SetUpOsc();
void ListMonomes();
void SetLight(int x, int y, float value);
void SetLightFlicker(int x, int y, float flickerMs);
std::string GetControlTooltip(MidiMessageType type, int control) override;
void SetLayoutData(ofxJSONElement& layout) override;
void ConnectToDevice(std::string deviceDesc);
void UpdateDeviceList(DropdownList* list);
void oscMessageReceived(const juce::OSCMessage& msg) override;
void SendValue(int page, int control, float value, bool forceNoteOn = false, int channel = -1) override;
bool IsInputConnected() override { return mHasMonome; }
bool Reconnect() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in) override;
private:
void SetLightInternal(int x, int y, float value);
Vec2i Rotate(int x, int y, int rotations);
static int sNextMonomeReceivePort;
juce::OSCSender mToSerialOsc;
juce::OSCSender mToMonome;
int mMonomeReceivePort{ -1 };
bool mIsOscSetUp{ false };
bool mHasMonome{ false };
bool mLightsInitialized{ false };
int mMaxColumns{ 16 };
int mGridRotation{ 0 };
juce::String mPrefix{ "monome" };
bool mJustRequestedDeviceList{ false };
std::string mPendingDeviceDesc;
struct MonomeDevice
{
void CopyFrom(MonomeDevice& other)
{
id = other.id;
product = other.product;
port = other.port;
}
std::string id;
std::string product;
int port{ 0 };
std::string GetDescription() { return id + " " + product; }
};
std::vector<MonomeDevice> mConnectedDeviceList;
MidiDeviceListener* mListener{ nullptr };
DropdownList* mListForMidiController{ nullptr };
MonomeDevice mLastConnectedDeviceInfo;
struct LightInfo
{
float mValue{ 0 };
double mLastUpdatedTime{ 0 };
double mLastSentTime{ 0 };
};
std::vector<LightInfo> mLights;
};
``` | /content/code_sandbox/Source/Monome.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 761 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
VolcaBeatsControl.h
Created: 28 Jan 2017 10:48:13pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "Slider.h"
class VolcaBeatsControl : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener
{
public:
VolcaBeatsControl();
virtual ~VolcaBeatsControl();
static IDrawableModule* Create() { return new VolcaBeatsControl(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 263;
height = 170;
}
float mClapSpeed{ .5 };
float mClaveSpeed{ .5 };
float mAgogoSpeed{ .5 };
float mCrashSpeed{ .5 };
float mStutterTime{ .5 };
float mStutterDepth{ 0 };
float mTomDecay{ .5 };
float mClosedHatDecay{ .5 };
float mOpenHatDecay{ .5 };
float mHatGrain{ .5 };
FloatSlider* mClapSpeedSlider{ nullptr };
FloatSlider* mClaveSpeedSlider{ nullptr };
FloatSlider* mAgogoSpeedSlider{ nullptr };
FloatSlider* mCrashSpeedSlider{ nullptr };
FloatSlider* mStutterTimeSlider{ nullptr };
FloatSlider* mStutterDepthSlider{ nullptr };
FloatSlider* mTomDecaySlider{ nullptr };
FloatSlider* mClosedHatDecaySlider{ nullptr };
FloatSlider* mOpenHatDecaySlider{ nullptr };
FloatSlider* mHatGrainSlider{ nullptr };
float mLevels[10]{};
FloatSlider* mLevelSliders[10]{ nullptr };
};
``` | /content/code_sandbox/Source/VolcaBeatsControl.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 681 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Metronome.h
// modularSynth
//
// Created by Ryan Challinor on 3/16/13.
//
//
#pragma once
#include <iostream>
#include "IAudioSource.h"
#include "EnvOscillator.h"
#include "IDrawableModule.h"
#include "Transport.h"
#include "Checkbox.h"
#include "Slider.h"
class Metronome : public IAudioSource, public ITimeListener, public IDrawableModule, public IFloatSliderListener
{
public:
Metronome();
~Metronome();
static IDrawableModule* Create() { return new Metronome(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//ITimeListener
void OnTimeEvent(double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override {}
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 80;
height = 35;
}
float mPhase{ 0 };
float mPhaseInc{ 0 };
EnvOscillator mOsc{ OscillatorType::kOsc_Sin };
float mVolume{ .5 };
FloatSlider* mVolumeSlider{ nullptr };
TransportListenerInfo* mTransportListenerInfo{ nullptr };
};
``` | /content/code_sandbox/Source/Metronome.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 520 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// VocoderCarrierInput.cpp
// modularSynth
//
// Created by Ryan Challinor on 4/18/13.
//
//
#include "VocoderCarrierInput.h"
#include "Vocoder.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "FillSaveDropdown.h"
#include "PatchCableSource.h"
VocoderCarrierInput::VocoderCarrierInput()
: IAudioProcessor(gBufferSize)
{
}
VocoderCarrierInput::~VocoderCarrierInput()
{
}
void VocoderCarrierInput::CreateUIControls()
{
IDrawableModule::CreateUIControls();
GetPatchCableSource()->AddTypeFilter("fftvocoder");
GetPatchCableSource()->AddTypeFilter("vocoder");
}
void VocoderCarrierInput::Process(double time)
{
PROFILER(VocoderCarrierInput);
if (GetTarget() == nullptr)
return;
if (mVocoder == nullptr || GetTarget() != mVocoderTarget)
{
mVocoder = dynamic_cast<VocoderBase*>(GetTarget());
mVocoderTarget = GetTarget();
}
if (mVocoder == nullptr)
return;
SyncBuffers();
mVocoder->SetCarrierBuffer(GetBuffer()->GetChannel(0), GetBuffer()->BufferSize());
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(0), GetBuffer()->BufferSize(), 0);
GetBuffer()->Reset();
}
void VocoderCarrierInput::DrawModule()
{
}
void VocoderCarrierInput::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("vocoder", moduleInfo, "", FillDropdown<VocoderBase*>);
SetUpFromSaveData();
}
void VocoderCarrierInput::SetUpFromSaveData()
{
IDrawableModule* vocoder = TheSynth->FindModule(mModuleSaveData.GetString("vocoder"), false);
mVocoder = dynamic_cast<VocoderBase*>(vocoder);
GetPatchCableSource()->SetTarget(dynamic_cast<IClickable*>(vocoder));
}
``` | /content/code_sandbox/Source/VocoderCarrierInput.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 526 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ControlRecorder.cpp
Created: 7 Apr 2024
Author: Ryan Challinor
==============================================================================
*/
#include "ControlRecorder.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "SynthGlobals.h"
#include "UIControlMacros.h"
#include "juce_core/juce_core.h"
ControlRecorder::ControlRecorder()
{
}
ControlRecorder::~ControlRecorder()
{
}
void ControlRecorder::CreateUIControls()
{
IDrawableModule::CreateUIControls();
float controlH;
UIBLOCK0();
CHECKBOX(mRecordCheckbox, "record", &mRecord);
UIBLOCK_SHIFTRIGHT();
CHECKBOX(mQuantizeLengthCheckbox, "quantize", &mQuantizeLength);
UIBLOCK_SHIFTRIGHT();
DROPDOWN(mQuantizeLengthSelector, "length", (int*)(&mQuantizeInterval), 60);
UIBLOCK_SHIFTLEFT();
FLOATSLIDER(mSpeedSlider, "speed", &mSpeed, .1f, 10);
UIBLOCK_NEWLINE();
BUTTON(mClearButton, "clear");
ENDUIBLOCK(mWidth, controlH);
mDisplayStartY = controlH + 3;
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
mQuantizeLengthSelector->AddLabel("8n", kInterval_8n);
mQuantizeLengthSelector->AddLabel("4n", kInterval_4n);
mQuantizeLengthSelector->AddLabel("2n", kInterval_2n);
mQuantizeLengthSelector->AddLabel("1", kInterval_1n);
mQuantizeLengthSelector->AddLabel("2", kInterval_2);
mQuantizeLengthSelector->AddLabel("3", kInterval_3);
mQuantizeLengthSelector->AddLabel("4", kInterval_4);
mQuantizeLengthSelector->AddLabel("8", kInterval_8);
mQuantizeLengthSelector->AddLabel("16", kInterval_16);
mQuantizeLengthSelector->AddLabel("32", kInterval_32);
mQuantizeLengthSelector->AddLabel("64", kInterval_64);
}
void ControlRecorder::Init()
{
IDrawableModule::Init();
}
void ControlRecorder::Poll()
{
IModulator::Poll();
if (mRecord)
RecordPoint();
}
float ControlRecorder::GetPlaybackTime(double time)
{
float measureTime = TheTransport->GetMeasureTime(time) - mRecordStartOffset;
if (!mQuantizeLength)
measureTime *= mSpeed;
if (mLength > 0)
{
while (measureTime < 0)
measureTime += mLength;
return fmod(measureTime, mLength);
}
return 0;
}
void ControlRecorder::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mRecordCheckbox->Draw();
mQuantizeLengthCheckbox->Draw();
mQuantizeLengthSelector->SetShowing(mQuantizeLength);
mQuantizeLengthSelector->Draw();
mSpeedSlider->SetShowing(!mQuantizeLength);
mSpeedSlider->Draw();
mClearButton->Draw();
DrawTextNormal("length: " + ofToString(mLength, 2) + " measures",
mClearButton->GetRect(K(local)).getMaxX() + 5, mClearButton->GetRect(K(local)).getMinY() + 12);
ofPushStyle();
ofSetColor(100, 100, 100, 100);
ofFill();
ofPushMatrix();
ofTranslate(3, mDisplayStartY);
ofSetColor(100, 100, 100, 100);
ofRect(0, 0, mWidth - 6, mHeight - 5 - mDisplayStartY);
mCurve.SetDimensions(mWidth - 6, mHeight - 5 - mDisplayStartY);
mCurve.Render();
ofSetColor(GetColor(kModuleCategory_Modulator));
if (GetPatchCableSource()->GetTarget())
DrawTextNormal(GetPatchCableSource()->GetTarget()->Name(), 5, 15);
if (mLength > 0 && !mRecord)
{
float playbackTime = GetPlaybackTime(gTime);
float lineX = ofLerp(3, mWidth - 6, playbackTime / mLength);
ofLine(lineX, 0, lineX, mHeight - 5 - mDisplayStartY);
}
ofPopMatrix();
ofPopStyle();
}
void ControlRecorder::Clear()
{
mLength = 0;
mSpeed = 1;
mCurve.Clear();
mHasRecorded = false;
}
void ControlRecorder::RecordPoint()
{
IUIControl* target = dynamic_cast<IUIControl*>(GetPatchCableSource()->GetTarget());
if (target)
{
float time = TheTransport->GetMeasureTime(gTime) - mRecordStartOffset;
mCurve.AddPointAtEnd(CurvePoint(time, target->GetMidiValue()));
mCurve.SetExtents(0, time);
mHasRecorded = true;
mLength = time;
}
}
void ControlRecorder::SetRecording(bool record)
{
mRecord = record;
if (mRecord)
{
mRecordStartOffset = TheTransport->GetMeasureTime(gTime);
Clear();
RecordPoint();
}
else
{
if (mQuantizeLength)
{
float quantizeResolution = TheTransport->GetMeasureFraction(mQuantizeInterval);
int quantizeIntervalSteps = juce::roundToInt(mLength / quantizeResolution);
if (quantizeIntervalSteps <= 0)
quantizeIntervalSteps = 1;
float quantizedLength = quantizeResolution * quantizeIntervalSteps;
mLength = quantizedLength;
mCurve.SetExtents(0, mLength);
}
mRecordStartOffset = fmod(mRecordStartOffset, mLength);
}
}
void ControlRecorder::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
if (fromUserClick && GetNumTargets() <= 1)
Clear();
mConnectedControl = dynamic_cast<IUIControl*>(GetPatchCableSource()->GetTarget());
}
void ControlRecorder::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mRecordCheckbox)
SetRecording(mRecord);
}
void ControlRecorder::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void ControlRecorder::ButtonClicked(ClickButton* button, double time)
{
if (button == mClearButton)
Clear();
}
void ControlRecorder::GetModuleDimensions(float& width, float& height)
{
width = mWidth;
height = mHeight;
}
void ControlRecorder::Resize(float w, float h)
{
w = MAX(w, 220);
h = MAX(h, 100);
mWidth = w;
mHeight = h;
}
void ControlRecorder::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void ControlRecorder::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void ControlRecorder::SetUpFromSaveData()
{
}
void ControlRecorder::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mWidth;
out << mHeight;
mCurve.SaveState(out);
out << mHasRecorded;
out << mLength;
out << mRecordStartOffset;
}
void ControlRecorder::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
in >> mWidth;
in >> mHeight;
mCurve.LoadState(in);
in >> mHasRecorded;
in >> mLength;
mCurve.SetExtents(0, mLength);
in >> mRecordStartOffset;
}
float ControlRecorder::Value(int samplesIn)
{
float playbackTime = GetPlaybackTime(gTime + samplesIn * gInvSampleRateMs);
float val = mCurve.Evaluate(playbackTime, true);
if (mConnectedControl != nullptr && mConnectedControl->ModulatorUsesLiteralValue())
return mConnectedControl->GetValueForMidiCC(val);
return val;
}
``` | /content/code_sandbox/Source/ControlRecorder.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,964 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ModulatorSubtract.cpp
Created: 9 Dec 2019 10:11:32pm
Author: Ryan Challinor
==============================================================================
*/
#include "ModulatorSubtract.h"
#include "Profiler.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
ModulatorSubtract::ModulatorSubtract()
{
}
void ModulatorSubtract::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mValue1Slider = new FloatSlider(this, "value 1", 3, 2, 100, 15, &mValue1, 0, 1);
mValue2Slider = new FloatSlider(this, "value 2", mValue1Slider, kAnchor_Below, 100, 15, &mValue2, 0, 1);
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
}
ModulatorSubtract::~ModulatorSubtract()
{
}
void ModulatorSubtract::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mValue1Slider->Draw();
mValue2Slider->Draw();
}
void ModulatorSubtract::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
if (GetSliderTarget() && fromUserClick)
{
mValue1 = GetSliderTarget()->GetValue();
mValue2 = 0;
mValue1Slider->SetExtents(GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax());
mValue1Slider->SetMode(GetSliderTarget()->GetMode());
}
}
float ModulatorSubtract::Value(int samplesIn)
{
ComputeSliders(samplesIn);
if (GetSliderTarget())
return ofClamp(mValue1 - mValue2, GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax());
else
return mValue1 - mValue2;
}
void ModulatorSubtract::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void ModulatorSubtract::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void ModulatorSubtract::SetUpFromSaveData()
{
}
``` | /content/code_sandbox/Source/ModulatorSubtract.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 606 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
EnvelopeModulator.h
Created: 16 Nov 2017 10:28:34pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "RadioButton.h"
#include "Slider.h"
#include "ClickButton.h"
#include "DropdownList.h"
#include "ADSR.h"
#include "ADSRDisplay.h"
#include "NoteEffectBase.h"
#include "IModulator.h"
#include "IPulseReceiver.h"
class EnvelopeModulator : public IDrawableModule, public IRadioButtonListener, public IFloatSliderListener, public IButtonListener, public IDropdownListener, public IIntSliderListener, public NoteEffectBase, public IModulator, public IPulseReceiver
{
public:
EnvelopeModulator();
virtual ~EnvelopeModulator();
static IDrawableModule* Create() { return new EnvelopeModulator(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return true; }
bool ShouldSuppressAutomaticOutputCable() override { return true; }
void Delete() { delete this; }
void DrawModule() override;
void Start(double time, const ::ADSR& adsr);
void SetEnabled(bool enabled) override { mEnabled = enabled; }
bool IsEnabled() const override { return mEnabled; }
void CreateUIControls() override;
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
bool IsResizable() const override { return false; }
void Resize(float w, float h) override;
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void OnPulse(double time, float velocity, int flags) override;
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override {}
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {}
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override {}
void GetModuleDimensions(float& width, float& height) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
private:
void OnClicked(float x, float y, bool right) override;
float mWidth{ 250 };
float mHeight{ 122 };
ADSRDisplay* mAdsrDisplay{ nullptr };
::ADSR mAdsr{ 10, 100, .5, 100 };
bool mUseVelocity{ false };
Checkbox* mUseVelocityCheckbox{ nullptr };
};
``` | /content/code_sandbox/Source/EnvelopeModulator.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 840 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
PitchRemap.cpp
Created: 7 May 2021 10:17:55pm
Author: Ryan Challinor
==============================================================================
*/
#include "PitchRemap.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
PitchRemap::PitchRemap()
{
for (size_t i = 0; i < mRemaps.size(); ++i)
{
mRemaps[i].mFromPitch = (int)i;
mRemaps[i].mToPitch = (int)i;
}
}
void PitchRemap::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
for (size_t i = 0; i < mRemaps.size(); ++i)
{
TEXTENTRY_NUM(mRemaps[i].mFromPitchEntry, ("from" + ofToString(i)).c_str(), 4, &mRemaps[i].mFromPitch, 0, 127);
UIBLOCK_SHIFTX(62);
TEXTENTRY_NUM(mRemaps[i].mToPitchEntry, ("to" + ofToString(i)).c_str(), 4, &mRemaps[i].mToPitch, 0, 127);
UIBLOCK_NEWLINE();
}
ENDUIBLOCK(mWidth, mHeight);
}
void PitchRemap::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
for (size_t i = 0; i < mRemaps.size(); ++i)
{
mRemaps[i].mFromPitchEntry->Draw();
ofRectangle rect = mRemaps[i].mFromPitchEntry->GetRect(true);
ofLine(rect.getMaxX() + 5, rect.getCenter().y, rect.getMaxX() + 20, rect.getCenter().y);
ofLine(rect.getMaxX() + 15, rect.getCenter().y - 4, rect.getMaxX() + 20, rect.getCenter().y);
ofLine(rect.getMaxX() + 15, rect.getCenter().y + 4, rect.getMaxX() + 20, rect.getCenter().y);
mRemaps[i].mToPitchEntry->Draw();
}
}
void PitchRemap::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mNoteOutput.Flush(time);
}
void PitchRemap::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
return;
}
if (pitch >= 0 && pitch < 128)
{
if (velocity > 0)
{
mInputNotes[pitch].mOn = true;
mInputNotes[pitch].mVelocity = velocity;
mInputNotes[pitch].mVoiceIdx = voiceIdx;
}
else
{
mInputNotes[pitch].mOn = false;
}
}
bool remapped = false;
for (size_t i = 0; i < mRemaps.size(); ++i)
{
if (pitch == mRemaps[i].mFromPitch)
{
PlayNoteOutput(time, mRemaps[i].mToPitch, velocity, voiceIdx, modulation);
remapped = true;
break;
}
}
if (!remapped)
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void PitchRemap::TextEntryComplete(TextEntry* entry)
{
//TODO(Ryan) make this handle mappings changing while notes are input
mNoteOutput.Flush(NextBufferTime(false));
}
void PitchRemap::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void PitchRemap::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/PitchRemap.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 968 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// TremoloEffect.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/27/12.
//
//
#include "TremoloEffect.h"
#include "OpenFrameworksPort.h"
#include "Profiler.h"
#include "UIControlMacros.h"
TremoloEffect::TremoloEffect()
{
mLFO.SetPeriod(mInterval);
mLFO.SetType(mOscType);
Clear(mWindow, kAntiPopWindowSize);
}
void TremoloEffect::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
FLOATSLIDER(mAmountSlider, "amount", &mAmount, 0, 1);
FLOATSLIDER(mOffsetSlider, "offset", &mOffset, 0, 1);
FLOATSLIDER(mDutySlider, "duty", &mDuty, 0, 1);
DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 45);
UIBLOCK_SHIFTRIGHT();
DROPDOWN(mOscSelector, "osc", (int*)(&mOscType), 45);
ENDUIBLOCK(mWidth, mHeight);
mIntervalSelector->AddLabel("1n", kInterval_1n);
mIntervalSelector->AddLabel("2n", kInterval_2n);
mIntervalSelector->AddLabel("4n", kInterval_4n);
mIntervalSelector->AddLabel("4nt", kInterval_4nt);
mIntervalSelector->AddLabel("8n", kInterval_8n);
mIntervalSelector->AddLabel("8nt", kInterval_8nt);
mIntervalSelector->AddLabel("16n", kInterval_16n);
mIntervalSelector->AddLabel("16nt", kInterval_16nt);
mIntervalSelector->AddLabel("32n", kInterval_32n);
mOscSelector->AddLabel("sin", kOsc_Sin);
mOscSelector->AddLabel("saw", kOsc_Saw);
mOscSelector->AddLabel("-saw", kOsc_NegSaw);
mOscSelector->AddLabel("squ", kOsc_Square);
mOscSelector->AddLabel("tri", kOsc_Tri);
}
void TremoloEffect::ProcessAudio(double time, ChannelBuffer* buffer)
{
PROFILER(TremoloEffect);
if (!mEnabled)
return;
float bufferSize = buffer->BufferSize();
ComputeSliders(0);
if (mAmount > 0)
{
for (int i = 0; i < bufferSize; ++i)
{
//smooth out LFO a bit to avoid pops with square/saw LFOs
mWindow[mWindowPos] = mLFO.Value(i + kAntiPopWindowSize / 2);
mWindowPos = (mWindowPos + 1) % kAntiPopWindowSize;
float lfoVal = 0;
for (int j = 0; j < kAntiPopWindowSize; ++j)
lfoVal += mWindow[j];
lfoVal /= kAntiPopWindowSize;
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
buffer->GetChannel(ch)[i] *= (1 - (mAmount * (1 - lfoVal)));
}
}
}
void TremoloEffect::DrawModule()
{
if (!mEnabled)
return;
mAmountSlider->Draw();
mIntervalSelector->Draw();
mOffsetSlider->Draw();
mOscSelector->Draw();
mDutySlider->Draw();
ofPushStyle();
ofSetColor(0, 200, 0, gModuleDrawAlpha * .3f);
ofFill();
ofRect(5, 4, mLFO.Value() * 85 * mAmount, 14);
ofPopStyle();
}
float TremoloEffect::GetEffectAmount()
{
if (!mEnabled)
return 0;
return mAmount;
}
void TremoloEffect::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mIntervalSelector)
mLFO.SetPeriod(mInterval);
if (list == mOscSelector)
mLFO.SetType(mOscType);
}
void TremoloEffect::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void TremoloEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mOffsetSlider)
mLFO.SetOffset(mOffset);
if (slider == mDutySlider)
{
mLFO.SetPulseWidth(mDuty);
}
}
``` | /content/code_sandbox/Source/TremoloEffect.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,104 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ADSR.h
// additiveSynth
//
// Created by Ryan Challinor on 11/19/12.
//
//
#pragma once
#include <iostream>
#include <vector>
#include <array>
#include "OpenFrameworksPort.h"
#define MAX_ADSR_STAGES 20
class FileStreamOut;
class FileStreamIn;
class ADSR
{
public:
struct Stage
{
float target{ 0 };
float time{ 1 };
float curve{ 0 };
};
struct EventInfo
{
EventInfo(){};
EventInfo(double startTime, double stopTime)
{
mStartBlendFromValue = 0;
mStopBlendFromValue = std::numeric_limits<float>::max();
mMult = 1;
mStartTime = startTime;
mStopTime = stopTime;
}
void Reset()
{
mStartBlendFromValue = 0;
mStopBlendFromValue = 0;
mMult = 1;
mStartTime = -10000;
mStopTime = -10000;
}
float mStartBlendFromValue{ 0 };
float mStopBlendFromValue{ 0 };
float mMult{ 1 };
double mStartTime{ -10000 };
double mStopTime{ -10000 };
};
ADSR(float a, float d, float s, float r)
{
Set(a, d, s, r);
}
ADSR()
: ADSR(1, 1, 1, 1)
{}
void Start(double time, float target, float timeScale = 1);
void Start(double time, float target, float a, float d, float s, float r, float timeScale = 1);
void Start(double time, float target, const ADSR& adsr, float timeScale = 1);
void Stop(double time, bool warn = true);
float Value(double time) const;
float Value(double time, const EventInfo* event) const;
void Set(float a, float d, float s, float r, float h = -1);
void Set(const ADSR& other);
void Clear()
{
for (auto& e : mEvents)
{
e.Reset();
}
}
void SetMaxSustain(float max) { mMaxSustain = max; }
void SetSustainStage(int stage) { mSustainStage = stage; }
bool IsDone(double time) const;
bool IsStandardADSR() const { return mNumStages == 3 && mSustainStage == 1; }
float GetStartTime(double time) const { return GetEventConst(time)->mStartTime; }
float GetStopTime(double time) const { return GetEventConst(time)->mStopTime; }
int GetNumStages() const { return mNumStages; }
void SetNumStages(int num) { mNumStages = CLAMP(num, 1, MAX_ADSR_STAGES); }
Stage& GetStageData(int stage) { return mStages[stage]; }
int GetStage(double time, double& stageStartTimeOut) const;
int GetStage(double time, double& stageStartTimeOut, const EventInfo* e) const;
float GetTimeScale() const { return mTimeScale; }
float& GetA() { return mStages[0].time; }
float& GetD() { return mStages[1].time; }
float& GetS() { return mStages[1].target; }
float& GetR() { return mStages[2].time; }
float& GetMaxSustain() { return mMaxSustain; }
int& GetSustainStage() { return mSustainStage; }
bool& GetHasSustainStage() { return mHasSustainStage; }
bool& GetFreeReleaseLevel() { return mFreeReleaseLevel; }
void SaveState(FileStreamOut& out);
void LoadState(FileStreamIn& in);
private:
EventInfo* GetEvent(double time);
const EventInfo* GetEventConst(double time) const;
float GetStageTimeScale(int stage) const;
std::array<EventInfo, 5> mEvents;
int mNextEventPointer{ 0 };
int mSustainStage{ 0 };
float mMaxSustain{ -1 };
Stage mStages[MAX_ADSR_STAGES];
int mNumStages{ 0 };
bool mHasSustainStage{ false };
bool mFreeReleaseLevel{ false };
float mTimeScale{ 1 };
};
``` | /content/code_sandbox/Source/ADSR.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,093 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ClipArranger.cpp
// Bespoke
//
// Created by Ryan Challinor on 8/26/14.
//
//
#include "ClipArranger.h"
#include "ArrangementController.h"
#include "ModularSynth.h"
ClipArranger::ClipArranger()
{
}
ClipArranger::~ClipArranger()
{
}
void ClipArranger::Poll()
{
}
void ClipArranger::Process(double time, float* left, float* right, int bufferSize)
{
if (mEnabled == false)
return;
if (ArrangementController::mPlay)
{
for (int i = 0; i < MAX_CLIPS; ++i)
mClips[i].Process(left, right, bufferSize);
}
}
void ClipArranger::DrawModule()
{
ofPushStyle();
ofSetColor(0, 0, 0);
ofFill();
ofRect(BUFFER_MARGIN_X, BUFFER_MARGIN_Y, mBufferWidth, mBufferHeight);
for (int i = 0; i < MAX_CLIPS; ++i)
{
if (mClips[i].mSample != nullptr)
{
float xStart = SampleToX(mClips[i].mStartSample);
float xPos = xStart;
float xEnd = SampleToX(mClips[i].mEndSample);
float sampleWidth = SampleToX(mClips[i].mStartSample + mClips[i].mSample->LengthInSamples()) - xStart;
for (; xPos < xEnd; xPos += sampleWidth)
{
ofPushMatrix();
ofTranslate(xPos, BUFFER_MARGIN_Y);
float length = mClips[i].mSample->LengthInSamples();
if (xPos + sampleWidth > xEnd)
{
float newWidth = xEnd - xPos;
length *= newWidth / sampleWidth;
sampleWidth = newWidth;
}
DrawAudioBuffer(sampleWidth, mBufferHeight, mClips[i].mSample->Data(), 0, length, 0);
ofPopMatrix();
}
ofSetColor(0, 255, 255);
ofNoFill();
ofSetLineWidth(i == mHighlightClip ? 3 : 1);
ofRect(xStart, BUFFER_MARGIN_Y, xEnd - xStart, mBufferHeight);
}
}
ofPopStyle();
}
void ClipArranger::GetModuleDimensions(float& w, float& h)
{
w = mBufferWidth + 100;
h = 25 + mBufferHeight;
}
void ClipArranger::OnClicked(float x, float y, bool right)
{
mMouseDown = true;
if (mHighlightClip != -1)
{
if (IsKeyHeld('x'))
{
delete mClips[mHighlightClip].mSample;
mClips[mHighlightClip].mSample = nullptr;
}
else
{
int mouseSample = MouseXToSample(x);
if (abs(mouseSample - mClips[mHighlightClip].mStartSample) < abs(mouseSample - mClips[mHighlightClip].mEndSample))
mMoveMode = kMoveMode_Start;
else
mMoveMode = kMoveMode_End;
}
}
}
void ClipArranger::MouseReleased()
{
if (mMouseDown)
{
mMouseDown = false;
mMoveMode = kMoveMode_None;
}
if (IsMousePosWithinClip(mLastMouseX, mLastMouseY))
{
Sample* heldSample = TheSynth->GetHeldSample();
if (heldSample)
{
Sample* sample = new Sample();
sample->Create(heldSample->Data());
AddSample(sample, mLastMouseX, mLastMouseY);
TheSynth->ClearHeldSample();
}
}
}
bool ClipArranger::MouseMoved(float x, float y)
{
mLastMouseX = x;
mLastMouseY = y;
int mouseSample = MouseXToSample(x);
if (!mMouseDown)
{
bool found = false;
if (IsMousePosWithinClip(x, y))
{
for (int i = 0; i < MAX_CLIPS; ++i)
{
if (mClips[i].mSample != nullptr)
{
if (mouseSample >= mClips[i].mStartSample && mouseSample < mClips[i].mEndSample)
{
mHighlightClip = i;
found = true;
break;
}
}
}
}
if (!found)
mHighlightClip = -1;
}
else
{
if (mHighlightClip != -1)
{
if (mMoveMode == kMoveMode_Start)
mClips[mHighlightClip].mStartSample = mouseSample;
else if (mMoveMode == kMoveMode_End)
mClips[mHighlightClip].mEndSample = mouseSample;
}
}
return false;
}
bool ClipArranger::IsMousePosWithinClip(int x, int y)
{
float w, h;
GetDimensions(w, h);
return x >= 0 && x < w && y >= 0 && y < h;
}
void ClipArranger::FilesDropped(std::vector<std::string> files, int x, int y)
{
Sample* sample = new Sample();
sample->Read(files[0].c_str());
AddSample(sample, x, y);
}
void ClipArranger::AddSample(Sample* sample, int x, int y)
{
Clip* clip = GetEmptyClip();
clip->mSample = sample;
clip->mStartSample = MouseXToSample(x);
clip->mEndSample = MIN(clip->mStartSample + clip->mSample->LengthInSamples(), ArrangementController::mSampleLength);
}
float ClipArranger::MouseXToBufferPos(float mouseX)
{
return (mouseX - BUFFER_MARGIN_X) / mBufferWidth;
}
int ClipArranger::MouseXToSample(float mouseX)
{
return MouseXToBufferPos(mouseX) * ArrangementController::mSampleLength;
}
float ClipArranger::SampleToX(int sample)
{
return float(sample) / ArrangementController::mSampleLength * mBufferWidth + BUFFER_MARGIN_X;
}
ClipArranger::Clip* ClipArranger::GetEmptyClip()
{
for (int i = 0; i < MAX_CLIPS; ++i)
{
if (mClips[i].mSample == nullptr)
return &mClips[i];
}
return nullptr;
}
void ClipArranger::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void ClipArranger::ButtonClicked(ClickButton* button, double time)
{
}
void ClipArranger::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void ClipArranger::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void ClipArranger::SetUpFromSaveData()
{
}
void ClipArranger::Clip::Process(float* left, float* right, int bufferSize)
{
if (mSample == nullptr)
return;
for (int i = 0; i < bufferSize; ++i)
{
int playhead = ArrangementController::mPlayhead + i;
if (playhead >= mStartSample &&
playhead < mEndSample)
{
int clipPos = playhead - mStartSample;
int samplePos = clipPos % mSample->LengthInSamples();
left[i] += mSample->Data()->GetChannel(0)[samplePos];
right[i] += mSample->Data()->GetChannel(1)[samplePos];
}
}
}
``` | /content/code_sandbox/Source/ClipArranger.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,760 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// PanicButton.h
// Bespoke
//
// Created by Ryan Challinor on 3/31/14.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "OpenFrameworksPort.h"
class PanicButton : public IDrawableModule
{
public:
PanicButton();
~PanicButton();
static IDrawableModule* Create() { return new PanicButton(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 300;
height = 150;
}
void OnClicked(float x, float y, bool right) override;
};
``` | /content/code_sandbox/Source/PanicButton.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 298 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
Inverter.cpp
Created: 13 Nov 2019 10:16:14pm
Author: Ryan Challinor
==============================================================================
*/
#include "Inverter.h"
#include "ModularSynth.h"
#include "Profiler.h"
Inverter::Inverter()
: IAudioProcessor(gBufferSize)
{
}
void Inverter::CreateUIControls()
{
IDrawableModule::CreateUIControls();
}
Inverter::~Inverter()
{
}
void Inverter::Process(double time)
{
PROFILER(Inverter);
SyncBuffers();
IAudioReceiver* target = GetTarget();
if (target)
{
ChannelBuffer* out = target->GetBuffer();
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
if (mEnabled)
Mult(GetBuffer()->GetChannel(ch), -1, out->BufferSize());
Add(out->GetChannel(ch), GetBuffer()->GetChannel(ch), out->BufferSize());
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch);
}
}
GetBuffer()->Reset();
}
void Inverter::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
}
void Inverter::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Inverter::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/Inverter.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 429 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// INoteSource.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/14/12.
//
//
#include "INoteSource.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Scale.h"
#include "PatchCableSource.h"
#include "Profiler.h"
#include "NoteOutputQueue.h"
void NoteOutput::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
ResetStackDepth();
PlayNoteInternal(time, pitch, velocity, voiceIdx, modulation, false);
}
void NoteOutput::PlayNoteInternal(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation, bool isFromMainThreadAndScheduled)
{
if (!IsAudioThread())
{
if (!isFromMainThreadAndScheduled) //if we specifically scheduled this ahead of time, there's no need to make adjustments. otherwise, account for immediately requesting a note from the non-audio thread
{
time += TheTransport->GetEventLookaheadMs();
if (velocity == 0)
time += gBufferSizeMs; //1 buffer later, to make sure notes get cleared
}
TheSynth->GetNoteOutputQueue()->QueuePlayNote(this, time, pitch, velocity, voiceIdx, modulation);
return;
}
const int kMaxDepth = 100;
if (mStackDepth > kMaxDepth)
{
TheSynth->LogEvent("note chain hit max stack depth", kLogEventType_Error);
return; //avoid stack overflow
}
++mStackDepth;
if (pitch >= 0 && pitch <= 127)
{
for (auto noteReceiver : mNoteSource->GetPatchCableSource()->GetNoteReceivers())
noteReceiver->PlayNote(time, pitch, velocity, voiceIdx, modulation);
if (velocity > 0)
{
mNoteOnTimes[pitch] = time;
mNotes[pitch] = true;
}
else
{
if (time > mNoteOnTimes[pitch])
mNotes[pitch] = false;
}
mNoteSource->GetPatchCableSource()->AddHistoryEvent(time, HasHeldNotes());
}
}
void NoteOutput::SendPressure(int pitch, int pressure)
{
for (auto noteReceiver : mNoteSource->GetPatchCableSource()->GetNoteReceivers())
noteReceiver->SendPressure(pitch, pressure);
}
void NoteOutput::SendCC(int control, int value, int voiceIdx)
{
for (auto noteReceiver : mNoteSource->GetPatchCableSource()->GetNoteReceivers())
noteReceiver->SendCC(control, value, voiceIdx);
}
void NoteOutput::SendMidi(const juce::MidiMessage& message)
{
for (auto noteReceiver : mNoteSource->GetPatchCableSource()->GetNoteReceivers())
noteReceiver->SendMidi(message);
}
bool NoteOutput::HasHeldNotes()
{
for (int i = 0; i < 128; ++i)
{
if (mNotes[i])
return true;
}
return false;
}
std::list<int> NoteOutput::GetHeldNotesList()
{
std::list<int> notes;
for (int i = 0; i < 128; ++i)
{
if (mNotes[i])
notes.push_back(i);
}
return notes;
}
void NoteOutput::Flush(double time)
{
if (!IsAudioThread())
{
TheSynth->GetNoteOutputQueue()->QueueFlush(this, time + TheTransport->GetEventLookaheadMs() + gBufferSizeMs); //include event lookahead, and make it 1 buffer later, to make sure notes get cleared
return;
}
bool flushed = false;
for (int i = 0; i < 128; ++i)
{
if (mNotes[i])
{
for (auto noteReceiver : mNoteSource->GetPatchCableSource()->GetNoteReceivers())
{
noteReceiver->PlayNote(time, i, 0);
noteReceiver->PlayNote(time + Transport::sEventEarlyMs, i, 0);
}
flushed = true;
mNotes[i] = false;
}
}
if (flushed)
mNoteSource->GetPatchCableSource()->AddHistoryEvent(time, false);
}
void INoteSource::PlayNoteOutput(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation, bool isFromMainThreadAndScheduled)
{
PROFILER(INoteSourcePlayOutput);
if (time < gTime && velocity > 0)
ofLog() << "Calling PlayNoteOutput() with a time in the past! " << ofToString(time / 1000) << " < " << ofToString(gTime / 1000);
if (!mInNoteOutput)
mNoteOutput.ResetStackDepth();
mInNoteOutput = true;
mNoteOutput.PlayNoteInternal(time, pitch, velocity, voiceIdx, modulation, isFromMainThreadAndScheduled);
mInNoteOutput = false;
}
void INoteSource::SendCCOutput(int control, int value, int voiceIdx /*=-1*/)
{
mNoteOutput.SendCC(control, value, voiceIdx);
}
void INoteSource::PreRepatch(PatchCableSource* cableSource)
{
mNoteOutput.Flush(NextBufferTime(false));
}
``` | /content/code_sandbox/Source/INoteSource.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,271 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// NoteToggle.cpp
// Bespoke
//
// Created by Ryan Challinor on 11/01/2021
//
//
#include "NoteToggle.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
NoteToggle::NoteToggle()
{
}
NoteToggle::~NoteToggle()
{
}
void NoteToggle::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mControlCable = new PatchCableSource(this, kConnectionType_ValueSetter);
AddPatchCableSource(mControlCable);
}
void NoteToggle::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
}
void NoteToggle::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
for (size_t i = 0; i < mTargets.size(); ++i)
{
if (i < mControlCable->GetPatchCables().size())
mTargets[i] = dynamic_cast<IUIControl*>(mControlCable->GetPatchCables()[i]->GetTarget());
else
mTargets[i] = nullptr;
}
}
void NoteToggle::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (pitch >= 0 && pitch < 128)
mHeldPitches[pitch] = (velocity > 0);
bool hasHeldNotes = false;
for (int i = 0; i < 128; ++i)
{
if (mHeldPitches[i])
hasHeldNotes = true;
}
for (size_t i = 0; i < mTargets.size(); ++i)
{
if (mTargets[i] != nullptr)
mTargets[i]->SetValue(hasHeldNotes ? 1 : 0, time);
}
}
void NoteToggle::GetModuleDimensions(float& width, float& height)
{
width = 100;
height = 10;
}
void NoteToggle::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void NoteToggle::SetUpFromSaveData()
{
}
``` | /content/code_sandbox/Source/NoteToggle.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 558 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// CommentDisplay.h
// Bespoke
//
// Created by Ryan Challinor on 2/1/15.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "OpenFrameworksPort.h"
#include "TextEntry.h"
class CommentDisplay : public IDrawableModule, public ITextEntryListener
{
public:
CommentDisplay();
virtual ~CommentDisplay();
static IDrawableModule* Create() { return new CommentDisplay(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void TextEntryComplete(TextEntry* entry) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
std::string mComment{};
TextEntry* mCommentEntry{ nullptr };
};
``` | /content/code_sandbox/Source/CommentDisplay.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 354 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ScriptModule.cpp
Created: 19 Apr 2020 1:52:34pm
Author: Ryan Challinor
==============================================================================
*/
#if BESPOKE_WINDOWS
#define ssize_t ssize_t_undef_hack //fixes conflict with ssize_t typedefs between python and juce
#endif
#include "ScriptModule.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Scale.h"
#include "UIControlMacros.h"
#include "PatchCableSource.h"
#include "Prefab.h"
#include "VersionInfo.h"
#if BESPOKE_WINDOWS
#undef ssize_t
#endif
#include "ScriptModule_PythonInterface.i"
#include "leathers/push"
#include "leathers/unused-value"
#include "leathers/range-loop-analysis"
#include "pybind11/embed.h"
#include "pybind11/stl.h"
#include "leathers/pop"
#include "juce_cryptography/juce_cryptography.h"
namespace py = pybind11;
using namespace juce;
//static
std::vector<ScriptModule*> ScriptModule::sScriptModules;
//static
std::list<ScriptModule*> ScriptModule::sScriptsRequestingInitExecution;
//static
ScriptModule* ScriptModule::sMostRecentLineExecutedModule = nullptr;
//static
ScriptModule* ScriptModule::sPriorExecutedModule = nullptr;
//static
double ScriptModule::sMostRecentRunTime = 0;
//static
std::string ScriptModule::sBackgroundTextString = "";
//static
float ScriptModule::sBackgroundTextSize = 30;
//static
ofVec2f ScriptModule::sBackgroundTextPos;
//static
ofColor ScriptModule::sBackgroundTextColor = ofColor::white;
//static
bool ScriptModule::sPythonInitialized = false;
//static
bool ScriptModule::sHasPythonEverSuccessfullyInitialized =
#ifdef BESPOKE_PORTABLE_PYTHON
true;
#else
false;
#endif
//static
bool ScriptModule::sHasLoadedUntrustedScript = false;
//static
ofxJSONElement ScriptModule::sStyleJSON;
ScriptModule::ScriptModule()
{
CheckIfPythonEverSuccessfullyInitialized();
if ((TheSynth->IsLoadingState() || Prefab::sLoadingPrefab) && sHasPythonEverSuccessfullyInitialized)
InitializePythonIfNecessary();
Reset();
mScriptModuleIndex = sScriptModules.size();
sScriptModules.push_back(this);
OSCReceiver::addListener(this);
}
ScriptModule::~ScriptModule()
{
}
void ScriptModule::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
DROPDOWN(mLoadScriptSelector, "loadscript", &mLoadScriptIndex, 120);
UIBLOCK_SHIFTRIGHT();
BUTTON(mLoadScriptButton, "load");
UIBLOCK_SHIFTRIGHT();
BUTTON(mSaveScriptButton, "save as");
UIBLOCK_SHIFTRIGHT();
BUTTON(mShowReferenceButton, "?");
UIBLOCK_NEWLINE();
UICONTROL_CUSTOM(mCodeEntry, new CodeEntry(UICONTROL_BASICS("code"), 500, 300));
BUTTON(mRunButton, "run");
UIBLOCK_SHIFTRIGHT();
BUTTON(mStopButton, "stop");
UIBLOCK_NEWLINE();
FLOATSLIDER(mASlider, "a", &mA, 0, 1);
UIBLOCK_SHIFTRIGHT();
FLOATSLIDER(mBSlider, "b", &mB, 0, 1);
UIBLOCK_SHIFTRIGHT();
FLOATSLIDER(mCSlider, "c", &mC, 0, 1);
UIBLOCK_SHIFTRIGHT();
FLOATSLIDER(mDSlider, "d", &mD, 0, 1);
ENDUIBLOCK(mWidth, mHeight);
UIBLOCK0();
BUTTON(mTrustScriptButton, "yes, I trust this script, load it");
UIBLOCK_SHIFTRIGHT();
BUTTON(mDontTrustScriptButton, "no, I don't trust this script, abort load");
ENDUIBLOCK0();
mPythonInstalledConfirmButton = new ClickButton(this, "yes, I have Python installed", 20, 100);
RefreshStyleFiles();
if (!sStyleJSON.empty())
mCodeEntry->SetStyleFromJSON(sStyleJSON[0u]);
}
void ScriptModule::UninitializePython()
{
if (sPythonInitialized)
py::finalize_interpreter();
sPythonInitialized = false;
}
namespace
{
// Py_SetPythonHome()'s signature varies depending on Python version. This converts to the string type we need.
std::string toPythonHome(const std::string& s, void (*)(char*)) { return s; }
std::wstring toPythonHome(const std::string& s, void (*)(const wchar_t*)) { return juce::String{ s }.toWideCharPointer(); }
}
//static
void ScriptModule::InitializePythonIfNecessary()
{
if (!sPythonInitialized)
{
#ifdef BESPOKE_PORTABLE_PYTHON
static const auto pythonHomeUtf8{ ofToFactoryPath("python") };
static auto PYTHONHOME{ toPythonHome(pythonHomeUtf8, Py_SetPythonHome) };
Py_SetPythonHome(PYTHONHOME.data());
#endif
py::initialize_interpreter();
#ifdef BESPOKE_PORTABLE_PYTHON
py::exec(std::string{ "import sys; sys.executable = '" } + pythonHomeUtf8 + "/" BESPOKE_PORTABLE_PYTHON "'; del sys");
#endif
py::exec(GetBootstrapImportString(), py::globals());
CodeEntry::OnPythonInit();
}
sPythonInitialized = true;
if (!sHasPythonEverSuccessfullyInitialized)
{
File(ofToDataPath("internal/python_" + std::string(Bespoke::PYTHON_VERSION) + "_installed")).create();
sHasPythonEverSuccessfullyInitialized = true;
}
}
//static
void ScriptModule::CheckIfPythonEverSuccessfullyInitialized()
{
if (!sHasPythonEverSuccessfullyInitialized)
{
if (File(ofToDataPath("internal/python_" + std::string(Bespoke::PYTHON_VERSION) + "_installed")).existsAsFile())
sHasPythonEverSuccessfullyInitialized = true;
}
}
void ScriptModule::OnClicked(float x, float y, bool right)
{
if (!sHasPythonEverSuccessfullyInitialized)
{
mPythonInstalledConfirmButton->TestClick(x, y, right);
}
else
{
IDrawableModule::OnClicked(x, y, right);
}
}
void ScriptModule::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
if (!sHasPythonEverSuccessfullyInitialized)
{
//DrawTextNormal("please ensure that you have Python 3.8 installed\nif you do not have Python 3.8 installed, Bespoke may crash\n\nclick to continue...", 20, 20);
juce::String pythonVersionRev = Bespoke::PYTHON_VERSION;
juce::String pythonVersionMinor = pythonVersionRev.substring(0, pythonVersionRev.lastIndexOfChar('.'));
if (pythonVersionRev.lastIndexOfChar('.') == -1)
pythonVersionMinor = "***ERROR***";
DrawTextNormal("this version of bespoke was built with Python " + pythonVersionRev.toStdString() + "\n" +
"please ensure that you have some flavor of Python " + pythonVersionMinor.toStdString() + " installed.\n" +
"(not an older or newer version!)\n\n" +
"if you do not, bespoke will crash!",
20, 20);
mCodeEntry->SetShowing(false);
mPythonInstalledConfirmButton->SetLabel(("yes, I have Python " + pythonVersionMinor.toStdString() + " installed").c_str());
mPythonInstalledConfirmButton->Draw();
return;
}
mTrustScriptButton->SetShowing(mIsScriptUntrusted);
mDontTrustScriptButton->SetShowing(mIsScriptUntrusted);
mLoadScriptSelector->SetShowing(!mIsScriptUntrusted);
mLoadScriptButton->SetShowing(!mIsScriptUntrusted);
mSaveScriptButton->SetShowing(!mIsScriptUntrusted);
mShowReferenceButton->SetShowing(!mIsScriptUntrusted);
mPythonInstalledConfirmButton->SetShowing(false);
mCodeEntry->SetShowing(true);
mLoadScriptSelector->Draw();
mLoadScriptButton->Draw();
mSaveScriptButton->Draw();
mShowReferenceButton->Draw();
mCodeEntry->Draw();
mRunButton->Draw();
mStopButton->Draw();
mASlider->Draw();
mBSlider->Draw();
mCSlider->Draw();
mDSlider->Draw();
if (mIsScriptUntrusted)
{
mTrustScriptButton->Draw();
mDontTrustScriptButton->Draw();
ofPushStyle();
ofFill();
ofRectangle buttonRect = mTrustScriptButton->GetRect(K(local));
ofSetColor(0, 255, 0, 80);
ofRect(buttonRect);
buttonRect = mDontTrustScriptButton->GetRect(K(local));
ofSetColor(255, 0, 0, 80);
ofRect(buttonRect);
ofPopStyle();
}
if (mLastError != "")
{
ofSetColor(255, 0, 0, gModuleDrawAlpha);
ofVec2f errorPos = mStopButton->GetPosition(true);
errorPos.x += 60;
errorPos.y += 12;
DrawTextNormal(mLastError, errorPos.x, errorPos.y);
}
mLineExecuteTracker.Draw(mCodeEntry, 0, ofColor::green);
mNotePlayTracker.Draw(mCodeEntry, 1, IDrawableModule::GetColor(kModuleCategory_Note));
mMethodCallTracker.Draw(mCodeEntry, 1, IDrawableModule::GetColor(kModuleCategory_Other));
mUIControlTracker.Draw(mCodeEntry, 1, IDrawableModule::GetColor(kModuleCategory_Modulator));
for (size_t i = 0; i < mScheduledNoteOutput.size(); ++i)
{
if (mScheduledNoteOutput[i].time != -1 &&
//mScheduledNoteOutput[i].velocity > 0 &&
gTime + 50 < mScheduledNoteOutput[i].time)
DrawTimer(mScheduledNoteOutput[i].lineNum, mScheduledNoteOutput[i].startTime, mScheduledNoteOutput[i].time, IDrawableModule::GetColor(kModuleCategory_Note), mScheduledNoteOutput[i].velocity > 0);
}
for (size_t i = 0; i < mScheduledMethodCall.size(); ++i)
{
if (mScheduledMethodCall[i].time != -1 &&
gTime + 50 < mScheduledMethodCall[i].time)
DrawTimer(mScheduledMethodCall[i].lineNum, mScheduledMethodCall[i].startTime, mScheduledMethodCall[i].time, IDrawableModule::GetColor(kModuleCategory_Other), true);
}
for (size_t i = 0; i < mScheduledUIControlValue.size(); ++i)
{
if (mScheduledUIControlValue[i].time != -1 &&
gTime + 50 < mScheduledUIControlValue[i].time)
DrawTimer(mScheduledUIControlValue[i].lineNum, mScheduledUIControlValue[i].startTime, mScheduledUIControlValue[i].time, IDrawableModule::GetColor(kModuleCategory_Modulator), true);
}
ofPushStyle();
for (size_t i = 0; i < mPrintDisplay.size(); ++i)
{
if (mPrintDisplay[i].time == -1)
continue;
float fadeMs = 500;
if (gTime - mPrintDisplay[i].time >= 0 && gTime - mPrintDisplay[i].time < fadeMs)
{
ofSetColor(ofColor::white, 255 * (1 - (gTime - mPrintDisplay[i].time) / fadeMs));
ofVec2f linePos = mCodeEntry->GetLinePos(mPrintDisplay[i].lineNum, K(end));
DrawTextNormal(mPrintDisplay[i].text, linePos.x + 10, linePos.y + 15);
}
else
{
mPrintDisplay[i].time = -1;
}
}
for (size_t i = 0; i < mUIControlModifications.size(); ++i)
{
if (mUIControlModifications[i].time == -1)
continue;
float fadeMs = 500;
if (gTime - mUIControlModifications[i].time >= 0 && gTime - mUIControlModifications[i].time < fadeMs)
{
ofSetColor(IDrawableModule::GetColor(kModuleCategory_Modulator), 255 * (1 - (gTime - mUIControlModifications[i].time) / fadeMs));
ofVec2f linePos = mCodeEntry->GetLinePos(mUIControlModifications[i].lineNum, K(end));
DrawTextNormal(ofToString(mUIControlModifications[i].value), linePos.x + 10, linePos.y + 15);
}
else
{
mUIControlModifications[i].time = -1;
}
}
ofPopStyle();
if (CodeEntry::HasJediNotInstalledWarning())
{
ofPushStyle();
ofRectangle buttonRect = mShowReferenceButton->GetRect(true);
ofFill();
ofSetColor(255, 255, 0);
float x = buttonRect.getMaxX() + 10;
float y = buttonRect.getCenter().y;
ofCircle(x, y, 6);
ofSetColor(0, 0, 0);
DrawTextBold("!", x - 2, y + 5, 15);
ofPopStyle();
if (mShowJediWarning)
TheSynth->SetNextDrawTooltip("warning: jedi is not installed, so scripting autocomplete will not work. to add autocomplete functionality, install jedi, which you can likely do with the command 'pip install jedi' in a terminal window");
}
}
void ScriptModule::DrawModuleUnclipped()
{
if (Minimized() || IsVisible() == false)
return;
mCodeEntry->RenderOverlay();
ofPushStyle();
if (mDrawDebug)
{
std::string debugText = mLastRunLiteralCode;
for (size_t i = 0; i < mScheduledNoteOutput.size(); ++i)
{
if (mScheduledNoteOutput[i].time != -1 &&
gTime + 50 < mScheduledNoteOutput[i].time)
debugText += "\nP:" + ofToString(mScheduledNoteOutput[i].pitch) + " V:" + ofToString(mScheduledNoteOutput[i].velocity) + ", " + ofToString(mScheduledNoteOutput[i].time) + " " + ofToString(mScheduledNoteOutput[i].startTime) + ", line:" + ofToString(mScheduledNoteOutput[i].lineNum);
}
for (size_t i = 0; i < mScheduledMethodCall.size(); ++i)
{
if (mScheduledMethodCall[i].time != -1 &&
gTime + 50 < mScheduledMethodCall[i].time)
debugText += "\n" + mScheduledMethodCall[i].method + ", " + ofToString(mScheduledMethodCall[i].time) + " " + ofToString(mScheduledMethodCall[i].startTime) + " " + ofToString(mScheduledMethodCall[i].lineNum);
}
for (size_t i = 0; i < mScheduledUIControlValue.size(); ++i)
{
if (mScheduledUIControlValue[i].time != -1 &&
gTime + 50 < mScheduledUIControlValue[i].time)
debugText += "\n" + std::string(mScheduledUIControlValue[i].control->Name()) + ": " + ofToString(mScheduledUIControlValue[i].value) + ", " + ofToString(mScheduledUIControlValue[i].time) + " " + ofToString(mScheduledUIControlValue[i].startTime) + " " + ofToString(mScheduledUIControlValue[i].lineNum);
}
std::string lineNumbers = "";
std::vector<std::string> lines = ofSplitString(mLastRunLiteralCode, "\n");
for (size_t i = 0; i < lines.size(); ++i)
{
lineNumbers += ofToString(i + 1) + "\n";
}
ofSetColor(100, 100, 100);
DrawTextNormal(lineNumbers, mWidth + 5, 0);
ofSetColor(255, 255, 255);
DrawTextNormal(debugText, mWidth + 30, 0);
}
for (size_t i = 0; i < mUIControlModifications.size(); ++i)
{
if (mUIControlModifications[i].time == -1)
continue;
float fadeMs = 200;
if (gTime - mUIControlModifications[i].time >= 0 && gTime - mUIControlModifications[i].time < fadeMs)
{
ofSetColor(IDrawableModule::GetColor(kModuleCategory_Modulator), 100 * (1 - (gTime - mUIControlModifications[i].time) / fadeMs));
ofVec2f linePos = mCodeEntry->GetLinePos(mUIControlModifications[i].lineNum, false);
ofPushMatrix();
ofTranslate(-mX, -mY);
ofSetLineWidth(1);
ofLine(mX + linePos.x + 11, mY + linePos.y + 10, mUIControlModifications[i].position.x, mUIControlModifications[i].position.y);
ofPopMatrix();
}
}
if (mDrawBoundModuleConnections && mBoundModuleConnections.size() > 0)
{
for (size_t i = 0; i < mBoundModuleConnections.size(); ++i)
{
if (mBoundModuleConnections[i].mTarget == nullptr)
continue;
if (mBoundModuleConnections[i].mTarget->IsDeleted())
{
mBoundModuleConnections[i].mTarget = nullptr;
continue;
}
ofVec2f linePos = mCodeEntry->GetLinePos(mBoundModuleConnections[i].mLineIndex, false);
ofSetColor(IDrawableModule::GetColor(kModuleCategory_Other), 30);
ofFill();
float codeY = mCodeEntry->GetPosition(true).y;
float topY = ofClamp(linePos.y + 3, codeY, codeY + mCodeEntry->GetRect().height);
float bottomY = ofClamp(linePos.y + 3 + mCodeEntry->GetCharHeight(), codeY, codeY + mCodeEntry->GetRect().height);
ofRectangle lineRect(linePos.x, topY, mCodeEntry->GetRect().width, bottomY - topY);
ofRect(lineRect, L(corner, 0));
ofSetLineWidth(2);
ofSetColor(IDrawableModule::GetColor(kModuleCategory_Other), 30);
float startX, startY, endX, endY;
ofRectangle targetRect = mBoundModuleConnections[i].mTarget->GetRect();
FindClosestSides(lineRect.x, lineRect.y, lineRect.width, lineRect.height, targetRect.x - mX, targetRect.y - mY, targetRect.width, targetRect.height, startX, startY, endX, endY, K(sidesOnly));
ofLine(startX, startY, endX, endY);
}
}
ofPopStyle();
}
void ScriptModule::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
if (cableSource->GetTarget() != nullptr && cableSource->GetConnectionType() == kConnectionType_Note)
Transport::sDoEventLookahead = true; //scripts that output notes require lookahead to be able to schedule on time
}
bool ScriptModule::MouseMoved(float x, float y)
{
if (CodeEntry::HasJediNotInstalledWarning())
{
ofRectangle buttonRect = mShowReferenceButton->GetRect(true);
float warningX = buttonRect.getMaxX() + 10;
float warningY = buttonRect.getCenter().y;
if (ofDistSquared(x, y, warningX, warningY) <= 6 * 6)
mShowJediWarning = true;
else
mShowJediWarning = false;
}
return IDrawableModule::MouseMoved(x, y);
}
void ScriptModule::DrawTimer(int lineNum, double startTime, double endTime, ofColor color, bool filled)
{
ofVec2f linePos = mCodeEntry->GetLinePos(lineNum, false);
linePos.x += 11;
linePos.y += 10;
float t = (gTime - startTime) / (endTime - startTime);
if (t > 0 && t < 1)
{
const float kRadius = 5;
ofPushStyle();
if (filled)
ofSetColor(color);
else
ofSetColor(color * .5f);
ofNoFill();
ofCircle(linePos.x, linePos.y, kRadius);
if (filled)
ofFill();
ofCircle(linePos.x + sin(t * TWO_PI) * kRadius, linePos.y - cos(t * TWO_PI) * kRadius, 2);
ofPopStyle();
}
}
void ScriptModule::Poll()
{
if (sHasPythonEverSuccessfullyInitialized)
InitializePythonIfNecessary();
if (!sPythonInitialized)
return;
if (ScriptModule::sHasLoadedUntrustedScript)
{
if (TheSynth->FindModule("scriptwarning") == nullptr)
{
ModuleFactory::Spawnable spawnable;
spawnable.mLabel = "scriptwarning";
TheSynth->SpawnModuleOnTheFly(spawnable, 50, 100, true);
TheSynth->SetAudioPaused(true);
}
mCodeEntry->Publish();
return;
}
if (sScriptsRequestingInitExecution.size() > 0)
{
for (auto s : sScriptsRequestingInitExecution)
{
s->mCodeEntry->Publish();
s->ExecuteCode();
}
sScriptsRequestingInitExecution.clear();
}
double time = gTime;
for (size_t i = 0; i < mScheduledPulseTimes.size(); ++i)
{
if (mScheduledPulseTimes[i] != -1)
{
double runTime = mScheduledPulseTimes[i];
mScheduledPulseTimes[i] = -1;
if (mLastError == "")
{
//if (runTime < time)
// ofLog() << "trying to run script triggered by pulse too late!";
RunCode(runTime, "on_pulse()");
}
}
}
for (size_t i = 0; i < mPendingNoteInput.size(); ++i)
{
if (mPendingNoteInput[i].time != -1 &&
time + TheTransport->GetEventLookaheadMs() > mPendingNoteInput[i].time)
{
if (mLastError == "")
{
//if (mPendingNoteInput[i].time < time)
// ofLog() << "trying to run script triggered by note too late!";
RunCode(mPendingNoteInput[i].time, "on_note(" + ofToString(mPendingNoteInput[i].pitch) + ", " + ofToString(mPendingNoteInput[i].velocity) + ")");
}
mPendingNoteInput[i].time = -1;
}
}
for (size_t i = 0; i < mScheduledUIControlValue.size(); ++i)
{
if (mScheduledUIControlValue[i].time != -1 &&
time + TheTransport->GetEventLookaheadMs() > mScheduledUIControlValue[i].time)
{
AdjustUIControl(mScheduledUIControlValue[i].control, mScheduledUIControlValue[i].value, mScheduledUIControlValue[i].time, mScheduledUIControlValue[i].lineNum);
mScheduledUIControlValue[i].time = -1;
}
}
//note offs first
for (size_t i = 0; i < mScheduledNoteOutput.size(); ++i)
{
if (mScheduledNoteOutput[i].time != -1 &&
mScheduledNoteOutput[i].velocity == 0 &&
time + TheTransport->GetEventLookaheadMs() > mScheduledNoteOutput[i].time)
{
PlayNote(mScheduledNoteOutput[i].time, mScheduledNoteOutput[i].pitch, mScheduledNoteOutput[i].velocity, mScheduledNoteOutput[i].pan, mScheduledNoteOutput[i].noteOutputIndex, mScheduledNoteOutput[i].lineNum);
mScheduledNoteOutput[i].time = -1;
}
}
//then note ons
for (size_t i = 0; i < mScheduledNoteOutput.size(); ++i)
{
if (mScheduledNoteOutput[i].time != -1 &&
mScheduledNoteOutput[i].velocity != 0 &&
time + TheTransport->GetEventLookaheadMs() > mScheduledNoteOutput[i].time)
{
PlayNote(mScheduledNoteOutput[i].time, mScheduledNoteOutput[i].pitch, mScheduledNoteOutput[i].velocity, mScheduledNoteOutput[i].pan, mScheduledNoteOutput[i].noteOutputIndex, mScheduledNoteOutput[i].lineNum);
mScheduledNoteOutput[i].time = -1;
}
}
for (size_t i = 0; i < mScheduledMethodCall.size(); ++i)
{
if (mScheduledMethodCall[i].time != -1 &&
time + TheTransport->GetEventLookaheadMs() > mScheduledMethodCall[i].time)
{
RunCode(mScheduledMethodCall[i].time, mScheduledMethodCall[i].method);
mMethodCallTracker.AddEvent(mScheduledMethodCall[i].lineNum);
mScheduledMethodCall[i].time = -1;
}
}
if (mMidiMessageQueue.size() > 0)
{
mMidiMessageQueueMutex.lock();
for (std::string& methodCall : mMidiMessageQueue)
RunCode(gTime, methodCall);
mMidiMessageQueue.clear();
mMidiMessageQueueMutex.unlock();
}
if (mHotloadScripts && !mLoadedScriptPath.empty())
{
File scriptFile = File(mLoadedScriptPath);
if (mLoadedScriptFiletime < scriptFile.getLastModificationTime())
{
std::unique_ptr<FileInputStream> input(scriptFile.createInputStream());
mCodeEntry->SetText(input->readString().toStdString());
mCodeEntry->Publish();
ExecuteCode();
mLoadedScriptFiletime = scriptFile.getLastModificationTime();
}
}
}
//static
float ScriptModule::GetScriptMeasureTime()
{
return TheTransport->GetMeasureTime(sMostRecentRunTime);
}
//static
float ScriptModule::GetTimeSigRatio()
{
return float(TheTransport->GetTimeSigTop()) / TheTransport->GetTimeSigBottom();
}
double ScriptModule::GetScheduledTime(double delayMeasureTime)
{
return sMostRecentRunTime + delayMeasureTime * TheTransport->MsPerBar();
}
void ScriptModule::PlayNoteFromScript(float pitch, float velocity, float pan, int noteOutputIndex)
{
PlayNote(sMostRecentRunTime, pitch, velocity, pan, noteOutputIndex, mNextLineToExecute);
}
void ScriptModule::PlayNoteFromScriptAfterDelay(float pitch, float velocity, double delayMeasureTime, float pan, int noteOutputIndex)
{
double time = GetScheduledTime(delayMeasureTime);
//if (velocity == 0)
// time -= gBufferSizeMs + 1; //TODO(Ryan) hack to make note offs happen a buffer early... figure out why scheduled lengths are longer than it takes to get the next pulse of the same interval
//ofLog() << "ScriptModule::PlayNoteFromScriptAfterDelay() " << velocity << " " << time << " " << sMostRecentRunTime << " " << (time - sMostRecentRunTime);
if (time <= sMostRecentRunTime)
{
if (time < gTime)
ofLog() << "script is trying to play a note in the past!";
PlayNote(time, pitch, velocity, pan, noteOutputIndex, mNextLineToExecute);
}
else
{
ScheduleNote(time, pitch, velocity, pan, noteOutputIndex);
}
}
void ScriptModule::SendCCFromScript(int control, int value, int noteOutputIndex)
{
if (noteOutputIndex == 0)
{
SendCC(control, value);
return;
}
if (noteOutputIndex - 1 < (int)mExtraNoteOutputs.size())
{
mExtraNoteOutputs[noteOutputIndex - 1]->SendCCOutput(control, value);
}
}
void ScriptModule::ScheduleNote(double time, float pitch, float velocity, float pan, int noteOutputIndex)
{
for (size_t i = 0; i < mScheduledNoteOutput.size(); ++i)
{
if (mScheduledNoteOutput[i].time == -1)
{
mScheduledNoteOutput[i].time = time;
mScheduledNoteOutput[i].startTime = sMostRecentRunTime;
mScheduledNoteOutput[i].pitch = pitch;
mScheduledNoteOutput[i].velocity = velocity;
mScheduledNoteOutput[i].pan = pan;
mScheduledNoteOutput[i].noteOutputIndex = noteOutputIndex;
mScheduledNoteOutput[i].lineNum = mNextLineToExecute;
break;
}
}
}
void ScriptModule::ScheduleMethod(std::string method, double delayMeasureTime)
{
for (size_t i = 0; i < mScheduledMethodCall.size(); ++i)
{
if (mScheduledMethodCall[i].time == -1)
{
double time = GetScheduledTime(delayMeasureTime);
mScheduledMethodCall[i].time = time;
mScheduledMethodCall[i].startTime = sMostRecentRunTime;
mScheduledMethodCall[i].method = method;
mScheduledMethodCall[i].lineNum = mNextLineToExecute;
break;
}
}
}
void ScriptModule::ScheduleUIControlValue(IUIControl* control, float value, double delayMeasureTime)
{
for (size_t i = 0; i < mScheduledUIControlValue.size(); ++i)
{
if (mScheduledUIControlValue[i].time == -1)
{
double time = GetScheduledTime(delayMeasureTime);
mScheduledUIControlValue[i].time = time;
mScheduledUIControlValue[i].startTime = sMostRecentRunTime;
mScheduledUIControlValue[i].control = control;
mScheduledUIControlValue[i].value = value;
mScheduledUIControlValue[i].lineNum = mNextLineToExecute;
break;
}
}
}
void ScriptModule::HighlightLine(int lineNum, int scriptModuleIndex)
{
ScriptModule* module = sScriptModules[scriptModuleIndex];
if (module != sMostRecentLineExecutedModule || sPriorExecutedModule == nullptr)
{
sPriorExecutedModule = sMostRecentLineExecutedModule;
sMostRecentLineExecutedModule = module;
}
sScriptModules[scriptModuleIndex]->mNextLineToExecute = lineNum;
sScriptModules[scriptModuleIndex]->mLineExecuteTracker.AddEvent(lineNum);
}
void ScriptModule::PrintText(std::string text)
{
for (size_t i = 0; i < mPrintDisplay.size(); ++i)
{
if (mPrintDisplay[i].time == -1 || mPrintDisplay[i].lineNum == mNextLineToExecute)
{
mPrintDisplay[i].time = gTime;
mPrintDisplay[i].text = text;
mPrintDisplay[i].lineNum = mNextLineToExecute;
break;
}
}
}
IUIControl* ScriptModule::GetUIControl(std::string path)
{
IUIControl* control;
if (ofIsStringInString(path, "~"))
control = TheSynth->FindUIControl(path);
else
control = TheSynth->FindUIControl(Path() + "~" + path);
return control;
}
void ScriptModule::AdjustUIControl(IUIControl* control, float value, double time, int lineNum)
{
control->SetValue(value, time);
mUIControlTracker.AddEvent(lineNum);
for (size_t i = 0; i < mUIControlModifications.size(); ++i)
{
if (mUIControlModifications[i].time == -1 || mUIControlModifications[i].lineNum == lineNum)
{
mUIControlModifications[i].time = gTime;
mUIControlModifications[i].position = control->GetRect().getCenter();
mUIControlModifications[i].value = value;
mUIControlModifications[i].lineNum = lineNum;
break;
}
}
}
void ScriptModule::PlayNote(double time, float pitch, float velocity, float pan, int noteOutputIndex, int lineNum)
{
if (velocity > 0)
{
//run through any scheduled note offs for this pitch
for (size_t i = 0; i < mScheduledNoteOutput.size(); ++i)
{
if (mScheduledNoteOutput[i].velocity == 0 &&
mScheduledNoteOutput[i].pitch == pitch &&
mScheduledNoteOutput[i].time != -1 &&
mScheduledNoteOutput[i].time - 3 <= time)
{
PlayNote(MIN(mScheduledNoteOutput[i].time, time), mScheduledNoteOutput[i].pitch, mScheduledNoteOutput[i].velocity, mScheduledNoteOutput[i].pan, mScheduledNoteOutput[i].noteOutputIndex, mScheduledNoteOutput[i].lineNum);
mScheduledNoteOutput[i].time = -1;
}
}
}
//ofLog() << "ScriptModule::PlayNote() " << velocity << " " << time;
int intPitch = int(pitch + .5f);
ModulationParameters modulation;
modulation.pan = pan;
if (pitch - intPitch != 0)
{
modulation.pitchBend = &mPitchBends[intPitch];
modulation.pitchBend->SetValue(pitch - intPitch);
}
SendNoteToIndex(noteOutputIndex, time, intPitch, (int)velocity, -1, modulation);
if (velocity > 0)
mNotePlayTracker.AddEvent(lineNum, ofToString(pitch) + " " + ofToString(velocity) + " " + ofToString(pan, 1));
}
void ScriptModule::SendNoteToIndex(int index, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (index == 0)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation, true);
return;
}
if (index - 1 < (int)mExtraNoteOutputs.size())
{
mExtraNoteOutputs[index - 1]->PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation, true);
}
}
void ScriptModule::SetNumNoteOutputs(int num)
{
while (num - 1 > (int)mExtraNoteOutputs.size())
{
auto noteCable = new AdditionalNoteCable();
noteCable->SetPatchCableSource(new PatchCableSource(this, kConnectionType_Note));
noteCable->GetPatchCableSource()->SetOverrideCableDir(ofVec2f(-1, 0), PatchCableSource::Side::kLeft);
AddPatchCableSource(noteCable->GetPatchCableSource());
noteCable->GetPatchCableSource()->SetManualPosition(0, 30 + 20 * (int)mExtraNoteOutputs.size());
mExtraNoteOutputs.push_back(noteCable);
}
}
void ScriptModule::ConnectOscInput(int port)
{
if (port != mOscInputPort)
{
mOscInputPort = port;
OSCReceiver::disconnect();
OSCReceiver::connect(port);
}
}
void ScriptModule::oscMessageReceived(const OSCMessage& msg)
{
std::string address = msg.getAddressPattern().toString().toStdString();
std::string messageString = address;
for (int i = 0; i < msg.size(); ++i)
{
if (msg[i].isFloat32())
messageString += " " + ofToString(msg[i].getFloat32());
if (msg[i].isInt32())
messageString += " " + ofToString(msg[i].getInt32());
if (msg[i].isString())
messageString += " " + msg[i].getString().toStdString();
}
RunCode(gTime, "on_osc(\"" + messageString + "\")");
}
void ScriptModule::MidiReceived(MidiMessageType messageType, int control, float value, int channel)
{
mMidiMessageQueueMutex.lock();
mMidiMessageQueue.push_back("on_midi(" + ofToString((int)messageType) + ", " + ofToString(control) + ", " + ofToString(value) + ", " + ofToString(channel) + ")");
mMidiMessageQueueMutex.unlock();
}
void ScriptModule::ButtonClicked(ClickButton* button, double time)
{
if (button == mPythonInstalledConfirmButton)
InitializePythonIfNecessary();
if (button == mRunButton)
{
mCodeEntry->Publish();
RunScript(time);
}
if (button == mStopButton)
Stop();
if (button == mSaveScriptButton)
{
FileChooser chooser("Save script as...", File(ofToDataPath("scripts/script.py")), "*.py", true, false, TheSynth->GetFileChooserParent());
if (chooser.browseForFileToSave(true))
{
std::string path = chooser.getResult().getFullPathName().toStdString();
File resourceFile(path);
TemporaryFile tempFile(resourceFile);
{
FileOutputStream output(tempFile.getFile());
if (!output.openedOk())
{
DBG("FileOutputStream didn't open correctly ...");
return;
}
output.writeText(mCodeEntry->GetText(false), false, false, nullptr);
output.flush(); // (called explicitly to force an fsync on posix)
if (output.getStatus().failed())
{
DBG("An error occurred in the FileOutputStream");
return;
}
}
bool success = tempFile.overwriteTargetFileWithTemporary();
if (!success)
{
DBG("An error occurred writing the file");
return;
}
RefreshScriptFiles();
for (size_t i = 0; i < mScriptFilePaths.size(); ++i)
{
if (mScriptFilePaths[i] == path)
{
mLoadScriptIndex = (int)i;
break;
}
}
}
}
if (button == mLoadScriptButton)
{
if (mLoadScriptIndex >= 0 && mLoadScriptIndex < (int)mScriptFilePaths.size())
{
mLoadedScriptPath = mScriptFilePaths[mLoadScriptIndex];
File resourceFile = File(mLoadedScriptPath);
if (!resourceFile.existsAsFile())
{
DBG("File doesn't exist ...");
return;
}
std::unique_ptr<FileInputStream> input(resourceFile.createInputStream());
if (!input->openedOk())
{
DBG("Failed to open file");
return;
}
mLoadedScriptFiletime = resourceFile.getLastModificationTime();
mCodeEntry->SetText(input->readString().toStdString());
}
}
if (button == mShowReferenceButton)
{
float moduleX, moduleY, moduleW, moduleH;
GetPosition(moduleX, moduleY);
GetDimensions(moduleW, moduleH);
ModuleFactory::Spawnable spawnable;
spawnable.mLabel = "scriptingreference";
TheSynth->SpawnModuleOnTheFly(spawnable, moduleX + moduleW, moduleY, true);
}
if (button == mTrustScriptButton)
{
RecordScriptAsTrusted();
mIsScriptUntrusted = false;
}
if (button == mDontTrustScriptButton)
{
TheSynth->SetAudioPaused(false);
TheSynth->ReloadInitialLayout();
}
}
void ScriptModule::DropdownClicked(DropdownList* list)
{
if (list == mLoadScriptSelector)
RefreshScriptFiles();
}
void ScriptModule::DropdownUpdated(DropdownList* list, int oldValue, double time)
{
}
void ScriptModule::RefreshStyleFiles()
{
ofxJSONElement root;
if (File(ofToDataPath("scriptstyles.json")).existsAsFile())
root.open(ofToDataPath("scriptstyles.json"));
else
root.open(ofToResourcePath("userdata_original/scriptstyles.json"));
sStyleJSON = root["styles"];
}
void ScriptModule::RefreshScriptFiles()
{
mScriptFilePaths.clear();
mLoadScriptSelector->Clear();
std::list<std::string> scripts;
for (const auto& entry : RangedDirectoryIterator{ File{ ofToDataPath("scripts") }, false, "*.py" })
{
const auto& file = entry.getFile();
scripts.push_back(file.getFileName().toStdString());
}
scripts.sort();
for (const auto& script : scripts)
{
mLoadScriptSelector->AddLabel(script, (int)mScriptFilePaths.size());
mScriptFilePaths.push_back(ofToDataPath("scripts/" + script));
}
}
void ScriptModule::ExecuteCode()
{
RunScript(NextBufferTime(false));
}
std::pair<int, int> ScriptModule::ExecuteBlock(int lineStart, int lineEnd)
{
return RunScript(gTime, lineStart, lineEnd);
}
void ScriptModule::OnCodeUpdated()
{
if (mBoundModuleConnections.size() > 0)
{
std::vector<std::string> lines = mCodeEntry->GetLines(false);
for (size_t i = 0; i < mBoundModuleConnections.size(); ++i)
{
if (mBoundModuleConnections[i].mLineText != lines[mBoundModuleConnections[i].mLineIndex])
{
bool found = false;
for (int j = 0; j < (int)lines.size(); ++j)
{
if (lines[j] == mBoundModuleConnections[i].mLineText)
{
found = true;
mBoundModuleConnections[i].mLineIndex = j;
}
}
if (!found)
mBoundModuleConnections[i].mTarget = nullptr;
}
}
}
}
void ScriptModule::OnPulse(double time, float velocity, int flags)
{
for (size_t i = 0; i < mScheduledPulseTimes.size(); ++i)
{
if (mScheduledPulseTimes[i] == -1)
{
mScheduledPulseTimes[i] = time;
break;
}
}
}
//INoteReceiver
void ScriptModule::PlayNote(double time, int pitch, int velocity, int voiceIdx /*= -1*/, ModulationParameters modulation /*= ModulationParameters()*/)
{
for (size_t i = 0; i < mPendingNoteInput.size(); ++i)
{
if (mPendingNoteInput[i].time == -1)
{
mPendingNoteInput[i].time = time;
mPendingNoteInput[i].pitch = pitch;
mPendingNoteInput[i].velocity = velocity;
break;
}
}
}
std::string ScriptModule::GetThisName()
{
return "me__" + ofToString(mScriptModuleIndex);
}
std::pair<int, int> ScriptModule::RunScript(double time, int lineStart /*=-1*/, int lineEnd /*=-1*/)
{
//should only be called from main thread
if (!sPythonInitialized)
{
TheSynth->LogEvent("trying to call ScriptModule::RunScript() before python is initialized", kLogEventType_Error);
return std::make_pair(0, 0);
}
py::exec(GetThisName() + " = scriptmodule.get_me(" + ofToString(mScriptModuleIndex) + ")", py::globals());
std::string code = mCodeEntry->GetText(true);
std::vector<std::string> lines = ofSplitString(code, "\n");
int executionStartLine = 0;
int executionEndLine = (int)lines.size();
if (lineStart != -1)
{
for (auto i = lineStart; i >= 0; --i)
{
if (lines[i][0] != ' ') //no indentation
{
executionStartLine = i;
break;
}
}
for (auto i = lineEnd + 1; i < (int)lines.size(); ++i)
{
if (lines[i][0] != ' ') //no indentation
{
executionEndLine = i - 1;
break;
}
}
}
code = "";
for (size_t i = 0; i < lines.size(); ++i)
{
std::string prefix = "";
if (i < executionStartLine || i > executionEndLine)
prefix = "#";
if (ShouldDisplayLineExecutionPre(i > 0 ? lines[i - 1] : "", lines[i]))
code += prefix + GetIndentation(lines[i]) + "me.highlight_line(" + ofToString(i) + "," + ofToString(mScriptModuleIndex) + ") ###instrumentation###\n";
code += prefix + lines[i] + "\n";
}
FixUpCode(code);
mLastRunLiteralCode = code;
RunCode(time, code);
return std::make_pair(executionStartLine, executionEndLine);
}
void ScriptModule::RunCode(double time, std::string code)
{
//should only be called from main thread
if (!sPythonInitialized)
{
TheSynth->LogEvent("trying to call ScriptModule::RunCode() before python is initialized", kLogEventType_Error);
return;
}
if (sHasLoadedUntrustedScript)
{
TheSynth->LogEvent("can't run scripts until user has added all loaded scripts to the allow list", kLogEventType_Error);
return;
}
sMostRecentRunTime = time;
mNextLineToExecute = -1;
ComputeSliders(0);
sPriorExecutedModule = nullptr;
try
{
FixUpCode(code);
py::exec(code, py::globals());
mCodeEntry->SetError(false);
mLastError = "";
}
catch (pybind11::error_already_set& e)
{
ofLog() << "python execution exception (error_already_set): " << e.what();
if (mNextLineToExecute == -1) //this script hasn't executed yet
sMostRecentLineExecutedModule = this;
sMostRecentLineExecutedModule->mLastError = (std::string)py::str(e.type()) + ": " + (std::string)py::str(e.value());
int lineNumber = sMostRecentLineExecutedModule->mNextLineToExecute;
if (lineNumber == -1)
{
std::string errorString = (std::string)py::str(e.value());
const std::string lineTextLabel = " line ";
const char* lineTextPos = strstr(errorString.c_str(), lineTextLabel.c_str());
if (lineTextPos != nullptr)
{
try
{
size_t start = lineTextPos + lineTextLabel.length() - errorString.c_str();
size_t len = errorString.size() - 1 - start;
std::string lineNumberText = errorString.substr(start, len);
int rawLineNumber = stoi(lineNumberText);
int realLineNumber = rawLineNumber - 1;
std::vector<std::string> lines = ofSplitString(sMostRecentLineExecutedModule->mLastRunLiteralCode, "\n");
for (size_t i = 0; i < lines.size() && i < rawLineNumber; ++i)
{
if (ofIsStringInString(lines[i], "###instrumentation###"))
--realLineNumber;
}
lineNumber = realLineNumber;
}
catch (std::exception)
{
}
}
}
sMostRecentLineExecutedModule->mCodeEntry->SetError(true, lineNumber);
}
catch (const std::exception& e)
{
ofLog() << "python execution exception: " << e.what();
}
}
std::string ScriptModule::GetMethodPrefix()
{
std::string prefix = Path();
ofStringReplace(prefix, "~", "");
return prefix;
}
void ScriptModule::FixUpCode(std::string& code)
{
std::string prefix = GetMethodPrefix();
ofStringReplace(code, "on_pulse(", "on_pulse__" + prefix + "(");
ofStringReplace(code, "on_note(", "on_note__" + prefix + "(");
ofStringReplace(code, "on_grid_button(", "on_grid_button__" + prefix + "(");
ofStringReplace(code, "on_osc(", "on_osc__" + prefix + "(");
ofStringReplace(code, "on_midi(", "on_midi__" + prefix + "(");
ofStringReplace(code, "this.", GetThisName() + ".");
ofStringReplace(code, "me.", GetThisName() + ".");
}
void ScriptModule::GetFirstAndLastCharacter(std::string line, char& first, char& last)
{
bool hasFirstCharacter = false;
first = 0;
last = 0;
for (size_t i = 0; i < line.length(); ++i)
{
char c = line[i];
if (c != ' ')
{
if (!hasFirstCharacter)
{
hasFirstCharacter = true;
first = c;
}
last = c;
}
}
}
bool ScriptModule::ShouldDisplayLineExecutionPre(std::string priorLine, std::string line)
{
if (!IsNonWhitespace(line))
return false;
char firstCharacter;
char lastCharacter;
GetFirstAndLastCharacter(priorLine, firstCharacter, lastCharacter);
if (firstCharacter == '@')
return false;
if (lastCharacter == ',')
return false;
GetFirstAndLastCharacter(line, firstCharacter, lastCharacter);
if (firstCharacter == '@')
return false;
if (firstCharacter == '#')
return false;
if (lastCharacter == ':' && (ofIsStringInString(line, "else") || ofIsStringInString(line, "elif") || ofIsStringInString(line, "except")))
return false;
return true;
}
std::string ScriptModule::GetIndentation(std::string line)
{
std::string ret;
for (size_t i = 0; i < line.length(); ++i)
{
if (line[i] == ' ')
ret += ' ';
else
break;
}
return ret;
}
bool ScriptModule::IsNonWhitespace(std::string line)
{
for (size_t i = 0; i < line.length(); ++i)
{
if (line[i] != ' ')
return true;
}
return false;
}
static std::string sContextToRestore = "";
void ScriptModule::SetContext()
{
sContextToRestore = IClickable::sPathLoadContext;
if (GetOwningContainer()->GetOwner() != nullptr)
IClickable::SetLoadContext(GetOwningContainer()->GetOwner());
}
void ScriptModule::ClearContext()
{
IClickable::sPathLoadContext = sContextToRestore;
}
void ScriptModule::OnModuleReferenceBound(IDrawableModule* target)
{
if (target != nullptr)
{
for (size_t i = 0; i < mBoundModuleConnections.size(); ++i)
{
if (mBoundModuleConnections[i].mTarget == target)
return;
}
std::string code = mCodeEntry->GetText(true);
std::vector<std::string> lines = ofSplitString(code, "\n");
if (mNextLineToExecute >= 0 && mNextLineToExecute < lines.size())
{
BoundModuleConnection connection;
connection.mLineIndex = mNextLineToExecute;
connection.mLineText = lines[mNextLineToExecute];
connection.mTarget = target;
mBoundModuleConnections.push_back(connection);
}
}
}
void ScriptModule::Stop()
{
double time = NextBufferTime(false);
//run through any scheduled note offs for this pitch
for (size_t i = 0; i < mScheduledNoteOutput.size(); ++i)
{
if (mScheduledNoteOutput[i].time != -1 &&
mScheduledNoteOutput[i].velocity == 0)
{
PlayNote(time, mScheduledNoteOutput[i].pitch, 0, 0, mScheduledNoteOutput[i].noteOutputIndex, mScheduledNoteOutput[i].lineNum);
mScheduledNoteOutput[i].time = -1;
}
}
Reset();
}
void ScriptModule::Reset()
{
for (size_t i = 0; i < mScheduledPulseTimes.size(); ++i)
mScheduledPulseTimes[i] = -1;
for (size_t i = 0; i < mScheduledNoteOutput.size(); ++i)
mScheduledNoteOutput[i].time = -1;
for (size_t i = 0; i < mScheduledMethodCall.size(); ++i)
mScheduledMethodCall[i].time = -1;
for (size_t i = 0; i < mScheduledUIControlValue.size(); ++i)
mScheduledUIControlValue[i].time = -1;
for (size_t i = 0; i < mPendingNoteInput.size(); ++i)
mPendingNoteInput[i].time = -1;
for (size_t i = 0; i < mPrintDisplay.size(); ++i)
mPrintDisplay[i].time = -1;
}
void ScriptModule::GetModuleDimensions(float& w, float& h)
{
w = mWidth;
h = mHeight;
}
void ScriptModule::Resize(float w, float h)
{
float entryW, entryH;
mCodeEntry->GetDimensions(entryW, entryH);
mCodeEntry->SetDimensions(entryW + w - mWidth, entryH + h - mHeight);
mRunButton->SetPosition(mRunButton->GetPosition(true).x, mRunButton->GetPosition(true).y + h - mHeight);
mStopButton->SetPosition(mStopButton->GetPosition(true).x, mStopButton->GetPosition(true).y + h - mHeight);
mASlider->SetPosition(mASlider->GetPosition(true).x, mASlider->GetPosition(true).y + h - mHeight);
mBSlider->SetPosition(mBSlider->GetPosition(true).x, mBSlider->GetPosition(true).y + h - mHeight);
mCSlider->SetPosition(mCSlider->GetPosition(true).x, mCSlider->GetPosition(true).y + h - mHeight);
mDSlider->SetPosition(mDSlider->GetPosition(true).x, mDSlider->GetPosition(true).y + h - mHeight);
mWidth = w;
mHeight = h;
}
void ScriptModule::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadBool("execute_on_init", moduleInfo, true);
mModuleSaveData.LoadInt("init_execute_priority", moduleInfo, 0, -9999, 9999, K(isTextField));
mModuleSaveData.LoadBool("syntax_highlighting", moduleInfo, true);
mModuleSaveData.LoadString("style", moduleInfo, "classic", [](DropdownList* list)
{
for (auto i = 0; i < sStyleJSON.size(); ++i)
{
try
{
list->AddLabel(sStyleJSON[i]["name"].asString(), i);
}
catch (Json::LogicError& e)
{
TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error);
}
}
});
mModuleSaveData.LoadBool("hotload_script_files", moduleInfo, false);
mModuleSaveData.LoadBool("draw_bound_module_connections", moduleInfo, true);
SetUpFromSaveData();
}
void ScriptModule::SetUpFromSaveData()
{
if (mModuleSaveData.GetBool("execute_on_init"))
{
mInitExecutePriority = mModuleSaveData.GetInt("init_execute_priority");
sScriptsRequestingInitExecution.insert(std::lower_bound(sScriptsRequestingInitExecution.begin(),
sScriptsRequestingInitExecution.end(),
this,
[](const ScriptModule* left, const ScriptModule* right)
{
return left->mInitExecutePriority < right->mInitExecutePriority;
}),
this);
}
mCodeEntry->SetDoSyntaxHighlighting(mModuleSaveData.GetBool("syntax_highlighting"));
std::string styleName = mModuleSaveData.GetString("style");
for (auto i = 0; i < sStyleJSON.size(); ++i)
{
try
{
if (sStyleJSON[i]["name"].asString() == styleName)
mCodeEntry->SetStyleFromJSON(sStyleJSON[i]);
}
catch (Json::LogicError& e)
{
TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error);
}
}
mHotloadScripts = mModuleSaveData.GetBool("hotload_script_files");
mDrawBoundModuleConnections = mModuleSaveData.GetBool("draw_bound_module_connections");
}
void ScriptModule::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void ScriptModule::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
out << (int)mExtraNoteOutputs.size();
IDrawableModule::SaveState(out);
out << mWidth;
out << mHeight;
RecordScriptAsTrusted();
}
void ScriptModule::LoadState(FileStreamIn& in, int rev)
{
if (ModularSynth::sLoadingFileSaveStateRev >= 421 && ModularSynth::sLoadingFileSaveStateRev < 423)
{
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
}
if (rev >= 2)
{
int extraNoteOutputs;
in >> extraNoteOutputs;
SetNumNoteOutputs(extraNoteOutputs + 1);
}
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev == 420)
{
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
}
float w, h;
in >> w;
in >> h;
Resize(w, h);
juce::String checksum = GetScriptChecksum();
juce::File trusted_python_scripts = File(ofToDataPath("internal/trusted_python_scripts"));
bool isScriptTrusted = false;
if (trusted_python_scripts.existsAsFile())
{
StringArray lines;
trusted_python_scripts.readLines(lines);
for (auto& line : lines)
{
if (line == checksum)
isScriptTrusted = true;
}
}
if (!isScriptTrusted)
sHasLoadedUntrustedScript = true;
mIsScriptUntrusted = !isScriptTrusted;
}
juce::String ScriptModule::GetScriptChecksum() const
{
juce::String code = mCodeEntry->GetText(false);
juce::String checksum = juce::SHA256(code.toUTF8()).toHexString();
return checksum;
}
void ScriptModule::RecordScriptAsTrusted()
{
juce::File trusted_python_scripts = File(ofToDataPath("internal/trusted_python_scripts"));
if (!trusted_python_scripts.existsAsFile())
trusted_python_scripts.create();
trusted_python_scripts.appendText("\n" + GetScriptChecksum());
}
void ScriptModule::LineEventTracker::Draw(CodeEntry* codeEntry, int style, ofColor color)
{
ofPushStyle();
ofFill();
for (int i = 0; i < (int)mText.size(); ++i)
{
float alpha = style == 0 ? 200 : 150;
float fadeMs = style == 0 ? 200 : 150;
if (gTime - mTimes[i] > 0 && gTime - mTimes[i] < fadeMs)
{
ofSetColor(color, alpha * (1 - (gTime - mTimes[i]) / fadeMs));
ofVec2f linePos = codeEntry->GetLinePos(i, false);
if (style == 0)
ofRect(linePos.x + 1, linePos.y + 3, 4, codeEntry->GetCharHeight(), L(corner, 0));
if (style == 1)
ofCircle(linePos.x + 11, linePos.y + 10, 5);
if (mText[i] != "")
{
linePos = codeEntry->GetLinePos(i, K(end));
DrawTextNormal(mText[i], linePos.x + 10, linePos.y + 15);
}
}
}
ofPopStyle();
}
ScriptReferenceDisplay::ScriptReferenceDisplay()
{
LoadText();
}
void ScriptReferenceDisplay::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mCloseButton = new ClickButton(this, "close", 3, 3);
}
ScriptReferenceDisplay::~ScriptReferenceDisplay()
{
}
void ScriptReferenceDisplay::LoadText()
{
File file(ofToResourcePath("scripting_reference.txt").c_str());
if (file.existsAsFile())
{
std::string text = file.loadFileAsString().toStdString();
ofStringReplace(text, "\r", "");
mText = ofSplitString(text, "\n");
}
mMaxScrollAmount = (int)mText.size() * 14;
}
void ScriptReferenceDisplay::DrawModule()
{
mCloseButton->Draw();
float y = 34;
for (size_t i = 0; i < mText.size(); ++i)
{
DrawTextNormal(mText[i], 4 - mScrollOffset.x, y - mScrollOffset.y);
y += 14;
}
}
bool ScriptReferenceDisplay::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll)
{
mScrollOffset.y = ofClamp(mScrollOffset.y - scrollY * 10, 0, mMaxScrollAmount);
return true;
}
void ScriptReferenceDisplay::GetModuleDimensions(float& w, float& h)
{
w = mWidth;
h = mHeight;
}
void ScriptReferenceDisplay::ButtonClicked(ClickButton* button, double time)
{
if (button == mCloseButton)
GetOwningContainer()->DeleteModule(this);
}
void ScriptWarningPopup::CreateUIControls()
{
IDrawableModule::CreateUIControls();
}
void ScriptWarningPopup::Poll()
{
IDrawableModule::Poll();
std::vector<IDrawableModule*> modules;
TheSynth->GetAllModules(modules);
int untrustedCount = 0;
for (auto* module : modules)
{
ScriptModule* script = dynamic_cast<ScriptModule*>(module);
if (script != nullptr && !script->IsScriptTrusted())
++untrustedCount;
}
mRemainingUntrustedScriptModules = untrustedCount;
if (untrustedCount == 0)
{
TheSynth->SetAudioPaused(false);
ScriptModule::sHasLoadedUntrustedScript = false;
if (Prefab::sLastLoadWasPrefab)
{
//get rid of this popup and continue loading prefab
GetOwningContainer()->DeleteModule(this);
}
else
{
//reload save file fresh
TheSynth->LoadState(TheSynth->GetLastSavePath());
}
}
}
void ScriptWarningPopup::DrawModule()
{
DrawTextNormal(std::string("") +
"heads up: this BSK file contains python scripts.\n\n" +
"generally, these python scripts are innocuous, and used to do cool things within bespoke.\n" +
"however, a malicious user could theoretically use python scripts to do bad things to your computer.\n\n" +
"do you trust the creator of this file? if so, please go to each script window and approve the script\n" +
"(" + ofToString(mRemainingUntrustedScriptModules) + " script" + (mRemainingUntrustedScriptModules == 1 ? "" : "s") + " remaining to be approved)",
3, 14);
}
``` | /content/code_sandbox/Source/ScriptModule.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 14,224 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// LFOController.h
// modularSynth
//
// Created by Ryan Challinor on 10/22/13.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "DropdownList.h"
#include "Slider.h"
#include "ClickButton.h"
class FloatSliderLFOControl;
class LFOController;
extern LFOController* TheLFOController;
class LFOController : public IDrawableModule, public IDropdownListener, public IFloatSliderListener, public IButtonListener
{
public:
LFOController();
~LFOController();
static IDrawableModule* Create() { return new LFOController(); }
static bool CanCreate() { return TheLFOController == nullptr; }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetSlider(FloatSlider* slider);
bool WantsBinding(FloatSlider* slider);
FloatSlider* GetControlled() { return mSlider; }
//IDrawableModule
void Poll() override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 130;
height = 77;
}
int dummy{ 0 };
float dummy2{ 0 };
DropdownList* mIntervalSelector{ nullptr };
DropdownList* mOscSelector{ nullptr };
FloatSlider* mMinSlider{ nullptr };
FloatSlider* mMaxSlider{ nullptr };
bool mWantBind{ false };
ClickButton* mBindButton{ nullptr };
double mStopBindTime{ -1 };
FloatSlider* mSlider{ nullptr };
FloatSliderLFOControl* mLFO{ nullptr };
};
``` | /content/code_sandbox/Source/LFOController.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 563 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// BitcrushEffect.h
// additiveSynth
//
// Created by Ryan Challinor on 11/21/12.
//
//
#pragma once
#include <iostream>
#include "IAudioEffect.h"
#include "Slider.h"
#include "Checkbox.h"
class BitcrushEffect : public IAudioEffect, public IIntSliderListener, public IFloatSliderListener
{
public:
BitcrushEffect();
static IAudioEffect* Create() { return new BitcrushEffect(); }
void CreateUIControls() override;
//IAudioEffect
void ProcessAudio(double time, ChannelBuffer* buffer) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
float GetEffectAmount() override;
std::string GetType() override { return "bitcrush"; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
float mCrush{ 1 };
float mDownsample{ 1 };
int mSampleCounter[ChannelBuffer::kMaxNumChannels]{};
float mHeldDownsample[ChannelBuffer::kMaxNumChannels]{};
FloatSlider* mCrushSlider{ nullptr };
FloatSlider* mDownsampleSlider{ nullptr };
float mWidth{ 200 };
float mHeight{ 20 };
};
``` | /content/code_sandbox/Source/BitcrushEffect.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 469 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ChordDisplayer.cpp
Created: 27 Mar 2018 9:23:27pm
Author: Ryan Challinor
==============================================================================
*/
#include "ChordDisplayer.h"
#include "SynthGlobals.h"
#include "Scale.h"
#include "FileStream.h"
#include <set>
ChordDisplayer::ChordDisplayer()
{
}
void ChordDisplayer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
std::list<int> notes = mNoteOutput.GetHeldNotesList();
if (notes.size() == 0)
return;
if (mAdvancedDetection)
{
std::vector<int> chord{ std::begin(notes), std::end(notes) };
std::set<std::string> chordNames = TheScale->GetChordDatabase().GetChordNamesAdvanced(chord, mUseScaleDegrees, mShowIntervals);
if (chordNames.size() <= 5)
{
int drawY = 14;
int drawHeight = 20;
for (std::string chordName : chordNames)
{
DrawTextNormal(chordName, 4, drawY);
drawY += drawHeight;
}
}
else
{
DrawTextNormal("(ambiguous)", 4, 14);
}
}
else
{
std::vector<int> chord{ std::begin(notes), std::end(notes) };
DrawTextNormal(TheScale->GetChordDatabase().GetChordName(chord), 4, 14);
}
}
void ChordDisplayer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void ChordDisplayer::GetModuleDimensions(float& width, float& height)
{
if (mAdvancedDetection)
{
width = 300;
height = 80;
}
else
{
width = 300;
height = 20;
}
}
void ChordDisplayer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadBool("advanced_detection", moduleInfo, false);
mModuleSaveData.LoadBool("use_scale_degrees", moduleInfo, false);
mModuleSaveData.LoadBool("show_intervals", moduleInfo, false);
SetUpFromSaveData();
}
void ChordDisplayer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mAdvancedDetection = mModuleSaveData.GetBool("advanced_detection");
mUseScaleDegrees = mModuleSaveData.GetBool("use_scale_degrees");
mShowIntervals = mModuleSaveData.GetBool("show_intervals");
}
void ChordDisplayer::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
}
void ChordDisplayer::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
LoadStateValidate(rev <= GetModuleSaveStateRev());
}
``` | /content/code_sandbox/Source/ChordDisplayer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 791 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
OSCOutput.cpp
Created: 27 Sep 2018 9:36:01pm
Author: Ryan Challinor
==============================================================================
*/
#include "OSCOutput.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
OSCOutput::OSCOutput()
{
for (int i = 0; i < OSC_OUTPUT_MAX_PARAMS; ++i)
{
mParams[i] = 0;
mLabels[i] = "slider" + ofToString(i);
}
}
OSCOutput::~OSCOutput()
{
}
void OSCOutput::Init()
{
IDrawableModule::Init();
mOscOut.connect(mOscOutAddress, mOscOutPort);
}
void OSCOutput::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
TEXTENTRY(mOscOutAddressEntry, "osc out address", 16, &mOscOutAddress);
UIBLOCK_SHIFTRIGHT();
TEXTENTRY_NUM(mOscOutPortEntry, "osc out port", 6, &mOscOutPort, 0, 99999);
UIBLOCK_NEWLINE();
UIBLOCK_SHIFTY(5);
for (int i = 0; i < 8; ++i)
{
TextEntry* labelEntry;
TEXTENTRY(labelEntry, ("label" + ofToString(i)).c_str(), 10, &mLabels[i]);
mLabelEntry.push_back(labelEntry);
UIBLOCK_SHIFTRIGHT();
FloatSlider* oscSlider;
FLOATSLIDER(oscSlider, mLabels[i].c_str(), &mParams[i], 0, 1);
mSliders.push_back(oscSlider);
UIBLOCK_NEWLINE();
}
UIBLOCK_SHIFTY(5);
TEXTENTRY(mNoteOutLabelEntry, "note out address", 10, &mNoteOutLabel);
ENDUIBLOCK(mWidth, mHeight);
mNoteOutLabelEntry->DrawLabel(true);
}
void OSCOutput::Poll()
{
ComputeSliders(0);
}
void OSCOutput::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mOscOutAddressEntry->Draw();
mOscOutPortEntry->Draw();
for (auto* entry : mLabelEntry)
entry->Draw();
for (auto* slider : mSliders)
slider->Draw();
mNoteOutLabelEntry->Draw();
}
void OSCOutput::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mNoteOutLabel.size() > 0)
{
juce::OSCMessage msg(("/bespoke/" + mNoteOutLabel).c_str());
float pitchOut = pitch;
if (modulation.pitchBend != nullptr)
pitchOut += modulation.pitchBend->GetValue(0);
msg.addFloat32(pitchOut);
msg.addFloat32(velocity);
mOscOut.send(msg);
}
}
void OSCOutput::SendFloat(std::string address, float val)
{
juce::OSCMessage msg(address.c_str());
msg.addFloat32(val);
mOscOut.send(msg);
}
void OSCOutput::SendInt(std::string address, int val)
{
juce::OSCMessage msg(address.c_str());
msg.addInt32(val);
mOscOut.send(msg);
}
void OSCOutput::SendString(std::string address, std::string val)
{
juce::OSCMessage msg(address.c_str());
msg.addString(val);
mOscOut.send(msg);
}
void OSCOutput::GetModuleDimensions(float& w, float& h)
{
w = mWidth;
h = mHeight;
}
void OSCOutput::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
juce::String address = "/bespoke/";
address += slider->Name();
juce::OSCMessage msg(address);
msg.addFloat32(slider->GetValue());
mOscOut.send(msg);
}
void OSCOutput::TextEntryComplete(TextEntry* entry)
{
int i = 0;
for (auto* iter : mLabelEntry)
{
if (iter == entry)
{
auto sliderIter = mSliders.begin();
advance(sliderIter, i);
(*sliderIter)->SetName(mLabels[i].c_str());
}
++i;
}
if (entry == mOscOutAddressEntry || entry == mOscOutPortEntry)
{
mOscOut.disconnect();
mOscOut.connect(mOscOutAddress, mOscOutPort);
}
}
void OSCOutput::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void OSCOutput::SetUpFromSaveData()
{
}
void OSCOutput::SaveLayout(ofxJSONElement& moduleInfo)
{
}
``` | /content/code_sandbox/Source/OSCOutput.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,160 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// PitchAssigner.h
// Bespoke
//
// Created by Ryan Challinor on 11/27/15.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
class PitchSetter : public NoteEffectBase, public IDrawableModule, public IIntSliderListener
{
public:
PitchSetter();
static IDrawableModule* Create() { return new PitchSetter(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 90;
height = 20;
}
int mPitch{ 36 };
IntSlider* mPitchSlider{ nullptr };
};
``` | /content/code_sandbox/Source/PitchSetter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 429 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
EnvelopeModulator.cpp
Created: 16 Nov 2017 10:28:34pm
Author: Ryan Challinor
==============================================================================
*/
#include "EnvelopeModulator.h"
#include "PatchCableSource.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
EnvelopeModulator::EnvelopeModulator()
{
mAdsr.GetFreeReleaseLevel() = true;
}
void EnvelopeModulator::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
mAdsrDisplay = new ADSRDisplay(this, "adsr", 105, 2, 100, 66, &mAdsr);
UIBLOCK0();
FLOATSLIDER(mMinSlider, "low", &mDummyMin, 0, 1);
FLOATSLIDER(mMaxSlider, "high", &mDummyMax, 0, 1);
CHECKBOX(mUseVelocityCheckbox, "use velocity", &mUseVelocity);
ENDUIBLOCK0();
}
EnvelopeModulator::~EnvelopeModulator()
{
}
void EnvelopeModulator::DrawModule()
{
if (Minimized())
return;
mMinSlider->Draw();
mMaxSlider->Draw();
mUseVelocityCheckbox->Draw();
mAdsrDisplay->Draw();
}
void EnvelopeModulator::Start(double time, const ::ADSR& adsr)
{
mAdsr.Start(time, 1, adsr);
}
void EnvelopeModulator::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
if (mNoteOutput.HasHeldNotes() == false)
{
mAdsr.Stop(time);
}
else if (velocity > 0)
{
mAdsr.Start(time, mUseVelocity ? velocity / 127.0f : 1);
}
}
void EnvelopeModulator::OnPulse(double time, float velocity, int flags)
{
mAdsr.Start(time, mUseVelocity ? velocity / 127.0f : 1);
}
void EnvelopeModulator::GetModuleDimensions(float& width, float& height)
{
width = 208;
height = 73;
}
void EnvelopeModulator::Resize(float w, float h)
{
mWidth = MAX(w, 250);
mHeight = MAX(h, 102);
}
void EnvelopeModulator::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
}
void EnvelopeModulator::MouseReleased()
{
IDrawableModule::MouseReleased();
}
bool EnvelopeModulator::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
return false;
}
float EnvelopeModulator::Value(int samplesIn /*= 0*/)
{
ComputeSliders(samplesIn);
if (GetSliderTarget())
return ofClamp(Interp(mAdsr.Value(gTime + samplesIn * gInvSampleRateMs), GetMin(), GetMax()), GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax());
return 0;
}
void EnvelopeModulator::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
}
void EnvelopeModulator::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void EnvelopeModulator::ButtonClicked(ClickButton* button, double time)
{
}
void EnvelopeModulator::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void EnvelopeModulator::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void EnvelopeModulator::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void EnvelopeModulator::SetUpFromSaveData()
{
}
void EnvelopeModulator::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mAdsr.SaveState(out);
}
void EnvelopeModulator::LoadState(FileStreamIn& in, int rev)
{
if (rev < 1)
{
// Temporary additional cable source
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
}
IDrawableModule::LoadState(in, rev);
if (rev < 1)
{
const auto target = GetPatchCableSource(1)->GetTarget();
if (target != nullptr)
GetPatchCableSource()->SetTarget(target);
RemovePatchCableSource(GetPatchCableSource(1));
mTargetCable = GetPatchCableSource();
}
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
mAdsr.LoadState(in);
}
``` | /content/code_sandbox/Source/EnvelopeModulator.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,227 |
```c++
#include "ModularSynth.h"
#include "IAudioSource.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "Scale.h"
#include "Transport.h"
#include "TextEntry.h"
#include "InputChannel.h"
#include "OutputChannel.h"
#include "TitleBar.h"
#include "LFOController.h"
#include "MidiController.h"
#include "ChaosEngine.h"
#include "ModuleSaveDataPanel.h"
#include "Profiler.h"
#include "Sample.h"
#include "FloatSliderLFOControl.h"
//#include <CoreServices/CoreServices.h>
#include "fenv.h"
#include <stdlib.h>
#include "GridController.h"
#include "FileStream.h"
#include "PatchCable.h"
#include "ADSRDisplay.h"
#include "QuickSpawnMenu.h"
#include "AudioToCV.h"
#include "ScriptModule.h"
#include "DrumPlayer.h"
#include "VSTPlugin.h"
#include "Prefab.h"
#include "HelpDisplay.h"
#include "nanovg/nanovg.h"
#include "UserPrefsEditor.h"
#include "Canvas.h"
#include "EffectChain.h"
#include "ClickButton.h"
#include "UserPrefs.h"
#include "NoteOutputQueue.h"
#include "juce_audio_processors/juce_audio_processors.h"
#include "juce_audio_formats/juce_audio_formats.h"
#if BESPOKE_WINDOWS
#include <windows.h>
#include <dbghelp.h>
#include <winbase.h>
#endif
ModularSynth* TheSynth = nullptr;
namespace
{
juce::String TheClipboard;
}
//static
bool ModularSynth::sShouldAutosave = false;
float ModularSynth::sBackgroundLissajousR = 0.408f;
float ModularSynth::sBackgroundLissajousG = 0.245f;
float ModularSynth::sBackgroundLissajousB = 0.418f;
float ModularSynth::sBackgroundR = 0.09f;
float ModularSynth::sBackgroundG = 0.09f;
float ModularSynth::sBackgroundB = 0.09f;
float ModularSynth::sCableAlpha = 1.0f;
int ModularSynth::sLoadingFileSaveStateRev = ModularSynth::kSaveStateRev;
int ModularSynth::sLastLoadedFileSaveStateRev = ModularSynth::kSaveStateRev;
std::thread::id ModularSynth::sAudioThreadId;
#if BESPOKE_WINDOWS
LONG WINAPI TopLevelExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo);
#endif
using namespace juce;
void AtExit()
{
TheSynth->Exit();
}
ModularSynth::ModularSynth()
{
assert(TheSynth == nullptr);
TheSynth = this;
#if BESPOKE_WINDOWS
SetUnhandledExceptionFilter(TopLevelExceptionHandler);
#endif
mAudioPluginFormatManager = std::make_unique<juce::AudioPluginFormatManager>();
mKnownPluginList = std::make_unique<juce::KnownPluginList>();
mAudioPluginFormatManager->addDefaultFormats();
}
ModularSynth::~ModularSynth()
{
DeleteAllModules();
delete mGlobalRecordBuffer;
mAudioPluginFormatManager.reset();
mKnownPluginList.reset();
SetMemoryTrackingEnabled(false); //avoid crashes when the tracking lists themselves are deleted
assert(TheSynth == this);
TheSynth = nullptr;
ScriptModule::UninitializePython();
}
void ModularSynth::CrashHandler(void*)
{
DumpStats(true, nullptr);
}
#if BESPOKE_WINDOWS
LONG WINAPI TopLevelExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)
{
ModularSynth::DumpStats(true, pExceptionInfo);
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
void ModularSynth::DumpStats(bool isCrash, void* crashContext)
{
std::string filename;
if (isCrash)
filename = ofToDataPath(ofGetTimestampString("crash_%Y-%m-%d_%H-%M.txt"));
else
filename = ofToDataPath(ofGetTimestampString("stats_%Y-%m-%d_%H-%M.txt"));
juce::File log(filename);
if (isCrash)
{
#if BESPOKE_WINDOWS
if (crashContext != nullptr)
{
log.appendText("stack frame:\n");
PEXCEPTION_POINTERS pExceptionInfo = (PEXCEPTION_POINTERS)crashContext;
HANDLE process = GetCurrentProcess();
SymInitialize(process, NULL, TRUE);
// StackWalk64() may modify context record passed to it, so we will
// use a copy.
CONTEXT context_record = *pExceptionInfo->ContextRecord;
// Initialize stack walking.
STACKFRAME64 stack_frame;
memset(&stack_frame, 0, sizeof(stack_frame));
#if defined(_WIN64)
int machine_type = IMAGE_FILE_MACHINE_AMD64;
stack_frame.AddrPC.Offset = context_record.Rip;
stack_frame.AddrFrame.Offset = context_record.Rbp;
stack_frame.AddrStack.Offset = context_record.Rsp;
#else
int machine_type = IMAGE_FILE_MACHINE_I386;
stack_frame.AddrPC.Offset = context_record.Eip;
stack_frame.AddrFrame.Offset = context_record.Ebp;
stack_frame.AddrStack.Offset = context_record.Esp;
#endif
stack_frame.AddrPC.Mode = AddrModeFlat;
stack_frame.AddrFrame.Mode = AddrModeFlat;
stack_frame.AddrStack.Mode = AddrModeFlat;
juce::HeapBlock<SYMBOL_INFO> symbol;
symbol.calloc(sizeof(SYMBOL_INFO) + 256, 1);
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
while (StackWalk64(machine_type,
GetCurrentProcess(),
GetCurrentThread(),
&stack_frame,
&context_record,
NULL,
&SymFunctionTableAccess64,
&SymGetModuleBase64,
NULL))
{
DWORD64 displacement = 0;
if (SymFromAddr(process, (DWORD64)stack_frame.AddrPC.Offset, &displacement, symbol))
{
IMAGEHLP_MODULE64 moduleInfo;
juce::zerostruct(moduleInfo);
moduleInfo.SizeOfStruct = sizeof(moduleInfo);
if (::SymGetModuleInfo64(process, symbol->ModBase, &moduleInfo))
log.appendText(String(moduleInfo.ModuleName) + String(": "));
log.appendText(String(symbol->Name) + String(" + 0x") + String::toHexString((juce::int64)displacement) + "\n");
}
}
log.appendText("\n\n\n");
}
#endif
log.appendText("backtrace:\n");
log.appendText(juce::SystemStats::getStackBacktrace());
log.appendText("\n\n\n");
}
log.appendText("OS: " + juce::SystemStats::getOperatingSystemName() + "\n");
log.appendText("CPU vendor: " + juce::SystemStats::getCpuVendor() + "\n");
log.appendText("CPU model: " + juce::SystemStats::getCpuModel() + "\n");
log.appendText("CPU speed: " + ofToString(juce::SystemStats::getCpuSpeedInMegahertz()) + " MHz\n");
log.appendText("num cores: " + ofToString(juce::SystemStats::getNumCpus()) + "\n");
log.appendText("num CPUs: " + ofToString(juce::SystemStats::getNumPhysicalCpus()) + "\n");
log.appendText("RAM: " + ofToString(juce::SystemStats::getMemorySizeInMegabytes()) + " MB\n");
log.appendText("computer: " + juce::SystemStats::getComputerName() + "\n");
log.appendText("language: " + juce::SystemStats::getUserLanguage() + "\n");
log.appendText("region: " + juce::SystemStats::getUserRegion() + "\n");
log.appendText("display language: " + juce::SystemStats::getDisplayLanguage() + "\n");
log.appendText("description: " + juce::SystemStats::getDeviceDescription() + "\n");
log.appendText("manufacturer: " + juce::SystemStats::getDeviceManufacturer() + "\n");
log.appendText("build: bespoke " + GetBuildInfoString() + ")\n");
}
bool ModularSynth::IsReady()
{
return gTime > 100;
}
void ModularSynth::Setup(juce::AudioDeviceManager* globalAudioDeviceManager, juce::AudioFormatManager* globalAudioFormatManager, juce::Component* mainComponent, juce::OpenGLContext* openGLContext)
{
mGlobalAudioDeviceManager = globalAudioDeviceManager;
mGlobalAudioFormatManager = globalAudioFormatManager;
mMainComponent = mainComponent;
mOpenGLContext = openGLContext;
sShouldAutosave = UserPrefs.autosave.Get();
mIOBufferSize = gBufferSize;
mGlobalRecordBuffer = new RollingBuffer(UserPrefs.record_buffer_length_minutes.Get() * 60 * gSampleRate);
mGlobalRecordBuffer->SetNumChannels(2);
juce::File(ofToDataPath("savestate")).createDirectory();
juce::File(ofToDataPath("savestate/autosave")).createDirectory();
juce::File(ofToDataPath("recordings")).createDirectory();
juce::File(ofToDataPath("samples")).createDirectory();
juce::File(ofToDataPath("scripts")).createDirectory();
juce::File(ofToDataPath("internal")).createDirectory();
juce::File(ofToDataPath("vst")).createDirectory();
SynthInit();
new Transport();
new Scale();
TheScale->CreateUIControls();
TheTransport->CreateUIControls();
TheScale->Init();
TheTransport->Init();
DrumPlayer::SetUpHitDirectories();
sBackgroundLissajousR = UserPrefs.lissajous_r.Get();
sBackgroundLissajousG = UserPrefs.lissajous_g.Get();
sBackgroundLissajousB = UserPrefs.lissajous_b.Get();
sBackgroundR = UserPrefs.background_r.Get();
sBackgroundG = UserPrefs.background_g.Get();
sBackgroundB = UserPrefs.background_b.Get();
sCableAlpha = UserPrefs.cable_alpha.Get();
Time time = Time::getCurrentTime();
if (fabsf(sBackgroundR - UserPrefs.background_r.GetDefault()) < .001f && fabsf(sBackgroundG - UserPrefs.background_g.GetDefault()) < .001f && fabsf(sBackgroundB - UserPrefs.background_b.GetDefault()) < .001f && time.getMonth() + 1 == 10 && time.getDayOfMonth() == 31)
{
sBackgroundLissajousR = 0.722f;
sBackgroundLissajousG = 0.328f;
sBackgroundLissajousB = 0.0f;
}
ResetLayout();
mConsoleListener = new ConsoleListener();
mConsoleEntry = new TextEntry(mConsoleListener, "console", 0, 20, 50, mConsoleText);
mConsoleEntry->SetRequireEnter(true);
}
void ModularSynth::LoadResources(void* nanoVG, void* fontBoundsNanoVG)
{
gNanoVG = (NVGcontext*)nanoVG;
gFontBoundsNanoVG = (NVGcontext*)fontBoundsNanoVG;
LoadGlobalResources();
if (!gFont.IsLoaded())
mFatalError = "couldn't load font from " + gFont.GetFontPath() + "\nmaybe bespoke can't find your resources directory?";
}
void ModularSynth::InitIOBuffers(int inputChannelCount, int outputChannelCount)
{
for (int i = 0; i < inputChannelCount; ++i)
mInputBuffers.push_back(new float[gBufferSize]);
for (int i = 0; i < outputChannelCount; ++i)
mOutputBuffers.push_back(new float[gBufferSize]);
}
std::string ModularSynth::GetUserPrefsPath()
{
std::string filename = "userprefs.json";
for (int i = 0; i < JUCEApplication::getCommandLineParameterArray().size(); ++i)
{
juce::String specified = JUCEApplication::getCommandLineParameterArray()[i];
if (specified.endsWith(".json"))
{
filename = specified.toStdString();
if (!juce::File(ofToDataPath(filename)).existsAsFile())
TheSynth->SetFatalError("couldn't find command-line-specified userprefs file at " + ofToDataPath(filename));
break;
}
}
return ofToDataPath(filename);
}
static int sFrameCount = 0;
void ModularSynth::Poll()
{
if (mFatalError == "")
{
if (!mInitialized && sFrameCount > 3) //let some frames render before blocking for a load
{
mUserPrefsEditor->CreatePrefsFileIfNonexistent();
if (!mStartupSaveStateFile.empty())
LoadState(mStartupSaveStateFile);
else
LoadLayoutFromFile(ofToDataPath(UserPrefs.layout.Get()));
mInitialized = true;
}
if (mWantReloadInitialLayout)
{
LoadLayoutFromFile(ofToDataPath(UserPrefs.layout.Get()));
mWantReloadInitialLayout = false;
}
}
mZoomer.Update();
if (!mIsLoadingState)
{
for (auto p : mExtraPollers)
p->Poll();
mModuleContainer.Poll();
mUILayerModuleContainer.Poll();
}
if (mShowLoadStatePopup)
{
mShowLoadStatePopup = false;
LoadStatePopupImp();
}
if (mScheduledEnvelopeEditorSpawnDisplay != nullptr)
{
mScheduledEnvelopeEditorSpawnDisplay->SpawnEnvelopeEditor();
mScheduledEnvelopeEditorSpawnDisplay = nullptr;
}
{
static MouseCursor sCurrentCursor = MouseCursor::NormalCursor;
MouseCursor desiredCursor;
if (mIsLoadingState)
{
desiredCursor = MouseCursor::WaitCursor;
}
else if (gHoveredUIControl != nullptr && gHoveredUIControl->IsMouseDown())
{
if (GetKeyModifiers() == kModifier_Shift)
desiredCursor = MouseCursor::CrosshairCursor;
else if (dynamic_cast<FloatSlider*>(gHoveredUIControl) != nullptr && dynamic_cast<FloatSlider*>(gHoveredUIControl)->GetModulator() != nullptr && dynamic_cast<FloatSlider*>(gHoveredUIControl)->GetModulator()->Active())
desiredCursor = MouseCursor::UpDownLeftRightResizeCursor;
else
desiredCursor = MouseCursor::LeftRightResizeCursor;
}
else if (gHoveredUIControl != nullptr && gHoveredUIControl->IsTextEntry())
{
desiredCursor = MouseCursor::IBeamCursor;
}
else if (gHoveredUIControl != nullptr && dynamic_cast<Canvas*>(gHoveredUIControl) != nullptr)
{
desiredCursor = dynamic_cast<Canvas*>(gHoveredUIControl)->GetMouseCursorType();
}
else if (mIsMousePanning)
{
desiredCursor = MouseCursor::DraggingHandCursor;
}
else if (GetKeyModifiers() == kModifier_Shift)
{
desiredCursor = MouseCursor::PointingHandCursor;
}
else
{
desiredCursor = MouseCursor::NormalCursor;
}
if (desiredCursor != sCurrentCursor)
{
sCurrentCursor = desiredCursor;
mMainComponent->setMouseCursor(desiredCursor);
}
}
bool shiftPressed = (GetKeyModifiers() == kModifier_Shift);
if (shiftPressed && !mIsShiftPressed && IKeyboardFocusListener::GetActiveKeyboardFocus() == nullptr)
{
double timeBetweenPresses = gTime - mLastShiftPressTime;
if (timeBetweenPresses < 400)
{
ToggleQuickSpawn();
mLastShiftPressTime = -9999; //clear timer
}
else
{
mLastShiftPressTime = gTime;
}
}
mIsShiftPressed = shiftPressed;
if (mArrangeDependenciesWhenLoadCompletes && !mIsLoadingState)
{
ArrangeAudioSourceDependencies();
mArrangeDependenciesWhenLoadCompletes = false;
}
++sFrameCount;
}
void ModularSynth::DeleteAllModules()
{
mModuleContainer.Clear();
for (int i = 0; i < mDeletedModules.size(); ++i)
delete mDeletedModules[i];
mDeletedModules.clear();
delete TheScale;
TheScale = nullptr;
delete TheTransport;
TheTransport = nullptr;
delete mConsoleListener;
mConsoleListener = nullptr;
}
bool SortPointsByY(ofVec2f a, ofVec2f b)
{
return a.y < b.y;
}
void ModularSynth::ZoomView(float zoomAmount, bool fromMouse)
{
float oldDrawScale = gDrawScale;
gDrawScale *= 1 + zoomAmount;
float minZoom = .1f;
float maxZoom = 8;
gDrawScale = ofClamp(gDrawScale, minZoom, maxZoom);
zoomAmount = (gDrawScale - oldDrawScale) / oldDrawScale; //find actual adjusted amount
ofVec2f zoomCenter;
if (fromMouse)
zoomCenter = ofVec2f(GetMouseX(&mModuleContainer), GetMouseY(&mModuleContainer)) + GetDrawOffset();
else
zoomCenter = ofVec2f(ofGetWidth() / gDrawScale * .5f, ofGetHeight() / gDrawScale * .5f);
GetDrawOffset() -= zoomCenter * zoomAmount;
mZoomer.CancelMovement();
mHideTooltipsUntilMouseMove = true;
}
void ModularSynth::SetZoomLevel(float zoomLevel)
{
float oldDrawScale = gDrawScale;
gDrawScale = zoomLevel;
float zoomAmount = (gDrawScale - oldDrawScale) / oldDrawScale;
ofVec2f zoomCenter = ofVec2f(ofGetWidth() / gDrawScale * .5f, ofGetHeight() / gDrawScale * .5f);
GetDrawOffset() -= zoomCenter * zoomAmount;
mZoomer.CancelMovement();
mHideTooltipsUntilMouseMove = true;
}
void ModularSynth::PanView(float x, float y)
{
GetDrawOffset() += ofVec2f(x, y) / gDrawScale;
mHideTooltipsUntilMouseMove = true;
}
void ModularSynth::PanTo(float x, float y)
{
SetDrawOffset(ofVec2f(ofGetWidth() / gDrawScale / 2 - x, ofGetHeight() / gDrawScale / 2 - y));
mHideTooltipsUntilMouseMove = true;
}
void ModularSynth::Draw(void* vg)
{
gNanoVG = (NVGcontext*)vg;
ofNoFill();
//DrawTextNormal("fps: "+ofToString(ofGetFrameRate(),4)+" "+ofToString(ofGetWidth()*ofGetHeight()), 100, 100,50);
//return;
mModuleContainer.SetDrawScale(gDrawScale);
mDrawRect.set(-GetDrawOffset().x, -GetDrawOffset().y, ofGetWidth() / gDrawScale, ofGetHeight() / gDrawScale);
if (mFatalError != "")
{
ofSetColor(255, 255, 255, 255);
DrawFallbackText(("bespoke " + GetBuildInfoString()).c_str(), 100, 50);
if (gFont.IsLoaded())
DrawTextNormal(mFatalError, 100, 100, 18);
else
DrawFallbackText(mFatalError.c_str(), 100, 100);
}
if (ScriptModule::sBackgroundTextString != "")
{
ofPushStyle();
ofSetColor(ScriptModule::sBackgroundTextColor);
DrawTextBold(ScriptModule::sBackgroundTextString, ScriptModule::sBackgroundTextPos.x, ScriptModule::sBackgroundTextPos.y + ScriptModule::sBackgroundTextSize, ScriptModule::sBackgroundTextSize);
ofPopStyle();
}
if (UserPrefs.draw_background_lissajous.Get())
DrawLissajous(mGlobalRecordBuffer, 0, 0, ofGetWidth(), ofGetHeight(), sBackgroundLissajousR, sBackgroundLissajousG, sBackgroundLissajousB);
if (gTime == 1 && mFatalError == "")
{
std::string loading("Bespoke is initializing audio...");
DrawTextNormal(loading, ofGetWidth() / 2 - GetStringWidth(loading, 28) / 2, ofGetHeight() / 2 - 6, 28);
return;
}
if (!mInitialized && mFatalError == "")
{
std::string loading("Bespoke is loading...");
DrawTextNormal(loading, ofGetWidth() / 2 - GetStringWidth(loading, 28) / 2, ofGetHeight() / 2 - 6, 28);
return;
}
ofPushMatrix();
ofScale(gDrawScale, gDrawScale, gDrawScale);
ofPushMatrix();
ofTranslate(GetDrawOffset().x, GetDrawOffset().y);
if (ShouldShowGridSnap())
{
ofPushStyle();
ofSetLineWidth(.5f);
ofSetColor(255, 255, 255, 40);
float gridSnapSize = UserPrefs.grid_snap_size.Get();
int gridLinesVertical = (int)ceil((ofGetWidth() / gDrawScale) / gridSnapSize);
for (int i = 0; i < gridLinesVertical; ++i)
{
float x = i * gridSnapSize - floor(GetDrawOffset().x / gridSnapSize) * gridSnapSize;
ofLine(x, -GetDrawOffset().y, x, -GetDrawOffset().y + ofGetHeight() / gDrawScale);
}
int gridLinesHorizontal = (int)ceil((ofGetHeight() / gDrawScale) / gridSnapSize);
for (int i = 0; i < gridLinesHorizontal; ++i)
{
float y = i * gridSnapSize - floor(GetDrawOffset().y / gridSnapSize) * gridSnapSize;
ofLine(-GetDrawOffset().x, y, -GetDrawOffset().x + ofGetWidth() / gDrawScale, y);
}
ofPopStyle();
}
ofNoFill();
TheSaveDataPanel->SetShowing(TheSaveDataPanel->GetModule());
TheSaveDataPanel->UpdatePosition();
mModuleContainer.DrawContents();
IClickable* dropTarget = nullptr;
if (PatchCable::sActivePatchCable != nullptr)
dropTarget = PatchCable::sActivePatchCable->GetDropTarget();
if (dropTarget)
{
ofPushStyle();
ofSetColor(255, 255, 255, 100);
ofSetLineWidth(.5f);
ofFill();
ofRectangle rect = dropTarget->GetRect();
IDrawableModule* dropTargetModule = dynamic_cast<IDrawableModule*>(dropTarget);
if (dropTargetModule && dropTargetModule->HasTitleBar())
{
rect.y -= IDrawableModule::TitleBarHeight();
rect.height += IDrawableModule::TitleBarHeight();
}
ofRect(rect);
ofPopStyle();
}
for (int i = 0; i < mLissajousDrawers.size(); ++i)
{
float moduleX, moduleY;
mLissajousDrawers[i]->GetPosition(moduleX, moduleY);
IAudioSource* source = dynamic_cast<IAudioSource*>(mLissajousDrawers[i]);
DrawLissajous(source->GetVizBuffer(), moduleX, moduleY - 240, 240, 240);
}
if (mGroupSelectContext != nullptr)
{
ofPushStyle();
ofSetColor(255, 255, 255);
ofRect(mClickStartX, mClickStartY, GetMouseX(&mModuleContainer) - mClickStartX, GetMouseY(&mModuleContainer) - mClickStartY);
ofPopStyle();
}
const bool kDrawCursorDot = false;
if (kDrawCursorDot)
{
ofPushStyle();
ofSetColor(255, 255, 255);
ofCircle(GetMouseX(&mModuleContainer), GetMouseY(&mModuleContainer), 1);
ofPopStyle();
}
/*TODO_PORT(Ryan)
const int starvationDisplayTicks = 500;
if (mSoundStream.getTickCount() - mSoundStream.GetLastStarvationTick() < starvationDisplayTicks)
{
ofPushStyle();
ofSetColor(255,255,255, (1.0f-(float(mSoundStream.getTickCount() - mSoundStream.GetLastStarvationTick())/starvationDisplayTicks))*255);
DrawTextNormal("X", 5, 15);
ofPopStyle();
}*/
if (mHeldSample)
{
ofPushMatrix();
ofPushStyle();
ofTranslate(GetMouseX(&mModuleContainer), GetMouseY(&mModuleContainer));
ofClipWindow(0, 0, 120, 70, true);
DrawAudioBuffer(120, 70, mHeldSample->Data(), 0, mHeldSample->LengthInSamples(), -1);
ofSetColor(255, 255, 255);
DrawTextNormal(mHeldSample->Name(), 0, 13);
ofPopStyle();
ofPopMatrix();
}
/*ofPushStyle();
ofNoFill();
ofSetLineWidth(3);
ofSetColor(0,255,0,100);
ofSetCircleResolution(100);
ofCircle(GetMouseX(&mModuleContainer), GetMouseY(&mModuleContainer), 30 + (TheTransport->GetMeasurePos() * 20));
ofPopStyle();*/
ofPopMatrix();
if (gTime - mLastClapboardTime < 100)
{
ofSetColor(255, 255, 255, (1 - (gTime - mLastClapboardTime) / 100) * 255);
ofFill();
ofRect(0, 0, ofGetWidth(), ofGetHeight());
}
ofPopMatrix();
ofPushMatrix();
{
float uiScale = mUILayerModuleContainer.GetDrawScale();
if (uiScale < .01f)
{
//safety check in case anything ever makes the UI inaccessible
LogEvent("correcting UI scale", kLogEventType_Error);
mUILayerModuleContainer.SetDrawScale(1);
uiScale = mUILayerModuleContainer.GetDrawScale();
}
ofScale(uiScale, uiScale, uiScale);
ofTranslate(mUILayerModuleContainer.GetDrawOffset().x, mUILayerModuleContainer.GetDrawOffset().y);
mUILayerModuleContainer.DrawContents();
Profiler::Draw();
DrawConsole();
}
ofPopMatrix();
for (auto* modal : mModalFocusItemStack)
{
ofPushMatrix();
float scale = modal->GetOwningContainer()->GetDrawScale();
ofVec2f offset = modal->GetOwningContainer()->GetDrawOffset();
ofScale(scale, scale, scale);
ofTranslate(offset.x, offset.y);
modal->Draw();
ofPopMatrix();
}
std::string tooltip = "";
ModuleContainer* tooltipContainer = nullptr;
ofVec2f tooltipPos(FLT_MAX, FLT_MAX);
if (mNextDrawTooltip != "")
{
tooltip = mNextDrawTooltip;
tooltipContainer = &mModuleContainer;
}
else if (HelpDisplay::sShowTooltips &&
!mHideTooltipsUntilMouseMove &&
!IUIControl::WasLastHoverSetManually() &&
mGroupSelectContext == nullptr &&
PatchCable::sActivePatchCable == nullptr &&
mGroupSelectedModules.empty() &&
mHeldSample == nullptr)
{
HelpDisplay* helpDisplay = TheTitleBar->GetHelpDisplay();
bool hasValidHoveredControl = gHoveredUIControl && gHoveredUIControl->GetModuleParent() && !gHoveredUIControl->GetModuleParent()->IsDeleted() && std::string(gHoveredUIControl->Name()) != "enabled";
if (gHoveredModule && (!hasValidHoveredControl || (gHoveredUIControl != nullptr && gHoveredUIControl->GetModuleParent() != gHoveredModule)))
{
if (gHoveredModule == mQuickSpawn)
{
std::string name = mQuickSpawn->GetHoveredModuleTypeName();
ofStringReplace(name, " " + std::string(ModuleFactory::kEffectChainSuffix), ""); //strip this suffix if it's there
tooltip = helpDisplay->GetModuleTooltipFromName(name);
tooltipContainer = mQuickSpawn->GetOwningContainer();
}
else if (gHoveredModule == GetTopModalFocusItem() && dynamic_cast<DropdownListModal*>(gHoveredModule))
{
DropdownListModal* list = dynamic_cast<DropdownListModal*>(gHoveredModule);
if (list->GetOwner()->GetModuleParent() == TheTitleBar)
{
std::string moduleTypeName = dynamic_cast<DropdownListModal*>(gHoveredModule)->GetHoveredLabel();
ofStringReplace(moduleTypeName, " (exp.)", "");
tooltip = helpDisplay->GetModuleTooltipFromName(moduleTypeName);
tooltipContainer = &mUILayerModuleContainer;
}
else if (dynamic_cast<EffectChain*>(list->GetOwner()->GetParent()) != nullptr)
{
std::string effectName = dynamic_cast<DropdownListModal*>(gHoveredModule)->GetHoveredLabel();
tooltip = helpDisplay->GetModuleTooltipFromName(effectName);
tooltipContainer = list->GetModuleParent()->GetOwningContainer();
}
}
else if (GetMouseY(&mModuleContainer) < gHoveredModule->GetPosition().y && gHoveredModule->HasTitleBar()) //this means we're hovering over the module's title bar
{
tooltip = helpDisplay->GetModuleTooltip(gHoveredModule);
tooltipContainer = gHoveredModule->GetOwningContainer();
}
if (tooltipContainer != nullptr)
{
tooltipPos.x = gHoveredModule->GetRect().getMaxX() + 10;
tooltipPos.y = GetMouseY(tooltipContainer) + 7;
}
}
else if (hasValidHoveredControl && !gHoveredUIControl->IsMouseDown())
{
tooltip = helpDisplay->GetUIControlTooltip(gHoveredUIControl);
tooltipContainer = gHoveredUIControl->GetModuleParent()->GetOwningContainer();
tooltipPos.x = gHoveredUIControl->GetRect().getMaxX() + 10;
tooltipPos.y = GetMouseY(tooltipContainer) + 18;
}
}
mNextDrawTooltip = "";
if (tooltip != "" && tooltipContainer != nullptr)
{
if (tooltipPos.x == FLT_MAX)
{
tooltipPos.x = GetMouseX(tooltipContainer) + 25;
tooltipPos.y = GetMouseY(tooltipContainer) + 30;
}
ofPushMatrix();
float scale = tooltipContainer->GetDrawScale();
ofVec2f offset = tooltipContainer->GetDrawOffset();
ofScale(scale, scale, scale);
ofTranslate(offset.x, offset.y);
float maxWidth = 300;
float fontSize = 13;
nvgFontFaceId(gNanoVG, gFont.GetFontHandle());
nvgFontSize(gNanoVG, fontSize);
float bounds[4];
nvgTextBoxBounds(gNanoVG, tooltipPos.x, tooltipPos.y, maxWidth, tooltip.c_str(), nullptr, bounds);
float padding = 3;
ofRectangle rect(bounds[0] - padding, bounds[1] - padding, bounds[2] - bounds[0] + padding * 2, bounds[3] - bounds[1] + padding * 2);
float minX = 5 - offset.x;
float maxX = ofGetWidth() / scale - rect.width - 5 - offset.x;
float minY = 5 - offset.y;
float maxY = ofGetHeight() / scale - rect.height - 5 - offset.y;
float onscreenRectX = ofClamp(rect.x, minX, maxX);
if (onscreenRectX < rect.x)
{
tooltipPos.y += 20;
rect.y += 20;
}
float onscreenRectY = ofClamp(rect.y, minY, maxY);
float tooltipBackgroundAlpha = 180;
ofFill();
ofSetColor(50, 50, 50, tooltipBackgroundAlpha);
ofRect(onscreenRectX, onscreenRectY, rect.width, rect.height);
ofNoFill();
ofSetColor(255, 255, 255, tooltipBackgroundAlpha);
ofRect(onscreenRectX, onscreenRectY, rect.width, rect.height);
ofSetColor(255, 255, 255);
//DrawTextNormal(tooltip, x + 5, y + 12);
gFont.DrawStringWrap(tooltip, fontSize, tooltipPos.x + (onscreenRectX - rect.x), tooltipPos.y + (onscreenRectY - rect.y), maxWidth);
ofPopMatrix();
}
ofPushStyle();
ofNoFill();
float centerX = ofGetWidth() * .5f;
float centerY = ofGetHeight() * .5f;
if (mSpaceMouseInfo.mTwist != 0)
{
if (mSpaceMouseInfo.mUsingTwist)
ofSetColor(0, 255, 255, 100);
else
ofSetColor(0, 100, 255, 100);
ofSetLineWidth(1.5f);
ofCircle(centerX + sin(mSpaceMouseInfo.mTwist * M_PI) * 20, centerY + cos(mSpaceMouseInfo.mTwist * M_PI) * 20, 3);
ofCircle(centerX + sin(mSpaceMouseInfo.mTwist * M_PI + M_PI) * 20, centerY + cos(mSpaceMouseInfo.mTwist * M_PI + M_PI) * 20, 3);
}
ofSetLineWidth(3);
if (mSpaceMouseInfo.mZoom != 0)
{
if (mSpaceMouseInfo.mUsingZoom)
ofSetColor(0, 255, 255, 100);
else
ofSetColor(0, 100, 255, 100);
ofCircle(centerX, centerY, 15 - (mSpaceMouseInfo.mZoom * 15));
}
if (mSpaceMouseInfo.mPan.x != 0 || mSpaceMouseInfo.mPan.y != 0)
{
if (mSpaceMouseInfo.mUsingPan)
ofSetColor(0, 255, 255, 100);
else
ofSetColor(0, 100, 255, 100);
ofLine(centerX, centerY, centerX + mSpaceMouseInfo.mPan.x * 40, centerY + mSpaceMouseInfo.mPan.y * 40);
}
ofPopStyle();
++mFrameCount;
}
void ModularSynth::PostRender()
{
mModuleContainer.PostRender();
mUILayerModuleContainer.PostRender();
}
void ModularSynth::DrawConsole()
{
/*if (!mErrors.empty())
{
ofPushStyle();
ofFill();
ofSetColor(255,0,0,128);
ofBeginShape();
ofVertex(0,0);
ofVertex(20,0);
ofVertex(0,20);
ofEndShape();
ofPopStyle();
}*/
float consoleY = TheTitleBar->GetRect().height + 15;
if (IKeyboardFocusListener::GetActiveKeyboardFocus() == mConsoleEntry)
{
mConsoleEntry->SetPosition(0, consoleY - 15);
mConsoleEntry->Draw();
consoleY += 17;
}
else
{
if (gHoveredUIControl != nullptr)
{
ofPushStyle();
ofSetColor(0, 255, 255);
DrawTextNormal(gHoveredUIControl->Path(), 0, consoleY - 4);
ofPopStyle();
}
}
if (mHasCircularDependency)
{
ofPushStyle();
float pulse = ofMap(sin(gTime / 500 * PI * 2), -1, 1, .5f, 1);
ofSetColor(255 * pulse, 255 * pulse, 0);
DrawTextNormal("circular dependency detected", 0, consoleY + 20);
ofPopStyle();
}
if (IKeyboardFocusListener::GetActiveKeyboardFocus() == mConsoleEntry)
{
int outputLines = (int)mEvents.size();
if (IKeyboardFocusListener::GetActiveKeyboardFocus() == mConsoleEntry)
outputLines += mErrors.size();
if (outputLines > 0)
{
ofPushStyle();
ofSetColor(0, 0, 0, 150);
ofFill();
float titleBarW, titleBarH;
TheTitleBar->GetDimensions(titleBarW, titleBarH);
ofRect(0, consoleY - 16, titleBarW, outputLines * 15 + 3);
ofPopStyle();
}
for (auto it = mEvents.begin(); it != mEvents.end(); ++it)
{
ofPushStyle();
if (it->type == kLogEventType_Error)
ofSetColor(255, 0, 0);
else if (it->type == kLogEventType_Warning)
ofSetColor(255, 255, 0);
else
ofSetColor(255, 255, 255);
gFontFixedWidth.DrawString(it->text, 13, 10, consoleY);
std::vector<std::string> lines = ofSplitString(it->text, "\n");
ofPopStyle();
consoleY += 15 * lines.size();
}
if (!mErrors.empty())
{
consoleY = 0;
ofPushStyle();
ofSetColor(255, 0, 0);
for (auto it = mErrors.begin(); it != mErrors.end(); ++it)
{
gFontFixedWidth.DrawString(*it, 13, 600, consoleY);
std::vector<std::string> lines = ofSplitString(*it, "\n");
consoleY += 15 * lines.size();
}
ofPopStyle();
}
}
}
void ModularSynth::Exit()
{
mAudioThreadMutex.Lock("exiting");
mAudioPaused = true;
mAudioThreadMutex.Unlock();
mModuleContainer.Exit();
DeleteAllModules();
ofExit();
}
void ModularSynth::Focus()
{
ReadClipboardTextFromSystem();
}
IDrawableModule* ModularSynth::GetLastClickedModule() const
{
return mLastClickedModule;
}
void ModularSynth::KeyPressed(int key, bool isRepeat)
{
mLastShiftPressTime = -9999; //reset timer for detecing double-shift press, so it doens't happen while typing
if (!isRepeat)
mHideTooltipsUntilMouseMove = true;
if (gHoveredUIControl &&
IKeyboardFocusListener::GetActiveKeyboardFocus() == nullptr &&
!isRepeat)
{
if (key == OF_KEY_DOWN || key == OF_KEY_UP || key == OF_KEY_LEFT || key == OF_KEY_RIGHT)
{
if (GetKeyModifiers() != kModifier_Command)
{
float inc;
if (key == OF_KEY_LEFT)
inc = -1;
else if (key == OF_KEY_RIGHT)
inc = 1;
else if ((key == OF_KEY_DOWN && gHoveredUIControl->InvertScrollDirection() == false) ||
(key == OF_KEY_UP && gHoveredUIControl->InvertScrollDirection() == true))
inc = -1;
else
inc = 1;
if (GetKeyModifiers() & kModifier_Shift)
inc *= .01f;
gHoveredUIControl->Increment(inc);
}
}
else if (key == '[')
{
gHoveredUIControl->Halve();
}
else if (key == ']')
{
gHoveredUIControl->Double();
}
else if (key == '\\')
{
gHoveredUIControl->ResetToOriginal();
}
else if ((toupper(key) == 'C' || toupper(key) == 'X') && GetKeyModifiers() == kModifier_Command)
{
TheSynth->CopyTextToClipboard(ofToString(gHoveredUIControl->GetValue()));
}
else if (key != ' ' && key != OF_KEY_TAB && key != '`' && key < CHAR_MAX && juce::CharacterFunctions::isPrintable((char)key) && (GetKeyModifiers() & kModifier_Alt) == false)
{
gHoveredUIControl->AttemptTextInput();
}
}
if (key == OF_KEY_ESC && PatchCable::sActivePatchCable != nullptr)
{
PatchCable::sActivePatchCable->Release();
return;
}
if (IKeyboardFocusListener::GetActiveKeyboardFocus() != nullptr &&
IKeyboardFocusListener::GetActiveKeyboardFocus()->ShouldConsumeKey(key)) //active text entry captures all input
{
IKeyboardFocusListener::GetActiveKeyboardFocus()->OnKeyPressed(key, isRepeat);
return;
}
if (gHoveredModule != nullptr)
{
IKeyboardFocusListener* focus = dynamic_cast<IKeyboardFocusListener*>(gHoveredModule);
if (focus && focus->ShouldConsumeKey(key))
{
focus->OnKeyPressed(key, isRepeat);
return;
}
}
key = KeyToLower(key); //now convert to lowercase because everything else just cares about keys as buttons (unmodified by shift)
if ((key == juce::KeyPress::backspaceKey || key == juce::KeyPress::deleteKey) && !isRepeat)
{
for (auto module : mGroupSelectedModules)
module->GetOwningContainer()->DeleteModule(module);
mGroupSelectedModules.clear();
}
if (key == KeyPress::F2Key && !isRepeat)
{
ADSRDisplay::ToggleDisplayMode();
}
if (key == '`' && !isRepeat)
{
if (GetKeyModifiers() == kModifier_Shift)
{
TriggerClapboard();
}
else
{
std::memset(mConsoleText, 0, MAX_TEXTENTRY_LENGTH);
mConsoleEntry->MakeActiveTextEntry(true);
}
}
if (key == KeyPress::F1Key && !isRepeat)
{
HelpDisplay::sShowTooltips = !HelpDisplay::sShowTooltips;
}
if (key == OF_KEY_TAB)
{
if (GetKeyModifiers() == kModifier_Shift)
IUIControl::SetNewManualHoverViaTab(-1);
else
IUIControl::SetNewManualHoverViaTab(1);
}
if (key == OF_KEY_LEFT || key == OF_KEY_RIGHT || key == OF_KEY_UP || key == OF_KEY_DOWN)
{
if (GetKeyModifiers() == kModifier_Command)
{
ofVec2f dir;
if (key == OF_KEY_LEFT)
dir = ofVec2f(-1, 0);
if (key == OF_KEY_RIGHT)
dir = ofVec2f(1, 0);
if (key == OF_KEY_UP)
dir = ofVec2f(0, -1);
if (key == OF_KEY_DOWN)
dir = ofVec2f(0, 1);
IUIControl::SetNewManualHoverViaArrow(dir);
}
}
if (key == OF_KEY_RETURN)
{
if (mMoveModule)
mMoveModule = nullptr; //drop module
if (IUIControl::WasLastHoverSetManually())
{
TextEntry* textEntry = dynamic_cast<TextEntry*>(gHoveredUIControl);
if (textEntry != nullptr)
textEntry->MakeActiveTextEntry(true);
}
}
mZoomer.OnKeyPressed(key);
if (CharacterFunctions::isDigit((char)key) && (GetKeyModifiers() & kModifier_Alt))
{
int num = key - '0';
assert(num >= 0 && num <= 9);
gHotBindUIControl[num] = gHoveredUIControl;
}
mModuleContainer.KeyPressed(key, isRepeat);
mUILayerModuleContainer.KeyPressed(key, isRepeat);
//if (key == '/' && !isRepeat)
// ofToggleFullscreen();
if (key == 'p' && GetKeyModifiers() == kModifier_Shift && !isRepeat)
mAudioPaused = !mAudioPaused;
if (key == 's' && GetKeyModifiers() == kModifier_Command && !isRepeat)
SaveCurrentState();
if (key == 's' && GetKeyModifiers() == (kModifier_Command | kModifier_Shift) && !isRepeat)
SaveStatePopup();
if (key == 'l' && GetKeyModifiers() == kModifier_Command && !isRepeat)
LoadStatePopup();
//if (key == 'c' && !isRepeat)
// mousePressed(GetMouseX(&mModuleContainer), GetMouseY(&mModuleContainer), 0);
//if (key == '=' && !isRepeat)
// ZoomView(.1f);
//if (key == '-' && !isRepeat)
// ZoomView(-.1f);
}
void ModularSynth::KeyReleased(int key)
{
key = KeyToLower(key);
//if (key == 'c')
// mouseReleased(GetMouseX(&mModuleContainer), GetMouseY(&mModuleContainer), 0);
mModuleContainer.KeyReleased(key);
mUILayerModuleContainer.KeyReleased(key);
}
float ModularSynth::GetMouseX(ModuleContainer* context, float rawX /*= FLT_MAX*/)
{
return ((rawX == FLT_MAX ? mMousePos.x : rawX) + UserPrefs.mouse_offset_x.Get()) / context->GetDrawScale() - context->GetDrawOffset().x;
}
float ModularSynth::GetMouseY(ModuleContainer* context, float rawY /*= FLT_MAX*/)
{
return ((rawY == FLT_MAX ? mMousePos.y : rawY) + UserPrefs.mouse_offset_y.Get()) / context->GetDrawScale() - context->GetDrawOffset().y;
}
void ModularSynth::SetMousePosition(ModuleContainer* context, float x, float y)
{
x = (x + context->GetDrawOffset().x) * context->GetDrawScale() - UserPrefs.mouse_offset_x.Get() + mMainComponent->getScreenX();
y = (y + context->GetDrawOffset().y) * context->GetDrawScale() - UserPrefs.mouse_offset_y.Get() + mMainComponent->getScreenY();
Desktop::setMousePosition(juce::Point<int>(x, y));
}
bool ModularSynth::IsMouseButtonHeld(int button) const
{
if (button >= 0 && button < (int)mIsMouseButtonHeld.size())
return mIsMouseButtonHeld[button];
return false;
}
bool ModularSynth::ShouldShowGridSnap() const
{
return (mMoveModule || (!mGroupSelectedModules.empty() && IsMouseButtonHeld(1))) && (GetKeyModifiers() & kModifier_Command);
}
void ModularSynth::MouseMoved(int intX, int intY)
{
bool changed = (mMousePos.x != intX || mMousePos.y != intY);
mMousePos.x = intX;
mMousePos.y = intY;
if (IsKeyHeld(' ') || mIsMousePanning)
{
GetDrawOffset() += (ofVec2f(intX, intY) - mLastMoveMouseScreenPos) / gDrawScale;
mZoomer.CancelMovement();
if (UserPrefs.wrap_mouse_on_pan.Get() &&
(intX <= 0 || intY <= 0 || intX >= ofGetWidth() || intY >= ofGetHeight()))
{
int wrappedX = (intX + (int)ofGetWidth()) % (int)ofGetWidth();
int wrappedY = (intY + (int)ofGetHeight()) % (int)ofGetHeight();
if (intX == 0 && wrappedX == 0)
wrappedX = ofGetWidth() - 1;
if (intY == 0 && wrappedY == 0)
wrappedY = ofGetHeight() - 1;
Desktop::setMousePosition(juce::Point<int>(wrappedX + mMainComponent->getScreenX(),
wrappedY + mMainComponent->getScreenY()));
intX = wrappedX;
intY = wrappedY;
}
}
mLastMoveMouseScreenPos = ofVec2f(intX, intY);
if (changed)
{
for (auto* modal : mModalFocusItemStack)
{
float x = GetMouseX(modal->GetOwningContainer());
float y = GetMouseY(modal->GetOwningContainer());
modal->NotifyMouseMoved(x, y);
}
mHideTooltipsUntilMouseMove = false;
}
if (mMoveModule)
{
float x = GetMouseX(&mModuleContainer);
float y = GetMouseY(&mModuleContainer);
float oldX, oldY;
mMoveModule->GetPosition(oldX, oldY);
float newX = x + mMoveModuleOffsetX;
float newY = y + mMoveModuleOffsetY;
if (ShouldShowGridSnap())
{
newX = round(newX / UserPrefs.grid_snap_size.Get()) * UserPrefs.grid_snap_size.Get();
newY = round((newY - mMoveModule->TitleBarHeight()) / UserPrefs.grid_snap_size.Get()) * UserPrefs.grid_snap_size.Get() + mMoveModule->TitleBarHeight();
if (GetKeyModifiers() & kModifier_Shift) // Snap to center of the module
{
newX -= std::fmod(mMoveModule->GetRect().width / 2, UserPrefs.grid_snap_size.Get());
newY -= std::fmod(mMoveModule->GetRect().height / 2, UserPrefs.grid_snap_size.Get());
}
}
mMoveModule->Move(newX - oldX, newY - oldY);
if (GetKeyModifiers() == kModifier_Shift)
{
for (auto* module : mModuleContainer.GetModules())
{
if (module == mMoveModule)
continue;
for (auto* patchCableSource : module->GetPatchCableSources())
{
if (patchCableSource->TestHover(x, y))
{
patchCableSource->FindValidTargets();
if (!patchCableSource->IsValidTarget(mMoveModule))
continue;
if (patchCableSource->GetPatchCables().size() == 0)
{
PatchCableSource::sAllowInsert = false;
patchCableSource->SetTarget(mMoveModule);
PatchCableSource::sAllowInsert = true;
break;
}
else if (patchCableSource->GetPatchCables().size() == 1 && patchCableSource->GetTarget() != mMoveModule &&
mMoveModule->GetPatchCableSource()) //insert
{
mMoveModule->GetPatchCableSource()->FindValidTargets();
if (mMoveModule->GetPatchCableSource()->IsValidTarget(patchCableSource->GetTarget()))
{
PatchCableSource::sAllowInsert = false;
mMoveModule->SetTarget(patchCableSource->GetTarget());
patchCableSource->SetTarget(mMoveModule);
PatchCableSource::sAllowInsert = true;
break;
}
}
}
}
if (!mHasAutopatchedToTargetDuringDrag)
{
const auto patchCableSources = mMoveModule->GetPatchCableSources();
for (auto* patchCableSource : patchCableSources)
{
if (patchCableSource && patchCableSource->GetTarget() == nullptr && module->HasTitleBar())
{
ofRectangle titleBarRect(module->GetPosition().x, module->GetPosition().y - IDrawableModule::TitleBarHeight(), module->IClickable::GetDimensions().x, IDrawableModule::TitleBarHeight());
if (titleBarRect.contains(patchCableSource->GetPosition().x, patchCableSource->GetPosition().y))
{
patchCableSource->FindValidTargets();
if (patchCableSource->IsValidTarget(module))
{
PatchCableSource::sAllowInsert = false;
patchCableSource->SetTarget(module);
mHasAutopatchedToTargetDuringDrag = true;
PatchCableSource::sAllowInsert = true;
break;
}
}
}
}
}
}
}
else
{
mHasAutopatchedToTargetDuringDrag = false;
}
return;
}
if (changed)
{
float x = GetMouseX(&mModuleContainer);
float y = GetMouseY(&mModuleContainer);
mModuleContainer.MouseMoved(x, y);
x = GetMouseX(&mUILayerModuleContainer);
y = GetMouseY(&mUILayerModuleContainer);
mUILayerModuleContainer.MouseMoved(x, y);
}
if (gHoveredUIControl && changed)
{
if (!gHoveredUIControl->IsMouseDown())
{
float x = GetMouseX(gHoveredUIControl->GetModuleParent()->GetOwningContainer());
float y = GetMouseY(gHoveredUIControl->GetModuleParent()->GetOwningContainer());
float uiX, uiY;
gHoveredUIControl->GetPosition(uiX, uiY);
float w, h;
gHoveredUIControl->GetDimensions(w, h);
const float kHoverBreakDistance = 5;
if (x < uiX - kHoverBreakDistance || y < uiY - kHoverBreakDistance || x > uiX + w + kHoverBreakDistance || y > uiY + h + kHoverBreakDistance || //moved far enough away from ui control
(y < gHoveredUIControl->GetModuleParent()->GetPosition().y && uiY > gHoveredUIControl->GetModuleParent()->GetPosition().y)) //hovering over title bar (and it's not the enable/disable checkbox)
gHoveredUIControl = nullptr;
}
}
gHoveredModule = GetModuleAtCursor();
}
void ModularSynth::MouseDragged(int intX, int intY, int button, const juce::MouseInputSource& source)
{
float x = GetMouseX(&mModuleContainer);
float y = GetMouseY(&mModuleContainer);
mLastMouseDragPos = ofVec2f(x, y);
if (button == 3)
return;
if ((GetKeyModifiers() & kModifier_Alt) && !mHasDuplicatedDuringDrag)
{
std::vector<IDrawableModule*> newGroupSelectedModules;
std::map<IDrawableModule*, IDrawableModule*> oldToNewModuleMap;
for (auto module : mGroupSelectedModules)
{
if (!module->IsSingleton())
{
IDrawableModule* newModule = DuplicateModule(module);
newGroupSelectedModules.push_back(newModule);
oldToNewModuleMap[module] = newModule;
if (module == mLastClickedModule)
mLastClickedModule = newModule;
}
}
for (auto module : newGroupSelectedModules)
{
for (auto* cableSource : module->GetPatchCableSources())
{
for (auto* cable : cableSource->GetPatchCables())
{
if (VectorContains(dynamic_cast<IDrawableModule*>(cable->GetTarget()), mGroupSelectedModules))
{
cableSource->SetPatchCableTarget(cable, oldToNewModuleMap[dynamic_cast<IDrawableModule*>(cable->GetTarget())], false);
}
}
}
}
mGroupSelectedModules = newGroupSelectedModules;
if (mMoveModule && !mMoveModule->IsSingleton())
mMoveModule = DuplicateModule(mMoveModule);
mHasDuplicatedDuringDrag = true;
}
if (mGroupSelectContext != nullptr)
{
const float gx = GetMouseX(mGroupSelectContext);
const float gy = GetMouseY(mGroupSelectContext);
ofRectangle rect = ofRectangle(ofPoint(MIN(mClickStartX, gx), MIN(mClickStartY, gy)), ofPoint(MAX(mClickStartX, gx), MAX(mClickStartY, gy)));
if (rect.width > 10 || rect.height > 10)
{
mGroupSelectContext->GetModulesWithinRect(rect, mGroupSelectedModules);
if (mGroupSelectedModules.size() > 0)
{
for (int i = (int)mGroupSelectedModules.size() - 1; i >= 0; --i) //do this backwards to preserve existing order
MoveToFront(mGroupSelectedModules[i]);
}
}
else
{
mGroupSelectedModules.clear();
}
}
else if (mLastClickedModule)
{
float oldX, oldY;
mLastClickedModule->GetPosition(oldX, oldY);
float newX = x + mMoveModuleOffsetX;
float newY = y + mMoveModuleOffsetY;
if (ShouldShowGridSnap())
{
newX = round(newX / UserPrefs.grid_snap_size.Get()) * UserPrefs.grid_snap_size.Get();
newY = round((newY - mLastClickedModule->TitleBarHeight()) / UserPrefs.grid_snap_size.Get()) * UserPrefs.grid_snap_size.Get() + mLastClickedModule->TitleBarHeight();
if (GetKeyModifiers() & kModifier_Shift) // Snap to center of the module
{
newX -= std::fmod(mLastClickedModule->GetRect().width / 2, UserPrefs.grid_snap_size.Get());
newY -= std::fmod(mLastClickedModule->GetRect().height / 2, UserPrefs.grid_snap_size.Get());
}
}
float adjustedDragX = newX - oldX;
float adjustedDragY = newY - oldY;
for (auto module : mGroupSelectedModules)
module->Move(adjustedDragX, adjustedDragY);
}
if (mMoveModule)
{
float oldX, oldY;
mMoveModule->GetPosition(oldX, oldY);
float newX = x + mMoveModuleOffsetX;
float newY = y + mMoveModuleOffsetY;
if (ShouldShowGridSnap())
{
newX = round(newX / UserPrefs.grid_snap_size.Get()) * UserPrefs.grid_snap_size.Get();
newY = round((newY - mMoveModule->TitleBarHeight()) / UserPrefs.grid_snap_size.Get()) * UserPrefs.grid_snap_size.Get() + mMoveModule->TitleBarHeight();
if (GetKeyModifiers() & kModifier_Shift) // Snap to center of the module
{
newX -= std::fmod(mMoveModule->GetRect().width / 2, UserPrefs.grid_snap_size.Get());
newY -= std::fmod(mMoveModule->GetRect().height / 2, UserPrefs.grid_snap_size.Get());
}
}
mMoveModule->Move(newX - oldX, newY - oldY);
}
if (mResizeModule)
{
float moduleX, moduleY;
mResizeModule->GetPosition(moduleX, moduleY);
float newWidth = x - moduleX;
float newHeight = y - moduleY;
ofVec2f minimumDimensions = mResizeModule->GetMinimumDimensions();
newWidth = MAX(newWidth, minimumDimensions.x);
newHeight = MAX(newHeight, minimumDimensions.y);
mResizeModule->Resize(newWidth, newHeight);
}
}
void ModularSynth::MousePressed(int intX, int intY, int button, const juce::MouseInputSource& source)
{
bool rightButton = button == 2;
mZoomer.ExitVanityPanningMode();
mMousePos.x = intX;
mMousePos.y = intY;
mLastClickWasEmptySpace = false;
if (button >= 0 && button < (int)mIsMouseButtonHeld.size())
mIsMouseButtonHeld[button] = true;
float x = GetMouseX(&mModuleContainer);
float y = GetMouseY(&mModuleContainer);
mLastMouseDragPos = ofVec2f(x, y);
mGroupSelectContext = nullptr;
IKeyboardFocusListener::sKeyboardFocusBeforeClick = IKeyboardFocusListener::GetActiveKeyboardFocus();
IKeyboardFocusListener::ClearActiveKeyboardFocus(K(notifyListeners));
if (button == 3)
{
mClickStartX = x;
mClickStartY = y;
mIsMousePanning = true;
return;
}
if (PatchCable::sActivePatchCable != nullptr)
{
if (rightButton)
PatchCable::sActivePatchCable->Destroy(true);
return;
}
if (mMoveModule)
{
mMoveModule = nullptr;
return;
}
if (InMidiMapMode())
{
if (gBindToUIControl == gHoveredUIControl) //if it's the same, clear it
gBindToUIControl = nullptr;
else
gBindToUIControl = gHoveredUIControl;
return;
}
if (gHoveredUIControl != nullptr &&
gHoveredUIControl->GetModuleParent() && !gHoveredUIControl->GetModuleParent()->IsDeleted() && !gHoveredUIControl->GetModuleParent()->IsHoveringOverResizeHandle() &&
!IUIControl::WasLastHoverSetManually() &&
mGroupSelectedModules.empty() &&
mQuickSpawn->IsShowing() == false &&
(GetTopModalFocusItem() == nullptr || gHoveredUIControl->GetModuleParent() == GetTopModalFocusItem()))
{
//if we have a hovered UI control, clamp clicks within its rect and direct them straight to it
ofVec2f controlClickPos(GetMouseX(gHoveredUIControl->GetModuleParent()->GetOwningContainer()), GetMouseY(gHoveredUIControl->GetModuleParent()->GetOwningContainer()));
controlClickPos -= gHoveredUIControl->GetParent()->GetPosition();
ofRectangle controlRect = gHoveredUIControl->GetRect(K(local));
controlClickPos.x = std::clamp(controlClickPos.x, controlRect.getMinX(), controlRect.getMaxX());
controlClickPos.y = std::clamp(controlClickPos.y, controlRect.getMinY(), controlRect.getMaxY());
if (gHoveredUIControl->GetModuleParent() != TheTitleBar)
mLastClickedModule = gHoveredUIControl->GetModuleParent();
gHoveredUIControl->TestClick(controlClickPos.x, controlClickPos.y, rightButton);
}
else
{
if (GetTopModalFocusItem())
{
float modalX = GetMouseX(GetTopModalFocusItem()->GetOwningContainer());
float modalY = GetMouseY(GetTopModalFocusItem()->GetOwningContainer());
bool clicked = GetTopModalFocusItem()->TestClick(modalX, modalY, rightButton);
if (!clicked)
{
FloatSliderLFOControl* lfo = dynamic_cast<FloatSliderLFOControl*>(GetTopModalFocusItem());
if (lfo) //if it's an LFO, don't dismiss it if you're adjusting the slider
{
FloatSlider* slider = lfo->GetOwner();
float uiX, uiY;
slider->GetPosition(uiX, uiY);
float w, h;
slider->GetDimensions(w, h);
if (x < uiX || y < uiY || x > uiX + w || y > uiY + h)
PopModalFocusItem();
}
else //otherwise, always dismiss if you click outside it
{
PopModalFocusItem();
}
}
else
{
return;
}
}
IDrawableModule* clickedModule = GetModuleAtCursor();
for (auto cable : mPatchCables)
{
bool checkCable = true;
if (clickedModule != nullptr) //if we clicked on a module
{
IDrawableModule* targetedModule = (cable->GetTarget() != nullptr) ? cable->GetTarget()->GetModuleParent() : nullptr;
if (targetedModule == nullptr || (clickedModule != targetedModule && clickedModule != targetedModule->GetParent())) //and it's not the module the cable is connected to, or its parent
{
if (clickedModule == GetTopModalFocusItem() || clickedModule->AlwaysOnTop() || //and the module is sorted above the source of the cable
mModuleContainer.IsHigherThan(clickedModule, cable->GetOwningModule()))
{
checkCable = false; //don't test this cable
}
}
}
bool cableClicked = false;
if (checkCable)
cableClicked = cable->TestClick(x, y, rightButton);
if (cableClicked)
return;
}
mClickStartX = x;
mClickStartY = y;
if (clickedModule == nullptr)
{
if (rightButton)
{
mIsMousePanning = true;
}
else
{
bool beginGroupSelect = true;
//only start lassoing if we have a bit of space from a module, to avoid a common issue I'm seeing where people lasso accidentally
if (GetModuleAtCursor(7, 7) || GetModuleAtCursor(-7, 7) || GetModuleAtCursor(7, -7) || GetModuleAtCursor(-7, -7))
beginGroupSelect = false;
if (beginGroupSelect)
{
SetGroupSelectContext(&mModuleContainer);
gHoveredUIControl = nullptr;
}
}
}
if (clickedModule != nullptr && clickedModule != TheTitleBar)
{
mLastClickedModule = clickedModule;
mMoveModuleOffsetX = clickedModule->GetPosition().x - x;
mMoveModuleOffsetY = clickedModule->GetPosition().y - y;
}
else
{
mLastClickedModule = nullptr;
}
mHasDuplicatedDuringDrag = false;
if (mGroupSelectedModules.empty() == false)
{
if (!VectorContains(clickedModule, mGroupSelectedModules))
mGroupSelectedModules.clear();
return;
}
if (clickedModule)
{
x = GetMouseX(clickedModule->GetModuleParent()->GetOwningContainer());
y = GetMouseY(clickedModule->GetModuleParent()->GetOwningContainer());
CheckClick(clickedModule, x, y, rightButton);
}
else if (TheSaveDataPanel != nullptr)
{
TheSaveDataPanel->SetModule(nullptr);
}
if (clickedModule == nullptr)
mLastClickWasEmptySpace = true;
if (mQuickSpawn != nullptr && mQuickSpawn->IsShowing() && clickedModule != mQuickSpawn)
mQuickSpawn->Hide();
}
}
void ModularSynth::ToggleQuickSpawn()
{
if (mQuickSpawn != nullptr && mQuickSpawn->IsShowing())
{
mQuickSpawn->Hide();
}
else
{
mQuickSpawn->ShowSpawnCategoriesPopup();
}
}
void ModularSynth::MouseScrolled(float xScroll, float yScroll, bool isSmoothScroll, bool isInvertedScroll, bool canZoomCanvas)
{
xScroll *= UserPrefs.scroll_multiplier_horizontal.Get();
yScroll *= UserPrefs.scroll_multiplier_vertical.Get();
if (IsKeyHeld(' ') || (GetModuleAtCursor() == nullptr && gHoveredUIControl == nullptr) || (dynamic_cast<Prefab*>(GetModuleAtCursor()) != nullptr && gHoveredUIControl == nullptr))
{
if (canZoomCanvas)
ZoomView(yScroll / 50, true);
}
else if (gHoveredUIControl)
{
#if JUCE_WINDOWS
yScroll += xScroll / 4; //taking advantage of logitech horizontal scroll wheel
#endif
TextEntry* textEntry = dynamic_cast<TextEntry*>(gHoveredUIControl);
if (textEntry)
{
if (isSmoothScroll) //slow this down into steps if you're using a smooth trackpad
{
if (fabs(yScroll) < .1f) //need more than a miniscule change
return;
static float sLastSmoothScrollTimeMs = -999;
if (sLastSmoothScrollTimeMs + 100 > gTime)
return;
sLastSmoothScrollTimeMs = gTime;
}
float val = textEntry->GetValue();
float change = yScroll > 0 ? 1 : -1;
if (GetKeyModifiers() & kModifier_Shift)
change *= .01f;
float min, max;
textEntry->GetRange(min, max);
textEntry->SetValue(std::clamp(val + change, min, max), NextBufferTime(false));
return;
}
float val = gHoveredUIControl->GetMidiValue();
float movementScale = 3;
FloatSlider* floatSlider = dynamic_cast<FloatSlider*>(gHoveredUIControl);
IntSlider* intSlider = dynamic_cast<IntSlider*>(gHoveredUIControl);
ClickButton* clickButton = dynamic_cast<ClickButton*>(gHoveredUIControl);
if (floatSlider || intSlider)
{
float w, h;
gHoveredUIControl->GetDimensions(w, h);
movementScale = 200.0f / w;
}
if (GetKeyModifiers() & kModifier_Shift)
movementScale *= .01f;
if (clickButton)
return;
float change = yScroll / 100 * movementScale;
if (floatSlider && floatSlider->GetModulator() && floatSlider->GetModulator()->Active() && floatSlider->GetModulator()->CanAdjustRange())
{
IModulator* modulator = floatSlider->GetModulator();
float min = floatSlider->GetMin();
float max = floatSlider->GetMax();
float modMin = ofMap(modulator->GetMin(), min, max, 0, 1);
float modMax = ofMap(modulator->GetMax(), min, max, 0, 1);
modulator->GetMin() = ofMap(modMin - change, 0, 1, min, max, K(clamp));
modulator->GetMax() = ofMap(modMax + change, 0, 1, min, max, K(clamp));
return;
}
if (gHoveredUIControl->InvertScrollDirection())
val -= change;
else
val += change;
val = ofClamp(val, 0, 1);
gHoveredUIControl->SetFromMidiCC(val, NextBufferTime(false), false);
gHoveredUIControl->NotifyMouseScrolled(GetMouseX(&mModuleContainer), GetMouseY(&mModuleContainer), xScroll, yScroll, isSmoothScroll, isInvertedScroll);
}
else
{
IDrawableModule* module = GetModuleAtCursor();
if (module)
module->NotifyMouseScrolled(GetMouseX(module->GetOwningContainer()), GetMouseY(module->GetOwningContainer()), xScroll, yScroll, isSmoothScroll, isInvertedScroll);
}
}
void ModularSynth::MouseMagnify(int intX, int intY, float scaleFactor, const juce::MouseInputSource& source)
{
mMousePos.x = intX;
mMousePos.y = intY;
ZoomView(scaleFactor - 1, true);
}
bool ModularSynth::InMidiMapMode()
{
return IsKeyHeld('m', kModifier_Shift);
}
bool ModularSynth::ShouldAccentuateActiveModules() const
{
return IsKeyHeld('s', kModifier_Shift);
}
bool ModularSynth::ShouldDimModule(IDrawableModule* module)
{
if (TheSynth->GetGroupSelectedModules().empty() == false)
{
if (!VectorContains(module->GetModuleParent(), TheSynth->GetGroupSelectedModules()))
return true;
}
if (PatchCable::sActivePatchCable &&
(PatchCable::sActivePatchCable->GetConnectionType() != kConnectionType_Modulator && PatchCable::sActivePatchCable->GetConnectionType() != kConnectionType_UIControl && PatchCable::sActivePatchCable->GetConnectionType() != kConnectionType_ValueSetter) &&
!PatchCable::sActivePatchCable->IsValidTarget(module))
{
return true;
}
if (TheSynth->GetHeldSample() != nullptr && !module->CanDropSample())
return true;
if (ScriptModule::sHasLoadedUntrustedScript &&
dynamic_cast<ScriptModule*>(module) == nullptr &&
dynamic_cast<ScriptWarningPopup*>(module) == nullptr)
return true;
return false;
}
void ModularSynth::RegisterPatchCable(PatchCable* cable)
{
mPatchCables.push_back(cable);
}
void ModularSynth::UnregisterPatchCable(PatchCable* cable)
{
RemoveFromVector(cable, mPatchCables);
}
void ModularSynth::PushModalFocusItem(IDrawableModule* item)
{
mModalFocusItemStack.push_back(item);
}
void ModularSynth::PopModalFocusItem()
{
if (mModalFocusItemStack.empty() == false)
mModalFocusItemStack.pop_back();
}
IDrawableModule* ModularSynth::GetTopModalFocusItem() const
{
if (mModalFocusItemStack.empty())
return nullptr;
return mModalFocusItemStack.back();
}
bool ModularSynth::IsModalFocusItem(IDrawableModule* item) const
{
return std::find(mModalFocusItemStack.begin(), mModalFocusItemStack.end(), item) == mModalFocusItemStack.end();
}
IDrawableModule* ModularSynth::GetModuleAtCursor(int offsetX /*=0*/, int offsetY /*=0*/)
{
float x = GetMouseX(&mUILayerModuleContainer) + offsetX;
float y = GetMouseY(&mUILayerModuleContainer) + offsetY;
IDrawableModule* uiLayerModule = mUILayerModuleContainer.GetModuleAt(x, y);
if (uiLayerModule)
return uiLayerModule;
x = GetMouseX(&mModuleContainer) + offsetX;
y = GetMouseY(&mModuleContainer) + offsetY;
return mModuleContainer.GetModuleAt(x, y);
}
void ModularSynth::CheckClick(IDrawableModule* clickedModule, float x, float y, bool rightButton)
{
if (clickedModule != TheTitleBar)
MoveToFront(clickedModule);
//check to see if we clicked in the move area
ofRectangle moduleRect = clickedModule->GetRect();
float modulePosX = x - moduleRect.x;
float modulePosY = y - moduleRect.y;
if (modulePosY < 0 && clickedModule != TheTitleBar && (!clickedModule->HasEnabledCheckbox() || modulePosX > 20) && modulePosX < moduleRect.width - 15)
SetMoveModule(clickedModule, moduleRect.x - x, moduleRect.y - y, false);
float parentX = 0;
float parentY = 0;
if (clickedModule->GetParent())
clickedModule->GetParent()->GetPosition(parentX, parentY);
//do the regular click
clickedModule->TestClick(x - parentX, y - parentY, rightButton);
}
void ModularSynth::MoveToFront(IDrawableModule* module)
{
if (module->GetOwningContainer())
module->GetOwningContainer()->MoveToFront(module);
}
void ModularSynth::OnModuleDeleted(IDrawableModule* module)
{
if (!module->CanBeDeleted() || module->IsDeleted())
return;
mDeletedModules.push_back(module);
mAudioThreadMutex.Lock("delete");
std::list<PatchCable*> cablesToRemove;
for (auto* cable : mPatchCables)
{
if (cable->GetOwningModule() == module)
cablesToRemove.push_back(cable);
}
for (auto* cable : cablesToRemove)
RemoveFromVector(cable, mPatchCables);
RemoveFromVector(dynamic_cast<IAudioSource*>(module), mSources);
RemoveFromVector(module, mLissajousDrawers);
TheTransport->RemoveAudioPoller(dynamic_cast<IAudioPoller*>(module));
//delete module; TODO(Ryan) deleting is hard... need to clear out everything with a reference to this, or switch to smart pointers
if (module == TheChaosEngine)
TheChaosEngine = nullptr;
if (module == TheLFOController)
TheLFOController = nullptr;
mAudioThreadMutex.Unlock();
}
void ModularSynth::MouseReleased(int intX, int intY, int button, const juce::MouseInputSource& source)
{
mMousePos.x = intX;
mMousePos.y = intY;
mMouseMovedSignificantlySincePressed = source.hasMovedSignificantlySincePressed();
if (button >= 0 && button < (int)mIsMouseButtonHeld.size())
mIsMouseButtonHeld[button] = false;
mIsMousePanning = false;
bool rightButton = button == 2;
if (button == 3)
return;
float x = GetMouseX(&mModuleContainer);
float y = GetMouseY(&mModuleContainer);
if (GetTopModalFocusItem())
{
GetTopModalFocusItem()->MouseReleased();
}
if (mResizeModule)
mResizeModule = nullptr;
if (mMoveModule)
{
Prefab::sJustReleasedModule = mMoveModule;
if (!mMouseMovedSignificantlySincePressed)
{
if (mMoveModule->WasMinimizeAreaClicked())
{
mMoveModule->ToggleMinimized();
mMoveModule = nullptr;
}
if (!mMoveModuleCanStickToCursor)
mMoveModule = nullptr;
}
else
{
mMoveModule = nullptr;
}
}
mModuleContainer.MouseReleased();
mUILayerModuleContainer.MouseReleased();
if (mHeldSample)
{
IDrawableModule* module = GetModuleAtCursor();
if (module)
{
float moduleX, moduleY;
module->GetPosition(moduleX, moduleY);
module->SampleDropped(x - moduleX, y - moduleY, GetHeldSample());
}
ClearHeldSample();
}
if (!mGroupSelectedModules.empty() && !mMouseMovedSignificantlySincePressed)
mGroupSelectedModules.clear();
if (rightButton && mLastClickWasEmptySpace && !mMouseMovedSignificantlySincePressed && mQuickSpawn != nullptr)
mQuickSpawn->ShowSpawnCategoriesPopup();
mClickStartX = INT_MAX;
mClickStartY = INT_MAX;
mGroupSelectContext = nullptr;
Prefab::sJustReleasedModule = nullptr;
}
void ModularSynth::AudioOut(float* const* output, int bufferSize, int nChannels)
{
PROFILER(audioOut_total);
sAudioThreadId = std::this_thread::get_id();
static bool sFirst = true;
if (sFirst)
{
FloatVectorOperations::disableDenormalisedNumberSupport();
sFirst = false;
}
if (mAudioPaused)
{
for (int ch = 0; ch < nChannels; ++ch)
{
for (int i = 0; i < bufferSize; ++i)
output[ch][i] = 0;
}
return;
}
ScopedMutex mutex(&mAudioThreadMutex, "audioOut()");
/////////// AUDIO PROCESSING STARTS HERE /////////////
mNoteOutputQueue->Process();
int oversampling = UserPrefs.oversampling.Get();
assert(bufferSize * oversampling == mIOBufferSize);
assert(nChannels == (int)mOutputBuffers.size());
assert(mIOBufferSize == gBufferSize); //need to be the same for now
//if we want these different, need to fix outBuffer here, and also fix audioIn()
//by now, many assumptions will have to be fixed to support mIOBufferSize and gBufferSize diverging
for (int ioOffset = 0; ioOffset < mIOBufferSize; ioOffset += gBufferSize)
{
for (size_t i = 0; i < mOutputBuffers.size(); ++i)
Clear(mOutputBuffers[i], mIOBufferSize);
double elapsed = gInvSampleRateMs * mIOBufferSize;
gTime += elapsed;
TheTransport->Advance(elapsed);
//process all audio
for (int i = 0; i < mSources.size(); ++i)
mSources[i]->Process(gTime);
if (gTime - mLastClapboardTime < 100)
{
for (int ch = 0; ch < nChannels; ++ch)
{
for (int i = 0; i < bufferSize; ++i)
{
float sample = sin(GetPhaseInc(440) * i) * (1 - ((gTime - mLastClapboardTime) / 100));
output[ch][i] = sample;
}
}
}
//put it into speakers
for (int ch = 0; ch < nChannels; ++ch)
{
if (oversampling == 1)
{
BufferCopy(output[ch], mOutputBuffers[ch], gBufferSize);
if (ch < 2)
mGlobalRecordBuffer->WriteChunk(output[ch], bufferSize, ch);
}
else
{
for (int sampleIndex = 0; sampleIndex < gBufferSize / oversampling; ++sampleIndex)
{
output[ch][sampleIndex] = 0;
for (int subsampleIndex = 0; subsampleIndex < oversampling; ++subsampleIndex)
{
float sample = mOutputBuffers[ch][sampleIndex * oversampling + subsampleIndex];
output[ch][sampleIndex] += sample / oversampling;
if (ch < 2)
mGlobalRecordBuffer->Write(sample, ch);
}
}
}
}
}
/////////// AUDIO PROCESSING ENDS HERE /////////////
mRecordingLength += bufferSize * oversampling;
mRecordingLength = MIN(mRecordingLength, mGlobalRecordBuffer->Size());
Profiler::PrintCounters();
}
void ModularSynth::AudioIn(const float* const* input, int bufferSize, int nChannels)
{
if (mAudioPaused)
return;
ScopedMutex mutex(&mAudioThreadMutex, "audioIn()");
int oversampling = UserPrefs.oversampling.Get();
assert(bufferSize * oversampling == mIOBufferSize);
assert(nChannels == (int)mInputBuffers.size());
for (int i = 0; i < nChannels; ++i)
{
if (oversampling == 1)
{
BufferCopy(mInputBuffers[i], input[i], bufferSize);
}
else
{
for (int sampleIndex = 0; sampleIndex < bufferSize * oversampling; ++sampleIndex)
{
mInputBuffers[i][sampleIndex] = input[i][sampleIndex / oversampling];
}
}
}
}
float* ModularSynth::GetInputBuffer(int channel)
{
assert(channel >= 0 && channel < mInputBuffers.size());
return mInputBuffers[channel];
}
float* ModularSynth::GetOutputBuffer(int channel)
{
assert(channel >= 0 && channel < mOutputBuffers.size());
return mOutputBuffers[channel];
}
void ModularSynth::TriggerClapboard()
{
mLastClapboardTime = gTime; //for synchronizing internally recorded audio and externally recorded video
}
void ModularSynth::FilesDropped(std::vector<std::string> files, int intX, int intY)
{
if (files.size() > 0)
{
float x = GetMouseX(&mModuleContainer, intX);
float y = GetMouseY(&mModuleContainer, intY);
IDrawableModule* target = GetModuleAtCursor();
if (files.size() == 1 && juce::String(files[0]).endsWith(".bsk"))
{
LoadState(files[0]);
return;
}
if (target != nullptr)
{
float moduleX, moduleY;
target->GetPosition(moduleX, moduleY);
x -= moduleX;
y -= moduleY;
target->FilesDropped(files, x, y);
}
}
}
struct SourceDepInfo
{
SourceDepInfo(IAudioSource* me)
: mMe(me)
{}
IAudioSource* mMe;
std::vector<IAudioSource*> mDeps;
};
void ModularSynth::ArrangeAudioSourceDependencies()
{
if (mIsLoadingState)
{
mArrangeDependenciesWhenLoadCompletes = true;
return;
}
//ofLog() << "Calculating audio source dependencies:";
std::vector<SourceDepInfo> deps;
for (int i = 0; i < mSources.size(); ++i)
deps.push_back(SourceDepInfo(mSources[i]));
for (int i = 0; i < mSources.size(); ++i)
{
for (int j = 0; j < mSources.size(); ++j)
{
for (int k = 0; k < mSources[i]->GetNumTargets(); ++k)
{
if (mSources[i]->GetTarget(k) != nullptr &&
mSources[i]->GetTarget(k) == dynamic_cast<IAudioReceiver*>(mSources[j]))
{
deps[j].mDeps.push_back(mSources[i]);
}
}
}
}
/*for (int i=0; i<deps.size(); ++i)
{
string depStr;
for (int j=0;j<deps[i].mDeps.size();++j)
{
depStr += dynamic_cast<IDrawableModule*>(deps[i].mDeps[j])->Name();
if (j<deps[i].mDeps.size()-1)
depStr += ", ";
}
ofLog() << dynamic_cast<IDrawableModule*>(deps[i].mMe)->Name() << "depends on:" << depStr;
}*/
//TODO(Ryan) detect circular dependencies
const int kMaxLoopCount = 1000; //how many times we loop over the graph before deciding that it must contain a circular dependency
mSources.clear();
int loopCount = 0;
while (deps.size() > 0 && loopCount < kMaxLoopCount) //stupid circular dependency detection, make better
{
for (int i = 0; i < deps.size(); ++i)
{
bool hasDeps = false;
for (int j = 0; j < deps[i].mDeps.size(); ++j)
{
bool found = false;
for (int k = 0; k < mSources.size(); ++k)
{
if (deps[i].mDeps[j] == mSources[k])
found = true;
}
if (!found) //has a dep that hasn't been added yet
hasDeps = true;
}
if (!hasDeps)
{
mSources.push_back(deps[i].mMe);
deps.erase(deps.begin() + i);
i -= 1;
}
}
++loopCount;
}
if (loopCount == kMaxLoopCount) //circular dependency, don't lose the rest of the sources
{
mHasCircularDependency = true;
ofLog() << "circular dependency detected";
for (int i = 0; i < deps.size(); ++i)
mSources.push_back(deps[i].mMe);
FindCircularDependencies();
}
else
{
if (mHasCircularDependency) //we used to have a circular dependency, now we don't
ClearCircularDependencyMarkers();
mHasCircularDependency = false;
}
/*ofLog() << "new ordering:";
for (int i=0; i<mSources.size(); ++i)
ofLog() << dynamic_cast<IDrawableModule*>(mSources[i])->Name();*/
}
void ModularSynth::FindCircularDependencies()
{
ClearCircularDependencyMarkers();
for (int i = 0; i < mSources.size(); ++i)
{
std::list<IAudioSource*> chain;
if (FindCircularDependencySearch(chain, mSources[i]))
break;
}
}
bool ModularSynth::FindCircularDependencySearch(std::list<IAudioSource*> chain, IAudioSource* searchFrom)
{
/*std::string debugString = "FindCircularDependencySearch(): ";
for (auto& element : chain)
debugString += dynamic_cast<IDrawableModule*>(element)->GetDisplayName() + "->";
debugString += dynamic_cast<IDrawableModule*>(searchFrom)->GetDisplayName();
ofLog() << debugString;*/
chain.push_back(searchFrom);
IAudioSource* end = chain.back();
for (int i = 0; i < end->GetNumTargets(); ++i)
{
IAudioReceiver* receiver = end->GetTarget(i);
IAudioSource* targetAsSource = dynamic_cast<IAudioSource*>(receiver);
if (targetAsSource != nullptr)
{
if (ListContains(targetAsSource, chain)) //found a circular dependency
{
std::string debugString = "FindCircularDependencySearch(): found! ";
for (auto& element : chain)
debugString += dynamic_cast<IDrawableModule*>(element)->GetDisplayName() + "->";
debugString += dynamic_cast<IDrawableModule*>(targetAsSource)->GetDisplayName();
ofLog() << debugString;
chain.push_back(targetAsSource);
std::vector<IAudioSource*> chainVec;
for (auto& element : chain)
chainVec.push_back(element);
for (int j = 0; j < (int)chainVec.size() - 1; ++j)
{
IDrawableModule* module = dynamic_cast<IDrawableModule*>(chainVec[j]);
for (int k = 0; k < (int)module->GetPatchCableSources().size(); ++k)
{
if (dynamic_cast<IAudioSource*>(module->GetPatchCableSource(k)->GetTarget()) == chainVec[j + 1])
module->GetPatchCableSource(k)->SetIsPartOfCircularDependency(true);
}
}
return true;
}
else
{
if (FindCircularDependencySearch(chain, targetAsSource))
return true;
}
}
}
return false;
}
void ModularSynth::ClearCircularDependencyMarkers()
{
for (int i = 0; i < mSources.size(); ++i)
{
IDrawableModule* module = dynamic_cast<IDrawableModule*>(mSources[i]);
for (int j = 0; j < (int)module->GetPatchCableSources().size(); ++j)
module->GetPatchCableSource(j)->SetIsPartOfCircularDependency(false);
}
}
void ModularSynth::ResetLayout()
{
mMainComponent->getTopLevelComponent()->setName("bespoke synth");
mCurrentSaveStatePath = "";
mModuleContainer.Clear();
mUILayerModuleContainer.Clear();
for (int i = 0; i < mDeletedModules.size(); ++i)
delete mDeletedModules[i];
mDeletedModules.clear();
mSources.clear();
mLissajousDrawers.clear();
mMoveModule = nullptr;
TheTransport->ClearListenersAndPollers();
TheScale->ClearListeners();
LFOPool::Shutdown();
IKeyboardFocusListener::ClearActiveKeyboardFocus(!K(notifyListeners));
ScriptModule::sBackgroundTextString = "";
ScriptModule::sHasLoadedUntrustedScript = false; //reset
ScriptModule::sScriptsRequestingInitExecution.clear();
mErrors.clear();
std::vector<PatchCable*> cablesToDelete = mPatchCables;
for (auto cable : cablesToDelete)
delete cable;
assert(mPatchCables.size() == 0); //everything should have been cleared out by that
gBindToUIControl = nullptr;
mModalFocusItemStack.clear();
gHoveredUIControl = nullptr;
mLastClickedModule = nullptr;
LFOPool::Init();
mZoomer.Init();
delete TheTitleBar;
delete TheSaveDataPanel;
delete mQuickSpawn;
delete mUserPrefsEditor;
delete mNoteOutputQueue;
TitleBar* titleBar = new TitleBar();
titleBar->SetPosition(0, 0);
titleBar->SetName("titlebar");
titleBar->SetTypeName("titlebar", kModuleCategory_Other);
titleBar->CreateUIControls();
titleBar->SetModuleFactory(&mModuleFactory);
titleBar->Init();
mUILayerModuleContainer.AddModule(titleBar);
if (UserPrefs.show_minimap.Get())
{
mMinimap = std::make_unique<Minimap>();
mMinimap->SetName("minimap");
mMinimap->SetTypeName("minimap", kModuleCategory_Other);
mMinimap->SetShouldDrawOutline(false);
mMinimap->CreateUIControls();
mMinimap->SetShowing(true);
mMinimap->Init();
mUILayerModuleContainer.AddModule(mMinimap.get());
TitleBar::sShowInitialHelpOverlay = false; //don't show initial help popup, it collides with minimap, and a user who has customized the settings likely doesn't need it
}
ModuleSaveDataPanel* saveDataPanel = new ModuleSaveDataPanel();
saveDataPanel->SetPosition(-200, 50);
saveDataPanel->SetName("savepanel");
saveDataPanel->CreateUIControls();
saveDataPanel->Init();
mModuleContainer.AddModule(saveDataPanel);
mQuickSpawn = new QuickSpawnMenu();
mQuickSpawn->SetName("quickspawn");
mQuickSpawn->CreateUIControls();
mQuickSpawn->Init();
mUILayerModuleContainer.AddModule(mQuickSpawn);
mModuleContainer.AddModule(mQuickSpawn->GetMainContainerFollower());
mUserPrefsEditor = new UserPrefsEditor();
mUserPrefsEditor->SetName("userprefseditor");
mUserPrefsEditor->SetTypeName("userprefseditor", kModuleCategory_Other);
mUserPrefsEditor->CreateUIControls();
mUserPrefsEditor->Init();
mUserPrefsEditor->SetShowing(false);
mModuleContainer.AddModule(mUserPrefsEditor);
if (mFatalError != "")
{
mUserPrefsEditor->Show();
TheTitleBar->SetShowing(false);
}
GetDrawOffset().set(0, 0);
SetUIScale(UserPrefs.ui_scale.Get());
mNoteOutputQueue = new NoteOutputQueue();
}
bool ModularSynth::LoadLayoutFromFile(std::string jsonFile, bool makeDefaultLayout /*= true*/)
{
ofLog() << "Loading layout: " << jsonFile;
mLoadedLayoutPath = String(jsonFile).replace(ofToDataPath("").c_str(), "").toStdString();
ofxJSONElement root;
bool loaded = root.open(jsonFile);
if (!loaded)
{
LogEvent("Couldn't load, error parsing " + jsonFile, kLogEventType_Error);
LogEvent("Try loading it up in a json validator", kLogEventType_Error);
return false;
}
LoadLayout(root);
if (juce::String(jsonFile).endsWith("blank.json"))
{
IDrawableModule* gain = FindModule("gain");
IDrawableModule* splitter = FindModule("splitter");
IDrawableModule* output1 = FindModule("output 1");
IDrawableModule* output2 = FindModule("output 2");
if (output1 != nullptr && output1->GetPosition().y > ofGetHeight() / gDrawScale - 40)
{
float offset = ofGetHeight() / gDrawScale - output1->GetPosition().y - 40;
if (gain != nullptr)
gain->SetPosition(gain->GetPosition().x, gain->GetPosition().y + offset);
if (splitter != nullptr)
splitter->SetPosition(splitter->GetPosition().x, splitter->GetPosition().y + offset);
if (output1 != nullptr)
output1->SetPosition(output1->GetPosition().x, output1->GetPosition().y + offset);
if (output2 != nullptr)
output2->SetPosition(output2->GetPosition().x, output2->GetPosition().y + offset);
}
if (output2 != nullptr && output2->GetPosition().x > ofGetWidth() / gDrawScale - 100)
{
float offset = ofGetWidth() / gDrawScale - output2->GetPosition().x - 100;
if (gain != nullptr)
gain->SetPosition(gain->GetPosition().x + offset, gain->GetPosition().y);
if (splitter != nullptr)
splitter->SetPosition(splitter->GetPosition().x + offset, splitter->GetPosition().y);
if (output1 != nullptr)
output1->SetPosition(output1->GetPosition().x + offset, output1->GetPosition().y);
if (output2 != nullptr)
output2->SetPosition(output2->GetPosition().x + offset, output2->GetPosition().y);
}
}
if (makeDefaultLayout)
UpdateUserPrefsLayout();
return true;
}
bool ModularSynth::LoadLayoutFromString(std::string jsonString)
{
ofxJSONElement root;
bool loaded = root.parse(jsonString);
if (!loaded)
{
LogEvent("Couldn't load, error parsing json string", kLogEventType_Error);
ofLog() << jsonString;
return false;
}
LoadLayout(root);
return true;
}
void ModularSynth::LoadLayout(ofxJSONElement json)
{
ScriptModule::UninitializePython();
Transport::sDoEventLookahead = false;
//ofLoadURLAsync("path_to_url"+jsonFile);
ScopedMutex mutex(&mAudioThreadMutex, "LoadLayout()");
std::lock_guard<std::recursive_mutex> renderLock(mRenderLock);
ResetLayout();
mModuleContainer.LoadModules(json["modules"]);
mUILayerModuleContainer.LoadModules(json["ui_modules"]);
//timer.PrintCosts();
mZoomer.LoadFromSaveData(json["zoomlocations"]);
ArrangeAudioSourceDependencies();
}
void ModularSynth::UpdateUserPrefsLayout()
{
//mUserPrefsFile["layout"] = mLoadedLayoutPath;
//mUserPrefsFile.save(GetUserPrefsPath(), true);
}
void ModularSynth::AddExtraPoller(IPollable* poller)
{
if (!ListContains(poller, mExtraPollers))
mExtraPollers.push_front(poller);
}
void ModularSynth::RemoveExtraPoller(IPollable* poller)
{
if (ListContains(poller, mExtraPollers))
mExtraPollers.remove(poller);
}
IDrawableModule* ModularSynth::CreateModule(const ofxJSONElement& moduleInfo)
{
IDrawableModule* module = nullptr;
try
{
if (moduleInfo["comment_out"].asBool()) //hack since json doesn't allow comments
return nullptr;
std::string type = moduleInfo["type"].asString();
type = ModuleFactory::FixUpTypeName(type);
try
{
if (type == "transport")
module = TheTransport;
else if (type == "scale")
module = TheScale;
else
module = mModuleFactory.MakeModule(type);
if (module == nullptr)
{
LogEvent("Couldn't create unknown module type \"" + type + "\"", kLogEventType_Error);
return nullptr;
}
if (module->IsSingleton() == false)
module->CreateUIControls();
module->LoadBasics(moduleInfo, type);
assert(strlen(module->Name()) > 0);
}
catch (UnknownModuleException& e)
{
LogEvent("Couldn't find referenced module \"" + e.mSearchName + "\" when loading \"" + moduleInfo["name"].asString() + "\"", kLogEventType_Error);
}
}
catch (Json::LogicError& e)
{
TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error);
}
return module;
}
void ModularSynth::SetUpModule(IDrawableModule* module, const ofxJSONElement& moduleInfo)
{
assert(module != nullptr);
try
{
mIsLoadingModule = true;
module->LoadLayoutBase(moduleInfo);
mIsLoadingModule = false;
}
catch (UnknownModuleException& e)
{
LogEvent("Couldn't find referenced module \"" + e.mSearchName + "\" when setting up \"" + moduleInfo["name"].asString() + "\"", kLogEventType_Error);
}
}
void ModularSynth::OnModuleAdded(IDrawableModule* module)
{
IAudioSource* source = dynamic_cast<IAudioSource*>(module);
if (source)
mSources.push_back(source);
}
void ModularSynth::AddDynamicModule(IDrawableModule* module)
{
mModuleContainer.AddModule(module);
}
void ModularSynth::ScheduleEnvelopeEditorSpawn(ADSRDisplay* adsrDisplay)
{
mScheduledEnvelopeEditorSpawnDisplay = adsrDisplay;
}
IDrawableModule* ModularSynth::FindModule(std::string name, bool fail)
{
if (name[0] == '$')
{
if (Prefab::sLoadingPrefab)
{
if (fail)
throw UnknownModuleException(name);
return nullptr;
}
return mModuleContainer.FindModule(name.substr(1, name.length() - 1), fail);
}
return mModuleContainer.FindModule(IClickable::sPathLoadContext + name, fail);
}
MidiController* ModularSynth::FindMidiController(std::string name, bool fail)
{
if (name == "")
return nullptr;
MidiController* m = nullptr;
try
{
m = dynamic_cast<MidiController*>(FindModule(name, fail));
if (m == nullptr && fail)
throw WrongModuleTypeException();
}
catch (UnknownModuleException& e)
{
LogEvent("Couldn't find referenced midi controller \"" + name + "\"", kLogEventType_Error);
}
catch (WrongModuleTypeException& e)
{
LogEvent("\"" + name + "\" is not a midicontroller", kLogEventType_Error);
}
return m;
}
IUIControl* ModularSynth::FindUIControl(std::string path)
{
if (path == "")
return nullptr;
if (path[0] == '$')
{
if (Prefab::sLoadingPrefab)
return nullptr;
return mModuleContainer.FindUIControl(path.substr(1, path.length() - 1));
}
return mModuleContainer.FindUIControl(IClickable::sPathLoadContext + path);
}
void ModularSynth::GrabSample(ChannelBuffer* data, std::string name, bool window, int numBars)
{
delete mHeldSample;
mHeldSample = new Sample();
mHeldSample->Create(data);
mHeldSample->SetName(name);
mHeldSample->SetNumBars(numBars);
//window sample to avoid clicks
if (window)
{
int length = data->BufferSize();
const int fadeSamples = 15;
if (length > fadeSamples * 2) //only window if there's enough space
{
for (int i = 0; i < fadeSamples; ++i)
{
for (int ch = 0; ch < mHeldSample->NumChannels(); ++ch)
{
float fade = float(i) / fadeSamples;
mHeldSample->Data()->GetChannel(ch)[i] *= fade;
mHeldSample->Data()->GetChannel(ch)[length - 1 - i] *= fade;
}
}
}
}
}
void ModularSynth::GrabSample(std::string filePath)
{
delete mHeldSample;
mHeldSample = new Sample();
mHeldSample->Read(filePath.c_str());
}
void ModularSynth::ClearHeldSample()
{
delete mHeldSample;
mHeldSample = nullptr;
}
void ModularSynth::LogEvent(std::string event, LogEventType type)
{
if (type == kLogEventType_Warning)
{
!ofLog() << "warning: " << event;
}
else if (type == kLogEventType_Error)
{
!ofLog() << "error: " << event;
mErrors.push_back(event);
}
mEvents.push_back(LogEventItem(gTime, event, type));
if (mEvents.size() > 30)
mEvents.pop_front();
}
IDrawableModule* ModularSynth::DuplicateModule(IDrawableModule* module)
{
juce::MemoryBlock block;
{
FileStreamOut out(block);
module->SaveState(out);
}
ofxJSONElement layoutData;
module->SaveLayoutBase(layoutData);
std::vector<IDrawableModule*> modules = mModuleContainer.GetModules();
std::string newName = GetUniqueName(layoutData["name"].asString(), modules);
layoutData["name"] = newName;
IDrawableModule* newModule = CreateModule(layoutData);
mModuleContainer.AddModule(newModule);
SetUpModule(newModule, layoutData);
newModule->Init();
assert(newModule);
newModule->SetName(module->Name()); //temporarily rename to the same as what we duplicated, so we can load state properly
{
FileStreamIn in(block);
mIsLoadingModule = true;
mIsDuplicatingModule = true;
newModule->LoadState(in, newModule->LoadModuleSaveStateRev(in));
mIsDuplicatingModule = false;
mIsLoadingModule = false;
}
newModule->SetName(newName.c_str());
return newModule;
}
ofxJSONElement ModularSynth::GetLayout()
{
ofxJSONElement root;
root["modules"] = mModuleContainer.WriteModules();
root["ui_modules"] = mUILayerModuleContainer.WriteModules();
root["zoomlocations"] = mZoomer.GetSaveData();
return root;
}
void ModularSynth::SaveLayout(std::string jsonFile, bool makeDefaultLayout /*= true*/)
{
if (jsonFile.empty())
jsonFile = ofToDataPath(mLoadedLayoutPath);
ofxJSONElement root = GetLayout();
root.save(jsonFile, true);
mLoadedLayoutPath = String(jsonFile).replace(ofToDataPath("").c_str(), "").toStdString();
TheTitleBar->ListLayouts();
if (makeDefaultLayout)
UpdateUserPrefsLayout();
}
void ModularSynth::SaveLayoutAsPopup()
{
FileChooser chooser("Save current layout as...", File(ofToDataPath("layouts/newlayout.json")), "*.json", true, false, GetFileChooserParent());
if (chooser.browseForFileToSave(true))
SaveLayout(chooser.getResult().getFullPathName().toStdString());
}
void ModularSynth::SaveCurrentState()
{
if (mCurrentSaveStatePath.empty() || IsCurrentSaveStateATemplate())
{
SaveStatePopup();
return;
}
SaveState(mCurrentSaveStatePath, false);
}
juce::Component* ModularSynth::GetFileChooserParent() const
{
#if BESPOKE_LINUX
return nullptr;
#else
return mMainComponent->getTopLevelComponent();
#endif
}
void ModularSynth::SaveStatePopup()
{
File targetFile;
String savestateDirPath = ofToDataPath("savestate/");
String templateName = "";
String date = ofGetTimestampString("%Y-%m-%d_%H-%M");
if (IsCurrentSaveStateATemplate())
templateName = File(mCurrentSaveStatePath).getFileNameWithoutExtension().toStdString() + "_";
targetFile = File(savestateDirPath + templateName + date + ".bsk");
FileChooser chooser("Save current state as...", targetFile, "*.bsk", true, false, GetFileChooserParent());
if (chooser.browseForFileToSave(true))
SaveState(chooser.getResult().getFullPathName().toStdString(), false);
}
void ModularSynth::LoadStatePopup()
{
mShowLoadStatePopup = true;
}
void ModularSynth::LoadStatePopupImp()
{
FileChooser chooser("Load state", File(ofToDataPath("savestate")), "*.bsk;*.bskt", true, false, GetFileChooserParent());
if (chooser.browseForFileToOpen())
LoadState(chooser.getResult().getFullPathName().toStdString());
}
void ModularSynth::SaveState(std::string file, bool autosave)
{
if (!autosave)
{
mCurrentSaveStatePath = file;
std::string filename = File(mCurrentSaveStatePath).getFileName().toStdString();
mMainComponent->getTopLevelComponent()->setName("bespoke synth - " + filename);
TheTitleBar->DisplayTemporaryMessage("saved " + filename);
}
mAudioThreadMutex.Lock("SaveState()");
//write to a temp file first, so we don't corrupt data if we crash mid-save
std::string tmpFilePath = ofToDataPath("tmp");
{
FileStreamOut out(tmpFilePath);
mZoomer.WriteCurrentLocation(-1);
out << GetLayout().getRawString(true);
mModuleContainer.SaveState(out);
mUILayerModuleContainer.SaveState(out);
}
juce::File writtenFile(tmpFilePath);
juce::File targetFile(file);
writtenFile.copyFileTo(targetFile);
mAudioThreadMutex.Unlock();
}
void ModularSynth::SetStartupSaveStateFile(std::string bskPath)
{
mStartupSaveStateFile = std::move(bskPath);
}
void ModularSynth::LoadState(std::string file)
{
ofLog() << "LoadState() " << file;
if (!juce::File(file).existsAsFile())
{
LogEvent("couldn't find file " + file, kLogEventType_Error);
return;
}
if (mInitialized)
TitleBar::sShowInitialHelpOverlay = false; //don't show initial help popup
FileStreamIn in(ofToDataPath(file));
if (in.Eof())
{
LogEvent("File is empty: " + file, kLogEventType_Error);
return;
}
mAudioThreadMutex.Lock("LoadState()");
LockRender(true);
mAudioPaused = true;
mIsLoadingState = true;
LockRender(false);
mAudioThreadMutex.Unlock();
//TODO(Ryan) here's a little hack to allow older BSK files that were saved in 32-bit to load.
//I guess this could bite me if someone ever has a very massive json. the number corresponds to a long-standing sanity check in FileStreamIn::operator>>(std::string &var), so this shouldn't break any current behavior.
//this should definitely be removed if anything about the structure of the BSK format changes.
uint64_t firstLength[1];
in.Peek(firstLength, sizeof(uint64_t));
if (firstLength[0] >= FileStreamIn::sMaxStringLength)
FileStreamIn::s32BitMode = true;
std::string jsonString;
in >> jsonString;
bool layoutLoaded = LoadLayoutFromString(jsonString);
if (layoutLoaded)
{
mIsLoadingModule = true;
mModuleContainer.LoadState(in);
if (ModularSynth::sLastLoadedFileSaveStateRev >= 424)
mUILayerModuleContainer.LoadState(in);
mIsLoadingModule = false;
TheTransport->Reset();
}
FileStreamIn::s32BitMode = false;
mCurrentSaveStatePath = file;
File savePath(mCurrentSaveStatePath);
std::string filename = savePath.getFileName().toStdString();
mMainComponent->getTopLevelComponent()->setName("bespoke synth - " + filename);
mAudioThreadMutex.Lock("LoadState()");
LockRender(true);
mAudioPaused = false;
mIsLoadingState = false;
LockRender(false);
mAudioThreadMutex.Unlock();
}
bool ModularSynth::IsCurrentSaveStateATemplate() const
{
if (mCurrentSaveStatePath == "")
return false;
File savePath(mCurrentSaveStatePath);
return savePath.getFileExtension().toStdString() == ".bskt";
}
IAudioReceiver* ModularSynth::FindAudioReceiver(std::string name, bool fail)
{
IAudioReceiver* a = nullptr;
if (name == "")
return nullptr;
try
{
a = dynamic_cast<IAudioReceiver*>(FindModule(name, fail));
if (a == nullptr)
throw WrongModuleTypeException();
}
catch (UnknownModuleException& e)
{
LogEvent("Couldn't find referenced audio receiver \"" + name + "\"", kLogEventType_Error);
}
catch (WrongModuleTypeException& e)
{
LogEvent("\"" + name + "\" is not an audio receiver", kLogEventType_Error);
}
return a;
}
INoteReceiver* ModularSynth::FindNoteReceiver(std::string name, bool fail)
{
INoteReceiver* n = nullptr;
if (name == "")
return nullptr;
try
{
n = dynamic_cast<INoteReceiver*>(FindModule(name, fail));
if (n == nullptr)
throw WrongModuleTypeException();
}
catch (UnknownModuleException& e)
{
LogEvent("Couldn't find referenced note receiver \"" + name + "\"", kLogEventType_Error);
}
catch (WrongModuleTypeException& e)
{
LogEvent("\"" + name + "\" is not a note receiver", kLogEventType_Error);
}
return n;
}
void ModularSynth::OnConsoleInput(std::string command /* = "" */)
{
if (command.empty())
command = mConsoleText;
std::vector<std::string> tokens = ofSplitString(command, " ", true, true);
if (tokens.size() > 0)
{
if (tokens[0] == "")
{
}
else if (tokens[0] == "clearerrors")
{
mErrors.clear();
}
else if (tokens[0] == "clearall")
{
mAudioThreadMutex.Lock("clearall");
std::lock_guard<std::recursive_mutex> renderLock(mRenderLock);
ResetLayout();
mAudioThreadMutex.Unlock();
}
else if (tokens[0] == "load")
{
LoadLayout(ofToDataPath(tokens[1]));
}
else if (tokens[0] == "save")
{
if (tokens.size() > 1)
SaveLayout(ofToDataPath(tokens[1]));
else
SaveLayout();
}
else if (tokens[0] == "write")
{
SaveOutput();
}
else if (tokens[0] == "reconnect")
{
ReconnectMidiDevices();
}
else if (tokens[0] == "profiler")
{
Profiler::ToggleProfiler();
}
else if (tokens[0] == "clear")
{
mErrors.clear();
mEvents.clear();
}
else if (tokens[0] == "minimizeall")
{
const std::vector<IDrawableModule*> modules = mModuleContainer.GetModules();
for (auto iter = modules.begin(); iter != modules.end(); ++iter)
{
(*iter)->SetMinimized(true);
}
}
else if (tokens[0] == "resettime")
{
gTime = 0;
}
else if (tokens[0] == "hightime")
{
gTime += 1000000;
}
else if (tokens[0] == "tempo")
{
if (tokens.size() >= 2)
{
float tempo = atof(tokens[1].c_str());
if (tempo > 0)
TheTransport->SetTempo(tempo);
}
}
else if (tokens[0] == "home")
{
mZoomer.GoHome();
}
else if (tokens[0] == "saveas")
{
SaveLayoutAsPopup();
}
else if (tokens[0] == "dev")
{
gShowDevModules = true;
TheTitleBar->SetModuleFactory(&mModuleFactory);
}
else if (tokens[0] == "dumpmem")
{
DumpUnfreedMemory();
}
else if (tokens[0] == "savestate")
{
if (tokens.size() >= 2)
SaveState(ofToDataPath("savestate/" + tokens[1]), false);
}
else if (tokens[0] == "loadstate")
{
if (tokens.size() >= 2)
LoadState(ofToDataPath("savestate/" + tokens[1]));
}
else if (tokens[0] == "s")
{
SaveState(ofToDataPath("savestate/quicksave.bsk"), false);
}
else if (tokens[0] == "l")
{
LoadState(ofToDataPath("savestate/quicksave.bsk"));
}
else if (tokens[0] == "getwindowinfo")
{
ofLog() << "pos:(" << mMainComponent->getTopLevelComponent()->getPosition().x << ", " << mMainComponent->getTopLevelComponent()->getPosition().y << ") size:(" << ofGetWidth() << ", " << ofGetHeight() << ")";
}
else if (tokens[0] == "getmouse")
{
ofLog() << "mouse pos raw:(" << mMousePos.x << ", " << mMousePos.y << ") "
<< " mouse pos canvas:(" << GetMouseX(&mModuleContainer) << ", " << GetMouseY(&mModuleContainer) << ")";
}
else if (tokens[0] == "screenshotmodule")
{
TheTitleBar->GetHelpDisplay()->ScreenshotModule(mModuleContainer.GetModules()[0]);
}
else if (tokens[0] == "forcecrash")
{
Sample* nullPointer = nullptr;
ofLog() << ofToString(nullPointer->Data()->GetChannel(0)[0]);
}
else if (tokens[0] == "dumpstats")
{
DumpStats(false, nullptr);
}
else
{
ofLog() << "Creating: " << mConsoleText;
ofVec2f grabOffset(-40, 10);
ModuleFactory::Spawnable spawnable;
spawnable.mLabel = mConsoleText;
IDrawableModule* module = SpawnModuleOnTheFly(spawnable, GetMouseX(&mModuleContainer) + grabOffset.x, GetMouseY(&mModuleContainer) + grabOffset.y);
TheSynth->SetMoveModule(module, grabOffset.x, grabOffset.y, true);
}
}
}
void ModularSynth::ClearConsoleInput()
{
mConsoleText[0] = 0;
mConsoleEntry->UpdateDisplayString();
}
namespace
{
class FileTimeComparator
{
public:
int compareElements(juce::File first, juce::File second)
{
return (first.getCreationTime() < second.getCreationTime()) ? 1 : ((first.getCreationTime() == second.getCreationTime()) ? 0 : -1);
}
};
}
void ModularSynth::DoAutosave()
{
const int kMaxAutosaveSlots = 10;
juce::File parentDirectory(ofToDataPath("savestate/autosave"));
Array<juce::File> autosaveFiles;
parentDirectory.findChildFiles(autosaveFiles, juce::File::findFiles, false, "*.bsk");
if (autosaveFiles.size() >= kMaxAutosaveSlots)
{
FileTimeComparator cmp;
autosaveFiles.sort(cmp, false);
for (int i = kMaxAutosaveSlots; i < autosaveFiles.size(); ++i) //delete oldest files beyond slot limit
autosaveFiles[i].deleteFile();
}
SaveState(ofToDataPath(ofGetTimestampString("savestate/autosave/autosave_%Y-%m-%d_%H-%M-%S.bsk")), true);
}
IDrawableModule* ModularSynth::SpawnModuleOnTheFly(ModuleFactory::Spawnable spawnable, float x, float y, bool addToContainer, std::string name)
{
if (mInitialized)
TitleBar::sShowInitialHelpOverlay = false; //don't show initial help popup
if (sShouldAutosave)
DoAutosave();
std::string moduleType = spawnable.mLabel;
moduleType = ModuleFactory::FixUpTypeName(moduleType);
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::EffectChain)
moduleType = "effectchain";
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Prefab)
moduleType = "prefab";
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Plugin)
moduleType = "vstplugin";
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::MidiController)
moduleType = "midicontroller";
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Preset)
moduleType = spawnable.mPresetModuleType;
if (name == "")
name = moduleType;
ofxJSONElement dummy;
dummy["type"] = moduleType;
std::vector<IDrawableModule*> modules = mModuleContainer.GetModules();
dummy["name"] = GetUniqueName(name, modules);
dummy["onthefly"] = true;
dummy["position"][0u] = x;
dummy["position"][1u] = y;
IDrawableModule* module = nullptr;
try
{
ScopedMutex mutex(&mAudioThreadMutex, "CreateModule");
module = CreateModule(dummy);
if (module != nullptr)
{
if (addToContainer)
mModuleContainer.AddModule(module);
SetUpModule(module, dummy);
module->Init();
}
}
catch (LoadingJSONException& e)
{
LogEvent("Error spawning \"" + spawnable.mLabel + "\" on the fly", kLogEventType_Warning);
}
catch (UnknownModuleException& e)
{
LogEvent("Error spawning \"" + spawnable.mLabel + "\" on the fly, couldn't find \"" + e.mSearchName + "\"", kLogEventType_Warning);
}
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::EffectChain)
{
EffectChain* effectChain = dynamic_cast<EffectChain*>(module);
if (effectChain != nullptr)
effectChain->AddEffect(spawnable.mLabel, spawnable.mLabel, K(onTheFly));
}
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Prefab)
{
Prefab* prefab = dynamic_cast<Prefab*>(module);
if (prefab != nullptr)
prefab->LoadPrefab("prefabs" + GetPathSeparator() + spawnable.mLabel);
}
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Plugin)
{
VSTPlugin* plugin = dynamic_cast<VSTPlugin*>(module);
if (plugin != nullptr)
plugin->SetVST(spawnable.mPluginDesc);
}
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::MidiController)
{
MidiController* controller = dynamic_cast<MidiController*>(module);
if (controller != nullptr)
{
controller->GetSaveData().SetString("devicein", spawnable.mLabel);
controller->SetUpFromSaveDataBase();
}
}
if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Preset)
{
std::string presetFilePath = ofToDataPath("presets/" + spawnable.mPresetModuleType + "/" + spawnable.mLabel);
ModuleSaveDataPanel::LoadPreset(module, presetFilePath);
module->SetName(GetUniqueName(juce::String(spawnable.mLabel).replace(".preset", "").toStdString(), modules).c_str());
}
return module;
}
void ModularSynth::SetMoveModule(IDrawableModule* module, float offsetX, float offsetY, bool canStickToCursor)
{
mMoveModule = module;
mMoveModuleOffsetX = offsetX;
mMoveModuleOffsetY = offsetY;
mMoveModuleCanStickToCursor = canStickToCursor;
}
void ModularSynth::AddMidiDevice(MidiDevice* device)
{
if (!VectorContains(device, mMidiDevices))
mMidiDevices.push_back(device);
}
void ModularSynth::ReconnectMidiDevices()
{
for (int i = 0; i < mMidiDevices.size(); ++i)
mMidiDevices[i]->Reconnect();
}
void ModularSynth::SaveOutput()
{
ScopedMutex mutex(&mAudioThreadMutex, "SaveOutput()");
std::string save_prefix = "recording_";
if (!mCurrentSaveStatePath.empty())
{
// This assumes that mCurrentSaveStatePath always has a valid filename at the end
std::string filename = File(mCurrentSaveStatePath).getFileNameWithoutExtension().toStdString();
save_prefix = filename + "_";
}
std::string filename = ofGetTimestampString(UserPrefs.recordings_path.Get() + save_prefix + "%Y-%m-%d_%H-%M.wav");
//string filenamePos = ofGetTimestampString("recordings/pos_%Y-%m-%d_%H-%M.wav");
assert(mRecordingLength <= mGlobalRecordBuffer->Size());
int channels = 2;
auto wavFormat = std::make_unique<juce::WavAudioFormat>();
juce::File outputFile(ofToDataPath(filename));
outputFile.create();
auto outputTo = outputFile.createOutputStream();
assert(outputTo != nullptr);
bool b1{ false };
auto writer = std::unique_ptr<juce::AudioFormatWriter>(wavFormat->createWriterFor(outputTo.release(), gSampleRate, channels, 16, b1, 0));
long long samplesRemaining = mRecordingLength;
const int chunkSize = 256;
float leftChannel[chunkSize];
float rightChannel[chunkSize];
float* chunk[2]{ leftChannel, rightChannel };
while (samplesRemaining > 0)
{
int numSamples = MIN(chunkSize, samplesRemaining);
for (int i = 0; i < numSamples; ++i)
{
chunk[0][i] = mGlobalRecordBuffer->GetSample(samplesRemaining - 1, 0);
chunk[1][i] = mGlobalRecordBuffer->GetSample(samplesRemaining - 1, 1);
--samplesRemaining;
}
writer->writeFromFloatArrays(chunk, channels, numSamples);
}
mGlobalRecordBuffer->ClearBuffer();
mRecordingLength = 0;
TheTitleBar->DisplayTemporaryMessage("wrote " + filename);
}
const String& ModularSynth::GetTextFromClipboard() const
{
return TheClipboard;
}
void ModularSynth::CopyTextToClipboard(const String& text)
{
TheClipboard = text;
SystemClipboard::copyTextToClipboard(text);
}
void ModularSynth::ReadClipboardTextFromSystem()
{
TheClipboard = SystemClipboard::getTextFromClipboard();
}
void ModularSynth::SetFatalError(std::string error)
{
if (mFatalError == "")
{
mFatalError = error;
if (mUserPrefsEditor != nullptr)
mUserPrefsEditor->Show();
if (TheTitleBar != nullptr)
TheTitleBar->SetShowing(false);
}
}
void ConsoleListener::TextEntryActivated(TextEntry* entry)
{
TheSynth->ClearConsoleInput();
}
void ConsoleListener::TextEntryComplete(TextEntry* entry)
{
TheSynth->OnConsoleInput();
}
``` | /content/code_sandbox/Source/ModularSynth.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 28,049 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
PitchToCV.cpp
Created: 28 Nov 2017 9:44:15pm
Author: Ryan Challinor
==============================================================================
*/
#include "PitchToCV.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "ModulationChain.h"
PitchToCV::PitchToCV()
{
}
PitchToCV::~PitchToCV()
{
}
void PitchToCV::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
mMinSlider = new FloatSlider(this, "min", 3, 2, 100, 15, &mDummyMin, 0, 1);
mMaxSlider = new FloatSlider(this, "max", mMinSlider, kAnchor_Below, 100, 15, &mDummyMax, 0, 1);
}
void PitchToCV::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mMinSlider->Draw();
mMaxSlider->Draw();
}
void PitchToCV::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
}
void PitchToCV::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled && velocity > 0)
{
mPitch = pitch;
mPitchBend = modulation.pitchBend;
}
}
float PitchToCV::Value(int samplesIn)
{
float bend = mPitchBend ? mPitchBend->GetValue(samplesIn) : 0;
return ofMap(mPitch + bend, 0, 127, GetMin(), GetMax(), K(clamped));
}
void PitchToCV::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void PitchToCV::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void PitchToCV::SetUpFromSaveData()
{
}
``` | /content/code_sandbox/Source/PitchToCV.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 577 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
MPETweaker.h
Created: 6 Aug 2021 9:11:11pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ModulationChain.h"
class MPETweaker : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener
{
public:
MPETweaker();
virtual ~MPETweaker();
static IDrawableModule* Create() { return new MPETweaker(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
float mWidth{ 200 };
float mHeight{ 20 };
float mPitchBendMultiplier{ 1 };
FloatSlider* mPitchBendMultiplierSlider{ nullptr };
float mPitchBendOffset{ 0 };
FloatSlider* mPitchBendOffsetSlider{ nullptr };
float mPressureMultiplier{ 1 };
FloatSlider* mPressureMultiplierSlider{ nullptr };
float mPressureOffset{ 0 };
FloatSlider* mPressureOffsetSlider{ nullptr };
float mModWheelMultiplier{ 1 };
FloatSlider* mModWheelMultiplierSlider{ nullptr };
float mModWheelOffset{ 0 };
FloatSlider* mModWheelOffsetSlider{ nullptr };
Modulations mModulationMult{ true };
Modulations mModulationOffset{ true };
};
``` | /content/code_sandbox/Source/MPETweaker.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 608 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
Prefab.cpp
Created: 25 Sep 2016 10:14:16am
Author: Ryan Challinor
==============================================================================
*/
#include "Prefab.h"
#include "Checkbox.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "juce_gui_basics/juce_gui_basics.h"
//static
bool Prefab::sLoadingPrefab = false;
bool Prefab::sLastLoadWasPrefab = false;
IDrawableModule* Prefab::sJustReleasedModule = nullptr;
namespace
{
const float paddingX = 10;
const float paddingY = 10;
}
Prefab::Prefab()
{
mModuleContainer.SetOwner(this);
}
Prefab::~Prefab()
{
}
void Prefab::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mSaveButton = new ClickButton(this, "save", 95, 2);
mLoadButton = new ClickButton(this, "load", mSaveButton, kAnchor_Right);
mDisbandButton = new ClickButton(this, "disband", mLoadButton, kAnchor_Right);
mRemoveModuleCable = new PatchCableSource(this, kConnectionType_Special);
mRemoveModuleCable->SetManualPosition(10, 10);
AddPatchCableSource(mRemoveModuleCable);
}
std::string Prefab::GetTitleLabel() const
{
if (mPrefabName != "")
return "prefab: " + mPrefabName;
return "prefab";
}
void Prefab::Poll()
{
float xMin, yMin;
GetPosition(xMin, yMin);
for (auto* module : mModuleContainer.GetModules())
{
xMin = MIN(xMin, module->GetPosition().x - paddingX);
yMin = MIN(yMin, module->GetPosition().y - 30);
}
int xOffset = GetPosition().x - xMin;
int yOffset = GetPosition().y - yMin;
for (auto* module : mModuleContainer.GetModules())
module->SetPosition(module->GetPosition(true).x + xOffset, module->GetPosition(true).y + yOffset);
if (abs(GetPosition().x - xMin) >= 1 || abs(GetPosition().y - yMin) >= 1)
SetPosition(xMin, yMin);
}
bool Prefab::IsMouseHovered()
{
return GetRect(false).contains(TheSynth->GetMouseX(GetOwningContainer()), TheSynth->GetMouseY(GetOwningContainer()));
}
bool Prefab::CanAddDropModules()
{
if (IsMouseHovered() && !TheSynth->IsGroupSelecting())
{
if (IsAddableModule(TheSynth->GetMoveModule()))
return true;
if (IsAddableModule(sJustReleasedModule))
return true;
if (!TheSynth->GetGroupSelectedModules().empty())
{
for (auto* module : TheSynth->GetGroupSelectedModules())
{
if (module == this || module->IsSingleton())
return false;
if (IsAddableModule(module))
return true;
}
}
}
return false;
}
bool Prefab::IsAddableModule(IDrawableModule* module)
{
if (module == nullptr || module == this || VectorContains(module, mModuleContainer.GetModules()))
return false;
if (dynamic_cast<Prefab*>(module) != nullptr)
return false;
if (dynamic_cast<Prefab*>(module->GetParent()) != nullptr)
return false;
return true;
}
void Prefab::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (y > 0 && !right)
TheSynth->SetGroupSelectContext(&mModuleContainer);
}
void Prefab::MouseReleased()
{
IDrawableModule::MouseReleased();
if (CanAddDropModules() && !VectorContains<IDrawableModule*>(this, TheSynth->GetGroupSelectedModules()))
{
if (IsAddableModule(sJustReleasedModule))
mModuleContainer.TakeModule(sJustReleasedModule);
for (auto* module : TheSynth->GetGroupSelectedModules())
{
if (IsAddableModule(module))
mModuleContainer.TakeModule(module);
}
}
}
void Prefab::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
if (CanAddDropModules() && TheSynth->IsMouseButtonHeld(1))
{
ofPushStyle();
ofSetColor(255, 255, 255, 80);
ofFill();
ofRect(0, 0, GetRect().width, GetRect().height);
ofPopStyle();
}
mSaveButton->Draw();
mLoadButton->Draw();
mDisbandButton->Draw();
DrawTextNormal("remove", 18, 14);
mModuleContainer.DrawModules();
}
void Prefab::DrawModuleUnclipped()
{
mModuleContainer.DrawUnclipped();
}
void Prefab::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
if (cableSource == mRemoveModuleCable)
{
IDrawableModule* module = dynamic_cast<IDrawableModule*>(cableSource->GetTarget());
if (module)
{
if (VectorContains(module, mModuleContainer.GetModules()))
{
GetOwningContainer()->TakeModule(module);
GetOwningContainer()->MoveToFront(this);
}
}
cableSource->Clear();
}
}
void Prefab::GetModuleDimensions(float& width, float& height)
{
float x, y;
GetPosition(x, y);
width = 215;
height = 40;
//if (PatchCable::sActivePatchCable && PatchCable::sActivePatchCable->GetOwningModule() == this)
// return;
for (auto* module : mModuleContainer.GetModules())
{
ofRectangle rect = module->GetRect();
if (rect.x - x + rect.width + paddingX > width)
width = rect.x - x + rect.width + paddingX;
if (rect.y - y + rect.height + paddingY > height)
height = rect.y - y + rect.height + paddingY;
}
}
void Prefab::ButtonClicked(ClickButton* button, double time)
{
using namespace juce;
if (button == mSaveButton)
{
FileChooser chooser("Save prefab as...", File(ofToDataPath("prefabs/prefab.pfb")), "*.pfb", true, false, TheSynth->GetFileChooserParent());
if (chooser.browseForFileToSave(true))
{
std::string savePath = chooser.getResult().getFullPathName().toStdString();
SavePrefab(savePath);
}
}
if (button == mLoadButton)
{
FileChooser chooser("Load prefab...", File(ofToDataPath("prefabs")), "*.pfb", true, false, TheSynth->GetFileChooserParent());
if (chooser.browseForFileToOpen())
{
std::string loadPath = chooser.getResult().getFullPathName().toStdString();
LoadPrefab(ofToDataPath(loadPath));
}
}
if (button == mDisbandButton)
{
auto modules = mModuleContainer.GetModules();
for (auto* module : modules)
GetOwningContainer()->TakeModule(module);
GetOwningContainer()->DeleteModule(this);
}
}
void Prefab::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
for (auto& module : mModuleContainer.GetModules())
{
module->SetEnabled(mEnabled);
}
}
}
void Prefab::SavePrefab(std::string savePath)
{
ofxJSONElement root;
root["modules"] = mModuleContainer.WriteModules();
std::stringstream ss(root.getRawString(true));
std::string line;
std::string lines;
while (getline(ss, line, '\n'))
{
const char* pos = strstr(line.c_str(), " : \"$");
if (pos != nullptr)
{
bool endsWithComma = line[line.length() - 1] == ',';
ofStringReplace(line, pos, " : \"\"");
if (endsWithComma)
line += ",";
}
lines += line + '\n';
}
UpdatePrefabName(savePath);
FileStreamOut out(ofToDataPath(savePath));
out << lines;
mModuleContainer.SaveState(out);
}
void Prefab::LoadPrefab(std::string loadPath)
{
sLoadingPrefab = true;
ScopedMutex mutex(TheSynth->GetAudioMutex(), "LoadPrefab()");
std::lock_guard<std::recursive_mutex> renderLock(TheSynth->GetRenderLock());
mModuleContainer.Clear();
FileStreamIn in(ofToDataPath(loadPath));
assert(in.OpenedOk());
std::string jsonString;
in >> jsonString;
ofxJSONElement root;
bool loaded = root.parse(jsonString);
if (!loaded)
{
TheSynth->LogEvent("Couldn't load, error parsing " + loadPath, kLogEventType_Error);
TheSynth->LogEvent("Try loading it up in a json validator", kLogEventType_Error);
return;
}
UpdatePrefabName(loadPath);
mModuleContainer.LoadModules(root["modules"]);
mModuleContainer.LoadState(in);
sLoadingPrefab = false;
}
void Prefab::UpdatePrefabName(std::string path)
{
std::vector<std::string> tokens = ofSplitString(path, GetPathSeparator());
mPrefabName = tokens[tokens.size() - 1];
ofStringReplace(mPrefabName, ".pfb", "");
}
void Prefab::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["modules"] = mModuleContainer.WriteModules();
}
void Prefab::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleContainer.LoadModules(moduleInfo["modules"]);
SetUpFromSaveData();
}
void Prefab::SetUpFromSaveData()
{
}
void Prefab::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mPrefabName;
}
void Prefab::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (!ModuleContainer::DoesModuleHaveMoreSaveData(in))
return; //this was saved before we added versioning, bail out
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
in >> mPrefabName;
}
``` | /content/code_sandbox/Source/Prefab.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,441 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ClipArranger.h
// Bespoke
//
// Created by Ryan Challinor on 8/26/14.
//
//
#pragma once
#include <iostream>
#include "IAudioReceiver.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ClickButton.h"
#include "RollingBuffer.h"
#include "Ramp.h"
#include "Checkbox.h"
#include "NamedMutex.h"
#include "Sample.h"
class ClipArranger : public IDrawableModule, public IFloatSliderListener, public IButtonListener
{
public:
ClipArranger();
virtual ~ClipArranger();
static IDrawableModule* Create() { return new ClipArranger(); }
void Poll() override;
void Process(double time, float* left, float* right, int bufferSize);
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
void FilesDropped(std::vector<std::string> files, int x, int y) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
float MouseXToBufferPos(float mouseX);
int MouseXToSample(float mouseX);
float SampleToX(int sample);
bool IsMousePosWithinClip(int x, int y);
void AddSample(Sample* sample, int x, int y);
static const int MAX_CLIPS = 50;
static const int BUFFER_MARGIN_X = 5;
static const int BUFFER_MARGIN_Y = 5;
class Clip
{
public:
Clip() {}
void Process(float* left, float* right, int bufferSize);
Sample* mSample{ nullptr };
int mStartSample{ 0 };
int mEndSample{ 0 };
};
enum ClipMoveMode
{
kMoveMode_None,
kMoveMode_Start,
kMoveMode_End
} mMoveMode{ ClipMoveMode::kMoveMode_None };
Clip* GetEmptyClip();
Clip mClips[MAX_CLIPS];
float mBufferWidth{ 800 };
float mBufferHeight{ 80 };
int mHighlightClip{ -1 };
bool mMouseDown{ false };
int mLastMouseX{ -1 };
int mLastMouseY{ -1 };
NamedMutex mMutex;
};
``` | /content/code_sandbox/Source/ClipArranger.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 701 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// BeatBloks.h
// modularSynth
//
// Created by Ryan Challinor on 11/9/13.
//
//
#pragma once
#include <iostream>
#include "IAudioSource.h"
#include "EnvOscillator.h"
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Slider.h"
#include "DropdownList.h"
#include "Transport.h"
#include "ClickButton.h"
#include "JumpBlender.h"
class Sample;
#define MEASURE_ZONE_HEIGHT 40
#define BEAT_ZONE_HEIGHT 60
class BeatBloks : public IAudioSource, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public IButtonListener, public INoteReceiver
{
public:
BeatBloks();
~BeatBloks();
static IDrawableModule* Create() { return new BeatBloks(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IDrawableModule
void FilesDropped(std::vector<std::string> files, int x, int y) override;
void Poll() override;
//IClickable
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
//IFloatSliderListener
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
//IDropdownListener
void DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
enum BlokType
{
kBlok_Bar,
kBlok_Beat,
kBlok_Tatum,
kBlok_Segment,
kBlok_Section
};
struct Blok
{
Blok(float startTime, float duration, float confidence)
: mStartTime(startTime)
, mDuration(duration)
, mConfidence(confidence)
{}
float mStartTime;
float mDuration;
float mConfidence;
BlokType mType{ BlokType::kBlok_Bar };
};
enum ReadState
{
kReadState_Start,
kReadState_Bars,
kReadState_Beats,
kReadState_Tatums,
kReadState_Sections,
kReadState_Segments
} mReadState{ kReadState_Start };
void UpdateSample();
void DoWrite();
void UpdateZoomExtents();
void ResetRead();
void ReadEchonestLine(const char* line);
float StartTime(const Blok& blok);
float GetInsertPosition(int& insertIndex);
void PlaceHeldBlok();
Blok* RemoveBlokAt(int x);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
Sample* mSample{ nullptr };
float mVolume{ .6 };
FloatSlider* mVolumeSlider{ nullptr };
float* mWriteBuffer;
bool mPlay{ false };
Checkbox* mPlayCheckbox{ nullptr };
bool mLoop{ true };
Checkbox* mLoopCheckbox{ nullptr };
int mMeasureEarly{ 0 };
float mClipStart{ 0 };
FloatSlider* mClipStartSlider{ nullptr };
float mClipEnd{ 1 };
FloatSlider* mClipEndSlider{ nullptr };
float mZoomStart{ 0 };
FloatSlider* mZoomStartSlider{ nullptr };
float mZoomEnd{ 1 };
FloatSlider* mZoomEndSlider{ nullptr };
float mOffset{ 0 };
FloatSlider* mOffsetSlider{ nullptr };
int mNumBars{ 1 };
IntSlider* mNumBarsSlider{ nullptr };
ClickButton* mWriteButton{ nullptr };
float mPlayheadRemainder{ 0 };
int mPlayheadWhole{ 0 };
bool mWantWrite{ false };
ClickButton* mDoubleLengthButton{ nullptr };
ClickButton* mHalveLengthButton{ nullptr };
std::vector<Blok> mBars;
std::vector<Blok> mBeats;
std::vector<Blok> mTatums;
std::vector<Blok> mSections;
std::vector<Blok> mSegments;
std::vector<Blok> mNothing;
BlokType mDrawBlokType{ BlokType::kBlok_Bar };
DropdownList* mDrawBlokTypeDropdown{ nullptr };
bool mLoading{ false };
Blok* mHeldBlok{ nullptr };
float mMouseX{ 0 };
float mMouseY{ 0 };
float mGrabOffsetX{ 0 };
float mGrabOffsetY{ 0 };
ClickButton* mGetLuckyButton{ nullptr };
ClickButton* mLoseYourselfButton{ nullptr };
float mRemixPlayhead{ 0 };
bool mPlayRemix{ false };
Checkbox* mPlayRemixCheckbox{ nullptr };
std::list<Blok*> mRemixBloks;
JumpBlender mRemixJumpBlender;
Blok* mLastPlayedRemixBlok{ nullptr };
float mLastLookupPlayhead{ 0 };
ClickButton* mClearRemixButton{ nullptr };
float mRemixZoomStart{ 0 };
FloatSlider* mRemixZoomStartSlider{ nullptr };
float mRemixZoomEnd;
FloatSlider* mRemixZoomEndSlider{ nullptr };
bool mBlockMultiPlaceEngaged{ false };
bool mPlayBlokPreview{ false };
float mBlokPreviewPlayhead{ 0 };
Ramp mBlokPreviewRamp;
bool mDrawSources{ false };
Checkbox* mDrawSourcesCheckbox{ nullptr };
int mLastRemovedRemixBlokIdx{ -1 };
};
``` | /content/code_sandbox/Source/BeatBloks.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,580 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Chord.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/16/13.
//
//
#include "Chord.h"
#include "SynthGlobals.h"
#include "Scale.h"
Chord::Chord(std::string name)
{
assert(name.length() >= 4);
std::string pitchName;
std::string typeName;
if (name[1] == 'b' || name[1] == '#')
{
pitchName = name.substr(0, 2);
typeName = name.substr(2, name.length() - 2);
}
else
{
pitchName = name.substr(0, 1);
typeName = name.substr(1, name.length() - 1);
}
mRootPitch = PitchFromNoteName(pitchName);
if (typeName == "maj")
mType = kChord_Maj;
else if (typeName == "min")
mType = kChord_Min;
else if (typeName == "aug")
mType = kChord_Aug;
else if (typeName == "dim")
mType = kChord_Dim;
else
mType = kChord_Unknown;
}
std::string Chord::Name(bool withDegree, bool withAccidentals, ScalePitches* scale)
{
if (scale == nullptr)
scale = &TheScale->GetScalePitches();
int degree;
std::vector<Accidental> accidentals;
if (withDegree || withAccidentals)
scale->GetChordDegreeAndAccidentals(*this, degree, accidentals);
std::string chordName = NoteName(mRootPitch);
if (mType == kChord_Maj)
chordName += "maj";
else if (mType == kChord_Min)
chordName += "min";
else if (mType == kChord_Aug)
chordName += "aug";
else if (mType == kChord_Dim)
chordName += "dim";
else
chordName += "???";
if (mInversion != 0)
chordName += "-" + ofToString(mInversion);
if (withDegree)
chordName += " " + GetRomanNumeralForDegree(degree) + " ";
if (withAccidentals)
{
std::string accidentalList;
for (int i = 0; i < accidentals.size(); ++i)
accidentalList += ofToString(accidentals[i].mPitch) + (accidentals[i].mDirection == 1 ? "#" : "b") + " ";
chordName += accidentalList;
}
return chordName;
}
void Chord::SetFromDegreeAndScale(int degree, const ScalePitches& scale, int inversion /*= 0*/)
{
mRootPitch = scale.GetPitchFromTone(degree) % TheScale->GetPitchesPerOctave();
mType = kChord_Unknown;
if (scale.IsInScale(mRootPitch + 4))
{
if (scale.IsInScale(mRootPitch + 7))
mType = kChord_Maj;
else if (scale.IsInScale(mRootPitch + 8))
mType = kChord_Aug;
}
else if (scale.IsInScale(mRootPitch + 3))
{
if (scale.IsInScale(mRootPitch + 7))
mType = kChord_Min;
else if (scale.IsInScale(mRootPitch + 6))
mType = kChord_Dim;
}
mInversion = inversion;
}
``` | /content/code_sandbox/Source/Chord.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 887 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ControlSequencer.h
// Bespoke
//
// Created by Ryan Challinor on 8/27/15.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "UIGrid.h"
#include "ClickButton.h"
#include "Checkbox.h"
#include "Transport.h"
#include "DropdownList.h"
#include "Slider.h"
#include "IPulseReceiver.h"
#include "INoteReceiver.h"
#include "IDrivableSequencer.h"
class PatchCableSource;
class ControlSequencer : public IDrawableModule, public ITimeListener, public IDropdownListener, public UIGridListener, public IButtonListener, public IIntSliderListener, public IPulseReceiver, public INoteReceiver, public IDrivableSequencer, public IFloatSliderListener
{
public:
ControlSequencer();
~ControlSequencer();
static IDrawableModule* Create() { return new ControlSequencer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return true; }
void CreateUIControls() override;
void Init() override;
IUIControl* GetUIControl() const { return mTargets.size() == 0 ? nullptr : mTargets[0]; }
//IGridListener
void GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) override;
//IDrawableModule
void Poll() override;
bool IsResizable() const override { return !mSliderMode; }
void Resize(float w, float h) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//ITimeListener
void OnTimeEvent(double time) override;
//IPulseReceiver
void OnPulse(double time, float velocity, int flags) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IDrivableSequencer
bool HasExternalPulseSource() const override { return mHasExternalPulseSource; }
void ResetExternalPulseSource() override { mHasExternalPulseSource = false; }
void CheckboxUpdated(Checkbox* checkbox, double time) override {}
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
bool LoadOldControl(FileStreamIn& in, std::string& oldName) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 3; }
static std::list<ControlSequencer*> sControlSequencers;
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
bool IsEnabled() const override { return mEnabled; }
private:
void Step(double time, int pulseFlags);
void SetGridSize(float w, float h);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override;
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
void MouseReleased() override;
UIGrid* mGrid{ nullptr };
std::array<IUIControl*, IDrawableModule::kMaxOutputsPerPatchCableSource> mTargets{};
NoteInterval mInterval{ kInterval_4n };
DropdownList* mIntervalSelector{ nullptr };
int mLength{ 8 };
IntSlider* mLengthSlider{ nullptr };
std::string mOldLengthStr;
int mLoadRev{ -1 };
PatchCableSource* mControlCable{ nullptr };
ClickButton* mRandomize{ nullptr };
bool mHasExternalPulseSource{ false };
int mStep{ 0 };
bool mSliderMode{ true };
std::array<FloatSlider*, 32> mStepSliders{};
bool mRecord{ false };
Checkbox* mRecordCheckbox{ nullptr };
TransportListenerInfo* mTransportListenerInfo{ nullptr };
};
``` | /content/code_sandbox/Source/ControlSequencer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,125 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
EQModule.h
Created: 2 Nov 2020 10:47:16pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "FFT.h"
#include "RollingBuffer.h"
#include "BiquadFilter.h"
#include "DropdownList.h"
class EQModule : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IDropdownListener
{
public:
EQModule();
virtual ~EQModule();
static IDrawableModule* Create() { return new EQModule(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SaveLayout(ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override;
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override;
void KeyPressed(int key, bool isRepeat) override;
void MouseReleased() override;
static const int kNumFFTBins = 1024 * 8;
static const int kBinIgnore = 2;
static const int kDrawYOffset = 100;
float FreqForBin(int bin) { return (float(bin) / kNumFFTBins) * gSampleRate; };
float PosForFreq(float freq) { return log2(freq / 20) / 10; };
float FreqForPos(float pos) { return 20.0 * std::pow(2.0, pos * 10); };
float PosForGain(float gain) { return .5f - gain / 30.0f; };
float GainForPos(float pos) { return (.5f - pos) * 30; }
float mWidth{ 825 };
float mHeight{ 255 };
float* mWindower{ nullptr };
float* mSmoother{ nullptr };
::FFT mFFT;
FFTData mFFTData;
RollingBuffer mRollingInputBuffer;
struct Filter
{
bool mEnabled{ false };
std::array<BiquadFilter, 2> mFilter;
Checkbox* mEnabledCheckbox{ nullptr };
DropdownList* mTypeSelector{ nullptr };
FloatSlider* mFSlider{ nullptr };
FloatSlider* mGSlider{ nullptr };
FloatSlider* mQSlider{ nullptr };
bool mNeedToCalculateCoefficients{ true };
bool UpdateCoefficientsIfNecessary();
};
std::array<Filter, 8> mFilters;
int mHoveredFilterHandleIndex{ -1 };
int mDragging{ false };
std::array<float, 1024> mFrequencyResponse{};
bool mNeedToUpdateFrequencyResponseGraph{ true };
float mDrawGain{ 1 };
bool mLiteCpuModulation{ true };
};
``` | /content/code_sandbox/Source/EQModule.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 953 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// BandVocoder.h
// modularSynth
//
// Created by Ryan Challinor on 1/1/14.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "RollingBuffer.h"
#include "Slider.h"
#include "BiquadFilterEffect.h"
#include "VocoderCarrierInput.h"
#include "PeakTracker.h"
#define VOCODER_MAX_BANDS 64
class BandVocoder : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public VocoderBase, public IIntSliderListener
{
public:
BandVocoder();
virtual ~BandVocoder();
static IDrawableModule* Create() { return new BandVocoder(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetCarrierBuffer(float* carrier, int bufferSize) override;
//IAudioReceiver
InputMode GetInputMode() override { return kInputMode_Mono; }
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 215;
h = 130;
}
void CalcFilters();
float* mCarrierInputBuffer{ nullptr };
float* mWorkBuffer{ nullptr };
float* mOutBuffer{ nullptr };
float mInputPreamp{ 1 };
float mCarrierPreamp{ 1 };
float mVolume{ 1 };
FloatSlider* mInputSlider{ nullptr };
FloatSlider* mCarrierSlider{ nullptr };
FloatSlider* mVolumeSlider{ nullptr };
float mDryWet{ 1 };
FloatSlider* mDryWetSlider{ nullptr };
float mQ{ 40 };
FloatSlider* mQSlider{ nullptr };
IntSlider* mNumBandsSlider{ nullptr };
int mNumBands{ 40 };
float mFreqBase{ 200 };
float mFreqRange{ 6000 };
FloatSlider* mFBaseSlider{ nullptr };
FloatSlider* mFRangeSlider{ nullptr };
float mRingTime{ .03 };
FloatSlider* mRingTimeSlider{ nullptr };
float mMaxBand{ 1 };
FloatSlider* mMaxBandSlider{ nullptr };
float mSpacingStyle{ 0 };
FloatSlider* mSpacingStyleSlider{ nullptr };
BiquadFilter mBiquadCarrier[VOCODER_MAX_BANDS]{};
BiquadFilter mBiquadOut[VOCODER_MAX_BANDS]{};
PeakTracker mPeaks[VOCODER_MAX_BANDS]{};
PeakTracker mOutputPeaks[VOCODER_MAX_BANDS]{};
bool mCarrierDataSet{ false };
};
``` | /content/code_sandbox/Source/BandVocoder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 841 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ModulationVisualizer.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/27/15.
//
//
#include "ModulationVisualizer.h"
#include "SynthGlobals.h"
#include "ModulationChain.h"
#include "PolyphonyMgr.h"
ModulationVisualizer::ModulationVisualizer()
{
mVoices.resize(kNumVoices);
}
void ModulationVisualizer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
int y = 15;
DrawTextNormal("global: " + mGlobalModulation.GetInfoString(), 3, y);
y += 15;
for (int i = 0; i < kNumVoices; ++i)
{
if (mVoices[i].mActive)
{
DrawTextNormal(ofToString(i) + ":" + mVoices[i].GetInfoString(), 3, y);
y += 15;
}
}
}
void ModulationVisualizer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
if (voiceIdx == -1)
{
mGlobalModulation.mActive = velocity > 0;
mGlobalModulation.mModulators = modulation;
}
else
{
mVoices[voiceIdx].mActive = velocity > 0;
mVoices[voiceIdx].mModulators = modulation;
}
}
void ModulationVisualizer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void ModulationVisualizer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
std::string ModulationVisualizer::VizVoice::GetInfoString()
{
std::string info;
if (mModulators.pitchBend)
info += "bend:" + ofToString(mModulators.pitchBend->GetValue(0), 2) + " ";
if (mModulators.modWheel)
info += "mod:" + ofToString(mModulators.modWheel->GetValue(0), 2) + " ";
if (mModulators.pressure)
info += "pressure:" + ofToString(mModulators.pressure->GetValue(0), 2) + " ";
info += "pan:" + ofToString(mModulators.pan, 2) + " ";
return info;
}
void ModulationVisualizer::Resize(float w, float h)
{
mWidth = w;
mHeight = h;
}
``` | /content/code_sandbox/Source/ModulationVisualizer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 674 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
AudioToPulse.cpp
Created: 31 Mar 2021 10:18:54pm
Author: Ryan Challinor
==============================================================================
*/
#include "AudioToPulse.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "Profiler.h"
#include "UIControlMacros.h"
AudioToPulse::AudioToPulse()
: IAudioProcessor(gBufferSize)
{
}
AudioToPulse::~AudioToPulse()
{
}
void AudioToPulse::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
FLOATSLIDER(mThresholdSlider, "threshold", &mThreshold, 0, 1);
FLOATSLIDER(mReleaseSlider, "release", &mRelease, .01f, 1000);
ENDUIBLOCK(mWidth, mHeight);
mThresholdSlider->SetMode(FloatSlider::kSquare);
mReleaseSlider->SetMode(FloatSlider::kSquare);
//update mReleaseFactor
FloatSliderUpdated(mReleaseSlider, 0, gTime);
GetPatchCableSource()->SetConnectionType(kConnectionType_Pulse);
}
void AudioToPulse::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mThresholdSlider->Draw();
mReleaseSlider->Draw();
ofPushStyle();
ofFill();
ofSetColor(0, 255, 0, gModuleDrawAlpha * .4f);
ofRectangle rect = mThresholdSlider->GetRect(true);
rect.width *= ofClamp(sqrtf(mPeak), 0, 1);
rect.height *= .5f;
ofRect(rect);
ofSetColor(255, 0, 0, gModuleDrawAlpha * .4f);
rect = mThresholdSlider->GetRect(true);
rect.width *= ofClamp(mEnvelope, 0, 1);
rect.height *= .5f;
rect.y += rect.height;
ofRect(rect);
ofPopStyle();
}
void AudioToPulse::Process(double time)
{
PROFILER(AudioToPulse);
if (!mEnabled)
return;
ComputeSliders(0);
SyncBuffers();
const float kAttackTimeMs = 1;
assert(GetBuffer()->BufferSize());
Clear(gWorkBuffer, gBufferSize);
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
Add(gWorkBuffer, GetBuffer()->GetChannel(ch), gBufferSize);
Mult(gWorkBuffer, 1.0f / GetBuffer()->NumActiveChannels(), gBufferSize);
for (int i = 0; i < gBufferSize; ++i)
{
const float decayTime = .01f;
float scalar = powf(0.5f, 1.0f / (decayTime * gSampleRate));
float input = fabsf(gWorkBuffer[i]);
if (input >= mPeak)
{
/* When we hit a peak, ride the peak to the top. */
mPeak = input;
}
else
{
/* Exponential decay of output when signal is low. */
mPeak = mPeak * scalar;
if (mPeak < FLT_EPSILON)
mPeak = 0.0;
}
float oldEnvelope = mEnvelope;
if (mPeak >= mThreshold && mEnvelope < 1)
mEnvelope = MIN(1, mEnvelope + gInvSampleRateMs / kAttackTimeMs);
if (mPeak < mThreshold && mEnvelope > 0)
mEnvelope = MAX(0, mEnvelope - gInvSampleRateMs / mRelease);
if (mEnvelope >= 0.01f && oldEnvelope < 0.01f)
DispatchPulse(GetPatchCableSource(), time + i * gInvSampleRateMs, 1, 0);
}
GetBuffer()->Reset();
}
void AudioToPulse::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mReleaseSlider)
mReleaseFactor = powf(.01f, 1.0f / (mRelease * gSampleRateMs));
}
void AudioToPulse::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void AudioToPulse::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void AudioToPulse::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/AudioToPulse.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,092 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Producer.cpp
// modularSynth
//
// Created by Ryan Challinor on 11/13/13.
//
//
#include "Producer.h"
#include "IAudioReceiver.h"
#include "Sample.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
const float mBufferX = 5;
const float mBufferY = 80;
const float mBufferW = 900;
const float mBufferH = 300;
Producer::Producer()
{
mWriteBuffer = new float[gBufferSize];
Clear(mWriteBuffer, gBufferSize);
mSample = new Sample();
for (int i = 0; i < PRODUCER_NUM_BIQUADS; ++i)
{
AddChild(&mBiquad[i]);
mBiquad[i].SetPosition(150 + 100 * i, mBufferY + 10);
mBiquad[i].SetFilterType(kFilterType_Lowpass);
mBiquad[i].SetFilterParams(1600, sqrt(2) / 2);
}
}
void Producer::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mVolumeSlider = new FloatSlider(this, "volume", 5, 20, 110, 15, &mVolume, 0, 2);
mPlayCheckbox = new Checkbox(this, "play", 5, 60, &mPlay);
mLoopCheckbox = new Checkbox(this, "loop", 55, 60, &mLoop);
mClipStartSlider = new FloatSlider(this, "start", mBufferX, mBufferY + mBufferH - 30, 900, 15, &mClipStart, 0, gSampleRate * 200);
mClipEndSlider = new FloatSlider(this, "end", mBufferX, mBufferY + mBufferH - 15, 900, 15, &mClipEnd, 0, gSampleRate * 200);
mZoomStartSlider = new FloatSlider(this, "zoomstart", mBufferX, mBufferY + mBufferH + 5, 900, 15, &mZoomStart, 0, gSampleRate * 200);
mZoomEndSlider = new FloatSlider(this, "zoomend", mBufferX, mBufferY + mBufferH + 20, 900, 15, &mZoomEnd, 0, gSampleRate * 200);
mNumBarsSlider = new IntSlider(this, "num bars", 215, 3, 220, 15, &mNumBars, 1, 16);
mOffsetSlider = new FloatSlider(this, "off", 215, 20, 110, 15, &mOffset, -1, 1, 4);
mWriteButton = new ClickButton(this, "write", 600, 50);
mDoubleLengthButton = new ClickButton(this, "double", 600, 10);
mHalveLengthButton = new ClickButton(this, "halve", 600, 28);
mTempoSlider = new FloatSlider(this, "tempo", 490, 10, 100, 15, &mTempo, 30, 200);
mStartOffsetSlider = new IntSlider(this, "start", 490, 28, 100, 15, &mStartOffset, 0, gSampleRate * 4);
mCalcTempoButton = new ClickButton(this, "calc tempo", 490, 46);
mRestartButton = new ClickButton(this, "restart", 100, 60);
for (int i = 0; i < PRODUCER_NUM_BIQUADS; ++i)
mBiquad[i].CreateUIControls();
}
Producer::~Producer()
{
delete[] mWriteBuffer;
delete mSample;
}
void Producer::Process(double time)
{
PROFILER(Producer);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr || mSample == nullptr || mPlay == false)
return;
ComputeSliders(0);
int bufferSize = target->GetBuffer()->BufferSize();
float* out = target->GetBuffer()->GetChannel(0);
assert(bufferSize == gBufferSize);
float volSq = mVolume * mVolume;
const float* data = mSample->Data()->GetChannel(0);
int numSamples = mSample->LengthInSamples();
for (int i = 0; i < bufferSize; ++i)
{
if (mPlayhead < numSamples)
{
out[i] += data[mPlayhead] * volSq;
}
else
{
mPlay = false;
out[i] = 0; //fill the rest with zero
}
mPlayhead += 1;
while (IsSkipMeasure(GetMeasureForSample(mPlayhead)))
{
mPlayhead += GetSamplesPerMeasure();
}
if (mLoop && mPlayhead > mClipEnd)
mPlayhead = mClipStart;
}
ChannelBuffer buff(out, bufferSize);
for (int i = 0; i < PRODUCER_NUM_BIQUADS; ++i)
mBiquad[i].ProcessAudio(gTime, &buff);
GetVizBuffer()->WriteChunk(out, bufferSize, 0);
}
void Producer::FilesDropped(std::vector<std::string> files, int x, int y)
{
mSample->Reset();
mSample->Read(files[0].c_str());
mClipStart = 0;
mClipEnd = mSample->LengthInSamples();
mZoomStart = 0;
mZoomEnd = mClipEnd;
mZoomStartSlider->SetExtents(0, mClipEnd);
mZoomEndSlider->SetExtents(0, mClipEnd);
UpdateZoomExtents();
}
void Producer::DropdownClicked(DropdownList* list)
{
}
void Producer::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void Producer::UpdateSample()
{
}
void Producer::ButtonClicked(ClickButton* button, double time)
{
if (button == mWriteButton)
{
DoWrite();
}
if (button == mDoubleLengthButton)
{
float newEnd = (mClipEnd - mClipStart) * 2 + mClipStart;
if (newEnd < mSample->LengthInSamples())
{
mClipEnd = newEnd;
mNumBars *= 2;
}
}
if (button == mHalveLengthButton)
{
if (mNumBars % 2 == 0)
{
float newEnd = (mClipEnd - mClipStart) / 2 + mClipStart;
mClipEnd = newEnd;
mNumBars /= 2;
}
}
if (button == mCalcTempoButton)
{
if (mClipStart < mClipEnd)
{
float samplesPerMeasure = mClipEnd - mClipStart;
float secondsPerMeasure = samplesPerMeasure / gSampleRate;
mTempo = 1 / secondsPerMeasure * 4 * 60 * mNumBars;
mStartOffset = ((mClipStart / samplesPerMeasure) - int(mClipStart / samplesPerMeasure)) * samplesPerMeasure;
}
}
if (button == mRestartButton)
mPlayhead = mClipStart;
}
void Producer::DoWrite()
{
if (mSample)
{
ChannelBuffer sample(mSample->LengthInSamples());
sample.CopyFrom(mSample->Data());
for (int i = 0; i < PRODUCER_NUM_BIQUADS; ++i)
mBiquad[i].ProcessAudio(gTime, &sample);
float* toWrite = new float[mSample->LengthInSamples()];
int pos = 0;
for (int i = 0; i < mSample->LengthInSamples(); ++i)
{
if (IsSkipMeasure(GetMeasureForSample(i)) == false)
{
toWrite[pos] = sample.GetChannel(0)[i];
++pos;
}
}
Sample::WriteDataToFile(ofGetTimestampString("producer/producer_%Y-%m-%d_%H-%M.wav").c_str(), &toWrite, pos);
mClipStart = 0;
mClipEnd = mSample->LengthInSamples();
mOffset = 0;
mZoomStart = 0;
mZoomEnd = mClipEnd;
mZoomStartSlider->SetExtents(0, mClipEnd);
mZoomEndSlider->SetExtents(0, mClipEnd);
UpdateZoomExtents();
}
}
void Producer::UpdateZoomExtents()
{
mClipStartSlider->SetExtents(mZoomStart, mZoomEnd);
mClipEndSlider->SetExtents(mZoomStart, mZoomEnd);
}
int Producer::GetMeasureSample(int measure)
{
return mStartOffset + measure * GetSamplesPerMeasure();
}
float Producer::GetBufferPos(int sample)
{
return (sample - mZoomStart) / (mZoomEnd - mZoomStart);
}
int Producer::GetMeasureForSample(int sample)
{
return (sample - mStartOffset) / GetSamplesPerMeasure();
}
int Producer::GetSamplesPerMeasure()
{
return gSampleRate / (mTempo / 60 / 4);
}
bool Producer::IsSkipMeasure(int measure)
{
return ListContains(measure, mSkipMeasures);
}
void Producer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mVolumeSlider->Draw();
mPlayCheckbox->Draw();
mLoopCheckbox->Draw();
if (mSample)
{
ofPushMatrix();
ofTranslate(mBufferX, mBufferY);
ofPushStyle();
mSample->LockDataMutex(true);
DrawAudioBuffer(mBufferW, mBufferH, mSample->Data(), mZoomStart, mZoomEnd, (int)mPlayhead);
mSample->LockDataMutex(false);
ofFill();
for (int measure = 0; GetMeasureSample(measure) < mZoomEnd; ++measure)
{
if (GetMeasureSample(measure) >= mZoomStart)
{
float pos = GetBufferPos(GetMeasureSample(measure));
ofSetColor(0, 0, 255);
ofRect(pos * mBufferW, 0, 1, mBufferH);
if (IsSkipMeasure(measure))
{
ofSetColor(255, 0, 0, 100);
ofRect(pos * mBufferW, 0, (GetBufferPos(GetMeasureSample(measure + 1)) - pos) * mBufferW, mBufferH);
}
}
}
/*int start = ofMap(mClipStart, 0, length, 0, width, true);
int end = ofMap(mClipEnd, 0, length, 0, width, true);
for (int i = 0; i < mNumBars; i++)
{
float barSpacing = float(end-start)/mNumBars;
int x = barSpacing * i + start;
x += barSpacing * -mOffset;
ofSetColor(255,255,0);
ofLine(x, 0, x, height);
}
ofSetColor(255,0,0);
ofLine(start,0,start,height);
ofLine(end,0,end,height);
ofSetColor(0,255,0);
int position = ofMap(pos, 0, length, 0, width, true);
ofLine(position,0,position,height);*/
ofPopStyle();
ofPopMatrix();
mClipStartSlider->Draw();
mClipEndSlider->Draw();
mZoomStartSlider->Draw();
mZoomEndSlider->Draw();
mNumBarsSlider->Draw();
mOffsetSlider->Draw();
mWriteButton->Draw();
mDoubleLengthButton->Draw();
mHalveLengthButton->Draw();
mTempoSlider->Draw();
mStartOffsetSlider->Draw();
mCalcTempoButton->Draw();
mRestartButton->Draw();
if (mSample)
DrawTextNormal(ofToString(mSample->GetPlayPosition()), 335, 50);
}
for (int i = 0; i < PRODUCER_NUM_BIQUADS; ++i)
mBiquad[i].Draw();
}
void Producer::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (right)
return;
if (x >= mBufferX && y >= mBufferY + 100 && x < mBufferX + mBufferW && y < mBufferY + mBufferH)
{
if (IsKeyHeld('x'))
{
float pos = (x - mBufferX) / mBufferW;
float sample = pos * (mZoomEnd - mZoomStart) + mZoomStart;
int measure = GetMeasureForSample(sample);
if (IsSkipMeasure(measure))
mSkipMeasures.remove(measure);
else
mSkipMeasures.push_back(measure);
}
else
{
mPlayhead = ofMap(x, mBufferX, mBufferX + mBufferW, mZoomStart, mZoomEnd, true);
}
}
}
void Producer::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mPlayCheckbox)
{
if (mSample)
mSample->Reset();
}
}
void Producer::GetModuleDimensions(float& width, float& height)
{
width = 910;
height = 430;
}
void Producer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mClipStartSlider)
{
if (mSample && mClipStart > mSample->LengthInSamples())
mClipStart = mSample->LengthInSamples();
}
if (slider == mClipEndSlider)
{
if (mSample && mClipEnd > mSample->LengthInSamples())
mClipEnd = mSample->LengthInSamples();
}
if (slider == mZoomStartSlider)
{
if (mSample && mZoomStart > mSample->LengthInSamples())
mZoomStart = mSample->LengthInSamples();
UpdateZoomExtents();
}
if (slider == mZoomEndSlider)
{
if (mSample && mZoomEnd > mSample->LengthInSamples())
mZoomEnd = mSample->LengthInSamples();
UpdateZoomExtents();
}
}
void Producer::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void Producer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mSample)
{
mPlay = false;
if (pitch == 16)
{
mSample->Reset();
}
else if (pitch >= 0 && pitch < 16 && velocity > 0)
{
int slice = (pitch / 8) * 8 + 7 - (pitch % 8);
int barLength = (mClipEnd - mClipStart) / mNumBars;
int position = -mOffset * barLength + (barLength / 4) * slice + mClipStart;
mSample->Play(time, 1, position);
}
}
}
void Producer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Producer::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/Producer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,548 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// PitchDive.h
// Bespoke
//
// Created by Ryan Challinor on 12/27/15.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ModulationChain.h"
#include "Transport.h"
class PitchDive : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener
{
public:
PitchDive();
virtual ~PitchDive();
static IDrawableModule* Create() { return new PitchDive(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 120;
height = 40;
}
float mStart;
FloatSlider* mStartSlider;
float mTime;
FloatSlider* mTimeSlider;
Modulations mModulation;
};
``` | /content/code_sandbox/Source/PitchDive.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 464 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// FMVoice.h
// modularSynth
//
// Created by Ryan Challinor on 1/6/13.
//
//
#pragma once
#include "IMidiVoice.h"
#include "IVoiceParams.h"
#include "ADSR.h"
#include "EnvOscillator.h"
class IDrawableModule;
class FMVoiceParams : public IVoiceParams
{
public:
::ADSR mOscADSRParams;
::ADSR mModIdxADSRParams;
::ADSR mHarmRatioADSRParams;
::ADSR mModIdxADSRParams2;
::ADSR mHarmRatioADSRParams2;
float mModIdx{ 0 };
float mHarmRatio{ 1 };
float mModIdx2{ 0 };
float mHarmRatio2{ 1 };
float mVol{ 1 };
float mPhaseOffset0{ 0 };
float mPhaseOffset1{ 0 };
float mPhaseOffset2{ 0 };
};
class FMVoice : public IMidiVoice
{
public:
FMVoice(IDrawableModule* owner = nullptr);
~FMVoice();
// IMidiVoice
void Start(double time, float amount) override;
void Stop(double time) override;
void ClearVoice() override;
bool Process(double time, ChannelBuffer* out, int oversampling) override;
void SetVoiceParams(IVoiceParams* params) override;
bool IsDone(double time) override;
private:
float mOscPhase{ 0 };
EnvOscillator mOsc{ kOsc_Sin };
float mHarmPhase{ 0 };
EnvOscillator mHarm{ kOsc_Sin };
::ADSR mModIdx;
float mHarmPhase2{ 0 };
EnvOscillator mHarm2{ kOsc_Sin };
::ADSR mModIdx2;
FMVoiceParams* mVoiceParams{ nullptr };
IDrawableModule* mOwner;
};
``` | /content/code_sandbox/Source/FMVoice.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 532 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
TakeRecorder.cpp
Created: 9 Aug 2017 11:31:59pm
Author: Ryan Challinor
==============================================================================
*/
#include "TakeRecorder.h"
#include "ModularSynth.h"
#include "Profiler.h"
TakeRecorder::TakeRecorder()
: IAudioProcessor(gBufferSize)
{
}
void TakeRecorder::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mStartSecondsSlider = new FloatSlider(this, "start", 5, 2, 110, 15, &mStartSeconds, 0, 4);
}
TakeRecorder::~TakeRecorder()
{
}
void TakeRecorder::Process(double time)
{
PROFILER(TakeRecorder);
if (!mEnabled)
return;
ComputeSliders(0);
SyncBuffers();
int bufferSize = GetBuffer()->BufferSize();
IAudioReceiver* target = GetTarget();
if (target)
{
Add(target->GetBuffer()->GetChannel(0), GetBuffer()->GetChannel(0), bufferSize);
}
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(0), bufferSize, 0);
GetBuffer()->Reset();
}
void TakeRecorder::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mStartSecondsSlider->Draw();
}
void TakeRecorder::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void TakeRecorder::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/TakeRecorder.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 444 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// OscController.h
// Bespoke
//
// Created by Ryan Challinor on 5/1/14.
//
//
#pragma once
#include "MidiDevice.h"
#include "INonstandardController.h"
#include "juce_osc/juce_osc.h"
struct OscMap
{
int mControl{ 0 };
std::string mAddress;
bool mIsFloat{ false };
float mFloatValue{ 0 };
int mIntValue{ 0 };
double mLastChangedTime{ -9999 }; //@TODO(Noxy): Unused but is in savestates.
};
class OscController : public INonstandardController,
private juce::OSCReceiver,
private juce::OSCReceiver::Listener<juce::OSCReceiver::MessageLoopCallback>
{
public:
OscController(MidiDeviceListener* listener, std::string outAddress, int outPort, int inPort);
~OscController();
void Connect();
void oscMessageReceived(const juce::OSCMessage& msg) override;
void SendValue(int page, int control, float value, bool forceNoteOn = false, int channel = -1) override;
int AddControl(std::string address, bool isFloat);
bool IsInputConnected() override { return mConnected; }
bool Reconnect() override
{
Connect();
return mConnected;
}
bool SetInPort(int port);
std::string GetControlTooltip(MidiMessageType type, int control) override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in) override;
private:
MidiDeviceListener* mListener{ nullptr };
int FindControl(std::string address);
void ConnectOutput();
std::string mOutAddress;
int mOutPort{ 0 };
int mInPort{ 0 };
juce::OSCSender mOscOut;
bool mConnected{ false };
bool mOutputConnected{ false };
std::vector<OscMap> mOscMap;
};
``` | /content/code_sandbox/Source/OscController.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 532 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// MultibandCompressor.cpp
// Bespoke
//
// Created by Ryan Challinor on 3/27/14.
//
//
#include "MultibandCompressor.h"
#include "ModularSynth.h"
#include "Profiler.h"
MultibandCompressor::MultibandCompressor()
: IAudioProcessor(gBufferSize)
{
mWorkBuffer = new float[GetBuffer()->BufferSize()];
Clear(mWorkBuffer, GetBuffer()->BufferSize());
mOutBuffer = new float[GetBuffer()->BufferSize()];
Clear(mOutBuffer, GetBuffer()->BufferSize());
CalcFilters();
}
void MultibandCompressor::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mDryWetSlider = new FloatSlider(this, "dry/wet", 5, 83, 100, 15, &mDryWet, 0, 1);
mNumBandsSlider = new IntSlider(this, "bands", 110, 29, 100, 15, &mNumBands, 1, COMPRESSOR_MAX_BANDS);
mFMinSlider = new FloatSlider(this, "fmin", 110, 47, 100, 15, &mFreqMin, 70, 400);
mFMaxSlider = new FloatSlider(this, "fmax", 110, 65, 100, 15, &mFreqMax, 300, gSampleRate / 2 - 1);
mRingTimeSlider = new FloatSlider(this, "ring", 110, 101, 100, 15, &mRingTime, .0001f, .1f, 4);
mMaxBandSlider = new FloatSlider(this, "max band", 5, 101, 100, 15, &mMaxBand, 0.001f, 1);
}
MultibandCompressor::~MultibandCompressor()
{
delete[] mOutBuffer;
delete[] mWorkBuffer;
}
void MultibandCompressor::Process(double time)
{
PROFILER(multiband);
if (!mEnabled)
return;
ComputeSliders(0);
SyncBuffers();
int bufferSize = GetBuffer()->BufferSize();
IAudioReceiver* target = GetTarget();
if (target)
{
Clear(mOutBuffer, bufferSize);
for (int i = 0; i < bufferSize; ++i)
{
float lower;
float highLeftover = GetBuffer()->GetChannel(0)[i];
for (int j = 0; j < mNumBands; ++j)
{
mFilters[j].ProcessSample(highLeftover, lower, highLeftover);
mPeaks[j].Process(&lower, 1);
float compress = ofClamp(1 / mPeaks[i].GetPeak(), 0, 10);
mOutBuffer[i] += lower * compress;
}
mOutBuffer[i] += highLeftover;
}
/*for (int i=0; i<mNumBands; ++i)
{
//get carrier band
BufferCopy(mWorkBuffer, mInputBuffer, bufferSize);
mFilters[i].ProcessSample(const double &sample, double &lowOut, double &highOut)(mWorkBuffer, bufferSize);
//calculate modulator band level
mPeaks[i].Process(mWorkBuffer, bufferSize);
//multiply carrier band by modulator band level
if (mPeaks[i].GetPeak() > 0)
{
float compress = ofClamp(1/mPeaks[i].GetPeak(), 0, 10);
Mult(mWorkBuffer, compress, bufferSize);
}
//accumulate output band into total output
Add(mOutBuffer, mWorkBuffer, bufferSize);
}*/
Mult(GetBuffer()->GetChannel(0), (1 - mDryWet), bufferSize);
Mult(mOutBuffer, mDryWet, bufferSize);
Add(target->GetBuffer()->GetChannel(0), GetBuffer()->GetChannel(0), bufferSize);
Add(target->GetBuffer()->GetChannel(0), mOutBuffer, bufferSize);
}
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(0), bufferSize, 0);
GetBuffer()->Reset();
}
void MultibandCompressor::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mDryWetSlider->Draw();
mFMinSlider->Draw();
mFMaxSlider->Draw();
mNumBandsSlider->Draw();
mRingTimeSlider->Draw();
mMaxBandSlider->Draw();
ofPushStyle();
ofFill();
ofSetColor(0, 255, 0);
const float width = 25;
for (int i = 0; i < mNumBands; ++i)
{
ofRect(i * (width + 3), -mPeaks[i].GetPeak() * 200, width, mPeaks[i].GetPeak() * 200);
}
ofPopStyle();
}
void MultibandCompressor::CalcFilters()
{
for (int i = 0; i < mNumBands; ++i)
{
float a = float(i) / mNumBands;
float f = mFreqMin * powf(mFreqMax / mFreqMin, a);
mFilters[i].SetCrossoverFreq(f);
}
}
void MultibandCompressor::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mNumBandsSlider)
{
CalcFilters();
}
}
void MultibandCompressor::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mFMinSlider || slider == mFMaxSlider)
{
CalcFilters();
}
if (slider == mRingTimeSlider)
{
for (int i = 0; i < COMPRESSOR_MAX_BANDS; ++i)
mPeaks[i].SetDecayTime(mRingTime);
}
if (slider == mMaxBandSlider)
{
for (int i = 0; i < COMPRESSOR_MAX_BANDS; ++i)
mPeaks[i].SetLimit(mMaxBand);
}
}
void MultibandCompressor::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void MultibandCompressor::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/MultibandCompressor.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,514 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// StepSequencer.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/12/12.
//
//
#include "StepSequencer.h"
#include "SynthGlobals.h"
#include "DrumPlayer.h"
#include "ModularSynth.h"
#include "MidiController.h"
namespace
{
const int kMetaStepLoop = 8;
}
StepSequencer::StepSequencer()
: mFlusher(this)
{
mFlusher.SetInterval(mStepInterval);
mMetaStepMasks = new juce::uint32[META_STEP_MAX * NUM_STEPSEQ_ROWS];
for (int i = 0; i < META_STEP_MAX * NUM_STEPSEQ_ROWS; ++i)
mMetaStepMasks[i] = 0xff;
}
void StepSequencer::Init()
{
IDrawableModule::Init();
mTransportListenerInfo = TheTransport->AddListener(this, mStepInterval, OffsetInfo(0, true), true);
}
void StepSequencer::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mGrid = new UIGrid("uigrid", 40, 45, 250, 150, 16, NUM_STEPSEQ_ROWS, this);
mStrengthSlider = new FloatSlider(this, "vel", 87, 22, 70, 15, &mStrength, 0, 1, 2);
mRandomizeButton = new ClickButton(this, "randomize", 160, 22);
mRandomizationDensitySlider = new FloatSlider(this, "r den", mRandomizeButton, kAnchor_Right, 65, 15, &mRandomizationDensity, 0, 1, 2);
mRandomizationAmountSlider = new FloatSlider(this, "r amt", mRandomizationDensitySlider, kAnchor_Right, 65, 15, &mRandomizationAmount, 0, 1, 2);
mNumMeasuresSlider = new IntSlider(this, "measures", 5, 22, 80, 15, &mNumMeasures, 1, 4);
mClearButton = new ClickButton(this, "clear", 5, 4);
mGridYOffDropdown = new DropdownList(this, "yoff", 295, 4, &mGridYOff);
mAdjustOffsetsCheckbox = new Checkbox(this, "offsets", 175, 4, &mAdjustOffsets);
mRepeatRateDropdown = new DropdownList(this, "repeat", 155, 22, (int*)(&mRepeatRate));
mStepIntervalDropdown = new DropdownList(this, "step", 133, 4, (int*)(&mStepInterval));
mCurrentColumnSlider = new IntSlider(this, "column", HIDDEN_UICONTROL, HIDDEN_UICONTROL, 100, 15, &mCurrentColumn, 0, 15);
mShiftLeftButton = new ClickButton(this, "<", 80, 4);
mShiftRightButton = new ClickButton(this, ">", 100, 4);
mGridControlTarget = new GridControlTarget(this, "grid", 240, 4);
mVelocityGridController = new GridControlTarget(this, "velocity", 240, 16);
mMetaStepGridController = new GridControlTarget(this, "metastep", 240, 28);
mGrid->SetMajorColSize(4);
mGrid->SetFlip(true);
mGridYOffDropdown->AddLabel("0", 0);
mGridYOffDropdown->AddLabel("1", 1);
mGridYOffDropdown->AddLabel("2", 2);
mGridYOffDropdown->AddLabel("3", 3);
mVelocityGridController->SetShowing(false);
mMetaStepGridController->SetShowing(false);
for (int i = 0; i < NUM_STEPSEQ_ROWS; ++i)
{
mRows[i] = new StepSequencerRow(this, mGrid, i);
mRows[i]->CreateUIControls();
mOffsets[i] = 0;
mOffsetSlider[i] = new FloatSlider(this, ("offset" + ofToString(i)).c_str(), 230, 185 - i * 9.4f, 90, 9, &mOffsets[i], -1, 1);
mRandomizeRowButton[i] = new ClickButton(this, ("random" + ofToString(i)).c_str(), mGridYOffDropdown->GetRect().getMaxX() + 4 + i * 60, 3);
mNoteRepeats[i] = new NoteRepeat(this, i);
}
mRepeatRateDropdown->AddLabel("no repeat", kInterval_None);
mRepeatRateDropdown->AddLabel("4n", kInterval_4n);
mRepeatRateDropdown->AddLabel("4nt", kInterval_4nt);
mRepeatRateDropdown->AddLabel("8n", kInterval_8n);
mRepeatRateDropdown->AddLabel("8nt", kInterval_8nt);
mRepeatRateDropdown->AddLabel("16n", kInterval_16n);
mRepeatRateDropdown->AddLabel("16nt", kInterval_16nt);
mRepeatRateDropdown->AddLabel("32n", kInterval_32n);
mRepeatRateDropdown->AddLabel("32nt", kInterval_32nt);
mRepeatRateDropdown->AddLabel("64n", kInterval_64n);
mStepIntervalDropdown->AddLabel("4n", kInterval_4n);
mStepIntervalDropdown->AddLabel("4nt", kInterval_4nt);
mStepIntervalDropdown->AddLabel("8n", kInterval_8n);
mStepIntervalDropdown->AddLabel("8nt", kInterval_8nt);
mStepIntervalDropdown->AddLabel("16n", kInterval_16n);
mStepIntervalDropdown->AddLabel("16nt", kInterval_16nt);
mStepIntervalDropdown->AddLabel("32n", kInterval_32n);
mStepIntervalDropdown->AddLabel("32nt", kInterval_32nt);
mStepIntervalDropdown->AddLabel("64n", kInterval_64n);
}
StepSequencer::~StepSequencer()
{
TheTransport->RemoveListener(this);
for (int i = 0; i < NUM_STEPSEQ_ROWS; ++i)
{
delete mRows[i];
delete mNoteRepeats[i];
}
delete[] mMetaStepMasks;
}
void StepSequencer::Poll()
{
IDrawableModule::Poll();
ComputeSliders(0);
if (HasGridController())
{
int numChunks = GetNumControllerChunks();
if (numChunks != mGridYOffDropdown->GetNumValues())
{
mGridYOffDropdown->Clear();
for (int i = 0; i < numChunks; ++i)
mGridYOffDropdown->AddLabel(ofToString(i).c_str(), i);
}
UpdateLights();
}
}
namespace
{
const float kMidwayVelocity = .75f;
}
void StepSequencer::UpdateLights(bool force /*=false*/)
{
if (!HasGridController() || mGridControlTarget->GetGridController() == nullptr)
return;
auto* gridController = mGridControlTarget->GetGridController();
for (int x = 0; x < GetGridControllerCols(); ++x)
{
for (int y = 0; y < GetGridControllerRows(); ++y)
{
if (gridController->IsMultisliderGrid())
{
Vec2i gridPos = ControllerToGrid(Vec2i(x, y));
gridController->SetLightDirect(x, y, (int)(mGrid->GetVal(gridPos.x, gridPos.y) * 127), force);
}
else
{
GridColor color = GetGridColor(x, y);
gridController->SetLight(x, y, color, force);
}
}
}
}
GridColor StepSequencer::GetGridColor(int x, int y)
{
Vec2i gridPos = ControllerToGrid(Vec2i(x, y));
bool cellOn = mGrid->GetVal(gridPos.x, gridPos.y) > 0;
bool cellBright = mGrid->GetVal(gridPos.x, gridPos.y) > kMidwayVelocity;
bool colOn = (mGrid->GetHighlightCol(gTime) == gridPos.x) && mEnabled;
GridColor color;
if (colOn)
{
if (cellBright)
color = kGridColor3Bright;
else if (cellOn)
color = kGridColor3Dim;
else
color = kGridColor2Dim;
}
else
{
if (cellBright)
color = kGridColor1Bright;
else if (cellOn)
color = kGridColor1Dim;
else
color = kGridColorOff;
}
return color;
}
void StepSequencer::UpdateVelocityLights()
{
if (mVelocityGridController->GetGridController() == nullptr)
return;
float stepVelocity = 0;
if (mHeldButtons.size() > 0)
stepVelocity = mGrid->GetVal(mHeldButtons.begin()->mCol, mHeldButtons.begin()->mRow);
for (int x = 0; x < mVelocityGridController->GetGridController()->NumCols(); ++x)
{
for (int y = 0; y < mVelocityGridController->GetGridController()->NumRows(); ++y)
{
GridColor color;
if (stepVelocity >= (8 - y) / 8.0f)
color = kGridColor2Bright;
else
color = kGridColorOff;
mVelocityGridController->GetGridController()->SetLight(x, y, color);
}
}
}
void StepSequencer::UpdateMetaLights()
{
if (mMetaStepGridController->GetGridController() == nullptr)
return;
bool hasHeldButtons = mHeldButtons.size() > 0;
juce::uint32 metaStepMask = 0;
if (hasHeldButtons)
metaStepMask = mMetaStepMasks[GetMetaStepMaskIndex(mHeldButtons.begin()->mCol, mHeldButtons.begin()->mRow)];
for (int x = 0; x < mMetaStepGridController->GetGridController()->NumCols(); ++x)
{
for (int y = 0; y < mMetaStepGridController->GetGridController()->NumRows(); ++y)
{
GridColor color;
if (hasHeldButtons && (metaStepMask & (1 << x)))
color = kGridColor1Bright;
else if (!hasHeldButtons && x == GetMetaStep(gTime))
color = kGridColor3Bright;
else
color = kGridColorOff;
mMetaStepGridController->GetGridController()->SetLight(x, y, color);
}
}
}
void StepSequencer::OnControllerPageSelected()
{
UpdateLights(true);
}
void StepSequencer::OnGridButton(int x, int y, float velocity, IGridController* grid)
{
if (mPush2Connected || grid == mGridControlTarget->GetGridController())
{
bool press = velocity > 0;
if (x >= 0 && y >= 0)
{
Vec2i gridPos = ControllerToGrid(Vec2i(x, y));
if (grid != nullptr && grid->IsMultisliderGrid())
{
mGrid->SetVal(gridPos.x, gridPos.y, velocity);
}
else
{
if (press)
{
mHeldButtons.push_back(HeldButton(gridPos.x, gridPos.y));
float val = mGrid->GetVal(gridPos.x, gridPos.y);
if (val != mStrength)
mGrid->SetVal(gridPos.x, gridPos.y, mStrength);
else
mGrid->SetVal(gridPos.x, gridPos.y, 0);
}
else
{
for (auto iter = mHeldButtons.begin(); iter != mHeldButtons.end(); ++iter)
{
if (iter->mCol == gridPos.x && iter->mRow == gridPos.y)
{
mHeldButtons.erase(iter);
break;
}
}
}
}
UpdateLights();
UpdateVelocityLights();
UpdateMetaLights();
}
}
else if (grid == mVelocityGridController->GetGridController())
{
if (velocity > 0)
{
for (auto iter : mHeldButtons)
{
float strength = (8 - y) / 8.0f;
mGrid->SetVal(iter.mCol, iter.mRow, strength);
}
UpdateVelocityLights();
}
}
else if (grid == mMetaStepGridController->GetGridController())
{
if (velocity > 0)
{
for (auto iter : mHeldButtons)
{
mMetaStepMasks[GetMetaStepMaskIndex(iter.mCol, iter.mRow)] ^= 1 << x;
}
UpdateMetaLights();
}
}
}
int StepSequencer::GetStep(int step, int pitch)
{
return ofClamp(mGrid->GetVal(step, pitch), 0, 1) * 127;
}
void StepSequencer::SetStep(int step, int pitch, int velocity)
{
mGrid->SetVal(step, pitch, ofClamp(velocity / 127.0f, 0, 1));
UpdateLights();
}
int StepSequencer::GetGridControllerRows()
{
if (mGridControlTarget->GetGridController())
return mGridControlTarget->GetGridController()->NumRows();
if (mPush2Connected)
return 8;
return 8;
}
int StepSequencer::GetGridControllerCols()
{
if (mGridControlTarget->GetGridController())
return mGridControlTarget->GetGridController()->NumCols();
if (mPush2Connected)
return 8;
return 8;
}
Vec2i StepSequencer::ControllerToGrid(const Vec2i& controller)
{
if (!HasGridController())
return Vec2i(0, 0);
int cols = GetGridControllerCols();
int numChunks = GetNumControllerChunks();
int chunkSize = mGrid->GetRows() / numChunks;
int col = controller.x + (controller.y / chunkSize) * cols;
int row = (chunkSize - 1) - (controller.y % chunkSize) + mGridYOff * chunkSize;
return Vec2i(col, row);
}
int StepSequencer::GetNumControllerChunks()
{
if (!HasGridController())
return 1;
int rows = GetGridControllerRows();
int cols = GetGridControllerCols();
int numBreaks = int((mGrid->GetCols() / MAX(1.0f, cols)) + .5f);
int numChunks = int(mGrid->GetRows() / MAX(1.0f, (rows / MAX(1, numBreaks))) + .5f);
return numChunks;
}
void StepSequencer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mGridYOffDropdown->SetShowing(HasGridController());
mAdjustOffsetsCheckbox->SetShowing(!mHasExternalPulseSource);
mCurrentColumnSlider->SetExtents(0, GetNumSteps(mStepInterval, mNumMeasures));
mRepeatRateDropdown->SetShowing(mNoteInputMode == NoteInputMode::RepeatHeld);
mGrid->Draw();
mStrengthSlider->Draw();
mNumMeasuresSlider->Draw();
mClearButton->Draw();
mAdjustOffsetsCheckbox->Draw();
mRepeatRateDropdown->Draw();
mGridYOffDropdown->Draw();
mStepIntervalDropdown->Draw();
mShiftLeftButton->Draw();
mShiftRightButton->Draw();
mGridControlTarget->Draw();
mVelocityGridController->Draw();
mMetaStepGridController->Draw();
mRandomizationAmountSlider->Draw();
mRandomizationDensitySlider->Draw();
mRandomizeButton->Draw();
float gridX, gridY;
mGrid->GetPosition(gridX, gridY, true);
for (int i = 0; i < NUM_STEPSEQ_ROWS; ++i)
{
if (i < mNumRows)
{
float y = gridY + mGrid->GetHeight() - (i + 1) * (mGrid->GetHeight() / float(mNumRows));
if (mAdjustOffsets)
{
mOffsetSlider[i]->SetShowing(true);
mOffsetSlider[i]->SetPosition(gridX + mGrid->GetWidth() + 5, y);
mOffsetSlider[i]->Draw();
}
else
{
mOffsetSlider[i]->SetShowing(false);
}
mRandomizeRowButton[i]->Draw();
mRows[i]->Draw(gridX, y);
}
else
{
mOffsetSlider[i]->SetShowing(false);
}
}
if (HasGridController())
{
ofPushStyle();
ofNoFill();
ofSetLineWidth(4);
ofSetColor(255, 0, 0, 50);
float squareh = float(mGrid->GetHeight()) / mNumRows;
float squarew = float(mGrid->GetWidth()) / GetNumSteps(mStepInterval, mNumMeasures);
int chunkSize = mGrid->GetRows() / GetNumControllerChunks();
float width = MIN(mGrid->GetWidth(), squarew * GetGridControllerCols() * GetNumControllerChunks());
ofRect(gridX, gridY + squareh * (mNumRows - chunkSize) - squareh * mGridYOff * chunkSize, width, squareh * chunkSize);
ofPopStyle();
}
ofPushStyle();
ofFill();
for (int col = 0; col < mGrid->GetCols(); ++col)
{
for (int row = 0; row < mGrid->GetRows(); ++row)
{
auto mask = mMetaStepMasks[GetMetaStepMaskIndex(col, row)];
ofVec2f pos = mGrid->GetCellPosition(col, row) + mGrid->GetPosition(true);
float cellWidth = (float)mGrid->GetWidth() / mGrid->GetCols();
float cellHeight = (float)mGrid->GetHeight() / mGrid->GetRows();
for (int i = 0; i < kMetaStepLoop; ++i)
{
if (mask != 0xff)
{
float x = pos.x + ((i % 4) + 1.5f) * (cellWidth / 6);
float y = pos.y + ((i / 4 + 1.5f) * (cellHeight / 4)) - cellHeight;
float radius = cellHeight * .08f;
if (i == GetMetaStep(gTime))
{
ofSetColor(255, 220, 0);
ofCircle(x, y, radius * 1.5f);
}
if ((mask & (1 << i)) == 0)
ofSetColor(0, 0, 0);
else
ofSetColor(255, 0, 0);
ofCircle(x, y, radius);
}
}
}
}
ofPopStyle();
}
void StepSequencer::DrawRowLabel(const char* label, int row, int x, int y)
{
DrawTextRightJustify(label, x, y + row * 9.4f);
}
void StepSequencer::GetModuleDimensions(float& width, float& height)
{
width = mGrid->GetWidth() + 45;
if (mAdjustOffsets)
width += 100;
height = mGrid->GetHeight() + 50;
}
void StepSequencer::Resize(float w, float h)
{
float extraW = 45;
float extraH = 50;
if (mAdjustOffsets)
extraW += 100;
mGrid->SetDimensions(MAX(w - extraW, 185), MAX(h - extraH, 46 + 13 * mNumRows));
}
void StepSequencer::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (mGrid->TestClick(x, y, right))
UpdateLights();
}
void StepSequencer::MouseReleased()
{
IDrawableModule::MouseReleased();
mGrid->MouseReleased();
UpdateLights();
}
bool StepSequencer::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
if (mGrid->NotifyMouseMoved(x, y))
UpdateLights();
return false;
}
bool StepSequencer::OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue)
{
mPush2Connected = true;
if (type == kMidiMessage_Note)
{
if (controlIndex >= 36 && controlIndex <= 99)
{
int gridIndex = controlIndex - 36;
int gridX = gridIndex % 8;
int gridY = 7 - gridIndex / 8;
OnGridButton(gridX, gridY, midiValue / 127, mGridControlTarget->GetGridController());
return true;
}
}
if (type == kMidiMessage_PitchBend)
{
float val = midiValue / MidiDevice::kPitchBendMax;
mGridYOffDropdown->SetFromMidiCC(val, gTime, true);
return true;
}
return false;
}
void StepSequencer::UpdatePush2Leds(Push2Control* push2)
{
mPush2Connected = true;
int numYChunks = GetNumControllerChunks();
for (int x = 0; x < 8; ++x)
{
for (int y = 0; y < 8; ++y)
{
int rowsPerChunk = std::max(1, (8 / numYChunks));
int chunkIndex = y / rowsPerChunk;
GridColor color = GetGridColor(x, y);
int pushColor = 0;
switch (color)
{
case kGridColorOff: //off
pushColor = (chunkIndex % 2 == 0) ? 0 : 124;
break;
case kGridColor1Dim: //
pushColor = 86;
break;
case kGridColor1Bright: //pressed
pushColor = 32;
break;
case kGridColor2Dim:
pushColor = 114;
break;
case kGridColor2Bright: //root
pushColor = 25;
break;
case kGridColor3Dim: //not in pentatonic
pushColor = 116;
break;
case kGridColor3Bright: //in pentatonic
pushColor = 115;
break;
}
push2->SetLed(kMidiMessage_Note, x + (7 - y) * 8 + 36, pushColor);
}
}
std::string touchStripLights = { 0x00, 0x21, 0x1D, 0x01, 0x01, 0x19 };
for (int i = 0; i < 16; ++i)
{
int ledLow = (int(((i * 2) / 32.0f) * numYChunks) == mGridYOff) ? 7 : 0;
int ledHigh = (int(((i * 2 + 1) / 32.0f) * numYChunks) == mGridYOff) ? 7 : 0;
unsigned char c = ledLow + (ledHigh << 3);
touchStripLights += c;
}
push2->GetDevice()->SendSysEx(touchStripLights);
}
int StepSequencer::GetNumSteps(NoteInterval interval, int numMeasures) const
{
return TheTransport->CountInStandardMeasure(interval) * TheTransport->GetTimeSigTop() / TheTransport->GetTimeSigBottom() * numMeasures;
}
int StepSequencer::GetStepNum(double time)
{
int measure = TheTransport->GetMeasure(time) % mNumMeasures;
int stepsPerMeasure = GetNumSteps(mStepInterval, mNumMeasures);
return TheTransport->GetQuantized(time, mTransportListenerInfo) % stepsPerMeasure + measure * stepsPerMeasure / mNumMeasures;
}
void StepSequencer::OnTimeEvent(double time)
{
if (!mHasExternalPulseSource)
Step(time, 1, 0);
}
void StepSequencer::Step(double time, float velocity, int pulseFlags)
{
if (!mIsSetUp)
return;
mGrid->SetGrid(GetNumSteps(mStepInterval, mNumMeasures), mNumRows);
if (!mEnabled)
{
UpdateLights();
return;
}
int direction = 1;
if (pulseFlags & kPulseFlag_Backward)
direction = -1;
if (pulseFlags & kPulseFlag_Repeat)
direction = 0;
mCurrentColumn = (mCurrentColumn + direction + GetNumSteps(mStepInterval, mNumMeasures)) % GetNumSteps(mStepInterval, mNumMeasures);
if (pulseFlags & kPulseFlag_Reset)
mCurrentColumn = 0;
else if (pulseFlags & kPulseFlag_Random)
mCurrentColumn = gRandom() % GetNumSteps(mStepInterval, mNumMeasures);
if (!mHasExternalPulseSource || (pulseFlags & kPulseFlag_SyncToTransport))
mCurrentColumn = GetStepNum(time);
if (pulseFlags & kPulseFlag_Align)
{
int stepsPerMeasure = TheTransport->GetStepsPerMeasure(this);
int numMeasures = ceil(float(GetNumSteps(mStepInterval, mNumMeasures)) / stepsPerMeasure);
int measure = TheTransport->GetMeasure(time) % numMeasures;
int step = ((TheTransport->GetQuantized(time, mTransportListenerInfo) % stepsPerMeasure) + measure * stepsPerMeasure) % GetNumSteps(mStepInterval, mNumMeasures);
mCurrentColumn = step;
}
mGrid->SetHighlightCol(time, mCurrentColumn);
UpdateLights();
UpdateMetaLights();
if (mHasExternalPulseSource)
{
for (auto& row : mRows)
row->PlayStep(time, mCurrentColumn);
}
}
void StepSequencer::PlayStepNote(double time, int note, float val)
{
mNoteOutput.PlayNote(time, note, val * 127);
}
void StepSequencer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mNoteInputMode == NoteInputMode::PlayStepIndex)
{
if (velocity > 0)
{
if (!mHasExternalPulseSource)
{
mHasExternalPulseSource = true;
mAdjustOffsets = false;
for (int i = 0; i < NUM_STEPSEQ_ROWS; ++i)
mOffsets[i] = 0;
}
mCurrentColumn = pitch % GetNumSteps(mStepInterval, mNumMeasures);
Step(time, velocity / 127.0f, kPulseFlag_Repeat);
}
}
else
{
if (mRepeatRate == kInterval_None)
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
else
mPadPressures[pitch] = velocity;
}
}
void StepSequencer::OnPulse(double time, float velocity, int flags)
{
if (!mHasExternalPulseSource)
{
mHasExternalPulseSource = true;
mAdjustOffsets = false;
for (int i = 0; i < NUM_STEPSEQ_ROWS; ++i)
mOffsets[i] = 0;
}
Step(time, velocity, flags);
}
void StepSequencer::SendPressure(int pitch, int pressure)
{
mPadPressures[pitch] = pressure;
}
void StepSequencer::Exit()
{
IDrawableModule::Exit();
if (mGridControlTarget->GetGridController() != nullptr && !mGridControlTarget->GetGridController()->IsConnected())
mGridControlTarget->GetGridController()->ResetLights();
}
int StepSequencer::GetMetaStep(double time)
{
return TheTransport->GetMeasure(time) % kMetaStepLoop;
}
bool StepSequencer::IsMetaStepActive(double time, int col, int row)
{
return mMetaStepMasks[GetMetaStepMaskIndex(col, row)] & (1 << GetMetaStep(time));
}
bool StepSequencer::HasGridController()
{
if (mPush2Connected)
return true;
return mGridControlTarget->GetGridController() != nullptr && mGridControlTarget->GetGridController()->IsConnected();
}
void StepSequencer::RandomizeRow(int row)
{
for (int col = 0; col < mGrid->GetCols(); ++col)
{
if (ofRandom(1) < mRandomizationAmount)
{
float value = 0;
if (ofRandom(1) < mRandomizationDensity)
value = ofRandom(1);
mGrid->SetVal(col, row, value);
}
}
}
void StepSequencer::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mNoteOutput.Flush(time);
}
void StepSequencer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mStrengthSlider)
{
mGrid->SetStrength(mStrength);
for (auto iter : mHeldButtons)
mGrid->SetVal(iter.mCol, iter.mRow, mStrength);
if (mHeldButtons.size() > 0)
UpdateLights();
}
for (int i = 0; i < NUM_STEPSEQ_ROWS; ++i)
{
if (slider == mOffsetSlider[i])
{
float offset = -mOffsets[i] / 32; //up to 1/32nd late or early
mRows[i]->SetOffset(offset);
mNoteRepeats[i]->SetOffset(offset);
mGrid->SetDrawOffset(i, mOffsets[i] / 2);
}
}
}
void StepSequencer::RadioButtonUpdated(RadioButton* radio, int oldVal, double time)
{
}
void StepSequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mNumMeasuresSlider)
{
mGrid->SetGrid(GetNumSteps(mStepInterval, mNumMeasures), mNumRows);
if (mNumMeasures > oldVal)
{
int newChunkCount = ceil(float(mNumMeasures) / oldVal);
int stepsPerChunk = GetNumSteps(mStepInterval, oldVal);
for (int chunk = 1; chunk < newChunkCount; ++chunk)
{
for (int col = 0; col < stepsPerChunk && col + stepsPerChunk * chunk < mGrid->GetCols(); ++col)
{
for (int row = 0; row < mGrid->GetRows(); ++row)
{
mGrid->SetVal(col + stepsPerChunk * chunk, row, mGrid->GetVal(col, row), false);
}
}
}
}
}
}
void StepSequencer::ButtonClicked(ClickButton* button, double time)
{
if (button == mShiftLeftButton || button == mShiftRightButton)
{
int shift = (button == mShiftRightButton) ? 1 : -1;
for (int row = 0; row < mGrid->GetRows(); ++row)
{
int start = (shift == 1) ? mGrid->GetCols() - 1 : 0;
int end = (shift == 1) ? 0 : mGrid->GetCols() - 1;
float startVal = mGrid->GetVal(start, row);
for (int col = start; col != end; col -= shift)
mGrid->SetVal(col, row, mGrid->GetVal(col - shift, row));
mGrid->SetVal(end, row, startVal);
}
}
if (button == mRandomizeButton)
{
for (int row = 0; row < mGrid->GetRows(); ++row)
RandomizeRow(row);
}
for (int row = 0; row < mRandomizeRowButton.size(); ++row)
{
if (button == mRandomizeRowButton[row])
RandomizeRow(row);
}
if (button == mClearButton)
mGrid->Clear();
}
void StepSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mRepeatRateDropdown)
{
for (int i = 0; i < NUM_STEPSEQ_ROWS; ++i)
mNoteRepeats[i]->SetInterval(mRepeatRate);
}
if (list == mStepIntervalDropdown)
{
UIGrid* oldGrid = new UIGrid(*mGrid);
int oldNumSteps = GetNumSteps((NoteInterval)oldVal, mNumMeasures);
int newNumSteps = GetNumSteps(mStepInterval, mNumMeasures);
for (int i = 0; i < mGrid->GetRows(); ++i)
{
for (int j = 0; j < newNumSteps; ++j)
{
float div = j * ((float)oldNumSteps / newNumSteps);
int col = (int)div;
if (div == col)
mGrid->SetVal(j, i, oldGrid->GetVal(col, i));
else
mGrid->SetVal(j, i, 0);
}
}
oldGrid->Delete();
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
transportListenerInfo->mInterval = mStepInterval;
mFlusher.SetInterval(mStepInterval);
mGrid->SetMajorColSize(TheTransport->CountInStandardMeasure(mStepInterval) / 4);
for (int i = 0; i < NUM_STEPSEQ_ROWS; ++i)
mRows[i]->UpdateTimeListener();
}
}
void StepSequencer::KeyPressed(int key, bool isRepeat)
{
IDrawableModule::KeyPressed(key, isRepeat);
ofVec2f mousePos(TheSynth->GetMouseX(GetOwningContainer()), TheSynth->GetMouseY(GetOwningContainer()));
if (key >= '1' && key <= '8' && mGrid->GetRect().contains(mousePos.x, mousePos.y))
{
int metaStep = key - '1';
auto cell = mGrid->GetGridCellAt(mousePos.x - mGrid->GetPosition().x, mousePos.y - mGrid->GetPosition().y);
mMetaStepMasks[GetMetaStepMaskIndex(cell.mCol, cell.mRow)] ^= (1 << metaStep);
}
}
void StepSequencer::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void StepSequencer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadInt("gridrows", moduleInfo, 8, 1, NUM_STEPSEQ_ROWS);
mModuleSaveData.LoadInt("gridmeasures", moduleInfo, 1, 1, 16);
mModuleSaveData.LoadBool("multislider_mode", moduleInfo, true);
EnumMap noteInputModeMap;
noteInputModeMap["play step index"] = (int)NoteInputMode::PlayStepIndex;
noteInputModeMap["repeat held"] = (int)NoteInputMode::RepeatHeld;
mModuleSaveData.LoadEnum<NoteInputMode>("note_input_mode", moduleInfo, (int)NoteInputMode::PlayStepIndex, nullptr, ¬eInputModeMap);
SetUpFromSaveData();
}
void StepSequencer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mNumRows = mModuleSaveData.GetInt("gridrows");
mGrid->SetGrid(GetNumSteps(mStepInterval, mNumMeasures), mNumRows);
bool multisliderMode = mModuleSaveData.GetBool("multislider_mode");
mGrid->SetGridMode(multisliderMode ? UIGrid::kMultisliderBipolar : UIGrid::kNormal);
mGrid->SetRestrictDragToRow(multisliderMode);
mGrid->SetRequireShiftForMultislider(true);
mNoteInputMode = mModuleSaveData.GetEnum<NoteInputMode>("note_input_mode");
if (mNoteInputMode == NoteInputMode::RepeatHeld)
mHasExternalPulseSource = false;
mIsSetUp = true;
}
void StepSequencer::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mGrid->SaveState(out);
int numMetaStepMasks = META_STEP_MAX * NUM_STEPSEQ_ROWS;
out << numMetaStepMasks;
for (int i = 0; i < numMetaStepMasks; ++i)
out << mMetaStepMasks[i];
out << mHasExternalPulseSource;
out << mGrid->GetWidth();
out << mGrid->GetHeight();
}
void StepSequencer::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
mGrid->LoadState(in);
if (rev >= 1)
{
int numMetaStepMasks;
in >> numMetaStepMasks;
for (int i = 0; i < numMetaStepMasks; ++i)
in >> mMetaStepMasks[i];
}
if (rev >= 2)
in >> mHasExternalPulseSource;
if (rev >= 3)
{
float gridWidth, gridHeight;
in >> gridWidth;
in >> gridHeight;
mGrid->SetDimensions(gridWidth, gridHeight);
}
}
StepSequencerRow::StepSequencerRow(StepSequencer* seq, UIGrid* grid, int row)
: mSeq(seq)
, mGrid(grid)
, mRow(row)
{
mRowPitch = row;
TheTransport->AddListener(this, mSeq->GetStepInterval(), OffsetInfo(0, true), true);
}
StepSequencerRow::~StepSequencerRow()
{
TheTransport->RemoveListener(this);
}
void StepSequencerRow::CreateUIControls()
{
mRowPitchEntry = new TextEntry(mSeq, ("rowpitch" + ofToString(mRow)).c_str(), -1, -1, 3, &mRowPitch, 0, 127);
}
void StepSequencerRow::OnTimeEvent(double time)
{
if (mSeq->IsEnabled() == false || mSeq->HasExternalPulseSource())
return;
float offsetMs = mOffset * TheTransport->MsPerBar();
int step = mSeq->GetStepNum(time + offsetMs);
PlayStep(time, step);
}
void StepSequencerRow::PlayStep(double time, int step)
{
float val = mGrid->GetVal(step, mRow);
if (val > 0 && mSeq->IsMetaStepActive(time, step, mRow))
{
mSeq->PlayStepNote(time, mRowPitch, val * val);
mPlayedSteps[mPlayedStepsRoundRobin].step = step;
mPlayedSteps[mPlayedStepsRoundRobin].time = time;
mPlayedStepsRoundRobin = (mPlayedStepsRoundRobin + 1) % mPlayedSteps.size();
}
}
void StepSequencerRow::SetOffset(float offset)
{
mOffset = offset;
UpdateTimeListener();
}
void StepSequencerRow::UpdateTimeListener()
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
{
transportListenerInfo->mInterval = mSeq->GetStepInterval();
transportListenerInfo->mOffsetInfo = OffsetInfo(mOffset, false);
}
}
void StepSequencerRow::Draw(float x, float y)
{
float xCellSize = float(mGrid->GetWidth()) / mGrid->GetCols();
float yCellSize = float(mGrid->GetHeight()) / mGrid->GetRows();
bool showTextEntry = yCellSize > 14;
mRowPitchEntry->SetShowing(showTextEntry);
mRowPitchEntry->SetPosition(x - 32, y);
mRowPitchEntry->Draw();
if (!showTextEntry)
DrawTextRightJustify(ofToString(mRowPitch), x - 7, y + 10);
const float kPlayHighlightDurationMs = 250;
for (size_t i = 0; i < mPlayedSteps.size(); ++i)
{
if (mPlayedSteps[i].time != -1)
{
if (gTime - mPlayedSteps[i].time < kPlayHighlightDurationMs)
{
if (gTime - mPlayedSteps[i].time > 0)
{
float fade = (1 - (gTime - mPlayedSteps[i].time) / kPlayHighlightDurationMs);
ofPushStyle();
ofSetLineWidth(3 * fade);
ofVec2f pos = mGrid->GetCellPosition(mPlayedSteps[i].step, mRow) + mGrid->GetPosition(true);
ofSetColor(ofColor::white, fade * 255);
ofRect(pos.x, pos.y, xCellSize, yCellSize);
ofPopStyle();
}
}
else
{
mPlayedSteps[i].time = -1;
}
}
}
}
NoteRepeat::NoteRepeat(StepSequencer* seq, int row)
: mSeq(seq)
, mRow(row)
, mOffset(0)
, mInterval(kInterval_None)
{
TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), true);
}
NoteRepeat::~NoteRepeat()
{
TheTransport->RemoveListener(this);
}
void NoteRepeat::OnTimeEvent(double time)
{
int pressure = mSeq->GetPadPressure(mRow);
if (pressure > 10)
mSeq->PlayStepNote(time, mSeq->GetRowPitch(mRow), pressure / 85.0f);
}
void NoteRepeat::SetInterval(NoteInterval interval)
{
mInterval = interval;
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
{
transportListenerInfo->mInterval = mInterval;
transportListenerInfo->mOffsetInfo = OffsetInfo(mOffset, false);
}
}
void NoteRepeat::SetOffset(float offset)
{
mOffset = offset;
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
{
transportListenerInfo->mInterval = mInterval;
transportListenerInfo->mOffsetInfo = OffsetInfo(mOffset, false);
}
}
StepSequencerNoteFlusher::StepSequencerNoteFlusher(StepSequencer* seq)
: mSeq(seq)
{
TheTransport->AddListener(this, mSeq->GetStepInterval(), OffsetInfo(.01f, false), true);
}
StepSequencerNoteFlusher::~StepSequencerNoteFlusher()
{
TheTransport->RemoveListener(this);
}
void StepSequencerNoteFlusher::SetInterval(NoteInterval interval)
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
{
transportListenerInfo->mInterval = interval;
transportListenerInfo->mOffsetInfo = OffsetInfo(.01f, false);
}
}
void StepSequencerNoteFlusher::OnTimeEvent(double time)
{
mSeq->Flush(time);
}
``` | /content/code_sandbox/Source/StepSequencer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 9,890 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteCounter.cpp
Created: 24 Apr 2021 3:47:48pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteCounter.h"
#include "SynthGlobals.h"
#include "DrumPlayer.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
NoteCounter::NoteCounter()
{
}
void NoteCounter::Init()
{
IDrawableModule::Init();
mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), true);
Reseed();
}
void NoteCounter::CreateUIControls()
{
IDrawableModule::CreateUIControls();
float desiredWidth = 116;
UIBLOCK(3, 3, desiredWidth - 6);
DROPDOWN(mIntervalSelector, "interval", ((int*)(&mInterval)), 50);
UIBLOCK_SHIFTRIGHT();
CHECKBOX(mSyncCheckbox, "sync", &mSync);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_PUSHSLIDERWIDTH(75);
INTSLIDER(mCustomDivisorSlider, "div", &mCustomDivisor, 1, 32);
UIBLOCK_POPSLIDERWIDTH();
UIBLOCK_NEWLINE();
INTSLIDER(mStartSlider, "start", &mStart, 0, 32);
INTSLIDER(mLengthSlider, "length", &mLength, 1, 32);
CHECKBOX(mRandomCheckbox, "random", &mRandom);
ENDUIBLOCK(mWidth, mHeight);
UIBLOCK(3, mHeight + 5, desiredWidth - 6);
INTSLIDER(mDeterministicLengthSlider, "beat length", &mDeterministicLength, 1, 16);
TEXTENTRY_NUM(mSeedEntry, "seed", 4, &mSeed, 0, 9999);
UIBLOCK_SHIFTRIGHT();
BUTTON(mPrevSeedButton, "<");
UIBLOCK_SHIFTRIGHT();
BUTTON(mReseedButton, "*");
UIBLOCK_SHIFTRIGHT();
BUTTON(mNextSeedButton, ">");
ENDUIBLOCK0();
mWidth = desiredWidth;
mSeedEntry->DrawLabel(true);
mPrevSeedButton->PositionTo(mSeedEntry, kAnchor_Right);
mReseedButton->PositionTo(mPrevSeedButton, kAnchor_Right);
mNextSeedButton->PositionTo(mReseedButton, kAnchor_Right);
mIntervalSelector->AddLabel("1n", kInterval_1n);
mIntervalSelector->AddLabel("2n", kInterval_2n);
mIntervalSelector->AddLabel("4n", kInterval_4n);
mIntervalSelector->AddLabel("4nt", kInterval_4nt);
mIntervalSelector->AddLabel("8n", kInterval_8n);
mIntervalSelector->AddLabel("8nt", kInterval_8nt);
mIntervalSelector->AddLabel("16n", kInterval_16n);
mIntervalSelector->AddLabel("16nt", kInterval_16nt);
mIntervalSelector->AddLabel("32n", kInterval_32n);
mIntervalSelector->AddLabel("64n", kInterval_64n);
mIntervalSelector->AddLabel("div", kInterval_CustomDivisor);
}
NoteCounter::~NoteCounter()
{
TheTransport->RemoveListener(this);
}
void NoteCounter::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mIntervalSelector->Draw();
mSyncCheckbox->Draw();
mStartSlider->Draw();
mLengthSlider->Draw();
mRandomCheckbox->Draw();
mCustomDivisorSlider->SetShowing(mInterval == kInterval_CustomDivisor);
mCustomDivisorSlider->Draw();
mDeterministicLengthSlider->SetShowing(mDeterministic && mRandom);
mDeterministicLengthSlider->Draw();
mSeedEntry->SetShowing(mDeterministic && mRandom);
mSeedEntry->Draw();
mPrevSeedButton->SetShowing(mDeterministic && mRandom);
mPrevSeedButton->Draw();
mReseedButton->SetShowing(mDeterministic && mRandom);
mReseedButton->Draw();
mNextSeedButton->SetShowing(mDeterministic && mRandom);
mNextSeedButton->Draw();
if (mDeterministic && mRandom)
{
ofRectangle lengthRect = mDeterministicLengthSlider->GetRect(true);
ofPushStyle();
ofSetColor(0, 255, 0);
ofFill();
float pos = fmod(TheTransport->GetMeasureTime(gTime) * TheTransport->GetTimeSigTop() / mDeterministicLength, 1);
const float kPipSize = 3;
float moduleWidth, moduleHeight;
GetModuleDimensions(moduleWidth, moduleHeight);
ofRect(ofMap(pos, 0, 1, 0, moduleWidth - kPipSize), lengthRect.y - 5, kPipSize, kPipSize);
ofPopStyle();
}
}
void NoteCounter::Step(double time, float velocity, int pulseFlags)
{
if (!mEnabled)
return;
bool sync = mSync || pulseFlags & kPulseFlag_SyncToTransport;
if (sync)
{
mStep = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo, mLength);
}
else
{
if (pulseFlags & kPulseFlag_Reset)
mStep = 0;
if (pulseFlags & kPulseFlag_Random)
mStep = GetRandom(time, 999) % mLength;
if (pulseFlags & kPulseFlag_Align)
{
int stepsPerMeasure = TheTransport->GetStepsPerMeasure(this);
int numMeasures = ceil(float(mLength) / stepsPerMeasure);
int measure = TheTransport->GetMeasure(time) % numMeasures;
int step = ((TheTransport->GetQuantized(time, mTransportListenerInfo) % stepsPerMeasure) + measure * stepsPerMeasure) % mLength;
mStep = step;
}
}
mNoteOutput.Flush(time);
if (mRandom)
PlayNoteOutput(time, GetRandom(time, 0) % mLength + mStart, 127, -1);
else
PlayNoteOutput(time, mStep + mStart, 127, -1);
if (!sync)
{
int direction = 1;
if (pulseFlags & kPulseFlag_Backward)
direction = -1;
if (pulseFlags & kPulseFlag_Repeat)
direction = 0;
mStep = (mStep + mLength + direction) % mLength;
}
}
std::uint64_t NoteCounter::GetRandom(double time, int seedOffset) const
{
std::uint64_t random;
if (mDeterministic && mRandom)
{
const int kStepResolution = 128;
uint64_t step = int(TheTransport->GetMeasureTime(time) * kStepResolution);
int randomIndex = step % ((mDeterministicLength * kStepResolution) / TheTransport->GetTimeSigTop());
random = abs(DeterministicRandom(mSeed + seedOffset, randomIndex));
}
else
{
random = gRandom();
}
return random;
}
void NoteCounter::OnTimeEvent(double time)
{
if (!mHasExternalPulseSource)
Step(time, 1, 0);
}
void NoteCounter::OnPulse(double time, float velocity, int flags)
{
mHasExternalPulseSource = true;
Step(time, velocity, flags);
}
void NoteCounter::Reseed()
{
mSeed = gRandom() % 10000;
}
void NoteCounter::ButtonClicked(ClickButton* button, double time)
{
if (button == mPrevSeedButton)
mSeed = (mSeed - 1 + 10000) % 10000;
if (button == mReseedButton)
Reseed();
if (button == mNextSeedButton)
mSeed = (mSeed + 1) % 10000;
}
void NoteCounter::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
mNoteOutput.Flush(time);
mStep = 0;
}
}
void NoteCounter::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mCustomDivisorSlider)
mTransportListenerInfo->mCustomDivisor = mCustomDivisor;
}
void NoteCounter::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mIntervalSelector)
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
transportListenerInfo->mInterval = mInterval;
}
}
void NoteCounter::GetModuleDimensions(float& width, float& height)
{
width = mWidth;
height = mHeight;
if (mDeterministic && mRandom)
height += 40;
if (mCustomDivisorSlider->IsShowing())
width += 60;
}
void NoteCounter::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadBool("deterministic_random", moduleInfo, false);
SetUpFromSaveData();
}
void NoteCounter::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mDeterministic = mModuleSaveData.GetBool("deterministic_random");
}
void NoteCounter::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mHasExternalPulseSource;
}
void NoteCounter::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (!ModuleContainer::DoesModuleHaveMoreSaveData(in))
return; //this was saved before we added versioning, bail out
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
if (rev == 1)
{
float dummy;
in >> dummy; //width
in >> dummy; //height
}
in >> mHasExternalPulseSource;
}
``` | /content/code_sandbox/Source/NoteCounter.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,362 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
PressureToCV.cpp
Created: 28 Nov 2017 9:44:32pm
Author: Ryan Challinor
==============================================================================
*/
#include "PressureToCV.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "ModulationChain.h"
PressureToCV::PressureToCV()
{
}
PressureToCV::~PressureToCV()
{
}
void PressureToCV::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
mMinSlider = new FloatSlider(this, "min", 3, 2, 100, 15, &mDummyMin, 0, 1);
mMaxSlider = new FloatSlider(this, "max", mMinSlider, kAnchor_Below, 100, 15, &mDummyMax, 0, 1);
}
void PressureToCV::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mMinSlider->Draw();
mMaxSlider->Draw();
}
void PressureToCV::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
}
void PressureToCV::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled && velocity > 0)
{
mPressure = modulation.pressure;
}
}
float PressureToCV::Value(int samplesIn)
{
float pressure = mPressure ? mPressure->GetValue(samplesIn) : ModulationParameters::kDefaultPressure;
return ofMap(pressure, 0, 1, GetMin(), GetMax(), K(clamped));
}
void PressureToCV::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void PressureToCV::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void PressureToCV::SetUpFromSaveData()
{
}
``` | /content/code_sandbox/Source/PressureToCV.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 568 |
```objective-c
#include <string>
namespace Bespoke
{
// These are generated at CMake time and are VersionInfo.cpp.in
extern const char* APP_NAME; // The application name. Taken from the top-level CMake project name.
extern const char* VERSION; // This will be the same string as Juce::Application::getApplicationVersion()
extern const char* PYTHON_VERSION; // The python version we compiled with
extern const char* CMAKE_INSTALL_PREFIX;
// These are generated at build time and are in VersionInfoBld.cpp.in
extern const char* GIT_BRANCH;
extern const char* GIT_HASH;
extern const char* BUILD_ARCH;
extern const char* BUILD_DATE;
extern const char* BUILD_TIME;
}
``` | /content/code_sandbox/Source/VersionInfo.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 157 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// NoteTransformer.cpp
// modularSynth
//
// Created by Ryan Challinor on 3/13/14.
//
//
#include "NoteTransformer.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
NoteTransformer::NoteTransformer()
{
for (int i = 0; i < 7; ++i)
{
mToneModSlider[i] = new IntSlider(this, ("tone " + ofToString(i)).c_str(), 17, 118 - i * 17, 100, 15, &mToneMod[i], -7, 7);
}
for (int i = 0; i < 127; ++i)
mLastNoteOnForPitch[i] = -1;
}
NoteTransformer::~NoteTransformer()
{
}
void NoteTransformer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
ofFill();
for (int i = 0; i < 7; ++i)
{
mToneModSlider[i]->Draw();
if (gTime - mLastTimeTonePlayed[i] > 0 && gTime - mLastTimeTonePlayed[i] < 200)
{
float alpha = 1 - (gTime - mLastTimeTonePlayed[i]) / 200;
ofSetColor(0, 255, 0, alpha * 255);
ofRect(2, 118 - i * 17, 10, 10);
}
}
}
void NoteTransformer::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mNoteOutput.Flush(time);
}
void NoteTransformer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
return;
}
if (velocity == 0) //note off the one we played for this pitch, in case the transformer changed it while the note was held
{
if (mLastNoteOnForPitch[pitch] != -1)
PlayNoteOutput(time, mLastNoteOnForPitch[pitch], 0, voiceIdx);
return;
}
int tone = TheScale->GetToneFromPitch(pitch);
if (velocity > 0)
mLastTimeTonePlayed[tone % 7] = time;
int pitchOffset = pitch - TheScale->GetPitchFromTone(tone);
tone += mToneMod[tone % TheScale->NumTonesInScale()];
int outPitch = TheScale->GetPitchFromTone(tone) + pitchOffset;
PlayNoteOutput(time, outPitch, velocity, voiceIdx, modulation);
mLastNoteOnForPitch[pitch] = outPitch;
}
void NoteTransformer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteTransformer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteTransformer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 780 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Selector.cpp
// Bespoke
//
// Created by Ryan Challinor on 2/7/16.
//
//
#include "Selector.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
Selector::Selector()
{
}
Selector::~Selector()
{
}
void Selector::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mSelector = new RadioButton(this, "selector", 3, 3, &mCurrentValue);
}
void Selector::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
for (int i = 0; i < (int)mControlCables.size(); ++i)
{
mControlCables[i]->SetManualPosition(GetRect(true).width - 5, 3 + RadioButton::GetSpacing() * (i + .5f));
}
mSelector->Draw();
}
void Selector::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
SyncList();
}
void Selector::SyncList()
{
mSelector->Clear();
for (int i = 0; i < (int)mControlCables.size(); ++i)
{
std::string controlName = "";
if (mControlCables[i]->GetTarget())
controlName = mControlCables[i]->GetTarget()->Path();
mSelector->AddLabel(controlName.c_str(), i);
}
}
void Selector::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
int range = (int)mControlCables.size() - 1;
if (velocity > 0 && range > 0)
SetIndex(pitch % range, time);
}
void Selector::RadioButtonUpdated(RadioButton* radio, int oldVal, double time)
{
SetIndex(mCurrentValue, time);
}
void Selector::SetIndex(int index, double time)
{
mCurrentValue = index;
std::vector<IUIControl*> controlsToEnable;
for (int i = 0; i < (int)mControlCables.size(); ++i)
{
for (auto* cable : mControlCables[i]->GetPatchCables())
{
IUIControl* uicontrol = dynamic_cast<IUIControl*>(cable->GetTarget());
if (uicontrol)
{
if (mCurrentValue == i)
controlsToEnable.push_back(uicontrol);
else
uicontrol->SetValue(0, time);
}
}
}
for (auto* control : controlsToEnable)
control->SetValue(1, time);
}
namespace
{
const float extraW = 20;
const float extraH = 6;
}
void Selector::GetModuleDimensions(float& width, float& height)
{
width = mSelector->GetRect().width + extraW;
height = mSelector->GetRect().height + extraH;
}
void Selector::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadInt("num_items", moduleInfo, 2, 1, 99, K(isTextField));
if (!moduleInfo["uicontrols"].isNull()) //handling for older revision loading
mModuleSaveData.SetInt("num_items", (int)moduleInfo["uicontrols"].size());
SetUpFromSaveData();
}
void Selector::SetUpFromSaveData()
{
int numItems = mModuleSaveData.GetInt("num_items");
int oldNumItems = (int)mControlCables.size();
if (numItems > oldNumItems)
{
for (int i = oldNumItems; i < numItems; ++i)
{
PatchCableSource* cable = new PatchCableSource(this, kConnectionType_ValueSetter);
AddPatchCableSource(cable);
mControlCables.push_back(cable);
}
}
else if (numItems < oldNumItems)
{
for (int i = oldNumItems - 1; i >= numItems; --i)
{
RemovePatchCableSource(mControlCables[i]);
}
mControlCables.resize(numItems);
}
SyncList();
}
``` | /content/code_sandbox/Source/Selector.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 987 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
Sequencer.h
Created: 17 Oct 2018 9:38:03pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "Transport.h"
#include "Checkbox.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "Slider.h"
#include "IPulseReceiver.h"
class PatchCableSource;
class Pulser : public IDrawableModule, public ITimeListener, public IButtonListener, public IDropdownListener, public IIntSliderListener, public IFloatSliderListener, public IAudioPoller, public IPulseSource
{
public:
Pulser();
virtual ~Pulser();
static IDrawableModule* Create() { return new Pulser(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IAudioPoller
void OnTransportAdvanced(float amount) override;
//ITimeListener
void OnTimeEvent(double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
float GetOffset();
enum TimeMode
{
kTimeMode_Step,
kTimeMode_Sync,
kTimeMode_Downbeat,
kTimeMode_Downbeat2,
kTimeMode_Downbeat4,
kTimeMode_Free,
kTimeMode_Align,
kTimeMode_Reset
};
NoteInterval mInterval{ NoteInterval::kInterval_16n };
DropdownList* mIntervalSelector{ nullptr };
TimeMode mTimeMode{ TimeMode::kTimeMode_Step };
DropdownList* mTimeModeSelector{ nullptr };
bool mRandomStep{ false };
Checkbox* mRandomStepCheckbox{ nullptr };
bool mWaitingForDownbeat{ false };
float mOffset{ 0 };
FloatSlider* mOffsetSlider{ nullptr };
FloatSlider* mFreeTimeSlider{ nullptr };
float mFreeTimeStep{ 30 };
float mFreeTimeCounter{ 0 };
int mResetLength{ 8 };
IntSlider* mResetLengthSlider{ nullptr };
int mCustomDivisor{ 8 };
IntSlider* mCustomDivisorSlider{ nullptr };
ClickButton* mRestartFreeTimeButton{ nullptr };
TransportListenerInfo* mTransportListenerInfo{ nullptr };
};
``` | /content/code_sandbox/Source/Pulser.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 804 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// KarplusStrongVoice.cpp
// modularSynth
//
// Created by Ryan Challinor on 2/11/13.
//
//
#include "KarplusStrongVoice.h"
#include "KarplusStrong.h"
#include "EnvOscillator.h"
#include "SynthGlobals.h"
#include "Scale.h"
#include "Profiler.h"
#include "ChannelBuffer.h"
#include "PolyphonyMgr.h"
#include "SingleOscillatorVoice.h"
#include "juce_core/juce_core.h"
KarplusStrongVoice::KarplusStrongVoice(IDrawableModule* owner)
: mBuffer(gSampleRate)
, mOwner(owner)
{
mOsc.Start(0, 1);
mEnv.SetNumStages(2);
mEnv.GetHasSustainStage() = false;
mEnv.GetStageData(0).target = 1;
mEnv.GetStageData(0).time = 3;
mEnv.GetStageData(1).target = 0;
mEnv.GetStageData(1).time = 3;
ClearVoice();
mKarplusStrongModule = dynamic_cast<KarplusStrong*>(mOwner);
}
KarplusStrongVoice::~KarplusStrongVoice()
{
}
bool KarplusStrongVoice::IsDone(double time)
{
return !mActive || mMuteRamp.Value(time) == 0;
}
bool KarplusStrongVoice::Process(double time, ChannelBuffer* out, int oversampling)
{
PROFILER(KarplusStrongVoice);
if (IsDone(time))
return false;
int bufferSize = out->BufferSize();
int channels = out->NumActiveChannels();
double sampleIncrementMs = gInvSampleRateMs;
double sampleRate = gSampleRate;
ChannelBuffer* destBuffer = out;
if (oversampling != 1)
{
gMidiVoiceWorkChannelBuffer.SetNumActiveChannels(channels);
destBuffer = &gMidiVoiceWorkChannelBuffer;
gMidiVoiceWorkChannelBuffer.Clear();
bufferSize *= oversampling;
sampleIncrementMs /= oversampling;
sampleRate *= oversampling;
}
float freq;
float filterRate;
float filterLerp;
float pitch;
float oscPhaseInc;
if (mVoiceParams->mLiteCPUMode)
DoParameterUpdate(0, oversampling, pitch, freq, filterRate, filterLerp, oscPhaseInc);
for (int pos = 0; pos < bufferSize; ++pos)
{
if (!mVoiceParams->mLiteCPUMode)
DoParameterUpdate(pos / oversampling, oversampling, pitch, freq, filterRate, filterLerp, oscPhaseInc);
if (mVoiceParams->mSourceType == kSourceTypeSaw)
mOsc.SetType(kOsc_Saw);
else
mOsc.SetType(kOsc_Sin);
mOscPhase += oscPhaseInc;
float sample = 0;
float oscSample = mOsc.Audio(time, mOscPhase);
float noiseSample = RandomSample();
float pitchBlend = ofClamp((pitch - 40) / 60.0f, 0, 1);
pitchBlend *= pitchBlend;
if (mVoiceParams->mSourceType == kSourceTypeSin || mVoiceParams->mSourceType == kSourceTypeSaw)
sample = oscSample;
else if (mVoiceParams->mSourceType == kSourceTypeNoise)
sample = noiseSample;
else if (mVoiceParams->mSourceType == kSourceTypeMix)
sample = noiseSample * pitchBlend + oscSample * (1 - pitchBlend);
else if (mVoiceParams->mSourceType == kSourceTypeInput || mVoiceParams->mSourceType == kSourceTypeInputNoEnvelope)
sample = mKarplusStrongModule->GetBuffer()->GetChannel(0)[pos / oversampling];
if (mVoiceParams->mSourceType != kSourceTypeInputNoEnvelope)
sample *= mEnv.Value(time) + mVoiceParams->mExcitation;
float samplesAgo = sampleRate / freq;
AssertIfDenormal(samplesAgo);
float feedbackSample = 0;
if (samplesAgo < mBuffer.Size())
{
//interpolated delay
int delay_pos = int(samplesAgo);
int posNext = int(samplesAgo) + 1;
if (delay_pos < mBuffer.Size())
{
float delay_sample = delay_pos < 0 ? 0 : mBuffer.GetSample(delay_pos, 0);
float nextSample = posNext >= mBuffer.Size() ? 0 : mBuffer.GetSample(posNext, 0);
float a = samplesAgo - delay_pos;
feedbackSample = (1 - a) * delay_sample + a * nextSample; //interpolate
JUCE_UNDENORMALISE(feedbackSample);
}
}
mFilteredSample = ofLerp(feedbackSample, mFilteredSample, filterLerp);
JUCE_UNDENORMALISE(mFilteredSample);
//sample += mFeedbackRamp.Value(time) * mFilterSample;
float feedback = mFilteredSample * sqrtf(mVoiceParams->mFeedback + GetPressure(pos) * .02f) * mMuteRamp.Value(time);
if (mVoiceParams->mInvert)
feedback *= -1;
float sampleForFeedbackBuffer = sample + feedback;
float outputSample;
if (mVoiceParams->mSourceType == kSourceTypeInputNoEnvelope)
outputSample = feedback; //don't include dry input in the output
else
outputSample = sampleForFeedbackBuffer;
JUCE_UNDENORMALISE(sample);
mBuffer.Write(sampleForFeedbackBuffer, 0);
if (channels == 1)
{
destBuffer->GetChannel(0)[pos] += outputSample;
}
else
{
destBuffer->GetChannel(0)[pos] += outputSample * GetLeftPanGain(GetPan());
destBuffer->GetChannel(1)[pos] += outputSample * GetRightPanGain(GetPan());
}
time += sampleIncrementMs;
}
if (oversampling != 1)
{
//assume power-of-two
while (oversampling > 1)
{
for (int i = 0; i < bufferSize; ++i)
{
for (int ch = 0; ch < channels; ++ch)
destBuffer->GetChannel(ch)[i] = (destBuffer->GetChannel(ch)[i * 2] + destBuffer->GetChannel(ch)[i * 2 + 1]) / 2;
}
oversampling /= 2;
bufferSize /= 2;
}
for (int ch = 0; ch < channels; ++ch)
Add(out->GetChannel(ch), destBuffer->GetChannel(ch), bufferSize);
}
return true;
}
void KarplusStrongVoice::DoParameterUpdate(int samplesIn,
int oversampling,
float& pitch,
float& freq,
float& filterRate,
float& filterLerp,
float& oscPhaseInc)
{
if (mOwner)
mOwner->ComputeSliders(samplesIn);
pitch = GetPitch(samplesIn);
if (mVoiceParams->mInvert)
pitch += 12; //inverting the pitch gives an octave down sound by halving the resonating frequency, so correct for that
freq = TheScale->PitchToFreq(pitch);
filterRate = mVoiceParams->mFilter * pow(freq / 300, exp2(mVoiceParams->mPitchTone)) * (1 + GetModWheel(samplesIn));
filterLerp = ofClamp(exp2(-filterRate / oversampling), 0, 1);
oscPhaseInc = GetPhaseInc(mVoiceParams->mExciterFreq) / oversampling;
}
void KarplusStrongVoice::Start(double time, float target)
{
float volume = ofLerp((1 - mVoiceParams->mVelToVolume), 1, target);
float envScale = SingleOscillatorVoice::GetADSRScale(target, -mVoiceParams->mVelToEnvelope);
mOscPhase = FPI / 2; //magic number that seems to keep things DC centered ok
mEnv.Clear();
mEnv.GetStageData(0).time = mVoiceParams->mExciterAttack * envScale;
mEnv.GetStageData(1).time = mVoiceParams->mExciterDecay;
mEnv.Start(time, volume);
mEnv.SetMaxSustain(10);
mMuteRamp.SetValue(1);
mActive = true;
}
void KarplusStrongVoice::Stop(double time)
{
mMuteRamp.Start(time, 0, time + 400);
}
void KarplusStrongVoice::ClearVoice()
{
mBuffer.ClearBuffer();
mFilteredSample = 0;
mActive = false;
}
void KarplusStrongVoice::SetVoiceParams(IVoiceParams* params)
{
mVoiceParams = dynamic_cast<KarplusStrongVoiceParams*>(params);
}
``` | /content/code_sandbox/Source/KarplusStrongVoice.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,034 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ChordDatabase.cpp
Created: 26 Mar 2018 9:54:44pm
Author: Ryan Challinor
==============================================================================
*/
#include "ChordDatabase.h"
#include "Scale.h"
#include <set>
ChordDatabase::ChordDatabase()
{
// Major scale like chords
//
// { 10.0f, -2.0f, -1.0f, 10.0f, -2.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, -1.0f, -1.0f } // Based on Mixolydian/Ionian mode
// ref: { 0/12, 1/13, 2/14, 3/15, 4/16, 5/17, 6/18, 7/19, 8/20, 9/21, 10/22, 11/23}));
// { C, C#, D, D#, E, F, F#, G, G#, A, A#, B}));
mChordShapes.push_back(ChordShape("", { 0, 4, 7 },
{ 10.0f, -2.0f, -1.0f, -5.0f, 10.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, -1.0f, -1.0f }, 2.0f));
mChordShapes.push_back(ChordShape("sus4", { 0, 5, 7 },
{ 10.0f, -2.0f, -1.0f, -5.0f, -5.0f, 10.0f, -2.0f, 10.0f, -2.0f, -1.0f, -1.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("sus2", { 0, 2, 7 },
{ 10.0f, -2.0f, 10.0f, -5.0f, -5.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, -1.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("2", { 0, 2, 4, 7 },
{ 10.0f, -2.0f, 10.0f, -5.0f, 10.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, -1.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("4", { 0, 4, 5, 7 },
{ 10.0f, -2.0f, -1.0f, -5.0f, 10.0f, 10.0f, -2.0f, 10.0f, -2.0f, -1.0f, -1.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("6", { 0, 4, 7, 9 },
{ 10.0f, -2.0f, -1.0f, -5.0f, 10.0f, -1.0f, -2.0f, 10.0f, -2.0f, 10.0f, -1.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("7", { 0, 4, 7, 10 },
{ 10.0f, -2.0f, -1.0f, -5.0f, 10.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, 10.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("9", { 0, 4, 7, 10, 14 },
{ 10.0f, -2.0f, 10.0f, -5.0f, 10.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, 8.00f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("11", { 0, 4, 7, 10, 14, 17 },
{ 10.0f, -2.0f, 8.00f, -5.0f, 10.0f, 10.0f, -2.0f, 10.0f, -2.0f, -1.0f, 8.00f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("13", { 0, 4, 7, 10, 14, 17, 21 },
{ 10.0f, -2.0f, 8.00f, -2.0f, 10.0f, 8.00f, -2.0f, 10.0f, -2.0f, 10.0f, 8.00f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("6/9", { 0, 4, 7, 9, 14 },
{ 10.0f, -2.0f, 10.0f, -5.0f, 10.0f, -1.0f, -2.0f, 10.0f, -2.0f, 10.0f, -5.0f, -5.0f }, 2.0f));
mChordShapes.push_back(ChordShape("maj7", { 0, 4, 7, 11 },
{ 10.0f, -2.0f, -1.0f, -5.0f, 10.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, -2.0f, 10.0f }, 2.0f));
mChordShapes.push_back(ChordShape("maj9", { 0, 4, 7, 11, 14 },
{ 10.0f, -2.0f, 10.0f, -5.0f, 10.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, -2.0f, 8.00f }, 2.0f));
mChordShapes.push_back(ChordShape("maj11", { 0, 4, 7, 11, 14, 17 },
{ 10.0f, -2.0f, 8.00f, -5.0f, 10.0f, 10.0f, -2.0f, 10.0f, -2.0f, -1.0f, -2.0f, 8.00f }, 2.0f));
mChordShapes.push_back(ChordShape("maj13", { 0, 4, 7, 11, 14, 17, 21 },
{ 10.0f, -2.0f, 8.00f, -5.0f, 10.0f, 8.00f, -2.0f, 10.0f, -2.0f, 10.0f, -2.0f, 8.00f }, 2.0f));
// Minor scale like chords
// { 10.0f, -2.0f, -1.0f, 10.0f, -2.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, -2.0f, -1.0f } // Based on Dorian/Aeolian mode
// ref: { 0/12, 1/13, 2/14, 3/15, 4/16, 5/17, 6/18, 7/19, 8/20, 9/21, 10/22, 11/23}));
// { C, C#, D, D#, E, F, F#, G, G#, A, A#, B}));
mChordShapes.push_back(ChordShape("m", { 0, 3, 7 },
{ 10.0f, -2.0f, -1.0f, 10.0f, -5.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, -1.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("m6", { 0, 3, 7, 9 },
{ 10.0f, -2.0f, -1.0f, 10.0f, -5.0f, -1.0f, -2.0f, 10.0f, -2.0f, 10.0f, -1.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("m7", { 0, 3, 7, 10 },
{ 10.0f, -2.0f, -1.0f, 10.0f, -5.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, 10.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("m9", { 0, 3, 7, 10, 14 },
{ 10.0f, -2.0f, 10.0f, 10.0f, -5.0f, -1.0f, -2.0f, 10.0f, -2.0f, -1.0f, 8.00f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("m11", { 0, 3, 7, 10, 14, 17 },
{ 10.0f, -2.0f, 8.00f, 10.0f, -5.0f, 10.0f, -2.0f, 10.0f, -2.0f, -1.0f, 8.00f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("m13", { 0, 3, 7, 10, 14, 17, 21 },
{ 10.0f, -2.0f, 8.00f, 10.0f, -5.0f, 8.00f, -2.0f, 10.0f, -2.0f, 10.0f, 8.00f, -2.0f }, 2.0f));
// Mixed
// { 10.0f, -2.0f, -2.0f, -1.0f, 10.0f, -2.0f, -2.0f, -1.0f, 10.0f, -2.0f, -2.0f, -1.0f } // Based on augmented scale
// { 10.0f, -2.0f, -1.0f, 10.0f, -2.0f, -1.0f, 10.0f, -2.0f, -1.0f, -1.0f, -2.0f, -1.0f } // Based on diminished scale
// { 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, -2.0f, -2.0f, -2.0f } // no scale? {:^c (i.e. don't alter mixed chords)
// ref: { 0/12, 1/13, 2/14, 3/15, 4/16, 5/17, 6/18, 7/19, 8/20, 9/21, 10/22, 11/23}));
// { C, C#, D, D#, E, F, F#, G, G#, A, A#, B}));
mChordShapes.push_back(ChordShape("aug", { 0, 4, 8 },
{ 10.0f, -2.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("aug7", { 0, 4, 8, 10 },
{ 10.0f, -2.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, -2.0f, 10.0f, -2.0f, 10.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("aug/maj7", { 0, 4, 8, 11 },
{ 10.0f, -2.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, 10.0f }, 2.0f));
mChordShapes.push_back(ChordShape("dim", { 0, 3, 6 },
{ 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, -2.0f, -2.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("dim7", { 0, 3, 6, 9 },
{ 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("min7dim5", { 0, 3, 6, 10 },
{ 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, -2.0f, 10.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("dom7dim5", { 0, 4, 6, 10 },
{ 10.0f, -2.0f, -2.0f, -2.0f, 10.0f, -2.0f, 10.0f, -2.0f, -2.0f, -2.0f, 10.0f, -2.0f }, 2.0f));
mChordShapes.push_back(ChordShape("min/maj7", { 0, 3, 7, 11 },
{ 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, 10.0f, -2.0f, -2.0f, -2.0f, -2.0f, 10.0f }, 2.0f));
}
std::set<std::string> ChordDatabase::GetChordNamesAdvanced(const std::vector<int>& pitches, bool useScaleDegrees, bool showIntervals) const
{
std::set<std::string> chordNames;
int numPitches = (int)pitches.size();
if (numPitches == 1 && useScaleDegrees && showIntervals)
{
// Show scale degree of played note. Not really chord detection, but may be useful
chordNames.insert(NoteNameScaleRelative(pitches[0], true));
return chordNames;
}
else if (numPitches == 2 && showIntervals)
{
// Intervals up to 11th
const std::vector<std::string> intervals = { "1st", "min 2nd", "2nd", "min 3rd", "3rd", "4th", "aug 4th/dim 5th", "5th",
"min 6th", "6th", "min 7th", "7th", "oct", "min 9th", "9th", "min 10th", "10th", "11th" };
int interval = abs(pitches[1] - pitches[0]);
int lowest = (pitches[0] < pitches[1] ? pitches[0] : pitches[1]) % 12;
if (interval < intervals.size())
chordNames.insert(intervals[interval] + "/" + NoteNameScaleRelative(lowest, useScaleDegrees));
return chordNames;
}
// Create a boolean vector with each pitch played, set to be in one octave
std::set<int> octavePitches;
for (int pitch : pitches)
{
octavePitches.insert(pitch % 12);
}
if (octavePitches.size() < 3)
return chordNames;
// Considering each played note as a possible root, find the root and chord with the greatest weight
float maxWeight = 0.0f;
int lowestPitch = pitches[0] % 12;
std::list<std::tuple<int, ChordShape>> bestChords; // Is this cursed?
// For each note played
for (int rootOctavePitch : octavePitches)
{
// Try note as the root, multiply with the weights of the notes to be played
for (ChordShape shape : mChordShapes)
{
float chordWeight = shape.mWeightSum;
// Add some extra weight if the lowest played note is the root
chordWeight += rootOctavePitch == lowestPitch ? shape.mRootPosBias : 0;
// Add the weights for the pitches in the chord
for (int octavePitch : octavePitches)
{
// Looping over the same stuff within the same loop, crazy!
chordWeight += 2.0f * shape.mWeights[(12 + octavePitch - rootOctavePitch) % 12];
}
// Consider the chords with the highest weight as the best fit
if (chordWeight > maxWeight + FLT_EPSILON)
{
maxWeight = chordWeight;
// Better weight than found before, replace list with this chord
bestChords.clear();
bestChords.push_back(std::make_tuple(rootOctavePitch, shape));
}
else if (chordWeight >= maxWeight - FLT_EPSILON)
{
// Equal weight as current best, add to list
bestChords.push_back(std::make_tuple(rootOctavePitch, shape));
}
}
}
for (const auto& chord : bestChords)
{
chordNames.insert(GetChordNameAdvanced(pitches, std::get<0>(chord), std::get<1>(chord), useScaleDegrees));
}
return chordNames;
}
std::string ChordDatabase::GetChordNameAdvanced(const std::vector<int>& pitches, const int root, const ChordShape shape, bool useScaleDegrees) const
{
std::string rootName;
std::string chordName;
if (useScaleDegrees)
{
rootName = ChordNameScaleRelative(root);
chordName = rootName + shape.mName;
}
else
{
rootName = NoteNameScaleRelative(root, false);
chordName = rootName + shape.mName;
}
// Alterations
std::set<int> rootScalePitches;
const std::set<int> majorScalePitches = { 0, 2, 4, 5, 7, 9, 11, 12, 14, 16, 17, 19, 21, 23 };
const std::vector<std::string> Alterations = { "1", "(m2)", "2", "(m3)", "3", "4", "(b5)", "5", "(#5)", "6", "(b7)", "7",
"8", "(b9)", "9", "(#9)", "10", "11", "(#11)", "12", "(b13)", "13", "(#13)", "14" };
std::string alterations = "";
int rootPitch = 0;
bool foundRoot = false;
// Find hightest root before other notes (Needed to distinguish between notes in different octaves and for inverted chords)
for (int pitch : pitches)
{
if ((12 + pitch - root) % 12 == 0)
{
rootPitch = pitch;
foundRoot = true;
continue;
}
if (foundRoot)
break;
}
// Calculate pitches in the key of the root
for (int pitch : pitches)
{
// Use difference between highest root up to two octaves, otherwise use first octave
rootScalePitches.insert(pitch - rootPitch >= 0 ? (pitch - rootPitch) % 24 : (12 + pitch - root) % 12);
}
// For all played notes
for (int shapePitch : shape.mElements)
{
// If pitch played, continue
if (rootScalePitches.find(shapePitch) != rootScalePitches.end() ||
rootScalePitches.find((shapePitch + 12) % 24) != rootScalePitches.end())
{
rootScalePitches.erase(shapePitch);
rootScalePitches.erase((shapePitch + 12) % 24);
continue;
}
// If pitch not played, test if alteration played instead
// shapepitch has to be in scale of root and alteration has to be played
if (majorScalePitches.find(shapePitch) != majorScalePitches.end())
{
// Don't need to modulo the indices here because rootScalePitches are <24
// and the indices must be found in rootScalePitches
// Alterations up
if (rootScalePitches.find(shapePitch + 1) != rootScalePitches.end())
{
alterations += Alterations[shapePitch + 1];
rootScalePitches.erase((shapePitch + 1));
}
else if (rootScalePitches.find(shapePitch + 12 + 1) != rootScalePitches.end())
{
// No +12 as the note from the shape is altered, not the note found in rootScalePitches
alterations += Alterations[shapePitch + 1];
rootScalePitches.erase((shapePitch + 12 + 1));
}
// Alterations down
else if (rootScalePitches.find(shapePitch - 1) != rootScalePitches.end())
{
alterations += Alterations[shapePitch - 1];
rootScalePitches.erase((shapePitch - 1));
}
else if (rootScalePitches.find(shapePitch + 12 - 1) != rootScalePitches.end())
{
alterations += Alterations[shapePitch - 1];
rootScalePitches.erase((shapePitch + 12 - 1));
}
// Otherwise, display missing pitches (except 5 because of neutral tone) as omitX
else if (shapePitch != 7 && shapePitch != 19)
{
alterations += "omit" + Alterations[shapePitch];
}
}
}
// Display left-over pitches as addX
for (int playedPitch : rootScalePitches)
{
alterations += "add" + Alterations[playedPitch];
}
// If lowest note is not the root, notate it ass the bass note
// (kind of extra since there's lots of inversions, might need a check to see if note is in the chord shape, or a check on the distance between the rest of the notes)
int lowest = 12 + pitches[0] - root % 12;
if (lowest % 12 != 0)
{
alterations += "/" + NoteNameScaleRelative(pitches[0], useScaleDegrees);
}
return chordName + alterations;
}
std::string ChordDatabase::ChordNameScaleRelative(int rootPitch) const
{
const std::vector<std::string> chordNames = { "I", "bII", "II", "bIII", "III", "IV", "bV", "V", "bVI", "VI", "bVII", "VII" };
int relpitch = (rootPitch + 12 - TheScale->ScaleRoot()) % 12;
return chordNames[relpitch];
}
std::string ChordDatabase::NoteNameScaleRelative(int pitch, bool useDegrees) const
{
if (useDegrees)
{
int relpitch = (pitch + 12 - TheScale->ScaleRoot()) % 12;
//const std::vector<std::string> flats = { "1^", "2^b", "2^", "3^b", "3^", "4^", "5^b", "5^", "6^b", "6^", "7^b", "7^" };
//const std::vector<std::string> sharps = { "1^", "1^#", "2^", "2^#", "3^", "4^", "4^#", "5^", "5^#", "6^", "6^#", "7^" };
// Choice of flats or sharps here depends strongly on context that can't really be gathered, so instead use some common options
const std::vector<std::string> accidentals = { "1^", "2^b", "2^", "3^b", "3^", "4^", "5^b", "5^", "5^#", "6^", "7^b", "7^" };
// For consistency with scale types, all scales are related to the major scale. i.e. in C minor Cb is 3^b rather than 3^.
return accidentals[relpitch];
}
else
{
pitch %= 12;
if (TheScale->GetType() == "aeolian")
{
const std::vector<int> flatScales = { 0, 2, 3, 5, 8, 10 }; // D G C F Ab Eb Bb
if (std::find(flatScales.begin(), flatScales.end(), TheScale->ScaleRoot()) != flatScales.end())
return NoteName(pitch, true);
else
return NoteName(pitch);
}
else
{
const std::vector<int> flatScales = { 0, 1, 3, 5, 6, 8, 10 }; // C F Bb Eb Ab Gb Db (Cb not included)
if (std::find(flatScales.begin(), flatScales.end(), TheScale->ScaleRoot()) != flatScales.end())
return NoteName(pitch, true);
else
return NoteName(pitch);
}
}
}
std::string ChordDatabase::GetChordName(std::vector<int> pitches) const
{
int numPitches = (int)pitches.size();
if (numPitches < 3)
return "None";
std::list<std::string> names;
sort(pitches.begin(), pitches.end());
for (int inversion = 0; inversion < numPitches; ++inversion)
{
for (ChordShape shape : mChordShapes)
{
if (shape.mElements.size() == numPitches)
{
int root = pitches[(numPitches - inversion) % numPitches] - (inversion > 0 ? 12 : 0);
bool match = true;
for (int i = 0; i < numPitches; ++i)
{
if (shape.mElements[(i + inversion) % numPitches] != pitches[i] - root - (i >= numPitches - inversion ? 12 : 0))
{
match = false;
break;
}
}
if (match)
{
int degree = TheScale->GetToneFromPitch(root) % 7;
names.push_back(NoteName(root) + shape.mName + (inversion == 0 ? "" : " (" + ofToString(inversion) + "inv)") + " (" + GetRomanNumeralForDegree(degree) + ")");
}
}
}
}
if (names.size() == 0)
return "Unknown";
std::string ret = "";
for (std::string name : names)
ret += name + "; ";
return ret.substr(0, ret.length() - 2);
}
std::vector<int> ChordDatabase::GetChord(std::string name, int inversion) const
{
std::vector<int> ret;
for (auto shape : mChordShapes)
{
if (shape.mName == name)
{
bool isInverted = (inversion != 0);
for (int i = 0; i < shape.mElements.size(); ++i)
{
int index = (i + inversion) % shape.mElements.size();
int val = shape.mElements[index];
if (index >= inversion && isInverted)
val -= 12;
ret.push_back(val);
}
}
}
return ret;
}
std::vector<std::string> ChordDatabase::GetChordNames() const
{
std::vector<std::string> ret;
for (auto shape : mChordShapes)
ret.push_back(shape.mName);
return ret;
}
``` | /content/code_sandbox/Source/ChordDatabase.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 7,271 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// FFT.h
// modularSynth
//
// Created by Ryan Challinor on 1/27/13.
//
//
#pragma once
#include <iostream>
#include "SynthGlobals.h"
// Variables for FFT routine
class FFT
{
public:
FFT(int nfft);
~FFT();
void Forward(float* input, float* output_re, float* output_im);
void Inverse(float* input_re, float* input_im, float* output);
private:
int mNfft{ 0 }; // size of FFT
int mNumfreqs{ 0 }; // number of frequencies represented (nfft/2 + 1)
float* mFft_data{ nullptr }; // array for writing/reading to/from FFT function
};
struct FFTData
{
FFTData(int windowSize, int freqDomainSize)
: mWindowSize(windowSize)
, mFreqDomainSize(freqDomainSize)
{
mRealValues = new float[freqDomainSize];
mImaginaryValues = new float[freqDomainSize];
mTimeDomain = new float[windowSize];
Clear();
}
~FFTData()
{
delete[] mRealValues;
delete[] mImaginaryValues;
delete[] mTimeDomain;
}
void Clear();
int mWindowSize{ 0 };
int mFreqDomainSize{ 0 };
float* mRealValues{ nullptr };
float* mImaginaryValues{ nullptr };
float* mTimeDomain{ nullptr };
};
#ifndef MAYER_H
#define MAYER_H
#define REAL float
void mayer_realfft(int n, REAL* real);
void mayer_realifft(int n, REAL* real);
#endif
``` | /content/code_sandbox/Source/FFT.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 461 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ControllingSong.h
// Bespoke
//
// Created by Ryan Challinor on 3/29/14.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "DropdownList.h"
#include "Checkbox.h"
#include "ClickButton.h"
#include "RadioButton.h"
#include "Slider.h"
#include "IAudioSource.h"
#include "MidiReader.h"
#include "Sample.h"
#include "ofxJSONElement.h"
class FollowingSong;
class ControllingSong : public IDrawableModule, public IDropdownListener, public IButtonListener, public IRadioButtonListener, public IIntSliderListener, public IAudioSource, public IFloatSliderListener
{
public:
ControllingSong();
~ControllingSong();
static IDrawableModule* Create() { return new ControllingSong(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void Poll() override;
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void RadioButtonUpdated(RadioButton* list, int oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
virtual void SaveLayout(ofxJSONElement& moduleInfo) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 560;
height = 160;
}
void LoadSong(int index);
ofMutex mLoadSongMutex;
bool mLoadingSong{ true };
int mCurrentSongIndex{ -1 };
MidiReader mMidiReader;
Sample mSample;
float mVolume{ .8 };
FloatSlider* mVolumeSlider{ nullptr };
bool mNeedNewSong{ true };
double mSongStartTime{ 0 };
ofxJSONElement mSongList;
int mTestBeatOffset{ 0 };
IntSlider* mTestBeatOffsetSlider{ nullptr };
bool mPlay{ false };
Checkbox* mPlayCheckbox{ nullptr };
bool mShuffle{ false };
Checkbox* mShuffleCheckbox{ nullptr };
ClickButton* mPhraseForwardButton{ nullptr };
ClickButton* mPhraseBackButton{ nullptr };
float mSpeed{ 1 };
FloatSlider* mSpeedSlider{ nullptr };
bool mMute{ false };
Checkbox* mMuteCheckbox{ nullptr };
DropdownList* mSongSelector{ nullptr };
ClickButton* mNextSongButton{ nullptr };
int mShuffleIndex{ 0 };
std::vector<int> mShuffleList{};
std::vector<FollowingSong*> mFollowSongs{};
};
``` | /content/code_sandbox/Source/ControllingSong.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 821 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// VocoderCarrierInput.h
// modularSynth
//
// Created by Ryan Challinor on 4/18/13.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
class VocoderBase
{
public:
virtual ~VocoderBase() {}
virtual void SetCarrierBuffer(float* buffer, int bufferSize) = 0;
};
class VocoderCarrierInput : public IAudioProcessor, public IDrawableModule
{
public:
VocoderCarrierInput();
virtual ~VocoderCarrierInput();
static IDrawableModule* Create() { return new VocoderCarrierInput(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioProcessor
InputMode GetInputMode() override { return kInputMode_Mono; }
//IAudioSource
void Process(double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 60;
h = 0;
}
VocoderBase* mVocoder{ nullptr };
IAudioReceiver* mVocoderTarget{ nullptr };
};
``` | /content/code_sandbox/Source/VocoderCarrierInput.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 427 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
MidiCapturer.h
Created: 15 Apr 2019 9:32:38pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "NoteEffectBase.h"
#include "Transport.h"
#include "INonstandardController.h"
class MidiDeviceListener;
class MidiCapturerDummyController : public INonstandardController
{
public:
MidiCapturerDummyController(MidiDeviceListener* listener);
virtual ~MidiCapturerDummyController() {}
void SendValue(int page, int control, float value, bool forceNoteOn = false, int channel = -1) override {}
void SendMidi(const juce::MidiMessage& message);
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in) override;
private:
MidiDeviceListener* mListener;
};
class MidiCapturer : public NoteEffectBase, public IDrawableModule, public IAudioPoller
{
public:
MidiCapturer();
virtual ~MidiCapturer();
static IDrawableModule* Create() { return new MidiCapturer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void Init() override;
void AddDummyController(MidiCapturerDummyController* controller);
//IAudioPoller
void OnTransportAdvanced(float amount) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendMidi(const juce::MidiMessage& message) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 300;
height = 150;
}
static const int kRingBufferLength = 1000;
int mRingBufferPos{ 0 };
juce::MidiMessage mMessages[kRingBufferLength];
std::list<MidiCapturerDummyController*> mDummyControllers;
int mPlayhead{ 0 };
};
``` | /content/code_sandbox/Source/MidiCapturer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 616 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// DrumSynth.cpp
// Bespoke
//
// Created by Ryan Challinor on 8/5/14.
//
//
#include "DrumSynth.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "MidiController.h"
#include "Profiler.h"
#include "UIControlMacros.h"
#include "IAudioReceiver.h"
#include "ADSRDisplay.h"
#define DRUMSYNTH_NO_CUTOFF 10000
namespace
{
const int kPadYOffset = 20;
}
DrumSynth::DrumSynth()
{
for (int i = 0; i < (int)mHits.size(); ++i)
{
int x = (i % DRUMSYNTH_PADS_HORIZONTAL) * DRUMSYNTH_PAD_WIDTH + 5;
int y = (1 - (i / DRUMSYNTH_PADS_HORIZONTAL)) * DRUMSYNTH_PAD_HEIGHT + kPadYOffset;
mHits[i] = new DrumSynthHit(this, i, x, y);
if (i == 0)
mHits[i]->mData.mVol = .5f;
}
}
void DrumSynth::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
FLOATSLIDER(mVolSlider, "vol", &mVolume, 0, 2);
ENDUIBLOCK0();
for (size_t i = 0; i < mHits.size(); ++i)
mHits[i]->CreateUIControls();
}
DrumSynth::~DrumSynth()
{
for (size_t i = 0; i < mHits.size(); ++i)
delete mHits[i];
}
void DrumSynth::Process(double time)
{
PROFILER(DrumSynth);
IAudioReceiver* target = GetTarget();
if (!mEnabled || (target == nullptr && !mUseIndividualOuts))
return;
int numChannels = mMonoOutput ? 1 : 2;
ComputeSliders(0);
SyncOutputBuffer(numChannels);
int oversampling = mOversampling;
int bufferSize = gBufferSize;
double sampleIncrementMs = gInvSampleRateMs;
double sampleRate = gSampleRate;
if (oversampling != 1)
{
bufferSize *= oversampling;
sampleIncrementMs /= oversampling;
sampleRate *= oversampling;
}
float volSq = mVolume * mVolume;
if (mUseIndividualOuts)
{
for (int i = 0; i < (int)mHits.size(); ++i)
{
int hitOversampling = oversampling;
int hitBufferSize = bufferSize;
if (GetTarget(i + 1) != nullptr)
{
Clear(gWorkBuffer, hitBufferSize);
mHits[i]->Process(time, gWorkBuffer, hitBufferSize, oversampling, sampleRate, sampleIncrementMs);
//assume power-of-two
while (hitOversampling > 1)
{
for (int j = 0; j < hitBufferSize; ++j)
gWorkBuffer[j] = (gWorkBuffer[j * 2] + gWorkBuffer[j * 2 + 1]) / 2;
hitOversampling /= 2;
hitBufferSize /= 2;
}
Mult(gWorkBuffer, volSq, hitBufferSize);
auto* targetBuffer = GetTarget(i + 1)->GetBuffer();
mHits[i]->mIndividualOutput->mVizBuffer->SetNumChannels(numChannels);
for (int ch = 0; ch < numChannels; ++ch)
{
mHits[i]->mIndividualOutput->mVizBuffer->WriteChunk(gWorkBuffer, hitBufferSize, ch);
Add(targetBuffer->GetChannel(ch), gWorkBuffer, hitBufferSize);
}
}
}
}
else
{
Clear(gWorkBuffer, bufferSize);
for (size_t i = 0; i < mHits.size(); ++i)
mHits[i]->Process(time, gWorkBuffer, bufferSize, oversampling, sampleRate, sampleIncrementMs);
//assume power-of-two
while (oversampling > 1)
{
for (int i = 0; i < bufferSize; ++i)
gWorkBuffer[i] = (gWorkBuffer[i * 2] + gWorkBuffer[i * 2 + 1]) / 2;
oversampling /= 2;
bufferSize /= 2;
}
Mult(gWorkBuffer, volSq, bufferSize);
for (int ch = 0; ch < numChannels; ++ch)
{
GetVizBuffer()->WriteChunk(gWorkBuffer, bufferSize, ch);
Add(target->GetBuffer()->GetChannel(ch), gWorkBuffer, bufferSize);
}
}
}
void DrumSynth::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (pitch >= 0 && pitch < mHits.size())
{
if (velocity > 0)
mHits[pitch]->Play(time, velocity / 127.0f);
}
}
void DrumSynth::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (right)
return;
x -= 5;
y -= kPadYOffset;
if (x < 0 || y < 0)
return;
x /= DRUMSYNTH_PAD_WIDTH;
y /= DRUMSYNTH_PAD_HEIGHT;
if (x < DRUMSYNTH_PADS_HORIZONTAL && y < DRUMSYNTH_PADS_VERTICAL)
{
int sampleIdx = GetAssociatedSampleIndex(x, y);
if (sampleIdx != -1)
{
//mHits[sampleIdx]->Play(gTime);
//mVelocity[sampleIdx] = 1;
}
}
}
void DrumSynth::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mVolSlider->Draw();
ofPushMatrix();
for (size_t i = 0; i < mHits.size(); ++i)
{
ofPushStyle();
if (mHits[i]->Level() > 0)
{
ofFill();
ofSetColor(200, 100, 0, gModuleDrawAlpha * sqrtf(mHits[i]->Level()));
ofRect(mHits[i]->mX, mHits[i]->mY, DRUMSYNTH_PAD_WIDTH, DRUMSYNTH_PAD_HEIGHT);
}
ofSetColor(200, 100, 0, gModuleDrawAlpha);
ofNoFill();
ofRect(mHits[i]->mX, mHits[i]->mY, DRUMSYNTH_PAD_WIDTH, DRUMSYNTH_PAD_HEIGHT);
ofPopStyle();
ofSetColor(255, 255, 255, gModuleDrawAlpha);
std::string name = ofToString(i);
DrawTextNormal(name, mHits[i]->mX + 5, mHits[i]->mY + 12);
mHits[i]->Draw();
}
ofPopMatrix();
}
int DrumSynth::GetAssociatedSampleIndex(int x, int y)
{
int pos = x + (DRUMSYNTH_PADS_VERTICAL - 1 - y) * DRUMSYNTH_PADS_HORIZONTAL;
if (pos < DRUMSYNTH_PADS_HORIZONTAL * DRUMSYNTH_PADS_VERTICAL)
return pos;
return -1;
}
void DrumSynth::GetModuleDimensions(float& width, float& height)
{
width = 10 + MIN(mHits.size(), DRUMSYNTH_PADS_HORIZONTAL) * DRUMSYNTH_PAD_WIDTH;
height = 2 + kPadYOffset + mHits.size() / DRUMSYNTH_PADS_HORIZONTAL * DRUMSYNTH_PAD_HEIGHT;
}
void DrumSynth::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void DrumSynth::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void DrumSynth::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void DrumSynth::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void DrumSynth::ButtonClicked(ClickButton* button, double time)
{
}
void DrumSynth::RadioButtonUpdated(RadioButton* radio, int oldVal, double time)
{
}
void DrumSynth::TextEntryComplete(TextEntry* entry)
{
}
void DrumSynth::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadBool("individual_outs", moduleInfo, false);
mModuleSaveData.LoadBool("mono", moduleInfo, false);
EnumMap oversamplingMap;
oversamplingMap["1"] = 1;
oversamplingMap["2"] = 2;
oversamplingMap["4"] = 4;
oversamplingMap["8"] = 8;
mModuleSaveData.LoadEnum<int>("oversampling", moduleInfo, 1, nullptr, &oversamplingMap);
SetUpFromSaveData();
}
void DrumSynth::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
bool useIndividualOuts = mModuleSaveData.GetBool("individual_outs");
if (useIndividualOuts)
{
for (size_t i = 0; i < mHits.size(); ++i)
{
if (mHits[i]->mIndividualOutput == nullptr)
mHits[i]->mIndividualOutput = new IndividualOutput(mHits[i]);
}
}
GetPatchCableSource()->SetShowing(!useIndividualOuts);
mUseIndividualOuts = useIndividualOuts;
mMonoOutput = mModuleSaveData.GetBool("mono");
mOversampling = mModuleSaveData.GetEnum<int>("oversampling");
}
DrumSynth::DrumSynthHit::DrumSynthHit(DrumSynth* parent, int index, int x, int y)
: mParent(parent)
, mIndex(index)
, mX(x)
, mY(y)
{
mFilter.SetFilterType(kFilterType_Lowpass);
mFilter.SetFilterParams(1000, sqrt(2) / 2);
}
DrumSynth::DrumSynthHit::~DrumSynthHit()
{
delete mIndividualOutput;
}
void DrumSynth::DrumSynthHit::CreateUIControls()
{
#undef UIBLOCK_OWNER
#define UIBLOCK_OWNER mParent //change owner
float width, height;
float kColumnWidth = (DRUMSYNTH_PAD_WIDTH - 5 * 2 - 3) * .5f;
UIBLOCK(mX + 5, mY + 15, kColumnWidth);
UICONTROL_CUSTOM(mToneAdsrDisplay, new ADSRDisplay(UICONTROL_BASICS(("adsrtone" + ofToString(mIndex)).c_str()), kColumnWidth, 36, mData.mTone.GetADSR()));
FLOATSLIDER(mVolSlider, ("vol" + ofToString(mIndex)).c_str(), &mData.mVol, 0, 1);
UIBLOCK_NEWCOLUMN();
UICONTROL_CUSTOM(mNoiseAdsrDisplay, new ADSRDisplay(UICONTROL_BASICS(("adsrnoise" + ofToString(mIndex)).c_str()), kColumnWidth, 36, mData.mNoise.GetADSR()));
FLOATSLIDER_DIGITS(mVolNoiseSlider, ("noise" + ofToString(mIndex)).c_str(), &mData.mVolNoise, 0, 1, 2);
ENDUIBLOCK(width, height);
UIBLOCK(mX + 5, height + 3);
UICONTROL_CUSTOM(mToneType, new RadioButton(UICONTROL_BASICS(("type" + ofToString(mIndex)).c_str()), (int*)(&mData.mTone.mOsc.mType)));
UIBLOCK_SHIFTX(30);
float freqAdsrWidth = DRUMSYNTH_PAD_WIDTH - 5 * 2 - 3 - 30;
UICONTROL_CUSTOM(mFreqAdsrDisplay, new ADSRDisplay(UICONTROL_BASICS(("adsrfreq" + ofToString(mIndex)).c_str()), freqAdsrWidth, 36, &mData.mFreqAdsr));
UIBLOCK_PUSHSLIDERWIDTH(freqAdsrWidth);
FLOATSLIDER(mFreqMaxSlider, ("freqmax" + ofToString(mIndex)).c_str(), &mData.mFreqMax, 0, 1600);
FLOATSLIDER(mFreqMinSlider, ("freqmin" + ofToString(mIndex)).c_str(), &mData.mFreqMin, 0, 1600);
UIBLOCK_NEWLINE();
float filterAdsrWidth = DRUMSYNTH_PAD_WIDTH - 5 * 2;
UICONTROL_CUSTOM(mFilterAdsrDisplay, new ADSRDisplay(UICONTROL_BASICS(("adsrfilter" + ofToString(mIndex)).c_str()), filterAdsrWidth, 36, &mData.mFilterAdsr));
UIBLOCK_PUSHSLIDERWIDTH(filterAdsrWidth);
FLOATSLIDER(mFilterCutoffMaxSlider, ("cutoffmax" + ofToString(mIndex)).c_str(), &mData.mCutoffMax, 10, DRUMSYNTH_NO_CUTOFF);
FLOATSLIDER(mFilterCutoffMinSlider, ("cutoffmin" + ofToString(mIndex)).c_str(), &mData.mCutoffMin, 10, DRUMSYNTH_NO_CUTOFF);
FLOATSLIDER_DIGITS(mFilterQSlider, ("q" + ofToString(mIndex)).c_str(), &mData.mQ, .1, 20, 3);
ENDUIBLOCK0();
#undef UIBLOCK_OWNER
#define UIBLOCK_OWNER this //reset
mToneType->AddLabel("sin", kOsc_Sin);
mToneType->AddLabel("saw", kOsc_Saw);
mToneType->AddLabel("squ", kOsc_Square);
mToneType->AddLabel("tri", kOsc_Tri);
mFreqAdsrDisplay->SetMaxTime(500);
mToneAdsrDisplay->SetMaxTime(500);
mNoiseAdsrDisplay->SetMaxTime(500);
mFilterAdsrDisplay->SetMaxTime(500);
mFreqMaxSlider->SetMode(FloatSlider::kSquare);
mFreqMinSlider->SetMode(FloatSlider::kSquare);
mFilterCutoffMaxSlider->SetMode(FloatSlider::kSquare);
mFilterCutoffMinSlider->SetMode(FloatSlider::kSquare);
mFilterCutoffMaxSlider->SetMaxValueDisplay("none");
}
void DrumSynth::DrumSynthHit::Play(double time, float velocity)
{
float envelopeScale = ofLerp(.2f, 1, velocity);
mData.mFreqAdsr.Start(time, 1, envelopeScale);
mData.mFilterAdsr.Start(time, 1, envelopeScale);
mData.mTone.GetADSR()->Start(time, velocity, envelopeScale);
mData.mNoise.GetADSR()->Start(time, velocity, envelopeScale);
}
void DrumSynth::DrumSynthHit::Process(double time, float* out, int bufferSize, int oversampling, double sampleRate, double sampleIncrementMs)
{
if (mData.mTone.GetADSR()->IsDone(time) && mData.mNoise.GetADSR()->IsDone(time))
{
mLevel.Reset();
mPhase = 0;
return;
}
for (size_t i = 0; i < bufferSize; ++i)
{
float freq = ofLerp(mData.mFreqMin, mData.mFreqMax, mData.mFreqAdsr.Value(time));
if (mData.mCutoffMax != DRUMSYNTH_NO_CUTOFF)
{
mFilter.SetSampleRate(sampleRate);
mFilter.SetFilterParams(ofLerp(mData.mCutoffMin, mData.mCutoffMax, mData.mFilterAdsr.Value(time)), mData.mQ);
}
float phaseInc = GetPhaseInc(freq) / oversampling;
float sample = mData.mTone.Audio(time, mPhase) * mData.mVol * mData.mVol;
float noise = mData.mNoise.Audio(time, mPhase);
noise *= noise * (noise > 0 ? 1 : -1); //square but keep sign
sample += noise * mData.mVolNoise * mData.mVolNoise;
if (mData.mCutoffMax != DRUMSYNTH_NO_CUTOFF)
sample = mFilter.Filter(sample);
mLevel.Process(&sample, 1);
out[i] += sample;
mPhase += phaseInc;
while (mPhase > FTWO_PI)
{
mPhase -= FTWO_PI;
}
time += sampleIncrementMs;
}
}
void DrumSynth::DrumSynthHit::Draw()
{
/*ofSetColor(255,0,0);
ofRect(mToneAdsrDisplay->GetRect(true));
ofSetColor(0,255,0);
ofRect(mNoiseAdsrDisplay->GetRect(true));
ofSetColor(0,0,255);
ofRect(mFreqAdsrDisplay->GetRect(true));*/
mToneAdsrDisplay->Draw();
mVolSlider->Draw();
mNoiseAdsrDisplay->Draw();
mVolNoiseSlider->Draw();
mToneType->Draw();
mFreqAdsrDisplay->Draw();
mFreqMaxSlider->Draw();
mFreqMinSlider->Draw();
mFilterAdsrDisplay->Draw();
mFilterCutoffMaxSlider->Draw();
mFilterCutoffMinSlider->Draw();
mFilterQSlider->Draw();
ofPushStyle();
ofSetColor(0, 0, 0, 100);
ofFill();
if (mData.mVol == 0)
{
ofRect(mToneAdsrDisplay->GetRect(true).grow(1));
ofRect(mFreqAdsrDisplay->GetRect(true).grow(1));
ofRect(mFreqMaxSlider->GetRect(true));
ofRect(mFreqMinSlider->GetRect(true));
ofRect(mToneType->GetRect(true));
}
if (mData.mVolNoise == 0)
{
ofRect(mNoiseAdsrDisplay->GetRect(true).grow(1));
}
if (mData.mVol == 0 && mData.mVolNoise == 0)
{
ofRect(mFilterCutoffMaxSlider->GetRect(true));
}
if (mData.mCutoffMax == DRUMSYNTH_NO_CUTOFF || (mData.mVol == 0 && mData.mVolNoise == 0))
{
ofRect(mFilterAdsrDisplay->GetRect(true).grow(1));
ofRect(mFilterCutoffMinSlider->GetRect(true));
ofRect(mFilterQSlider->GetRect(true));
}
ofPopStyle();
}
DrumSynth::DrumSynthHitSerialData::DrumSynthHitSerialData()
{
mTone.GetADSR()->SetNumStages(2);
mTone.GetADSR()->GetHasSustainStage() = false;
mTone.GetADSR()->GetStageData(0).time = 1;
mTone.GetADSR()->GetStageData(0).target = 1;
mTone.GetADSR()->GetStageData(1).time = 100;
mTone.GetADSR()->GetStageData(1).target = 0;
mNoise.GetADSR()->SetNumStages(2);
mNoise.GetADSR()->GetHasSustainStage() = false;
mNoise.GetADSR()->GetStageData(0).time = 1;
mNoise.GetADSR()->GetStageData(0).target = 1;
mNoise.GetADSR()->GetStageData(1).time = 40;
mNoise.GetADSR()->GetStageData(1).target = 0;
mFreqAdsr.SetNumStages(2);
mFreqAdsr.GetHasSustainStage() = false;
mFreqAdsr.GetStageData(0).time = 1;
mFreqAdsr.GetStageData(0).target = 1;
mFreqAdsr.GetStageData(1).time = 500;
mFreqAdsr.GetStageData(1).target = 0;
mFilterAdsr.SetNumStages(2);
mFilterAdsr.GetHasSustainStage() = false;
mFilterAdsr.GetStageData(0).time = 1;
mFilterAdsr.GetStageData(0).target = 1;
mFilterAdsr.GetStageData(1).time = 500;
mFilterAdsr.GetStageData(1).target = 0;
}
``` | /content/code_sandbox/Source/DrumSynth.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 4,660 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteStrummer.h
Created: 2 Apr 2018 9:27:16pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "NoteEffectBase.h"
#include "Slider.h"
#include "Transport.h"
class NoteStrummer : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller
{
public:
NoteStrummer();
virtual ~NoteStrummer();
static IDrawableModule* Create() { return new NoteStrummer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 200;
height = 35;
}
float mStrum{ 0 };
float mLastStrumPos{ 0 };
FloatSlider* mStrumSlider{ nullptr };
std::list<int> mNotes;
};
``` | /content/code_sandbox/Source/NoteStrummer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 471 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// VelocityCurve.cpp
// Bespoke
//
// Created by Ryan Challinor on 4/17/22.
//
//
#include "VelocityCurve.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
namespace
{
const int kAdsrTime = 10000;
}
VelocityCurve::VelocityCurve()
{
mEnvelopeControl.SetADSR(&mAdsr);
mEnvelopeControl.SetViewLength(kAdsrTime);
mEnvelopeControl.SetFixedLengthMode(true);
mAdsr.GetFreeReleaseLevel() = true;
mAdsr.SetNumStages(2);
mAdsr.GetHasSustainStage() = false;
mAdsr.GetStageData(0).target = 0;
mAdsr.GetStageData(0).time = 0.01f;
mAdsr.GetStageData(1).target = 1;
mAdsr.GetStageData(1).time = kAdsrTime - .02f;
}
void VelocityCurve::CreateUIControls()
{
IDrawableModule::CreateUIControls();
}
void VelocityCurve::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mEnvelopeControl.Draw();
const double kDisplayInputMs = 400;
if (gTime < mLastInputTime + kDisplayInputMs)
{
float pos = mLastInputVelocity / 127.0f * mEnvelopeControl.GetDimensions().x + mEnvelopeControl.GetPosition().x;
ofPushStyle();
ofSetColor(0, 255, 0, (1 - (gTime - mLastInputTime) / kDisplayInputMs) * 255);
ofLine(pos, mEnvelopeControl.GetPosition().y, pos, mEnvelopeControl.GetPosition().y + mEnvelopeControl.GetDimensions().y);
ofPopStyle();
}
}
void VelocityCurve::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled)
{
if (velocity > 0)
{
mLastInputVelocity = velocity;
mLastInputTime = time;
ComputeSliders(0);
ADSR::EventInfo adsrEvent(0, kAdsrTime);
float val = ofClamp(mAdsr.Value(velocity / 127.0f * kAdsrTime, &adsrEvent), 0, 1);
if (std::isnan(val))
val = 0;
velocity = val * 127;
if (velocity <= 0)
velocity = 1;
}
}
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void VelocityCurve::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
mEnvelopeControl.OnClicked(x, y, right);
}
void VelocityCurve::MouseReleased()
{
IDrawableModule::MouseReleased();
mEnvelopeControl.MouseReleased();
}
bool VelocityCurve::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mEnvelopeControl.MouseMoved(x, y);
return false;
}
void VelocityCurve::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void VelocityCurve::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
void VelocityCurve::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mAdsr.SaveState(out);
}
void VelocityCurve::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
mAdsr.LoadState(in);
}
``` | /content/code_sandbox/Source/VelocityCurve.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 959 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// INoteSource.h
// modularSynth
//
// Created by Ryan Challinor on 12/12/12.
//
//
#pragma once
#include "readerwriterqueue.h"
#include "ModulationChain.h"
class NoteOutput;
class NoteOutputQueue
{
public:
void QueuePlayNote(NoteOutput* target, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation);
void QueueFlush(NoteOutput* target, double time);
void Process();
private:
struct PendingNoteOutput
{
NoteOutput* target;
bool isFlush{ false };
double time{ 0 };
int pitch{ 0 };
int velocity{ 0 };
int voiceIdx{ -1 };
ModulationParameters modulation{};
};
moodycamel::ReaderWriterQueue<PendingNoteOutput> mQueue;
};
``` | /content/code_sandbox/Source/NoteOutputQueue.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 277 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// DropdownList.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/18/12.
//
//
#include "DropdownList.h"
#include "SynthGlobals.h"
#include "FileStream.h"
#include "ModularSynth.h"
#include "Push2Control.h"
DropdownList::DropdownList(IDropdownListener* owner, const char* name, int x, int y, int* var, float width)
: mVar(var)
, mLastSetValue(*var)
, mModalList(this)
, mOwner(owner)
{
assert(owner);
SetName(name);
mLabelSize = GetStringWidth(name) + 3;
SetPosition(x, y);
SetParent(dynamic_cast<IClickable*>(owner));
(dynamic_cast<IDrawableModule*>(owner))->AddUIControl(this);
mModalList.SetTypeName("dropdownlist", kModuleCategory_Other);
if (width == -1)
mAutoCalculateWidth = true;
else
mWidth = width;
}
DropdownList::DropdownList(IDropdownListener* owner, const char* name, IUIControl* anchor, AnchorDirection anchorDirection, int* var, float width)
: DropdownList(owner, name, -1, -1, var, width)
{
PositionTo(anchor, anchorDirection);
}
DropdownList::~DropdownList()
{
}
void DropdownList::AddLabel(std::string label, int value)
{
DropdownListElement element;
element.mLabel = label;
element.mValue = value;
mElements.push_back(element);
CalculateWidth();
mHeight = kItemSpacing;
CalcSliderVal();
}
void DropdownList::RemoveLabel(int value)
{
for (auto iter = mElements.begin(); iter != mElements.end(); ++iter)
{
if (iter->mValue == value)
{
mElements.erase(iter);
CalculateWidth();
mHeight = kItemSpacing;
CalcSliderVal();
break;
}
}
}
void DropdownList::SetLabel(std::string label, int value)
{
bool found = false;
for (auto iter = mElements.begin(); iter != mElements.end(); ++iter)
{
if (iter->mValue == value)
{
found = true;
iter->mLabel = label;
CalculateWidth();
mHeight = kItemSpacing;
CalcSliderVal();
break;
}
}
if (!found)
AddLabel(label, value);
}
void DropdownList::CalculateWidth()
{
mMaxItemWidth = mWidth;
for (int i = 0; i < mElements.size(); ++i)
{
int width = GetStringWidth(mElements[i].mLabel) + (mDrawTriangle ? 15 : 3);
if (width > mMaxItemWidth)
mMaxItemWidth = width;
}
if (mAutoCalculateWidth)
mWidth = MIN(mMaxItemWidth, 180);
}
void DropdownList::SetWidth(int width)
{
if (width != mWidth)
{
mWidth = width;
CalculateWidth();
}
}
std::string DropdownList::GetLabel(int val) const
{
for (int i = 0; i < mElements.size(); ++i)
{
if (mElements[i].mValue == val)
return mElements[i].mLabel;
}
return "";
}
void DropdownList::Poll()
{
if (*mVar != mLastSetValue)
CalcSliderVal();
mDropdownIsOpen = (TheSynth->GetTopModalFocusItem() == &mModalList);
}
void DropdownList::Render()
{
ofPushStyle();
float w, h;
GetDimensions(w, h);
ofColor color, textColor;
IUIControl::GetColors(color, textColor);
float xOffset = 0;
if (mDisplayStyle == DropdownDisplayStyle::kNormal)
{
if (mDrawLabel)
{
DrawTextNormal(Name(), mX, mY + 12);
xOffset = mLabelSize;
}
DrawBeacon(mX + mWidth / 2 + xOffset, mY + mHeight / 2);
ofFill();
ofSetColor(0, 0, 0, gModuleDrawAlpha * .5f);
ofRect(mX + 1 + xOffset, mY + 1, w - xOffset, h);
ofSetColor(color);
ofRect(mX + xOffset, mY, w - xOffset, h);
ofNoFill();
ofSetColor(textColor);
ofPushMatrix();
ofClipWindow(mX, mY, w - (mDrawTriangle ? 12 : 0), h, true);
DrawTextNormal(GetDisplayValue(*mVar), mX + 2 + xOffset, mY + 12);
ofPopMatrix();
if (mDrawTriangle)
{
ofSetLineWidth(.5f);
ofTriangle(mX + w - 11, mY + 4, mX + w - 3, mY + 4, mX + w - 7, mY + 11);
}
}
else if (mDisplayStyle == DropdownDisplayStyle::kHamburger)
{
ofSetColor(textColor);
ofSetLineWidth(1.0f);
ofLine(mX + 6, mY + 4.5f, mX + 14, mY + 4.5f);
ofLine(mX + 6, mY + 7.5f, mX + 14, mY + 7.5f);
ofLine(mX + 6, mY + 10.5f, mX + 14, mY + 10.5f);
}
ofPopStyle();
DrawHover(mX + xOffset, mY, w - xOffset, h);
if (mLastScrolledTime + 300 > gTime && TheSynth->GetTopModalFocusItem() != &mModalList && !Push2Control::sDrawingPush2Display)
{
const float kCentering = 7;
float pw, ph;
GetPopupDimensions(pw, ph);
mModalList.SetPosition(0, 0);
ofPushMatrix();
ofTranslate(mX, mY + kCentering - ph * mSliderVal);
mModalList.SetIsScrolling(true);
mModalList.Render();
mModalList.SetIsScrolling(false);
ofPopMatrix();
ofPushStyle();
ofFill();
ofColor categoryColor = IDrawableModule::GetColor(GetModuleParent()->GetModuleCategory());
categoryColor.a = 80;
ofSetColor(categoryColor);
ofRect(mX, mY, pw, mHeight);
ofPopStyle();
}
}
void DropdownList::DrawDropdown(int w, int h, bool isScrolling)
{
ofPushStyle();
if (isScrolling)
mModalList.SetDimensions(mMaxItemWidth, (int)mElements.size() * kItemSpacing);
int hoverIndex = -1;
float dropdownW, dropdownH;
mModalList.GetDimensions(dropdownW, dropdownH);
if (mModalList.GetMouseX() >= 0 && mModalList.GetMouseY() >= 0 && mModalList.GetMouseX() < dropdownW && mModalList.GetMouseY() < dropdownH)
hoverIndex = GetItemIndexAt(mModalList.GetMouseX(), mModalList.GetMouseY());
int maxPerColumn = mMaxPerColumn;
int displayColumns = mDisplayColumns;
int totalColumns = mTotalColumns;
int currentPagedColumn = mCurrentPagedColumn;
if (isScrolling)
{
maxPerColumn = 9999;
displayColumns = 1;
totalColumns = 1;
mCurrentPagedColumn = 0;
}
bool paged = (displayColumns < totalColumns);
float pageHeaderShift = (paged ? kPageBarSpacing : 0);
mModalList.SetShowPagingControls(paged);
ofSetColor(0, 0, 0);
ofFill();
ofRect(0, 0, w, h);
for (int i = 0; i < mElements.size(); ++i)
{
int col = i / maxPerColumn - currentPagedColumn;
if (col < 0)
continue;
if (col >= displayColumns)
break;
if (i == hoverIndex)
{
ofSetColor(100, 100, 100, 100);
ofRect(mMaxItemWidth * col, (i % maxPerColumn) * kItemSpacing + pageHeaderShift, mMaxItemWidth, kItemSpacing);
}
if (VectorContains(i, mSeparators))
{
ofPushStyle();
ofSetColor(100, 100, 100, 100);
ofSetLineWidth(1);
ofLine(mMaxItemWidth * col + 3, (i % maxPerColumn) * kItemSpacing + pageHeaderShift, mMaxItemWidth * (col + 1) - 3, (i % maxPerColumn) * kItemSpacing + pageHeaderShift);
ofPopStyle();
}
if (mVar && mElements[i].mValue == *mVar)
ofSetColor(255, 255, 0);
else
ofSetColor(255, 255, 255);
DrawTextNormal(mElements[i].mLabel, 1 + mMaxItemWidth * col, (i % maxPerColumn) * kItemSpacing + 12 + pageHeaderShift);
}
ofSetColor(255, 255, 255);
if (paged)
{
DrawTextNormal("page " + ofToString(mCurrentPagedColumn / displayColumns + 1) + "/" + ofToString(totalColumns / displayColumns + 1), 30, 14);
}
ofSetLineWidth(.5f);
ofNoFill();
ofRect(0, 0, w, h);
ofPopStyle();
}
void DropdownList::ChangePage(int direction)
{
int newColumn = mCurrentPagedColumn + direction * mDisplayColumns;
if (newColumn >= 0 && newColumn < ceil(float(mTotalColumns) / mDisplayColumns) * mDisplayColumns)
mCurrentPagedColumn = newColumn;
}
void DropdownList::CopyContentsTo(DropdownList* list) const
{
list->Clear();
for (auto& element : mElements)
list->AddLabel(element.mLabel, element.mValue);
}
void DropdownList::GetDimensions(float& width, float& height)
{
width = mWidth;
if (mDrawLabel)
width += mLabelSize;
height = mHeight;
}
bool DropdownList::DropdownClickedAt(int x, int y)
{
int index = GetItemIndexAt(x, y);
if (index >= 0 && index < mElements.size())
{
SetIndex(index, NextBufferTime(false), K(forceUpdate));
return true;
}
return false;
}
namespace
{
float ToScreenPosX(float x, IDrawableModule* parent)
{
return (x + parent->GetOwningContainer()->GetDrawOffset().x) * parent->GetOwningContainer()->GetDrawScale();
}
float ToScreenPosY(float y, IDrawableModule* parent)
{
return (y + parent->GetOwningContainer()->GetDrawOffset().y) * parent->GetOwningContainer()->GetDrawScale();
}
float FromScreenPosX(float x, IDrawableModule* parent)
{
return (x / parent->GetOwningContainer()->GetDrawScale()) - parent->GetOwningContainer()->GetDrawOffset().x;
}
}
void DropdownList::OnClicked(float x, float y, bool right)
{
if (right || mDropdownIsOpen)
return;
mOwner->DropdownClicked(this);
if (mElements.empty())
return;
mModalList.SetUpModal();
ofVec2f modalPos = GetModalListPosition();
mModalList.SetOwningContainer(GetModuleParent()->GetOwningContainer());
float screenY = (modalPos.y + GetModuleParent()->GetOwningContainer()->GetDrawOffset().y) * GetModuleParent()->GetOwningContainer()->GetDrawScale();
float maxX = ofGetWidth() - 5;
float maxY = ofGetHeight() - 5;
const int kMinPerColumn = 3;
mMaxPerColumn = std::max(kMinPerColumn, int((maxY - screenY) / (kItemSpacing * GetModuleParent()->GetOwningContainer()->GetDrawScale()))) - 1;
mTotalColumns = 1 + ((int)mElements.size() - 1) / mMaxPerColumn;
int maxDisplayColumns = std::max(1, int((ofGetWidth() / GetModuleParent()->GetOwningContainer()->GetDrawScale()) / mMaxItemWidth));
mDisplayColumns = std::min(mTotalColumns, maxDisplayColumns);
mCurrentPagedColumn = 0;
bool paged = (mDisplayColumns < mTotalColumns);
ofVec2f modalDimensions(mMaxItemWidth * mDisplayColumns, kItemSpacing * std::min((int)mElements.size(), mMaxPerColumn + (paged ? 1 : 0)));
modalPos.x = std::max(FromScreenPosX(5.0f, GetModuleParent()), std::min(modalPos.x, FromScreenPosX(maxX - modalDimensions.x * GetModuleParent()->GetOwningContainer()->GetDrawScale(), GetModuleParent())));
mModalList.SetPosition(modalPos.x, modalPos.y);
mModalList.SetDimensions(modalDimensions.x, modalDimensions.y);
TheSynth->PushModalFocusItem(&mModalList);
}
int DropdownList::GetItemIndexAt(int x, int y)
{
bool paged = (mDisplayColumns < mTotalColumns);
int indexOffset = 0;
if (paged)
{
y -= kPageBarSpacing;
if (y < 0)
return -1;
indexOffset = mCurrentPagedColumn * mMaxPerColumn;
}
return y / kItemSpacing + x / mMaxItemWidth * mMaxPerColumn + indexOffset;
}
ofVec2f DropdownList::GetModalListPosition() const
{
float thisx, thisy;
GetPosition(thisx, thisy);
if (mDrawLabel)
thisx += mLabelSize;
return ofVec2f(thisx, thisy + kItemSpacing);
}
bool DropdownList::MouseMoved(float x, float y)
{
CheckHover(x, y);
return false;
}
void DropdownList::MouseReleased()
{
}
void DropdownList::Clear()
{
mElements.clear();
if (mAutoCalculateWidth)
mWidth = 35;
mHeight = kItemSpacing;
}
void DropdownList::SetFromMidiCC(float slider, double time, bool setViaModulator)
{
slider = ofClamp(slider, 0, 1);
SetIndex(int(slider * mElements.size()), time, false);
mSliderVal = slider;
mLastSetValue = *mVar;
if (!setViaModulator)
mLastScrolledTime = time; //don't do scrolling display if a modulator is changing our value
}
float DropdownList::GetValueForMidiCC(float slider) const
{
if (mElements.empty())
return 0;
int index = int(slider * mElements.size());
index = ofClamp(index, 0, mElements.size() - 1);
return mElements[index].mValue;
}
void DropdownList::SetIndex(int i, double time, bool forceUpdate)
{
if (mElements.empty())
return;
i = ofClamp(i, 0, mElements.size() - 1);
SetValue(mElements[i].mValue, time, forceUpdate);
}
void DropdownList::SetValue(float value, double time, bool forceUpdate /*= false*/)
{
int intValue = (int)value;
if (intValue != *mVar || forceUpdate)
{
int oldVal = *mVar;
*mVar = intValue;
CalcSliderVal();
gControlTactileFeedback = 1;
mOwner->DropdownUpdated(this, oldVal, time);
}
}
float DropdownList::GetValue() const
{
return *mVar;
}
float DropdownList::GetMidiValue() const
{
return mSliderVal;
}
int DropdownList::FindItemIndex(float val) const
{
for (int i = 0; i < mElements.size(); ++i)
{
if (mElements[i].mValue == val)
return i;
}
return -1;
}
std::string DropdownList::GetDisplayValue(float val) const
{
int itemIndex = FindItemIndex(val);
if (itemIndex >= 0 && itemIndex < mElements.size())
return mElements[itemIndex].mLabel;
else
return mUnknownItemString.c_str();
}
void DropdownList::CalcSliderVal()
{
int itemIndex = FindItemIndex(*mVar);
mSliderVal = ofMap(itemIndex + .5f, 0, mElements.size(), 0, 1);
mLastSetValue = *mVar;
}
void DropdownList::Increment(float amount)
{
int itemIndex = FindItemIndex(*mVar);
SetIndex(itemIndex + (int)amount, gTime, false);
}
EnumMap DropdownList::GetEnumMap()
{
EnumMap ret;
for (int i = 0; i < mElements.size(); ++i)
ret[mElements[i].mLabel] = mElements[i].mValue;
return ret;
}
namespace
{
const int kSaveStateRev = 1;
}
void DropdownList::SaveState(FileStreamOut& out)
{
out << kSaveStateRev;
out << GetLabel(*mVar);
}
void DropdownList::LoadState(FileStreamIn& in, bool shouldSetValue)
{
int rev;
in >> rev;
LoadStateValidate(rev <= kSaveStateRev);
if (rev < 1)
{
float var;
in >> var;
if (shouldSetValue)
SetValueDirect(var, gTime);
}
else
{
std::string label;
in >> label;
if (shouldSetValue)
{
for (int i = 0; i < mElements.size(); ++i)
{
if (mElements[i].mLabel == label)
{
SetIndex(i, gTime, false);
break;
}
}
}
}
}
void DropdownListModal::SetUpModal()
{
if (mPagePrevButton == nullptr)
CreateUIControls();
}
void DropdownListModal::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mPagePrevButton = new ClickButton(this, " < ", 3, 3);
mPageNextButton = new ClickButton(this, " > ", 100, 3);
}
void DropdownListModal::SetShowPagingControls(bool show)
{
if (mPagePrevButton)
mPagePrevButton->SetShowing(show);
if (mPageNextButton)
mPageNextButton->SetShowing(show);
}
void DropdownListModal::DrawModule()
{
mOwner->DrawDropdown(mWidth, mHeight, mIsScrolling);
if (mPagePrevButton)
mPagePrevButton->Draw();
if (mPageNextButton)
mPageNextButton->Draw();
}
std::string DropdownListModal::GetHoveredLabel()
{
int index = mOwner->GetItemIndexAt((int)mMouseX, (int)mMouseY);
if (index >= 0 && index < mOwner->GetNumValues())
return mOwner->GetElement(index).mLabel;
return "";
}
bool DropdownListModal::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mMouseX = x;
mMouseY = y;
return false;
}
void DropdownListModal::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (right)
return;
if (mOwner->DropdownClickedAt(x, y))
TheSynth->PopModalFocusItem();
}
void DropdownListModal::ButtonClicked(ClickButton* button, double time)
{
if (button == mPagePrevButton)
mOwner->ChangePage(-1);
if (button == mPageNextButton)
mOwner->ChangePage(1);
}
``` | /content/code_sandbox/Source/DropdownList.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 4,579 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
Prefab.h
Created: 25 Sep 2016 10:14:15am
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "ClickButton.h"
#include "ModuleContainer.h"
class PatchCableSource;
class Prefab : public IDrawableModule, public IButtonListener
{
public:
Prefab();
~Prefab();
static IDrawableModule* Create() { return new Prefab(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
std::string GetTitleLabel() const override;
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
ModuleContainer* GetContainer() override { return &mModuleContainer; }
void Poll() override;
bool ShouldClipContents() override { return false; }
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 0; }
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
void LoadPrefab(std::string loadPath);
static bool sLoadingPrefab;
static bool sLastLoadWasPrefab;
static IDrawableModule* sJustReleasedModule;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void DrawModuleUnclipped() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
void MouseReleased() override;
bool CanAddDropModules();
bool IsAddableModule(IDrawableModule* module);
bool IsMouseHovered();
void SavePrefab(std::string savePath);
void UpdatePrefabName(std::string path);
PatchCableSource* mRemoveModuleCable{ nullptr };
ClickButton* mSaveButton{ nullptr };
ClickButton* mLoadButton{ nullptr };
ClickButton* mDisbandButton{ nullptr };
ModuleContainer mModuleContainer;
std::string mPrefabName{ "" };
};
``` | /content/code_sandbox/Source/Prefab.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 672 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// SignalGenerator.cpp
// Bespoke
//
// Created by Ryan Challinor on 6/26/14.
//
//
#include "SignalGenerator.h"
#include "SynthGlobals.h"
#include "IAudioReceiver.h"
#include "ofxJSONElement.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "Scale.h"
#include "FloatSliderLFOControl.h"
#include "UIControlMacros.h"
SignalGenerator::SignalGenerator()
{
mWriteBuffer = new float[gBufferSize];
mOsc.Start(0, 1);
}
void SignalGenerator::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
UIBLOCK_PUSHSLIDERWIDTH(171);
FLOATSLIDER(mFreqSlider, "freq", &mFreq, 1, 4000);
DROPDOWN(mFreqModeSelector, "freq mode", (int*)(&mFreqMode), 55);
UIBLOCK_SHIFTRIGHT();
DROPDOWN(mOscSelector, "osc", (int*)(&mOscType), 50);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_PUSHSLIDERWIDTH(60);
FLOATSLIDER(mPulseWidthSlider, "pw", &mPulseWidth, 0.01f, .99f);
UIBLOCK_NEWLINE();
UIBLOCK_PUSHSLIDERWIDTH(80);
FLOATSLIDER(mFreqSliderAmountSlider, "slider", &mFreqSliderAmount, 0, 1);
UIBLOCK_SHIFTLEFT();
FLOATSLIDER(mFreqRampTimeSlider, "ramp", &mFreqRampTime, 0, 1000);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_SHIFTX(8);
FLOATSLIDER(mShuffleSlider, "shuffle", &mShuffle, 0, 1);
UIBLOCK_NEWLINE();
FLOATSLIDER(mSoftenSlider, "soften", &mSoften, 0, 1);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_SHIFTX(8);
FLOATSLIDER_DIGITS(mPhaseOffsetSlider, "phase", &mPhaseOffset, 0, 1, 3);
UIBLOCK_NEWLINE();
DROPDOWN(mMultSelector, "mult", &mMult, 40);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_SHIFTX(5);
DROPDOWN(mSyncModeSelector, "syncmode", (int*)(&mSyncMode), 60);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_PUSHSLIDERWIDTH(60);
FLOATSLIDER(mSyncFreqSlider, "syncf", &mSyncFreq, 10, 999.9f);
UIBLOCK_SHIFTLEFT();
FLOATSLIDER(mSyncRatioSlider, "syncratio", &mSyncRatio, .1f, 10.0f);
UIBLOCK_NEWLINE();
UIBLOCK_PUSHSLIDERWIDTH(80);
FLOATSLIDER(mVolSlider, "vol", &mVol, 0, 1);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_SHIFTX(8);
FLOATSLIDER_DIGITS(mDetuneSlider, "detune", &mDetune, -.05f, .05f, 3);
ENDUIBLOCK0();
mSyncModeSelector->AddLabel("no sync", (int)Oscillator::SyncMode::None);
mSyncModeSelector->AddLabel("ratio", (int)Oscillator::SyncMode::Ratio);
mSyncModeSelector->AddLabel("freq", (int)Oscillator::SyncMode::Frequency);
mSyncFreqSlider->SetShowName(false);
mSyncRatioSlider->SetShowName(false);
mSyncRatioSlider->SetMode(FloatSlider::kSquare);
mSyncFreqSlider->PositionTo(mSyncModeSelector, kAnchor_Right);
mSyncRatioSlider->PositionTo(mSyncModeSelector, kAnchor_Right);
SetFreqMode(kFreqMode_Instant);
mOscSelector->AddLabel("sin", kOsc_Sin);
mOscSelector->AddLabel("squ", kOsc_Square);
mOscSelector->AddLabel("tri", kOsc_Tri);
mOscSelector->AddLabel("saw", kOsc_Saw);
mOscSelector->AddLabel("-saw", kOsc_NegSaw);
mOscSelector->AddLabel("noise", kOsc_Random);
mMultSelector->AddLabel("1/8", -8);
mMultSelector->AddLabel("1/7", -7);
mMultSelector->AddLabel("1/6", -6);
mMultSelector->AddLabel("1/5", -5);
mMultSelector->AddLabel("1/4", -4);
mMultSelector->AddLabel("1/3", -3);
mMultSelector->AddLabel("1/2", -2);
mMultSelector->AddLabel("1", 1);
mMultSelector->AddLabel("2", 2);
mMultSelector->AddLabel("3", 3);
mMultSelector->AddLabel("4", 4);
mMultSelector->AddLabel("5", 5);
mMultSelector->AddLabel("6", 6);
mMultSelector->AddLabel("7", 7);
mMultSelector->AddLabel("8", 8);
mFreqModeSelector->AddLabel("instant", kFreqMode_Instant);
mFreqModeSelector->AddLabel("ramp", kFreqMode_Ramp);
mFreqModeSelector->AddLabel("slider", kFreqMode_Slider);
mFreqSlider->SetMode(FloatSlider::kSquare);
mFreqRampTimeSlider->SetMode(FloatSlider::kSquare);
mSoftenSlider->SetShowing(mOscType == kOsc_Square || mOscType == kOsc_Saw || mOscType == kOsc_NegSaw);
}
SignalGenerator::~SignalGenerator()
{
delete[] mWriteBuffer;
}
void SignalGenerator::Process(double time)
{
PROFILER(SignalGenerator);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
int bufferSize = target->GetBuffer()->BufferSize();
float* out = target->GetBuffer()->GetChannel(0);
assert(bufferSize == gBufferSize);
Clear(mWriteBuffer, gBufferSize);
for (int pos = 0; pos < bufferSize; ++pos)
{
ComputeSliders(pos);
if (mResetPhaseAtMs > 0 && time > mResetPhaseAtMs)
{
mPhase = mPhaseOffset;
mResetPhaseAtMs = -9999;
}
float volSq = mVol * mVol;
if (mFreqMode == kFreqMode_Root)
mFreq = TheScale->PitchToFreq(TheScale->ScaleRoot() + 24);
else if (mFreqMode == kFreqMode_Ramp)
mFreq = mFreqRamp.Value(time);
else if (mFreqMode == kFreqMode_Slider)
mFreq = ofLerp(mFreqSliderStart, mFreqSliderEnd, mFreqSliderAmount);
float mult = mMult;
if (mult < 0)
mult = -1.0f / mult;
float outputFreq = mFreq * exp2(mDetune) * mult;
float phaseInc = GetPhaseInc(outputFreq);
float syncPhaseInc = 0;
if (mSyncMode == Oscillator::SyncMode::Frequency)
syncPhaseInc = GetPhaseInc(mSyncFreq);
else if (mSyncMode == Oscillator::SyncMode::Ratio)
syncPhaseInc = GetPhaseInc(outputFreq * mSyncRatio);
mPhase += phaseInc;
if (mPhase == INFINITY)
{
ofLog() << "Infinite phase.";
}
else
{
while (mPhase > FTWO_PI * 2)
{
mPhase -= FTWO_PI * 2;
mSyncPhase = 0;
}
}
mSyncPhase += syncPhaseInc;
if (mSyncMode != Oscillator::SyncMode::None)
mWriteBuffer[pos] += mOsc.Audio(time, mSyncPhase) * volSq;
else
mWriteBuffer[pos] += mOsc.Audio(time, mPhase + mPhaseOffset * FTWO_PI) * volSq;
time += gInvSampleRateMs;
}
GetVizBuffer()->WriteChunk(mWriteBuffer, bufferSize, 0);
Add(out, mWriteBuffer, bufferSize);
}
void SignalGenerator::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (velocity > 0)
{
if (mFreqMode == kFreqMode_Instant)
{
mFreq = TheScale->PitchToFreq(pitch);
}
else if (mFreqMode == kFreqMode_Ramp)
{
mFreqRamp.Start(time, TheScale->PitchToFreq(pitch), time + mFreqRampTime);
}
else if (mFreqMode == kFreqMode_Slider)
{
float freq = TheScale->PitchToFreq(pitch);
if (freq >= mFreq)
{
mFreqSliderAmount = 0;
mFreqSliderStart = mFreq;
mFreqSliderEnd = freq;
}
else
{
mFreqSliderAmount = 1;
mFreqSliderStart = freq;
mFreqSliderEnd = mFreq;
}
}
}
}
void SignalGenerator::OnPulse(double time, float velocity, int flags)
{
mResetPhaseAtMs = time;
}
void SignalGenerator::SetEnabled(bool enabled)
{
mEnabled = enabled;
}
void SignalGenerator::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mSyncFreqSlider->SetShowing(mSyncMode == Oscillator::SyncMode::Frequency);
mSyncRatioSlider->SetShowing(mSyncMode == Oscillator::SyncMode::Ratio);
mVolSlider->Draw();
mPulseWidthSlider->Draw();
mShuffleSlider->Draw();
mMultSelector->Draw();
mSyncModeSelector->Draw();
mSyncFreqSlider->Draw();
mSyncRatioSlider->Draw();
mOscSelector->Draw();
mDetuneSlider->Draw();
mFreqSlider->Draw();
mFreqModeSelector->Draw();
mFreqSliderAmountSlider->Draw();
mFreqRampTimeSlider->Draw();
mSoftenSlider->Draw();
mPhaseOffsetSlider->Draw();
}
void SignalGenerator::GetModuleDimensions(float& width, float& height)
{
width = 180;
height = 108;
}
void SignalGenerator::SetType(OscillatorType type)
{
mOscType = type;
mOsc.SetType(type);
}
void SignalGenerator::SetFreqMode(SignalGenerator::FreqMode mode)
{
mFreqMode = mode;
mFreqSliderAmountSlider->SetShowing(mFreqMode == kFreqMode_Slider);
mFreqRampTimeSlider->SetShowing(mFreqMode == kFreqMode_Ramp);
if (mFreqMode == kFreqMode_Slider)
{
mFreqSliderAmount = 0;
mFreqSliderStart = mFreq;
mFreqSliderEnd = mFreq;
}
if (mFreqMode == kFreqMode_Ramp)
{
mFreqRamp.SetValue(mFreq);
}
}
void SignalGenerator::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadFloat("vol", moduleInfo, 0, mVolSlider);
mModuleSaveData.LoadEnum<OscillatorType>("osc", moduleInfo, kOsc_Sin, mOscSelector);
mModuleSaveData.LoadFloat("detune", moduleInfo, 0, mDetuneSlider);
mModuleSaveData.LoadEnum<FreqMode>("freq_mode", moduleInfo, kFreqMode_Instant, mFreqModeSelector);
SetUpFromSaveData();
}
void SignalGenerator::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
SetVol(mModuleSaveData.GetFloat("vol"));
SetType(mModuleSaveData.GetEnum<OscillatorType>("osc"));
mDetune = mModuleSaveData.GetFloat("detune");
SetFreqMode(mModuleSaveData.GetEnum<FreqMode>("freq_mode"));
}
void SignalGenerator::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mOscSelector)
{
mOsc.SetType(mOscType);
mSoftenSlider->SetShowing(mOscType == kOsc_Square || mOscType == kOsc_Saw || mOscType == kOsc_NegSaw);
}
if (list == mFreqModeSelector)
SetFreqMode(mFreqMode);
}
void SignalGenerator::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mPulseWidthSlider)
mOsc.SetPulseWidth(mPulseWidth);
if (slider == mShuffleSlider)
mOsc.mOsc.SetShuffle(mShuffle);
if (slider == mFreqSlider)
{
if (mFreqMode == kFreqMode_Ramp)
mFreqRamp.Start(time, mFreq, time + mFreqRampTime);
}
if (slider == mSoftenSlider)
mOsc.mOsc.SetSoften(mSoften);
}
void SignalGenerator::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void SignalGenerator::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void SignalGenerator::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
}
void SignalGenerator::LoadState(FileStreamIn& in, int rev)
{
mLoadRev = rev;
IDrawableModule::LoadState(in, rev);
}
bool SignalGenerator::LoadOldControl(FileStreamIn& in, std::string& oldName)
{
if (mLoadRev < 1)
{
if (oldName == "sync")
{
//load checkbox
int checkboxRev;
in >> checkboxRev;
float checkboxVal;
in >> checkboxVal;
if (checkboxVal > 0)
mSyncMode = Oscillator::SyncMode::Frequency;
else
mSyncMode = Oscillator::SyncMode::None;
return true;
}
}
return false;
}
``` | /content/code_sandbox/Source/SignalGenerator.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,293 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// HelpDisplay.cpp
// Bespoke
//
// Created by Ryan Challinor on 2/7/15.
//
//
#include "HelpDisplay.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "TitleBar.h"
#include "EffectChain.h"
#include "UserPrefs.h"
#include "VersionInfo.h"
#include "juce_gui_basics/juce_gui_basics.h"
#include "juce_opengl/juce_opengl.h"
bool HelpDisplay::sShowTooltips = false;
bool HelpDisplay::sTooltipsLoaded = false;
std::list<HelpDisplay::ModuleTooltipInfo> HelpDisplay::sTooltips;
HelpDisplay::HelpDisplay()
{
LoadHelp();
sShowTooltips = UserPrefs.show_tooltips_on_load.Get();
LoadTooltips();
}
void HelpDisplay::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mShowTooltipsCheckbox = new Checkbox(this, "show tooltips", 3, 22, &sShowTooltips);
mCopyBuildInfoButton = new ClickButton(this, "copy build info", mShowTooltipsCheckbox, kAnchor_Right);
mDumpModuleInfoButton = new ClickButton(this, "dump module info", 200, 22);
mDoModuleScreenshotsButton = new ClickButton(this, "do screenshots", mDumpModuleInfoButton, kAnchor_Right);
mDoModuleDocumentationButton = new ClickButton(this, "do documentation", mDoModuleScreenshotsButton, kAnchor_Right);
mTutorialVideoLinkButton = new ClickButton(this, "youtu.be/SYBc8X2IxqM", 160, 61);
mDocsLinkButton = new ClickButton(this, "bespokesynth.com/docs", 95, 80);
mDiscordLinkButton = new ClickButton(this, "bespoke discord", 304, 80);
//mDumpModuleInfo->SetShowing(false);
}
HelpDisplay::~HelpDisplay()
{
}
void HelpDisplay::LoadHelp()
{
juce::File file(ofToResourcePath("help.txt").c_str());
if (file.existsAsFile())
{
std::string help = file.loadFileAsString().toStdString();
ofStringReplace(help, "\r", "");
mHelpText = ofSplitString(help, "\n");
}
mMaxScrollAmount = (int)mHelpText.size() * 14;
}
void HelpDisplay::DrawModule()
{
ofPushStyle();
ofSetColor(50, 50, 50, 200);
ofFill();
ofRect(0, 0, mWidth, mHeight);
ofPopStyle();
DrawTextRightJustify(GetBuildInfoString(), mWidth - 5, 12);
mShowTooltipsCheckbox->Draw();
mCopyBuildInfoButton->Draw();
mDumpModuleInfoButton->SetShowing(GetKeyModifiers() == kModifier_Shift);
mDumpModuleInfoButton->Draw();
mDoModuleScreenshotsButton->SetShowing(GetKeyModifiers() == kModifier_Shift);
mDoModuleScreenshotsButton->Draw();
mDoModuleDocumentationButton->SetShowing(GetKeyModifiers() == kModifier_Shift);
mDoModuleDocumentationButton->Draw();
DrawTextNormal("video overview available at:", 4, 73);
mTutorialVideoLinkButton->Draw();
DrawTextNormal("documentation:", 4, 92);
mDocsLinkButton->Draw();
DrawTextNormal("join the ", 260, 92);
mDiscordLinkButton->Draw();
mHeight = 100;
const int kLineHeight = 14;
ofClipWindow(0, mHeight, mWidth, (int)mHelpText.size() * kLineHeight, true);
for (size_t i = 0; i < mHelpText.size(); ++i)
{
DrawTextNormal(mHelpText[i], 4, mHeight - mScrollOffsetY);
mHeight += 14;
}
ofResetClipWindow();
if (mScreenshotCountdown <= 0)
{
if (mScreenshotState == ScreenshotState::WaitingForScreenshot)
{
std::string typeName = mScreenshotsToProcess.begin()->mLabel;
mScreenshotsToProcess.pop_front();
ofRectangle rect = mScreenshotModule->GetRect();
rect.y -= IDrawableModule::TitleBarHeight();
rect.height += IDrawableModule::TitleBarHeight();
rect.grow(10);
RenderScreenshot(rect.x, rect.y, rect.width, rect.height, typeName + ".png");
mScreenshotCountdown = 10;
if (!mScreenshotsToProcess.empty())
mScreenshotState = ScreenshotState::WaitingForSpawn;
else
mScreenshotState = ScreenshotState::None;
}
}
else
{
--mScreenshotCountdown;
}
}
void HelpDisplay::Poll()
{
if (mScreenshotState == ScreenshotState::WaitingForSpawn)
{
if (mScreenshotModule != nullptr)
mScreenshotModule->GetOwningContainer()->DeleteModule(mScreenshotModule);
mScreenshotModule = TheSynth->SpawnModuleOnTheFly(mScreenshotsToProcess.front(), 100, 300);
if (mScreenshotsToProcess.front().mLabel == "drumplayer")
mScreenshotModule->FindUIControl("edit")->SetValue(1, gTime);
mScreenshotState = ScreenshotState::WaitingForScreenshot;
mScreenshotCountdown = 10;
}
}
bool HelpDisplay::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll)
{
mScrollOffsetY = ofClamp(mScrollOffsetY - scrollY * 10, 0, mMaxScrollAmount);
return true;
}
void HelpDisplay::GetModuleDimensions(float& w, float& h)
{
if (mScreenshotsToProcess.size() > 0)
{
w = 10;
h = 10;
}
else
{
w = mWidth;
h = mHeight;
}
}
void HelpDisplay::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mShowTooltipsCheckbox)
{
if (sShowTooltips) // && !mTooltipsLoaded)
LoadTooltips();
}
}
void HelpDisplay::LoadTooltips()
{
sTooltips.clear();
ModuleTooltipInfo moduleInfo;
UIControlTooltipInfo controlInfo;
juce::File tooltipsFile(ofToResourcePath(UserPrefs.tooltips.Get()));
if (tooltipsFile.existsAsFile())
{
juce::StringArray lines;
tooltipsFile.readLines(lines);
for (int i = 0; i < lines.size(); ++i)
{
if (lines[i].isNotEmpty())
{
juce::String line = lines[i].replace("\\n", "\n");
std::vector<std::string> tokens = ofSplitString(line.toStdString(), "~");
if (tokens.size() == 2)
{
if (!moduleInfo.module.empty())
sTooltips.push_back(moduleInfo); //add this one and start a new one
moduleInfo.module = tokens[0];
moduleInfo.tooltip = tokens[1];
moduleInfo.controlTooltips.clear();
}
else if (tokens.size() == 3)
{
controlInfo.controlName = tokens[1];
controlInfo.tooltip = tokens[2];
moduleInfo.controlTooltips.push_back(controlInfo);
}
}
}
}
sTooltips.push_back(moduleInfo); //get the last one
sTooltipsLoaded = true;
}
HelpDisplay::ModuleTooltipInfo* HelpDisplay::FindModuleInfo(std::string moduleTypeName)
{
for (auto& info : sTooltips)
{
if (info.module == moduleTypeName)
return &info;
}
return nullptr;
}
namespace
{
bool StringMatch(juce::String pattern, juce::String target)
{
/*if (pattern.endsWithChar('*'))
{
ppattern = pattern.removeCharacters("*");
return target.startsWith(pattern);
}
else
{
return pattern == target;
}*/
int m = pattern.length();
int n = target.length();
// empty pattern can only match with
// empty string
if (m == 0)
return (n == 0);
// lookup table for storing results of
// subproblems
std::vector<std::vector<bool>> lookup(n + 1, std::vector<bool>(m + 1));
// empty pattern can match with empty string
lookup[0][0] = true;
// Only '*' can match with empty string
for (int j = 1; j <= m; j++)
if (pattern[j - 1] == '*')
lookup[0][j] = lookup[0][j - 1];
// fill the table in bottom-up fashion
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
// Two cases if we see a '*'
// a) We ignore * character and move
// to next character in the pattern,
// i.e., * indicates an empty sequence.
// b) '*' character matches with ith
// character in input
if (pattern[j - 1] == '*')
lookup[i][j] = lookup[i][j - 1] || lookup[i - 1][j];
else if (target[i - 1] == pattern[j - 1])
lookup[i][j] = lookup[i - 1][j - 1];
// If characters don't match
else
lookup[i][j] = false;
}
}
return lookup[n][m];
}
}
HelpDisplay::UIControlTooltipInfo* HelpDisplay::FindControlInfo(IUIControl* control)
{
ModuleTooltipInfo* moduleInfo = nullptr;
IDrawableModule* parent = dynamic_cast<IDrawableModule*>(control->GetParent());
if (parent != nullptr)
moduleInfo = FindModuleInfo(parent->GetTypeName());
if (moduleInfo)
{
std::string controlName = control->Name();
for (auto& info : moduleInfo->controlTooltips)
{
if (StringMatch(info.controlName, controlName))
return &info;
}
}
//didn't find it, try again with the "module parent"
parent = control->GetModuleParent();
if (parent != nullptr)
moduleInfo = FindModuleInfo(parent->GetTypeName());
if (moduleInfo)
{
std::string controlName = control->Name();
for (auto& info : moduleInfo->controlTooltips)
{
if (StringMatch(info.controlName, controlName))
return &info;
}
}
return nullptr;
}
std::string HelpDisplay::GetUIControlTooltip(IUIControl* control)
{
std::string name = control->Name();
std::string tooltip;
UIControlTooltipInfo* controlInfo = FindControlInfo(control);
if (controlInfo && controlInfo->tooltip.size() > 0)
tooltip = controlInfo->tooltip;
else
tooltip = "[no tooltip found]";
return name + ": " + tooltip;
}
std::string HelpDisplay::GetModuleTooltip(IDrawableModule* module)
{
if (module == TheTitleBar)
return "";
return GetModuleTooltipFromName(module->GetTypeName());
}
std::string HelpDisplay::GetModuleTooltipFromName(std::string moduleTypeName)
{
std::string tooltip;
ModuleTooltipInfo* moduleInfo = FindModuleInfo(moduleTypeName);
if (moduleInfo && moduleInfo->tooltip.size() > 0)
tooltip = moduleInfo->tooltip;
else
tooltip = "[no tooltip found]";
return moduleTypeName + ": " + tooltip;
}
void HelpDisplay::ButtonClicked(ClickButton* button, double time)
{
if (button == mTutorialVideoLinkButton)
{
juce::URL("path_to_url").launchInDefaultBrowser();
}
if (button == mDocsLinkButton)
{
juce::URL("path_to_url").launchInDefaultBrowser();
}
if (button == mDiscordLinkButton)
{
juce::URL("path_to_url").launchInDefaultBrowser();
}
if (button == mCopyBuildInfoButton)
{
juce::SystemClipboard::copyTextToClipboard("bespoke " + juce::String(GetBuildInfoString()) + " - " + juce::SystemStats::getOperatingSystemName() + " - " + Bespoke::GIT_BRANCH + " " + Bespoke::GIT_HASH);
}
if (button == mDumpModuleInfoButton)
{
LoadTooltips();
std::vector<ModuleCategory> moduleTypes = {
kModuleCategory_Note,
kModuleCategory_Synth,
kModuleCategory_Audio,
kModuleCategory_Instrument,
kModuleCategory_Processor,
kModuleCategory_Modulator,
kModuleCategory_Pulse,
kModuleCategory_Other
};
for (auto type : moduleTypes)
{
const auto& modules = TheSynth->GetModuleFactory()->GetSpawnableModules(type);
for (auto toSpawn : modules)
TheSynth->SpawnModuleOnTheFly(toSpawn, 0, 0);
}
std::string output;
std::vector<IDrawableModule*> modules;
TheSynth->GetAllModules(modules);
for (auto* topLevelModule : modules)
{
if (topLevelModule->GetTypeName() == "effectchain")
{
EffectChain* effectChain = dynamic_cast<EffectChain*>(topLevelModule);
std::vector<std::string> effects = TheSynth->GetEffectFactory()->GetSpawnableEffects();
for (std::string effect : effects)
effectChain->AddEffect(effect, effect, !K(onTheFly));
}
std::vector<IDrawableModule*> toDump;
toDump.push_back(topLevelModule);
for (auto* child : topLevelModule->GetChildren())
toDump.push_back(child);
std::list<std::string> addedModuleNames;
for (auto* module : toDump)
{
if (ListContains(module->GetTypeName(), addedModuleNames) || module->GetTypeName().length() == 0)
continue;
addedModuleNames.push_back(module->GetTypeName());
std::string moduleTooltip = "[no tooltip]";
ModuleTooltipInfo* moduleInfo = FindModuleInfo(module->GetTypeName());
if (moduleInfo)
{
moduleTooltip = moduleInfo->tooltip;
ofStringReplace(moduleTooltip, "\n", "\\n");
}
output += "\n\n\n" + module->GetTypeName() + "~" + moduleTooltip + "\n";
std::vector<IUIControl*> controls = module->GetUIControls();
std::list<std::string> addedControlNames;
for (auto* control : controls)
{
if (control->GetParent() != module && VectorContains(dynamic_cast<IDrawableModule*>(control->GetParent()), toDump))
continue; //we'll print this control's info when we are printing for the specific parent module
std::string controlName = control->Name();
if (controlName != "enabled")
{
std::string controlTooltip = "[no tooltip]";
UIControlTooltipInfo* controlInfo = FindControlInfo(control);
if (controlInfo)
{
controlName = controlInfo->controlName;
controlTooltip = controlInfo->tooltip;
ofStringReplace(controlTooltip, "\n", "\\n");
}
if (!ListContains(controlName, addedControlNames))
{
output += "~" + controlName + "~" + controlTooltip + "\n";
addedControlNames.push_back(controlName);
}
}
}
}
}
juce::File moduleDump(ofToDataPath("module_dump.txt"));
moduleDump.replaceWithText(output);
}
if (button == mDoModuleScreenshotsButton)
{
/*mScreenshotsToProcess.push_back("sampleplayer");
mScreenshotsToProcess.push_back("drumplayer");
mScreenshotsToProcess.push_back("notesequencer");*/
std::vector<ModuleCategory> moduleTypes = {
kModuleCategory_Note,
kModuleCategory_Synth,
kModuleCategory_Audio,
kModuleCategory_Instrument,
kModuleCategory_Processor,
kModuleCategory_Modulator,
kModuleCategory_Pulse,
kModuleCategory_Other
};
for (auto type : moduleTypes)
{
const auto& modules = TheSynth->GetModuleFactory()->GetSpawnableModules(type);
for (auto toSpawn : modules)
mScreenshotsToProcess.push_back(toSpawn);
}
for (auto effect : TheSynth->GetEffectFactory()->GetSpawnableEffects())
{
ModuleFactory::Spawnable spawnable;
spawnable.mLabel = effect;
spawnable.mSpawnMethod = ModuleFactory::SpawnMethod::EffectChain;
mScreenshotsToProcess.push_back(spawnable);
}
mScreenshotState = ScreenshotState::WaitingForSpawn;
}
if (button == mDoModuleDocumentationButton)
{
ofxJSONElement docs;
LoadTooltips();
for (auto moduleType : sTooltips)
{
docs[moduleType.module]["description"] = moduleType.tooltip;
for (auto control : moduleType.controlTooltips)
{
docs[moduleType.module]["controls"][control.controlName] = control.tooltip;
}
std::string typeName = "unknown";
if (moduleType.module == "scale" || moduleType.module == "transport" || moduleType.module == "vstplugin")
typeName = "other";
docs[moduleType.module]["type"] = typeName;
docs[moduleType.module]["canReceiveAudio"] = false;
docs[moduleType.module]["canReceiveNote"] = false;
docs[moduleType.module]["canReceivePulses"] = false;
}
std::vector<ModuleCategory> moduleCategories = {
kModuleCategory_Note,
kModuleCategory_Synth,
kModuleCategory_Audio,
kModuleCategory_Instrument,
kModuleCategory_Processor,
kModuleCategory_Modulator,
kModuleCategory_Pulse,
kModuleCategory_Other
};
for (auto category : moduleCategories)
{
const auto& modules = TheSynth->GetModuleFactory()->GetSpawnableModules(category);
for (auto toSpawn : modules)
{
IDrawableModule* module = TheSynth->SpawnModuleOnTheFly(toSpawn, 100, 300);
std::string moduleType;
switch (module->GetModuleCategory())
{
case kModuleCategory_Note: moduleType = "note effects"; break;
case kModuleCategory_Synth: moduleType = "synths"; break;
case kModuleCategory_Audio: moduleType = "audio effects"; break;
case kModuleCategory_Instrument: moduleType = "instruments"; break;
case kModuleCategory_Processor: moduleType = "effect chain"; break;
case kModuleCategory_Modulator: moduleType = "modulators"; break;
case kModuleCategory_Pulse: moduleType = "pulse"; break;
case kModuleCategory_Other: moduleType = "other"; break;
case kModuleCategory_Unknown: moduleType = "unknown"; break;
}
docs[toSpawn.mLabel]["type"] = moduleType;
docs[toSpawn.mLabel]["canReceiveAudio"] = module->CanReceiveAudio();
docs[toSpawn.mLabel]["canReceiveNote"] = module->CanReceiveNotes();
docs[toSpawn.mLabel]["canReceivePulses"] = module->CanReceivePulses();
module->GetOwningContainer()->DeleteModule(module);
}
}
for (auto effect : TheSynth->GetEffectFactory()->GetSpawnableEffects())
docs[effect]["type"] = "effect chain";
docs.save(ofToDataPath("module_documentation.json"), true);
}
}
void HelpDisplay::ScreenshotModule(IDrawableModule* module)
{
mScreenshotModule = module;
}
void HelpDisplay::RenderScreenshot(int x, int y, int width, int height, std::string filename)
{
float scale = gDrawScale * TheSynth->GetPixelRatio();
x = (x + TheSynth->GetDrawOffset().x) * scale;
y = (y + TheSynth->GetDrawOffset().y) * scale;
width = width * scale;
height = height * scale;
unsigned char* pixels = new unsigned char[3 * (width) * (height)];
juce::gl::glReadBuffer(juce::gl::GL_BACK);
int oldAlignment;
juce::gl::glGetIntegerv(juce::gl::GL_PACK_ALIGNMENT, &oldAlignment);
juce::gl::glPixelStorei(juce::gl::GL_PACK_ALIGNMENT, 1); //tight packing
juce::gl::glReadPixels(x, ofGetHeight() * scale - y - height, width, height, juce::gl::GL_RGB, juce::gl::GL_UNSIGNED_BYTE, pixels);
juce::gl::glPixelStorei(juce::gl::GL_PACK_ALIGNMENT, oldAlignment);
juce::Image image(juce::Image::RGB, width, height, true);
for (int ix = 0; ix < width; ++ix)
{
for (int iy = 0; iy < height; ++iy)
{
int pos = (ix + (height - 1 - iy) * width) * 3;
image.setPixelAt(ix, iy, juce::Colour(pixels[pos], pixels[pos + 1], pixels[pos + 2]));
}
}
{
juce::File(ofToDataPath("screenshots")).createDirectory();
juce::File pngFile(ofToDataPath("screenshots/" + filename));
if (pngFile.existsAsFile())
pngFile.deleteFile();
juce::FileOutputStream stream(pngFile);
juce::PNGImageFormat pngWriter;
pngWriter.writeImageToStream(image, stream);
}
/*{
juce::File rawFile(ofToDataPath("screenshot.txt"));
if (rawFile.existsAsFile())
rawFile.deleteFile();
FileOutputStream stream(rawFile);
for (int i = 0; i < width*height * 3; ++i)
stream << pixels[i] << ' ';
}*/
}
``` | /content/code_sandbox/Source/HelpDisplay.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 5,027 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Arpeggiator.h
// modularSynth
//
// Created by Ryan Challinor on 12/2/12.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Transport.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "Slider.h"
#include "UIGrid.h"
#include "Scale.h"
#include "ModulationChain.h"
class Arpeggiator : public NoteEffectBase, public IDrawableModule, public ITimeListener, public IButtonListener, public IDropdownListener, public IIntSliderListener, public IFloatSliderListener, public IScaleListener
{
public:
Arpeggiator();
~Arpeggiator();
static IDrawableModule* Create() { return new Arpeggiator(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IClickable
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//ITimeListener
void OnTimeEvent(double time) override;
//IScaleListener
void OnScaleChanged() override;
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
//IDropdownListener
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
//IIntSliderListener
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void OnClicked(float x, float y, bool right) override;
std::string GetArpNoteDisplay(int pitch);
void UpdateInterval();
struct ArpNote
{
ArpNote(int _pitch, int _vel, int _voiceIdx, ModulationParameters _modulation)
: pitch(_pitch)
, vel(_vel)
, voiceIdx(_voiceIdx)
, modulation(_modulation)
{}
int pitch;
int vel;
int voiceIdx;
ModulationParameters modulation;
};
std::vector<ArpNote> mChord;
float mWidth;
float mHeight;
NoteInterval mInterval{ NoteInterval::kInterval_16n };
int mLastPitch{ -1 };
int mArpIndex{ -1 };
char mArpString[MAX_TEXTENTRY_LENGTH]{};
DropdownList* mIntervalSelector{ nullptr };
int mArpStep{ 1 };
int mArpPingPongDirection{ 1 };
IntSlider* mArpStepSlider{ nullptr };
int mCurrentOctaveOffset{ 0 };
int mOctaveRepeats{ 1 };
IntSlider* mOctaveRepeatsSlider{ nullptr };
std::array<bool, 128> mInputNotes{ false };
ofMutex mChordMutex;
TransportListenerInfo* mTransportListenerInfo{ nullptr };
};
``` | /content/code_sandbox/Source/Arpeggiator.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 929 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Lissajous.h
// Bespoke
//
// Created by Ryan Challinor on 6/26/14.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
#define NUM_LISSAJOUS_POINTS 3000
class Lissajous : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener
{
public:
Lissajous();
virtual ~Lissajous();
static IDrawableModule* Create() { return new Lissajous(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = mWidth;
h = mHeight;
}
float mWidth{ 500 };
float mHeight{ 500 };
float mScale{ 1 };
FloatSlider* mScaleSlider{ nullptr };
ofVec2f mLissajousPoints[NUM_LISSAJOUS_POINTS];
int mOffset{ 0 };
bool mAutocorrelationMode{ true };
bool mOnlyHasOneChannel{ true };
};
``` | /content/code_sandbox/Source/Lissajous.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 520 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteLatch.cpp
Created: 11 Apr 2020 3:28:14pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteLatch.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
NoteLatch::NoteLatch()
{
}
void NoteLatch::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
}
void NoteLatch::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
for (int i = 0; i < 128; ++i)
{
if (mNoteState[i])
{
PlayNoteOutput(time, i, 0);
mNoteState[i] = false;
}
}
}
}
void NoteLatch::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled)
{
if (velocity > 0)
{
if (!mNoteState[pitch])
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
else
PlayNoteOutput(time, pitch, 0, voiceIdx, modulation);
mNoteState[pitch] = !mNoteState[pitch];
}
}
else
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
}
void NoteLatch::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteLatch::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteLatch.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 459 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ChaosEngine.h
// modularSynth
//
// Created by Ryan Challinor on 11/18/13.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "DropdownList.h"
#include "Checkbox.h"
#include "ClickButton.h"
#include "ofxJSONElement.h"
#include "Scale.h"
#include "RadioButton.h"
#include "INoteSource.h"
#include "Slider.h"
#include "Chord.h"
class ChaosEngine;
extern ChaosEngine* TheChaosEngine;
class ChaosEngine : public IDrawableModule, public IDropdownListener, public IButtonListener, public IRadioButtonListener, public INoteSource, public IIntSliderListener
{
public:
ChaosEngine();
~ChaosEngine();
static IDrawableModule* Create() { return new ChaosEngine(); }
static bool CanCreate() { return TheChaosEngine == nullptr; }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void Poll() override;
void AudioUpdate();
void RestartProgression()
{
mRestarting = true;
mChordProgressionIdx = -1;
}
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void RadioButtonUpdated(RadioButton* list, int oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
struct ProgressionChord
{
ProgressionChord(int degree, int beatLength = -1)
: mDegree(degree)
, mBeatLength(beatLength)
{}
ProgressionChord(int degree, std::vector<Accidental> accidentals, int beatLength = -1)
: mDegree(degree)
, mAccidentals(accidentals)
, mBeatLength(beatLength)
{}
ProgressionChord(const ofxJSONElement& chordInfo, ScalePitches scale);
bool SameChord(const ProgressionChord& chord)
{
return mDegree == chord.mDegree &&
mAccidentals == chord.mAccidentals;
}
int mDegree{ 0 };
int mBeatLength{ -1 };
std::vector<Accidental> mAccidentals;
int mInversion{ 0 };
};
struct SongSection
{
std::string mName;
std::vector<ProgressionChord> mChords;
};
struct Song
{
std::string mName;
float mTempo{ 120 };
int mTimeSigTop{ 4 };
int mTimeSigBottom{ 4 };
int mScaleRoot{ 0 };
std::string mScaleType;
std::vector<SongSection> mSections;
};
void SetPitchColor(int pitch);
void DrawKeyboard(float x, float y);
void DrawGuitar(float x, float y);
bool IsChordRoot(int pitch);
void ReadSongs();
void UpdateProgression(int beat);
void GenerateRandomProgression();
std::vector<int> GetCurrentChordPitches();
ofRectangle GetKeyboardKeyRect(int pitch, bool& isBlackKey);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 610;
height = 700;
}
void OnClicked(float x, float y, bool right) override;
ClickButton* mChaosButton{ nullptr };
bool mTotalChaos{ false };
Checkbox* mTotalChaosCheckbox{ nullptr };
double mChaosArrivalTime{ -1 };
int mLastAudioUpdateMeasure{ -1 };
int mLastAudioUpdateBeat{ -1 };
int mBeatsLeftToChordChange{ -1 };
bool mRestarting{ false };
int mChordProgressionIdx{ -1 };
std::vector<ProgressionChord> mChordProgression;
ofMutex mProgressionMutex;
IntSlider* mChordProgressionSlider{ nullptr };
int mSectionIdx{ 0 };
RadioButton* mSectionDropdown{ nullptr };
int mSongIdx{ -1 };
DropdownList* mSongDropdown{ nullptr };
std::vector<Song> mSongs;
ClickButton* mReadSongsButton{ nullptr };
bool mPlayChord{ false };
Checkbox* mPlayChordCheckbox{ nullptr };
bool mProgress{ true };
Checkbox* mProgressCheckbox{ nullptr };
int mDegree{ 0 };
IntSlider* mDegreeSlider{ nullptr };
Chord mInputChord;
DropdownList* mRootNoteList{ nullptr };
DropdownList* mChordTypeList{ nullptr };
IntSlider* mInversionSlider{ nullptr };
std::vector<Chord> mInputChords;
ClickButton* mAddChordButton{ nullptr };
ClickButton* mRemoveChordButton{ nullptr };
ClickButton* mSetProgressionButton{ nullptr };
ClickButton* mRandomProgressionButton{ nullptr };
bool mHideBeat{ false };
Checkbox* mHideBeatCheckbox{ nullptr };
};
``` | /content/code_sandbox/Source/ChaosEngine.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,313 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Beats.h
// modularSynth
//
// Created by Ryan Challinor on 2/2/14.
//
//
#pragma once
#include <iostream>
#include "IAudioSource.h"
#include "EnvOscillator.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Slider.h"
#include "DropdownList.h"
#include "Transport.h"
#include "ClickButton.h"
#include "RadioButton.h"
#include "OpenFrameworksPort.h"
#include "BiquadFilter.h"
#include "Ramp.h"
#include "ChannelBuffer.h"
class Beats;
#define BEAT_COLUMN_WIDTH 150
struct BeatData
{
void LoadBeat(Sample* sample);
void RecalcPos(double time, bool doubleTime, int numBars);
Sample* mBeat{ nullptr };
};
class BeatColumn
{
public:
BeatColumn(Beats* owner, int index);
~BeatColumn();
void Draw(int x, int y);
void CreateUIControls();
void AddBeat(Sample* sample);
void Process(double time, ChannelBuffer* buffer, int bufferSize);
int GetNumSamples() { return (int)mSamples.size(); }
void SaveState(FileStreamOut& out);
void LoadState(FileStreamIn& in);
void RadioButtonUpdated(RadioButton* list, int oldVal, double time);
void ButtonClicked(ClickButton* button, double time);
private:
RadioButton* mSelector{ nullptr };
int mSampleIndex{ -1 };
float mVolume{ 0 };
FloatSlider* mVolumeSlider{ nullptr };
BeatData mBeatData;
int mIndex{ 0 };
float mFilter{ 0 };
FloatSlider* mFilterSlider{ nullptr };
std::array<BiquadFilter, 2> mLowpass;
std::array<BiquadFilter, 2> mHighpass;
Beats* mOwner{ nullptr };
Ramp mFilterRamp;
bool mDoubleTime{ false };
Checkbox* mDoubleTimeCheckbox{ nullptr };
int mNumBars{ 4 };
IntSlider* mNumBarsSlider{ nullptr };
std::vector<Sample*> mSamples;
float mPan{ 0 };
FloatSlider* mPanSlider{ nullptr };
ClickButton* mDeleteButton{ nullptr };
};
class Beats : public IAudioSource, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public ITimeListener, public IButtonListener, public IRadioButtonListener
{
public:
Beats();
virtual ~Beats();
static IDrawableModule* Create() { return new Beats(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
int GetNumColumns() const { return (int)mBeatColumns.size(); }
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IDrawableModule
void FilesDropped(std::vector<std::string> files, int x, int y) override;
void SampleDropped(int x, int y, Sample* sample) override;
bool CanDropSample() const override { return true; }
bool MouseMoved(float x, float y) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void RadioButtonUpdated(RadioButton* list, int oldVal, double time) override;
//ITimeListener
void OnTimeEvent(double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 2; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
ChannelBuffer mWriteBuffer;
std::vector<BeatColumn*> mBeatColumns;
int mHighlightColumn{ -1 };
};
``` | /content/code_sandbox/Source/Beats.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,111 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// RingModulator.h
// modularSynth
//
// Created by Ryan Challinor on 3/7/13.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "ClickButton.h"
#include "Slider.h"
#include "EnvOscillator.h"
#include "Ramp.h"
#include "INoteReceiver.h"
class RingModulator : public IAudioProcessor, public IDrawableModule, public IButtonListener, public IFloatSliderListener, public INoteReceiver
{
public:
RingModulator();
virtual ~RingModulator();
static IDrawableModule* Create() { return new RingModulator(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IAudioSource
void Process(double time) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 130;
height = 68;
}
ChannelBuffer mDryBuffer;
float mFreq{ 220 };
float mDryWet{ 1 };
float mVolume{ 1 };
FloatSlider* mFreqSlider{ nullptr };
FloatSlider* mDryWetSlider{ nullptr };
FloatSlider* mVolumeSlider{ nullptr };
EnvOscillator mModOsc{ kOsc_Sin };
float mPhase{ 0 };
Ramp mFreqRamp;
float mGlideTime{ 0 };
FloatSlider* mGlideSlider{ nullptr };
};
``` | /content/code_sandbox/Source/RingModulator.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 641 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// BiquadFilterEffect.cpp
// modularSynth
//
// Created by Ryan Challinor on 11/29/12.
//
//
#include "BiquadFilterEffect.h"
#include "SynthGlobals.h"
#include "FloatSliderLFOControl.h"
#include "Profiler.h"
BiquadFilterEffect::BiquadFilterEffect()
: mDryBuffer(gBufferSize)
{
}
void BiquadFilterEffect::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mTypeSelector = new RadioButton(this, "type", 4, 52, (int*)(&mBiquad[0].mType), kRadioHorizontal);
mFSlider = new FloatSlider(this, "F", 4, 4, 80, 15, &mBiquad[0].mF, 10, 4000);
mQSlider = new FloatSlider(this, "Q", 4, 20, 80, 15, &mBiquad[0].mQ, .1f, 18, 3);
mGSlider = new FloatSlider(this, "G", 4, 36, 80, 15, &mBiquad[0].mDbGain, -96, 96, 1);
mTypeSelector->AddLabel("lp", kFilterType_Lowpass);
mTypeSelector->AddLabel("hp", kFilterType_Highpass);
mTypeSelector->AddLabel("bp", kFilterType_Bandpass);
mTypeSelector->AddLabel("pk", kFilterType_Peak);
mTypeSelector->AddLabel("ap", kFilterType_Allpass);
mFSlider->SetMaxValueDisplay("inf");
mFSlider->SetMode(FloatSlider::kSquare);
mQSlider->SetMode(FloatSlider::kSquare);
mQSlider->SetShowing(mBiquad[0].UsesQ());
mGSlider->SetShowing(mBiquad[0].UsesGain());
}
BiquadFilterEffect::~BiquadFilterEffect()
{
}
void BiquadFilterEffect::Init()
{
IDrawableModule::Init();
}
void BiquadFilterEffect::ProcessAudio(double time, ChannelBuffer* buffer)
{
PROFILER(BiquadFilterEffect);
if (!mEnabled)
return;
float bufferSize = buffer->BufferSize();
if (buffer->NumActiveChannels() != mDryBuffer.NumActiveChannels())
mCoefficientsHaveChanged = true; //force filters for other channels to get updated
mDryBuffer.SetNumActiveChannels(buffer->NumActiveChannels());
const float fadeOutStart = mFSlider->GetMax() * .75f;
const float fadeOutEnd = mFSlider->GetMax();
bool fadeOut = mBiquad[0].mF > fadeOutStart && mBiquad[0].mType == kFilterType_Lowpass;
if (fadeOut)
mDryBuffer.CopyFrom(buffer);
for (int i = 0; i < bufferSize; ++i)
{
ComputeSliders(i);
if (mCoefficientsHaveChanged)
{
mBiquad[0].UpdateFilterCoeff();
for (int ch = 1; ch < buffer->NumActiveChannels(); ++ch)
mBiquad[ch].CopyCoeffFrom(mBiquad[0]);
mCoefficientsHaveChanged = false;
}
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
buffer->GetChannel(ch)[i] = mBiquad[ch].Filter(buffer->GetChannel(ch)[i]);
}
if (fadeOut)
{
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
{
float dryness = ofMap(mBiquad[0].mF, fadeOutStart, fadeOutEnd, 0, 1);
Mult(buffer->GetChannel(ch), 1 - dryness, bufferSize);
Mult(mDryBuffer.GetChannel(ch), dryness, bufferSize);
Add(buffer->GetChannel(ch), mDryBuffer.GetChannel(ch), bufferSize);
}
}
}
void BiquadFilterEffect::DrawModule()
{
mTypeSelector->Draw();
mFSlider->Draw();
mQSlider->Draw();
mGSlider->Draw();
auto FreqForPos = [](float pos)
{
return 20.0 * std::pow(2.0, pos * 10);
};
float w, h;
GetModuleDimensions(w, h);
ofSetColor(52, 204, 235);
ofSetLineWidth(1);
ofBeginShape();
const int kPixelStep = 1;
for (int x = 0; x < w + kPixelStep; x += kPixelStep)
{
float freq = FreqForPos(x / w);
if (freq < gSampleRate / 2)
{
float response = mBiquad[0].GetMagnitudeResponseAt(freq);
ofVertex(x, (.5f - .666f * log10(response)) * h);
}
}
ofEndShape(false);
}
float BiquadFilterEffect::GetEffectAmount()
{
if (!mEnabled)
return 0;
if (mBiquad[0].mType == kFilterType_Lowpass)
return ofClamp(1 - (mBiquad[0].mF / (mFSlider->GetMax() * .75f)), 0, 1);
if (mBiquad[0].mType == kFilterType_Highpass)
return ofClamp(mBiquad[0].mF / (mFSlider->GetMax() * .75f), 0, 1);
if (mBiquad[0].mType == kFilterType_Bandpass)
return ofClamp(.3f + (mBiquad[0].mQ / mQSlider->GetMax()), 0, 1);
if (mBiquad[0].mType == kFilterType_Peak)
return ofClamp(fabsf(mBiquad[0].mDbGain / 96), 0, 1);
return 0;
}
void BiquadFilterEffect::GetModuleDimensions(float& width, float& height)
{
width = 120;
height = 69;
}
void BiquadFilterEffect::Clear()
{
for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i)
mBiquad[i].Clear();
}
void BiquadFilterEffect::ResetFilter()
{
if (mBiquad[0].mType == kFilterType_Lowpass)
mBiquad[0].SetFilterParams(mFSlider->GetMax(), sqrt(2) / 2);
if (mBiquad[0].mType == kFilterType_Highpass)
mBiquad[0].SetFilterParams(mFSlider->GetMin(), sqrt(2) / 2);
for (int ch = 1; ch < ChannelBuffer::kMaxNumChannels; ++ch)
mBiquad[ch].CopyCoeffFrom(mBiquad[0]);
Clear();
}
void BiquadFilterEffect::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void BiquadFilterEffect::RadioButtonUpdated(RadioButton* list, int oldVal, double time)
{
if (list == mTypeSelector)
{
if (mBiquad[0].mType == kFilterType_Lowpass)
mBiquad[0].SetFilterParams(mFSlider->GetMax(), sqrt(2) / 2);
if (mBiquad[0].mType == kFilterType_Highpass)
mBiquad[0].SetFilterParams(mFSlider->GetMin(), sqrt(2) / 2);
mQSlider->SetShowing(mBiquad[0].UsesQ());
mGSlider->SetShowing(mBiquad[0].UsesGain());
mCoefficientsHaveChanged = true;
}
}
bool BiquadFilterEffect::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
if (mMouseControl)
{
float thisx, thisy;
GetPosition(thisx, thisy);
x += thisx;
y += thisy;
mFSlider->SetValue(x * 2 + 150, NextBufferTime(false));
mQSlider->SetValue(y / 100.0f, NextBufferTime(false));
}
return false;
}
void BiquadFilterEffect::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i)
mBiquad[i].Clear();
}
}
void BiquadFilterEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mFSlider || slider == mQSlider || slider == mGSlider)
mCoefficientsHaveChanged = true;
}
void BiquadFilterEffect::LoadLayout(const ofxJSONElement& info)
{
}
void BiquadFilterEffect::SetUpFromSaveData()
{
ResetFilter();
}
void BiquadFilterEffect::SaveLayout(ofxJSONElement& info)
{
mModuleSaveData.Save(info);
}
``` | /content/code_sandbox/Source/BiquadFilterEffect.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,162 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// NoteStepSequencer.h
// modularSynth
//
// Created by Ryan Challinor on 11/3/13.
//
//
#pragma once
#include <iostream>
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Transport.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "INoteSource.h"
#include "Slider.h"
#include "UIGrid.h"
#include "MidiController.h"
#include "Scale.h"
#include "IPulseReceiver.h"
#include "GridController.h"
#include "IDrivableSequencer.h"
#include "Push2Control.h"
#define NSS_MAX_STEPS 32
class PatchCableSource;
class NoteStepSequencer : public IDrawableModule, public ITimeListener, public INoteSource, public IButtonListener, public IDropdownListener, public IIntSliderListener, public IFloatSliderListener, public MidiDeviceListener, public UIGridListener, public IAudioPoller, public IScaleListener, public INoteReceiver, public IPulseReceiver, public IGridControllerListener, public IDrivableSequencer, public IPush2GridController
{
public:
NoteStepSequencer();
virtual ~NoteStepSequencer();
static IDrawableModule* Create() { return new NoteStepSequencer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return true; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override;
void SetMidiController(std::string name);
UIGrid* GetGrid() const { return mGrid; }
int RowToPitch(int row);
int PitchToRow(int pitch);
void SetStep(int index, int step, int velocity, float length);
void SetPitch(int index, int pitch, int velocity, float length);
//IDrawableModule
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
void Poll() override;
//IClickable
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override;
//IPush2GridController
bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) override;
void UpdatePush2Leds(Push2Control* push2) override;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
//ITimeListener
void OnTimeEvent(double time) override;
//IPulseReceiver
void OnPulse(double time, float velocity, int flags) override;
//IScaleListener
void OnScaleChanged() override;
//MidiDeviceListener
void OnMidiNote(MidiNote& note) override;
void OnMidiControl(MidiControl& control) override;
//UIGridListener
void GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IGridControllerListener
void OnControllerPageSelected() override;
void OnGridButton(int x, int y, float velocity, IGridController* grid) override;
//IDrivableSequencer
bool HasExternalPulseSource() const override { return mHasExternalPulseSource; }
void ResetExternalPulseSource() override { mHasExternalPulseSource = false; }
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 3; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
void UpdateGridControllerLights(bool force);
int ButtonToStep(int button);
int StepToButton(int step);
void SyncGridToSeq();
void UpdateLights();
void ShiftSteps(int amount);
void UpdateVelocityGridPos();
void SetUpStepControls();
float ExtraWidth() const;
float ExtraHeight() const;
void RandomizePitches(bool fifths);
void RandomizeVelocities();
void RandomizeLengths();
void Step(double time, float velocity, int pulseFlags);
void SendNoteToCable(int index, double time, int pitch, int velocity);
void GetPush2Layout(int& sequenceRows, int& pitchCols, int& pitchRows);
enum NoteMode
{
kNoteMode_Scale,
kNoteMode_Chromatic,
kNoteMode_Pentatonic,
kNoteMode_Fifths
};
int mTones[NSS_MAX_STEPS]{};
int mVels[NSS_MAX_STEPS]{};
float mNoteLengths[NSS_MAX_STEPS]{};
NoteInterval mInterval{ NoteInterval::kInterval_8n };
int mArpIndex{ -1 };
DropdownList* mIntervalSelector{ nullptr };
UIGrid* mGrid{ nullptr };
UIGrid* mVelocityGrid{ nullptr };
int mLastPitch{ -1 };
int mLastStepIndex{ -1 };
float mLastNoteLength{ 1 };
double mLastNoteEndTime{ 0 };
bool mAlreadyDidNoteOff{ false };
int mOctave{ 3 };
IntSlider* mOctaveSlider{ nullptr };
NoteMode mNoteMode{ NoteMode::kNoteMode_Scale };
DropdownList* mNoteModeSelector{ nullptr };
IntSlider* mLoopResetPointSlider{ nullptr };
int mLoopResetPoint{ 0 };
int mStepLengthSubdivisions{ 2 };
int mLength{ 8 };
IntSlider* mLengthSlider{ nullptr };
bool mSetLength{ false };
int mNoteRange{ 15 };
bool mShowStepControls{ false };
int mRowOffset{ 0 };
MidiController* mController{ nullptr };
ClickButton* mShiftBackButton{ nullptr };
ClickButton* mShiftForwardButton{ nullptr };
ClickButton* mClearButton{ nullptr };
ClickButton* mRandomizeAllButton{ nullptr };
ClickButton* mRandomizePitchButton{ nullptr };
ClickButton* mRandomizeLengthButton{ nullptr };
ClickButton* mRandomizeVelocityButton{ nullptr };
float mRandomizePitchChance{ 1 };
int mRandomizePitchVariety{ 4 };
float mRandomizeLengthChance{ 1 };
float mRandomizeLengthRange{ 1 };
float mRandomizeVelocityChance{ 1 };
float mRandomizeVelocityDensity{ .6 };
FloatSlider* mRandomizePitchChanceSlider{ nullptr };
IntSlider* mRandomizePitchVarietySlider{ nullptr };
FloatSlider* mRandomizeLengthChanceSlider{ nullptr };
FloatSlider* mRandomizeLengthRangeSlider{ nullptr };
FloatSlider* mRandomizeVelocityChanceSlider{ nullptr };
FloatSlider* mRandomizeVelocityDensitySlider{ nullptr };
std::array<double, NSS_MAX_STEPS> mLastStepPlayTime{ -1 };
std::array<DropdownList*, NSS_MAX_STEPS> mToneDropdowns;
std::array<IntSlider*, NSS_MAX_STEPS> mVelocitySliders;
std::array<FloatSlider*, NSS_MAX_STEPS> mLengthSliders;
bool mHasExternalPulseSource{ false };
std::array<AdditionalNoteCable*, NSS_MAX_STEPS> mStepCables;
TransportListenerInfo* mTransportListenerInfo{ nullptr };
GridControlTarget* mGridControlTarget{ nullptr };
int mGridControlOffsetX{ 0 };
int mGridControlOffsetY{ 0 };
IntSlider* mGridControlOffsetXSlider{ nullptr };
IntSlider* mGridControlOffsetYSlider{ nullptr };
int mPush2HeldStep{ -1 };
bool mPush2HeldStepWasEdited{ false };
double mPush2ButtonPressTime{ -1 };
int mQueuedPush2Tone{ -1 };
int mQueuedPush2Vel{ 127 };
float mQueuedPush2Length{ 1 };
bool mGridSyncQueued{ false };
bool mPush2VelocityHeld{ false };
bool mPush2LengthHeld{ false };
enum class Push2GridDisplayMode
{
PerStep,
GridView
};
Push2GridDisplayMode mPush2GridDisplayMode{ Push2GridDisplayMode::PerStep };
};
``` | /content/code_sandbox/Source/NoteStepSequencer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,183 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// FMVoice.cpp
// modularSynth
//
// Created by Ryan Challinor on 1/6/13.
//
//
#include "FMVoice.h"
#include "EnvOscillator.h"
#include "SynthGlobals.h"
#include "Scale.h"
#include "Profiler.h"
#include "ChannelBuffer.h"
#include "PolyphonyMgr.h"
FMVoice::FMVoice(IDrawableModule* owner)
: mOwner(owner)
{
}
FMVoice::~FMVoice()
{
}
bool FMVoice::IsDone(double time)
{
return mOsc.GetADSR()->IsDone(time);
}
bool FMVoice::Process(double time, ChannelBuffer* out, int oversampling)
{
PROFILER(FMVoice);
if (IsDone(time))
return false;
int bufferSize = out->BufferSize();
int channels = out->NumActiveChannels();
double sampleIncrementMs = gInvSampleRateMs;
ChannelBuffer* destBuffer = out;
if (oversampling != 1)
{
gMidiVoiceWorkChannelBuffer.SetNumActiveChannels(channels);
destBuffer = &gMidiVoiceWorkChannelBuffer;
gMidiVoiceWorkChannelBuffer.Clear();
bufferSize *= oversampling;
sampleIncrementMs /= oversampling;
}
for (int pos = 0; pos < bufferSize; ++pos)
{
if (mOwner)
mOwner->ComputeSliders(pos / oversampling);
float oscFreq = TheScale->PitchToFreq(GetPitch(pos / oversampling));
float harmFreq = oscFreq * mHarm.GetADSR()->Value(time) * mVoiceParams->mHarmRatio;
float harmFreq2 = harmFreq * mHarm2.GetADSR()->Value(time) * mVoiceParams->mHarmRatio2;
float harmPhaseInc2 = GetPhaseInc(harmFreq2) / oversampling;
mHarmPhase2 += harmPhaseInc2;
while (mHarmPhase2 > FTWO_PI)
{
mHarmPhase2 -= FTWO_PI;
}
float modHarmFreq = harmFreq + mHarm2.Audio(time, mHarmPhase2 + mVoiceParams->mPhaseOffset2) * harmFreq2 * mModIdx2.Value(time) * mVoiceParams->mModIdx2;
float harmPhaseInc = GetPhaseInc(modHarmFreq) / oversampling;
mHarmPhase += harmPhaseInc;
while (mHarmPhase > FTWO_PI)
{
mHarmPhase -= FTWO_PI;
}
float modOscFreq = oscFreq + mHarm.Audio(time, mHarmPhase + mVoiceParams->mPhaseOffset1) * harmFreq * mModIdx.Value(time) * mVoiceParams->mModIdx;
float oscPhaseInc = GetPhaseInc(modOscFreq) / oversampling;
mOscPhase += oscPhaseInc;
while (mOscPhase > FTWO_PI)
{
mOscPhase -= FTWO_PI;
}
float sample = mOsc.Audio(time, mOscPhase + mVoiceParams->mPhaseOffset0) * mVoiceParams->mVol / 20.0f;
if (channels == 1)
{
destBuffer->GetChannel(0)[pos] += sample;
}
else
{
destBuffer->GetChannel(0)[pos] += sample * GetLeftPanGain(GetPan());
destBuffer->GetChannel(1)[pos] += sample * GetRightPanGain(GetPan());
}
time += sampleIncrementMs;
}
if (oversampling != 1)
{
//assume power-of-two
while (oversampling > 1)
{
for (int i = 0; i < bufferSize; ++i)
{
for (int ch = 0; ch < channels; ++ch)
destBuffer->GetChannel(ch)[i] = (destBuffer->GetChannel(ch)[i * 2] + destBuffer->GetChannel(ch)[i * 2 + 1]) / 2;
}
oversampling /= 2;
bufferSize /= 2;
}
for (int ch = 0; ch < channels; ++ch)
Add(out->GetChannel(ch), destBuffer->GetChannel(ch), bufferSize);
}
return true;
}
void FMVoice::Start(double time, float target)
{
if (mHarm.GetADSR()->GetR() <= 1)
mHarm.GetADSR()->Clear();
if (mModIdx.GetR() <= 1)
mModIdx.Clear();
if (mHarm2.GetADSR()->GetR() <= 1)
mHarm2.GetADSR()->Clear();
if (mModIdx2.GetR() <= 1)
mModIdx2.Clear();
mOsc.Start(time, target,
mVoiceParams->mOscADSRParams);
mHarm.Start(time, 1,
mVoiceParams->mHarmRatioADSRParams);
mModIdx.Start(time, 1,
mVoiceParams->mModIdxADSRParams);
mHarm2.Start(time, 1,
mVoiceParams->mHarmRatioADSRParams2);
mModIdx2.Start(time, 1,
mVoiceParams->mModIdxADSRParams2);
}
void FMVoice::Stop(double time)
{
mOsc.Stop(time);
if (mHarm.GetADSR()->GetR() > 1)
mHarm.Stop(time);
if (mModIdx.GetR() > 1)
mModIdx.Stop(time);
if (mHarm2.GetADSR()->GetR() > 1)
mHarm2.Stop(time);
if (mModIdx2.GetR() > 1)
mModIdx2.Stop(time);
}
void FMVoice::ClearVoice()
{
mOsc.GetADSR()->Clear();
mHarm.GetADSR()->Clear();
mModIdx.Clear();
mHarm2.GetADSR()->Clear();
mModIdx2.Clear();
mOscPhase = 0;
mHarmPhase = 0;
mHarmPhase2 = 0;
}
void FMVoice::SetVoiceParams(IVoiceParams* params)
{
mVoiceParams = dynamic_cast<FMVoiceParams*>(params);
}
``` | /content/code_sandbox/Source/FMVoice.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,474 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.