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.

1669 lines
53KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #if JUCE_MAC
  19. #include <juce_gui_basics/native/juce_mac_PerScreenDisplayLinks.h>
  20. #endif
  21. namespace juce
  22. {
  23. #if JUCE_IOS
  24. struct AppInactivityCallback // NB: this is a duplicate of an internal declaration in juce_core
  25. {
  26. virtual ~AppInactivityCallback() {}
  27. virtual void appBecomingInactive() = 0;
  28. };
  29. extern Array<AppInactivityCallback*> appBecomingInactiveCallbacks;
  30. // On iOS, all GL calls will crash when the app is running in the background, so
  31. // this prevents them from happening (which some messy locking behaviour)
  32. struct iOSBackgroundProcessCheck : public AppInactivityCallback
  33. {
  34. iOSBackgroundProcessCheck() { isBackgroundProcess(); appBecomingInactiveCallbacks.add (this); }
  35. ~iOSBackgroundProcessCheck() override { appBecomingInactiveCallbacks.removeAllInstancesOf (this); }
  36. bool isBackgroundProcess()
  37. {
  38. const bool b = Process::isForegroundProcess();
  39. isForeground.set (b ? 1 : 0);
  40. return ! b;
  41. }
  42. void appBecomingInactive() override
  43. {
  44. int counter = 2000;
  45. while (--counter > 0 && isForeground.get() != 0)
  46. Thread::sleep (1);
  47. }
  48. private:
  49. Atomic<int> isForeground;
  50. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSBackgroundProcessCheck)
  51. };
  52. #endif
  53. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  54. extern JUCE_API double getScaleFactorForWindow (HWND);
  55. #endif
  56. static bool contextHasTextureNpotFeature()
  57. {
  58. if (getOpenGLVersion() >= Version (2))
  59. return true;
  60. // If the version is < 2, we can't use the newer extension-checking API
  61. // so we have to use glGetString
  62. const auto* extensionsBegin = glGetString (GL_EXTENSIONS);
  63. if (extensionsBegin == nullptr)
  64. return false;
  65. const auto* extensionsEnd = findNullTerminator (extensionsBegin);
  66. const std::string extensionsString (extensionsBegin, extensionsEnd);
  67. const auto stringTokens = StringArray::fromTokens (extensionsString.c_str(), false);
  68. return stringTokens.contains ("GL_ARB_texture_non_power_of_two");
  69. }
  70. template <typename Fn> struct ScopeGuard : Fn
  71. {
  72. ~ScopeGuard() { Fn::operator()(); }
  73. };
  74. template <typename Fn> ScopeGuard (Fn) -> ScopeGuard<Fn>;
  75. //==============================================================================
  76. class OpenGLContext::CachedImage : public CachedComponentImage
  77. {
  78. template <typename T, typename U>
  79. static constexpr bool isFlagSet (const T& t, const U& u) { return (t & u) != 0; }
  80. struct AreaAndScale
  81. {
  82. Rectangle<int> area;
  83. double scale;
  84. auto tie() const { return std::tie (area, scale); }
  85. auto operator== (const AreaAndScale& other) const { return tie() == other.tie(); }
  86. auto operator!= (const AreaAndScale& other) const { return tie() != other.tie(); }
  87. };
  88. class LockedAreaAndScale
  89. {
  90. public:
  91. auto get() const
  92. {
  93. const ScopedLock lock (mutex);
  94. return data;
  95. }
  96. template <typename Fn>
  97. void set (const AreaAndScale& d, Fn&& ifDifferent)
  98. {
  99. const auto old = [&]
  100. {
  101. const ScopedLock lock (mutex);
  102. return std::exchange (data, d);
  103. }();
  104. if (old != d)
  105. ifDifferent();
  106. }
  107. private:
  108. CriticalSection mutex;
  109. AreaAndScale data { {}, 1.0 };
  110. };
  111. public:
  112. CachedImage (OpenGLContext& c, Component& comp,
  113. const OpenGLPixelFormat& pixFormat, void* contextToShare)
  114. : context (c),
  115. component (comp)
  116. {
  117. nativeContext.reset (new NativeContext (component, pixFormat, contextToShare,
  118. c.useMultisampling, c.versionRequired));
  119. if (nativeContext->createdOk())
  120. context.nativeContext = nativeContext.get();
  121. else
  122. nativeContext.reset();
  123. }
  124. ~CachedImage() override
  125. {
  126. stop();
  127. }
  128. //==============================================================================
  129. void start()
  130. {
  131. if (nativeContext != nullptr)
  132. resume();
  133. }
  134. void stop()
  135. {
  136. // make sure everything has finished executing
  137. state |= StateFlags::pendingDestruction;
  138. if (workQueue.size() > 0)
  139. {
  140. if (! renderThread->contains (this))
  141. resume();
  142. while (workQueue.size() != 0)
  143. Thread::sleep (20);
  144. }
  145. pause();
  146. }
  147. //==============================================================================
  148. void pause()
  149. {
  150. renderThread->remove (this);
  151. if ((state.fetch_and (~StateFlags::initialised) & StateFlags::initialised) != 0)
  152. {
  153. context.makeActive();
  154. shutdownOnThread();
  155. OpenGLContext::deactivateCurrentContext();
  156. }
  157. }
  158. void resume()
  159. {
  160. renderThread->add (this);
  161. }
  162. //==============================================================================
  163. void paint (Graphics&) override
  164. {
  165. if (MessageManager::getInstance()->isThisTheMessageThread())
  166. {
  167. updateViewportSize();
  168. }
  169. else
  170. {
  171. // If you hit this assertion, it's because paint has been called from a thread other
  172. // than the message thread. This commonly happens when nesting OpenGL contexts, because
  173. // the 'outer' OpenGL renderer will attempt to call paint on the 'inner' context's
  174. // component from the OpenGL thread.
  175. // Nesting OpenGL contexts is not directly supported, however there is a workaround:
  176. // https://forum.juce.com/t/opengl-how-do-3d-with-custom-shaders-and-2d-with-juce-paint-methods-work-together/28026/7
  177. jassertfalse;
  178. }
  179. }
  180. bool invalidateAll() override
  181. {
  182. validArea.clear();
  183. triggerRepaint();
  184. return false;
  185. }
  186. bool invalidate (const Rectangle<int>& area) override
  187. {
  188. validArea.subtract (area.toFloat().transformedBy (transform).getSmallestIntegerContainer());
  189. triggerRepaint();
  190. return false;
  191. }
  192. void releaseResources() override
  193. {
  194. stop();
  195. }
  196. void triggerRepaint()
  197. {
  198. state |= (StateFlags::pendingRender | StateFlags::paintComponents);
  199. renderThread->triggerRepaint();
  200. }
  201. //==============================================================================
  202. bool ensureFrameBufferSize (Rectangle<int> viewportArea)
  203. {
  204. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  205. auto fbW = cachedImageFrameBuffer.getWidth();
  206. auto fbH = cachedImageFrameBuffer.getHeight();
  207. if (fbW != viewportArea.getWidth() || fbH != viewportArea.getHeight() || ! cachedImageFrameBuffer.isValid())
  208. {
  209. if (! cachedImageFrameBuffer.initialise (context, viewportArea.getWidth(), viewportArea.getHeight()))
  210. return false;
  211. validArea.clear();
  212. JUCE_CHECK_OPENGL_ERROR
  213. }
  214. return true;
  215. }
  216. void clearRegionInFrameBuffer (const RectangleList<int>& list)
  217. {
  218. glClearColor (0, 0, 0, 0);
  219. glEnable (GL_SCISSOR_TEST);
  220. auto previousFrameBufferTarget = OpenGLFrameBuffer::getCurrentFrameBufferTarget();
  221. cachedImageFrameBuffer.makeCurrentRenderingTarget();
  222. auto imageH = cachedImageFrameBuffer.getHeight();
  223. for (auto& r : list)
  224. {
  225. glScissor (r.getX(), imageH - r.getBottom(), r.getWidth(), r.getHeight());
  226. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  227. }
  228. glDisable (GL_SCISSOR_TEST);
  229. context.extensions.glBindFramebuffer (GL_FRAMEBUFFER, previousFrameBufferTarget);
  230. JUCE_CHECK_OPENGL_ERROR
  231. }
  232. struct ScopedContextActivator
  233. {
  234. bool activate (OpenGLContext& ctx)
  235. {
  236. if (! active)
  237. active = ctx.makeActive();
  238. return active;
  239. }
  240. ~ScopedContextActivator()
  241. {
  242. if (active)
  243. OpenGLContext::deactivateCurrentContext();
  244. }
  245. private:
  246. bool active = false;
  247. };
  248. enum class RenderStatus
  249. {
  250. nominal,
  251. messageThreadAborted,
  252. noWork,
  253. };
  254. RenderStatus renderFrame (MessageManager::Lock& mmLock)
  255. {
  256. if (! isFlagSet (state, StateFlags::initialised))
  257. {
  258. switch (initialiseOnThread())
  259. {
  260. case InitResult::fatal:
  261. case InitResult::retry: return RenderStatus::noWork;
  262. case InitResult::success: break;
  263. }
  264. }
  265. state |= StateFlags::initialised;
  266. #if JUCE_IOS
  267. if (backgroundProcessCheck.isBackgroundProcess())
  268. return RenderStatus::noWork;
  269. #endif
  270. std::optional<MessageManager::Lock::ScopedTryLockType> scopedLock;
  271. ScopedContextActivator contextActivator;
  272. const auto stateToUse = state.fetch_and (StateFlags::persistent);
  273. if (! isFlagSet (stateToUse, StateFlags::pendingRender) && ! context.continuousRepaint)
  274. return RenderStatus::noWork;
  275. const auto isUpdating = isFlagSet (stateToUse, StateFlags::paintComponents);
  276. if (context.renderComponents && isUpdating)
  277. {
  278. bool abortScope = false;
  279. // If we early-exit here, we need to restore these flags so that the render is
  280. // attempted again in the next time slice.
  281. const ScopeGuard scope { [&] { if (! abortScope) state |= stateToUse; } };
  282. // This avoids hogging the message thread when doing intensive rendering.
  283. std::this_thread::sleep_until (lastMMLockReleaseTime + std::chrono::milliseconds { 2 });
  284. if (renderThread->isListChanging())
  285. return RenderStatus::messageThreadAborted;
  286. doWorkWhileWaitingForLock (contextActivator);
  287. scopedLock.emplace (mmLock);
  288. // If we can't get the lock here, it's probably because a context has been removed
  289. // on the main thread.
  290. // We return, just in case this renderer needs to be removed from the rendering thread.
  291. // If another renderer is being removed instead, then we should be able to get the lock
  292. // next time round.
  293. if (! scopedLock->isLocked())
  294. return RenderStatus::messageThreadAborted;
  295. abortScope = true;
  296. }
  297. if (! contextActivator.activate (context))
  298. return RenderStatus::noWork;
  299. {
  300. NativeContext::Locker locker (*nativeContext);
  301. JUCE_CHECK_OPENGL_ERROR
  302. doWorkWhileWaitingForLock (contextActivator);
  303. const auto currentAreaAndScale = areaAndScale.get();
  304. const auto viewportArea = currentAreaAndScale.area;
  305. if (context.renderer != nullptr)
  306. {
  307. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  308. context.currentRenderScale = currentAreaAndScale.scale;
  309. context.renderer->renderOpenGL();
  310. clearGLError();
  311. bindVertexArray();
  312. }
  313. if (context.renderComponents)
  314. {
  315. if (isUpdating)
  316. {
  317. paintComponent (currentAreaAndScale);
  318. if (! isFlagSet (state, StateFlags::initialised))
  319. return RenderStatus::noWork;
  320. scopedLock.reset();
  321. lastMMLockReleaseTime = std::chrono::steady_clock::now();
  322. }
  323. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  324. drawComponentBuffer();
  325. }
  326. }
  327. nativeContext->swapBuffers();
  328. return RenderStatus::nominal;
  329. }
  330. void updateViewportSize()
  331. {
  332. JUCE_ASSERT_MESSAGE_THREAD
  333. if (auto* peer = component.getPeer())
  334. {
  335. #if JUCE_MAC
  336. updateScreen();
  337. const auto displayScale = Desktop::getInstance().getGlobalScaleFactor() * [this]
  338. {
  339. if (auto* view = getCurrentView())
  340. {
  341. if ([view respondsToSelector: @selector (backingScaleFactor)])
  342. return [(id) view backingScaleFactor];
  343. if (auto* window = [view window])
  344. return [window backingScaleFactor];
  345. }
  346. return areaAndScale.get().scale;
  347. }();
  348. #else
  349. const auto displayScale = Desktop::getInstance().getDisplays()
  350. .getDisplayForRect (component.getTopLevelComponent()
  351. ->getScreenBounds())
  352. ->scale;
  353. #endif
  354. const auto localBounds = component.getLocalBounds();
  355. const auto newArea = peer->getComponent().getLocalArea (&component, localBounds).withZeroOrigin() * displayScale;
  356. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  357. // Some hosts (Pro Tools 2022.7) do not take the current DPI into account when sizing
  358. // plugin editor windows. Instead of querying the OS for the DPI of the editor window,
  359. // we approximate based on the physical size of the window that was actually provided
  360. // for the context to draw into. This may break if the OpenGL context's component is
  361. // scaled differently in its width and height - but in this case, a single scale factor
  362. // isn't that helpful anyway.
  363. const auto newScale = (float) newArea.getWidth() / (float) localBounds.getWidth();
  364. #else
  365. const auto newScale = (float) displayScale;
  366. #endif
  367. areaAndScale.set ({ newArea, newScale }, [&]
  368. {
  369. // Transform is only accessed when the message manager is locked
  370. transform = AffineTransform::scale ((float) newArea.getWidth() / (float) localBounds.getWidth(),
  371. (float) newArea.getHeight() / (float) localBounds.getHeight());
  372. nativeContext->updateWindowPosition (peer->getAreaCoveredBy (component));
  373. invalidateAll();
  374. });
  375. }
  376. }
  377. void bindVertexArray() noexcept
  378. {
  379. if (shouldUseCustomVAO())
  380. if (vertexArrayObject != 0)
  381. context.extensions.glBindVertexArray (vertexArrayObject);
  382. }
  383. void checkViewportBounds()
  384. {
  385. auto screenBounds = component.getTopLevelComponent()->getScreenBounds();
  386. if (lastScreenBounds != screenBounds)
  387. {
  388. updateViewportSize();
  389. lastScreenBounds = screenBounds;
  390. }
  391. }
  392. void paintComponent (const AreaAndScale& currentAreaAndScale)
  393. {
  394. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  395. // you mustn't set your own cached image object when attaching a GL context!
  396. jassert (get (component) == this);
  397. if (! ensureFrameBufferSize (currentAreaAndScale.area))
  398. return;
  399. RectangleList<int> invalid (currentAreaAndScale.area);
  400. invalid.subtract (validArea);
  401. validArea = currentAreaAndScale.area;
  402. if (! invalid.isEmpty())
  403. {
  404. clearRegionInFrameBuffer (invalid);
  405. {
  406. std::unique_ptr<LowLevelGraphicsContext> g (createOpenGLGraphicsContext (context, cachedImageFrameBuffer));
  407. g->clipToRectangleList (invalid);
  408. g->addTransform (transform);
  409. paintOwner (*g);
  410. JUCE_CHECK_OPENGL_ERROR
  411. }
  412. if (! context.isActive())
  413. context.makeActive();
  414. }
  415. JUCE_CHECK_OPENGL_ERROR
  416. }
  417. void drawComponentBuffer()
  418. {
  419. if (contextRequiresTexture2DEnableDisable())
  420. glEnable (GL_TEXTURE_2D);
  421. #if JUCE_WINDOWS
  422. // some stupidly old drivers are missing this function, so try to at least avoid a crash here,
  423. // but if you hit this assertion you may want to have your own version check before using the
  424. // component rendering stuff on such old drivers.
  425. jassert (context.extensions.glActiveTexture != nullptr);
  426. if (context.extensions.glActiveTexture != nullptr)
  427. #endif
  428. {
  429. context.extensions.glActiveTexture (GL_TEXTURE0);
  430. }
  431. glBindTexture (GL_TEXTURE_2D, cachedImageFrameBuffer.getTextureID());
  432. bindVertexArray();
  433. const Rectangle<int> cacheBounds (cachedImageFrameBuffer.getWidth(), cachedImageFrameBuffer.getHeight());
  434. context.copyTexture (cacheBounds, cacheBounds, cacheBounds.getWidth(), cacheBounds.getHeight(), false);
  435. glBindTexture (GL_TEXTURE_2D, 0);
  436. JUCE_CHECK_OPENGL_ERROR
  437. }
  438. void paintOwner (LowLevelGraphicsContext& llgc)
  439. {
  440. Graphics g (llgc);
  441. #if JUCE_ENABLE_REPAINT_DEBUGGING
  442. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  443. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  444. #endif
  445. {
  446. g.saveState();
  447. }
  448. #endif
  449. JUCE_TRY
  450. {
  451. component.paintEntireComponent (g, false);
  452. }
  453. JUCE_CATCH_EXCEPTION
  454. #if JUCE_ENABLE_REPAINT_DEBUGGING
  455. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  456. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  457. #endif
  458. {
  459. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  460. // clearly when things are being repainted.
  461. g.restoreState();
  462. static Random rng;
  463. g.fillAll (Colour ((uint8) rng.nextInt (255),
  464. (uint8) rng.nextInt (255),
  465. (uint8) rng.nextInt (255),
  466. (uint8) 0x50));
  467. }
  468. #endif
  469. }
  470. void handleResize()
  471. {
  472. updateViewportSize();
  473. #if JUCE_MAC
  474. if (isFlagSet (state, StateFlags::initialised))
  475. {
  476. [nativeContext->view update];
  477. // We're already on the message thread, no need to lock it again.
  478. MessageManager::Lock mml;
  479. renderFrame (mml);
  480. }
  481. #endif
  482. }
  483. //==============================================================================
  484. InitResult initialiseOnThread()
  485. {
  486. // On android, this can get called twice, so drop any previous state.
  487. associatedObjectNames.clear();
  488. associatedObjects.clear();
  489. cachedImageFrameBuffer.release();
  490. context.makeActive();
  491. if (const auto nativeResult = nativeContext->initialiseOnRenderThread (context); nativeResult != InitResult::success)
  492. return nativeResult;
  493. #if JUCE_ANDROID
  494. // On android the context may be created in initialiseOnRenderThread
  495. // and we therefore need to call makeActive again
  496. context.makeActive();
  497. #endif
  498. gl::loadFunctions();
  499. if (shouldUseCustomVAO())
  500. {
  501. context.extensions.glGenVertexArrays (1, &vertexArrayObject);
  502. bindVertexArray();
  503. }
  504. #if JUCE_DEBUG
  505. if (getOpenGLVersion() >= Version { 4, 3 } && glDebugMessageCallback != nullptr)
  506. {
  507. glEnable (GL_DEBUG_OUTPUT);
  508. glDebugMessageCallback ([] (GLenum type, GLenum, GLuint, GLenum severity, GLsizei, const GLchar* message, const void*)
  509. {
  510. // This may reiterate issues that are also flagged by JUCE_CHECK_OPENGL_ERROR.
  511. // The advantage of this callback is that it will catch *all* errors, even if we
  512. // forget to check manually.
  513. DBG ("OpenGL DBG message: " << message);
  514. jassertquiet (type != GL_DEBUG_TYPE_ERROR && severity != GL_DEBUG_SEVERITY_HIGH);
  515. }, nullptr);
  516. }
  517. #endif
  518. const auto currentViewportArea = areaAndScale.get().area;
  519. glViewport (0, 0, currentViewportArea.getWidth(), currentViewportArea.getHeight());
  520. nativeContext->setSwapInterval (1);
  521. #if ! JUCE_OPENGL_ES
  522. JUCE_CHECK_OPENGL_ERROR
  523. shadersAvailable = OpenGLShaderProgram::getLanguageVersion() > 0;
  524. clearGLError();
  525. #endif
  526. textureNpotSupported = contextHasTextureNpotFeature();
  527. if (context.renderer != nullptr)
  528. context.renderer->newOpenGLContextCreated();
  529. return InitResult::success;
  530. }
  531. void shutdownOnThread()
  532. {
  533. if (context.renderer != nullptr)
  534. context.renderer->openGLContextClosing();
  535. if (vertexArrayObject != 0)
  536. context.extensions.glDeleteVertexArrays (1, &vertexArrayObject);
  537. associatedObjectNames.clear();
  538. associatedObjects.clear();
  539. cachedImageFrameBuffer.release();
  540. nativeContext->shutdownOnRenderThread();
  541. }
  542. /* Returns true if the context requires a non-zero vertex array object (VAO) to be bound.
  543. If the context is a compatibility context, we can just pretend that VAOs don't exist,
  544. and use the default VAO all the time instead. This provides a more consistent experience
  545. in user code, which might make calls (like glVertexPointer()) that only work when VAO 0 is
  546. bound in OpenGL 3.2+.
  547. */
  548. bool shouldUseCustomVAO() const
  549. {
  550. #if JUCE_OPENGL_ES
  551. return false;
  552. #else
  553. clearGLError();
  554. GLint mask = 0;
  555. glGetIntegerv (GL_CONTEXT_PROFILE_MASK, &mask);
  556. // The context isn't aware of the profile mask, so it pre-dates the core profile
  557. if (glGetError() == GL_INVALID_ENUM)
  558. return false;
  559. // Also assumes a compatibility profile if the mask is completely empty for some reason
  560. return (mask & (GLint) GL_CONTEXT_CORE_PROFILE_BIT) != 0;
  561. #endif
  562. }
  563. //==============================================================================
  564. struct BlockingWorker : public OpenGLContext::AsyncWorker
  565. {
  566. BlockingWorker (OpenGLContext::AsyncWorker::Ptr && workerToUse)
  567. : originalWorker (std::move (workerToUse))
  568. {}
  569. void operator() (OpenGLContext& calleeContext)
  570. {
  571. if (originalWorker != nullptr)
  572. (*originalWorker) (calleeContext);
  573. finishedSignal.signal();
  574. }
  575. void block() noexcept { finishedSignal.wait(); }
  576. OpenGLContext::AsyncWorker::Ptr originalWorker;
  577. WaitableEvent finishedSignal;
  578. };
  579. void doWorkWhileWaitingForLock (ScopedContextActivator& contextActivator)
  580. {
  581. while (const auto work = workQueue.removeAndReturn (0))
  582. {
  583. if (renderThread->isListChanging() || ! contextActivator.activate (context))
  584. break;
  585. NativeContext::Locker locker (*nativeContext);
  586. (*work) (context);
  587. clearGLError();
  588. }
  589. }
  590. void execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock)
  591. {
  592. if (! isFlagSet (state, StateFlags::pendingDestruction))
  593. {
  594. if (shouldBlock)
  595. {
  596. auto blocker = new BlockingWorker (std::move (workerToUse));
  597. OpenGLContext::AsyncWorker::Ptr worker (*blocker);
  598. workQueue.add (worker);
  599. renderThread->abortLock();
  600. context.triggerRepaint();
  601. blocker->block();
  602. }
  603. else
  604. {
  605. workQueue.add (std::move (workerToUse));
  606. renderThread->abortLock();
  607. context.triggerRepaint();
  608. }
  609. }
  610. else
  611. {
  612. jassertfalse; // you called execute AFTER you detached your OpenGLContext
  613. }
  614. }
  615. //==============================================================================
  616. static CachedImage* get (Component& c) noexcept
  617. {
  618. return dynamic_cast<CachedImage*> (c.getCachedComponentImage());
  619. }
  620. class RenderThread
  621. {
  622. public:
  623. RenderThread() = default;
  624. ~RenderThread()
  625. {
  626. flags.setDestructing();
  627. thread.join();
  628. }
  629. void add (CachedImage* x)
  630. {
  631. const std::scoped_lock lock { listMutex };
  632. images.push_back (x);
  633. }
  634. void remove (CachedImage* x)
  635. {
  636. JUCE_ASSERT_MESSAGE_THREAD;
  637. flags.setSafe (false);
  638. abortLock();
  639. {
  640. const std::scoped_lock lock { callbackMutex, listMutex };
  641. images.remove (x);
  642. }
  643. flags.setSafe (true);
  644. }
  645. bool contains (CachedImage* x)
  646. {
  647. const std::scoped_lock lock { listMutex };
  648. return std::find (images.cbegin(), images.cend(), x) != images.cend();
  649. }
  650. void triggerRepaint() { flags.setRenderRequested(); }
  651. void abortLock() { messageManagerLock.abort(); }
  652. bool isListChanging() { return ! flags.isSafe(); }
  653. private:
  654. RenderStatus renderAll()
  655. {
  656. auto result = RenderStatus::noWork;
  657. const std::scoped_lock lock { callbackMutex, listMutex };
  658. for (auto* x : images)
  659. {
  660. listMutex.unlock();
  661. const ScopeGuard scope { [&] { listMutex.lock(); } };
  662. const auto status = x->renderFrame (messageManagerLock);
  663. switch (status)
  664. {
  665. case RenderStatus::noWork: break;
  666. case RenderStatus::nominal: result = RenderStatus::nominal; break;
  667. case RenderStatus::messageThreadAborted: return RenderStatus::messageThreadAborted;
  668. }
  669. }
  670. return result;
  671. }
  672. /* Allows the main thread to communicate changes to the render thread.
  673. When the render thread needs to change in some way (asked to resume rendering,
  674. a renderer is added/removed, or the thread needs to stop prior to destruction),
  675. the main thread can set the appropriate flag on this structure. The render thread
  676. will call waitForWork() repeatedly, pausing when the render thread has no work to do,
  677. and resuming when requested by the main thread.
  678. */
  679. class Flags
  680. {
  681. public:
  682. void setDestructing() { update ([] (auto& f) { f |= destructorCalled; }); }
  683. void setRenderRequested() { update ([] (auto& f) { f |= renderRequested; }); }
  684. void setSafe (const bool safe)
  685. {
  686. update ([safe] (auto& f)
  687. {
  688. if (safe)
  689. f |= listSafe;
  690. else
  691. f &= ~listSafe;
  692. });
  693. }
  694. bool isSafe()
  695. {
  696. const std::scoped_lock lock { mutex };
  697. return (flags & listSafe) != 0;
  698. }
  699. /* Blocks until the 'safe' flag is set, and at least one other flag is set.
  700. After returning, the renderRequested flag will be unset.
  701. Returns true if rendering should continue.
  702. */
  703. bool waitForWork (bool requestRender)
  704. {
  705. std::unique_lock lock { mutex };
  706. flags |= (requestRender ? renderRequested : 0);
  707. condvar.wait (lock, [this] { return flags > listSafe; });
  708. flags &= ~renderRequested;
  709. return ((flags & destructorCalled) == 0);
  710. }
  711. private:
  712. template <typename Fn>
  713. void update (Fn fn)
  714. {
  715. {
  716. const std::scoped_lock lock { mutex };
  717. fn (flags);
  718. }
  719. condvar.notify_one();
  720. }
  721. enum
  722. {
  723. renderRequested = 1 << 0,
  724. destructorCalled = 1 << 1,
  725. listSafe = 1 << 2
  726. };
  727. std::mutex mutex;
  728. std::condition_variable condvar;
  729. int flags = listSafe;
  730. };
  731. MessageManager::Lock messageManagerLock;
  732. std::mutex listMutex, callbackMutex;
  733. std::list<CachedImage*> images;
  734. Flags flags;
  735. std::thread thread { [this]
  736. {
  737. Thread::setCurrentThreadName ("OpenGL Renderer");
  738. while (flags.waitForWork (renderAll() != RenderStatus::noWork)) {}
  739. } };
  740. };
  741. //==============================================================================
  742. friend class NativeContext;
  743. std::unique_ptr<NativeContext> nativeContext;
  744. OpenGLContext& context;
  745. Component& component;
  746. SharedResourcePointer<RenderThread> renderThread;
  747. OpenGLFrameBuffer cachedImageFrameBuffer;
  748. RectangleList<int> validArea;
  749. Rectangle<int> lastScreenBounds;
  750. AffineTransform transform;
  751. GLuint vertexArrayObject = 0;
  752. LockedAreaAndScale areaAndScale;
  753. StringArray associatedObjectNames;
  754. ReferenceCountedArray<ReferenceCountedObject> associatedObjects;
  755. WaitableEvent canPaintNowFlag, finishedPaintingFlag;
  756. #if JUCE_OPENGL_ES
  757. bool shadersAvailable = true;
  758. #else
  759. bool shadersAvailable = false;
  760. #endif
  761. bool textureNpotSupported = false;
  762. std::chrono::steady_clock::time_point lastMMLockReleaseTime{};
  763. #if JUCE_MAC
  764. NSView* getCurrentView() const
  765. {
  766. JUCE_ASSERT_MESSAGE_THREAD;
  767. if (auto* peer = component.getPeer())
  768. return static_cast<NSView*> (peer->getNativeHandle());
  769. return nullptr;
  770. }
  771. NSWindow* getCurrentWindow() const
  772. {
  773. JUCE_ASSERT_MESSAGE_THREAD;
  774. if (auto* view = getCurrentView())
  775. return [view window];
  776. return nullptr;
  777. }
  778. NSScreen* getCurrentScreen() const
  779. {
  780. JUCE_ASSERT_MESSAGE_THREAD;
  781. if (auto* window = getCurrentWindow())
  782. return [window screen];
  783. return nullptr;
  784. }
  785. void updateScreen()
  786. {
  787. const auto screen = getCurrentScreen();
  788. const auto display = ScopedDisplayLink::getDisplayIdForScreen (screen);
  789. if (lastDisplay.exchange (display) == display)
  790. return;
  791. const auto newRefreshPeriod = sharedDisplayLinks->getNominalVideoRefreshPeriodSForScreen (display);
  792. if (newRefreshPeriod != 0.0 && std::exchange (refreshPeriod, newRefreshPeriod) != newRefreshPeriod)
  793. nativeContext->setNominalVideoRefreshPeriodS (newRefreshPeriod);
  794. updateColourSpace();
  795. }
  796. void updateColourSpace()
  797. {
  798. if (auto* view = nativeContext->getNSView())
  799. if (auto* window = [view window])
  800. [window setColorSpace: [NSColorSpace sRGBColorSpace]];
  801. }
  802. std::atomic<CGDirectDisplayID> lastDisplay { 0 };
  803. double refreshPeriod = 0.0;
  804. FunctionNotificationCenterObserver observer { NSWindowDidChangeScreenNotification,
  805. getCurrentWindow(),
  806. [this] { updateScreen(); } };
  807. // Note: the NSViewComponentPeer also has a SharedResourcePointer<PerScreenDisplayLinks> to
  808. // avoid unnecessarily duplicating display-link threads.
  809. SharedResourcePointer<PerScreenDisplayLinks> sharedDisplayLinks;
  810. #endif
  811. enum StateFlags
  812. {
  813. pendingRender = 1 << 0,
  814. paintComponents = 1 << 1,
  815. pendingDestruction = 1 << 2,
  816. initialised = 1 << 3,
  817. // Flags that may change state after each frame
  818. transient = pendingRender | paintComponents,
  819. // Flags that should retain their state after each frame
  820. persistent = initialised | pendingDestruction
  821. };
  822. std::atomic<int> state { 0 };
  823. ReferenceCountedArray<OpenGLContext::AsyncWorker, CriticalSection> workQueue;
  824. #if JUCE_IOS
  825. iOSBackgroundProcessCheck backgroundProcessCheck;
  826. #endif
  827. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedImage)
  828. };
  829. //==============================================================================
  830. class OpenGLContext::Attachment : public ComponentMovementWatcher,
  831. private Timer
  832. {
  833. public:
  834. Attachment (OpenGLContext& c, Component& comp)
  835. : ComponentMovementWatcher (&comp), context (c)
  836. {
  837. if (canBeAttached (comp))
  838. attach();
  839. }
  840. ~Attachment() override
  841. {
  842. detach();
  843. }
  844. void detach()
  845. {
  846. auto& comp = *getComponent();
  847. stop();
  848. comp.setCachedComponentImage (nullptr);
  849. context.nativeContext = nullptr;
  850. }
  851. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
  852. {
  853. auto& comp = *getComponent();
  854. if (isAttached (comp) != canBeAttached (comp))
  855. componentVisibilityChanged();
  856. if (comp.getWidth() > 0 && comp.getHeight() > 0
  857. && context.nativeContext != nullptr)
  858. {
  859. if (auto* c = CachedImage::get (comp))
  860. c->handleResize();
  861. if (auto* peer = comp.getTopLevelComponent()->getPeer())
  862. context.nativeContext->updateWindowPosition (peer->getAreaCoveredBy (comp));
  863. }
  864. }
  865. using ComponentMovementWatcher::componentMovedOrResized;
  866. void componentPeerChanged() override
  867. {
  868. detach();
  869. componentVisibilityChanged();
  870. }
  871. void componentVisibilityChanged() override
  872. {
  873. auto& comp = *getComponent();
  874. if (canBeAttached (comp))
  875. {
  876. if (isAttached (comp))
  877. comp.repaint(); // (needed when windows are un-minimised)
  878. else
  879. attach();
  880. }
  881. else
  882. {
  883. detach();
  884. }
  885. }
  886. using ComponentMovementWatcher::componentVisibilityChanged;
  887. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  888. void componentBeingDeleted (Component& c) override
  889. {
  890. /* You must call detach() or delete your OpenGLContext to remove it
  891. from a component BEFORE deleting the component that it is using!
  892. */
  893. jassertfalse;
  894. ComponentMovementWatcher::componentBeingDeleted (c);
  895. }
  896. #endif
  897. private:
  898. OpenGLContext& context;
  899. bool canBeAttached (const Component& comp) noexcept
  900. {
  901. return (! context.overrideCanAttach) && comp.getWidth() > 0 && comp.getHeight() > 0 && isShowingOrMinimised (comp);
  902. }
  903. static bool isShowingOrMinimised (const Component& c)
  904. {
  905. if (! c.isVisible())
  906. return false;
  907. if (auto* p = c.getParentComponent())
  908. return isShowingOrMinimised (*p);
  909. return c.getPeer() != nullptr;
  910. }
  911. static bool isAttached (const Component& comp) noexcept
  912. {
  913. return comp.getCachedComponentImage() != nullptr;
  914. }
  915. void attach()
  916. {
  917. auto& comp = *getComponent();
  918. auto* newCachedImage = new CachedImage (context, comp,
  919. context.openGLPixelFormat,
  920. context.contextToShareWith);
  921. comp.setCachedComponentImage (newCachedImage);
  922. start();
  923. }
  924. void stop()
  925. {
  926. stopTimer();
  927. auto& comp = *getComponent();
  928. #if JUCE_MAC
  929. [[(NSView*) comp.getWindowHandle() window] disableScreenUpdatesUntilFlush];
  930. #endif
  931. if (auto* oldCachedImage = CachedImage::get (comp))
  932. oldCachedImage->stop(); // (must stop this before detaching it from the component)
  933. }
  934. void start()
  935. {
  936. auto& comp = *getComponent();
  937. if (auto* cachedImage = CachedImage::get (comp))
  938. {
  939. cachedImage->start(); // (must wait until this is attached before starting its thread)
  940. cachedImage->updateViewportSize();
  941. startTimer (400);
  942. }
  943. }
  944. void timerCallback() override
  945. {
  946. if (auto* cachedImage = CachedImage::get (*getComponent()))
  947. cachedImage->checkViewportBounds();
  948. }
  949. };
  950. //==============================================================================
  951. OpenGLContext::OpenGLContext()
  952. {
  953. }
  954. OpenGLContext::~OpenGLContext()
  955. {
  956. detach();
  957. }
  958. void OpenGLContext::setRenderer (OpenGLRenderer* rendererToUse) noexcept
  959. {
  960. // This method must not be called when the context has already been attached!
  961. // Call it before attaching your context, or use detach() first, before calling this!
  962. jassert (nativeContext == nullptr);
  963. renderer = rendererToUse;
  964. }
  965. void OpenGLContext::setComponentPaintingEnabled (bool shouldPaintComponent) noexcept
  966. {
  967. // This method must not be called when the context has already been attached!
  968. // Call it before attaching your context, or use detach() first, before calling this!
  969. jassert (nativeContext == nullptr);
  970. renderComponents = shouldPaintComponent;
  971. }
  972. void OpenGLContext::setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept
  973. {
  974. continuousRepaint = shouldContinuouslyRepaint;
  975. #if JUCE_MAC
  976. if (auto* component = getTargetComponent())
  977. {
  978. detach();
  979. attachment.reset (new Attachment (*this, *component));
  980. }
  981. #endif
  982. triggerRepaint();
  983. }
  984. void OpenGLContext::setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept
  985. {
  986. // This method must not be called when the context has already been attached!
  987. // Call it before attaching your context, or use detach() first, before calling this!
  988. jassert (nativeContext == nullptr);
  989. openGLPixelFormat = preferredPixelFormat;
  990. }
  991. void OpenGLContext::setTextureMagnificationFilter (OpenGLContext::TextureMagnificationFilter magFilterMode) noexcept
  992. {
  993. texMagFilter = magFilterMode;
  994. }
  995. void OpenGLContext::setNativeSharedContext (void* nativeContextToShareWith) noexcept
  996. {
  997. // This method must not be called when the context has already been attached!
  998. // Call it before attaching your context, or use detach() first, before calling this!
  999. jassert (nativeContext == nullptr);
  1000. contextToShareWith = nativeContextToShareWith;
  1001. }
  1002. void OpenGLContext::setMultisamplingEnabled (bool b) noexcept
  1003. {
  1004. // This method must not be called when the context has already been attached!
  1005. // Call it before attaching your context, or use detach() first, before calling this!
  1006. jassert (nativeContext == nullptr);
  1007. useMultisampling = b;
  1008. }
  1009. void OpenGLContext::setOpenGLVersionRequired (OpenGLVersion v) noexcept
  1010. {
  1011. versionRequired = v;
  1012. }
  1013. void OpenGLContext::attachTo (Component& component)
  1014. {
  1015. component.repaint();
  1016. if (getTargetComponent() != &component)
  1017. {
  1018. detach();
  1019. attachment.reset (new Attachment (*this, component));
  1020. }
  1021. }
  1022. void OpenGLContext::detach()
  1023. {
  1024. if (auto* a = attachment.get())
  1025. {
  1026. a->detach(); // must detach before nulling our pointer
  1027. attachment.reset();
  1028. }
  1029. nativeContext = nullptr;
  1030. }
  1031. bool OpenGLContext::isAttached() const noexcept
  1032. {
  1033. return nativeContext != nullptr;
  1034. }
  1035. Component* OpenGLContext::getTargetComponent() const noexcept
  1036. {
  1037. return attachment != nullptr ? attachment->getComponent() : nullptr;
  1038. }
  1039. OpenGLContext* OpenGLContext::getContextAttachedTo (Component& c) noexcept
  1040. {
  1041. if (auto* ci = CachedImage::get (c))
  1042. return &(ci->context);
  1043. return nullptr;
  1044. }
  1045. static ThreadLocalValue<OpenGLContext*> currentThreadActiveContext;
  1046. OpenGLContext* OpenGLContext::getCurrentContext()
  1047. {
  1048. return currentThreadActiveContext.get();
  1049. }
  1050. bool OpenGLContext::makeActive() const noexcept
  1051. {
  1052. auto& current = currentThreadActiveContext.get();
  1053. if (nativeContext != nullptr && nativeContext->makeActive())
  1054. {
  1055. current = const_cast<OpenGLContext*> (this);
  1056. return true;
  1057. }
  1058. current = nullptr;
  1059. return false;
  1060. }
  1061. bool OpenGLContext::isActive() const noexcept
  1062. {
  1063. return nativeContext != nullptr && nativeContext->isActive();
  1064. }
  1065. void OpenGLContext::deactivateCurrentContext()
  1066. {
  1067. NativeContext::deactivateCurrentContext();
  1068. currentThreadActiveContext.get() = nullptr;
  1069. }
  1070. void OpenGLContext::triggerRepaint()
  1071. {
  1072. if (auto* cachedImage = getCachedImage())
  1073. cachedImage->triggerRepaint();
  1074. }
  1075. void OpenGLContext::swapBuffers()
  1076. {
  1077. if (nativeContext != nullptr)
  1078. nativeContext->swapBuffers();
  1079. }
  1080. unsigned int OpenGLContext::getFrameBufferID() const noexcept
  1081. {
  1082. return nativeContext != nullptr ? nativeContext->getFrameBufferID() : 0;
  1083. }
  1084. bool OpenGLContext::setSwapInterval (int numFramesPerSwap)
  1085. {
  1086. return nativeContext != nullptr && nativeContext->setSwapInterval (numFramesPerSwap);
  1087. }
  1088. int OpenGLContext::getSwapInterval() const
  1089. {
  1090. return nativeContext != nullptr ? nativeContext->getSwapInterval() : 0;
  1091. }
  1092. void* OpenGLContext::getRawContext() const noexcept
  1093. {
  1094. return nativeContext != nullptr ? nativeContext->getRawContext() : nullptr;
  1095. }
  1096. OpenGLContext::CachedImage* OpenGLContext::getCachedImage() const noexcept
  1097. {
  1098. if (auto* comp = getTargetComponent())
  1099. return CachedImage::get (*comp);
  1100. return nullptr;
  1101. }
  1102. bool OpenGLContext::areShadersAvailable() const
  1103. {
  1104. auto* c = getCachedImage();
  1105. return c != nullptr && c->shadersAvailable;
  1106. }
  1107. bool OpenGLContext::isTextureNpotSupported() const
  1108. {
  1109. auto* c = getCachedImage();
  1110. return c != nullptr && c->textureNpotSupported;
  1111. }
  1112. ReferenceCountedObject* OpenGLContext::getAssociatedObject (const char* name) const
  1113. {
  1114. jassert (name != nullptr);
  1115. auto* c = getCachedImage();
  1116. // This method must only be called from an openGL rendering callback.
  1117. jassert (c != nullptr && nativeContext != nullptr);
  1118. jassert (getCurrentContext() != nullptr);
  1119. auto index = c->associatedObjectNames.indexOf (name);
  1120. return index >= 0 ? c->associatedObjects.getUnchecked (index).get() : nullptr;
  1121. }
  1122. void OpenGLContext::setAssociatedObject (const char* name, ReferenceCountedObject* newObject)
  1123. {
  1124. jassert (name != nullptr);
  1125. if (auto* c = getCachedImage())
  1126. {
  1127. // This method must only be called from an openGL rendering callback.
  1128. jassert (nativeContext != nullptr);
  1129. jassert (getCurrentContext() != nullptr);
  1130. const int index = c->associatedObjectNames.indexOf (name);
  1131. if (index >= 0)
  1132. {
  1133. if (newObject != nullptr)
  1134. {
  1135. c->associatedObjects.set (index, newObject);
  1136. }
  1137. else
  1138. {
  1139. c->associatedObjectNames.remove (index);
  1140. c->associatedObjects.remove (index);
  1141. }
  1142. }
  1143. else if (newObject != nullptr)
  1144. {
  1145. c->associatedObjectNames.add (name);
  1146. c->associatedObjects.add (newObject);
  1147. }
  1148. }
  1149. }
  1150. void OpenGLContext::setImageCacheSize (size_t newSize) noexcept { imageCacheMaxSize = newSize; }
  1151. size_t OpenGLContext::getImageCacheSize() const noexcept { return imageCacheMaxSize; }
  1152. void OpenGLContext::execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock)
  1153. {
  1154. if (auto* c = getCachedImage())
  1155. c->execute (std::move (workerToUse), shouldBlock);
  1156. else
  1157. jassertfalse; // You must have attached the context to a component
  1158. }
  1159. //==============================================================================
  1160. struct DepthTestDisabler
  1161. {
  1162. DepthTestDisabler() noexcept
  1163. {
  1164. glGetBooleanv (GL_DEPTH_TEST, &wasEnabled);
  1165. if (wasEnabled)
  1166. glDisable (GL_DEPTH_TEST);
  1167. }
  1168. ~DepthTestDisabler() noexcept
  1169. {
  1170. if (wasEnabled)
  1171. glEnable (GL_DEPTH_TEST);
  1172. }
  1173. GLboolean wasEnabled;
  1174. };
  1175. //==============================================================================
  1176. void OpenGLContext::copyTexture (const Rectangle<int>& targetClipArea,
  1177. const Rectangle<int>& anchorPosAndTextureSize,
  1178. const int contextWidth, const int contextHeight,
  1179. bool flippedVertically)
  1180. {
  1181. if (contextWidth <= 0 || contextHeight <= 0)
  1182. return;
  1183. JUCE_CHECK_OPENGL_ERROR
  1184. glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  1185. glEnable (GL_BLEND);
  1186. DepthTestDisabler depthDisabler;
  1187. if (areShadersAvailable())
  1188. {
  1189. struct OverlayShaderProgram : public ReferenceCountedObject
  1190. {
  1191. OverlayShaderProgram (OpenGLContext& context)
  1192. : program (context), params (program)
  1193. {}
  1194. static const OverlayShaderProgram& select (OpenGLContext& context)
  1195. {
  1196. static const char programValueID[] = "juceGLComponentOverlayShader";
  1197. OverlayShaderProgram* program = static_cast<OverlayShaderProgram*> (context.getAssociatedObject (programValueID));
  1198. if (program == nullptr)
  1199. {
  1200. program = new OverlayShaderProgram (context);
  1201. context.setAssociatedObject (programValueID, program);
  1202. }
  1203. program->program.use();
  1204. return *program;
  1205. }
  1206. struct BuiltProgram : public OpenGLShaderProgram
  1207. {
  1208. explicit BuiltProgram (OpenGLContext& ctx)
  1209. : OpenGLShaderProgram (ctx)
  1210. {
  1211. addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (
  1212. "attribute " JUCE_HIGHP " vec2 position;"
  1213. "uniform " JUCE_HIGHP " vec2 screenSize;"
  1214. "uniform " JUCE_HIGHP " float textureBounds[4];"
  1215. "uniform " JUCE_HIGHP " vec2 vOffsetAndScale;"
  1216. "varying " JUCE_HIGHP " vec2 texturePos;"
  1217. "void main()"
  1218. "{"
  1219. JUCE_HIGHP " vec2 scaled = position / (0.5 * screenSize.xy);"
  1220. "gl_Position = vec4 (scaled.x - 1.0, 1.0 - scaled.y, 0, 1.0);"
  1221. "texturePos = (position - vec2 (textureBounds[0], textureBounds[1])) / vec2 (textureBounds[2], textureBounds[3]);"
  1222. "texturePos = vec2 (texturePos.x, vOffsetAndScale.x + vOffsetAndScale.y * texturePos.y);"
  1223. "}"));
  1224. addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (
  1225. "uniform sampler2D imageTexture;"
  1226. "varying " JUCE_HIGHP " vec2 texturePos;"
  1227. "void main()"
  1228. "{"
  1229. "gl_FragColor = texture2D (imageTexture, texturePos);"
  1230. "}"));
  1231. link();
  1232. }
  1233. };
  1234. struct Params
  1235. {
  1236. Params (OpenGLShaderProgram& prog)
  1237. : positionAttribute (prog, "position"),
  1238. screenSize (prog, "screenSize"),
  1239. imageTexture (prog, "imageTexture"),
  1240. textureBounds (prog, "textureBounds"),
  1241. vOffsetAndScale (prog, "vOffsetAndScale")
  1242. {}
  1243. void set (const float targetWidth, const float targetHeight, const Rectangle<float>& bounds, bool flipVertically) const
  1244. {
  1245. const GLfloat m[] = { bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight() };
  1246. textureBounds.set (m, 4);
  1247. imageTexture.set (0);
  1248. screenSize.set (targetWidth, targetHeight);
  1249. vOffsetAndScale.set (flipVertically ? 0.0f : 1.0f,
  1250. flipVertically ? 1.0f : -1.0f);
  1251. }
  1252. OpenGLShaderProgram::Attribute positionAttribute;
  1253. OpenGLShaderProgram::Uniform screenSize, imageTexture, textureBounds, vOffsetAndScale;
  1254. };
  1255. BuiltProgram program;
  1256. Params params;
  1257. };
  1258. auto left = (GLshort) targetClipArea.getX();
  1259. auto top = (GLshort) targetClipArea.getY();
  1260. auto right = (GLshort) targetClipArea.getRight();
  1261. auto bottom = (GLshort) targetClipArea.getBottom();
  1262. const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top };
  1263. auto& program = OverlayShaderProgram::select (*this);
  1264. program.params.set ((float) contextWidth, (float) contextHeight, anchorPosAndTextureSize.toFloat(), flippedVertically);
  1265. GLuint vertexBuffer = 0;
  1266. extensions.glGenBuffers (1, &vertexBuffer);
  1267. extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  1268. extensions.glBufferData (GL_ARRAY_BUFFER, sizeof (vertices), vertices, GL_STATIC_DRAW);
  1269. auto index = (GLuint) program.params.positionAttribute.attributeID;
  1270. extensions.glVertexAttribPointer (index, 2, GL_SHORT, GL_FALSE, 4, nullptr);
  1271. extensions.glEnableVertexAttribArray (index);
  1272. JUCE_CHECK_OPENGL_ERROR
  1273. if (extensions.glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
  1274. {
  1275. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  1276. extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
  1277. extensions.glUseProgram (0);
  1278. extensions.glDisableVertexAttribArray (index);
  1279. extensions.glDeleteBuffers (1, &vertexBuffer);
  1280. }
  1281. else
  1282. {
  1283. clearGLError();
  1284. }
  1285. }
  1286. else
  1287. {
  1288. jassert (attachment == nullptr); // Running on an old graphics card!
  1289. }
  1290. JUCE_CHECK_OPENGL_ERROR
  1291. }
  1292. #if JUCE_ANDROID
  1293. void OpenGLContext::NativeContext::surfaceCreated (LocalRef<jobject>)
  1294. {
  1295. {
  1296. const std::lock_guard lock { nativeHandleMutex };
  1297. jassert (hasInitialised);
  1298. // has the context already attached?
  1299. jassert (surface.get() == EGL_NO_SURFACE && context.get() == EGL_NO_CONTEXT);
  1300. const auto window = getNativeWindow();
  1301. if (window == nullptr)
  1302. {
  1303. // failed to get a pointer to the native window so bail out
  1304. jassertfalse;
  1305. return;
  1306. }
  1307. // create the surface
  1308. surface.reset (eglCreateWindowSurface (display, config, window.get(), nullptr));
  1309. jassert (surface.get() != EGL_NO_SURFACE);
  1310. // create the OpenGL context
  1311. EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
  1312. context.reset (eglCreateContext (display, config, EGL_NO_CONTEXT, contextAttribs));
  1313. jassert (context.get() != EGL_NO_CONTEXT);
  1314. }
  1315. if (auto* cached = CachedImage::get (component))
  1316. {
  1317. cached->resume();
  1318. cached->triggerRepaint();
  1319. }
  1320. }
  1321. void OpenGLContext::NativeContext::surfaceDestroyed (LocalRef<jobject>)
  1322. {
  1323. if (auto* cached = CachedImage::get (component))
  1324. cached->pause();
  1325. {
  1326. const std::lock_guard lock { nativeHandleMutex };
  1327. context.reset (EGL_NO_CONTEXT);
  1328. surface.reset (EGL_NO_SURFACE);
  1329. }
  1330. }
  1331. #endif
  1332. } // namespace juce