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.

299 lines
11KB

  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. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  21. class OpenGLContext::NativeContext
  22. {
  23. public:
  24. NativeContext (Component& component,
  25. const OpenGLPixelFormat& pixFormat,
  26. void* contextToShare,
  27. bool shouldUseMultisampling,
  28. OpenGLVersion version)
  29. : owner (component)
  30. {
  31. NSOpenGLPixelFormatAttribute attribs[64] = { 0 };
  32. createAttribs (attribs, version, pixFormat, shouldUseMultisampling);
  33. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  34. static MouseForwardingNSOpenGLViewClass cls;
  35. view = [cls.createInstance() initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  36. pixelFormat: format];
  37. if ([view respondsToSelector: @selector (setWantsBestResolutionOpenGLSurface:)])
  38. [view setWantsBestResolutionOpenGLSurface: YES];
  39. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  40. [[NSNotificationCenter defaultCenter] addObserver: view
  41. selector: @selector (_surfaceNeedsUpdate:)
  42. name: NSViewGlobalFrameDidChangeNotification
  43. object: view];
  44. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  45. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  46. shareContext: (NSOpenGLContext*) contextToShare] autorelease];
  47. [view setOpenGLContext: renderContext];
  48. [format release];
  49. viewAttachment = NSViewComponent::attachViewToComponent (component, view);
  50. }
  51. ~NativeContext()
  52. {
  53. [[NSNotificationCenter defaultCenter] removeObserver: view];
  54. [renderContext clearDrawable];
  55. [renderContext setView: nil];
  56. [view setOpenGLContext: nil];
  57. [view release];
  58. }
  59. static void createAttribs (NSOpenGLPixelFormatAttribute* attribs, OpenGLVersion version,
  60. const OpenGLPixelFormat& pixFormat, bool shouldUseMultisampling)
  61. {
  62. ignoreUnused (version);
  63. int numAttribs = 0;
  64. attribs[numAttribs++] = NSOpenGLPFAOpenGLProfile;
  65. attribs[numAttribs++] = version >= openGL3_2 ? NSOpenGLProfileVersion3_2Core
  66. : NSOpenGLProfileVersionLegacy;
  67. attribs[numAttribs++] = NSOpenGLPFADoubleBuffer;
  68. attribs[numAttribs++] = NSOpenGLPFAClosestPolicy;
  69. attribs[numAttribs++] = NSOpenGLPFANoRecovery;
  70. attribs[numAttribs++] = NSOpenGLPFAColorSize;
  71. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.redBits + pixFormat.greenBits + pixFormat.blueBits);
  72. attribs[numAttribs++] = NSOpenGLPFAAlphaSize;
  73. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.alphaBits;
  74. attribs[numAttribs++] = NSOpenGLPFADepthSize;
  75. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.depthBufferBits;
  76. attribs[numAttribs++] = NSOpenGLPFAStencilSize;
  77. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.stencilBufferBits;
  78. attribs[numAttribs++] = NSOpenGLPFAAccumSize;
  79. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.accumulationBufferRedBits + pixFormat.accumulationBufferGreenBits
  80. + pixFormat.accumulationBufferBlueBits + pixFormat.accumulationBufferAlphaBits);
  81. if (shouldUseMultisampling)
  82. {
  83. attribs[numAttribs++] = NSOpenGLPFAMultisample;
  84. attribs[numAttribs++] = NSOpenGLPFASampleBuffers;
  85. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) 1;
  86. attribs[numAttribs++] = NSOpenGLPFASamples;
  87. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.multisamplingLevel;
  88. }
  89. }
  90. bool initialiseOnRenderThread (OpenGLContext&) { return true; }
  91. void shutdownOnRenderThread() { deactivateCurrentContext(); }
  92. bool createdOk() const noexcept { return getRawContext() != nullptr; }
  93. void* getRawContext() const noexcept { return static_cast<void*> (renderContext); }
  94. GLuint getFrameBufferID() const noexcept { return 0; }
  95. bool makeActive() const noexcept
  96. {
  97. jassert (renderContext != nil);
  98. if ([renderContext view] != view)
  99. [renderContext setView: view];
  100. if (NSOpenGLContext* context = [view openGLContext])
  101. {
  102. [context makeCurrentContext];
  103. return true;
  104. }
  105. return false;
  106. }
  107. bool isActive() const noexcept
  108. {
  109. return [NSOpenGLContext currentContext] == renderContext;
  110. }
  111. static void deactivateCurrentContext()
  112. {
  113. [NSOpenGLContext clearCurrentContext];
  114. }
  115. struct Locker
  116. {
  117. Locker (NativeContext& nc) : cglContext ((CGLContextObj) [nc.renderContext CGLContextObj])
  118. {
  119. CGLLockContext (cglContext);
  120. }
  121. ~Locker()
  122. {
  123. CGLUnlockContext (cglContext);
  124. }
  125. private:
  126. CGLContextObj cglContext;
  127. };
  128. void swapBuffers()
  129. {
  130. auto now = Time::getMillisecondCounterHiRes();
  131. [renderContext flushBuffer];
  132. if (minSwapTimeMs > 0)
  133. {
  134. // When our window is entirely occluded by other windows, flushBuffer
  135. // fails to wait for the swap interval, so the render loop spins at full
  136. // speed, burning CPU. This hack detects when things are going too fast
  137. // and sleeps if necessary.
  138. auto swapTime = Time::getMillisecondCounterHiRes() - now;
  139. auto frameTime = (int) (now - lastSwapTime);
  140. if (swapTime < 0.5 && frameTime < minSwapTimeMs - 3)
  141. {
  142. if (underrunCounter > 3)
  143. {
  144. Thread::sleep (2 * (minSwapTimeMs - frameTime));
  145. now = Time::getMillisecondCounterHiRes();
  146. }
  147. else
  148. {
  149. ++underrunCounter;
  150. }
  151. }
  152. else
  153. {
  154. if (underrunCounter > 0)
  155. --underrunCounter;
  156. }
  157. }
  158. lastSwapTime = now;
  159. }
  160. void updateWindowPosition (Rectangle<int>)
  161. {
  162. if (auto* peer = owner.getTopLevelComponent()->getPeer())
  163. {
  164. const auto newArea = peer->getAreaCoveredBy (owner);
  165. if (convertToRectInt ([view frame]) != newArea)
  166. [view setFrame: makeNSRect (newArea)];
  167. }
  168. }
  169. bool setSwapInterval (int numFramesPerSwapIn)
  170. {
  171. numFramesPerSwap = numFramesPerSwapIn;
  172. // The macOS OpenGL programming guide says that numFramesPerSwap
  173. // can only be 0 or 1.
  174. jassert (isPositiveAndBelow (numFramesPerSwap, 2));
  175. [renderContext setValues: (const GLint*) &numFramesPerSwap
  176. forParameter: getSwapIntervalParameter()];
  177. updateMinSwapTime();
  178. return true;
  179. }
  180. int getSwapInterval() const
  181. {
  182. GLint numFrames = 0;
  183. [renderContext getValues: &numFrames
  184. forParameter: getSwapIntervalParameter()];
  185. return numFrames;
  186. }
  187. void setNominalVideoRefreshPeriodS (double periodS)
  188. {
  189. jassert (periodS > 0.0);
  190. videoRefreshPeriodS = periodS;
  191. updateMinSwapTime();
  192. }
  193. void updateMinSwapTime()
  194. {
  195. minSwapTimeMs = static_cast<int> (numFramesPerSwap * 1000 * videoRefreshPeriodS);
  196. }
  197. static NSOpenGLContextParameter getSwapIntervalParameter()
  198. {
  199. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
  200. if (@available (macOS 10.12, *))
  201. return NSOpenGLContextParameterSwapInterval;
  202. #endif
  203. return NSOpenGLCPSwapInterval;
  204. }
  205. Component& owner;
  206. NSOpenGLContext* renderContext = nil;
  207. NSOpenGLView* view = nil;
  208. ReferenceCountedObjectPtr<ReferenceCountedObject> viewAttachment;
  209. double lastSwapTime = 0;
  210. std::atomic<int> minSwapTimeMs { 0 };
  211. int underrunCounter = 0, numFramesPerSwap = 0;
  212. double videoRefreshPeriodS = 1.0 / 60.0;
  213. //==============================================================================
  214. struct MouseForwardingNSOpenGLViewClass : public ObjCClass<NSOpenGLView>
  215. {
  216. MouseForwardingNSOpenGLViewClass() : ObjCClass<NSOpenGLView> ("JUCEGLView_")
  217. {
  218. addMethod (@selector (rightMouseDown:), rightMouseDown);
  219. addMethod (@selector (rightMouseUp:), rightMouseUp);
  220. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse);
  221. addMethod (@selector (accessibilityHitTest:), accessibilityHitTest);
  222. registerClass();
  223. }
  224. private:
  225. static void rightMouseDown (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseDown: ev]; }
  226. static void rightMouseUp (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseUp: ev]; }
  227. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  228. static id accessibilityHitTest (id self, SEL, NSPoint p) { return [[(NSOpenGLView*) self superview] accessibilityHitTest: p]; }
  229. };
  230. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
  231. };
  232. //==============================================================================
  233. bool OpenGLHelpers::isContextActive()
  234. {
  235. return CGLGetCurrentContext() != CGLContextObj();
  236. }
  237. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  238. } // namespace juce