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.

1253 lines
46KB

  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: OpenGLDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Simple 3D OpenGL application.
  24. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
  25. juce_gui_basics, juce_gui_extra, juce_opengl
  26. exporters: xcode_mac, vs2017, linux_make, androidstudio, xcode_iphone
  27. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  28. type: Component
  29. mainClass: OpenGLDemoClasses::OpenGLDemo
  30. useLocalCopy: 1
  31. END_JUCE_PIP_METADATA
  32. *******************************************************************************/
  33. #pragma once
  34. #include "../Assets/DemoUtilities.h"
  35. #include "../Assets/WavefrontObjParser.h"
  36. //==============================================================================
  37. struct OpenGLDemoClasses
  38. {
  39. /** Vertex data to be passed to the shaders.
  40. For the purposes of this demo, each vertex will have a 3D position, a colour and a
  41. 2D texture co-ordinate. Of course you can ignore these or manipulate them in the
  42. shader programs but are some useful defaults to work from.
  43. */
  44. struct Vertex
  45. {
  46. float position[3];
  47. float normal[3];
  48. float colour[4];
  49. float texCoord[2];
  50. };
  51. //==============================================================================
  52. // This class just manages the attributes that the demo shaders use.
  53. struct Attributes
  54. {
  55. Attributes (OpenGLContext& openGLContext, OpenGLShaderProgram& shader)
  56. {
  57. position .reset (createAttribute (openGLContext, shader, "position"));
  58. normal .reset (createAttribute (openGLContext, shader, "normal"));
  59. sourceColour .reset (createAttribute (openGLContext, shader, "sourceColour"));
  60. textureCoordIn.reset (createAttribute (openGLContext, shader, "textureCoordIn"));
  61. }
  62. void enable (OpenGLContext& openGLContext)
  63. {
  64. if (position.get() != nullptr)
  65. {
  66. openGLContext.extensions.glVertexAttribPointer (position->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), 0);
  67. openGLContext.extensions.glEnableVertexAttribArray (position->attributeID);
  68. }
  69. if (normal.get() != nullptr)
  70. {
  71. openGLContext.extensions.glVertexAttribPointer (normal->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 3));
  72. openGLContext.extensions.glEnableVertexAttribArray (normal->attributeID);
  73. }
  74. if (sourceColour.get() != nullptr)
  75. {
  76. openGLContext.extensions.glVertexAttribPointer (sourceColour->attributeID, 4, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 6));
  77. openGLContext.extensions.glEnableVertexAttribArray (sourceColour->attributeID);
  78. }
  79. if (textureCoordIn.get() != nullptr)
  80. {
  81. openGLContext.extensions.glVertexAttribPointer (textureCoordIn->attributeID, 2, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 10));
  82. openGLContext.extensions.glEnableVertexAttribArray (textureCoordIn->attributeID);
  83. }
  84. }
  85. void disable (OpenGLContext& openGLContext)
  86. {
  87. if (position.get() != nullptr) openGLContext.extensions.glDisableVertexAttribArray (position->attributeID);
  88. if (normal.get() != nullptr) openGLContext.extensions.glDisableVertexAttribArray (normal->attributeID);
  89. if (sourceColour.get() != nullptr) openGLContext.extensions.glDisableVertexAttribArray (sourceColour->attributeID);
  90. if (textureCoordIn.get() != nullptr) openGLContext.extensions.glDisableVertexAttribArray (textureCoordIn->attributeID);
  91. }
  92. std::unique_ptr<OpenGLShaderProgram::Attribute> position, normal, sourceColour, textureCoordIn;
  93. private:
  94. static OpenGLShaderProgram::Attribute* createAttribute (OpenGLContext& openGLContext,
  95. OpenGLShaderProgram& shader,
  96. const char* attributeName)
  97. {
  98. if (openGLContext.extensions.glGetAttribLocation (shader.getProgramID(), attributeName) < 0)
  99. return nullptr;
  100. return new OpenGLShaderProgram::Attribute (shader, attributeName);
  101. }
  102. };
  103. //==============================================================================
  104. // This class just manages the uniform values that the demo shaders use.
  105. struct Uniforms
  106. {
  107. Uniforms (OpenGLContext& openGLContext, OpenGLShaderProgram& shader)
  108. {
  109. projectionMatrix.reset (createUniform (openGLContext, shader, "projectionMatrix"));
  110. viewMatrix .reset (createUniform (openGLContext, shader, "viewMatrix"));
  111. texture .reset (createUniform (openGLContext, shader, "demoTexture"));
  112. lightPosition .reset (createUniform (openGLContext, shader, "lightPosition"));
  113. bouncingNumber .reset (createUniform (openGLContext, shader, "bouncingNumber"));
  114. }
  115. std::unique_ptr<OpenGLShaderProgram::Uniform> projectionMatrix, viewMatrix, texture, lightPosition, bouncingNumber;
  116. private:
  117. static OpenGLShaderProgram::Uniform* createUniform (OpenGLContext& openGLContext,
  118. OpenGLShaderProgram& shader,
  119. const char* uniformName)
  120. {
  121. if (openGLContext.extensions.glGetUniformLocation (shader.getProgramID(), uniformName) < 0)
  122. return nullptr;
  123. return new OpenGLShaderProgram::Uniform (shader, uniformName);
  124. }
  125. };
  126. //==============================================================================
  127. /** This loads a 3D model from an OBJ file and converts it into some vertex buffers
  128. that we can draw.
  129. */
  130. struct Shape
  131. {
  132. Shape (OpenGLContext& openGLContext)
  133. {
  134. if (shapeFile.load (loadEntireAssetIntoString ("teapot.obj")).wasOk())
  135. for (auto* s : shapeFile.shapes)
  136. vertexBuffers.add (new VertexBuffer (openGLContext, *s));
  137. }
  138. void draw (OpenGLContext& openGLContext, Attributes& attributes)
  139. {
  140. for (auto* vertexBuffer : vertexBuffers)
  141. {
  142. vertexBuffer->bind();
  143. attributes.enable (openGLContext);
  144. glDrawElements (GL_TRIANGLES, vertexBuffer->numIndices, GL_UNSIGNED_INT, 0);
  145. attributes.disable (openGLContext);
  146. }
  147. }
  148. private:
  149. struct VertexBuffer
  150. {
  151. VertexBuffer (OpenGLContext& context, WavefrontObjFile::Shape& shape) : openGLContext (context)
  152. {
  153. numIndices = shape.mesh.indices.size();
  154. openGLContext.extensions.glGenBuffers (1, &vertexBuffer);
  155. openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  156. Array<Vertex> vertices;
  157. createVertexListFromMesh (shape.mesh, vertices, Colours::green);
  158. openGLContext.extensions.glBufferData (GL_ARRAY_BUFFER, vertices.size() * (int) sizeof (Vertex),
  159. vertices.getRawDataPointer(), GL_STATIC_DRAW);
  160. openGLContext.extensions.glGenBuffers (1, &indexBuffer);
  161. openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
  162. openGLContext.extensions.glBufferData (GL_ELEMENT_ARRAY_BUFFER, numIndices * (int) sizeof (juce::uint32),
  163. shape.mesh.indices.getRawDataPointer(), GL_STATIC_DRAW);
  164. }
  165. ~VertexBuffer()
  166. {
  167. openGLContext.extensions.glDeleteBuffers (1, &vertexBuffer);
  168. openGLContext.extensions.glDeleteBuffers (1, &indexBuffer);
  169. }
  170. void bind()
  171. {
  172. openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  173. openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
  174. }
  175. GLuint vertexBuffer, indexBuffer;
  176. int numIndices;
  177. OpenGLContext& openGLContext;
  178. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VertexBuffer)
  179. };
  180. WavefrontObjFile shapeFile;
  181. OwnedArray<VertexBuffer> vertexBuffers;
  182. static void createVertexListFromMesh (const WavefrontObjFile::Mesh& mesh, Array<Vertex>& list, Colour colour)
  183. {
  184. auto scale = 0.2f;
  185. WavefrontObjFile::TextureCoord defaultTexCoord = { 0.5f, 0.5f };
  186. WavefrontObjFile::Vertex defaultNormal = { 0.5f, 0.5f, 0.5f };
  187. for (int i = 0; i < mesh.vertices.size(); ++i)
  188. {
  189. auto& v = mesh.vertices.getReference (i);
  190. auto& n = (i < mesh.normals.size() ? mesh.normals.getReference (i)
  191. : defaultNormal);
  192. auto& tc = (i < mesh.textureCoords.size() ? mesh.textureCoords.getReference (i)
  193. : defaultTexCoord);
  194. list.add ({ { scale * v.x, scale * v.y, scale * v.z, },
  195. { scale * n.x, scale * n.y, scale * n.z, },
  196. { colour.getFloatRed(), colour.getFloatGreen(), colour.getFloatBlue(), colour.getFloatAlpha() },
  197. { tc.x, tc.y } });
  198. }
  199. }
  200. };
  201. //==============================================================================
  202. // These classes are used to load textures from the various sources that the demo uses..
  203. struct DemoTexture
  204. {
  205. virtual ~DemoTexture() {}
  206. virtual bool applyTo (OpenGLTexture&) = 0;
  207. String name;
  208. };
  209. struct DynamicTexture : public DemoTexture
  210. {
  211. DynamicTexture() { name = "Dynamically-generated texture"; }
  212. Image image;
  213. BouncingNumber x, y;
  214. bool applyTo (OpenGLTexture& texture) override
  215. {
  216. int size = 128;
  217. if (! image.isValid())
  218. image = Image (Image::ARGB, size, size, true);
  219. {
  220. Graphics g (image);
  221. g.fillAll (Colours::lightcyan);
  222. g.setColour (Colours::darkred);
  223. g.drawRect (0, 0, size, size, 2);
  224. g.setColour (Colours::green);
  225. g.fillEllipse (x.getValue() * size * 0.9f, y.getValue() * size * 0.9f, size * 0.1f, size * 0.1f);
  226. g.setColour (Colours::black);
  227. g.setFont (40);
  228. g.drawFittedText (String (Time::getCurrentTime().getMilliseconds()), image.getBounds(), Justification::centred, 1);
  229. }
  230. texture.loadImage (image);
  231. return true;
  232. }
  233. };
  234. struct BuiltInTexture : public DemoTexture
  235. {
  236. BuiltInTexture (const char* nm, const void* imageData, size_t imageSize)
  237. : image (resizeImageToPowerOfTwo (ImageFileFormat::loadFrom (imageData, imageSize)))
  238. {
  239. name = nm;
  240. }
  241. Image image;
  242. bool applyTo (OpenGLTexture& texture) override
  243. {
  244. texture.loadImage (image);
  245. return false;
  246. }
  247. };
  248. struct TextureFromFile : public DemoTexture
  249. {
  250. TextureFromFile (const File& file)
  251. {
  252. name = file.getFileName();
  253. image = resizeImageToPowerOfTwo (ImageFileFormat::loadFrom (file));
  254. }
  255. Image image;
  256. bool applyTo (OpenGLTexture& texture) override
  257. {
  258. texture.loadImage (image);
  259. return false;
  260. }
  261. };
  262. struct TextureFromAsset : public DemoTexture
  263. {
  264. TextureFromAsset (const char* assetName)
  265. {
  266. name = assetName;
  267. image = resizeImageToPowerOfTwo (getImageFromAssets (assetName));
  268. }
  269. Image image;
  270. bool applyTo (OpenGLTexture& texture) override
  271. {
  272. texture.loadImage (image);
  273. return false;
  274. }
  275. };
  276. static Image resizeImageToPowerOfTwo (Image image)
  277. {
  278. if (! (isPowerOfTwo (image.getWidth()) && isPowerOfTwo (image.getHeight())))
  279. return image.rescaled (jmin (1024, nextPowerOfTwo (image.getWidth())),
  280. jmin (1024, nextPowerOfTwo (image.getHeight())));
  281. return image;
  282. }
  283. class OpenGLDemo;
  284. //==============================================================================
  285. /**
  286. This component sits on top of the main GL demo, and contains all the sliders
  287. and widgets that control things.
  288. */
  289. class DemoControlsOverlay : public Component,
  290. private CodeDocument::Listener,
  291. private Slider::Listener,
  292. private Timer
  293. {
  294. public:
  295. DemoControlsOverlay (OpenGLDemo& d)
  296. : demo (d)
  297. {
  298. addAndMakeVisible (statusLabel);
  299. statusLabel.setJustificationType (Justification::topLeft);
  300. statusLabel.setFont (Font (14.0f));
  301. addAndMakeVisible (sizeSlider);
  302. sizeSlider.setRange (0.0, 1.0, 0.001);
  303. sizeSlider.addListener (this);
  304. addAndMakeVisible (zoomLabel);
  305. zoomLabel.attachToComponent (&sizeSlider, true);
  306. addAndMakeVisible (speedSlider);
  307. speedSlider.setRange (0.0, 0.5, 0.001);
  308. speedSlider.addListener (this);
  309. speedSlider.setSkewFactor (0.5f);
  310. addAndMakeVisible (speedLabel);
  311. speedLabel.attachToComponent (&speedSlider, true);
  312. addAndMakeVisible (showBackgroundToggle);
  313. showBackgroundToggle.onClick = [this] { demo.doBackgroundDrawing = showBackgroundToggle.getToggleState(); };
  314. addAndMakeVisible (tabbedComp);
  315. tabbedComp.setTabBarDepth (25);
  316. tabbedComp.setColour (TabbedButtonBar::tabTextColourId, Colours::grey);
  317. tabbedComp.addTab ("Vertex", Colours::transparentBlack, &vertexEditorComp, false);
  318. tabbedComp.addTab ("Fragment", Colours::transparentBlack, &fragmentEditorComp, false);
  319. vertexDocument.addListener (this);
  320. fragmentDocument.addListener (this);
  321. textures.add (new TextureFromAsset ("portmeirion.jpg"));
  322. textures.add (new TextureFromAsset ("tile_background.png"));
  323. textures.add (new TextureFromAsset ("juce_icon.png"));
  324. textures.add (new DynamicTexture());
  325. addAndMakeVisible (textureBox);
  326. textureBox.onChange = [this] { selectTexture (textureBox.getSelectedId()); };
  327. updateTexturesList();
  328. addAndMakeVisible (presetBox);
  329. presetBox.onChange = [this] { selectPreset (presetBox.getSelectedItemIndex()); };
  330. auto presets = getPresets();
  331. for (int i = 0; i < presets.size(); ++i)
  332. presetBox.addItem (presets[i].name, i + 1);
  333. addAndMakeVisible (presetLabel);
  334. presetLabel.attachToComponent (&presetBox, true);
  335. addAndMakeVisible (textureLabel);
  336. textureLabel.attachToComponent (&textureBox, true);
  337. lookAndFeelChanged();
  338. }
  339. void initialise()
  340. {
  341. showBackgroundToggle.setToggleState (false, sendNotification);
  342. textureBox.setSelectedItemIndex (0);
  343. presetBox .setSelectedItemIndex (0);
  344. speedSlider.setValue (0.01);
  345. sizeSlider .setValue (0.5);
  346. }
  347. void resized() override
  348. {
  349. auto area = getLocalBounds().reduced (4);
  350. auto top = area.removeFromTop (75);
  351. auto sliders = top.removeFromRight (area.getWidth() / 2);
  352. showBackgroundToggle.setBounds (sliders.removeFromBottom (25));
  353. speedSlider .setBounds (sliders.removeFromBottom (25));
  354. sizeSlider .setBounds (sliders.removeFromBottom (25));
  355. top.removeFromRight (70);
  356. statusLabel.setBounds (top);
  357. auto shaderArea = area.removeFromBottom (area.getHeight() / 2);
  358. auto presets = shaderArea.removeFromTop (25);
  359. presets.removeFromLeft (100);
  360. presetBox.setBounds (presets.removeFromLeft (150));
  361. presets.removeFromLeft (100);
  362. textureBox.setBounds (presets);
  363. shaderArea.removeFromTop (4);
  364. tabbedComp.setBounds (shaderArea);
  365. }
  366. void mouseDown (const MouseEvent& e) override
  367. {
  368. demo.draggableOrientation.mouseDown (e.getPosition());
  369. }
  370. void mouseDrag (const MouseEvent& e) override
  371. {
  372. demo.draggableOrientation.mouseDrag (e.getPosition());
  373. }
  374. void mouseWheelMove (const MouseEvent&, const MouseWheelDetails& d) override
  375. {
  376. sizeSlider.setValue (sizeSlider.getValue() + d.deltaY);
  377. }
  378. void mouseMagnify (const MouseEvent&, float magnifyAmmount) override
  379. {
  380. sizeSlider.setValue (sizeSlider.getValue() + magnifyAmmount - 1.0f);
  381. }
  382. void selectPreset (int preset)
  383. {
  384. const auto& p = getPresets()[preset];
  385. vertexDocument .replaceAllContent (p.vertexShader);
  386. fragmentDocument.replaceAllContent (p.fragmentShader);
  387. startTimer (1);
  388. }
  389. void selectTexture (int itemID)
  390. {
  391. #if JUCE_MODAL_LOOPS_PERMITTED
  392. if (itemID == 1000)
  393. {
  394. auto lastLocation = File::getSpecialLocation (File::userPicturesDirectory);
  395. FileChooser fc ("Choose an image to open...", lastLocation, "*.jpg;*.jpeg;*.png;*.gif");
  396. if (fc.browseForFileToOpen())
  397. {
  398. lastLocation = fc.getResult();
  399. textures.add (new TextureFromFile (fc.getResult()));
  400. updateTexturesList();
  401. textureBox.setSelectedId (textures.size());
  402. }
  403. }
  404. else
  405. #endif
  406. {
  407. if (auto* t = textures[itemID - 1])
  408. demo.setTexture (t);
  409. }
  410. }
  411. void updateTexturesList()
  412. {
  413. textureBox.clear();
  414. for (int i = 0; i < textures.size(); ++i)
  415. textureBox.addItem (textures.getUnchecked (i)->name, i + 1);
  416. #if JUCE_MODAL_LOOPS_PERMITTED
  417. textureBox.addSeparator();
  418. textureBox.addItem ("Load from a file...", 1000);
  419. #endif
  420. }
  421. void updateShader()
  422. {
  423. startTimer (10);
  424. }
  425. Label statusLabel;
  426. private:
  427. void sliderValueChanged (Slider*) override
  428. {
  429. demo.scale = (float) sizeSlider .getValue();
  430. demo.rotationSpeed = (float) speedSlider.getValue();
  431. }
  432. enum { shaderLinkDelay = 500 };
  433. void codeDocumentTextInserted (const String& /*newText*/, int /*insertIndex*/) override
  434. {
  435. startTimer (shaderLinkDelay);
  436. }
  437. void codeDocumentTextDeleted (int /*startIndex*/, int /*endIndex*/) override
  438. {
  439. startTimer (shaderLinkDelay);
  440. }
  441. void timerCallback() override
  442. {
  443. stopTimer();
  444. demo.setShaderProgram (vertexDocument .getAllContent(),
  445. fragmentDocument.getAllContent());
  446. }
  447. void lookAndFeelChanged() override
  448. {
  449. auto editorBackground = getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground,
  450. Colours::white);
  451. for (int i = tabbedComp.getNumTabs(); i >= 0; --i)
  452. tabbedComp.setTabBackgroundColour (i, editorBackground);
  453. vertexEditorComp .setColour (CodeEditorComponent::backgroundColourId, editorBackground);
  454. fragmentEditorComp.setColour (CodeEditorComponent::backgroundColourId, editorBackground);
  455. }
  456. OpenGLDemo& demo;
  457. Label speedLabel { {}, "Speed:" },
  458. zoomLabel { {}, "Zoom:" };
  459. CodeDocument vertexDocument, fragmentDocument;
  460. CodeEditorComponent vertexEditorComp { vertexDocument, nullptr },
  461. fragmentEditorComp { fragmentDocument, nullptr };
  462. TabbedComponent tabbedComp { TabbedButtonBar::TabsAtLeft };
  463. ComboBox presetBox, textureBox;
  464. Label presetLabel { {}, "Shader Preset:" },
  465. textureLabel { {}, "Texture:" };
  466. Slider speedSlider, sizeSlider;
  467. ToggleButton showBackgroundToggle { "Draw 2D graphics in background" };
  468. OwnedArray<DemoTexture> textures;
  469. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoControlsOverlay)
  470. };
  471. //==============================================================================
  472. /** This is the main demo component - the GL context gets attached to it, and
  473. it implements the OpenGLRenderer callback so that it can do real GL work.
  474. */
  475. class OpenGLDemo : public Component,
  476. private OpenGLRenderer,
  477. private AsyncUpdater
  478. {
  479. public:
  480. OpenGLDemo()
  481. {
  482. if (auto* peer = getPeer())
  483. peer->setCurrentRenderingEngine (0);
  484. setOpaque (true);
  485. controlsOverlay.reset (new DemoControlsOverlay (*this));
  486. addAndMakeVisible (controlsOverlay.get());
  487. openGLContext.setRenderer (this);
  488. openGLContext.attachTo (*this);
  489. openGLContext.setContinuousRepainting (true);
  490. controlsOverlay->initialise();
  491. setSize (500, 500);
  492. }
  493. ~OpenGLDemo()
  494. {
  495. openGLContext.detach();
  496. }
  497. void newOpenGLContextCreated() override
  498. {
  499. // nothing to do in this case - we'll initialise our shaders + textures
  500. // on demand, during the render callback.
  501. freeAllContextObjects();
  502. if (controlsOverlay.get() != nullptr)
  503. controlsOverlay->updateShader();
  504. }
  505. void openGLContextClosing() override
  506. {
  507. // When the context is about to close, you must use this callback to delete
  508. // any GPU resources while the context is still current.
  509. freeAllContextObjects();
  510. if (lastTexture != nullptr)
  511. setTexture (lastTexture);
  512. }
  513. void freeAllContextObjects()
  514. {
  515. shape .reset();
  516. shader .reset();
  517. attributes.reset();
  518. uniforms .reset();
  519. texture .release();
  520. }
  521. // This is a virtual method in OpenGLRenderer, and is called when it's time
  522. // to do your GL rendering.
  523. void renderOpenGL() override
  524. {
  525. jassert (OpenGLHelpers::isContextActive());
  526. auto desktopScale = (float) openGLContext.getRenderingScale();
  527. OpenGLHelpers::clear (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground,
  528. Colours::lightblue));
  529. if (textureToUse != nullptr)
  530. if (! textureToUse->applyTo (texture))
  531. textureToUse = nullptr;
  532. // First draw our background graphics to demonstrate the OpenGLGraphicsContext class
  533. if (doBackgroundDrawing)
  534. drawBackground2DStuff (desktopScale);
  535. updateShader(); // Check whether we need to compile a new shader
  536. if (shader.get() == nullptr)
  537. return;
  538. // Having used the juce 2D renderer, it will have messed-up a whole load of GL state, so
  539. // we need to initialise some important settings before doing our normal GL 3D drawing..
  540. glEnable (GL_DEPTH_TEST);
  541. glDepthFunc (GL_LESS);
  542. glEnable (GL_BLEND);
  543. glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  544. openGLContext.extensions.glActiveTexture (GL_TEXTURE0);
  545. glEnable (GL_TEXTURE_2D);
  546. glViewport (0, 0, roundToInt (desktopScale * getWidth()), roundToInt (desktopScale * getHeight()));
  547. texture.bind();
  548. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  549. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  550. shader->use();
  551. if (uniforms->projectionMatrix.get() != nullptr)
  552. uniforms->projectionMatrix->setMatrix4 (getProjectionMatrix().mat, 1, false);
  553. if (uniforms->viewMatrix.get() != nullptr)
  554. uniforms->viewMatrix->setMatrix4 (getViewMatrix().mat, 1, false);
  555. if (uniforms->texture.get() != nullptr)
  556. uniforms->texture->set ((GLint) 0);
  557. if (uniforms->lightPosition.get() != nullptr)
  558. uniforms->lightPosition->set (-15.0f, 10.0f, 15.0f, 0.0f);
  559. if (uniforms->bouncingNumber.get() != nullptr)
  560. uniforms->bouncingNumber->set (bouncingNumber.getValue());
  561. shape->draw (openGLContext, *attributes);
  562. // Reset the element buffers so child Components draw correctly
  563. openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
  564. openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0);
  565. if (! controlsOverlay->isMouseButtonDown())
  566. rotation += (float) rotationSpeed;
  567. }
  568. Matrix3D<float> getProjectionMatrix() const
  569. {
  570. auto w = 1.0f / (scale + 0.1f);
  571. auto h = w * getLocalBounds().toFloat().getAspectRatio (false);
  572. return Matrix3D<float>::fromFrustum (-w, w, -h, h, 4.0f, 30.0f);
  573. }
  574. Matrix3D<float> getViewMatrix() const
  575. {
  576. auto viewMatrix = draggableOrientation.getRotationMatrix()
  577. * Vector3D<float> (0.0f, 1.0f, -10.0f);
  578. auto rotationMatrix = Matrix3D<float>::rotation ({ rotation, rotation, -0.3f });
  579. return rotationMatrix * viewMatrix;
  580. }
  581. void setTexture (DemoTexture* t)
  582. {
  583. lastTexture = textureToUse = t;
  584. }
  585. void setShaderProgram (const String& vertexShader, const String& fragmentShader)
  586. {
  587. newVertexShader = vertexShader;
  588. newFragmentShader = fragmentShader;
  589. }
  590. void paint (Graphics&) override {}
  591. void resized() override
  592. {
  593. controlsOverlay->setBounds (getLocalBounds());
  594. draggableOrientation.setViewport (getLocalBounds());
  595. }
  596. Draggable3DOrientation draggableOrientation;
  597. bool doBackgroundDrawing = false;
  598. float scale = 0.5f, rotationSpeed = 0.0f;
  599. BouncingNumber bouncingNumber;
  600. private:
  601. void handleAsyncUpdate() override
  602. {
  603. controlsOverlay->statusLabel.setText (statusText, dontSendNotification);
  604. }
  605. void drawBackground2DStuff (float desktopScale)
  606. {
  607. // Create an OpenGLGraphicsContext that will draw into this GL window..
  608. std::unique_ptr<LowLevelGraphicsContext> glRenderer (createOpenGLGraphicsContext (openGLContext,
  609. roundToInt (desktopScale * getWidth()),
  610. roundToInt (desktopScale * getHeight())));
  611. if (glRenderer.get() != nullptr)
  612. {
  613. Graphics g (*glRenderer);
  614. g.addTransform (AffineTransform::scale (desktopScale));
  615. for (auto s : stars)
  616. {
  617. auto size = 0.25f;
  618. // This stuff just creates a spinning star shape and fills it..
  619. Path p;
  620. p.addStar ({ getWidth() * s.x.getValue(),
  621. getHeight() * s.y.getValue() },
  622. 7,
  623. getHeight() * size * 0.5f,
  624. getHeight() * size,
  625. s.angle.getValue());
  626. auto hue = s.hue.getValue();
  627. g.setGradientFill (ColourGradient (Colours::green.withRotatedHue (hue).withAlpha (0.8f),
  628. 0, 0,
  629. Colours::red.withRotatedHue (hue).withAlpha (0.5f),
  630. 0, (float) getHeight(), false));
  631. g.fillPath (p);
  632. }
  633. }
  634. }
  635. OpenGLContext openGLContext;
  636. std::unique_ptr<DemoControlsOverlay> controlsOverlay;
  637. float rotation = 0.0f;
  638. std::unique_ptr<OpenGLShaderProgram> shader;
  639. std::unique_ptr<Shape> shape;
  640. std::unique_ptr<Attributes> attributes;
  641. std::unique_ptr<Uniforms> uniforms;
  642. OpenGLTexture texture;
  643. DemoTexture* textureToUse = nullptr;
  644. DemoTexture* lastTexture = nullptr;
  645. String newVertexShader, newFragmentShader, statusText;
  646. struct BackgroundStar
  647. {
  648. SlowerBouncingNumber x, y, hue, angle;
  649. };
  650. BackgroundStar stars[3];
  651. //==============================================================================
  652. void updateShader()
  653. {
  654. if (newVertexShader.isNotEmpty() || newFragmentShader.isNotEmpty())
  655. {
  656. std::unique_ptr<OpenGLShaderProgram> newShader (new OpenGLShaderProgram (openGLContext));
  657. if (newShader->addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (newVertexShader))
  658. && newShader->addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (newFragmentShader))
  659. && newShader->link())
  660. {
  661. shape .reset();
  662. attributes.reset();
  663. uniforms .reset();
  664. shader.reset (newShader.release());
  665. shader->use();
  666. shape .reset (new Shape (openGLContext));
  667. attributes.reset (new Attributes (openGLContext, *shader));
  668. uniforms .reset (new Uniforms (openGLContext, *shader));
  669. statusText = "GLSL: v" + String (OpenGLShaderProgram::getLanguageVersion(), 2);
  670. }
  671. else
  672. {
  673. statusText = newShader->getLastError();
  674. }
  675. triggerAsyncUpdate();
  676. newVertexShader = {};
  677. newFragmentShader = {};
  678. }
  679. }
  680. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLDemo)
  681. };
  682. //==============================================================================
  683. struct ShaderPreset
  684. {
  685. const char* name;
  686. const char* vertexShader;
  687. const char* fragmentShader;
  688. };
  689. static Array<ShaderPreset> getPresets()
  690. {
  691. #define SHADER_DEMO_HEADER \
  692. "/* This is a live OpenGL Shader demo.\n" \
  693. " Edit the shader program below and it will be \n" \
  694. " compiled and applied to the model above!\n" \
  695. "*/\n\n"
  696. ShaderPreset presets[] =
  697. {
  698. {
  699. "Texture + Lighting",
  700. SHADER_DEMO_HEADER
  701. "attribute vec4 position;\n"
  702. "attribute vec4 normal;\n"
  703. "attribute vec4 sourceColour;\n"
  704. "attribute vec2 textureCoordIn;\n"
  705. "\n"
  706. "uniform mat4 projectionMatrix;\n"
  707. "uniform mat4 viewMatrix;\n"
  708. "uniform vec4 lightPosition;\n"
  709. "\n"
  710. "varying vec4 destinationColour;\n"
  711. "varying vec2 textureCoordOut;\n"
  712. "varying float lightIntensity;\n"
  713. "\n"
  714. "void main()\n"
  715. "{\n"
  716. " destinationColour = sourceColour;\n"
  717. " textureCoordOut = textureCoordIn;\n"
  718. "\n"
  719. " vec4 light = viewMatrix * lightPosition;\n"
  720. " lightIntensity = dot (light, normal);\n"
  721. "\n"
  722. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  723. "}\n",
  724. SHADER_DEMO_HEADER
  725. #if JUCE_OPENGL_ES
  726. "varying lowp vec4 destinationColour;\n"
  727. "varying lowp vec2 textureCoordOut;\n"
  728. "varying highp float lightIntensity;\n"
  729. #else
  730. "varying vec4 destinationColour;\n"
  731. "varying vec2 textureCoordOut;\n"
  732. "varying float lightIntensity;\n"
  733. #endif
  734. "\n"
  735. "uniform sampler2D demoTexture;\n"
  736. "\n"
  737. "void main()\n"
  738. "{\n"
  739. #if JUCE_OPENGL_ES
  740. " highp float l = max (0.3, lightIntensity * 0.3);\n"
  741. " highp vec4 colour = vec4 (l, l, l, 1.0);\n"
  742. #else
  743. " float l = max (0.3, lightIntensity * 0.3);\n"
  744. " vec4 colour = vec4 (l, l, l, 1.0);\n"
  745. #endif
  746. " gl_FragColor = colour * texture2D (demoTexture, textureCoordOut);\n"
  747. "}\n"
  748. },
  749. {
  750. "Textured",
  751. SHADER_DEMO_HEADER
  752. "attribute vec4 position;\n"
  753. "attribute vec4 sourceColour;\n"
  754. "attribute vec2 textureCoordIn;\n"
  755. "\n"
  756. "uniform mat4 projectionMatrix;\n"
  757. "uniform mat4 viewMatrix;\n"
  758. "\n"
  759. "varying vec4 destinationColour;\n"
  760. "varying vec2 textureCoordOut;\n"
  761. "\n"
  762. "void main()\n"
  763. "{\n"
  764. " destinationColour = sourceColour;\n"
  765. " textureCoordOut = textureCoordIn;\n"
  766. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  767. "}\n",
  768. SHADER_DEMO_HEADER
  769. #if JUCE_OPENGL_ES
  770. "varying lowp vec4 destinationColour;\n"
  771. "varying lowp vec2 textureCoordOut;\n"
  772. #else
  773. "varying vec4 destinationColour;\n"
  774. "varying vec2 textureCoordOut;\n"
  775. #endif
  776. "\n"
  777. "uniform sampler2D demoTexture;\n"
  778. "\n"
  779. "void main()\n"
  780. "{\n"
  781. " gl_FragColor = texture2D (demoTexture, textureCoordOut);\n"
  782. "}\n"
  783. },
  784. {
  785. "Flat Colour",
  786. SHADER_DEMO_HEADER
  787. "attribute vec4 position;\n"
  788. "attribute vec4 sourceColour;\n"
  789. "attribute vec2 textureCoordIn;\n"
  790. "\n"
  791. "uniform mat4 projectionMatrix;\n"
  792. "uniform mat4 viewMatrix;\n"
  793. "\n"
  794. "varying vec4 destinationColour;\n"
  795. "varying vec2 textureCoordOut;\n"
  796. "\n"
  797. "void main()\n"
  798. "{\n"
  799. " destinationColour = sourceColour;\n"
  800. " textureCoordOut = textureCoordIn;\n"
  801. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  802. "}\n",
  803. SHADER_DEMO_HEADER
  804. #if JUCE_OPENGL_ES
  805. "varying lowp vec4 destinationColour;\n"
  806. "varying lowp vec2 textureCoordOut;\n"
  807. #else
  808. "varying vec4 destinationColour;\n"
  809. "varying vec2 textureCoordOut;\n"
  810. #endif
  811. "\n"
  812. "void main()\n"
  813. "{\n"
  814. " gl_FragColor = destinationColour;\n"
  815. "}\n"
  816. },
  817. {
  818. "Rainbow",
  819. SHADER_DEMO_HEADER
  820. "attribute vec4 position;\n"
  821. "attribute vec4 sourceColour;\n"
  822. "attribute vec2 textureCoordIn;\n"
  823. "\n"
  824. "uniform mat4 projectionMatrix;\n"
  825. "uniform mat4 viewMatrix;\n"
  826. "\n"
  827. "varying vec4 destinationColour;\n"
  828. "varying vec2 textureCoordOut;\n"
  829. "\n"
  830. "varying float xPos;\n"
  831. "varying float yPos;\n"
  832. "varying float zPos;\n"
  833. "\n"
  834. "void main()\n"
  835. "{\n"
  836. " vec4 v = vec4 (position);\n"
  837. " xPos = clamp (v.x, 0.0, 1.0);\n"
  838. " yPos = clamp (v.y, 0.0, 1.0);\n"
  839. " zPos = clamp (v.z, 0.0, 1.0);\n"
  840. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  841. "}",
  842. SHADER_DEMO_HEADER
  843. #if JUCE_OPENGL_ES
  844. "varying lowp vec4 destinationColour;\n"
  845. "varying lowp vec2 textureCoordOut;\n"
  846. "varying lowp float xPos;\n"
  847. "varying lowp float yPos;\n"
  848. "varying lowp float zPos;\n"
  849. #else
  850. "varying vec4 destinationColour;\n"
  851. "varying vec2 textureCoordOut;\n"
  852. "varying float xPos;\n"
  853. "varying float yPos;\n"
  854. "varying float zPos;\n"
  855. #endif
  856. "\n"
  857. "void main()\n"
  858. "{\n"
  859. " gl_FragColor = vec4 (xPos, yPos, zPos, 1.0);\n"
  860. "}"
  861. },
  862. {
  863. "Changing Colour",
  864. SHADER_DEMO_HEADER
  865. "attribute vec4 position;\n"
  866. "attribute vec2 textureCoordIn;\n"
  867. "\n"
  868. "uniform mat4 projectionMatrix;\n"
  869. "uniform mat4 viewMatrix;\n"
  870. "\n"
  871. "varying vec2 textureCoordOut;\n"
  872. "\n"
  873. "void main()\n"
  874. "{\n"
  875. " textureCoordOut = textureCoordIn;\n"
  876. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  877. "}\n",
  878. SHADER_DEMO_HEADER
  879. "#define PI 3.1415926535897932384626433832795\n"
  880. "\n"
  881. #if JUCE_OPENGL_ES
  882. "precision mediump float;\n"
  883. "varying lowp vec2 textureCoordOut;\n"
  884. #else
  885. "varying vec2 textureCoordOut;\n"
  886. #endif
  887. "uniform float bouncingNumber;\n"
  888. "\n"
  889. "void main()\n"
  890. "{\n"
  891. " float b = bouncingNumber;\n"
  892. " float n = b * PI * 2.0;\n"
  893. " float sn = (sin (n * textureCoordOut.x) * 0.5) + 0.5;\n"
  894. " float cn = (sin (n * textureCoordOut.y) * 0.5) + 0.5;\n"
  895. "\n"
  896. " vec4 col = vec4 (b, sn, cn, 1.0);\n"
  897. " gl_FragColor = col;\n"
  898. "}\n"
  899. },
  900. {
  901. "Simple Light",
  902. SHADER_DEMO_HEADER
  903. "attribute vec4 position;\n"
  904. "attribute vec4 normal;\n"
  905. "\n"
  906. "uniform mat4 projectionMatrix;\n"
  907. "uniform mat4 viewMatrix;\n"
  908. "uniform vec4 lightPosition;\n"
  909. "\n"
  910. "varying float lightIntensity;\n"
  911. "\n"
  912. "void main()\n"
  913. "{\n"
  914. " vec4 light = viewMatrix * lightPosition;\n"
  915. " lightIntensity = dot (light, normal);\n"
  916. "\n"
  917. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  918. "}\n",
  919. SHADER_DEMO_HEADER
  920. #if JUCE_OPENGL_ES
  921. "varying highp float lightIntensity;\n"
  922. #else
  923. "varying float lightIntensity;\n"
  924. #endif
  925. "\n"
  926. "void main()\n"
  927. "{\n"
  928. #if JUCE_OPENGL_ES
  929. " highp float l = lightIntensity * 0.25;\n"
  930. " highp vec4 colour = vec4 (l, l, l, 1.0);\n"
  931. #else
  932. " float l = lightIntensity * 0.25;\n"
  933. " vec4 colour = vec4 (l, l, l, 1.0);\n"
  934. #endif
  935. "\n"
  936. " gl_FragColor = colour;\n"
  937. "}\n"
  938. },
  939. {
  940. "Flattened",
  941. SHADER_DEMO_HEADER
  942. "attribute vec4 position;\n"
  943. "attribute vec4 normal;\n"
  944. "\n"
  945. "uniform mat4 projectionMatrix;\n"
  946. "uniform mat4 viewMatrix;\n"
  947. "uniform vec4 lightPosition;\n"
  948. "\n"
  949. "varying float lightIntensity;\n"
  950. "\n"
  951. "void main()\n"
  952. "{\n"
  953. " vec4 light = viewMatrix * lightPosition;\n"
  954. " lightIntensity = dot (light, normal);\n"
  955. "\n"
  956. " vec4 v = vec4 (position);\n"
  957. " v.z = v.z * 0.1;\n"
  958. "\n"
  959. " gl_Position = projectionMatrix * viewMatrix * v;\n"
  960. "}\n",
  961. SHADER_DEMO_HEADER
  962. #if JUCE_OPENGL_ES
  963. "varying highp float lightIntensity;\n"
  964. #else
  965. "varying float lightIntensity;\n"
  966. #endif
  967. "\n"
  968. "void main()\n"
  969. "{\n"
  970. #if JUCE_OPENGL_ES
  971. " highp float l = lightIntensity * 0.25;\n"
  972. " highp vec4 colour = vec4 (l, l, l, 1.0);\n"
  973. #else
  974. " float l = lightIntensity * 0.25;\n"
  975. " vec4 colour = vec4 (l, l, l, 1.0);\n"
  976. #endif
  977. "\n"
  978. " gl_FragColor = colour;\n"
  979. "}\n"
  980. },
  981. {
  982. "Toon Shader",
  983. SHADER_DEMO_HEADER
  984. "attribute vec4 position;\n"
  985. "attribute vec4 normal;\n"
  986. "\n"
  987. "uniform mat4 projectionMatrix;\n"
  988. "uniform mat4 viewMatrix;\n"
  989. "uniform vec4 lightPosition;\n"
  990. "\n"
  991. "varying float lightIntensity;\n"
  992. "\n"
  993. "void main()\n"
  994. "{\n"
  995. " vec4 light = viewMatrix * lightPosition;\n"
  996. " lightIntensity = dot (light, normal);\n"
  997. "\n"
  998. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  999. "}\n",
  1000. SHADER_DEMO_HEADER
  1001. #if JUCE_OPENGL_ES
  1002. "varying highp float lightIntensity;\n"
  1003. #else
  1004. "varying float lightIntensity;\n"
  1005. #endif
  1006. "\n"
  1007. "void main()\n"
  1008. "{\n"
  1009. #if JUCE_OPENGL_ES
  1010. " highp float intensity = lightIntensity * 0.5;\n"
  1011. " highp vec4 colour;\n"
  1012. #else
  1013. " float intensity = lightIntensity * 0.5;\n"
  1014. " vec4 colour;\n"
  1015. #endif
  1016. "\n"
  1017. " if (intensity > 0.95)\n"
  1018. " colour = vec4 (1.0, 0.5, 0.5, 1.0);\n"
  1019. " else if (intensity > 0.5)\n"
  1020. " colour = vec4 (0.6, 0.3, 0.3, 1.0);\n"
  1021. " else if (intensity > 0.25)\n"
  1022. " colour = vec4 (0.4, 0.2, 0.2, 1.0);\n"
  1023. " else\n"
  1024. " colour = vec4 (0.2, 0.1, 0.1, 1.0);\n"
  1025. "\n"
  1026. " gl_FragColor = colour;\n"
  1027. "}\n"
  1028. }
  1029. };
  1030. return Array<ShaderPreset> (presets, numElementsInArray (presets));
  1031. }
  1032. };