2020-07-15 18:59:57 +00:00
/**************************************************************************/
/* godot_view.mm */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#import "godot_view.h"
2022-02-16 12:56:32 +00:00
2023-06-08 12:51:32 +00:00
#import "display_layer.h"
#import "display_server_ios.h"
#import "godot_view_renderer.h"
2022-10-30 03:31:13 +00:00
#include "core/config/project_settings.h"
2020-07-15 18:59:57 +00:00
#include "core/os/keyboard.h"
2020-11-07 22:33:38 +00:00
#include "core/string/ustring.h"
2020-07-15 18:59:57 +00:00
#import <CoreMotion/CoreMotion.h>
2023-03-04 16:24:00 +00:00
static const int max_touches = 32;
2021-03-16 20:08:55 +00:00
static const float earth_gravity = 9.80665;
2020-07-15 18:59:57 +00:00
@interface GodotView () {
UITouch *godot_touches[max_touches];
}
@property(assign, nonatomic) BOOL isActive;
// 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
@property(strong, nonatomic) CADisplayLink *displayLink;
// An animation timer that, when animation is started, will periodically call -drawView at the given rate.
// Only used if CADisplayLink is not
@property(strong, nonatomic) NSTimer *animationTimer;
@property(strong, nonatomic) CALayer<DisplayLayer> *renderingLayer;
@property(strong, nonatomic) CMMotionManager *motionManager;
@end
@implementation GodotView
- (CALayer<DisplayLayer> *)initializeRenderingForDriver:(NSString *)driverName {
if (self.renderingLayer) {
return self.renderingLayer;
}
CALayer<DisplayLayer> *layer;
if ([driverName isEqualToString:@"vulkan"]) {
2023-01-20 22:20:30 +00:00
#if defined(TARGET_OS_SIMULATOR) && TARGET_OS_SIMULATOR
if (@available(iOS 13, *)) {
layer = [GodotMetalLayer layer];
} else {
return nil;
}
#else
2020-07-15 18:59:57 +00:00
layer = [GodotMetalLayer layer];
2023-01-20 22:20:30 +00:00
#endif
2022-09-08 00:44:36 +00:00
} else if ([driverName isEqualToString:@"opengl3"]) {
2023-09-27 18:15:17 +00:00
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations" // OpenGL is deprecated in iOS 12.0
2020-07-15 18:59:57 +00:00
layer = [GodotOpenGLLayer layer];
2023-09-27 18:15:17 +00:00
#pragma clang diagnostic pop
2020-07-15 18:59:57 +00:00
} else {
return nil;
}
layer.frame = self.bounds;
layer.contentsScale = self.contentScaleFactor;
[self.layer addSublayer:layer];
self.renderingLayer = layer;
[layer initializeDisplayLayer];
return self.renderingLayer;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
[self godot_commonInit];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self godot_commonInit];
}
return self;
}
- (void)dealloc {
[self stopRendering];
self.renderer = nil;
2020-07-27 12:04:13 +00:00
self.delegate = nil;
2020-07-15 18:59:57 +00:00
if (self.renderingLayer) {
[self.renderingLayer removeFromSuperlayer];
self.renderingLayer = nil;
}
if (self.motionManager) {
[self.motionManager stopDeviceMotionUpdates];
self.motionManager = nil;
}
if (self.displayLink) {
[self.displayLink invalidate];
self.displayLink = nil;
}
if (self.animationTimer) {
[self.animationTimer invalidate];
self.animationTimer = nil;
}
}
- (void)godot_commonInit {
2022-12-23 13:57:56 +00:00
self.contentScaleFactor = [UIScreen mainScreen].scale;
2020-07-15 18:59:57 +00:00
[self initTouches];
2022-02-26 20:18:28 +00:00
self.multipleTouchEnabled = YES;
2020-07-15 18:59:57 +00:00
// Configure and start accelerometer
if (!self.motionManager) {
2020-10-01 19:18:39 +00:00
self.motionManager = [[CMMotionManager alloc] init];
2020-07-15 18:59:57 +00:00
if (self.motionManager.deviceMotionAvailable) {
self.motionManager.deviceMotionUpdateInterval = 1.0 / 70.0;
[self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical];
} else {
self.motionManager = nil;
}
}
}
2024-01-19 18:46:26 +00:00
- (void)system_theme_changed {
DisplayServerIOS *ds = (DisplayServerIOS *)DisplayServer::get_singleton();
if (ds) {
ds->emit_system_theme_changed();
}
}
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
if (@available(iOS 13.0, *)) {
[super traitCollectionDidChange:previousTraitCollection];
if ([UITraitCollection currentTraitCollection].userInterfaceStyle != previousTraitCollection.userInterfaceStyle) {
[self system_theme_changed];
}
}
}
2020-07-15 18:59:57 +00:00
- (void)stopRendering {
if (!self.isActive) {
return;
}
self.isActive = NO;
2023-03-15 08:40:36 +00:00
print_verbose("Stop animation!");
2020-07-15 18:59:57 +00:00
if (self.useCADisplayLink) {
[self.displayLink invalidate];
self.displayLink = nil;
} else {
[self.animationTimer invalidate];
self.animationTimer = nil;
}
[self clearTouches];
}
- (void)startRendering {
if (self.isActive) {
return;
}
self.isActive = YES;
2023-03-15 08:40:36 +00:00
print_verbose("Start animation!");
2020-07-15 18:59:57 +00:00
if (self.useCADisplayLink) {
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView)];
2022-10-30 03:31:13 +00:00
if (GLOBAL_GET("display/window/ios/allow_high_refresh_rate")) {
self.displayLink.preferredFramesPerSecond = 120;
} else {
self.displayLink.preferredFramesPerSecond = 60;
}
2020-07-15 18:59:57 +00:00
// Setup DisplayLink in main thread
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
} else {
2022-10-30 03:31:13 +00:00
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0 / 60) target:self selector:@selector(drawView) userInfo:nil repeats:YES];
2020-07-15 18:59:57 +00:00
}
}
- (void)drawView {
if (!self.isActive) {
2023-03-15 08:40:36 +00:00
print_verbose("Draw view not active!");
2020-07-15 18:59:57 +00:00
return;
}
if (self.useCADisplayLink) {
// Pause the CADisplayLink to avoid recursion
[self.displayLink setPaused:YES];
// Process all input events
2022-02-16 12:56:32 +00:00
while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, TRUE) == kCFRunLoopRunHandledSource) {
// Continue.
}
2020-07-15 18:59:57 +00:00
// We are good to go, resume the CADisplayLink
[self.displayLink setPaused:NO];
}
2023-01-20 22:20:30 +00:00
[self.renderingLayer startRenderDisplayLayer];
2020-07-15 18:59:57 +00:00
if (!self.renderer) {
return;
}
if ([self.renderer setupView:self]) {
return;
}
2020-07-27 12:04:13 +00:00
if (self.delegate) {
BOOL delegateFinishedSetup = [self.delegate godotViewFinishedSetup:self];
if (!delegateFinishedSetup) {
return;
}
}
2020-07-15 18:59:57 +00:00
[self handleMotion];
[self.renderer renderOnView:self];
2023-01-20 22:20:30 +00:00
[self.renderingLayer stopRenderDisplayLayer];
2020-07-15 18:59:57 +00:00
}
- (BOOL)canRender {
if (self.useCADisplayLink) {
return self.displayLink != nil;
} else {
return self.animationTimer != nil;
}
}
- (void)setRenderingInterval:(NSTimeInterval)renderingInterval {
_renderingInterval = renderingInterval;
if (self.canRender) {
[self stopRendering];
[self startRendering];
}
}
- (void)layoutSubviews {
if (self.renderingLayer) {
self.renderingLayer.frame = self.bounds;
[self.renderingLayer layoutDisplayLayer];
2022-07-20 06:28:22 +00:00
if (DisplayServerIOS::get_singleton()) {
DisplayServerIOS::get_singleton()->resize_window(self.bounds.size);
2020-07-15 18:59:57 +00:00
}
}
[super layoutSubviews];
}
// MARK: - Input
// MARK: Touches
- (void)initTouches {
for (int i = 0; i < max_touches; i++) {
2021-04-29 09:47:24 +00:00
godot_touches[i] = nullptr;
2020-07-15 18:59:57 +00:00
}
}
- (int)getTouchIDForTouch:(UITouch *)p_touch {
int first = -1;
for (int i = 0; i < max_touches; i++) {
2021-04-29 09:47:24 +00:00
if (first == -1 && godot_touches[i] == nullptr) {
2020-07-15 18:59:57 +00:00
first = i;
continue;
}
if (godot_touches[i] == p_touch) {
return i;
}
}
if (first != -1) {
godot_touches[first] = p_touch;
return first;
}
return -1;
}
- (int)removeTouch:(UITouch *)p_touch {
int remaining = 0;
for (int i = 0; i < max_touches; i++) {
2021-04-29 09:47:24 +00:00
if (godot_touches[i] == nullptr) {
2020-07-15 18:59:57 +00:00
continue;
}
if (godot_touches[i] == p_touch) {
2021-04-29 09:47:24 +00:00
godot_touches[i] = nullptr;
2020-07-15 18:59:57 +00:00
} else {
++remaining;
}
}
return remaining;
}
- (void)clearTouches {
for (int i = 0; i < max_touches; i++) {
2021-04-29 09:47:24 +00:00
godot_touches[i] = nullptr;
2020-07-15 18:59:57 +00:00
}
}
2022-11-26 03:18:35 +00:00
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
int tid = [self getTouchIDForTouch:touch];
ERR_FAIL_COND(tid == -1);
CGPoint touchPoint = [touch locationInView:self];
DisplayServerIOS::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, true, touch.tapCount > 1);
2020-07-15 18:59:57 +00:00
}
}
2022-11-26 03:18:35 +00:00
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
int tid = [self getTouchIDForTouch:touch];
ERR_FAIL_COND(tid == -1);
CGPoint touchPoint = [touch locationInView:self];
CGPoint prev_point = [touch previousLocationInView:self];
CGFloat alt = [touch altitudeAngle];
CGVector azim = [touch azimuthUnitVectorInView:self];
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));
2020-07-15 18:59:57 +00:00
}
}
2022-11-26 03:18:35 +00:00
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
int tid = [self getTouchIDForTouch:touch];
ERR_FAIL_COND(tid == -1);
[self removeTouch:touch];
CGPoint touchPoint = [touch locationInView:self];
DisplayServerIOS::get_singleton()->touch_press(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, false, false);
2020-07-15 18:59:57 +00:00
}
}
2022-11-26 03:18:35 +00:00
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
int tid = [self getTouchIDForTouch:touch];
ERR_FAIL_COND(tid == -1);
DisplayServerIOS::get_singleton()->touches_canceled(tid);
2020-07-15 18:59:57 +00:00
}
[self clearTouches];
}
// MARK: Motion
- (void)handleMotion {
if (!self.motionManager) {
return;
}
// Just using polling approach for now, we can set this up so it sends
// data to us in intervals, might be better. See Apple reference pages
// for more details:
// https://developer.apple.com/reference/coremotion/cmmotionmanager?language=objc
// Apple splits our accelerometer date into a gravity and user movement
2021-03-16 20:08:55 +00:00
// component. We add them back together.
2020-07-15 18:59:57 +00:00
CMAcceleration gravity = self.motionManager.deviceMotion.gravity;
CMAcceleration acceleration = self.motionManager.deviceMotion.userAcceleration;
2021-03-16 20:08:55 +00:00
// To be consistent with Android we convert the unit of measurement from g (Earth's gravity)
// to m/s^2.
gravity.x *= earth_gravity;
gravity.y *= earth_gravity;
gravity.z *= earth_gravity;
acceleration.x *= earth_gravity;
acceleration.y *= earth_gravity;
acceleration.z *= earth_gravity;
2020-07-15 18:59:57 +00:00
///@TODO We don't seem to be getting data here, is my device broken or
/// is this code incorrect?
CMMagneticField magnetic = self.motionManager.deviceMotion.magneticField.field;
///@TODO we can access rotationRate as a CMRotationRate variable
///(processed date) or CMGyroData (raw data), have to see what works
/// best
CMRotationRate rotation = self.motionManager.deviceMotion.rotationRate;
// Adjust for screen orientation.
// [[UIDevice currentDevice] orientation] changes even if we've fixed
// our orientation which is not a good thing when you're trying to get
// your user to move the screen in all directions and want consistent
// output
///@TODO Using [[UIApplication sharedApplication] statusBarOrientation]
/// is a bit of a hack. Godot obviously knows the orientation so maybe
/// we
// can use that instead? (note that left and right seem swapped)
UIInterfaceOrientation interfaceOrientation = UIInterfaceOrientationUnknown;
if (@available(iOS 13, *)) {
interfaceOrientation = [UIApplication sharedApplication].delegate.window.windowScene.interfaceOrientation;
#if !defined(TARGET_OS_SIMULATOR) || !TARGET_OS_SIMULATOR
} else {
interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
#endif
}
switch (interfaceOrientation) {
case UIInterfaceOrientationLandscapeLeft: {
2022-07-20 06:28:22 +00:00
DisplayServerIOS::get_singleton()->update_gravity(-gravity.y, gravity.x, gravity.z);
DisplayServerIOS::get_singleton()->update_accelerometer(-(acceleration.y + gravity.y), (acceleration.x + gravity.x), acceleration.z + gravity.z);
DisplayServerIOS::get_singleton()->update_magnetometer(-magnetic.y, magnetic.x, magnetic.z);
DisplayServerIOS::get_singleton()->update_gyroscope(-rotation.y, rotation.x, rotation.z);
2020-07-15 18:59:57 +00:00
} break;
case UIInterfaceOrientationLandscapeRight: {
2022-07-20 06:28:22 +00:00
DisplayServerIOS::get_singleton()->update_gravity(gravity.y, -gravity.x, gravity.z);
DisplayServerIOS::get_singleton()->update_accelerometer((acceleration.y + gravity.y), -(acceleration.x + gravity.x), acceleration.z + gravity.z);
DisplayServerIOS::get_singleton()->update_magnetometer(magnetic.y, -magnetic.x, magnetic.z);
DisplayServerIOS::get_singleton()->update_gyroscope(rotation.y, -rotation.x, rotation.z);
2020-07-15 18:59:57 +00:00
} break;
case UIInterfaceOrientationPortraitUpsideDown: {
2022-07-20 06:28:22 +00:00
DisplayServerIOS::get_singleton()->update_gravity(-gravity.x, gravity.y, gravity.z);
DisplayServerIOS::get_singleton()->update_accelerometer(-(acceleration.x + gravity.x), (acceleration.y + gravity.y), acceleration.z + gravity.z);
DisplayServerIOS::get_singleton()->update_magnetometer(-magnetic.x, magnetic.y, magnetic.z);
DisplayServerIOS::get_singleton()->update_gyroscope(-rotation.x, rotation.y, rotation.z);
2020-07-15 18:59:57 +00:00
} break;
default: { // assume portrait
2022-07-20 06:28:22 +00:00
DisplayServerIOS::get_singleton()->update_gravity(gravity.x, gravity.y, gravity.z);
DisplayServerIOS::get_singleton()->update_accelerometer(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z);
DisplayServerIOS::get_singleton()->update_magnetometer(magnetic.x, magnetic.y, magnetic.z);
DisplayServerIOS::get_singleton()->update_gyroscope(rotation.x, rotation.y, rotation.z);
2020-07-15 18:59:57 +00:00
} break;
}
}
@end