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.

1244 lines
37KB

  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() { 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 = new NativeContext (component, pixFormat, contextToShare,
  62. c.useMultisampling, c.versionRequired);
  63. if (nativeContext->createdOk())
  64. context.nativeContext = nativeContext;
  65. else
  66. nativeContext.reset();
  67. }
  68. ~CachedImage()
  69. {
  70. stop();
  71. }
  72. //==============================================================================
  73. void start()
  74. {
  75. if (nativeContext != nullptr)
  76. {
  77. renderThread = 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 * scale);
  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. lastScreenBounds = component.getTopLevelComponent()->getScreenBounds();
  224. auto newScale = Desktop::getInstance().getDisplays()
  225. .getDisplayContaining (lastScreenBounds.getCentre()).scale;
  226. auto newArea = peer->getComponent().getLocalArea (&component, component.getLocalBounds())
  227. .withZeroOrigin()
  228. * newScale;
  229. if (scale != newScale || viewportArea != newArea)
  230. {
  231. scale = newScale;
  232. viewportArea = newArea;
  233. if (canTriggerUpdate)
  234. invalidateAll();
  235. }
  236. }
  237. }
  238. void bindVertexArray() noexcept
  239. {
  240. #if JUCE_OPENGL3
  241. if (vertexArrayObject != 0)
  242. context.extensions.glBindVertexArray (vertexArrayObject);
  243. #endif
  244. }
  245. void checkViewportBounds()
  246. {
  247. auto screenBounds = component.getTopLevelComponent()->getScreenBounds();
  248. if (lastScreenBounds != screenBounds)
  249. updateViewportSize (true);
  250. }
  251. void paintComponent()
  252. {
  253. // you mustn't set your own cached image object when attaching a GL context!
  254. jassert (get (component) == this);
  255. if (! ensureFrameBufferSize())
  256. return;
  257. RectangleList<int> invalid (viewportArea);
  258. invalid.subtract (validArea);
  259. validArea = viewportArea;
  260. if (! invalid.isEmpty())
  261. {
  262. clearRegionInFrameBuffer (invalid);
  263. {
  264. ScopedPointer<LowLevelGraphicsContext> g (createOpenGLGraphicsContext (context, cachedImageFrameBuffer));
  265. g->clipToRectangleList (invalid);
  266. g->addTransform (AffineTransform::scale ((float) scale));
  267. paintOwner (*g);
  268. JUCE_CHECK_OPENGL_ERROR
  269. }
  270. if (! context.isActive())
  271. context.makeActive();
  272. }
  273. JUCE_CHECK_OPENGL_ERROR
  274. }
  275. void drawComponentBuffer()
  276. {
  277. #if ! JUCE_ANDROID
  278. glEnable (GL_TEXTURE_2D);
  279. clearGLError();
  280. #endif
  281. #if JUCE_WINDOWS
  282. // some stupidly old drivers are missing this function, so try to at least avoid a crash here,
  283. // but if you hit this assertion you may want to have your own version check before using the
  284. // component rendering stuff on such old drivers.
  285. jassert (context.extensions.glActiveTexture != nullptr);
  286. if (context.extensions.glActiveTexture != nullptr)
  287. #endif
  288. context.extensions.glActiveTexture (GL_TEXTURE0);
  289. glBindTexture (GL_TEXTURE_2D, cachedImageFrameBuffer.getTextureID());
  290. bindVertexArray();
  291. const Rectangle<int> cacheBounds (cachedImageFrameBuffer.getWidth(), cachedImageFrameBuffer.getHeight());
  292. context.copyTexture (cacheBounds, cacheBounds, cacheBounds.getWidth(), cacheBounds.getHeight(), false);
  293. glBindTexture (GL_TEXTURE_2D, 0);
  294. JUCE_CHECK_OPENGL_ERROR
  295. }
  296. void paintOwner (LowLevelGraphicsContext& llgc)
  297. {
  298. Graphics g (llgc);
  299. #if JUCE_ENABLE_REPAINT_DEBUGGING
  300. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  301. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  302. #endif
  303. {
  304. g.saveState();
  305. }
  306. #endif
  307. JUCE_TRY
  308. {
  309. component.paintEntireComponent (g, false);
  310. }
  311. JUCE_CATCH_EXCEPTION
  312. #if JUCE_ENABLE_REPAINT_DEBUGGING
  313. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  314. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  315. #endif
  316. {
  317. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  318. // clearly when things are being repainted.
  319. g.restoreState();
  320. static Random rng;
  321. g.fillAll (Colour ((uint8) rng.nextInt (255),
  322. (uint8) rng.nextInt (255),
  323. (uint8) rng.nextInt (255),
  324. (uint8) 0x50));
  325. }
  326. #endif
  327. }
  328. void handleResize()
  329. {
  330. updateViewportSize (true);
  331. #if JUCE_MAC
  332. if (hasInitialised)
  333. {
  334. [nativeContext->view update];
  335. renderFrame();
  336. }
  337. #endif
  338. }
  339. //==============================================================================
  340. JobStatus runJob() override
  341. {
  342. {
  343. // Allow the message thread to finish setting-up the context before using it..
  344. MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock, false);
  345. do
  346. {
  347. if (shouldExit())
  348. return ThreadPoolJob::jobHasFinished;
  349. } while (! mmLock.retryLock());
  350. }
  351. initialiseOnThread();
  352. hasInitialised = true;
  353. while (! shouldExit())
  354. {
  355. #if JUCE_IOS
  356. if (backgroundProcessCheck.isBackgroundProcess())
  357. {
  358. repaintEvent.wait (300);
  359. continue;
  360. }
  361. #endif
  362. if (shouldExit())
  363. break;
  364. if (! renderFrame())
  365. repaintEvent.wait (5); // failed to render, so avoid a tight fail-loop.
  366. else if (! context.continuousRepaint && ! shouldExit())
  367. repaintEvent.wait (-1);
  368. }
  369. hasInitialised = false;
  370. context.makeActive();
  371. shutdownOnThread();
  372. OpenGLContext::deactivateCurrentContext();
  373. return ThreadPoolJob::jobHasFinished;
  374. }
  375. void initialiseOnThread()
  376. {
  377. // On android, this can get called twice, so drop any previous state..
  378. associatedObjectNames.clear();
  379. associatedObjects.clear();
  380. cachedImageFrameBuffer.release();
  381. context.makeActive();
  382. nativeContext->initialiseOnRenderThread (context);
  383. #if JUCE_ANDROID
  384. // On android the context may be created in initialiseOnRenderThread
  385. // and we therefore need to call makeActive again
  386. context.makeActive();
  387. #endif
  388. context.extensions.initialise();
  389. #if JUCE_OPENGL3
  390. if (OpenGLShaderProgram::getLanguageVersion() > 1.2)
  391. {
  392. context.extensions.glGenVertexArrays (1, &vertexArrayObject);
  393. bindVertexArray();
  394. }
  395. #endif
  396. glViewport (0, 0, component.getWidth(), component.getHeight());
  397. nativeContext->setSwapInterval (1);
  398. #if ! JUCE_OPENGL_ES
  399. JUCE_CHECK_OPENGL_ERROR
  400. shadersAvailable = OpenGLShaderProgram::getLanguageVersion() > 0;
  401. clearGLError();
  402. #endif
  403. if (context.renderer != nullptr)
  404. context.renderer->newOpenGLContextCreated();
  405. }
  406. void shutdownOnThread()
  407. {
  408. if (context.renderer != nullptr)
  409. context.renderer->openGLContextClosing();
  410. #if JUCE_OPENGL3
  411. if (vertexArrayObject != 0)
  412. context.extensions.glDeleteVertexArrays (1, &vertexArrayObject);
  413. #endif
  414. associatedObjectNames.clear();
  415. associatedObjects.clear();
  416. cachedImageFrameBuffer.release();
  417. nativeContext->shutdownOnRenderThread();
  418. }
  419. //==============================================================================
  420. struct BlockingWorker : public OpenGLContext::AsyncWorker
  421. {
  422. BlockingWorker (OpenGLContext::AsyncWorker::Ptr && workerToUse)
  423. : originalWorker (static_cast<OpenGLContext::AsyncWorker::Ptr&&> (workerToUse))
  424. {}
  425. void operator() (OpenGLContext& calleeContext)
  426. {
  427. if (originalWorker != nullptr)
  428. (*originalWorker) (calleeContext);
  429. finishedSignal.signal();
  430. }
  431. void block() noexcept { finishedSignal.wait(); }
  432. OpenGLContext::AsyncWorker::Ptr originalWorker;
  433. WaitableEvent finishedSignal;
  434. };
  435. bool doWorkWhileWaitingForLock (bool contextIsAlreadyActive)
  436. {
  437. bool contextActivated = false;
  438. for (OpenGLContext::AsyncWorker::Ptr work = workQueue.removeAndReturn (0);
  439. work != nullptr && (! shouldExit()); work = workQueue.removeAndReturn (0))
  440. {
  441. if ((! contextActivated) && (! contextIsAlreadyActive))
  442. {
  443. if (! context.makeActive())
  444. break;
  445. contextActivated = true;
  446. }
  447. NativeContext::Locker locker (*nativeContext);
  448. (*work) (context);
  449. clearGLError();
  450. }
  451. if (contextActivated)
  452. OpenGLContext::deactivateCurrentContext();
  453. return shouldExit();
  454. }
  455. void execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock, bool calledFromDestructor = false)
  456. {
  457. if (calledFromDestructor || destroying.get() == 0)
  458. {
  459. BlockingWorker* blocker = (shouldBlock ? new BlockingWorker (static_cast<OpenGLContext::AsyncWorker::Ptr&&> (workerToUse)) : nullptr);
  460. OpenGLContext::AsyncWorker::Ptr worker = (blocker != nullptr ? blocker : static_cast<OpenGLContext::AsyncWorker::Ptr&&> (workerToUse));
  461. workQueue.add (worker);
  462. messageManagerLock.abort();
  463. context.triggerRepaint();
  464. if (blocker != nullptr)
  465. blocker->block();
  466. }
  467. else
  468. {
  469. jassertfalse; // you called execute AFTER you detached your openglcontext
  470. }
  471. }
  472. //==============================================================================
  473. static CachedImage* get (Component& c) noexcept
  474. {
  475. return dynamic_cast<CachedImage*> (c.getCachedComponentImage());
  476. }
  477. //==============================================================================
  478. friend class NativeContext;
  479. ScopedPointer<NativeContext> nativeContext;
  480. OpenGLContext& context;
  481. Component& component;
  482. OpenGLFrameBuffer cachedImageFrameBuffer;
  483. RectangleList<int> validArea;
  484. Rectangle<int> viewportArea, lastScreenBounds;
  485. double scale = 1.0;
  486. #if JUCE_OPENGL3
  487. GLuint vertexArrayObject = 0;
  488. #endif
  489. StringArray associatedObjectNames;
  490. ReferenceCountedArray<ReferenceCountedObject> associatedObjects;
  491. WaitableEvent canPaintNowFlag, finishedPaintingFlag, repaintEvent;
  492. #if JUCE_OPENGL_ES
  493. bool shadersAvailable = true;
  494. #else
  495. bool shadersAvailable = false;
  496. #endif
  497. bool hasInitialised = false;
  498. Atomic<int> needsUpdate { 1 }, destroying;
  499. uint32 lastMMLockReleaseTime = 0;
  500. ScopedPointer<ThreadPool> renderThread;
  501. ReferenceCountedArray<OpenGLContext::AsyncWorker, CriticalSection> workQueue;
  502. MessageManager::Lock messageManagerLock;
  503. #if JUCE_IOS
  504. iOSBackgroundProcessCheck backgroundProcessCheck;
  505. #endif
  506. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedImage)
  507. };
  508. //==============================================================================
  509. class OpenGLContext::Attachment : public ComponentMovementWatcher,
  510. private Timer
  511. {
  512. public:
  513. Attachment (OpenGLContext& c, Component& comp)
  514. : ComponentMovementWatcher (&comp), context (c)
  515. {
  516. if (canBeAttached (comp))
  517. attach();
  518. }
  519. ~Attachment()
  520. {
  521. detach();
  522. }
  523. void detach()
  524. {
  525. auto& comp = *getComponent();
  526. stop();
  527. comp.setCachedComponentImage (nullptr);
  528. context.nativeContext = nullptr;
  529. }
  530. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
  531. {
  532. auto& comp = *getComponent();
  533. if (isAttached (comp) != canBeAttached (comp))
  534. componentVisibilityChanged();
  535. if (comp.getWidth() > 0 && comp.getHeight() > 0
  536. && context.nativeContext != nullptr)
  537. {
  538. if (auto* c = CachedImage::get (comp))
  539. c->handleResize();
  540. if (auto* peer = comp.getTopLevelComponent()->getPeer())
  541. context.nativeContext->updateWindowPosition (peer->getAreaCoveredBy (comp));
  542. }
  543. }
  544. void componentPeerChanged() override
  545. {
  546. detach();
  547. componentVisibilityChanged();
  548. }
  549. void componentVisibilityChanged() override
  550. {
  551. auto& comp = *getComponent();
  552. if (canBeAttached (comp))
  553. {
  554. if (isAttached (comp))
  555. comp.repaint(); // (needed when windows are un-minimised)
  556. else
  557. attach();
  558. }
  559. else
  560. {
  561. detach();
  562. }
  563. }
  564. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  565. void componentBeingDeleted (Component& c) override
  566. {
  567. /* You must call detach() or delete your OpenGLContext to remove it
  568. from a component BEFORE deleting the component that it is using!
  569. */
  570. jassertfalse;
  571. ComponentMovementWatcher::componentBeingDeleted (c);
  572. }
  573. #endif
  574. void update()
  575. {
  576. auto& comp = *getComponent();
  577. if (canBeAttached (comp))
  578. start();
  579. else
  580. stop();
  581. }
  582. private:
  583. OpenGLContext& context;
  584. bool canBeAttached (const Component& comp) noexcept
  585. {
  586. return (! context.overrideCanAttach) && comp.getWidth() > 0 && comp.getHeight() > 0 && isShowingOrMinimised (comp);
  587. }
  588. static bool isShowingOrMinimised (const Component& c)
  589. {
  590. if (! c.isVisible())
  591. return false;
  592. if (auto* p = c.getParentComponent())
  593. return isShowingOrMinimised (*p);
  594. return c.getPeer() != nullptr;
  595. }
  596. static bool isAttached (const Component& comp) noexcept
  597. {
  598. return comp.getCachedComponentImage() != nullptr;
  599. }
  600. void attach()
  601. {
  602. auto& comp = *getComponent();
  603. auto* newCachedImage = new CachedImage (context, comp,
  604. context.openGLPixelFormat,
  605. context.contextToShareWith);
  606. comp.setCachedComponentImage (newCachedImage);
  607. start();
  608. }
  609. void stop()
  610. {
  611. stopTimer();
  612. auto& comp = *getComponent();
  613. #if JUCE_MAC
  614. [[(NSView*) comp.getWindowHandle() window] disableScreenUpdatesUntilFlush];
  615. #endif
  616. if (auto* oldCachedImage = CachedImage::get (comp))
  617. oldCachedImage->stop(); // (must stop this before detaching it from the component)
  618. }
  619. void start()
  620. {
  621. auto& comp = *getComponent();
  622. if (auto* cachedImage = CachedImage::get (comp))
  623. {
  624. cachedImage->start(); // (must wait until this is attached before starting its thread)
  625. cachedImage->updateViewportSize (true);
  626. startTimer (400);
  627. }
  628. }
  629. void timerCallback() override
  630. {
  631. if (auto* cachedImage = CachedImage::get (*getComponent()))
  632. cachedImage->checkViewportBounds();
  633. }
  634. };
  635. //==============================================================================
  636. OpenGLContext::OpenGLContext()
  637. {
  638. }
  639. OpenGLContext::~OpenGLContext()
  640. {
  641. detach();
  642. }
  643. void OpenGLContext::setRenderer (OpenGLRenderer* rendererToUse) noexcept
  644. {
  645. // This method must not be called when the context has already been attached!
  646. // Call it before attaching your context, or use detach() first, before calling this!
  647. jassert (nativeContext == nullptr);
  648. renderer = rendererToUse;
  649. }
  650. void OpenGLContext::setComponentPaintingEnabled (bool shouldPaintComponent) noexcept
  651. {
  652. // This method must not be called when the context has already been attached!
  653. // Call it before attaching your context, or use detach() first, before calling this!
  654. jassert (nativeContext == nullptr);
  655. renderComponents = shouldPaintComponent;
  656. }
  657. void OpenGLContext::setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept
  658. {
  659. continuousRepaint = shouldContinuouslyRepaint;
  660. triggerRepaint();
  661. }
  662. void OpenGLContext::setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept
  663. {
  664. // This method must not be called when the context has already been attached!
  665. // Call it before attaching your context, or use detach() first, before calling this!
  666. jassert (nativeContext == nullptr);
  667. openGLPixelFormat = preferredPixelFormat;
  668. }
  669. void OpenGLContext::setTextureMagnificationFilter (OpenGLContext::TextureMagnificationFilter magFilterMode) noexcept
  670. {
  671. texMagFilter = magFilterMode;
  672. }
  673. void OpenGLContext::setNativeSharedContext (void* nativeContextToShareWith) noexcept
  674. {
  675. // This method must not be called when the context has already been attached!
  676. // Call it before attaching your context, or use detach() first, before calling this!
  677. jassert (nativeContext == nullptr);
  678. contextToShareWith = nativeContextToShareWith;
  679. }
  680. void OpenGLContext::setMultisamplingEnabled (bool b) noexcept
  681. {
  682. // This method must not be called when the context has already been attached!
  683. // Call it before attaching your context, or use detach() first, before calling this!
  684. jassert (nativeContext == nullptr);
  685. useMultisampling = b;
  686. }
  687. void OpenGLContext::setOpenGLVersionRequired (OpenGLVersion v) noexcept
  688. {
  689. versionRequired = v;
  690. }
  691. void OpenGLContext::attachTo (Component& component)
  692. {
  693. component.repaint();
  694. if (getTargetComponent() != &component)
  695. {
  696. detach();
  697. attachment = new Attachment (*this, component);
  698. }
  699. }
  700. void OpenGLContext::detach()
  701. {
  702. if (auto* a = attachment.get())
  703. {
  704. a->detach(); // must detach before nulling our pointer
  705. attachment.reset();
  706. }
  707. nativeContext = nullptr;
  708. }
  709. bool OpenGLContext::isAttached() const noexcept
  710. {
  711. return nativeContext != nullptr;
  712. }
  713. Component* OpenGLContext::getTargetComponent() const noexcept
  714. {
  715. return attachment != nullptr ? attachment->getComponent() : nullptr;
  716. }
  717. OpenGLContext* OpenGLContext::getContextAttachedTo (Component& c) noexcept
  718. {
  719. if (auto* ci = CachedImage::get (c))
  720. return &(ci->context);
  721. return nullptr;
  722. }
  723. static ThreadLocalValue<OpenGLContext*> currentThreadActiveContext;
  724. OpenGLContext* OpenGLContext::getCurrentContext()
  725. {
  726. return currentThreadActiveContext.get();
  727. }
  728. bool OpenGLContext::makeActive() const noexcept
  729. {
  730. auto& current = currentThreadActiveContext.get();
  731. if (nativeContext != nullptr && nativeContext->makeActive())
  732. {
  733. current = const_cast<OpenGLContext*> (this);
  734. return true;
  735. }
  736. current = nullptr;
  737. return false;
  738. }
  739. bool OpenGLContext::isActive() const noexcept
  740. {
  741. return nativeContext != nullptr && nativeContext->isActive();
  742. }
  743. void OpenGLContext::deactivateCurrentContext()
  744. {
  745. NativeContext::deactivateCurrentContext();
  746. currentThreadActiveContext.get() = nullptr;
  747. }
  748. void OpenGLContext::triggerRepaint()
  749. {
  750. if (auto* cachedImage = getCachedImage())
  751. cachedImage->triggerRepaint();
  752. }
  753. void OpenGLContext::swapBuffers()
  754. {
  755. if (nativeContext != nullptr)
  756. nativeContext->swapBuffers();
  757. }
  758. unsigned int OpenGLContext::getFrameBufferID() const noexcept
  759. {
  760. return nativeContext != nullptr ? nativeContext->getFrameBufferID() : 0;
  761. }
  762. bool OpenGLContext::setSwapInterval (int numFramesPerSwap)
  763. {
  764. return nativeContext != nullptr && nativeContext->setSwapInterval (numFramesPerSwap);
  765. }
  766. int OpenGLContext::getSwapInterval() const
  767. {
  768. return nativeContext != nullptr ? nativeContext->getSwapInterval() : 0;
  769. }
  770. void* OpenGLContext::getRawContext() const noexcept
  771. {
  772. return nativeContext != nullptr ? nativeContext->getRawContext() : nullptr;
  773. }
  774. OpenGLContext::CachedImage* OpenGLContext::getCachedImage() const noexcept
  775. {
  776. if (auto* comp = getTargetComponent())
  777. return CachedImage::get (*comp);
  778. return nullptr;
  779. }
  780. bool OpenGLContext::areShadersAvailable() const
  781. {
  782. auto* c = getCachedImage();
  783. return c != nullptr && c->shadersAvailable;
  784. }
  785. ReferenceCountedObject* OpenGLContext::getAssociatedObject (const char* name) const
  786. {
  787. jassert (name != nullptr);
  788. auto* c = getCachedImage();
  789. // This method must only be called from an openGL rendering callback.
  790. jassert (c != nullptr && nativeContext != nullptr);
  791. jassert (getCurrentContext() != nullptr);
  792. const int index = c->associatedObjectNames.indexOf (name);
  793. return index >= 0 ? c->associatedObjects.getUnchecked (index) : nullptr;
  794. }
  795. void OpenGLContext::setAssociatedObject (const char* name, ReferenceCountedObject* newObject)
  796. {
  797. jassert (name != nullptr);
  798. if (auto* c = getCachedImage())
  799. {
  800. // This method must only be called from an openGL rendering callback.
  801. jassert (nativeContext != nullptr);
  802. jassert (getCurrentContext() != nullptr);
  803. const int index = c->associatedObjectNames.indexOf (name);
  804. if (index >= 0)
  805. {
  806. if (newObject != nullptr)
  807. {
  808. c->associatedObjects.set (index, newObject);
  809. }
  810. else
  811. {
  812. c->associatedObjectNames.remove (index);
  813. c->associatedObjects.remove (index);
  814. }
  815. }
  816. else if (newObject != nullptr)
  817. {
  818. c->associatedObjectNames.add (name);
  819. c->associatedObjects.add (newObject);
  820. }
  821. }
  822. }
  823. void OpenGLContext::setImageCacheSize (size_t newSize) noexcept { imageCacheMaxSize = newSize; }
  824. size_t OpenGLContext::getImageCacheSize() const noexcept { return imageCacheMaxSize; }
  825. void OpenGLContext::execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock)
  826. {
  827. if (auto* c = getCachedImage())
  828. c->execute (static_cast<OpenGLContext::AsyncWorker::Ptr&&> (workerToUse), shouldBlock);
  829. else
  830. jassertfalse; // You must have attached the context to a component
  831. }
  832. void OpenGLContext::overrideCanBeAttached (bool newCanAttach)
  833. {
  834. if (overrideCanAttach != newCanAttach)
  835. {
  836. overrideCanAttach = newCanAttach;
  837. if (auto* a = attachment.get())
  838. a->update();
  839. }
  840. }
  841. //==============================================================================
  842. struct DepthTestDisabler
  843. {
  844. DepthTestDisabler() noexcept
  845. {
  846. glGetBooleanv (GL_DEPTH_TEST, &wasEnabled);
  847. if (wasEnabled)
  848. glDisable (GL_DEPTH_TEST);
  849. }
  850. ~DepthTestDisabler() noexcept
  851. {
  852. if (wasEnabled)
  853. glEnable (GL_DEPTH_TEST);
  854. }
  855. GLboolean wasEnabled;
  856. };
  857. //==============================================================================
  858. void OpenGLContext::copyTexture (const Rectangle<int>& targetClipArea,
  859. const Rectangle<int>& anchorPosAndTextureSize,
  860. const int contextWidth, const int contextHeight,
  861. bool flippedVertically)
  862. {
  863. if (contextWidth <= 0 || contextHeight <= 0)
  864. return;
  865. JUCE_CHECK_OPENGL_ERROR
  866. glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  867. glEnable (GL_BLEND);
  868. DepthTestDisabler depthDisabler;
  869. if (areShadersAvailable())
  870. {
  871. struct OverlayShaderProgram : public ReferenceCountedObject
  872. {
  873. OverlayShaderProgram (OpenGLContext& context)
  874. : program (context), builder (program), params (program)
  875. {}
  876. static const OverlayShaderProgram& select (OpenGLContext& context)
  877. {
  878. static const char programValueID[] = "juceGLComponentOverlayShader";
  879. OverlayShaderProgram* program = static_cast<OverlayShaderProgram*> (context.getAssociatedObject (programValueID));
  880. if (program == nullptr)
  881. {
  882. program = new OverlayShaderProgram (context);
  883. context.setAssociatedObject (programValueID, program);
  884. }
  885. program->program.use();
  886. return *program;
  887. }
  888. struct ProgramBuilder
  889. {
  890. ProgramBuilder (OpenGLShaderProgram& prog)
  891. {
  892. prog.addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (
  893. "attribute " JUCE_HIGHP " vec2 position;"
  894. "uniform " JUCE_HIGHP " vec2 screenSize;"
  895. "uniform " JUCE_HIGHP " float textureBounds[4];"
  896. "uniform " JUCE_HIGHP " vec2 vOffsetAndScale;"
  897. "varying " JUCE_HIGHP " vec2 texturePos;"
  898. "void main()"
  899. "{"
  900. JUCE_HIGHP " vec2 scaled = position / (0.5 * screenSize.xy);"
  901. "gl_Position = vec4 (scaled.x - 1.0, 1.0 - scaled.y, 0, 1.0);"
  902. "texturePos = (position - vec2 (textureBounds[0], textureBounds[1])) / vec2 (textureBounds[2], textureBounds[3]);"
  903. "texturePos = vec2 (texturePos.x, vOffsetAndScale.x + vOffsetAndScale.y * texturePos.y);"
  904. "}"));
  905. prog.addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (
  906. "uniform sampler2D imageTexture;"
  907. "varying " JUCE_HIGHP " vec2 texturePos;"
  908. "void main()"
  909. "{"
  910. "gl_FragColor = texture2D (imageTexture, texturePos);"
  911. "}"));
  912. prog.link();
  913. }
  914. };
  915. struct Params
  916. {
  917. Params (OpenGLShaderProgram& prog)
  918. : positionAttribute (prog, "position"),
  919. screenSize (prog, "screenSize"),
  920. imageTexture (prog, "imageTexture"),
  921. textureBounds (prog, "textureBounds"),
  922. vOffsetAndScale (prog, "vOffsetAndScale")
  923. {}
  924. void set (const float targetWidth, const float targetHeight, const Rectangle<float>& bounds, bool flipVertically) const
  925. {
  926. const GLfloat m[] = { bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight() };
  927. textureBounds.set (m, 4);
  928. imageTexture.set (0);
  929. screenSize.set (targetWidth, targetHeight);
  930. vOffsetAndScale.set (flipVertically ? 0.0f : 1.0f,
  931. flipVertically ? 1.0f : -1.0f);
  932. }
  933. OpenGLShaderProgram::Attribute positionAttribute;
  934. OpenGLShaderProgram::Uniform screenSize, imageTexture, textureBounds, vOffsetAndScale;
  935. };
  936. OpenGLShaderProgram program;
  937. ProgramBuilder builder;
  938. Params params;
  939. };
  940. auto left = (GLshort) targetClipArea.getX();
  941. auto top = (GLshort) targetClipArea.getY();
  942. auto right = (GLshort) targetClipArea.getRight();
  943. auto bottom = (GLshort) targetClipArea.getBottom();
  944. const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top };
  945. auto& program = OverlayShaderProgram::select (*this);
  946. program.params.set ((float) contextWidth, (float) contextHeight, anchorPosAndTextureSize.toFloat(), flippedVertically);
  947. GLuint vertexBuffer = 0;
  948. extensions.glGenBuffers (1, &vertexBuffer);
  949. extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  950. extensions.glBufferData (GL_ARRAY_BUFFER, sizeof (vertices), vertices, GL_STATIC_DRAW);
  951. auto index = (GLuint) program.params.positionAttribute.attributeID;
  952. extensions.glVertexAttribPointer (index, 2, GL_SHORT, GL_FALSE, 4, 0);
  953. extensions.glEnableVertexAttribArray (index);
  954. JUCE_CHECK_OPENGL_ERROR
  955. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  956. extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
  957. extensions.glUseProgram (0);
  958. extensions.glDisableVertexAttribArray (index);
  959. extensions.glDeleteBuffers (1, &vertexBuffer);
  960. }
  961. else
  962. {
  963. jassert (attachment == nullptr); // Running on an old graphics card!
  964. }
  965. JUCE_CHECK_OPENGL_ERROR
  966. }
  967. #if JUCE_ANDROID
  968. EGLDisplay OpenGLContext::NativeContext::display = EGL_NO_DISPLAY;
  969. EGLDisplay OpenGLContext::NativeContext::config;
  970. void OpenGLContext::NativeContext::surfaceCreated (jobject holder)
  971. {
  972. ignoreUnused (holder);
  973. if (auto* cachedImage = CachedImage::get (component))
  974. {
  975. if (auto* pool = cachedImage->renderThread.get())
  976. {
  977. if (! pool->contains (cachedImage))
  978. {
  979. cachedImage->resume();
  980. cachedImage->context.triggerRepaint();
  981. }
  982. }
  983. }
  984. }
  985. void OpenGLContext::NativeContext::surfaceDestroyed (jobject holder)
  986. {
  987. ignoreUnused (holder);
  988. // unlike the name suggests this will be called just before the
  989. // surface is destroyed. We need to pause the render thread.
  990. if (auto* cachedImage = CachedImage::get (component))
  991. {
  992. cachedImage->pause();
  993. if (auto* threadPool = cachedImage->renderThread.get())
  994. threadPool->waitForJobToFinish (cachedImage, -1);
  995. }
  996. }
  997. #endif
  998. } // namespace juce