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.

393 lines
17KB

  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. namespace juce
  19. {
  20. class OpenGLTexture;
  21. //==============================================================================
  22. /**
  23. Creates an OpenGL context, which can be attached to a component.
  24. To render some OpenGL, you should create an instance of an OpenGLContext,
  25. and call attachTo() to make it use a component as its render target.
  26. To provide threaded rendering, you can supply an OpenGLRenderer object that
  27. will be used to render each frame.
  28. Before your target component or OpenGLRenderer is deleted, you MUST call
  29. detach() or delete the OpenGLContext to allow the background thread to
  30. stop and the native resources to be freed safely.
  31. @see OpenGLRenderer
  32. @tags{OpenGL}
  33. */
  34. class JUCE_API OpenGLContext
  35. {
  36. public:
  37. OpenGLContext();
  38. /** Destructor. */
  39. ~OpenGLContext();
  40. //==============================================================================
  41. /** Gives the context an OpenGLRenderer to use to do the drawing.
  42. The object that you give it will not be owned by the context, so it's the caller's
  43. responsibility to manage its lifetime and make sure that it doesn't get deleted
  44. while the context may be using it. To stop the context using a renderer, just call
  45. this method with a null pointer.
  46. Note: This must be called BEFORE attaching your context to a target component!
  47. */
  48. void setRenderer (OpenGLRenderer*) noexcept;
  49. /** Attaches the context to a target component.
  50. If the component is not fully visible, this call will wait until the component
  51. is shown before actually creating a native context for it.
  52. When a native context is created, a thread is started, and will be used to call
  53. the OpenGLRenderer methods. The context will be floated above the target component,
  54. and when the target moves, it will track it. If the component is hidden/shown, the
  55. context may be deleted and re-created.
  56. */
  57. void attachTo (Component&);
  58. /** Detaches the context from its target component and deletes any native resources.
  59. If the context has not been attached, this will do nothing. Otherwise, it will block
  60. until the context and its thread have been cleaned up.
  61. */
  62. void detach();
  63. /** Returns true if the context is attached to a component and is on-screen.
  64. Note that if you call attachTo() for a non-visible component, this method will
  65. return false until the component is made visible.
  66. */
  67. bool isAttached() const noexcept;
  68. /** Returns the component to which this context is currently attached, or nullptr. */
  69. Component* getTargetComponent() const noexcept;
  70. /** If the given component has an OpenGLContext attached, then this will return it. */
  71. static OpenGLContext* getContextAttachedTo (Component& component) noexcept;
  72. //==============================================================================
  73. /** Sets the pixel format which you'd like to use for the target GL surface.
  74. Note: This must be called BEFORE attaching your context to a target component!
  75. */
  76. void setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept;
  77. /** Texture magnification filters, used by setTextureMagnificationFilter(). */
  78. enum TextureMagnificationFilter
  79. {
  80. nearest,
  81. linear
  82. };
  83. /** Sets the texture magnification filter. By default the texture magnification
  84. filter is linear. However, for faster rendering you may want to use the
  85. 'nearest' magnification filter. This option will not affect any textures
  86. created before this function was called. */
  87. void setTextureMagnificationFilter (TextureMagnificationFilter magFilterMode) noexcept;
  88. //==============================================================================
  89. /** Provides a context with which you'd like this context's resources to be shared.
  90. The object passed-in here is a platform-dependent native context object, and
  91. must not be deleted while this context may still be using it! To turn off sharing,
  92. you can call this method with a null pointer.
  93. Note: This must be called BEFORE attaching your context to a target component!
  94. */
  95. void setNativeSharedContext (void* nativeContextToShareWith) noexcept;
  96. /** Enables multisampling on platforms where this is implemented.
  97. If enabling this, you must call this method before attachTo().
  98. */
  99. void setMultisamplingEnabled (bool) noexcept;
  100. /** Returns true if shaders can be used in this context. */
  101. bool areShadersAvailable() const;
  102. /** Returns true if non-power-of-two textures are supported in this context. */
  103. bool isTextureNpotSupported() const;
  104. /** OpenGL versions, used by setOpenGLVersionRequired().
  105. The Core profile doesn't include some legacy functionality, including the
  106. fixed-function pipeline.
  107. The Compatibility profile is backwards-compatible, and includes functionality
  108. deprecated in the Core profile. However, not all implementations provide
  109. compatibility profiles targeting later versions of OpenGL. To run on the
  110. broadest range of hardware, using the 3.2 Core profile is recommended.
  111. */
  112. enum OpenGLVersion
  113. {
  114. defaultGLVersion = 0, ///< Whatever the device decides to give us, normally a compatibility profile
  115. openGL3_2, ///< 3.2 Core profile
  116. openGL4_1, ///< 4.1 Core profile, the latest supported by macOS at time of writing
  117. openGL4_3 ///< 4.3 Core profile, will enable improved debugging support when building in Debug
  118. };
  119. /** Sets a preference for the version of GL that this context should use, if possible.
  120. Some platforms may ignore this value.
  121. */
  122. void setOpenGLVersionRequired (OpenGLVersion) noexcept;
  123. /** Enables or disables the use of the GL context to perform 2D rendering
  124. of the component to which it is attached.
  125. If this is false, then only your OpenGLRenderer will be used to perform
  126. any rendering. If true, then each time your target's paint() method needs
  127. to be called, an OpenGLGraphicsContext will be used to render it, (after
  128. calling your OpenGLRenderer if there is one).
  129. By default this is set to true. If you're not using any paint() method functionality
  130. and are doing all your rendering in an OpenGLRenderer, you should disable it
  131. to improve performance.
  132. Note: This must be called BEFORE attaching your context to a target component!
  133. */
  134. void setComponentPaintingEnabled (bool shouldPaintComponent) noexcept;
  135. /** Enables or disables continuous repainting.
  136. If set to true, the context will run a loop, re-rendering itself without waiting
  137. for triggerRepaint() to be called, at a frequency determined by the swap interval
  138. (see setSwapInterval). If false, then after each render callback, it will wait for
  139. another call to triggerRepaint() before rendering again.
  140. This is disabled by default.
  141. @see setSwapInterval
  142. */
  143. void setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept;
  144. /** Asynchronously causes a repaint to be made. */
  145. void triggerRepaint();
  146. //==============================================================================
  147. /** This retrieves an object that was previously stored with setAssociatedObject().
  148. If no object is found with the given name, this will return nullptr.
  149. This method must only be called from within the GL rendering methods.
  150. @see setAssociatedObject
  151. */
  152. ReferenceCountedObject* getAssociatedObject (const char* name) const;
  153. /** Attaches a named object to the context, which will be deleted when the context is
  154. destroyed.
  155. This allows you to store an object which will be released before the context is
  156. deleted. The main purpose is for caching GL objects such as shader programs, which
  157. will become invalid when the context is deleted.
  158. This method must only be called from within the GL rendering methods.
  159. */
  160. void setAssociatedObject (const char* name, ReferenceCountedObject* newObject);
  161. //==============================================================================
  162. /** Makes this context the currently active one.
  163. You should never need to call this in normal use - the context will already be
  164. active when OpenGLRenderer::renderOpenGL() is invoked.
  165. */
  166. bool makeActive() const noexcept;
  167. /** Returns true if this context is currently active for the calling thread. */
  168. bool isActive() const noexcept;
  169. /** If any context is active on the current thread, this deactivates it.
  170. Note that on some platforms, like Android, this isn't possible.
  171. */
  172. static void deactivateCurrentContext();
  173. /** Returns the context that's currently in active use by the calling thread, or
  174. nullptr if no context is active.
  175. */
  176. static OpenGLContext* getCurrentContext();
  177. //==============================================================================
  178. /** Swaps the buffers (if the context can do this).
  179. There's normally no need to call this directly - the buffers will be swapped
  180. automatically after your OpenGLRenderer::renderOpenGL() method has been called.
  181. */
  182. void swapBuffers();
  183. /** Sets whether the context checks the vertical sync before swapping.
  184. The value is the number of frames to allow between buffer-swapping. This is
  185. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  186. and greater numbers indicate that it should swap less often.
  187. By default, this will be set to 1.
  188. Returns true if it sets the value successfully - some platforms won't support
  189. this setting.
  190. @see setContinuousRepainting
  191. */
  192. bool setSwapInterval (int numFramesPerSwap);
  193. /** Returns the current swap-sync interval.
  194. See setSwapInterval() for info about the value returned.
  195. */
  196. int getSwapInterval() const;
  197. //==============================================================================
  198. /** Execute a lambda, function or functor on the OpenGL thread with an active
  199. context.
  200. This method will attempt to execute functor on the OpenGL thread. If
  201. blockUntilFinished is true then the method will block until the functor
  202. has finished executing.
  203. This function can only be called if the context is attached to a component.
  204. Otherwise, this function will assert.
  205. This function is useful when you need to execute house-keeping tasks such
  206. as allocating, deallocating textures or framebuffers. As such, the functor
  207. will execute without locking the message thread. Therefore, it is not
  208. intended for any drawing commands or GUI code. Any GUI code should be
  209. executed in the OpenGLRenderer::renderOpenGL callback instead.
  210. */
  211. template <typename T>
  212. void executeOnGLThread (T&& functor, bool blockUntilFinished);
  213. //==============================================================================
  214. /** Returns the scale factor used by the display that is being rendered.
  215. The scale is that of the display - see Displays::Display::scale
  216. Note that this should only be called during an OpenGLRenderer::renderOpenGL()
  217. callback - at other times the value it returns is undefined.
  218. */
  219. double getRenderingScale() const noexcept { return currentRenderScale; }
  220. //==============================================================================
  221. /** If this context is backed by a frame buffer, this returns its ID number,
  222. or 0 if the context does not use a framebuffer.
  223. */
  224. unsigned int getFrameBufferID() const noexcept;
  225. /** Returns an OS-dependent handle to some kind of underlying OS-provided GL context.
  226. The exact type of the value returned will depend on the OS and may change
  227. if the implementation changes. If you want to use this, digging around in the
  228. native code is probably the best way to find out what it is.
  229. */
  230. void* getRawContext() const noexcept;
  231. /** Returns true if this context is using the core profile.
  232. @see OpenGLVersion
  233. */
  234. bool isCoreProfile() const;
  235. /** This structure holds a set of dynamically loaded GL functions for use on this context. */
  236. OpenGLExtensionFunctions extensions;
  237. //==============================================================================
  238. /** Draws the currently selected texture into this context at its original size.
  239. @param targetClipArea the target area to draw into (in top-left origin coords)
  240. @param anchorPosAndTextureSize the position of this rectangle is the texture's top-left
  241. anchor position in the target space, and the size must be
  242. the total size of the texture.
  243. @param contextWidth the width of the context or framebuffer that is being drawn into,
  244. used for scaling of the coordinates.
  245. @param contextHeight the height of the context or framebuffer that is being drawn into,
  246. used for vertical flipping of the y coordinates.
  247. @param textureOriginIsBottomLeft if true, the texture's origin is treated as being at
  248. (0, 0). If false, it is assumed to be (0, 1)
  249. */
  250. void copyTexture (const Rectangle<int>& targetClipArea,
  251. const Rectangle<int>& anchorPosAndTextureSize,
  252. int contextWidth, int contextHeight,
  253. bool textureOriginIsBottomLeft);
  254. /** Changes the amount of GPU memory that the internal cache for Images is allowed to use. */
  255. void setImageCacheSize (size_t cacheSizeBytes) noexcept;
  256. /** Returns the amount of GPU memory that the internal cache for Images is allowed to use. */
  257. size_t getImageCacheSize() const noexcept;
  258. //==============================================================================
  259. #ifndef DOXYGEN
  260. class NativeContext;
  261. #endif
  262. private:
  263. enum class InitResult
  264. {
  265. fatal,
  266. retry,
  267. success
  268. };
  269. friend class OpenGLTexture;
  270. class CachedImage;
  271. class Attachment;
  272. NativeContext* nativeContext = nullptr;
  273. OpenGLRenderer* renderer = nullptr;
  274. double currentRenderScale = 1.0;
  275. std::unique_ptr<Attachment> attachment;
  276. OpenGLPixelFormat openGLPixelFormat;
  277. void* contextToShareWith = nullptr;
  278. OpenGLVersion versionRequired = defaultGLVersion;
  279. size_t imageCacheMaxSize = 8 * 1024 * 1024;
  280. bool renderComponents = true, useMultisampling = false, overrideCanAttach = false;
  281. std::atomic<bool> continuousRepaint { false };
  282. TextureMagnificationFilter texMagFilter = linear;
  283. //==============================================================================
  284. struct AsyncWorker : public ReferenceCountedObject
  285. {
  286. using Ptr = ReferenceCountedObjectPtr<AsyncWorker>;
  287. virtual void operator() (OpenGLContext&) = 0;
  288. ~AsyncWorker() override = default;
  289. };
  290. template <typename FunctionType>
  291. struct AsyncWorkerFunctor : public AsyncWorker
  292. {
  293. AsyncWorkerFunctor (FunctionType functorToUse) : functor (functorToUse) {}
  294. void operator() (OpenGLContext& callerContext) override { functor (callerContext); }
  295. FunctionType functor;
  296. JUCE_DECLARE_NON_COPYABLE (AsyncWorkerFunctor)
  297. };
  298. //==============================================================================
  299. CachedImage* getCachedImage() const noexcept;
  300. void execute (AsyncWorker::Ptr, bool);
  301. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext)
  302. };
  303. //==============================================================================
  304. #ifndef DOXYGEN
  305. template <typename FunctionType>
  306. void OpenGLContext::executeOnGLThread (FunctionType&& f, bool shouldBlock) { execute (new AsyncWorkerFunctor<FunctionType> (f), shouldBlock); }
  307. #endif
  308. } // namespace juce