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.

1323 lines
40KB

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