UnityAppController+Rendering.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. #include "UnityAppController+Rendering.h"
  2. #include "UnityAppController+Thermal.h"
  3. #include "UnityAppController+ViewHandling.h"
  4. #include "Unity/InternalProfiler.h"
  5. #include "Unity/DisplayManager.h"
  6. #include "UI/UnityView.h"
  7. #include <dlfcn.h>
  8. #import <Metal/Metal.h>
  9. extern bool _didResignActive;
  10. static int _renderingAPI = 0;
  11. static void SelectRenderingAPIImpl();
  12. @implementation UnityAppController (Rendering)
  13. #if !PLATFORM_VISIONOS
  14. - (BOOL)usingCompositorLayer
  15. {
  16. return NO;
  17. }
  18. #endif
  19. - (void)createCADisplayLink
  20. {
  21. _displayLink = [CADisplayLink displayLinkWithTarget: self selector: @selector(repaintDisplayLink)];
  22. [self callbackFramerateChange: -1];
  23. [_displayLink addToRunLoop: [NSRunLoop currentRunLoop] forMode: NSRunLoopCommonModes];
  24. printf_console("CADisplayLink created\n");
  25. }
  26. #if UNITY_USES_METAL_DISPLAY_LINK
  27. - (void)createMetalDisplayLink API_AVAILABLE(ios(17.0), tvos(17.0))
  28. {
  29. _usesMetalDisplayLink = YES;
  30. _metalDisplayLink = [[CAMetalDisplayLink alloc] initWithMetalLayer:(CAMetalLayer*)_unityView.layer];
  31. _metalDisplayLink.preferredFrameLatency = 2;
  32. _metalDisplayLink.paused = NO;
  33. _metalDisplayLink.delegate = self;
  34. [self callbackFramerateChange: -1];
  35. [_metalDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  36. printf_console("CAMetalDisplayLink created\n");
  37. }
  38. #endif
  39. - (void)createDisplayLink
  40. {
  41. _usesMetalDisplayLink = NO; // we will set it to YES inside createMetalDisplayLink
  42. #if UNITY_USES_METAL_DISPLAY_LINK
  43. if (@available(iOS 17.0, tvOS 17.0, *))
  44. {
  45. if ([self shouldUseMetalDisplayLink])
  46. [self createMetalDisplayLink];
  47. }
  48. #endif
  49. if (!_usesMetalDisplayLink)
  50. [self createCADisplayLink];
  51. }
  52. - (void)destroyDisplayLink
  53. {
  54. [_displayLink invalidate];
  55. _displayLink = nil;
  56. #if UNITY_USES_METAL_DISPLAY_LINK
  57. if (@available(iOS 17.0, tvOS 17.0, *))
  58. {
  59. [_metalDisplayLink invalidate];
  60. _metalDisplayLink = nil;
  61. }
  62. #endif
  63. }
  64. - (void)pauseDisplayLink
  65. {
  66. _displayLink.paused = YES;
  67. #if UNITY_USES_METAL_DISPLAY_LINK
  68. if (@available(iOS 17.0, tvOS 17.0, *))
  69. _metalDisplayLink.paused = YES;
  70. #endif
  71. }
  72. - (void)unpauseDisplayLink
  73. {
  74. _displayLink.paused = NO;
  75. #if UNITY_USES_METAL_DISPLAY_LINK
  76. if (@available(iOS 17.0, tvOS 17.0, *))
  77. _metalDisplayLink.paused = NO;
  78. #endif
  79. }
  80. - (void)switchToCADisplayLinkImpl
  81. {
  82. if (_usesMetalDisplayLink)
  83. {
  84. #if UNITY_USES_METAL_DISPLAY_LINK
  85. if (@available(iOS 17.0, tvOS 17.0, *))
  86. {
  87. _metalDisplayLink.paused = YES;
  88. [_metalDisplayLink invalidate];
  89. _metalDisplayLink = nil;
  90. }
  91. #endif
  92. _usesMetalDisplayLink = NO;
  93. [self createCADisplayLink];
  94. }
  95. }
  96. - (void)switchToCADisplayLink
  97. {
  98. dispatch_async(dispatch_get_main_queue(), ^() {
  99. [self switchToCADisplayLinkImpl];
  100. });
  101. }
  102. #if UNITY_USES_METAL_DISPLAY_LINK
  103. - (void)switchToMetalDisplayLinkImpl API_AVAILABLE(ios(17.0), tvos(17.0))
  104. {
  105. if (!_usesMetalDisplayLink && [self shouldUseMetalDisplayLink])
  106. {
  107. _displayLink.paused = YES;
  108. [_displayLink invalidate];
  109. _displayLink = nil;
  110. [self createMetalDisplayLink];
  111. }
  112. }
  113. - (void)switchToMetalDisplayLink
  114. {
  115. dispatch_async(dispatch_get_main_queue(), ^() {
  116. [self switchToMetalDisplayLinkImpl];
  117. });
  118. }
  119. #endif
  120. - (void)repaintDisplayLink
  121. {
  122. if (self.usingCompositorLayer == NO)
  123. {
  124. UnityDisplayLinkCallback(_displayLink.timestamp);
  125. [self repaint];
  126. }
  127. else
  128. {
  129. [self repaintCompositorLayer];
  130. }
  131. }
  132. #if UNITY_USES_METAL_DISPLAY_LINK
  133. - (void)metalDisplayLink:(CAMetalDisplayLink*)link needsUpdate:(CAMetalDisplayLinkUpdate*)update
  134. {
  135. // we have found an issue on some devices in iOS handling of metal display link
  136. // [NSAttributedString initWithData: options: documentAttributes: error:]
  137. // will load webkit on the first call which, in turn, will call metal display link callback
  138. // (most likely because it takes so slow)
  139. // When NSAttributedString is used in plugin (called from unity player loop)
  140. // this results in a recursive [metalDisplayLink: needsUpdate:] call
  141. // While Unity playerloop returns immediately, our trampoline rendering implementation
  142. // is not "ready" for it, and we will get a crash
  143. // While this is purely apple iOS bug, we still want to work around it since
  144. // 1. It is hard for users to track down the crash (it will crash in unrelated code)
  145. // 2. It is hard for users to fix it (since they need to fix plugins logic considerably to use other means for HTML string)
  146. // thus we try to catch this case here: if nextDrawable is still set, we did not yet ended previous frame
  147. // which is only possible if the recursive call was made, so we just ignore this frame.
  148. // It will result in metal debug driver logging GPU Timeout Errors, but everything works fine
  149. UnityDisplaySurfaceMTL* displaySurface = (UnityDisplaySurfaceMTL*)_mainDisplay.surface;
  150. if(displaySurface->swapchain.nextDrawable != nil)
  151. return;
  152. UnityDisplayLinkCallback(0);
  153. displaySurface->swapchain.nextDrawable = update.drawable;
  154. [self repaint];
  155. }
  156. #endif
  157. - (void)repaint
  158. {
  159. if (_unityView.skipRendering)
  160. return;
  161. #if UNITY_SUPPORT_ROTATION
  162. [self checkOrientationRequest];
  163. #endif
  164. [_unityView recreateRenderingSurfaceIfNeeded];
  165. [_unityView processKeyboard];
  166. UnityDeliverUIEvents();
  167. // we want to support both CADisplayLink and CAMetalDisplayLink
  168. // the major complication is that they work quite differently under the hood
  169. // CADisplayLink: you can consider this a simple timer-based callback
  170. // so if we get this while in background - we might be not allowed to render at all
  171. // and before we were having an explicit check to repain only if we are not paused
  172. // CAMetalDisplayLink: unlike CADisplayLink (where we query drawable from view),
  173. // the callback comes when we are asked explicitly to render view contents (we are given drawable)
  174. // and we cannot bypass rendering when asked at all
  175. if(UnityIsPaused())
  176. {
  177. if(self.unityUsesMetalDisplayLink)
  178. UnityRenderWithoutPlayerLoopWithBackbuffer(GetMainDisplaySurface()->unityColorBuffer, GetMainDisplaySurface()->unityDepthBuffer);
  179. }
  180. else
  181. {
  182. UnityRepaint();
  183. }
  184. id<MTLCommandBuffer> cb = [UnityGetMetalCommandQueue() commandBuffer];
  185. cb.label = @"Present";
  186. [[DisplayManager Instance] presentWith:cb];
  187. [cb commit];
  188. #if !PLATFORM_VISIONOS
  189. if (UnityResolutionScalingFixedDPIFactorChanged())
  190. _unityView.contentScaleFactor = UnityScreenScaleFactor([UIScreen mainScreen]);
  191. #endif
  192. UnityCheckUnloadAndQuit();
  193. }
  194. #if !PLATFORM_VISIONOS
  195. - (void)repaintCompositorLayer
  196. {
  197. }
  198. #endif
  199. - (void)callbackGfxInited
  200. {
  201. assert(self.engineLoadState < kUnityEngineLoadStateRenderingInitialized && "Graphics should not have been initialized at this point");
  202. InitRendering();
  203. [self advanceEngineLoadState: kUnityEngineLoadStateRenderingInitialized];
  204. [self shouldAttachRenderDelegate];
  205. [_unityView updateLayerDrawableSizeFromBounds];
  206. [_unityView updateUnityBackbufferSize];
  207. [_unityView recreateRenderingSurface];
  208. [_renderDelegate mainDisplayInited: _mainDisplay.surface];
  209. _mainDisplay.surface->allowScreenshot = 1;
  210. }
  211. - (void)callbackFramerateChange:(int)targetFPS
  212. {
  213. if (targetFPS <= 0)
  214. targetFPS = UnityGetTargetFPS();
  215. // on tvos it is possible to start application without a screen attached
  216. // alas, mainScreen is set in this case, but the values provided are bogus
  217. // and in the case of maxFPS = 0 we will end up in endless recursion
  218. #if !PLATFORM_VISIONOS
  219. const int maxFPS = (int)[UIScreen mainScreen].maximumFramesPerSecond;
  220. #else
  221. // no UIScreen on VisionOS
  222. const int maxFPS = 90;
  223. #endif
  224. if (maxFPS > 0 && targetFPS > maxFPS)
  225. {
  226. targetFPS = maxFPS;
  227. // note that this changes FPS, resulting in UnityFramerateChangeCallback call, calling this method recursively recursively
  228. UnitySetTargetFPS(targetFPS);
  229. return;
  230. }
  231. if (UnityShouldAdjustPerformanceOnThermalStateChange())
  232. targetFPS = [self adjustFrameRateForThermalState:targetFPS];
  233. if(_usesMetalDisplayLink)
  234. {
  235. #if UNITY_USES_METAL_DISPLAY_LINK
  236. if (@available(iOS 17.0, tvOS 17.0, *))
  237. _metalDisplayLink.preferredFrameRateRange = CAFrameRateRangeMake(targetFPS, targetFPS, targetFPS);
  238. #endif
  239. }
  240. else
  241. {
  242. _displayLink.preferredFrameRateRange = CAFrameRateRangeMake(targetFPS, targetFPS, targetFPS);
  243. }
  244. }
  245. - (void)selectRenderingAPI
  246. {
  247. NSAssert(_renderingAPI == 0, @"[UnityAppController selectRenderingApi] called twice");
  248. SelectRenderingAPIImpl();
  249. }
  250. - (UnityRenderingAPI)renderingAPI
  251. {
  252. NSAssert(_renderingAPI != 0, @"[UnityAppController renderingAPI] called before [UnityAppController selectRenderingApi]");
  253. return (UnityRenderingAPI)_renderingAPI;
  254. }
  255. @end
  256. UNITY_EXPORT extern "C" void UnityGfxInitedCallback()
  257. {
  258. [GetAppController() callbackGfxInited];
  259. }
  260. UNITY_EXPORT extern "C" void UnityPresentContextCallback()
  261. {
  262. }
  263. UNITY_EXPORT extern "C" void UnityFramerateChangeCallback(int targetFPS)
  264. {
  265. [GetAppController() callbackFramerateChange: targetFPS];
  266. }
  267. static NSBundle* _MetalBundle = nil;
  268. static id<MTLDevice> _MetalDevice = nil;
  269. static id<MTLCommandQueue> _MetalCommandQueue = nil;
  270. static void SelectRenderingAPIImpl()
  271. {
  272. assert(_renderingAPI == 0 && "Rendering API selection was done twice");
  273. _renderingAPI = UnityGetRenderingAPI();
  274. if (_renderingAPI == apiMetal)
  275. {
  276. _MetalBundle = [NSBundle bundleWithPath: @"/System/Library/Frameworks/Metal.framework"];
  277. _MetalDevice = MTLCreateSystemDefaultDevice();
  278. _MetalCommandQueue = [_MetalDevice newCommandQueueWithMaxCommandBufferCount: UnityCommandQueueMaxCommandBufferCountMTL()];
  279. assert(_MetalDevice != nil && _MetalCommandQueue != nil && "Could not initialize Metal.");
  280. }
  281. }
  282. UNITY_EXPORT extern "C" NSBundle* UnityGetMetalBundle() { return _MetalBundle; }
  283. UNITY_EXPORT extern "C" MTLDeviceRef UnityGetMetalDevice() { return _MetalDevice; }
  284. UNITY_EXPORT extern "C" MTLCommandQueueRef UnityGetMetalCommandQueue() { return _MetalCommandQueue; }
  285. UNITY_EXPORT extern "C" int UnitySelectedRenderingAPI() { return _renderingAPI; }
  286. UNITY_EXPORT extern "C" void UnitySelectRenderingAPI() { SelectRenderingAPIImpl(); }
  287. // deprecated and no longer used by unity itself (will soon be removed)
  288. UNITY_EXPORT extern "C" MTLCommandQueueRef UnityGetMetalDrawableCommandQueue() { return UnityGetMetalCommandQueue(); }
  289. UNITY_EXPORT extern "C" UnityRenderBufferHandle UnityBackbufferColor() { return GetMainDisplaySurface()->unityColorBuffer; }
  290. UNITY_EXPORT extern "C" UnityRenderBufferHandle UnityBackbufferDepth() { return GetMainDisplaySurface()->unityDepthBuffer; }
  291. UNITY_EXPORT extern "C" void DisplayManagerEndFrameRendering() { [[DisplayManager Instance] endFrameRendering]; }
  292. UNITY_EXPORT extern "C" void UnityPrepareScreenshot() { UnitySetRenderTarget(GetMainDisplaySurface()->unityColorBuffer, GetMainDisplaySurface()->unityDepthBuffer); }
  293. UNITY_EXPORT extern "C" void UnityRepaint()
  294. {
  295. @autoreleasepool
  296. {
  297. Profiler_FrameStart();
  298. if (UnityIsBatchmode())
  299. UnityBatchPlayerLoop();
  300. else
  301. UnityPlayerLoopWithBackbuffer(GetMainDisplaySurface()->unityColorBuffer, GetMainDisplaySurface()->unityDepthBuffer);
  302. Profiler_FrameEnd();
  303. }
  304. }
  305. UNITY_EXPORT extern "C" void UnitySetMaxQueuedFrames(unsigned count)
  306. {
  307. assert(2 <= count && count <= 3);
  308. UnityAppController* app = GetAppController();
  309. if (app.unityUsesMetalDisplayLink)
  310. {
  311. #if UNITY_USES_METAL_DISPLAY_LINK
  312. if (@available(iOS 17.0, tvOS 17.0, *))
  313. app.unityMetalDisplayLink.preferredFrameLatency = count - 1;
  314. #endif
  315. }
  316. else
  317. {
  318. dispatch_async(dispatch_get_main_queue(), ^() {
  319. CALayer* layer = app.unityView.layer;
  320. if ([layer isKindOfClass: [CAMetalLayer class]])
  321. ((CAMetalLayer*)layer).maximumDrawableCount = count;
  322. });
  323. }
  324. }