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.

697 lines
24KB

  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: BlocksDrawingDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Blocks application to draw shapes.
  24. dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
  25. juce_audio_processors, juce_audio_utils, juce_blocks_basics,
  26. juce_core, juce_data_structures, juce_events, juce_graphics,
  27. juce_gui_basics, juce_gui_extra
  28. exporters: xcode_mac, vs2017, linux_make, xcode_iphone
  29. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  30. type: Component
  31. mainClass: BlocksDrawingDemo
  32. useLocalCopy: 1
  33. END_JUCE_PIP_METADATA
  34. *******************************************************************************/
  35. #pragma once
  36. //==============================================================================
  37. /**
  38. Represents a single LED on a Lightpad
  39. */
  40. struct LEDComponent : public Component
  41. {
  42. LEDComponent() : ledColour (Colours::black) { setInterceptsMouseClicks (false, false); }
  43. void setColour (Colour newColour)
  44. {
  45. ledColour = newColour;
  46. repaint();
  47. }
  48. void paint (Graphics& g) override
  49. {
  50. g.setColour (ledColour);
  51. g.fillEllipse (getLocalBounds().toFloat());
  52. }
  53. Colour ledColour;
  54. };
  55. //==============================================================================
  56. /**
  57. A component that is used to represent a Lightpad on-screen
  58. */
  59. class DrawableLightpadComponent : public Component
  60. {
  61. public:
  62. DrawableLightpadComponent ()
  63. {
  64. for (auto x = 0; x < 15; ++x)
  65. for (auto y = 0; y < 15; ++y)
  66. addAndMakeVisible (leds.add (new LEDComponent()));
  67. }
  68. void paint (Graphics& g) override
  69. {
  70. auto r = getLocalBounds().toFloat();
  71. // Clip the drawing area to only draw in the block area
  72. {
  73. Path clipArea;
  74. clipArea.addRoundedRectangle (r, r.getWidth() / 20.0f);
  75. g.reduceClipRegion (clipArea);
  76. }
  77. // Fill a black square for the Lightpad
  78. g.fillAll (Colours::black);
  79. }
  80. void resized() override
  81. {
  82. auto r = getLocalBounds().reduced (10);
  83. auto circleWidth = r.getWidth() / 15;
  84. auto circleHeight = r.getHeight() / 15;
  85. for (auto x = 0; x < 15; ++x)
  86. for (auto y = 0; y < 15; ++y)
  87. leds.getUnchecked ((x * 15) + y)->setBounds (r.getX() + (x * circleWidth),
  88. r.getY() + (y * circleHeight),
  89. circleWidth, circleHeight);
  90. }
  91. void mouseDown (const MouseEvent& e) override
  92. {
  93. for (auto x = 0; x < 15; ++x)
  94. for (auto y = 0; y < 15; ++y)
  95. if (leds.getUnchecked ((x * 15) + y)->getBounds().contains (e.position.toInt()))
  96. listeners.call ([&] (Listener& l) { l.ledClicked (x, y, e.pressure); });
  97. }
  98. void mouseDrag (const MouseEvent& e) override
  99. {
  100. for (auto x = 0; x < 15; ++x)
  101. {
  102. for (auto y = 0; y < 15; ++y)
  103. {
  104. if (leds.getUnchecked ((x * 15) + y)->getBounds().contains (e.position.toInt()))
  105. {
  106. auto t = e.eventTime;
  107. if (lastLED == Point<int> (x, y) && t.toMilliseconds() - lastMouseEventTime.toMilliseconds() < 50)
  108. return;
  109. listeners.call ([&] (Listener& l) { l.ledClicked (x, y, e.pressure); });
  110. lastLED = { x, y };
  111. lastMouseEventTime = t;
  112. }
  113. }
  114. }
  115. }
  116. //==============================================================================
  117. /** Sets the colour of one of the LEDComponents */
  118. void setLEDColour (int x, int y, Colour c)
  119. {
  120. x = jmin (x, 14);
  121. y = jmin (y, 14);
  122. leds.getUnchecked ((x * 15) + y)->setColour (c);
  123. }
  124. //==============================================================================
  125. struct Listener
  126. {
  127. virtual ~Listener() {}
  128. /** Called when an LEDComponent has been clicked */
  129. virtual void ledClicked (int x, int y, float z) = 0;
  130. };
  131. void addListener (Listener* l) { listeners.add (l); }
  132. void removeListener (Listener* l) { listeners.remove (l); }
  133. private:
  134. OwnedArray<LEDComponent> leds;
  135. ListenerList<Listener> listeners;
  136. Time lastMouseEventTime;
  137. Point<int> lastLED;
  138. };
  139. //==============================================================================
  140. /**
  141. A struct that handles the setup and layout of the DrumPadGridProgram
  142. */
  143. struct ColourGrid
  144. {
  145. ColourGrid (int cols, int rows)
  146. : numColumns (cols),
  147. numRows (rows)
  148. {
  149. constructGridFillArray();
  150. }
  151. /** Creates a GridFill object for each pad in the grid and sets its colour
  152. and fill before adding it to an array of GridFill objects
  153. */
  154. void constructGridFillArray()
  155. {
  156. gridFillArray.clear();
  157. auto counter = 0;
  158. for (auto i = 0; i < numColumns; ++i)
  159. {
  160. for (auto j = 0; j < numRows; ++j)
  161. {
  162. DrumPadGridProgram::GridFill fill;
  163. Colour colourToUse = colourArray.getUnchecked (counter);
  164. fill.colour = colourToUse.withBrightness (colourToUse == currentColour ? 1.0f : 0.1f);
  165. if (colourToUse == Colours::black)
  166. fill.fillType = DrumPadGridProgram::GridFill::FillType::hollow;
  167. else
  168. fill.fillType = DrumPadGridProgram::GridFill::FillType::filled;
  169. gridFillArray.add (fill);
  170. if (++counter == colourArray.size())
  171. counter = 0;
  172. }
  173. }
  174. }
  175. /** Sets which colour should be active for a given touch co-ordinate. Returns
  176. true if the colour has changed
  177. */
  178. bool setActiveColourForTouch (int x, int y)
  179. {
  180. auto colourHasChanged = false;
  181. auto xindex = x / 5;
  182. auto yindex = y / 5;
  183. auto newColour = colourArray.getUnchecked ((yindex * 3) + xindex);
  184. if (currentColour != newColour)
  185. {
  186. currentColour = newColour;
  187. constructGridFillArray();
  188. colourHasChanged = true;
  189. }
  190. return colourHasChanged;
  191. }
  192. //==============================================================================
  193. int numColumns, numRows;
  194. Array<DrumPadGridProgram::GridFill> gridFillArray;
  195. Array<Colour> colourArray = { Colours::white, Colours::red, Colours::green,
  196. Colours::blue, Colours::hotpink, Colours::orange,
  197. Colours::magenta, Colours::cyan, Colours::black };
  198. Colour currentColour = Colours::hotpink;
  199. //==============================================================================
  200. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourGrid)
  201. };
  202. //==============================================================================
  203. /**
  204. The main component
  205. */
  206. class BlocksDrawingDemo : public Component,
  207. public TopologySource::Listener,
  208. private TouchSurface::Listener,
  209. private ControlButton::Listener,
  210. private DrawableLightpadComponent::Listener,
  211. private Timer
  212. {
  213. public:
  214. //==============================================================================
  215. BlocksDrawingDemo()
  216. {
  217. activeLeds.clear();
  218. // Register MainContentComponent as a listener to the PhysicalTopologySource object
  219. topologySource.addListener (this);
  220. infoLabel.setText ("Connect a Lightpad Block to draw.", dontSendNotification);
  221. infoLabel.setJustificationType (Justification::centred);
  222. addAndMakeVisible (infoLabel);
  223. addAndMakeVisible (lightpadComponent);
  224. lightpadComponent.setVisible (false);
  225. lightpadComponent.addListener (this);
  226. clearButton.setButtonText ("Clear");
  227. clearButton.onClick = [this] { clearLEDs(); };
  228. clearButton.setAlwaysOnTop (true);
  229. addAndMakeVisible (clearButton);
  230. brightnessSlider.setRange (0.0, 1.0);
  231. brightnessSlider.setValue (1.0);
  232. brightnessSlider.setAlwaysOnTop (true);
  233. brightnessSlider.setTextBoxStyle (Slider::TextEntryBoxPosition::NoTextBox, false, 0, 0);
  234. brightnessSlider.onValueChange = [this]
  235. {
  236. brightnessLED.setColour (layout.currentColour
  237. .withBrightness (layout.currentColour == Colours::black ? 0.0f
  238. : static_cast<float> (brightnessSlider.getValue())));
  239. };
  240. addAndMakeVisible (brightnessSlider);
  241. brightnessLED.setAlwaysOnTop (true);
  242. brightnessLED.setColour (layout.currentColour.withBrightness (static_cast<float> (brightnessSlider.getValue())));
  243. addAndMakeVisible (brightnessLED);
  244. #if JUCE_IOS
  245. connectButton.setButtonText ("Connect");
  246. connectButton.onClick = [] { BluetoothMidiDevicePairingDialogue::open(); };
  247. connectButton.setAlwaysOnTop (true);
  248. addAndMakeVisible (connectButton);
  249. #endif
  250. setSize (600, 600);
  251. }
  252. ~BlocksDrawingDemo()
  253. {
  254. if (activeBlock != nullptr)
  255. detachActiveBlock();
  256. lightpadComponent.removeListener (this);
  257. }
  258. void resized() override
  259. {
  260. infoLabel.centreWithSize (getWidth(), 100);
  261. auto bounds = getLocalBounds().reduced (20);
  262. // top buttons
  263. auto topButtonArea = bounds.removeFromTop (getHeight() / 20);
  264. topButtonArea.removeFromLeft (20);
  265. clearButton.setBounds (topButtonArea.removeFromLeft (80));
  266. #if JUCE_IOS
  267. topButtonArea.removeFromRight (20);
  268. connectButton.setBounds (topButtonArea.removeFromRight (80));
  269. #endif
  270. bounds.removeFromTop (20);
  271. auto orientation = Desktop::getInstance().getCurrentOrientation();
  272. if (orientation == Desktop::DisplayOrientation::upright
  273. || orientation == Desktop::DisplayOrientation::upsideDown)
  274. {
  275. auto brightnessControlBounds = bounds.removeFromBottom (getHeight() / 10);
  276. brightnessSlider.setSliderStyle (Slider::SliderStyle::LinearHorizontal);
  277. brightnessLED.setBounds (brightnessControlBounds.removeFromLeft (getHeight() / 10));
  278. brightnessSlider.setBounds (brightnessControlBounds);
  279. }
  280. else
  281. {
  282. auto brightnessControlBounds = bounds.removeFromRight (getWidth() / 10);
  283. brightnessSlider.setSliderStyle (Slider::SliderStyle::LinearVertical);
  284. brightnessLED.setBounds (brightnessControlBounds.removeFromTop (getWidth() / 10));
  285. brightnessSlider.setBounds (brightnessControlBounds);
  286. }
  287. // lightpad component
  288. auto sideLength = jmin (bounds.getWidth() - 40, bounds.getHeight() - 40);
  289. lightpadComponent.centreWithSize (sideLength, sideLength);
  290. }
  291. /** Overridden from TopologySource::Listener. Called when the topology changes */
  292. void topologyChanged() override
  293. {
  294. lightpadComponent.setVisible (false);
  295. infoLabel.setVisible (true);
  296. // Reset the activeBlock object
  297. if (activeBlock != nullptr)
  298. detachActiveBlock();
  299. // Get the array of currently connected Block objects from the PhysicalTopologySource
  300. auto blocks = topologySource.getCurrentTopology().blocks;
  301. // Iterate over the array of Block objects
  302. for (auto b : blocks)
  303. {
  304. // Find the first Lightpad
  305. if (b->getType() == Block::Type::lightPadBlock)
  306. {
  307. activeBlock = b;
  308. // Register MainContentComponent as a listener to the touch surface
  309. if (auto surface = activeBlock->getTouchSurface())
  310. surface->addListener (this);
  311. // Register MainContentComponent as a listener to any buttons
  312. for (auto button : activeBlock->getButtons())
  313. button->addListener (this);
  314. // Get the LEDGrid object from the Lightpad and set its program to the program for the current mode
  315. if (auto grid = activeBlock->getLEDGrid())
  316. {
  317. // Work out scale factors to translate X and Y touches to LED indexes
  318. scaleX = (float) (grid->getNumColumns() - 1) / activeBlock->getWidth();
  319. scaleY = (float) (grid->getNumRows() - 1) / activeBlock->getHeight();
  320. setLEDProgram (*activeBlock);
  321. }
  322. // Make the on screen Lighpad component visible
  323. lightpadComponent.setVisible (true);
  324. infoLabel.setVisible (false);
  325. break;
  326. }
  327. }
  328. }
  329. private:
  330. //==============================================================================
  331. /** Overridden from TouchSurface::Listener. Called when a Touch is received on the Lightpad */
  332. void touchChanged (TouchSurface&, const TouchSurface::Touch& touch) override
  333. {
  334. // Translate X and Y touch events to LED indexes
  335. auto xLed = roundToInt (touch.x * scaleX);
  336. auto yLed = roundToInt (touch.y * scaleY);
  337. if (currentMode == colourPalette)
  338. {
  339. if (layout.setActiveColourForTouch (xLed, yLed))
  340. {
  341. if (auto* colourPaletteProgram = getPaletteProgram())
  342. {
  343. colourPaletteProgram->setGridFills (layout.numColumns, layout.numRows, layout.gridFillArray);
  344. brightnessLED.setColour (layout.currentColour
  345. .withBrightness (layout.currentColour == Colours::black ? 0.0f
  346. : static_cast<float> (brightnessSlider.getValue())));
  347. }
  348. }
  349. }
  350. else if (currentMode == canvas)
  351. {
  352. drawLED ((uint32) xLed, (uint32) yLed, touch.z, layout.currentColour);
  353. }
  354. }
  355. /** Overridden from ControlButton::Listener. Called when a button on the Lightpad is pressed */
  356. void buttonPressed (ControlButton&, Block::Timestamp) override {}
  357. /** Overridden from ControlButton::Listener. Called when a button on the Lightpad is released */
  358. void buttonReleased (ControlButton&, Block::Timestamp) override
  359. {
  360. if (currentMode == canvas)
  361. {
  362. // Wait 500ms to see if there is a second press
  363. if (! isTimerRunning())
  364. startTimer (500);
  365. else
  366. doublePress = true;
  367. }
  368. else if (currentMode == colourPalette)
  369. {
  370. // Switch to canvas mode and set the LEDGrid program
  371. currentMode = canvas;
  372. setLEDProgram (*activeBlock);
  373. }
  374. }
  375. void ledClicked (int x, int y, float z) override
  376. {
  377. drawLED ((uint32) x, (uint32) y,
  378. z == 0.0f ? static_cast<float> (brightnessSlider.getValue())
  379. : z * static_cast<float> (brightnessSlider.getValue()), layout.currentColour);
  380. }
  381. void timerCallback() override
  382. {
  383. if (doublePress)
  384. {
  385. clearLEDs();
  386. // Reset the doublePress flag
  387. doublePress = false;
  388. }
  389. else
  390. {
  391. // Switch to colour palette mode and set the LEDGrid program
  392. currentMode = colourPalette;
  393. setLEDProgram (*activeBlock);
  394. }
  395. stopTimer();
  396. }
  397. /** Removes TouchSurface and ControlButton listeners and sets activeBlock to nullptr */
  398. void detachActiveBlock()
  399. {
  400. if (auto surface = activeBlock->getTouchSurface())
  401. surface->removeListener (this);
  402. for (auto button : activeBlock->getButtons())
  403. button->removeListener (this);
  404. activeBlock = nullptr;
  405. }
  406. /** Sets the LEDGrid Program for the selected mode */
  407. void setLEDProgram (Block& block)
  408. {
  409. if (currentMode == canvas)
  410. {
  411. block.setProgram (new BitmapLEDProgram (block));
  412. // Redraw any previously drawn LEDs
  413. redrawLEDs();
  414. }
  415. else if (currentMode == colourPalette)
  416. {
  417. block.setProgram (new DrumPadGridProgram (block));
  418. // Setup the grid layout
  419. if (auto* program = getPaletteProgram())
  420. program->setGridFills (layout.numColumns, layout.numRows, layout.gridFillArray);
  421. }
  422. }
  423. void clearLEDs()
  424. {
  425. if (auto* canvasProgram = getCanvasProgram())
  426. {
  427. // Clear the LED grid
  428. for (uint32 x = 0; x < 15; ++x)
  429. {
  430. for (uint32 y = 0; y < 15; ++ y)
  431. {
  432. canvasProgram->setLED (x, y, Colours::black);
  433. lightpadComponent.setLEDColour ((int) x, (int) y, Colours::black);
  434. }
  435. }
  436. // Clear the ActiveLED array
  437. activeLeds.clear();
  438. }
  439. }
  440. /** Sets an LED on the Lightpad for a given touch co-ordinate and pressure */
  441. void drawLED (uint32 x0, uint32 y0, float z, Colour drawColour)
  442. {
  443. if (auto* canvasProgram = getCanvasProgram())
  444. {
  445. // Check if the activeLeds array already contains an ActiveLED object for this LED
  446. auto index = getLEDAt (x0, y0);
  447. // If the colour is black then just set the LED to black and return
  448. if (drawColour == Colours::black)
  449. {
  450. if (index >= 0)
  451. {
  452. canvasProgram->setLED (x0, y0, Colours::black);
  453. lightpadComponent.setLEDColour ((int) x0, (int) y0, Colours::black);
  454. activeLeds.remove (index);
  455. }
  456. return;
  457. }
  458. // If there is no ActiveLED obejct for this LED then create one,
  459. // add it to the array, set the LED on the Block and return
  460. if (index < 0)
  461. {
  462. ActiveLED led;
  463. led.x = x0;
  464. led.y = y0;
  465. led.colour = drawColour;
  466. led.brightness = z;
  467. activeLeds.add (led);
  468. canvasProgram->setLED (led.x, led.y, led.colour.withBrightness (led.brightness));
  469. lightpadComponent.setLEDColour ((int) led.x, (int) led.y, led.colour.withBrightness (led.brightness));
  470. return;
  471. }
  472. // Get the ActiveLED object for this LED
  473. auto currentLed = activeLeds.getReference (index);
  474. // If the LED colour is the same as the draw colour, add the brightnesses together.
  475. // If it is different, blend the colours
  476. if (currentLed.colour == drawColour)
  477. currentLed.brightness = jmin (currentLed.brightness + z, 1.0f);
  478. else
  479. currentLed.colour = currentLed.colour.interpolatedWith (drawColour, z);
  480. // Set the LED on the Block and change the ActiveLED object in the activeLeds array
  481. if (canvasProgram != nullptr)
  482. canvasProgram->setLED (currentLed.x, currentLed.y, currentLed.colour.withBrightness (currentLed.brightness));
  483. lightpadComponent.setLEDColour ((int) currentLed.x, (int) currentLed.y, currentLed.colour.withBrightness (currentLed.brightness));
  484. activeLeds.set (index, currentLed);
  485. }
  486. }
  487. /** Redraws the LEDs on the Lightpad from the activeLeds array */
  488. void redrawLEDs()
  489. {
  490. if (auto* canvasProgram = getCanvasProgram())
  491. {
  492. // Iterate over the activeLeds array and set the LEDs on the Block
  493. for (auto led : activeLeds)
  494. {
  495. canvasProgram->setLED (led.x, led.y, led.colour.withBrightness (led.brightness));
  496. lightpadComponent.setLEDColour ((int) led.x, (int) led.y, led.colour.withBrightness (led.brightness));
  497. }
  498. }
  499. }
  500. //==============================================================================
  501. BitmapLEDProgram* getCanvasProgram()
  502. {
  503. if (activeBlock != nullptr)
  504. return dynamic_cast<BitmapLEDProgram*> (activeBlock->getProgram());
  505. return nullptr;
  506. }
  507. DrumPadGridProgram* getPaletteProgram()
  508. {
  509. if (activeBlock != nullptr)
  510. return dynamic_cast<DrumPadGridProgram*> (activeBlock->getProgram());
  511. return nullptr;
  512. }
  513. //==============================================================================
  514. /**
  515. A struct that represents an active LED on the Lightpad.
  516. Has a position, colour and brightness.
  517. */
  518. struct ActiveLED
  519. {
  520. uint32 x, y;
  521. Colour colour;
  522. float brightness;
  523. /** Returns true if this LED occupies the given co-ordinates */
  524. bool occupies (uint32 xPos, uint32 yPos) const
  525. {
  526. return xPos == x && yPos == y;
  527. }
  528. };
  529. Array<ActiveLED> activeLeds;
  530. int getLEDAt (uint32 x, uint32 y) const
  531. {
  532. for (auto i = 0; i < activeLeds.size(); ++i)
  533. if (activeLeds.getReference (i).occupies (x, y))
  534. return i;
  535. return -1;
  536. }
  537. //==============================================================================
  538. enum DisplayMode
  539. {
  540. colourPalette = 0,
  541. canvas
  542. };
  543. DisplayMode currentMode = colourPalette;
  544. //==============================================================================
  545. ColourGrid layout { 3, 3 };
  546. PhysicalTopologySource topologySource;
  547. Block::Ptr activeBlock;
  548. float scaleX = 0.0f;
  549. float scaleY = 0.0f;
  550. bool doublePress = false;
  551. Label infoLabel;
  552. DrawableLightpadComponent lightpadComponent;
  553. TextButton clearButton;
  554. LEDComponent brightnessLED;
  555. Slider brightnessSlider;
  556. #if JUCE_IOS
  557. TextButton connectButton;
  558. #endif
  559. //==============================================================================
  560. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlocksDrawingDemo)
  561. };