The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1051 lines
41KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: MPEDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Simple MPE synthesiser application.
  24. dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
  25. juce_audio_processors, juce_audio_utils, juce_core,
  26. juce_data_structures, juce_events, juce_graphics,
  27. juce_gui_basics, juce_gui_extra
  28. exporters: xcode_mac, vs2019, linux_make, androidstudio, xcode_iphone
  29. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  30. type: Component
  31. mainClass: MPEDemo
  32. useLocalCopy: 1
  33. END_JUCE_PIP_METADATA
  34. *******************************************************************************/
  35. #pragma once
  36. //==============================================================================
  37. class ZoneColourPicker
  38. {
  39. public:
  40. ZoneColourPicker() {}
  41. //==============================================================================
  42. Colour getColourForMidiChannel (int midiChannel) noexcept
  43. {
  44. if (legacyModeEnabled)
  45. return Colours::white;
  46. if (zoneLayout.getLowerZone().isUsingChannelAsMemberChannel (midiChannel))
  47. return getColourForZone (true);
  48. if (zoneLayout.getUpperZone().isUsingChannelAsMemberChannel (midiChannel))
  49. return getColourForZone (false);
  50. return Colours::transparentBlack;
  51. }
  52. //==============================================================================
  53. Colour getColourForZone (bool isLowerZone) const noexcept
  54. {
  55. if (legacyModeEnabled)
  56. return Colours::white;
  57. if (isLowerZone)
  58. return Colours::blue;
  59. return Colours::red;
  60. }
  61. //==============================================================================
  62. void setZoneLayout (MPEZoneLayout layout) noexcept { zoneLayout = layout; }
  63. void setLegacyModeEnabled (bool shouldBeEnabled) noexcept { legacyModeEnabled = shouldBeEnabled; }
  64. private:
  65. //==============================================================================
  66. MPEZoneLayout zoneLayout;
  67. bool legacyModeEnabled = false;
  68. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZoneColourPicker)
  69. };
  70. //==============================================================================
  71. class NoteComponent : public Component
  72. {
  73. public:
  74. NoteComponent (const MPENote& n, Colour colourToUse)
  75. : note (n), colour (colourToUse)
  76. {}
  77. //==============================================================================
  78. void update (const MPENote& newNote, Point<float> newCentre)
  79. {
  80. note = newNote;
  81. centre = newCentre;
  82. setBounds (getSquareAroundCentre (jmax (getNoteOnRadius(), getNoteOffRadius(), getPressureRadius()))
  83. .getUnion (getTextRectangle())
  84. .getSmallestIntegerContainer()
  85. .expanded (3));
  86. repaint();
  87. }
  88. //==============================================================================
  89. void paint (Graphics& g) override
  90. {
  91. if (note.keyState == MPENote::keyDown || note.keyState == MPENote::keyDownAndSustained)
  92. drawPressedNoteCircle (g, colour);
  93. else if (note.keyState == MPENote::sustained)
  94. drawSustainedNoteCircle (g, colour);
  95. else
  96. return;
  97. drawNoteLabel (g, colour);
  98. }
  99. //==============================================================================
  100. MPENote note;
  101. Colour colour;
  102. Point<float> centre;
  103. private:
  104. //==============================================================================
  105. void drawPressedNoteCircle (Graphics& g, Colour zoneColour)
  106. {
  107. g.setColour (zoneColour.withAlpha (0.3f));
  108. g.fillEllipse (translateToLocalBounds (getSquareAroundCentre (getNoteOnRadius())));
  109. g.setColour (zoneColour);
  110. g.drawEllipse (translateToLocalBounds (getSquareAroundCentre (getPressureRadius())), 2.0f);
  111. }
  112. //==============================================================================
  113. void drawSustainedNoteCircle (Graphics& g, Colour zoneColour)
  114. {
  115. g.setColour (zoneColour);
  116. Path circle, dashedCircle;
  117. circle.addEllipse (translateToLocalBounds (getSquareAroundCentre (getNoteOffRadius())));
  118. float dashLengths[] = { 3.0f, 3.0f };
  119. PathStrokeType (2.0, PathStrokeType::mitered).createDashedStroke (dashedCircle, circle, dashLengths, 2);
  120. g.fillPath (dashedCircle);
  121. }
  122. //==============================================================================
  123. void drawNoteLabel (Graphics& g, Colour /**zoneColour*/)
  124. {
  125. auto textBounds = translateToLocalBounds (getTextRectangle()).getSmallestIntegerContainer();
  126. g.drawText ("+", textBounds, Justification::centred);
  127. g.drawText (MidiMessage::getMidiNoteName (note.initialNote, true, true, 3), textBounds, Justification::centredBottom);
  128. g.setFont (Font (22.0f, Font::bold));
  129. g.drawText (String (note.midiChannel), textBounds, Justification::centredTop);
  130. }
  131. //==============================================================================
  132. Rectangle<float> getSquareAroundCentre (float radius) const noexcept
  133. {
  134. return Rectangle<float> (radius * 2.0f, radius * 2.0f).withCentre (centre);
  135. }
  136. Rectangle<float> translateToLocalBounds (Rectangle<float> r) const noexcept
  137. {
  138. return r - getPosition().toFloat();
  139. }
  140. Rectangle<float> getTextRectangle() const noexcept
  141. {
  142. return Rectangle<float> (30.0f, 50.0f).withCentre (centre);
  143. }
  144. float getNoteOnRadius() const noexcept { return note.noteOnVelocity .asUnsignedFloat() * maxNoteRadius; }
  145. float getNoteOffRadius() const noexcept { return note.noteOffVelocity.asUnsignedFloat() * maxNoteRadius; }
  146. float getPressureRadius() const noexcept { return note.pressure .asUnsignedFloat() * maxNoteRadius; }
  147. const float maxNoteRadius = 100.0f;
  148. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NoteComponent)
  149. };
  150. //==============================================================================
  151. class Visualiser : public Component,
  152. public MPEInstrument::Listener,
  153. private AsyncUpdater
  154. {
  155. public:
  156. //==============================================================================
  157. Visualiser (ZoneColourPicker& zoneColourPicker)
  158. : colourPicker (zoneColourPicker)
  159. {}
  160. //==============================================================================
  161. void paint (Graphics& g) override
  162. {
  163. g.fillAll (Colours::black);
  164. auto noteDistance = float (getWidth()) / 128;
  165. for (auto i = 0; i < 128; ++i)
  166. {
  167. auto x = noteDistance * (float) i;
  168. auto noteHeight = int (MidiMessage::isMidiNoteBlack (i) ? 0.7 * getHeight() : getHeight());
  169. g.setColour (MidiMessage::isMidiNoteBlack (i) ? Colours::white : Colours::grey);
  170. g.drawLine (x, 0.0f, x, (float) noteHeight);
  171. if (i > 0 && i % 12 == 0)
  172. {
  173. g.setColour (Colours::grey);
  174. auto octaveNumber = (i / 12) - 2;
  175. g.drawText ("C" + String (octaveNumber), (int) x - 15, getHeight() - 30, 30, 30, Justification::centredBottom);
  176. }
  177. }
  178. }
  179. //==============================================================================
  180. void noteAdded (MPENote newNote) override
  181. {
  182. const ScopedLock sl (lock);
  183. activeNotes.add (newNote);
  184. triggerAsyncUpdate();
  185. }
  186. void notePressureChanged (MPENote note) override { noteChanged (note); }
  187. void notePitchbendChanged (MPENote note) override { noteChanged (note); }
  188. void noteTimbreChanged (MPENote note) override { noteChanged (note); }
  189. void noteKeyStateChanged (MPENote note) override { noteChanged (note); }
  190. void noteChanged (MPENote changedNote)
  191. {
  192. const ScopedLock sl (lock);
  193. for (auto& note : activeNotes)
  194. if (note.noteID == changedNote.noteID)
  195. note = changedNote;
  196. triggerAsyncUpdate();
  197. }
  198. void noteReleased (MPENote finishedNote) override
  199. {
  200. const ScopedLock sl (lock);
  201. for (auto i = activeNotes.size(); --i >= 0;)
  202. if (activeNotes.getReference(i).noteID == finishedNote.noteID)
  203. activeNotes.remove (i);
  204. triggerAsyncUpdate();
  205. }
  206. private:
  207. //==============================================================================
  208. const MPENote* findActiveNote (int noteID) const noexcept
  209. {
  210. for (auto& note : activeNotes)
  211. if (note.noteID == noteID)
  212. return &note;
  213. return nullptr;
  214. }
  215. NoteComponent* findNoteComponent (int noteID) const noexcept
  216. {
  217. for (auto& noteComp : noteComponents)
  218. if (noteComp->note.noteID == noteID)
  219. return noteComp;
  220. return nullptr;
  221. }
  222. //==============================================================================
  223. void handleAsyncUpdate() override
  224. {
  225. const ScopedLock sl (lock);
  226. for (auto i = noteComponents.size(); --i >= 0;)
  227. if (findActiveNote (noteComponents.getUnchecked(i)->note.noteID) == nullptr)
  228. noteComponents.remove (i);
  229. for (auto& note : activeNotes)
  230. if (findNoteComponent (note.noteID) == nullptr)
  231. addAndMakeVisible (noteComponents.add (new NoteComponent (note, colourPicker.getColourForMidiChannel(note.midiChannel))));
  232. for (auto& noteComp : noteComponents)
  233. if (auto* noteInfo = findActiveNote (noteComp->note.noteID))
  234. noteComp->update (*noteInfo, getCentrePositionForNote (*noteInfo));
  235. }
  236. //==============================================================================
  237. Point<float> getCentrePositionForNote (MPENote note) const
  238. {
  239. auto n = float (note.initialNote) + float (note.totalPitchbendInSemitones);
  240. auto x = (float) getWidth() * n / 128;
  241. auto y = (float) getHeight() * (1 - note.timbre.asUnsignedFloat());
  242. return { x, y };
  243. }
  244. //==============================================================================
  245. OwnedArray<NoteComponent> noteComponents;
  246. CriticalSection lock;
  247. Array<MPENote> activeNotes;
  248. ZoneColourPicker& colourPicker;
  249. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Visualiser)
  250. };
  251. //==============================================================================
  252. class MPESetupComponent : public Component,
  253. public ChangeBroadcaster
  254. {
  255. public:
  256. //==============================================================================
  257. class Listener
  258. {
  259. public:
  260. virtual ~Listener() {}
  261. virtual void zoneChanged (bool isLower, int numMemberChans, int perNotePb, int masterPb) = 0;
  262. virtual void allZonesCleared() = 0;
  263. virtual void legacyModeChanged (bool legacyModeEnabled, int pitchbendRange, Range<int> channelRange) = 0;
  264. virtual void voiceStealingEnabledChanged (bool voiceStealingEnabled) = 0;
  265. virtual void numberOfVoicesChanged (int numberOfVoices) = 0;
  266. };
  267. void addListener (Listener* listenerToAdd) { listeners.add (listenerToAdd); }
  268. void removeListener (Listener* listenerToRemove) { listeners.remove (listenerToRemove); }
  269. //==============================================================================
  270. MPESetupComponent()
  271. {
  272. addAndMakeVisible (isLowerZoneButton);
  273. isLowerZoneButton.setToggleState (true, NotificationType::dontSendNotification);
  274. initialiseComboBoxWithConsecutiveIntegers (memberChannels, memberChannelsLabel, 0, 16, defaultMemberChannels);
  275. initialiseComboBoxWithConsecutiveIntegers (masterPitchbendRange, masterPitchbendRangeLabel, 0, 96, defaultMasterPitchbendRange);
  276. initialiseComboBoxWithConsecutiveIntegers (notePitchbendRange, notePitchbendRangeLabel, 0, 96, defaultNotePitchbendRange);
  277. initialiseComboBoxWithConsecutiveIntegers (legacyStartChannel, legacyStartChannelLabel, 1, 16, 1, false);
  278. initialiseComboBoxWithConsecutiveIntegers (legacyEndChannel, legacyEndChannelLabel, 1, 16, 16, false);
  279. initialiseComboBoxWithConsecutiveIntegers (legacyPitchbendRange, legacyPitchbendRangeLabel, 0, 96, 2, false);
  280. addAndMakeVisible (setZoneButton);
  281. setZoneButton.onClick = [this] { setZoneButtonClicked(); };
  282. addAndMakeVisible (clearAllZonesButton);
  283. clearAllZonesButton.onClick = [this] { clearAllZonesButtonClicked(); };
  284. addAndMakeVisible (legacyModeEnabledToggle);
  285. legacyModeEnabledToggle.onClick = [this] { legacyModeEnabledToggleClicked(); };
  286. addAndMakeVisible (voiceStealingEnabledToggle);
  287. voiceStealingEnabledToggle.onClick = [this] { voiceStealingEnabledToggleClicked(); };
  288. initialiseComboBoxWithConsecutiveIntegers (numberOfVoices, numberOfVoicesLabel, 1, 20, 15);
  289. }
  290. //==============================================================================
  291. void resized() override
  292. {
  293. Rectangle<int> r (proportionOfWidth (0.65f), 15, proportionOfWidth (0.25f), 3000);
  294. auto h = 24;
  295. auto hspace = 6;
  296. auto hbigspace = 18;
  297. isLowerZoneButton.setBounds (r.removeFromTop (h));
  298. r.removeFromTop (hspace);
  299. memberChannels.setBounds (r.removeFromTop (h));
  300. r.removeFromTop (hspace);
  301. notePitchbendRange.setBounds (r.removeFromTop (h));
  302. r.removeFromTop (hspace);
  303. masterPitchbendRange.setBounds (r.removeFromTop (h));
  304. legacyStartChannel .setBounds (isLowerZoneButton .getBounds());
  305. legacyEndChannel .setBounds (memberChannels .getBounds());
  306. legacyPitchbendRange.setBounds (notePitchbendRange.getBounds());
  307. r.removeFromTop (hbigspace);
  308. auto buttonLeft = proportionOfWidth (0.5f);
  309. setZoneButton.setBounds (r.removeFromTop (h).withLeft (buttonLeft));
  310. r.removeFromTop (hspace);
  311. clearAllZonesButton.setBounds (r.removeFromTop (h).withLeft (buttonLeft));
  312. r.removeFromTop (hbigspace);
  313. auto toggleLeft = proportionOfWidth (0.25f);
  314. legacyModeEnabledToggle.setBounds (r.removeFromTop (h).withLeft (toggleLeft));
  315. r.removeFromTop (hspace);
  316. voiceStealingEnabledToggle.setBounds (r.removeFromTop (h).withLeft (toggleLeft));
  317. r.removeFromTop (hspace);
  318. numberOfVoices.setBounds (r.removeFromTop (h));
  319. }
  320. private:
  321. //==============================================================================
  322. void initialiseComboBoxWithConsecutiveIntegers (ComboBox& comboBox, Label& labelToAttach,
  323. int firstValue, int numValues, int valueToSelect,
  324. bool makeVisible = true)
  325. {
  326. for (auto i = 0; i < numValues; ++i)
  327. comboBox.addItem (String (i + firstValue), i + 1);
  328. comboBox.setSelectedId (valueToSelect - firstValue + 1);
  329. labelToAttach.attachToComponent (&comboBox, true);
  330. if (makeVisible)
  331. addAndMakeVisible (comboBox);
  332. else
  333. addChildComponent (comboBox);
  334. if (&comboBox == &numberOfVoices)
  335. comboBox.onChange = [this] { numberOfVoicesChanged(); };
  336. else if (&comboBox == &legacyPitchbendRange)
  337. comboBox.onChange = [this] { if (legacyModeEnabledToggle.getToggleState()) legacyModePitchbendRangeChanged(); };
  338. else if (&comboBox == &legacyStartChannel || &comboBox == &legacyEndChannel)
  339. comboBox.onChange = [this] { if (legacyModeEnabledToggle.getToggleState()) legacyModeChannelRangeChanged(); };
  340. }
  341. //==============================================================================
  342. void setZoneButtonClicked()
  343. {
  344. auto isLowerZone = isLowerZoneButton.getToggleState();
  345. auto numMemberChannels = memberChannels.getText().getIntValue();
  346. auto perNotePb = notePitchbendRange.getText().getIntValue();
  347. auto masterPb = masterPitchbendRange.getText().getIntValue();
  348. if (isLowerZone)
  349. zoneLayout.setLowerZone (numMemberChannels, perNotePb, masterPb);
  350. else
  351. zoneLayout.setUpperZone (numMemberChannels, perNotePb, masterPb);
  352. listeners.call ([&] (Listener& l) { l.zoneChanged (isLowerZone, numMemberChannels, perNotePb, masterPb); });
  353. }
  354. //==============================================================================
  355. void clearAllZonesButtonClicked()
  356. {
  357. zoneLayout.clearAllZones();
  358. listeners.call ([] (Listener& l) { l.allZonesCleared(); });
  359. }
  360. //==============================================================================
  361. void legacyModeEnabledToggleClicked()
  362. {
  363. auto legacyModeEnabled = legacyModeEnabledToggle.getToggleState();
  364. isLowerZoneButton .setVisible (! legacyModeEnabled);
  365. memberChannels .setVisible (! legacyModeEnabled);
  366. notePitchbendRange .setVisible (! legacyModeEnabled);
  367. masterPitchbendRange.setVisible (! legacyModeEnabled);
  368. setZoneButton .setVisible (! legacyModeEnabled);
  369. clearAllZonesButton .setVisible (! legacyModeEnabled);
  370. legacyStartChannel .setVisible (legacyModeEnabled);
  371. legacyEndChannel .setVisible (legacyModeEnabled);
  372. legacyPitchbendRange.setVisible (legacyModeEnabled);
  373. if (areLegacyModeParametersValid())
  374. {
  375. listeners.call ([&] (Listener& l) { l.legacyModeChanged (legacyModeEnabledToggle.getToggleState(),
  376. legacyPitchbendRange.getText().getIntValue(),
  377. getLegacyModeChannelRange()); });
  378. }
  379. else
  380. {
  381. handleInvalidLegacyModeParameters();
  382. }
  383. }
  384. //==============================================================================
  385. void voiceStealingEnabledToggleClicked()
  386. {
  387. auto newState = voiceStealingEnabledToggle.getToggleState();
  388. listeners.call ([=] (Listener& l) { l.voiceStealingEnabledChanged (newState); });
  389. }
  390. //==============================================================================
  391. void numberOfVoicesChanged()
  392. {
  393. listeners.call ([this] (Listener& l) { l.numberOfVoicesChanged (numberOfVoices.getText().getIntValue()); });
  394. }
  395. void legacyModePitchbendRangeChanged()
  396. {
  397. jassert (legacyModeEnabledToggle.getToggleState() == true);
  398. listeners.call ([this] (Listener& l) { l.legacyModeChanged (true,
  399. legacyPitchbendRange.getText().getIntValue(),
  400. getLegacyModeChannelRange()); });
  401. }
  402. void legacyModeChannelRangeChanged()
  403. {
  404. jassert (legacyModeEnabledToggle.getToggleState() == true);
  405. if (areLegacyModeParametersValid())
  406. {
  407. listeners.call ([this] (Listener& l) { l.legacyModeChanged (true,
  408. legacyPitchbendRange.getText().getIntValue(),
  409. getLegacyModeChannelRange()); });
  410. }
  411. else
  412. {
  413. handleInvalidLegacyModeParameters();
  414. }
  415. }
  416. //==============================================================================
  417. bool areLegacyModeParametersValid() const
  418. {
  419. return legacyStartChannel.getText().getIntValue() <= legacyEndChannel.getText().getIntValue();
  420. }
  421. void handleInvalidLegacyModeParameters() const
  422. {
  423. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  424. "Invalid legacy mode channel layout",
  425. "Cannot set legacy mode start/end channel:\n"
  426. "The end channel must not be less than the start channel!",
  427. "Got it");
  428. }
  429. //==============================================================================
  430. Range<int> getLegacyModeChannelRange() const
  431. {
  432. return { legacyStartChannel.getText().getIntValue(),
  433. legacyEndChannel.getText().getIntValue() + 1 };
  434. }
  435. //==============================================================================
  436. MPEZoneLayout zoneLayout;
  437. ComboBox memberChannels, masterPitchbendRange, notePitchbendRange;
  438. ToggleButton isLowerZoneButton { "Lower zone" };
  439. Label memberChannelsLabel { {}, "Nr. of member channels:" };
  440. Label masterPitchbendRangeLabel { {}, "Master pitchbend range (semitones):" };
  441. Label notePitchbendRangeLabel { {}, "Note pitchbend range (semitones):" };
  442. TextButton setZoneButton { "Set zone" };
  443. TextButton clearAllZonesButton { "Clear all zones" };
  444. ComboBox legacyStartChannel, legacyEndChannel, legacyPitchbendRange;
  445. Label legacyStartChannelLabel { {}, "First channel:" };
  446. Label legacyEndChannelLabel { {}, "Last channel:" };
  447. Label legacyPitchbendRangeLabel { {}, "Pitchbend range (semitones):"};
  448. ToggleButton legacyModeEnabledToggle { "Enable Legacy Mode" };
  449. ToggleButton voiceStealingEnabledToggle { "Enable synth voice stealing" };
  450. ComboBox numberOfVoices;
  451. Label numberOfVoicesLabel { {}, "Number of synth voices"};
  452. ListenerList<Listener> listeners;
  453. const int defaultMemberChannels = 15,
  454. defaultMasterPitchbendRange = 2,
  455. defaultNotePitchbendRange = 48;
  456. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPESetupComponent)
  457. };
  458. //==============================================================================
  459. class ZoneLayoutComponent : public Component,
  460. public MPESetupComponent::Listener
  461. {
  462. public:
  463. //==============================================================================
  464. ZoneLayoutComponent (const ZoneColourPicker& zoneColourPicker)
  465. : colourPicker (zoneColourPicker)
  466. {}
  467. //==============================================================================
  468. void paint (Graphics& g) override
  469. {
  470. paintBackground (g);
  471. if (legacyModeEnabled)
  472. paintLegacyMode (g);
  473. else
  474. paintZones (g);
  475. }
  476. //==============================================================================
  477. void zoneChanged (bool isLowerZone, int numMemberChannels,
  478. int perNotePitchbendRange, int masterPitchbendRange) override
  479. {
  480. if (isLowerZone)
  481. zoneLayout.setLowerZone (numMemberChannels, perNotePitchbendRange, masterPitchbendRange);
  482. else
  483. zoneLayout.setUpperZone (numMemberChannels, perNotePitchbendRange, masterPitchbendRange);
  484. repaint();
  485. }
  486. void allZonesCleared() override
  487. {
  488. zoneLayout.clearAllZones();
  489. repaint();
  490. }
  491. void legacyModeChanged (bool legacyModeShouldBeEnabled, int pitchbendRange, Range<int> channelRange) override
  492. {
  493. legacyModeEnabled = legacyModeShouldBeEnabled;
  494. legacyModePitchbendRange = pitchbendRange;
  495. legacyModeChannelRange = channelRange;
  496. repaint();
  497. }
  498. void voiceStealingEnabledChanged (bool) override { /* not interested in this change */ }
  499. void numberOfVoicesChanged (int) override { /* not interested in this change */ }
  500. private:
  501. //==============================================================================
  502. void paintBackground (Graphics& g)
  503. {
  504. g.setColour (Colours::black);
  505. auto channelWidth = getChannelRectangleWidth();
  506. for (auto i = 0; i < numMidiChannels; ++i)
  507. {
  508. auto x = float (i) * channelWidth;
  509. Rectangle<int> channelArea ((int) x, 0, (int) channelWidth, getHeight());
  510. g.drawLine ({ x, 0.0f, x, float (getHeight()) });
  511. g.drawText (String (i + 1), channelArea.reduced (4, 4), Justification::topLeft, false);
  512. }
  513. }
  514. //==============================================================================
  515. void paintZones (Graphics& g)
  516. {
  517. auto channelWidth = getChannelRectangleWidth();
  518. Array<MPEZoneLayout::Zone> activeZones;
  519. if (zoneLayout.getLowerZone().isActive()) activeZones.add (zoneLayout.getLowerZone());
  520. if (zoneLayout.getUpperZone().isActive()) activeZones.add (zoneLayout.getUpperZone());
  521. for (auto zone : activeZones)
  522. {
  523. auto zoneColour = colourPicker.getColourForZone (zone.isLowerZone());
  524. auto xPos = zone.isLowerZone() ? 0 : zone.getLastMemberChannel() - 1;
  525. Rectangle<int> zoneRect { int (channelWidth * (float) xPos), 20,
  526. int (channelWidth * (float) (zone.numMemberChannels + 1)), getHeight() - 20 };
  527. g.setColour (zoneColour);
  528. g.drawRect (zoneRect, 3);
  529. auto masterRect = zone.isLowerZone() ? zoneRect.removeFromLeft ((int) channelWidth) : zoneRect.removeFromRight ((int) channelWidth);
  530. g.setColour (zoneColour.withAlpha (0.3f));
  531. g.fillRect (masterRect);
  532. g.setColour (zoneColour.contrasting());
  533. g.drawText ("<>" + String (zone.masterPitchbendRange), masterRect.reduced (4), Justification::top, false);
  534. g.drawText ("<>" + String (zone.perNotePitchbendRange), masterRect.reduced (4), Justification::bottom, false);
  535. }
  536. }
  537. //==============================================================================
  538. void paintLegacyMode (Graphics& g)
  539. {
  540. auto startChannel = legacyModeChannelRange.getStart() - 1;
  541. auto numChannels = legacyModeChannelRange.getEnd() - startChannel - 1;
  542. Rectangle<int> zoneRect (int (getChannelRectangleWidth() * (float) startChannel), 0,
  543. int (getChannelRectangleWidth() * (float) numChannels), getHeight());
  544. zoneRect.removeFromTop (20);
  545. g.setColour (Colours::white);
  546. g.drawRect (zoneRect, 3);
  547. g.drawText ("LGCY", zoneRect.reduced (4, 4), Justification::topLeft, false);
  548. g.drawText ("<>" + String (legacyModePitchbendRange), zoneRect.reduced (4, 4), Justification::bottomLeft, false);
  549. }
  550. //==============================================================================
  551. float getChannelRectangleWidth() const noexcept
  552. {
  553. return (float) getWidth() / (float) numMidiChannels;
  554. }
  555. //==============================================================================
  556. MPEZoneLayout zoneLayout;
  557. const ZoneColourPicker& colourPicker;
  558. bool legacyModeEnabled = false;
  559. int legacyModePitchbendRange = 48;
  560. Range<int> legacyModeChannelRange = { 1, 17 };
  561. const int numMidiChannels = 16;
  562. };
  563. //==============================================================================
  564. class MPEDemoSynthVoice : public MPESynthesiserVoice
  565. {
  566. public:
  567. //==============================================================================
  568. MPEDemoSynthVoice() {}
  569. //==============================================================================
  570. void noteStarted() override
  571. {
  572. jassert (currentlyPlayingNote.isValid());
  573. jassert (currentlyPlayingNote.keyState == MPENote::keyDown
  574. || currentlyPlayingNote.keyState == MPENote::keyDownAndSustained);
  575. level .setTargetValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  576. frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
  577. timbre .setTargetValue (currentlyPlayingNote.timbre.asUnsignedFloat());
  578. phase = 0.0;
  579. auto cyclesPerSample = frequency.getNextValue() / currentSampleRate;
  580. phaseDelta = MathConstants<double>::twoPi * cyclesPerSample;
  581. tailOff = 0.0;
  582. }
  583. void noteStopped (bool allowTailOff) override
  584. {
  585. jassert (currentlyPlayingNote.keyState == MPENote::off);
  586. if (allowTailOff)
  587. {
  588. // start a tail-off by setting this flag. The render callback will pick up on
  589. // this and do a fade out, calling clearCurrentNote() when it's finished.
  590. if (tailOff == 0.0) // we only need to begin a tail-off if it's not already doing so - the
  591. // stopNote method could be called more than once.
  592. tailOff = 1.0;
  593. }
  594. else
  595. {
  596. // we're being told to stop playing immediately, so reset everything..
  597. clearCurrentNote();
  598. phaseDelta = 0.0;
  599. }
  600. }
  601. void notePressureChanged() override
  602. {
  603. level.setTargetValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  604. }
  605. void notePitchbendChanged() override
  606. {
  607. frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
  608. }
  609. void noteTimbreChanged() override
  610. {
  611. timbre.setTargetValue (currentlyPlayingNote.timbre.asUnsignedFloat());
  612. }
  613. void noteKeyStateChanged() override {}
  614. void setCurrentSampleRate (double newRate) override
  615. {
  616. if (currentSampleRate != newRate)
  617. {
  618. noteStopped (false);
  619. currentSampleRate = newRate;
  620. level .reset (currentSampleRate, smoothingLengthInSeconds);
  621. timbre .reset (currentSampleRate, smoothingLengthInSeconds);
  622. frequency.reset (currentSampleRate, smoothingLengthInSeconds);
  623. }
  624. }
  625. //==============================================================================
  626. virtual void renderNextBlock (AudioBuffer<float>& outputBuffer,
  627. int startSample,
  628. int numSamples) override
  629. {
  630. if (phaseDelta != 0.0)
  631. {
  632. if (tailOff > 0.0)
  633. {
  634. while (--numSamples >= 0)
  635. {
  636. auto currentSample = getNextSample() * (float) tailOff;
  637. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  638. outputBuffer.addSample (i, startSample, currentSample);
  639. ++startSample;
  640. tailOff *= 0.99;
  641. if (tailOff <= 0.005)
  642. {
  643. clearCurrentNote();
  644. phaseDelta = 0.0;
  645. break;
  646. }
  647. }
  648. }
  649. else
  650. {
  651. while (--numSamples >= 0)
  652. {
  653. auto currentSample = getNextSample();
  654. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  655. outputBuffer.addSample (i, startSample, currentSample);
  656. ++startSample;
  657. }
  658. }
  659. }
  660. }
  661. using MPESynthesiserVoice::renderNextBlock;
  662. private:
  663. //==============================================================================
  664. float getNextSample() noexcept
  665. {
  666. auto levelDb = (level.getNextValue() - 1.0) * maxLevelDb;
  667. auto amplitude = pow (10.0f, 0.05f * levelDb) * maxLevel;
  668. // timbre is used to blend between a sine and a square.
  669. auto f1 = std::sin (phase);
  670. auto f2 = copysign (1.0, f1);
  671. auto a2 = timbre.getNextValue();
  672. auto a1 = 1.0 - a2;
  673. auto nextSample = float (amplitude * ((a1 * f1) + (a2 * f2)));
  674. auto cyclesPerSample = frequency.getNextValue() / currentSampleRate;
  675. phaseDelta = MathConstants<double>::twoPi * cyclesPerSample;
  676. phase = std::fmod (phase + phaseDelta, MathConstants<double>::twoPi);
  677. return nextSample;
  678. }
  679. //==============================================================================
  680. SmoothedValue<double> level, timbre, frequency;
  681. double phase = 0.0;
  682. double phaseDelta = 0.0;
  683. double tailOff = 0.0;
  684. const double maxLevel = 0.05;
  685. const double maxLevelDb = 31.0;
  686. const double smoothingLengthInSeconds = 0.01;
  687. };
  688. //==============================================================================
  689. class MPEDemo : public Component,
  690. private AudioIODeviceCallback,
  691. private MidiInputCallback,
  692. private MPESetupComponent::Listener
  693. {
  694. public:
  695. //==============================================================================
  696. MPEDemo()
  697. : audioSetupComp (audioDeviceManager, 0, 0, 0, 256, true, true, true, false),
  698. zoneLayoutComp (colourPicker),
  699. visualiserComp (colourPicker)
  700. {
  701. #ifndef JUCE_DEMO_RUNNER
  702. audioDeviceManager.initialise (0, 2, nullptr, true, {}, nullptr);
  703. #endif
  704. audioDeviceManager.addMidiInputDeviceCallback ({}, this);
  705. audioDeviceManager.addAudioCallback (this);
  706. addAndMakeVisible (audioSetupComp);
  707. addAndMakeVisible (MPESetupComp);
  708. addAndMakeVisible (zoneLayoutComp);
  709. addAndMakeVisible (visualiserViewport);
  710. visualiserViewport.setScrollBarsShown (false, true);
  711. visualiserViewport.setViewedComponent (&visualiserComp, false);
  712. visualiserViewport.setViewPositionProportionately (0.5, 0.0);
  713. MPESetupComp.addListener (&zoneLayoutComp);
  714. MPESetupComp.addListener (this);
  715. visualiserInstrument.addListener (&visualiserComp);
  716. synth.setVoiceStealingEnabled (false);
  717. for (auto i = 0; i < 15; ++i)
  718. synth.addVoice (new MPEDemoSynthVoice());
  719. setSize (880, 720);
  720. }
  721. ~MPEDemo() override
  722. {
  723. audioDeviceManager.removeMidiInputDeviceCallback ({}, this);
  724. audioDeviceManager.removeAudioCallback (this);
  725. }
  726. //==============================================================================
  727. void resized() override
  728. {
  729. auto visualiserCompWidth = 2800;
  730. auto visualiserCompHeight = 300;
  731. auto zoneLayoutCompHeight = 60;
  732. auto audioSetupCompRelativeWidth = 0.55f;
  733. auto r = getLocalBounds();
  734. visualiserViewport.setBounds (r.removeFromBottom (visualiserCompHeight));
  735. visualiserComp .setBounds ({ visualiserCompWidth,
  736. visualiserViewport.getHeight() - visualiserViewport.getScrollBarThickness() });
  737. zoneLayoutComp.setBounds (r.removeFromBottom (zoneLayoutCompHeight));
  738. audioSetupComp.setBounds (r.removeFromLeft (proportionOfWidth (audioSetupCompRelativeWidth)));
  739. MPESetupComp .setBounds (r);
  740. }
  741. //==============================================================================
  742. void audioDeviceIOCallback (const float** /*inputChannelData*/, int /*numInputChannels*/,
  743. float** outputChannelData, int numOutputChannels,
  744. int numSamples) override
  745. {
  746. AudioBuffer<float> buffer (outputChannelData, numOutputChannels, numSamples);
  747. buffer.clear();
  748. MidiBuffer incomingMidi;
  749. midiCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  750. synth.renderNextBlock (buffer, incomingMidi, 0, numSamples);
  751. }
  752. void audioDeviceAboutToStart (AudioIODevice* device) override
  753. {
  754. auto sampleRate = device->getCurrentSampleRate();
  755. midiCollector.reset (sampleRate);
  756. synth.setCurrentPlaybackSampleRate (sampleRate);
  757. }
  758. void audioDeviceStopped() override {}
  759. private:
  760. //==============================================================================
  761. void handleIncomingMidiMessage (MidiInput* /*source*/,
  762. const MidiMessage& message) override
  763. {
  764. visualiserInstrument.processNextMidiEvent (message);
  765. midiCollector.addMessageToQueue (message);
  766. }
  767. //==============================================================================
  768. void zoneChanged (bool isLowerZone, int numMemberChannels,
  769. int perNotePitchbendRange, int masterPitchbendRange) override
  770. {
  771. auto* midiOutput = audioDeviceManager.getDefaultMidiOutput();
  772. if (midiOutput != nullptr)
  773. {
  774. if (isLowerZone)
  775. midiOutput->sendBlockOfMessagesNow (MPEMessages::setLowerZone (numMemberChannels, perNotePitchbendRange, masterPitchbendRange));
  776. else
  777. midiOutput->sendBlockOfMessagesNow (MPEMessages::setUpperZone (numMemberChannels, perNotePitchbendRange, masterPitchbendRange));
  778. }
  779. if (isLowerZone)
  780. zoneLayout.setLowerZone (numMemberChannels, perNotePitchbendRange, masterPitchbendRange);
  781. else
  782. zoneLayout.setUpperZone (numMemberChannels, perNotePitchbendRange, masterPitchbendRange);
  783. visualiserInstrument.setZoneLayout (zoneLayout);
  784. synth.setZoneLayout (zoneLayout);
  785. colourPicker.setZoneLayout (zoneLayout);
  786. }
  787. void allZonesCleared() override
  788. {
  789. auto* midiOutput = audioDeviceManager.getDefaultMidiOutput();
  790. if (midiOutput != nullptr)
  791. midiOutput->sendBlockOfMessagesNow (MPEMessages::clearAllZones());
  792. zoneLayout.clearAllZones();
  793. visualiserInstrument.setZoneLayout (zoneLayout);
  794. synth.setZoneLayout (zoneLayout);
  795. colourPicker.setZoneLayout (zoneLayout);
  796. }
  797. void legacyModeChanged (bool legacyModeShouldBeEnabled, int pitchbendRange, Range<int> channelRange) override
  798. {
  799. colourPicker.setLegacyModeEnabled (legacyModeShouldBeEnabled);
  800. if (legacyModeShouldBeEnabled)
  801. {
  802. synth.enableLegacyMode (pitchbendRange, channelRange);
  803. visualiserInstrument.enableLegacyMode (pitchbendRange, channelRange);
  804. }
  805. else
  806. {
  807. synth.setZoneLayout (zoneLayout);
  808. visualiserInstrument.setZoneLayout (zoneLayout);
  809. }
  810. }
  811. void voiceStealingEnabledChanged (bool voiceStealingEnabled) override
  812. {
  813. synth.setVoiceStealingEnabled (voiceStealingEnabled);
  814. }
  815. void numberOfVoicesChanged (int numberOfVoices) override
  816. {
  817. if (numberOfVoices < synth.getNumVoices())
  818. synth.reduceNumVoices (numberOfVoices);
  819. else
  820. while (synth.getNumVoices() < numberOfVoices)
  821. synth.addVoice (new MPEDemoSynthVoice());
  822. }
  823. //==============================================================================
  824. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  825. #ifndef JUCE_DEMO_RUNNER
  826. AudioDeviceManager audioDeviceManager;
  827. #else
  828. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (0, 2) };
  829. #endif
  830. MPEZoneLayout zoneLayout;
  831. ZoneColourPicker colourPicker;
  832. AudioDeviceSelectorComponent audioSetupComp;
  833. MPESetupComponent MPESetupComp;
  834. ZoneLayoutComponent zoneLayoutComp;
  835. Visualiser visualiserComp;
  836. Viewport visualiserViewport;
  837. MPEInstrument visualiserInstrument;
  838. MPESynthesiser synth;
  839. MidiMessageCollector midiCollector;
  840. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPEDemo)
  841. };