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.

880 lines
28KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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. class OpenGLContext::CachedImage : public CachedComponentImage,
  18. public Thread
  19. {
  20. public:
  21. CachedImage (OpenGLContext& c, Component& comp,
  22. const OpenGLPixelFormat& pixFormat, void* contextToShare)
  23. : Thread ("OpenGL Rendering"),
  24. context (c), component (comp),
  25. scale (1.0),
  26. #if JUCE_OPENGL_ES
  27. shadersAvailable (true),
  28. #else
  29. shadersAvailable (false),
  30. #endif
  31. hasInitialised (false),
  32. needsUpdate (1), lastMMLockReleaseTime (0)
  33. {
  34. nativeContext = new NativeContext (component, pixFormat, contextToShare, c.useMultisampling);
  35. if (nativeContext->createdOk())
  36. context.nativeContext = nativeContext;
  37. else
  38. nativeContext = nullptr;
  39. }
  40. ~CachedImage()
  41. {
  42. stop();
  43. }
  44. void start()
  45. {
  46. #if ! JUCE_ANDROID
  47. if (nativeContext != nullptr)
  48. startThread (6);
  49. #endif
  50. }
  51. void stop()
  52. {
  53. #if ! JUCE_ANDROID
  54. stopThread (10000);
  55. #endif
  56. hasInitialised = false;
  57. }
  58. //==============================================================================
  59. void paint (Graphics&) override {}
  60. bool invalidateAll() override
  61. {
  62. validArea.clear();
  63. triggerRepaint();
  64. return false;
  65. }
  66. bool invalidate (const Rectangle<int>& area) override
  67. {
  68. validArea.subtract (area * scale);
  69. triggerRepaint();
  70. return false;
  71. }
  72. void releaseResources() override {}
  73. void triggerRepaint()
  74. {
  75. needsUpdate = 1;
  76. #if JUCE_ANDROID
  77. if (nativeContext != nullptr)
  78. nativeContext->triggerRepaint();
  79. #else
  80. notify();
  81. #endif
  82. }
  83. //==============================================================================
  84. bool ensureFrameBufferSize()
  85. {
  86. const int fbW = cachedImageFrameBuffer.getWidth();
  87. const int fbH = cachedImageFrameBuffer.getHeight();
  88. if (fbW != viewportArea.getWidth() || fbH != viewportArea.getHeight() || ! cachedImageFrameBuffer.isValid())
  89. {
  90. if (! cachedImageFrameBuffer.initialise (context, viewportArea.getWidth(), viewportArea.getHeight()))
  91. return false;
  92. validArea.clear();
  93. JUCE_CHECK_OPENGL_ERROR
  94. }
  95. return true;
  96. }
  97. void clearRegionInFrameBuffer (const RectangleList<int>& list)
  98. {
  99. glClearColor (0, 0, 0, 0);
  100. glEnable (GL_SCISSOR_TEST);
  101. const GLuint previousFrameBufferTarget = OpenGLFrameBuffer::getCurrentFrameBufferTarget();
  102. cachedImageFrameBuffer.makeCurrentRenderingTarget();
  103. const int imageH = cachedImageFrameBuffer.getHeight();
  104. for (const Rectangle<int>* i = list.begin(), * const e = list.end(); i != e; ++i)
  105. {
  106. glScissor (i->getX(), imageH - i->getBottom(), i->getWidth(), i->getHeight());
  107. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  108. }
  109. glDisable (GL_SCISSOR_TEST);
  110. context.extensions.glBindFramebuffer (GL_FRAMEBUFFER, previousFrameBufferTarget);
  111. JUCE_CHECK_OPENGL_ERROR
  112. }
  113. bool renderFrame()
  114. {
  115. ScopedPointer<MessageManagerLock> mmLock;
  116. const bool isUpdating = needsUpdate.compareAndSetBool (0, 1);
  117. if (context.renderComponents && isUpdating)
  118. {
  119. // This avoids hogging the message thread when doing intensive rendering.
  120. if (lastMMLockReleaseTime + 1 >= Time::getMillisecondCounter())
  121. wait (2);
  122. mmLock = new MessageManagerLock (this); // need to acquire this before locking the context.
  123. if (! mmLock->lockWasGained())
  124. return false;
  125. }
  126. if (! context.makeActive())
  127. return false;
  128. NativeContext::Locker locker (*nativeContext);
  129. JUCE_CHECK_OPENGL_ERROR
  130. if (context.renderer != nullptr)
  131. {
  132. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  133. context.currentRenderScale = scale;
  134. context.renderer->renderOpenGL();
  135. clearGLError();
  136. }
  137. if (context.renderComponents)
  138. {
  139. if (isUpdating)
  140. {
  141. paintComponent();
  142. mmLock = nullptr;
  143. lastMMLockReleaseTime = Time::getMillisecondCounter();
  144. }
  145. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  146. drawComponentBuffer();
  147. }
  148. context.swapBuffers();
  149. return true;
  150. }
  151. void updateViewportSize (bool canTriggerUpdate)
  152. {
  153. if (ComponentPeer* peer = component.getPeer())
  154. {
  155. const double newScale = Desktop::getInstance().getDisplays()
  156. .getDisplayContaining (component.getScreenBounds().getCentre()).scale;
  157. Rectangle<int> newArea (peer->getComponent().getLocalArea (&component, component.getLocalBounds())
  158. .withPosition (0, 0)
  159. * newScale);
  160. if (scale != newScale || viewportArea != newArea)
  161. {
  162. scale = newScale;
  163. viewportArea = newArea;
  164. if (canTriggerUpdate)
  165. invalidateAll();
  166. }
  167. }
  168. }
  169. void paintComponent()
  170. {
  171. // you mustn't set your own cached image object when attaching a GL context!
  172. jassert (get (component) == this);
  173. updateViewportSize (false);
  174. if (! ensureFrameBufferSize())
  175. return;
  176. RectangleList<int> invalid (viewportArea);
  177. invalid.subtract (validArea);
  178. validArea = viewportArea;
  179. if (! invalid.isEmpty())
  180. {
  181. clearRegionInFrameBuffer (invalid);
  182. {
  183. ScopedPointer<LowLevelGraphicsContext> g (createOpenGLGraphicsContext (context, cachedImageFrameBuffer));
  184. g->clipToRectangleList (invalid);
  185. g->addTransform (AffineTransform::scale ((float) scale));
  186. paintOwner (*g);
  187. JUCE_CHECK_OPENGL_ERROR
  188. }
  189. if (! context.isActive())
  190. context.makeActive();
  191. }
  192. JUCE_CHECK_OPENGL_ERROR
  193. }
  194. void drawComponentBuffer()
  195. {
  196. #if ! JUCE_ANDROID
  197. glEnable (GL_TEXTURE_2D);
  198. clearGLError();
  199. #endif
  200. context.extensions.glActiveTexture (GL_TEXTURE0);
  201. glBindTexture (GL_TEXTURE_2D, cachedImageFrameBuffer.getTextureID());
  202. const Rectangle<int> cacheBounds (cachedImageFrameBuffer.getWidth(), cachedImageFrameBuffer.getHeight());
  203. context.copyTexture (cacheBounds, cacheBounds, cacheBounds.getWidth(), cacheBounds.getHeight(), false);
  204. glBindTexture (GL_TEXTURE_2D, 0);
  205. JUCE_CHECK_OPENGL_ERROR
  206. }
  207. void paintOwner (LowLevelGraphicsContext& llgc)
  208. {
  209. Graphics g (llgc);
  210. #if JUCE_ENABLE_REPAINT_DEBUGGING
  211. g.saveState();
  212. #endif
  213. JUCE_TRY
  214. {
  215. component.paintEntireComponent (g, false);
  216. }
  217. JUCE_CATCH_EXCEPTION
  218. #if JUCE_ENABLE_REPAINT_DEBUGGING
  219. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  220. // clearly when things are being repainted.
  221. g.restoreState();
  222. static Random rng;
  223. g.fillAll (Colour ((uint8) rng.nextInt (255),
  224. (uint8) rng.nextInt (255),
  225. (uint8) rng.nextInt (255),
  226. (uint8) 0x50));
  227. #endif
  228. }
  229. void handleResize()
  230. {
  231. updateViewportSize (true);
  232. #if JUCE_MAC
  233. if (hasInitialised)
  234. {
  235. [nativeContext->view update];
  236. renderFrame();
  237. }
  238. #endif
  239. }
  240. //==============================================================================
  241. void run() override
  242. {
  243. {
  244. // Allow the message thread to finish setting-up the context before using it..
  245. MessageManagerLock mml (this);
  246. if (! mml.lockWasGained())
  247. return;
  248. }
  249. initialiseOnThread();
  250. hasInitialised = true;
  251. while (! threadShouldExit())
  252. {
  253. if (! renderFrame())
  254. wait (5); // failed to render, so avoid a tight fail-loop.
  255. }
  256. shutdownOnThread();
  257. }
  258. void initialiseOnThread()
  259. {
  260. // On android, this can get called twice, so drop any previous state..
  261. associatedObjectNames.clear();
  262. associatedObjects.clear();
  263. cachedImageFrameBuffer.release();
  264. context.makeActive();
  265. nativeContext->initialiseOnRenderThread (context);
  266. glViewport (0, 0, component.getWidth(), component.getHeight());
  267. context.extensions.initialise();
  268. nativeContext->setSwapInterval (1);
  269. #if JUCE_USE_OPENGL_SHADERS && ! JUCE_OPENGL_ES
  270. shadersAvailable = OpenGLShaderProgram::getLanguageVersion() > 0;
  271. #endif
  272. if (context.renderer != nullptr)
  273. context.renderer->newOpenGLContextCreated();
  274. }
  275. void shutdownOnThread()
  276. {
  277. if (context.renderer != nullptr)
  278. context.renderer->openGLContextClosing();
  279. cachedImageFrameBuffer.release();
  280. nativeContext->shutdownOnRenderThread();
  281. associatedObjectNames.clear();
  282. associatedObjects.clear();
  283. }
  284. //==============================================================================
  285. static CachedImage* get (Component& c) noexcept
  286. {
  287. return dynamic_cast<CachedImage*> (c.getCachedComponentImage());
  288. }
  289. //==============================================================================
  290. ScopedPointer<NativeContext> nativeContext;
  291. OpenGLContext& context;
  292. Component& component;
  293. OpenGLFrameBuffer cachedImageFrameBuffer;
  294. RectangleList<int> validArea;
  295. Rectangle<int> viewportArea;
  296. double scale;
  297. StringArray associatedObjectNames;
  298. ReferenceCountedArray<ReferenceCountedObject> associatedObjects;
  299. WaitableEvent canPaintNowFlag, finishedPaintingFlag;
  300. bool shadersAvailable, hasInitialised;
  301. Atomic<int> needsUpdate;
  302. uint32 lastMMLockReleaseTime;
  303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedImage)
  304. };
  305. //==============================================================================
  306. #if JUCE_ANDROID
  307. void OpenGLContext::NativeContext::contextCreatedCallback()
  308. {
  309. isInsideGLCallback = true;
  310. if (CachedImage* const c = CachedImage::get (component))
  311. c->initialiseOnThread();
  312. else
  313. jassertfalse;
  314. isInsideGLCallback = false;
  315. }
  316. void OpenGLContext::NativeContext::renderCallback()
  317. {
  318. isInsideGLCallback = true;
  319. if (CachedImage* const c = CachedImage::get (component))
  320. c->renderFrame();
  321. isInsideGLCallback = false;
  322. }
  323. #endif
  324. //==============================================================================
  325. class OpenGLContext::Attachment : public ComponentMovementWatcher
  326. {
  327. public:
  328. Attachment (OpenGLContext& c, Component& comp)
  329. : ComponentMovementWatcher (&comp), context (c)
  330. {
  331. if (canBeAttached (comp))
  332. attach();
  333. }
  334. ~Attachment()
  335. {
  336. detach();
  337. }
  338. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
  339. {
  340. Component& comp = *getComponent();
  341. if (isAttached (comp) != canBeAttached (comp))
  342. componentVisibilityChanged();
  343. if (comp.getWidth() > 0 && comp.getHeight() > 0
  344. && context.nativeContext != nullptr)
  345. {
  346. if (CachedImage* const c = CachedImage::get (comp))
  347. c->handleResize();
  348. if (ComponentPeer* peer = comp.getTopLevelComponent()->getPeer())
  349. context.nativeContext->updateWindowPosition (peer->getAreaCoveredBy (comp));
  350. }
  351. }
  352. void componentPeerChanged() override
  353. {
  354. detach();
  355. componentVisibilityChanged();
  356. }
  357. void componentVisibilityChanged() override
  358. {
  359. Component& comp = *getComponent();
  360. if (canBeAttached (comp))
  361. {
  362. if (! isAttached (comp))
  363. attach();
  364. }
  365. else
  366. {
  367. detach();
  368. }
  369. }
  370. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  371. void componentBeingDeleted (Component& c) override
  372. {
  373. /* You must call detach() or delete your OpenGLContext to remove it
  374. from a component BEFORE deleting the component that it is using!
  375. */
  376. jassertfalse;
  377. ComponentMovementWatcher::componentBeingDeleted (c);
  378. }
  379. #endif
  380. private:
  381. OpenGLContext& context;
  382. static bool canBeAttached (const Component& comp) noexcept
  383. {
  384. return comp.getWidth() > 0 && comp.getHeight() > 0 && isShowingOrMinimised (comp);
  385. }
  386. static bool isShowingOrMinimised (const Component& c)
  387. {
  388. if (! c.isVisible())
  389. return false;
  390. if (Component* p = c.getParentComponent())
  391. return isShowingOrMinimised (*p);
  392. return c.getPeer() != nullptr;
  393. }
  394. static bool isAttached (const Component& comp) noexcept
  395. {
  396. return comp.getCachedComponentImage() != nullptr;
  397. }
  398. void attach()
  399. {
  400. Component& comp = *getComponent();
  401. CachedImage* const newCachedImage = new CachedImage (context, comp,
  402. context.pixelFormat,
  403. context.contextToShareWith);
  404. comp.setCachedComponentImage (newCachedImage);
  405. newCachedImage->start(); // (must wait until this is attached before starting its thread)
  406. newCachedImage->updateViewportSize (true);
  407. }
  408. void detach()
  409. {
  410. Component& comp = *getComponent();
  411. #if JUCE_MAC
  412. [[(NSView*) comp.getWindowHandle() window] disableScreenUpdatesUntilFlush];
  413. #endif
  414. if (CachedImage* const oldCachedImage = CachedImage::get (comp))
  415. oldCachedImage->stop(); // (must stop this before detaching it from the component)
  416. comp.setCachedComponentImage (nullptr);
  417. context.nativeContext = nullptr;
  418. }
  419. };
  420. //==============================================================================
  421. OpenGLContext::OpenGLContext()
  422. : nativeContext (nullptr), renderer (nullptr), currentRenderScale (1.0),
  423. contextToShareWith (nullptr), renderComponents (true), useMultisampling (false)
  424. {
  425. }
  426. OpenGLContext::~OpenGLContext()
  427. {
  428. detach();
  429. }
  430. void OpenGLContext::setRenderer (OpenGLRenderer* rendererToUse) noexcept
  431. {
  432. // This method must not be called when the context has already been attached!
  433. // Call it before attaching your context, or use detach() first, before calling this!
  434. jassert (nativeContext == nullptr);
  435. renderer = rendererToUse;
  436. }
  437. void OpenGLContext::setComponentPaintingEnabled (bool shouldPaintComponent) noexcept
  438. {
  439. // This method must not be called when the context has already been attached!
  440. // Call it before attaching your context, or use detach() first, before calling this!
  441. jassert (nativeContext == nullptr);
  442. renderComponents = shouldPaintComponent;
  443. }
  444. void OpenGLContext::setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept
  445. {
  446. // This method must not be called when the context has already been attached!
  447. // Call it before attaching your context, or use detach() first, before calling this!
  448. jassert (nativeContext == nullptr);
  449. pixelFormat = preferredPixelFormat;
  450. }
  451. void OpenGLContext::setNativeSharedContext (void* nativeContextToShareWith) noexcept
  452. {
  453. // This method must not be called when the context has already been attached!
  454. // Call it before attaching your context, or use detach() first, before calling this!
  455. jassert (nativeContext == nullptr);
  456. contextToShareWith = nativeContextToShareWith;
  457. }
  458. void OpenGLContext::setMultisamplingEnabled (bool b) noexcept
  459. {
  460. // This method must not be called when the context has already been attached!
  461. // Call it before attaching your context, or use detach() first, before calling this!
  462. jassert (nativeContext == nullptr);
  463. useMultisampling = b;
  464. }
  465. void OpenGLContext::attachTo (Component& component)
  466. {
  467. component.repaint();
  468. if (getTargetComponent() != &component)
  469. {
  470. detach();
  471. attachment = new Attachment (*this, component);
  472. }
  473. }
  474. void OpenGLContext::detach()
  475. {
  476. attachment = nullptr;
  477. nativeContext = nullptr;
  478. }
  479. bool OpenGLContext::isAttached() const noexcept
  480. {
  481. return nativeContext != nullptr;
  482. }
  483. Component* OpenGLContext::getTargetComponent() const noexcept
  484. {
  485. return attachment != nullptr ? attachment->getComponent() : nullptr;
  486. }
  487. static ThreadLocalValue<OpenGLContext*> currentThreadActiveContext;
  488. OpenGLContext* OpenGLContext::getCurrentContext()
  489. {
  490. return currentThreadActiveContext.get();
  491. }
  492. bool OpenGLContext::makeActive() const noexcept
  493. {
  494. OpenGLContext*& current = currentThreadActiveContext.get();
  495. if (nativeContext != nullptr && nativeContext->makeActive())
  496. {
  497. current = const_cast <OpenGLContext*> (this);
  498. return true;
  499. }
  500. current = nullptr;
  501. return false;
  502. }
  503. bool OpenGLContext::isActive() const noexcept
  504. {
  505. return nativeContext != nullptr && nativeContext->isActive();
  506. }
  507. void OpenGLContext::deactivateCurrentContext()
  508. {
  509. NativeContext::deactivateCurrentContext();
  510. currentThreadActiveContext.get() = nullptr;
  511. }
  512. void OpenGLContext::triggerRepaint()
  513. {
  514. if (CachedImage* const cachedImage = getCachedImage())
  515. cachedImage->triggerRepaint();
  516. }
  517. void OpenGLContext::swapBuffers()
  518. {
  519. if (nativeContext != nullptr)
  520. nativeContext->swapBuffers();
  521. }
  522. unsigned int OpenGLContext::getFrameBufferID() const noexcept
  523. {
  524. return nativeContext != nullptr ? nativeContext->getFrameBufferID() : 0;
  525. }
  526. bool OpenGLContext::setSwapInterval (int numFramesPerSwap)
  527. {
  528. return nativeContext != nullptr && nativeContext->setSwapInterval (numFramesPerSwap);
  529. }
  530. int OpenGLContext::getSwapInterval() const
  531. {
  532. return nativeContext != nullptr ? nativeContext->getSwapInterval() : 0;
  533. }
  534. void* OpenGLContext::getRawContext() const noexcept
  535. {
  536. return nativeContext != nullptr ? nativeContext->getRawContext() : nullptr;
  537. }
  538. OpenGLContext::CachedImage* OpenGLContext::getCachedImage() const noexcept
  539. {
  540. if (Component* const comp = getTargetComponent())
  541. return CachedImage::get (*comp);
  542. return nullptr;
  543. }
  544. bool OpenGLContext::areShadersAvailable() const
  545. {
  546. CachedImage* const c = getCachedImage();
  547. return c != nullptr && c->shadersAvailable;
  548. }
  549. ReferenceCountedObject* OpenGLContext::getAssociatedObject (const char* name) const
  550. {
  551. jassert (name != nullptr);
  552. CachedImage* const c = getCachedImage();
  553. // This method must only be called from an openGL rendering callback.
  554. jassert (c != nullptr && nativeContext != nullptr);
  555. jassert (getCurrentContext() != nullptr);
  556. const int index = c->associatedObjectNames.indexOf (name);
  557. return index >= 0 ? c->associatedObjects.getUnchecked (index) : nullptr;
  558. }
  559. void OpenGLContext::setAssociatedObject (const char* name, ReferenceCountedObject* newObject)
  560. {
  561. jassert (name != nullptr);
  562. CachedImage* const c = getCachedImage();
  563. // This method must only be called from an openGL rendering callback.
  564. jassert (c != nullptr && nativeContext != nullptr);
  565. jassert (getCurrentContext() != nullptr);
  566. const int index = c->associatedObjectNames.indexOf (name);
  567. if (index >= 0)
  568. {
  569. c->associatedObjects.set (index, newObject);
  570. }
  571. else
  572. {
  573. c->associatedObjectNames.add (name);
  574. c->associatedObjects.add (newObject);
  575. }
  576. }
  577. void OpenGLContext::copyTexture (const Rectangle<int>& targetClipArea,
  578. const Rectangle<int>& anchorPosAndTextureSize,
  579. const int contextWidth, const int contextHeight,
  580. bool flippedVertically)
  581. {
  582. if (contextWidth <= 0 || contextHeight <= 0)
  583. return;
  584. JUCE_CHECK_OPENGL_ERROR
  585. glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  586. glEnable (GL_BLEND);
  587. #if JUCE_USE_OPENGL_SHADERS
  588. if (areShadersAvailable())
  589. {
  590. struct OverlayShaderProgram : public ReferenceCountedObject
  591. {
  592. OverlayShaderProgram (OpenGLContext& context)
  593. : program (context), builder (program), params (program)
  594. {}
  595. static const OverlayShaderProgram& select (OpenGLContext& context)
  596. {
  597. static const char programValueID[] = "juceGLComponentOverlayShader";
  598. OverlayShaderProgram* program = static_cast <OverlayShaderProgram*> (context.getAssociatedObject (programValueID));
  599. if (program == nullptr)
  600. {
  601. program = new OverlayShaderProgram (context);
  602. context.setAssociatedObject (programValueID, program);
  603. }
  604. program->program.use();
  605. return *program;
  606. }
  607. struct ProgramBuilder
  608. {
  609. ProgramBuilder (OpenGLShaderProgram& prog)
  610. {
  611. prog.addShader ("attribute " JUCE_HIGHP " vec2 position;"
  612. "uniform " JUCE_HIGHP " vec2 screenSize;"
  613. "varying " JUCE_HIGHP " vec2 pixelPos;"
  614. "void main()"
  615. "{"
  616. "pixelPos = position;"
  617. JUCE_HIGHP " vec2 scaled = position / (0.5 * screenSize.xy);"
  618. "gl_Position = vec4 (scaled.x - 1.0, 1.0 - scaled.y, 0, 1.0);"
  619. "}",
  620. GL_VERTEX_SHADER);
  621. prog.addShader ("uniform sampler2D imageTexture;"
  622. "uniform " JUCE_HIGHP " float textureBounds[4];"
  623. "uniform " JUCE_HIGHP " vec2 vOffsetAndScale;"
  624. "varying " JUCE_HIGHP " vec2 pixelPos;"
  625. "void main()"
  626. "{"
  627. JUCE_HIGHP " vec2 texturePos = (pixelPos - vec2 (textureBounds[0], textureBounds[1]))"
  628. "/ vec2 (textureBounds[2], textureBounds[3]);"
  629. "gl_FragColor = texture2D (imageTexture, vec2 (texturePos.x, vOffsetAndScale.x + vOffsetAndScale.y * texturePos.y));"
  630. "}",
  631. GL_FRAGMENT_SHADER);
  632. prog.link();
  633. }
  634. };
  635. struct Params
  636. {
  637. Params (OpenGLShaderProgram& prog)
  638. : positionAttribute (prog, "position"),
  639. screenSize (prog, "screenSize"),
  640. imageTexture (prog, "imageTexture"),
  641. textureBounds (prog, "textureBounds"),
  642. vOffsetAndScale (prog, "vOffsetAndScale")
  643. {}
  644. void set (const float targetWidth, const float targetHeight, const Rectangle<float>& bounds, bool flipVertically) const
  645. {
  646. const GLfloat m[] = { bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight() };
  647. textureBounds.set (m, 4);
  648. imageTexture.set (0);
  649. screenSize.set (targetWidth, targetHeight);
  650. vOffsetAndScale.set (flipVertically ? 0.0f : 1.0f,
  651. flipVertically ? 1.0f : -1.0f);
  652. }
  653. OpenGLShaderProgram::Attribute positionAttribute;
  654. OpenGLShaderProgram::Uniform screenSize, imageTexture, textureBounds, vOffsetAndScale;
  655. };
  656. OpenGLShaderProgram program;
  657. ProgramBuilder builder;
  658. Params params;
  659. };
  660. const GLshort left = (GLshort) targetClipArea.getX();
  661. const GLshort top = (GLshort) targetClipArea.getY();
  662. const GLshort right = (GLshort) targetClipArea.getRight();
  663. const GLshort bottom = (GLshort) targetClipArea.getBottom();
  664. const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top };
  665. const OverlayShaderProgram& program = OverlayShaderProgram::select (*this);
  666. program.params.set ((float) contextWidth, (float) contextHeight, anchorPosAndTextureSize.toFloat(), flippedVertically);
  667. const GLuint index = (GLuint) program.params.positionAttribute.attributeID;
  668. extensions.glVertexAttribPointer (index, 2, GL_SHORT, GL_FALSE, 4, vertices);
  669. extensions.glEnableVertexAttribArray (index);
  670. JUCE_CHECK_OPENGL_ERROR
  671. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  672. extensions.glUseProgram (0);
  673. extensions.glDisableVertexAttribArray (index);
  674. }
  675. #if JUCE_USE_OPENGL_FIXED_FUNCTION
  676. else
  677. #endif
  678. #endif
  679. #if JUCE_USE_OPENGL_FIXED_FUNCTION
  680. {
  681. glEnable (GL_SCISSOR_TEST);
  682. glScissor (targetClipArea.getX(), contextHeight - targetClipArea.getBottom(),
  683. targetClipArea.getWidth(), targetClipArea.getHeight());
  684. JUCE_CHECK_OPENGL_ERROR
  685. glColor4f (1.0f, 1.0f, 1.0f, 1.0f);
  686. glDisableClientState (GL_COLOR_ARRAY);
  687. glDisableClientState (GL_NORMAL_ARRAY);
  688. glEnableClientState (GL_VERTEX_ARRAY);
  689. glEnableClientState (GL_TEXTURE_COORD_ARRAY);
  690. OpenGLHelpers::prepareFor2D (contextWidth, contextHeight);
  691. JUCE_CHECK_OPENGL_ERROR
  692. const GLfloat textureCoords[] = { 0, 0, 1.0f, 0, 0, 1.0f, 1.0f, 1.0f };
  693. glTexCoordPointer (2, GL_FLOAT, 0, textureCoords);
  694. const GLshort left = (GLshort) anchorPosAndTextureSize.getX();
  695. const GLshort right = (GLshort) anchorPosAndTextureSize.getRight();
  696. const GLshort top = (GLshort) (contextHeight - anchorPosAndTextureSize.getY());
  697. const GLshort bottom = (GLshort) (contextHeight - anchorPosAndTextureSize.getBottom());
  698. const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top };
  699. glVertexPointer (2, GL_SHORT, 0, vertices);
  700. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  701. glDisable (GL_SCISSOR_TEST);
  702. }
  703. #endif
  704. JUCE_CHECK_OPENGL_ERROR
  705. }