UnityAppController+Rendering.mm 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. #include "UnityAppController+Rendering.h"
  2. #include "UnityAppController+ViewHandling.h"
  3. #include "Unity/InternalProfiler.h"
  4. #include "Unity/UnityMetalSupport.h"
  5. #include "Unity/DisplayManager.h"
  6. #include "Unity/EAGLContextHelper.h"
  7. #include "UI/UnityView.h"
  8. #include <dlfcn.h>
  9. // On some devices presenting render buffer may sporadically take long time to complete even with very simple scenes.
  10. // In these cases display link still fires at steady frame rate but input processing becomes stuttering.
  11. // As a workaround this switch disables display link during rendering a frame.
  12. // If you are running a GPU bound scene and experience frame drop you may want to disable this switch.
  13. #define ENABLE_DISPLAY_LINK_PAUSING 1
  14. #define ENABLE_RUNLOOP_ACCEPT_INPUT 1
  15. // _glesContextCreated was renamed to _renderingInited
  16. extern bool _renderingInited;
  17. extern bool _unityAppReady;
  18. extern bool _skipPresent;
  19. extern bool _didResignActive;
  20. static int _renderingAPI = 0;
  21. static int SelectRenderingAPIImpl();
  22. static bool _enableRunLoopAcceptInput = false;
  23. @implementation UnityAppController (Rendering)
  24. - (void)createDisplayLink
  25. {
  26. _displayLink = [CADisplayLink displayLinkWithTarget: self selector: @selector(repaintDisplayLink)];
  27. [self callbackFramerateChange: -1];
  28. [_displayLink addToRunLoop: [NSRunLoop currentRunLoop] forMode: NSRunLoopCommonModes];
  29. }
  30. - (void)destroyDisplayLink
  31. {
  32. [_displayLink invalidate];
  33. _displayLink = nil;
  34. }
  35. - (void)processTouchEvents
  36. {
  37. // On multicore devices running at 60 FPS some touch event delivery isn't properly interleaved with graphical frames.
  38. // Running additional run loop here improves event handling in those cases.
  39. // Passing here an NSDate from the past invokes run loop only once.
  40. #if ENABLE_RUNLOOP_ACCEPT_INPUT
  41. // We get "NSInternalInconsistencyException: unexpected start state" exception if there are events queued and app is
  42. // going to background at the same time. This happens when we render additional frame after receiving
  43. // applicationWillResignActive. So check if we are supposed to ignore input.
  44. bool ignoreInput = [[UIApplication sharedApplication] isIgnoringInteractionEvents];
  45. if (!ignoreInput && _enableRunLoopAcceptInput)
  46. {
  47. // Additional acceptInput call crashes on iOS8- unless using invalid NSRunLoopCommonModes, while on iOS10 that mode
  48. // produces warnings and does not improve touch event delivery, so we need to differentiate by iOS version.
  49. // Note: Starting with iOS 10 there's a typedef NSRunLoopMode used instead of NSString
  50. static NSString* inputMode = (_ios90orNewer ? NSDefaultRunLoopMode : NSRunLoopCommonModes);
  51. static NSDate* past = [NSDate date];
  52. [[NSRunLoop currentRunLoop] acceptInputForMode: inputMode beforeDate: past];
  53. }
  54. #endif
  55. }
  56. - (void)repaintDisplayLink
  57. {
  58. #if ENABLE_DISPLAY_LINK_PAUSING
  59. _displayLink.paused = YES;
  60. #endif
  61. if (!_didResignActive)
  62. {
  63. [self repaint];
  64. [self processTouchEvents];
  65. }
  66. #if ENABLE_DISPLAY_LINK_PAUSING
  67. _displayLink.paused = NO;
  68. #endif
  69. }
  70. - (void)repaint
  71. {
  72. #if UNITY_SUPPORT_ROTATION
  73. [self checkOrientationRequest];
  74. #endif
  75. [_unityView recreateRenderingSurfaceIfNeeded];
  76. UnityDeliverUIEvents();
  77. if (!UnityIsPaused())
  78. UnityRepaint();
  79. }
  80. - (void)callbackGfxInited
  81. {
  82. InitRendering();
  83. _renderingInited = true;
  84. [self shouldAttachRenderDelegate];
  85. [_renderDelegate mainDisplayInited: _mainDisplay.surface];
  86. [_unityView recreateRenderingSurface];
  87. _mainDisplay.surface->allowScreenshot = 1;
  88. }
  89. - (void)callbackPresent:(const UnityFrameStats*)frameStats
  90. {
  91. if (_skipPresent || _didResignActive)
  92. return;
  93. [[DisplayManager Instance] present];
  94. Profiler_FramePresent(frameStats);
  95. }
  96. - (void)callbackFramerateChange:(int)targetFPS
  97. {
  98. int maxFPS = (int)[UIScreen mainScreen].maximumFramesPerSecond;
  99. if (targetFPS <= 0)
  100. targetFPS = UnityGetTargetFPS();
  101. if (targetFPS > maxFPS)
  102. targetFPS = maxFPS;
  103. _enableRunLoopAcceptInput = (targetFPS == maxFPS && UnityDeviceCPUCount() > 1);
  104. _displayLink.preferredFramesPerSecond = targetFPS;
  105. }
  106. - (void)selectRenderingAPI
  107. {
  108. NSAssert(_renderingAPI == 0, @"[UnityAppController selectRenderingApi] called twice");
  109. _renderingAPI = SelectRenderingAPIImpl();
  110. }
  111. - (UnityRenderingAPI)renderingAPI
  112. {
  113. NSAssert(_renderingAPI != 0, @"[UnityAppController renderingAPI] called before [UnityAppController selectRenderingApi]");
  114. return (UnityRenderingAPI)_renderingAPI;
  115. }
  116. @end
  117. extern "C" void UnityGfxInitedCallback()
  118. {
  119. [GetAppController() callbackGfxInited];
  120. }
  121. extern "C" void UnityPresentContextCallback(struct UnityFrameStats const* unityFrameStats)
  122. {
  123. [GetAppController() callbackPresent: unityFrameStats];
  124. }
  125. extern "C" void UnityFramerateChangeCallback(int targetFPS)
  126. {
  127. [GetAppController() callbackFramerateChange: targetFPS];
  128. }
  129. extern "C" void UnityInitMainScreenRenderingCallback()
  130. {
  131. [GetAppController().mainDisplay initRendering];
  132. }
  133. static NSBundle* _MetalBundle = nil;
  134. static id<MTLDevice> _MetalDevice = nil;
  135. static EAGLContext* _GlesContext = nil;
  136. static bool IsMetalSupported(int /*api*/)
  137. {
  138. _MetalBundle = [NSBundle bundleWithPath: @"/System/Library/Frameworks/Metal.framework"];
  139. if (_MetalBundle)
  140. {
  141. [_MetalBundle load];
  142. _MetalDevice = ((MTLCreateSystemDefaultDeviceFunc)::dlsym(dlopen(0, RTLD_LOCAL | RTLD_LAZY), "MTLCreateSystemDefaultDevice"))();
  143. if (_MetalDevice)
  144. return true;
  145. }
  146. [_MetalBundle unload];
  147. return false;
  148. }
  149. static bool IsGlesSupported(int api)
  150. {
  151. _GlesContext = [[EAGLContext alloc] initWithAPI: (EAGLRenderingAPI)api];
  152. return _GlesContext != nil;
  153. }
  154. typedef bool(*CheckSupportedFunc)(int);
  155. static int SelectRenderingAPIImpl()
  156. {
  157. #if UNITY_CAN_USE_METAL
  158. const bool canSupportMetal = _ios80orNewer;
  159. #else
  160. const bool canSupportMetal = false;
  161. #endif
  162. // Get list of graphics APIs to try from player settings
  163. const int kMaxAPIs = 3;
  164. int apis[kMaxAPIs];
  165. const int apiCount = UnityGetRenderingAPIs(kMaxAPIs, apis);
  166. // Go over them and try each
  167. for (int i = 0; i < apiCount; ++i)
  168. {
  169. int api = apis[i];
  170. // Metal
  171. if (api == apiMetal)
  172. {
  173. if (!canSupportMetal)
  174. continue;
  175. if (!IsMetalSupported(0))
  176. continue;
  177. return api;
  178. }
  179. // GLES3
  180. if (api == apiOpenGLES3)
  181. {
  182. if (!IsGlesSupported(kEAGLRenderingAPIOpenGLES3))
  183. continue;
  184. return api;
  185. }
  186. // GLES2
  187. if (api == apiOpenGLES2)
  188. {
  189. if (!IsGlesSupported(kEAGLRenderingAPIOpenGLES2))
  190. continue;
  191. return api;
  192. }
  193. }
  194. return 0;
  195. }
  196. extern "C" NSBundle* UnityGetMetalBundle() {
  197. return _MetalBundle;
  198. }
  199. extern "C" MTLDeviceRef UnityGetMetalDevice() { return _MetalDevice; }
  200. extern "C" MTLCommandQueueRef UnityGetMetalCommandQueue() { return ((UnityDisplaySurfaceMTL*)GetMainDisplaySurface())->commandQueue; }
  201. extern "C" MTLCommandQueueRef UnityGetMetalDrawableCommandQueue() { return ((UnityDisplaySurfaceMTL*)GetMainDisplaySurface())->drawableCommandQueue; }
  202. extern "C" EAGLContext* UnityGetDataContextEAGL() {
  203. return _GlesContext;
  204. }
  205. extern "C" int UnitySelectedRenderingAPI() { return _renderingAPI; }
  206. extern "C" UnityRenderBufferHandle UnityBackbufferColor() { return GetMainDisplaySurface()->unityColorBuffer; }
  207. extern "C" UnityRenderBufferHandle UnityBackbufferDepth() { return GetMainDisplaySurface()->unityDepthBuffer; }
  208. extern "C" void DisplayManagerEndFrameRendering() { [[DisplayManager Instance] endFrameRendering]; }
  209. extern "C" void UnityPrepareScreenshot() { UnitySetRenderTarget(GetMainDisplaySurface()->unityColorBuffer, GetMainDisplaySurface()->unityDepthBuffer); }
  210. extern "C" void UnityRepaint()
  211. {
  212. @autoreleasepool
  213. {
  214. // this will handle running on metal just fine (nop)
  215. EAGLContextSetCurrentAutoRestore autorestore(GetMainDisplaySurface());
  216. Profiler_FrameStart();
  217. UnityInputProcess();
  218. UnityPlayerLoop();
  219. Profiler_FrameEnd();
  220. }
  221. }