Debian Codegraph @

drivers/apple_embedded/godot_view_apple_embedded.mm

raw
1 /**************************************************************************/
2 /* godot_view_apple_embedded.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
31 #import "godot_view_apple_embedded.h"
32
33 #import "display_layer_apple_embedded.h"
34 #import "display_server_apple_embedded.h"
35 #import "godot_view_renderer.h"
36
37 #include "core/config/project_settings.h"
38 #include "core/os/keyboard.h"
39 #include "core/string/ustring.h"
40
41 #import <CoreMotion/CoreMotion.h>
42
43 static const int max_touches = 32;
44 static const float earth_gravity = 9.80665;
45
46 @interface GDTView () {
47 UITouch *godot_touches[max_touches];
48 }
49
50 @property(assign, nonatomic) BOOL isActive;
51
52 // 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
53 @property(strong, nonatomic) CADisplayLink *displayLink;
54
55 // An animation timer that, when animation is started, will periodically call -drawView at the given rate.
56 // Only used if CADisplayLink is not
57 @property(strong, nonatomic) NSTimer *animationTimer;
58
59 @property(strong, nonatomic) CALayer<GDTDisplayLayer> *renderingLayer;
60
61 @property(strong, nonatomic) CMMotionManager *motionManager;
62
63 @property(assign, nonatomic) BOOL delegateDidFinishSetUp;
64
65 @end
66
67 @implementation GDTView
68
69 // Implemented in subclasses
70 - (CALayer<GDTDisplayLayer> *)initializeRenderingForDriver:(NSString *)driverName {
71 return nil;
72 }
73
74 - (instancetype)initWithCoder:(NSCoder *)coder {
75 self = [super initWithCoder:coder];
76
77 if (self) {
78 [self godot_commonInit];
79 }
80
81 return self;
82 }
83
84 - (instancetype)initWithFrame:(CGRect)frame {
85 self = [super initWithFrame:frame];
86
87 if (self) {
88 [self godot_commonInit];
89 }
90
91 return self;
92 }
93
94 - (void)dealloc {
95 [self stopRendering];
96
97 self.renderer = nil;
98 self.delegate = nil;
99
100 if (self.renderingLayer) {
101 [self.renderingLayer removeFromSuperlayer];
102 self.renderingLayer = nil;
103 }
104
105 if (self.motionManager) {
106 [self.motionManager stopDeviceMotionUpdates];
107 self.motionManager = nil;
108 }
109
110 if (self.displayLink) {
111 [self.displayLink invalidate];
112 self.displayLink = nil;
113 }
114
115 if (self.animationTimer) {
116 [self.animationTimer invalidate];
117 self.animationTimer = nil;
118 }
119 }
120
121 - (void)godot_commonInit {
122 self.preferredFrameRate = 60;
123 self.useCADisplayLink = bool(GLOBAL_DEF("display.AppleEmbedded/use_cadisplaylink", true)) ? YES : NO;
124
125 #if !defined(VISIONOS_ENABLED)
126 self.contentScaleFactor = [UIScreen mainScreen].scale;
127 #endif
128
129 if (@available(iOS 17.0, *)) {
130 [self registerForTraitChanges:@[ [UITraitUserInterfaceStyle class] ] withTarget:self action:@selector(traitCollectionDidChangeWithView:previousTraitCollection:)];
131 }
132
133 [self initTouches];
134
135 self.multipleTouchEnabled = YES;
136
137 // Configure and start accelerometer
138 if (!self.motionManager) {
139 self.motionManager = [[CMMotionManager alloc] init];
140 if (self.motionManager.deviceMotionAvailable) {
141 self.motionManager.deviceMotionUpdateInterval = 1.0 / 70.0;
142 [self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical];
143 } else {
144 self.motionManager = nil;
145 }
146 }
147 }
148
149 - (void)system_theme_changed {
150 DisplayServerAppleEmbedded *ds = (DisplayServerAppleEmbedded *)DisplayServer::get_singleton();
151 if (ds) {
152 ds->emit_system_theme_changed();
153 }
154 }
155
156 - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
157 if (@available(iOS 13.0, *)) {
158 #if !defined(VISIONOS_ENABLED)
159 [super traitCollectionDidChange:previousTraitCollection];
160 #endif
161 [self traitCollectionDidChangeWithView:self
162 previousTraitCollection:previousTraitCollection];
163 }
164 }
165
166 - (void)traitCollectionDidChangeWithView:(UIView *)view previousTraitCollection:(UITraitCollection *)previousTraitCollection {
167 if (@available(iOS 13.0, *)) {
168 if ([UITraitCollection currentTraitCollection].userInterfaceStyle != previousTraitCollection.userInterfaceStyle) {
169 [self system_theme_changed];
170 }
171 }
172 }
173
174 - (void)stopRendering {
175 if (!self.isActive) {
176 return;
177 }
178
179 self.isActive = NO;
180
181 print_verbose("Stop animation!");
182
183 if (self.useCADisplayLink) {
184 [self.displayLink invalidate];
185 self.displayLink = nil;
186 } else {
187 [self.animationTimer invalidate];
188 self.animationTimer = nil;
189 }
190
191 [self clearTouches];
192 }
193
194 - (void)startRendering {
195 if (self.isActive) {
196 return;
197 }
198
199 self.isActive = YES;
200
201 print_verbose("Start animation!");
202
203 if (self.useCADisplayLink) {
204 self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView)];
205 self.displayLink.preferredFramesPerSecond = self.preferredFrameRate;
206
207 // Setup DisplayLink in main thread
208 [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
209 } else {
210 self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0 / self.preferredFrameRate) target:self selector:@selector(drawView) userInfo:nil repeats:YES];
211 }
212 }
213
214 - (void)drawView {
215 if (!self.isActive) {
216 print_verbose("Draw view not active!");
217 return;
218 }
219
220 if (self.useCADisplayLink) {
221 // Pause the CADisplayLink to avoid recursion
222 [self.displayLink setPaused:YES];
223
224 // Process all input events
225 while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, TRUE) == kCFRunLoopRunHandledSource) {
226 // Continue.
227 }
228
229 // We are good to go, resume the CADisplayLink
230 [self.displayLink setPaused:NO];
231 }
232
233 [self.renderingLayer startRenderDisplayLayer];
234
235 if (!self.renderer) {
236 return;
237 }
238
239 if ([self.renderer setupView:self]) {
240 return;
241 }
242
243 if (self.delegate && !self.delegateDidFinishSetUp) {
244 [self layoutRenderingLayer]; // Trigger DisplayServerVisionOS::resize_window after Main::start()
245 self.delegateDidFinishSetUp = [self.delegate godotViewFinishedSetup:self];
246 if (!_delegateDidFinishSetUp) {
247 return;
248 }
249 }
250
251 [self handleMotion];
252 [self.renderer renderOnView:self];
253
254 [self.renderingLayer stopRenderDisplayLayer];
255 }
256
257 - (BOOL)canRender {
258 if (self.useCADisplayLink) {
259 return self.displayLink != nil;
260 } else {
261 return self.animationTimer != nil;
262 }
263 }
264
265 - (void)setPreferredFrameRate:(float)preferredFrameRate {
266 _preferredFrameRate = preferredFrameRate;
267
268 if (self.canRender) {
269 [self stopRendering];
270 [self startRendering];
271 }
272 }
273
274 - (void)layoutSubviews {
275 [super layoutSubviews];
276 [self layoutRenderingLayer];
277 }
278
279 - (void)layoutRenderingLayer {
280 if (self.renderingLayer) {
281 self.renderingLayer.frame = self.bounds;
282 [self.renderingLayer layoutDisplayLayer];
283
284 if (DisplayServerAppleEmbedded::get_singleton()) {
285 DisplayServerAppleEmbedded::get_singleton()->resize_window(self.bounds.size);
286 }
287 }
288 }
289
290 // MARK: - Input
291
292 // MARK: Touches
293
294 - (void)initTouches {
295 for (int i = 0; i < max_touches; i++) {
296 godot_touches[i] = nullptr;
297 }
298 }
299
300 - (int)getTouchIDForTouch:(UITouch *)p_touch {
301 int first = -1;
302 for (int i = 0; i < max_touches; i++) {
303 if (first == -1 && godot_touches[i] == nullptr) {
304 first = i;
305 continue;
306 }
307 if (godot_touches[i] == p_touch) {
308 return i;
309 }
310 }
311
312 if (first != -1) {
313 godot_touches[first] = p_touch;
314 return first;
315 }
316
317 return -1;
318 }
319
320 - (int)removeTouch:(UITouch *)p_touch {
321 int remaining = 0;
322 for (int i = 0; i < max_touches; i++) {
323 if (godot_touches[i] == nullptr) {
324 continue;
325 }
326 if (godot_touches[i] == p_touch) {
327 godot_touches[i] = nullptr;
328 } else {
329 ++remaining;
330 }
331 }
332 return remaining;
333 }
334
335 - (void)clearTouches {
336 for (int i = 0; i < max_touches; i++) {
337 godot_touches[i] = nullptr;
338 }
339 }
340
341 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
342 for (UITouch *touch in touches) {
343 int tid = [self getTouchIDForTouch:touch];
344 ERR_FAIL_COND(tid == -1);
345 CGPoint touchPoint = [touch locationInView:self];
346 DisplayServerAppleEmbedded::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, true, touch.tapCount > 1);
347 }
348 }
349
350 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
351 for (UITouch *touch in touches) {
352 int tid = [self getTouchIDForTouch:touch];
353 ERR_FAIL_COND(tid == -1);
354 CGPoint touchPoint = [touch locationInView:self];
355 CGPoint prev_point = [touch previousLocationInView:self];
356 CGFloat alt = [touch altitudeAngle];
357 CGVector azim = [touch azimuthUnitVectorInView:self];
358 DisplayServerAppleEmbedded::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));
359 }
360 }
361
362 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
363 for (UITouch *touch in touches) {
364 int tid = [self getTouchIDForTouch:touch];
365 ERR_FAIL_COND(tid == -1);
366 [self removeTouch:touch];
367 CGPoint touchPoint = [touch locationInView:self];
368 DisplayServerAppleEmbedded::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, false, false);
369 }
370 }
371
372 - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
373 for (UITouch *touch in touches) {
374 int tid = [self getTouchIDForTouch:touch];
375 ERR_FAIL_COND(tid == -1);
376 DisplayServerAppleEmbedded::get_singleton()->touches_canceled(tid);
377 }
378 [self clearTouches];
379 }
380
381 // MARK: Motion
382
383 - (void)handleMotion {
384 if (!self.motionManager) {
385 return;
386 }
387
388 // Just using polling approach for now, we can set this up so it sends
389 // data to us in intervals, might be better. See Apple reference pages
390 // for more details:
391 // https://developer.apple.com/reference/coremotion/cmmotionmanager?language=objc
392
393 // Apple splits our accelerometer date into a gravity and user movement
394 // component. We add them back together.
395 CMAcceleration gravity = self.motionManager.deviceMotion.gravity;
396 CMAcceleration acceleration = self.motionManager.deviceMotion.userAcceleration;
397
398 // To be consistent with Android we convert the unit of measurement from g (Earth's gravity)
399 // to m/s^2.
400 gravity.x *= earth_gravity;
401 gravity.y *= earth_gravity;
402 gravity.z *= earth_gravity;
403 acceleration.x *= earth_gravity;
404 acceleration.y *= earth_gravity;
405 acceleration.z *= earth_gravity;
406
407 ///@TODO We don't seem to be getting data here, is my device broken or
408 /// is this code incorrect?
409 CMMagneticField magnetic = self.motionManager.deviceMotion.magneticField.field;
410
411 ///@TODO we can access rotationRate as a CMRotationRate variable
412 ///(processed date) or CMGyroData (raw data), have to see what works
413 /// best
414 CMRotationRate rotation = self.motionManager.deviceMotion.rotationRate;
415
416 // Adjust for screen orientation.
417 // [[UIDevice currentDevice] orientation] changes even if we've fixed
418 // our orientation which is not a good thing when you're trying to get
419 // your user to move the screen in all directions and want consistent
420 // output
421 #if defined(VISIONOS_ENABLED)
422 UIInterfaceOrientation interfaceOrientation = [UIApplication sharedApplication].delegate.window.windowScene.effectiveGeometry.interfaceOrientation;
423 #else
424 UIInterfaceOrientation interfaceOrientation = [UIApplication sharedApplication].delegate.window.windowScene.interfaceOrientation;
425 #endif
426
427 switch (interfaceOrientation) {
428 case UIInterfaceOrientationLandscapeLeft: {
429 DisplayServerAppleEmbedded::get_singleton()->update_gravity(Vector3(gravity.x, gravity.y, gravity.z).rotated(Vector3(0, 0, 1), -Math::PI * 0.5));
430 DisplayServerAppleEmbedded::get_singleton()->update_accelerometer(Vector3(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z).rotated(Vector3(0, 0, 1), -Math::PI * 0.5));
431 DisplayServerAppleEmbedded::get_singleton()->update_magnetometer(Vector3(magnetic.x, magnetic.y, magnetic.z).rotated(Vector3(0, 0, 1), -Math::PI * 0.5));
432 DisplayServerAppleEmbedded::get_singleton()->update_gyroscope(Vector3(rotation.x, rotation.y, rotation.z).rotated(Vector3(0, 0, 1), -Math::PI * 0.5));
433 } break;
434 case UIInterfaceOrientationLandscapeRight: {
435 DisplayServerAppleEmbedded::get_singleton()->update_gravity(Vector3(gravity.x, gravity.y, gravity.z).rotated(Vector3(0, 0, 1), Math::PI * 0.5));
436 DisplayServerAppleEmbedded::get_singleton()->update_accelerometer(Vector3(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z).rotated(Vector3(0, 0, 1), Math::PI * 0.5));
437 DisplayServerAppleEmbedded::get_singleton()->update_magnetometer(Vector3(magnetic.x, magnetic.y, magnetic.z).rotated(Vector3(0, 0, 1), Math::PI * 0.5));
438 DisplayServerAppleEmbedded::get_singleton()->update_gyroscope(Vector3(rotation.x, rotation.y, rotation.z).rotated(Vector3(0, 0, 1), Math::PI * 0.5));
439 } break;
440 case UIInterfaceOrientationPortraitUpsideDown: {
441 DisplayServerAppleEmbedded::get_singleton()->update_gravity(Vector3(gravity.x, gravity.y, gravity.z).rotated(Vector3(0, 0, 1), Math::PI));
442 DisplayServerAppleEmbedded::get_singleton()->update_accelerometer(Vector3(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z).rotated(Vector3(0, 0, 1), Math::PI));
443 DisplayServerAppleEmbedded::get_singleton()->update_magnetometer(Vector3(magnetic.x, magnetic.y, magnetic.z).rotated(Vector3(0, 0, 1), Math::PI));
444 DisplayServerAppleEmbedded::get_singleton()->update_gyroscope(Vector3(rotation.x, rotation.y, rotation.z).rotated(Vector3(0, 0, 1), Math::PI));
445 } break;
446 default: { // assume portrait
447 DisplayServerAppleEmbedded::get_singleton()->update_gravity(Vector3(gravity.x, gravity.y, gravity.z));
448 DisplayServerAppleEmbedded::get_singleton()->update_accelerometer(Vector3(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z));
449 DisplayServerAppleEmbedded::get_singleton()->update_magnetometer(Vector3(magnetic.x, magnetic.y, magnetic.z));
450 DisplayServerAppleEmbedded::get_singleton()->update_gyroscope(Vector3(rotation.x, rotation.y, rotation.z));
451 } break;
452 }
453 }
454
455 @end