godot_view.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. #include "core/project_settings.h"
  32. #include "os_iphone.h"
  33. #include "servers/audio_server.h"
  34. #import <OpenGLES/EAGLDrawable.h>
  35. #import <QuartzCore/QuartzCore.h>
  36. #import "display_layer.h"
  37. #import "godot_view_gesture_recognizer.h"
  38. #import "godot_view_renderer.h"
  39. #import <CoreMotion/CoreMotion.h>
  40. static const int max_touches = 32;
  41. @interface GodotView () {
  42. UITouch *godot_touches[max_touches];
  43. }
  44. @property(assign, nonatomic) BOOL isActive;
  45. // 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
  46. @property(strong, nonatomic) CADisplayLink *displayLink;
  47. // An animation timer that, when animation is started, will periodically call -drawView at the given rate.
  48. // Only used if CADisplayLink is not
  49. @property(strong, nonatomic) NSTimer *animationTimer;
  50. @property(strong, nonatomic) CALayer<DisplayLayer> *renderingLayer;
  51. @property(strong, nonatomic) CMMotionManager *motionManager;
  52. @property(strong, nonatomic) GodotViewGestureRecognizer *delayGestureRecognizer;
  53. @end
  54. @implementation GodotView
  55. // Implement this to override the default layer class (which is [CALayer class]).
  56. // We do this so that our view will be backed by a layer that is capable of OpenGL ES rendering.
  57. - (CALayer<DisplayLayer> *)initializeRendering {
  58. if (self.renderingLayer) {
  59. return self.renderingLayer;
  60. }
  61. CALayer<DisplayLayer> *layer = [GodotOpenGLLayer layer];
  62. layer.frame = self.bounds;
  63. layer.contentsScale = self.contentScaleFactor;
  64. [self.layer addSublayer:layer];
  65. self.renderingLayer = layer;
  66. [layer initializeDisplayLayer];
  67. return self.renderingLayer;
  68. }
  69. - (instancetype)initWithCoder:(NSCoder *)coder {
  70. self = [super initWithCoder:coder];
  71. if (self) {
  72. [self godot_commonInit];
  73. }
  74. return self;
  75. }
  76. - (instancetype)initWithFrame:(CGRect)frame {
  77. self = [super initWithFrame:frame];
  78. if (self) {
  79. [self godot_commonInit];
  80. }
  81. return self;
  82. }
  83. // Stop animating and release resources when they are no longer needed.
  84. - (void)dealloc {
  85. [self stopRendering];
  86. self.renderer = nil;
  87. self.delegate = nil;
  88. if (self.renderingLayer) {
  89. [self.renderingLayer removeFromSuperlayer];
  90. self.renderingLayer = nil;
  91. }
  92. if (self.motionManager) {
  93. [self.motionManager stopDeviceMotionUpdates];
  94. self.motionManager = nil;
  95. }
  96. if (self.displayLink) {
  97. [self.displayLink invalidate];
  98. self.displayLink = nil;
  99. }
  100. if (self.animationTimer) {
  101. [self.animationTimer invalidate];
  102. self.animationTimer = nil;
  103. }
  104. if (self.delayGestureRecognizer) {
  105. self.delayGestureRecognizer = nil;
  106. }
  107. }
  108. - (void)godot_commonInit {
  109. self.contentScaleFactor = [UIScreen mainScreen].nativeScale;
  110. [self initTouches];
  111. self.multipleTouchEnabled = YES;
  112. // Configure and start accelerometer
  113. if (!self.motionManager) {
  114. self.motionManager = [[CMMotionManager alloc] init];
  115. if (self.motionManager.deviceMotionAvailable) {
  116. self.motionManager.deviceMotionUpdateInterval = 1.0 / 70.0;
  117. [self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical];
  118. } else {
  119. self.motionManager = nil;
  120. }
  121. }
  122. // Initialize delay gesture recognizer
  123. GodotViewGestureRecognizer *gestureRecognizer = [[GodotViewGestureRecognizer alloc] init];
  124. self.delayGestureRecognizer = gestureRecognizer;
  125. [self addGestureRecognizer:self.delayGestureRecognizer];
  126. }
  127. - (void)startRendering {
  128. if (self.isActive) {
  129. return;
  130. }
  131. self.isActive = YES;
  132. printf("start animation!\n");
  133. if (self.useCADisplayLink) {
  134. self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView)];
  135. // Approximate frame rate
  136. // assumes device refreshes at 60 fps
  137. int displayFPS = (NSInteger)(1.0 / self.renderingInterval);
  138. self.displayLink.preferredFramesPerSecond = displayFPS;
  139. // Setup DisplayLink in main thread
  140. [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  141. } else {
  142. self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:self.renderingInterval target:self selector:@selector(drawView) userInfo:nil repeats:YES];
  143. }
  144. }
  145. - (void)stopRendering {
  146. if (!self.isActive) {
  147. return;
  148. }
  149. self.isActive = NO;
  150. printf("******** stop animation!\n");
  151. if (self.useCADisplayLink) {
  152. [self.displayLink invalidate];
  153. self.displayLink = nil;
  154. } else {
  155. [self.animationTimer invalidate];
  156. self.animationTimer = nil;
  157. }
  158. [self clearTouches];
  159. }
  160. // Updates the OpenGL view when the timer fires
  161. - (void)drawView {
  162. if (!self.isActive) {
  163. printf("draw view not active!\n");
  164. return;
  165. }
  166. if (self.useCADisplayLink) {
  167. // Pause the CADisplayLink to avoid recursion
  168. [self.displayLink setPaused:YES];
  169. // Process all input events
  170. while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, TRUE) == kCFRunLoopRunHandledSource)
  171. ;
  172. // We are good to go, resume the CADisplayLink
  173. [self.displayLink setPaused:NO];
  174. }
  175. [self.renderingLayer startRenderDisplayLayer];
  176. if (!self.renderer) {
  177. return;
  178. }
  179. if ([self.renderer setupView:self]) {
  180. return;
  181. }
  182. if (self.delegate) {
  183. BOOL delegateFinishedSetup = [self.delegate godotViewFinishedSetup:self];
  184. if (!delegateFinishedSetup) {
  185. return;
  186. }
  187. }
  188. [self handleMotion];
  189. [self.renderer renderOnView:self];
  190. [self.renderingLayer stopRenderDisplayLayer];
  191. }
  192. - (BOOL)canRender {
  193. if (self.useCADisplayLink) {
  194. return self.displayLink != nil;
  195. } else {
  196. return self.animationTimer != nil;
  197. }
  198. }
  199. - (void)setRenderingInterval:(NSTimeInterval)renderingInterval {
  200. _renderingInterval = renderingInterval;
  201. if (self.canRender) {
  202. [self stopRendering];
  203. [self startRendering];
  204. }
  205. }
  206. // If our view is resized, we'll be asked to layout subviews.
  207. // This is the perfect opportunity to also update the framebuffer so that it is
  208. // the same size as our display area.
  209. - (void)layoutSubviews {
  210. if (self.renderingLayer) {
  211. self.renderingLayer.frame = self.bounds;
  212. [self.renderingLayer layoutDisplayLayer];
  213. }
  214. [super layoutSubviews];
  215. }
  216. // MARK: - Input
  217. // MARK: Touches
  218. - (void)initTouches {
  219. for (int i = 0; i < max_touches; i++) {
  220. godot_touches[i] = NULL;
  221. }
  222. }
  223. - (int)getTouchIDForTouch:(UITouch *)p_touch {
  224. int first = -1;
  225. for (int i = 0; i < max_touches; i++) {
  226. if (first == -1 && godot_touches[i] == NULL) {
  227. first = i;
  228. continue;
  229. }
  230. if (godot_touches[i] == p_touch) {
  231. return i;
  232. }
  233. }
  234. if (first != -1) {
  235. godot_touches[first] = p_touch;
  236. return first;
  237. }
  238. return -1;
  239. }
  240. - (int)removeTouch:(UITouch *)p_touch {
  241. int remaining = 0;
  242. for (int i = 0; i < max_touches; i++) {
  243. if (godot_touches[i] == NULL) {
  244. continue;
  245. }
  246. if (godot_touches[i] == p_touch) {
  247. godot_touches[i] = NULL;
  248. } else {
  249. ++remaining;
  250. }
  251. }
  252. return remaining;
  253. }
  254. - (void)clearTouches {
  255. for (int i = 0; i < max_touches; i++) {
  256. godot_touches[i] = NULL;
  257. }
  258. }
  259. - (void)godotTouchesBegan:(NSSet *)touchesSet withEvent:(UIEvent *)event {
  260. NSArray *tlist = [event.allTouches allObjects];
  261. for (unsigned int i = 0; i < [tlist count]; i++) {
  262. if ([touchesSet containsObject:[tlist objectAtIndex:i]]) {
  263. UITouch *touch = [tlist objectAtIndex:i];
  264. int tid = [self getTouchIDForTouch:touch];
  265. ERR_FAIL_COND(tid == -1);
  266. CGPoint touchPoint = [touch locationInView:self];
  267. if (touch.type == UITouchTypeStylus) {
  268. OSIPhone::get_singleton()->pencil_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, true, touch.tapCount > 1);
  269. } else {
  270. OSIPhone::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, true, touch.tapCount > 1);
  271. }
  272. }
  273. }
  274. }
  275. - (void)godotTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  276. NSArray *tlist = [event.allTouches allObjects];
  277. for (unsigned int i = 0; i < [tlist count]; i++) {
  278. if ([touches containsObject:[tlist objectAtIndex:i]]) {
  279. UITouch *touch = [tlist objectAtIndex:i];
  280. int tid = [self getTouchIDForTouch:touch];
  281. ERR_FAIL_COND(tid == -1);
  282. CGPoint touchPoint = [touch locationInView:self];
  283. CGPoint prev_point = [touch previousLocationInView:self];
  284. CGFloat force = touch.force;
  285. // Vector2 tilt = touch.azimuthUnitVector;
  286. if (touch.type == UITouchTypeStylus) {
  287. OSIPhone::get_singleton()->pencil_drag(tid, prev_point.x * self.contentScaleFactor, prev_point.y * self.contentScaleFactor, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, force);
  288. } else {
  289. OSIPhone::get_singleton()->touch_drag(tid, prev_point.x * self.contentScaleFactor, prev_point.y * self.contentScaleFactor, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor);
  290. }
  291. }
  292. }
  293. }
  294. - (void)godotTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  295. NSArray *tlist = [event.allTouches allObjects];
  296. for (unsigned int i = 0; i < [tlist count]; i++) {
  297. if ([touches containsObject:[tlist objectAtIndex:i]]) {
  298. UITouch *touch = [tlist objectAtIndex:i];
  299. int tid = [self getTouchIDForTouch:touch];
  300. ERR_FAIL_COND(tid == -1);
  301. [self removeTouch:touch];
  302. CGPoint touchPoint = [touch locationInView:self];
  303. if (touch.type == UITouchTypeStylus) {
  304. OSIPhone::get_singleton()->pencil_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, false, false);
  305. } else {
  306. OSIPhone::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, false, false);
  307. }
  308. }
  309. }
  310. }
  311. - (void)godotTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
  312. NSArray *tlist = [event.allTouches allObjects];
  313. for (unsigned int i = 0; i < [tlist count]; i++) {
  314. if ([touches containsObject:[tlist objectAtIndex:i]]) {
  315. UITouch *touch = [tlist objectAtIndex:i];
  316. int tid = [self getTouchIDForTouch:touch];
  317. ERR_FAIL_COND(tid == -1);
  318. if (touch.type == UITouchTypeStylus) {
  319. OSIPhone::get_singleton()->pencil_cancelled(tid);
  320. } else {
  321. OSIPhone::get_singleton()->touches_cancelled(tid);
  322. }
  323. }
  324. }
  325. [self clearTouches];
  326. }
  327. // MARK: Motion
  328. - (void)handleMotion {
  329. if (!self.motionManager) {
  330. return;
  331. }
  332. // Just using polling approach for now, we can set this up so it sends
  333. // data to us in intervals, might be better. See Apple reference pages
  334. // for more details:
  335. // https://developer.apple.com/reference/coremotion/cmmotionmanager?language=objc
  336. // Apple splits our accelerometer date into a gravity and user movement
  337. // component. We add them back together
  338. CMAcceleration gravity = self.motionManager.deviceMotion.gravity;
  339. CMAcceleration acceleration = self.motionManager.deviceMotion.userAcceleration;
  340. ///@TODO We don't seem to be getting data here, is my device broken or
  341. /// is this code incorrect?
  342. CMMagneticField magnetic = self.motionManager.deviceMotion.magneticField.field;
  343. ///@TODO we can access rotationRate as a CMRotationRate variable
  344. ///(processed date) or CMGyroData (raw data), have to see what works
  345. /// best
  346. CMRotationRate rotation = self.motionManager.deviceMotion.rotationRate;
  347. // Adjust for screen orientation.
  348. // [[UIDevice currentDevice] orientation] changes even if we've fixed
  349. // our orientation which is not a good thing when you're trying to get
  350. // your user to move the screen in all directions and want consistent
  351. // output
  352. ///@TODO Using [[UIApplication sharedApplication] statusBarOrientation]
  353. /// is a bit of a hack. Godot obviously knows the orientation so maybe
  354. /// we
  355. // can use that instead? (note that left and right seem swapped)
  356. UIInterfaceOrientation interfaceOrientation = UIInterfaceOrientationUnknown;
  357. if (@available(iOS 13, *)) {
  358. interfaceOrientation = [UIApplication sharedApplication].delegate.window.windowScene.interfaceOrientation;
  359. } else {
  360. interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  361. }
  362. switch (interfaceOrientation) {
  363. case UIInterfaceOrientationLandscapeLeft: {
  364. OSIPhone::get_singleton()->update_gravity(-gravity.y, gravity.x, gravity.z);
  365. OSIPhone::get_singleton()->update_accelerometer(-(acceleration.y + gravity.y), (acceleration.x + gravity.x), acceleration.z + gravity.z);
  366. OSIPhone::get_singleton()->update_magnetometer(-magnetic.y, magnetic.x, magnetic.z);
  367. OSIPhone::get_singleton()->update_gyroscope(-rotation.y, rotation.x, rotation.z);
  368. } break;
  369. case UIInterfaceOrientationLandscapeRight: {
  370. OSIPhone::get_singleton()->update_gravity(gravity.y, -gravity.x, gravity.z);
  371. OSIPhone::get_singleton()->update_accelerometer((acceleration.y + gravity.y), -(acceleration.x + gravity.x), acceleration.z + gravity.z);
  372. OSIPhone::get_singleton()->update_magnetometer(magnetic.y, -magnetic.x, magnetic.z);
  373. OSIPhone::get_singleton()->update_gyroscope(rotation.y, -rotation.x, rotation.z);
  374. } break;
  375. case UIInterfaceOrientationPortraitUpsideDown: {
  376. OSIPhone::get_singleton()->update_gravity(-gravity.x, gravity.y, gravity.z);
  377. OSIPhone::get_singleton()->update_accelerometer(-(acceleration.x + gravity.x), (acceleration.y + gravity.y), acceleration.z + gravity.z);
  378. OSIPhone::get_singleton()->update_magnetometer(-magnetic.x, magnetic.y, magnetic.z);
  379. OSIPhone::get_singleton()->update_gyroscope(-rotation.x, rotation.y, rotation.z);
  380. } break;
  381. default: { // assume portrait
  382. OSIPhone::get_singleton()->update_gravity(gravity.x, gravity.y, gravity.z);
  383. OSIPhone::get_singleton()->update_accelerometer(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z);
  384. OSIPhone::get_singleton()->update_magnetometer(magnetic.x, magnetic.y, magnetic.z);
  385. OSIPhone::get_singleton()->update_gyroscope(rotation.x, rotation.y, rotation.z);
  386. } break;
  387. }
  388. }
  389. @end