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.

1229 lines
46KB

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