#import #import extern "C" UIViewController *UnityGetGLViewController(void); typedef void (*RankCallback)(int, const char *); typedef void (*PlayerCallback)(const char *); typedef void (*ProfileCallback)(const char *, const char *, const void *, int); namespace { enum Board { BestNight, TotalScore, BoardCount }; NSString *const keys[] = { @"BestNightRankID", @"TotalScoreRankID" }; NSInteger desired[BoardCount], confirmed[BoardCount]; bool submitting[BoardCount], installed, resolvingAuth; NSUInteger session; NSString *account; PlayerCallback signedIn; ProfileCallback profileChanged; NSUInteger photoRequest; void (^afterAuth)(void); void RefreshPlayerProfile() { NSUInteger request = ++photoRequest; if (!profileChanged) return; GKLocalPlayer *player = GKLocalPlayer.localPlayer; if (!player.isAuthenticated) { profileChanged(nullptr, nullptr, nullptr, 0); return; } NSString *playerID = [player.gamePlayerID copy]; NSString *name = player.displayName.length ? player.displayName : player.alias; // Publish the name immediately. A negative length means the photo is still pending. profileChanged(playerID.UTF8String, name.UTF8String, nullptr, -1); [player loadPhotoForSize:GKPhotoSizeNormal withCompletionHandler:^(UIImage *image, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ if (request != photoRequest || !profileChanged || !player.isAuthenticated || ![playerID isEqualToString:player.gamePlayerID] || (!image && error)) return; NSData *png = image ? UIImagePNGRepresentation(image) : nil; profileChanged(playerID.UTF8String, name.UTF8String, png.bytes, (int)png.length); }); }]; } NSString *BoardID(int board) { id value = [NSBundle.mainBundle objectForInfoDictionaryKey:keys[board]]; if (![value isKindOfClass:NSString.class]) return nil; return [value stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; } bool ValidBoards() { NSString *night = BoardID(BestNight), *score = BoardID(TotalScore); return night.length && score.length && ![night isEqualToString:score]; } void Flush() { GKLocalPlayer *player = GKLocalPlayer.localPlayer; if (!player.isAuthenticated || ![account isEqualToString:player.gamePlayerID] || !ValidBoards()) return; for (int i = 0; i < BoardCount; ++i) { NSInteger value = desired[i]; if (submitting[i] || value <= confirmed[i]) continue; submitting[i] = true; NSUInteger generation = session; [GKLeaderboard submitScore:value context:0 player:player leaderboardIDs:@[BoardID(i)] completionHandler:^(NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ if (session != generation) return; submitting[i] = false; if (error) { NSLog(@"[TowerDevil] Game Center score submission failed: %@", error.localizedDescription); return; // The saved profile is retried on the next sync or leaderboard visit. } confirmed[i] = value; if (desired[i] > value) Flush(); }); }]; } } void Authenticate() { if (installed) return; installed = true; resolvingAuth = true; GKLocalPlayer.localPlayer.authenticateHandler = ^(UIViewController *controller, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ if (controller) { UIViewController *host = UnityGetGLViewController(); while (host.presentedViewController && host.presentedViewController != controller) host = host.presentedViewController; if (host && !controller.presentingViewController) [host presentViewController:controller animated:YES completion:nil]; return; } resolvingAuth = false; GKLocalPlayer *player = GKLocalPlayer.localPlayer; NSString *current = player.isAuthenticated ? player.gamePlayerID : nil; if (current != account && ![current isEqualToString:account]) { account = [current copy]; ++session; for (int i = 0; i < BoardCount; ++i) { desired[i] = confirmed[i] = 0; submitting[i] = false; } } if (current.length && signedIn) signedIn(current.UTF8String); RefreshPlayerProfile(); void (^pending)(void) = afterAuth; afterAuth = nil; if (pending) pending(); }); }; } void Reply(int request, RankCallback callback, NSDictionary *result) { NSData *data = [NSJSONSerialization dataWithJSONObject:result options:0 error:nil]; NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; callback(request, json.UTF8String); } NSDictionary *Row(GKLeaderboardEntry *entry, bool mine) { return @{@"rank": @(entry.rank), @"name": entry.player.displayName ?: @"", @"score": @(entry.score), @"mine": @(mine)}; } void Load(int board, int request, RankCallback callback) { if (!ValidBoards()) { Reply(request, callback, @{@"error": @"Game Center leaderboard IDs are missing or invalid."}); return; } if (!GKLocalPlayer.localPlayer.isAuthenticated) { Reply(request, callback, @{@"error": @"Sign in to Game Center in iOS Settings, then try again."}); return; } Flush(); NSUInteger generation = session; NSString *identifier = BoardID(board); [GKLeaderboard loadLeaderboardsWithIDs:@[identifier] completionHandler:^(NSArray *boards, NSError *error) { GKLeaderboard *leaderboard = boards.firstObject; if (error || ![leaderboard.baseLeaderboardID isEqualToString:identifier]) { dispatch_async(dispatch_get_main_queue(), ^{ Reply(request, callback, @{@"error": @"This leaderboard is unavailable. Try again later."}); }); return; } [leaderboard loadEntriesForPlayerScope:GKLeaderboardPlayerScopeGlobal timeScope:GKLeaderboardTimeScopeAllTime range:NSMakeRange(1, 10) completionHandler:^(GKLeaderboardEntry *local, NSArray *entries, NSInteger total, NSError *loadError) { dispatch_async(dispatch_get_main_queue(), ^{ if (loadError || session != generation || !GKLocalPlayer.localPlayer.isAuthenticated) { Reply(request, callback, @{@"error": @"Could not load standings. Try again."}); return; } NSMutableArray *rows = [NSMutableArray array]; bool includesLocal = false; for (GKLeaderboardEntry *entry in entries) { bool mine = [entry.player.gamePlayerID isEqualToString:account]; [rows addObject:Row(entry, mine)]; includesLocal |= mine; } if (!includesLocal && local.rank > 0 && local.rank <= total) [rows addObject:Row(local, true)]; Reply(request, callback, @{@"entries": rows}); }); }]; }]; } } // namespace extern "C" void TDGameCenterObserveProfile(ProfileCallback callback) { dispatch_async(dispatch_get_main_queue(), ^{ profileChanged = callback; RefreshPlayerProfile(); }); } extern "C" void TDGameCenterSync(const char *owner, int bestNight, int totalScore, PlayerCallback player) { NSString *ownerID = owner ? [NSString stringWithUTF8String:owner] : nil; dispatch_async(dispatch_get_main_queue(), ^{ signedIn = player; Authenticate(); if (!account.length || ![account isEqualToString:ownerID]) return; desired[BestNight] = bestNight; desired[TotalScore] = totalScore; Flush(); }); } extern "C" void TDGameCenterLoad(int board, int request, RankCallback callback) { dispatch_async(dispatch_get_main_queue(), ^{ Authenticate(); if (resolvingAuth) afterAuth = ^{ Load(board, request, callback); }; else Load(board, request, callback); }); }