Spaces to tabs and layout adjustments on .mm files

This commit is contained in:
BastiaanOlij 2017-04-08 09:47:13 +10:00
parent 63ddee793e
commit 33ea9fc4a7
12 changed files with 1172 additions and 1300 deletions

1
.gitattributes vendored
View file

@ -5,5 +5,6 @@ drivers/* linguist-vendored
*.cpp eol=lf *.cpp eol=lf
*.h eol=lf *.h eol=lf
*.mm eol=lf
*.py eol=lf *.py eol=lf
*.hpp eol=lf *.hpp eol=lf

View file

@ -58,10 +58,10 @@ void _set_keep_screen_on(bool p_enabled);
Error _shell_open(String p_uri) { Error _shell_open(String p_uri) {
NSString* url = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()]; NSString* url = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()];
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]]) if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]])
return ERR_CANT_OPEN; return ERR_CANT_OPEN;
printf("opening url %ls\n", p_uri.c_str()); printf("opening url %ls\n", p_uri.c_str());
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
[url release]; [url release];
return OK; return OK;
@ -84,8 +84,7 @@ CMMotionManager *motionManager;
bool motionInitialised; bool motionInitialised;
static ViewController* mainViewController = nil; static ViewController* mainViewController = nil;
+ (ViewController*) getViewController + (ViewController*) getViewController {
{
return mainViewController; return mainViewController;
} }
@ -93,157 +92,152 @@ static int frame_count = 0;
- (void)drawView:(GLView*)view; { - (void)drawView:(GLView*)view; {
switch (frame_count) { switch (frame_count) {
case 0: {
int backingWidth;
int backingHeight;
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
case 0: { OS::VideoMode vm;
int backingWidth; vm.fullscreen = true;
int backingHeight; vm.width = backingWidth;
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth); vm.height = backingHeight;
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight); vm.resizable = false;
OS::get_singleton()->set_video_mode(vm);
if (!OS::get_singleton()) {
OS::VideoMode vm; exit(0);
vm.fullscreen = true;
vm.width = backingWidth;
vm.height = backingHeight;
vm.resizable = false;
OS::get_singleton()->set_video_mode(vm);
if (!OS::get_singleton()) {
exit(0);
};
++frame_count;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//NSString *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
OSIPhone::get_singleton()->set_data_dir(String::utf8([documentsDirectory UTF8String]));
NSString *locale_code = [[[NSLocale preferredLanguages] objectAtIndex:0] substringToIndex:2];
OSIPhone::get_singleton()->set_locale(String::utf8([locale_code UTF8String]));
NSString* uuid;
if ([[UIDevice currentDevice]respondsToSelector:@selector(identifierForVendor)]) {
uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
}else{
// before iOS 6, so just generate an identifier and store it
uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"identiferForVendor"];
if( !uuid ) {
CFUUIDRef cfuuid = CFUUIDCreate(NULL);
uuid = (__bridge_transfer NSString*)CFUUIDCreateString(NULL, cfuuid);
CFRelease(cfuuid);
[[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"identifierForVendor"];
}
}
OSIPhone::get_singleton()->set_unique_ID(String::utf8([uuid UTF8String]));
}; break;
/*
case 1: {
++frame_count;
} break;
*/
case 1: {
Main::setup2();
++frame_count;
// this might be necessary before here
NSDictionary* dict = [[NSBundle mainBundle] infoDictionary];
for (NSString* key in dict) {
NSObject* value = [dict objectForKey:key];
String ukey = String::utf8([key UTF8String]);
// we need a NSObject to Variant conversor
if ([value isKindOfClass:[NSString class]]) {
NSString* str = (NSString*)value;
String uval = String::utf8([str UTF8String]);
Globals::get_singleton()->set("Info.plist/"+ukey, uval);
} else if ([value isKindOfClass:[NSNumber class]]) {
NSNumber* n = (NSNumber*)value;
double dval = [n doubleValue];
Globals::get_singleton()->set("Info.plist/"+ukey, dval);
}; };
// do stuff ++frame_count;
}
} break; NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
/* NSString *documentsDirectory = [paths objectAtIndex:0];
case 3: { //NSString *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
++frame_count; OSIPhone::get_singleton()->set_data_dir(String::utf8([documentsDirectory UTF8String]));
} break;
*/
case 2: {
Main::start(); NSString *locale_code = [[[NSLocale preferredLanguages] objectAtIndex:0] substringToIndex:2];
++frame_count; OSIPhone::get_singleton()->set_locale(String::utf8([locale_code UTF8String]));
}; break; // no fallthrough NSString* uuid;
if ([[UIDevice currentDevice]respondsToSelector:@selector(identifierForVendor)]) {
uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
} else {
default: { // before iOS 6, so just generate an identifier and store it
uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"identiferForVendor"];
if (OSIPhone::get_singleton()) { if( !uuid ) {
if (motionInitialised) { CFUUIDRef cfuuid = CFUUIDCreate(NULL);
// Just using polling approach for now, we can set this up so it sends data to us in intervals, might be better. uuid = (__bridge_transfer NSString*)CFUUIDCreateString(NULL, cfuuid);
// See Apple reference pages for more details: CFRelease(cfuuid);
// https://developer.apple.com/reference/coremotion/cmmotionmanager?language=objc [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"identifierForVendor"];
}
// Apple splits our accelerometer date into a gravity and user movement component. We add them back together
CMAcceleration gravity = motionManager.deviceMotion.gravity;
CMAcceleration acceleration = motionManager.deviceMotion.userAcceleration;
///@TODO We don't seem to be getting data here, is my device broken or is this code incorrect?
CMMagneticField magnetic = 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 = 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)
switch ([[UIApplication sharedApplication] statusBarOrientation]) {
case UIDeviceOrientationLandscapeLeft: {
OSIPhone::get_singleton()->update_gravity(-gravity.y, gravity.x, gravity.z);
OSIPhone::get_singleton()->update_accelerometer(-(acceleration.y + gravity.y), (acceleration.x + gravity.x), acceleration.z + gravity.z);
OSIPhone::get_singleton()->update_magnetometer(-magnetic.y, magnetic.x, magnetic.z);
OSIPhone::get_singleton()->update_gyroscope(-rotation.y, rotation.x, rotation.z);
}; break;
case UIDeviceOrientationLandscapeRight: {
OSIPhone::get_singleton()->update_gravity(gravity.y, -gravity.x, gravity.z);
OSIPhone::get_singleton()->update_accelerometer((acceleration.y + gravity.y), -(acceleration.x + gravity.x), acceleration.z + gravity.z);
OSIPhone::get_singleton()->update_magnetometer(magnetic.y, -magnetic.x, magnetic.z);
OSIPhone::get_singleton()->update_gyroscope(rotation.y, -rotation.x, rotation.z);
}; break;
case UIDeviceOrientationPortraitUpsideDown: {
OSIPhone::get_singleton()->update_gravity(-gravity.x, gravity.y, gravity.z);
OSIPhone::get_singleton()->update_accelerometer(-(acceleration.x + gravity.x), (acceleration.y + gravity.y), acceleration.z + gravity.z);
OSIPhone::get_singleton()->update_magnetometer(-magnetic.x, magnetic.y, magnetic.z);
OSIPhone::get_singleton()->update_gyroscope(-rotation.x, rotation.y, rotation.z);
}; break;
default: { // assume portrait
OSIPhone::get_singleton()->update_gravity(gravity.x, gravity.y, gravity.z);
OSIPhone::get_singleton()->update_accelerometer(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z);
OSIPhone::get_singleton()->update_magnetometer(magnetic.x, magnetic.y, magnetic.z);
OSIPhone::get_singleton()->update_gyroscope(rotation.x, rotation.y, rotation.z);
}; break;
};
} }
bool quit_request = OSIPhone::get_singleton()->iterate(); OSIPhone::get_singleton()->set_unique_ID(String::utf8([uuid UTF8String]));
}; break;
/*
case 1: {
++frame_count;
}; break;
*/
case 1: {
Main::setup2();
++frame_count;
// this might be necessary before here
NSDictionary* dict = [[NSBundle mainBundle] infoDictionary];
for (NSString* key in dict) {
NSObject* value = [dict objectForKey:key];
String ukey = String::utf8([key UTF8String]);
// we need a NSObject to Variant conversor
if ([value isKindOfClass:[NSString class]]) {
NSString* str = (NSString*)value;
String uval = String::utf8([str UTF8String]);
Globals::get_singleton()->set("Info.plist/"+ukey, uval);
} else if ([value isKindOfClass:[NSNumber class]]) {
NSNumber* n = (NSNumber*)value;
double dval = [n doubleValue];
Globals::get_singleton()->set("Info.plist/"+ukey, dval);
};
// do stuff
}
}; break;
/*
case 3: {
++frame_count;
} break;
*/
case 2: {
Main::start();
++frame_count;
}; break; // no fallthrough
default: {
if (OSIPhone::get_singleton()) {
if (motionInitialised) {
// 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 component. We add them back together
CMAcceleration gravity = motionManager.deviceMotion.gravity;
CMAcceleration acceleration = motionManager.deviceMotion.userAcceleration;
///@TODO We don't seem to be getting data here, is my device broken or is this code incorrect?
CMMagneticField magnetic = 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 = 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)
switch ([[UIApplication sharedApplication] statusBarOrientation]) {
case UIDeviceOrientationLandscapeLeft: {
OSIPhone::get_singleton()->update_gravity(-gravity.y, gravity.x, gravity.z);
OSIPhone::get_singleton()->update_accelerometer(-(acceleration.y + gravity.y), (acceleration.x + gravity.x), acceleration.z + gravity.z);
OSIPhone::get_singleton()->update_magnetometer(-magnetic.y, magnetic.x, magnetic.z);
OSIPhone::get_singleton()->update_gyroscope(-rotation.y, rotation.x, rotation.z);
}; break;
case UIDeviceOrientationLandscapeRight: {
OSIPhone::get_singleton()->update_gravity(gravity.y, -gravity.x, gravity.z);
OSIPhone::get_singleton()->update_accelerometer((acceleration.y + gravity.y), -(acceleration.x + gravity.x), acceleration.z + gravity.z);
OSIPhone::get_singleton()->update_magnetometer(magnetic.y, -magnetic.x, magnetic.z);
OSIPhone::get_singleton()->update_gyroscope(rotation.y, -rotation.x, rotation.z);
}; break;
case UIDeviceOrientationPortraitUpsideDown: {
OSIPhone::get_singleton()->update_gravity(-gravity.x, gravity.y, gravity.z);
OSIPhone::get_singleton()->update_accelerometer(-(acceleration.x + gravity.x), (acceleration.y + gravity.y), acceleration.z + gravity.z);
OSIPhone::get_singleton()->update_magnetometer(-magnetic.x, magnetic.y, magnetic.z);
OSIPhone::get_singleton()->update_gyroscope(-rotation.x, rotation.y, rotation.z);
}; break;
default: { // assume portrait
OSIPhone::get_singleton()->update_gravity(gravity.x, gravity.y, gravity.z);
OSIPhone::get_singleton()->update_accelerometer(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z);
OSIPhone::get_singleton()->update_magnetometer(magnetic.x, magnetic.y, magnetic.z);
OSIPhone::get_singleton()->update_gyroscope(rotation.x, rotation.y, rotation.z);
}; break;
};
}
bool quit_request = OSIPhone::get_singleton()->iterate();
};
}; };
};
}; };
}; };
@ -275,12 +269,12 @@ static int frame_count = 0;
//glView.autoresizesSubviews = YES; //glView.autoresizesSubviews = YES;
//[glView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth]; //[glView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth];
int backingWidth; int backingWidth;
int backingHeight; int backingHeight;
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
iphone_main(backingWidth, backingHeight, gargc, gargv); iphone_main(backingWidth, backingHeight, gargc, gargv);
view_controller = [[ViewController alloc] init]; view_controller = [[ViewController alloc] init];
view_controller.view = glView; view_controller.view = glView;
@ -296,13 +290,13 @@ static int frame_count = 0;
[window makeKeyAndVisible]; [window makeKeyAndVisible];
if (!motionInitialised) { if (!motionInitialised) {
motionManager = [[CMMotionManager alloc] init]; motionManager = [[CMMotionManager alloc] init];
if (motionManager.deviceMotionAvailable) { if (motionManager.deviceMotionAvailable) {
motionManager.deviceMotionUpdateInterval = 1.0/70.0; motionManager.deviceMotionUpdateInterval = 1.0/70.0;
[motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical]; [motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical];
motionInitialised = YES; motionInitialised = YES;
}; };
}; };
//OSIPhone::screen_width = rect.size.width - rect.origin.x; //OSIPhone::screen_width = rect.size.width - rect.origin.x;
//OSIPhone::screen_height = rect.size.height - rect.origin.y; //OSIPhone::screen_height = rect.size.height - rect.origin.y;
@ -310,33 +304,29 @@ static int frame_count = 0;
mainViewController = view_controller; mainViewController = view_controller;
#ifdef MODULE_GAME_ANALYTICS_ENABLED #ifdef MODULE_GAME_ANALYTICS_ENABLED
printf("********************* didFinishLaunchingWithOptions\n"); printf("********************* didFinishLaunchingWithOptions\n");
if(!Globals::get_singleton()->has("mobileapptracker/advertiser_id")) if (!Globals::get_singleton()->has("mobileapptracker/advertiser_id")) {
{ return;
return; }
} if (!Globals::get_singleton()->has("mobileapptracker/conversion_key")) {
if(!Globals::get_singleton()->has("mobileapptracker/conversion_key")) return;
{ }
return;
}
String adid = GLOBAL_DEF("mobileapptracker/advertiser_id",""); String adid = GLOBAL_DEF("mobileapptracker/advertiser_id","");
String convkey = GLOBAL_DEF("mobileapptracker/conversion_key",""); String convkey = GLOBAL_DEF("mobileapptracker/conversion_key","");
NSString * advertiser_id = [NSString stringWithUTF8String:adid.utf8().get_data()]; NSString * advertiser_id = [NSString stringWithUTF8String:adid.utf8().get_data()];
NSString * conversion_key = [NSString stringWithUTF8String:convkey.utf8().get_data()]; NSString * conversion_key = [NSString stringWithUTF8String:convkey.utf8().get_data()];
// Account Configuration info - must be set // Account Configuration info - must be set
[MobileAppTracker initializeWithMATAdvertiserId:advertiser_id [MobileAppTracker initializeWithMATAdvertiserId:advertiser_id MATConversionKey:conversion_key];
MATConversionKey:conversion_key];
// Used to pass us the IFA, enables highly accurate 1-to-1 attribution. // Used to pass us the IFA, enables highly accurate 1-to-1 attribution.
// Required for many advertising networks. // Required for many advertising networks.
[MobileAppTracker setAppleAdvertisingIdentifier:[[ASIdentifierManager sharedManager] advertisingIdentifier] [MobileAppTracker setAppleAdvertisingIdentifier:[[ASIdentifierManager sharedManager] advertisingIdentifier]
advertisingTrackingEnabled:[[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]]; advertisingTrackingEnabled:[[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]];
#endif #endif
}; };
- (void)applicationWillTerminate:(UIApplication*)application { - (void)applicationWillTerminate:(UIApplication*)application {
@ -344,53 +334,53 @@ static int frame_count = 0;
printf("********************* will terminate\n"); printf("********************* will terminate\n");
if (motionInitialised) { if (motionInitialised) {
///@TODO is this the right place to clean this up? ///@TODO is this the right place to clean this up?
[motionManager stopDeviceMotionUpdates]; [motionManager stopDeviceMotionUpdates];
[motionManager release]; [motionManager release];
motionManager = nil; motionManager = nil;
motionInitialised = NO; motionInitialised = NO;
}; };
iphone_finish(); iphone_finish();
}; };
- (void)applicationDidEnterBackground:(UIApplication *)application - (void)applicationDidEnterBackground:(UIApplication *)application {
{
printf("********************* did enter background\n"); printf("********************* did enter background\n");
///@TODO maybe add pause motionManager? and where would we unpause it? ///@TODO maybe add pause motionManager? and where would we unpause it?
if (OS::get_singleton()->get_main_loop()) if (OS::get_singleton()->get_main_loop())
OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
[view_controller.view stopAnimation]; [view_controller.view stopAnimation];
if (OS::get_singleton()->native_video_is_playing()) { if (OS::get_singleton()->native_video_is_playing()) {
OSIPhone::get_singleton()->native_video_focus_out(); OSIPhone::get_singleton()->native_video_focus_out();
}; };
} }
- (void)applicationWillEnterForeground:(UIApplication *)application - (void)applicationWillEnterForeground:(UIApplication *)application {
{
printf("********************* did enter foreground\n"); printf("********************* did enter foreground\n");
//OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); //OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
[view_controller.view startAnimation]; [view_controller.view startAnimation];
} }
- (void) applicationWillResignActive:(UIApplication *)application - (void) applicationWillResignActive:(UIApplication *)application {
{
printf("********************* will resign active\n"); printf("********************* will resign active\n");
//OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); //OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
[view_controller.view stopAnimation]; // FIXME: pause seems to be recommended elsewhere [view_controller.view stopAnimation]; // FIXME: pause seems to be recommended elsewhere
} }
- (void) applicationDidBecomeActive:(UIApplication *)application - (void) applicationDidBecomeActive:(UIApplication *)application {
{
printf("********************* did become active\n"); printf("********************* did become active\n");
#ifdef MODULE_GAME_ANALYTICS_ENABLED #ifdef MODULE_GAME_ANALYTICS_ENABLED
printf("********************* mobile app tracker found\n"); printf("********************* mobile app tracker found\n");
[MobileAppTracker measureSession]; [MobileAppTracker measureSession];
#endif #endif
if (OS::get_singleton()->get_main_loop()) if (OS::get_singleton()->get_main_loop())
OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
[view_controller.view startAnimation]; // FIXME: resume seems to be recommended elsewhere [view_controller.view startAnimation]; // FIXME: resume seems to be recommended elsewhere
if (OSIPhone::get_singleton()->native_video_is_playing()) { if (OSIPhone::get_singleton()->native_video_is_playing()) {
OSIPhone::get_singleton()->native_video_unpause(); OSIPhone::get_singleton()->native_video_unpause();
}; };
@ -409,9 +399,9 @@ static int frame_count = 0;
#ifdef MODULE_PARSE_ENABLED #ifdef MODULE_PARSE_ENABLED
NSLog(@"Handling application openURL"); NSLog(@"Handling application openURL");
return [[FBSDKApplicationDelegate sharedInstance] application:application return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url openURL:url
sourceApplication:sourceApplication sourceApplication:sourceApplication
annotation:annotation]; annotation:annotation];
#endif #endif
@ -448,8 +438,7 @@ static int frame_count = 0;
#endif #endif
} }
- (void)dealloc - (void)dealloc {
{
[window release]; [window release];
[super dealloc]; [super dealloc];
} }

View file

@ -51,15 +51,15 @@ void GameCenter::_bind_methods() {
ObjectTypeDB::bind_method(_MD("connect"),&GameCenter::connect); ObjectTypeDB::bind_method(_MD("connect"),&GameCenter::connect);
ObjectTypeDB::bind_method(_MD("is_connected"),&GameCenter::is_connected); ObjectTypeDB::bind_method(_MD("is_connected"),&GameCenter::is_connected);
ObjectTypeDB::bind_method(_MD("post_score"),&GameCenter::post_score); ObjectTypeDB::bind_method(_MD("post_score"), &GameCenter::post_score);
ObjectTypeDB::bind_method(_MD("award_achievement"),&GameCenter::award_achievement); ObjectTypeDB::bind_method(_MD("award_achievement"), &GameCenter::award_achievement);
ObjectTypeDB::bind_method(_MD("reset_achievements"),&GameCenter::reset_achievements); ObjectTypeDB::bind_method(_MD("reset_achievements"), &GameCenter::reset_achievements);
ObjectTypeDB::bind_method(_MD("request_achievements"),&GameCenter::request_achievements); ObjectTypeDB::bind_method(_MD("request_achievements"), &GameCenter::request_achievements);
ObjectTypeDB::bind_method(_MD("request_achievement_descriptions"),&GameCenter::request_achievement_descriptions); ObjectTypeDB::bind_method(_MD("request_achievement_descriptions"), &GameCenter::request_achievement_descriptions);
ObjectTypeDB::bind_method(_MD("show_game_center"),&GameCenter::show_game_center); ObjectTypeDB::bind_method(_MD("show_game_center"), &GameCenter::show_game_center);
ObjectTypeDB::bind_method(_MD("get_pending_event_count"),&GameCenter::get_pending_event_count); ObjectTypeDB::bind_method(_MD("get_pending_event_count"), &GameCenter::get_pending_event_count);
ObjectTypeDB::bind_method(_MD("pop_pending_event"),&GameCenter::pop_pending_event); ObjectTypeDB::bind_method(_MD("pop_pending_event"), &GameCenter::pop_pending_event);
}; };
@ -77,27 +77,25 @@ Error GameCenter::connect() {
ViewController *root_controller=(ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController; ViewController *root_controller=(ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController;
ERR_FAIL_COND_V(!root_controller, FAILED); ERR_FAIL_COND_V(!root_controller, FAILED);
//this handler is called serveral times. first when the view needs to be shown, then again after the view is cancelled or the user logs in. or if the user's already logged in, it's called just once to confirm they're authenticated. This is why no result needs to be specified in the presentViewController phase. in this case, more calls to this function will follow. //this handler is called serveral times. first when the view needs to be shown, then again after the view is cancelled or the user logs in. or if the user's already logged in, it's called just once to confirm they're authenticated. This is why no result needs to be specified in the presentViewController phase. in this case, more calls to this function will follow.
player.authenticateHandler = (^(UIViewController *controller, NSError *error) { player.authenticateHandler = (^(UIViewController *controller, NSError *error) {
if (controller) { if (controller) {
[root_controller presentViewController:controller animated:YES completion:nil]; [root_controller presentViewController:controller animated:YES completion:nil];
} } else {
else { Dictionary ret;
Dictionary ret; ret["type"] = "authentication";
ret["type"] = "authentication"; if (player.isAuthenticated) {
if (player.isAuthenticated) { ret["result"] = "ok";
ret["result"] = "ok"; GameCenter::get_singleton()->connected = true;
GameCenter::get_singleton()->connected = true; } else {
} else { ret["result"] = "error";
ret["result"] = "error"; ret["error_code"] = error.code;
ret["error_code"] = error.code; ret["error_description"] = [error.localizedDescription UTF8String];
ret["error_description"] = [error.localizedDescription UTF8String]; GameCenter::get_singleton()->connected = false;
GameCenter::get_singleton()->connected = false; };
};
pending_events.push_back(ret);
};
pending_events.push_back(ret);
};
}); });
return OK; return OK;
@ -121,7 +119,6 @@ Error GameCenter::post_score(Variant p_score) {
ERR_FAIL_COND_V([GKScore respondsToSelector:@selector(reportScores)], ERR_UNAVAILABLE); ERR_FAIL_COND_V([GKScore respondsToSelector:@selector(reportScores)], ERR_UNAVAILABLE);
[GKScore reportScores:@[reporter] withCompletionHandler:^(NSError* error) { [GKScore reportScores:@[reporter] withCompletionHandler:^(NSError* error) {
Dictionary ret; Dictionary ret;
ret["type"] = "post_score"; ret["type"] = "post_score";
if (error == nil) { if (error == nil) {
@ -331,7 +328,8 @@ Error GameCenter::show_game_center(Variant p_params) {
void GameCenter::game_center_closed() { void GameCenter::game_center_closed() {
Dictionary ret; Dictionary ret;
ret["type"] = "show_game_center";
ret["type"] = "show_game_center";
ret["result"] = "ok"; ret["result"] = "ok";
pending_events.push_back(ret); pending_events.push_back(ret);
} }

View file

@ -90,9 +90,9 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s
[_instance.avPlayer addObserver:_instance forKeyPath:@"status" options:0 context:nil]; [_instance.avPlayer addObserver:_instance forKeyPath:@"status" options:0 context:nil];
[[NSNotificationCenter defaultCenter] addObserver:_instance [[NSNotificationCenter defaultCenter] addObserver:_instance
selector:@selector(playerItemDidReachEnd:) selector:@selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification name:AVPlayerItemDidPlayToEndTimeNotification
object:[_instance.avPlayer currentItem]]; object:[_instance.avPlayer currentItem]];
[_instance.avPlayer addObserver:_instance forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:0]; [_instance.avPlayer addObserver:_instance forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:0];
@ -103,13 +103,11 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s
AVMediaSelectionGroup *audioGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicAudible]; AVMediaSelectionGroup *audioGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicAudible];
NSMutableArray *allAudioParams = [NSMutableArray array]; NSMutableArray *allAudioParams = [NSMutableArray array];
for (id track in audioGroup.options) for (id track in audioGroup.options) {
{
NSString* language = [[track locale] localeIdentifier]; NSString* language = [[track locale] localeIdentifier];
NSLog(@"subtitle lang: %@", language); NSLog(@"subtitle lang: %@", language);
if ([language isEqualToString:[NSString stringWithUTF8String:p_audio_track.utf8()]]) if ([language isEqualToString:[NSString stringWithUTF8String:p_audio_track.utf8()]]) {
{
AVMutableAudioMixInputParameters *audioInputParams = [AVMutableAudioMixInputParameters audioMixInputParameters]; AVMutableAudioMixInputParameters *audioInputParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
[audioInputParams setVolume:p_volume atTime:kCMTimeZero]; [audioInputParams setVolume:p_volume atTime:kCMTimeZero];
[audioInputParams setTrackID:[track trackID]]; [audioInputParams setTrackID:[track trackID]];
@ -121,23 +119,21 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s
[_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: audioGroup]; [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: audioGroup];
[_instance.avPlayer.currentItem setAudioMix:audioMix]; [_instance.avPlayer.currentItem setAudioMix:audioMix];
break; break;
} }
} }
AVMediaSelectionGroup *subtitlesGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicLegible]; AVMediaSelectionGroup *subtitlesGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicLegible];
NSArray *useableTracks = [AVMediaSelectionGroup mediaSelectionOptionsFromArray:subtitlesGroup.options withoutMediaCharacteristics:[NSArray arrayWithObject:AVMediaCharacteristicContainsOnlyForcedSubtitles]]; NSArray *useableTracks = [AVMediaSelectionGroup mediaSelectionOptionsFromArray:subtitlesGroup.options withoutMediaCharacteristics:[NSArray arrayWithObject:AVMediaCharacteristicContainsOnlyForcedSubtitles]];
for (id track in useableTracks) for (id track in useableTracks) {
{
NSString* language = [[track locale] localeIdentifier]; NSString* language = [[track locale] localeIdentifier];
NSLog(@"subtitle lang: %@", language); NSLog(@"subtitle lang: %@", language);
if ([language isEqualToString:[NSString stringWithUTF8String:p_subtitle_track.utf8()]]) if ([language isEqualToString:[NSString stringWithUTF8String:p_subtitle_track.utf8()]]) {
{ [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: subtitlesGroup];
[_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: subtitlesGroup]; break;
break; }
}
} }
video_playing = true; video_playing = true;
@ -237,7 +233,7 @@ static int get_first_id(UITouch* p_touch) {
static void clear_touches() { static void clear_touches() {
for (int i=0; i<max_touches; i++) { for (int i = 0; i < max_touches; i++) {
touches[i] = NULL; touches[i] = NULL;
}; };
@ -245,39 +241,34 @@ static void clear_touches() {
// Implement this to override the default layer class (which is [CALayer class]). // Implement this to override the default layer class (which is [CALayer class]).
// We do this so that our view will be backed by a layer that is capable of OpenGL ES rendering. // We do this so that our view will be backed by a layer that is capable of OpenGL ES rendering.
+ (Class) layerClass + (Class) layerClass {
{
return [CAEAGLLayer class]; return [CAEAGLLayer class];
} }
//The GL view is stored in the nib file. When it's unarchived it's sent -initWithCoder: //The GL view is stored in the nib file. When it's unarchived it's sent -initWithCoder:
- (id)initWithCoder:(NSCoder*)coder - (id)initWithCoder:(NSCoder*)coder {
{
active = FALSE; active = FALSE;
if((self = [super initWithCoder:coder])) if((self = [super initWithCoder:coder])) {
{
self = [self initGLES]; self = [self initGLES];
} }
return self; return self;
} }
-(id)initGLES -(id)initGLES {
{
// Get our backing layer // Get our backing layer
CAEAGLLayer *eaglLayer = (CAEAGLLayer*) self.layer; CAEAGLLayer *eaglLayer = (CAEAGLLayer*) self.layer;
// Configure it so that it is opaque, does not retain the contents of the backbuffer when displayed, and uses RGBA8888 color. // Configure it so that it is opaque, does not retain the contents of the backbuffer when displayed, and uses RGBA8888 color.
eaglLayer.opaque = YES; eaglLayer.opaque = YES;
eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking,
kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat,
nil]; nil];
// Create our EAGLContext, and if successful make it current and create our framebuffer. // Create our EAGLContext, and if successful make it current and create our framebuffer.
context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
if(!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer]) if(!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer]) {
{
[self release]; [self release];
return nil; return nil;
} }
@ -287,14 +278,12 @@ static void clear_touches() {
return self; return self;
} }
-(id<GLViewDelegate>)delegate -(id<GLViewDelegate>)delegate {
{
return delegate; return delegate;
} }
// Update the delegate, and if it needs a -setupView: call, set our internal flag so that it will be called. // Update the delegate, and if it needs a -setupView: call, set our internal flag so that it will be called.
-(void)setDelegate:(id<GLViewDelegate>)d -(void)setDelegate:(id<GLViewDelegate>)d {
{
delegate = d; delegate = d;
delegateSetup = ![delegate respondsToSelector:@selector(setupView:)]; delegateSetup = ![delegate respondsToSelector:@selector(setupView:)];
} }
@ -305,8 +294,7 @@ static void clear_touches() {
// This is the perfect opportunity to also update the framebuffer so that it is // This is the perfect opportunity to also update the framebuffer so that it is
// the same size as our display area. // the same size as our display area.
-(void)layoutSubviews -(void)layoutSubviews {
{
//printf("HERE\n"); //printf("HERE\n");
[EAGLContext setCurrentContext:context]; [EAGLContext setCurrentContext:context];
[self destroyFramebuffer]; [self destroyFramebuffer];
@ -316,8 +304,7 @@ static void clear_touches() {
} }
- (BOOL)createFramebuffer - (BOOL)createFramebuffer {
{
// Generate IDs for a framebuffer object and a color renderbuffer // Generate IDs for a framebuffer object and a color renderbuffer
UIScreen* mainscr = [UIScreen mainScreen]; UIScreen* mainscr = [UIScreen mainScreen];
printf("******** screen size %i, %i\n", (int)mainscr.currentMode.size.width, (int)mainscr.currentMode.size.height); printf("******** screen size %i, %i\n", (int)mainscr.currentMode.size.width, (int)mainscr.currentMode.size.height);
@ -344,8 +331,7 @@ static void clear_touches() {
glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight); glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
{
NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES)); NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
return NO; return NO;
} }
@ -365,24 +351,22 @@ static void clear_touches() {
} }
// Clean up any buffers we have allocated. // Clean up any buffers we have allocated.
- (void)destroyFramebuffer - (void)destroyFramebuffer {
{
glDeleteFramebuffersOES(1, &viewFramebuffer); glDeleteFramebuffersOES(1, &viewFramebuffer);
viewFramebuffer = 0; viewFramebuffer = 0;
glDeleteRenderbuffersOES(1, &viewRenderbuffer); glDeleteRenderbuffersOES(1, &viewRenderbuffer);
viewRenderbuffer = 0; viewRenderbuffer = 0;
if(depthRenderbuffer) if(depthRenderbuffer) {
{
glDeleteRenderbuffersOES(1, &depthRenderbuffer); glDeleteRenderbuffersOES(1, &depthRenderbuffer);
depthRenderbuffer = 0; depthRenderbuffer = 0;
} }
} }
- (void)startAnimation - (void)startAnimation {
{
if (active) if (active)
return; return;
active = TRUE; active = TRUE;
printf("start animation!\n"); printf("start animation!\n");
if (useCADisplayLink) { if (useCADisplayLink) {
@ -396,59 +380,53 @@ static void clear_touches() {
// Setup DisplayLink in main thread // Setup DisplayLink in main thread
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
} } else {
else {
animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(drawView) userInfo:nil repeats:YES]; animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(drawView) userInfo:nil repeats:YES];
} }
if (video_playing) if (video_playing) {
{
_unpause_video(); _unpause_video();
} }
} }
- (void)stopAnimation - (void)stopAnimation {
{
if (!active) if (!active)
return; return;
active = FALSE; active = FALSE;
printf("******** stop animation!\n"); printf("******** stop animation!\n");
if (useCADisplayLink) { if (useCADisplayLink) {
[displayLink invalidate]; [displayLink invalidate];
displayLink = nil; displayLink = nil;
} } else {
else {
[animationTimer invalidate]; [animationTimer invalidate];
animationTimer = nil; animationTimer = nil;
} }
clear_touches(); clear_touches();
if (video_playing) if (video_playing) {
{
// save position // save position
} }
} }
- (void)setAnimationInterval:(NSTimeInterval)interval - (void)setAnimationInterval:(NSTimeInterval)interval {
{
animationInterval = interval; animationInterval = interval;
if ( (useCADisplayLink && displayLink) || ( !useCADisplayLink && animationTimer ) ) { if ((useCADisplayLink && displayLink) || (!useCADisplayLink && animationTimer)) {
[self stopAnimation]; [self stopAnimation];
[self startAnimation]; [self startAnimation];
} }
} }
// Updates the OpenGL view when the timer fires // Updates the OpenGL view when the timer fires
- (void)drawView - (void)drawView {
{
if (useCADisplayLink) { if (useCADisplayLink) {
// Pause the CADisplayLink to avoid recursion // Pause the CADisplayLink to avoid recursion
[displayLink setPaused: YES]; [displayLink setPaused: YES];
// Process all input events // Process all input events
while(CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource); while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource);
// We are good to go, resume the CADisplayLink // We are good to go, resume the CADisplayLink
[displayLink setPaused: NO]; [displayLink setPaused: NO];
@ -463,8 +441,7 @@ static void clear_touches() {
[EAGLContext setCurrentContext:context]; [EAGLContext setCurrentContext:context];
// If our drawing delegate needs to have the view setup, then call -setupView: and flag that it won't need to be called again. // If our drawing delegate needs to have the view setup, then call -setupView: and flag that it won't need to be called again.
if(!delegateSetup) if(!delegateSetup) {
{
[delegate setupView:self]; [delegate setupView:self];
delegateSetup = YES; delegateSetup = YES;
} }
@ -483,8 +460,7 @@ static void clear_touches() {
#endif #endif
} }
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
{
NSArray* tlist = [[event allTouches] allObjects]; NSArray* tlist = [[event allTouches] allObjects];
for (unsigned int i=0; i< [tlist count]; i++) { for (unsigned int i=0; i< [tlist count]; i++) {
@ -501,8 +477,7 @@ static void clear_touches() {
}; };
} }
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
{
NSArray* tlist = [[event allTouches] allObjects]; NSArray* tlist = [[event allTouches] allObjects];
for (unsigned int i=0; i< [tlist count]; i++) { for (unsigned int i=0; i< [tlist count]; i++) {
@ -512,6 +487,7 @@ static void clear_touches() {
UITouch* touch = [tlist objectAtIndex:i]; UITouch* touch = [tlist objectAtIndex:i];
if (touch.phase != UITouchPhaseMoved) if (touch.phase != UITouchPhaseMoved)
continue; continue;
int tid = get_touch_id(touch); int tid = get_touch_id(touch);
ERR_FAIL_COND(tid == -1); ERR_FAIL_COND(tid == -1);
int first = get_first_id(touch); int first = get_first_id(touch);
@ -523,8 +499,7 @@ static void clear_touches() {
} }
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
{
NSArray* tlist = [[event allTouches] allObjects]; NSArray* tlist = [[event allTouches] allObjects];
for (unsigned int i=0; i< [tlist count]; i++) { for (unsigned int i=0; i< [tlist count]; i++) {
@ -533,6 +508,7 @@ static void clear_touches() {
UITouch* touch = [tlist objectAtIndex:i]; UITouch* touch = [tlist objectAtIndex:i];
if (touch.phase != UITouchPhaseEnded) if (touch.phase != UITouchPhaseEnded)
continue; continue;
int tid = get_touch_id(touch); int tid = get_touch_id(touch);
ERR_FAIL_COND(tid == -1); ERR_FAIL_COND(tid == -1);
int rem = remove_touch(touch); int rem = remove_touch(touch);
@ -566,6 +542,7 @@ static void clear_touches() {
- (void)deleteBackward { - (void)deleteBackward {
if (keyboard_text.length()) if (keyboard_text.length())
keyboard_text.erase(keyboard_text.length() - 1, 1); keyboard_text.erase(keyboard_text.length() - 1, 1);
OSIPhone::get_singleton()->key(KEY_BACKSPACE, true); OSIPhone::get_singleton()->key(KEY_BACKSPACE, true);
}; };
@ -590,12 +567,12 @@ static void clear_touches() {
switch (routeChangeReason) { switch (routeChangeReason) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable: case AVAudioSessionRouteChangeReasonNewDeviceAvailable: {
NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable"); NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
NSLog(@"Headphone/Line plugged in"); NSLog(@"Headphone/Line plugged in");
break; }; break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: {
NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable"); NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
NSLog(@"Headphone/Line was pulled. Resuming video play...."); NSLog(@"Headphone/Line was pulled. Resuming video play....");
if (_is_video_playing()) { if (_is_video_playing()) {
@ -605,24 +582,22 @@ static void clear_touches() {
NSLog(@"resumed play"); NSLog(@"resumed play");
}); });
}; };
break; }; break;
case AVAudioSessionRouteChangeReasonCategoryChange: case AVAudioSessionRouteChangeReasonCategoryChange: {
// called at start - also when other audio wants to play // called at start - also when other audio wants to play
NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange"); NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
break; }; break;
} }
} }
// When created via code however, we get initWithFrame // When created via code however, we get initWithFrame
-(id)initWithFrame:(CGRect)frame -(id)initWithFrame:(CGRect)frame {
{
self = [super initWithFrame:frame]; self = [super initWithFrame:frame];
_instance = self; _instance = self;
printf("after init super %p\n", self); printf("after init super %p\n", self);
if(self != nil) if(self != nil) {
{
self = [self initGLES]; self = [self initGLES];
printf("after init gles %p\n", self); printf("after init gles %p\n", self);
} }
@ -631,8 +606,8 @@ static void clear_touches() {
printf("******** adding observer for sound routing changes\n"); printf("******** adding observer for sound routing changes\n");
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:)
name:AVAudioSessionRouteChangeNotification name:AVAudioSessionRouteChangeNotification
object:nil]; object:nil];
//self.autoresizesSubviews = YES; //self.autoresizesSubviews = YES;
//[self setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth]; //[self setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth];
@ -649,12 +624,10 @@ static void clear_touches() {
// } // }
// Stop animating and release resources when they are no longer needed. // Stop animating and release resources when they are no longer needed.
- (void)dealloc - (void)dealloc {
{
[self stopAnimation]; [self stopAnimation];
if([EAGLContext currentContext] == context) if([EAGLContext currentContext] == context) {
{
[EAGLContext setCurrentContext:nil]; [EAGLContext setCurrentContext:nil];
} }
@ -665,24 +638,24 @@ static void clear_touches() {
} }
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context { change:(NSDictionary *)change context:(void *)context {
if (object == _instance.avPlayerItem && [keyPath isEqualToString:@"status"]) { if (object == _instance.avPlayerItem && [keyPath isEqualToString:@"status"]) {
if (_instance.avPlayerItem.status == AVPlayerStatusFailed || _instance.avPlayer.status == AVPlayerStatusFailed) { if (_instance.avPlayerItem.status == AVPlayerStatusFailed || _instance.avPlayer.status == AVPlayerStatusFailed) {
_stop_video(); _stop_video();
video_found_error = true; video_found_error = true;
}
if(_instance.avPlayer.status == AVPlayerStatusReadyToPlay &&
_instance.avPlayerItem.status == AVPlayerItemStatusReadyToPlay &&
CMTIME_COMPARE_INLINE(video_current_time, ==, kCMTimeZero)) {
//NSLog(@"time: %@", video_current_time);
[_instance.avPlayer seekToTime:video_current_time];
video_current_time = kCMTimeZero;
} }
}
if(_instance.avPlayer.status == AVPlayerStatusReadyToPlay &&
_instance.avPlayerItem.status == AVPlayerItemStatusReadyToPlay &&
CMTIME_COMPARE_INLINE(video_current_time, ==, kCMTimeZero)) {
//NSLog(@"time: %@", video_current_time);
[_instance.avPlayer seekToTime:video_current_time];
video_current_time = kCMTimeZero;
}
}
if (object == _instance.avPlayer && [keyPath isEqualToString:@"rate"]) { if (object == _instance.avPlayer && [keyPath isEqualToString:@"rate"]) {
NSLog(@"Player playback rate changed: %.5f", _instance.avPlayer.rate); NSLog(@"Player playback rate changed: %.5f", _instance.avPlayer.rate);
@ -698,40 +671,40 @@ static void clear_touches() {
} }
- (void)playerItemDidReachEnd:(NSNotification *)notification { - (void)playerItemDidReachEnd:(NSNotification *)notification {
_stop_video(); _stop_video();
} }
/* /*
- (void)moviePlayBackDidFinish:(NSNotification*)notification { - (void)moviePlayBackDidFinish:(NSNotification*)notification {
NSNumber* reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]; NSNumber* reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
switch ([reason intValue]) { switch ([reason intValue]) {
case MPMovieFinishReasonPlaybackEnded: case MPMovieFinishReasonPlaybackEnded:
//NSLog(@"Playback Ended"); //NSLog(@"Playback Ended");
break; break;
case MPMovieFinishReasonPlaybackError: case MPMovieFinishReasonPlaybackError:
//NSLog(@"Playback Error"); //NSLog(@"Playback Error");
video_found_error = true; video_found_error = true;
break; break;
case MPMovieFinishReasonUserExited: case MPMovieFinishReasonUserExited:
//NSLog(@"User Exited"); //NSLog(@"User Exited");
video_found_error = true; video_found_error = true;
break; break;
default: default:
//NSLog(@"Unsupported reason!"); //NSLog(@"Unsupported reason!");
break; break;
} }
MPMoviePlayerController *player = [notification object]; MPMoviePlayerController *player = [notification object];
[[NSNotificationCenter defaultCenter] [[NSNotificationCenter defaultCenter]
removeObserver:self removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification name:MPMoviePlayerPlaybackDidFinishNotification
object:player]; object:player];
[_instance.moviePlayerController stop]; [_instance.moviePlayerController stop];
[_instance.moviePlayerController.view removeFromSuperview]; [_instance.moviePlayerController.view removeFromSuperview];
//[[MPMusicPlayerController applicationMusicPlayer] setVolume: video_previous_volume]; //[[MPMusicPlayerController applicationMusicPlayer] setVolume: video_previous_volume];
video_playing = false; video_playing = false;

View file

@ -44,14 +44,14 @@ extern "C" {
ICloud* ICloud::instance = NULL; ICloud* ICloud::instance = NULL;
void ICloud::_bind_methods() { void ICloud::_bind_methods() {
ObjectTypeDB::bind_method(_MD("remove_key"),&ICloud::remove_key); ObjectTypeDB::bind_method(_MD("remove_key"), &ICloud::remove_key);
ObjectTypeDB::bind_method(_MD("set_key_values"),&ICloud::set_key_values); ObjectTypeDB::bind_method(_MD("set_key_values"), &ICloud::set_key_values);
ObjectTypeDB::bind_method(_MD("get_key_value"),&ICloud::get_key_value); ObjectTypeDB::bind_method(_MD("get_key_value"), &ICloud::get_key_value);
ObjectTypeDB::bind_method(_MD("synchronize_key_values"),&ICloud::synchronize_key_values); ObjectTypeDB::bind_method(_MD("synchronize_key_values"), &ICloud::synchronize_key_values);
ObjectTypeDB::bind_method(_MD("get_all_key_values"),&ICloud::get_all_key_values); ObjectTypeDB::bind_method(_MD("get_all_key_values"), &ICloud::get_all_key_values);
ObjectTypeDB::bind_method(_MD("get_pending_event_count"),&ICloud::get_pending_event_count); ObjectTypeDB::bind_method(_MD("get_pending_event_count"), &ICloud::get_pending_event_count);
ObjectTypeDB::bind_method(_MD("pop_pending_event"),&ICloud::pop_pending_event); ObjectTypeDB::bind_method(_MD("pop_pending_event"), &ICloud::pop_pending_event);
}; };
int ICloud::get_pending_event_count() { int ICloud::get_pending_event_count() {
@ -76,8 +76,7 @@ Variant nsobject_to_variant(NSObject* object) {
if ([object isKindOfClass:[NSString class]]) { if ([object isKindOfClass:[NSString class]]) {
const char* str = [(NSString*)object UTF8String]; const char* str = [(NSString*)object UTF8String];
return String::utf8(str != NULL ? str : ""); return String::utf8(str != NULL ? str : "");
} } else if ([object isKindOfClass:[NSData class]]) {
else if ([object isKindOfClass:[NSData class]]) {
ByteArray ret; ByteArray ret;
NSData* data = (NSData*)object; NSData* data = (NSData*)object;
if ([data length] > 0) { if ([data length] > 0) {
@ -88,8 +87,7 @@ Variant nsobject_to_variant(NSObject* object) {
} }
} }
return ret; return ret;
} } else if ([object isKindOfClass:[NSArray class]]) {
else if ([object isKindOfClass:[NSArray class]]) {
Array result; Array result;
NSArray* array = (NSArray*)object; NSArray* array = (NSArray*)object;
for (unsigned int i = 0; i < [array count]; ++i) { for (unsigned int i = 0; i < [array count]; ++i) {
@ -97,8 +95,7 @@ Variant nsobject_to_variant(NSObject* object) {
result.push_back(nsobject_to_variant(value)); result.push_back(nsobject_to_variant(value));
} }
return result; return result;
} } else if ([object isKindOfClass:[NSDictionary class]]) {
else if ([object isKindOfClass:[NSDictionary class]]) {
Dictionary result; Dictionary result;
NSDictionary* dic = (NSDictionary*)object; NSDictionary* dic = (NSDictionary*)object;
@ -112,8 +109,7 @@ Variant nsobject_to_variant(NSObject* object) {
result[nsobject_to_variant(k)] = nsobject_to_variant(v); result[nsobject_to_variant(k)] = nsobject_to_variant(v);
} }
return result; return result;
} } else if ([object isKindOfClass:[NSNumber class]]) {
else if ([object isKindOfClass:[NSNumber class]]) {
//Every type except numbers can reliably identify its type. The following is comparing to the *internal* representation, which isn't guaranteed to match the type that was used to create it, and is not advised, particularly when dealing with potential platform differences (ie, 32/64 bit) //Every type except numbers can reliably identify its type. The following is comparing to the *internal* representation, which isn't guaranteed to match the type that was used to create it, and is not advised, particularly when dealing with potential platform differences (ie, 32/64 bit)
//To avoid errors, we'll cast as broadly as possible, and only return int or float. //To avoid errors, we'll cast as broadly as possible, and only return int or float.
//bool, char, int, uint, longlong -> int //bool, char, int, uint, longlong -> int
@ -121,37 +117,28 @@ Variant nsobject_to_variant(NSObject* object) {
NSNumber* num = (NSNumber*)object; NSNumber* num = (NSNumber*)object;
if(strcmp([num objCType], @encode(BOOL)) == 0) { if(strcmp([num objCType], @encode(BOOL)) == 0) {
return Variant((int)[num boolValue]); return Variant((int)[num boolValue]);
} } else if(strcmp([num objCType], @encode(char)) == 0) {
else if(strcmp([num objCType], @encode(char)) == 0) {
return Variant((int)[num charValue]); return Variant((int)[num charValue]);
} } else if(strcmp([num objCType], @encode(int)) == 0) {
else if(strcmp([num objCType], @encode(int)) == 0) {
return Variant([num intValue]); return Variant([num intValue]);
} } else if(strcmp([num objCType], @encode(unsigned int)) == 0) {
else if(strcmp([num objCType], @encode(unsigned int)) == 0) {
return Variant((int)[num unsignedIntValue]); return Variant((int)[num unsignedIntValue]);
} } else if(strcmp([num objCType], @encode(long long)) == 0) {
else if(strcmp([num objCType], @encode(long long)) == 0) {
return Variant((int)[num longValue]); return Variant((int)[num longValue]);
} } else if(strcmp([num objCType], @encode(float)) == 0) {
else if(strcmp([num objCType], @encode(float)) == 0) {
return Variant([num floatValue]); return Variant([num floatValue]);
} } else if(strcmp([num objCType], @encode(double)) == 0) {
else if(strcmp([num objCType], @encode(double)) == 0) {
return Variant((float)[num doubleValue]); return Variant((float)[num doubleValue]);
} }
} } else if ([object isKindOfClass:[NSDate class]]) {
else if ([object isKindOfClass:[NSDate class]]) {
//this is a type that icloud supports...but how did you submit it in the first place? //this is a type that icloud supports...but how did you submit it in the first place?
//I guess this is a type that *might* show up, if you were, say, trying to make your game //I guess this is a type that *might* show up, if you were, say, trying to make your game
//compatible with existing cloud data written by another engine's version of your game //compatible with existing cloud data written by another engine's version of your game
WARN_PRINT("NSDate unsupported, returning null Variant") WARN_PRINT("NSDate unsupported, returning null Variant")
return Variant(); return Variant();
} } else if ([object isKindOfClass:[NSNull class]] or object == nil) {
else if ([object isKindOfClass:[NSNull class]] or object == nil) {
return Variant(); return Variant();
} } else {
else {
WARN_PRINT("Trying to convert unknown NSObject type to Variant"); WARN_PRINT("Trying to convert unknown NSObject type to Variant");
return Variant(); return Variant();
} }
@ -160,17 +147,13 @@ Variant nsobject_to_variant(NSObject* object) {
NSObject* variant_to_nsobject(Variant v) { NSObject* variant_to_nsobject(Variant v) {
if (v.get_type() == Variant::STRING) { if (v.get_type() == Variant::STRING) {
return [[[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()] autorelease]; return [[[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()] autorelease];
} } else if (v.get_type() == Variant::REAL) {
else if (v.get_type() == Variant::REAL) {
return [NSNumber numberWithDouble:(double)v]; return [NSNumber numberWithDouble:(double)v];
} } else if (v.get_type() == Variant::INT) {
else if (v.get_type() == Variant::INT) {
return [NSNumber numberWithLongLong:(long)(int)v]; return [NSNumber numberWithLongLong:(long)(int)v];
} } else if (v.get_type() == Variant::BOOL) {
else if (v.get_type() == Variant::BOOL) {
return [NSNumber numberWithBool:BOOL((bool)v)]; return [NSNumber numberWithBool:BOOL((bool)v)];
} } else if (v.get_type() == Variant::DICTIONARY) {
else if (v.get_type() == Variant::DICTIONARY) {
NSMutableDictionary* result = [[[NSMutableDictionary alloc] init] autorelease]; NSMutableDictionary* result = [[[NSMutableDictionary alloc] init] autorelease];
Dictionary dic = v; Dictionary dic = v;
Array keys = dic.keys(); Array keys = dic.keys();
@ -185,8 +168,7 @@ NSObject* variant_to_nsobject(Variant v) {
[result setObject:value forKey:key]; [result setObject:value forKey:key];
} }
return result; return result;
} } else if (v.get_type() == Variant::ARRAY) {
else if (v.get_type() == Variant::ARRAY) {
NSMutableArray* result = [[[NSMutableArray alloc] init] autorelease]; NSMutableArray* result = [[[NSMutableArray alloc] init] autorelease];
Array arr = v; Array arr = v;
for (unsigned int i = 0; i < arr.size(); ++i) { for (unsigned int i = 0; i < arr.size(); ++i) {
@ -198,8 +180,7 @@ NSObject* variant_to_nsobject(Variant v) {
[result addObject:value]; [result addObject:value];
} }
return result; return result;
} } else if (v.get_type() == Variant::RAW_ARRAY) {
else if (v.get_type() == Variant::RAW_ARRAY) {
ByteArray arr = v; ByteArray arr = v;
ByteArray::Read r = arr.read(); ByteArray::Read r = arr.read();
NSData* result = [NSData dataWithBytes:r.ptr() length:arr.size()]; NSData* result = [NSData dataWithBytes:r.ptr() length:arr.size()];
@ -296,8 +277,7 @@ Error ICloud::synchronize_key_values() {
BOOL result = [store synchronize]; BOOL result = [store synchronize];
if (result == YES) { if (result == YES) {
return OK; return OK;
} } else {
else {
return FAILED; return FAILED;
} }
} }
@ -306,14 +286,14 @@ Error ICloud::initial_sync() {
//you sometimes have to write something to the store to get it to download new data. go apple! //you sometimes have to write something to the store to get it to download new data. go apple!
NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
if ([store boolForKey:@"isb"]) if ([store boolForKey:@"isb"])
{ {
[store setBool:NO forKey:@"isb"]; [store setBool:NO forKey:@"isb"];
} }
else else
{ {
[store setBool:YES forKey:@"isb"]; [store setBool:YES forKey:@"isb"];
} }
return synchronize(); return synchronize();
} }
*/ */
ICloud::ICloud() { ICloud::ICloud() {
@ -340,14 +320,11 @@ ICloud::ICloud() {
if (change == NSUbiquitousKeyValueStoreServerChange) { if (change == NSUbiquitousKeyValueStoreServerChange) {
reason = "server"; reason = "server";
} } else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) {
else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) {
reason = "initial_sync"; reason = "initial_sync";
} } else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) {
else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) {
reason = "quota_violation"; reason = "quota_violation";
} } else if (change == NSUbiquitousKeyValueStoreAccountChange) {
else if (change == NSUbiquitousKeyValueStoreAccountChange) {
reason = "account"; reason = "account";
} }

View file

@ -35,8 +35,8 @@
#include "in_app_store.h" #include "in_app_store.h"
extern "C" { extern "C" {
#import <StoreKit/StoreKit.h> #import <StoreKit/StoreKit.h>
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
}; };
bool auto_finish_transactions = true; bool auto_finish_transactions = true;
@ -50,8 +50,7 @@ NSMutableDictionary* pending_transactions = [NSMutableDictionary dictionary];
// SKProduct extension // SKProduct extension
//----------------------------------// //----------------------------------//
@implementation SKProduct (LocalizedPrice) @implementation SKProduct (LocalizedPrice)
- (NSString *)localizedPrice - (NSString *)localizedPrice {
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
@ -164,95 +163,91 @@ Error InAppStore::request_product_info(Variant p_params) {
- (void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray*) transactions { - (void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray*) transactions {
printf("transactions updated!\n"); printf("transactions updated!\n");
for (SKPaymentTransaction* transaction in transactions) { for (SKPaymentTransaction* transaction in transactions) {
switch (transaction.transactionState) { switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased: {
printf("status purchased!\n");
String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
String transactionId = String::utf8([transaction.transactionIdentifier UTF8String]);
InAppStore::get_singleton()->_record_purchase(pid);
Dictionary ret;
ret["type"] = "purchase";
ret["result"] = "ok";
ret["product_id"] = pid;
ret["transaction_id"] = transactionId;
case SKPaymentTransactionStatePurchased: { NSData* receipt = nil;
printf("status purchased!\n"); int sdk_version = 6;
String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
String transactionId = String::utf8([transaction.transactionIdentifier UTF8String]);
InAppStore::get_singleton()->_record_purchase(pid);
Dictionary ret;
ret["type"] = "purchase";
ret["result"] = "ok";
ret["product_id"] = pid;
ret["transaction_id"] = transactionId;
NSData* receipt = nil; if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){
int sdk_version = 6;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){ NSURL *receiptFileURL = nil;
NSBundle *bundle = [NSBundle mainBundle];
if ([bundle respondsToSelector:@selector(appStoreReceiptURL)]) {
NSURL *receiptFileURL = nil; // Get the transaction receipt file path location in the app bundle.
NSBundle *bundle = [NSBundle mainBundle]; receiptFileURL = [bundle appStoreReceiptURL];
if ([bundle respondsToSelector:@selector(appStoreReceiptURL)]) {
// Get the transaction receipt file path location in the app bundle. // Read in the contents of the transaction file.
receiptFileURL = [bundle appStoreReceiptURL]; receipt = [NSData dataWithContentsOfURL:receiptFileURL];
sdk_version = 7;
// Read in the contents of the transaction file. } else {
receipt = [NSData dataWithContentsOfURL:receiptFileURL]; // Fall back to deprecated transaction receipt,
sdk_version = 7; // which is still available in iOS 7.
} else { // Use SKPaymentTransaction's transactionReceipt.
// Fall back to deprecated transaction receipt, receipt = transaction.transactionReceipt;
// which is still available in iOS 7. }
// Use SKPaymentTransaction's transactionReceipt. } else {
receipt = transaction.transactionReceipt; receipt = transaction.transactionReceipt;
} }
}else{ NSString* receipt_to_send = nil;
receipt = transaction.transactionReceipt; if (receipt != nil) {
} receipt_to_send = [receipt description];
}
Dictionary receipt_ret;
receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : "");
receipt_ret["sdk"] = sdk_version;
ret["receipt"] = receipt_ret;
NSString* receipt_to_send = nil; InAppStore::get_singleton()->_post_event(ret);
if (receipt != nil)
{
receipt_to_send = [receipt description];
}
Dictionary receipt_ret;
receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : "");
receipt_ret["sdk"] = sdk_version;
ret["receipt"] = receipt_ret;
InAppStore::get_singleton()->_post_event(ret); if (auto_finish_transactions){
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
} else {
[pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier];
}
if (auto_finish_transactions){ #ifdef MODULE_FUSEBOXX_ENABLED
[[SKPaymentQueue defaultQueue] finishTransaction:transaction]; printf("Registering transaction on Fuseboxx!\n");
} [FuseSDK registerInAppPurchase: transaction];
else{ #endif
[pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier]; }; break;
} case SKPaymentTransactionStateFailed: {
printf("status transaction failed!\n");
String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
Dictionary ret;
ret["type"] = "purchase";
ret["result"] = "error";
ret["product_id"] = pid;
InAppStore::get_singleton()->_post_event(ret);
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}; break;
case SKPaymentTransactionStateRestored: {
printf("status transaction restored!\n");
String pid = String::utf8([transaction.originalTransaction.payment.productIdentifier UTF8String]);
InAppStore::get_singleton()->_record_purchase(pid);
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}; break;
default: {
printf("status default %i!\n", (int)transaction.transactionState);
#ifdef MODULE_FUSEBOXX_ENABLED }; break;
printf("Registering transaction on Fuseboxx!\n");
[FuseSDK registerInAppPurchase: transaction];
#endif
} break;
case SKPaymentTransactionStateFailed: {
printf("status transaction failed!\n");
String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
Dictionary ret;
ret["type"] = "purchase";
ret["result"] = "error";
ret["product_id"] = pid;
InAppStore::get_singleton()->_post_event(ret);
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
} break;
case SKPaymentTransactionStateRestored: {
printf("status transaction restored!\n");
String pid = String::utf8([transaction.originalTransaction.payment.productIdentifier UTF8String]);
InAppStore::get_singleton()->_record_purchase(pid);
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
} break;
default:
printf("status default %i!\n", (int)transaction.transactionState);
break;
}; };
}; };
}; };
@ -266,7 +261,7 @@ Error InAppStore::purchase(Variant p_params) {
if (![SKPaymentQueue canMakePayments]) if (![SKPaymentQueue canMakePayments])
return ERR_UNAVAILABLE; return ERR_UNAVAILABLE;
printf("purchasing!\n"); printf("purchasing!\n");
Dictionary params = p_params; Dictionary params = p_params;
ERR_FAIL_COND_V(!params.has("product_id"), ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(!params.has("product_id"), ERR_INVALID_PARAMETER);
@ -274,7 +269,7 @@ Error InAppStore::purchase(Variant p_params) {
SKPayment *payment = [SKPayment paymentWithProductIdentifier:pid]; SKPayment *payment = [SKPayment paymentWithProductIdentifier:pid];
SKPaymentQueue* defq = [SKPaymentQueue defaultQueue]; SKPaymentQueue* defq = [SKPaymentQueue defaultQueue];
[defq addPayment:payment]; [defq addPayment:payment];
printf("purchase sent!\n"); printf("purchase sent!\n");
return OK; return OK;
}; };
@ -317,20 +312,20 @@ InAppStore::InAppStore() {
TransObserver* observer = [[TransObserver alloc] init]; TransObserver* observer = [[TransObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:observer]; [[SKPaymentQueue defaultQueue] addTransactionObserver:observer];
//pending_transactions = [NSMutableDictionary dictionary]; //pending_transactions = [NSMutableDictionary dictionary];
}; };
void InAppStore::finish_transaction(String product_id){ void InAppStore::finish_transaction(String product_id){
NSString* prod_id = [NSString stringWithCString:product_id.utf8().get_data() encoding:NSUTF8StringEncoding]; NSString* prod_id = [NSString stringWithCString:product_id.utf8().get_data() encoding:NSUTF8StringEncoding];
if ([pending_transactions objectForKey:prod_id]){ if ([pending_transactions objectForKey:prod_id]) {
[[SKPaymentQueue defaultQueue] finishTransaction:[pending_transactions objectForKey:prod_id]]; [[SKPaymentQueue defaultQueue] finishTransaction:[pending_transactions objectForKey:prod_id]];
[pending_transactions removeObjectForKey:prod_id]; [pending_transactions removeObjectForKey:prod_id];
} }
}; };
void InAppStore::set_auto_finish_transaction(bool b){ void InAppStore::set_auto_finish_transaction(bool b){
auto_finish_transactions = b; auto_finish_transactions = b;
} }
InAppStore::~InAppStore() { InAppStore::~InAppStore() {

View file

@ -43,14 +43,11 @@ String iOS::get_rate_url(int p_app_id) const {
//ios7 before //ios7 before
String ret = templ; String ret = templ;
// iOS 7 needs a different templateReviewURL @see https://github.com/arashpayan/appirater/issues/131 if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 && [[[UIDevice currentDevice] systemVersion] floatValue] < 7.1) {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 && [[[UIDevice currentDevice] systemVersion] floatValue] < 7.1) // iOS 7 needs a different templateReviewURL @see https://github.com/arashpayan/appirater/issues/131
{
ret = templ_iOS7; ret = templ_iOS7;
} } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
// iOS 8 needs a different templateReviewURL also @see https://github.com/arashpayan/appirater/issues/182 // iOS 8 needs a different templateReviewURL also @see https://github.com/arashpayan/appirater/issues/182
else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
ret = templ_iOS8; ret = templ_iOS8;
} }

View file

@ -33,8 +33,7 @@
int gargc; int gargc;
char** gargv; char** gargv;
int main(int argc, char *argv[]) int main(int argc, char *argv[]) {
{
printf("*********** main.m\n"); printf("*********** main.m\n");
gargc = argc; gargc = argc;
gargv = argv; gargv = argv;

View file

@ -32,42 +32,42 @@
extern "C" { extern "C" {
int add_path(int, char**); int add_path(int, char**);
int add_cmdline(int, char**); int add_cmdline(int, char**);
int add_path(int p_argc, char** p_args) { int add_path(int p_argc, char** p_args) {
NSString* str = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_path"]; NSString* str = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_path"];
if (!str)
return p_argc;
p_args[p_argc++] = "-path";
[str retain]; // memory leak lol (maybe make it static here and delete it in ViewController destructor? @todo
p_args[p_argc++] = (char*)[str cString];
p_args[p_argc] = NULL;
return p_argc;
};
int add_cmdline(int p_argc, char** p_args) {
NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_cmdline"];
if (!arr)
return p_argc;
for (int i=0; i < [arr count]; i++) {
NSString* str = [arr objectAtIndex:i];
if (!str) if (!str)
continue; return p_argc;
[str retain]; // @todo delete these at some point
p_args[p_argc++] = "-path";
[str retain]; // memory leak lol (maybe make it static here and delete it in ViewController destructor? @todo
p_args[p_argc++] = (char*)[str cString]; p_args[p_argc++] = (char*)[str cString];
p_args[p_argc] = NULL;
return p_argc;
}; };
p_args[p_argc] = NULL; int add_cmdline(int p_argc, char** p_args) {
return p_argc; NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_cmdline"];
}; if (!arr)
return p_argc;
for (int i=0; i < [arr count]; i++) {
NSString* str = [arr objectAtIndex:i];
if (!str)
continue;
[str retain]; // @todo delete these at some point
p_args[p_argc++] = (char*)[str cString];
};
p_args[p_argc] = NULL;
return p_argc;
};
}; };
@ -90,53 +90,52 @@ int add_cmdline(int p_argc, char** p_args) {
NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]; NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"];
switch(p_orientation) { switch(p_orientation) {
case UIInterfaceOrientationLandscapeLeft: case UIInterfaceOrientationLandscapeLeft:
return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO; return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO;
case UIInterfaceOrientationLandscapeRight: case UIInterfaceOrientationLandscapeRight:
return [arr indexOfObject:@"UIInterfaceOrientationLandscapeRight"] != NSNotFound ? YES : NO; return [arr indexOfObject:@"UIInterfaceOrientationLandscapeRight"] != NSNotFound ? YES : NO;
case UIInterfaceOrientationPortrait: case UIInterfaceOrientationPortrait:
return [arr indexOfObject:@"UIInterfaceOrientationPortrait"] != NSNotFound ? YES : NO; return [arr indexOfObject:@"UIInterfaceOrientationPortrait"] != NSNotFound ? YES : NO;
case UIInterfaceOrientationPortraitUpsideDown: case UIInterfaceOrientationPortraitUpsideDown:
return [arr indexOfObject:@"UIInterfaceOrientationPortraitUpsideDown"] != NSNotFound ? YES : NO; return [arr indexOfObject:@"UIInterfaceOrientationPortraitUpsideDown"] != NSNotFound ? YES : NO;
default: default:
return NO; return NO;
} }
}; };
uint8_t supported = OSIPhone::get_singleton()->get_orientations(); uint8_t supported = OSIPhone::get_singleton()->get_orientations();
switch(p_orientation) { switch(p_orientation) {
case UIInterfaceOrientationLandscapeLeft: case UIInterfaceOrientationLandscapeLeft:
return supported & (1<<OSIPhone::LandscapeLeft) ? YES : NO; return supported & (1<<OSIPhone::LandscapeLeft) ? YES : NO;
case UIInterfaceOrientationLandscapeRight: case UIInterfaceOrientationLandscapeRight:
return supported & (1<<OSIPhone::LandscapeRight) ? YES : NO; return supported & (1<<OSIPhone::LandscapeRight) ? YES : NO;
case UIInterfaceOrientationPortrait: case UIInterfaceOrientationPortrait:
return supported & (1<<OSIPhone::PortraitDown) ? YES : NO; return supported & (1<<OSIPhone::PortraitDown) ? YES : NO;
case UIInterfaceOrientationPortraitUpsideDown: case UIInterfaceOrientationPortraitUpsideDown:
return supported & (1<<OSIPhone::PortraitUp) ? YES : NO; return supported & (1<<OSIPhone::PortraitUp) ? YES : NO;
default: default:
return NO; return NO;
} }
}; };
- (BOOL)prefersStatusBarHidden - (BOOL)prefersStatusBarHidden {
{
return YES; return YES;
} }
#ifdef GAME_CENTER_ENABLED #ifdef GAME_CENTER_ENABLED
- (void) gameCenterViewControllerDidFinish:(GKGameCenterViewController*) gameCenterViewController { - (void) gameCenterViewControllerDidFinish:(GKGameCenterViewController*) gameCenterViewController {
//[gameCenterViewController dismissViewControllerAnimated:YES completion:^{GameCenter::get_singleton()->game_center_closed();}];//version for signaling when overlay is completely gone //[gameCenterViewController dismissViewControllerAnimated:YES completion:^{GameCenter::get_singleton()->game_center_closed();}];//version for signaling when overlay is completely gone
GameCenter::get_singleton()->game_center_closed(); GameCenter::get_singleton()->game_center_closed();
[gameCenterViewController dismissViewControllerAnimated:YES completion:nil]; [gameCenterViewController dismissViewControllerAnimated:YES completion:nil];
} }
#endif #endif

View file

@ -39,30 +39,30 @@ int main(int argc, char** argv) {
int first_arg = 1; int first_arg = 1;
const char* dbg_arg = "-NSDocumentRevisionsDebugMode"; const char* dbg_arg = "-NSDocumentRevisionsDebugMode";
printf("arguments\n"); printf("arguments\n");
for (int i=0; i<argc; i++) { for (int i = 0; i < argc; i++) {
if (strcmp(dbg_arg, argv[i]) == 0) if (strcmp(dbg_arg, argv[i]) == 0)
first_arg = i+2; first_arg = i+2;
printf("%i: %s\n", i, argv[i]); printf("%i: %s\n", i, argv[i]);
}; };
if (argc>=1 && argv[0][0]=='/') { if (argc >= 1 && argv[0][0] == '/') {
//potentially launched from finder //potentially launched from finder
int len = strlen(argv[0]); int len = strlen(argv[0]);
while (len--) { while (len--) {
if (argv[0][len] == '/') break; if (argv[0][len] == '/') break;
} }
if (len>=0) { if (len >= 0) {
char *path = (char *)malloc(len+1); char *path = (char *)malloc(len+1);
memcpy(path, argv[0], len); memcpy(path, argv[0], len);
path[len]=0; path[len] = 0;
char *pathinfo = (char*)malloc(strlen(path)+strlen("/../Info.plist")+1); char *pathinfo = (char*)malloc(strlen(path) + strlen("/../Info.plist")+1);
//in real code you would check for errors in malloc here //in real code you would check for errors in malloc here
strcpy(pathinfo, path); strcpy(pathinfo, path);
strcat(pathinfo, "/../Info.plist"); strcat(pathinfo, "/../Info.plist");
FILE*f=fopen(pathinfo,"rb"); FILE*f=fopen(pathinfo, "rb");
if (f) { if (f) {
//running from app bundle, as Info.plist was found //running from app bundle, as Info.plist was found
fclose(f); fclose(f);
@ -74,15 +74,12 @@ int main(int argc, char** argv) {
free(path); free(path);
free(pathinfo); free(pathinfo);
} }
} }
OS_OSX os; OS_OSX os;
Error err = Main::setup(argv[0],argc-first_arg,&argv[first_arg]); Error err = Main::setup(argv[0], argc-first_arg, &argv[first_arg]);
if (err!=OK) if (err!=OK)
return 255; return 255;

View file

@ -43,18 +43,18 @@ static BOOL gCalledAppMainline = FALSE;
static NSString *getApplicationName(void) static NSString *getApplicationName(void)
{ {
const NSDictionary *dict; const NSDictionary *dict;
NSString *appName = 0; NSString *appName = 0;
/* Determine the application name */ /* Determine the application name */
dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
if (dict) if (dict)
appName = [dict objectForKey: @"CFBundleName"]; appName = [dict objectForKey: @"CFBundleName"];
if (![appName length]) if (![appName length])
appName = [[NSProcessInfo processInfo] processName]; appName = [[NSProcessInfo processInfo] processName];
return appName; return appName;
} }
/* The main class of the application, the application's delegate */ /* The main class of the application, the application's delegate */
@ -62,97 +62,97 @@ static NSString *getApplicationName(void)
static void setApplicationMenu(void) static void setApplicationMenu(void)
{ {
/* warning: this code is very odd */ /* warning: this code is very odd */
NSMenu *appleMenu; NSMenu *appleMenu;
NSMenuItem *menuItem; NSMenuItem *menuItem;
NSString *title; NSString *title;
NSString *appName; NSString *appName;
appName = getApplicationName(); appName = getApplicationName();
appleMenu = [[NSMenu alloc] initWithTitle:@""]; appleMenu = [[NSMenu alloc] initWithTitle:@""];
/* Add menu items */ /* Add menu items */
title = [@"About " stringByAppendingString:appName]; title = [@"About " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]]; [appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Hide " stringByAppendingString:appName]; title = [@"Hide " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]]; [appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Quit " stringByAppendingString:appName]; title = [@"Quit " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
/* Put menu into the menubar */ /* Put menu into the menubar */
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[menuItem setSubmenu:appleMenu]; [menuItem setSubmenu:appleMenu];
[[NSApp mainMenu] addItem:menuItem]; [[NSApp mainMenu] addItem:menuItem];
/* Tell the application object that this is now the application menu */ /* Tell the application object that this is now the application menu */
[NSApp setAppleMenu:appleMenu]; [NSApp setAppleMenu:appleMenu];
/* Finally give up our references to the objects */ /* Finally give up our references to the objects */
[appleMenu release]; [appleMenu release];
[menuItem release]; [menuItem release];
} }
/* Create a window menu */ /* Create a window menu */
static void setupWindowMenu(void) static void setupWindowMenu(void)
{ {
NSMenu *windowMenu; NSMenu *windowMenu;
NSMenuItem *windowMenuItem; NSMenuItem *windowMenuItem;
NSMenuItem *menuItem; NSMenuItem *menuItem;
windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
/* "Minimize" item */ /* "Minimize" item */
menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
[windowMenu addItem:menuItem]; [windowMenu addItem:menuItem];
[menuItem release]; [menuItem release];
/* Put menu into the menubar */ /* Put menu into the menubar */
windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
[windowMenuItem setSubmenu:windowMenu]; [windowMenuItem setSubmenu:windowMenu];
[[NSApp mainMenu] addItem:windowMenuItem]; [[NSApp mainMenu] addItem:windowMenuItem];
/* Tell the application object that this is now the window menu */ /* Tell the application object that this is now the window menu */
[NSApp setWindowsMenu:windowMenu]; [NSApp setWindowsMenu:windowMenu];
/* Finally give up our references to the objects */ /* Finally give up our references to the objects */
[windowMenu release]; [windowMenu release];
[windowMenuItem release]; [windowMenuItem release];
} }
/* Replacement for NSApplicationMain */ /* Replacement for NSApplicationMain */
static void CustomApplicationMain (int argc, char **argv) static void CustomApplicationMain (int argc, char **argv)
{ {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
GodotMain *main; GodotMain *main;
/* Ensure the application object is initialised */ /* Ensure the application object is initialised */
[NSApplication sharedApplication]; [NSApplication sharedApplication];
/* Set up the menubar */ /* Set up the menubar */
[NSApp setMainMenu:[[NSMenu alloc] init]]; [NSApp setMainMenu:[[NSMenu alloc] init]];
setApplicationMenu(); setApplicationMenu();
setupWindowMenu(); setupWindowMenu();
main = [[main alloc] init]; main = [[main alloc] init];
[NSApp setDelegate:main]; [NSApp setDelegate:main];
/* Start the main event loop */ /* Start the main event loop */
[NSApp run]; [NSApp run];
[main release]; [main release];
[pool release]; [pool release];
} }
extern int godot_main(int argc, char** argv); extern int godot_main(int argc, char** argv);
@ -160,10 +160,10 @@ extern int godot_main(int argc, char** argv);
/* Called when the internal event loop has just started running */ /* Called when the internal event loop has just started running */
- (void) applicationDidFinishLaunching: (NSNotification *) note - (void) applicationDidFinishLaunching: (NSNotification *) note
{ {
int status; int status;
/* Hand off to main application code */ /* Hand off to main application code */
gCalledAppMainline = TRUE; gCalledAppMainline = TRUE;
int ret = godot_main(global_argc, global_argv); int ret = godot_main(global_argc, global_argv);
@ -172,44 +172,43 @@ extern int godot_main(int argc, char** argv);
@end @end
#ifdef main #ifdef main
# undef main #undef main
#endif #endif
int main (int argc, char **argv) int main (int argc, char **argv)
{ {
/* Copy the arguments into a global variable */ /* Copy the arguments into a global variable */
/* This is passed if we are launched by double-clicking */ /* This is passed if we are launched by double-clicking */
if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
global_argv = (char **) malloc(sizeof (char *) * 2); global_argv = (char **) malloc(sizeof (char *) * 2);
global_argv[0] = argv[0]; global_argv[0] = argv[0];
global_argv[1] = NULL; global_argv[1] = NULL;
global_argc = 1; global_argc = 1;
// chdir to binary's dir when launched from finder // chdir to binary's dir when launched from finder
int len = strlen(global_argv[0]); int len = strlen(global_argv[0]);
while (len--){ while (len--){
if (global_argv[0][len] == '/') break; if (global_argv[0][len] == '/') break;
} }
if (len>=0) { if (len>=0) {
char *path = (char *)malloc(len+1); char *path = (char *)malloc(len+1);
memcpy(path, global_argv[0], len); memcpy(path, global_argv[0], len);
path[len]=0; path[len]=0;
printf("Path: %s\n", path); printf("Path: %s\n", path);
chdir(path); chdir(path);
} }
} else { } else {
int i; int i;
global_argc = argc; global_argc = argc;
global_argv = (char **) malloc(sizeof (char *) * (argc+1)); global_argv = (char **) malloc(sizeof (char *) * (argc+1));
for (i = 0; i <= argc; i++) for (i = 0; i <= argc; i++)
global_argv[i] = argv[i]; global_argv[i] = argv[i];
} }
CustomApplicationMain (argc, argv); CustomApplicationMain (argc, argv);
return 0; return 0;
} }

File diff suppressed because it is too large Load diff