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.

260 lines
9.6KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  16. class OpenGLContext::NativeContext
  17. {
  18. public:
  19. NativeContext (Component& component,
  20. const OpenGLPixelFormat& pixFormat,
  21. void* contextToShare,
  22. bool shouldUseMultisampling,
  23. OpenGLVersion version)
  24. {
  25. NSOpenGLPixelFormatAttribute attribs[64] = { 0 };
  26. createAttribs (attribs, version, pixFormat, shouldUseMultisampling);
  27. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  28. static MouseForwardingNSOpenGLViewClass cls;
  29. view = [cls.createInstance() initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  30. pixelFormat: format];
  31. if ([view respondsToSelector: @selector (setWantsBestResolutionOpenGLSurface:)])
  32. [view setWantsBestResolutionOpenGLSurface: YES];
  33. [[NSNotificationCenter defaultCenter] addObserver: view
  34. selector: @selector (_surfaceNeedsUpdate:)
  35. name: NSViewGlobalFrameDidChangeNotification
  36. object: view];
  37. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  38. shareContext: (NSOpenGLContext*) contextToShare] autorelease];
  39. [view setOpenGLContext: renderContext];
  40. [format release];
  41. viewAttachment = NSViewComponent::attachViewToComponent (component, view);
  42. }
  43. ~NativeContext()
  44. {
  45. [[NSNotificationCenter defaultCenter] removeObserver: view];
  46. [renderContext clearDrawable];
  47. [renderContext setView: nil];
  48. [view setOpenGLContext: nil];
  49. [view release];
  50. }
  51. static void createAttribs (NSOpenGLPixelFormatAttribute* attribs, OpenGLVersion version,
  52. const OpenGLPixelFormat& pixFormat, bool shouldUseMultisampling)
  53. {
  54. ignoreUnused (version);
  55. int numAttribs = 0;
  56. #if JUCE_OPENGL3
  57. attribs[numAttribs++] = NSOpenGLPFAOpenGLProfile;
  58. attribs[numAttribs++] = version >= openGL3_2 ? NSOpenGLProfileVersion3_2Core
  59. : NSOpenGLProfileVersionLegacy;
  60. #endif
  61. attribs[numAttribs++] = NSOpenGLPFADoubleBuffer;
  62. attribs[numAttribs++] = NSOpenGLPFAClosestPolicy;
  63. attribs[numAttribs++] = NSOpenGLPFANoRecovery;
  64. attribs[numAttribs++] = NSOpenGLPFAColorSize;
  65. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.redBits + pixFormat.greenBits + pixFormat.blueBits);
  66. attribs[numAttribs++] = NSOpenGLPFAAlphaSize;
  67. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.alphaBits;
  68. attribs[numAttribs++] = NSOpenGLPFADepthSize;
  69. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.depthBufferBits;
  70. attribs[numAttribs++] = NSOpenGLPFAStencilSize;
  71. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.stencilBufferBits;
  72. attribs[numAttribs++] = NSOpenGLPFAAccumSize;
  73. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.accumulationBufferRedBits + pixFormat.accumulationBufferGreenBits
  74. + pixFormat.accumulationBufferBlueBits + pixFormat.accumulationBufferAlphaBits);
  75. if (shouldUseMultisampling)
  76. {
  77. attribs[numAttribs++] = NSOpenGLPFAMultisample;
  78. attribs[numAttribs++] = NSOpenGLPFASampleBuffers;
  79. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) 1;
  80. attribs[numAttribs++] = NSOpenGLPFASamples;
  81. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.multisamplingLevel;
  82. }
  83. }
  84. bool initialiseOnRenderThread (OpenGLContext&) { return true; }
  85. void shutdownOnRenderThread() { deactivateCurrentContext(); }
  86. bool createdOk() const noexcept { return getRawContext() != nullptr; }
  87. void* getRawContext() const noexcept { return static_cast<void*> (renderContext); }
  88. GLuint getFrameBufferID() const noexcept { return 0; }
  89. bool makeActive() const noexcept
  90. {
  91. jassert (renderContext != nil);
  92. if ([renderContext view] != view)
  93. [renderContext setView: view];
  94. if (NSOpenGLContext* context = [view openGLContext])
  95. {
  96. [context makeCurrentContext];
  97. return true;
  98. }
  99. return false;
  100. }
  101. bool isActive() const noexcept
  102. {
  103. return [NSOpenGLContext currentContext] == renderContext;
  104. }
  105. static void deactivateCurrentContext()
  106. {
  107. [NSOpenGLContext clearCurrentContext];
  108. }
  109. struct Locker
  110. {
  111. Locker (NativeContext& nc) : cglContext ((CGLContextObj) [nc.renderContext CGLContextObj])
  112. {
  113. CGLLockContext (cglContext);
  114. }
  115. ~Locker()
  116. {
  117. CGLUnlockContext (cglContext);
  118. }
  119. private:
  120. CGLContextObj cglContext;
  121. };
  122. void swapBuffers()
  123. {
  124. auto now = Time::getMillisecondCounterHiRes();
  125. [renderContext flushBuffer];
  126. if (minSwapTimeMs > 0)
  127. {
  128. // When our window is entirely occluded by other windows, flushBuffer
  129. // fails to wait for the swap interval, so the render loop spins at full
  130. // speed, burning CPU. This hack detects when things are going too fast
  131. // and sleeps if necessary.
  132. auto swapTime = Time::getMillisecondCounterHiRes() - now;
  133. auto frameTime = (int) (now - lastSwapTime);
  134. if (swapTime < 0.5 && frameTime < minSwapTimeMs - 3)
  135. {
  136. if (underrunCounter > 3)
  137. {
  138. Thread::sleep (2 * (minSwapTimeMs - frameTime));
  139. now = Time::getMillisecondCounterHiRes();
  140. }
  141. else
  142. {
  143. ++underrunCounter;
  144. }
  145. }
  146. else
  147. {
  148. if (underrunCounter > 0)
  149. --underrunCounter;
  150. }
  151. }
  152. lastSwapTime = now;
  153. }
  154. void updateWindowPosition (Rectangle<int>) {}
  155. bool setSwapInterval (int numFramesPerSwap)
  156. {
  157. // The macOS OpenGL programming guide says that numFramesPerSwap
  158. // can only be 0 or 1.
  159. jassert (isPositiveAndBelow (numFramesPerSwap, 2));
  160. minSwapTimeMs = (numFramesPerSwap * 1000) / 60;
  161. [renderContext setValues: (const GLint*) &numFramesPerSwap
  162. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12
  163. forParameter: NSOpenGLContextParameterSwapInterval];
  164. #else
  165. forParameter: NSOpenGLCPSwapInterval];
  166. #endif
  167. return true;
  168. }
  169. int getSwapInterval() const
  170. {
  171. GLint numFrames = 0;
  172. [renderContext getValues: &numFrames
  173. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12
  174. forParameter: NSOpenGLContextParameterSwapInterval];
  175. #else
  176. forParameter: NSOpenGLCPSwapInterval];
  177. #endif
  178. return numFrames;
  179. }
  180. NSOpenGLContext* renderContext = nil;
  181. NSOpenGLView* view = nil;
  182. ReferenceCountedObjectPtr<ReferenceCountedObject> viewAttachment;
  183. double lastSwapTime = 0;
  184. int minSwapTimeMs = 0, underrunCounter = 0;
  185. //==============================================================================
  186. struct MouseForwardingNSOpenGLViewClass : public ObjCClass<NSOpenGLView>
  187. {
  188. MouseForwardingNSOpenGLViewClass() : ObjCClass<NSOpenGLView> ("JUCEGLView_")
  189. {
  190. addMethod (@selector (rightMouseDown:), rightMouseDown, "v@:@");
  191. addMethod (@selector (rightMouseUp:), rightMouseUp, "v@:@");
  192. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "v@:@");
  193. registerClass();
  194. }
  195. private:
  196. static void rightMouseDown (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseDown: ev]; }
  197. static void rightMouseUp (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseUp: ev]; }
  198. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  199. };
  200. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
  201. };
  202. //==============================================================================
  203. bool OpenGLHelpers::isContextActive()
  204. {
  205. return CGLGetCurrentContext() != CGLContextObj();
  206. }
  207. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  208. } // namespace juce