godot_view.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /**************************************************************************/
  2. /* godot_view.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #import "godot_view.h"
  31. #import "display_layer.h"
  32. #import "display_server_ios.h"
  33. #import "godot_view_renderer.h"
  34. #include "core/config/project_settings.h"
  35. #include "core/os/keyboard.h"
  36. #include "core/string/ustring.h"
  37. #import <CoreMotion/CoreMotion.h>
  38. static const int max_touches = 32;
  39. static const float earth_gravity = 9.80665;
  40. @interface GodotView () {
  41. UITouch *godot_touches[max_touches];
  42. }
  43. @property(assign, nonatomic) BOOL isActive;
  44. // CADisplayLink available on 3.1+ synchronizes the animation timer & drawing with the refresh rate of the display, only supports animation intervals of 1/60 1/30 & 1/15
  45. @property(strong, nonatomic) CADisplayLink *displayLink;
  46. // An animation timer that, when animation is started, will periodically call -drawView at the given rate.
  47. // Only used if CADisplayLink is not
  48. @property(strong, nonatomic) NSTimer *animationTimer;
  49. @property(strong, nonatomic) CALayer<DisplayLayer> *renderingLayer;
  50. @property(strong, nonatomic) CMMotionManager *motionManager;
  51. @end
  52. @implementation GodotView
  53. - (CALayer<DisplayLayer> *)initializeRenderingForDriver:(NSString *)driverName {
  54. if (self.renderingLayer) {
  55. return self.renderingLayer;
  56. }
  57. CALayer<DisplayLayer> *layer;
  58. if ([driverName isEqualToString:@"vulkan"]) {
  59. #if defined(TARGET_OS_SIMULATOR) && TARGET_OS_SIMULATOR
  60. if (@available(iOS 13, *)) {
  61. layer = [GodotMetalLayer layer];
  62. } else {
  63. return nil;
  64. }
  65. #else
  66. layer = [GodotMetalLayer layer];
  67. #endif
  68. } else if ([driverName isEqualToString:@"opengl3"]) {
  69. #pragma clang diagnostic push
  70. #pragma clang diagnostic ignored "-Wdeprecated-declarations" // OpenGL is deprecated in iOS 12.0
  71. layer = [GodotOpenGLLayer layer];
  72. #pragma clang diagnostic pop
  73. } else {
  74. return nil;
  75. }
  76. layer.frame = self.bounds;
  77. layer.contentsScale = self.contentScaleFactor;
  78. [self.layer addSublayer:layer];
  79. self.renderingLayer = layer;
  80. [layer initializeDisplayLayer];
  81. return self.renderingLayer;
  82. }
  83. - (instancetype)initWithCoder:(NSCoder *)coder {
  84. self = [super initWithCoder:coder];
  85. if (self) {
  86. [self godot_commonInit];
  87. }
  88. return self;
  89. }
  90. - (instancetype)initWithFrame:(CGRect)frame {
  91. self = [super initWithFrame:frame];
  92. if (self) {
  93. [self godot_commonInit];
  94. }
  95. return self;
  96. }
  97. - (void)dealloc {
  98. [self stopRendering];
  99. self.renderer = nil;
  100. self.delegate = nil;
  101. if (self.renderingLayer) {
  102. [self.renderingLayer removeFromSuperlayer];
  103. self.renderingLayer = nil;
  104. }
  105. if (self.motionManager) {
  106. [self.motionManager stopDeviceMotionUpdates];
  107. self.motionManager = nil;
  108. }
  109. if (self.displayLink) {
  110. [self.displayLink invalidate];
  111. self.displayLink = nil;
  112. }
  113. if (self.animationTimer) {
  114. [self.animationTimer invalidate];
  115. self.animationTimer = nil;
  116. }
  117. }
  118. - (void)godot_commonInit {
  119. self.contentScaleFactor = [UIScreen mainScreen].scale;
  120. [self initTouches];
  121. self.multipleTouchEnabled = YES;
  122. // Configure and start accelerometer
  123. if (!self.motionManager) {
  124. self.motionManager = [[CMMotionManager alloc] init];
  125. if (self.motionManager.deviceMotionAvailable) {
  126. self.motionManager.deviceMotionUpdateInterval = 1.0 / 70.0;
  127. [self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical];
  128. } else {
  129. self.motionManager = nil;
  130. }
  131. }
  132. }
  133. - (void)stopRendering {
  134. if (!self.isActive) {
  135. return;
  136. }
  137. self.isActive = NO;
  138. print_verbose("Stop animation!");
  139. if (self.useCADisplayLink) {
  140. [self.displayLink invalidate];
  141. self.displayLink = nil;
  142. } else {
  143. [self.animationTimer invalidate];
  144. self.animationTimer = nil;
  145. }
  146. [self clearTouches];
  147. }
  148. - (void)startRendering {
  149. if (self.isActive) {
  150. return;
  151. }
  152. self.isActive = YES;
  153. print_verbose("Start animation!");
  154. if (self.useCADisplayLink) {
  155. self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView)];
  156. if (GLOBAL_GET("display/window/ios/allow_high_refresh_rate")) {
  157. self.displayLink.preferredFramesPerSecond = 120;
  158. } else {
  159. self.displayLink.preferredFramesPerSecond = 60;
  160. }
  161. // Setup DisplayLink in main thread
  162. [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  163. } else {
  164. self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0 / 60) target:self selector:@selector(drawView) userInfo:nil repeats:YES];
  165. }
  166. }
  167. - (void)drawView {
  168. if (!self.isActive) {
  169. print_verbose("Draw view not active!");
  170. return;
  171. }
  172. if (self.useCADisplayLink) {
  173. // Pause the CADisplayLink to avoid recursion
  174. [self.displayLink setPaused:YES];
  175. // Process all input events
  176. while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, TRUE) == kCFRunLoopRunHandledSource) {
  177. // Continue.
  178. }
  179. // We are good to go, resume the CADisplayLink
  180. [self.displayLink setPaused:NO];
  181. }
  182. [self.renderingLayer startRenderDisplayLayer];
  183. if (!self.renderer) {
  184. return;
  185. }
  186. if ([self.renderer setupView:self]) {
  187. return;
  188. }
  189. if (self.delegate) {
  190. BOOL delegateFinishedSetup = [self.delegate godotViewFinishedSetup:self];
  191. if (!delegateFinishedSetup) {
  192. return;
  193. }
  194. }
  195. [self handleMotion];
  196. [self.renderer renderOnView:self];
  197. [self.renderingLayer stopRenderDisplayLayer];
  198. }
  199. - (BOOL)canRender {
  200. if (self.useCADisplayLink) {
  201. return self.displayLink != nil;
  202. } else {
  203. return self.animationTimer != nil;
  204. }
  205. }
  206. - (void)setRenderingInterval:(NSTimeInterval)renderingInterval {
  207. _renderingInterval = renderingInterval;
  208. if (self.canRender) {
  209. [self stopRendering];
  210. [self startRendering];
  211. }
  212. }
  213. - (void)layoutSubviews {
  214. if (self.renderingLayer) {
  215. self.renderingLayer.frame = self.bounds;
  216. [self.renderingLayer layoutDisplayLayer];
  217. if (DisplayServerIOS::get_singleton()) {
  218. DisplayServerIOS::get_singleton()->resize_window(self.bounds.size);
  219. }
  220. }
  221. [super layoutSubviews];
  222. }
  223. // MARK: - Input
  224. // MARK: Touches
  225. - (void)initTouches {
  226. for (int i = 0; i < max_touches; i++) {
  227. godot_touches[i] = nullptr;
  228. }
  229. }
  230. - (int)getTouchIDForTouch:(UITouch *)p_touch {
  231. int first = -1;
  232. for (int i = 0; i < max_touches; i++) {
  233. if (first == -1 && godot_touches[i] == nullptr) {
  234. first = i;
  235. continue;
  236. }
  237. if (godot_touches[i] == p_touch) {
  238. return i;
  239. }
  240. }
  241. if (first != -1) {
  242. godot_touches[first] = p_touch;
  243. return first;
  244. }
  245. return -1;
  246. }
  247. - (int)removeTouch:(UITouch *)p_touch {
  248. int remaining = 0;
  249. for (int i = 0; i < max_touches; i++) {
  250. if (godot_touches[i] == nullptr) {
  251. continue;
  252. }
  253. if (godot_touches[i] == p_touch) {
  254. godot_touches[i] = nullptr;
  255. } else {
  256. ++remaining;
  257. }
  258. }
  259. return remaining;
  260. }
  261. - (void)clearTouches {
  262. for (int i = 0; i < max_touches; i++) {
  263. godot_touches[i] = nullptr;
  264. }
  265. }
  266. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  267. for (UITouch *touch in touches) {
  268. int tid = [self getTouchIDForTouch:touch];
  269. ERR_FAIL_COND(tid == -1);
  270. CGPoint touchPoint = [touch locationInView:self];
  271. DisplayServerIOS::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, true, touch.tapCount > 1);
  272. }
  273. }
  274. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  275. for (UITouch *touch in touches) {
  276. int tid = [self getTouchIDForTouch:touch];
  277. ERR_FAIL_COND(tid == -1);
  278. CGPoint touchPoint = [touch locationInView:self];
  279. CGPoint prev_point = [touch previousLocationInView:self];
  280. CGFloat alt = [touch altitudeAngle];
  281. CGVector azim = [touch azimuthUnitVectorInView:self];
  282. DisplayServerIOS::get_singleton()->touch_drag(tid, prev_point.x * self.contentScaleFactor, prev_point.y * self.contentScaleFactor, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, [touch force] / [touch maximumPossibleForce], Vector2(azim.dx, azim.dy) * Math::cos(alt));
  283. }
  284. }
  285. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  286. for (UITouch *touch in touches) {
  287. int tid = [self getTouchIDForTouch:touch];
  288. ERR_FAIL_COND(tid == -1);
  289. [self removeTouch:touch];
  290. CGPoint touchPoint = [touch locationInView:self];
  291. DisplayServerIOS::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, false, false);
  292. }
  293. }
  294. - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
  295. for (UITouch *touch in touches) {
  296. int tid = [self getTouchIDForTouch:touch];
  297. ERR_FAIL_COND(tid == -1);
  298. DisplayServerIOS::get_singleton()->touches_canceled(tid);
  299. }
  300. [self clearTouches];
  301. }
  302. // MARK: Motion
  303. - (void)handleMotion {
  304. if (!self.motionManager) {
  305. return;
  306. }
  307. // Just using polling approach for now, we can set this up so it sends
  308. // data to us in intervals, might be better. See Apple reference pages
  309. // for more details:
  310. // https://developer.apple.com/reference/coremotion/cmmotionmanager?language=objc
  311. // Apple splits our accelerometer date into a gravity and user movement
  312. // component. We add them back together.
  313. CMAcceleration gravity = self.motionManager.deviceMotion.gravity;
  314. CMAcceleration acceleration = self.motionManager.deviceMotion.userAcceleration;
  315. // To be consistent with Android we convert the unit of measurement from g (Earth's gravity)
  316. // to m/s^2.
  317. gravity.x *= earth_gravity;
  318. gravity.y *= earth_gravity;
  319. gravity.z *= earth_gravity;
  320. acceleration.x *= earth_gravity;
  321. acceleration.y *= earth_gravity;
  322. acceleration.z *= earth_gravity;
  323. ///@TODO We don't seem to be getting data here, is my device broken or
  324. /// is this code incorrect?
  325. CMMagneticField magnetic = self.motionManager.deviceMotion.magneticField.field;
  326. ///@TODO we can access rotationRate as a CMRotationRate variable
  327. ///(processed date) or CMGyroData (raw data), have to see what works
  328. /// best
  329. CMRotationRate rotation = self.motionManager.deviceMotion.rotationRate;
  330. // Adjust for screen orientation.
  331. // [[UIDevice currentDevice] orientation] changes even if we've fixed
  332. // our orientation which is not a good thing when you're trying to get
  333. // your user to move the screen in all directions and want consistent
  334. // output
  335. ///@TODO Using [[UIApplication sharedApplication] statusBarOrientation]
  336. /// is a bit of a hack. Godot obviously knows the orientation so maybe
  337. /// we
  338. // can use that instead? (note that left and right seem swapped)
  339. UIInterfaceOrientation interfaceOrientation = UIInterfaceOrientationUnknown;
  340. if (@available(iOS 13, *)) {
  341. interfaceOrientation = [UIApplication sharedApplication].delegate.window.windowScene.interfaceOrientation;
  342. #if !defined(TARGET_OS_SIMULATOR) || !TARGET_OS_SIMULATOR
  343. } else {
  344. interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  345. #endif
  346. }
  347. switch (interfaceOrientation) {
  348. case UIInterfaceOrientationLandscapeLeft: {
  349. DisplayServerIOS::get_singleton()->update_gravity(-gravity.y, gravity.x, gravity.z);
  350. DisplayServerIOS::get_singleton()->update_accelerometer(-(acceleration.y + gravity.y), (acceleration.x + gravity.x), acceleration.z + gravity.z);
  351. DisplayServerIOS::get_singleton()->update_magnetometer(-magnetic.y, magnetic.x, magnetic.z);
  352. DisplayServerIOS::get_singleton()->update_gyroscope(-rotation.y, rotation.x, rotation.z);
  353. } break;
  354. case UIInterfaceOrientationLandscapeRight: {
  355. DisplayServerIOS::get_singleton()->update_gravity(gravity.y, -gravity.x, gravity.z);
  356. DisplayServerIOS::get_singleton()->update_accelerometer((acceleration.y + gravity.y), -(acceleration.x + gravity.x), acceleration.z + gravity.z);
  357. DisplayServerIOS::get_singleton()->update_magnetometer(magnetic.y, -magnetic.x, magnetic.z);
  358. DisplayServerIOS::get_singleton()->update_gyroscope(rotation.y, -rotation.x, rotation.z);
  359. } break;
  360. case UIInterfaceOrientationPortraitUpsideDown: {
  361. DisplayServerIOS::get_singleton()->update_gravity(-gravity.x, gravity.y, gravity.z);
  362. DisplayServerIOS::get_singleton()->update_accelerometer(-(acceleration.x + gravity.x), (acceleration.y + gravity.y), acceleration.z + gravity.z);
  363. DisplayServerIOS::get_singleton()->update_magnetometer(-magnetic.x, magnetic.y, magnetic.z);
  364. DisplayServerIOS::get_singleton()->update_gyroscope(-rotation.x, rotation.y, rotation.z);
  365. } break;
  366. default: { // assume portrait
  367. DisplayServerIOS::get_singleton()->update_gravity(gravity.x, gravity.y, gravity.z);
  368. DisplayServerIOS::get_singleton()->update_accelerometer(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z);
  369. DisplayServerIOS::get_singleton()->update_magnetometer(magnetic.x, magnetic.y, magnetic.z);
  370. DisplayServerIOS::get_singleton()->update_gyroscope(rotation.x, rotation.y, rotation.z);
  371. } break;
  372. }
  373. }
  374. @end