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.

1703 lines
54KB

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