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.

1048 lines
40KB

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