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.

1259 lines
46KB

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