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.

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