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.

1266 lines
38KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. #if JUCE_IOS
  22. struct AppInactivityCallback // NB: this is a duplicate of an internal declaration in juce_core
  23. {
  24. virtual ~AppInactivityCallback() {}
  25. virtual void appBecomingInactive() = 0;
  26. };
  27. extern Array<AppInactivityCallback*> appBecomingInactiveCallbacks;
  28. // On iOS, all GL calls will crash when the app is running in the background, so
  29. // this prevents them from happening (which some messy locking behaviour)
  30. struct iOSBackgroundProcessCheck : public AppInactivityCallback
  31. {
  32. iOSBackgroundProcessCheck() { isBackgroundProcess(); appBecomingInactiveCallbacks.add (this); }
  33. ~iOSBackgroundProcessCheck() override { appBecomingInactiveCallbacks.removeAllInstancesOf (this); }
  34. bool isBackgroundProcess()
  35. {
  36. const bool b = Process::isForegroundProcess();
  37. isForeground.set (b ? 1 : 0);
  38. return ! b;
  39. }
  40. void appBecomingInactive() override
  41. {
  42. int counter = 2000;
  43. while (--counter > 0 && isForeground.get() != 0)
  44. Thread::sleep (1);
  45. }
  46. private:
  47. Atomic<int> isForeground;
  48. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSBackgroundProcessCheck)
  49. };
  50. #endif
  51. //==============================================================================
  52. class OpenGLContext::CachedImage : public CachedComponentImage,
  53. private ThreadPoolJob
  54. {
  55. public:
  56. CachedImage (OpenGLContext& c, Component& comp,
  57. const OpenGLPixelFormat& pixFormat, void* contextToShare)
  58. : ThreadPoolJob ("OpenGL Rendering"),
  59. context (c), component (comp)
  60. {
  61. nativeContext.reset (new NativeContext (component, pixFormat, contextToShare,
  62. c.useMultisampling, c.versionRequired));
  63. if (nativeContext->createdOk())
  64. context.nativeContext = nativeContext.get();
  65. else
  66. nativeContext.reset();
  67. }
  68. ~CachedImage() override
  69. {
  70. stop();
  71. }
  72. //==============================================================================
  73. void start()
  74. {
  75. if (nativeContext != nullptr)
  76. {
  77. renderThread.reset (new ThreadPool (1));
  78. resume();
  79. }
  80. }
  81. void stop()
  82. {
  83. if (renderThread != nullptr)
  84. {
  85. // make sure everything has finished executing
  86. destroying.set (1);
  87. if (workQueue.size() > 0)
  88. {
  89. if (! renderThread->contains (this))
  90. resume();
  91. while (workQueue.size() != 0)
  92. Thread::sleep (20);
  93. }
  94. pause();
  95. renderThread.reset();
  96. }
  97. hasInitialised = false;
  98. }
  99. //==============================================================================
  100. void pause()
  101. {
  102. signalJobShouldExit();
  103. messageManagerLock.abort();
  104. if (renderThread != nullptr)
  105. {
  106. repaintEvent.signal();
  107. renderThread->removeJob (this, true, -1);
  108. }
  109. }
  110. void resume()
  111. {
  112. if (renderThread != nullptr)
  113. renderThread->addJob (this, false);
  114. }
  115. //==============================================================================
  116. void paint (Graphics&) override
  117. {
  118. updateViewportSize (false);
  119. }
  120. bool invalidateAll() override
  121. {
  122. validArea.clear();
  123. triggerRepaint();
  124. return false;
  125. }
  126. bool invalidate (const Rectangle<int>& area) override
  127. {
  128. validArea.subtract (area.toFloat().transformedBy (transform).getSmallestIntegerContainer());
  129. triggerRepaint();
  130. return false;
  131. }
  132. void releaseResources() override
  133. {
  134. stop();
  135. }
  136. void triggerRepaint()
  137. {
  138. needsUpdate = 1;
  139. repaintEvent.signal();
  140. }
  141. //==============================================================================
  142. bool ensureFrameBufferSize()
  143. {
  144. auto fbW = cachedImageFrameBuffer.getWidth();
  145. auto fbH = cachedImageFrameBuffer.getHeight();
  146. if (fbW != viewportArea.getWidth() || fbH != viewportArea.getHeight() || ! cachedImageFrameBuffer.isValid())
  147. {
  148. if (! cachedImageFrameBuffer.initialise (context, viewportArea.getWidth(), viewportArea.getHeight()))
  149. return false;
  150. validArea.clear();
  151. JUCE_CHECK_OPENGL_ERROR
  152. }
  153. return true;
  154. }
  155. void clearRegionInFrameBuffer (const RectangleList<int>& list)
  156. {
  157. glClearColor (0, 0, 0, 0);
  158. glEnable (GL_SCISSOR_TEST);
  159. auto previousFrameBufferTarget = OpenGLFrameBuffer::getCurrentFrameBufferTarget();
  160. cachedImageFrameBuffer.makeCurrentRenderingTarget();
  161. auto imageH = cachedImageFrameBuffer.getHeight();
  162. for (auto& r : list)
  163. {
  164. glScissor (r.getX(), imageH - r.getBottom(), r.getWidth(), r.getHeight());
  165. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  166. }
  167. glDisable (GL_SCISSOR_TEST);
  168. context.extensions.glBindFramebuffer (GL_FRAMEBUFFER, previousFrameBufferTarget);
  169. JUCE_CHECK_OPENGL_ERROR
  170. }
  171. bool renderFrame()
  172. {
  173. MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock, false);
  174. const bool isUpdating = needsUpdate.compareAndSetBool (0, 1);
  175. if (context.renderComponents && isUpdating)
  176. {
  177. // This avoids hogging the message thread when doing intensive rendering.
  178. if (lastMMLockReleaseTime + 1 >= Time::getMillisecondCounter())
  179. Thread::sleep (2);
  180. while (! shouldExit())
  181. {
  182. doWorkWhileWaitingForLock (false);
  183. if (mmLock.retryLock())
  184. break;
  185. }
  186. if (shouldExit())
  187. return false;
  188. }
  189. if (! context.makeActive())
  190. return false;
  191. NativeContext::Locker locker (*nativeContext);
  192. JUCE_CHECK_OPENGL_ERROR
  193. doWorkWhileWaitingForLock (true);
  194. if (context.renderer != nullptr)
  195. {
  196. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  197. context.currentRenderScale = scale;
  198. context.renderer->renderOpenGL();
  199. clearGLError();
  200. bindVertexArray();
  201. }
  202. if (context.renderComponents)
  203. {
  204. if (isUpdating)
  205. {
  206. paintComponent();
  207. if (! hasInitialised)
  208. return false;
  209. messageManagerLock.exit();
  210. lastMMLockReleaseTime = Time::getMillisecondCounter();
  211. }
  212. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  213. drawComponentBuffer();
  214. }
  215. context.swapBuffers();
  216. OpenGLContext::deactivateCurrentContext();
  217. return true;
  218. }
  219. void updateViewportSize (bool canTriggerUpdate)
  220. {
  221. if (auto* peer = component.getPeer())
  222. {
  223. #if JUCE_WINDOWS
  224. auto newScale = nativeContext->getWindowScaleFactor (component.getTopLevelComponent()->getScreenBounds());
  225. #else
  226. auto newScale = Desktop::getInstance().getDisplays().findDisplayForRect (component.getTopLevelComponent()->getScreenBounds()).scale;
  227. #endif
  228. auto localBounds = component.getLocalBounds();
  229. auto newArea = peer->getComponent().getLocalArea (&component, localBounds).withZeroOrigin() * newScale;
  230. if (scale != newScale || viewportArea != newArea)
  231. {
  232. scale = newScale;
  233. viewportArea = newArea;
  234. transform = AffineTransform::scale ((float) newArea.getWidth() / (float) localBounds.getWidth(),
  235. (float) newArea.getHeight() / (float) localBounds.getHeight());
  236. if (canTriggerUpdate)
  237. invalidateAll();
  238. }
  239. }
  240. }
  241. void bindVertexArray() noexcept
  242. {
  243. #if JUCE_OPENGL3
  244. if (vertexArrayObject != 0)
  245. context.extensions.glBindVertexArray (vertexArrayObject);
  246. #endif
  247. }
  248. void checkViewportBounds()
  249. {
  250. auto screenBounds = component.getTopLevelComponent()->getScreenBounds();
  251. if (lastScreenBounds != screenBounds)
  252. updateViewportSize (true);
  253. }
  254. void paintComponent()
  255. {
  256. // you mustn't set your own cached image object when attaching a GL context!
  257. jassert (get (component) == this);
  258. if (! ensureFrameBufferSize())
  259. return;
  260. RectangleList<int> invalid (viewportArea);
  261. invalid.subtract (validArea);
  262. validArea = viewportArea;
  263. if (! invalid.isEmpty())
  264. {
  265. clearRegionInFrameBuffer (invalid);
  266. {
  267. std::unique_ptr<LowLevelGraphicsContext> g (createOpenGLGraphicsContext (context, cachedImageFrameBuffer));
  268. g->clipToRectangleList (invalid);
  269. g->addTransform (transform);
  270. paintOwner (*g);
  271. JUCE_CHECK_OPENGL_ERROR
  272. }
  273. if (! context.isActive())
  274. context.makeActive();
  275. }
  276. JUCE_CHECK_OPENGL_ERROR
  277. }
  278. void drawComponentBuffer()
  279. {
  280. #if ! JUCE_ANDROID
  281. glEnable (GL_TEXTURE_2D);
  282. clearGLError();
  283. #endif
  284. #if JUCE_WINDOWS
  285. // some stupidly old drivers are missing this function, so try to at least avoid a crash here,
  286. // but if you hit this assertion you may want to have your own version check before using the
  287. // component rendering stuff on such old drivers.
  288. jassert (context.extensions.glActiveTexture != nullptr);
  289. if (context.extensions.glActiveTexture != nullptr)
  290. #endif
  291. context.extensions.glActiveTexture (GL_TEXTURE0);
  292. glBindTexture (GL_TEXTURE_2D, cachedImageFrameBuffer.getTextureID());
  293. bindVertexArray();
  294. const Rectangle<int> cacheBounds (cachedImageFrameBuffer.getWidth(), cachedImageFrameBuffer.getHeight());
  295. context.copyTexture (cacheBounds, cacheBounds, cacheBounds.getWidth(), cacheBounds.getHeight(), false);
  296. glBindTexture (GL_TEXTURE_2D, 0);
  297. JUCE_CHECK_OPENGL_ERROR
  298. }
  299. void paintOwner (LowLevelGraphicsContext& llgc)
  300. {
  301. Graphics g (llgc);
  302. #if JUCE_ENABLE_REPAINT_DEBUGGING
  303. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  304. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  305. #endif
  306. {
  307. g.saveState();
  308. }
  309. #endif
  310. JUCE_TRY
  311. {
  312. component.paintEntireComponent (g, false);
  313. }
  314. JUCE_CATCH_EXCEPTION
  315. #if JUCE_ENABLE_REPAINT_DEBUGGING
  316. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  317. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  318. #endif
  319. {
  320. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  321. // clearly when things are being repainted.
  322. g.restoreState();
  323. static Random rng;
  324. g.fillAll (Colour ((uint8) rng.nextInt (255),
  325. (uint8) rng.nextInt (255),
  326. (uint8) rng.nextInt (255),
  327. (uint8) 0x50));
  328. }
  329. #endif
  330. }
  331. void handleResize()
  332. {
  333. updateViewportSize (true);
  334. #if JUCE_MAC
  335. if (hasInitialised)
  336. {
  337. [nativeContext->view update];
  338. renderFrame();
  339. }
  340. #endif
  341. }
  342. //==============================================================================
  343. JobStatus runJob() override
  344. {
  345. {
  346. // Allow the message thread to finish setting-up the context before using it..
  347. MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock, false);
  348. do
  349. {
  350. if (shouldExit())
  351. return ThreadPoolJob::jobHasFinished;
  352. } while (! mmLock.retryLock());
  353. }
  354. if (! initialiseOnThread())
  355. {
  356. hasInitialised = false;
  357. return ThreadPoolJob::jobHasFinished;
  358. }
  359. hasInitialised = true;
  360. while (! shouldExit())
  361. {
  362. #if JUCE_IOS
  363. if (backgroundProcessCheck.isBackgroundProcess())
  364. {
  365. repaintEvent.wait (300);
  366. continue;
  367. }
  368. #endif
  369. if (shouldExit())
  370. break;
  371. if (! renderFrame())
  372. repaintEvent.wait (5); // failed to render, so avoid a tight fail-loop.
  373. else if (! context.continuousRepaint && ! shouldExit())
  374. repaintEvent.wait (-1);
  375. }
  376. hasInitialised = false;
  377. context.makeActive();
  378. shutdownOnThread();
  379. OpenGLContext::deactivateCurrentContext();
  380. return ThreadPoolJob::jobHasFinished;
  381. }
  382. bool initialiseOnThread()
  383. {
  384. // On android, this can get called twice, so drop any previous state..
  385. associatedObjectNames.clear();
  386. associatedObjects.clear();
  387. cachedImageFrameBuffer.release();
  388. context.makeActive();
  389. if (! nativeContext->initialiseOnRenderThread (context))
  390. return false;
  391. #if JUCE_ANDROID
  392. // On android the context may be created in initialiseOnRenderThread
  393. // and we therefore need to call makeActive again
  394. context.makeActive();
  395. #endif
  396. context.extensions.initialise();
  397. #if JUCE_OPENGL3
  398. if (OpenGLShaderProgram::getLanguageVersion() > 1.2)
  399. {
  400. context.extensions.glGenVertexArrays (1, &vertexArrayObject);
  401. bindVertexArray();
  402. }
  403. #endif
  404. glViewport (0, 0, component.getWidth(), component.getHeight());
  405. nativeContext->setSwapInterval (1);
  406. #if ! JUCE_OPENGL_ES
  407. JUCE_CHECK_OPENGL_ERROR
  408. shadersAvailable = OpenGLShaderProgram::getLanguageVersion() > 0;
  409. clearGLError();
  410. #endif
  411. if (context.renderer != nullptr)
  412. context.renderer->newOpenGLContextCreated();
  413. return true;
  414. }
  415. void shutdownOnThread()
  416. {
  417. if (context.renderer != nullptr)
  418. context.renderer->openGLContextClosing();
  419. #if JUCE_OPENGL3
  420. if (vertexArrayObject != 0)
  421. context.extensions.glDeleteVertexArrays (1, &vertexArrayObject);
  422. #endif
  423. associatedObjectNames.clear();
  424. associatedObjects.clear();
  425. cachedImageFrameBuffer.release();
  426. nativeContext->shutdownOnRenderThread();
  427. }
  428. //==============================================================================
  429. struct BlockingWorker : public OpenGLContext::AsyncWorker
  430. {
  431. BlockingWorker (OpenGLContext::AsyncWorker::Ptr && workerToUse)
  432. : originalWorker (std::move (workerToUse))
  433. {}
  434. void operator() (OpenGLContext& calleeContext)
  435. {
  436. if (originalWorker != nullptr)
  437. (*originalWorker) (calleeContext);
  438. finishedSignal.signal();
  439. }
  440. void block() noexcept { finishedSignal.wait(); }
  441. OpenGLContext::AsyncWorker::Ptr originalWorker;
  442. WaitableEvent finishedSignal;
  443. };
  444. bool doWorkWhileWaitingForLock (bool contextIsAlreadyActive)
  445. {
  446. bool contextActivated = false;
  447. for (OpenGLContext::AsyncWorker::Ptr work = workQueue.removeAndReturn (0);
  448. work != nullptr && (! shouldExit()); work = workQueue.removeAndReturn (0))
  449. {
  450. if ((! contextActivated) && (! contextIsAlreadyActive))
  451. {
  452. if (! context.makeActive())
  453. break;
  454. contextActivated = true;
  455. }
  456. NativeContext::Locker locker (*nativeContext);
  457. (*work) (context);
  458. clearGLError();
  459. }
  460. if (contextActivated)
  461. OpenGLContext::deactivateCurrentContext();
  462. return shouldExit();
  463. }
  464. void execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock, bool calledFromDestructor = false)
  465. {
  466. if (calledFromDestructor || destroying.get() == 0)
  467. {
  468. if (shouldBlock)
  469. {
  470. auto blocker = new BlockingWorker (std::move (workerToUse));
  471. OpenGLContext::AsyncWorker::Ptr worker (*blocker);
  472. workQueue.add (worker);
  473. messageManagerLock.abort();
  474. context.triggerRepaint();
  475. blocker->block();
  476. }
  477. else
  478. {
  479. workQueue.add (std::move (workerToUse));
  480. messageManagerLock.abort();
  481. context.triggerRepaint();
  482. }
  483. }
  484. else
  485. {
  486. jassertfalse; // you called execute AFTER you detached your openglcontext
  487. }
  488. }
  489. //==============================================================================
  490. static CachedImage* get (Component& c) noexcept
  491. {
  492. return dynamic_cast<CachedImage*> (c.getCachedComponentImage());
  493. }
  494. //==============================================================================
  495. friend class NativeContext;
  496. std::unique_ptr<NativeContext> nativeContext;
  497. OpenGLContext& context;
  498. Component& component;
  499. OpenGLFrameBuffer cachedImageFrameBuffer;
  500. RectangleList<int> validArea;
  501. Rectangle<int> viewportArea, lastScreenBounds;
  502. double scale = 1.0;
  503. AffineTransform transform;
  504. #if JUCE_OPENGL3
  505. GLuint vertexArrayObject = 0;
  506. #endif
  507. StringArray associatedObjectNames;
  508. ReferenceCountedArray<ReferenceCountedObject> associatedObjects;
  509. WaitableEvent canPaintNowFlag, finishedPaintingFlag, repaintEvent;
  510. #if JUCE_OPENGL_ES
  511. bool shadersAvailable = true;
  512. #else
  513. bool shadersAvailable = false;
  514. #endif
  515. bool hasInitialised = false;
  516. Atomic<int> needsUpdate { 1 }, destroying;
  517. uint32 lastMMLockReleaseTime = 0;
  518. std::unique_ptr<ThreadPool> renderThread;
  519. ReferenceCountedArray<OpenGLContext::AsyncWorker, CriticalSection> workQueue;
  520. MessageManager::Lock messageManagerLock;
  521. #if JUCE_IOS
  522. iOSBackgroundProcessCheck backgroundProcessCheck;
  523. #endif
  524. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedImage)
  525. };
  526. //==============================================================================
  527. class OpenGLContext::Attachment : public ComponentMovementWatcher,
  528. private Timer
  529. {
  530. public:
  531. Attachment (OpenGLContext& c, Component& comp)
  532. : ComponentMovementWatcher (&comp), context (c)
  533. {
  534. if (canBeAttached (comp))
  535. attach();
  536. }
  537. ~Attachment() override
  538. {
  539. detach();
  540. }
  541. void detach()
  542. {
  543. auto& comp = *getComponent();
  544. stop();
  545. comp.setCachedComponentImage (nullptr);
  546. context.nativeContext = nullptr;
  547. }
  548. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
  549. {
  550. auto& comp = *getComponent();
  551. if (isAttached (comp) != canBeAttached (comp))
  552. componentVisibilityChanged();
  553. if (comp.getWidth() > 0 && comp.getHeight() > 0
  554. && context.nativeContext != nullptr)
  555. {
  556. if (auto* c = CachedImage::get (comp))
  557. c->handleResize();
  558. if (auto* peer = comp.getTopLevelComponent()->getPeer())
  559. context.nativeContext->updateWindowPosition (peer->getAreaCoveredBy (comp));
  560. }
  561. }
  562. using ComponentMovementWatcher::componentMovedOrResized;
  563. void componentPeerChanged() override
  564. {
  565. detach();
  566. componentVisibilityChanged();
  567. }
  568. void componentVisibilityChanged() override
  569. {
  570. auto& comp = *getComponent();
  571. if (canBeAttached (comp))
  572. {
  573. if (isAttached (comp))
  574. comp.repaint(); // (needed when windows are un-minimised)
  575. else
  576. attach();
  577. }
  578. else
  579. {
  580. detach();
  581. }
  582. }
  583. using ComponentMovementWatcher::componentVisibilityChanged;
  584. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  585. void componentBeingDeleted (Component& c) override
  586. {
  587. /* You must call detach() or delete your OpenGLContext to remove it
  588. from a component BEFORE deleting the component that it is using!
  589. */
  590. jassertfalse;
  591. ComponentMovementWatcher::componentBeingDeleted (c);
  592. }
  593. #endif
  594. void update()
  595. {
  596. auto& comp = *getComponent();
  597. if (canBeAttached (comp))
  598. start();
  599. else
  600. stop();
  601. }
  602. private:
  603. OpenGLContext& context;
  604. bool canBeAttached (const Component& comp) noexcept
  605. {
  606. return (! context.overrideCanAttach) && comp.getWidth() > 0 && comp.getHeight() > 0 && isShowingOrMinimised (comp);
  607. }
  608. static bool isShowingOrMinimised (const Component& c)
  609. {
  610. if (! c.isVisible())
  611. return false;
  612. if (auto* p = c.getParentComponent())
  613. return isShowingOrMinimised (*p);
  614. return c.getPeer() != nullptr;
  615. }
  616. static bool isAttached (const Component& comp) noexcept
  617. {
  618. return comp.getCachedComponentImage() != nullptr;
  619. }
  620. void attach()
  621. {
  622. auto& comp = *getComponent();
  623. auto* newCachedImage = new CachedImage (context, comp,
  624. context.openGLPixelFormat,
  625. context.contextToShareWith);
  626. comp.setCachedComponentImage (newCachedImage);
  627. start();
  628. }
  629. void stop()
  630. {
  631. stopTimer();
  632. auto& comp = *getComponent();
  633. #if JUCE_MAC
  634. [[(NSView*) comp.getWindowHandle() window] disableScreenUpdatesUntilFlush];
  635. #endif
  636. if (auto* oldCachedImage = CachedImage::get (comp))
  637. oldCachedImage->stop(); // (must stop this before detaching it from the component)
  638. }
  639. void start()
  640. {
  641. auto& comp = *getComponent();
  642. if (auto* cachedImage = CachedImage::get (comp))
  643. {
  644. cachedImage->start(); // (must wait until this is attached before starting its thread)
  645. cachedImage->updateViewportSize (true);
  646. startTimer (400);
  647. }
  648. }
  649. void timerCallback() override
  650. {
  651. if (auto* cachedImage = CachedImage::get (*getComponent()))
  652. cachedImage->checkViewportBounds();
  653. }
  654. };
  655. //==============================================================================
  656. OpenGLContext::OpenGLContext()
  657. {
  658. }
  659. OpenGLContext::~OpenGLContext()
  660. {
  661. detach();
  662. }
  663. void OpenGLContext::setRenderer (OpenGLRenderer* rendererToUse) noexcept
  664. {
  665. // This method must not be called when the context has already been attached!
  666. // Call it before attaching your context, or use detach() first, before calling this!
  667. jassert (nativeContext == nullptr);
  668. renderer = rendererToUse;
  669. }
  670. void OpenGLContext::setComponentPaintingEnabled (bool shouldPaintComponent) noexcept
  671. {
  672. // This method must not be called when the context has already been attached!
  673. // Call it before attaching your context, or use detach() first, before calling this!
  674. jassert (nativeContext == nullptr);
  675. renderComponents = shouldPaintComponent;
  676. }
  677. void OpenGLContext::setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept
  678. {
  679. continuousRepaint = shouldContinuouslyRepaint;
  680. triggerRepaint();
  681. }
  682. void OpenGLContext::setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept
  683. {
  684. // This method must not be called when the context has already been attached!
  685. // Call it before attaching your context, or use detach() first, before calling this!
  686. jassert (nativeContext == nullptr);
  687. openGLPixelFormat = preferredPixelFormat;
  688. }
  689. void OpenGLContext::setTextureMagnificationFilter (OpenGLContext::TextureMagnificationFilter magFilterMode) noexcept
  690. {
  691. texMagFilter = magFilterMode;
  692. }
  693. void OpenGLContext::setNativeSharedContext (void* nativeContextToShareWith) noexcept
  694. {
  695. // This method must not be called when the context has already been attached!
  696. // Call it before attaching your context, or use detach() first, before calling this!
  697. jassert (nativeContext == nullptr);
  698. contextToShareWith = nativeContextToShareWith;
  699. }
  700. void OpenGLContext::setMultisamplingEnabled (bool b) noexcept
  701. {
  702. // This method must not be called when the context has already been attached!
  703. // Call it before attaching your context, or use detach() first, before calling this!
  704. jassert (nativeContext == nullptr);
  705. useMultisampling = b;
  706. }
  707. void OpenGLContext::setOpenGLVersionRequired (OpenGLVersion v) noexcept
  708. {
  709. versionRequired = v;
  710. }
  711. void OpenGLContext::attachTo (Component& component)
  712. {
  713. component.repaint();
  714. if (getTargetComponent() != &component)
  715. {
  716. detach();
  717. attachment.reset (new Attachment (*this, component));
  718. }
  719. }
  720. void OpenGLContext::detach()
  721. {
  722. if (auto* a = attachment.get())
  723. {
  724. a->detach(); // must detach before nulling our pointer
  725. attachment.reset();
  726. }
  727. nativeContext = nullptr;
  728. }
  729. bool OpenGLContext::isAttached() const noexcept
  730. {
  731. return nativeContext != nullptr;
  732. }
  733. Component* OpenGLContext::getTargetComponent() const noexcept
  734. {
  735. return attachment != nullptr ? attachment->getComponent() : nullptr;
  736. }
  737. OpenGLContext* OpenGLContext::getContextAttachedTo (Component& c) noexcept
  738. {
  739. if (auto* ci = CachedImage::get (c))
  740. return &(ci->context);
  741. return nullptr;
  742. }
  743. static ThreadLocalValue<OpenGLContext*> currentThreadActiveContext;
  744. OpenGLContext* OpenGLContext::getCurrentContext()
  745. {
  746. return currentThreadActiveContext.get();
  747. }
  748. bool OpenGLContext::makeActive() const noexcept
  749. {
  750. auto& current = currentThreadActiveContext.get();
  751. if (nativeContext != nullptr && nativeContext->makeActive())
  752. {
  753. current = const_cast<OpenGLContext*> (this);
  754. return true;
  755. }
  756. current = nullptr;
  757. return false;
  758. }
  759. bool OpenGLContext::isActive() const noexcept
  760. {
  761. return nativeContext != nullptr && nativeContext->isActive();
  762. }
  763. void OpenGLContext::deactivateCurrentContext()
  764. {
  765. NativeContext::deactivateCurrentContext();
  766. currentThreadActiveContext.get() = nullptr;
  767. }
  768. void OpenGLContext::triggerRepaint()
  769. {
  770. if (auto* cachedImage = getCachedImage())
  771. cachedImage->triggerRepaint();
  772. }
  773. void OpenGLContext::swapBuffers()
  774. {
  775. if (nativeContext != nullptr)
  776. nativeContext->swapBuffers();
  777. }
  778. unsigned int OpenGLContext::getFrameBufferID() const noexcept
  779. {
  780. return nativeContext != nullptr ? nativeContext->getFrameBufferID() : 0;
  781. }
  782. bool OpenGLContext::setSwapInterval (int numFramesPerSwap)
  783. {
  784. return nativeContext != nullptr && nativeContext->setSwapInterval (numFramesPerSwap);
  785. }
  786. int OpenGLContext::getSwapInterval() const
  787. {
  788. return nativeContext != nullptr ? nativeContext->getSwapInterval() : 0;
  789. }
  790. void* OpenGLContext::getRawContext() const noexcept
  791. {
  792. return nativeContext != nullptr ? nativeContext->getRawContext() : nullptr;
  793. }
  794. OpenGLContext::CachedImage* OpenGLContext::getCachedImage() const noexcept
  795. {
  796. if (auto* comp = getTargetComponent())
  797. return CachedImage::get (*comp);
  798. return nullptr;
  799. }
  800. bool OpenGLContext::areShadersAvailable() const
  801. {
  802. auto* c = getCachedImage();
  803. return c != nullptr && c->shadersAvailable;
  804. }
  805. ReferenceCountedObject* OpenGLContext::getAssociatedObject (const char* name) const
  806. {
  807. jassert (name != nullptr);
  808. auto* c = getCachedImage();
  809. // This method must only be called from an openGL rendering callback.
  810. jassert (c != nullptr && nativeContext != nullptr);
  811. jassert (getCurrentContext() != nullptr);
  812. auto index = c->associatedObjectNames.indexOf (name);
  813. return index >= 0 ? c->associatedObjects.getUnchecked (index).get() : nullptr;
  814. }
  815. void OpenGLContext::setAssociatedObject (const char* name, ReferenceCountedObject* newObject)
  816. {
  817. jassert (name != nullptr);
  818. if (auto* c = getCachedImage())
  819. {
  820. // This method must only be called from an openGL rendering callback.
  821. jassert (nativeContext != nullptr);
  822. jassert (getCurrentContext() != nullptr);
  823. const int index = c->associatedObjectNames.indexOf (name);
  824. if (index >= 0)
  825. {
  826. if (newObject != nullptr)
  827. {
  828. c->associatedObjects.set (index, newObject);
  829. }
  830. else
  831. {
  832. c->associatedObjectNames.remove (index);
  833. c->associatedObjects.remove (index);
  834. }
  835. }
  836. else if (newObject != nullptr)
  837. {
  838. c->associatedObjectNames.add (name);
  839. c->associatedObjects.add (newObject);
  840. }
  841. }
  842. }
  843. void OpenGLContext::setImageCacheSize (size_t newSize) noexcept { imageCacheMaxSize = newSize; }
  844. size_t OpenGLContext::getImageCacheSize() const noexcept { return imageCacheMaxSize; }
  845. void OpenGLContext::execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock)
  846. {
  847. if (auto* c = getCachedImage())
  848. c->execute (std::move (workerToUse), shouldBlock);
  849. else
  850. jassertfalse; // You must have attached the context to a component
  851. }
  852. //==============================================================================
  853. struct DepthTestDisabler
  854. {
  855. DepthTestDisabler() noexcept
  856. {
  857. glGetBooleanv (GL_DEPTH_TEST, &wasEnabled);
  858. if (wasEnabled)
  859. glDisable (GL_DEPTH_TEST);
  860. }
  861. ~DepthTestDisabler() noexcept
  862. {
  863. if (wasEnabled)
  864. glEnable (GL_DEPTH_TEST);
  865. }
  866. GLboolean wasEnabled;
  867. };
  868. //==============================================================================
  869. void OpenGLContext::copyTexture (const Rectangle<int>& targetClipArea,
  870. const Rectangle<int>& anchorPosAndTextureSize,
  871. const int contextWidth, const int contextHeight,
  872. bool flippedVertically)
  873. {
  874. if (contextWidth <= 0 || contextHeight <= 0)
  875. return;
  876. JUCE_CHECK_OPENGL_ERROR
  877. glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  878. glEnable (GL_BLEND);
  879. DepthTestDisabler depthDisabler;
  880. if (areShadersAvailable())
  881. {
  882. struct OverlayShaderProgram : public ReferenceCountedObject
  883. {
  884. OverlayShaderProgram (OpenGLContext& context)
  885. : program (context), builder (program), params (program)
  886. {}
  887. static const OverlayShaderProgram& select (OpenGLContext& context)
  888. {
  889. static const char programValueID[] = "juceGLComponentOverlayShader";
  890. OverlayShaderProgram* program = static_cast<OverlayShaderProgram*> (context.getAssociatedObject (programValueID));
  891. if (program == nullptr)
  892. {
  893. program = new OverlayShaderProgram (context);
  894. context.setAssociatedObject (programValueID, program);
  895. }
  896. program->program.use();
  897. return *program;
  898. }
  899. struct ProgramBuilder
  900. {
  901. ProgramBuilder (OpenGLShaderProgram& prog)
  902. {
  903. prog.addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (
  904. "attribute " JUCE_HIGHP " vec2 position;"
  905. "uniform " JUCE_HIGHP " vec2 screenSize;"
  906. "uniform " JUCE_HIGHP " float textureBounds[4];"
  907. "uniform " JUCE_HIGHP " vec2 vOffsetAndScale;"
  908. "varying " JUCE_HIGHP " vec2 texturePos;"
  909. "void main()"
  910. "{"
  911. JUCE_HIGHP " vec2 scaled = position / (0.5 * screenSize.xy);"
  912. "gl_Position = vec4 (scaled.x - 1.0, 1.0 - scaled.y, 0, 1.0);"
  913. "texturePos = (position - vec2 (textureBounds[0], textureBounds[1])) / vec2 (textureBounds[2], textureBounds[3]);"
  914. "texturePos = vec2 (texturePos.x, vOffsetAndScale.x + vOffsetAndScale.y * texturePos.y);"
  915. "}"));
  916. prog.addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (
  917. "uniform sampler2D imageTexture;"
  918. "varying " JUCE_HIGHP " vec2 texturePos;"
  919. "void main()"
  920. "{"
  921. "gl_FragColor = texture2D (imageTexture, texturePos);"
  922. "}"));
  923. prog.link();
  924. }
  925. };
  926. struct Params
  927. {
  928. Params (OpenGLShaderProgram& prog)
  929. : positionAttribute (prog, "position"),
  930. screenSize (prog, "screenSize"),
  931. imageTexture (prog, "imageTexture"),
  932. textureBounds (prog, "textureBounds"),
  933. vOffsetAndScale (prog, "vOffsetAndScale")
  934. {}
  935. void set (const float targetWidth, const float targetHeight, const Rectangle<float>& bounds, bool flipVertically) const
  936. {
  937. const GLfloat m[] = { bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight() };
  938. textureBounds.set (m, 4);
  939. imageTexture.set (0);
  940. screenSize.set (targetWidth, targetHeight);
  941. vOffsetAndScale.set (flipVertically ? 0.0f : 1.0f,
  942. flipVertically ? 1.0f : -1.0f);
  943. }
  944. OpenGLShaderProgram::Attribute positionAttribute;
  945. OpenGLShaderProgram::Uniform screenSize, imageTexture, textureBounds, vOffsetAndScale;
  946. };
  947. OpenGLShaderProgram program;
  948. ProgramBuilder builder;
  949. Params params;
  950. };
  951. auto left = (GLshort) targetClipArea.getX();
  952. auto top = (GLshort) targetClipArea.getY();
  953. auto right = (GLshort) targetClipArea.getRight();
  954. auto bottom = (GLshort) targetClipArea.getBottom();
  955. const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top };
  956. auto& program = OverlayShaderProgram::select (*this);
  957. program.params.set ((float) contextWidth, (float) contextHeight, anchorPosAndTextureSize.toFloat(), flippedVertically);
  958. GLuint vertexBuffer = 0;
  959. extensions.glGenBuffers (1, &vertexBuffer);
  960. extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  961. extensions.glBufferData (GL_ARRAY_BUFFER, sizeof (vertices), vertices, GL_STATIC_DRAW);
  962. auto index = (GLuint) program.params.positionAttribute.attributeID;
  963. extensions.glVertexAttribPointer (index, 2, GL_SHORT, GL_FALSE, 4, nullptr);
  964. extensions.glEnableVertexAttribArray (index);
  965. JUCE_CHECK_OPENGL_ERROR
  966. if (extensions.glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
  967. {
  968. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  969. extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
  970. extensions.glUseProgram (0);
  971. extensions.glDisableVertexAttribArray (index);
  972. extensions.glDeleteBuffers (1, &vertexBuffer);
  973. }
  974. else
  975. {
  976. clearGLError();
  977. }
  978. }
  979. else
  980. {
  981. jassert (attachment == nullptr); // Running on an old graphics card!
  982. }
  983. JUCE_CHECK_OPENGL_ERROR
  984. }
  985. #if JUCE_ANDROID
  986. EGLDisplay OpenGLContext::NativeContext::display = EGL_NO_DISPLAY;
  987. EGLDisplay OpenGLContext::NativeContext::config;
  988. void OpenGLContext::NativeContext::surfaceCreated (LocalRef<jobject> holder)
  989. {
  990. ignoreUnused (holder);
  991. if (auto* cachedImage = CachedImage::get (component))
  992. {
  993. if (auto* pool = cachedImage->renderThread.get())
  994. {
  995. if (! pool->contains (cachedImage))
  996. {
  997. cachedImage->resume();
  998. cachedImage->context.triggerRepaint();
  999. }
  1000. }
  1001. }
  1002. }
  1003. void OpenGLContext::NativeContext::surfaceDestroyed (LocalRef<jobject> holder)
  1004. {
  1005. ignoreUnused (holder);
  1006. // unlike the name suggests this will be called just before the
  1007. // surface is destroyed. We need to pause the render thread.
  1008. if (auto* cachedImage = CachedImage::get (component))
  1009. {
  1010. cachedImage->pause();
  1011. if (auto* threadPool = cachedImage->renderThread.get())
  1012. threadPool->waitForJobToFinish (cachedImage, -1);
  1013. }
  1014. }
  1015. #endif
  1016. } // namespace juce