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
```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 **/ // // EuclideanSequencer.h // Bespoke // // Created by Jack van Klaren on Mar 17 2024. // Based on CircleSequencer by Ryan Challinor // // #pragma once #include <iostream> #include "Transport.h" #include "UIGrid.h" #include "Slider.h" #include "DropdownList.h" #include "IDrawableModule.h" #include "INoteSource.h" #include "TextEntry.h" #include "ClickButton.h" #include "Scale.h" class EuclideanSequencer; #define EUCLIDEAN_SEQUENCER_MAX_STEPS 32 #define EUCLIDEAN_ROTATION_MIN -16 #define EUCLIDEAN_ROTATION_MAX 16 #define EUCLIDEAN_INITIALSTATE_MAX 4 class EuclideanSequencerRing { public: EuclideanSequencerRing(EuclideanSequencer* owner, int index); void Draw(); void OnClicked(float x, float y, bool right); void SetSteps(int steps); int GetSteps(); void SetOnsets(int onsets); void SetRotation(int rotation); void SetOffset(float offset); void SetPitch(int pitch); int GetPitch(); void MouseReleased(); void MouseMoved(float x, float y); void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time); void CreateUIControls(); void InitialState(int state); void Clear(); void OnTransportAdvanced(float amount); void SaveState(FileStreamOut& out); void LoadState(FileStreamIn& in); private: float GetRadius() { return 90 - mIndex * 15; } int GetStepIndex(int x, int y, float& radiusOut); EuclideanSequencer* mOwner{ nullptr }; int mIndex{ 0 }; std::array<float, EUCLIDEAN_SEQUENCER_MAX_STEPS> mSteps{}; float mLength{ 4 }; FloatSlider* mLengthSlider{ nullptr }; float mOnset{ 4 }; FloatSlider* mOnsetSlider{ nullptr }; float mRotation{ 0 }; FloatSlider* mRotationSlider{ nullptr }; float mOffset{ 0 }; FloatSlider* mOffsetSlider{ nullptr }; int mPitch{ 0 }; TextEntry* mNoteSelector{ nullptr }; AdditionalNoteCable* mDestinationCable{ nullptr }; int mCurrentlyClickedStepIdx{ -1 }; int mHighlightStepIdx{ -1 }; float mLastMouseRadius{ -1 }; std::string GetEuclideanRhythm(int pulses, int steps, int rotation); }; class EuclideanSequencer : public IDrawableModule, public INoteSource, public IAudioPoller, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public ITextEntryListener, public IButtonListener { public: EuclideanSequencer(); ~EuclideanSequencer(); static IDrawableModule* Create() { return new EuclideanSequencer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; void SetEnabled(bool on) override { mEnabled = on; } //IDrawableModule bool IsResizable() const override { return true; } void Resize(float w, float h) override; //IAudioPoller void OnTransportAdvanced(float amount) override; //IClickable void MouseReleased() override; 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 DropdownUpdated(DropdownList* list, int oldVal, double time) override; void TextEntryComplete(TextEntry* entry) override {} void ButtonClicked(ClickButton* button, double time) override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 2; } virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } bool PlayShortNotes() const { return mPlayShortNotes; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } float mWidth{ 785 }; // was 650 = random buttons visible float mHeight{ 200 }; const float mWidthMin = 590; const float mWidthMax = 785; void OnClicked(float x, float y, bool right) override; // ModuleSaveData bool mPlayShortNotes{ false }; ClickButton* mRandomizeButton{ nullptr }; ClickButton* mRndLengthButton{ nullptr }; ClickButton* mRndOnsetsButton{ nullptr }; ClickButton* mRndRotationButton{ nullptr }; ClickButton* mRndOffsetButton{ nullptr }; ClickButton* mRndNoteButton{ nullptr }; ClickButton* mRnd0Button{ nullptr }; ClickButton* mRnd1Button{ nullptr }; ClickButton* mRnd2Button{ nullptr }; ClickButton* mRnd3Button{ nullptr }; ClickButton* mClearButton{ nullptr }; float mOffset{ 0 }; FloatSlider* mOffsetSlider{ nullptr }; float mRndLengthChance{ 0.5f }; FloatSlider* mRndLengthChanceSlider{ nullptr }; float mRndLengthLo{ 1 }; FloatSlider* mRndLengthLoSlider{ nullptr }; float mRndLengthHi{ 24 }; FloatSlider* mRndLengthHiSlider{ nullptr }; float mRndOnsetChance{ 0.5f }; FloatSlider* mRndOnsetChanceSlider{ nullptr }; float mRndOnsetLo{ 1 }; FloatSlider* mRndOnsetLoSlider{ nullptr }; float mRndOnsetHi{ 12 }; FloatSlider* mRndOnsetHiSlider{ nullptr }; float mRndRotationChance{ 0.5f }; FloatSlider* mRndRotationChanceSlider{ nullptr }; float mRndRotationLo{ 0 }; FloatSlider* mRndRotationLoSlider{ nullptr }; float mRndRotationHi{ 4 }; FloatSlider* mRndRotationHiSlider{ nullptr }; float mRndOffsetChance{ 0.0f }; FloatSlider* mRndOffsetChanceSlider{ nullptr }; float mRndOffsetLo{ -0.1f }; FloatSlider* mRndOffsetLoSlider{ nullptr }; float mRndOffsetHi{ 0.1f }; FloatSlider* mRndOffsetHiSlider{ nullptr }; float mRndNoteChance{ 0.5f }; FloatSlider* mRndNoteChanceSlider{ nullptr }; float mRndOctaveLo{ 2 }; FloatSlider* mRndOctaveLoSlider{ nullptr }; float mRndOctaveHi{ 4 }; FloatSlider* mRndOctaveHiSlider{ nullptr }; void RandomizeLength(int ringIndex); void RandomizeOnset(int ringIndex); void RandomizeRotation(int ringIndex); void RandomizeOffset(int ringIndex); void RandomizeNote(int ringIndex, bool force); std::vector<EuclideanSequencerRing*> mEuclideanSequencerRings; }; ```
/content/code_sandbox/Source/EuclideanSequencer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,777
```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 **/ /* ============================================================================== NoteRatchet.h Created: 2 Aug 2021 10:32:20pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Checkbox.h" #include "DropdownList.h" class NoteRatchet : public NoteEffectBase, public IDrawableModule, public IDropdownListener { public: NoteRatchet(); static IDrawableModule* Create() { return new NoteRatchet(); } 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 DropdownUpdated(DropdownList* list, 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 }; NoteInterval mRatchetDuration{ NoteInterval::kInterval_8n }; DropdownList* mRatchetDurationSelector{ nullptr }; NoteInterval mRatchetSubdivision{ NoteInterval::kInterval_32n }; DropdownList* mRatchetSubdivisionSelector{ nullptr }; bool mSkipFirst{ false }; Checkbox* mSkipFirstCheckbox{ nullptr }; }; ```
/content/code_sandbox/Source/NoteRatchet.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
522
```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 **/ // // Created by Ryan Challinor on 11/05/22. // #include "SongBuilder.h" #include "SynthGlobals.h" #include "UIControlMacros.h" #include "FileStream.h" #include "PatchCableSource.h" #include "ofxJSONElement.h" #include "RadioButton.h" namespace { const float kLeftMarginX = 3; const float kSongSequencerWidth = 175; const float kGridStartY = 20; const float kSceneTabWidth = 165; const float kTargetTabHeightTop = 30; const float kTargetTabHeightBottom = 10; const float kRowHeight = 20; const float kColumnWidth = 50; const float kSpacingX = 3; const float kSpacingY = 3; } SongBuilder::SongBuilder() { for (int i = 0; i < kMaxSequencerScenes; ++i) { mSequencerSceneId[i] = -1; mSequencerSceneSelector[i] = nullptr; mSequencerStepLength[i] = 4; mSequencerStepLengthEntry[i] = nullptr; mSequencerContextMenu[i] = nullptr; mSequencerContextMenuSelection[i] = ContextMenuItems::kNone; } const float kColorDim = .7f; ofColor grey = IDrawableModule::GetColor(kModuleCategory_Other); mColors.push_back(TargetColor("grey", grey * kColorDim)); mColors.push_back(TargetColor("red", ofColor::red * kColorDim)); mColors.push_back(TargetColor("orange", ofColor::orange * kColorDim)); mColors.push_back(TargetColor("yellow", ofColor::yellow * kColorDim)); mColors.push_back(TargetColor("green", ofColor::green * kColorDim)); mColors.push_back(TargetColor("cyan", ofColor::cyan * kColorDim)); mColors.push_back(TargetColor("blue", ofColor::blue * kColorDim)); mColors.push_back(TargetColor("purple", ofColor::purple * kColorDim)); mColors.push_back(TargetColor("magenta", ofColor::magenta * kColorDim)); mTransportPriority = ITimeListener::kTransportPriorityVeryEarly; } void SongBuilder::Init() { IDrawableModule::Init(); TheTransport->AddListener(this, kInterval_1n, OffsetInfo(gBufferSizeMs, true), true); SetActiveScene(gTime, 0); } void SongBuilder::CreateUIControls() { IDrawableModule::CreateUIControls(); float width, height; UIBLOCK0(); CHECKBOX(mUseSequencerCheckbox, "use sequencer", &mUseSequencer); UIBLOCK_SHIFTRIGHT(); CHECKBOX(mActivateFirstSceneOnStopCheckbox, "activate first scene on stop", &mActivateFirstSceneOnStop); UIBLOCK_NEWLINE(); BUTTON_STYLE(mPlaySequenceButton, "play", ButtonDisplayStyle::kPlay); UIBLOCK_SHIFTRIGHT(); BUTTON_STYLE(mStopSequenceButton, "stop", ButtonDisplayStyle::kStop); UIBLOCK_SHIFTRIGHT(); BUTTON_STYLE(mPauseSequenceButton, "pause", ButtonDisplayStyle::kPause); UIBLOCK_SHIFTRIGHT(); CHECKBOX(mLoopCheckbox, "loop", &mLoopSequence); UIBLOCK_SHIFTRIGHT(); TEXTENTRY_NUM(mSequenceLoopStartEntry, "loop start", 3, &mSequenceLoopStartIndex, 0, kMaxSequencerScenes - 1); UIBLOCK_SHIFTRIGHT(); TEXTENTRY_NUM(mSequenceLoopEndEntry, "loop end", 3, &mSequenceLoopEndIndex, 0, kMaxSequencerScenes - 1); ENDUIBLOCK(width, height); UIBLOCK(10, height + 4); for (int i = 0; i < kMaxSequencerScenes; ++i) { DROPDOWN(mSequencerSceneSelector[i], ("scene" + ofToString(i)).c_str(), &mSequencerSceneId[i], 80); mSequencerSceneSelector[i]->SetCableTargetable(false); mSequencerSceneSelector[i]->SetDrawTriangle(false); UIBLOCK_SHIFTRIGHT(); TEXTENTRY_NUM(mSequencerStepLengthEntry[i], ("bars" + ofToString(i)).c_str(), 3, &mSequencerStepLength[i], 1, 999); UIBLOCK_SHIFTRIGHT(); BUTTON_STYLE(mSequencerPlayFromButton[i], ("play from " + ofToString(i)).c_str(), ButtonDisplayStyle::kPlay); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mSequencerContextMenu[i], ("contextmenu" + ofToString(i)).c_str(), ((int*)&mSequencerContextMenuSelection[i]), 20); mSequencerContextMenu[i]->AddLabel("duplicate", (int)ContextMenuItems::kDuplicate); mSequencerContextMenu[i]->AddLabel("delete", (int)ContextMenuItems::kDelete); mSequencerContextMenu[i]->AddLabel("move up", (int)ContextMenuItems::kMoveUp); mSequencerContextMenu[i]->AddLabel("move down", (int)ContextMenuItems::kMoveDown); mSequencerContextMenu[i]->SetCableTargetable(false); mSequencerContextMenu[i]->SetDisplayStyle(DropdownDisplayStyle::kHamburger); UIBLOCK_NEWLINE(); } ENDUIBLOCK0(); mChangeQuantizeSelector = new DropdownList(this, "change quantize", -1, -1, (int*)(&mChangeQuantizeInterval)); mAddTargetButton = new ClickButton(this, "add target", -1, -1, ButtonDisplayStyle::kPlus); mAddTargetButton->SetCableTargetable(false); mChangeQuantizeSelector->AddLabel("jump", kInterval_None); mChangeQuantizeSelector->AddLabel("switch", kInterval_Free); mChangeQuantizeSelector->AddLabel("1n", kInterval_1n); mChangeQuantizeSelector->AddLabel("2", kInterval_2); mChangeQuantizeSelector->AddLabel("4", kInterval_4); } SongBuilder::~SongBuilder() { TheTransport->RemoveListener(this); } void SongBuilder::DrawModule() { if (Minimized() || IsVisible() == false) return; int gridStartX = kLeftMarginX; if (ShowSongSequencer()) gridStartX += kSongSequencerWidth; mUseSequencerCheckbox->Draw(); mActivateFirstSceneOnStopCheckbox->SetShowing(ShowSongSequencer()); mActivateFirstSceneOnStopCheckbox->SetPosition(gridStartX, 3); mActivateFirstSceneOnStopCheckbox->Draw(); mChangeQuantizeSelector->SetPosition(gridStartX, kGridStartY + kTargetTabHeightTop - 29); mChangeQuantizeSelector->Draw(); mAddTargetButton->SetPosition(gridStartX + kSceneTabWidth - 22, kGridStartY + 8); mAddTargetButton->Draw(); mPlaySequenceButton->SetShowing(ShowSongSequencer()); mPlaySequenceButton->Draw(); mStopSequenceButton->SetShowing(ShowSongSequencer()); mStopSequenceButton->Draw(); mPauseSequenceButton->SetShowing(ShowSongSequencer()); mPauseSequenceButton->Draw(); mLoopCheckbox->SetShowing(ShowSongSequencer()); mLoopCheckbox->Draw(); mSequenceLoopStartEntry->SetShowing(ShowSongSequencer() && mLoopSequence); mSequenceLoopStartEntry->Draw(); mSequenceLoopEndEntry->SetShowing(ShowSongSequencer() && mLoopSequence); mSequenceLoopEndEntry->Draw(); //separator if (ShowSongSequencer()) ofLine(gridStartX - 8, kGridStartY + kTargetTabHeightTop + kSpacingY, gridStartX - 8, kGridStartY + kTargetTabHeightTop + (int)mScenes.size() * (kRowHeight + kSpacingY)); DrawTextNormal("scenes:", gridStartX, kGridStartY + kTargetTabHeightTop - 1); for (int i = 0; i < (int)mScenes.size(); ++i) { if (mScenes[i] != nullptr) mScenes[i]->Draw(this, gridStartX, kGridStartY + kTargetTabHeightTop + kSpacingY + i * (kRowHeight + kSpacingY), i); } for (int i = 0; i < (int)mTargets.size(); ++i) { if (mTargets[i] != nullptr) mTargets[i]->Draw(gridStartX + kSceneTabWidth + i * (kColumnWidth + kSpacingX), kGridStartY, (int)mScenes.size()); } bool sequenceComplete = false; int sequenceLength = 0; for (int i = 0; i < kMaxSequencerScenes; ++i) { bool show = mUseSequencer && !sequenceComplete; mSequencerSceneSelector[i]->SetShowing(show); mSequencerStepLengthEntry[i]->SetShowing(show && mSequencerSceneId[i] != kSequenceEndId); mSequencerContextMenu[i]->SetShowing(show && mSequencerSceneId[i] >= 0); mSequencerPlayFromButton[i]->SetShowing(show && mSequencerSceneId[i] >= 0); mSequencerSceneSelector[i]->Draw(); mSequencerStepLengthEntry[i]->Draw(); mSequencerContextMenu[i]->Draw(); mSequencerPlayFromButton[i]->Draw(); if (show && mLoopSequence && i == mSequenceLoopEndIndex && mSequenceLoopEndIndex >= mSequenceLoopStartIndex) { ofPushStyle(); ofRectangle upperRect = mSequencerSceneSelector[mSequenceLoopStartIndex]->GetRect(K(local)); ofRectangle lowerRect = mSequencerSceneSelector[mSequenceLoopEndIndex]->GetRect(K(local)); ofSetColor(150, 150, 150); ofSetLineWidth(1); ofLine(upperRect.getMinX() - 5, upperRect.getMinY(), lowerRect.getMinX() - 5, lowerRect.getMaxY()); ofLine(upperRect.getMinX() - 5, upperRect.getMinY(), upperRect.getMinX() - 0, upperRect.getMinY()); ofLine(lowerRect.getMinX() - 5, lowerRect.getMaxY(), lowerRect.getMinX() - 0, lowerRect.getMaxY()); ofPopStyle(); } if (mSequencerSceneId[i] < 0) { if (show && !sequenceComplete) { ofRectangle rect = mSequencerStepLengthEntry[i]->GetRect(K(local)); int sequenceLengthSeconds = int(sequenceLength * TheTransport->MsPerBar() / 1000); int sequenceLengthMinutes = sequenceLengthSeconds / 60; sequenceLengthSeconds %= 60; std::string lengthTime = ofToString(sequenceLengthMinutes) + ":"; if (sequenceLengthSeconds < 10) lengthTime += "0"; //zero pad lengthTime += ofToString(sequenceLengthSeconds); DrawTextNormal(ofToString(sequenceLength) + " (" + lengthTime + ")", rect.x, rect.y + 12); } sequenceComplete = true; } else if (!sequenceComplete) { sequenceLength += mSequencerStepLength[i]; } } if (ShowSongSequencer() && mSequenceStepIndex != -1) { ofPushStyle(); ofFill(); if (!mSequenceStartQueued) { ofSetColor(0, 255, 0); ofRectangle sceneEntryRect = mSequencerSceneSelector[mSequenceStepIndex]->GetRect(K(local)); ofRect(sceneEntryRect.getMinX() - 5, sceneEntryRect.getCenter().y - 2, 4, 4); ofSetColor(0, 255, 0, 100); ofRectangle lengthEntryRect = mSequencerStepLengthEntry[mSequenceStepIndex]->GetRect(K(local)); float progress = MIN(TheTransport->GetMeasureTime(gTime) / mSequencerStepLength[mSequenceStepIndex], 1.0f); lengthEntryRect.width *= progress; ofRect(lengthEntryRect); } if (mSequencePaused) { ofSetColor(0, 0, 255, 100); ofRectangle pauseButtonRect = mPauseSequenceButton->GetRect(K(local)); ofRect(pauseButtonRect); } else { ofSetColor(0, 255, 0, 100); ofRectangle playButtonRect = mPlaySequenceButton->GetRect(K(local)); ofRect(playButtonRect); } ofPopStyle(); } } void SongBuilder::Poll() { if (mWantRefreshValueDropdowns) { for (int i = 0; i < (int)mScenes.size(); ++i) { for (int j = 0; j < (int)mTargets.size(); ++j) mScenes[i]->mValues[j]->UpdateDropdownContents(mTargets[j]); } mWantRefreshValueDropdowns = false; } } void SongBuilder::OnTimeEvent(double time) { if (mJustResetClock) { mJustResetClock = false; return; } if (mQueuedScene != -1 && (mChangeQuantizeInterval == kInterval_None || TheTransport->GetMeasure(time + TheTransport->GetListenerInfo(this)->mOffsetInfo.mOffset) % (int)TheTransport->GetMeasureFraction(mChangeQuantizeInterval) == 0)) { SetActiveScene(time, mQueuedScene); mQueuedScene = -1; } if (mSequenceStepIndex != -1) { if (TheTransport->GetMeasure(time + TheTransport->GetListenerInfo(this)->mOffsetInfo.mOffset) >= mSequencerStepLength[mSequenceStepIndex] && !mSequencePaused) { if (mLoopSequence && mSequenceStepIndex == mSequenceLoopEndIndex && mSequenceLoopEndIndex >= mSequenceLoopStartIndex) mSequenceStepIndex = mSequenceLoopStartIndex; else ++mSequenceStepIndex; if (mSequencerSceneId[mSequenceStepIndex] == kSequenceEndId) { mSequenceStepIndex = -1; //all done! if (mActivateFirstSceneOnStop) SetActiveScene(time, 0); } else { SetActiveSceneById(time, mSequencerSceneId[mSequenceStepIndex]); if (mResetOnSceneChange) mWantResetClock = true; } } } if (mSequenceStartQueued) { mSequenceStepIndex = mSequenceStartStepIndex; SetActiveSceneById(time, mSequencerSceneId[mSequenceStepIndex]); mSequenceStartQueued = false; mWantResetClock = true; } if (mWantResetClock) { TheTransport->SetQueuedMeasure(time, 0); mWantResetClock = false; mJustResetClock = true; } } void SongBuilder::OnPulse(double time, float velocity, int flags) { if (velocity > 0 && mCurrentScene < (int)mScenes.size() - 1) SetActiveScene(time, mCurrentScene + 1); } void SongBuilder::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (velocity > 0 && pitch < (int)mScenes.size()) SetActiveScene(time, pitch); } void SongBuilder::SetActiveSceneById(double time, int newSceneId) { for (int i = 0; i < (int)mScenes.size(); ++i) { if (mScenes[i]->mId == newSceneId) { SetActiveScene(time, i); break; } } } void SongBuilder::SetActiveScene(double time, int newScene) { if (newScene < (int)mScenes.size()) { for (int i = 0; i < (int)mTargets.size(); ++i) { for (auto& cable : mTargets[i]->mCable->GetPatchCables()) { IUIControl* target = dynamic_cast<IUIControl*>(cable->GetTarget()); if (target != nullptr) { if (mTargets[i]->mDisplayType == ControlTarget::DisplayType::TextEntry) target->SetValue(mScenes[newScene]->mValues[i]->mFloatValue, time); if (mTargets[i]->mDisplayType == ControlTarget::DisplayType::Checkbox) target->SetValue(mScenes[newScene]->mValues[i]->mBoolValue ? 1 : 0, time); if (mTargets[i]->mDisplayType == ControlTarget::DisplayType::Dropdown) target->SetValue(mScenes[newScene]->mValues[i]->mIntValue, time); } } } } mCurrentScene = newScene; } void SongBuilder::RefreshSequencerDropdowns() { for (int i = 0; i < kMaxSequencerScenes; ++i) { mSequencerSceneSelector[i]->Clear(); mSequencerSceneSelector[i]->AddLabel("-stop-", kSequenceEndId); for (auto* scene : mScenes) mSequencerSceneSelector[i]->AddLabel(scene->mName, scene->mId); } } void SongBuilder::GetModuleDimensions(float& width, float& height) { width = kLeftMarginX + kSceneTabWidth + (int)mTargets.size() * (kColumnWidth + kSpacingX) + 3; if (ShowSongSequencer()) width += kSongSequencerWidth; height = kGridStartY + kTargetTabHeightTop + kTargetTabHeightBottom + kSpacingY + (int)mScenes.size() * (kRowHeight + kSpacingY) + 3; if (ShowSongSequencer()) { for (int i = 0; i < kMaxSequencerScenes; ++i) { if (i == kMaxSequencerScenes - 1 || mSequencerSceneId[i] < 0) //end of sequence { ofRectangle rect = mSequencerSceneSelector[i]->GetRect(K(local)); if (rect.getMaxY() + 3 > height) height = rect.getMaxY() + 3; break; } } } } void SongBuilder::PostRepatch(PatchCableSource* cable, bool fromUserClick) { int targetIndex = -1; for (int i = 0; i < (int)mTargets.size(); ++i) { if (cable == mTargets[i]->mCable) { mTargets[i]->TargetControlUpdated(); targetIndex = i; break; } } if (targetIndex != -1) { if (fromUserClick) { for (int i = 0; i < (int)mScenes.size(); ++i) mScenes[i]->TargetControlUpdated(mTargets[targetIndex], targetIndex, true); if (mTargets[targetIndex]->GetTarget() == nullptr) { mTargets[targetIndex]->CleanUp(); mTargets.erase(mTargets.begin() + targetIndex); } } mTargets[targetIndex]->mHadTarget = (mTargets[targetIndex]->GetTarget() != nullptr); } } void SongBuilder::PlaySequence(double time, int startIndex) { if (mSequencePaused && startIndex == -1) { mSequencePaused = false; } else { if (startIndex == -1) mSequenceStartStepIndex = 0; else mSequenceStartStepIndex = startIndex; mWantResetClock = true; mSequencePaused = false; mSequenceStartQueued = true; } } bool SongBuilder::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 (x == 0) { if (mUseSequencer) { switch (y) { case 0: mPlaySequenceButton->SetValue(1, gTime); break; case 1: mStopSequenceButton->SetValue(1, gTime); break; default: break; } } } else { int index = y + (x - 1) * 8; if (index < mScenes.size()) mScenes[index]->mActivateButton->SetValue(1, gTime); } return true; } } return false; } void SongBuilder::UpdatePush2Leds(Push2Control* push2) { for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { int pushColor = 0; int pushColorBlink = -1; if (x == 0) { if (mUseSequencer) { switch (y) { case 0: pushColor = mSequenceStepIndex == -1 ? 86 : 126; if (mSequenceStartQueued) pushColorBlink = 0; break; case 1: pushColor = mSequenceStepIndex == -1 ? 127 : 68; break; default: break; } } } else { int index = y + (x - 1) * 8; if (index < mScenes.size()) { if (index == mCurrentScene) pushColor = 120; else pushColor = 124; if (index == mQueuedScene) pushColorBlink = 0; } } push2->SetLed(kMidiMessage_Note, x + (7 - y) * 8 + 36, pushColor, pushColorBlink); } } } bool SongBuilder::DrawToPush2Screen() { ofPushStyle(); ofSetColor(255, 255, 255); if (mQueuedScene >= 0 && mQueuedScene < mScenes.size()) DrawTextNormal("queued: " + mScenes[mQueuedScene]->mName, 100, -2); else if (mCurrentScene >= 0 && mCurrentScene < mScenes.size()) DrawTextNormal("scene: " + mScenes[mCurrentScene]->mName, 100, -2); ofPopStyle(); return false; } void SongBuilder::ButtonClicked(ClickButton* button, double time) { if (button == mPlaySequenceButton) { PlaySequence(time, -1); if (mChangeQuantizeInterval == kInterval_None) //jump TheTransport->Reset(); } if (button == mStopSequenceButton) { mSequenceStartQueued = false; mSequenceStepIndex = -1; mSequencePaused = false; if (mActivateFirstSceneOnStop) SetActiveScene(time, 0); } if (button == mPauseSequenceButton) { if (mSequencePaused) { mSequencePaused = false; } else if (mSequenceStepIndex != -1) { mSequencePaused = true; } } for (int i = 0; i < (int)mScenes.size(); ++i) { if (button == mScenes[i]->mActivateButton) { mSequenceStepIndex = -1; //stop playing if (mChangeQuantizeInterval == kInterval_Free) //switch { SetActiveScene(time, i); } else if (mChangeQuantizeInterval == kInterval_None) //jump { mQueuedScene = i; TheTransport->Reset(); } else { mQueuedScene = i; } } } for (int i = 0; i < (int)mTargets.size(); ++i) { if (button == mTargets[i]->mMoveLeftButton) { if (i > 0) { ControlTarget* target = mTargets[i]; mTargets.erase(mTargets.begin() + i); mTargets.insert(mTargets.begin() + (i - 1), target); for (auto* scene : mScenes) scene->MoveValue(i, -1); gHoveredUIControl = nullptr; } break; } if (button == mTargets[i]->mMoveRightButton) { if (i < (int)mTargets.size() - 1) { ControlTarget* target = mTargets[i]; mTargets.erase(mTargets.begin() + i); mTargets.insert(mTargets.begin() + (i + 1), target); for (auto* scene : mScenes) scene->MoveValue(i, 1); gHoveredUIControl = nullptr; } break; } if (button == mTargets[i]->mCycleDisplayTypeButton) { while (true) { mTargets[i]->mDisplayType = (ControlTarget::DisplayType)(((int)mTargets[i]->mDisplayType + 1) % (int)ControlTarget::DisplayType::NumDisplayTypes); if (mTargets[i]->mDisplayType == ControlTarget::DisplayType::Dropdown && dynamic_cast<DropdownList*>(mTargets[i]->GetTarget()) == nullptr && dynamic_cast<RadioButton*>(mTargets[i]->GetTarget()) == nullptr) continue; //invalid option else break; } break; } } if (button == mAddTargetButton) AddTarget(); for (int i = 0; i < kMaxSequencerScenes; ++i) { if (button == mSequencerPlayFromButton[i]) { PlaySequence(time, i); if (mChangeQuantizeInterval == kInterval_None) //jump TheTransport->Reset(); } } } void SongBuilder::TextEntryComplete(TextEntry* entry) { for (int i = 0; i < (int)mScenes.size(); ++i) { if (entry == mScenes[i]->mNameEntry) RefreshSequencerDropdowns(); } } void SongBuilder::DropdownClicked(DropdownList* list) { int refreshValueColumn = -1; for (int i = 0; i < (int)mScenes.size(); ++i) { for (int j = 0; j < (int)mScenes[i]->mValues.size(); ++j) { if (list == mScenes[i]->mValues[j]->mValueSelector && mTargets[j]->GetTarget() != nullptr && mTargets[j]->mDisplayType == ControlTarget::DisplayType::Dropdown) refreshValueColumn = j; } } if (refreshValueColumn != -1) { for (int i = 0; i < (int)mScenes.size(); ++i) mScenes[i]->mValues[refreshValueColumn]->UpdateDropdownContents(mTargets[refreshValueColumn]); } } void SongBuilder::ControlValue::UpdateDropdownContents(ControlTarget* target) { if (target->mDisplayType == ControlTarget::DisplayType::Dropdown) { DropdownList* targetList = dynamic_cast<DropdownList*>(target->GetTarget()); if (targetList) targetList->CopyContentsTo(mValueSelector); RadioButton* targetRadio = dynamic_cast<RadioButton*>(target->GetTarget()); if (targetRadio) targetRadio->CopyContentsTo(mValueSelector); } } void SongBuilder::DropdownUpdated(DropdownList* list, int oldVal, double time) { for (int i = 0; i < (int)mScenes.size(); ++i) { if (list == mScenes[i]->mContextMenu) { switch (mScenes[i]->mContextMenuSelection) { case ContextMenuItems::kDuplicate: DuplicateScene(i); break; case ContextMenuItems::kDelete: if (mScenes.size() > 1) { mScenes[i]->CleanUp(); mScenes.erase(mScenes.begin() + i); RefreshSequencerDropdowns(); i = -1; } break; case ContextMenuItems::kMoveUp: if (i > 0) { SongScene* scene = mScenes[i]; mScenes.erase(mScenes.begin() + i); --i; mScenes.insert(mScenes.begin() + i, scene); RefreshSequencerDropdowns(); } break; case ContextMenuItems::kMoveDown: if (i < (int)mScenes.size() - 1) { SongScene* scene = mScenes[i]; mScenes.erase(mScenes.begin() + i); ++i; mScenes.insert(mScenes.begin() + i, scene); RefreshSequencerDropdowns(); } break; case ContextMenuItems::kNone: break; } if (i != -1) mScenes[i]->mContextMenuSelection = ContextMenuItems::kNone; break; } } for (int i = 0; i < kMaxSequencerScenes; ++i) { if (list == mSequencerContextMenu[i]) { switch (mSequencerContextMenuSelection[i]) { case ContextMenuItems::kDuplicate: for (int j = kMaxSequencerScenes - 1; j > i; --j) { mSequencerSceneId[j] = mSequencerSceneId[j - 1]; mSequencerStepLength[j] = mSequencerStepLength[j - 1]; } break; case ContextMenuItems::kDelete: for (int j = i; j < kMaxSequencerScenes - 1; ++j) { mSequencerSceneId[j] = mSequencerSceneId[j + 1]; mSequencerStepLength[j] = mSequencerStepLength[j + 1]; } break; case ContextMenuItems::kMoveUp: if (i > 0) { int temp = mSequencerSceneId[i]; mSequencerSceneId[i] = mSequencerSceneId[i - 1]; mSequencerSceneId[i - 1] = temp; temp = mSequencerStepLength[i]; mSequencerStepLength[i] = mSequencerStepLength[i - 1]; mSequencerStepLength[i - 1] = temp; } break; case ContextMenuItems::kMoveDown: if (i < kMaxSequencerScenes - 1 && mSequencerSceneId[i + 1] >= 0) { int temp = mSequencerSceneId[i]; mSequencerSceneId[i] = mSequencerSceneId[i + 1]; mSequencerSceneId[i + 1] = temp; temp = mSequencerStepLength[i]; mSequencerStepLength[i] = mSequencerStepLength[i + 1]; mSequencerStepLength[i + 1] = temp; } break; case ContextMenuItems::kNone: break; } mSequencerContextMenuSelection[i] = ContextMenuItems::kNone; break; } } } void SongBuilder::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void SongBuilder::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadBool("reset_transport_every_sequencer_scene", moduleInfo, true); if (IsSpawningOnTheFly(moduleInfo)) { mScenes.push_back(new SongScene("off")); mScenes.push_back(new SongScene("intro")); mScenes.push_back(new SongScene("verse")); mScenes.push_back(new SongScene("prechorus")); mScenes.push_back(new SongScene("chorus")); mScenes.push_back(new SongScene("bridge")); mScenes.push_back(new SongScene("outro")); for (auto* scene : mScenes) scene->CreateUIControls(this); RefreshSequencerDropdowns(); } SetUpFromSaveData(); } void SongBuilder::SetUpFromSaveData() { mResetOnSceneChange = mModuleSaveData.GetBool("reset_transport_every_sequencer_scene"); } void SongBuilder::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); out << (int)mTargets.size(); for (auto* target : mTargets) { out << target->mId; target->mCable->SaveState(out); out << (int)target->mDisplayType; } out << (int)mScenes.size(); for (auto* scene : mScenes) { out << scene->mName; out << scene->mId; out << (int)scene->mValues.size(); for (auto* value : scene->mValues) { out << value->mId; out << value->mFloatValue; out << value->mBoolValue; out << value->mIntValue; } } IDrawableModule::SaveState(out); } void SongBuilder::LoadState(FileStreamIn& in, int rev) { int numTargets; in >> numTargets; mTargets.resize(numTargets); for (int i = 0; i < numTargets; ++i) { mTargets[i] = new ControlTarget(); if (rev >= 1) in >> mTargets[i]->mId; mTargets[i]->CreateUIControls(this); mTargets[i]->mCable->LoadState(in); int displayType; in >> displayType; mTargets[i]->mDisplayType = (ControlTarget::DisplayType)displayType; } for (auto* scene : mScenes) scene->CleanUp(); int numScenes; in >> numScenes; mScenes.resize(numScenes); for (int i = 0; i < numScenes; ++i) { mScenes[i] = new SongScene(""); in >> mScenes[i]->mName; in >> mScenes[i]->mId; mScenes[i]->CreateUIControls(this); int numValues; in >> numValues; mScenes[i]->mValues.resize(numValues); for (int j = 0; j < numValues; ++j) { mScenes[i]->mValues[j] = new ControlValue(); in >> mScenes[i]->mValues[j]->mId; in >> mScenes[i]->mValues[j]->mFloatValue; in >> mScenes[i]->mValues[j]->mBoolValue; in >> mScenes[i]->mValues[j]->mIntValue; mScenes[i]->mValues[j]->CreateUIControls(this); mScenes[i]->TargetControlUpdated(mTargets[j], j, false); } } RefreshSequencerDropdowns(); mWantRefreshValueDropdowns = true; IDrawableModule::LoadState(in, rev); } void SongBuilder::DuplicateScene(int sceneIndex) { std::vector<std::string> sceneNames; for (auto* scene : mScenes) sceneNames.push_back(scene->mName); std::string numberless = mScenes[sceneIndex]->mName; while (numberless.size() > 1 && isdigit(numberless[numberless.size() - 1])) numberless = numberless.substr(0, numberless.size() - 1); std::string newSceneName = GetUniqueName(numberless, sceneNames); SongScene* newScene = new SongScene(newSceneName); newScene->CreateUIControls(this); mScenes.insert(mScenes.begin() + sceneIndex + 1, newScene); for (auto* value : mScenes[sceneIndex]->mValues) { newScene->AddValue(this); auto* newValue = newScene->mValues[newScene->mValues.size() - 1]; newValue->mFloatValue = value->mFloatValue; newValue->mBoolValue = value->mBoolValue; newValue->mIntValue = value->mIntValue; } RefreshSequencerDropdowns(); } void SongBuilder::AddTarget() { ControlTarget* target = new ControlTarget(); target->CreateUIControls(this); mTargets.push_back(target); for (int i = 0; i < (int)mScenes.size(); ++i) mScenes[i]->AddValue(this); } void SongBuilder::SongScene::CreateUIControls(SongBuilder* owner) { if (mId == -1) { //find unique id mId = 0; for (auto* scene : owner->mScenes) { if (scene != this && mId <= scene->mId) mId = scene->mId + 1; } } #undef UIBLOCK_OWNER #define UIBLOCK_OWNER owner //change owner UIBLOCK0(); BUTTON_STYLE(mActivateButton, ("go" + ofToString(mId)).c_str(), ButtonDisplayStyle::kPlay); TEXTENTRY(mNameEntry, ("name" + ofToString(mId)).c_str(), 12, &mName); DROPDOWN(mContextMenu, ("context " + ofToString(mId)).c_str(), (int*)(&mContextMenuSelection), 20); ENDUIBLOCK0(); #undef UIBLOCK_OWNER #define UIBLOCK_OWNER this //reset mContextMenu->AddLabel("duplicate", (int)ContextMenuItems::kDuplicate); mContextMenu->AddLabel("delete", (int)ContextMenuItems::kDelete); mContextMenu->AddLabel("move up", (int)ContextMenuItems::kMoveUp); mContextMenu->AddLabel("move down", (int)ContextMenuItems::kMoveDown); mContextMenu->SetCableTargetable(false); mContextMenu->SetDisplayStyle(DropdownDisplayStyle::kHamburger); } void SongBuilder::SongScene::AddValue(SongBuilder* owner) { ControlValue* value = new ControlValue(); value->CreateUIControls(owner); int index = (int)mValues.size(); mValues.push_back(value); TargetControlUpdated(owner->mTargets[index], index, false); } void SongBuilder::SongScene::TargetControlUpdated(SongBuilder::ControlTarget* target, int targetIndex, bool wasManuallyPatched) { IUIControl* control = target->GetTarget(); if (control != nullptr) { if (!target->mHadTarget) { mValues[targetIndex]->mFloatValue = control->GetValue(); mValues[targetIndex]->mBoolValue = control->GetValue() > 0; mValues[targetIndex]->mIntValue = (int)control->GetValue(); mValues[targetIndex]->UpdateDropdownContents(target); } } else if (wasManuallyPatched) //user intentionally deleted connection { mValues[targetIndex]->CleanUp(); mValues.erase(mValues.begin() + targetIndex); } } void SongBuilder::SongScene::Draw(SongBuilder* owner, float x, float y, int sceneIndex) { float width = GetWidth(); float height = kRowHeight; ofPushStyle(); ofNoFill(); ofSetColor(ofColor(150, 150, 150)); ofRect(x, y, width, height); if (sceneIndex == owner->mCurrentScene) { ofFill(); ofSetColor(ofColor(130, 130, 130, 130)); ofRect(x, y, width, height); } if (sceneIndex == owner->mQueuedScene) { ofFill(); ofSetColor(ofColor(0, 130, 0, ofMap(sin(TheTransport->GetMeasurePos(gTime) * TWO_PI * 4), -1, 1, 50, 100))); ofRect(x, y, width, height); } ofPopStyle(); mActivateButton->SetPosition(x + 3, y + 3); mActivateButton->Draw(); mNameEntry->PositionTo(mActivateButton, kAnchor_Right); mNameEntry->Draw(); mContextMenu->PositionTo(mNameEntry, kAnchor_Right); mContextMenu->Draw(); for (int i = 0; i < (int)mValues.size(); ++i) mValues[i]->Draw(x + kSceneTabWidth + i * (kColumnWidth + kSpacingX), y, sceneIndex, owner->mTargets[i]); } void SongBuilder::SongScene::MoveValue(int index, int amount) { if (index + amount >= 0 && index + amount < (int)mValues.size()) { ControlValue* value = mValues[index]; mValues.erase(mValues.begin() + index); index += amount; mValues.insert(mValues.begin() + index, value); } } float SongBuilder::SongScene::GetWidth() const { return kSceneTabWidth + (int)mValues.size() * (kColumnWidth + kSpacingX); } void SongBuilder::SongScene::CleanUp() { mNameEntry->RemoveFromOwner(); mActivateButton->RemoveFromOwner(); mContextMenu->RemoveFromOwner(); for (auto& value : mValues) value->CleanUp(); } void SongBuilder::ControlTarget::CreateUIControls(SongBuilder* owner) { if (mId == -1) { //find unique id mId = 0; for (auto* target : owner->mTargets) { if (target != this && target != nullptr && mId <= target->mId) mId = target->mId + 1; } } mOwner = owner; mCable = new PatchCableSource(owner, kConnectionType_UIControl); owner->AddPatchCableSource(mCable); mCable->SetAllowMultipleTargets(true); mCable->SetOverrideCableDir(ofVec2f(0, 1), PatchCableSource::Side::kBottom); mMoveLeftButton = new ClickButton(owner, "move left", -1, -1, ButtonDisplayStyle::kArrowLeft); mMoveRightButton = new ClickButton(owner, "move right", -1, -1, ButtonDisplayStyle::kArrowRight); mCycleDisplayTypeButton = new ClickButton(owner, "type", -1, -1); mColorSelector = new DropdownList(owner, ("color" + ofToString(mId)).c_str(), -1, -1, &mColorIndex, 25); // Block modulation cables from connecting to these controls as it behaves wrong (and saves incorrectly) except for the color button, that one is fun and works. mMoveLeftButton->SetCableTargetable(false); mMoveRightButton->SetCableTargetable(false); mCycleDisplayTypeButton->SetCableTargetable(false); for (int i = 0; i < (int)owner->mColors.size(); ++i) mColorSelector->AddLabel(owner->mColors[i].name, i); mColorSelector->SetDrawTriangle(false); } void SongBuilder::ControlTarget::Draw(float x, float y, int numRows) { ofPushStyle(); ofFill(); ofSetColor(GetColor() * .7f); ofRect(x, y, kColumnWidth, kTargetTabHeightTop); ofRect(x, y + kTargetTabHeightTop + kSpacingY + numRows * (kRowHeight + kSpacingY), kColumnWidth, kTargetTabHeightBottom); ofPopStyle(); IUIControl* target = GetTarget(); if (target) { ofPushMatrix(); ofClipWindow(x, y, kColumnWidth, kTargetTabHeightTop, true); std::string text = target->Path(false, true); if (mDisplayType == DisplayType::Checkbox) ofStringReplace(text, "~enabled", ""); std::string displayString; const int kSliceSize = 11; int cursor = 0; for (; cursor + kSliceSize < (int)text.size(); cursor += kSliceSize) displayString += text.substr(cursor, kSliceSize) + "\n"; displayString += text.substr(cursor, (int)text.size() - cursor); DrawTextNormal(displayString, x + 2, y + 9, 7); ofPopMatrix(); } float bottomY = y + kTargetTabHeightTop + kSpacingY + numRows * (kRowHeight + kSpacingY); mCable->SetManualPosition(x + kColumnWidth * .5f, bottomY + 5); mCable->SetColor(GetColor()); mMoveLeftButton->SetPosition(x, bottomY - 3); if (gHoveredUIControl == mMoveLeftButton) mMoveLeftButton->Draw(); mMoveRightButton->SetPosition(x + kColumnWidth - 20, bottomY - 3); if (gHoveredUIControl == mMoveRightButton) mMoveRightButton->Draw(); mCycleDisplayTypeButton->SetPosition(x, y + kTargetTabHeightTop - 15); if (gHoveredUIControl == mCycleDisplayTypeButton) mCycleDisplayTypeButton->Draw(); mColorSelector->SetPosition(x + 25, y + kTargetTabHeightTop - 15); if (gHoveredUIControl == mColorSelector) mColorSelector->Draw(); } IUIControl* SongBuilder::ControlTarget::GetTarget() const { IUIControl* target = nullptr; if (!mCable->GetPatchCables().empty()) target = dynamic_cast<IUIControl*>(mCable->GetPatchCables()[0]->GetTarget()); return target; } void SongBuilder::ControlTarget::TargetControlUpdated() { IUIControl* target = GetTarget(); if (dynamic_cast<Checkbox*>(target) != nullptr || dynamic_cast<ClickButton*>(target) != nullptr) mDisplayType = DisplayType::Checkbox; else if (dynamic_cast<DropdownList*>(target) != nullptr || dynamic_cast<RadioButton*>(target) != nullptr) mDisplayType = DisplayType::Dropdown; else mDisplayType = DisplayType::TextEntry; } void SongBuilder::ControlTarget::CleanUp() { mCable->GetOwner()->RemovePatchCableSource(mCable); mMoveLeftButton->RemoveFromOwner(); mMoveRightButton->RemoveFromOwner(); mCycleDisplayTypeButton->RemoveFromOwner(); mColorSelector->RemoveFromOwner(); } void SongBuilder::ControlValue::CreateUIControls(SongBuilder* owner) { if (mId == -1) { //find unique id mId = 0; for (auto* scene : owner->mScenes) { for (auto* value : scene->mValues) { if (value != this && mId <= value->mId) mId = value->mId + 1; } } } mValueEntry = new TextEntry(owner, ("value " + ofToString(mId)).c_str(), -1, -1, 4, &mFloatValue, -9999, 9999); mCheckbox = new Checkbox(owner, ("checkbox " + ofToString(mId)).c_str(), -1, -1, &mBoolValue); mCheckbox->SetDisplayText(false); mValueSelector = new DropdownList(owner, ("dropdown " + ofToString(mId)).c_str(), -1, -1, &mIntValue, kColumnWidth); mValueSelector->SetDrawTriangle(false); mValueEntry->SetShowing(false); mCheckbox->SetShowing(false); mValueSelector->SetShowing(false); } void SongBuilder::ControlValue::Draw(float x, float y, int sceneIndex, ControlTarget* target) { ofPushStyle(); ofFill(); ofSetColor(target->GetColor() * .7f); ofRect(x, y + 2, kColumnWidth, kRowHeight - 4); ofPopStyle(); mValueEntry->SetPosition(x + 7, y + 3); mValueEntry->Draw(); mCheckbox->SetPosition(x + 20, y + 3); mCheckbox->Draw(); mValueSelector->SetPosition(x, y + 2); mValueEntry->SetShowing(target->GetTarget() && target->mDisplayType == ControlTarget::DisplayType::TextEntry); mCheckbox->SetShowing(target->GetTarget() && target->mDisplayType == ControlTarget::DisplayType::Checkbox); mValueSelector->SetShowing(target->GetTarget() && target->mDisplayType == ControlTarget::DisplayType::Dropdown); mValueSelector->Draw(); } void SongBuilder::ControlValue::CleanUp() { mValueEntry->RemoveFromOwner(); mCheckbox->RemoveFromOwner(); mValueSelector->RemoveFromOwner(); } ```
/content/code_sandbox/Source/SongBuilder.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
11,084
```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 **/ // // NoteTable.h // modularSynth // // Created by Ryan Challinor on 11/3/13. // // #pragma once #include <iostream> #include "INoteReceiver.h" #include "IDrawableModule.h" #include "DropdownList.h" #include "ClickButton.h" #include "INoteSource.h" #include "Slider.h" #include "UIGrid.h" #include "Scale.h" #include "GridController.h" #include "Push2Control.h" class PatchCableSource; class NoteTable : public IDrawableModule, public INoteSource, public IButtonListener, public IDropdownListener, public IIntSliderListener, public IFloatSliderListener, public UIGridListener, public INoteReceiver, public IGridControllerListener, public IPush2GridController { public: NoteTable(); virtual ~NoteTable(); static IDrawableModule* Create() { return new NoteTable(); } 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; } void Poll() override; UIGrid* GetGrid() const { return mGrid; } int RowToPitch(int row); int PitchToRow(int pitch); //IDrawableModule bool IsResizable() const override { return true; } void Resize(float w, float h) override; //IClickable void MouseReleased() override; bool MouseMoved(float x, float y) 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; //IPush2GridController bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) override; void UpdatePush2Leds(Push2Control* push2) 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; 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); void PlayColumn(double time, int column, int velocity, int voiceIdx, ModulationParameters modulation); float ExtraWidth() const; float ExtraHeight() const; void RandomizePitches(bool fifths); void GetPush2Layout(int& sequenceRows, int& pitchCols, int& pitchRows); void SetColumnRow(int column, int row); enum NoteMode { kNoteMode_Scale, kNoteMode_Chromatic, kNoteMode_Pentatonic, kNoteMode_Fifths }; UIGrid* mGrid{ nullptr }; int mOctave{ 3 }; IntSlider* mOctaveSlider{ nullptr }; NoteMode mNoteMode{ NoteMode::kNoteMode_Scale }; DropdownList* mNoteModeSelector{ nullptr }; int mLength{ 8 }; IntSlider* mLengthSlider{ nullptr }; int mNoteRange{ 15 }; bool mShowColumnCables{ false }; int mRowOffset{ 0 }; ClickButton* mRandomizePitchButton{ nullptr }; float mRandomizePitchChance{ 1 }; float mRandomizePitchRange{ 1 }; FloatSlider* mRandomizePitchChanceSlider{ nullptr }; FloatSlider* mRandomizePitchRangeSlider{ nullptr }; ClickButton* mClearButton{ nullptr }; static constexpr int kMaxLength = 32; std::array<double, kMaxLength> mLastColumnPlayTime{}; std::array<bool[128], kMaxLength> mLastColumnNoteOnPitches{}; std::array<AdditionalNoteCable*, kMaxLength> mColumnCables{ nullptr }; std::array<double, 128> mPitchPlayTimes{}; std::array<bool, 128> mQueuedPitches{}; GridControlTarget* mGridControlTarget{ nullptr }; int mGridControlOffsetX{ 0 }; int mGridControlOffsetY{ 0 }; IntSlider* mGridControlOffsetXSlider{ nullptr }; IntSlider* mGridControlOffsetYSlider{ nullptr }; int mPush2HeldStep{ -1 }; enum class Push2GridDisplayMode { PerStep, GridView }; Push2GridDisplayMode mPush2GridDisplayMode{ Push2GridDisplayMode::PerStep }; }; ```
/content/code_sandbox/Source/NoteTable.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,362
```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 **/ // // SlowLayers.h // Bespoke // // Created by Ryan Challinor on 1/13/15. // // #pragma once #include <iostream> #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "RollingBuffer.h" #include "ClickButton.h" #include "RadioButton.h" #include "Slider.h" #include "DropdownList.h" class SlowLayers : public IAudioProcessor, public IDrawableModule, public IDropdownListener, public IButtonListener, public IFloatSliderListener, public IRadioButtonListener { public: SlowLayers(); virtual ~SlowLayers(); static IDrawableModule* Create() { return new SlowLayers(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Clear(); int NumBars() { return mNumBars; } void SetNumBars(int numBars); //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IAudioProcessor InputMode GetInputMode() override { return kInputMode_Mono; } bool CheckNeedsDraw() override { return true; } void ButtonClicked(ClickButton* button, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void DropdownUpdated(DropdownList* list, 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; int LoopLength() const; static const int BUFFER_X = 4; static const int BUFFER_Y = 4; static const int BUFFER_W = 155; static const int BUFFER_H = 93; float* mBuffer{ nullptr }; float mLoopPos{ 0 }; int mNumBars{ 1 }; float mVol{ 1 }; float mFeedIn{ 1 }; float mSmoothedVol{ 1 }; FloatSlider* mVolSlider{ nullptr }; ClickButton* mClearButton{ nullptr }; DropdownList* mNumBarsSelector{ nullptr }; FloatSlider* mFeedInSlider{ nullptr }; }; ```
/content/code_sandbox/Source/SlowLayers.h
objective-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 **/ // // EffectChain.cpp // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #include "EffectChain.h" #include "IAudioEffect.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" const double gSwapLength = 150.0; EffectChain::EffectChain() : IAudioProcessor(gBufferSize) , mDryBuffer(gBufferSize) { } EffectChain::~EffectChain() { for (int i = 0; i < mEffects.size(); ++i) delete mEffects[i]; } void EffectChain::CreateUIControls() { IDrawableModule::CreateUIControls(); mVolumeSlider = new FloatSlider(this, "volume", 10, 100, 100, 15, &mVolume, 0, 2); mEffectSpawnList = new DropdownList(this, "effect", 10, 100, &mSpawnIndex); mSpawnEffectButton = new ClickButton(this, "spawn", -1, -1); mPush2ExitEffectButton = new ClickButton(this, "exit effect", HIDDEN_UICONTROL, HIDDEN_UICONTROL); mPush2ExitEffectButton->SetShowing(false); } void EffectChain::Init() { IDrawableModule::Init(); mEffectTypesToSpawn = TheSynth->GetEffectFactory()->GetSpawnableEffects(); mEffectSpawnList->SetUnknownItemString("add effect:"); for (int i = 0; i < mEffectTypesToSpawn.size(); ++i) mEffectSpawnList->AddLabel(mEffectTypesToSpawn[i].c_str(), i); mInitialized = true; } void EffectChain::AddEffect(std::string type, std::string desiredName, bool onTheFly) { if (mEffects.size() >= MAX_EFFECTS_IN_CHAIN) return; IAudioEffect* effect = TheSynth->GetEffectFactory()->MakeEffect(type); if (effect == nullptr) throw UnknownEffectTypeException(); assert(effect->GetType() == type); //make sure things are named the same in code std::vector<std::string> otherEffectNames; for (auto* e : mEffects) otherEffectNames.push_back(e->Name()); std::string name = GetUniqueName(desiredName, otherEffectNames); effect->SetName(name.c_str()); effect->SetTypeName(type, kModuleCategory_Processor); effect->SetParent(this); effect->CreateUIControls(); if (onTheFly) { ofxJSONElement empty; effect->LoadLayoutBase(empty); effect->SetUpFromSaveDataBase(); } if (mInitialized) //if we've already been initialized, call init on this effect->Init(); mEffectMutex.lock(); mEffects.push_back(effect); mEffectMutex.unlock(); AddChild(effect); float* dryWet = &(mDryWetLevels[mEffects.size() - 1]); *dryWet = 1; EffectControls controls; controls.mMoveLeftButton = new ClickButton(this, "<", 0, 0); controls.mMoveLeftButton->SetCableTargetable(false); controls.mMoveRightButton = new ClickButton(this, ">", 0, 0); controls.mMoveRightButton->SetCableTargetable(false); controls.mDeleteButton = new ClickButton(this, "x", 0, 0); controls.mDeleteButton->SetCableTargetable(false); controls.mDryWetSlider = new FloatSlider(this, ("mix" + ofToString(mEffects.size() - 1)).c_str(), 0, 0, 60, 13, dryWet, 0, 1, 2); controls.mPush2DisplayEffectButton = new ClickButton(this, ("edit " + name).c_str(), 0, 0); controls.mPush2DisplayEffectButton->SetShowing(false); controls.mPush2DisplayEffectButton->SetCableTargetable(false); mEffectControls.push_back(controls); } void EffectChain::Process(double time) { IAudioReceiver* target = GetTarget(); if (target == nullptr) return; ComputeSliders(0); SyncBuffers(); mDryBuffer.SetNumActiveChannels(GetBuffer()->NumActiveChannels()); int bufferSize = GetBuffer()->BufferSize(); if (mEnabled) { mEffectMutex.lock(); for (int i = 0; i < mEffects.size(); ++i) { mDryBuffer.CopyFrom(GetBuffer()); mEffects[i]->ProcessAudio(time, GetBuffer()); float* dryWetBuffer = gWorkBuffer; float* invDryWetBuffer = gWorkBuffer + bufferSize; for (int j = 0; j < bufferSize; ++j) { ComputeSliders(j); dryWetBuffer[j] = mDryWetLevels[i]; invDryWetBuffer[j] = 1.0f - mDryWetLevels[i]; } for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Mult(mDryBuffer.GetChannel(ch), invDryWetBuffer, bufferSize); Mult(GetBuffer()->GetChannel(ch), dryWetBuffer, bufferSize); Add(GetBuffer()->GetChannel(ch), mDryBuffer.GetChannel(ch), bufferSize); } } mEffectMutex.unlock(); } for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { float* buffer = GetBuffer()->GetChannel(ch); float volSq = mVolume * mVolume; for (int i = 0; i < bufferSize; ++i) buffer[i] *= volSq; Add(target->GetBuffer()->GetChannel(ch), buffer, bufferSize); GetVizBuffer()->WriteChunk(buffer, bufferSize, ch); } GetBuffer()->Reset(); } void EffectChain::Poll() { if (mWantToDeleteEffectAtIndex != -1) { DeleteEffect(mWantToDeleteEffectAtIndex); mWantToDeleteEffectAtIndex = -1; } } void EffectChain::DrawModule() { if (Minimized() || IsVisible() == false) return; mEffectSpawnList->SetShowing(mShowSpawnList); mSpawnEffectButton->SetShowing(mShowSpawnList && mSpawnIndex != -1); if (mSpawnIndex != -1) mSpawnEffectButton->SetLabel((std::string("spawn ") + mEffectSpawnList->GetLabel(mSpawnIndex)).c_str()); for (int i = 0; i < mEffects.size(); ++i) { ofVec2f pos = GetEffectPos(i); if (gTime < mSwapTime) //in swap animation { double progress = 1 - (mSwapTime - gTime) / gSwapLength; if (i == mSwapFromIdx) { pos.set(mSwapToPos.x * (1 - progress) + pos.x * progress, mSwapToPos.y * (1 - progress) + pos.y * progress); } if (i == mSwapToIdx) { pos.set(mSwapFromPos.x * (1 - progress) + pos.x * progress, mSwapFromPos.y * (1 - progress) + pos.y * progress); } } mEffects[i]->SetPosition(pos.x, pos.y); float w, h; mEffects[i]->GetDimensions(w, h); w = MAX(w, MIN_EFFECT_WIDTH); mEffectControls[i].mMoveLeftButton->SetShowing(i > 0); mEffectControls[i].mMoveLeftButton->SetPosition(pos.x + w / 2 - 46, pos.y - 30); mEffectControls[i].mMoveLeftButton->Draw(); mEffectControls[i].mMoveRightButton->SetShowing(i < (int)mEffects.size() - 1 && !(GetKeyModifiers() & kModifier_Shift)); mEffectControls[i].mMoveRightButton->SetPosition(pos.x + w / 2 + 35, pos.y - 30); mEffectControls[i].mMoveRightButton->Draw(); mEffectControls[i].mDeleteButton->SetShowing(i == (int)mEffects.size() - 1 || (GetKeyModifiers() & kModifier_Shift)); mEffectControls[i].mDeleteButton->SetPosition(pos.x + w / 2 + 35, pos.y - 30); mEffectControls[i].mDeleteButton->Draw(); mEffectControls[i].mDryWetSlider->SetPosition(pos.x + w / 2 - 30, pos.y - 29); mEffectControls[i].mDryWetSlider->Draw(); } for (int i = 0; i < mEffects.size(); ++i) { mEffects[i]->Draw(); float x, y, w, h; mEffects[i]->GetPosition(x, y, true); mEffects[i]->GetDimensions(w, h); w = MAX(w, MIN_EFFECT_WIDTH); if (mDryWetLevels[i] == 0) { ofPushStyle(); ofFill(); ofSetColor(0, 0, 0, 100); ofRect(x, y - IDrawableModule::TitleBarHeight(), w, h + IDrawableModule::TitleBarHeight()); ofPopStyle(); } if (i < mEffects.size() - 1) { ofPushMatrix(); ofTranslate(x, y); mEffects[i]->DrawConnection(mEffects[i + 1]); ofPopMatrix(); } } float w, h; GetDimensions(w, h); mVolumeSlider->SetPosition(4, h - 17); mVolumeSlider->Draw(); mEffectSpawnList->SetPosition(106, h - 17); mEffectSpawnList->Draw(); mSpawnEffectButton->SetPosition(mEffectSpawnList->GetRect(true).getMaxX() + 2, h - 17); mSpawnEffectButton->Draw(); } int EffectChain::NumRows() const { return ((int)mEffects.size() + mNumFXWide - 1) / mNumFXWide; //round up } int EffectChain::GetRowHeight(int row) const { float max = 0; for (int i = 0; i < mEffects.size(); ++i) { if (i / mNumFXWide == row) { float w, h; mEffects[i]->GetDimensions(w, h); h += IDrawableModule::TitleBarHeight(); h += 20; max = MAX(h, max); } } return max; } ofVec2f EffectChain::GetEffectPos(int index) const { float xPos = 10; float yPos = 32; for (int i = 0; i < mEffects.size(); ++i) { if (i > 0 && i % mNumFXWide == 0) //newline { xPos = 10; yPos += GetRowHeight(i / mNumFXWide - 1); } if (i == index) return ofVec2f(xPos, yPos); float w, h; mEffects[i]->GetDimensions(w, h); w = MAX(w, MIN_EFFECT_WIDTH); xPos += w + 20; } return ofVec2f(xPos, yPos); } void EffectChain::GetPush2OverrideControls(std::vector<IUIControl*>& controls) const { int effectIndex = -1; if (mPush2DisplayEffect != nullptr) { for (int i = 0; i < (int)mEffects.size(); ++i) { if (mEffects[i] == mPush2DisplayEffect) effectIndex = i; } } if (effectIndex == -1) { controls.push_back(mVolumeSlider); controls.push_back(mEffectSpawnList); for (int i = 0; i < (int)mEffects.size(); ++i) controls.push_back(mEffectControls[i].mPush2DisplayEffectButton); if (mSpawnIndex != -1) controls.push_back(mSpawnEffectButton); } else { controls.push_back(mEffectControls[effectIndex].mDryWetSlider); controls.push_back(mPush2ExitEffectButton); controls.push_back(mEffectControls[effectIndex].mMoveLeftButton); controls.push_back(mEffectControls[effectIndex].mMoveRightButton); controls.push_back(mEffectControls[effectIndex].mDeleteButton); for (auto* control : mPush2DisplayEffect->GetUIControls()) controls.push_back(control); } } void EffectChain::GetModuleDimensions(float& width, float& height) { int maxX = 100; if (mShowSpawnList) maxX += 100; int maxY = 0; for (int i = 0; i < mEffects.size(); ++i) { float x, y, w, h; mEffects[i]->GetPosition(x, y, true); mEffects[i]->GetDimensions(w, h); w = MAX(w, MIN_EFFECT_WIDTH); maxX = MAX(maxX, x + w); maxY = MAX(maxY, y + h); } width = maxX + 10; height = maxY + 24; } void EffectChain::KeyPressed(int key, bool isRepeat) { IDrawableModule::KeyPressed(key, isRepeat); for (int i = 0; i < mEffects.size(); ++i) mEffects[i]->KeyPressed(key, isRepeat); } void EffectChain::KeyReleased(int key) { for (int i = 0; i < mEffects.size(); ++i) mEffects[i]->KeyReleased(key); } void EffectChain::DeleteEffect(int index) { assert(!mEffects.empty()); { RemoveUIControl(mEffectControls[index].mMoveLeftButton); RemoveUIControl(mEffectControls[index].mMoveRightButton); RemoveUIControl(mEffectControls[index].mDeleteButton); RemoveUIControl(mEffectControls[index].mDryWetSlider); RemoveUIControl(mEffectControls[index].mPush2DisplayEffectButton); mEffectControls[index].mMoveLeftButton->Delete(); mEffectControls[index].mMoveRightButton->Delete(); mEffectControls[index].mDeleteButton->Delete(); mEffectControls[index].mDryWetSlider->Delete(); mEffectControls[index].mPush2DisplayEffectButton->Delete(); //remove the element from mEffectControls int i = 0; for (auto iter = mEffectControls.begin(); iter != mEffectControls.end(); ++iter) { if (iter->mDeleteButton == mEffectControls[index].mDeleteButton) //delete buttons match, we found the right one { mEffectControls.erase(iter); break; } ++i; } for (; i < mEffectControls.size() + 1; ++i) mDryWetLevels[i] = mDryWetLevels[i + 1]; UpdateReshuffledDryWetSliders(); } { mEffectMutex.lock(); IAudioEffect* toRemove = mEffects[index]; RemoveFromVector(toRemove, mEffects); RemoveChild(toRemove); //delete toRemove; TODO(Ryan) can't do this in case stuff is referring to its UI controls mEffectMutex.unlock(); } } void EffectChain::MoveEffect(int fromIndex, int direction) { int newIndex = fromIndex + direction; if (newIndex >= 0 && newIndex < mEffects.size()) { mSwapFromIdx = fromIndex; mSwapToIdx = newIndex; mEffects[mSwapFromIdx]->GetPosition(mSwapFromPos.x, mSwapFromPos.y, true); mEffects[mSwapToIdx]->GetPosition(mSwapToPos.x, mSwapToPos.y, true); mSwapTime = gTime + gSwapLength; mEffectMutex.lock(); IAudioEffect* swap = mEffects[newIndex]; mEffects[newIndex] = mEffects[fromIndex]; mEffects[fromIndex] = swap; mEffectMutex.unlock(); float level = mDryWetLevels[newIndex]; mDryWetLevels[newIndex] = mDryWetLevels[fromIndex]; mDryWetLevels[fromIndex] = level; FloatSlider* dryWetSlider = mEffectControls[newIndex].mDryWetSlider; mEffectControls[newIndex].mDryWetSlider = mEffectControls[fromIndex].mDryWetSlider; mEffectControls[fromIndex].mDryWetSlider = dryWetSlider; ClickButton* displayButton = mEffectControls[newIndex].mPush2DisplayEffectButton; mEffectControls[newIndex].mPush2DisplayEffectButton = mEffectControls[fromIndex].mPush2DisplayEffectButton; mEffectControls[fromIndex].mPush2DisplayEffectButton = displayButton; UpdateReshuffledDryWetSliders(); } } void EffectChain::UpdateReshuffledDryWetSliders() { for (size_t i = 0; i < mEffectControls.size(); ++i) { mEffectControls[i].mDryWetSlider->SetName(("mix" + ofToString(i)).c_str()); mEffectControls[i].mDryWetSlider->SetVar(&mDryWetLevels[i]); } } void EffectChain::ButtonClicked(ClickButton* button, double time) { if (button == mSpawnEffectButton) { if (mSpawnIndex >= 0 && mSpawnIndex < (int)mEffectTypesToSpawn.size()) { AddEffect(mEffectTypesToSpawn[mSpawnIndex], mEffectTypesToSpawn[mSpawnIndex], K(onTheFly)); mSpawnIndex = -1; } } if (button == mPush2ExitEffectButton) mPush2DisplayEffect = nullptr; for (int i = 0; i < (int)mEffectControls.size(); ++i) { if (button == mEffectControls[i].mMoveLeftButton) MoveEffect(i, -1); if (button == mEffectControls[i].mMoveRightButton) MoveEffect(i, 1); if (button == mEffectControls[i].mDeleteButton) { mWantToDeleteEffectAtIndex = i; return; } if (button == mEffectControls[i].mPush2DisplayEffectButton) { mPush2DisplayEffect = mEffects[i]; mPush2ExitEffectButton->SetLabel((std::string("exit ") + mEffects[i]->Name()).c_str()); } } } void EffectChain::CheckboxUpdated(Checkbox* checkbox, double time) { } void EffectChain::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void EffectChain::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mEffectSpawnList) { if (TheSynth->GetTopModalFocusItem() == mEffectSpawnList->GetModalDropdown()) { AddEffect(mEffectTypesToSpawn[mSpawnIndex], mEffectTypesToSpawn[mSpawnIndex], K(onTheFly)); mSpawnIndex = -1; } } } std::vector<IUIControl*> EffectChain::ControlsToIgnoreInSaveState() const { std::vector<IUIControl*> ignore; ignore.push_back(mSpawnEffectButton); return ignore; } void EffectChain::UpdateOldControlName(std::string& oldName) { IDrawableModule::UpdateOldControlName(oldName); if (oldName.size() > 2 && oldName[0] == 'd' && oldName[1] == 'w') ofStringReplace(oldName, "dw", "mix"); } void EffectChain::LoadBasics(const ofxJSONElement& moduleInfo, std::string typeName) { IDrawableModule::LoadBasics(moduleInfo, typeName); const ofxJSONElement& effects = moduleInfo["effects"]; for (int i = 0; i < effects.size(); ++i) { try { std::string type = effects[i]["type"].asString(); std::string name; if (effects[i]["name"].isNull()) //old version before name was saved name = type; else name = effects[i]["name"].asString(); AddEffect(type, name, !K(onTheFly)); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } } } void EffectChain::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadInt("widecount", moduleInfo, 5, 1, 50, true); mModuleSaveData.LoadBool("showspawnlist", moduleInfo, true); const ofxJSONElement& effects = moduleInfo["effects"]; assert(mEffects.size() == effects.size()); for (int i = 0; i < mEffects.size(); ++i) { try { std::string type = effects[i]["type"].asString(); assert(mEffects[i]->GetType() == type); mEffects[i]->LoadLayoutBase(effects[i]); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } } SetUpFromSaveData(); } void EffectChain::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); SetWideCount(mModuleSaveData.GetInt("widecount")); mShowSpawnList = mModuleSaveData.GetBool("showspawnlist"); for (int i = 0; i < mEffects.size(); ++i) mEffects[i]->SetUpFromSaveDataBase(); } void EffectChain::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["effects"].resize((unsigned int)mEffects.size()); for (int i = 0; i < mEffects.size(); ++i) { ofxJSONElement save; mEffects[i]->SaveLayoutBase(save); moduleInfo["effects"][i] = save; moduleInfo["effects"][i]["type"] = mEffects[i]->GetType(); } } ```
/content/code_sandbox/Source/EffectChain.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5,026
```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 **/ // // PitchToValue.h // Bespoke // // Created by Andrius Merkys on 12/20/23. // // #pragma once #include "IDrawableModule.h" #include "INoteReceiver.h" #include "IModulator.h" class PatchCableSource; class IUIControl; class PitchToValue : public IDrawableModule, public INoteReceiver, public IModulator { public: PitchToValue(); virtual ~PitchToValue(); static IDrawableModule* Create() { return new PitchToValue(); } static bool AcceptsNotes() { return true; } 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 float Value(int samplesIn = 0) override; bool Active() const override { return mEnabled; } bool CanAdjustRange() const override { return false; } //IPatchable void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 110; height = 0; } bool IsEnabled() const override { return mEnabled; } int mValue; }; ```
/content/code_sandbox/Source/PitchToValue.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
481
```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 **/ // // NoteOctaver.h // modularSynth // // Created by Ryan Challinor on 5/27/13. // // #pragma once #include <iostream> #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Checkbox.h" #include "INoteSource.h" #include "Slider.h" class NoteOctaver : public NoteEffectBase, public IDrawableModule, public IIntSliderListener { public: NoteOctaver(); static IDrawableModule* Create() { return new NoteOctaver(); } 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; //IIntSliderListener 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: struct NoteInfo { bool mOn{ false }; int mVelocity{ 0 }; int mVoiceIdx{ -1 }; int mOutputPitch{ 0 }; }; //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } float mWidth{ 200 }; float mHeight{ 20 }; int mOctave{ 0 }; IntSlider* mOctaveSlider{ nullptr }; std::array<NoteInfo, 128> mInputNotes; Checkbox* mRetriggerCheckbox{ nullptr }; bool mRetrigger{ false }; }; ```
/content/code_sandbox/Source/NoteOctaver.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
551
```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 **/ // // SwitchAndRamp.h // Bespoke // // Created by Ryan Challinor on 03/27/22. // // #pragma once #include "ChannelBuffer.h" class SwitchAndRamp { public: SwitchAndRamp(); void StartSwitch(); float Process(int channel, float input, float rampSpeed = .005f); private: std::array<bool, ChannelBuffer::kMaxNumChannels> mSwitching{ false }; std::array<float, ChannelBuffer::kMaxNumChannels> mLastOutput; std::array<float, ChannelBuffer::kMaxNumChannels> mOffset; }; ```
/content/code_sandbox/Source/SwitchAndRamp.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
231
```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 **/ // // MultiBandTracker.h // modularSynth // // Created by Ryan Challinor on 2/28/14. // // #pragma once #include "OpenFrameworksPort.h" #include "LinkwitzRileyFilter.h" #include "PeakTracker.h" class MultiBandTracker { public: MultiBandTracker(); ~MultiBandTracker(); void SetRange(float minFreq, float maxFreq); void SetNumBands(int numBands); void Process(float* buffer, int bufferSize); float GetBand(int idx); int NumBands() { return mNumBands; } private: std::vector<CLinkwitzRiley_4thOrder> mBands; std::vector<PeakTracker> mPeaks; int mNumBands{ 8 }; float mMinFreq{ 150 }; float mMaxFreq{ 15000 }; float* mWorkBuffer{ nullptr }; ofMutex mMutex; }; ```
/content/code_sandbox/Source/MultiBandTracker.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
305
```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 **/ // // IAudioSource.h // modularSynth // // Created by Ryan Challinor on 11/22/12. // // #pragma once #include "RollingBuffer.h" #include "SynthGlobals.h" #include "IPatchable.h" class IAudioReceiver; #define VIZ_BUFFER_SECONDS .1f class IAudioSource : public virtual IPatchable { public: IAudioSource() : mVizBuffer(VIZ_BUFFER_SECONDS * gSampleRate) {} virtual ~IAudioSource() {} virtual void Process(double time) = 0; IAudioReceiver* GetTarget(int index = 0); virtual int GetNumTargets() { return 1; } RollingBuffer* GetVizBuffer() { return &mVizBuffer; } protected: void SyncOutputBuffer(int numChannels); private: RollingBuffer mVizBuffer; }; ```
/content/code_sandbox/Source/IAudioSource.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
286
```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 **/ // // LaunchpadNoteDisplayer.h // modularSynth // // Created by Ryan Challinor on 4/16/13. // // #pragma once #include <iostream> #include "NoteEffectBase.h" #include "IDrawableModule.h" class LaunchpadKeyboard; class LaunchpadNoteDisplayer : public NoteEffectBase, public IDrawableModule { public: LaunchpadNoteDisplayer(); static IDrawableModule* Create() { return new LaunchpadNoteDisplayer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void SetLaunchpad(LaunchpadKeyboard* launchpad) { mLaunchpad = launchpad; } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void DrawModuleUnclipped() override; void GetModuleDimensions(float& width, float& height) override { width = 80; height = 0; } LaunchpadKeyboard* mLaunchpad{ nullptr }; }; ```
/content/code_sandbox/Source/LaunchpadNoteDisplayer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
406
```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.cpp Created: 2 Nov 2020 10:47:17pm Author: Ryan Challinor ============================================================================== */ #include "EQModule.h" #include "ModularSynth.h" #include "Profiler.h" #include "UIControlMacros.h" #include "Checkbox.h" EQModule::EQModule() : IAudioProcessor(gBufferSize) , mFFT(kNumFFTBins) , mFFTData(kNumFFTBins, kNumFFTBins / 2 + 1) , mRollingInputBuffer(kNumFFTBins) { // Generate a window with a single raised cosine from N/4 to 3N/4 mWindower = new float[kNumFFTBins]; for (int i = 0; i < kNumFFTBins; ++i) mWindower[i] = -.5f * cos(FTWO_PI * i / kNumFFTBins) + .5f; mSmoother = new float[kNumFFTBins / 2 + 1 - kBinIgnore]; for (int i = 0; i < kNumFFTBins / 2 + 1 - kBinIgnore; ++i) mSmoother[i] = 0; assert(mFilters.size() == 8); auto types = new FilterType[8]{ kFilterType_LowShelf, kFilterType_Peak, kFilterType_Peak, kFilterType_HighShelf, kFilterType_Peak, kFilterType_Peak, kFilterType_Peak, kFilterType_Peak }; auto cutoffs = new float[8]{ 30, 200, 1000, 5000, 100, 10000, 5000, 18000 }; for (size_t i = 0; i < mFilters.size(); ++i) { auto& filter = mFilters[i]; filter.mEnabled = i < 4; for (auto& biquad : filter.mFilter) { biquad.SetFilterParams(cutoffs[i], sqrtf(2) / 2); biquad.SetFilterType(types[i]); } filter.mNeedToCalculateCoefficients = true; } } void EQModule::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); for (size_t i = 0; i < mFilters.size(); ++i) { auto& filter = mFilters[i]; CHECKBOX(filter.mEnabledCheckbox, ("enabled" + ofToString(i)).c_str(), &filter.mEnabled); DROPDOWN(filter.mTypeSelector, ("type" + ofToString(i)).c_str(), (int*)(&filter.mFilter[0].mType), 45); FLOATSLIDER(filter.mFSlider, ("f" + ofToString(i)).c_str(), &filter.mFilter[0].mF, 20, 20000); FLOATSLIDER(filter.mGSlider, ("g" + ofToString(i)).c_str(), &filter.mFilter[0].mDbGain, -15, 15); FLOATSLIDER_DIGITS(filter.mQSlider, ("q" + ofToString(i)).c_str(), &filter.mFilter[0].mQ, .1f, 18, 3); UIBLOCK_NEWCOLUMN(); filter.mTypeSelector->AddLabel("lp", kFilterType_Lowpass); filter.mTypeSelector->AddLabel("hp", kFilterType_Highpass); filter.mTypeSelector->AddLabel("bp", kFilterType_Bandpass); filter.mTypeSelector->AddLabel("pk", kFilterType_Peak); filter.mTypeSelector->AddLabel("nt", kFilterType_Notch); filter.mTypeSelector->AddLabel("hs", kFilterType_HighShelf); filter.mTypeSelector->AddLabel("ls", kFilterType_LowShelf); filter.mFSlider->SetMode(FloatSlider::kSquare); filter.mQSlider->SetMode(FloatSlider::kSquare); filter.mGSlider->SetShowing(filter.mFilter[0].UsesGain()); filter.mQSlider->SetShowing(filter.mFilter[0].UsesQ()); } ENDUIBLOCK0(); } EQModule::~EQModule() { delete[] mWindower; delete[] mSmoother; } void EQModule::Process(double time) { PROFILER(EQModule); if (mLiteCpuModulation) { ComputeSliders(0); for (auto& filter : mFilters) { if (filter.mEnabled) { bool updated = filter.UpdateCoefficientsIfNecessary(); if (updated) mNeedToUpdateFrequencyResponseGraph = true; } } } IAudioReceiver* target = GetTarget(); if (target == nullptr) return; SyncBuffers(); if (mEnabled) { Clear(gWorkBuffer, GetBuffer()->BufferSize()); ChannelBuffer* out = target->GetBuffer(); gWorkChannelBuffer.SetNumActiveChannels(out->NumActiveChannels()); if (!mLiteCpuModulation) //should we try to recalculate filters every sample? { for (int i = 0; i < GetBuffer()->BufferSize(); ++i) { ComputeSliders(i); for (auto& filter : mFilters) { if (filter.mEnabled) { bool updated = filter.UpdateCoefficientsIfNecessary(); if (updated) mNeedToUpdateFrequencyResponseGraph = true; } } for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { float sample = GetBuffer()->GetChannel(ch)[i]; for (auto& filter : mFilters) { if (filter.mEnabled) sample = filter.mFilter[ch].Filter(sample); } gWorkChannelBuffer.GetChannel(ch)[i] = sample; } } } else { for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { BufferCopy(gWorkChannelBuffer.GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); for (auto& filter : mFilters) { if (filter.mEnabled) filter.mFilter[ch].Filter(gWorkChannelBuffer.GetChannel(ch), GetBuffer()->BufferSize()); } } } for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Add(out->GetChannel(ch), gWorkChannelBuffer.GetChannel(ch), GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(gWorkChannelBuffer.GetChannel(ch), GetBuffer()->BufferSize(), ch); } for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) Add(gWorkBuffer, gWorkChannelBuffer.GetChannel(ch), GetBuffer()->BufferSize()); mRollingInputBuffer.WriteChunk(gWorkBuffer, GetBuffer()->BufferSize(), 0); //copy rolling input buffer into working buffer and window it mRollingInputBuffer.ReadChunk(mFFTData.mTimeDomain, kNumFFTBins, 0, 0); Mult(mFFTData.mTimeDomain, mWindower, kNumFFTBins); mFFT.Forward(mFFTData.mTimeDomain, mFFTData.mRealValues, mFFTData.mImaginaryValues); } else //passthrough { for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { float* buffer = GetBuffer()->GetChannel(ch); Add(target->GetBuffer()->GetChannel(ch), buffer, GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(buffer, GetBuffer()->BufferSize(), ch); } } GetBuffer()->Reset(); } void EQModule::DrawModule() { if (Minimized() || IsVisible() == false) return; for (auto& filter : mFilters) { filter.mTypeSelector->SetShowing(filter.mEnabled); filter.mFSlider->SetShowing(filter.mEnabled); filter.mGSlider->SetShowing(filter.mEnabled && filter.mFilter[0].UsesGain()); filter.mQSlider->SetShowing(filter.mEnabled && filter.mFilter[0].UsesQ()); filter.mEnabledCheckbox->Draw(); filter.mTypeSelector->Draw(); filter.mFSlider->Draw(); filter.mQSlider->Draw(); filter.mGSlider->Draw(); } ofPushStyle(); ofPushMatrix(); float w, h; GetDimensions(w, h); h -= kDrawYOffset; //raw ofSetColor(255, 255, 255); ofSetLineWidth(1); int end = kNumFFTBins / 2 + 1; ofBeginShape(); int lastX = -1; for (int i = kBinIgnore; i < end; i++) { float freq = FreqForBin(i); float x = PosForFreq(freq) * w; float samp = ofClamp(sqrtf(fabsf(mFFTData.mRealValues[i]) / end) * 3 * mDrawGain, 0, 1); float y = (1 - samp) * h + kDrawYOffset; if (int(x) != lastX) ofVertex(x, y); lastX = int(x); mSmoother[i - kBinIgnore] = ofLerp(mSmoother[i - kBinIgnore], samp, .1f); } ofEndShape(false); //smoothed ofSetColor(245, 58, 135); ofSetLineWidth(3); ofBeginShape(); for (int i = kBinIgnore; i < end; i++) { float freq = FreqForBin(i); float x = PosForFreq(freq) * w; float y = (1 - mSmoother[i - kBinIgnore]) * h + kDrawYOffset; if (int(x) != lastX) ofVertex(x, y); lastX = int(x); } ofEndShape(false); //frequency response ofSetColor(52, 204, 235); ofSetLineWidth(3); ofBeginShape(); const int kPixelStep = 2; bool updateFrequencyResponseGraph = false; if (mNeedToUpdateFrequencyResponseGraph) { updateFrequencyResponseGraph = true; mNeedToUpdateFrequencyResponseGraph = false; } for (int x = 0; x < w + kPixelStep; x += kPixelStep) { float response = 1; float freq = FreqForPos(x / w); if (freq < gSampleRate / 2) { int responseGraphIndex = x / kPixelStep; if (updateFrequencyResponseGraph || responseGraphIndex >= mFrequencyResponse.size()) { for (auto& filter : mFilters) { if (filter.mEnabled) response *= filter.mFilter[0].GetMagnitudeResponseAt(freq); } if (responseGraphIndex < mFrequencyResponse.size()) mFrequencyResponse[responseGraphIndex] = response; } else { response = mFrequencyResponse[responseGraphIndex]; } ofVertex(x, (.5f - .666f * log10(response)) * h + kDrawYOffset); } } ofEndShape(false); ofSetLineWidth(1); for (size_t i = 0; i < mFilters.size(); ++i) { auto& filter = mFilters[i]; if (filter.mEnabled) { float x = PosForFreq(filter.mFilter[0].mF) * w; float y = PosForGain(filter.mFilter[0].mDbGain) * h + kDrawYOffset; ofFill(); ofSetColor(255, 210, 0); ofCircle(x, y, 8); if (i == mHoveredFilterHandleIndex) { ofNoFill(); ofSetColor(255, 255, 255); ofCircle(x, y, 8); } ofSetColor(0, 0, 0); DrawTextBold(ofToString(i), x - 3, y + 5); } } ofPopMatrix(); ofPopStyle(); } bool EQModule::Filter::UpdateCoefficientsIfNecessary() { if (mNeedToCalculateCoefficients) { mFilter[0].UpdateFilterCoeff(); for (size_t ch = 1; ch < mFilter.size(); ++ch) mFilter[ch].CopyCoeffFrom(mFilter[0]); mNeedToCalculateCoefficients = false; return true; } return false; } void EQModule::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); if (!right) mDragging = true; } void EQModule::MouseReleased() { IDrawableModule::MouseReleased(); mDragging = false; } bool EQModule::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); float w, h; GetDimensions(w, h); h -= kDrawYOffset; if (mDragging) { if (mHoveredFilterHandleIndex != -1) { auto* fSlider = mFilters[mHoveredFilterHandleIndex].mFSlider; auto* gSlider = mFilters[mHoveredFilterHandleIndex].mGSlider; fSlider->SetValue(ofClamp(FreqForPos(x / w), fSlider->GetMin(), fSlider->GetMax()), NextBufferTime(false)); gSlider->SetValue(ofClamp(GainForPos((y - kDrawYOffset) / h), gSlider->GetMin(), gSlider->GetMax()), NextBufferTime(false)); } } else { mHoveredFilterHandleIndex = -1; for (int i = 0; i < mFilters.size(); ++i) { if (mFilters[i].mEnabled && abs(x - PosForFreq(mFilters[i].mFilter[0].mF) * w) < 5 && abs((y - kDrawYOffset) - PosForGain(mFilters[i].mFilter[0].mDbGain) * h) < 5) { mHoveredFilterHandleIndex = i; break; } } } return false; } bool EQModule::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { if (mHoveredFilterHandleIndex != -1) { auto* qSlider = mFilters[mHoveredFilterHandleIndex].mQSlider; float add = (2 * scrollY) / MAX(qSlider->GetModulatorMax() / qSlider->GetValue(), 0.1); if (GetKeyModifiers() & kModifier_Command) { add *= 4; } else if (GetKeyModifiers() & kModifier_Shift) { add /= 10; } qSlider->SetValue(ofClamp(qSlider->GetValue() + add, qSlider->GetMin(), qSlider->GetMax()), NextBufferTime(false)); } return false; } void EQModule::KeyPressed(int key, bool isRepeat) { IDrawableModule::KeyPressed(key, isRepeat); if (mHoveredFilterHandleIndex != -1) { auto* qSlider = mFilters[mHoveredFilterHandleIndex].mQSlider; if (key == '\\') { qSlider->ResetToOriginal(); } else if (key == '[') { qSlider->Halve(); } else if (key == ']') { qSlider->Double(); } else if ((toupper(key) == 'C' || toupper(key) == 'X') && GetKeyModifiers() == kModifier_Command) { TheSynth->CopyTextToClipboard(ofToString(qSlider->GetValue())); } } } void EQModule::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { for (auto& filter : mFilters) { if (filter.mEnabled) { if (slider == filter.mFSlider || slider == filter.mQSlider || slider == filter.mGSlider) { filter.mNeedToCalculateCoefficients = true; } } } } void EQModule::DropdownUpdated(DropdownList* list, int oldVal, double time) { for (auto& filter : mFilters) { if (list == filter.mTypeSelector) { filter.mFilter[0].SetFilterType(filter.mFilter[0].mType); filter.mNeedToCalculateCoefficients = true; } } } void EQModule::CheckboxUpdated(Checkbox* checkbox, double time) { for (auto& filter : mFilters) { if (checkbox == filter.mEnabledCheckbox) { filter.mFilter[0].Clear(); filter.mFilter[1].Clear(); mNeedToUpdateFrequencyResponseGraph = true; } } } void EQModule::GetModuleDimensions(float& w, float& h) { w = MAX(208, mWidth); h = MAX(150, mHeight); } void EQModule::Resize(float w, float h) { mWidth = w; mHeight = h; mModuleSaveData.SetInt("width", w); mModuleSaveData.SetInt("height", h); mNeedToUpdateFrequencyResponseGraph = true; } void EQModule::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadInt("width", moduleInfo, mWidth, 50, 2000, K(isTextField)); mModuleSaveData.LoadInt("height", moduleInfo, mHeight, 50, 2000, K(isTextField)); mModuleSaveData.LoadFloat("draw_gain", moduleInfo, 1, .1f, 4, K(isTextField)); mModuleSaveData.LoadBool("lite_cpu_modulation", moduleInfo, true); SetUpFromSaveData(); } void EQModule::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["width"] = mWidth; moduleInfo["height"] = mHeight; } void EQModule::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mWidth = mModuleSaveData.GetInt("width"); mHeight = mModuleSaveData.GetInt("height"); mDrawGain = mModuleSaveData.GetFloat("draw_gain"); mLiteCpuModulation = mModuleSaveData.GetBool("lite_cpu_modulation"); } ```
/content/code_sandbox/Source/EQModule.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
4,207
```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 **/ // // DistortionEffect.cpp // modularSynth // // Created by Ryan Challinor on 12/2/12. // // #include "DistortionEffect.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "Profiler.h" #include "UIControlMacros.h" DistortionEffect::DistortionEffect() { SetClip(1); for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) { mDCRemover[i].SetFilterParams(10, sqrt(2) / 2); mDCRemover[i].SetFilterType(kFilterType_Highpass); mDCRemover[i].UpdateFilterCoeff(); mPeakTracker[i].SetDecayTime(.1f); } } void DistortionEffect::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); DROPDOWN(mTypeDropdown, "type", (int*)(&mType), 50); FLOATSLIDER(mClipSlider, "clip", &mClip, 0.001f, 1); FLOATSLIDER(mPreampSlider, "preamp", &mPreamp, 1, 10); FLOATSLIDER(mFuzzAmountSlider, "fuzz", &mFuzzAmount, -1, 1); CHECKBOX(mRemoveInputDCCheckbox, "center input", &mRemoveInputDC); ENDUIBLOCK(mWidth, mHeight); mTypeDropdown->AddLabel("clean", kClean); mTypeDropdown->AddLabel("warm", kWarm); mTypeDropdown->AddLabel("dirty", kDirty); mTypeDropdown->AddLabel("soft", kSoft); mTypeDropdown->AddLabel("asym", kAsymmetric); mTypeDropdown->AddLabel("fold", kFold); mTypeDropdown->AddLabel("grungy", kGrungy); } void DistortionEffect::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(DistortionEffect); if (!mEnabled) return; float bufferSize = buffer->BufferSize(); for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) { if (mRemoveInputDC) mDCRemover[ch].Filter(buffer->GetChannel(ch), bufferSize); mPeakTracker[ch].Process(buffer->GetChannel(ch), bufferSize); if (mType == kDirty) { for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); buffer->GetChannel(ch)[i] = (ofClamp((buffer->GetChannel(ch)[i] + mFuzzAmount * mPeakTracker[ch].GetPeak()) * mPreamp * mGain, -1, 1)) / mGain; } } else if (mType == kClean) { for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); buffer->GetChannel(ch)[i] = tanh((buffer->GetChannel(ch)[i] + mFuzzAmount * mPeakTracker[ch].GetPeak()) * mPreamp * mGain) / mGain; } } else if (mType == kWarm) { for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); buffer->GetChannel(ch)[i] = sin((buffer->GetChannel(ch)[i] + mFuzzAmount * mPeakTracker[ch].GetPeak()) * mPreamp * mGain) / mGain; } } else if (mType == kGrungy) { for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); buffer->GetChannel(ch)[i] = asin(ofClamp((buffer->GetChannel(ch)[i] + mFuzzAmount * mPeakTracker[ch].GetPeak()) * mPreamp * mGain, -1, 1)) / mGain; } } //soft and asymmetric from path_to_url~gary/courses/projects/618_2009/NickDonaldson/#Distortion else if (mType == kSoft) { for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); float sample = (buffer->GetChannel(ch)[i] + mFuzzAmount * mPeakTracker[ch].GetPeak()) * mPreamp * mGain; if (sample > 1) sample = .66666f; else if (sample < -1) sample = -.66666f; else sample = sample - (sample * sample * sample) / 3.0f; buffer->GetChannel(ch)[i] = sample / mGain; } } else if (mType == kAsymmetric) { for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); float sample = (buffer->GetChannel(ch)[i] * .5f + mFuzzAmount * mPeakTracker[ch].GetPeak()) * mPreamp * mGain; if (sample >= .320018f) sample = .630035f; else if (sample >= -.08905f) sample = -6.153f * sample * sample + 3.9375f * sample; else if (sample >= -1) sample = -.75f * (1 - powf(1 - (fabsf(sample) - .032847f), 12) + .333f * (fabsf(sample) - .032847f)) + .01f; else sample = -.9818f; buffer->GetChannel(ch)[i] = sample / mGain; } } else if (mType == kFold) { for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); float sample = ofClamp((buffer->GetChannel(ch)[i] * .5f + mFuzzAmount * mPeakTracker[ch].GetPeak()) * mPreamp * mGain, -100, 100); while (sample > 1 || sample < -1) { if (sample > 1) sample = 2 - sample; if (sample < -1) sample = -2 - sample; } buffer->GetChannel(ch)[i] = sample / mGain; } } } } void DistortionEffect::SetClip(float amount) { mClip = amount; mGain = 1 / pow(amount, 3); } void DistortionEffect::GetModuleDimensions(float& width, float& height) { width = mWidth; height = mHeight; } void DistortionEffect::DrawModule() { if (!IsEnabled()) return; mClipSlider->Draw(); mTypeDropdown->Draw(); mPreampSlider->Draw(); mRemoveInputDCCheckbox->Draw(); mFuzzAmountSlider->Draw(); } float DistortionEffect::GetEffectAmount() { if (!mEnabled) return 0; return ofClamp((mPreamp - 1) / 10 + (1 - mClip), 0, 1); } void DistortionEffect::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) mDCRemover[i].Clear(); } } void DistortionEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mClipSlider) SetClip(mClip); } ```
/content/code_sandbox/Source/DistortionEffect.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,796
```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 **/ /* ============================================================================== NoteHocket.h Created: 19 Dec 2019 10:40:58pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IDrawableModule.h" #include "INoteSource.h" #include "Slider.h" #include "TextEntry.h" #include "ClickButton.h" class NoteHocket : public INoteReceiver, public INoteSource, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public ITextEntryListener, public IButtonListener { public: NoteHocket(); static IDrawableModule* Create() { return new NoteHocket(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) override; void SendCC(int control, int value, int voiceIdx = -1) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {} void TextEntryComplete(TextEntry* entry) override {} void ButtonClicked(ClickButton* button, 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 true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void SendNoteToIndex(int index, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation); void Reseed(); void AdjustHeight(); static const int kMaxDestinations = 16; int mNumDestinations{ 5 }; float mWeight[kMaxDestinations]{}; FloatSlider* mWeightSlider[kMaxDestinations]{ nullptr }; std::vector<AdditionalNoteCable*> mDestinationCables; float mWidth{ 200 }; float mHeight{ 20 }; int mLastNoteDestinations[128]; bool mDeterministic{ false }; int mLength{ 4 }; IntSlider* mLengthSlider{ nullptr }; int mSeed{ 0 }; TextEntry* mSeedEntry{ nullptr }; ClickButton* mReseedButton{ nullptr }; ClickButton* mPrevSeedButton{ nullptr }; ClickButton* mNextSeedButton{ nullptr }; }; ```
/content/code_sandbox/Source/NoteHocket.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
698
```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 **/ /* ============================================================================== ModuleContainer.cpp Created: 16 Oct 2016 3:47:21pm Author: Ryan Challinor ============================================================================== */ #include "ModuleContainer.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "TitleBar.h" #include "PerformanceTimer.h" #include "SynthGlobals.h" #include "QuickSpawnMenu.h" #include "Prefab.h" #include "juce_core/juce_core.h" ModuleContainer::ModuleContainer() { } ofVec2f ModuleContainer::GetOwnerPosition() const { if (mOwner) return mOwner->GetPosition(); return ofVec2f(); } void ModuleContainer::GetAllModules(std::vector<IDrawableModule*>& out) { out.insert(out.begin(), mModules.begin(), mModules.end()); for (int i = 0; i < mModules.size(); ++i) { if (mModules[i]->GetContainer()) mModules[i]->GetContainer()->GetAllModules(out); } } void ModuleContainer::DrawContents() { DrawPatchCables(!K(parentMinimized), !K(inFront)); DrawModules(); DrawPatchCables(!K(parentMinimized), K(inFront)); DrawUnclipped(); } void ModuleContainer::DrawModules() { for (int i = (int)mModules.size() - 1; i >= 0; --i) { if (!mModules[i]->AlwaysOnTop()) mModules[i]->Draw(); } for (int i = (int)mModules.size() - 1; i >= 0; --i) { if (mModules[i]->AlwaysOnTop()) mModules[i]->Draw(); } } void ModuleContainer::DrawUnclipped() { for (int i = (int)mModules.size() - 1; i >= 0; --i) { if (!mModules[i]->AlwaysOnTop()) mModules[i]->RenderUnclipped(); } for (int i = (int)mModules.size() - 1; i >= 0; --i) { if (mModules[i]->AlwaysOnTop()) mModules[i]->RenderUnclipped(); } } void ModuleContainer::PostRender() { for (int i = (int)mModules.size() - 1; i >= 0; --i) mModules[i]->PostRender(); } void ModuleContainer::DrawPatchCables(bool parentMinimized, bool inFront) { if (mOwner != nullptr && mOwner->Minimized()) parentMinimized = true; for (int i = (int)mModules.size() - 1; i >= 0; --i) { mModules[i]->DrawPatchCables(parentMinimized, inFront); if (mModules[i]->GetContainer()) mModules[i]->GetContainer()->DrawPatchCables(parentMinimized, inFront); } } void ModuleContainer::Poll() { if (mOwner != nullptr) return; for (int i = 0; i < mModules.size(); ++i) { if (mModules[i]->GetContainer()) mModules[i]->GetContainer()->Poll(); mModules[i]->BasePoll(); } } void ModuleContainer::Clear() { std::vector<IDrawableModule*> modulesToDelete = mModules; for (auto* module : modulesToDelete) { if (module) { if (module->GetContainer()) module->GetContainer()->Clear(); if (module->IsSingleton() == false) DeleteModule(module); } } mModules.clear(); } void ModuleContainer::Exit() { for (int i = 0; i < mModules.size(); ++i) { if (mModules[i]->GetContainer()) mModules[i]->GetContainer()->Exit(); mModules[i]->Exit(); } } void ModuleContainer::KeyPressed(int key, bool isRepeat) { for (int i = 0; i < mModules.size(); ++i) { if (mModules[i]->GetContainer()) mModules[i]->GetContainer()->KeyPressed(key, isRepeat); mModules[i]->KeyPressed(key, isRepeat); } } void ModuleContainer::KeyReleased(int key) { for (int i = 0; i < mModules.size(); ++i) { if (mModules[i]->GetContainer()) mModules[i]->GetContainer()->KeyReleased(key); mModules[i]->KeyReleased(key); } } void ModuleContainer::MouseMoved(float x, float y) { if (mOwner != nullptr) return; for (int i = (int)mModules.size() - 1; i >= 0; --i) //run this backwards so that we can figure out the top hover control { ModuleContainer* subcontainer = mModules[i]->GetContainer(); if (subcontainer) { subcontainer->MouseMoved(x - subcontainer->GetOwnerPosition().x, y - subcontainer->GetOwnerPosition().y); } mModules[i]->NotifyMouseMoved(x, y); } } void ModuleContainer::MouseReleased() { if (mOwner != nullptr) return; for (int i = 0; i < mModules.size(); i++) { ModuleContainer* subcontainer = mModules[i]->GetContainer(); if (subcontainer) subcontainer->MouseReleased(); mModules[i]->MouseReleased(); } } IDrawableModule* ModuleContainer::GetModuleAt(float x, float y) { if (mOwner != nullptr) { float ownerX, ownerY; mOwner->GetPosition(ownerX, ownerY); x -= ownerX; y -= ownerY; } const auto& modalItems = TheSynth->GetModalFocusItemStack(); for (int i = (int)modalItems.size() - 1; i >= 0; --i) { if (modalItems[i]->GetOwningContainer() == this && modalItems[i]->TestClick(x, y, false, true)) return modalItems[i]; } for (int i = 0; i < mModules.size(); ++i) { if (mModules[i]->AlwaysOnTop() && mModules[i]->TestClick(x, y, false, true)) { ModuleContainer* subcontainer = mModules[i]->GetContainer(); if (subcontainer) { IDrawableModule* contained = subcontainer->GetModuleAt(x - subcontainer->GetOwnerPosition().x, y - subcontainer->GetOwnerPosition().y); if (contained) { return contained; } } return mModules[i]; } } for (int i = 0; i < mModules.size(); ++i) { if (!mModules[i]->AlwaysOnTop() && mModules[i]->TestClick(x, y, false, true)) { ModuleContainer* subcontainer = mModules[i]->GetContainer(); if (subcontainer) { IDrawableModule* contained = subcontainer->GetModuleAt(x, y); if (contained) { return contained; } } return mModules[i]; } } return nullptr; } ofVec2f ModuleContainer::GetDrawOffset() { if (mOwner != nullptr && mOwner->GetOwningContainer() != nullptr) return mDrawOffset + mOwner->GetOwningContainer()->GetDrawOffset(); return mDrawOffset; } float ModuleContainer::GetDrawScale() const { if (mOwner != nullptr && mOwner->GetOwningContainer() != nullptr) return mDrawScale * mOwner->GetOwningContainer()->GetDrawScale(); return mDrawScale; } void ModuleContainer::GetModulesWithinRect(ofRectangle rect, std::vector<IDrawableModule*>& output) { output.clear(); for (int i = 0; i < mModules.size(); ++i) { if (mModules[i]->IsWithinRect(rect) && mModules[i] != TheQuickSpawnMenu && mModules[i]->IsShowing()) output.push_back(mModules[i]); } } void ModuleContainer::MoveToFront(IDrawableModule* module) { if (mOwner && mOwner->GetOwningContainer() != nullptr) mOwner->GetOwningContainer()->MoveToFront(mOwner); for (int i = 0; i < mModules.size(); ++i) { if (mModules[i] == module) { for (int j = i; j > 0; --j) mModules[j] = mModules[j - 1]; mModules[0] = module; break; } } } void ModuleContainer::AddModule(IDrawableModule* module) { mModules.push_back(module); MoveToFront(module); TheSynth->OnModuleAdded(module); module->SetOwningContainer(this); if (mOwner) mOwner->AddChild(module); } void ModuleContainer::TakeModule(IDrawableModule* module) { assert(module->GetOwningContainer()); //module must already be in a container ofVec2f oldOwnerPos = module->GetOwningContainer()->GetOwnerPosition(); if (module->GetOwningContainer()->mOwner) module->GetOwningContainer()->mOwner->RemoveChild(module); RemoveFromVector(module, module->GetOwningContainer()->mModules); std::string newName = GetUniqueName(module->Name(), mModules); mModules.push_back(module); MoveToFront(module); ofVec2f offset = oldOwnerPos - GetOwnerPosition(); module->SetPosition(module->GetPosition(true).x + offset.x, module->GetPosition(true).y + offset.y); module->SetOwningContainer(this); if (mOwner) mOwner->AddChild(module); else //root modulecontainer module->SetName(newName.c_str()); } void ModuleContainer::DeleteModule(IDrawableModule* module, bool fail /*= true*/) { if (!module->CanBeDeleted()) return; if (module->HasSpecialDelete()) { module->DoSpecialDelete(); RemoveFromVector(module, mModules, fail); return; } if (module->GetParent()) module->GetParent()->GetModuleParent()->RemoveChild(module); RemoveFromVector(module, mModules, fail); for (const auto iter : mModules) { if (iter->GetPatchCableSource()) { std::vector<PatchCable*> cablesToDestroy; for (auto cable : iter->GetPatchCableSource()->GetPatchCables()) { if (cable->GetTarget() == module) cablesToDestroy.push_back(cable); } for (const auto cable : cablesToDestroy) cable->Destroy(false); } } // Remove all cables that targeted controls on this module IUIControl::DestroyCablesTargetingControls(module->GetUIControls()); for (const auto child : module->GetChildren()) { child->MarkAsDeleted(); child->SetEnabled(false); child->Exit(); TheSynth->OnModuleDeleted(child); } module->MarkAsDeleted(); module->SetEnabled(false); module->Exit(); TheSynth->OnModuleDeleted(module); } void ModuleContainer::DeleteCablesForControl(const IUIControl* control) { // Remove all cables that targetted control on this module std::vector<IDrawableModule*> modules; TheSynth->GetAllModules(modules); std::vector<PatchCable*> cablesToDestroy; for (const auto module_iter : modules) { for (const auto source : module_iter->GetPatchCableSources()) { for (const auto cable : source->GetPatchCables()) { if (cable->GetTarget() == control) { cablesToDestroy.push_back(cable); break; } } } } for (const auto cable : cablesToDestroy) cable->Destroy(false); } IDrawableModule* ModuleContainer::FindModule(std::string name, bool fail) { /*string ownerPath = ""; if (mOwner) ownerPath = mOwner->Path(); if (strstr(name.c_str(), ownerPath.c_str()) != name.c_str()) //path doesn't start with ownerPath return nullptr; name = name.substr(ownerPath.length());*/ if (name == "") return nullptr; for (int i = 0; i < mModules.size(); ++i) { if (name == mModules[i]->Name()) return mModules[i]; std::vector<std::string> tokens = ofSplitString(name, "~"); if (mModules[i]->GetContainer()) { if (tokens[0] == mModules[i]->Name()) { ofStringReplace(name, tokens[0] + "~", "", true); return mModules[i]->GetContainer()->FindModule(name, fail); } } if (tokens.size() == 2 && tokens[0] == mModules[i]->Name()) { IDrawableModule* child = nullptr; try { child = mModules[i]->FindChild(tokens[1].c_str(), fail); } catch (UnknownModuleException& e) { } if (child) return child; } } if (fail) throw UnknownModuleException(name); return nullptr; } IUIControl* ModuleContainer::FindUIControl(std::string path) { /*string ownerPath = ""; if (mOwner) ownerPath = mOwner->Path(); if (strstr(path.c_str(), ownerPath.c_str()) != path.c_str()) //path doesn't start with ownerPath return nullptr; path = path.substr(ownerPath.length());*/ if (path == "") return nullptr; std::vector<std::string> tokens = ofSplitString(path, "~"); std::string control = tokens[tokens.size() - 1]; std::string modulePath = path.substr(0, path.length() - (control.length() + 1)); IDrawableModule* module = FindModule(modulePath, false); if (module) { try { module->OnUIControlRequested(control.c_str()); return module->FindUIControl(control.c_str()); } catch (UnknownUIControlException& e) { TheSynth->LogEvent("Couldn't find UI control at path \"" + path + "\"", kLogEventType_Error); return nullptr; } } TheSynth->LogEvent("Couldn't find module at path \"" + modulePath + "\"", kLogEventType_Error); return nullptr; } bool ModuleContainer::IsHigherThan(IDrawableModule* checkFor, IDrawableModule* checkAgainst) const { while (checkFor->GetParent()) checkFor = dynamic_cast<IDrawableModule*>(checkFor->GetParent()); for (int i = 0; i < mModules.size(); ++i) { if (checkFor == mModules[i]) return true; if (checkAgainst == mModules[i]) return false; } return false; } void ModuleContainer::LoadModules(const ofxJSONElement& modules) { PerformanceTimer timer; { TimerInstance t("load", timer); //two-pass loading for dependencies if (mOwner) IClickable::SetLoadContext(mOwner); { TimerInstance t("create", timer); for (int i = 0; i < modules.size(); ++i) { try { TimerInstance t("create " + modules[i]["name"].asString(), timer); IDrawableModule* module = TheSynth->CreateModule(modules[i]); if (module != nullptr) { //ofLog() << "create " << module->Name(); AddModule(module); } } catch (LoadingJSONException& e) { TheSynth->LogEvent("Couldn't load json", kLogEventType_Error); } } } { TimerInstance t("setup", timer); for (int i = 0; i < modules.size(); ++i) { try { TimerInstance t("setup " + modules[i]["name"].asString(), timer); IDrawableModule* module = FindModule(modules[i]["name"].asString(), true); if (module != nullptr) { //ofLog() << "setup " << module->Name(); TheSynth->SetUpModule(module, modules[i]); } } catch (LoadingJSONException& e) { TheSynth->LogEvent("Couldn't set up modules from json", kLogEventType_Error); } catch (UnknownModuleException& e) { TheSynth->LogEvent("Couldn't find module \"" + e.mSearchName + "\"", kLogEventType_Error); } } } { TimerInstance t("init", timer); for (int i = 0; i < mModules.size(); ++i) { TimerInstance t(std::string("init ") + mModules[i]->Name(), timer); if (mModules[i]->IsSingleton() == false) mModules[i]->Init(); } } IClickable::ClearLoadContext(); } } bool ModuleSorter(const IDrawableModule* a, const IDrawableModule* b) { return std::string(a->Name()) < std::string(b->Name()); } ofxJSONElement ModuleContainer::WriteModules() { if (mOwner) IClickable::SetSaveContext(mOwner); for (auto i = mModules.begin(); i != mModules.end(); ++i) UpdateTarget(*i); ofxJSONElement modules; std::vector<IDrawableModule*> saveModules; for (int i = 0; i < mModules.size(); ++i) { IDrawableModule* module = mModules[i]; if (module->IsSaveable()) saveModules.push_back(module); } sort(saveModules.begin(), saveModules.end(), ModuleSorter); modules.resize((unsigned int)saveModules.size()); for (int i = 0; i < saveModules.size(); ++i) { ofxJSONElement moduleInfo; saveModules[i]->SaveLayoutBase(moduleInfo); modules[i] = moduleInfo; } IClickable::ClearSaveContext(); return modules; } void ModuleContainer::SaveState(FileStreamOut& out) { out << ModularSynth::kSaveStateRev; int savedModules = 0; for (auto* module : mModules) { if (module->IsSaveable()) ++savedModules; } out << savedModules; if (mOwner) IClickable::SetSaveContext(mOwner); for (auto* module : mModules) { if (module->IsSaveable()) { //ofLog() << "Saving " << module->Name(); out << std::string(module->Name()); module->SaveState(out); for (int i = 0; i < GetModuleSeparatorLength(); ++i) out << GetModuleSeparator()[i]; } } IClickable::ClearSaveContext(); } void ModuleContainer::LoadState(FileStreamIn& in) { Prefab::sLastLoadWasPrefab = Prefab::sLoadingPrefab; bool wasLoadingState = TheSynth->IsLoadingState(); TheSynth->SetIsLoadingState(true); static int sModuleContainerLoadStack = 0; ++sModuleContainerLoadStack; int header; in >> header; assert(header <= ModularSynth::kSaveStateRev); ModularSynth::sLoadingFileSaveStateRev = header; ModularSynth::sLastLoadedFileSaveStateRev = header; int savedModules; in >> savedModules; if (mOwner) IClickable::SetLoadContext(mOwner); for (int i = 0; i < savedModules; ++i) { std::string moduleName; in >> moduleName; //ofLog() << "Loading " << moduleName; IDrawableModule* module = FindModule(moduleName, false); try { if (module == nullptr) throw LoadStateException(); module->LoadState(in, module->LoadModuleSaveStateRev(in)); for (int j = 0; j < GetModuleSeparatorLength(); ++j) { char separatorChar; in >> separatorChar; if (separatorChar != GetModuleSeparator()[j]) { ofLog() << "Error loading state for " << module->Name(); //something went wrong, let's print some info to try to figure it out ofLog() << "Read char " + ofToString(separatorChar) + " but expected " + GetModuleSeparator()[j] + "!"; ofLog() << "Save state file position is " + ofToString(in.GetFilePosition()) + ", EoF is " + (in.Eof() ? "true" : "false"); std::string nextFewChars = "Next 10 characters are:"; for (int c = 0; c < 10; ++c) { char ch; in >> ch; nextFewChars += ofToString(ch); } ofLog() << nextFewChars; } assert(separatorChar == GetModuleSeparator()[j]); } } catch (LoadStateException& e) { TheSynth->LogEvent("Error loading state for module \"" + moduleName + "\"", kLogEventType_Error); //read through the rest of the module until we find the spacer, so we can continue loading the next module int separatorProgress = 0; juce::uint64 safetyCheck = 0; while (!in.Eof() && safetyCheck < 1000000) { char val; in >> val; if (val == GetModuleSeparator()[separatorProgress]) ++separatorProgress; else separatorProgress = 0; if (separatorProgress == GetModuleSeparatorLength()) break; //we did it! ++safetyCheck; } } } for (auto module : mModules) module->PostLoadState(); IClickable::ClearLoadContext(); TheSynth->SetIsLoadingState(wasLoadingState); --sModuleContainerLoadStack; if (sModuleContainerLoadStack <= 0) ModularSynth::sLoadingFileSaveStateRev = ModularSynth::kSaveStateRev; //reset to current } //static bool ModuleContainer::DoesModuleHaveMoreSaveData(FileStreamIn& in) { char test[GetModuleSeparatorLength() + 1]; in.Peek(test, GetModuleSeparatorLength()); test[GetModuleSeparatorLength()] = 0; if (strcmp(GetModuleSeparator(), test) == 0) return false; return true; } ```
/content/code_sandbox/Source/ModuleContainer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5,126
```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.cpp // Bespoke // // Created by Ryan Challinor on 4/14/14. // // #include "VelocityStepSequencer.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "FillSaveDropdown.h" #include "MidiController.h" #define ARP_REST -100 #define ARP_HOLD -101 VelocityStepSequencer::VelocityStepSequencer() { } void VelocityStepSequencer::Init() { IDrawableModule::Init(); mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(-.1f, true), false); } void VelocityStepSequencer::CreateUIControls() { IDrawableModule::CreateUIControls(); mIntervalSelector = new DropdownList(this, "interval", 115, 2, (int*)(&mInterval)); mLengthSlider = new IntSlider(this, "len", 115, 20, 40, 15, &mLength, 1, VSS_MAX_STEPS); mResetOnDownbeatCheckbox = new Checkbox(this, "downbeat", 5, 20, &mResetOnDownbeat); mIntervalSelector->AddLabel("64n", kInterval_64n); mIntervalSelector->AddLabel("32n", kInterval_32n); mIntervalSelector->AddLabel("16nt", kInterval_16nt); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("8nt", kInterval_8nt); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("4nt", kInterval_4nt); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("2n", kInterval_2n); mIntervalSelector->AddLabel("1n", kInterval_1n); for (int i = 0; i < VSS_MAX_STEPS; ++i) { mVels[i] = 80; mVelSliders[i] = new IntSlider(this, ("vel" + ofToString(i + 1)).c_str(), 10, 35 + i * 15, 80, 15, &(mVels[i]), 1, 127); } } VelocityStepSequencer::~VelocityStepSequencer() { TheTransport->RemoveListener(this); } void VelocityStepSequencer::SetMidiController(std::string name) { if (mController) mController->RemoveListener(this); mController = TheSynth->FindMidiController(name); if (mController) mController->AddListener(this, 0); } void VelocityStepSequencer::DrawModule() { if (Minimized() || IsVisible() == false) return; mIntervalSelector->Draw(); mLengthSlider->Draw(); mResetOnDownbeatCheckbox->Draw(); for (int i = 0; i < VSS_MAX_STEPS; ++i) mVelSliders[i]->Draw(); ofPushStyle(); ofSetColor(0, 255, 0, 50); ofFill(); ofRect(10, 35 + mArpIndex * 15, 80, 15); ofPopStyle(); } void VelocityStepSequencer::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); } void VelocityStepSequencer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } PlayNoteOutput(time, pitch, velocity > 0 ? mCurrentVelocity : 0, voiceIdx, modulation); } void VelocityStepSequencer::OnTimeEvent(double time) { ++mArpIndex; if (mArpIndex >= mLength) mArpIndex = 0; if (mResetOnDownbeat && TheTransport->GetQuantized(time, mTransportListenerInfo) == 0) mArpIndex = 0; mCurrentVelocity = mVels[mArpIndex]; } void VelocityStepSequencer::OnMidiNote(MidiNote& note) { } void VelocityStepSequencer::OnMidiControl(MidiControl& control) { if (!mEnabled) return; if (control.mControl >= 41 && control.mControl <= 48) { int step = control.mControl - 41; if (control.mValue >= 1) mVels[step] = control.mValue; } } void VelocityStepSequencer::ButtonClicked(ClickButton* button, double time) { } void VelocityStepSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) { transportListenerInfo->mInterval = mInterval; transportListenerInfo->mOffsetInfo = OffsetInfo(-.1f, true); } } } void VelocityStepSequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void VelocityStepSequencer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadString("controller", moduleInfo, "", FillDropdown<MidiController*>); SetUpFromSaveData(); } void VelocityStepSequencer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); SetMidiController(mModuleSaveData.GetString("controller")); } ```
/content/code_sandbox/Source/VelocityStepSequencer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,391
```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 **/ // // FreqDomainBoilerplate.h // modularSynth // // Created by Ryan Challinor on 4/24/13. // // #pragma once #include <iostream> #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "FFT.h" #include "RollingBuffer.h" #include "Slider.h" #include "BiquadFilterEffect.h" class FreqDomainBoilerplate : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener { public: FreqDomainBoilerplate(); virtual ~FreqDomainBoilerplate(); static IDrawableModule* Create() { return new FreqDomainBoilerplate(); } 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; } //IAudioReceiver InputMode GetInputMode() override { return kInputMode_Mono; } //IAudioSource void Process(double time) override; //IButtonListener void CheckboxUpdated(Checkbox* checkbox, double time) override; //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) 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; float* mWindower{ nullptr }; ::FFT mFFT; RollingBuffer mRollingInputBuffer; RollingBuffer mRollingOutputBuffer; float mInputPreamp{ 1 }; float mValue1{ 1 }; float mVolume{ 1 }; FloatSlider* mInputSlider{ nullptr }; FloatSlider* mValue1Slider{ nullptr }; FloatSlider* mVolumeSlider{ nullptr }; float mDryWet{ 1 }; FloatSlider* mDryWetSlider{ nullptr }; float mValue2{ 1 }; FloatSlider* mValue2Slider{ nullptr }; float mValue3{ 0 }; FloatSlider* mValue3Slider{ nullptr }; float mPhaseOffset{ 0 }; FloatSlider* mPhaseOffsetSlider{ nullptr }; }; ```
/content/code_sandbox/Source/FreqDomainBoilerplate.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
628
```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 **/ // // CanvasElement.h // Bespoke // // Created by Ryan Challinor on 1/4/15. // // #pragma once #include "Curve.h" #include "ModulationChain.h" class Canvas; class Sample; class IUIControl; class FloatSlider; class IntSlider; class TextEntry; class FileStreamIn; class FileStreamOut; class PatchCableSource; class EventCanvas; class CanvasElement { public: CanvasElement(Canvas* canvas, int col, int row, float offset, float length); virtual ~CanvasElement() {} void Draw(ofVec2f offset); void DrawOffscreen(); void SetHighlight(bool highlight) { mHighlighted = highlight; } bool GetHighlighted() const { return mHighlighted; } ofRectangle GetRect(bool clamp, bool wrapped, ofVec2f offset = ofVec2f(0, 0)) const; float GetStart() const; void SetStart(float start, bool preserveLength); virtual float GetEnd() const; void SetEnd(float end); std::vector<IUIControl*>& GetUIControls() { return mUIControls; } void MoveElementByDrag(ofVec2f dragOffset); virtual bool IsResizable() const { return true; } virtual CanvasElement* CreateDuplicate() const = 0; virtual void CheckboxUpdated(std::string label, bool value, double time); virtual void FloatSliderUpdated(std::string label, float oldVal, float newVal, double time); virtual void IntSliderUpdated(std::string label, int oldVal, float newVal, double time); virtual void ButtonClicked(std::string label, double time); virtual void SaveState(FileStreamOut& out); virtual void LoadState(FileStreamIn& in); int mRow; int mCol; float mOffset; float mLength; protected: virtual void DrawContents(bool clamp, bool wrapped, ofVec2f offset) = 0; void DrawElement(bool clamp, bool wrapped, ofVec2f offset); void AddElementUIControl(IUIControl* control); void GetDragDestinationData(ofVec2f dragOffset, int& newRow, int& newCol, float& newOffset) const; ofRectangle GetRectAtDestination(bool clamp, bool wrapped, ofVec2f dragOffset) const; float GetStart(int col, float offset) const; float GetEnd(int col, float offset, float length) const; Canvas* mCanvas{ nullptr }; bool mHighlighted{ false }; std::vector<IUIControl*> mUIControls; }; class NoteCanvasElement : public CanvasElement { public: NoteCanvasElement(Canvas* canvas, int col, int row, float offset, float length); static CanvasElement* Create(Canvas* canvas, int col, int row) { return new NoteCanvasElement(canvas, col, row, 0, 1); } void SetVelocity(float vel) { mVelocity = vel; } float GetVelocity() const { return mVelocity; } void SetVoiceIdx(int voiceIdx) { mVoiceIdx = voiceIdx; } int GetVoiceIdx() const { return mVoiceIdx; } ModulationChain* GetPitchBend() { return &mPitchBend; } ModulationChain* GetModWheel() { return &mModWheel; } ModulationChain* GetPressure() { return &mPressure; } float GetPan() { return mPan; } void UpdateModulation(float pos); void WriteModulation(float pos, float pitchBend, float modWheel, float pressure, float pan); CanvasElement* CreateDuplicate() const override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in) override; private: void DrawContents(bool clamp, bool wrapped, ofVec2f offset) override; float mVelocity{ .8 }; FloatSlider* mElementOffsetSlider{ nullptr }; FloatSlider* mElementLengthSlider{ nullptr }; IntSlider* mElementRowSlider{ nullptr }; IntSlider* mElementColSlider{ nullptr }; FloatSlider* mVelocitySlider{ nullptr }; int mVoiceIdx{ -1 }; ModulationChain mPitchBend{ ModulationParameters::kDefaultPitchBend }; ModulationChain mModWheel{ ModulationParameters::kDefaultModWheel }; ModulationChain mPressure{ ModulationParameters::kDefaultPressure }; float mPan{ 0 }; Curve mPitchBendCurve{ ModulationParameters::kDefaultPitchBend }; Curve mModWheelCurve{ ModulationParameters::kDefaultModWheel }; Curve mPressureCurve{ ModulationParameters::kDefaultPressure }; Curve mPanCurve{ 0 }; }; class SampleCanvasElement : public CanvasElement { public: SampleCanvasElement(Canvas* canvas, int col, int row, float offset, float length); ~SampleCanvasElement(); static CanvasElement* Create(Canvas* canvas, int col, int row) { return new SampleCanvasElement(canvas, col, row, 0, 1); } void SetSample(Sample* sample); Sample* GetSample() const { return mSample; } float GetVolume() const { return mVolume; } bool IsMuted() const { return mMute; } CanvasElement* CreateDuplicate() const override; void CheckboxUpdated(std::string label, bool value, double time) override; void ButtonClicked(std::string label, double time) override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in) override; private: void DrawContents(bool clamp, bool wrapped, ofVec2f offset) override; Sample* mSample{ nullptr }; FloatSlider* mElementOffsetSlider{ nullptr }; float mVolume{ 1 }; FloatSlider* mVolumeSlider{ nullptr }; bool mMute{ false }; Checkbox* mMuteCheckbox{ nullptr }; ClickButton* mSplitSampleButton{ nullptr }; ClickButton* mResetSpeedButton{ nullptr }; }; class EventCanvasElement : public CanvasElement { public: EventCanvasElement(Canvas* canvas, int col, int row, float offset); ~EventCanvasElement(); static CanvasElement* Create(Canvas* canvas, int col, int row) { return new EventCanvasElement(canvas, col, row, 0); } CanvasElement* CreateDuplicate() const override; void SetUIControl(IUIControl* control); void SetValue(float value) { mValue = value; } void Trigger(double time); void TriggerEnd(double time); bool IsResizable() const override { return mIsCheckbox; } float GetEnd() const override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in) override; private: void DrawContents(bool clamp, bool wrapped, ofVec2f offset) override; IUIControl* mUIControl{ nullptr }; float mValue{ 0 }; TextEntry* mValueEntry{ nullptr }; EventCanvas* mEventCanvas{ nullptr }; bool mIsCheckbox{ false }; bool mIsButton{ false }; }; ```
/content/code_sandbox/Source/CanvasElement.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,621
```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 **/ /* ============================================================================== MPESmoother.h Created: 4 Aug 2021 9:45:25pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Slider.h" #include "ModulationChain.h" #include "Transport.h" class MPESmoother : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller { public: MPESmoother(); virtual ~MPESmoother(); static IDrawableModule* Create() { return new MPESmoother(); } 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; } void Init() override; //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void OnTransportAdvanced(float amount) 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 mPitchSmooth{ .02 }; FloatSlider* mPitchSmoothSlider{ nullptr }; float mPressureSmooth{ .02 }; FloatSlider* mPressureSmoothSlider{ nullptr }; float mModWheelSmooth{ .02 }; FloatSlider* mModWheelSmoothSlider{ nullptr }; std::array<ModulationParameters, kNumVoices> mModulationInput; std::array<ModulationCollection, kNumVoices> mModulationOutput; }; ```
/content/code_sandbox/Source/MPESmoother.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
583
```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 **/ /* ============================================================================== PitchRemap.h Created: 7 May 2021 10:17:52pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "TextEntry.h" class PitchRemap : public NoteEffectBase, public IDrawableModule, public ITextEntryListener { public: PitchRemap(); static IDrawableModule* Create() { return new PitchRemap(); } 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 TextEntryComplete(TextEntry* entry) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: struct NoteInfo { NoteInfo() : mOn(false) , mVelocity(0) , mVoiceIdx(-1) {} bool mOn; int mVelocity; int mVoiceIdx; }; //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } struct Remap { int mFromPitch; TextEntry* mFromPitchEntry; int mToPitch; TextEntry* mToPitchEntry; }; float mWidth{ 200 }; float mHeight{ 20 }; std::array<Remap, 8> mRemaps; std::array<NoteInfo, 128> mInputNotes; }; ```
/content/code_sandbox/Source/PitchRemap.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
554
```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 **/ // // SlowLayers.cpp // Bespoke // // Created by Ryan Challinor on 1/13/15. // // #include "SlowLayers.h" #include "SynthGlobals.h" #include "Transport.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" #include "Profiler.h" SlowLayers::SlowLayers() : IAudioProcessor(gBufferSize) { //TODO(Ryan) buffer sizes mBuffer = new float[MAX_BUFFER_SIZE]; Clear(); } void SlowLayers::CreateUIControls() { IDrawableModule::CreateUIControls(); mClearButton = new ClickButton(this, "clear", 147, 102); mVolSlider = new FloatSlider(this, "volume", 4, 102, 110, 15, &mVol, 0, 2); mNumBarsSelector = new DropdownList(this, "num bars", 165, 4, &mNumBars); mFeedInSlider = new FloatSlider(this, "feed in", 4, 120, 110, 15, &mFeedIn, 0, 1); 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); } SlowLayers::~SlowLayers() { delete[] mBuffer; } void SlowLayers::Process(double time) { PROFILER(SlowLayers); IAudioReceiver* target = GetTarget(); if (!mEnabled || target == nullptr) return; ComputeSliders(0); SyncBuffers(); int bufferSize = GetBuffer()->BufferSize(); float* out = target->GetBuffer()->GetChannel(0); int loopLengthInSamples = LoopLength(); int layers = 4; for (int i = 0; i < bufferSize; ++i) { float smooth = .001f; mSmoothedVol = mSmoothedVol * (1 - smooth) + mVol * smooth; float volSq = mSmoothedVol * mSmoothedVol; double measurePos = TheTransport->GetMeasureTime(time); measurePos = DoubleWrap(measurePos, 1 << layers * mNumBars); int offset = measurePos * loopLengthInSamples; mBuffer[offset % loopLengthInSamples] += GetBuffer()->GetChannel(0)[i] * mFeedIn; float output = (1 - mFeedIn) * GetBuffer()->GetChannel(0)[i]; for (int j = 0; j < layers; ++j) output += GetInterpolatedSample(offset / float(1 << j), mBuffer, loopLengthInSamples); output *= volSq; out[i] += output; time += gInvSampleRateMs; } Add(out, GetBuffer()->GetChannel(0), bufferSize); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(0), bufferSize, 0); GetBuffer()->Reset(); } int SlowLayers::LoopLength() const { return TheTransport->GetDuration(kInterval_1n) * mNumBars * gSampleRate / 1000; } void SlowLayers::DrawModule() { if (Minimized() || IsVisible() == false) return; ofPushMatrix(); ofTranslate(BUFFER_X, BUFFER_Y); DrawAudioBuffer(BUFFER_W, BUFFER_H, mBuffer, 0, LoopLength(), TheTransport->GetMeasurePos(gTime) * LoopLength(), mVol); ofSetColor(255, 255, 0, gModuleDrawAlpha); for (int i = 1; i < mNumBars; ++i) { float x = BUFFER_W / mNumBars * i; ofLine(x, BUFFER_H / 2 - 5, x, BUFFER_H / 2 + 5); } ofSetColor(255, 255, 255, gModuleDrawAlpha); ofPopMatrix(); mClearButton->Draw(); mNumBarsSelector->Draw(); mVolSlider->Draw(); mFeedInSlider->Draw(); } void SlowLayers::Clear() { ::Clear(mBuffer, MAX_BUFFER_SIZE); } void SlowLayers::SetNumBars(int numBars) { mNumBars = numBars; } void SlowLayers::GetModuleDimensions(float& width, float& height) { width = 197; height = 155; } void SlowLayers::ButtonClicked(ClickButton* button, double time) { if (button == mClearButton) ::Clear(mBuffer, MAX_BUFFER_SIZE); } void SlowLayers::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void SlowLayers::RadioButtonUpdated(RadioButton* radio, int oldVal, double time) { } void SlowLayers::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void SlowLayers::CheckboxUpdated(Checkbox* checkbox, double time) { } void SlowLayers::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void SlowLayers::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/SlowLayers.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,295
```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 **/ // // SliderSequencer.cpp // Bespoke // // Created by Ryan Challinor on 3/25/14. // // #include "SliderSequencer.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" #include "DrumPlayer.h" SliderSequencer::SliderSequencer() { for (int i = 0; i < 8; ++i) mSliderLines.push_back(new SliderLine(this, 10, 40 + i * 15, i)); } void SliderSequencer::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void SliderSequencer::CreateUIControls() { IDrawableModule::CreateUIControls(); mDivisionSlider = new IntSlider(this, "division", 10, 20, 100, 15, &mDivision, 1, 4); for (int i = 0; i < mSliderLines.size(); ++i) mSliderLines[i]->CreateUIControls(); } SliderSequencer::~SliderSequencer() { TheTransport->RemoveAudioPoller(this); for (int i = 0; i < mSliderLines.size(); ++i) delete mSliderLines[i]; } double SliderSequencer::MeasurePos(double time) { double pos = TheTransport->GetMeasurePos(time) * mDivision; while (pos > 1) pos -= 1; return pos; } void SliderSequencer::OnTransportAdvanced(float amount) { PROFILER(SliderSequencer); if (!mEnabled) return; ComputeSliders(0); double time = NextBufferTime(true); double current = MeasurePos(time); for (int i = 0; i < mSliderLines.size(); ++i) { if (mSliderLines[i]->mVelocity == 0) continue; if ((mSliderLines[i]->mPoint > mLastMeasurePos || mLastMeasurePos > current) && mSliderLines[i]->mPoint <= current) { double remainder = DoubleWrap(current - mSliderLines[i]->mPoint, 1); double remainderMs = TheTransport->MsPerBar() * remainder; PlayNoteOutput(time - remainderMs, mSliderLines[i]->mPitch, mSliderLines[i]->mVelocity * 127, -1); PlayNoteOutput(time - remainderMs + TheTransport->GetDuration(kInterval_16n), mSliderLines[i]->mPitch, 0, -1); mSliderLines[i]->mPlayTime = time; } mSliderLines[i]->mPlaying = mSliderLines[i]->mPlayTime + 100 > time; } mLastMeasurePos = current; } void SliderSequencer::DrawModule() { if (Minimized() || IsVisible() == false) return; mDivisionSlider->Draw(); for (int i = 0; i < mSliderLines.size(); ++i) mSliderLines[i]->Draw(); if (mEnabled) { ofPushStyle(); ofSetLineWidth(1); ofSetColor(0, 255, 0); ofFill(); ofRect(10 + 180 * MeasurePos(gTime), 40, 1, 120); ofPopStyle(); } } void SliderSequencer::CheckboxUpdated(Checkbox* checkbox, double time) { } void SliderSequencer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void SliderSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void SliderSequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void SliderSequencer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void SliderSequencer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } SliderLine::SliderLine(SliderSequencer* owner, int x, int y, int index) : mX(x) , mY(y) , mOwner(owner) , mIndex(index) { } void SliderLine::CreateUIControls() { mSlider = new FloatSlider(mOwner, ("time" + ofToString(mIndex)).c_str(), mX, mY, 180, 15, &mPoint, 0, 1); mVelocitySlider = new FloatSlider(mOwner, ("vel" + ofToString(mIndex)).c_str(), mX + 185, mY, 80, 15, &mVelocity, 0, .99f, 2); mNoteSelector = new TextEntry(mOwner, ("note" + ofToString(mIndex)).c_str(), mX + 270, mY, 4, &mPitch, 0, 127); mPlayingCheckbox = new Checkbox(mOwner, ("playing" + ofToString(mIndex)).c_str(), HIDDEN_UICONTROL, HIDDEN_UICONTROL, &mPlaying); } void SliderLine::Draw() { ofPushStyle(); ofFill(); ofSetColor(255, 255, 0); if (mPlaying) ofRect(mX, mY, 10, 10); ofPopStyle(); mSlider->Draw(); mNoteSelector->Draw(); mVelocitySlider->Draw(); } ```
/content/code_sandbox/Source/SliderSequencer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,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 **/ // // CircleSequencer.cpp // Bespoke // // Created by Ryan Challinor on 3/3/15. // // #include "CircleSequencer.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" #include "DrumPlayer.h" namespace { ofVec2f PolToCar(float pos, float radius) { return ofVec2f(radius * sin(pos * TWO_PI), radius * -cos(pos * TWO_PI)); } ofVec2f CarToPol(float x, float y) { float pos = FloatWrap(atan2(x, -y) / TWO_PI, 1); return ofVec2f(pos, sqrtf(x * x + y * y)); } } CircleSequencer::CircleSequencer() { for (int i = 0; i < 4; ++i) mCircleSequencerRings.push_back(new CircleSequencerRing(this, i)); } void CircleSequencer::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void CircleSequencer::CreateUIControls() { IDrawableModule::CreateUIControls(); for (int i = 0; i < mCircleSequencerRings.size(); ++i) mCircleSequencerRings[i]->CreateUIControls(); } CircleSequencer::~CircleSequencer() { TheTransport->RemoveAudioPoller(this); for (int i = 0; i < mCircleSequencerRings.size(); ++i) delete mCircleSequencerRings[i]; } void CircleSequencer::OnTransportAdvanced(float amount) { PROFILER(CircleSequencer); if (!mEnabled) return; ComputeSliders(0); for (int i = 0; i < mCircleSequencerRings.size(); ++i) mCircleSequencerRings[i]->OnTransportAdvanced(amount); } void CircleSequencer::DrawModule() { if (Minimized() || IsVisible() == false) return; for (int i = 0; i < mCircleSequencerRings.size(); ++i) mCircleSequencerRings[i]->Draw(); ofPushStyle(); ofSetColor(ofColor::lime); float pos = TheTransport->GetMeasurePos(gTime); ofVec2f end = PolToCar(pos, 100); ofLine(100, 100, 100 + end.x, 100 + end.y); ofPopStyle(); } void CircleSequencer::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); for (int i = 0; i < mCircleSequencerRings.size(); ++i) mCircleSequencerRings[i]->OnClicked(x, y, right); } void CircleSequencer::MouseReleased() { IDrawableModule::MouseReleased(); for (int i = 0; i < mCircleSequencerRings.size(); ++i) mCircleSequencerRings[i]->MouseReleased(); } bool CircleSequencer::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); for (int i = 0; i < mCircleSequencerRings.size(); ++i) mCircleSequencerRings[i]->MouseMoved(x, y); return false; } void CircleSequencer::CheckboxUpdated(Checkbox* checkbox, double time) { } void CircleSequencer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void CircleSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void CircleSequencer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void CircleSequencer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } void CircleSequencer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << (int)mCircleSequencerRings.size(); for (size_t i = 0; i < mCircleSequencerRings.size(); ++i) mCircleSequencerRings[i]->SaveState(out); } void CircleSequencer::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()); int numRings; in >> numRings; for (size_t i = 0; i < mCircleSequencerRings.size() && i < numRings; ++i) mCircleSequencerRings[i]->LoadState(in); } CircleSequencerRing::CircleSequencerRing(CircleSequencer* owner, int index) : mPitch(index) , mOwner(owner) , mIndex(index) { mSteps.fill(0); } void CircleSequencerRing::CreateUIControls() { int y = mIndex * 20 + 20; mLengthSelector = new DropdownList(mOwner, ("length" + ofToString(mIndex)).c_str(), 220, y, &mLength); mNoteSelector = new TextEntry(mOwner, ("note" + ofToString(mIndex)).c_str(), 260, y, 4, &mPitch, 0, 127); mOffsetSlider = new FloatSlider(mOwner, ("offset" + ofToString(mIndex)).c_str(), 300, y, 90, 15, &mOffset, -.25f, .25f, 2); for (int i = 0; i < CIRCLE_SEQUENCER_MAX_STEPS; ++i) mLengthSelector->AddLabel(ofToString(i + 1).c_str(), i + 1); } void CircleSequencerRing::Draw() { ofPushStyle(); switch (mIndex) { case 0: ofSetColor(255, 150, 150); break; case 1: ofSetColor(255, 255, 150); break; case 2: ofSetColor(150, 255, 255); break; case 3: ofSetColor(150, 150, 255); break; default: ofSetColor(255, 255, 255); break; } ofSetCircleResolution(40); ofNoFill(); ofCircle(100, 100, GetRadius()); ofFill(); for (int i = 0; i < mLength; ++i) { float pos = float(i) / mLength - mOffset; ofVec2f p1 = PolToCar(pos, GetRadius() - 3); ofVec2f p2 = PolToCar(pos, GetRadius() + 3); ofLine(p1.x + 100, p1.y + 100, p2.x + 100, p2.y + 100); ofVec2f point = PolToCar(pos, GetRadius()); if (mSteps[i] > 0) ofCircle(100 + point.x, 100 + point.y, 3 + 6 * mSteps[i]); if (i == mHighlightStepIdx) { ofPushStyle(); ofSetColor(255, 255, 255, 100); ofSetLineWidth(.5f); ofNoFill(); ofCircle(100 + point.x, 100 + point.y, 3 + 6); ofPopStyle(); } } ofPopStyle(); mLengthSelector->Draw(); mNoteSelector->Draw(); mOffsetSlider->Draw(); } int CircleSequencerRing::GetStepIndex(int x, int y, float& radiusOut) { ofVec2f polar = CarToPol(x - 100, y - 100); float pos = FloatWrap(polar.x + mOffset, 1); int idx = int(pos * mLength + .5f) % mLength; ofVec2f stepPos = PolToCar(float(idx) / mLength - mOffset, GetRadius()); if (ofDistSquared(x, y, stepPos.x + 100, stepPos.y + 100) < 7 * 7) { radiusOut = polar.y; return idx; } return -1; } void CircleSequencerRing::OnClicked(float x, float y, bool right) { if (right) return; mCurrentlyClickedStepIdx = GetStepIndex(x, y, mLastMouseRadius); if (mCurrentlyClickedStepIdx != -1) { if (mSteps[mCurrentlyClickedStepIdx]) mSteps[mCurrentlyClickedStepIdx] = 0; else mSteps[mCurrentlyClickedStepIdx] = .5f; } } void CircleSequencerRing::MouseReleased() { mCurrentlyClickedStepIdx = -1; } void CircleSequencerRing::MouseMoved(float x, float y) { if (mCurrentlyClickedStepIdx != -1) { ofVec2f polar = CarToPol(x - 100, y - 100); float change = (polar.y - mLastMouseRadius) / 50.0f; mSteps[mCurrentlyClickedStepIdx] = ofClamp(mSteps[mCurrentlyClickedStepIdx] + change, 0, 1); mLastMouseRadius = polar.y; } else { float radius; mHighlightStepIdx = GetStepIndex(x, y, radius); } } void CircleSequencerRing::OnTransportAdvanced(float amount) { PROFILER(CircleSequencerRing); TransportListenerInfo info(nullptr, kInterval_CustomDivisor, OffsetInfo(mOffset, false), false); info.mCustomDivisor = mLength + (mLength == 1); // +1 if mLength(Steps) == 1: fixes not playing onset 1 when mLength = 1: force oldStep <> newStep double remainderMs; const int oldStep = TheTransport->GetQuantized(NextBufferTime(true) - gBufferSizeMs, &info); const int newStep = TheTransport->GetQuantized(NextBufferTime(true), &info, &remainderMs); const int oldMeasure = TheTransport->GetMeasure(NextBufferTime(true) - gBufferSizeMs); const int newMeasure = TheTransport->GetMeasure(NextBufferTime(true)); if (oldStep != newStep && mSteps[newStep] > 0) { const double time = NextBufferTime(true) - remainderMs; mOwner->PlayNoteOutput(time, mPitch, mSteps[newStep] * 127, -1); mOwner->PlayNoteOutput(time + TheTransport->GetDuration(kInterval_16n), mPitch, 0, -1); } } void CircleSequencerRing::SaveState(FileStreamOut& out) { out << (int)mSteps.size(); for (size_t i = 0; i < mSteps.size(); ++i) out << mSteps[i]; } void CircleSequencerRing::LoadState(FileStreamIn& in) { int numSteps; in >> numSteps; for (size_t i = 0; i < mSteps.size() && i < numSteps; ++i) in >> mSteps[i]; } ```
/content/code_sandbox/Source/CircleSequencer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,693
```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 **/ /* ============================================================================== MidiControlChange.h Created: 5 Aug 2021 9:32:12pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Slider.h" #include "TextEntry.h" class MidiControlChange : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public ITextEntryListener { public: MidiControlChange(); static IDrawableModule* Create() { return new MidiControlChange(); } 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 TextEntryComplete(TextEntry* entry) 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 mControl{ 0 }; TextEntry* mControlEntry{ nullptr }; float mValue{ 0 }; FloatSlider* mValueSlider{ nullptr }; bool mResendDuplicateValue{ false }; }; ```
/content/code_sandbox/Source/MidiControlChange.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
498
```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 **/ // // SingleOscillator.h // modularSynth // // Created by Ryan Challinor on 12/4/13. // // #pragma once #include <iostream> #include "IAudioSource.h" #include "PolyphonyMgr.h" #include "SingleOscillatorVoice.h" #include "INoteReceiver.h" #include "IDrawableModule.h" #include "Slider.h" #include "DropdownList.h" #include "ADSRDisplay.h" #include "Checkbox.h" #include "RadioButton.h" #include "Oscillator.h" class ofxJSONElement; class SingleOscillator : public IAudioSource, public INoteReceiver, public IDrawableModule, public IDropdownListener, public IFloatSliderListener, public IIntSliderListener, public IRadioButtonListener { public: SingleOscillator(); ~SingleOscillator(); static IDrawableModule* Create() { return new SingleOscillator(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetType(OscillatorType type) { mVoiceParams.mOscType = type; } void SetDetune(float detune) { mVoiceParams.mDetune = detune; } //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) 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 {} void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void RadioButtonUpdated(RadioButton* list, int oldVal, double time) override; bool HasDebugDraw() const override { return true; } virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 1; } bool LoadOldControl(FileStreamIn& in, std::string& oldName) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void DrawModuleUnclipped() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void UpdateOldControlName(std::string& oldName) override; float mWidth{ 200 }; float mHeight{ 20 }; PolyphonyMgr mPolyMgr; NoteInputBuffer mNoteInputBuffer; OscillatorVoiceParams mVoiceParams; FloatSlider* mVolSlider{ nullptr }; FloatSlider* mPhaseOffsetSlider{ nullptr }; DropdownList* mOscSelector{ nullptr }; FloatSlider* mPulseWidthSlider{ nullptr }; FloatSlider* mSoftenSlider{ nullptr }; int mMult{ 1 }; DropdownList* mMultSelector{ nullptr }; ADSRDisplay* mADSRDisplay{ nullptr }; DropdownList* mSyncModeSelector{ nullptr }; FloatSlider* mSyncFreqSlider{ nullptr }; FloatSlider* mSyncRatioSlider{ nullptr }; FloatSlider* mDetuneSlider{ nullptr }; IntSlider* mUnisonSlider{ nullptr }; FloatSlider* mUnisonWidthSlider{ nullptr }; FloatSlider* mShuffleSlider{ nullptr }; FloatSlider* mVelToVolumeSlider{ nullptr }; FloatSlider* mVelToEnvelopeSlider{ nullptr }; Checkbox* mLiteCPUModeCheckbox{ nullptr }; FloatSlider* mFilterCutoffMaxSlider{ nullptr }; FloatSlider* mFilterCutoffMinSlider{ nullptr }; FloatSlider* mFilterQSlider{ nullptr }; ADSRDisplay* mFilterADSRDisplay{ nullptr }; ChannelBuffer mWriteBuffer; Oscillator mDrawOsc{ OscillatorType::kOsc_Square }; int mLoadRev{ -1 }; struct DebugLine { std::string text; ofColor color; }; std::array<DebugLine, 20> mDebugLines; int mDebugLinesPos{ 0 }; }; ```
/content/code_sandbox/Source/SingleOscillator.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,107
```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 **/ /* ============================================================================== DCOffset.h Created: 1 Dec 2019 3:24:31pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "Slider.h" class DCOffset : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener { public: DCOffset(); virtual ~DCOffset(); static IDrawableModule* Create() { return new DCOffset(); } 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; } //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& w, float& h) override { w = 120; h = 22; } float mOffset{ 0 }; FloatSlider* mOffsetSlider{ nullptr }; }; ```
/content/code_sandbox/Source/DCOffset.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
412
```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 **/ // // TimelineControl.cpp // Bespoke // // Created by Ryan Challinor on 5/3/16. // // #include "TimelineControl.h" #include "Transport.h" #include "SynthGlobals.h" #include "ModularSynth.h" TimelineControl::TimelineControl() { } void TimelineControl::CreateUIControls() { IDrawableModule::CreateUIControls(); mTimeSlider = new FloatSlider(this, "measure", 3, 3, GetSliderWidth(), 15, &mTime, 0, mNumMeasures); mNumMeasuresEntry = new TextEntry(this, "length", -1, -1, 5, &mNumMeasures, 4, 2048); mResetButton = new ClickButton(this, "reset", -1, -1); mLoopCheckbox = new Checkbox(this, "loop", -1, -1, &mLoop); mDockCheckbox = new Checkbox(this, "dock", -1, -1, &mDock); mLoopStartSlider = new IntSlider(this, "loop start", -1, -1, GetSliderWidth(), 15, &mLoopStart, 0, mNumMeasures); mLoopEndSlider = new IntSlider(this, "loop end", -1, -1, GetSliderWidth(), 15, &mLoopEnd, 0, mNumMeasures); mNumMeasuresEntry->DrawLabel(true); mNumMeasuresEntry->PositionTo(mTimeSlider, kAnchor_Below); mResetButton->PositionTo(mNumMeasuresEntry, kAnchor_Right_Padded); mLoopCheckbox->PositionTo(mResetButton, kAnchor_Right_Padded); mDockCheckbox->PositionTo(mLoopCheckbox, kAnchor_Right_Padded); mLoopStartSlider->PositionTo(mNumMeasuresEntry, kAnchor_Below); mLoopEndSlider->PositionTo(mLoopStartSlider, kAnchor_Below); mLoopStartSlider->SetShowing(mLoop); mLoopEndSlider->SetShowing(mLoop); } TimelineControl::~TimelineControl() { } void TimelineControl::DrawModule() { mTime = TheTransport->GetMeasureTime(gTime); if (Minimized()) return; if (mDock) { float w, h; GetModuleDimensions(w, h); SetPosition(0, ofGetHeight() / GetOwningContainer()->GetDrawScale() - h); Resize(ofGetWidth() / GetOwningContainer()->GetDrawScale(), h); } mDockCheckbox->SetShowing(GetOwningContainer() == TheSynth->GetRootContainer() || GetOwningContainer() == TheSynth->GetUIContainer()); mTimeSlider->Draw(); mNumMeasuresEntry->Draw(); mResetButton->Draw(); mLoopCheckbox->Draw(); mDockCheckbox->Draw(); mLoopStartSlider->Draw(); mLoopEndSlider->Draw(); } void TimelineControl::GetModuleDimensions(float& w, float& h) { w = mWidth; h = mLoop ? 74 : 38; } void TimelineControl::Resize(float width, float height) { mWidth = width; mTimeSlider->SetDimensions(GetSliderWidth(), 15); mLoopStartSlider->SetDimensions(GetSliderWidth(), 15); mLoopEndSlider->SetDimensions(GetSliderWidth(), 15); } void TimelineControl::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mLoopCheckbox) { mLoopStartSlider->SetShowing(mLoop); mLoopEndSlider->SetShowing(mLoop); if (mLoop) TheTransport->SetLoop(mLoopStart, mLoopEnd); else TheTransport->ClearLoop(); } if (checkbox == mDockCheckbox) { if (mDock && GetOwningContainer() == TheSynth->GetRootContainer()) { TheSynth->GetUIContainer()->TakeModule(this); float w, h; GetModuleDimensions(w, h); Resize(ofGetWidth() / GetOwningContainer()->GetDrawScale(), h); gHoveredUIControl = nullptr; } if (!mDock && GetOwningContainer() == TheSynth->GetUIContainer()) { TheSynth->GetRootContainer()->TakeModule(this); float w, h; GetModuleDimensions(w, h); Resize(ofGetWidth() / GetOwningContainer()->GetDrawScale(), h); SetPosition(-TheSynth->GetDrawOffset().x, -TheSynth->GetDrawOffset().y + ofGetHeight() / GetOwningContainer()->GetDrawScale() - h); gHoveredUIControl = nullptr; } } } void TimelineControl::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mTimeSlider) { TheTransport->SetMeasureTime(mTime); } } void TimelineControl::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mLoopStartSlider || slider == mLoopEndSlider) { if (slider == mLoopStartSlider) { mLoopStart = MIN(mLoopStart, mNumMeasures - 1); mLoopEnd = MAX(mLoopEnd, mLoopStart + 1); } if (slider == mLoopEndSlider) { mLoopEnd = MAX(mLoopEnd, 1); mLoopStart = MIN(mLoopStart, mLoopEnd - 1); } if (mLoop) TheTransport->SetLoop(mLoopStart, mLoopEnd); } } void TimelineControl::TextEntryComplete(TextEntry* entry) { if (entry == mNumMeasuresEntry) { mNumMeasures = std::max(mNumMeasures, 4); mTimeSlider->SetExtents(0, mNumMeasures); mLoopStartSlider->SetExtents(0, mNumMeasures); mLoopEndSlider->SetExtents(0, mNumMeasures); } } void TimelineControl::ButtonClicked(ClickButton* button, double time) { if (button == mResetButton) TheTransport->Reset(); } void TimelineControl::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadFloat("width", moduleInfo, 390, 100, 99999, K(isTextField)); SetUpFromSaveData(); } void TimelineControl::SetUpFromSaveData() { Resize(mModuleSaveData.GetFloat("width"), 0); } void TimelineControl::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["width"] = mWidth; } ```
/content/code_sandbox/Source/TimelineControl.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,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 **/ // // HelpDisplay.h // Bespoke // // Created by Ryan Challinor on 2/7/15. // // #pragma once #include "IDrawableModule.h" #include "RadioButton.h" #include "ClickButton.h" #include "ModuleFactory.h" class HelpDisplay : public IDrawableModule, public IRadioButtonListener, public IButtonListener { public: HelpDisplay(); virtual ~HelpDisplay(); static IDrawableModule* Create() { return new HelpDisplay(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } bool IsSaveable() override { return false; } bool HasTitleBar() const override { return false; } void CreateUIControls() override; void Poll() override; void Show() { mScrollOffsetY = 0; } std::string GetUIControlTooltip(IUIControl* control); std::string GetModuleTooltip(IDrawableModule* module); std::string GetModuleTooltipFromName(std::string moduleTypeName); void CheckboxUpdated(Checkbox* checkbox, double time) override; void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override {} void ButtonClicked(ClickButton* button, double time) override; void ScreenshotModule(IDrawableModule* module); static bool sShowTooltips; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override; bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override; void RenderScreenshot(int x, int y, int width, int height, std::string filename); struct UIControlTooltipInfo { std::string controlName; std::string tooltip; }; struct ModuleTooltipInfo { std::string module; std::string tooltip; std::list<UIControlTooltipInfo> controlTooltips; }; void LoadHelp(); void LoadTooltips(); ModuleTooltipInfo* FindModuleInfo(std::string moduleTypeName); UIControlTooltipInfo* FindControlInfo(IUIControl* control); std::vector<std::string> mHelpText; Checkbox* mShowTooltipsCheckbox{ nullptr }; ClickButton* mCopyBuildInfoButton{ nullptr }; ClickButton* mDumpModuleInfoButton{ nullptr }; ClickButton* mDoModuleScreenshotsButton{ nullptr }; ClickButton* mDoModuleDocumentationButton{ nullptr }; ClickButton* mTutorialVideoLinkButton{ nullptr }; ClickButton* mDocsLinkButton{ nullptr }; ClickButton* mDiscordLinkButton{ nullptr }; float mWidth{ 700 }; float mHeight{ 700 }; static bool sTooltipsLoaded; static std::list<ModuleTooltipInfo> sTooltips; std::list<ModuleFactory::Spawnable> mScreenshotsToProcess; IDrawableModule* mScreenshotModule{ nullptr }; float mScrollOffsetY{ 0 }; float mMaxScrollAmount{ 0 }; enum class ScreenshotState { None, WaitingForSpawn, WaitingForScreenshot }; ScreenshotState mScreenshotState{ ScreenshotState::None }; int mScreenshotCountdown{ 0 }; }; ```
/content/code_sandbox/Source/HelpDisplay.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
845
```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 **/ /* ============================================================================== GlobalControls.h Created: 26 Sep 2020 11:34:18am Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IDrawableModule.h" #include "OpenFrameworksPort.h" #include "Slider.h" class GlobalControls : public IDrawableModule, public IFloatSliderListener { public: GlobalControls(); virtual ~GlobalControls(); static IDrawableModule* Create() { return new GlobalControls(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Poll() override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveLayout(ofxJSONElement& moduleInfo) override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 0; } std::vector<IUIControl*> ControlsToNotSetDuringLoadState() const override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; FloatSlider* mZoomSlider{ nullptr }; FloatSlider* mXSlider{ nullptr }; FloatSlider* mYSlider{ nullptr }; FloatSlider* mMouseScrollXSlider{ nullptr }; FloatSlider* mMouseScrollYSlider{ nullptr }; FloatSlider* mBackgroundLissajousRSlider{ nullptr }; FloatSlider* mBackgroundLissajousGSlider{ nullptr }; FloatSlider* mBackgroundLissajousBSlider{ nullptr }; FloatSlider* mBackgroundRSlider{ nullptr }; FloatSlider* mBackgroundGSlider{ nullptr }; FloatSlider* mBackgroundBSlider{ nullptr }; FloatSlider* mCornerRadiusSlider{ nullptr }; FloatSlider* mCableAlphaSlider{ nullptr }; float mWidth{ 200 }; float mHeight{ 20 }; float mMouseScrollX{ 0 }; float mMouseScrollY{ 0 }; }; ```
/content/code_sandbox/Source/GlobalControls.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
611
```c++ /* ============================================================================== This file was auto-generated! It contains the basic startup code for a Juce application. ============================================================================== */ #include "juce_gui_basics/juce_gui_basics.h" #include <memory> #include "VSTScanner.h" #include "SynthGlobals.h" #include "VersionInfo.h" using namespace juce; Component* createMainContentComponent(); std::unique_ptr<juce::ApplicationProperties> appProperties; void SetStartupSaveStateFile(const String& bskPath, Component* mainComponent); juce::ApplicationProperties& getAppProperties() { return *appProperties; } //============================================================================== class BespokeApplication : public JUCEApplication { public: //============================================================================== BespokeApplication() = default; const String getApplicationName() override { return Bespoke::APP_NAME; } const String getApplicationVersion() override { return Bespoke::VERSION; } bool moreThanOneInstanceAllowed() override { return true; } //============================================================================== void initialise(const String& commandLine) override { // Parse command line arguments that should cause us to exit auto cliArgv = JUCEApplication::getCommandLineParameterArray(); for (int i = 0; i < cliArgv.size(); ++i) { bool should_exit = false; juce::String argument = cliArgv[i]; if (argument == "-h" || argument == "--help") { std::cout << "A modular DAW for Mac, Windows, and Linux.\n" << "\n" << "Usage: BespokeSynth [OPTIONS] [path].json [path].bsk(t)\n" << "\n" << "Arguments:\n" << " [path].bsk(t) the project file to open (must end in .bsk or .bskt)\n" << " [path].json path to userprefs.json (must end in .json)\n" << "\n" << "Options:\n" << " -o, --option <option> <value> Temporarily override settings in preferences file\n" << " -h, --help Print help\n" << " -v, --version Print version\n" << std::flush; should_exit = true; } else if (argument == "-v" || argument == "--version") { std::cout << "bespoke synth " << GetBuildInfoString() << std::endl; should_exit = true; } else if (argument == "-o" || argument == "--option") { if ((cliArgv[i + 1].isEmpty()) || (cliArgv[i + 2].isEmpty())) { CliErrorExpectedOpt(argument); should_exit = true; } } if (should_exit == true) { JUCEApplicationBase::quit(); return; } } auto scannerSubprocess = std::make_unique<PluginScannerSubprocess>(); if (scannerSubprocess->initialiseFromCommandLine(commandLine, kScanProcessUID)) { storedScannerSubprocess = std::move(scannerSubprocess); return; } mainWindow = std::make_unique<MainWindow>("bespoke synth"); juce::PropertiesFile::Options options; options.applicationName = "Bespoke Synth"; options.filenameSuffix = "settings"; options.osxLibrarySubFolder = "Preferences"; appProperties = std::make_unique<juce::ApplicationProperties>(); appProperties->setStorageParameters(options); } // Prints an error for arguments that expected an argument but were not given one void CliErrorExpectedOpt(String argument) { std::cout << "Error: value is required for '" << argument << "' but none was supplied" << "\n\nFor more information, try '--help'" << std::endl; } void shutdown() override { // Add your application's shutdown code here.. mainWindow.reset(); appProperties.reset(); } //============================================================================== void systemRequestedQuit() override { // This is called when the app is being asked to quit: you can ignore this // request and let the app carry on running, or call quit() to allow the app to close. quit(); } void anotherInstanceStarted(const String& commandLine) override { // When another instance of the app is launched while this one is running, // this method is invoked, and the commandLine parameter tells you what // the other instance's command-line arguments were. // This is also called when opening the app with a file. if (commandLine.isNotEmpty() && commandLine.endsWith(".bsk")) SetStartupSaveStateFile(commandLine, mainWindow->getContentComponent()); } //============================================================================== /* This class implements the desktop window that contains an instance of our MainContentComponent class. */ class MainWindow : public DocumentWindow { public: MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons) { setUsingNativeTitleBar(true); setContentOwned(createMainContentComponent(), true); setResizable(true, true); centreWithSize(getWidth(), getHeight()); setVisible(true); } void closeButtonPressed() override { // This is called when the user tries to close this window. Here, we'll just // ask the app to quit when this happens, but you can change this to do // whatever you need. JUCEApplication::getInstance()->systemRequestedQuit(); } /* Note: Be careful if you override any DocumentWindow methods - the base class uses a lot of them, so by overriding you might break its functionality. It's best to do all your work in your content component instead, but if you really have to override any DocumentWindow methods, make sure your subclass also calls the superclass's method. */ private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow) }; private: std::unique_ptr<MainWindow> mainWindow; std::unique_ptr<PluginScannerSubprocess> storedScannerSubprocess; }; //============================================================================== // This macro generates the main() routine that launches the app. START_JUCE_APPLICATION(BespokeApplication) ```
/content/code_sandbox/Source/Main.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,349
```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 **/ // // GroupControl.h // Bespoke // // Created by Ryan Challinor on 2/7/16. // // #pragma once #include "IDrawableModule.h" #include "Checkbox.h" class PatchCableSource; class GroupControl : public IDrawableModule { public: GroupControl(); ~GroupControl(); static IDrawableModule* Create() { return new GroupControl(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void CheckboxUpdated(Checkbox* checkbox, 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; Checkbox* mGroupCheckbox{ nullptr }; bool mGroupEnabled{ false }; std::vector<PatchCableSource*> mControlCables; }; ```
/content/code_sandbox/Source/GroupControl.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
387
```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 **/ /* ============================================================================== DCOffset.cpp Created: 1 Dec 2019 3:24:31pm Author: Ryan Challinor ============================================================================== */ #include "DCOffset.h" #include "ModularSynth.h" #include "Profiler.h" DCOffset::DCOffset() : IAudioProcessor(gBufferSize) { } void DCOffset::CreateUIControls() { IDrawableModule::CreateUIControls(); mOffsetSlider = new FloatSlider(this, "offset", 5, 2, 110, 15, &mOffset, -1, 1); } DCOffset::~DCOffset() { } void DCOffset::Process(double time) { PROFILER(DCOffset); IAudioReceiver* target = GetTarget(); if (target) { ComputeSliders(0); SyncBuffers(); int bufferSize = GetBuffer()->BufferSize(); ChannelBuffer* out = target->GetBuffer(); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { float* buffer = GetBuffer()->GetChannel(ch); if (mEnabled) for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); buffer[i] += mOffset; } Add(out->GetChannel(ch), buffer, bufferSize); GetVizBuffer()->WriteChunk(buffer, bufferSize, ch); } } GetBuffer()->Reset(); } void DCOffset::DrawModule() { if (Minimized() || IsVisible() == false) return; mOffsetSlider->Draw(); } void DCOffset::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void DCOffset::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/DCOffset.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
503
```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 **/ /* ============================================================================== ModulatorAccum.h Created: 2 Aug 2021 10:32:56pm Author: Ryan Challinor ============================================================================== */ #pragma once #pragma once #include "IDrawableModule.h" #include "Slider.h" #include "IModulator.h" #include "Transport.h" class PatchCableSource; class ModulatorAccum : public IDrawableModule, public IFloatSliderListener, public IModulator, public IAudioPoller { public: ModulatorAccum(); virtual ~ModulatorAccum(); static IDrawableModule* Create() { return new ModulatorAccum(); } 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; } void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; //IModulator float Value(int samplesIn = 0) override; bool Active() const override { return mEnabled; } //IAudioPoller void OnTransportAdvanced(float amount) override; FloatSlider* GetTarget() { return GetSliderTarget(); } //IFloatSliderListener 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& w, float& h) override { w = mWidth; h = mHeight; } float mWidth{ 200 }; float mHeight{ 20 }; float mValue{ 0 }; float mVelocity{ 0 }; FloatSlider* mValueSlider{ nullptr }; FloatSlider* mVelocitySlider{ nullptr }; }; ```
/content/code_sandbox/Source/ModulatorAccum.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
562
```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 **/ // // SampleCanvas.h // Bespoke // // Created by Ryan Challinor on 6/24/15. // // #pragma once #include "IDrawableModule.h" #include "IAudioSource.h" #include "Transport.h" #include "Canvas.h" #include "Slider.h" #include "DropdownList.h" class CanvasControls; class CanvasTimeline; class CanvasScrollbar; class SampleCanvas : public IDrawableModule, public IAudioSource, public ICanvasListener, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener { public: SampleCanvas(); ~SampleCanvas(); static IDrawableModule* Create() { return new SampleCanvas(); } 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; } bool IsResizable() const override { return true; } void Resize(float w, float h) override; void Process(double time) override; NoteInterval GetInterval() const { return mInterval; } void CanvasUpdated(Canvas* canvas) override; void OnClicked(float x, float y, bool right) override; 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; } 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 DropdownUpdated(DropdownList* list, int oldVal, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 1; } bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void SetNumMeasures(int numMeasures); void UpdateNumColumns(); double GetCurPos(double time) const; Canvas* mCanvas{ nullptr }; CanvasControls* mCanvasControls{ nullptr }; CanvasTimeline* mCanvasTimeline{ nullptr }; CanvasScrollbar* mCanvasScrollbarHorizontal{ nullptr }; CanvasScrollbar* mCanvasScrollbarVertical{ nullptr }; IntSlider* mNumMeasuresSlider{ nullptr }; int mNumMeasures{ 4 }; NoteInterval mInterval{ NoteInterval::kInterval_1n }; DropdownList* mIntervalSelector{ nullptr }; }; ```
/content/code_sandbox/Source/SampleCanvas.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
732
```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 **/ // // ClipLauncher.h // Bespoke // // Created by Ryan Challinor on 1/17/15. // // #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 "OpenFrameworksPort.h" #include "JumpBlender.h" class Sample; class Looper; class ClipLauncher : public IAudioSource, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public ITimeListener, public IButtonListener { public: ClipLauncher(); ~ClipLauncher(); static IDrawableModule* Create() { return new ClipLauncher(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; int GetRowY(int idx); //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; void DropdownClicked(DropdownList* list) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void ButtonClicked(ClickButton* button, double time) override; void OnTimeEvent(double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: void RecalcPos(double time, int idx); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; class SampleData { public: SampleData() {} ~SampleData(); void Init(ClipLauncher* launcher, int index); void Draw(); Sample* mSample{ nullptr }; int mNumBars{ 1 }; float mVolume{ 1 }; Checkbox* mGrabCheckbox{ nullptr }; Checkbox* mPlayCheckbox{ nullptr }; ClipLauncher* mClipLauncher{ nullptr }; int mIndex{ 0 }; bool mPlay{ false }; bool mHasSample{ false }; }; Looper* mLooper{ nullptr }; float mVolume{ 1 }; FloatSlider* mVolumeSlider{ nullptr }; std::vector<SampleData> mSamples; JumpBlender mJumpBlender; ofMutex mSampleMutex; }; ```
/content/code_sandbox/Source/ClipLauncher.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
720
```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 **/ // // RhythmSequencer.cpp // Bespoke // // Created by Ryan Challinor on 12/5/23. // // #include "RhythmSequencer.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "UIControlMacros.h" RhythmSequencer::RhythmSequencer() { mTransportPriority = ITimeListener::kTransportPriorityLate; for (size_t i = 0; i < mInputPitches.size(); ++i) mInputPitches[i] = false; } void RhythmSequencer::Init() { IDrawableModule::Init(); mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(-.1f, true), false); } void RhythmSequencer::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 40); UIBLOCK_SHIFTRIGHT(); INTSLIDER(mLengthSlider, "length", &mLength, 1, kMaxSteps); UIBLOCK_SHIFTRIGHT(); CHECKBOX(mLinkLengthsCheckbox, "link lengths", &mLinkLengths); UIBLOCK_NEWLINE(); UIBLOCK_PUSHSLIDERWIDTH(70); INTSLIDER(mLengthActionSlider, "len act", &mLengthAction, 1, kMaxSteps); UIBLOCK_SHIFTRIGHT(); INTSLIDER(mLengthVelSlider, "len vel", &mLengthVel, 1, kMaxSteps); UIBLOCK_SHIFTRIGHT(); INTSLIDER(mLengthOctaveSlider, "len oct", &mLengthOctave, 1, kMaxSteps); UIBLOCK_SHIFTRIGHT(); INTSLIDER(mLengthDegreeSlider, "len deg", &mLengthDegree, 1, kMaxSteps); UIBLOCK_NEWLINE(); UIBLOCK_POPSLIDERWIDTH(); UIBLOCK_PUSHSLIDERWIDTH(70); UIBLOCK_SHIFTY(5); for (int i = 0; i < kMaxSteps; ++i) { xOffset += 10; DROPDOWN(mStepData[i].mActionSelector, ("action " + ofToString(i + 1)).c_str(), (int*)(&(mStepData[i].mAction)), 60); UIBLOCK_SHIFTRIGHT(); FLOATSLIDER_DIGITS(mStepData[i].mVelSlider, ("vel " + ofToString(i + 1)).c_str(), &(mStepData[i].mVel), 1.0f / 127.0f, 1.0f, 2); UIBLOCK_SHIFTRIGHT(); INTSLIDER(mStepData[i].mOctaveSlider, ("octave " + ofToString(i + 1)).c_str(), &(mStepData[i].mOctave), -3, 3); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mStepData[i].mDegreeSelector, ("degree " + ofToString(i + 1)).c_str(), &(mStepData[i].mDegree), 70); UIBLOCK_NEWLINE(); mStepData[i].mActionSelector->AddLabel("on", (int)StepAction::On); mStepData[i].mActionSelector->AddLabel("hold", (int)StepAction::Hold); mStepData[i].mActionSelector->AddLabel("off", (int)StepAction::Off); mStepData[i].mDegreeSelector->AddLabel("I", 0); mStepData[i].mDegreeSelector->AddLabel("II", 1); mStepData[i].mDegreeSelector->AddLabel("III", 2); mStepData[i].mDegreeSelector->AddLabel("IV", 3); mStepData[i].mDegreeSelector->AddLabel("V", 4); mStepData[i].mDegreeSelector->AddLabel("VI", 5); mStepData[i].mDegreeSelector->AddLabel("VII", 6); } UIBLOCK_POPSLIDERWIDTH(); ENDUIBLOCK(mWidth, mHeight); mIntervalSelector->AddLabel("64n", kInterval_64n); mIntervalSelector->AddLabel("32n", kInterval_32n); mIntervalSelector->AddLabel("16nt", kInterval_16nt); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("8nt", kInterval_8nt); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("4nt", kInterval_4nt); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("2n", kInterval_2n); mIntervalSelector->AddLabel("1n", kInterval_1n); } RhythmSequencer::~RhythmSequencer() { TheTransport->RemoveListener(this); } void RhythmSequencer::DrawModule() { if (Minimized() || IsVisible() == false) return; mIntervalSelector->SetShowing(!mHasExternalPulseSource); mIntervalSelector->Draw(); mLengthSlider->SetShowing(mLinkLengths); mLengthSlider->Draw(); mLinkLengthsCheckbox->Draw(); mLengthActionSlider->SetShowing(!mLinkLengths); mLengthActionSlider->Draw(); mLengthVelSlider->SetShowing(!mLinkLengths); mLengthVelSlider->Draw(); mLengthOctaveSlider->SetShowing(!mLinkLengths); mLengthOctaveSlider->Draw(); mLengthDegreeSlider->SetShowing(!mLinkLengths); mLengthDegreeSlider->Draw(); for (int i = 0; i < kMaxSteps; ++i) { mStepData[i].mActionSelector->Draw(); mStepData[i].mVelSlider->Draw(); mStepData[i].mOctaveSlider->Draw(); mStepData[i].mDegreeSelector->Draw(); } ofPushStyle(); if (mStepData[mArpIndexAction].mAction == StepAction::On) ofSetColor(0, 255, 0, 80); else if (DoesStepHold(mArpIndexAction, 0)) ofSetColor(255, 255, 0, 80); else ofSetColor(255, 0, 0, 80); ofFill(); if (mArpIndexAction >= 0 && mArpIndexAction < kMaxSteps) ofRect(mStepData[mArpIndexAction].mActionSelector->GetRect(true)); if (mArpIndexVel >= 0 && mArpIndexVel < kMaxSteps) ofRect(mStepData[mArpIndexVel].mVelSlider->GetRect(true)); if (mArpIndexOctave >= 0 && mArpIndexOctave < kMaxSteps) ofRect(mStepData[mArpIndexOctave].mOctaveSlider->GetRect(true)); if (mArpIndexDegree >= 0 && mArpIndexDegree < kMaxSteps) ofRect(mStepData[mArpIndexDegree].mDegreeSelector->GetRect(true)); ofSetColor(0, 255, 0, 255); for (int i = 0; i < (int)mStepData.size(); ++i) { if (mStepData[i].mAction == StepAction::On && i < mLengthAction) { ofRectangle rect = mStepData[i].mActionSelector->GetRect(true); ofCircle(rect.x - 6, rect.getCenter().y, 3); } if (DoesStepHold(i, 0) && i < mLengthAction) { ofRectangle rect = mStepData[i].mActionSelector->GetRect(true); ofLine(rect.x - 6, rect.getCenter().y + 1, rect.x - 6, rect.getCenter().y - 16); } } { ofSetColor(0, 0, 0, 100); ofRectangle rect = mStepData[(mLinkLengths ? mLength : mLengthAction) - 1].mActionSelector->GetRect(true); ofRect(rect.x, rect.getMaxY(), rect.width, mHeight - rect.getMaxY()); rect = mStepData[(mLinkLengths ? mLength : mLengthVel) - 1].mVelSlider->GetRect(true); ofRect(rect.x, rect.getMaxY(), rect.width, mHeight - rect.getMaxY()); rect = mStepData[(mLinkLengths ? mLength : mLengthOctave) - 1].mOctaveSlider->GetRect(true); ofRect(rect.x, rect.getMaxY(), rect.width, mHeight - rect.getMaxY()); rect = mStepData[(mLinkLengths ? mLength : mLengthDegree) - 1].mDegreeSelector->GetRect(true); ofRect(rect.x, rect.getMaxY(), rect.width, mHeight - rect.getMaxY()); } ofPopStyle(); } bool RhythmSequencer::DoesStepHold(int index, int depth) const { if (depth >= mLengthAction) return false; if (mStepData[index].mAction == StepAction::Hold) { int previous = (index + mLengthAction - 1) % mLengthAction; if (mStepData[previous].mAction == StepAction::On) return true; if (mStepData[previous].mAction == StepAction::Hold) return DoesStepHold(previous, depth + 1); } return false; } void RhythmSequencer::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { mNoteOutput.Flush(time); for (int i = 0; i < 128; ++i) mInputPitches[i] = false; } } void RhythmSequencer::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) mInputPitches[pitch] = velocity > 0; } void RhythmSequencer::OnPulse(double time, float velocity, int flags) { mHasExternalPulseSource = true; Step(time, velocity, flags); } void RhythmSequencer::OnTimeEvent(double time) { if (!mHasExternalPulseSource) Step(time, 1, 0); } void RhythmSequencer::Step(double time, float velocity, int pulseFlags) { if (!mEnabled) return; mArpIndex = GetArpIndex(time, mArpIndex, mLength, pulseFlags); if (mLinkLengths) { mArpIndexAction = mArpIndex; mArpIndexVel = mArpIndex; mArpIndexOctave = mArpIndex; mArpIndexDegree = mArpIndex; mLengthAction = mLength; mLengthVel = mLength; mLengthOctave = mLength; mLengthDegree = mLength; } else { mArpIndexAction = GetArpIndex(time, mArpIndexAction, mLengthAction, pulseFlags); mArpIndexVel = GetArpIndex(time, mArpIndexVel, mLengthVel, pulseFlags); mArpIndexOctave = GetArpIndex(time, mArpIndexOctave, mLengthOctave, pulseFlags); mArpIndexDegree = GetArpIndex(time, mArpIndexDegree, mLengthDegree, pulseFlags); } if (mEnabled) { bool* outputNotes = mNoteOutput.GetNotes(); for (int pitch = 0; pitch < 128; ++pitch) { if (outputNotes[pitch] && mStepData[mArpIndexAction].mAction != StepAction::Hold) mNoteOutput.PlayNote(time, pitch, 0); } for (int pitch = 0; pitch < 128; ++pitch) { if (mInputPitches[pitch] && mStepData[mArpIndexAction].mAction == StepAction::On) { int tone = TheScale->GetToneFromPitch(pitch) + mStepData[mArpIndexDegree].mDegree; int adjustedPitch = TheScale->GetPitchFromTone(tone) + mStepData[mArpIndexOctave].mOctave * 12; if (adjustedPitch >= 0 && adjustedPitch < 128) mNoteOutput.PlayNote(time, adjustedPitch, mStepData[mArpIndexVel].mVel * velocity * 127.0f); } } } } int RhythmSequencer::GetArpIndex(double time, int current, int length, int pulseFlags) { int direction = 1; if (pulseFlags & kPulseFlag_Backward) direction = -1; if (pulseFlags & kPulseFlag_Repeat) direction = 0; current += direction; if (direction > 0 && current >= length) current -= length; if (direction < 0 && current < 0) current += length; if (pulseFlags & kPulseFlag_Reset) current = 0; else if (pulseFlags & kPulseFlag_Random) current = gRandom() % length; if (!mHasExternalPulseSource || (pulseFlags & kPulseFlag_SyncToTransport)) { current = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo, length); } if (pulseFlags & kPulseFlag_Align) { int stepsPerMeasure = TheTransport->GetStepsPerMeasure(this); int numMeasures = ceil(float(length) / stepsPerMeasure); int measure = TheTransport->GetMeasure(time) % numMeasures; int step = ((TheTransport->GetQuantized(time, mTransportListenerInfo) % stepsPerMeasure) + measure * stepsPerMeasure) % length; current = step; } return current; } void RhythmSequencer::ButtonClicked(ClickButton* button, double time) { } void RhythmSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) { transportListenerInfo->mInterval = mInterval; transportListenerInfo->mOffsetInfo = OffsetInfo(-.1f, true); } } } void RhythmSequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void RhythmSequencer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void RhythmSequencer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } void RhythmSequencer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << mHasExternalPulseSource; } void RhythmSequencer::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (rev >= 0) in >> mHasExternalPulseSource; } ```
/content/code_sandbox/Source/RhythmSequencer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
3,575
```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 **/ // // EffectFactory.cpp // Bespoke // // Created by Ryan Challinor on 12/1/14. // // #include "EffectFactory.h" #include "BitcrushEffect.h" #include "DelayEffect.h" #include "BiquadFilterEffect.h" #include "DistortionEffect.h" //#include "Stutter.h" #include "TremoloEffect.h" #include "Compressor.h" #include "NoiseEffect.h" #include "GateEffect.h" //#include "ReverbEffect.h" #include "Muter.h" #include "Pumper.h" #include "LiveGranulator.h" #include "DCRemoverEffect.h" #include "FreeverbEffect.h" #include "EQEffect.h" //#include "AudioUnitEffect.h" #include "PitchShiftEffect.h" #include "ButterworthFilterEffect.h" #include "GainStageEffect.h" EffectFactory::EffectFactory() { Register("bitcrush", &(BitcrushEffect::Create)); Register("delay", &(DelayEffect::Create)); Register("biquad", &(BiquadFilterEffect::Create)); Register("distortion", &(DistortionEffect::Create)); //Register("stutter", &(Stutter::Create)); stutter is now a standalone module as StutterControl Register("tremolo", &(TremoloEffect::Create)); Register("compressor", &(Compressor::Create)); Register("noisify", &(NoiseEffect::Create)); Register("gate", &(GateEffect::Create)); //Register("reverb", &(ReverbEffect::Create)); Register("muter", &(Muter::Create)); Register("pumper", &(Pumper::Create)); Register("granulator", &(LiveGranulator::Create)); Register("dcremover", &(DCRemoverEffect::Create)); Register("freeverb", &(FreeverbEffect::Create)); Register("basiceq", &(EQEffect::Create)); //Register("audiounit", &(AudioUnitEffect::Create)); Register("pitchshift", &(PitchShiftEffect::Create)); //Register("formant", &(FormantFilterEffect::Create)); Register("butterworth", &(ButterworthFilterEffect::Create)); Register("gainstage", &(GainStageEffect::Create)); } void EffectFactory::Register(std::string type, CreateEffectFn creator) { mFactoryMap[type] = creator; } IAudioEffect* EffectFactory::MakeEffect(std::string type) { if (type == "eq") //fix up old save data type = "basiceq"; auto iter = mFactoryMap.find(type); if (iter != mFactoryMap.end()) return iter->second(); return nullptr; } std::vector<std::string> EffectFactory::GetSpawnableEffects() { std::vector<std::string> effects; for (auto iter = mFactoryMap.begin(); iter != mFactoryMap.end(); ++iter) effects.push_back(iter->first); sort(effects.begin(), effects.end()); return effects; } ```
/content/code_sandbox/Source/EffectFactory.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
740
```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 **/ // // SamplerGrid.cpp // Bespoke // // Created by Ryan Challinor on 6/12/14. // // #include "SamplerGrid.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "IAudioReceiver.h" #include "ofxJSONElement.h" #include "ModularSynth.h" #include "Sample.h" #include "Profiler.h" #include "EnvOscillator.h" #include "MidiController.h" SamplerGrid::SamplerGrid() : IAudioProcessor(gBufferSize) { } void SamplerGrid::CreateUIControls() { IDrawableModule::CreateUIControls(); mGrid = new UIGrid("uigrid", 2, 2, 90, 90, mCols, mRows, this); mGrid->SetListener(this); mGrid->SetMomentary(true); mPassthroughCheckbox = new Checkbox(this, "passthrough", mGrid, kAnchor_Right, &mPassthrough); mVolumeSlider = new FloatSlider(this, "vol", mPassthroughCheckbox, kAnchor_Below, 90, 15, &mVolume, 0, 2); mClearCheckbox = new Checkbox(this, "clear", mVolumeSlider, kAnchor_Below, &mClear); mEditCheckbox = new Checkbox(this, "edit", mClearCheckbox, kAnchor_Below, &mEditMode); mDuplicateCheckbox = new Checkbox(this, "duplicate", mEditCheckbox, kAnchor_Below, &mDuplicate); mEditStartSlider = new IntSlider(this, "start", mEditSampleX, mEditSampleY + mEditSampleHeight + 1, mEditSampleWidth, 15, &mDummyInt, 0, 1); mEditEndSlider = new IntSlider(this, "end", mEditStartSlider, kAnchor_Below, mEditSampleWidth, 15, &mDummyInt, 0, 1); mGridControlTarget = new GridControlTarget(this, "grid", 4, 4); mGridControlTarget->PositionTo(mClearCheckbox, kAnchor_Right); InitGrid(); } SamplerGrid::~SamplerGrid() { delete[] mGridSamples; } void SamplerGrid::Init() { IDrawableModule::Init(); UpdateLights(); } void SamplerGrid::Poll() { } void SamplerGrid::Process(double time) { PROFILER(SamplerGrid); 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); int bufferSize = GetBuffer()->BufferSize(); Clear(gWorkBuffer, gBufferSize); float volSq = mVolume * mVolume; for (int i = 0; i < gBufferSize; ++i) { for (int j = 0; j < mRows * mCols; ++j) { GridSample& sample = mGridSamples[j]; float rampVal = sample.mRamp.Value(time); if (rampVal > 0 && sample.mPlayhead < sample.mSampleEnd) { gWorkBuffer[i] += sample.mSampleData[sample.mPlayhead] * rampVal * volSq; ++sample.mPlayhead; if (sample.mRamp.Target(time) == 1 && sample.mPlayhead + SAMPLE_RAMP_MS / gInvSampleRateMs >= sample.mSampleEnd) sample.mRamp.Start(time, 0, time + SAMPLE_RAMP_MS); } } time += gInvSampleRateMs; } if (mRecordingSample != -1) { GridSample& sample = mGridSamples[mRecordingSample]; for (int i = 0; i < gBufferSize; ++i) { if (GetBuffer()->GetChannel(0)[i] != 0) sample.mHasSample = true; if (sample.mPlayhead < MAX_SAMPLER_GRID_LENGTH && sample.mHasSample) { sample.mSampleData[sample.mPlayhead] = GetBuffer()->GetChannel(0)[i]; // + gWorkBuffer[i]; ++sample.mPlayhead; sample.mSampleLength = sample.mPlayhead; sample.mSampleStart = 0; sample.mSampleEnd = sample.mPlayhead; } } } if (mPassthrough) { for (int i = 0; i < gBufferSize; ++i) gWorkBuffer[i] += GetBuffer()->GetChannel(0)[i]; } GetVizBuffer()->WriteChunk(gWorkBuffer, bufferSize, 0); Add(target->GetBuffer()->GetChannel(0), gWorkBuffer, bufferSize); GetBuffer()->Reset(); } void SamplerGrid::OnControllerPageSelected() { if (mGridControlTarget->GetGridController()) mGridControlTarget->GetGridController()->ResetLights(); /*delete[] mGridSamples; mCols = grid->NumCols(); if (mLastColumnIsGroup) mCols -= 1; mRows = grid->NumRows(); InitGrid();*/ UpdateLights(); } void SamplerGrid::InitGrid() { delete[] mGridSamples; mGridSamples = new GridSample[mRows * mCols]; for (int i = 0; i < mRows * mCols; ++i) { mGridSamples[i].mPlayhead = 0; mGridSamples[i].mHasSample = false; mGridSamples[i].mSampleLength = 0; } mGrid->SetGrid(mCols, mRows); } void SamplerGrid::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) { OnGridButton(col, row, value, nullptr); } void SamplerGrid::OnGridButton(int x, int y, float velocity, IGridController* grid) { bool bOn = velocity > 0; if (y < mRows && x < mCols) { int gridSampleIdx = GridToIdx(x, y); if (mDuplicate) { if (mEditSample) { mGridSamples[gridSampleIdx].mHasSample = true; mGridSamples[gridSampleIdx].mSampleLength = mEditSample->mSampleLength; mGridSamples[gridSampleIdx].mPlayhead = 0; mGridSamples[gridSampleIdx].mSampleStart = mEditSample->mSampleStart; mGridSamples[gridSampleIdx].mSampleEnd = mEditSample->mSampleEnd; BufferCopy(mGridSamples[gridSampleIdx].mSampleData, mEditSample->mSampleData, mEditSample->mSampleLength); } mDuplicate = false; } else if (mClear && bOn) { mGridSamples[gridSampleIdx].mHasSample = false; mGridSamples[gridSampleIdx].mSampleLength = 0; mGridSamples[gridSampleIdx].mPlayhead = 0; } else if (mGridSamples[gridSampleIdx].mHasSample) { if (bOn) mGridSamples[gridSampleIdx].mPlayhead = mGridSamples[gridSampleIdx].mSampleStart; mGridSamples[gridSampleIdx].mRamp.Start(gTime, bOn ? 1 : 0, gTime + SAMPLE_RAMP_MS); } else if (bOn) { if (mRecordingSample != -1) mGridSamples[mRecordingSample].mRecordingArmed = false; mGridSamples[gridSampleIdx].mRecordingArmed = true; mRecordingSample = gridSampleIdx; } if (bOn) SetEditSample(&mGridSamples[gridSampleIdx]); if (!bOn && mRecordingSample == gridSampleIdx) mRecordingSample = -1; } /*else if (x == mCols) { for (int i=0; i<mCols; ++i) { int gridSampleIdx = GridToIdx(i, y); if (mClear && bOn) { mGridSamples[gridSampleIdx].mHasSample = false; mGridSamples[gridSampleIdx].mSampleLength = 0; mGridSamples[gridSampleIdx].mPlayhead = 0; } else if (mGridSamples[gridSampleIdx].mHasSample && gridSampleIdx != mRecordingSample) { if (bOn) mGridSamples[gridSampleIdx].mPlayhead = mGridSamples[gridSampleIdx].mSampleStart; mGridSamples[gridSampleIdx].mRamp.Start(bOn ? 1 : 0, SAMPLE_RAMP_MS); } } }*/ UpdateLights(); } void SamplerGrid::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { OnGridButton(pitch % mCols, (pitch / mCols) % mRows, velocity / 127.0f, nullptr); } void SamplerGrid::SetEditSample(SamplerGrid::GridSample* sample) { mEditSample = sample; mEditStartSlider->SetVar(&mEditSample->mSampleStart); mEditStartSlider->SetExtents(0, mEditSample->mSampleLength); mEditEndSlider->SetVar(&mEditSample->mSampleEnd); mEditEndSlider->SetExtents(0, mEditSample->mSampleLength); } void SamplerGrid::UpdateLights() { if (!mGridControlTarget->GetGridController()) return; //clear lights for (int x = 0; x < mCols; ++x) { mGridControlTarget->GetGridController()->SetLight(x, mRows, mClear ? kGridColor1Bright : kGridColorOff); for (int y = 0; y < mRows; ++y) { int idx = GridToIdx(x, y); mGridControlTarget->GetGridController()->SetLight(x, y, mGridSamples[idx].mHasSample ? kGridColor2Bright : kGridColorOff); } } for (int y = 0; y < mRows; ++y) { mGridControlTarget->GetGridController()->SetLight(mCols, y, kGridColor1Bright); } mGridControlTarget->GetGridController()->SetLight(mCols, mRows, mClear ? kGridColor1Bright : kGridColorOff); } void SamplerGrid::SetEnabled(bool enabled) { mEnabled = enabled; } void SamplerGrid::DrawModule() { if (Minimized() || IsVisible() == false) return; mPassthroughCheckbox->Draw(); mVolumeSlider->Draw(); mEditCheckbox->Draw(); mClearCheckbox->Draw(); mGrid->Draw(); mGridControlTarget->Draw(); ofPushStyle(); ofSetColor(255, 255, 255, 100); ofFill(); for (int x = 0; x < mCols; ++x) { for (int y = 0; y < mRows; ++y) { int idx = GridToIdx(x, y); if (mGridSamples[idx].mHasSample) { ofVec2f cellPos = mGrid->GetCellPosition(x, y); ofVec2f gridSize = mGrid->IClickable::GetDimensions(); ofVec2f gridPos = mGrid->IClickable::GetPosition(); ofRect(gridPos.x + cellPos.x, gridPos.y + cellPos.y, gridSize.x / mCols, gridSize.y / mCols); } } } ofPopStyle(); if (mEditMode) { mDuplicateCheckbox->Draw(); if (mEditSample && mEditSample->mSampleLength > 0) { ofPushMatrix(); ofTranslate(mEditSampleX, mEditSampleY); DrawAudioBuffer(mEditSampleWidth, mEditSampleHeight, mEditSample->mSampleData, 0, mEditSample->mSampleLength, mEditSample->mPlayhead); ofPushStyle(); ofFill(); ofSetColor(0, 0, 0, 80); float clipStartAmount = float(mEditSample->mSampleStart) / mEditSample->mSampleLength; float clipEndAmount = float(mEditSample->mSampleEnd) / mEditSample->mSampleLength; ofRect(0, 0, mEditSampleWidth * clipStartAmount, mEditSampleHeight); ofRect(mEditSampleWidth * clipEndAmount, 0, mEditSampleWidth * (1 - clipEndAmount), mEditSampleHeight); ofPopStyle(); ofPopMatrix(); mEditStartSlider->Draw(); mEditEndSlider->Draw(); } } } void SamplerGrid::GetModuleDimensions(float& width, float& height) { if (mEditMode) { width = mEditSampleWidth; height = mEditSampleY + mEditSampleHeight + 17 * 2; } else { width = 188; height = mEditSampleY; } } void SamplerGrid::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); mGrid->TestClick(x, y, right); if (x >= mEditSampleX && x < mEditSampleX + mEditSampleWidth && y >= mEditSampleY && y < mEditSampleY + mEditSampleHeight) { if (mEditSample) { //TODO(Ryan) multichannel ChannelBuffer temp(mEditSample->mSampleData + mEditSample->mSampleStart, mEditSample->mSampleEnd - mEditSample->mSampleStart); TheSynth->GrabSample(&temp, "gridsample", K(window)); } } } void SamplerGrid::MouseReleased() { IDrawableModule::MouseReleased(); mGrid->MouseReleased(); } void SamplerGrid::FilesDropped(std::vector<std::string> files, int x, int y) { Sample sample; sample.Read(files[0].c_str()); SampleDropped(x, y, &sample); } void SamplerGrid::SampleDropped(int x, int y, Sample* sample) { assert(sample); int numSamples = sample->LengthInSamples(); if (numSamples <= 0) return; if (mEditSample == nullptr) return; mEditSample->mPlayhead = 0; mEditSample->mHasSample = true; mEditSample->mSampleLength = MIN(MAX_SAMPLER_GRID_LENGTH, numSamples); mEditSample->mSampleStart = 0; mEditSample->mSampleEnd = mEditSample->mSampleLength; //TODO(Ryan) multichannel for (int i = 0; i < mEditSample->mSampleLength; ++i) mEditSample->mSampleData[i] = sample->Data()->GetChannel(0)[i]; SetEditSample(mEditSample); //refresh } void SamplerGrid::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadBool("last_column_is_group", moduleInfo, true); SetUpFromSaveData(); } void SamplerGrid::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mLastColumnIsGroup = mModuleSaveData.GetBool("last_column_is_group"); } void SamplerGrid::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void SamplerGrid::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void SamplerGrid::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void SamplerGrid::CheckboxUpdated(Checkbox* checkbox, double time) { } void SamplerGrid::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); for (int i = 0; i < mCols * mRows; ++i) { out << mGridSamples[i].mPlayhead; out << mGridSamples[i].mHasSample; out << mGridSamples[i].mSampleLength; out << mGridSamples[i].mSampleStart; out << mGridSamples[i].mSampleEnd; if (mGridSamples[i].mHasSample) out.Write(mGridSamples[i].mSampleData, mGridSamples[i].mSampleLength); } } void SamplerGrid::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); //LoadStateValidate(false); //TODO(Ryan) temp hack fix because samplergrid was loading funny for (int i = 0; i < mCols * mRows; ++i) { in >> mGridSamples[i].mPlayhead; in >> mGridSamples[i].mHasSample; in >> mGridSamples[i].mSampleLength; in >> mGridSamples[i].mSampleStart; in >> mGridSamples[i].mSampleEnd; if (mGridSamples[i].mHasSample) in.Read(mGridSamples[i].mSampleData, mGridSamples[i].mSampleLength); } } ```
/content/code_sandbox/Source/SamplerGrid.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
4,023
```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 **/ // // PitchChorus.h // Bespoke // // Created by Ryan Challinor on 6/19/15. // // #pragma once #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "Slider.h" #include "PitchShifter.h" #include "INoteReceiver.h" #include "Ramp.h" #include "Checkbox.h" class PitchChorus : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public INoteReceiver { public: PitchChorus(); virtual ~PitchChorus(); static IDrawableModule* Create() { return new PitchChorus(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; //IAudioProcessor InputMode GetInputMode() override { return kInputMode_Mono; } //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void CheckboxUpdated(Checkbox* checkbox, double time) override {} 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 {} bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = 120; h = 22; } static const int kNumShifters = 5; struct PitchShifterVoice { PitchShifterVoice() : mShifter(1024) , mOn(false) , mPitch(-1) {} PitchShifter mShifter; bool mOn; Ramp mRamp; int mPitch; }; float* mOutputBuffer; PitchShifterVoice mShifters[kNumShifters]; bool mPassthrough; Checkbox* mPassthroughCheckbox; }; ```
/content/code_sandbox/Source/PitchChorus.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
586
```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.cpp Created: 15 Apr 2019 9:32:38pm Author: Ryan Challinor ============================================================================== */ #include "MidiCapturer.h" #include "SynthGlobals.h" #include "MidiDevice.h" MidiCapturerDummyController::MidiCapturerDummyController(MidiDeviceListener* listener) { mListener = listener; dynamic_cast<MidiCapturer*>(TheSynth->FindModule("midicapturer"))->AddDummyController(this); } void MidiCapturerDummyController::SendMidi(const juce::MidiMessage& message) { MidiDevice::SendMidiMessage(mListener, "midicapturer", message); } namespace { const int kSaveStateRev = 1; } void MidiCapturerDummyController::SaveState(FileStreamOut& out) { out << kSaveStateRev; } void MidiCapturerDummyController::LoadState(FileStreamIn& in) { int rev; in >> rev; LoadStateValidate(rev <= kSaveStateRev); } MidiCapturer::MidiCapturer() { for (int i = 0; i < kRingBufferLength; ++i) mMessages[i].setTimeStamp(-1); } void MidiCapturer::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } MidiCapturer::~MidiCapturer() { TheTransport->RemoveAudioPoller(this); } void MidiCapturer::DrawModule() { if (Minimized() || IsVisible() == false) return; } void MidiCapturer::OnTransportAdvanced(float amount) { while (mMessages[mPlayhead].getTimeStamp() > 0 && mMessages[mPlayhead].getTimeStamp() < TheTransport->GetMeasureTime(gTime) - 1) { for (auto c : mDummyControllers) c->SendMidi(mMessages[mPlayhead]); mMessages[mPlayhead].setTimeStamp(-1); //TODO(Ryan) remove this mPlayhead = (mPlayhead + 1) % kRingBufferLength; } } void MidiCapturer::AddDummyController(MidiCapturerDummyController* controller) { mDummyControllers.push_back(controller); } void MidiCapturer::SendMidi(const juce::MidiMessage& message) { //ofLog() << message.getDescription(); auto copy = message; copy.setTimeStamp(TheTransport->GetMeasureTime(gTime)); mMessages[mRingBufferPos] = copy; mRingBufferPos = (mRingBufferPos + 1) % kRingBufferLength; } void MidiCapturer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void MidiCapturer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void MidiCapturer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/MidiCapturer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
774
```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 **/ // // PatchCableSource.h // Bespoke // // Created by Ryan Challinor on 12/13/15. // // #pragma once #include "PatchCable.h" #include "IClickable.h" #include "SynthGlobals.h" #include "IDrawableModule.h" class IAudioReceiver; class INoteReceiver; class IPulseReceiver; class IModulator; enum DefaultPatchBehavior { kDefaultPatchBehavior_Repatch, kDefaultPatchBehavior_Add }; enum PatchCableDrawMode { kPatchCableDrawMode_Normal, kPatchCableDrawMode_CablesOnHoverOnly, kPatchCableDrawMode_SourceOnHoverOnly }; #define NOTE_HISTORY_LENGTH 250 struct NoteHistoryEvent { bool mOn{ false }; double mTime{ 0 }; int mData{ 0 }; }; class NoteHistory { public: void AddEvent(double time, bool on, int data); bool CurrentlyOn(); double GetLastOnEventTime() { return mLastOnEventTime; } const NoteHistoryEvent& GetHistoryEvent(int ago) const; static const int kHistorySize = 100; private: NoteHistoryEvent mHistory[kHistorySize]{}; int mHistoryPos{ 0 }; double mLastOnEventTime{ -999 }; }; class PatchCableSource : public IClickable { public: enum class Side { kNone, kBottom, kLeft, kRight }; PatchCableSource(IDrawableModule* owner, ConnectionType type); virtual ~PatchCableSource(); PatchCable* AddPatchCable(IClickable* target); const std::vector<PatchCable*>& GetPatchCables() const { return mPatchCables; } void Clear(); void FindValidTargets(); bool IsValidTarget(IClickable* target) const; void CableGrabbed(); ConnectionType GetConnectionType() const { return mType; } void SetConnectionType(ConnectionType type); IDrawableModule* GetOwner() const { return mOwner; } void SetOverrideVizBuffer(RollingBuffer* viz) { mOverrideVizBuffer = viz; } RollingBuffer* GetOverrideVizBuffer() const { return mOverrideVizBuffer; } void UpdatePosition(bool parentMinimized); void SetManualPosition(int x, int y) { mManualPositionX = x; mManualPositionY = y; mAutomaticPositioning = false; } void RemovePatchCable(PatchCable* cable, bool fromUserAction = false); void ClearPatchCables(); void SetPatchCableTarget(PatchCable* cable, IClickable* target, bool fromUserClick); const std::vector<INoteReceiver*>& GetNoteReceivers() const { return mNoteReceivers; } const std::vector<IPulseReceiver*>& GetPulseReceivers() const { return mPulseReceivers; } IAudioReceiver* GetAudioReceiver() const { return mAudioReceiver; } IClickable* GetTarget() const; void SetTarget(IClickable* target); void SetAllowMultipleTargets(bool allow) { mAllowMultipleTargets = allow; } void SetDefaultPatchBehavior(DefaultPatchBehavior beh) { mDefaultPatchBehavior = beh; } void SetPatchCableDrawMode(PatchCableDrawMode mode) { mPatchCableDrawMode = mode; } void SetColor(ofColor color) { mColor = color; } ofColor GetColor() const; void SetEnabled(bool enabled) { mEnabled = enabled; } bool Enabled() const; void AddTypeFilter(std::string type) { mTypeFilter.push_back(type); } void ClearTypeFilter() { mTypeFilter.clear(); } void SetManualSide(Side side) { mManualSide = side; } void SetClickable(bool clickable) { mClickable = clickable; } bool TestHover(float x, float y) const; void SetOverrideCableDir(ofVec2f dir, Side side) { mHasOverrideCableDir = true; mOverrideCableDir = dir; mManualSide = side; } ofVec2f GetCableStart(int index) const; ofVec2f GetCableStartDir(int index, ofVec2f dest) const; void SetModulatorOwner(IModulator* modulator) { mModulatorOwner = modulator; } IModulator* GetModulatorOwner() const { return mModulatorOwner; } void SetIsPartOfCircularDependency(bool set) { mIsPartOfCircularDependency = set; } bool GetIsPartOfCircularDependency() const { return mIsPartOfCircularDependency; } void AddHistoryEvent(double time, bool on, int data = 0) { mNoteHistory.AddEvent(time, on, data); if (on) { mLastOnEventTime = time; } } NoteHistory& GetHistory() { return mNoteHistory; } double GetLastOnEventTime() const { return mLastOnEventTime; } void DrawSource(); void DrawCables(bool parentMinimized); void Render() override; bool TestClick(float x, float y, bool right, bool testOnly = false) override; bool MouseMoved(float x, float y) override; void MouseReleased() override; void GetDimensions(float& width, float& height) override { width = 10; height = 10; } void KeyPressed(int key, bool isRepeat); bool IsHovered() const { return mHoverIndex != -1; } void SaveState(FileStreamOut& out); void LoadState(FileStreamIn& in); static bool sAllowInsert; static bool sIsLoadingModulePreset; protected: void OnClicked(float x, float y, bool right) override; private: bool InAddCableMode() const; int GetHoverIndex(float x, float y) const; std::vector<PatchCable*> mPatchCables; int mHoverIndex{ -1 }; //-1 = not hovered ConnectionType mType{ ConnectionType::kConnectionType_Audio }; bool mAllowMultipleTargets{ true }; DefaultPatchBehavior mDefaultPatchBehavior{ DefaultPatchBehavior::kDefaultPatchBehavior_Repatch }; PatchCableDrawMode mPatchCableDrawMode{ PatchCableDrawMode::kPatchCableDrawMode_Normal }; IDrawableModule* mOwner{ nullptr }; RollingBuffer* mOverrideVizBuffer{ nullptr }; bool mAutomaticPositioning{ true }; int mManualPositionX{ 0 }; int mManualPositionY{ 0 }; ofColor mColor; bool mEnabled{ true }; bool mClickable{ true }; Side mSide{ Side::kNone }; Side mManualSide{ Side::kNone }; bool mHasOverrideCableDir{ false }; ofVec2f mOverrideCableDir; bool mIsPartOfCircularDependency{ false }; std::vector<INoteReceiver*> mNoteReceivers; std::vector<IPulseReceiver*> mPulseReceivers; IAudioReceiver* mAudioReceiver{ nullptr }; std::vector<std::string> mTypeFilter; std::vector<IClickable*> mValidTargets; NoteHistory mNoteHistory; double mLastOnEventTime{ -9999 }; IModulator* mModulatorOwner{ nullptr }; enum class DrawPass { kSource, kCables }; DrawPass mDrawPass{ DrawPass::kSource }; bool mParentMinimized{ false }; IDrawableModule* mLastSeenAutopatchableModule{ nullptr }; }; ```
/content/code_sandbox/Source/PatchCableSource.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,794
```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.cpp // Bespoke // // Created by Ryan Challinor on 2/1/15. // // #include "CommentDisplay.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include <cstring> CommentDisplay::CommentDisplay() { } CommentDisplay::~CommentDisplay() { } void CommentDisplay::CreateUIControls() { IDrawableModule::CreateUIControls(); mCommentEntry = new TextEntry(this, "comment", 2, 2, MAX_TEXTENTRY_LENGTH - 1, &mComment); mCommentEntry->SetFlexibleWidth(true); } void CommentDisplay::DrawModule() { if (Minimized() || IsVisible() == false) return; mCommentEntry->Draw(); } void CommentDisplay::GetModuleDimensions(float& w, float& h) { mCommentEntry->GetDimensions(w, h); w += 4; h += 4; } void CommentDisplay::TextEntryComplete(TextEntry* entry) { } void CommentDisplay::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("comment", moduleInfo, "insert comment here"); SetUpFromSaveData(); } void CommentDisplay::SetUpFromSaveData() { mComment = mModuleSaveData.GetString("comment"); } void CommentDisplay::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["comment"] = mComment; } ```
/content/code_sandbox/Source/CommentDisplay.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
403
```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 **/ // // Sample.cpp // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #include "Sample.h" #include "SynthGlobals.h" #include "FileStream.h" #include "ModularSynth.h" #include "ChannelBuffer.h" #include <memory> #include "juce_audio_formats/juce_audio_formats.h" Sample::Sample() { } Sample::~Sample() { } bool Sample::Read(const char* path, bool mono, ReadType readType) { mReadPath = path; ofStringReplace(mReadPath, GetPathSeparator(), "/"); std::vector<std::string> tokens = ofSplitString(mReadPath, "/"); mName = tokens[tokens.size() - 1]; juce::File file(ofToDataPath(mReadPath)); delete mReader; mReader = TheSynth->GetAudioFormatManager().createReaderFor(file); if (mReader != nullptr) { mData.Resize((int)mReader->lengthInSamples); if (mono) mData.SetNumActiveChannels(1); else mData.SetNumActiveChannels(mReader->numChannels); mData.Clear(); mNumSamples = (int)mReader->lengthInSamples; mOffset = mNumSamples; mOriginalSampleRate = mReader->sampleRate; mSampleRateRatio = float(mOriginalSampleRate) / gSampleRate; mReadBuffer = std::make_unique<juce::AudioSampleBuffer>(); mReadBuffer->setSize(mReader->numChannels, mNumSamples); if (readType == ReadType::Sync) { mReader->read(mReadBuffer.get(), 0, mNumSamples, 0, true, true); FinishRead(); } else if (readType == ReadType::Async) { mSamplesLeftToRead = mNumSamples; startTimer(100); } return true; } else { TheSynth->LogEvent("failed to load sample " + file.getFullPathName().toStdString(), kLogEventType_Error); } return false; } void Sample::FinishRead() { if (mData.NumActiveChannels() == 1 && mReadBuffer->getNumChannels() > 1) { BufferCopy(mData.GetChannel(0), mReadBuffer->getReadPointer(0), mReadBuffer->getNumSamples()); //put first channel in for (int ch = 1; ch < mReadBuffer->getNumChannels(); ++ch) Add(mData.GetChannel(0), mReadBuffer->getReadPointer(ch), mReadBuffer->getNumSamples()); //add the other channels Mult(mData.GetChannel(0), 1.0f / mReadBuffer->getNumChannels(), mReadBuffer->getNumSamples()); //normalize volume } else { for (int ch = 0; ch < mReadBuffer->getNumChannels(); ++ch) BufferCopy(mData.GetChannel(ch), mReadBuffer->getReadPointer(ch), mReadBuffer->getNumSamples()); } } //juce::Timer void Sample::timerCallback() { int samplesToRead = 44100 * 10; if (samplesToRead > mSamplesLeftToRead) samplesToRead = mSamplesLeftToRead; int startSample = mNumSamples - mSamplesLeftToRead; mReader->read(mReadBuffer.get(), startSample, samplesToRead, startSample, true, true); mSamplesLeftToRead -= samplesToRead; if (mSamplesLeftToRead <= 0) { FinishRead(); stopTimer(); } } void Sample::Create(int length) { mData.Resize(length); mData.SetNumActiveChannels(1); Setup(length); } void Sample::Create(ChannelBuffer* data) { int channels = data->NumActiveChannels(); int length = data->BufferSize(); mData.Resize(length); mData.SetNumActiveChannels(channels); for (int ch = 0; ch < channels; ++ch) BufferCopy(mData.GetChannel(ch), data->GetChannel(ch), length); Setup(length); } void Sample::Setup(int length) { mNumSamples = length; mRate = 1; mOffset = length; mOriginalSampleRate = gSampleRate; mSampleRateRatio = 1; mStopPoint = -1; mName = "newsample"; mReadPath = ""; } bool Sample::Write(const char* path /*=nullptr*/) { const std::string writeTo = path ? path : mReadPath; WriteDataToFile(writeTo, &mData, mNumSamples); return true; } //static bool Sample::WriteDataToFile(const std::string& path, float** data, int numSamples, int channels) { auto wavFormat = std::make_unique<juce::WavAudioFormat>(); juce::File outputFile(ofToDataPath(path)); 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)); writer->writeFromFloatArrays(data, channels, numSamples); return true; } //static bool Sample::WriteDataToFile(const std::string& path, ChannelBuffer* data, int numSamples) { int numChannels = data->NumActiveChannels(); float** channelData = new float*[numChannels]; for (int ch = 0; ch < numChannels; ++ch) channelData[ch] = data->GetChannel(ch); bool ret = WriteDataToFile(path, channelData, numSamples, numChannels); delete[] channelData; return ret; } void Sample::Play(double startTime, float rate /*=1*/, int offset /*=0*/, int stopPoint /*=-1*/) { mPlayMutex.lock(); mStartTime = startTime; mOffset = offset; mRate = rate; if (stopPoint != -1) SetStopPoint(stopPoint); else ClearStopPoint(); mPlayMutex.unlock(); } bool Sample::ConsumeData(double time, ChannelBuffer* out, int size, bool replace) { assert(size <= out->BufferSize()); mPlayMutex.lock(); float end = mNumSamples; if (mStopPoint != -1) end = mStopPoint; if (mLooping && mOffset >= mNumSamples) mOffset -= mNumSamples; if (mOffset >= end || std::isnan(mOffset)) { mPlayMutex.unlock(); return false; } LockDataMutex(true); for (int i = 0; i < size; ++i) { if (time < mStartTime) { if (replace) { for (int ch = 0; ch < out->NumActiveChannels(); ++ch) out->GetChannel(ch)[i] = 0; } } else { for (int ch = 0; ch < out->NumActiveChannels(); ++ch) { int dataChannel = MIN(ch, mData.NumActiveChannels() - 1); float sample = 0; if (mOffset < end || mLooping) sample = GetInterpolatedSample(mOffset, mData.GetChannel(dataChannel), mNumSamples) * mVolume; if (replace) out->GetChannel(ch)[i] = sample; else out->GetChannel(ch)[i] += sample; } mOffset += mRate * mSampleRateRatio; } time += gInvSampleRateMs; } LockDataMutex(false); mPlayMutex.unlock(); return true; } void Sample::PadBack(int amount) { //TODO(Ryan) /*int newSamples = mNumSamples + amount; float* newData = new float[newSamples]; BufferCopy(newData, mData, mNumSamples); Clear(newData+mNumSamples, amount); LockDataMutex(true); delete mData; mData = newData; LockDataMutex(false); mNumSamples = newSamples;*/ } void Sample::ClipTo(int start, int end) { //TODO(Ryan) /*assert(start < end); assert(end <= mNumSamples); int newSamples = end-start; float* newData = new float[newSamples]; BufferCopy(newData, mData+start, newSamples); LockDataMutex(true); delete mData; mData = newData; LockDataMutex(false); mNumSamples = newSamples;*/ } void Sample::ShiftWrap(int numSamplesToShift) { //TODO(Ryan) /*assert(numSamplesToShift <= mNumSamples); float* newData = new float[mNumSamples]; int chunk = mNumSamples - numSamplesToShift; BufferCopy(newData, mData+numSamplesToShift, chunk); BufferCopy(newData+chunk, mData, numSamplesToShift); LockDataMutex(true); delete mData; mData = newData; LockDataMutex(false);*/ } void Sample::CopyFrom(Sample* sample) { mNumSamples = sample->mNumSamples; if (mData.BufferSize() != sample->mData.BufferSize()) mData.Resize(sample->mNumSamples); mData.CopyFrom(&sample->mData); mNumBars = sample->mNumBars; mLooping = sample->mLooping; mRate = sample->mRate; mOriginalSampleRate = sample->mOriginalSampleRate; mSampleRateRatio = sample->mSampleRateRatio; mStopPoint = sample->mStopPoint; mName = sample->mName; mReadPath = sample->mReadPath; } namespace { const int kSaveStateRev = 1; } void Sample::SaveState(FileStreamOut& out) { out << kSaveStateRev; out << mNumSamples; if (mNumSamples > 0) mData.Save(out, mNumSamples); out << mNumBars; out << mLooping; out << mRate; out << mOriginalSampleRate; out << mStopPoint; out << mName; out << mReadPath; } void Sample::LoadState(FileStreamIn& in) { int rev; in >> rev; in >> mNumSamples; if (mNumSamples > 0) { int readLength; mData.Load(in, readLength, ChannelBuffer::LoadMode::kSetBufferSize); assert(readLength == mNumSamples); /*for (int ch=0; ch<mData.NumActiveChannels(); ++ch) { float* channelBuffer = mData.GetChannel(ch); for (int i=0; i<mData.BufferSize(); ++i) { assert(channelBuffer[i] >= -1 && channelBuffer[i] <= 1); } }*/ } in >> mNumBars; in >> mLooping; in >> mRate; if (rev == 0) { in >> mSampleRateRatio; mOriginalSampleRate = gSampleRate * mSampleRateRatio; } else { in >> mOriginalSampleRate; mSampleRateRatio = float(mOriginalSampleRate) / gSampleRate; } in >> mStopPoint; in >> mName; in >> mReadPath; } ```
/content/code_sandbox/Source/Sample.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,589
```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 **/ /* ============================================================================== ModWheelToCV.h Created: 28 Nov 2017 10:44:25pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "INoteReceiver.h" #include "IModulator.h" #include "Slider.h" class PatchCableSource; class ModulationChain; class ModWheelToCV : public IDrawableModule, public INoteReceiver, public IModulator, public IFloatSliderListener { public: ModWheelToCV(); virtual ~ModWheelToCV(); static IDrawableModule* Create() { return new ModWheelToCV(); } 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 * 2 + 2; } ModulationChain* mModWheel{ nullptr }; }; ```
/content/code_sandbox/Source/ModWheelToCV.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
550
```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 **/ // // Canvas.h // Bespoke // // Created by Ryan Challinor on 12/29/14. // // #pragma once #include <iostream> #include "IUIControl.h" #include "CanvasElement.h" #include "juce_gui_basics/juce_gui_basics.h" #define MAX_CANVAS_MASK_ELEMENTS 128 class Canvas; class CanvasControls; class CanvasElement; typedef CanvasElement* (*CreateCanvasElementFn)(Canvas* canvas, int col, int row); class ICanvasListener { public: virtual ~ICanvasListener() {} virtual void CanvasUpdated(Canvas* canvas) = 0; virtual void ElementRemoved(CanvasElement* element) {} }; struct CanvasCoord { CanvasCoord(int _col, int _row) : col(_col) , row(_row) {} int col; int row; }; class Canvas : public IUIControl { public: enum HighlightEnd { kHighlightEnd_None, kHighlightEnd_Start, kHighlightEnd_End }; enum DragMode { kDragNone = 0, kDragHorizontal = 1, kDragVertical = 2, kDragBoth = kDragHorizontal | kDragVertical }; public: Canvas(IDrawableModule* parent, int x, int y, int w, int h, float length, int rows, int cols, CreateCanvasElementFn elementCreator); ~Canvas(); void Render() override; 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; void Clear(); void SetListener(ICanvasListener* listener) { mListener = listener; } void SetDimensions(int width, int height) { mWidth = width; mHeight = height; } float GetWidth() const { return mWidth; } float GetHeight() const { return mHeight; } void SetLength(float length) { mLength = length; } float GetLength() const { return mLength; } void SetNumRows(int rows) { mNumRows = rows; } void SetNumCols(int cols) { mNumCols = cols; } int GetNumRows() const { return mNumRows; } int GetNumCols() const { return mNumCols; } void RescaleNumCols(int cols); void AddElement(CanvasElement* element); void RemoveElement(CanvasElement* element); void SelectElement(CanvasElement* element); void SelectElements(std::vector<CanvasElement*> elements); void SetControls(CanvasControls* controls) { mControls = controls; } CanvasControls* GetControls() { return mControls; } std::vector<CanvasElement*>& GetElements() { return mElements; } void FillElementsAt(float pos, std::vector<CanvasElement*>& elements) const; void EraseElementsAt(float pos); CanvasElement* GetElementAt(float pos, int row); void SetCursorPos(float pos) { mCursorPos = pos; } float GetCursorPos() const { return mCursorPos; } CanvasElement* CreateElement(int col, int row) { return mElementCreator(this, col, row); } CanvasCoord GetCoordAt(int x, int y); void SetNumVisibleRows(int rows) { mNumVisibleRows = rows; } int GetNumVisibleRows() const { return MIN(mNumVisibleRows, mNumRows); } void SetRowOffset(int offset) { mRowOffset = ofClamp(offset, 0, mNumRows - mNumVisibleRows); } int GetRowOffset() const { return mRowOffset; } bool ShouldWrap() const { return mWrap; } HighlightEnd GetHighlightEnd() const { return mHighlightEnd; } void SetMajorColumnInterval(int interval) { mMajorColumnInterval = interval; } void SetDragMode(DragMode mode) { mDragMode = mode; } DragMode GetDragMode() const { return mDragMode; } bool IsRowVisible(int row) const; void SetRowColor(int row, ofColor color); juce::MouseCursor GetMouseCursorType(); ofVec2f RescaleForZoom(float x, float y) const; //IUIControl void SetFromMidiCC(float slider, double time, bool setViaModulator) override {} void SetValue(float value, double time, bool forceUpdate = false) override {} void KeyPressed(int key, bool isRepeat) override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, bool shouldSetValue = true) override; bool IsSliderControl() override { return false; } bool IsButtonControl() override { return false; } bool GetNoHover() const override { return true; } bool CanBeTargetedBy(PatchCableSource* source) const override; bool ShouldSerializeForSnapshot() const override { return true; } float mViewStart{ 0 }; float mViewEnd; float mLoopStart{ 0 }; float mLoopEnd; private: void OnClicked(float x, float y, bool right) override; void GetDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } bool IsOnElement(CanvasElement* element, float x, float y) const; float QuantizeToGrid(float input) const; bool mClick{ false }; CanvasElement* mClickedElement{ nullptr }; ofVec2f mClickedElementStartMousePos; float mWidth; float mHeight; float mLength; ICanvasListener* mListener{ nullptr }; std::vector<CanvasElement*> mElements; CanvasControls* mControls{ nullptr }; float mCursorPos{ -1 }; CreateCanvasElementFn mElementCreator; int mRowOffset{ 0 }; bool mWrap{ false }; bool mDragSelecting{ false }; ofRectangle mDragSelectRect; bool mDragCanvasMoving{ false }; bool mDragCanvasZooming{ false }; ofVec2f mDragCanvasStartMousePos; ofVec2f mDragCanvasStartCanvasPos; ofVec2f mDragZoomStartDimensions; HighlightEnd mHighlightEnd{ HighlightEnd::kHighlightEnd_None }; CanvasElement* mHighlightEndElement{ nullptr }; HighlightEnd mDragEnd{ HighlightEnd::kHighlightEnd_None }; int mMajorColumnInterval{ -1 }; bool mHasDuplicatedThisDrag{ false }; float mScrollVerticalPartial{ 0 }; std::array<ofColor, 128> mRowColors; int mNumRows; int mNumCols; int mNumVisibleRows; DragMode mDragMode{ DragMode::kDragBoth }; friend CanvasControls; }; ```
/content/code_sandbox/Source/Canvas.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,593
```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 **/ /* ============================================================================== NoteStreamDisplay.h Created: 21 May 2020 11:13:12pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "NoteEffectBase.h" #include "ClickButton.h" class NoteStreamDisplay : public NoteEffectBase, public IDrawableModule, public IButtonListener { public: NoteStreamDisplay(); static IDrawableModule* Create() { return new NoteStreamDisplay(); } void CreateUIControls() override; static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } bool IsResizable() const override { return true; } void Resize(float w, float h) override; //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void ButtonClicked(ClickButton* button, double time) override; bool HasDebugDraw() const override { return true; } void LoadLayout(const ofxJSONElement& moduleInfo) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void DrawModuleUnclipped() override; void GetModuleDimensions(float& w, float& h) override { w = mWidth; h = mHeight; } bool IsElementActive(int index) const; float GetYPos(int pitch, float noteHeight) const; struct NoteStreamElement { int pitch{ 0 }; int velocity{ 0 }; double timeOn{ -1 }; double timeOff{ -1 }; }; static const int kNoteStreamCapacity = 100; NoteStreamElement mNoteStream[kNoteStreamCapacity]; float mWidth{ 400 }; float mHeight{ 200 }; float mDurationMs{ 2000 }; int mPitchMin{ 127 }; int mPitchMax{ 0 }; ClickButton* mResetButton{ nullptr }; }; ```
/content/code_sandbox/Source/NoteStreamDisplay.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
588
```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 **/ /* ============================================================================== ModulatorSmoother.cpp Created: 29 Nov 2017 9:35:32pm Author: Ryan Challinor ============================================================================== */ #include "ModulatorSmoother.h" #include "Profiler.h" #include "ModularSynth.h" #include "PatchCableSource.h" ModulatorSmoother::ModulatorSmoother() { } void ModulatorSmoother::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void ModulatorSmoother::CreateUIControls() { IDrawableModule::CreateUIControls(); mInputSlider = new FloatSlider(this, "input", 3, 2, 100, 15, &mInput, 0, 1); mSmoothSlider = new FloatSlider(this, "smooth", mInputSlider, kAnchor_Below, 100, 15, &mSmooth, 0, 1); mSmoothSlider->SetMode(FloatSlider::kSquare); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } ModulatorSmoother::~ModulatorSmoother() { TheTransport->RemoveAudioPoller(this); } void ModulatorSmoother::DrawModule() { if (Minimized() || IsVisible() == false) return; mInputSlider->Draw(); mSmoothSlider->Draw(); } void ModulatorSmoother::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); if (GetSliderTarget() && fromUserClick) { mInput = GetSliderTarget()->GetValue(); mInputSlider->SetExtents(GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax()); mInputSlider->SetMode(GetSliderTarget()->GetMode()); } } void ModulatorSmoother::OnTransportAdvanced(float amount) { mRamp.Start(gTime, mInput, gTime + (amount * TheTransport->MsPerBar() * (mSmooth * 300))); } float ModulatorSmoother::Value(int samplesIn) { ComputeSliders(samplesIn); return ofClamp(mRamp.Value(gTime + samplesIn * gInvSampleRateMs), GetMin(), GetMax()); } void ModulatorSmoother::SaveLayout(ofxJSONElement& moduleInfo) { } void ModulatorSmoother::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void ModulatorSmoother::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/ModulatorSmoother.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
676
```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 **/ /* ============================================================================== IPulseReceiver.cpp Created: 20 Sep 2018 9:24:33pm Author: Ryan Challinor ============================================================================== */ #include "IPulseReceiver.h" #include "PatchCableSource.h" void IPulseSource::DispatchPulse(PatchCableSource* destination, double time, float velocity, int flags) { if (time == destination->GetLastOnEventTime()) //avoid stack overflow return; const std::vector<IPulseReceiver*>& receivers = destination->GetPulseReceivers(); destination->AddHistoryEvent(time, true, flags); destination->AddHistoryEvent(time + 15, false); for (auto* receiver : receivers) receiver->OnPulse(time, velocity, flags); } ```
/content/code_sandbox/Source/IPulseReceiver.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
265
```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 **/ // // ModwheelToPressure.cpp // Bespoke // // Created by Ryan Challinor on 1/4/16. // // #include "ModwheelToPressure.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" ModwheelToPressure::ModwheelToPressure() { } ModwheelToPressure::~ModwheelToPressure() { } void ModwheelToPressure::DrawModule() { if (Minimized() || IsVisible() == false) return; } void ModwheelToPressure::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) { modulation.pressure = modulation.modWheel; modulation.modWheel = nullptr; } PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void ModwheelToPressure::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void ModwheelToPressure::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/ModwheelToPressure.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
334
```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 **/ // // VelocitySetter.cpp // modularSynth // // Created by Ryan Challinor on 5/16/13. // // #include "VelocitySetter.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "ModularSynth.h" VelocitySetter::VelocitySetter() { } void VelocitySetter::CreateUIControls() { IDrawableModule::CreateUIControls(); mVelocitySlider = new FloatSlider(this, "vel", 5, 2, 80, 15, &mVelocity, 0, 1); mRandomnessSlider = new FloatSlider(this, "rand", 5, 20, 80, 15, &mRandomness, 0, 1); } void VelocitySetter::DrawModule() { if (Minimized() || IsVisible() == false) return; mVelocitySlider->Draw(); mRandomnessSlider->Draw(); } void VelocitySetter::CheckboxUpdated(Checkbox* checkbox, double time) { } void VelocitySetter::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { ComputeSliders(0); float random = ofRandom(1 - mRandomness, 1); if (mEnabled && velocity != 0) { PlayNoteOutput(time, pitch, int(mVelocity * 127 * random), voiceIdx, modulation); } else { PlayNoteOutput(time, pitch, int(velocity * random), voiceIdx, modulation); if (velocity != 0) mVelocity = velocity / 127.0f; } } void VelocitySetter::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void VelocitySetter::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/VelocitySetter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
503
```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.cpp // modularSynth // // Created by Ryan Challinor on 11/22/12. // // #include "SynthGlobals.h" #include "ModularSynth.h" #include "IAudioSource.h" #include "INoteSource.h" #include "IAudioReceiver.h" #include "GridController.h" #include "RollingBuffer.h" #include "TextEntry.h" #include "PatchCable.h" #include "PatchCableSource.h" #include "ChannelBuffer.h" #include "IPulseReceiver.h" #include "exprtk/exprtk.hpp" #include "UserPrefs.h" #include "juce_audio_formats/juce_audio_formats.h" #include "juce_gui_basics/juce_gui_basics.h" #ifdef JUCE_MAC #import <execinfo.h> #endif using namespace juce; int gBufferSize = -999; //values set in SetGlobalSampleRateAndBufferSize(), setting them to bad values here to highlight any bugs int gSampleRate = -999; double gTwoPiOverSampleRate = -999; double gSampleRateMs = -999; double gInvSampleRateMs = -999; double gBufferSizeMs = -999; double gNyquistLimit = -999; bool gPrintMidiInput = false; double gTime = 1; //using a double here, so I'm going to lose nanosecond accuracy //if I run for 4 months straight //this means I'll lose 44100 hz sample accuracy in 7100 years of //continuous uptime IUIControl* gBindToUIControl = nullptr; RetinaTrueTypeFont gFont; RetinaTrueTypeFont gFontBold; RetinaTrueTypeFont gFontFixedWidth; float gModuleDrawAlpha = 255; float gNullBuffer[kWorkBufferSize]; float gZeroBuffer[kWorkBufferSize]; float gWorkBuffer[kWorkBufferSize]; ChannelBuffer gWorkChannelBuffer(kWorkBufferSize); IDrawableModule* gHoveredModule = nullptr; IUIControl* gHoveredUIControl = nullptr; IUIControl* gHotBindUIControl[10]; float gControlTactileFeedback = 0; float gDrawScale = 1; bool gShowDevModules = false; float gCornerRoundness = 1; std::random_device gRandomDevice; bespoke::core::Xoshiro256ss gRandom(gRandomDevice); std::uniform_real_distribution<float> gRandom01(0.0f, 1.f); std::uniform_real_distribution<float> gRandomBipolarDist(-1.f, 1.f); void SynthInit() { std::locale::global(std::locale::classic()); Clear(gZeroBuffer, kWorkBufferSize); for (int i = 0; i < 10; ++i) gHotBindUIControl[i] = nullptr; TheSynth->GetAudioFormatManager().registerBasicFormats(); assert(kNumVoices <= 16); //assumption that we don't have more voices than midi channels } void LoadGlobalResources() { gFont.LoadFont(ofToResourcePath("frabk.ttf")); gFontBold.LoadFont(ofToResourcePath("frabk_m.ttf")); gFontFixedWidth.LoadFont(ofToResourcePath("iosevka-type-light.ttf")); //gModuleShader.load(ofToResourcePath("shaders/module.vert"), ofToResourcePath("shaders/module.frag")); } void SetGlobalSampleRateAndBufferSize(int rate, int size) { assert(size <= kWorkBufferSize); gBufferSize = size * UserPrefs.oversampling.Get(); gSampleRate = rate * UserPrefs.oversampling.Get(); gTwoPiOverSampleRate = TWO_PI / gSampleRate; gSampleRateMs = gSampleRate / 1000.0; gInvSampleRateMs = 1000.0 / gSampleRate; gBufferSizeMs = gBufferSize / gSampleRateMs; gNyquistLimit = gSampleRate / 2.0f; } std::string GetBuildInfoString() { return #if DEBUG "DEBUG BUILD " + #endif #if BESPOKE_NIGHTLY && !BESPOKE_SUPPRESS_NIGHTLY_LABEL "NIGHTLY " + #endif juce::JUCEApplication::getInstance()->getApplicationVersion().toStdString() + " (" + std::string(__DATE__) + " " + std::string(__TIME__) + ")"; } 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*/) { ofPushMatrix(); if (buffer != nullptr) { int numChannels = buffer->NumActiveChannels(); for (int i = 0; i < numChannels; ++i) { DrawAudioBuffer(width, height / numChannels, buffer->GetChannel(i), start, MIN(end, buffer->BufferSize()), pos, vol, color, wraparoundFrom, wraparoundTo, buffer->BufferSize()); ofTranslate(0, height / numChannels); } } ofPopMatrix(); } 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*/) { vol = MAX(.1f, vol); //make sure we at least draw something if there is waveform data ofPushStyle(); ofSetLineWidth(1); ofFill(); ofSetColor(255, 255, 255, 50); if (width > 0) ofRect(0, 0, width, height); else ofRect(width, 0, -width, height); float length = end - 1 - start; if (length < 0) length = length + wraparoundFrom - wraparoundTo; if (length < 0) length += bufferSize; if (length > 0) { const float kStepSize = 3; float samplesPerStep = length / abs(width) * kStepSize; start = start - (int(start) % MAX(1, int(samplesPerStep))); if (buffer && length > 0) { float step = width > 0 ? kStepSize : -kStepSize; samplesPerStep = length / width * step; ofSetColor(color); for (float i = 0; abs(i) < abs(width); i += step) { float mag = 0; int position = i / width * length + start; //rms int j; int inc = 1 + samplesPerStep / 100; for (j = 0; j < samplesPerStep; j += inc) { int sampleIdx = position + j; if (wraparoundFrom != -1 && sampleIdx > wraparoundFrom) sampleIdx = sampleIdx - wraparoundFrom + wraparoundTo; if (bufferSize > 0) sampleIdx %= bufferSize; mag = MAX(mag, fabsf(buffer[sampleIdx])); } mag = pow(mag, .25f); mag *= height / 2 * vol; if (mag > height / 2) { //ofSetColor(255,0,0); mag = height / 2; } else { //ofSetColor(color); } if (mag == 0) mag = .1f; ofLine(i, height / 2 - mag, i, height / 2 + mag); } if (pos != -1) { ofSetColor(0, 255, 0); int position = ofMap(pos, start, end, 0, width, true); ofLine(position, 0, position, height); } } } ofPopStyle(); } void Add(float* dst, const float* src, int bufferSize) { #ifdef USE_VECTOR_OPS FloatVectorOperations::add(dst, src, bufferSize); #else for (int i = 0; i < bufferSize; ++i) { dst[i] += src[i]; } #endif } void Subtract(float* dst, const float* src, int bufferSize) { #ifdef USE_VECTOR_OPS FloatVectorOperations::subtract(dst, src, bufferSize); #else for (int i = 0; i < bufferSize; ++i) { dst[i] -= src[i]; } #endif } void Mult(float* buff, float val, int bufferSize) { #ifdef USE_VECTOR_OPS FloatVectorOperations::multiply(buff, val, bufferSize); #else for (int i = 0; i < bufferSize; ++i) { buff[i] *= val; } #endif } void Mult(float* dst, const float* src, int bufferSize) { #ifdef USE_VECTOR_OPS FloatVectorOperations::multiply(dst, src, bufferSize); #else for (int i = 0; i < bufferSize; ++i) { dst[i] *= src[i]; } #endif } void Clear(float* buffer, int bufferSize) { #ifdef USE_VECTOR_OPS FloatVectorOperations::clear(buffer, bufferSize); #else bzero(buffer, bufferSize * sizeof(float)); #endif } void BufferCopy(float* dst, const float* src, int bufferSize) { #ifdef USE_VECTOR_OPS FloatVectorOperations::copy(dst, src, bufferSize); #else memcpy(dst, src, bufferSize * sizeof(float)); #endif } std::string NoteName(int pitch, bool flat, bool includeOctave) { int octave = pitch / 12; pitch %= 12; std::string ret = "x"; switch (pitch) { default: case 0: ret = "C"; break; case 1: //ret = "C#/Db"; ret = flat ? "Db" : "C#"; break; case 2: ret = "D"; break; case 3: //ret = "D#/Eb"; ret = flat ? "Eb" : "D#"; break; case 4: ret = "E"; break; case 5: ret = "F"; break; case 6: //ret = "F#/Gb"; ret = flat ? "Gb" : "F#"; break; case 7: ret = "G"; break; case 8: //ret = "G#/Ab"; ret = flat ? "Ab" : "G#"; break; case 9: ret = "A"; break; case 10: //ret = "A#/Bb"; ret = flat ? "Bb" : "A#"; break; case 11: ret = "B"; break; } if (includeOctave) ret += ofToString(octave - 2); return ret; } int PitchFromNoteName(std::string noteName) { int octave = -2; if (isdigit(noteName[noteName.length() - 1])) { octave = noteName[noteName.length() - 1] - '0'; if (noteName[noteName.length() - 2] == '-') octave *= -1; if (octave < 0) noteName = noteName.substr(0, noteName.length() - 2); else noteName = noteName.substr(0, noteName.length() - 1); } int pitch; for (pitch = 0; pitch < 12; ++pitch) { if (noteName == NoteName(pitch, false) || noteName == NoteName(pitch, true)) break; } if (pitch == 12) TheSynth->LogEvent("error finding pitch for note " + noteName, kLogEventType_Error); return pitch + (octave + 2) * 12; } float Interp(float a, float start, float end) { return a * (end - start) + start; } double GetPhaseInc(float freq) { return freq * gTwoPiOverSampleRate; } float FloatWrap(float num, float space) { if (space == 0) num = 0; num -= space * floor(num / space); return num; } double DoubleWrap(double num, float space) { if (space == 0) num = 0; num -= space * floor(num / space); return num; } void DrawTextNormal(std::string text, int x, int y, float size) { gFont.DrawString(text, size, x, y); } void DrawTextRightJustify(std::string text, int x, int y, float size) { gFont.DrawString(text, size, x - gFont.GetStringWidth(text, size), y); } void DrawTextBold(std::string text, int x, int y, float size) { gFontBold.DrawString(text, size, x, y); } float GetStringWidth(std::string text, float size) { return gFont.GetStringWidth(text, size); } void AssertIfDenormal(float input) { assert(input == 0 || input != input || fabsf(input) > std::numeric_limits<float>::min()); } float GetInterpolatedSample(double offset, const float* buffer, int bufferSize) { offset = DoubleWrap(offset, bufferSize); int pos = int(offset); int posNext = int(offset + 1) % bufferSize; float sample = buffer[pos]; float nextSample = buffer[posNext]; float a = offset - pos; float output = (1 - a) * sample + a * nextSample; //interpolate return output; } float GetInterpolatedSample(double offset, ChannelBuffer* buffer, int bufferSize, float channelBlend) { assert(channelBlend <= buffer->NumActiveChannels()); assert(channelBlend >= 0); if (buffer->NumActiveChannels() == 1) return GetInterpolatedSample(offset, buffer->GetChannel(0), bufferSize); int channelA = floor(channelBlend); if (channelA == buffer->NumActiveChannels() - 1) channelA -= 1; int channelB = channelA + 1; return (1 - (channelBlend - channelA)) * GetInterpolatedSample(offset, buffer->GetChannel(channelA), bufferSize) + (channelBlend - channelA) * GetInterpolatedSample(offset, buffer->GetChannel(channelB), bufferSize); } void WriteInterpolatedSample(double offset, float* buffer, int bufferSize, float sample) { offset = DoubleWrap(offset, bufferSize); int pos = int(offset); int posNext = int(offset + 1) % bufferSize; float a = offset - pos; buffer[pos] += (1 - a) * sample; buffer[posNext] += a * sample; } std::string GetRomanNumeralForDegree(int degree) { std::string roman; switch ((degree + 700) % 7) { default: case 0: roman = "I"; break; case 1: roman = "II"; break; case 2: roman = "III"; break; case 3: roman = "IV"; break; case 4: roman = "V"; break; case 5: roman = "VI"; break; case 6: roman = "VII"; break; } return roman; } void UpdateTarget(IDrawableModule* module) { IAudioSource* audioSource = dynamic_cast<IAudioSource*>(module); INoteSource* noteSource = dynamic_cast<INoteSource*>(module); IGridController* grid = dynamic_cast<IGridController*>(module); IPulseSource* pulseSource = dynamic_cast<IPulseSource*>(module); std::string targetName = ""; if (audioSource) { for (int i = 0; i < audioSource->GetNumTargets(); ++i) { IDrawableModule* target = dynamic_cast<IDrawableModule*>(audioSource->GetTarget(i)); if (target) targetName = target->Path(); else targetName = ""; module->GetSaveData().SetString("target" + (i == 0 ? "" : ofToString(i + 1)), targetName); } } if (noteSource || grid || pulseSource) { if (module->GetPatchCableSource()) { const std::vector<PatchCable*>& cables = module->GetPatchCableSource()->GetPatchCables(); for (int i = 0; i < cables.size(); ++i) { PatchCable* cable = cables[i]; IClickable* target = cable->GetTarget(); if (target) { targetName += target->Path(); if (i < cables.size() - 1) targetName += ","; } } } module->GetSaveData().SetString("target", targetName); } } void DrawLissajous(RollingBuffer* buffer, float x, float y, float w, float h, float r, float g, float b) { ofPushStyle(); ofSetLineWidth(1.5f); int secondChannel = 1; if (buffer->NumChannels() == 1) secondChannel = 0; ofSetColor(r * 255, g * 255, b * 255, 70); ofBeginShape(); const int delaySamps = 90; int numPoints = MIN(buffer->Size() - delaySamps - 1, .02f * gSampleRate); for (int i = 100; i < numPoints; ++i) { float vx = x + w / 2 + buffer->GetSample(i, 0) * .8f * MIN(w, h); float vy = y + h / 2 + buffer->GetSample(i + delaySamps, secondChannel) * .8f * MIN(w, h); //float alpha = 1 - (i/float(numPoints)); //ofSetColor(r*255,g*255,b*255,alpha*alpha*255); ofVertex(vx, vy); } ofEndShape(); ofPopStyle(); } void StringCopy(char* dest, const char* source, int destLength) { if (dest == source) return; strncpy(dest, source, destLength); dest[destLength - 1] = 0; } int GetKeyModifiers() { int ret = 0; if (ModifierKeys::currentModifiers.isShiftDown()) ret |= kModifier_Shift; if (ModifierKeys::currentModifiers.isAltDown()) ret |= kModifier_Alt; #if BESPOKE_MAC if (ModifierKeys::currentModifiers.isCtrlDown()) ret |= kModifier_Control; //control and command interfere with each other on non-mac keyboards #endif if (ModifierKeys::currentModifiers.isCommandDown()) ret |= kModifier_Command; return ret; } bool IsKeyHeld(int key, int modifiers) { return IKeyboardFocusListener::GetActiveKeyboardFocus() == nullptr && KeyPress::isKeyCurrentlyDown(key) && GetKeyModifiers() == modifiers && TheSynth->GetMainComponent()->hasKeyboardFocus(true); } int KeyToLower(int key) { if (key < CHAR_MAX && CharacterFunctions::isLetter((char)key)) return tolower(key); if (key == '!') return '1'; if (key == '@') return '2'; if (key == '#') return '3'; if (key == '$') return '4'; if (key == '%') return '5'; if (key == '^') return '6'; if (key == '&') return '7'; if (key == '*') return '8'; if (key == '(') return '9'; if (key == ')') return '0'; if (key == '~') return '`'; if (key == '_') return '-'; if (key == '+') return '='; if (key == '<') return ','; if (key == '>') return '.'; if (key == '?') return '/'; if (key == ':') return ';'; if (key == '"') return '\''; if (key == '{') return '['; if (key == '}') return ']'; if (key == '|') return '\\'; return key; } float EaseIn(float start, float end, float a) { return (end - start) * a * a + start; } float EaseOut(float start, float end, float a) { return -(end - start) * a * (a - 2) + start; } float Bias(float value, float bias) { assert(bias >= 0 && bias <= 1); const float kLog25 = log(25); bias = .2f * expf(kLog25 * bias); //pow(25,bias) return pow(value, bias); } float Pow2(float in) { const float kLog2 = log(2); return expf(kLog2 * in); } void PrintCallstack() { #ifdef JUCE_MAC void* callstack[128]; int frameCount = backtrace(callstack, 128); char** frameStrings = backtrace_symbols(callstack, frameCount); if (frameStrings != nullptr) { // Start with frame 1 because frame 0 is PrintBacktrace() for (int i = 1; i < frameCount; i++) { printf("%s\n", frameStrings[i]); } free(frameStrings); } #endif } bool IsInUnitBox(ofVec2f pos) { return pos.x >= 0 && pos.x < 1 && pos.y >= 0 && pos.y < 1; } std::string GetUniqueName(std::string name, std::vector<IDrawableModule*> existing) { std::string strippedName = name; while (strippedName.length() > 1 && CharacterFunctions::isDigit((char)strippedName[strippedName.length() - 1])) strippedName.resize(strippedName.length() - 1); int suffix = 1; std::string suffixString = name; ofStringReplace(suffixString, strippedName, ""); if (!suffixString.empty()) suffix = atoi(suffixString.c_str()); while (true) { bool isNameUnique = true; for (int i = 0; i < existing.size(); ++i) { if (existing[i]->Name() == name) { ++suffix; name = strippedName + ofToString(suffix); isNameUnique = false; break; } } if (isNameUnique) break; } return name; } std::string GetUniqueName(std::string name, std::vector<std::string> existing) { std::string origName = name; int suffix = 1; while (true) { bool isNameUnique = true; for (int i = 0; i < existing.size(); ++i) { if (existing[i] == name) { ++suffix; name = origName + ofToString(suffix); isNameUnique = false; break; } } if (isNameUnique) break; } return name; } float DistSqToLine(ofVec2f point, ofVec2f a, ofVec2f b) { float l2 = a.distanceSquared(b); if (l2 == 0.0f) return point.distanceSquared(a); float t = ((point.x - b.x) * (a.x - b.x) + (point.y - b.y) * (a.y - b.y)) / l2; if (t < 0.0f) return point.distanceSquared(a); if (t > 1.0f) return point.distanceSquared(b); return point.distanceSquared(ofVec2f(b.x + t * (a.x - b.x), b.y + t * (a.y - b.y))); } //Jenkins one-at-a-time hash uint32_t JenkinsHash(const char* key) { uint32_t hash, i; for (hash = i = 0; key[i] != 0; ++i) { hash += key[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; } void LoadStateValidate(bool assertion) { if (!assertion) throw LoadStateException(); } double NextBufferTime(bool includeLookahead) { double time = gTime + gBufferSizeMs; if (includeLookahead) time += TheTransport->GetEventLookaheadMs(); return time; } bool IsAudioThread() { return std::this_thread::get_id() == ModularSynth::GetAudioThreadID(); } float GetLeftPanGain(float pan) { return 1 - ofClamp(pan, -1, 1); } float GetRightPanGain(float pan) { return ofClamp(pan, -1, 1) + 1; } void DrawFallbackText(const char* text, float posX, float posY) { static int simplex[95][112] = { 0, 16, /* Ascii 32 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 10, /* Ascii 33 */ 5, 21, 5, 7, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 16, /* Ascii 34 */ 4, 21, 4, 14, -1, -1, 12, 21, 12, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 21, /* Ascii 35 */ 11, 25, 4, -7, -1, -1, 17, 25, 10, -7, -1, -1, 4, 12, 18, 12, -1, -1, 3, 6, 17, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 20, /* Ascii 36 */ 8, 25, 8, -4, -1, -1, 12, 25, 12, -4, -1, -1, 17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 31, 24, /* Ascii 37 */ 21, 21, 3, 0, -1, -1, 8, 21, 10, 19, 10, 17, 9, 15, 7, 14, 5, 14, 3, 16, 3, 18, 4, 20, 6, 21, 8, 21, 10, 20, 13, 19, 16, 19, 19, 20, 21, 21, -1, -1, 17, 7, 15, 6, 14, 4, 14, 2, 16, 0, 18, 0, 20, 1, 21, 3, 21, 5, 19, 7, 17, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 34, 26, /* Ascii 38 */ 23, 12, 23, 13, 22, 14, 21, 14, 20, 13, 19, 11, 17, 6, 15, 3, 13, 1, 11, 0, 7, 0, 5, 1, 4, 2, 3, 4, 3, 6, 4, 8, 5, 9, 12, 13, 13, 14, 14, 16, 14, 18, 13, 20, 11, 21, 9, 20, 8, 18, 8, 16, 9, 13, 11, 10, 16, 3, 18, 1, 20, 0, 22, 0, 23, 1, 23, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 10, /* Ascii 39 */ 5, 19, 4, 20, 5, 21, 6, 20, 6, 18, 5, 16, 4, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 14, /* Ascii 40 */ 11, 25, 9, 23, 7, 20, 5, 16, 4, 11, 4, 7, 5, 2, 7, -2, 9, -5, 11, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 14, /* Ascii 41 */ 3, 25, 5, 23, 7, 20, 9, 16, 10, 11, 10, 7, 9, 2, 7, -2, 5, -5, 3, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 16, /* Ascii 42 */ 8, 21, 8, 9, -1, -1, 3, 18, 13, 12, -1, -1, 13, 18, 3, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 26, /* Ascii 43 */ 13, 18, 13, 0, -1, -1, 4, 9, 22, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 10, /* Ascii 44 */ 6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 26, /* Ascii 45 */ 4, 9, 22, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 10, /* Ascii 46 */ 5, 2, 4, 1, 5, 0, 6, 1, 5, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 22, /* Ascii 47 */ 20, 25, 2, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 20, /* Ascii 48 */ 9, 21, 6, 20, 4, 17, 3, 12, 3, 9, 4, 4, 6, 1, 9, 0, 11, 0, 14, 1, 16, 4, 17, 9, 17, 12, 16, 17, 14, 20, 11, 21, 9, 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 20, /* Ascii 49 */ 6, 17, 8, 18, 11, 21, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 14, 20, /* Ascii 50 */ 4, 16, 4, 17, 5, 19, 6, 20, 8, 21, 12, 21, 14, 20, 15, 19, 16, 17, 16, 15, 15, 13, 13, 10, 3, 0, 17, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, 20, /* Ascii 51 */ 5, 21, 16, 21, 10, 13, 13, 13, 15, 12, 16, 11, 17, 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, 20, /* Ascii 52 */ 13, 21, 3, 7, 18, 7, -1, -1, 13, 21, 13, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 20, /* Ascii 53 */ 15, 21, 5, 21, 4, 12, 5, 13, 8, 14, 11, 14, 14, 13, 16, 11, 17, 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 23, 20, /* Ascii 54 */ 16, 18, 15, 20, 12, 21, 10, 21, 7, 20, 5, 17, 4, 12, 4, 7, 5, 3, 7, 1, 10, 0, 11, 0, 14, 1, 16, 3, 17, 6, 17, 7, 16, 10, 14, 12, 11, 13, 10, 13, 7, 12, 5, 10, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 20, /* Ascii 55 */ 17, 21, 7, 0, -1, -1, 3, 21, 17, 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 29, 20, /* Ascii 56 */ 8, 21, 5, 20, 4, 18, 4, 16, 5, 14, 7, 13, 11, 12, 14, 11, 16, 9, 17, 7, 17, 4, 16, 2, 15, 1, 12, 0, 8, 0, 5, 1, 4, 2, 3, 4, 3, 7, 4, 9, 6, 11, 9, 12, 13, 13, 15, 14, 16, 16, 16, 18, 15, 20, 12, 21, 8, 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 23, 20, /* Ascii 57 */ 16, 14, 15, 11, 13, 9, 10, 8, 9, 8, 6, 9, 4, 11, 3, 14, 3, 15, 4, 18, 6, 20, 9, 21, 10, 21, 13, 20, 15, 18, 16, 14, 16, 9, 15, 4, 13, 1, 10, 0, 8, 0, 5, 1, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 10, /* Ascii 58 */ 5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 14, 10, /* Ascii 59 */ 5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 24, /* Ascii 60 */ 20, 18, 4, 9, 20, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 26, /* Ascii 61 */ 4, 12, 22, 12, -1, -1, 4, 6, 22, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 24, /* Ascii 62 */ 4, 18, 20, 9, 4, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, 18, /* Ascii 63 */ 3, 16, 3, 17, 4, 19, 5, 20, 7, 21, 11, 21, 13, 20, 14, 19, 15, 17, 15, 15, 14, 13, 13, 12, 9, 10, 9, 7, -1, -1, 9, 2, 8, 1, 9, 0, 10, 1, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 55, 27, /* Ascii 64 */ 18, 13, 17, 15, 15, 16, 12, 16, 10, 15, 9, 14, 8, 11, 8, 8, 9, 6, 11, 5, 14, 5, 16, 6, 17, 8, -1, -1, 12, 16, 10, 14, 9, 11, 9, 8, 10, 6, 11, 5, -1, -1, 18, 16, 17, 8, 17, 6, 19, 5, 21, 5, 23, 7, 24, 10, 24, 12, 23, 15, 22, 17, 20, 19, 18, 20, 15, 21, 12, 21, 9, 20, 7, 19, 5, 17, 4, 15, 3, 12, 3, 9, 4, 6, 5, 4, 7, 2, 9, 1, 12, 0, 15, 0, 18, 1, 20, 2, 21, 3, -1, -1, 19, 16, 18, 8, 18, 6, 19, 5, 8, 18, /* Ascii 65 */ 9, 21, 1, 0, -1, -1, 9, 21, 17, 0, -1, -1, 4, 7, 14, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 23, 21, /* Ascii 66 */ 4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, 11, -1, -1, 4, 11, 13, 11, 16, 10, 17, 9, 18, 7, 18, 4, 17, 2, 16, 1, 13, 0, 4, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 18, 21, /* Ascii 67 */ 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, 21, /* Ascii 68 */ 4, 21, 4, 0, -1, -1, 4, 21, 11, 21, 14, 20, 16, 18, 17, 16, 18, 13, 18, 8, 17, 5, 16, 3, 14, 1, 11, 0, 4, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 19, /* Ascii 69 */ 4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11, -1, -1, 4, 0, 17, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 18, /* Ascii 70 */ 4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 22, 21, /* Ascii 71 */ 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 18, 8, -1, -1, 13, 8, 18, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 22, /* Ascii 72 */ 4, 21, 4, 0, -1, -1, 18, 21, 18, 0, -1, -1, 4, 11, 18, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 8, /* Ascii 73 */ 4, 21, 4, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 16, /* Ascii 74 */ 12, 21, 12, 5, 11, 2, 10, 1, 8, 0, 6, 0, 4, 1, 3, 2, 2, 5, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 21, /* Ascii 75 */ 4, 21, 4, 0, -1, -1, 18, 21, 4, 7, -1, -1, 9, 12, 18, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 17, /* Ascii 76 */ 4, 21, 4, 0, -1, -1, 4, 0, 16, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 24, /* Ascii 77 */ 4, 21, 4, 0, -1, -1, 4, 21, 12, 0, -1, -1, 20, 21, 12, 0, -1, -1, 20, 21, 20, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 22, /* Ascii 78 */ 4, 21, 4, 0, -1, -1, 4, 21, 18, 0, -1, -1, 18, 21, 18, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 21, 22, /* Ascii 79 */ 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 13, 21, /* Ascii 80 */ 4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 14, 17, 12, 16, 11, 13, 10, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 24, 22, /* Ascii 81 */ 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, -1, -1, 12, 4, 18, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 16, 21, /* Ascii 82 */ 4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, 11, 4, 11, -1, -1, 11, 11, 18, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, 20, /* Ascii 83 */ 17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 16, /* Ascii 84 */ 8, 21, 8, 0, -1, -1, 1, 21, 15, 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 22, /* Ascii 85 */ 4, 21, 4, 6, 5, 3, 7, 1, 10, 0, 12, 0, 15, 1, 17, 3, 18, 6, 18, 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 18, /* Ascii 86 */ 1, 21, 9, 0, -1, -1, 17, 21, 9, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 24, /* Ascii 87 */ 2, 21, 7, 0, -1, -1, 12, 21, 7, 0, -1, -1, 12, 21, 17, 0, -1, -1, 22, 21, 17, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 20, /* Ascii 88 */ 3, 21, 17, 0, -1, -1, 17, 21, 3, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, 18, /* Ascii 89 */ 1, 21, 9, 11, 9, 0, -1, -1, 17, 21, 9, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 20, /* Ascii 90 */ 17, 21, 3, 0, -1, -1, 3, 21, 17, 21, -1, -1, 3, 0, 17, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 14, /* Ascii 91 */ 4, 25, 4, -7, -1, -1, 5, 25, 5, -7, -1, -1, 4, 25, 11, 25, -1, -1, 4, -7, 11, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 14, /* Ascii 92 */ 0, 21, 14, -3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 14, /* Ascii 93 */ 9, 25, 9, -7, -1, -1, 10, 25, 10, -7, -1, -1, 3, 25, 10, 25, -1, -1, 3, -7, 10, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 16, /* Ascii 94 */ 6, 15, 8, 18, 10, 15, -1, -1, 3, 12, 8, 17, 13, 12, -1, -1, 8, 17, 8, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 16, /* Ascii 95 */ 0, -2, 16, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 10, /* Ascii 96 */ 6, 21, 5, 20, 4, 18, 4, 16, 5, 15, 6, 16, 5, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 19, /* Ascii 97 */ 15, 14, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 19, /* Ascii 98 */ 4, 21, 4, 0, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 14, 18, /* Ascii 99 */ 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 19, /* Ascii 100 */ 15, 21, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 18, /* Ascii 101 */ 3, 8, 15, 8, 15, 10, 14, 12, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 12, /* Ascii 102 */ 10, 21, 8, 21, 6, 20, 5, 17, 5, 0, -1, -1, 2, 14, 9, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 22, 19, /* Ascii 103 */ 15, 14, 15, -2, 14, -5, 13, -6, 11, -7, 8, -7, 6, -6, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 19, /* Ascii 104 */ 4, 21, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 8, /* Ascii 105 */ 3, 21, 4, 20, 5, 21, 4, 22, 3, 21, -1, -1, 4, 14, 4, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 10, /* Ascii 106 */ 5, 21, 6, 20, 7, 21, 6, 22, 5, 21, -1, -1, 6, 14, 6, -3, 5, -6, 3, -7, 1, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 17, /* Ascii 107 */ 4, 21, 4, 0, -1, -1, 14, 14, 4, 4, -1, -1, 8, 8, 15, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 8, /* Ascii 108 */ 4, 21, 4, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 18, 30, /* Ascii 109 */ 4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0, -1, -1, 15, 10, 18, 13, 20, 14, 23, 14, 25, 13, 26, 10, 26, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 19, /* Ascii 110 */ 4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 19, /* Ascii 111 */ 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, 16, 6, 16, 8, 15, 11, 13, 13, 11, 14, 8, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 19, /* Ascii 112 */ 4, 14, 4, -7, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 19, /* Ascii 113 */ 15, 14, 15, -7, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 13, /* Ascii 114 */ 4, 14, 4, 0, -1, -1, 4, 8, 5, 11, 7, 13, 9, 14, 12, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 17, /* Ascii 115 */ 14, 11, 13, 13, 10, 14, 7, 14, 4, 13, 3, 11, 4, 9, 6, 8, 11, 7, 13, 6, 14, 4, 14, 3, 13, 1, 10, 0, 7, 0, 4, 1, 3, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 12, /* Ascii 116 */ 5, 21, 5, 4, 6, 1, 8, 0, 10, 0, -1, -1, 2, 14, 9, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 19, /* Ascii 117 */ 4, 14, 4, 4, 5, 1, 7, 0, 10, 0, 12, 1, 15, 4, -1, -1, 15, 14, 15, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 16, /* Ascii 118 */ 2, 14, 8, 0, -1, -1, 14, 14, 8, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 22, /* Ascii 119 */ 3, 14, 7, 0, -1, -1, 11, 14, 7, 0, -1, -1, 11, 14, 15, 0, -1, -1, 19, 14, 15, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 17, /* Ascii 120 */ 3, 14, 14, 0, -1, -1, 14, 14, 3, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 16, /* Ascii 121 */ 2, 14, 8, 0, -1, -1, 14, 14, 8, 0, 6, -4, 4, -6, 2, -7, 1, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 17, /* Ascii 122 */ 14, 14, 3, 0, -1, -1, 3, 14, 14, 14, -1, -1, 3, 0, 14, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 39, 14, /* Ascii 123 */ 9, 25, 7, 24, 6, 23, 5, 21, 5, 19, 6, 17, 7, 16, 8, 14, 8, 12, 6, 10, -1, -1, 7, 24, 6, 22, 6, 20, 7, 18, 8, 17, 9, 15, 9, 13, 8, 11, 4, 9, 8, 7, 9, 5, 9, 3, 8, 1, 7, 0, 6, -2, 6, -4, 7, -6, -1, -1, 6, 8, 8, 6, 8, 4, 7, 2, 6, 1, 5, -1, 5, -3, 6, -5, 7, -6, 9, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 8, /* Ascii 124 */ 4, 25, 4, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 39, 14, /* Ascii 125 */ 5, 25, 7, 24, 8, 23, 9, 21, 9, 19, 8, 17, 7, 16, 6, 14, 6, 12, 8, 10, -1, -1, 7, 24, 8, 22, 8, 20, 7, 18, 6, 17, 5, 15, 5, 13, 6, 11, 10, 9, 6, 7, 5, 5, 5, 3, 6, 1, 7, 0, 8, -2, 8, -4, 7, -6, -1, -1, 8, 8, 6, 6, 6, 4, 7, 2, 8, 1, 9, -1, 9, -3, 8, -5, 7, -6, 5, -7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 23, 24, /* Ascii 126 */ 3, 6, 3, 8, 4, 11, 6, 12, 8, 12, 10, 11, 14, 8, 16, 7, 18, 7, 20, 8, 21, 10, -1, -1, 3, 8, 4, 10, 6, 11, 8, 11, 10, 10, 14, 7, 16, 6, 18, 6, 20, 7, 21, 10, 21, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; float scale = .5f; ofVec2f pen; pen.set(posX, posY); for (const auto* c = text; *c; ++c) { const auto ch = *c; if (ch == '\n') { pen.set(posX, pen.y + scale * 60); continue; } const auto* it = simplex[ch - 32]; const auto nvtcs = *it++; const auto spacing = *it++; auto from = ofVec2f(-1, -1); for (size_t i = 0; i < nvtcs; ++i) { const auto x = *it++; const auto y = *it++; const auto to = ofVec2f(x, y); if ((from.x != -1 || from.y != -1) && (to.x != -1 || to.y != -1)) ofLine(pen.x + from.x * scale, pen.y - from.y * scale, pen.x + to.x * scale, pen.y - to.y * scale); from = to; } pen += ofVec2f(spacing * scale, 0); } } bool EvaluateExpression(std::string expressionStr, float currentValue, float& output) { exprtk::symbol_table<float> symbolTable; exprtk::expression<float> expression; symbolTable.add_variable("current_value", currentValue); symbolTable.add_constants(); expression.register_symbol_table(symbolTable); juce::String input = expressionStr; if (input.startsWith("+=")) input = input.replace("+=", "current_value+"); if (input.startsWith("*=")) input = input.replace("*=", "current_value*"); if (input.startsWith("/=")) input = input.replace("/=", "current_value/"); if (input.startsWith("-=")) input = input.replace("-=", "current_value-"); exprtk::parser<float> parser; bool expressionValid = parser.compile(input.toStdString(), expression); if (expressionValid) { output = expression.value(); return true; } return false; } ofLog::~ofLog() { std::string output = ofToString(gTime / 1000, 8) + ": " + mMessage; DBG(output); if (mSendToBespokeConsole) TheSynth->LogEvent(output, kLogEventType_Verbose); } #ifdef BESPOKE_DEBUG_ALLOCATIONS FILE* logAllocationsFile; namespace { const int maxFilenameLen = 90; typedef struct { uint32 address; uint32 size; char file[maxFilenameLen]; uint32 line; bool allocated; } AllocInfo; bool enableTracking = false; template <class T> class my_allocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; my_allocator() {} my_allocator(const my_allocator&) {} pointer allocate(size_type n, const void* = 0) { T* t = (T*)malloc(n * sizeof(T)); return t; } void deallocate(void* p, size_type) { if (p) free(p); } pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } my_allocator<T>& operator=(const my_allocator&) { return *this; } #undef new void construct(pointer p, const T& val) { new ((T*)p) T(val); } #define new DEBUG_NEW void destroy(pointer p) { p->~T(); } size_type max_size() const { return size_t(-1); } template <class U> struct rebind { typedef my_allocator<U> other; }; template <class U> my_allocator(const my_allocator<U>&) {} template <class U> my_allocator& operator=(const my_allocator<U>&) { return *this; } }; map<uint32, AllocInfo*, less<int>, my_allocator<pair<uint32, AllocInfo*> > > allocList; void AddTrack(uint32 addr, uint32 asize, const char* fname, uint32 lnum) { if (enableTracking) { fprintf(logAllocationsFile, "%-90s: LINE %5d, ADDRESS %08x %8d newed\n", fname, lnum, addr, asize); /*AllocInfo* info = (AllocInfo*)malloc(sizeof(AllocInfo)); info->address = addr; strncpy(info->file, fname, maxFilenameLen-1); info->file[maxFilenameLen-1] = 0; info->line = lnum; info->size = asize; info->allocated = true; allocList[addr] = info;*/ } }; void RemoveTrack(uint32 addr) { if (enableTracking) { //fprintf(logAllocationsFile, "ADDRESS %08x deleted\n", addr); /*auto info = allocList.find(addr); if (info == allocList.end()) { //assert(false); //Trying to free a never allocated address! ofLog() << "Trying to free a never allocated address!"; } else { if (info->second->allocated == false) assert(false); //Trying to free an already freed address! else info->second->allocated = false; }*/ } }; } void SetMemoryTrackingEnabled(bool enabled) { if (enabled && logAllocationsFile == nullptr) { logAllocationsFile = fopen(ofToDataPath("allocationslog.txt").c_str(), "w"); } enableTracking = enabled; } void DumpUnfreedMemory() { uint32 totalSize = 0; char buf[1024]; map<string, int> perFileTotal; for (auto element : allocList) { const AllocInfo* info = element.second; if (info && info->allocated) { snprintf(buf, sizeof(buf), "%-90s: LINE %5d, ADDRESS %08x %8d unfreed", info->file, info->line, info->address, info->size); ofLog() << buf; totalSize += info->size; perFileTotal[info->file] += info->size; } } ofLog() << "-----------------------------------------------------------"; for (auto fileInfo : perFileTotal) { snprintf(buf, sizeof(buf), "%-90s: %10d unfreed", fileInfo.first.c_str(), fileInfo.second); ofLog() << buf; } ofLog() << "-----------------------------------------------------------"; snprintf(buf, sizeof(buf), "Total Unfreed: %d bytes", totalSize); ofLog() << buf; }; #undef new void* operator new(std::size_t size) throw(std::bad_alloc) { void* ptr = (void*)malloc(size); //AddTrack((uint32)ptr, size, "<unknown>", 0); return (ptr); } void* operator new(std::size_t size, const char* file, int line) throw(std::bad_alloc) { void* ptr = (void*)malloc(size); AddTrack((uint32)ptr, size, file, line); return (ptr); } void operator delete(void* p) throw() { //RemoveTrack((uint32)p); free(p); } void* operator new[](std::size_t size) throw(std::bad_alloc) { void* ptr = (void*)malloc(size); //AddTrack((uint32)ptr, size, "<unknown>", 0); return (ptr); } void* operator new[](std::size_t size, const char* file, int line) throw(std::bad_alloc) { void* ptr = (void*)malloc(size); AddTrack((uint32)ptr, size, file, line); return (ptr); } void operator delete[](void* p) throw() { //RemoveTrack((uint32)p); free(p); } #define new DEBUG_NEW #else void SetMemoryTrackingEnabled(bool enabled) { } void DumpUnfreedMemory() { ofLog() << "This only works with BESPOKE_DEBUG_ALLOCATIONS defined"; }; #endif ```
/content/code_sandbox/Source/SynthGlobals.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
50,694
```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 **/ // // TriggerDetector.h // modularSynth // // Created by Ryan Challinor on 3/22/14. // // #pragma once #include "RollingBuffer.h" class TriggerDetector { public: TriggerDetector(); void Process(float sample); float GetValue(); bool CheckTriggered(); void SetThreshold(float thresh) { mThreshold = thresh; } void Draw(int x, int y); float mSharpness{ 0 }; private: float mThreshold{ .2 }; bool mTriggered{ false }; bool mWaitingForFall{ false }; RollingBuffer mHistory; float mAvg{ 0 }; }; ```
/content/code_sandbox/Source/TriggerDetector.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
237
```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 "INoteReceiver.h" #include "IPatchable.h" class IDrawableModule; class INoteSource; //intercepts notes to keep track of them for visualization class NoteOutput : public INoteReceiver { public: explicit NoteOutput(INoteSource* source) : mNoteSource(source) {} void Flush(double time); //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void SendPressure(int pitch, int pressure) override; void SendCC(int control, int value, int voiceIdx = -1) override; void SendMidi(const juce::MidiMessage& message) override; void PlayNoteInternal(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation, bool isFromMainThreadAndScheduled); void ResetStackDepth() { mStackDepth = 0; } bool* GetNotes() { return mNotes; } bool HasHeldNotes(); std::list<int> GetHeldNotesList(); private: bool mNotes[128]{}; double mNoteOnTimes[128]{}; INoteSource* mNoteSource{ nullptr }; int mStackDepth{ 0 }; }; class INoteSource : public virtual IPatchable { public: INoteSource() : mNoteOutput(this) {} virtual ~INoteSource() {} void PlayNoteOutput(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters(), bool isFromMainThreadAndScheduled = false); void SendCCOutput(int control, int value, int voiceIdx = -1); //IPatchable void PreRepatch(PatchCableSource* cableSource) override; protected: NoteOutput mNoteOutput; bool mInNoteOutput{ false }; }; class AdditionalNoteCable : public INoteSource { public: void SetPatchCableSource(PatchCableSource* cable) { mCable = cable; } PatchCableSource* GetPatchCableSource(int index = 0) override { return mCable; } void Flush(double time) { mNoteOutput.Flush(time); } private: PatchCableSource* mCable{ nullptr }; }; ```
/content/code_sandbox/Source/INoteSource.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
631
```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 **/ // // Monophonify.cpp // modularSynth // // Created by Ryan Challinor on 12/12/12. // // #include "Monophonify.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" #include "UIControlMacros.h" Monophonify::Monophonify() { for (int i = 0; i < 128; ++i) mHeldNotes[i] = -1; } void Monophonify::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); DROPDOWN(mPortamentoModeSelector, "mode", ((int*)&mPortamentoMode), 90); FLOATSLIDER(mGlideSlider, "glide", &mGlideTime, 0, 1000); ENDUIBLOCK(mWidth, mHeight); mPortamentoModeSelector->AddLabel("always", (int)PortamentoMode::kAlways); mPortamentoModeSelector->AddLabel("retrigger held", (int)PortamentoMode::kRetriggerHeld); mPortamentoModeSelector->AddLabel("bend held", (int)PortamentoMode::kBendHeld); mGlideSlider->SetMode(FloatSlider::kSquare); } void Monophonify::DrawModule() { if (Minimized() || IsVisible() == false) return; mPortamentoModeSelector->Draw(); mGlideSlider->Draw(); } void Monophonify::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) return; mPitchBend.AppendTo(modulation.pitchBend); modulation.pitchBend = &mPitchBend; voiceIdx = mVoiceIdx; if (velocity > 0) { mLastVelocity = velocity; int currentlyHeldPitch = GetMostRecentCurrentlyHeldPitch(); if (currentlyHeldPitch != -1) { if (mPortamentoMode == PortamentoMode::kBendHeld) { //just bend to the new note mPitchBend.RampValue(time, mPitchBend.GetIndividualValue(0), pitch - mInitialPitch, mGlideTime); } else { //trigger new note and bend mPitchBend.RampValue(time, currentlyHeldPitch - pitch + mPitchBend.GetIndividualValue(0), 0, mGlideTime); PlayNoteOutput(time, currentlyHeldPitch, 0, -1, modulation); PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } } else { if (mPortamentoMode == PortamentoMode::kAlways && mLastPlayedPitch != -1) { //bend to new note mPitchBend.RampValue(time, mLastPlayedPitch - pitch + mPitchBend.GetIndividualValue(0), 0, mGlideTime); } else { //reset pitch bend mPitchBend.RampValue(time, 0, 0, 0); } mInitialPitch = pitch; PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } mLastPlayedPitch = pitch; mHeldNotes[pitch] = time; } else { bool wasCurrNote = (pitch == GetMostRecentCurrentlyHeldPitch()); mHeldNotes[pitch] = -1; if (wasCurrNote) { int returnToPitch = GetMostRecentCurrentlyHeldPitch(); if (returnToPitch != -1) { if (mPortamentoMode == PortamentoMode::kBendHeld) { //bend back to old note mPitchBend.RampValue(time, mPitchBend.GetIndividualValue(0), returnToPitch - mInitialPitch, mGlideTime); } else { //bend back to old note and retrigger mPitchBend.RampValue(time, pitch - returnToPitch + mPitchBend.GetIndividualValue(0), 0, mGlideTime); PlayNoteOutput(time, returnToPitch, mLastVelocity, voiceIdx, modulation); } } else { if (mPortamentoMode == PortamentoMode::kBendHeld) { //stop pitch that we started with PlayNoteOutput(time, mInitialPitch, 0, voiceIdx, modulation); } else { //stop released pitch PlayNoteOutput(time, pitch, 0, voiceIdx, modulation); } } } } } int Monophonify::GetMostRecentCurrentlyHeldPitch() const { int mostRecentPitch = -1; double mostRecentTime = 0; for (int i = 0; i < 128; ++i) { if (mHeldNotes[i] > mostRecentTime) { mostRecentPitch = i; mostRecentTime = mHeldNotes[i]; } } return mostRecentPitch; } void Monophonify::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { mNoteOutput.Flush(time); for (int i = 0; i < 128; ++i) mHeldNotes[i] = -1; } } void Monophonify::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void Monophonify::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadInt("voice_idx", moduleInfo, 0, 0, kNumVoices - 1); SetUpFromSaveData(); } void Monophonify::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); mVoiceIdx = mModuleSaveData.GetInt("voice_idx"); } ```
/content/code_sandbox/Source/Monophonify.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,445
```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 **/ // // NoteSustain.cpp // Bespoke // // Created by Ryan Challinor on 6/19/15. // // #include "NoteSustain.h" #include "SynthGlobals.h" NoteSustain::NoteSustain() { } void NoteSustain::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void NoteSustain::CreateUIControls() { IDrawableModule::CreateUIControls(); mSustainSlider = new FloatSlider(this, "duration", 5, 2, 100, 15, &mSustain, 0.01f, 4, 4); mSustainSlider->SetMode(FloatSlider::kSquare); } NoteSustain::~NoteSustain() { TheTransport->RemoveAudioPoller(this); } void NoteSustain::DrawModule() { if (Minimized() || IsVisible() == false) return; mSustainSlider->Draw(); } void NoteSustain::OnTransportAdvanced(float amount) { for (auto iter = mNoteOffs.begin(); iter != mNoteOffs.end();) { if (iter->mTime < gTime) { PlayNoteOutput(gTime, iter->mPitch, 0, iter->mVoiceIdx); iter = mNoteOffs.erase(iter); } else { ++iter; } } } void NoteSustain::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } if (velocity > 0) PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); if (velocity > 0) { ComputeSliders(0); float durationMs = mSustain / (float(TheTransport->GetTimeSigTop()) / TheTransport->GetTimeSigBottom()) * TheTransport->MsPerBar(); bool found = false; for (auto& queued : mNoteOffs) { if (queued.mPitch == pitch) { queued.mTime = time + durationMs; queued.mVoiceIdx = voiceIdx; found = true; break; } } if (!found) mNoteOffs.push_back(QueuedNoteOff(time + durationMs, pitch, voiceIdx)); } } void NoteSustain::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void NoteSustain::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void NoteSustain::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/NoteSustain.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
710
```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 **/ // // LinkwitzRileyFilter.cpp // Bespoke // // Created by Ryan Challinor on 4/30/14. // // #include "LinkwitzRileyFilter.h" ```
/content/code_sandbox/Source/LinkwitzRileyFilter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
139
```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 **/ /* ============================================================================== SamplePlayer.h Created: 19 Oct 2017 10:10:15pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IAudioProcessor.h" #include "EnvOscillator.h" #include "INoteReceiver.h" #include "IDrawableModule.h" #include "Checkbox.h" #include "Slider.h" #include "DropdownList.h" #include "ClickButton.h" #include "TextEntry.h" #include "RadioButton.h" #include "GateEffect.h" #include "IPulseReceiver.h" #include "SwitchAndRamp.h" #include "juce_osc/juce_osc.h" class Sample; class SamplePlayer : public IAudioProcessor, public IDrawableModule, public INoteReceiver, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public IButtonListener, public IRadioButtonListener, public ITextEntryListener, public IPulseReceiver, private juce::OSCReceiver, private juce::OSCReceiver::Listener<juce::OSCReceiver::RealtimeCallback> { public: SamplePlayer(); ~SamplePlayer(); static IDrawableModule* Create() { return new SamplePlayer(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; void Init() override; void Poll() override; 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 {} void OnPulse(double time, float velocity, int flags) override; //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } 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 IsResizable() const override { return true; } void Resize(float width, float height) override { mWidth = ofClamp(width, 210, 9999); mHeight = ofClamp(height, 125, 9999); } void SetCuePoint(int pitch, float startSeconds, float lengthSeconds, float speed); void FillData(std::vector<float> data); ChannelBuffer* GetCueSampleData(int cueIndex); float GetLengthInSeconds() const; void oscMessageReceived(const juce::OSCMessage& msg) override; void oscBundleReceived(const juce::OSCBundle& bundle) 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 TextEntryComplete(TextEntry* entry) override; void RadioButtonUpdated(RadioButton* radio, int oldVal, 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; } std::vector<IUIControl*> ControlsToIgnoreInSaveState() const override; bool IsEnabled() const override { return mEnabled; } private: void UpdateSample(Sample* sample, bool ownsSample); float GetPlayPositionForMouse(float mouseX) const; float GetSecondsForMouse(float mouseX) const; void GetPlayInfoForPitch(int pitch, float& startSeconds, float& lengthSeconds, float& speed, bool& stopOnNoteOff) const; void DownloadYoutube(std::string url, std::string titles); void SearchYoutube(std::string searchTerm); void LoadFile(); void SaveFile(); void OnYoutubeSearchComplete(std::string searchTerm, double searchStartTime); void OnYoutubeDownloadComplete(std::string filename, std::string title); void SetCuePointForX(float mouseX); int GetZoomStartSample() const; int GetZoomEndSample() const; float GetZoomStartSeconds() const; float GetZoomEndSeconds() const; void UpdateActiveCuePoint(); void PlayCuePoint(double time, int index, int velocity, float speedMult, float startOffsetSeconds); void RunProcess(const juce::StringArray& args); void AutoSlice(int slices); void StopRecording(); //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; bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override; float mWidth{ 608 }; float mHeight{ 150 }; Sample* mSample{ nullptr }; bool mOwnsSample{ true }; float mVolume{ 1 }; FloatSlider* mVolumeSlider{ nullptr }; float mSpeed{ 1 }; float mPlaySpeed{ 1 }; float mCuePointSpeed{ 1 }; FloatSlider* mSpeedSlider{ nullptr }; ClickButton* mPlayButton{ nullptr }; ClickButton* mPauseButton{ nullptr }; ClickButton* mStopButton{ nullptr }; bool mPlay{ false }; bool mLoop{ false }; bool mRecord{ false }; Checkbox* mLoopCheckbox{ nullptr }; Checkbox* mRecordCheckbox{ nullptr }; bool mScrubbingSample{ false }; std::string mYoutubeId; ClickButton* mDownloadYoutubeButton{ nullptr }; TextEntry* mDownloadYoutubeSearch{ nullptr }; char mYoutubeSearch[MAX_TEXTENTRY_LENGTH]{}; ClickButton* mLoadFileButton{ nullptr }; ClickButton* mSaveFileButton{ nullptr }; bool mIsLoadingSample{ false }; float mZoomLevel{ 1 }; float mZoomOffset{ 0 }; ClickButton* mTrimToZoomButton{ nullptr }; bool mOscWheelGrabbed{ false }; float mOscWheelPos{ 0 }; float mOscWheelSpeed{ 0 }; ChannelBuffer mDrawBuffer{ 0 }; NoteInputBuffer mNoteInputBuffer; ::ADSR mAdsr{ 10, 1, 1, 10 }; struct SampleCuePoint { float startSeconds{ 0 }; float lengthSeconds{ 0 }; float speed{ 1 }; bool stopOnNoteOff{ false }; }; std::vector<SampleCuePoint> mSampleCuePoints{ 128 }; DropdownList* mCuePointSelector{ nullptr }; FloatSlider* mCuePointStartSlider{ nullptr }; FloatSlider* mCuePointLengthSlider{ nullptr }; FloatSlider* mCuePointSpeedSlider{ nullptr }; Checkbox* mCuePointStopCheckbox{ nullptr }; int mActiveCuePointIndex{ 0 }; int mHoveredCuePointIndex{ -1 }; bool mSetCuePoint{ false }; Checkbox* mSetCuePointCheckbox{ nullptr }; bool mSelectPlayedCuePoint{ false }; Checkbox* mSelectPlayedCuePointCheckbox{ nullptr }; int mRecentPlayedCuePoint{ -1 }; ClickButton* mPlayCurrentCuePointButton{ nullptr }; bool mShowGrid{ false }; Checkbox* mShowGridCheckbox{ nullptr }; ClickButton* mAutoSlice4{ nullptr }; ClickButton* mAutoSlice8{ nullptr }; ClickButton* mAutoSlice16{ nullptr }; ClickButton* mAutoSlice32{ nullptr }; ClickButton* mPlayHoveredClipButton{ nullptr }; ClickButton* mGrabHoveredClipButton{ nullptr }; std::string mErrorString; #define kMaxYoutubeSearchResults 10 enum class RunningProcessType { None, SearchYoutube, DownloadYoutube }; struct YoutubeSearchResult { std::string name; std::string channel; float lengthSeconds{ 0 }; std::string youtubeId; }; RunningProcessType mRunningProcessType{ RunningProcessType::None }; juce::ChildProcess* mRunningProcess{ nullptr }; std::function<void()> mOnRunningProcessComplete; std::vector<YoutubeSearchResult> mYoutubeSearchResults; std::array<ClickButton*, kMaxYoutubeSearchResults> mSearchResultButtons{}; SwitchAndRamp mSwitchAndRamp; std::vector<ChannelBuffer*> mRecordChunks; bool mDoRecording{ false }; //separate this out from mRecord to allow setup in main thread before audio thread starts recording int mRecordingLength{ 0 }; bool mRecordingAppendMode{ false }; Checkbox* mRecordingAppendModeCheckbox{ nullptr }; bool mRecordAsClips{ false }; Checkbox* mRecordAsClipsCheckbox{ nullptr }; GateEffect mRecordGate; int mRecordAsClipsCueIndex{ 0 }; bool mStopOnNoteOff{ false }; }; ```
/content/code_sandbox/Source/SamplePlayer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,209
```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 **/ // // ButterworthFilterEffect.cpp // Bespoke // // Created by Ryan Challinor on 5/19/16. // // #include "ButterworthFilterEffect.h" #include "SynthGlobals.h" #include "FloatSliderLFOControl.h" #include "Profiler.h" #include "UIControlMacros.h" ButterworthFilterEffect::ButterworthFilterEffect() : mDryBuffer(gBufferSize) { } void ButterworthFilterEffect::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mFSlider, "F", &mF, 10, 4000); FLOATSLIDER_DIGITS(mQSlider, "Q", &mQ, 0, 1, 3); ENDUIBLOCK(mWidth, mHeight); mFSlider->SetMaxValueDisplay("inf"); mFSlider->SetMode(FloatSlider::kSquare); } ButterworthFilterEffect::~ButterworthFilterEffect() { } void ButterworthFilterEffect::Init() { IDrawableModule::Init(); } void ButterworthFilterEffect::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(ButterworthFilterEffect); if (!mEnabled) return; float bufferSize = buffer->BufferSize(); mDryBuffer.SetNumActiveChannels(buffer->NumActiveChannels()); const float fadeOutStart = mFSlider->GetMax() * .75f; const float fadeOutEnd = mFSlider->GetMax(); bool fadeOut = mF > fadeOutStart; if (fadeOut) mDryBuffer.CopyFrom(buffer); for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); if (mCoefficientsHaveChanged) { mButterworth[0].Set(mF, mQ); for (int ch = 1; ch < buffer->NumActiveChannels(); ++ch) mButterworth[ch].CopyCoeffFrom(mButterworth[0]); mCoefficientsHaveChanged = false; } for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) buffer->GetChannel(ch)[i] = mButterworth[ch].Run(buffer->GetChannel(ch)[i]); } if (fadeOut) { for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) { float dryness = ofMap(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 ButterworthFilterEffect::DrawModule() { mFSlider->Draw(); mQSlider->Draw(); } float ButterworthFilterEffect::GetEffectAmount() { if (!mEnabled) return 0; return ofClamp(1 - (mF / (mFSlider->GetMax() * .75f)), 0, 1); } void ButterworthFilterEffect::ResetFilter() { for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) mButterworth[i].Clear(); } void ButterworthFilterEffect::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void ButterworthFilterEffect::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { ResetFilter(); } } void ButterworthFilterEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mFSlider || slider == mQSlider) mCoefficientsHaveChanged = true; } void ButterworthFilterEffect::LoadLayout(const ofxJSONElement& info) { mModuleSaveData.LoadFloat("f_min", info, 10, 1, 40000, K(isTextField)); mModuleSaveData.LoadFloat("f_max", info, 10000, 1, 40000, K(isTextField)); } void ButterworthFilterEffect::SetUpFromSaveData() { mFSlider->SetExtents(mModuleSaveData.GetFloat("f_min"), mModuleSaveData.GetFloat("f_max")); ResetFilter(); } void ButterworthFilterEffect::SaveLayout(ofxJSONElement& info) { mModuleSaveData.Save(info); } ```
/content/code_sandbox/Source/ButterworthFilterEffect.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,064
```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 **/ // // Transport.cpp // modularSynth // // Created by Ryan Challinor on 12/2/12. // // #include "Transport.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "ChaosEngine.h" Transport* TheTransport = nullptr; //statics bool Transport::sDoEventLookahead = false; double Transport::sEventEarlyMs = 150; Transport::Transport() { assert(TheTransport == nullptr); TheTransport = this; SetName("transport"); SetRandomTempo(); } void Transport::SetRandomTempo() { SetTempo(gRandom() % 80 + 75); } void Transport::CreateUIControls() { IDrawableModule::CreateUIControls(); mTempoSlider = new FloatSlider(this, "tempo", 5, 4, 93, 15, &mTempo, 20, 225); mIncreaseTempoButton = new ClickButton(this, " + ", 118, 4); mDecreaseTempoButton = new ClickButton(this, " - ", 101, 4); mSwingSlider = new FloatSlider(this, "swing", 5, 22, 93, 15, &mSwing, .5f, .7f); mSwingIntervalDropdown = new DropdownList(this, "swing interval", 101, 22, &mSwingInterval); mTimeSigTopDropdown = new DropdownList(this, "timesigtop", 101, 42, &mTimeSigTop); mTimeSigBottomDropdown = new DropdownList(this, "timesigbottom", 101, 60, &mTimeSigBottom); mResetButton = new ClickButton(this, "reset", 5, 78); mPlayPauseButton = new ClickButton(this, "play/pause", 42, 78, ButtonDisplayStyle::kPause); mNudgeBackButton = new ClickButton(this, " < ", 80, 78); mNudgeForwardButton = new ClickButton(this, " > ", 110, 78); mSetTempoCheckbox = new Checkbox(this, "set tempo", HIDDEN_UICONTROL, HIDDEN_UICONTROL, &mSetTempoBool); mTimeSigTopDropdown->AddLabel("2", 2); mTimeSigTopDropdown->AddLabel("3", 3); mTimeSigTopDropdown->AddLabel("4", 4); mTimeSigTopDropdown->AddLabel("5", 5); mTimeSigTopDropdown->AddLabel("6", 6); mTimeSigTopDropdown->AddLabel("7", 7); mTimeSigTopDropdown->AddLabel("8", 8); mTimeSigTopDropdown->AddLabel("9", 9); mTimeSigTopDropdown->AddLabel("10", 10); mTimeSigTopDropdown->AddLabel("11", 11); mTimeSigTopDropdown->AddLabel("12", 12); mTimeSigTopDropdown->AddLabel("13", 13); mTimeSigTopDropdown->AddLabel("14", 14); mTimeSigTopDropdown->AddLabel("15", 15); mTimeSigTopDropdown->AddLabel("16", 16); mTimeSigTopDropdown->AddLabel("17", 17); mTimeSigTopDropdown->AddLabel("18", 18); mTimeSigTopDropdown->AddLabel("19", 19); mTimeSigBottomDropdown->AddLabel("2", 2); mTimeSigBottomDropdown->AddLabel("4", 4); mTimeSigBottomDropdown->AddLabel("8", 8); mTimeSigBottomDropdown->AddLabel("16", 16); mSwingIntervalDropdown->AddLabel("4n", 4); mSwingIntervalDropdown->AddLabel("8n", 8); mSwingIntervalDropdown->AddLabel("16n", 16); } void Transport::Init() { IDrawableModule::Init(); } void Transport::Poll() { if (mWantSetRandomTempo) { SetRandomTempo(); mWantSetRandomTempo = false; } } void Transport::KeyPressed(int key, bool isRepeat) { IDrawableModule::KeyPressed(key, isRepeat); } void Transport::Advance(double ms) { if (mNudgeFactor != 0) { const float kNudgePower = .05f; float nudgeScale = (1 + mNudgeFactor * kNudgePower); const float kRamp = .005f; if (mNudgeFactor > 0) mNudgeFactor = MAX(0, mNudgeFactor - ms * kRamp); if (mNudgeFactor < 0) mNudgeFactor = MIN(0, mNudgeFactor + ms * kRamp); ms *= nudgeScale; } double amount = ms / MsPerBar(); assert(amount > 0); double oldMeasureTime = mMeasureTime; mMeasureTime += amount; if (int(mMeasureTime) != int(oldMeasureTime) && mMeasureTime >= mJumpFromMeasure) { if (mQueuedMeasure != -1) { SetMeasure(mQueuedMeasure); if (mLoopStartMeasure != -1) mQueuedMeasure = mLoopStartMeasure; else mQueuedMeasure = -1; } } if (TheChaosEngine) TheChaosEngine->AudioUpdate(); UpdateListeners(ms); for (std::list<IAudioPoller*>::iterator i = mAudioPollers.begin(); i != mAudioPollers.end(); ++i) { IAudioPoller* poller = *i; poller->OnTransportAdvanced(amount); } } float QuadraticBezier(float x, float a, float b) { // adapted from BEZMATH.PS (1993) // by Don Lancaster, SYNERGETICS Inc. // path_to_url float epsilon = 0.00001f; a = ofClamp(a, 0, 1); b = ofClamp(b, 0, 1); if (a == 0.5f) { a += epsilon; } // solve t from x (an inverse operation) float om2a = 1 - 2 * a; float t = (sqrtf(a * a + om2a * x) - a) / om2a; float y = (1 - 2 * b) * (t * t) + (2 * b) * t; return y; } double Transport::Swing(double measurePos) { double swingSlices = double(mSwingInterval) * mTimeSigTop / 4.0; double swingPos = measurePos * swingSlices; int swingBeat = int(swingPos); swingPos -= swingBeat; double swung = SwingBeat(swingPos); return (swingBeat + swung) / swingSlices; } double Transport::SwingBeat(double pos) { double swingDouble = mSwing; double term = (.5 - swingDouble) / (swingDouble * swingDouble - swingDouble); pos = term * pos * pos + (1 - term) * pos; return pos; } void Transport::Nudge(double amount) { mNudgeFactor += amount; } void Transport::DrawModule() { if (Minimized() || IsVisible() == false) return; double measurePos = GetMeasurePos(gTime); int count = int(fmod(mMeasureTime, 1) * mTimeSigTop) + 1; std::string display; display += ofToString(measurePos, 2) + " " + ofToString(GetMeasure(gTime)) + "\n"; display += ofToString(count); DrawTextNormal(display, 5, 52); ofPushStyle(); float w, h; GetDimensions(w, h); ofFill(); ofSetColor(255, 255, 255, 50); float beatWidth = w / mTimeSigTop; ofRect((count - 1) * beatWidth, 0, beatWidth, h, 0); if (count % 2) ofSetColor(255, 0, 255); else ofSetColor(0, 255, 255); ofLine(w * measurePos, 0, w * measurePos, h); ofRect(0, 95, w * ((measurePos + (GetMeasure(gTime) % 4)) / 4), 5); ofPopStyle(); mSwingSlider->Draw(); mResetButton->Draw(); if (TheSynth->IsAudioPaused()) mPlayPauseButton->SetDisplayStyle(ButtonDisplayStyle::kPlay); else mPlayPauseButton->SetDisplayStyle(ButtonDisplayStyle::kPause); mPlayPauseButton->Draw(); mTimeSigTopDropdown->Draw(); mTimeSigBottomDropdown->Draw(); mSwingIntervalDropdown->Draw(); mNudgeBackButton->Draw(); mNudgeForwardButton->Draw(); mIncreaseTempoButton->Draw(); mDecreaseTempoButton->Draw(); mTempoSlider->Draw(); ofBeginShape(); for (int i = 0; i < w - 1; ++i) { float pos = i / float(w - 1); float swung = Swing(pos); ofVertex(i + 1, h - 1 - swung * (h - 1)); } ofEndShape(); ofRect(0, h - Swing(measurePos) * h, 4, 1); float nudgeMinX = mNudgeBackButton->GetRect(true).getMinX(); float nudgeMaxX = mNudgeForwardButton->GetRect(true).getMaxX(); float nudgeX = ofLerp(nudgeMinX, nudgeMaxX, (mNudgeFactor / 15) + .5f); ofLine(nudgeX, mNudgeBackButton->GetRect(true).getMinY(), nudgeX, mNudgeBackButton->GetRect(true).getMaxY()); } void Transport::Reset() { if (mLoopEndMeasure != -1) mMeasureTime = mLoopEndMeasure - .01f; else mMeasureTime = .99f; SetQueuedMeasure(NextBufferTime(true), 0); if (TheSynth->IsAudioPaused()) TheSynth->SetAudioPaused(false); } void Transport::ButtonClicked(ClickButton* button, double time) { if (button == mResetButton) Reset(); if (button == mNudgeBackButton) Nudge(-1); if (button == mNudgeForwardButton) Nudge(1); if (button == mIncreaseTempoButton) SetTempo(floor(mTempo + 1)); if (button == mDecreaseTempoButton) SetTempo(ceil(mTempo - 1)); if (button == mPlayPauseButton) TheSynth->SetAudioPaused(!TheSynth->IsAudioPaused()); } TransportListenerInfo* Transport::AddListener(ITimeListener* listener, NoteInterval interval, OffsetInfo offsetInfo, bool useEventLookahead) { #if DEBUG IDrawableModule* module = dynamic_cast<IDrawableModule*>(listener); if (module != nullptr) assert(module->IsInitialized()); #endif //try to update first in case we already point to this TransportListenerInfo* info = GetListenerInfo(listener); if (info != nullptr) { info->mInterval = interval; info->mOffsetInfo = offsetInfo; info->mUseEventLookahead = useEventLookahead; } else { mListeners.push_front(TransportListenerInfo(listener, interval, offsetInfo, useEventLookahead)); } return GetListenerInfo(listener); } TransportListenerInfo* Transport::GetListenerInfo(ITimeListener* listener) { for (std::list<TransportListenerInfo>::iterator i = mListeners.begin(); i != mListeners.end(); ++i) { TransportListenerInfo& info = *i; if (info.mListener == listener) return &info; } return nullptr; } void Transport::RemoveListener(ITimeListener* listener) { for (std::list<TransportListenerInfo>::iterator i = mListeners.begin(); i != mListeners.end();) { TransportListenerInfo& info = *i; if (info.mListener == listener) i = mListeners.erase(i); else ++i; } } void Transport::AddAudioPoller(IAudioPoller* poller) { #if DEBUG IDrawableModule* module = dynamic_cast<IDrawableModule*>(poller); if (module != nullptr) assert(module->IsInitialized()); #endif if (!ListContains(poller, mAudioPollers)) mAudioPollers.push_front(poller); } void Transport::RemoveAudioPoller(IAudioPoller* poller) { mAudioPollers.remove(poller); } void Transport::ClearListenersAndPollers() { mListeners.clear(); mAudioPollers.clear(); } int Transport::GetQuantized(double time, const TransportListenerInfo* listenerInfo, double* remainderMs /*=nullptr*/) { double offsetMs; if (listenerInfo->mOffsetInfo.mOffsetIsInMs) offsetMs = listenerInfo->mOffsetInfo.mOffset; else offsetMs = listenerInfo->mOffsetInfo.mOffset * MsPerBar(); time += offsetMs; int measure = GetMeasure(time); double measurePos = GetMeasurePos(time); double pos = Swing(measurePos); //TODO(Ryan) it seems like most of these cases below could be collapsed into a single case //(but there will probably be fallout that needs to be fixed up in various places) //changing GetQuantized() to return an unclamped range across the board seems like the right way to go NoteInterval interval = listenerInfo->mInterval; switch (interval) { case kInterval_1n: case kInterval_2: case kInterval_3: case kInterval_4: case kInterval_8: case kInterval_16: case kInterval_32: case kInterval_64: { pos *= double(mTimeSigTop) / mTimeSigBottom; int ret = measure / (int)GetMeasureFraction(interval); if (remainderMs != nullptr) *remainderMs = (pos + measure % (int)GetMeasureFraction(interval)) * MsPerBar(); return ret; //unclamped } case kInterval_None: interval = kInterval_16n; //just pick some default value [[fallthrough]]; case kInterval_2n: case kInterval_2nt: case kInterval_4n: case kInterval_4nt: case kInterval_8n: case kInterval_8nt: case kInterval_16n: case kInterval_16nt: case kInterval_32n: case kInterval_32nt: case kInterval_64n: { pos *= double(mTimeSigTop) / mTimeSigBottom; double ret = pos * CountInStandardMeasure(interval); if (remainderMs != nullptr) { double remainder = ret - (int)ret; if (mSwing == .5f) *remainderMs = remainder * GetDuration(interval); else *remainderMs = 0; //TODO(Ryan) this is incorrect, figure out how to properly calculate remainderMs when swing is applied } return (int)ret; //wraps around CountInStandardMeasure(interval) range } case kInterval_4nd: case kInterval_8nd: case kInterval_16nd: { pos *= double(mTimeSigTop) / mTimeSigBottom; double ret = (measure + pos) / GetMeasureFraction(interval); if (remainderMs != nullptr) { double remainder = ret - (int)ret; if (mSwing == .5f) *remainderMs = remainder * GetDuration(interval); else *remainderMs = 0; //TODO(Ryan) this is incorrect, figure out how to properly calculate remainderMs when swing is applied } return (int)ret; //unclamped } case kInterval_CustomDivisor: { double ret = pos * listenerInfo->mCustomDivisor; if (remainderMs != nullptr) { double remainder = ret - (int)ret; if (mSwing == .5f) *remainderMs = remainder * (MsPerBar() / listenerInfo->mCustomDivisor); else *remainderMs = 0; //TODO(Ryan) this is incorrect, figure out how to properly calculate remainderMs when swing is applied } return (int)ret; //wraps around custom divisor } default: //TODO(Ryan) this doesn't really make sense, does it? //assert(false); TheSynth->LogEvent("error: GetQuantized() called with invalid interval " + ofToString(interval), kLogEventType_Error); return 0; } return 0; } int Transport::CountInStandardMeasure(NoteInterval interval) { switch (interval) { case kInterval_1n: return 1; case kInterval_2n: return 2; case kInterval_2nt: return 3; case kInterval_4n: return 4; case kInterval_4nt: return 6; case kInterval_8n: return 8; case kInterval_8nt: return 12; case kInterval_16n: return 16; case kInterval_16nt: return 24; case kInterval_32n: return 32; case kInterval_32nt: return 48; case kInterval_64n: return 64; case kInterval_None: return 16; //TODO(Ryan) whatever default: //TODO(Ryan) this doesn't really make sense, does it? //assert(false); TheSynth->LogEvent("error: CountInStandardMeasure() called with invalid interval " + ofToString(interval), kLogEventType_Error); return 1; } return 0; } int Transport::GetStepsPerMeasure(ITimeListener* listener) { TransportListenerInfo* info = GetListenerInfo(listener); if (info != nullptr) { if (info->mInterval == kInterval_CustomDivisor) return info->mCustomDivisor; return CountInStandardMeasure(info->mInterval) * GetTimeSigTop() / GetTimeSigBottom(); } TheSynth->LogEvent("error: GetStepsPerMeasure() called with unregistered listener", kLogEventType_Error); return 8; } int Transport::GetSyncedStep(double time, ITimeListener* listener, const TransportListenerInfo* listenerInfo, int length) { double offsetMs; if (listenerInfo->mOffsetInfo.mOffsetIsInMs) offsetMs = listenerInfo->mOffsetInfo.mOffset; else offsetMs = listenerInfo->mOffsetInfo.mOffset * MsPerBar(); int step; if (GetMeasureFraction(listenerInfo->mInterval) < 1) { int stepsPerMeasure = GetStepsPerMeasure(listener); int measure = GetMeasure(time + offsetMs); step = GetQuantized(time, listenerInfo) + measure * stepsPerMeasure; //GetQuantized() handles offset internally } else { int measure = GetMeasure(time + offsetMs); step = int(measure / GetMeasureFraction(listenerInfo->mInterval)); } if (length > 0) step %= length; return step; } double Transport::GetDuration(NoteInterval interval) { return MsPerBar() * GetMeasureFraction(interval); } double Transport::GetMeasureTimeInternal(double time) const { return mMeasureTime + (time - gTime) / MsPerBar(); } double Transport::GetMeasureTime(double time) const { double measureTime = GetMeasureTimeInternal(time); if (mQueuedMeasure != -1 && measureTime >= mJumpFromMeasure) measureTime = mQueuedMeasure + measureTime - mJumpFromMeasure; return measureTime; } void Transport::SetQueuedMeasure(double time, int measure) { mQueuedMeasure = -1; //clear if (mLoopEndMeasure != -1) mJumpFromMeasure = mLoopEndMeasure; else mJumpFromMeasure = GetMeasure(time) + 1; mQueuedMeasure = measure; } bool Transport::IsPastQueuedMeasureJump(double time) const { double measureTime = GetMeasureTimeInternal(time); if (mQueuedMeasure != -1 && measureTime >= mJumpFromMeasure) return true; return false; } double Transport::GetMeasureFraction(NoteInterval interval) { switch (interval) { case kInterval_1n: return 1.0; case kInterval_2n: return GetMeasureFraction(kInterval_4n) * 2; case kInterval_2nt: return GetMeasureFraction(kInterval_2n) * 2.0 / 3.0; case kInterval_4n: return 1.0 / mTimeSigTop; case kInterval_4nt: return GetMeasureFraction(kInterval_4n) * 2.0 / 3.0; case kInterval_8n: return GetMeasureFraction(kInterval_4n) * .5; case kInterval_8nt: return GetMeasureFraction(kInterval_8n) * 2.0 / 3.0; case kInterval_16n: return GetMeasureFraction(kInterval_4n) * .25; case kInterval_16nt: return GetMeasureFraction(kInterval_16n) * 2.0 / 3.0; case kInterval_32n: return GetMeasureFraction(kInterval_4n) * .125; case kInterval_32nt: return GetMeasureFraction(kInterval_32n) * 2.0 / 3.0; case kInterval_64n: return GetMeasureFraction(kInterval_4n) * .0625; case kInterval_4nd: return GetMeasureFraction(kInterval_4n) * 1.5; case kInterval_8nd: return GetMeasureFraction(kInterval_8n) * 1.5; case kInterval_16nd: return GetMeasureFraction(kInterval_16n) * 1.5; case kInterval_2: return 2; case kInterval_3: return 3; case kInterval_4: return 4; case kInterval_8: return 8; case kInterval_16: return 16; case kInterval_32: return 32; case kInterval_64: return 64; default: return GetMeasureFraction(kInterval_16n); } } void Transport::UpdateListeners(double jumpMs) { std::list<int> priorities; for (const auto& info : mListeners) { if (info.mListener != nullptr && !ListContains(info.mListener->mTransportPriority, priorities)) priorities.push_back(info.mListener->mTransportPriority); } priorities.sort(); for (const auto& priority : priorities) { for (const auto& info : mListeners) { if (info.mListener != nullptr && info.mListener->mTransportPriority == priority && info.mInterval != kInterval_None && info.mInterval != kInterval_Free) { double lookaheadMs = jumpMs; if (info.mUseEventLookahead) lookaheadMs = MAX(lookaheadMs, GetEventLookaheadMs()); double checkTime = gTime + lookaheadMs; double remainderMs; int oldStep = GetQuantized(checkTime - jumpMs, &info); int newStep = GetQuantized(checkTime, &info, &remainderMs); bool oldJumped = IsPastQueuedMeasureJump(checkTime - jumpMs); bool newJumped = IsPastQueuedMeasureJump(checkTime); if (oldStep != newStep || oldJumped != newJumped) { double time = checkTime - remainderMs + .0001; //TODO(Ryan) investigate this fudge number. I would think that subtracting remainderMs from checkTime would give me a number that gives me the same GetQuantized() result with a zero remainder, but sometimes it is just short of the correct quantization /*ofLog() << oldStep << " " << newStep << " " << remainderMs << " " << jumpMs << " " << checkTime << " " << time << " " << GetQuantized(checkTime, info.mInterval) << " " << GetQuantized(time, info.mInterval); if (GetQuantized(checkTime + offsetMs, info.mInterval) != GetQuantized(time + offsetMs, info.mInterval)) { double aboveRemainderMs; GetQuantized(checkTime + offsetMs, info.mInterval, &aboveRemainderMs); double remainderShouldBeZeroMs; GetQuantized(time + offsetMs, info.mInterval, &remainderShouldBeZeroMs); ofLog() << remainderShouldBeZeroMs; }*/ //assert(GetQuantized(checkTime + offsetMs, info.mInterval) == GetQuantized(time + offsetMs, info.mInterval)); info.mListener->OnTimeEvent(time); } } } } } void Transport::OnDrumEvent(NoteInterval drumEvent) { for (const auto& info : mListeners) { if (info.mInterval == drumEvent) info.mListener->OnTimeEvent(0); //TODO(Ryan) calc sample offset } } void Transport::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void Transport::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mSetTempoCheckbox) { if (mSetTempoBool) { mStartRecordTime = time; } else if (mStartRecordTime != -1) { int numBars = 1; float recordedTime = time - mStartRecordTime; int beats = numBars * GetTimeSigTop(); float minutes = recordedTime / 1000.0f / 60.0f; SetTempo(beats / minutes); SetDownbeat(); } } } void Transport::DropdownUpdated(DropdownList* list, int oldVal, double time) { } //static bool Transport::IsTripletInterval(NoteInterval interval) { if (interval == kInterval_2nt || interval == kInterval_4nt || interval == kInterval_8nt || interval == kInterval_16nt || interval == kInterval_32nt) return true; return false; } void Transport::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadBool("randomize_tempo_on_load", moduleInfo, false); SetUpFromSaveData(); } void Transport::SetUpFromSaveData() { if (mModuleSaveData.GetBool("randomize_tempo_on_load")) mWantSetRandomTempo = true; } void Transport::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << mMeasureTime; } void Transport::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); if (rev == 0) //load as float instead of double { float measurePos; in >> measurePos; mMeasureTime = measurePos; } else { in >> mMeasureTime; } } ```
/content/code_sandbox/Source/Transport.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
6,343
```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 **/ // // Ramp.h // modularSynth // // Created by Ryan Challinor on 11/26/12. // // #pragma once #include <array> class Ramp { public: void Start(double curTime, float end, double endTime); void Start(double curTime, float start, float end, double endTime); void SetValue(float val); bool HasValue(double time) const; float Value(double time) const; float Target(double time) const { return GetCurrentRampData(time)->mEndValue; } private: struct RampData { double mStartTime{ -1 }; float mStartValue{ 0 }; float mEndValue{ 1 }; double mEndTime{ -1 }; }; const RampData* GetCurrentRampData(double time) const; std::array<RampData, 10> mRampDatas; int mRampDataPointer{ 0 }; }; ```
/content/code_sandbox/Source/Ramp.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
297
```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 **/ // // FourOnTheFloor.cpp // modularSynth // // Created by Ryan Challinor on 6/23/13. // // #include "FourOnTheFloor.h" #include "SynthGlobals.h" #include "DrumPlayer.h" #include "ModularSynth.h" FourOnTheFloor::FourOnTheFloor() { } void FourOnTheFloor::Init() { IDrawableModule::Init(); TheTransport->AddListener(this, kInterval_4n, OffsetInfo(0, true), true); } void FourOnTheFloor::CreateUIControls() { IDrawableModule::CreateUIControls(); mTwoOnTheFloorCheckbox = new Checkbox(this, "two", 4, 2, &mTwoOnTheFloor); } FourOnTheFloor::~FourOnTheFloor() { TheTransport->RemoveListener(this); } void FourOnTheFloor::DrawModule() { if (Minimized() || IsVisible() == false) return; mTwoOnTheFloorCheckbox->Draw(); } void FourOnTheFloor::OnTimeEvent(double time) { if (!mEnabled) return; int kick = 0; PlayNoteOutput(time, kick, 127, -1); } void FourOnTheFloor::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mTwoOnTheFloorCheckbox) { if (mTwoOnTheFloor) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = kInterval_2n; } else { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = kInterval_4n; } } } void FourOnTheFloor::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void FourOnTheFloor::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/FourOnTheFloor.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
561
```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 **/ // // Rewriter.cpp // modularSynth // // Created by Ryan Challinor on 3/16/13. // // #include "Rewriter.h" #include "Looper.h" #include "ModularSynth.h" #include "Transport.h" #include "MidiController.h" #include "Profiler.h" #include "FillSaveDropdown.h" #include "PatchCableSource.h" #include "AudioSend.h" #include "UIControlMacros.h" Rewriter::Rewriter() : IAudioProcessor(gBufferSize) , mRecordBuffer(MAX_BUFFER_SIZE) { } namespace { const int kBufferHeight = 40; } void Rewriter::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); BUTTON(mRewriteButton, "go"); UIBLOCK_SHIFTRIGHT(); BUTTON(mStartRecordTimeButton, "new loop"); ENDUIBLOCK(mWidth, mHeight); mWidth = 110; mHeight += kBufferHeight + 3; mLooperCable = new PatchCableSource(this, kConnectionType_Special); mLooperCable->SetManualPosition(mWidth - 10, 10); mLooperCable->AddTypeFilter("looper"); ofColor color = mLooperCable->GetColor(); color.a *= .3f; mLooperCable->SetColor(color); AddPatchCableSource(mLooperCable); } Rewriter::~Rewriter() { } void Rewriter::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { if (cableSource == mLooperCable) { if (mConnectedLooper) mConnectedLooper->SetRewriter(nullptr); mConnectedLooper = dynamic_cast<Looper*>(mLooperCable->GetTarget()); if (mConnectedLooper) mConnectedLooper->SetRewriter(this); } } void Rewriter::Process(double time) { PROFILER(Rewriter); IAudioReceiver* target = GetTarget(); if (target == nullptr) return; SyncBuffers(); mRecordBuffer.SetNumChannels(GetBuffer()->NumActiveChannels()); int bufferSize = GetBuffer()->BufferSize(); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { mRecordBuffer.WriteChunk(GetBuffer()->GetChannel(ch), bufferSize, ch); Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), bufferSize); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), bufferSize, ch); } GetBuffer()->Reset(); } void Rewriter::DrawModule() { if (Minimized() || IsVisible() == false) return; mRewriteButton->Draw(); mStartRecordTimeButton->Draw(); if (mStartRecordTime != -1) { ofSetColor(255, 100, 0, 100 + 50 * (cosf(TheTransport->GetMeasurePos(gTime) * 4 * FTWO_PI))); ofRect(mStartRecordTimeButton->GetRect(true)); } if (mConnectedLooper) { int loopSamples = abs(int(TheTransport->MsPerBar() / 1000 * gSampleRate)) * mConnectedLooper->GetNumBars(); ofRectangle rect(3, mHeight - kBufferHeight - 3, mWidth - 6, kBufferHeight); float playhead = fmod(TheTransport->GetMeasureTime(gTime), mConnectedLooper->GetNumBars()) / mConnectedLooper->GetNumBars(); //mRecordBuffer.Draw(rect.x, rect.y, rect.width, rect.height, loopSamples, L(channel,0), loopSamples * playhead); //mRecordBuffer.Draw(rect.x, rect.y, rect.width * playhead, rect.height, loopSamples * playhead, L(channel, 0)); ofPushMatrix(); ofTranslate(rect.x, rect.y); int nowOffset = mRecordBuffer.GetRawBufferOffset(0); int startSample = nowOffset - loopSamples * playhead; if (startSample < 0) startSample += mRecordBuffer.Size(); int endSample = startSample - 1; if (endSample < 0) endSample += loopSamples; int loopBeginSample = startSample - loopSamples * (1 - playhead); if (loopBeginSample < 0) loopBeginSample += mRecordBuffer.Size(); DrawAudioBuffer(rect.width, rect.height, mRecordBuffer.GetRawBuffer()->GetChannel(0), startSample, endSample, -1, 1, ofColor::black, nowOffset, loopBeginSample, mRecordBuffer.Size()); ofPopMatrix(); ofSetColor(0, 255, 0); ofLine(rect.x + rect.width * playhead, rect.y, rect.x + rect.width * playhead, rect.y + rect.height); } else { DrawTextNormal("connect a looper", 5, mHeight - 3 - kBufferHeight / 2); } } void Rewriter::ButtonClicked(ClickButton* button, double time) { if (button == mStartRecordTimeButton) { if (mStartRecordTime == -1) mStartRecordTime = time; else mStartRecordTime = -1; } if (button == mRewriteButton) Go(time); } void Rewriter::CheckboxUpdated(Checkbox* checkbox, double time) { } void Rewriter::Go(double time) { if (mConnectedLooper) { if (mStartRecordTime != -1) { float recordedMs = time - mStartRecordTime; float numBarsCurrentTempo = recordedMs / TheTransport->MsPerBar(); int numBars = int(numBarsCurrentTempo + .5f); numBars = MAX(1, int(Pow2(floor(log2(numBars))))); //find closest power of 2 int beats = numBars * TheTransport->GetTimeSigTop(); float minutes = recordedMs / 1000.0f / 60.0f; float bpm = beats / minutes; TheTransport->SetTempo(bpm); TheTransport->SetDownbeat(); mConnectedLooper->SetNumBars(numBars); mStartRecordTime = -1; } mConnectedLooper->SetNumBars(mConnectedLooper->GetRecorderNumBars()); mConnectedLooper->Commit(&mRecordBuffer, true, 0); AudioSend* connectedSend = dynamic_cast<AudioSend*>(mConnectedLooper->GetTarget()); if (connectedSend) connectedSend->SetSend(1, true); TheSynth->ArrangeAudioSourceDependencies(); } } void Rewriter::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadString("looper", moduleInfo, "", FillDropdown<Looper*>); SetUpFromSaveData(); } void Rewriter::SaveLayout(ofxJSONElement& moduleInfo) { std::string targetPath = ""; if (mConnectedLooper) targetPath = mConnectedLooper->Path(); moduleInfo["looper"] = targetPath; } void Rewriter::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mLooperCable->SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("looper"), false)); } ```
/content/code_sandbox/Source/Rewriter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,707
```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 **/ // // SaveStateLoader.h // Bespoke // // Created by Ryan Challinor on 7/23/24. // // #pragma once #include <iostream> #include <utility> #include "IDrawableModule.h" #include "OpenFrameworksPort.h" #include "ClickButton.h" class SaveStateLoader : public IDrawableModule, public IButtonListener { public: SaveStateLoader(); virtual ~SaveStateLoader(); static IDrawableModule* Create() { return new SaveStateLoader(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Poll() override; void ButtonClicked(ClickButton* button, double time) override; bool IsEnabled() const override { return true; } 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: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; bool HasValidFile(int index) const; void UpdateButtonLabel(int index); struct LoadButton { std::string mFilePath{ "" }; ClickButton* mButton{ nullptr }; bool mShouldShowSelectDialog{ false }; }; std::array<LoadButton, 30> mLoadButtons; int mNumDisplayButtons{ 1 }; }; ```
/content/code_sandbox/Source/SaveStateLoader.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
463
```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 **/ // // NoteGate.cpp // Bespoke // // Created by Ryan Challinor on 5/22/16. // // #include "NoteGate.h" #include "SynthGlobals.h" NoteGate::NoteGate() { } NoteGate::~NoteGate() { } void NoteGate::CreateUIControls() { IDrawableModule::CreateUIControls(); mGateCheckbox = new Checkbox(this, "open", 3, 4, &mGate); } void NoteGate::DrawModule() { if (Minimized() || IsVisible() == false) return; mGateCheckbox->Draw(); } void NoteGate::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mGate || (velocity == 0 && mActiveNotes[pitch].velocity > 0)) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); mActiveNotes[pitch].velocity = velocity; mActiveNotes[pitch].voiceIdx = voiceIdx; mActiveNotes[pitch].modulation = modulation; } } void NoteGate::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mGateCheckbox) { if (!mGate) { for (int pitch = 0; pitch < 128; ++pitch) { if (mActiveNotes[pitch].velocity > 0) { PlayNoteOutput(time + gBufferSizeMs, pitch, 0, mActiveNotes[pitch].voiceIdx, mActiveNotes[pitch].modulation); mActiveNotes[pitch].velocity = 0; } } } } } void NoteGate::GetModuleDimensions(float& width, float& height) { width = 80; height = 20; } void NoteGate::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void NoteGate::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/NoteGate.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
545
```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 **/ // // NoteToggle.h // Bespoke // // Created by Ryan Challinor on 11/02/2021 // // #pragma once #include "IDrawableModule.h" #include "INoteReceiver.h" class PatchCableSource; class NoteToggle : public IDrawableModule, public INoteReceiver { public: NoteToggle(); ~NoteToggle(); static IDrawableModule* Create() { return new NoteToggle(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() 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 {} //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; std::array<bool, 128> mHeldPitches{ false }; PatchCableSource* mControlCable{ nullptr }; std::array<IUIControl*, IDrawableModule::kMaxOutputsPerPatchCableSource> mTargets{}; }; ```
/content/code_sandbox/Source/NoteToggle.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
445
```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 **/ /* ============================================================================== FubbleModule.cpp Created: 8 Aug 2020 10:03:56am Author: Ryan Challinor ============================================================================== */ #include "FubbleModule.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "SynthGlobals.h" #include "UIControlMacros.h" #include "juce_core/juce_core.h" FubbleModule::FubbleModule() : mAxisH(this, true) , mAxisV(this, false) { UpdatePerlinSeed(); } FubbleModule::~FubbleModule() { } void FubbleModule::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); CHECKBOX(mQuantizeLengthCheckbox, "quantize", &mQuantizeLength); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mQuantizeLengthSelector, "length", (int*)(&mQuantizeInterval), 60); UIBLOCK_SHIFTLEFT(); FLOATSLIDER(mSpeedSlider, "speed", &mSpeed, .1f, 10); UIBLOCK_SHIFTRIGHT(); BUTTON(mClearButton, "clear"); ENDUIBLOCK0(); UIBLOCK(10, mHeight - kBottomControlHeight + 3, 135); FLOATSLIDER(mPerlinStrengthSlider, "mutate amount", &mPerlinStrength, 0, 2); FLOATSLIDER(mPerlinScaleSlider, "mutate warp", &mPerlinScale, 0, 5); FLOATSLIDER(mPerlinSpeedSlider, "mutate noise", &mPerlinSpeed, 0, 2); UIBLOCK_SHIFTRIGHT(); BUTTON(mUpdatePerlinSeedButton, "reseed"); ENDUIBLOCK0(); mAxisH.SetCableSource(new PatchCableSource(this, kConnectionType_Modulator)); AddPatchCableSource(mAxisH.GetCableSource()); mAxisV.SetCableSource(new PatchCableSource(this, kConnectionType_Modulator)); AddPatchCableSource(mAxisV.GetCableSource()); 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 FubbleModule::Init() { IDrawableModule::Init(); } void FubbleModule::Poll() { if (mIsDrawing) { RecordPoint(); } else { if (mPerlinStrength > 0) { double perlinTime = gTime; int numPoints = mAxisH.mCurve.GetNumPoints(); for (int i = 0; i < numPoints; ++i) { CurvePoint* pointH = mAxisH.mCurve.GetPoint(i); CurvePoint* pointV = mAxisV.mCurve.GetPoint(i); float deltaH = ofMap(GetPerlinNoiseValue(perlinTime, pointH->mValue, pointV->mValue, true), 0, 1, -mPerlinStrength, mPerlinStrength) * .003f; float deltaV = ofMap(GetPerlinNoiseValue(perlinTime, pointH->mValue, pointV->mValue, false), 0, 1, -mPerlinStrength, mPerlinStrength) * .003f; //try to keep in bounds if (pointH->mValue < 0) deltaH -= pointH->mValue * .1f; if (pointH->mValue > 1) deltaH -= (pointH->mValue - 1) * .1f; if (pointV->mValue < 0) deltaV -= pointV->mValue * .1f; if (pointV->mValue > 1) deltaV -= (pointV->mValue - 1) * .1f; pointH->mValue += deltaH; pointV->mValue += deltaV; } } } } float FubbleModule::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 FubbleModule::DrawModule() { if (Minimized() || IsVisible() == false) return; mQuantizeLengthCheckbox->Draw(); mQuantizeLengthSelector->SetShowing(mQuantizeLength); mQuantizeLengthSelector->Draw(); mSpeedSlider->SetShowing(!mQuantizeLength); mSpeedSlider->Draw(); mClearButton->Draw(); mPerlinStrengthSlider->Draw(); mPerlinScaleSlider->Draw(); mPerlinSpeedSlider->Draw(); mUpdatePerlinSeedButton->Draw(); ofPushStyle(); ofSetColor(100, 100, 100, 100); ofFill(); ofPushMatrix(); ofRectangle rect = GetFubbleRect(); ofTranslate(rect.x, rect.y); ofRect(0, 0, rect.width, rect.height); if (mPerlinStrength > 0) { double perlinTime = gTime; const int kGridSize = 30; for (int col = 0; col < kGridSize; ++col) { for (int row = 0; row < kGridSize; ++row) { float x = col * (rect.width / kGridSize); float y = row * (rect.height / kGridSize); ofSetColor(GetPerlinNoiseValue(perlinTime, x / rect.width, y / rect.height, true) * 255, 0, GetPerlinNoiseValue(perlinTime, x / rect.width, y / rect.height, false) * 255, ofClamp(mPerlinStrength, 0, 1) * 255); ofRect(x, y, (rect.width / kGridSize) + .5f, (rect.height / kGridSize) + .5f, 0); } } } ofSetColor(GetColor(kModuleCategory_Modulator)); ofPushMatrix(); if (mAxisH.GetCableSource()->GetTarget()) DrawTextNormal(mAxisH.GetCableSource()->GetTarget()->Name(), rect.width * .4f, rect.height - 2); ofRotate(-PI * .5f); if (mAxisV.GetCableSource()->GetTarget()) DrawTextNormal(mAxisV.GetCableSource()->GetTarget()->Name(), -rect.height * .6f, rect.width - 2); ofPopMatrix(); //draw curve ofPushStyle(); ofSetColor(GetColor(kModuleCategory_Modulator)); DrawTextNormal("length: " + ofToString(mLength, 2), 5, 15); ofSetColor(220, 220, 220); ofNoFill(); ofBeginShape(); for (float t = 0; t < mLength; t += .01f) { float x = mAxisH.mCurve.Evaluate(t) * rect.width; float y = (1 - mAxisV.mCurve.Evaluate(t)) * rect.height; ofVertex(x, y); } ofEndShape(); //draw individual points /*ofFill(); ofSetColor(220,220,220,100); int numPoints = mAxisH.mCurve.GetNumPoints(); const int kMaxDrawPoints = 100; float step = MAX(1, numPoints/kMaxDrawPoints); for (float i=0; int(i)<numPoints; i+=step) { float x = mAxisH.mCurve.GetPoint(int(i))->mValue * rect.width; float y = (1 - mAxisV.mCurve.GetPoint(int(i))->mValue) * rect.height; //ofRect(x-3,y-3,6,6,0); ofCircle(x,y,2.5f); }*/ ofFill(); ofSetColor(255, 255, 255); if (mAxisH.mHasRecorded) { float time = mIsDrawing ? mRecordStartOffset : GetPlaybackTime(gTime); float currentX = mAxisH.mCurve.Evaluate(time, true) * rect.width; float currentY = (1 - mAxisV.mCurve.Evaluate(time, true)) * rect.height; ofCircle(currentX, currentY, 4); } if (mIsDrawing || IsHovered() || mIsRightClicking) { ofNoFill(); ofSetColor(GetColor(kModuleCategory_Modulator), (mIsDrawing || mIsRightClicking) ? 255 : 50); ofCircle(GetFubbleMouseCoord().x * rect.width, (1 - GetFubbleMouseCoord().y) * rect.height, 5); } ofPopStyle(); ofPopMatrix(); ofPushMatrix(); ofTranslate(10, mHeight - (kTimelineSectionHeight + kBottomControlHeight) + 3); ofSetColor(100, 100, 100, 100); ofRect(0, 0, mWidth - 20, 20); mAxisH.mCurve.SetDimensions(mWidth - 20, 20); mAxisH.mCurve.Render(); ofSetColor(GetColor(kModuleCategory_Modulator)); if (mAxisH.GetCableSource()->GetTarget()) DrawTextNormal(mAxisH.GetCableSource()->GetTarget()->Name(), 5, 15); ofTranslate(0, 25); ofSetColor(100, 100, 100, 100); ofRect(0, 0, mWidth - 20, 20); mAxisV.mCurve.SetDimensions(mWidth - 20, 20); mAxisV.mCurve.Render(); ofSetColor(GetColor(kModuleCategory_Modulator)); if (mAxisV.GetCableSource()->GetTarget()) DrawTextNormal(mAxisV.GetCableSource()->GetTarget()->Name(), 5, 15); ofPopMatrix(); ofPopStyle(); if (mLength > 0) { float playbackTime = GetPlaybackTime(gTime); float lineX = ofLerp(10, mWidth - 20, playbackTime / mLength); ofLine(lineX, mHeight - (kTimelineSectionHeight + kBottomControlHeight), lineX, mHeight - (kBottomControlHeight)); } float rightAlign = mWidth - 5; float leftAlign = 5; if (mAxisH.GetCableSource()->GetTarget() && mAxisH.GetCableSource()->GetTarget()->GetRect().getCenter().x < GetRect().getCenter().x) { mAxisH.GetCableSource()->SetManualPosition(leftAlign, mHeight - (kBottomControlHeight + kTimelineSectionHeight) + 13); mAxisH.GetCableSource()->SetOverrideCableDir(ofVec2f(-1, 0), PatchCableSource::Side::kLeft); } else { mAxisH.GetCableSource()->SetManualPosition(rightAlign, mHeight - (kBottomControlHeight + kTimelineSectionHeight) + 13); mAxisH.GetCableSource()->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight); } if (mAxisV.GetCableSource()->GetTarget() && mAxisV.GetCableSource()->GetTarget()->GetRect().getCenter().x < GetRect().getCenter().x) { mAxisV.GetCableSource()->SetManualPosition(leftAlign, mHeight - (kBottomControlHeight + kTimelineSectionHeight) + 38); mAxisV.GetCableSource()->SetOverrideCableDir(ofVec2f(-1, 0), PatchCableSource::Side::kLeft); } else { mAxisV.GetCableSource()->SetManualPosition(rightAlign, mHeight - (kBottomControlHeight + kTimelineSectionHeight) + 38); mAxisV.GetCableSource()->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight); } } float FubbleModule::GetPerlinNoiseValue(double time, float x, float y, bool horizontal) { float perlinScale = mPerlinScale * 2.0f; float perlinSpeed = mPerlinSpeed * .002f; if (horizontal) return mNoise.noise(x * perlinScale, y * perlinScale, time * perlinSpeed + mPerlinSeed); else return mNoise.noise(y * perlinScale * .997f, x * perlinScale * .984f, time * 1.011f * perlinSpeed + 420 + mPerlinSeed); } void FubbleModule::DrawModuleUnclipped() { if (Minimized() || IsVisible() == false) return; DrawTextNormal("(concept by @_ojack_)", 60, -3, 9); } ofRectangle FubbleModule::GetFubbleRect() { return ofRectangle(10, kTopControlHeight, mWidth - 20, mHeight - (kTimelineSectionHeight + kBottomControlHeight + kTopControlHeight)); } ofVec2f FubbleModule::GetFubbleMouseCoord() { ofRectangle fubbleRect = GetFubbleRect(); return ofVec2f(ofClamp((mMouseX - fubbleRect.x) / fubbleRect.width, 0, 1), ofClamp(1 - ((mMouseY - fubbleRect.y) / fubbleRect.height), 0, 1)); } void FubbleModule::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); mMouseX = x; mMouseY = y; if (IsHovered()) { if (right) { mIsRightClicking = true; } else { mIsDrawing = true; mRecordStartOffset = TheTransport->GetMeasureTime(gTime); Clear(); RecordPoint(); } } } void FubbleModule::Clear() { mLength = 0; mSpeed = 1; mAxisH.mCurve.Clear(); mAxisH.mHasRecorded = false; mAxisV.mCurve.Clear(); mAxisV.mHasRecorded = false; } bool FubbleModule::IsHovered() { return GetFubbleRect().contains(mMouseX, mMouseY); } void FubbleModule::RecordPoint() { float time = TheTransport->GetMeasureTime(gTime) - mRecordStartOffset; auto coord = GetFubbleMouseCoord(); mAxisH.mCurve.AddPointAtEnd(CurvePoint(time, coord.x)); mAxisV.mCurve.AddPointAtEnd(CurvePoint(time, coord.y)); mAxisH.mCurve.SetExtents(0, time); mAxisV.mCurve.SetExtents(0, time); mAxisH.mHasRecorded = true; mAxisV.mHasRecorded = true; mLength = time; } void FubbleModule::MouseReleased() { IDrawableModule::MouseReleased(); mIsRightClicking = false; if (mIsDrawing) { mIsDrawing = false; if (mQuantizeLength) { float quantizeResolution = TheTransport->GetMeasureFraction(mQuantizeInterval); int quantizeIntervalSteps = juce::roundToInt(mLength / quantizeResolution); if (quantizeIntervalSteps <= 0) quantizeIntervalSteps = 1; float quantizedLength = quantizeResolution * quantizeIntervalSteps; mLength = quantizedLength; mAxisH.mCurve.SetExtents(0, mLength); mAxisV.mCurve.SetExtents(0, mLength); } mRecordStartOffset = fmod(mRecordStartOffset, mLength); } } bool FubbleModule::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); mMouseX = x; mMouseY = y; return false; } void FubbleModule::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { if (cableSource == mAxisH.GetCableSource()) mAxisH.UpdateControl(); if (cableSource == mAxisV.GetCableSource()) mAxisV.UpdateControl(); } void FubbleModule::CheckboxUpdated(Checkbox* checkbox, double time) { } void FubbleModule::DropdownUpdated(DropdownList* list, int oldVal, double time) { /*int newSteps = int(mLength/4.0f * TheTransport->CountInStandardMeasure(mInterval)); if (list == mIntervalSelector) { if (newSteps > 0) { SetNumSteps(newSteps, true); } else { mInterval = (NoteInterval)oldVal; } } if (list == mLengthSelector) { if (newSteps > 0) SetNumSteps(newSteps, false); else mLength = oldVal; }*/ } void FubbleModule::ButtonClicked(ClickButton* button, double time) { if (button == mClearButton) Clear(); if (button == mUpdatePerlinSeedButton) UpdatePerlinSeed(); } void FubbleModule::GetModuleDimensions(float& width, float& height) { width = mWidth; height = mHeight; } void FubbleModule::Resize(float w, float h) { w = MAX(w, 211); h = MAX(h, 180); mPerlinStrengthSlider->SetPosition(mPerlinStrengthSlider->GetPosition(true).x, mPerlinStrengthSlider->GetPosition(true).y + h - mHeight); mPerlinScaleSlider->SetPosition(mPerlinScaleSlider->GetPosition(true).x, mPerlinScaleSlider->GetPosition(true).y + h - mHeight); mPerlinSpeedSlider->SetPosition(mPerlinSpeedSlider->GetPosition(true).x, mPerlinSpeedSlider->GetPosition(true).y + h - mHeight); mUpdatePerlinSeedButton->SetPosition(mUpdatePerlinSeedButton->GetPosition(true).x, mUpdatePerlinSeedButton->GetPosition(true).y + h - mHeight); mWidth = w; mHeight = h; } void FubbleModule::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["uicontrol_h"] = mAxisH.GetCableSource()->GetTarget() ? mAxisH.GetCableSource()->GetTarget()->Path() : ""; moduleInfo["uicontrol_v"] = mAxisV.GetCableSource()->GetTarget() ? mAxisV.GetCableSource()->GetTarget()->Path() : ""; moduleInfo["width"] = mWidth; moduleInfo["height"] = mHeight; } void FubbleModule::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("uicontrol_h", moduleInfo); mModuleSaveData.LoadString("uicontrol_v", moduleInfo); mModuleSaveData.LoadInt("width", moduleInfo, mWidth, 120, 1000); mModuleSaveData.LoadInt("height", moduleInfo, mHeight, 15, 1000); SetUpFromSaveData(); } void FubbleModule::SetUpFromSaveData() { { std::string controlPathH = mModuleSaveData.GetString("uicontrol_h"); if (!controlPathH.empty()) { auto uicontrol = TheSynth->FindUIControl(controlPathH); if (uicontrol) { mAxisH.GetCableSource()->SetTarget(uicontrol); mAxisH.UpdateControl(); } } } { std::string controlPathV = mModuleSaveData.GetString("uicontrol_v"); if (!controlPathV.empty()) { auto uicontrol = TheSynth->FindUIControl(controlPathV); if (uicontrol) { mAxisV.GetCableSource()->SetTarget(uicontrol); mAxisV.UpdateControl(); } } } Resize(mModuleSaveData.GetInt("width"), mModuleSaveData.GetInt("height")); } void FubbleModule::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mAxisH.mCurve.SaveState(out); mAxisV.mCurve.SaveState(out); out << mAxisH.mHasRecorded << mAxisV.mHasRecorded; out << mLength; out << mRecordStartOffset; } void FubbleModule::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); mAxisH.mCurve.LoadState(in); mAxisV.mCurve.LoadState(in); if (rev >= 2) in >> mAxisH.mHasRecorded >> mAxisV.mHasRecorded; if (rev >= 3) { in >> mLength; mAxisH.mCurve.SetExtents(0, mLength); mAxisV.mCurve.SetExtents(0, mLength); in >> mRecordStartOffset; } } float FubbleModule::FubbleAxis::Value(int samplesIn) { float playbackTime = mOwner->GetPlaybackTime(gTime + samplesIn * gInvSampleRateMs); float val; if (mOwner->mIsDrawing || mOwner->mIsRightClicking) val = mIsHorizontal ? mOwner->GetFubbleMouseCoord().x : mOwner->GetFubbleMouseCoord().y; else val = mCurve.Evaluate(playbackTime, true); return ofMap(val, 0, 1, GetMin(), GetMax(), K(clamp)); } ```
/content/code_sandbox/Source/FubbleModule.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5,130
```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 **/ /* ============================================================================== SampleLayerer.cpp Created: 2 Jun 2019 2:43:58pm Author: Ryan Challinor ============================================================================== */ #include "SampleLayerer.h" ```
/content/code_sandbox/Source/SampleLayerer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
142
```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 **/ /* ============================================================================== ChordHold.cpp Created: 3 Mar 2021 9:56:09pm Author: Ryan Challinor ============================================================================== */ #include "ChordHolder.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" ChordHolder::ChordHolder() { } void ChordHolder::CreateUIControls() { IDrawableModule::CreateUIControls(); mStopButton = new ClickButton(this, "stop", 3, 3); mOnlyPlayWhenPulsedCheckbox = new Checkbox(this, "pulse to play", 40, 3, &mOnlyPlayWhenPulsed); } void ChordHolder::DrawModule() { if (Minimized() || IsVisible() == false) return; mStopButton->Draw(); mOnlyPlayWhenPulsedCheckbox->Draw(); } void ChordHolder::Stop(double time) { for (int i = 0; i < 128; ++i) { if (mNotePlaying[i] && !mNoteInputHeld[i]) { PlayNoteOutput(time, i, 0, -1); mNotePlaying[i] = false; } } } void ChordHolder::ButtonClicked(ClickButton* button, double time) { if (button == mStopButton) Stop(time); } void ChordHolder::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { if (mEnabled) { for (int i = 0; i < 128; ++i) mNotePlaying[i] = mNoteInputHeld[i]; } else { Stop(time); } } } void ChordHolder::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) { if (velocity > 0) { bool anyInputNotesHeld = false; for (int i = 0; i < 128; ++i) { if (mNoteInputHeld[i]) anyInputNotesHeld = true; } if (!anyInputNotesHeld) //new input, clear any existing output { for (int i = 0; i < 128; ++i) { if (mNotePlaying[i]) { PlayNoteOutput(time, i, 0, -1); mNotePlaying[i] = false; } } } if (!mOnlyPlayWhenPulsed) { if (!mNotePlaying[pitch]) //don't replay already-sustained notes PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); mNotePlaying[pitch] = true; //stop playing any voices in the chord that aren't being held anymore for (int i = 0; i < 128; ++i) { if (i != pitch && mNotePlaying[i] && !mNoteInputHeld[i]) { PlayNoteOutput(time, i, 0, -1); mNotePlaying[i] = false; } } } } } else { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } mNoteInputHeld[pitch] = velocity > 0; } void ChordHolder::OnPulse(double time, float velocity, int flags) { for (int i = 0; i < 128; ++i) { if (mNotePlaying[i]) { PlayNoteOutput(time, i, 0, -1); mNotePlaying[i] = false; } if (mNoteInputHeld[i]) { PlayNoteOutput(time, i, velocity * 127, -1); mNotePlaying[i] = true; } } } void ChordHolder::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void ChordHolder::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/ChordHolder.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,010
```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 **/ // // ModuleFactory.h // modularSynth // // Created by Ryan Challinor on 1/20/14. // // #pragma once #include "IDrawableModule.h" #include "juce_core/juce_core.h" #include "juce_audio_processors/juce_audio_processors.h" typedef IDrawableModule* (*CreateModuleFn)(void); typedef bool (*CanCreateModuleFn)(void); class ModuleFactory { public: ModuleFactory(); enum class SpawnMethod { Module, EffectChain, Prefab, Plugin, MidiController, Preset }; struct Spawnable { SpawnMethod mSpawnMethod{ SpawnMethod::Module }; std::string mLabel{ "" }; std::string mDecorator{ "" }; std::string mPresetModuleType{ "" }; juce::PluginDescription mPluginDesc{}; static std::string GetPluginLabel(juce::PluginDescription pluginDesc) { std::string pluginType = pluginDesc.pluginFormatName.toLowerCase().toStdString(); if (pluginType == "audiounit") pluginType = "au"; //"audiounit" is too long, shorten it return pluginType; } static bool CompareAlphabetical(Spawnable a, Spawnable b) { juce::String aLower = juce::String(a.mLabel).toLowerCase(); juce::String bLower = juce::String(b.mLabel).toLowerCase(); if (aLower == bLower) return a.mDecorator < b.mDecorator; return aLower < bLower; } }; struct ModuleInfo { CreateModuleFn mCreatorFn{ nullptr }; CanCreateModuleFn mCanCreateFn{ nullptr }; ModuleCategory mCategory{ ModuleCategory::kModuleCategory_Unknown }; bool mIsHidden{ false }; bool mIsExperimental{ false }; bool mCanReceiveAudio{ false }; bool mCanReceiveNotes{ false }; bool mCanReceivePulses{ false }; }; IDrawableModule* MakeModule(std::string type); std::vector<Spawnable> GetSpawnableModules(ModuleCategory moduleCategory); std::vector<Spawnable> GetSpawnableModules(std::string keys, bool continuousString); ModuleCategory GetModuleCategory(std::string typeName); ModuleCategory GetModuleCategory(Spawnable spawnable); ModuleInfo GetModuleInfo(std::string typeName); bool IsExperimental(std::string typeName); static void GetPrefabs(std::vector<Spawnable>& prefabs); static void GetPresets(std::vector<Spawnable>& presets); static std::string FixUpTypeName(std::string typeName); static constexpr const char* kPluginSuffix = "[plugin]"; static constexpr const char* kPrefabSuffix = "[prefab]"; static constexpr const char* kMidiControllerSuffix = "[midicontroller]"; static constexpr const char* kEffectChainSuffix = "[effectchain]"; private: void Register(std::string type, CreateModuleFn creator, CanCreateModuleFn canCreate, ModuleCategory moduleCategory, bool hidden, bool experimental, bool canReceiveAudio, bool canReceiveNotes, bool canReceivePulses); std::map<std::string, ModuleInfo> mFactoryMap; }; ```
/content/code_sandbox/Source/ModuleFactory.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
795
```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 **/ // // NoteSinger.cpp // modularSynth // // Created by Ryan Challinor on 5/23/13. // // #include "NoteSinger.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" NoteSinger::NoteSinger() : IAudioReceiver(gBufferSize) { TheScale->AddListener(this); mWorkBuffer = new float[GetBuffer()->BufferSize()]; Clear(mWorkBuffer, GetBuffer()->BufferSize()); OnScaleChanged(); } void NoteSinger::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void NoteSinger::CreateUIControls() { IDrawableModule::CreateUIControls(); mOctaveSlider = new IntSlider(this, "oct", 35, 32, 60, 15, &mOctave, -2, 2); } NoteSinger::~NoteSinger() { TheTransport->RemoveAudioPoller(this); TheScale->RemoveListener(this); } void NoteSinger::OnTransportAdvanced(float amount) { PROFILER(NoteSinger); if (!mEnabled) return; ComputeSliders(0); SyncInputBuffer(); int pitch = -1; int bestBucket = -1; float bestPeak = -1; for (int i = 0; i < mNumBuckets; ++i) { BufferCopy(mWorkBuffer, GetBuffer()->GetChannel(0), GetBuffer()->BufferSize()); mBands[i].Filter(mWorkBuffer, GetBuffer()->BufferSize()); mPeaks[i].Process(mWorkBuffer, GetBuffer()->BufferSize()); float peak = mPeaks[i].GetPeak(); if (peak > bestPeak) { int numPitchesInScale = TheScale->NumTonesInScale(); if (bestBucket != -1 && peak < 2 * bestPeak && i % numPitchesInScale == bestBucket % numPitchesInScale) continue; //don't let a harmonic beat a fundamental bestBucket = i; bestPeak = peak; } } assert(bestBucket != -1); pitch = GetPitchForBucket(bestBucket) + mOctave * 12; if (pitch != mPitch && bestPeak > .01f) { PlayNoteOutput(gTime, pitch, 80, -1); PlayNoteOutput(gTime, mPitch, 0, -1); mPitch = pitch; } GetBuffer()->Reset(); } void NoteSinger::DrawModule() { if (Minimized() || IsVisible() == false) return; mOctaveSlider->Draw(); for (int i = 0; i < mNumBuckets; ++i) { float x = ofMap(i, 0, mNumBuckets, 0, 100); ofSetColor(255, 0, 255); ofLine(x, 50, x, 50 - ofMap(MIN(mPeaks[i].GetPeak(), 1), 0, 1, 0, 50)); } } void NoteSinger::OnScaleChanged() { mNumBuckets = MIN(TheScale->NumTonesInScale() * 4, NOTESINGER_MAX_BUCKETS); for (int i = 0; i < mNumBuckets; ++i) { int pitch = GetPitchForBucket(i); float f = TheScale->PitchToFreq(pitch); mBands[i].SetFilterType(kFilterType_Bandpass); mBands[i].SetFilterParams(f, 40 + mNumBuckets * 2 - i * 2); mPeaks[i].SetDecayTime(.05f); } } int NoteSinger::GetPitchForBucket(int bucket) { return TheScale->GetPitchFromTone(bucket + TheScale->NumTonesInScale() * 2); } void NoteSinger::ButtonClicked(ClickButton* button, double time) { } void NoteSinger::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { PlayNoteOutput(time, mPitch, 0, -1); mPitch = -1; } } void NoteSinger::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void NoteSinger::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/NoteSinger.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,094
```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 **/ // // MidiDevice.cpp // additiveSynth // // Created by Ryan Challinor on 11/19/12. // // #include "MidiDevice.h" #include "SynthGlobals.h" #include "ModularSynth.h" using namespace juce; MidiDevice::MidiDevice(MidiDeviceListener* listener) : mListener(listener) { } MidiDevice::~MidiDevice() { auto& deviceManager = TheSynth->GetAudioDeviceManager(); deviceManager.removeMidiInputDeviceCallback(mDeviceInInfo.identifier, this); if (mMidiOut.get()) mMidiOut->stopBackgroundThread(); } bool MidiDevice::ConnectInput(const char* name) { DisconnectInput(); bool found = false; auto devices = MidiInput::getAvailableDevices(); for (int i = 0; i < devices.size(); ++i) { if (devices[i].name == name) { mDeviceInInfo = devices[i]; found = true; break; } } if (!found) { mIsInputEnabled = false; return false; } auto& deviceManager = TheSynth->GetAudioDeviceManager(); deviceManager.setMidiInputDeviceEnabled(mDeviceInInfo.identifier, true); deviceManager.addMidiInputDeviceCallback(mDeviceInInfo.identifier, this); mIsInputEnabled = deviceManager.isMidiInputDeviceEnabled(mDeviceInInfo.identifier); TheSynth->AddMidiDevice(this); //TODO(Ryan) need better place for this, but constructor is too early return mIsInputEnabled; } void MidiDevice::ConnectInput(int index) { ConnectInput(MidiInput::getAvailableDevices()[index].name.toRawUTF8()); } bool MidiDevice::ConnectOutput(const char* name, int channel /*= 1*/) { DisconnectOutput(); bool found = false; auto devices = MidiOutput::getAvailableDevices(); for (int i = 0; i < devices.size(); ++i) { if (devices[i].name == name) { found = ConnectOutput(i, channel); break; } } if (!found) { TheSynth->LogEvent("Failed to connect to Midi Output: " + std::string(name), kLogEventType_Error); DisconnectOutput(); } return found; } bool MidiDevice::ConnectOutput(int index, int channel /*= 1*/) { mMidiOut.reset(); mMidiOut = MidiOutput::openDevice(MidiOutput::getAvailableDevices()[index].identifier); if (mMidiOut) { mMidiOut->startBackgroundThread(); mDeviceOutInfo = mMidiOut->getDeviceInfo(); assert(channel > 0 && channel <= 16); mOutputChannel = channel; return true; } return false; } void MidiDevice::DisconnectInput() { auto& deviceManager = TheSynth->GetAudioDeviceManager(); if (mDeviceInInfo.identifier.isNotEmpty()) { deviceManager.setMidiInputDeviceEnabled(mDeviceInInfo.identifier, false); deviceManager.removeMidiInputDeviceCallback(mDeviceOutInfo.identifier, this); } } void MidiDevice::DisconnectOutput() { if (mMidiOut) mMidiOut->stopBackgroundThread(); mMidiOut.reset(); mMidiOut = nullptr; mDeviceOutInfo.name = ""; mDeviceOutInfo.identifier = ""; } bool MidiDevice::Reconnect() { bool ret = false; if (mDeviceInInfo.identifier.isNotEmpty()) ret = ConnectInput(mDeviceInInfo.name.toRawUTF8()); if (mDeviceOutInfo.identifier.isNotEmpty()) ConnectOutput(mDeviceOutInfo.name.toRawUTF8()); return ret; } bool MidiDevice::IsInputConnected(bool immediate) { static juce::Array<juce::MidiDeviceInfo> sConnectedInputDevices; static double sLastUpdatedListTime = -9999; if (sLastUpdatedListTime + 5000 < gTime || immediate) //refresh every 5 seconds (getAvailableDevices() is slow on windows) { sConnectedInputDevices = MidiInput::getAvailableDevices(); sLastUpdatedListTime = gTime; } for (auto& device : sConnectedInputDevices) { if (device.identifier == mDeviceInInfo.identifier) return true; } return false; } std::vector<std::string> MidiDevice::GetPortList(bool forInput) { std::vector<std::string> portList; if (forInput) { for (auto& device : MidiInput::getAvailableDevices()) portList.push_back(device.name.toStdString()); } else { for (auto& device : MidiOutput::getAvailableDevices()) portList.push_back(device.name.toStdString()); } return portList; } void MidiDevice::SendNote(double time, int pitch, int velocity, bool forceNoteOn, int channel) { if (mMidiOut) { if (channel == -1) channel = mOutputChannel; int sampleNumber = (time - gTime) * gSampleRateMs; juce::MidiBuffer midiBuffer; if (velocity > 0 || forceNoteOn) midiBuffer.addEvent(MidiMessage::noteOn(channel, pitch, (uint8)velocity), sampleNumber); else midiBuffer.addEvent(MidiMessage::noteOff(channel, pitch), sampleNumber); mMidiOut->sendBlockOfMessages(midiBuffer, Time::getMillisecondCounter(), gSampleRate); } } void MidiDevice::SendCC(int ctl, int value, int channel /* = -1*/) { if (mMidiOut) { if (channel == -1) channel = mOutputChannel; mMidiOut->sendMessageNow(MidiMessage::controllerEvent(channel, ctl, value)); } } void MidiDevice::SendAftertouch(int pressure, int channel /* = -1*/) { if (mMidiOut) { if (channel == -1) channel = mOutputChannel; //TODO_PORT(Ryan) pitch number? mMidiOut->sendMessageNow(MidiMessage::aftertouchChange(channel, 0, pressure)); } } void MidiDevice::SendProgramChange(int program, int channel /* = -1*/) { if (mMidiOut) { if (channel == -1) channel = mOutputChannel; mMidiOut->sendMessageNow(MidiMessage::programChange(channel, program)); } } void MidiDevice::SendPitchBend(int bend, int channel /* = -1*/) { if (mMidiOut) { if (channel == -1) channel = mOutputChannel; mMidiOut->sendMessageNow(MidiMessage::pitchWheel(channel, bend)); } } void MidiDevice::SendSysEx(std::string data) { if (mMidiOut) { mMidiOut->sendMessageNow(MidiMessage::createSysExMessage(data.c_str(), data.length())); } } void MidiDevice::SendData(unsigned char a, unsigned char b, unsigned char c) { if (mMidiOut) { mMidiOut->sendMessageNow(MidiMessage(a, b, c)); } } void MidiDevice::SendMessage(double time, juce::MidiMessage message) { if (mMidiOut) { int sampleNumber = (time - gTime) * gSampleRateMs; juce::MidiBuffer midiBuffer; midiBuffer.addEvent(message, sampleNumber); mMidiOut->sendBlockOfMessages(midiBuffer, Time::getMillisecondCounter(), gSampleRate); } } void MidiDevice::handleIncomingMidiMessage(MidiInput* source, const MidiMessage& message) { if (TheSynth->IsReady() == false) return; if (mListener) { MidiDevice::SendMidiMessage(mListener, mDeviceInInfo.name.toRawUTF8(), message); if (gPrintMidiInput) ofLog() << mDeviceInInfo.name << " " << message.getDescription(); } } //static void MidiDevice::SendMidiMessage(MidiDeviceListener* listener, const char* deviceName, const MidiMessage& message) { listener->OnMidi(message); if (message.isNoteOnOrOff()) { MidiNote note; note.mDeviceName = deviceName; note.mTimestampMs = message.getTimeStamp() * 1000; //message.getTimeStamp() is equivalent to Time::getMillisecondCounter() / 1000.0 (see juce_MidiDevices.h) note.mPitch = message.getNoteNumber(); if (message.isNoteOn()) note.mVelocity = message.getVelocity(); else note.mVelocity = 0; note.mChannel = message.getChannel(); listener->OnMidiNote(note); } if (message.isController()) { MidiControl control; control.mDeviceName = deviceName; control.mControl = message.getControllerNumber(); control.mValue = message.getControllerValue(); control.mChannel = message.getChannel(); listener->OnMidiControl(control); } if (message.isProgramChange()) { MidiProgramChange program; program.mDeviceName = deviceName; program.mProgram = message.getProgramChangeNumber(); program.mChannel = message.getChannel(); listener->OnMidiProgramChange(program); } if (message.isPitchWheel()) { MidiPitchBend pitchBend; pitchBend.mDeviceName = deviceName; pitchBend.mValue = message.getPitchWheelValue(); pitchBend.mChannel = message.getChannel(); listener->OnMidiPitchBend(pitchBend); } if (message.isChannelPressure()) { MidiPressure pressure; pressure.mDeviceName = deviceName; //TODO_PORT(Ryan) - is this correct for the pitch? does pitch have meaning for channel pressure messages? pressure.mPitch = message.getNoteNumber(); pressure.mPressure = message.getChannelPressureValue(); pressure.mChannel = message.getChannel(); listener->OnMidiPressure(pressure); } if (message.isAftertouch()) { MidiPressure pressure; pressure.mDeviceName = deviceName; pressure.mPitch = -1; pressure.mPressure = message.getAfterTouchValue(); pressure.mChannel = message.getChannel(); listener->OnMidiPressure(pressure); } /*if (message.isMidiClock()) { static double sLastTime = -1; static std::array<float, 40> sTempos; static int sTempoIdx = 0; if (sLastTime > 0) { double deltaSeconds = (message.getTimeStamp() - sLastTime); double pulsesPerSecond = 1 / deltaSeconds; double beatsPerSecond = pulsesPerSecond / 24; double instantTempo = beatsPerSecond * 60; sTempos[sTempoIdx] = instantTempo; sTempoIdx = (sTempoIdx + 1) % sTempos.size(); double avgTempo = 0; for (auto& tempo : sTempos) avgTempo += tempo; avgTempo /= sTempos.size(); if (sTempoIdx == 0) ofLog() << avgTempo; } sLastTime = message.getTimeStamp(); } if (message.isMidiStart()) { ofLog() << "midi start"; } if (message.isMidiStop()) { ofLog() << "midi stop"; } if (message.isMidiContinue()) { ofLog() << "midi continue"; } if (message.isSongPositionPointer()) { ofLog() << "midi position pointer " << ofToString(message.getSongPositionPointerMidiBeat()); } if (message.isQuarterFrame()) { ofLog() << "midi quarter frame " << ofToString(message.getQuarterFrameValue()) << " " << ofToString(message.getQuarterFrameSequenceNumber()); }*/ } ```
/content/code_sandbox/Source/MidiDevice.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,734
```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 **/ /* ============================================================================== RadioSequencer.cpp Created: 10 Jun 2017 4:53:15pm Author: Ryan Challinor ============================================================================== */ #include "RadioSequencer.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "UIControlMacros.h" #include "MathUtils.h" RadioSequencer::RadioSequencer() { mTransportPriority = ITimeListener::kTransportPriorityEarly; } void RadioSequencer::Init() { IDrawableModule::Init(); mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), false); } RadioSequencer::~RadioSequencer() { TheTransport->RemoveListener(this); } void RadioSequencer::CreateUIControls() { IDrawableModule::CreateUIControls(); int width, height; UIBLOCK(3, 3, 200); INTSLIDER(mLengthSlider, "length", &mLength, 1, 16); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 40); UIBLOCK_SHIFTRIGHT(); UICONTROL_CUSTOM(mGridControlTarget, new GridControlTarget(UICONTROL_BASICS("grid"))); ENDUIBLOCK(width, height); mGrid = new UIGrid("uigrid", 5, 25, mGridControlTarget->GetRect().getMaxX() - 6, 170, mLength, 8, this); mGrid->SetHighlightCol(gTime, -1); mGrid->SetSingleColumnMode(true); mGrid->SetMajorColSize(4); mGrid->SetListener(this); mIntervalSelector->AddLabel("8", kInterval_8); mIntervalSelector->AddLabel("4", kInterval_4); 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); SyncControlCablesToGrid(); } void RadioSequencer::Poll() { UpdateGridLights(); } void RadioSequencer::OnControllerPageSelected() { UpdateGridLights(); } void RadioSequencer::OnGridButton(int x, int y, float velocity, IGridController* grid) { if (velocity > 0) { float currentVal = mGrid->GetVal(x, y); mGrid->SetVal(x, y, currentVal > 0 ? 0 : 1); } UpdateGridLights(); } void RadioSequencer::UpdateGridLights() { bool blinkOn = true; TransportListenerInfo transportInfo(this, kInterval_16n, OffsetInfo(0, false), false); if (TheTransport->GetQuantized(gTime, &transportInfo) % 2 == 1) blinkOn = false; if (mGridControlTarget->GetGridController()) { for (int row = 0; row < mGrid->GetRows(); ++row) { for (int col = 0; col < mGrid->GetCols(); ++col) { if (mGrid->GetVal(col, row) == 1) mGridControlTarget->GetGridController()->SetLight(col, row, GridColor::kGridColor1Bright); else if (col == mGrid->GetHighlightCol(NextBufferTime(true))) mGridControlTarget->GetGridController()->SetLight(col, row, blinkOn ? GridColor::kGridColor1Dim : GridColor::kGridColorOff); else mGridControlTarget->GetGridController()->SetLight(col, row, GridColor::kGridColorOff); } } } } void RadioSequencer::Step(double time, int pulseFlags) { int length = mLength; if (length <= 0) length = 1; int direction = 1; if (pulseFlags & kPulseFlag_Backward) direction = -1; if (pulseFlags & kPulseFlag_Repeat) direction = 0; mStep = (mStep + direction + length) % length; if (pulseFlags & kPulseFlag_Reset) mStep = 0; else if (pulseFlags & kPulseFlag_Random) mStep = gRandom() % length; if (!mHasExternalPulseSource || (pulseFlags & kPulseFlag_SyncToTransport)) { mStep = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo, length); } if (pulseFlags & kPulseFlag_Align) { int stepsPerMeasure = TheTransport->GetStepsPerMeasure(this); int numMeasures = ceil(float(length) / stepsPerMeasure); int measure = TheTransport->GetMeasure(time) % numMeasures; int step = ((TheTransport->GetQuantized(time, mTransportListenerInfo) % stepsPerMeasure) + measure * stepsPerMeasure) % length; mStep = step; } if (!mEnabled) return; mGrid->SetHighlightCol(time, mStep); std::vector<IUIControl*> controlsToEnable; for (int i = 0; i < mControlCables.size(); ++i) { for (auto* cable : mControlCables[i]->GetPatchCables()) { IUIControl* uicontrol = dynamic_cast<IUIControl*>(cable->GetTarget()); if (uicontrol) { if (mGrid->GetVal(mStep, i) > 0) controlsToEnable.push_back(uicontrol); else uicontrol->SetValue(0, time); } } } for (auto* control : controlsToEnable) control->SetValue(1, time); UpdateGridLights(); } void RadioSequencer::OnPulse(double time, float velocity, int flags) { mHasExternalPulseSource = true; Step(time, flags); } void RadioSequencer::OnTimeEvent(double time) { if (!mHasExternalPulseSource) Step(time, 0); } void RadioSequencer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (velocity > 0) { mHasExternalPulseSource = true; mStep = pitch % std::max(1, mLength); Step(time, kPulseFlag_Repeat); } } void RadioSequencer::DrawModule() { if (Minimized() || IsVisible() == false) return; mGrid->Draw(); mIntervalSelector->Draw(); mLengthSlider->Draw(); mGridControlTarget->Draw(); for (int i = 0; i < mControlCables.size(); ++i) { mControlCables[i]->SetManualPosition(GetRect(true).width, mGrid->GetPosition(true).y + (mGrid->GetHeight() / mGrid->GetRows()) * (i + .5f)); } } void RadioSequencer::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); mGrid->TestClick(x, y, right); } void RadioSequencer::MouseReleased() { IDrawableModule::MouseReleased(); mGrid->MouseReleased(); } bool RadioSequencer::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); mGrid->NotifyMouseMoved(x, y); return false; } void RadioSequencer::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) { if (grid == mGrid) { } } void RadioSequencer::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { } void RadioSequencer::SyncControlCablesToGrid() { if (mGrid->GetRows() == mControlCables.size()) return; //nothing to do if (mGrid->GetRows() > mControlCables.size()) { int oldSize = (int)mControlCables.size(); mControlCables.resize(mGrid->GetRows()); for (int i = oldSize; i < mControlCables.size(); ++i) { mControlCables[i] = new PatchCableSource(this, kConnectionType_ValueSetter); mControlCables[i]->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight); //mControlCables[i]->SetColor(GetRowColor(i)); AddPatchCableSource(mControlCables[i]); } } else { for (int i = mGrid->GetRows(); i < mControlCables.size(); ++i) RemovePatchCableSource(mControlCables[i]); mControlCables.resize(mGrid->GetRows()); } } void RadioSequencer::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { if (!mEnabled && mDisableAllWhenDisabled) { for (int i = 0; i < mControlCables.size(); ++i) { for (auto* cable : mControlCables[i]->GetPatchCables()) { IUIControl* uicontrol = dynamic_cast<IUIControl*>(cable->GetTarget()); if (uicontrol) uicontrol->SetValue(0, time); } } } } } void RadioSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mInterval; } } void RadioSequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mLengthSlider) { mGrid->SetGrid(mLength, mGrid->GetRows()); 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) { for (int row = 0; row < mGrid->GetRows(); ++row) mGrid->SetVal(i, row, mGrid->GetVal(i % oldLengthPow2, row)); } } } } namespace { const float extraW = 10; const float extraH = 30; } void RadioSequencer::GetModuleDimensions(float& width, float& height) { width = mGrid->GetWidth() + extraW; height = mGrid->GetHeight() + extraH; } void RadioSequencer::Resize(float w, float h) { w = MAX(w - extraW, 200); h = MAX(h - extraH, 170); SetGridSize(w, h); } void RadioSequencer::SetGridSize(float w, float h) { mGrid->SetDimensions(w, h); } void RadioSequencer::SaveLayout(ofxJSONElement& moduleInfo) { } void RadioSequencer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadBool("one_per_column_mode", moduleInfo, true); mModuleSaveData.LoadInt("num_rows", moduleInfo, 8, 1, 16, false); mModuleSaveData.LoadBool("disable_all_when_disabled", moduleInfo, true); SetUpFromSaveData(); } void RadioSequencer::SetUpFromSaveData() { mGrid->SetSingleColumnMode(mModuleSaveData.GetBool("one_per_column_mode")); mGrid->SetGrid(mLength, mModuleSaveData.GetInt("num_rows")); mDisableAllWhenDisabled = mModuleSaveData.GetBool("disable_all_when_disabled"); SyncControlCablesToGrid(); } void RadioSequencer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mGrid->SaveState(out); out << mGrid->GetWidth(); out << mGrid->GetHeight(); } void RadioSequencer::LoadState(FileStreamIn& in, int rev) { mLoadRev = rev; if (ModularSynth::sLoadingFileSaveStateRev == 422) { in >> mLoadRev; LoadStateValidate(mLoadRev <= GetModuleSaveStateRev()); } IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev <= 421) { in >> mLoadRev; LoadStateValidate(mLoadRev <= GetModuleSaveStateRev()); } if (rev <= 1) { int size; in >> size; mControlCables.resize(size); for (auto cable : mControlCables) { std::string path; in >> path; } } mGrid->LoadState(in); if (mLoadRev >= 1) { float width, height; in >> width; in >> height; mGrid->SetDimensions(width, height); } if (mLoadRev == 0) { //port old data float len = 0; if (mOldLengthStr == "4") len = 4; if (mOldLengthStr == "6") len = 6; if (mOldLengthStr == "8") len = 8; if (mOldLengthStr == "16") len = 16; if (mOldLengthStr == "32") len = 32; if (mOldLengthStr == "64") len = 64; if (mOldLengthStr == "128") len = 128; mLength = int(len * TheTransport->CountInStandardMeasure(mInterval)); int min, max; mLengthSlider->GetRange(min, max); if (mLength > max) mLengthSlider->SetExtents(min, mLength); } } bool RadioSequencer::LoadOldControl(FileStreamIn& in, std::string& oldName) { if (mLoadRev < 1) { if (oldName == "length") { //load dropdown string int dropdownRev; in >> dropdownRev; in >> mOldLengthStr; return true; } } return false; } ```
/content/code_sandbox/Source/RadioSequencer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
3,492
```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 **/ /* ============================================================================== AudioLevelToCV.cpp Created: 9 Oct 2018 10:26:30pm Author: Ryan Challinor ============================================================================== */ #include "AudioLevelToCV.h" #include "Profiler.h" #include "ModularSynth.h" #include "PatchCableSource.h" AudioLevelToCV::AudioLevelToCV() : IAudioProcessor(gBufferSize) { mModulationBuffer = new float[gBufferSize]; } void AudioLevelToCV::CreateUIControls() { IDrawableModule::CreateUIControls(); mGainSlider = new FloatSlider(this, "gain", 3, 2, 100, 15, &mGain, 1, 100); mAttackSlider = new FloatSlider(this, "attack", mGainSlider, kAnchor_Below, 100, 15, &mAttack, .01f, 1000); mReleaseSlider = new FloatSlider(this, "release", mAttackSlider, kAnchor_Below, 100, 15, &mRelease, .01f, 1000); mMinSlider = new FloatSlider(this, "min", mReleaseSlider, kAnchor_Below, 100, 15, &mDummyMin, 0, 1); mMaxSlider = new FloatSlider(this, "max", mMinSlider, kAnchor_Below, 100, 15, &mDummyMax, 0, 1); mGainSlider->SetMode(FloatSlider::kSquare); mAttackSlider->SetMode(FloatSlider::kSquare); mReleaseSlider->SetMode(FloatSlider::kSquare); //update mAttackFactor and mReleaseFactor FloatSliderUpdated(mAttackSlider, 0, gTime); FloatSliderUpdated(mReleaseSlider, 0, gTime); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } AudioLevelToCV::~AudioLevelToCV() { delete[] mModulationBuffer; } void AudioLevelToCV::DrawModule() { if (Minimized() || IsVisible() == false) return; mGainSlider->Draw(); mAttackSlider->Draw(); mReleaseSlider->Draw(); mMinSlider->Draw(); mMaxSlider->Draw(); ofPushStyle(); ofSetColor(0, 255, 0, gModuleDrawAlpha); ofBeginShape(); float x, y; float w, h; mGainSlider->GetPosition(x, y, K(local)); mGainSlider->GetDimensions(w, h); for (int i = 0; i < gBufferSize; ++i) { ofVertex(ofMap(mModulationBuffer[i], 0, 1, x, x + w, K(clamp)), ofMap(i, 0, gBufferSize, y, y + h), K(clamp)); } ofEndShape(); ofPopStyle(); } void AudioLevelToCV::Process(double time) { PROFILER(AudioLevelToCV); if (!mEnabled) return; ComputeSliders(0); SyncBuffers(); assert(GetBuffer()->BufferSize()); Clear(gWorkBuffer, gBufferSize); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) Add(gWorkBuffer, GetBuffer()->GetChannel(ch), gBufferSize); for (int i = 0; i < gBufferSize; ++i) { float sample = fabsf(gWorkBuffer[i]); if (sample > mVal) mVal = mAttackFactor * (mVal - sample) + sample; else mVal = mReleaseFactor * (mVal - sample) + sample; mModulationBuffer[i] = mVal * mGain; } GetBuffer()->Reset(); } void AudioLevelToCV::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); } float AudioLevelToCV::Value(int samplesIn) { return ofMap(mModulationBuffer[samplesIn], 0, 1, GetMin(), GetMax(), K(clamp)); } void AudioLevelToCV::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mAttackSlider) mAttackFactor = powf(.01f, 1.0f / (mAttack * gSampleRateMs)); if (slider == mReleaseSlider) mReleaseFactor = powf(.01f, 1.0f / (mRelease * gSampleRateMs)); } void AudioLevelToCV::SaveLayout(ofxJSONElement& moduleInfo) { } void AudioLevelToCV::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void AudioLevelToCV::SetUpFromSaveData() { } void AudioLevelToCV::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); } void AudioLevelToCV::LoadState(FileStreamIn& in, int rev) { if (rev < 1) { // Temporary additional cable source mTargetCable = new PatchCableSource(this, kConnectionType_Audio); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } IDrawableModule::LoadState(in, rev); if (rev < 1) { 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()); } ```
/content/code_sandbox/Source/AudioLevelToCV.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,399
```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 **/ // // Capo.h // modularSynth // // Created by Ryan Challinor on 1/5/14. // // #pragma once #include <iostream> #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Checkbox.h" #include "Slider.h" class Capo : public NoteEffectBase, public IDrawableModule, public IIntSliderListener { public: Capo(); static IDrawableModule* Create() { return new Capo(); } 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; //IIntSliderListener 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: struct NoteInfo { bool mOn{ false }; int mVelocity{ 0 }; int mVoiceIdx{ -1 }; int mOutputPitch{ 0 }; }; int TransformPitch(int pitch); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } float mWidth{ 200 }; float mHeight{ 20 }; int mCapo{ 0 }; IntSlider* mCapoSlider{ nullptr }; std::array<NoteInfo, 128> mInputNotes; Checkbox* mRetriggerCheckbox{ nullptr }; bool mRetrigger{ false }; Checkbox* mDiatonicCheckbox{ nullptr }; bool mDiatonic{ false }; }; ```
/content/code_sandbox/Source/Capo.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
567
```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 **/ // // FreqDelay.cpp // modularSynth // // Created by Ryan Challinor on 5/10/13. // // #include "FreqDelay.h" #include "ModularSynth.h" #include "Profiler.h" #include "Scale.h" FreqDelay::FreqDelay() : IAudioProcessor(gBufferSize) , mDryBuffer(gBufferSize) { AddChild(&mDelayEffect); mDelayEffect.SetPosition(5, 30); mDelayEffect.SetEnabled(true); mDelayEffect.SetDelay(15); } void FreqDelay::CreateUIControls() { IDrawableModule::CreateUIControls(); mDryWetSlider = new FloatSlider(this, "dry/wet", 7, 2, 100, 15, &mDryWet, 0, 1); mDelayEffect.CreateUIControls(); mDelayEffect.SetShortMode(true); } FreqDelay::~FreqDelay() { } void FreqDelay::Process(double time) { PROFILER(FreqDelay); IAudioReceiver* target = GetTarget(); if (target == nullptr) return; SyncBuffers(); mDryBuffer.SetNumActiveChannels(GetBuffer()->NumActiveChannels()); int bufferSize = GetBuffer()->BufferSize(); mDryBuffer.CopyFrom(GetBuffer()); mDelayEffect.ProcessAudio(time, GetBuffer()); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Mult(mDryBuffer.GetChannel(ch), (1 - mDryWet), bufferSize); Mult(GetBuffer()->GetChannel(ch), mDryWet, bufferSize); Add(GetBuffer()->GetChannel(ch), mDryBuffer.GetChannel(ch), bufferSize); Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), bufferSize); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), bufferSize, ch); } GetBuffer()->Reset(); } void FreqDelay::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (velocity > 0) { float freq = TheScale->PitchToFreq(pitch); float ms = 1000 / freq; mDelayEffect.SetDelay(ms); } } void FreqDelay::DrawModule() { if (Minimized() || IsVisible() == false) return; mDelayEffect.Draw(); mDryWetSlider->Draw(); } void FreqDelay::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void FreqDelay::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void FreqDelay::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/FreqDelay.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
705
```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 **/ /* ============================================================================== NoteExpressionRouter.cpp Created: 15 Oct 2021 Author: Paul Walker @baconpaul ============================================================================== */ #include "NoteExpressionRouter.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "UIControlMacros.h" NoteExpressionRouter::NoteExpressionRouter() { mSymbolTable.add_variable("p", mSTNote); mSymbolTable.add_variable("v", mSTVelocity); for (auto i = 0; i < kMaxDestinations; ++i) { mExpressions[i].register_symbol_table(mSymbolTable); auto p = exprtk::parser<float>(); p.compile("1", mExpressions[i]); } } void NoteExpressionRouter::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); for (int i = 0; i < kMaxDestinations; ++i) { TEXTENTRY(mExpressionWidget[i], ("expression" + ofToString(i)).c_str(), 30, mExpressionText[i]); mDestinationCables[i] = new AdditionalNoteCable(); mDestinationCables[i]->SetPatchCableSource(new PatchCableSource(this, kConnectionType_Note)); mDestinationCables[i]->GetPatchCableSource()->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight); AddPatchCableSource(mDestinationCables[i]->GetPatchCableSource()); ofRectangle rect = mExpressionWidget[i]->GetRect(true); mDestinationCables[i]->GetPatchCableSource()->SetManualPosition(rect.getMaxX() + 10, rect.y + rect.height / 2); } ENDUIBLOCK(mWidth, mHeight); mWidth += 20; GetPatchCableSource()->SetEnabled(false); } void NoteExpressionRouter::DrawModule() { if (Minimized() || IsVisible() == false) return; for (int i = 0; i < kMaxDestinations; ++i) mExpressionWidget[i]->Draw(); } void NoteExpressionRouter::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { mSTNote = pitch; mSTVelocity = velocity; for (auto i = 0; i < kMaxDestinations; ++i) { auto rt = mExpressions[i].value(); if (rt != 0) { mDestinationCables[i]->PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } } } void NoteExpressionRouter::SendCC(int control, int value, int voiceIdx) { SendCCOutput(control, value, voiceIdx); } void NoteExpressionRouter::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void NoteExpressionRouter::SetUpFromSaveData() { } void NoteExpressionRouter::SaveLayout(ofxJSONElement& moduleInfo) { } void NoteExpressionRouter::TextEntryComplete(TextEntry* entry) { if (strlen(entry->GetText()) == 0) return; for (auto i = 0; i < kMaxDestinations; ++i) { if (entry == mExpressionWidget[i]) { auto p = exprtk::parser<float>(); if (!p.compile(entry->GetText(), mExpressions[i])) { ofLog() << "Error parsing expression '" << entry->GetText() << "' " << p.error(); } } } } ```
/content/code_sandbox/Source/NoteExpressionRouter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
868
```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 **/ // // AbletonLink.cpp // // Created by Ryan Challinor on 12/9/21. // // #include "AbletonLink.h" #include "OpenFrameworksPort.h" #include "Transport.h" #include "ModularSynth.h" #include "UIControlMacros.h" #include "juce_audio_devices/juce_audio_devices.h" #include "ableton/Link.hpp" #include "ableton/link/Timeline.hpp" #include "ableton/link/HostTimeFilter.hpp" static ableton::link::HostTimeFilter<ableton::link::platform::Clock> sHostTimeFilter; AbletonLink::AbletonLink() { sHostTimeFilter.reset(); mNumPeers = 0; mTempo = TheTransport->GetTempo(); mLink = std::make_unique<ableton::Link>(mTempo); mLink->enable(true); mLink->setNumPeersCallback([this](std::size_t p) { mNumPeers = p; }); mLink->setTempoCallback([this](const double bpm) { if (mEnabled) TheTransport->SetTempo(bpm); mTempo = bpm; }); } void AbletonLink::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } AbletonLink::~AbletonLink() { TheTransport->RemoveAudioPoller(this); } void AbletonLink::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mOffsetMsSlider, "offset ms", &mOffsetMs, -1000, 1000); BUTTON(mResetButton, "reset next downbeat"); ENDUIBLOCK(mWidth, mHeight); mHeight = 80; } void AbletonLink::Poll() { } void AbletonLink::OnTransportAdvanced(float amount) { if (mEnabled && mLink.get() != nullptr) { if (mTempo != TheTransport->GetTempo()) { mTempo = TheTransport->GetTempo(); auto sessionState = mLink->captureAudioSessionState(); sessionState.setTempo(mTempo, mLink->clock().micros()); mLink->commitAudioSessionState(sessionState); } auto& deviceManager = TheSynth->GetAudioDeviceManager(); if (deviceManager.getCurrentAudioDevice() != nullptr) { auto sampleRate = deviceManager.getCurrentAudioDevice()->getCurrentSampleRate(); auto bufferSize = deviceManager.getCurrentAudioDevice()->getCurrentBufferSizeSamples(); const auto hostTimeUs = sHostTimeFilter.sampleTimeToHostTime(mSampleTime); const auto outputLatencyUs = std::chrono::microseconds{ std::llround(1.0e6 * bufferSize / sampleRate) }; auto offsetUs = std::chrono::microseconds{ llround(mOffsetMs * 1000) }; auto adjustedTimeUs = hostTimeUs + outputLatencyUs + offsetUs; auto sessionState = mLink->captureAudioSessionState(); double quantum = TheTransport->GetTimeSigTop(); mLastReceivedBeat = sessionState.beatAtTime(adjustedTimeUs, quantum); double measureTime = mLastReceivedBeat / quantum; double localMeasureTime = TheTransport->GetMeasureTime(gTime); double difference = measureTime - localMeasureTime; if (abs(difference) > .01f) { //too far off, correct TheTransport->SetMeasureTime(measureTime); ofLog() << "correcting transport position for ableton link"; } // Timeline modifications are complete, commit the results //mLink->commitAudioSessionState(sessionState); mSampleTime += gBufferSize; } } } void AbletonLink::DrawModule() { if (Minimized() || IsVisible() == false) return; mOffsetMsSlider->Draw(); mResetButton->Draw(); DrawTextNormal("peers: " + ofToString(mNumPeers) + "\ntempo: " + ofToString(mTempo) + "\nbeat: " + ofToString(mLastReceivedBeat), 3, 48); } void AbletonLink::CheckboxUpdated(Checkbox* checkbox, double time) { } void AbletonLink::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void AbletonLink::ButtonClicked(ClickButton* button, double time) { if (button == mResetButton) { auto sessionState = mLink->captureAudioSessionState(); double quantum = TheTransport->GetTimeSigTop(); sessionState.requestBeatAtTime(0, mLink->clock().micros(), quantum); mLink->commitAudioSessionState(sessionState); } } ```
/content/code_sandbox/Source/AbletonLink.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,133
```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 **/ /* ============================================================================== PitchPanner.cpp Created: 25 Mar 2018 9:57:24am Author: Ryan Challinor ============================================================================== */ #include "PitchPanner.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" PitchPanner::PitchPanner() : mPitchLeft(36) , mPitchLeftSlider(nullptr) , mPitchRight(96) , mPitchRightSlider(nullptr) { } void PitchPanner::CreateUIControls() { IDrawableModule::CreateUIControls(); mPitchLeftSlider = new IntSlider(this, "left", 4, 2, 100, 15, &mPitchLeft, 0, 127); mPitchRightSlider = new IntSlider(this, "right", mPitchLeftSlider, kAnchor_Below, 100, 15, &mPitchRight, 0, 127); } void PitchPanner::DrawModule() { if (Minimized() || IsVisible() == false) return; mPitchLeftSlider->Draw(); mPitchRightSlider->Draw(); } void PitchPanner::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) modulation.pan = ofMap(pitch, mPitchLeft, mPitchRight, -1, 1); PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void PitchPanner::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void PitchPanner::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/PitchPanner.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
474
```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 **/ // // VinylTempoControl.cpp // Bespoke // // Created by Ryan Challinor on 12/18/14. // // #include "VinylTempoControl.h" #include "OpenFrameworksPort.h" #include "DrumPlayer.h" #include "ModularSynth.h" #include "Profiler.h" VinylTempoControl* TheVinylTempoControl = nullptr; VinylTempoControl::VinylTempoControl() : IAudioProcessor(gBufferSize) , mVinylProcessor(gSampleRate) { //mModulationBuffer = new float[gBufferSize]; } VinylTempoControl::~VinylTempoControl() { //delete[] mModulationBuffer; } void VinylTempoControl::CreateUIControls() { IDrawableModule::CreateUIControls(); mUseVinylControlCheckbox = new Checkbox(this, "control", 4, 2, &mUseVinylControl); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } void VinylTempoControl::DrawModule() { if (Minimized() || IsVisible() == false) return; mUseVinylControlCheckbox->Draw(); if (CanStartVinylControl()) DrawTextNormal(ofToString(mVinylProcessor.GetPitch(), 2), 60, 14); } void VinylTempoControl::Process(double time) { PROFILER(VinylTempoControl); if (!mEnabled) return; ComputeSliders(0); SyncBuffers(); assert(GetBuffer()->BufferSize()); if (GetBuffer()->NumActiveChannels() >= 2) { mVinylProcessor.Process(GetBuffer()->GetChannel(0), GetBuffer()->GetChannel(1), gBufferSize); if (mUseVinylControl) { float speed = mVinylProcessor.GetPitch() / mReferencePitch; if (speed == 0 || mVinylProcessor.GetStopped()) speed = .0001f; mSpeed = speed; } else { mReferencePitch = mVinylProcessor.GetPitch(); } } GetBuffer()->Reset(); } void VinylTempoControl::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); } float VinylTempoControl::Value(int samplesIn) { //return mModulationBuffer[samplesIn]; return mSpeed; } bool VinylTempoControl::CanStartVinylControl() { return !mVinylProcessor.GetStopped() && fabsf(mVinylProcessor.GetPitch()) > .001f; } void VinylTempoControl::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mUseVinylControlCheckbox) { if (!CanStartVinylControl()) mUseVinylControl = false; } } void VinylTempoControl::SaveLayout(ofxJSONElement& moduleInfo) { } void VinylTempoControl::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void VinylTempoControl::SetUpFromSaveData() { } void VinylTempoControl::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); } void VinylTempoControl::LoadState(FileStreamIn& in, int rev) { if (rev < 1) { // Temporary additional cable source mTargetCable = new PatchCableSource(this, kConnectionType_Audio); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } IDrawableModule::LoadState(in, rev); if (rev < 1) { 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()); } //////////////////////////////////////////////////////////////////////////////// VinylProcessor::VinylProcessor(int sampleRate) : mSampleRate(sampleRate) { struct timecode_def* def; def = timecoder_find_definition("serato_2a"); assert(def != NULL); timecoder_init(&mTimecoder, def, 1.0, gSampleRate, false); } VinylProcessor::~VinylProcessor() { timecoder_clear(&mTimecoder); timecoder_free_lookup(); } //@TODO(Noxy): Warning C6262 Function uses '16448' bytes of stack : exceeds / analyze : stacksize '16384'. Consider moving some data to heap. void VinylProcessor::Process(float* left, float* right, int numSamples) { float* in[2]; in[0] = left; in[1] = right; const float kConvert = (float)(1 << 15); signed short data[8196]; for (int n = 0; n < numSamples; n++) { for (int ch = 0; ch < 2; ch++) data[n * 2 + ch] = (signed short)(kConvert * (float)in[ch][n]); } timecoder_submit(&mTimecoder, data, numSamples); mPitch = timecoder_get_pitch(&mTimecoder); } ```
/content/code_sandbox/Source/VinylTempoControl.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,306
```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 **/ // // PitchDetector.cpp // modularSynth // // Created by Ryan Challinor on 3/16/14. // // #include "PitchDetector.h" #include "FFT.h" #include "SynthGlobals.h" #define L2SC (float)3.32192809488736218171 PitchDetector::PitchDetector() { mfs = gSampleRate; mcbsize = 2048; mcorrsize = mcbsize / 2 + 1; mpmax = 1 / (float)70; // max and min periods (ms) mpmin = 1 / (float)700; // eventually may want to bring these out as sliders mnmax = (unsigned long)(gSampleRate * mpmax); if (mnmax > mcorrsize) { mnmax = mcorrsize; } mnmin = (unsigned long)(gSampleRate * mpmin); mcbi = (float*)calloc(mcbsize, sizeof(float)); mcbiwr = 0; // Generate a window with a single raised cosine from N/4 to 3N/4 mcbwindow = (float*)calloc(mcbsize, sizeof(float)); for (int ti = 0; ti < (mcbsize / 2); ti++) { mcbwindow[ti + mcbsize / 4] = -0.5 * cos(4 * PI * ti / (mcbsize - 1)) + 0.5; } mnoverlap = 4; mFFT = new ::FFT((int)mcbsize); mffttime = (float*)calloc(mcbsize, sizeof(float)); mfftfreqre = (float*)calloc(mcorrsize, sizeof(float)); mfftfreqim = (float*)calloc(mcorrsize, sizeof(float)); // ---- Calculate autocorrelation of window ---- macwinv = (float*)calloc(mcbsize, sizeof(float)); for (int ti = 0; ti < mcbsize; ti++) { mffttime[ti] = mcbwindow[ti]; } mFFT->Forward(mcbwindow, mfftfreqre, mfftfreqim); for (int ti = 0; ti < mcorrsize; ti++) { mfftfreqre[ti] = (mfftfreqre[ti]) * (mfftfreqre[ti]) + (mfftfreqim[ti]) * (mfftfreqim[ti]); mfftfreqim[ti] = 0; } mFFT->Inverse(mfftfreqre, mfftfreqim, mffttime); for (long ti = 1; ti < mcbsize; ti++) { macwinv[ti] = mffttime[ti] / mffttime[0]; if (macwinv[ti] > 0.000001) { macwinv[ti] = (float)1 / macwinv[ti]; } else { macwinv[ti] = 0; } } macwinv[0] = 1; // ---- END Calculate autocorrelation of window ---- mlrshift = 0; mptarget = 0; msptarget = 0; mvthresh = 0.7; // The voiced confidence (unbiased peak) threshold level } PitchDetector::~PitchDetector() { delete mFFT; free(mcbi); free(mcbwindow); free(macwinv); free(mffttime); free(mfftfreqre); free(mfftfreqim); } float PitchDetector::DetectPitch(float* buffer, int bufferSize) { long int N; long int Nf; long int fs; long int ti; long int ti2; long int ti3; long int ti4; float tf; float tf2; float pperiod; float* pfInput = buffer; maref = (float)mTune; N = mcbsize; Nf = mcorrsize; fs = mfs; float inpitch = 0; float conf = mconf; /******************* * MAIN DSP LOOP * *******************/ for (int lSampleIndex = 0; lSampleIndex < bufferSize; lSampleIndex++) { // load data into circular buffer tf = (float)*(pfInput++); ti4 = mcbiwr; mcbi[ti4] = tf; // Input write pointer logic mcbiwr++; if (mcbiwr >= N) { mcbiwr = 0; } // ******************** // * Low-rate section * // ******************** // Every N/noverlap samples, run pitch estimation / manipulation code if ((mcbiwr) % (N / mnoverlap) == 0) { // ---- Obtain autocovariance ---- // Window and fill FFT buffer ti2 = mcbiwr; for (ti = 0; ti < N; ti++) { mffttime[ti] = (float)(mcbi[(ti2 - ti + N) % N] * mcbwindow[ti]); } // Calculate FFT mFFT->Forward(mffttime, mfftfreqre, mfftfreqim); // Remove DC mfftfreqre[0] = 0; mfftfreqim[0] = 0; // Take magnitude squared for (ti = 1; ti < Nf; ti++) { mfftfreqre[ti] = (mfftfreqre[ti]) * (mfftfreqre[ti]) + (mfftfreqim[ti]) * (mfftfreqim[ti]); mfftfreqim[ti] = 0; } // Calculate IFFT mFFT->Inverse(mfftfreqre, mfftfreqim, mffttime); // Normalize tf = (float)1 / mffttime[0]; for (ti = 1; ti < N; ti++) { mffttime[ti] = mffttime[ti] * tf; } mffttime[0] = 1; // ---- END Obtain autocovariance ---- // ---- Calculate pitch and confidence ---- // Calculate pitch period // Pitch period is determined by the location of the max (biased) // peak within a given range // Confidence is determined by the corresponding unbiased height tf2 = 0; pperiod = mpmin; for (ti = mnmin; ti < mnmax; ti++) { ti2 = ti - 1; ti3 = ti + 1; if (ti2 < 0) { ti2 = 0; } if (ti3 > Nf) { ti3 = Nf; } tf = mffttime[ti]; if (tf > mffttime[ti2] && tf >= mffttime[ti3] && tf > tf2) { tf2 = tf; ti4 = ti; } } if (tf2 > 0) { conf = tf2 * macwinv[ti4]; if (ti4 > 0 && ti4 < Nf) { // Find the center of mass in the vicinity of the detected peak tf = mffttime[ti4 - 1] * (ti4 - 1); tf = tf + mffttime[ti4] * (ti4); tf = tf + mffttime[ti4 + 1] * (ti4 + 1); tf = tf / (mffttime[ti4 - 1] + mffttime[ti4] + mffttime[ti4 + 1]); pperiod = tf / fs; } else { pperiod = (float)ti4 / fs; } } // Convert to semitones tf = (float)-12 * log10((float)maref * pperiod) * L2SC; if (conf >= mvthresh) { inpitch = tf; } mconf = conf; mPitch = inpitch + 69; mConfidence = MIN(conf, 1); // ---- END Calculate pitch and confidence ---- } } // Tell the host the algorithm latency mLatency = (N - 1); return mPitch; } ```
/content/code_sandbox/Source/PitchDetector.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,011
```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 **/ // // MultitrackRecorder.h // Bespoke // // Created by Ryan Challinor on 5/13/14. // // #pragma once #include <iostream> #include "IDrawableModule.h" #include "Slider.h" #include "ClickButton.h" #include "Checkbox.h" #include "IAudioProcessor.h" #include "ModuleContainer.h" class MultitrackRecorderTrack; class MultitrackRecorder : public IDrawableModule, public IButtonListener { public: MultitrackRecorder(); virtual ~MultitrackRecorder(); static IDrawableModule* Create() { return new MultitrackRecorder(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; ModuleContainer* GetContainer() override { return &mModuleContainer; } bool IsResizable() const override { return true; } void Resize(float width, float height) override { mWidth = ofClamp(width, 210, 9999); } void RemoveTrack(MultitrackRecorderTrack* track); void ButtonClicked(ClickButton* button, double time) override; void CheckboxUpdated(Checkbox* checkbox, 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 0; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void AddTrack(); int GetRecordingLength(); float mWidth{ 700 }; float mHeight{ 142 }; ModuleContainer mModuleContainer; ClickButton* mAddTrackButton{ nullptr }; Checkbox* mRecordCheckbox{ nullptr }; bool mRecord{ false }; ClickButton* mBounceButton{ nullptr }; ClickButton* mClearButton{ nullptr }; std::vector<MultitrackRecorderTrack*> mTracks; std::string mStatusString; double mStatusStringTime{ -9999 }; }; class MultitrackRecorderTrack : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IButtonListener { public: MultitrackRecorderTrack(); virtual ~MultitrackRecorderTrack(); static IDrawableModule* Create() { return new MultitrackRecorderTrack(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; bool HasTitleBar() const override { return false; } void Poll() override; void Process(double time) override; void Setup(MultitrackRecorder* recorder, int minLength); void SetRecording(bool record); Sample* BounceRecording(); void Clear(); int GetRecordingLength() const { return mRecordingLength; } void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void ButtonClicked(ClickButton* button, double time) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; MultitrackRecorder* mRecorder{ nullptr }; std::vector<ChannelBuffer*> mRecordChunks; bool mDoRecording{ false }; int mRecordingLength{ 0 }; ClickButton* mDeleteButton{ nullptr }; }; ```
/content/code_sandbox/Source/MultitrackRecorder.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
957
```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 **/ // // Curve.cpp // Bespoke // // Created by Ryan Challinor on 3/5/16. // // #include "Curve.h" #include "FileStream.h" #include <algorithm> Curve::Curve(float defaultValue) : mDefaultValue(defaultValue) { } void Curve::AddPoint(CurvePoint point) { if (IsAtCapacity()) return; bool inserted = false; for (int i = 0; i < mNumCurvePoints; ++i) { if (mPoints[i].mTime > point.mTime) { for (int j = i; j < mNumCurvePoints; ++j) mPoints[j + 1] = mPoints[j]; mPoints[i] = point; inserted = true; ++mNumCurvePoints; break; } } if (!inserted) AddPointAtEnd(point); } void Curve::AddPointAtEnd(CurvePoint point) { if (IsAtCapacity()) return; mPoints[mNumCurvePoints] = point; ++mNumCurvePoints; } int Curve::FindIndexForTime(float time) { int max = mNumCurvePoints - 1; int left = 0; int right = max; while (left <= right) { int mid = left + (right - left) / 2; if (mPoints[mid].mTime < time && (mid == max || mPoints[mid + 1].mTime >= time)) // Check if x is present at mid return mid; if (mPoints[mid].mTime < time) // If time greater, ignore left half left = mid + 1; else // If time is smaller, ignore right half right = mid - 1; } // if we reach here, then element was not present return -1; } float Curve::Evaluate(float time, bool holdEndForLoop) { float retVal = mDefaultValue; if (mNumCurvePoints > 0) { if (time <= mPoints[0].mTime) { if (holdEndForLoop) return mPoints[mNumCurvePoints - 1].mValue; else return mPoints[0].mValue; } int beforeIndex = 0; int quickCheckIndex = mLastEvalIndex; if (quickCheckIndex < mNumCurvePoints && mPoints[quickCheckIndex].mTime < time && (quickCheckIndex == mNumCurvePoints - 1 || mPoints[quickCheckIndex + 1].mTime >= time)) { beforeIndex = quickCheckIndex; } else { /*for (int i=1; i<mNumCurvePoints; ++i) { if (mPoints[i].mTime >= time) { beforeIndex = i-1; break; } }*/ beforeIndex = FindIndexForTime(time); assert(beforeIndex >= 0 && beforeIndex < mNumCurvePoints); } mLastEvalIndex = beforeIndex; int afterIndex = MIN(beforeIndex + 1, mNumCurvePoints - 1); retVal = ofMap(time, mPoints[beforeIndex].mTime, mPoints[afterIndex].mTime, mPoints[beforeIndex].mValue, mPoints[afterIndex].mValue, K(clamp)); } return retVal; } void Curve::Render() { ofPushStyle(); ofNoFill(); ofSetColor(mColor); ofBeginShape(); for (int i = 0; i < mWidth; ++i) { float val = Evaluate(ofMap(float(i) / mWidth, 0, 1, mStart, mEnd)); if (i > 0) { ofVertex(i + mX, mY + (1 - val) * mHeight); } } ofEndShape(); ofPopStyle(); } void Curve::Clear() { mNumCurvePoints = 0; } CurvePoint* Curve::GetPoint(int index) { assert(index < mNumCurvePoints); return &mPoints[index]; } void Curve::OnClicked(float x, float y, bool right) { ofLog() << "curve clicked"; } bool Curve::MouseMoved(float x, float y) { ofLog() << "curve mousemoved"; return false; } bool Curve::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { ofLog() << "curve mousescrolled"; return false; } namespace { const int kSaveStateRev = 1; } void Curve::SaveState(FileStreamOut& out) { out << kSaveStateRev; out << mNumCurvePoints; for (int i = 0; i < mNumCurvePoints; ++i) out << mPoints[i].mTime << mPoints[i].mValue; } void Curve::LoadState(FileStreamIn& in) { int rev; in >> rev; LoadStateValidate(rev <= kSaveStateRev); in >> mNumCurvePoints; for (int i = 0; i < mNumCurvePoints; ++i) in >> mPoints[i].mTime >> mPoints[i].mValue; } ```
/content/code_sandbox/Source/Curve.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,258
```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.cpp // modularSynth // // Created by Ryan Challinor on 3/26/13. // // #include "Muter.h" #include "SynthGlobals.h" #include "Profiler.h" Muter::Muter() { mRamp.SetValue(0); } void Muter::CreateUIControls() { IDrawableModule::CreateUIControls(); mPassCheckbox = new Checkbox(this, "pass", 5, 2, &mPass); mRampTimeSlider = new FloatSlider(this, "ms", 5, 20, 70, 15, &mRampTimeMs, 3, 1000); mRampTimeSlider->SetMode(FloatSlider::kSquare); } Muter::~Muter() { } void Muter::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(Muter); float bufferSize = buffer->BufferSize(); for (int i = 0; i < bufferSize; ++i) { for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) buffer->GetChannel(ch)[i] *= mRamp.Value(time); time += gInvSampleRateMs; } } void Muter::DrawModule() { mPassCheckbox->Draw(); mRampTimeSlider->Draw(); } void Muter::CheckboxUpdated(Checkbox* checkbox, double time) { mRamp.Start(time, mPass ? 1 : 0, time + mRampTimeMs); } ```
/content/code_sandbox/Source/Muter.cpp
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 **/ // // IDrawableModule.h // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #pragma once #include "IClickable.h" #include "IPollable.h" #include "ModuleSaveData.h" #include "IPatchable.h" class Checkbox; class IUIControl; class FileStreamIn; class FileStreamOut; class FloatSlider; class RollingBuffer; class ofxJSONElement; class Sample; class PatchCable; class PatchCableSource; class ModuleContainer; class UIGrid; enum ModuleCategory { kModuleCategory_Note, kModuleCategory_Synth, kModuleCategory_Audio, kModuleCategory_Instrument, kModuleCategory_Processor, kModuleCategory_Modulator, kModuleCategory_Pulse, kModuleCategory_Other, kModuleCategory_Unknown }; struct PatchCableOld { ofVec2f start; ofVec2f end; ofVec2f plug; }; class IDrawableModule : public IClickable, public IPollable, public virtual IPatchable { public: IDrawableModule(); virtual ~IDrawableModule(); static bool CanCreate() { return true; } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void Render() override; void RenderUnclipped(); virtual void PostRender() {} void DrawFrame(float width, float height, bool drawModule, float& titleBarHeight, float& highlight); void DrawPatchCables(bool parentMinimized, bool inFront); bool CheckNeedsDraw() override; virtual bool AlwaysOnTop() { return false; } void ToggleMinimized(); void SetMinimized(bool minimized, bool animate = true) { if (!HasTitleBar()) return; mMinimized = minimized; if (!animate) mMinimizeAnimation = minimized ? 1 : 0; } virtual void KeyPressed(int key, bool isRepeat); virtual void KeyReleased(int key); void DrawConnection(IClickable* target); void AddUIControl(IUIControl* control); void RemoveUIControl(IUIControl* control, bool cleanUpReferences = true); void AddUIGrid(UIGrid* grid); IUIControl* FindUIControl(const char* name, bool fail = true) const; std::vector<IUIControl*> GetUIControls() const; std::vector<UIGrid*> GetUIGrids() const; virtual void OnUIControlRequested(const char* name) {} void AddChild(IDrawableModule* child); void RemoveChild(IDrawableModule* child); IDrawableModule* FindChild(const char* name, bool fail) const; void GetDimensions(float& width, float& height) override; virtual void GetModuleDimensions(float& width, float& height) { width = 10; height = 10; } virtual void Init(); virtual void Exit(); bool IsInitialized() const { return mInitialized; } bool Minimized() const { return mMinimizeAnimation > 0; } bool WasMinimizeAreaClicked() const { return mWasMinimizeAreaClicked; } virtual void MouseReleased() override; virtual void FilesDropped(std::vector<std::string> files, int x, int y) {} virtual std::string GetTitleLabel() const { return Name(); } virtual bool HasTitleBar() const { return true; } static float TitleBarHeight() { return mTitleBarHeight; } static ofColor GetColor(ModuleCategory type); virtual void SetEnabled(bool enabled) {} virtual bool IsEnabled() const { return true; } virtual bool CanMinimize() { return true; } virtual void SampleDropped(int x, int y, Sample* sample) {} virtual bool CanDropSample() const { return false; } void BasePoll(); //calls poll, using this to guarantee base poll is always called bool IsWithinRect(const ofRectangle& rect); bool IsVisible(); std::vector<IDrawableModule*> GetChildren() const { return mChildren; } virtual bool IsResizable() const { return false; } virtual void Resize(float width, float height) { assert(false); } bool IsHoveringOverResizeHandle() const { return mHoveringOverResizeHandle; } void SetTypeName(std::string type, ModuleCategory category) { mTypeName = type; mModuleCategory = category; } void SetTarget(IClickable* target); void SetUpPatchCables(std::string targets); void AddPatchCableSource(PatchCableSource* source); void RemovePatchCableSource(PatchCableSource* source); bool TestClick(float x, float y, bool right, bool testOnly = false) override; std::string GetTypeName() const { return mTypeName; } ModuleCategory GetModuleCategory() const { return mModuleCategory; } virtual bool IsSingleton() const { return false; } virtual bool CanBeDeleted() const { return (IsSingleton() ? false : true); } virtual bool HasSpecialDelete() const { return false; } virtual void DoSpecialDelete() {} void ComputeSliders(int samplesIn); void SetOwningContainer(ModuleContainer* container) { mOwningContainer = container; } ModuleContainer* GetOwningContainer() const { return mOwningContainer; } virtual ModuleContainer* GetContainer() { return nullptr; } void SetShouldDrawOutline(bool should) { mShouldDrawOutline = should; } ofVec2f GetMinimumDimensions(); bool HasEnabledCheckbox() const { return mEnabledCheckbox != nullptr; } Checkbox* GetEnabledCheckbox() const { return mEnabledCheckbox; } void MarkAsDeleted() { mDeleted = true; } bool IsDeleted() const { return mDeleted; } virtual bool ShouldClipContents() { return true; } bool CanReceiveAudio() { return mCanReceiveAudio; } bool CanReceiveNotes() { return mCanReceiveNotes; } bool CanReceivePulses() { return mCanReceivePulses; } virtual bool ShouldSuppressAutomaticOutputCable() { return false; } virtual void CheckboxUpdated(Checkbox* checkbox, double time) {} virtual void LoadBasics(const ofxJSONElement& moduleInfo, std::string typeName); virtual void CreateUIControls(); void LoadLayoutBase(const ofxJSONElement& moduleInfo); void SaveLayoutBase(ofxJSONElement& moduleInfo); void SetUpFromSaveDataBase(); virtual bool IsSaveable() { return true; } ModuleSaveData& GetSaveData() { return mModuleSaveData; } virtual void SaveState(FileStreamOut& out); virtual void LoadState(FileStreamIn& in, int rev); int LoadModuleSaveStateRev(FileStreamIn& in); virtual int GetModuleSaveStateRev() const { return -1; } virtual void PostLoadState() {} virtual std::vector<IUIControl*> ControlsToNotSetDuringLoadState() const; virtual std::vector<IUIControl*> ControlsToIgnoreInSaveState() const; virtual void UpdateOldControlName(std::string& oldName) {} virtual bool LoadOldControl(FileStreamIn& in, std::string& oldName) { return false; } virtual bool CanModuleTypeSaveState() const { return true; } bool IsSpawningOnTheFly(const ofxJSONElement& moduleInfo); virtual bool HasDebugDraw() const { return false; } virtual bool HasPush2OverrideControls() const { return false; } virtual void GetPush2OverrideControls(std::vector<IUIControl*>& controls) const {} virtual bool DrawToPush2Screen() { return false; } //IPatchable PatchCableSource* GetPatchCableSource(int index = 0) override { if (index < mPatchCableSources.size()) return mPatchCableSources[index]; return nullptr; } std::vector<PatchCableSource*> GetPatchCableSources() { return mPatchCableSources; } static void FindClosestSides(float xThis, float yThis, float wThis, float hThis, float xThat, float yThat, float wThat, float hThat, float& startX, float& startY, float& endX, float& endY, bool sidesOnly = false); static float sHueNote; static float sHueAudio; static float sHueInstrument; static float sHueNoteSource; static float sSaturation; static float sBrightness; bool mDrawDebug{ false }; static constexpr int kMaxOutputsPerPatchCableSource = 32; protected: void Poll() override {} void OnClicked(float x, float y, bool right) override; bool MouseMoved(float x, float y) override; void AddDebugLine(std::string text, int maxLines); ModuleSaveData mModuleSaveData; Checkbox* mEnabledCheckbox{ nullptr }; bool mEnabled{ true }; ModuleCategory mModuleCategory{ ModuleCategory::kModuleCategory_Unknown }; std::string mDebugDisplayText; private: virtual void PreDrawModule() {} virtual void DrawModule() = 0; virtual void DrawModuleUnclipped() {} float GetMinimizedWidth(); PatchCableOld GetPatchCableOld(IClickable* target); virtual void LoadLayout(const ofxJSONElement& moduleInfo) {} virtual void SaveLayout(ofxJSONElement& moduleInfo) {} virtual void SetUpFromSaveData() {} virtual bool ShouldSavePatchCableSources() const { return true; } std::vector<IUIControl*> mUIControls; std::vector<IDrawableModule*> mChildren; std::vector<FloatSlider*> mFloatSliders; std::vector<UIGrid*> mUIGrids; static const int mTitleBarHeight = 12; std::string mTypeName; static const int sResizeCornerSize = 8; ModuleContainer* mOwningContainer{ nullptr }; bool mMinimized{ false }; bool mWasMinimizeAreaClicked{ false }; float mMinimizeAnimation{ 0 }; bool mUIControlsCreated{ false }; bool mInitialized{ false }; std::string mLastTitleLabel; float mTitleLabelWidth{ 0 }; bool mShouldDrawOutline{ true }; bool mHoveringOverResizeHandle{ false }; bool mDeleted{ false }; bool mCanReceiveAudio{ false }; bool mCanReceiveNotes{ false }; bool mCanReceivePulses{ false }; IKeyboardFocusListener* mKeyboardFocusListener{ nullptr }; ofMutex mSliderMutex; std::vector<PatchCableSource*> mPatchCableSources; }; ```
/content/code_sandbox/Source/IDrawableModule.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,462
```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.cpp Created: 28 Jan 2017 10:48:14pm Author: Ryan Challinor ============================================================================== */ #include "VolcaBeatsControl.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" VolcaBeatsControl::VolcaBeatsControl() { for (int i = 0; i < 10; ++i) { mLevels[i] = 1; mLevelSliders[i] = nullptr; } } VolcaBeatsControl::~VolcaBeatsControl() { } void VolcaBeatsControl::CreateUIControls() { IDrawableModule::CreateUIControls(); mClapSpeedSlider = new FloatSlider(this, "clap speed", 5, 5, 140, 15, &mClapSpeed, 0, 1); mClaveSpeedSlider = new FloatSlider(this, "clave speed", mClapSpeedSlider, kAnchor_Below, 140, 15, &mClaveSpeed, 0, 1); mAgogoSpeedSlider = new FloatSlider(this, "agogo speed", mClaveSpeedSlider, kAnchor_Below, 140, 15, &mAgogoSpeed, 0, 1); mCrashSpeedSlider = new FloatSlider(this, "crash speed", mAgogoSpeedSlider, kAnchor_Below, 140, 15, &mCrashSpeed, 0, 1); mStutterTimeSlider = new FloatSlider(this, "stutter time", mCrashSpeedSlider, kAnchor_Below, 140, 15, &mStutterTime, 0, 1); mStutterDepthSlider = new FloatSlider(this, "stutter depth", mStutterTimeSlider, kAnchor_Below, 140, 15, &mStutterDepth, 0, 1); mTomDecaySlider = new FloatSlider(this, "tom decay", mStutterDepthSlider, kAnchor_Below, 140, 15, &mTomDecay, 0, 1); mClosedHatDecaySlider = new FloatSlider(this, "closed hat decay", mTomDecaySlider, kAnchor_Below, 140, 15, &mClosedHatDecay, 0, 1); mOpenHatDecaySlider = new FloatSlider(this, "open hat decay", mClosedHatDecaySlider, kAnchor_Below, 140, 15, &mOpenHatDecay, 0, 1); mHatGrainSlider = new FloatSlider(this, "hat grain", mOpenHatDecaySlider, kAnchor_Below, 140, 15, &mHatGrain, 0, 1); for (int i = 0; i < 10; ++i) { mLevelSliders[i] = new FloatSlider(this, ("level " + ofToString(i)).c_str(), 155, 5, 100, 15, &mLevels[i], 0, 1); if (i > 0) mLevelSliders[i]->PositionTo(mLevelSliders[i - 1], kAnchor_Below); } } void VolcaBeatsControl::DrawModule() { if (Minimized() || IsVisible() == false) return; mClapSpeedSlider->Draw(); mClaveSpeedSlider->Draw(); mAgogoSpeedSlider->Draw(); mCrashSpeedSlider->Draw(); mStutterTimeSlider->Draw(); mStutterDepthSlider->Draw(); mTomDecaySlider->Draw(); mClosedHatDecaySlider->Draw(); mOpenHatDecaySlider->Draw(); mHatGrainSlider->Draw(); for (int i = 0; i < 10; ++i) mLevelSliders[i]->Draw(); } void VolcaBeatsControl::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } if (pitch < 10) { mLevelSliders[pitch]->Compute(); velocity *= mLevels[pitch]; } switch (pitch) { case 0: //kick pitch = 36; if (velocity > 0) SendCC(40, velocity); break; case 1: //snare pitch = 38; if (velocity > 0) SendCC(41, velocity); break; case 2: //closed pitch = 42; if (velocity > 0) { SendCC(44, velocity); mClosedHatDecaySlider->Compute(); mHatGrainSlider->Compute(); } break; case 3: //ride pitch = 67; if (velocity > 0) { SendCC(48, velocity); mAgogoSpeedSlider->Compute(); } break; case 4: //clap pitch = 39; if (velocity > 0) { SendCC(46, velocity); mClapSpeedSlider->Compute(); } break; case 5: //crash pitch = 49; if (velocity > 0) { SendCC(49, velocity); mCrashSpeedSlider->Compute(); } break; case 6: //open pitch = 46; if (velocity > 0) { SendCC(45, velocity); mOpenHatDecaySlider->Compute(); mHatGrainSlider->Compute(); } break; case 7: //stick pitch = 75; if (velocity > 0) { SendCC(47, velocity); mClaveSpeedSlider->Compute(); } break; case 8: //floor pitch = 43; if (velocity > 0) { SendCC(42, velocity); mTomDecaySlider->Compute(); } break; case 9: //low pitch = 50; if (velocity > 0) { SendCC(43, velocity); mTomDecaySlider->Compute(); } break; default: pitch = -1; } mStutterTimeSlider->Compute(); mStutterDepthSlider->Compute(); if (pitch != -1) PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void VolcaBeatsControl::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mClapSpeedSlider) SendCC(50, (int)(mClapSpeed * 127)); if (slider == mClaveSpeedSlider) SendCC(51, (int)(mClaveSpeed * 127)); if (slider == mAgogoSpeedSlider) SendCC(52, (int)(mAgogoSpeed * 127)); if (slider == mCrashSpeedSlider) SendCC(53, (int)(mCrashSpeed * 127)); if (slider == mStutterTimeSlider) SendCC(54, (int)(mStutterTime * 127)); if (slider == mStutterDepthSlider) SendCC(55, (int)(mStutterDepth * 127)); if (slider == mTomDecaySlider) SendCC(56, (int)(mTomDecay * 127)); if (slider == mClosedHatDecaySlider) SendCC(57, (int)(mClosedHatDecay * 127)); if (slider == mOpenHatDecaySlider) SendCC(58, (int)(mOpenHatDecay * 127)); if (slider == mHatGrainSlider) SendCC(59, (int)(mHatGrain * 127)); } void VolcaBeatsControl::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void VolcaBeatsControl::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/VolcaBeatsControl.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,937
```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 **/ // // FeedbackModule.cpp // Bespoke // // Created by Ryan Challinor on 2/1/16. // // #include "FeedbackModule.h" #include "Profiler.h" #include "PatchCableSource.h" #include "ModularSynth.h" FeedbackModule::FeedbackModule() : IAudioProcessor(gBufferSize) , mFeedbackVizBuffer(VIZ_BUFFER_SECONDS * gSampleRate) { AddChild(&mDelay); mDelay.SetPosition(4, 32); mDelay.SetEnabled(true); mDelay.SetName("delay"); for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) mGainScale[i] = 1; } void FeedbackModule::CreateUIControls() { IDrawableModule::CreateUIControls(); mFeedbackTargetCable = new PatchCableSource(this, kConnectionType_Audio); mFeedbackTargetCable->SetManualPosition(108, 8); mFeedbackTargetCable->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight); mFeedbackTargetCable->SetOverrideVizBuffer(&mFeedbackVizBuffer); AddPatchCableSource(mFeedbackTargetCable); mDelay.CreateUIControls(); mDelay.SetFeedbackModuleMode(); ofRectangle delayModuleRect = mDelay.GetRect(true); mSignalLimitSlider = new FloatSlider(this, "limit", delayModuleRect.x, delayModuleRect.getMaxY() + 3, delayModuleRect.width, 15, &mSignalLimit, 0.01f, 1); mSignalLimitSlider->SetMode(FloatSlider::kSquare); } FeedbackModule::~FeedbackModule() { } void FeedbackModule::Process(double time) { PROFILER(FeedbackModule); ComputeSliders(0); SyncBuffers(); int bufferSize = GetBuffer()->BufferSize(); IAudioReceiver* target = GetTarget(); if (target) { for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), bufferSize); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), bufferSize, ch); } } if (mFeedbackTarget && mEnabled) { mFeedbackTarget->GetBuffer()->SetNumActiveChannels(GetBuffer()->NumActiveChannels()); mFeedbackVizBuffer.SetNumChannels(GetBuffer()->NumActiveChannels()); mDelay.ProcessAudio(time, GetBuffer()); const double kReleaseMs = 50; const double kReleaseCoeff = exp(-1000.0 / (kReleaseMs * gSampleRate)); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { float* channel = GetBuffer()->GetChannel(ch); for (int i = 0; i < bufferSize; ++i) { //ofLog() << "input: " << channel[i]; if (abs(channel[i]) * mGainScale[ch] > mSignalLimit) { mGainScale[ch] = mSignalLimit / abs(channel[i]); //limit immediately //ofLog() << "limiting, new scale " << mGainScale[ch]; } else { mGainScale[ch] = MIN(1 - kReleaseCoeff * (mGainScale[ch] - 1), //blend towards 1 mSignalLimit / abs(channel[i])); //but don't make the scale less than it would have to be to limit the output //ofLog() << "releasing, new scale " << mGainScale[ch]; } channel[i] *= mGainScale[ch]; //ofLog() << "output: " << channel[i]; //assert(abs(channel[i]) <= mSignalLimit); } if (mDelay.IsEnabled()) { Add(mFeedbackTarget->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), bufferSize); mFeedbackVizBuffer.WriteChunk(GetBuffer()->GetChannel(ch), bufferSize, ch); } else { mFeedbackVizBuffer.WriteChunk(gZeroBuffer, gBufferSize, ch); } } } GetBuffer()->Reset(); } void FeedbackModule::DrawModule() { if (Minimized() || IsVisible() == false) return; mDelay.Draw(); mSignalLimitSlider->Draw(); DrawTextRightJustify("feedback out:", 100, 12); } void FeedbackModule::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { if (cableSource == mFeedbackTargetCable) { mFeedbackTarget = mFeedbackTargetCable->GetAudioReceiver(); } } void FeedbackModule::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadString("feedbacktarget", moduleInfo); SetUpFromSaveData(); } void FeedbackModule::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["feedbacktarget"] = mFeedbackTarget ? dynamic_cast<IDrawableModule*>(mFeedbackTarget)->Name() : ""; } void FeedbackModule::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mFeedbackTargetCable->SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("feedbacktarget"), false)); } ```
/content/code_sandbox/Source/FeedbackModule.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,269
```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.cpp // modularSynth // // Created by Ryan Challinor on 1/14/13. // // #include "MidiController.h" #include "IUIControl.h" #include "SynthGlobals.h" #include "ofxJSONElement.h" #include "ModularSynth.h" //#include "Xbox360Controller.h" #include "Transport.h" #include "Monome.h" #include "Profiler.h" #include "OscController.h" #include "PatchCableSource.h" #include "GridController.h" #include "MidiCapturer.h" #include "ScriptModule.h" #include "Push2Control.h" #include "QwertyController.h" using namespace juce; //static double MidiController::sLastConnectedActivityTime = -9999; IUIControl* MidiController::sLastActivityUIControl = nullptr; double MidiController::sLastBoundControlTime = -9999; IUIControl* MidiController::sLastBoundUIControl = nullptr; bool UIControlConnection::sDrawCables = true; namespace { const int kLayoutControlsX = 5; const int kLayoutControlsY = 110; const int kLayoutButtonsX = 250; const int kLayoutButtonsY = 10; } MidiController::MidiController() : mDevice(this) { mListeners.resize(MAX_MIDI_PAGES); } void MidiController::CreateUIControls() { IDrawableModule::CreateUIControls(); mControllerList = new DropdownList(this, "controller", 3, 2, &mControllerIndex, 157); mMappingDisplayModeSelector = new RadioButton(this, "mappingdisplay", mControllerList, kAnchor_Below, (int*)&mMappingDisplayMode, kRadioHorizontal); mBindCheckbox = new Checkbox(this, "bind (hold shift)", mMappingDisplayModeSelector, kAnchor_Below, &mBindMode); mPageSelector = new DropdownList(this, "page", mBindCheckbox, kAnchor_Right, &mControllerPage); mAddConnectionButton = new ClickButton(this, "add", 12, 300); mLayoutFileDropdown = new DropdownList(this, "layout", 3, 70, &mLayoutFileIndex); mOscInPortEntry = new TextEntry(this, "osc input port", 3, 88, 6, &mOscInPort, 0, 99999); mMonomeDeviceDropdown = new DropdownList(this, "monome", 3, 88, &mMonomeDeviceIndex); //mDrawCablesCheckbox = new Checkbox(this,"draw cables",200,26,&UIControlConnection::sDrawCables); for (int i = 0; i < MAX_MIDI_PAGES; ++i) mPageSelector->AddLabel(("page " + ofToString(i)).c_str(), i); mMappingDisplayModeSelector->AddLabel("hide", kHide); mMappingDisplayModeSelector->AddLabel("layout", kLayout); mMappingDisplayModeSelector->AddLabel("list", kList); mLayoutFileDropdown->DrawLabel(true); mOscInPortEntry->DrawLabel(true); mMonomeDeviceDropdown->DrawLabel(true); mLayoutFileDropdown->AddLabel(kDefaultLayout, 0); File dir(ofToDataPath("controllers")); Array<File> files; for (auto file : dir.findChildFiles(File::findFiles, false, "*.json")) files.add(file); files.sort(); for (auto file : files) mLayoutFileDropdown->AddLabel(file.getFileName().toStdString(), mLayoutFileDropdown->GetNumValues()); } MidiController::~MidiController() { TheTransport->RemoveAudioPoller(this); delete mNonstandardController; for (auto i = mConnections.begin(); i != mConnections.end(); ++i) delete *i; } void MidiController::Init() { IDrawableModule::Init(); for (auto i = mConnections.begin(); i != mConnections.end(); ++i) delete *i; mConnections.clear(); mHasCreatedConnectionUIControls = false; TheTransport->AddAudioPoller(this); } void MidiController::AddListener(MidiDeviceListener* listener, int page) { mListeners[page].push_back(listener); if (page == mControllerPage) listener->ControllerPageSelected(); } void MidiController::RemoveListener(MidiDeviceListener* listener) { for (int i = 0; i < MAX_MIDI_PAGES; ++i) mListeners[i].remove(listener); } UIControlConnection* MidiController::AddControlConnection(MidiMessageType messageType, int control, int channel, IUIControl* uicontrol, int page /*= -1*/) { if (page == -1) page = mControllerPage; RemoveConnection(control, messageType, channel, page); UIControlConnection* connection = new UIControlConnection(this); connection->mMessageType = messageType; connection->mControl = control; connection->SetUIControl(uicontrol); connection->mChannel = channel; connection->mPage = page; if (dynamic_cast<Checkbox*>(uicontrol) != nullptr) connection->mType = kControlType_Toggle; else if (dynamic_cast<TextEntry*>(uicontrol) != nullptr) connection->mType = kControlType_Direct; else connection->mType = kControlType_Slider; if (mSlidersDefaultToIncremental) connection->mIncrementAmount = 1; int layoutControl = GetLayoutControlIndexForMidi(messageType, control); if (layoutControl != -1) { connection->mIncrementAmount = mLayoutControls[layoutControl].mIncrementAmount; connection->mMidiOffValue = mLayoutControls[layoutControl].mOffVal; connection->mMidiOnValue = mLayoutControls[layoutControl].mOnVal; connection->mScaleOutput = mLayoutControls[layoutControl].mScaleOutput; connection->m14BitMode = mLayoutControls[layoutControl].m14BitMode; if (mLayoutControls[layoutControl].mConnectionType != kControlType_Default) connection->mType = mLayoutControls[layoutControl].mConnectionType; } connection->CreateUIControls((int)mConnections.size()); mConnections.push_back(connection); if (uicontrol != nullptr) uicontrol->AddRemoteController(); return connection; } void MidiController::AddControlConnection(const ofxJSONElement& connection) { try { if (connection.isMember("grid_index")) { int index = connection["grid_index"].asInt(); if (index < (int)mGrids.size()) { GridLayout* grid = mGrids[index]; for (int page = 0; page < connection["grid_pages"].size(); ++page) { std::string path = connection["grid_pages"][page].asString(); if (path.length() > 0) grid->mGridControlTarget[page] = dynamic_cast<GridControlTarget*>(GetOwningContainer()->FindUIControl(path)); else grid->mGridControlTarget[page] = nullptr; } } return; } int control = connection["control"].asInt() % MIDI_PAGE_WIDTH; std::string path = connection["uicontrol"].asString(); std::string type = connection["type"].asString(); MidiMessageType msgType = kMidiMessage_Control; if (type == "control") { msgType = kMidiMessage_Control; } else if (type == "note") { msgType = kMidiMessage_Note; } else if (type == "program") { msgType = kMidiMessage_Program; } else if (type == "pitchbend") { msgType = kMidiMessage_PitchBend; control = MIDI_PITCH_BEND_CONTROL_NUM; } int channel = -1; if (!connection["channel"].isNull()) channel = connection["channel"].asInt(); int page = -1; bool pageless = false; if (!connection["page"].isNull()) page = connection["page"].asInt(); if (page == -1) pageless = true; UIControlConnection* controlConnection = new UIControlConnection(this); controlConnection->mMessageType = msgType; controlConnection->mControl = control; if (controlConnection->mUIControl == nullptr && controlConnection->mSpecialBinding == kSpecialBinding_None) controlConnection->mShouldRetryForUIControlAt = path; ControlType controlType = kControlType_SetValue; if (connection["toggle"].asBool()) controlType = kControlType_Toggle; else if (connection["direct"].asBool()) controlType = kControlType_Direct; else if (connection["value"].isNull()) controlType = kControlType_Slider; else if (connection["release"].asBool()) controlType = kControlType_SetValueOnRelease; controlConnection->mType = controlType; controlConnection->mChannel = channel; controlConnection->mPage = page; controlConnection->mPageless = pageless; if (!connection["midi_on_value"].isNull()) controlConnection->mMidiOnValue = connection["midi_on_value"].asInt(); if (!connection["midi_off_value"].isNull()) controlConnection->mMidiOffValue = connection["midi_off_value"].asInt(); if (!connection["blink"].isNull()) controlConnection->mBlink = connection["blink"].asBool(); if (!connection["value"].isNull()) controlConnection->mValue = connection["value"].asDouble(); if (!connection["increment_amount"].isNull()) controlConnection->mIncrementAmount = connection["increment_amount"].asDouble(); if (!connection["twoway"].isNull()) controlConnection->mTwoWay = connection["twoway"].asBool(); if (!connection["feedbackcontrol"].isNull()) controlConnection->mFeedbackControl = connection["feedbackcontrol"].asInt(); if (!connection["14bit"].isNull()) controlConnection->m14BitMode = connection["14bit"].asBool(); controlConnection->SetUIControl(path); //controlConnection->CreateUIControls(this, mConnections.size()); //do this on the first draw instead, to avoid a long init time when setting up a bunch of minimized controllers mConnections.push_back(controlConnection); if (!connection["pages"].isNull()) { for (int i = 0; i < connection["pages"].size(); ++i) { IUIControl* uicontrolNextPage = TheSynth->FindUIControl(connection["pages"][i].asCString()); if (uicontrolNextPage) { UIControlConnection* nextPageConnection = new UIControlConnection(*controlConnection); nextPageConnection->mPage += i + 1; nextPageConnection->SetUIControl(uicontrolNextPage); nextPageConnection->mEditorControls.clear(); //TODO(Ryan) temp fix nextPageConnection->CreateUIControls((int)mConnections.size()); mConnections.push_back(nextPageConnection); uicontrolNextPage->AddRemoteController(); } } } } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } } void MidiController::OnTransportAdvanced(float amount) { PROFILER(MidiController); mQueuedMessageMutex.lock(); double firstNoteTimestampMs = -1; double lastPlayTime = -1; for (auto note = mQueuedNotes.begin(); note != mQueuedNotes.end(); ++note) { int voiceIdx = -1; if (mUseChannelAsVoice) voiceIdx = note->mChannel - 1; //TODO(Ryan) how can I use note->mTimestamp to get more accurate timing for midi input? //this here is not accurate, but prevents notes played within the same buffer from having the exact same time double playTime; if (firstNoteTimestampMs == -1) //this is the first note { firstNoteTimestampMs = note->mTimestampMs; playTime = gTime; } else { playTime = gTime + (note->mTimestampMs - firstNoteTimestampMs); if (playTime <= lastPlayTime) playTime += .01; //hack to handle note on/off in the same frame } lastPlayTime = playTime; PlayNoteOutput(playTime, note->mPitch + mNoteOffset, MIN(127, note->mVelocity * mVelocityMult), voiceIdx, ModulationParameters(mModulation.GetPitchBend(voiceIdx), mModulation.GetModWheel(voiceIdx), mModulation.GetPressure(voiceIdx), 0)); for (auto i = mListeners[mControllerPage].begin(); i != mListeners[mControllerPage].end(); ++i) (*i)->OnMidiNote(*note); } mQueuedNotes.clear(); for (auto ctrl = mQueuedControls.begin(); ctrl != mQueuedControls.end(); ++ctrl) { if (mSendCCOutput) { int voiceIdx = -1; if (mUseChannelAsVoice) voiceIdx = ctrl->mChannel - 1; SendCCOutput(ctrl->mControl, ctrl->mValue, voiceIdx); } for (auto i = mListeners[mControllerPage].begin(); i != mListeners[mControllerPage].end(); ++i) (*i)->OnMidiControl(*ctrl); } mQueuedControls.clear(); for (auto note = mQueuedProgramChanges.begin(); note != mQueuedProgramChanges.end(); ++note) { for (auto i = mListeners[mControllerPage].begin(); i != mListeners[mControllerPage].end(); ++i) (*i)->OnMidiProgramChange(*note); } mQueuedProgramChanges.clear(); for (auto note = mQueuedPitchBends.begin(); note != mQueuedPitchBends.end(); ++note) { for (auto i = mListeners[mControllerPage].begin(); i != mListeners[mControllerPage].end(); ++i) (*i)->OnMidiPitchBend(*note); } mQueuedPitchBends.clear(); mQueuedMessageMutex.unlock(); } void MidiController::OnMidiNote(MidiNote& note) { if (!mEnabled || (mChannelFilter != ChannelFilter::kAny && note.mChannel != (int)mChannelFilter)) return; if (mUseChannelAsVoice && note.mVelocity > 0) { int voiceIdx = note.mChannel - 1; mModulation.GetPitchBend(voiceIdx)->SetValue(0); } MidiReceived(kMidiMessage_Note, note.mPitch, note.mVelocity / 127.0f, note.mVelocity, note.mChannel); mQueuedMessageMutex.lock(); mQueuedNotes.push_back(note); mQueuedMessageMutex.unlock(); if (mPrintInput) ofLog() << Name() << " note: " << note.mPitch << ", " << note.mVelocity; } void MidiController::OnMidiControl(MidiControl& control) { if (!mEnabled || (mChannelFilter != ChannelFilter::kAny && control.mChannel != (int)mChannelFilter)) return; int voiceIdx = -1; if (mUseChannelAsVoice) voiceIdx = control.mChannel - 1; if (control.mControl == mModwheelCC) { //if (mModwheelCC == 74) //MPE // mModulation.GetModWheel(voiceIdx)->SetValue((control.mValue-63) / 127.0f * 2); //else mModulation.GetModWheel(voiceIdx)->SetValue(control.mValue / 127.0f); } MidiReceived(kMidiMessage_Control, control.mControl, control.mValue / 127.0f, control.mValue, control.mChannel); mQueuedMessageMutex.lock(); mQueuedControls.push_back(control); mQueuedMessageMutex.unlock(); if (mPrintInput) ofLog() << Name() << " control: " << control.mControl << ", " << control.mValue; } void MidiController::OnMidiPressure(MidiPressure& pressure) { if (!mEnabled || (mChannelFilter != ChannelFilter::kAny && pressure.mChannel != (int)mChannelFilter)) return; int voiceIdx = -1; if (mUseChannelAsVoice) voiceIdx = pressure.mChannel - 1; mModulation.GetPressure(voiceIdx)->SetValue(pressure.mPressure / 127.0f); mNoteOutput.SendPressure(pressure.mPitch, pressure.mPressure); } void MidiController::OnMidiProgramChange(MidiProgramChange& program) { if (!mEnabled || (mChannelFilter != ChannelFilter::kAny && program.mChannel != (int)mChannelFilter)) return; MidiReceived(kMidiMessage_Program, program.mProgram, 1, 1, program.mChannel); mQueuedMessageMutex.lock(); mQueuedProgramChanges.push_back(program); mQueuedMessageMutex.unlock(); if (mPrintInput) ofLog() << Name() << " program change: " << program.mProgram; } void MidiController::OnMidiPitchBend(MidiPitchBend& pitchBend) { if (!mEnabled || (mChannelFilter != ChannelFilter::kAny && pitchBend.mChannel != (int)mChannelFilter)) return; int voiceIdx = -1; float amount = (pitchBend.mValue - 8192.0f) / (8192.0f / mPitchBendRange); if (mUseChannelAsVoice) voiceIdx = pitchBend.mChannel - 1; else mCurrentPitchBend = amount; mModulation.GetPitchBend(voiceIdx)->SetValue(amount); MidiReceived(kMidiMessage_PitchBend, MIDI_PITCH_BEND_CONTROL_NUM, pitchBend.mValue / 16383.0f, pitchBend.mValue, pitchBend.mChannel); //16383 = max pitch bend mQueuedMessageMutex.lock(); mQueuedPitchBends.push_back(pitchBend); mQueuedMessageMutex.unlock(); if (mPrintInput) ofLog() << Name() << " pitch bend: " << pitchBend.mValue; } void MidiController::OnMidi(const MidiMessage& message) { if (!mEnabled || (mChannelFilter != ChannelFilter::kAny && message.getChannel() != (int)mChannelFilter && !message.isSysEx())) return; mNoteOutput.SendMidi(message); } void MidiController::MidiReceived(MidiMessageType messageType, int control, float value, int rawValue, int channel) { assert(mEnabled); mLastActivityBound = false; //if (value > 0) mLastActivityTime = gTime; GetLayoutControl(control, messageType).mLastActivityTime = gTime; GetLayoutControl(control, messageType).mLastValue = value; if (JustBoundControl()) //no midi messages if we just bound something, to avoid changing that thing we just bound return; if (messageType == kMidiMessage_Control) mLastInput = "cc "; if (messageType == kMidiMessage_Note) mLastInput = "note "; if (messageType == kMidiMessage_Program) mLastInput = "program change "; if (messageType == kMidiMessage_PitchBend) mLastInput = "pitchbend"; if (messageType != kMidiMessage_PitchBend) mLastInput += ofToString(control); mLastInput += ", value: " + ofToString(value, 2) + " (" + ofToString(rawValue) + "), channel: " + ofToString(channel); if (mBindMode && gBindToUIControl) { if (messageType == kMidiMessage_Control && mLayoutControls[GetLayoutControlIndexForMidi(messageType, control + 32)].m14BitMode) { //this is the MSB half of a 14-bit message, do nothing and let the LSB half bind } else { AddControlConnection(messageType, control, channel, gBindToUIControl); sLastBoundControlTime = gTime; sLastBoundUIControl = gBindToUIControl; sLastBoundUIControl->StartBeacon(); gBindToUIControl = nullptr; return; } } if (Push2Control::sBindToUIControl) { AddControlConnection(messageType, control, channel, Push2Control::sBindToUIControl); sLastBoundControlTime = gTime; sLastBoundUIControl = Push2Control::sBindToUIControl; sLastBoundUIControl->StartBeacon(); Push2Control::sBindToUIControl = nullptr; return; } if (mBindMode && gHoveredUIControl && (GetKeyModifiers() == kModifier_Shift)) { if (messageType == kMidiMessage_Control && mLayoutControls[GetLayoutControlIndexForMidi(messageType, control + 32)].m14BitMode) { //this is the MSB half of a 14-bit message, do nothing and let the LSB half bind } else { AddControlConnection(messageType, control, channel, gHoveredUIControl); sLastBoundControlTime = gTime; sLastBoundUIControl = gHoveredUIControl; sLastBoundUIControl->StartBeacon(); return; } } for (auto i = mConnections.begin(); i != mConnections.end(); ++i) { UIControlConnection* connection = *i; if (connection->mMessageType == messageType && (connection->mControl == control || messageType == kMidiMessage_PitchBend) && (connection->mPageless || connection->mPage == mControllerPage) && (connection->mChannel == -1 || connection->mChannel == channel)) { float controlValueRange = 127.0f; if (connection->m14BitMode && messageType == kMidiMessage_Control && control - 32 >= 0) //in 14-bit mode, the most sigificant bit comes from the control 32 higher, so this control must be at least 32 { controlValueRange = 16383.0f; float mostSignificantBitValue = GetLayoutControl(control - 32, kMidiMessage_Control).mLastValue; int MSB = mostSignificantBitValue * 127.0f; int LSB = value * 127.0f; int combined = (MSB << 7) + LSB; value = combined / controlValueRange; } mLastActivityBound = true; //if (value > 0) connection->mLastActivityTime = gTime; IUIControl* uicontrol = connection->GetUIControl(); if (uicontrol == nullptr) continue; if (mShowActivityUIOverlay) { sLastActivityUIControl = uicontrol; sLastConnectedActivityTime = gTime; } if (connection->mType == kControlType_Slider) { if (connection->mIncrementAmount != 0) { float curValue = uicontrol->GetMidiValue(); float increment = connection->mIncrementAmount / 100; if (GetKeyModifiers() & kModifier_Shift) increment /= 50; const float midpoint = ceil(controlValueRange / 2) / controlValueRange; if (value != midpoint) { float change = (value - midpoint); //float sign = change > 0 ? 1 : -1; //change = sign * sqrtf(fabsf(change)); //make response fall off for bigger changes curValue += (increment * 127.0f) * change; uicontrol->SetFromMidiCC(curValue, NextBufferTime(false), false); } } else { if (connection->mMessageType == kMidiMessage_Note) value = value > 0 ? 1 : 0; if (connection->mScaleOutput && (connection->mMidiOffValue != 0 || connection->mMidiOnValue != controlValueRange)) value = ofLerp(connection->mMidiOffValue / controlValueRange, connection->mMidiOnValue / controlValueRange, value); uicontrol->SetFromMidiCC(value, NextBufferTime(false), false); } uicontrol->StartBeacon(); } else if (connection->mType == kControlType_Toggle) { if (value > 0) { float val = uicontrol->GetMidiValue(); uicontrol->SetValue(val == 0, NextBufferTime(false)); uicontrol->StartBeacon(); } } else if (connection->mType == kControlType_SetValue) { if (value > 0 || mUseNegativeEdge) { if (connection->mIncrementAmount != 0) { const float midpoint = ceil(controlValueRange / 2) / controlValueRange; if (value > midpoint) uicontrol->Increment(connection->mIncrementAmount); else uicontrol->Increment(-connection->mIncrementAmount); } else { uicontrol->SetValue(connection->mValue, NextBufferTime(false), K(forceUpdate)); } uicontrol->StartBeacon(); } } else if (connection->mType == kControlType_SetValueOnRelease) { if (value == 0) { if (connection->mIncrementAmount != 0) uicontrol->Increment(connection->mIncrementAmount); else uicontrol->SetValue(connection->mValue, NextBufferTime(false), K(forceUpdate)); uicontrol->StartBeacon(); } } else if (connection->mType == kControlType_Direct) { uicontrol->SetValue(rawValue, NextBufferTime(false), K(forceUpdate)); uicontrol->StartBeacon(); } if (!mSendTwoWayOnChange) connection->mLastControlValue = int(uicontrol->GetMidiValue() * controlValueRange); //set expected value here, so we don't send the value. otherwise, this will send the input value right back as output. (although, this behavior is desirable for some controllers, hence mSendTwoWayOnChange) if (mResendFeedbackOnRelease && value == 0) connection->mLastControlValue = -999; //force feedback update on release } } for (auto* grid : mGrids) { if (grid->mType == messageType && grid->mGridControlTarget[mControllerPage] != nullptr && grid->mGridControlTarget[mControllerPage]->GetGridController() != nullptr) { for (int i = 0; i < grid->mControls.size(); ++i) { if (grid->mControls[i] == control) { dynamic_cast<GridControllerMidi*>(grid->mGridControlTarget[mControllerPage]->GetGridController())->OnInput(control, value); grid->mGridCable->AddHistoryEvent(gTime, grid->mGridControlTarget[mControllerPage]->GetGridController()->HasInput()); break; } } } } /*if (mLastActivityBound == false && mTwoWay) //if this didn't affect anything, give that feedback on the controller by keeping it at zero { //if (messageType == kMidiMessage_Note) // SendNote(control, 0); if (messageType == kMidiMessage_Control) SendCC(mControllerPage, control, 0); }*/ for (auto* script : mScriptListeners) script->MidiReceived(messageType, control, value, channel); } void MidiController::OnKeyPressed(int key, bool isRepeat) { if (mEnabled && !isRepeat) { QwertyController* qwerty = dynamic_cast<QwertyController*>(mNonstandardController); if (qwerty != nullptr) qwerty->OnKeyPressed(KeyToLower(key)); } } void MidiController::KeyReleased(int key) { if (mDeviceIn == "keyboard") { QwertyController* qwerty = dynamic_cast<QwertyController*>(mNonstandardController); if (qwerty != nullptr) qwerty->OnKeyReleased(KeyToLower(key)); } } bool MidiController::ShouldConsumeKey(int key) { return (gHoveredUIControl == nullptr || gHoveredUIControl->GetModuleParent() != this) && key != 32; //32 = space bar, which is used for panning the canvas } bool MidiController::CanTakeFocus() { return mDeviceIn == "keyboard"; } void MidiController::AddScriptListener(ScriptModule* script) { if (!VectorContains(script, mScriptListeners)) mScriptListeners.push_back(script); } void MidiController::RemoveConnection(int control, MidiMessageType messageType, int channel, int page) { IUIControl* removed = nullptr; for (auto i = mConnections.begin(); i != mConnections.end(); ++i) { if ((*i)->mControl == control && (*i)->mMessageType == messageType && (*i)->mChannel == channel && ((*i)->mPage == page || (*i)->mPageless)) { removed = (*i)->mUIControl; delete *i; i = mConnections.erase(i); break; } } if (removed) { bool remotelyControlled = false; for (auto i = mConnections.begin(); i != mConnections.end(); ++i) { if ((*i)->mUIControl == removed) { remotelyControlled = true; break; } } if (!remotelyControlled) removed->RemoveRemoteController(); } } void MidiController::Poll() { bool lastBlink = mBlink; mBlink = int(TheTransport->GetMeasurePos(gTime) * TheTransport->GetTimeSigTop() * 2) % 2 == 0; if (IsInputConnected(!K(immediate)) || mReconnectWaitTimer > 0) { if (!mIsConnected && gTime - mInitialConnectionTime > 1000) { if (mNonstandardController) { if (mNonstandardController->Reconnect()) { ResyncControllerState(); mIsConnected = true; for (auto* grid : mGrids) { if (grid->mGridControlTarget[mControllerPage] != nullptr && grid->mGridControlTarget[mControllerPage]->GetGridController() != nullptr) dynamic_cast<GridControllerMidi*>(grid->mGridControlTarget[mControllerPage]->GetGridController())->OnControllerPageSelected(); } } } else { if (mReconnectWaitTimer <= 0) { mReconnectWaitTimer = 1000; mDevice.DisconnectInput(); mDevice.DisconnectOutput(); } else { mReconnectWaitTimer -= 1 / (ofGetFrameRate()) * 1000; if (mReconnectWaitTimer <= 0) ConnectDevice(); } } if (mIsConnected) { for (auto i = mListeners[mControllerPage].begin(); i != mListeners[mControllerPage].end(); ++i) (*i)->ControllerPageSelected(); } } } else { if (mIsConnected) { mDevice.DisconnectInput(); mDevice.DisconnectOutput(); mIsConnected = false; } } if (mTwoWay) { for (auto i = mConnections.begin(); i != mConnections.end(); ++i) { UIControlConnection* connection = *i; if (connection->mTwoWay == false) continue; IUIControl* uicontrol = connection->GetUIControl(); if (uicontrol == nullptr) continue; if (JustBoundControl() && uicontrol == sLastBoundUIControl) continue; if (!connection->mPageless && connection->mPage != mControllerPage) continue; int control = connection->mControl; int messageType = connection->mMessageType; if (connection->mFeedbackControl != -1) // "self" { control = connection->mFeedbackControl % 128; if (connection->mFeedbackControl < 128) messageType = kMidiMessage_Control; else messageType = kMidiMessage_Note; } if (connection->mFeedbackControl == -2) // "none" continue; bool shouldUpdateOutput = false; int curValue = int(uicontrol->GetMidiValue() * 127); if (curValue != connection->mLastControlValue) shouldUpdateOutput = true; if (connection->mBlink && lastBlink != mBlink) shouldUpdateOutput = true; if (mShouldSendControllerInfoStrings && uicontrol->GetDisplayValue(uicontrol->GetValue()) != connection->mLastDisplayValue) shouldUpdateOutput = true; if (shouldUpdateOutput) { if (connection->mType == kControlType_Toggle) { int outVal = curValue; if (curValue && (connection->mMidiOnValue != 127 || connection->mBlink)) { if (connection->mBlink == false) outVal = connection->mMidiOnValue; else outVal = mBlink ? connection->mMidiOnValue : connection->mMidiOffValue; } else if (!curValue && connection->mMidiOffValue != 0) { outVal = connection->mMidiOffValue; } if (messageType == kMidiMessage_Note) SendNote(mControllerPage, control, outVal, true, connection->mChannel); else if (messageType == kMidiMessage_Control) SendCC(mControllerPage, control, outVal, connection->mChannel); else if (messageType == kMidiMessage_PitchBend) SendPitchBend(mControllerPage, outVal, connection->mChannel); } else if (connection->mType == kControlType_Slider) { int outVal = curValue; if (connection->mMidiOnValue != 127 || connection->mMidiOffValue != 0) //uses defined slider range for output { outVal = int((curValue / 127.0f) * (connection->mMidiOnValue - connection->mMidiOffValue) + connection->mMidiOffValue); } if (messageType == kMidiMessage_Note) SendNote(mControllerPage, control, outVal, true, connection->mChannel); else if (messageType == kMidiMessage_Control) SendCC(mControllerPage, control, outVal, connection->mChannel); else if (messageType == kMidiMessage_PitchBend) SendPitchBend(mControllerPage, outVal, connection->mChannel); } else if (connection->mType == kControlType_SetValue) { float realValue = uicontrol->GetValue(); bool valuesAreEqual = fabsf(realValue - connection->mValue) < .0001f; int outVal = 0; if ((!uicontrol->IsBitmask() && valuesAreEqual) || (uicontrol->IsBitmask() && ((int)realValue & (1 << (int)connection->mValue)))) { if (connection->mBlink == false) outVal = connection->mMidiOnValue; else outVal = mBlink ? connection->mMidiOnValue : connection->mMidiOffValue; } else { outVal = connection->mMidiOffValue; } if (messageType == kMidiMessage_Note) SendNote(mControllerPage, control, outVal, true, connection->mChannel); else if (messageType == kMidiMessage_Control) SendCC(mControllerPage, control, outVal, connection->mChannel); else if (messageType == kMidiMessage_PitchBend) SendPitchBend(mControllerPage, outVal, connection->mChannel); } else if (connection->mType == kControlType_Direct) { curValue = uicontrol->GetValue(); if (messageType == kMidiMessage_Note) SendNote(mControllerPage, control, uicontrol->GetValue(), true, connection->mChannel); else if (messageType == kMidiMessage_Control) SendCC(mControllerPage, control, uicontrol->GetValue(), connection->mChannel); else if (messageType == kMidiMessage_PitchBend) SendPitchBend(mControllerPage, uicontrol->GetValue(), connection->mChannel); } connection->mLastControlValue = curValue; if (mShouldSendControllerInfoStrings && connection->mType != kControlType_SetValue && connection->mType != kControlType_SetValueOnRelease) { std::string displayValue = uicontrol->GetDisplayValue(uicontrol->GetValue()); SendControllerInfoString(control, 1, displayValue); connection->mLastDisplayValue = displayValue; } } } } if (mNonstandardController != nullptr) mNonstandardController->Poll(); auto connections = mConnections; for (auto* connection : connections) connection->Poll(); } void MidiController::Exit() { IDrawableModule::Exit(); for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; if (connection->mMessageType == kMidiMessage_Control) mDevice.SendCC(connection->mControl, 0, connection->mChannel); if (connection->mMessageType == kMidiMessage_Note) mDevice.SendNote(gTime, connection->mControl, 0, false, connection->mChannel); } } void MidiController::DrawModule() { if (gTime - mLastActivityTime > 0 && gTime - mLastActivityTime < 200) { ofPushStyle(); if (mLastActivityBound) ofSetColor(0, 255, 0, 255 * (1 - (gTime - mLastActivityTime) / 200)); else ofSetColor(255, 0, 0, 255 * (1 - (gTime - mLastActivityTime) / 200)); ofFill(); ofRect(30 + gFont.GetStringWidth(Name(), 13), -11, 10, 10); ofPopStyle(); } if (!mIsConnected) { float xStart = 30 + gFont.GetStringWidth(Name(), 13); float yStart = -11; ofPushStyle(); ofSetColor(ofColor::red); ofLine(xStart, yStart, xStart + 10, yStart + 10); ofLine(xStart + 10, yStart, xStart, yStart + 10); ofPopStyle(); } if (TheSynth->GetLastClickedModule() == this) { for (auto i = mListeners[mControllerPage].begin(); i != mListeners[mControllerPage].end(); ++i) DrawConnection(dynamic_cast<IDrawableModule*>(*i)); } if (Minimized() || IsVisible() == false) return; if (!mHasCreatedConnectionUIControls) { int i = 0; for (UIControlConnection* connection : mConnections) { connection->CreateUIControls(i); ++i; } mHasCreatedConnectionUIControls = true; } mControllerList->Draw(); mMappingDisplayModeSelector->Draw(); mBindCheckbox->Draw(); mPageSelector->Draw(); //mDrawCablesCheckbox->Draw(); mLayoutFileDropdown->SetShowing(mMappingDisplayMode == kLayout); mLayoutFileDropdown->Draw(); mOscInPortEntry->SetShowing(mDeviceIn == "osccontroller" && mMappingDisplayMode == kLayout); mOscInPortEntry->Draw(); mMonomeDeviceDropdown->SetShowing(mDeviceIn == "monome" && mMappingDisplayMode == kLayout); mMonomeDeviceDropdown->Draw(); for (int i = 0; i < NUM_LAYOUT_CONTROLS; ++i) { if (mLayoutControls[i].mControlCable) mLayoutControls[i].mControlCable->SetEnabled(false); } for (auto* grid : mGrids) { if (grid->mGridCable) grid->mGridCable->SetEnabled(mMappingDisplayMode == kLayout); } if (mMappingDisplayMode == kHide) { for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; connection->SetShowing(false); //set all to not be showing } } else { float w, h; GetDimensions(w, h); DrawTextNormal("last input: " + mLastInput, 60, h - 5); if (gTime - mLastActivityTime > 0 && gTime - mLastActivityTime < 200) { ofPushStyle(); if (mLastActivityBound) ofSetColor(0, 255, 0, 255 * (1 - (gTime - mLastActivityTime) / 200)); else ofSetColor(255, 0, 0, 255 * (1 - (gTime - mLastActivityTime) / 200)); ofFill(); ofRect(48, h - 14, 10, 10); ofPopStyle(); } mPageSelector->SetShowing(true); } if (mMappingDisplayMode == kLayout) { ofPushStyle(); if (mReconnectWaitTimer > 0) { ofSetColor(ofColor::yellow); DrawTextNormal("reconnecting...", 3, 63); } else if (mIsConnected) { ofSetColor(ofColor::green); DrawTextNormal("connected", 3, 63); } else { ofSetColor(ofColor::red); DrawTextNormal("not connected", 3, 63); } ofPopStyle(); ofPushStyle(); ofNoFill(); for (int i = 0; i < NUM_LAYOUT_CONTROLS; ++i) { ControlLayoutElement& control = mLayoutControls[i]; if (control.mActive) { ofVec2f center(control.mPosition.x + control.mDimensions.x / 2, control.mPosition.y + control.mDimensions.y / 2); float uiControlValue = 0; if (control.mControlCable) { control.mControlCable->SetEnabled(UIControlConnection::sDrawCables); control.mControlCable->SetManualPosition(center.x, center.y); control.mControlCable->SetPatchCableDrawMode(kPatchCableDrawMode_SourceOnHoverOnly); UIControlConnection* connection = GetConnectionForControl(control.mType, control.mControl); if (connection) { control.mControlCable->SetTarget(connection->mUIControl); if (connection->mUIControl) { uiControlValue = connection->mUIControl->GetMidiValue(); control.mControlCable->GetPatchCables()[0]->SetUIControlConnection(connection); } } else { if (PatchCable::sActivePatchCable == nullptr) control.mControlCable->ClearPatchCables(); } } if (gTime - control.mLastActivityTime < 200) { ofPushStyle(); if (control.mControlCable && control.mControlCable->GetTarget()) ofSetColor(0, 255, 0, 255 * (1 - (gTime - control.mLastActivityTime) / 200)); else ofSetColor(255, 0, 0, 255 * (1 - (gTime - control.mLastActivityTime) / 200)); ofFill(); ofRect(control.mPosition.x, control.mPosition.y, 5, 5); ofPopStyle(); } ofPushStyle(); if (mHighlightedLayoutElement == i) { ofSetColor(255, 255, 255, gModuleDrawAlpha); } else { if (control.mLastActivityTime > 0) ofSetColor(IDrawableModule::GetColor(GetModuleCategory()), gModuleDrawAlpha); else ofSetColor(IDrawableModule::GetColor(GetModuleCategory()), gModuleDrawAlpha * .3f); } if (control.mDrawType == kDrawType_Button) { ofRect(control.mPosition.x, control.mPosition.y, control.mDimensions.x, control.mDimensions.y, 4); bool on = control.mLastValue > 0; if (control.mType == kMidiMessage_Program) on = control.mLastValue > 0 && (gTime - control.mLastActivityTime < 250); if (on) { float fadeAmount = ofClamp(ofLerp(.5f, 1, control.mLastValue), 0, 1); ofPushStyle(); ofFill(); ofSetColor(255 * fadeAmount, 255 * fadeAmount, 255 * fadeAmount, gModuleDrawAlpha); ofRect(control.mPosition.x, control.mPosition.y, control.mDimensions.x, control.mDimensions.y, 4); ofPopStyle(); } } if (control.mDrawType == kDrawType_Knob) { float value = control.mLastValue; if (control.mIncrementAmount != 0) value = uiControlValue; ofCircle(center.x, center.y, control.mDimensions.x / 2); ofPushStyle(); ofSetColor(255, 255, 255, gModuleDrawAlpha); float angle = ofLerp(.1f, .9f, value) * FTWO_PI; ofLine(center.x, center.y, center.x - sinf(angle) * control.mDimensions.x / 2, center.y + cosf(angle) * control.mDimensions.x / 2); ofPopStyle(); } if (control.mDrawType == kDrawType_Slider) { float value = control.mLastValue; if (control.mIncrementAmount != 0) value = uiControlValue; ofRect(control.mPosition.x, control.mPosition.y, control.mDimensions.x, control.mDimensions.y, 0); ofPushStyle(); ofSetColor(255, 255, 255, gModuleDrawAlpha); ofFill(); if (control.mDimensions.x > control.mDimensions.y) ofLine(control.mPosition.x + value * control.mDimensions.x, control.mPosition.y, control.mPosition.x + value * control.mDimensions.x, control.mPosition.y + control.mDimensions.y); else ofLine(control.mPosition.x, control.mPosition.y + (1 - value) * control.mDimensions.y, control.mPosition.x + control.mDimensions.x, control.mPosition.y + (1 - value) * control.mDimensions.y); ofPopStyle(); } ofPopStyle(); } } for (auto* grid : mGrids) ofRect(grid->mPosition.x, grid->mPosition.y, grid->mDimensions.x, grid->mDimensions.y); ofPopStyle(); for (auto connection : mConnections) connection->SetShowing(false); //set all to not be showing ofPushStyle(); ofFill(); ofSetColor(50, 50, 50, gModuleDrawAlpha * .5f); ofRect(kLayoutControlsX, kLayoutControlsY, 235, 140); ofPopStyle(); if (mLayoutLoadError != "") gFont.DrawStringWrap(mLayoutLoadError, 13, 3, kLayoutControlsY + 160, 235); if (mHighlightedLayoutElement != -1) { UIControlConnection* connection = GetConnectionForControl(mLayoutControls[mHighlightedLayoutElement].mType, mLayoutControls[mHighlightedLayoutElement].mControl); if (connection) connection->DrawLayout(); } } if (mMappingDisplayMode == kList) { ofPushStyle(); if (mIsConnected) { ofSetColor(ofColor::green); DrawTextNormal("connected", 165, 13); } else { ofSetColor(ofColor::red); DrawTextNormal("not connected", 165, 13); } ofPopStyle(); float w, h; GetDimensions(w, h); mAddConnectionButton->SetPosition(mAddConnectionButton->GetPosition(true).x, h - 17); mAddConnectionButton->Draw(); //DrawTextNormal(" MIDI out all", 12, 34); //DrawTextNormal("midi num chan path type value inc feedback off on blink pages", 12, 46); std::list<UIControlConnection*> toDraw; //draw pageless ones first for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; connection->SetShowing(false); //set all to not be showing if (connection->mPageless) { toDraw.push_back(connection); } } //draw ones on this page second for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; if (connection->mPage == mControllerPage && connection->mPageless == false) { toDraw.push_back(connection); } } int i = 0; for (auto iter = toDraw.begin(); iter != toDraw.end();) { UIControlConnection* connection = *iter; ++iter; UIControlConnection* next = nullptr; if (iter != toDraw.end()) next = *iter; connection->SetNext(next); connection->DrawList(i); ControlLayoutElement& control = GetLayoutControl(connection->mControl, connection->mMessageType); if (control.mControlCable) { int x = 370; int y = 59 + 20 * i; control.mControlCable->SetEnabled(UIControlConnection::sDrawCables); control.mControlCable->SetManualPosition(x, y); control.mControlCable->SetPatchCableDrawMode(kPatchCableDrawMode_Normal); control.mControlCable->SetTarget(connection->mUIControl); if (connection->mUIControl) control.mControlCable->GetPatchCables()[0]->SetUIControlConnection(connection); } ++i; } } } namespace { const int kHoveredLayoutElement_GridOffset = 1000; } void MidiController::DrawModuleUnclipped() { if (mHoveredLayoutElement != -1) { std::string tooltip; ofVec2f pos; if (mHoveredLayoutElement < kHoveredLayoutElement_GridOffset) { tooltip = GetLayoutTooltip(mHoveredLayoutElement); pos = mLayoutControls[mHoveredLayoutElement].mPosition; pos.x += mLayoutControls[mHoveredLayoutElement].mDimensions.x + 3; pos.y += mLayoutControls[mHoveredLayoutElement].mDimensions.y / 2; } else { tooltip = "grid"; auto* grid = mGrids[mHoveredLayoutElement - kHoveredLayoutElement_GridOffset]; pos = grid->mPosition; pos.x += 18; } float width = GetStringWidth(tooltip); ofFill(); ofSetColor(50, 50, 50); ofRect(pos.x, pos.y, width + 10, 15); ofNoFill(); ofSetColor(255, 255, 255); ofRect(pos.x, pos.y, width + 10, 15); ofSetColor(255, 255, 255); DrawTextNormal(tooltip, pos.x + 5, pos.y + 12); } } std::string MidiController::GetLayoutTooltip(int controlIndex) { if (controlIndex >= 0 && controlIndex < mLayoutControls.size()) { if (mNonstandardController != nullptr) return mNonstandardController->GetControlTooltip(mLayoutControls[controlIndex].mType, mLayoutControls[controlIndex].mControl); return GetDefaultTooltip(mLayoutControls[controlIndex].mType, mLayoutControls[controlIndex].mControl); } return ""; } //static std::string MidiController::GetDefaultTooltip(MidiMessageType type, int control) { std::string str; if (type == kMidiMessage_Note) str = "note "; else if (type == kMidiMessage_Control) str = "cc "; else if (type == kMidiMessage_PitchBend) return "pitchbend"; else if (type == kMidiMessage_Program) str = "program "; return str + ofToString(control); } UIControlConnection* MidiController::GetConnectionForCableSource(const PatchCableSource* source) { for (const auto& c : mLayoutControls) { if (c.mActive && c.mControlCable == source) { return GetConnectionForControl(c.mType, c.mControl); } } return nullptr; } void MidiController::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); if (right) return; if (mMappingDisplayMode == kLayout) { for (int i = 0; i < NUM_LAYOUT_CONTROLS; ++i) { ControlLayoutElement& control = mLayoutControls[i]; if (control.mActive) { ofRectangle controlRect(control.mPosition.x, control.mPosition.y, control.mDimensions.x, control.mDimensions.y); if (controlRect.contains(x, y)) { mHighlightedLayoutElement = i; break; } } } } } bool MidiController::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); mHoveredLayoutElement = -1; if (mMappingDisplayMode == kLayout) { for (int i = 0; i < NUM_LAYOUT_CONTROLS; ++i) { ControlLayoutElement& control = mLayoutControls[i]; if (control.mActive) { ofRectangle controlRect(control.mPosition.x, control.mPosition.y, control.mDimensions.x, control.mDimensions.y); if (controlRect.contains(x, y)) { mHoveredLayoutElement = i; control.mControlCable->SetPatchCableDrawMode(kPatchCableDrawMode_Normal); } else { control.mControlCable->SetPatchCableDrawMode(kPatchCableDrawMode_SourceOnHoverOnly); } } } int i = 0; for (auto* grid : mGrids) { ofRectangle controlRect(grid->mPosition.x - 5, grid->mPosition.y - 5, 10, 10); if (controlRect.contains(x, y)) mHoveredLayoutElement = i + kHoveredLayoutElement_GridOffset; ++i; } } return false; } bool MidiController::IsInputConnected(bool immediate) { if (mNonstandardController != nullptr) return mNonstandardController->IsInputConnected(); return mDevice.IsInputConnected(immediate); } int MidiController::GetNumConnectionsOnPage(int page) { int i = 0; for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; if (connection->mPage == mControllerPage || connection->mPageless) ++i; } return i; } void MidiController::SetEntirePageToZero(int page) { for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; if (connection->mPage == page && connection->mPageless == false) { if (connection->mMessageType == kMidiMessage_Control) mDevice.SendCC(connection->mControl, 0, connection->mChannel); if (connection->mMessageType == kMidiMessage_Note) mDevice.SendNote(gTime, connection->mControl, 0, false, connection->mChannel); } } } void MidiController::HighlightPageControls(int page) { for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; if (connection->mPage == page && connection->mPageless == false) { if (connection->mUIControl) connection->mUIControl->StartBeacon(); } } } void MidiController::GetModuleDimensions(float& width, float& height) { if (mMappingDisplayMode == kList) { width = 943; height = 72 + 20 * GetNumConnectionsOnPage(mControllerPage); } else if (mMappingDisplayMode == kLayout) { width = MAX(408, mLayoutWidth); height = MAX(145, mLayoutHeight); } else { width = 163; height = 54; } } void MidiController::ResyncControllerState() { if (mControllerPage >= 0 && mControllerPage < mListeners.size()) { for (auto i = mListeners[mControllerPage].begin(); i != mListeners[mControllerPage].end(); ++i) (*i)->ControllerPageSelected(); } for (int i = 0; i < NUM_LAYOUT_CONTROLS; ++i) { if (mLayoutControls[i].mActive) { UIControlConnection* connection = GetConnectionForControl(mLayoutControls[i].mType, mLayoutControls[i].mControl); if (connection && mLayoutControls[i].mControlCable) { mLayoutControls[i].mControlCable->SetTarget(connection->mUIControl); if (connection->mUIControl != nullptr) { if (mShouldSendControllerInfoStrings) { SendControllerInfoString(mLayoutControls[i].mControl, 0, connection->mUIControl->Path()); if (connection->mType == kControlType_SetValue || connection->mType == kControlType_SetValueOnRelease) { SendControllerInfoString(mLayoutControls[i].mControl, 1, connection->mUIControl->GetDisplayValue(connection->mValue)); } } } } } } for (auto* grid : mGrids) { if (grid->mGridControlTarget[mControllerPage] != nullptr) { //reset target GridControlTarget* target = grid->mGridControlTarget[mControllerPage]; grid->mGridCable->ClearPatchCables(); grid->mGridCable->SetTarget(target); } else { grid->mGridCable->ClearPatchCables(); } } HighlightPageControls(mControllerPage); for (auto i = mConnections.begin(); i != mConnections.end(); ++i) { (*i)->mLastControlValue = -1; } } void MidiController::SendNote(int page, int pitch, int velocity, bool forceNoteOn /*= false*/, int channel /*= -1*/) { if (channel == -1) channel = mOutChannel; if (page == mControllerPage) { mDevice.SendNote(gTime, pitch, velocity, forceNoteOn, channel); if (mNonstandardController) mNonstandardController->SendValue(page, pitch, velocity / 127.0f, forceNoteOn, channel); } } void MidiController::SendCC(int page, int ctl, int value, int channel /*= -1*/) { if (channel == -1) channel = mOutChannel; if (page == mControllerPage) { mDevice.SendCC(ctl, value, channel); if (mNonstandardController) mNonstandardController->SendValue(page, ctl, value / 127.0f, channel); } } void MidiController::SendProgramChange(int page, int program, int channel /*= -1*/) { if (channel == -1) channel = mOutChannel; if (page == mControllerPage) { mDevice.SendProgramChange(program, channel); } } void MidiController::SendPitchBend(int page, int bend, int channel /*= -1*/) { if (channel == -1) channel = mOutChannel; if (page == mControllerPage) mDevice.SendPitchBend(bend, channel); } void MidiController::SendData(int page, unsigned char a, unsigned char b, unsigned char c) { if (page == mControllerPage) { mDevice.SendData(a, b, c); } } void MidiController::SendSysEx(int page, std::string data) { if (page == mControllerPage) { mDevice.SendSysEx(data); } } UIControlConnection* MidiController::GetConnectionForControl(MidiMessageType messageType, int control) { for (auto i = mConnections.begin(); i != mConnections.end(); ++i) { UIControlConnection* connection = *i; if (connection->mMessageType == messageType && connection->mControl == control && (connection->mPageless || connection->mPage == mControllerPage)) return connection; } return nullptr; } ControlLayoutElement& MidiController::GetLayoutControl(int control, MidiMessageType type) { int index = NUM_LAYOUT_CONTROLS - 1; if (type == kMidiMessage_Control) index = control; else if (type == kMidiMessage_Note) index = control + 128; else if (type == kMidiMessage_Program) index = control + 128 + 128; else if (type == kMidiMessage_PitchBend) index = 128 + 128 + 128; return mLayoutControls[index]; } void MidiController::LoadControllerLayout(std::string filename) { if (filename != kDefaultLayout) mLastLoadedLayoutFile = ofToDataPath("controllers/" + filename); else mLastLoadedLayoutFile = ""; for (int i = 0; i < mLayoutFileDropdown->GetNumValues(); ++i) { if (filename == mLayoutFileDropdown->GetLabel(i)) mLayoutFileIndex = i; } for (int i = 0; i < NUM_LAYOUT_CONTROLS; ++i) { mLayoutControls[i].mActive = false; RemovePatchCableSource(mLayoutControls[i].mControlCable); mLayoutControls[i].mControlCable = nullptr; } for (auto grid : mGrids) { RemovePatchCableSource(grid->mGridCable); delete grid; } mGrids.clear(); bool useDefaultLayout = true; bool loaded = mLastLoadedLayoutFile != "" && mLayoutData.open(mLastLoadedLayoutFile); try { if (loaded) { if (mNonstandardController != nullptr) mNonstandardController->SetLayoutData(mLayoutData); if (!mLayoutData["outchannel"].isNull()) { mOutChannel = mLayoutData["outchannel"].asInt(); mModuleSaveData.SetInt("outchannel", mOutChannel); } if (!mLayoutData["outdevice"].isNull()) { mDeviceOut = mLayoutData["outdevice"].asString(); mModuleSaveData.SetString("deviceout", mDeviceOut); mTwoWay = true; mDevice.ConnectOutput(mDeviceOut.c_str(), mOutChannel); } if (!mLayoutData["usechannelasvoice"].isNull()) { SetUseChannelAsVoice(mLayoutData["usechannelasvoice"].asBool()); mModuleSaveData.SetBool("usechannelasvoice", mUseChannelAsVoice); } if (!mLayoutData["pitchbendrange"].isNull()) { SetPitchBendRange(mLayoutData["pitchbendrange"].asInt()); mModuleSaveData.SetFloat("pitchbendrange", mPitchBendRange); } if (!mLayoutData["modwheelcc"].isNull()) { mModwheelCC = mLayoutData["modwheelcc"].asInt(); mModuleSaveData.SetInt("modwheelcc(1or74)", mModwheelCC); } if (!mLayoutData["modwheeloffset"].isNull()) { mModWheelOffset = mLayoutData["modwheeloffset"].asDouble(); mModuleSaveData.SetFloat("modwheeloffset", mModWheelOffset); } if (!mLayoutData["pressureoffset"].isNull()) { mPressureOffset = mLayoutData["pressureoffset"].asDouble(); mModuleSaveData.SetFloat("pressureoffset", mPressureOffset); } if (!mLayoutData["twoway_on_change"].isNull()) { mSendTwoWayOnChange = mLayoutData["twoway_on_change"].asBool(); mModuleSaveData.SetBool("twoway_on_change", mSendTwoWayOnChange); } if (!mLayoutData["resend_feedback_on_release"].isNull()) { mResendFeedbackOnRelease = mLayoutData["resend_feedback_on_release"].asBool(); mModuleSaveData.SetBool("resend_feedback_on_release", mResendFeedbackOnRelease); } if (!mLayoutData["channelfilter"].isNull()) { const int layoutChannelFilter = mLayoutData["channelfilter"].asInt(); if (layoutChannelFilter >= (int)ChannelFilter::k1 && layoutChannelFilter <= (int)ChannelFilter::k16) { mChannelFilter = (ChannelFilter)layoutChannelFilter; // The enum is restored by casting from an int mModuleSaveData.SetInt("channelfilter", layoutChannelFilter); } } if (!mLayoutData["groups"].isNull()) { useDefaultLayout = false; for (int group = 0; group < mLayoutData["groups"].size(); ++group) { int rows = mLayoutData["groups"][group]["rows"].asInt(); int cols = mLayoutData["groups"][group]["cols"].asInt(); ofVec2f pos; pos.x = (mLayoutData["groups"][group]["position"])[0u].asDouble(); pos.y = (mLayoutData["groups"][group]["position"])[1u].asDouble(); ofVec2f dim; dim.x = (mLayoutData["groups"][group]["dimensions"])[0u].asDouble(); dim.y = (mLayoutData["groups"][group]["dimensions"])[1u].asDouble(); ofVec2f spacing; spacing.x = (mLayoutData["groups"][group]["spacing"])[0u].asDouble(); spacing.y = (mLayoutData["groups"][group]["spacing"])[1u].asDouble(); MidiMessageType messageType = kMidiMessage_Control; if (mLayoutData["groups"][group]["messageType"] == "control") messageType = kMidiMessage_Control; if (mLayoutData["groups"][group]["messageType"] == "note") messageType = kMidiMessage_Note; if (mLayoutData["groups"][group]["messageType"] == "pitchbend") messageType = kMidiMessage_PitchBend; if (mLayoutData["groups"][group]["messageType"] == "program") messageType = kMidiMessage_Program; ControlDrawType drawType{ kDrawType_Slider }; if (mLayoutData["groups"][group]["drawType"] == "button") drawType = kDrawType_Button; if (mLayoutData["groups"][group]["drawType"] == "knob") drawType = kDrawType_Knob; if (mLayoutData["groups"][group]["drawType"] == "slider") drawType = kDrawType_Slider; float incrementAmount = 0; if (!mLayoutData["groups"][group]["incremental"].isNull()) incrementAmount = mLayoutData["groups"][group]["incremental"].asBool() ? 1 : 0; if (!mLayoutData["groups"][group]["increment_amount"].isNull()) incrementAmount = mLayoutData["groups"][group]["increment_amount"].asDouble(); bool is14Bit = false; if (!mLayoutData["groups"][group]["14bit"].isNull()) is14Bit = mLayoutData["groups"][group]["14bit"].asBool(); int offVal = 0; int onVal = 127; if (!mLayoutData["groups"][group]["colors"].isNull() && mLayoutData["groups"][group]["colors"].size() > 2) { offVal = mLayoutData["groups"][group]["colors"][0u].asInt(); onVal = mLayoutData["groups"][group]["colors"][2u].asInt(); } ControlType connectionType = kControlType_Default; if (mLayoutData["groups"][group]["connection_type"] == "slider") connectionType = kControlType_Slider; if (mLayoutData["groups"][group]["connection_type"] == "set") connectionType = kControlType_SetValue; if (mLayoutData["groups"][group]["connection_type"] == "release") connectionType = kControlType_SetValueOnRelease; if (mLayoutData["groups"][group]["connection_type"] == "toggle") connectionType = kControlType_Toggle; if (mLayoutData["groups"][group]["connection_type"] == "direct") connectionType = kControlType_Direct; for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { int index = col + row * cols; int control = mLayoutData["groups"][group]["controls"][index].asInt(); GetLayoutControl(control, messageType).Setup(this, messageType, control, drawType, incrementAmount, is14Bit, offVal, onVal, false, connectionType, pos.x + kLayoutButtonsX + spacing.x * col, pos.y + kLayoutButtonsY + spacing.y * row, dim.x, dim.y); //clear out values on controllers /*if (messageType == kMidiMessage_Note) SendNote(0, control, offVal, true); if (messageType == kMidiMessage_Control) SendCC(0, control, offVal);*/ } } bool noGrid = false; if (!mLayoutData["groups"][group]["no_grid"].isNull()) noGrid = mLayoutData["groups"][group]["no_grid"].asBool(); if (!noGrid && drawType == kDrawType_Button && rows * cols >= 8) //we're a button grid { GridLayout* grid = new GridLayout(); grid->mRows = rows; grid->mCols = cols; grid->mPosition.set(pos.x + kLayoutButtonsX - 2, pos.y + kLayoutButtonsY - 2); grid->mDimensions.set(spacing.x * cols + 2, spacing.y * rows + 2); grid->mType = messageType; grid->mGridCable = new PatchCableSource(this, kConnectionType_Grid); grid->mGridCable->SetManualPosition(pos.x + kLayoutButtonsX - 2, pos.y + kLayoutButtonsY - 2); grid->mGridCable->AddTypeFilter("gridcontroller"); AddPatchCableSource(grid->mGridCable); for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { int index = col + row * cols; int control = mLayoutData["groups"][group]["controls"][index].asInt(); grid->mControls.push_back(control); } } if (!mLayoutData["groups"][group]["colors"].isNull() && mLayoutData["groups"][group]["colors"].size() > 0) { for (int i = 0; i < mLayoutData["groups"][group]["colors"].size(); ++i) grid->mColors.push_back(mLayoutData["groups"][group]["colors"][i].asInt()); } else { grid->mColors.push_back(0); grid->mColors.push_back(127); } mGrids.push_back(grid); } } } } } catch (Json::LogicError& e) { loaded = false; TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } if (!loaded) { mLayoutFileIndex = 0; mLayoutData.clear(); if (mLastLoadedLayoutFile == "") mLayoutLoadError = "using default layout. set up controller files in " + ofToDataPath("controllers"); else mLayoutLoadError = "couldn't load layout file at " + mLastLoadedLayoutFile + ", using the default layout instead"; } else { mLayoutLoadError = ""; } if (useDefaultLayout) { const float kSpacingX = 20; const float kSpacingY = 20; for (int i = 0; i < 128; ++i) { GetLayoutControl(i, kMidiMessage_Control).Setup(this, kMidiMessage_Control, i, kDrawType_Slider, 0, false, 0, 127, true, kControlType_Default, i % 8 * kSpacingX + kLayoutButtonsX + 9, i / 8 * kSpacingY + kLayoutButtonsY, kSpacingX * .666f, kSpacingY * .93f); GetLayoutControl(i, kMidiMessage_Note).Setup(this, kMidiMessage_Note, i, kDrawType_Button, 0, false, 0, 127, true, kControlType_Default, i % 8 * kSpacingX + 8 * kSpacingX + kLayoutButtonsX + 15, i / 8 * kSpacingY + kLayoutButtonsY, kSpacingX * .93f, kSpacingY * .93f); } GetLayoutControl(0, kMidiMessage_PitchBend).Setup(this, kMidiMessage_PitchBend, 0, kDrawType_Slider, 0, false, 0, 127, true, kControlType_Default, kLayoutButtonsX + kSpacingX * 17, kLayoutButtonsY, 25, 100); } mLayoutWidth = 0; mLayoutHeight = 300; for (int i = 0; i < NUM_LAYOUT_CONTROLS; ++i) { if (mLayoutControls[i].mActive) { mLayoutWidth = MAX(mLayoutWidth, mLayoutControls[i].mPosition.x + mLayoutControls[i].mDimensions.x + 5); mLayoutHeight = MAX(mLayoutHeight, mLayoutControls[i].mPosition.y + mLayoutControls[i].mDimensions.y + 20); } } } void MidiController::OnDeviceChanged() { if (!mDeviceIn.empty()) { std::string filename = mDeviceIn + ".json"; ofStringReplace(filename, "/", ""); LoadControllerLayout(filename); } else { LoadControllerLayout(kDefaultLayout); } mModulation.GetModWheel(-1)->SetValue(mModWheelOffset); mModulation.GetPressure(-1)->SetValue(mPressureOffset); } void MidiController::CheckboxUpdated(Checkbox* checkbox, double time) { for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; if (checkbox == connection->mPagelessCheckbox) { if (connection->mPageless == false) //just made this not pageless connection->mPage = mControllerPage; //make the current page this connection's page } } } void MidiController::ButtonClicked(ClickButton* button, double time) { if (button == mAddConnectionButton) { int index; for (index = 0; index <= 127; ++index) { bool isAvailable = true; for (auto* connection : mConnections) { if (connection->mMessageType == kMidiMessage_Control && connection->mControl == index) { isAvailable = false; break; } } if (isAvailable) break; } AddControlConnection(kMidiMessage_Control, index, -1, nullptr); } for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; if (button == connection->mRemoveButton) { mConnections.remove(connection); delete connection; break; } if (button == connection->mCopyButton) { UIControlConnection* copy = connection->MakeCopy(); copy->CreateUIControls((int)mConnections.size()); mConnections.push_back(copy); //make a copy of this one break; } } } void MidiController::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mPageSelector) { SetEntirePageToZero(oldVal); ResyncControllerState(); } if (list == mControllerList) { if (TheSynth->GetTopModalFocusItem() == mControllerList->GetModalDropdown()) { ConnectDevice(); OnDeviceChanged(); } else { UpdateControllerIndex(); } } if (list == mMonomeDeviceDropdown) { Monome* monome = dynamic_cast<Monome*>(mNonstandardController); if (monome) monome->ConnectToDevice(mMonomeDeviceDropdown->GetLabel(mMonomeDeviceIndex)); } if (list == mLayoutFileDropdown) { LoadControllerLayout(mLayoutFileDropdown->GetLabel(mLayoutFileIndex)); } } void MidiController::DropdownClicked(DropdownList* list) { if (list == mControllerList) { BuildControllerList(); } } void MidiController::RadioButtonUpdated(RadioButton* radio, int oldVal, double time) { if (radio == mMappingDisplayModeSelector) { mAddConnectionButton->SetShowing(mMappingDisplayMode == kList); } } void MidiController::TextEntryActivated(TextEntry* entry) { //if you click a text entry while a UI control is in bind mode, use that one's path for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; if (entry == connection->mUIControlPathEntry) { if (gBindToUIControl) { if (connection->mUIControl) connection->mUIControl->RemoveRemoteController(); connection->SetUIControl(gBindToUIControl); gBindToUIControl->AddRemoteController(); gBindToUIControl = nullptr; IKeyboardFocusListener::ClearActiveKeyboardFocus(!K(notifyListeners)); } } } } void MidiController::TextEntryComplete(TextEntry* entry) { for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { UIControlConnection* connection = *iter; if (entry == connection->mUIControlPathEntry) connection->SetUIControl(connection->mUIControlPathInput); if (entry == connection->mValueEntry) { if (mShouldSendControllerInfoStrings) { if (connection->mType == kControlType_SetValue || connection->mType == kControlType_SetValueOnRelease) { SendControllerInfoString(connection->mControl, 1, connection->mUIControl->GetDisplayValue(connection->mValue)); } } } } if (entry == mOscInPortEntry) { OscController* osc = dynamic_cast<OscController*>(mNonstandardController); if (osc != nullptr) osc->SetInPort(mOscInPort); } } void MidiController::PreRepatch(PatchCableSource* cableSource) { for (auto* grid : mGrids) { if (cableSource == grid->mGridCable) { grid->mGridControlTarget[mControllerPage] = dynamic_cast<GridControlTarget*>(cableSource->GetTarget()); if (grid->mGridControlTarget[mControllerPage] && grid->mGridControlTarget[mControllerPage]->GetGridController()) { GridControllerMidi* gridMidi = dynamic_cast<GridControllerMidi*>(grid->mGridControlTarget[mControllerPage]->GetGridController()); if (gridMidi != nullptr) gridMidi->UnhookController(); } return; } } } void MidiController::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { for (auto* grid : mGrids) { if (cableSource == grid->mGridCable) { grid->mGridControlTarget[mControllerPage] = dynamic_cast<GridControlTarget*>(cableSource->GetTarget()); if (grid->mGridControlTarget[mControllerPage]) { GridControllerMidi* gridController = new GridControllerMidi(); grid->mGridControlTarget[mControllerPage]->SetGridController(gridController); gridController->SetUp(grid, mControllerPage, this); } return; } } bool repatched = false; for (auto* connection : mConnections) { repatched = connection->PostRepatch(cableSource, fromUserClick); if (repatched) break; } if (cableSource->GetTarget()) //need to make connection { if (fromUserClick && !repatched) { int layoutControl = GetLayoutControlIndexForCable(cableSource); if (layoutControl != -1) { UIControlConnection* connection = AddControlConnection(mLayoutControls[layoutControl].mType, mLayoutControls[layoutControl].mControl, -1, dynamic_cast<IUIControl*>(cableSource->GetTarget())); RadioButton* radioButton = dynamic_cast<RadioButton*>(cableSource->GetTarget()); if (radioButton && mLayoutControls[layoutControl].mDrawType == kDrawType_Button) { connection->mType = kControlType_SetValue; float closestSq = FLT_MAX; int closestIdx = 0; ofVec2f mousePos(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()); for (int i = 0; i < radioButton->GetNumValues(); ++i) { float distSq = (mousePos - radioButton->GetOptionPosition(i)).distanceSquared(); if (distSq < closestSq) { closestSq = distSq; closestIdx = i; } } connection->mValue = closestIdx; } } } } else // need to remove a connection if no cables remain { auto uiConnection = GetConnectionForCableSource(cableSource); if (uiConnection == nullptr || (uiConnection->mSpecialBinding == kSpecialBinding_None && uiConnection->mUIControlPathInput[0] != 0)) { mConnections.remove(uiConnection); delete uiConnection; } } } void MidiController::OnCableGrabbed(PatchCableSource* cableSource) { int layoutControl = GetLayoutControlIndexForCable(cableSource); if (layoutControl != -1) { mHighlightedLayoutElement = layoutControl; } } int MidiController::GetLayoutControlIndexForCable(PatchCableSource* cable) const { for (int i = 0; i < NUM_LAYOUT_CONTROLS; ++i) { if (mLayoutControls[i].mControlCable == cable) return i; } return -1; } int MidiController::GetLayoutControlIndexForMidi(MidiMessageType type, int control) const { for (int i = 0; i < NUM_LAYOUT_CONTROLS; ++i) { if (mLayoutControls[i].mType == type && mLayoutControls[i].mControl == control) return i; } return -1; } static std::vector<std::string> sCachedInputDevices; //static std::vector<std::string> MidiController::GetAvailableInputDevices() { if (!juce::MessageManager::existsAndIsCurrentThread()) return sCachedInputDevices; std::vector<std::string> devices; for (auto& d : MidiInput::getAvailableDevices()) { if (d.identifier == "blah") //my BCF-2000 and BCR-2000 both report as a BCF-2000, come up with some hack here to name it correctly devices.push_back("BCR-2000"); else devices.push_back(d.name.toStdString()); } devices.push_back("keyboard"); devices.push_back("monome"); devices.push_back("osccontroller"); sCachedInputDevices = devices; return devices; } static std::vector<std::string> sCachedOutputDevices; //static std::vector<std::string> MidiController::GetAvailableOutputDevices() { if (!juce::MessageManager::existsAndIsCurrentThread()) return sCachedOutputDevices; std::vector<std::string> devices; for (auto& d : MidiOutput::getAvailableDevices()) devices.push_back(d.name.toStdString()); devices.push_back("keyboard"); devices.push_back("monome"); devices.push_back("osccontroller"); sCachedOutputDevices = devices; return devices; } namespace { void FillMidiInput(DropdownList* list) { assert(list); const auto& devices = MidiController::GetAvailableInputDevices(); for (int i = 0; i < devices.size(); ++i) list->AddLabel(devices[i].c_str(), i); } void FillMidiOutput(DropdownList* list) { assert(list); const auto& devices = MidiController::GetAvailableOutputDevices(); for (int i = 0; i < devices.size(); ++i) list->AddLabel(devices[i].c_str(), i); } } void MidiController::BuildControllerList() { mControllerList->Clear(); FillMidiInput(mControllerList); } void MidiController::ConnectDevice() { mDevice.DisconnectInput(); mDevice.DisconnectOutput(); ResyncControllerState(); std::string deviceInName = mControllerList->GetLabel(mControllerIndex); std::string deviceOutName = String(deviceInName).replace("Input", "Output").replace("input", "output").toStdString(); bool hasOutput = false; for (const auto& device : MidiOutput::getAvailableDevices()) { if (device.name.toStdString() == deviceOutName) { hasOutput = true; break; } } mDeviceIn = deviceInName; mDeviceOut = hasOutput ? deviceOutName : ""; mModuleSaveData.SetString("devicein", mDeviceIn); mModuleSaveData.SetString("deviceout", mDeviceOut); if (mDeviceIn == "xboxcontroller") { //TODO_PORT(Ryan) //Xbox360Controller* xbox = new Xbox360Controller(this); //mNonstandardController = xbox; } else if (mDeviceIn == "keyboard") { if (dynamic_cast<Monome*>(mNonstandardController) == nullptr) { QwertyController* qwerty = new QwertyController(this); mNonstandardController = qwerty; } } else if (mDeviceIn == "monome") { if (dynamic_cast<Monome*>(mNonstandardController) == nullptr) { Monome* monome = new Monome(this); monome->UpdateDeviceList(mMonomeDeviceDropdown); mNonstandardController = monome; } } else if (mDeviceIn == "osccontroller") { if (dynamic_cast<OscController*>(mNonstandardController) == nullptr) { OscController* osc = new OscController(this, "", -1, mOscInPort); mNonstandardController = osc; } } else if (mDeviceIn == "midicapturer") { if (dynamic_cast<MidiCapturerDummyController*>(mNonstandardController) == nullptr) { MidiCapturerDummyController* cap = new MidiCapturerDummyController(this); mNonstandardController = cap; } } else if (mDeviceIn.length() > 0) //not one of the special options, must be midi { if (mNonstandardController != nullptr) { delete mNonstandardController; mNonstandardController = nullptr; } mDevice.ConnectInput(mDeviceIn.c_str()); } if (mDeviceOut.length() > 0 && mNonstandardController == nullptr) { mTwoWay = true; mDevice.ConnectOutput(mDeviceOut.c_str(), mOutChannel); } if (mDeviceOut == "Bespoke Turn") mShouldSendControllerInfoStrings = true; else mShouldSendControllerInfoStrings = false; if (mNonstandardController != nullptr) mNonstandardController->SetLayoutData(mLayoutData); mIsConnected = IsInputConnected(K(immediate)); mInitialConnectionTime = gTime; } void MidiController::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("devicein", moduleInfo, "", FillMidiInput); mModuleSaveData.LoadString("deviceout", moduleInfo, "", FillMidiOutput); mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadFloat("velocitymult", moduleInfo, 1, 0, 10, K(isTextField)); mModuleSaveData.LoadBool("usechannelasvoice", moduleInfo, false); EnumMap channelMap; channelMap["any"] = (int)ChannelFilter::kAny; channelMap["01"] = (int)ChannelFilter::k1; channelMap["02"] = (int)ChannelFilter::k2; channelMap["03"] = (int)ChannelFilter::k3; channelMap["04"] = (int)ChannelFilter::k4; channelMap["05"] = (int)ChannelFilter::k5; channelMap["06"] = (int)ChannelFilter::k6; channelMap["07"] = (int)ChannelFilter::k7; channelMap["08"] = (int)ChannelFilter::k8; channelMap["09"] = (int)ChannelFilter::k9; channelMap["10"] = (int)ChannelFilter::k10; channelMap["11"] = (int)ChannelFilter::k11; channelMap["12"] = (int)ChannelFilter::k12; channelMap["13"] = (int)ChannelFilter::k13; channelMap["14"] = (int)ChannelFilter::k14; channelMap["15"] = (int)ChannelFilter::k15; channelMap["16"] = (int)ChannelFilter::k16; mModuleSaveData.LoadEnum<ChannelFilter>("channelfilter", moduleInfo, (int)ChannelFilter::kAny, nullptr, &channelMap); mModuleSaveData.LoadInt("noteoffset", moduleInfo, 0, -999, 999, K(isTextField)); mModuleSaveData.LoadFloat("pitchbendrange", moduleInfo, 2, 1, 96, K(isTextField)); mModuleSaveData.LoadInt("modwheelcc(1or74)", moduleInfo, 1, 0, 127, K(isTextField)); mModuleSaveData.LoadFloat("modwheeloffset", moduleInfo, 0, 0, 1, K(isTextField)); mModuleSaveData.LoadFloat("pressureoffset", moduleInfo, 0, 0, 1, K(isTextField)); mModuleSaveData.LoadInt("outchannel", moduleInfo, 1, 1, 16); mModuleSaveData.LoadBool("send_cc_output", moduleInfo, false); mModuleSaveData.LoadBool("negativeedge", moduleInfo, false); mModuleSaveData.LoadBool("incrementalsliders", moduleInfo, false); mModuleSaveData.LoadBool("twoway_on_change", moduleInfo, true); mModuleSaveData.LoadBool("resend_feedback_on_release", moduleInfo, false); mModuleSaveData.LoadBool("show_activity_ui_overlay", moduleInfo, true); mConnectionsJson = moduleInfo["connections"]; SetUpFromSaveData(); } void MidiController::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); SetVelocityMult(mModuleSaveData.GetFloat("velocitymult")); SetUseChannelAsVoice(mModuleSaveData.GetBool("usechannelasvoice")); mChannelFilter = mModuleSaveData.GetEnum<ChannelFilter>("channelfilter"); SetNoteOffset(mModuleSaveData.GetInt("noteoffset")); SetPitchBendRange(mModuleSaveData.GetFloat("pitchbendrange")); mModwheelCC = mModuleSaveData.GetInt("modwheelcc(1or74)"); mModWheelOffset = mModuleSaveData.GetFloat("modwheeloffset"); mPressureOffset = mModuleSaveData.GetFloat("pressureoffset"); mModulation.GetModWheel(-1)->SetValue(mModWheelOffset); mModulation.GetPressure(-1)->SetValue(mPressureOffset); mDeviceIn = mModuleSaveData.GetString("devicein"); mDeviceOut = mModuleSaveData.GetString("deviceout"); mOutChannel = mModuleSaveData.GetInt("outchannel"); assert(mOutChannel > 0 && mOutChannel <= 16); mSendCCOutput = mModuleSaveData.GetBool("send_cc_output"); UseNegativeEdge(mModuleSaveData.GetBool("negativeedge")); mSlidersDefaultToIncremental = mModuleSaveData.GetBool("incrementalsliders"); mSendTwoWayOnChange = mModuleSaveData.GetBool("twoway_on_change"); mResendFeedbackOnRelease = mModuleSaveData.GetBool("resend_feedback_on_release"); mShowActivityUIOverlay = mModuleSaveData.GetBool("show_activity_ui_overlay"); BuildControllerList(); UpdateControllerIndex(); ConnectDevice(); OnDeviceChanged(); ResyncControllerState(); } void MidiController::UpdateControllerIndex() { mControllerIndex = -1; const auto& devices = GetAvailableInputDevices(); for (int i = 0; i < devices.size(); ++i) { if (devices[i].c_str() == mDeviceIn) mControllerIndex = i; } } void MidiController::SendControllerInfoString(int control, int type, std::string str) { //ofLog() << "sending string: " << str; // byte 1: relevant cc // byte 2: type (0: control name, 1: control value) (other relevant data could go into this byte in the future) // following bytes: string std::string toSend; toSend.push_back((char)control); toSend.push_back((char)type); for (int i = 0; i < str.length(); ++i) { char ch = str[i]; if (ch < 127) toSend.push_back(ch); } SendSysEx(0, toSend); } void MidiController::SaveLayout(ofxJSONElement& moduleInfo) { mConnectionsJson.clear(); mConnectionsJson.resize((int)mConnections.size() + (int)mGrids.size()); int i = 0; for (auto iter = mConnections.begin(); iter != mConnections.end(); ++iter) { const UIControlConnection* connection = *iter; mConnectionsJson[i]["control"] = connection->mControl; if (connection->mSpecialBinding == kSpecialBinding_Hover) { mConnectionsJson[i]["uicontrol"] = "hover"; } else if (connection->mSpecialBinding >= kSpecialBinding_HotBind0 && connection->mSpecialBinding <= kSpecialBinding_HotBind9) { mConnectionsJson[i]["uicontrol"] = "hotbind" + ofToString(connection->mSpecialBinding - kSpecialBinding_HotBind0); } else if (connection->mUIControl) { mConnectionsJson[i]["uicontrol"] = connection->mUIControl->Path(); } if (connection->mMessageType == kMidiMessage_Control) mConnectionsJson[i]["type"] = "control"; if (connection->mMessageType == kMidiMessage_Note) mConnectionsJson[i]["type"] = "note"; if (connection->mMessageType == kMidiMessage_Program) mConnectionsJson[i]["type"] = "program"; if (connection->mMessageType == kMidiMessage_PitchBend) mConnectionsJson[i]["type"] = "pitchbend"; if (connection->mChannel != -1) mConnectionsJson[i]["channel"] = connection->mChannel; if (!connection->mPageless) mConnectionsJson[i]["page"] = connection->mPage; if (connection->mType == kControlType_SetValue) mConnectionsJson[i]["value"] = connection->mValue; else if (connection->mType == kControlType_Toggle) mConnectionsJson[i]["toggle"] = true; else if (connection->mType == kControlType_Direct) mConnectionsJson[i]["direct"] = true; else if (connection->mType == kControlType_SetValueOnRelease) { mConnectionsJson[i]["value"] = connection->mValue; mConnectionsJson[i]["release"] = true; } if (connection->mMidiOffValue != 0) mConnectionsJson[i]["midi_off_value"] = connection->mMidiOffValue; if (connection->mMidiOnValue != 127) mConnectionsJson[i]["midi_on_value"] = connection->mMidiOnValue; if (connection->mBlink) mConnectionsJson[i]["blink"] = true; if (connection->mIncrementAmount != 0) mConnectionsJson[i]["increment_amount"] = connection->mIncrementAmount; if (connection->mTwoWay == false) mConnectionsJson[i]["twoway"] = false; if (connection->mFeedbackControl != -1) mConnectionsJson[i]["feedbackcontrol"] = connection->mFeedbackControl; if (connection->m14BitMode) mConnectionsJson[i]["14bit"] = connection->m14BitMode; ++i; } int gridIndex = 0; for (auto* grid : mGrids) { mConnectionsJson[i]["grid_index"] = gridIndex; mConnectionsJson[i]["grid_pages"].resize(MAX_MIDI_PAGES); for (int page = 0; page < MAX_MIDI_PAGES; ++page) { auto* target = grid->mGridControlTarget[page]; if (target != nullptr) mConnectionsJson[i]["grid_pages"][page] = target->Path(); else mConnectionsJson[i]["grid_pages"][page] = ""; } ++i; ++gridIndex; } moduleInfo["connections"] = mConnectionsJson; } void MidiController::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); bool hasNonstandardController = (mNonstandardController != nullptr); out << hasNonstandardController; if (hasNonstandardController) mNonstandardController->SaveState(out); } void MidiController::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); for (int i = 0; i < mConnectionsJson.size(); ++i) AddControlConnection(mConnectionsJson[i]); if (!ModuleContainer::DoesModuleHaveMoreSaveData(in)) return; //this was saved before we added versioning, bail out if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); bool hasNonstandardController; in >> hasNonstandardController; if (hasNonstandardController) { assert(mNonstandardController != nullptr); mNonstandardController->LoadState(in); } } void UIControlConnection::SetUIControl(IUIControl* control) { mUIControl = control; if (mUIControl != nullptr) { if (mUIOwner->ShouldSendControllerInfoStrings()) { mUIOwner->SendControllerInfoString(mControl, 0, mUIControl->Path()); if (mType == kControlType_SetValue || mType == kControlType_SetValueOnRelease) { mUIOwner->SendControllerInfoString(mControl, 1, mUIControl->GetDisplayValue(mValue)); } } } } void UIControlConnection::SetUIControl(std::string path) { if (mUIControl) mUIControl->RemoveRemoteController(); if (path == "hover") { mUIControl = nullptr; mSpecialBinding = kSpecialBinding_Hover; } else if (path.substr(0, 7) == "hotbind") { mUIControl = nullptr; int index = path[7] - '0'; mSpecialBinding = SpecialControlBinding(int(kSpecialBinding_HotBind0) + index); } else { mUIControl = nullptr; try { SetUIControl(mUIOwner->GetOwningContainer()->FindUIControl(path)); } catch (std::exception e) { } mSpecialBinding = kSpecialBinding_None; if (mUIControl) mUIControl->AddRemoteController(); } } void UIControlConnection::CreateUIControls(int index) { if (!mEditorControls.empty()) { TheSynth->LogEvent("Error setting up UIControlConnection", kLogEventType_Error); return; } static int sControlID = 0; mMessageTypeDropdown = new DropdownList(mUIOwner, "messagetype", 12, -1, ((int*)&mMessageType), 50); mControlEntry = new TextEntry(mUIOwner, "control", -1, -1, 3, &mControl, 0, 127); mControlEntry->PositionTo(mMessageTypeDropdown, kAnchor_Right); mChannelDropdown = new DropdownList(mUIOwner, "channel", mControlEntry, kAnchor_Right, &mChannel, 40); mUIControlPathEntry = new TextEntry(mUIOwner, "path", -1, -1, 25, mUIControlPathInput); mUIControlPathEntry->PositionTo(mChannelDropdown, kAnchor_Right); mControlTypeDropdown = new DropdownList(mUIOwner, "controltype", mUIControlPathEntry, kAnchor_Right, ((int*)&mType), 55); mValueEntry = new TextEntry(mUIOwner, "value", -1, -1, 5, &mValue, -FLT_MAX, FLT_MAX); mValueEntry->PositionTo(mControlTypeDropdown, kAnchor_Right); mIncrementalEntry = new TextEntry(mUIOwner, "increment", -1, -1, 4, &mIncrementAmount, -FLT_MAX, FLT_MAX); mIncrementalEntry->PositionTo(mValueEntry, kAnchor_Right); mTwoWayCheckbox = new Checkbox(mUIOwner, "twoway", mIncrementalEntry, kAnchor_Right, &mTwoWay); mFeedbackDropdown = new DropdownList(mUIOwner, "feedback", mTwoWayCheckbox, kAnchor_Right, &mFeedbackControl, 40); mMidiOffEntry = new TextEntry(mUIOwner, "midi off", -1, -1, 3, &mMidiOffValue, 0, 16383); mMidiOffEntry->PositionTo(mFeedbackDropdown, kAnchor_Right); mMidiOnEntry = new TextEntry(mUIOwner, "midi on", -1, -1, 3, &mMidiOnValue, 0, 16383); mMidiOnEntry->PositionTo(mMidiOffEntry, kAnchor_Right); mScaleOutputCheckbox = new Checkbox(mUIOwner, "scale", mMidiOnEntry, kAnchor_Right, &mScaleOutput); mBlinkCheckbox = new Checkbox(mUIOwner, "blink", mScaleOutputCheckbox, kAnchor_Right, &mBlink); mPagelessCheckbox = new Checkbox(mUIOwner, "pageless", mBlinkCheckbox, kAnchor_Right, &mPageless); m14BitModeCheckbox = new Checkbox(mUIOwner, "14bit", mPagelessCheckbox, kAnchor_Right, &m14BitMode); mRemoveButton = new ClickButton(mUIOwner, " x ", mPagelessCheckbox, kAnchor_Right); mCopyButton = new ClickButton(mUIOwner, "copy", mRemoveButton, kAnchor_Right); ++sControlID; mEditorControls.push_back(mMessageTypeDropdown); mEditorControls.push_back(mControlEntry); mEditorControls.push_back(mChannelDropdown); mEditorControls.push_back(mUIControlPathEntry); mEditorControls.push_back(mControlTypeDropdown); mEditorControls.push_back(mValueEntry); mEditorControls.push_back(mMidiOffEntry); mEditorControls.push_back(mMidiOnEntry); mEditorControls.push_back(mScaleOutputCheckbox); mEditorControls.push_back(mBlinkCheckbox); mEditorControls.push_back(mIncrementalEntry); mEditorControls.push_back(mTwoWayCheckbox); mEditorControls.push_back(mFeedbackDropdown); mEditorControls.push_back(mPagelessCheckbox); mEditorControls.push_back(m14BitModeCheckbox); mEditorControls.push_back(mRemoveButton); mEditorControls.push_back(mCopyButton); for (auto iter = mEditorControls.begin(); iter != mEditorControls.end(); ++iter) { //(*iter)->SetNoHover(true); (*iter)->SetShouldSaveState(false); } mMessageTypeDropdown->AddLabel("note", kMidiMessage_Note); mMessageTypeDropdown->AddLabel("cc", kMidiMessage_Control); mMessageTypeDropdown->AddLabel("prgm", kMidiMessage_Program); mMessageTypeDropdown->AddLabel("bend", kMidiMessage_PitchBend); mChannelDropdown->AddLabel("any", -1); mChannelDropdown->AddLabel("0", 0); mChannelDropdown->AddLabel("1", 1); mChannelDropdown->AddLabel("2", 2); mChannelDropdown->AddLabel("3", 3); mChannelDropdown->AddLabel("4", 4); mChannelDropdown->AddLabel("5", 5); mChannelDropdown->AddLabel("6", 6); mChannelDropdown->AddLabel("7", 7); mChannelDropdown->AddLabel("8", 8); mChannelDropdown->AddLabel("9", 9); mChannelDropdown->AddLabel("10", 10); mChannelDropdown->AddLabel("11", 11); mChannelDropdown->AddLabel("12", 12); mChannelDropdown->AddLabel("13", 13); mChannelDropdown->AddLabel("14", 14); mChannelDropdown->AddLabel("15", 15); mControlTypeDropdown->AddLabel("slider", kControlType_Slider); mControlTypeDropdown->AddLabel("set", kControlType_SetValue); mControlTypeDropdown->AddLabel("release", kControlType_SetValueOnRelease); mControlTypeDropdown->AddLabel("toggle", kControlType_Toggle); mControlTypeDropdown->AddLabel("direct", kControlType_Direct); mFeedbackDropdown->AddLabel("self", -1); mFeedbackDropdown->AddLabel("none", -2); for (int i = 0; i <= 127; ++i) //CCs mFeedbackDropdown->AddLabel(("cc" + ofToString(i)).c_str(), i); for (int i = 0; i <= 127; ++i) //notes mFeedbackDropdown->AddLabel(("n" + ofToString(i)).c_str(), i + 128); } void UIControlConnection::SetShowing(bool enabled) { for (auto iter = mEditorControls.begin(); iter != mEditorControls.end(); ++iter) (*iter)->SetShowing(enabled); } void UIControlConnection::Poll() { if (!mShouldRetryForUIControlAt.empty()) { SetUIControl(mShouldRetryForUIControlAt); mShouldRetryForUIControlAt = ""; } if (mUIControl || mSpecialBinding != kSpecialBinding_None) { if (mSpecialBinding == kSpecialBinding_Hover) { StringCopy(mUIControlPathInput, "hover", MAX_TEXTENTRY_LENGTH); } else if (mSpecialBinding >= kSpecialBinding_HotBind0 && mSpecialBinding <= kSpecialBinding_HotBind9) { StringCopy(mUIControlPathInput, ("hotbind" + ofToString(mSpecialBinding - kSpecialBinding_HotBind0)).c_str(), MAX_TEXTENTRY_LENGTH); } else if (mUIControl != nullptr) { StringCopy(mUIControlPathInput, mUIControl->Path().c_str(), MAX_TEXTENTRY_LENGTH); if (mUIOwner->GetLayoutControl(mControl, mMessageType).mControlCable) mUIOwner->GetLayoutControl(mControl, mMessageType).mControlCable->SetTarget(mUIControl); } if (mUIControlPathEntry != nullptr) mUIControlPathEntry->SetInErrorMode(false); } else { if (mUIControlPathEntry != nullptr) mUIControlPathEntry->SetInErrorMode(true); if (PatchCable::sActivePatchCable == nullptr) { if (mUIOwner->GetLayoutControl(mControl, mMessageType).mControlCable) mUIOwner->GetLayoutControl(mControl, mMessageType).mControlCable->ClearPatchCables(); } } } void UIControlConnection::PreDraw() { SetShowing(true); if (mUIOwner->GetLayoutControl(mControl, mMessageType).mControlCable) mUIOwner->GetLayoutControl(mControl, mMessageType).mControlCable->SetEnabled(sDrawCables); mControlEntry->SetShowing(mMessageType != kMidiMessage_PitchBend); mValueEntry->SetShowing((mType == kControlType_SetValue || mType == kControlType_SetValueOnRelease) && mIncrementAmount == 0); mIncrementalEntry->SetShowing(mType == kControlType_Slider || mType == kControlType_SetValue || mType == kControlType_SetValueOnRelease); } void UIControlConnection::DrawList(int index) { PreDraw(); mControlEntry->DrawLabel(false); mChannelDropdown->DrawLabel(false); mValueEntry->DrawLabel(false); mMidiOffEntry->DrawLabel(false); mMidiOnEntry->DrawLabel(false); mIncrementalEntry->DrawLabel(false); mFeedbackDropdown->DrawLabel(false); if (mControl < 32) m14BitModeCheckbox->SetShowing(false); int x = 12; int y = 52 + 20 * index; for (auto iter = mEditorControls.begin(); iter != mEditorControls.end(); ++iter) { (*iter)->SetPosition(x, y); (*iter)->Draw(); x += (*iter)->GetRect().width + 3; if (*iter == mUIControlPathEntry) x += 13; } ofRectangle rect = mUIControlPathEntry->GetRect(true); if (mUIOwner->GetLayoutControl(mControl, mMessageType).mControlCable) mUIOwner->GetLayoutControl(mControl, mMessageType).mControlCable->SetManualPosition(rect.x + rect.width - 5, rect.y + rect.height / 2); if (gTime - mLastActivityTime > 0 && gTime - mLastActivityTime < 200) { ofPushStyle(); if (GetUIControl()) ofSetColor(0, 255, 0, 255 * (1 - (gTime - mLastActivityTime) / 200)); else ofSetColor(255, 0, 0, 255 * (1 - (gTime - mLastActivityTime) / 200)); ofFill(); ofRect(1, y + 3, 10, 10); ofPopStyle(); } } void UIControlConnection::DrawLayout() { PreDraw(); mControlEntry->DrawLabel(true); mChannelDropdown->DrawLabel(true); mValueEntry->DrawLabel(true); mMidiOffEntry->DrawLabel(true); mMidiOnEntry->DrawLabel(true); mIncrementalEntry->DrawLabel(true); mFeedbackDropdown->DrawLabel(true); mMessageTypeDropdown->SetPosition(kLayoutControlsX + 5, kLayoutControlsY + 3); mControlEntry->PositionTo(mMessageTypeDropdown, kAnchor_Right_Padded); mChannelDropdown->PositionTo(mControlEntry, kAnchor_Right_Padded); mUIControlPathEntry->PositionTo(mMessageTypeDropdown, kAnchor_Below); mControlTypeDropdown->PositionTo(mUIControlPathEntry, kAnchor_Below); mValueEntry->PositionTo(mControlTypeDropdown, kAnchor_Right); mMidiOffEntry->PositionTo(mControlTypeDropdown, kAnchor_Below); mMidiOnEntry->PositionTo(mMidiOffEntry, kAnchor_Right_Padded); mScaleOutputCheckbox->PositionTo(mMidiOnEntry, kAnchor_Right_Padded); mBlinkCheckbox->PositionTo(mMidiOffEntry, kAnchor_Below); mIncrementalEntry->PositionTo(mBlinkCheckbox, kAnchor_Right_Padded); mTwoWayCheckbox->PositionTo(mBlinkCheckbox, kAnchor_Below); mFeedbackDropdown->PositionTo(mTwoWayCheckbox, kAnchor_Right_Padded); mPagelessCheckbox->PositionTo(mTwoWayCheckbox, kAnchor_Below); m14BitModeCheckbox->PositionTo(mPagelessCheckbox, kAnchor_Right); mRemoveButton->PositionTo(mPagelessCheckbox, kAnchor_Below); mCopyButton->SetShowing(false); if (mControl < 32) m14BitModeCheckbox->SetShowing(false); for (auto iter = mEditorControls.begin(); iter != mEditorControls.end(); ++iter) (*iter)->Draw(); } void UIControlConnection::SetNext(UIControlConnection* next) { mControlEntry->SetNextTextEntry(next ? next->mControlEntry : nullptr); mUIControlPathEntry->SetNextTextEntry(next ? next->mUIControlPathEntry : nullptr); mValueEntry->SetNextTextEntry(next ? next->mValueEntry : nullptr); mMidiOffEntry->SetNextTextEntry(next ? next->mMidiOffEntry : nullptr); mMidiOnEntry->SetNextTextEntry(next ? next->mMidiOnEntry : nullptr); mIncrementalEntry->SetNextTextEntry(next ? next->mIncrementalEntry : nullptr); } bool UIControlConnection::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { if (cableSource == mUIOwner->GetLayoutControl(mControl, mMessageType).mControlCable && (mPage == mUIOwner->GetPage() || mPageless) && fromUserClick) { SetUIControl(dynamic_cast<IUIControl*>(cableSource->GetTarget())); return true; } return false; } UIControlConnection::~UIControlConnection() { for (auto iter = mEditorControls.begin(); iter != mEditorControls.end(); ++iter) { mUIOwner->RemoveUIControl(*iter); (*iter)->Delete(); } mEditorControls.clear(); } void ControlLayoutElement::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) { assert(incrementAmount == 0 || type == kMidiMessage_Control); //only control type can be incremental mActive = true; mType = type; mControl = control; mDrawType = drawType; mIncrementAmount = incrementAmount; m14BitMode = is14Bit; mOffVal = offVal; mOnVal = onVal; mScaleOutput = scaleOutput; mConnectionType = connectionType; mPosition.set(x, y); mDimensions.set(w, h); mLastValue = 0; mLastActivityTime = -9999; if (mControlCable == nullptr) { mControlCable = new PatchCableSource(owner, kConnectionType_UIControl); owner->AddPatchCableSource(mControlCable); ofColor color = mControlCable->GetColor(); color.a *= .25f; mControlCable->SetColor(color); } } ```
/content/code_sandbox/Source/MidiController.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
26,226
```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 **/ /* ============================================================================== CanvasScrollbar.h Created: 22 Mar 2021 12:19:47am Author: Ryan Challinor ============================================================================== */ #pragma once #include "IUIControl.h" class Canvas; class CanvasScrollbar : public IUIControl { public: enum class Style { kHorizontal, kVertical }; CanvasScrollbar(Canvas* canvas, std::string name, Style style); ~CanvasScrollbar() {} 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 {} void KeyPressed(int key, bool isRepeat) override {} void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, bool shouldSetValue = true) override; bool IsSliderControl() override { return false; } bool IsButtonControl() override { return false; } bool GetNoHover() const override { return true; } void Render() override; 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; private: void OnClicked(float x, float y, bool right) override; void GetDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } float GetBarStart() const; float GetBarEnd() const; float mWidth{ 200 }; float mHeight{ 20 }; bool mClick{ false }; ofVec2f mClickMousePos; ofVec2f mDragOffset; float mScrollBarOffset{ 0 }; Style mStyle{ Style::kHorizontal }; bool mAutoHide{ true }; Canvas* mCanvas{ nullptr }; }; ```
/content/code_sandbox/Source/CanvasScrollbar.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
544
```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 **/ /* ============================================================================== GridSliders.cpp Created: 2 Aug 2021 10:32:05pm Author: Ryan Challinor ============================================================================== */ #include "GridSliders.h" #include "ModularSynth.h" #include "PatchCableSource.h" GridSliders::GridSliders() { } void GridSliders::Init() { IDrawableModule::Init(); } GridSliders::~GridSliders() { } void GridSliders::CreateUIControls() { IDrawableModule::CreateUIControls(); mDirectionSelector = new DropdownList(this, "direction", 40, 3, (int*)(&mDirection)); mGridControlTarget = new GridControlTarget(this, "grid", 3, 3); mDirectionSelector->AddLabel("vertical", (int)Direction::kVertical); mDirectionSelector->AddLabel("horizontal", (int)Direction::kHorizontal); for (size_t i = 0; i < mControlCables.size(); ++i) { mControlCables[i] = new PatchCableSource(this, kConnectionType_ValueSetter); mControlCables[i]->SetManualPosition(i * 12 + 8, 28); mControlCables[i]->SetManualSide(PatchCableSource::Side::kBottom); AddPatchCableSource(mControlCables[i]); } } void GridSliders::Poll() { if (mGridControlTarget->GetGridController()) { int length; if (mDirection == Direction::kVertical) length = mGridControlTarget->GetGridController()->NumRows(); else length = mGridControlTarget->GetGridController()->NumCols(); for (size_t i = 0; i < mControlCables.size(); ++i) { GridColor color = GridColor::kGridColorOff; float value = 0; if (mControlCables[i]->GetTarget()) value = dynamic_cast<IUIControl*>(mControlCables[i]->GetTarget())->GetMidiValue(); for (int j = 0; j < length; ++j) { float squareValue = j / float(length - 1); if (squareValue <= value + .01f) color = GridColor::kGridColor1Bright; else color = GridColor::kGridColorOff; int row, col; if (mDirection == Direction::kVertical) { row = length - j - 1; col = i; } else { row = i; col = j; } mGridControlTarget->GetGridController()->SetLight(col, row, color); } } } } void GridSliders::OnControllerPageSelected() { } void GridSliders::OnGridButton(int x, int y, float velocity, IGridController* grid) { if (velocity > 0) { int sliderIndex, squareIndex, length; if (mDirection == Direction::kVertical) { sliderIndex = x; squareIndex = grid->NumRows() - y - 1; length = mGridControlTarget->GetGridController()->NumRows(); } else { sliderIndex = y; squareIndex = x; length = mGridControlTarget->GetGridController()->NumCols(); } if (sliderIndex < mControlCables.size() && mControlCables[sliderIndex]->GetTarget()) { float value = squareIndex / float(length - 1); for (auto& cable : mControlCables[sliderIndex]->GetPatchCables()) dynamic_cast<IUIControl*>(cable->GetTarget())->SetFromMidiCC(value, NextBufferTime(false), false); } } } void GridSliders::DrawModule() { if (Minimized() || IsVisible() == false) return; mGridControlTarget->Draw(); mDirectionSelector->Draw(); for (size_t i = 0; i < mControlCables.size(); ++i) { bool drawCable = false; int numCables = 0; if (mGridControlTarget->GetGridController()) { if (mDirection == Direction::kVertical) numCables = mGridControlTarget->GetGridController()->NumCols(); else numCables = mGridControlTarget->GetGridController()->NumRows(); if (mGridControlTarget->GetGridController() && (int)i < numCables) drawCable = true; } mControlCables[i]->SetShowing(drawCable); } } void GridSliders::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); } void GridSliders::MouseReleased() { IDrawableModule::MouseReleased(); } bool GridSliders::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); return false; } void GridSliders::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { } void GridSliders::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mDirectionSelector) { } } void GridSliders::GetModuleDimensions(float& width, float& height) { float cablesWidth = 0; for (size_t i = 0; i < mControlCables.size(); ++i) { if (mControlCables[i]->IsShowing()) cablesWidth = i * 12 + 8 + 8; } width = MAX(120, cablesWidth); height = 28; } void GridSliders::SaveLayout(ofxJSONElement& moduleInfo) { } void GridSliders::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void GridSliders::SetUpFromSaveData() { } void GridSliders::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << (int)mControlCables.size(); for (auto cable : mControlCables) { std::string path = ""; if (cable->GetTarget()) path = cable->GetTarget()->Path(); out << path; } } void GridSliders::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); int size; in >> size; for (int i = 0; i < size; ++i) { std::string path; in >> path; if (i < (int)mControlCables.size()) mControlCables[i]->SetTarget(TheSynth->FindUIControl(path)); } } ```
/content/code_sandbox/Source/GridSliders.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,630
```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 **/ /* ============================================================================== NoteChance.cpp Created: 29 Jan 2020 9:17:02pm Author: Ryan Challinor ============================================================================== */ #include "NoteChance.h" #include "SynthGlobals.h" #include "UIControlMacros.h" NoteChance::NoteChance() { Reseed(); } NoteChance::~NoteChance() { } void NoteChance::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mChanceSlider, "chance", &mChance, 0, 1); CHECKBOX(mDeterministicCheckbox, "deterministic", &mDeterministic); UIBLOCK_SHIFTY(5); INTSLIDER(mLengthSlider, "beat length", &mLength, 1, 16); TEXTENTRY_NUM(mSeedEntry, "seed", 4, &mSeed, 0, 9999); UIBLOCK_SHIFTRIGHT(); BUTTON(mPrevSeedButton, "<"); UIBLOCK_SHIFTRIGHT(); BUTTON(mReseedButton, "*"); UIBLOCK_SHIFTRIGHT(); BUTTON(mNextSeedButton, ">"); ENDUIBLOCK0(); mSeedEntry->DrawLabel(true); mPrevSeedButton->PositionTo(mSeedEntry, kAnchor_Right); mReseedButton->PositionTo(mPrevSeedButton, kAnchor_Right); mNextSeedButton->PositionTo(mReseedButton, kAnchor_Right); } void NoteChance::DrawModule() { if (Minimized() || IsVisible() == false) return; mChanceSlider->Draw(); mDeterministicCheckbox->Draw(); if (gTime - mLastAcceptTime > 0 && gTime - mLastAcceptTime < 200) { ofPushStyle(); ofSetColor(0, 255, 0, 255 * (1 - (gTime - mLastAcceptTime) / 200)); ofFill(); ofRect(106, 2, 10, 7); ofPopStyle(); } if (gTime - mLastRejectTime > 0 && gTime - mLastRejectTime < 200) { ofPushStyle(); ofSetColor(255, 0, 0, 255 * (1 - (gTime - mLastRejectTime) / 200)); ofFill(); ofRect(106, 9, 10, 7); ofPopStyle(); } mLengthSlider->SetShowing(mDeterministic); mLengthSlider->Draw(); mSeedEntry->SetShowing(mDeterministic); mSeedEntry->Draw(); mPrevSeedButton->SetShowing(mDeterministic); mPrevSeedButton->Draw(); mReseedButton->SetShowing(mDeterministic); mReseedButton->Draw(); mNextSeedButton->SetShowing(mDeterministic); mNextSeedButton->Draw(); if (mDeterministic) { ofRectangle lengthRect = mLengthSlider->GetRect(true); ofPushStyle(); ofSetColor(0, 255, 0); ofFill(); float pos = fmod(TheTransport->GetMeasureTime(gTime) * TheTransport->GetTimeSigTop() / mLength, 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 NoteChance::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } if (velocity > 0) ComputeSliders(0); float random; if (mDeterministic) { const int kStepResolution = 128; uint64_t step = int(TheTransport->GetMeasureTime(time) * kStepResolution); int randomIndex = step % ((mLength * kStepResolution) / TheTransport->GetTimeSigTop()); random = ((abs(DeterministicRandom(mSeed, randomIndex)) % 10000) / 10000.0f); } else { random = ofRandom(1); } bool accept = random <= mChance; if (accept || velocity == 0) PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); if (velocity > 0) { if (accept) mLastAcceptTime = time; else mLastRejectTime = time; } } void NoteChance::Reseed() { mSeed = gRandom() % 10000; } void NoteChance::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 NoteChance::GetModuleDimensions(float& width, float& height) { width = 118; height = mDeterministic ? 78 : 38; } void NoteChance::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void NoteChance::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/NoteChance.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,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 **/ // // WaveformViewer.h // modularSynth // // Created by Ryan Challinor on 12/19/12. // // #pragma once #include <iostream> #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "Slider.h" #include "TextEntry.h" #include "INoteReceiver.h" #define BUFFER_VIZ_SIZE 10000 class WaveformViewer : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public ITextEntryListener, public INoteReceiver { public: WaveformViewer(); virtual ~WaveformViewer(); static IDrawableModule* Create() { return new WaveformViewer(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return true; } 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 IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {} void TextEntryComplete(TextEntry* entry) 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 {} bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = mWidth; h = mHeight; } float mAudioView[BUFFER_VIZ_SIZE][2]{}; bool mDoubleBufferFlip{ false }; int mBufferVizOffset[2]{}; float mVizPhase[2]{}; float mDisplayFreq{ 220 }; int mLengthSamples{ 2048 }; float mDrawGain{ 2 }; bool mPhaseAlign{ true }; float mWidth{ 600 }; float mHeight{ 150 }; bool mDrawWaveform{ true }; bool mDrawCircle{ false }; FloatSlider* mHueNote{ nullptr }; FloatSlider* mHueAudio{ nullptr }; FloatSlider* mHueInstrument{ nullptr }; FloatSlider* mHueNoteSource{ nullptr }; FloatSlider* mSaturation{ nullptr }; FloatSlider* mBrightness{ nullptr }; TextEntry* mDisplayFreqEntry{ nullptr }; IntSlider* mLengthSamplesSlider{ nullptr }; FloatSlider* mDrawGainSlider{ nullptr }; }; ```
/content/code_sandbox/Source/WaveformViewer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
762
```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 **/ /* ============================================================================== CanvasTimeline.cpp Created: 20 Mar 2021 12:35:05am Author: Ryan Challinor ============================================================================== */ #include "CanvasTimeline.h" #include "Canvas.h" #include "ModularSynth.h" CanvasTimeline::CanvasTimeline(Canvas* canvas, std::string name) : mCanvas(canvas) { SetName(name.c_str()); SetParent(canvas->GetModuleParent()); } void CanvasTimeline::Render() { ofRectangle canvasRect = mCanvas->GetRect(true); SetPosition(canvasRect.x, canvasRect.y - 10); SetDimensions(canvasRect.width, 10); ofPushMatrix(); ofTranslate(mX, mY); float startX = ofMap(mCanvas->mLoopStart, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); float endX = ofMap(mCanvas->mLoopEnd, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); if (mClick && (mHoverMode == HoverMode::kStart || mHoverMode == HoverMode::kMiddle)) startX += mDragOffset.x; if (mClick && (mHoverMode == HoverMode::kEnd || mHoverMode == HoverMode::kMiddle)) endX += mDragOffset.x; ofPushStyle(); if (mClick && mHoverMode == HoverMode::kMiddle) { ofSetColor(150, 150, 150); ofNoFill(); float quantizedStart = GetQuantizedForX(startX, HoverMode::kMiddle); float quantizedStartX = ofMap(quantizedStart, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); float quantizedEnd = GetQuantizedForX(endX, HoverMode::kMiddle); float quantizedEndX = ofMap(quantizedEnd, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); ofRect(quantizedStartX, 0, quantizedEndX - quantizedStartX, mHeight / 2, 0); } if (mHoverMode == HoverMode::kMiddle) ofSetColor(255, 200, 0); else ofSetColor(100, 100, 100); ofFill(); ofRect(startX, 0, endX - startX, mHeight / 2, 0); if (mClick && mHoverMode == HoverMode::kStart) { ofSetColor(150, 150, 150); ofNoFill(); float quantized = GetQuantizedForX(startX, HoverMode::kStart); float quantizedX = ofMap(quantized, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); DrawTriangle(quantizedX, 1); } if (mHoverMode == HoverMode::kStart) ofSetColor(255, 200, 0); else ofSetColor(150, 150, 150); ofFill(); DrawTriangle(startX, 1); if (mClick && mHoverMode == HoverMode::kEnd) { ofSetColor(150, 150, 150); ofNoFill(); float quantized = GetQuantizedForX(endX, HoverMode::kEnd); float quantizedX = ofMap(quantized, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); DrawTriangle(quantizedX, -1); } if (mHoverMode == HoverMode::kEnd) ofSetColor(255, 200, 0); else ofSetColor(150, 150, 150); ofFill(); DrawTriangle(endX, -1); ofPopStyle(); ofPopMatrix(); } void CanvasTimeline::DrawTriangle(float posX, int direction) { ofBeginShape(); ofVertex(posX, 0); ofVertex(posX, mHeight); ofVertex(posX + mHeight * direction, 0); ofVertex(posX, 0); ofEndShape(); } float CanvasTimeline::GetQuantizedForX(float posX, HoverMode clampSide) { float pos = ((posX / mWidth) * (mCanvas->mViewEnd - mCanvas->mViewStart)) + mCanvas->mViewStart; int measure = CLAMP(int(pos + .5f), 0, mCanvas->GetLength()); if (clampSide == HoverMode::kStart) { if (measure >= mCanvas->mLoopEnd) measure = mCanvas->mLoopEnd - 1; } if (clampSide == HoverMode::kEnd) { if (measure <= mCanvas->mLoopStart) measure = mCanvas->mLoopStart + 1; } return measure; } void CanvasTimeline::OnClicked(float x, float y, bool right) { mClickMousePos.set(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()); mDragOffset.set(0, 0); mClick = true; } void CanvasTimeline::MouseReleased() { if (mClick) { float loopLength = mCanvas->mLoopEnd - mCanvas->mLoopStart; if (mHoverMode == HoverMode::kStart || mHoverMode == HoverMode::kMiddle) { float startX = ofMap(mCanvas->mLoopStart, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); startX += mDragOffset.x; float quantized = GetQuantizedForX(startX, mHoverMode); mCanvas->mLoopStart = quantized; } if (mHoverMode == HoverMode::kEnd || mHoverMode == HoverMode::kMiddle) { float endX = ofMap(mCanvas->mLoopEnd, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); endX += mDragOffset.x; float quantized = GetQuantizedForX(endX, mHoverMode); mCanvas->mLoopEnd = quantized; } if (mHoverMode == HoverMode::kMiddle) { mCanvas->mLoopStart = ofClamp(mCanvas->mLoopStart, 0, mCanvas->GetLength() - loopLength); mCanvas->mLoopEnd = ofClamp(mCanvas->mLoopEnd, loopLength, mCanvas->GetLength()); } } mClick = false; } bool CanvasTimeline::MouseMoved(float x, float y) { CheckHover(x, y); if (!mClick) { mHoverMode = HoverMode::kNone; float startX = ofMap(mCanvas->mLoopStart, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); float endX = ofMap(mCanvas->mLoopEnd, mCanvas->mViewStart, mCanvas->mViewEnd, 0, mWidth); ofRectangle betweenRect(startX, 0, endX - startX, mHeight); if (betweenRect.contains(x, y)) mHoverMode = HoverMode::kMiddle; ofRectangle loopStartRect(startX, 0, mHeight, mHeight); if (loopStartRect.contains(x, y)) mHoverMode = HoverMode::kStart; ofRectangle loopEndRect(endX - mHeight, 0, mHeight, mHeight); if (loopEndRect.contains(x, y)) mHoverMode = HoverMode::kEnd; } else { mDragOffset = (ofVec2f(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()) - mClickMousePos) / gDrawScale; } return false; } bool CanvasTimeline::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { return false; } void CanvasTimeline::SaveState(FileStreamOut& out) { } void CanvasTimeline::LoadState(FileStreamIn& in, bool shouldSetValue) { } ```
/content/code_sandbox/Source/CanvasTimeline.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,896
```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 **/ // // SampleDrawer.cpp // Bespoke // // Created by Ryan Challinor on 2/9/15. // // #include "SampleDrawer.h" #include "Sample.h" #include "SynthGlobals.h" void SampleDrawer::Draw(int playPosition, float vol, ofColor color) { ofPushMatrix(); ofTranslate(mX, mY); mSample->LockDataMutex(true); DrawAudioBuffer(mWidth, mHeight, mSample->Data(), mStartSample, mEndSample, playPosition, vol, color); mSample->LockDataMutex(false); ofPopMatrix(); } void SampleDrawer::DrawLine(int sample, ofColor color) { ofPushStyle(); ofSetColor(color); int position = ofMap(sample, mStartSample, mEndSample, mX, mX + mWidth, K(clamp)); ofLine(position, mY, position, mY + mHeight); ofPopStyle(); } int SampleDrawer::GetSampleAtMouse(int x, int y) { if (x >= mX && y >= mY && x <= mX + mWidth && y <= mY + mHeight) return (int)ofMap(x, mX, mX + mWidth, mStartSample, mEndSample); return -1; } ```
/content/code_sandbox/Source/SampleDrawer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
377
```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 **/ /* ============================================================================== QuickSpawnMenu.h Created: 22 Oct 2017 7:49:16pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "ModuleFactory.h" #include "PatchCable.h" //dummy module to follow the quickspawn menu around on the main canvas layer, rather than the UI layer class QuickSpawnFollower : public IDrawableModule { public: void SetUp(); void DrawModule() override {} void GetDimensions(float& width, float& height) override; bool HasTitleBar() const override { return false; } bool IsSaveable() override { return false; } void UpdateLocation(); PatchCableSource* mTempConnectionCable{ nullptr }; }; class QuickSpawnMenu : public IDrawableModule { public: QuickSpawnMenu(); virtual ~QuickSpawnMenu(); void Init() override; void DrawModule() override; void DrawModuleUnclipped() override; void SetDimensions(int w, int h) { mWidth = w; mHeight = h; } bool HasTitleBar() const override { return false; } bool IsSaveable() override { return false; } std::string GetHoveredModuleTypeName(); void Hide(); void ShowSpawnCategoriesPopup(); void ShowSpawnCategoriesPopupForCable(PatchCable* cable); void SetTempConnection(IClickable* target, ConnectionType connectionType); QuickSpawnFollower* GetMainContainerFollower() const { return mMainContainerFollower; } void KeyPressed(int key, bool isRepeat) override; void KeyReleased(int key) override; void MouseReleased() override; bool IsSingleton() const override { return true; } void GetDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } private: const ModuleFactory::Spawnable* GetElementAt(int x, int y) const; int GetIndexAt(int x, int y) const; void UpdateDisplay(); void OnSelectItem(int index); void MoveMouseToIndex(int index); void ResetAppearPos(); void UpdatePosition(); bool MatchesFilter(const ModuleFactory::Spawnable& spawnable) const; 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; enum class MenuMode { SingleLetter, ModuleCategories, SingleCategory, Search }; float mWidth{ 200 }; float mHeight{ 20 }; int mLastHoverX{ 0 }; int mLastHoverY{ 0 }; juce::String mHeldKeys; ofVec2f mAppearAtMousePos; std::vector<ModuleFactory::Spawnable> mElements; std::vector<int> mCategoryIndices; int mHighlightIndex{ -1 }; MenuMode mMenuMode{ MenuMode::SingleLetter }; int mSelectedCategoryIndex{ -1 }; juce::String mSearchString; float mScrollOffset{ 0 }; PatchCable* mFilterForCable{ nullptr }; QuickSpawnFollower* mMainContainerFollower; }; extern QuickSpawnMenu* TheQuickSpawnMenu; ```
/content/code_sandbox/Source/QuickSpawnMenu.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
845
```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 **/ // // TimelineControl.h // Bespoke // // Created by Ryan Challinor on 5/3/16. // // #pragma once #include "IDrawableModule.h" #include "Slider.h" #include "TextEntry.h" #include "ClickButton.h" class TimelineControl : public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public ITextEntryListener, public IButtonListener { public: TimelineControl(); ~TimelineControl(); static IDrawableModule* Create() { return new TimelineControl(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() 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 TextEntryComplete(TextEntry* entry) override; void ButtonClicked(ClickButton* button, double time) override; bool HasTitleBar() const override { return !mDock; } bool IsResizable() const override { return !mDock; } void Resize(float width, float height) 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& w, float& h) override; float GetSliderWidth() { return mWidth - 6; } float mWidth{ 400 }; int mNumMeasures{ 32 }; TextEntry* mNumMeasuresEntry{ nullptr }; float mTime{ 0 }; FloatSlider* mTimeSlider{ nullptr }; ClickButton* mResetButton{ nullptr }; bool mLoop{ false }; Checkbox* mLoopCheckbox{ nullptr }; int mLoopStart{ 0 }; IntSlider* mLoopStartSlider{ nullptr }; int mLoopEnd{ 8 }; IntSlider* mLoopEndSlider{ nullptr }; bool mDock{ false }; Checkbox* mDockCheckbox{ nullptr }; }; ```
/content/code_sandbox/Source/TimelineControl.h
objective-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 **/ /* ============================================================================== PulseDisplayer.h Created: 26 Jan 2023 Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "IPulseReceiver.h" class PulseDisplayer : public IDrawableModule, public IPulseSource, public IPulseReceiver { public: PulseDisplayer(); virtual ~PulseDisplayer(); static IDrawableModule* Create() { return new PulseDisplayer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IPulseReceiver void OnPulse(double time, float velocity, int flags) 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 mWidth{ 150 }; float mHeight{ 30 }; int mLastReceivedFlags{ 0 }; double mLastReceivedFlagTime{ 0 }; }; ```
/content/code_sandbox/Source/PulseDisplayer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
388
```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 **/ // // LocationZoomer.h // Bespoke // // Created by Ryan Challinor on 12/6/14. // // #pragma once #include "OpenFrameworksPort.h" #include "ofxJSONElement.h" class LocationZoomer { public: LocationZoomer(); void Init(); void Update(); void OnKeyPressed(char key); void CancelMovement() { mCurrentProgress = 1; } void GoHome(); ofxJSONElement GetSaveData(); void LoadFromSaveData(const ofxJSONElement& saveData); void EnterVanityPanningMode(); void ExitVanityPanningMode(); void WriteCurrentLocation(char key); bool HasLocation(char key); void MoveToLocation(char key); private: void PickNewVanityPanningDestination(); struct Location { float mZoomLevel{ 1 }; ofVec2f mOffset{ 0, 0 }; }; Location mLoadLocation{}; std::map<int, Location> mLocations{}; Location mStart{}; Location mDestination{}; float mCurrentProgress{ 1 }; float mSpeed{ 2 }; Location mHome{}; bool mInVanityPanningMode{ false }; }; ```
/content/code_sandbox/Source/LocationZoomer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
360
```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 **/ // // RandomNoteGenerator.h // Bespoke // // Created by Ryan Challinor on 11/28/15. // // #pragma once #include <stdio.h> #include "IDrawableModule.h" #include "INoteSource.h" #include "Transport.h" #include "Slider.h" #include "DropdownList.h" class RandomNoteGenerator : public IDrawableModule, public INoteSource, public ITimeListener, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener { public: RandomNoteGenerator(); ~RandomNoteGenerator(); static IDrawableModule* Create() { return new RandomNoteGenerator(); } 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; } //ITimeListener void OnTimeEvent(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; void DropdownUpdated(DropdownList* list, 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 = 92; } NoteInterval mInterval{ NoteInterval::kInterval_16n }; DropdownList* mIntervalSelector{ nullptr }; float mProbability{ .5 }; FloatSlider* mProbabilitySlider{ nullptr }; int mPitch{ 36 }; IntSlider* mPitchSlider{ nullptr }; float mVelocity{ .8 }; FloatSlider* mVelocitySlider{ nullptr }; float mOffset{ 0 }; FloatSlider* mOffsetSlider{ nullptr }; int mSkip{ 1 }; IntSlider* mSkipSlider{ nullptr }; int mSkipCount{ 0 }; }; ```
/content/code_sandbox/Source/RandomNoteGenerator.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
599
```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 **/ // // ModuleSaveData.cpp // modularSynth // // Created by Ryan Challinor on 1/19/14. // // #include "ModuleSaveData.h" #include "ModularSynth.h" #include "ofxJSONElement.h" #include "SynthGlobals.h" #include "DropdownList.h" #include "RadioButton.h" #include "Slider.h" ModuleSaveData::ModuleSaveData() { } ModuleSaveData::~ModuleSaveData() { for (auto iter = mValues.begin(); iter != mValues.end(); ++iter) delete *iter; } ModuleSaveData::SaveVal* ModuleSaveData::GetVal(std::string prop) { for (auto iter = mValues.begin(); iter != mValues.end(); ++iter) { if ((*iter)->mProperty == prop) return *iter; } //didn't find it, add ModuleSaveData::SaveVal* newVal = new ModuleSaveData::SaveVal(prop); mValues.push_back(newVal); return newVal; } void ModuleSaveData::Save(ofxJSONElement& moduleInfo) { for (auto i = mValues.begin(); i != mValues.end(); ++i) { const SaveVal* save = *i; assert(save); switch (save->mType) { case kInt: moduleInfo[save->mProperty] = save->mInt; break; case kFloat: moduleInfo[save->mProperty] = save->mFloat; break; case kBool: moduleInfo[save->mProperty] = save->mBool; break; case kString: moduleInfo[save->mProperty] = save->mString; break; } } } void ModuleSaveData::SetInt(std::string prop, int val) { SaveVal* save = GetVal(prop); assert(save && save->mType == kInt); save->mInt = val; } void ModuleSaveData::SetInt(std::string prop, int val, int min, int max, bool isTextField) { SaveVal* save = GetVal(prop); assert(save); save->mType = kInt; save->mInt = val; save->mMin = min; save->mMax = max; save->mIsTextField = isTextField; } void ModuleSaveData::SetFloat(std::string prop, float val) { SaveVal* save = GetVal(prop); assert(save && save->mType == kFloat); save->mFloat = val; } void ModuleSaveData::SetFloat(std::string prop, float val, float min, float max, bool isTextField) { SaveVal* save = GetVal(prop); assert(save); save->mType = kFloat; save->mFloat = val; save->mMin = min; save->mMax = max; save->mIsTextField = isTextField; } void ModuleSaveData::SetBool(std::string prop, bool val) { SaveVal* save = GetVal(prop); assert(save); save->mType = kBool; save->mBool = val; } void ModuleSaveData::SetString(std::string prop, std::string val) { SaveVal* save = GetVal(prop); assert(save); save->mType = kString; StringCopy(save->mString, val.c_str(), MAX_TEXTENTRY_LENGTH); } void ModuleSaveData::SetExtents(std::string prop, float min, float max) { SaveVal* save = GetVal(prop); assert(save); save->mMin = min; save->mMax = max; } bool ModuleSaveData::HasProperty(std::string prop) { for (auto i = mValues.begin(); i != mValues.end(); ++i) { if ((*i)->mProperty == prop) return true; } return false; } int ModuleSaveData::GetInt(std::string prop) { const SaveVal* save = GetVal(prop); assert(save); assert(save->mType == kInt); return save->mInt; } float ModuleSaveData::GetFloat(std::string prop) { const SaveVal* save = GetVal(prop); assert(save); assert(save->mType == kFloat); return save->mFloat; } bool ModuleSaveData::GetBool(std::string prop) { const SaveVal* save = GetVal(prop); assert(save); assert(save->mType == kBool); return save->mBool; } std::string ModuleSaveData::GetString(std::string prop) { const SaveVal* save = GetVal(prop); assert(save); assert(save->mType == kString); return save->mString; } int ModuleSaveData::LoadInt(std::string prop, const ofxJSONElement& moduleInfo, int defaultValue, int min, int max, bool isTextField) { int val = defaultValue; try { if (!moduleInfo[prop].isNull()) val = moduleInfo[prop].asInt(); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } SetInt(prop, val, min, max, isTextField); return val; } int ModuleSaveData::LoadInt(std::string prop, const ofxJSONElement& moduleInfo, int defaultValue, IntSlider* slider, bool isTextField) { int min = 0; int max = 10; if (slider) slider->GetRange(min, max); return LoadInt(prop, moduleInfo, defaultValue, min, max, isTextField); } float ModuleSaveData::LoadFloat(std::string prop, const ofxJSONElement& moduleInfo, float defaultValue, float min, float max, bool isTextField) { float val = defaultValue; try { if (!moduleInfo[prop].isNull()) val = moduleInfo[prop].asDouble(); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } SetFloat(prop, val, min, max, isTextField); return val; } float ModuleSaveData::LoadFloat(std::string prop, const ofxJSONElement& moduleInfo, float defaultValue, FloatSlider* slider, bool isTextField) { float min = 0; float max = 1; if (slider) slider->GetRange(min, max); return LoadFloat(prop, moduleInfo, defaultValue, min, max, isTextField); } bool ModuleSaveData::LoadBool(std::string prop, const ofxJSONElement& moduleInfo, bool defaultValue) { bool val = defaultValue; try { if (!moduleInfo[prop].isNull()) val = moduleInfo[prop].asBool(); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } SetBool(prop, val); return val; } std::string ModuleSaveData::LoadString(std::string prop, const ofxJSONElement& moduleInfo, std::string defaultValue, FillDropdownFn fillFn) { std::string val = defaultValue; try { if (!moduleInfo[prop].isNull()) val = moduleInfo[prop].asString(); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } SetString(prop, val); SaveVal* save = GetVal(prop); assert(save); save->mFillDropdownFn = fillFn; return val; } void ModuleSaveData::UpdatePropertyMax(std::string prop, float max) { if (HasProperty(prop)) { SaveVal* save = GetVal(prop); assert(save); save->mMax = max; } } void ModuleSaveData::SetEnumMapFromList(std::string prop, IUIControl* list) { SaveVal* save = GetVal(prop); assert(save); DropdownList* dropdownList = dynamic_cast<DropdownList*>(list); RadioButton* radioButton = dynamic_cast<RadioButton*>(list); if (dropdownList) save->mEnumValues = dropdownList->GetEnumMap(); if (radioButton) save->mEnumValues = radioButton->GetEnumMap(); } void ModuleSaveData::SetEnumMap(std::string prop, EnumMap* map) { SaveVal* save = GetVal(prop); assert(save); save->mEnumValues = *map; } ```
/content/code_sandbox/Source/ModuleSaveData.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,009