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.

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