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.

947 lines
29KB

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