purplelilgirl

makes games & other things

Posts tagged cocos2d

0 notes

Thoughts while reading Cocos2d-X by Example Beginner’s Guide Chapters 1 & 2

Packt published a new book on Cocos2d-X, “Cocos2d-X by Example Beginner’s Guide” by Roger Engelbert (http://www.packtpub.com/cocos2d-x-by-example/book)

Cocos2d-X by Example Beginner's Guide

First off, book cover is adorable.


Second, the book’s spiel says no programming knowledge required, oh really now? Anyway, I know Cocos2d, but I don’t know Cocos2dx nor C++, the language for Cocos2dx, so here I go. If I can make some cookie cutter games at the end of this review then…

I’m just going to spurt words while I read the blog and maybe give an overall summary and reviews at the end of this post. You can ignore the italicized parts, those are just random ramblings.

#nowplaying Lana Del Rey’s Young and Beautiful #onloop after watching “The Great Gatsby” last night.

Chapter 1 covers Installation. Installing Cocos2dx and whatnots.

The book assumes that you are on a Mac and you have Xcode, which yeah, I am and iOS dev and all, I have Xcode.

Okay, the book gives pretty clear instructions on where to download Cocos2dx. now, I just need a few minutes to download them.

Cram my Crash Course for Creativity assignment till then.

Okay, the instructions for installing are pretty clear. Although my Terminal had some other suggestions for how to properly install it. Anyway, that’s done. So when I create a new project in Xcode now I’ll be able to see the different Cocos2dx templates, awesome.

Just “built” and run my first Cocos2dx program, okay, the coconut head is silver and blue now. Looks kinda funky like Pepsi Blue.

Anyway, he did a brief run through on how to run the Cocos2dx samples so that we could see all the infinite possibilities, okay not really infinite, but it’s a pretty long list of sample tests.

And then, he says might need to spend some money on additional tools. He recommend and uses four tools.

TexturePacker, although you can also use Zwoptex as a free alternative. TexturePacker’s Andreas Löw actually used to offer (not sure if he still does, try tweeting him) licenses for bloggers. So yah, I have a free copy of TexturePacker.

ParticleDesigner, which will ease the process of making particles. No, I don’t have that. I’ll probably look for some free alternatives, the author didn’t mention or recommend any.

A tool to help build bitmap fonts, he recommended Glyph designer (not free), bmGlyph (cheaper, but yah, still not free) and FontBuilder (yeah, free). According to him “It is not extremely hard to build a Bitmap font by hand, not nearly as hard as building a particle effect from scratch, but doing it once is enough to convince you to get one of these tools fast.” Back in my Cocos2d days I used Hiero (free) and Photoshop (self advertise: blog on How to Make Fancy Labels using Cocos2d http://purplelilgirl.tumblr.com/post/2854271507/how-to-make-fancy-labels-using-cocos2d).

And according to him, no contest cfxr for sound effects. Free!

And we are done with Chapter 1. We installed Cocos2dx, and run a few sample projects and got to know the structure of basic Cocos2dx applications, so on to Chapter 2.

Chapter 2 gives an intro of C++ and Cocos2dx.

“This chapter will be aimed at two types of developers: the original Cocos2d developer who is scared of C++ but won’t admit it to his friends; and the C++ coder who never even heard of Cocos2d and finds Objective-C funny looking.”

I’m the first type, but I’m not afraid to admit that I’m afraid of C++. I am terrified of C++. If you give me an exam in C++, I will (and have, twice) submit an empty exam sheet (surprisingly passed one of those exams, I think the examiner took pity on account of my C++ phobia).

Can you tell that I’m stalling?

First the author goes through the basics of Cocos2d, if you know Cocos2d then you’re good to go. So far…

And then comes the dreaded C++ bits.

He says, “Don’t worry. The C part is easy, the first plus goes by really fast, but that second plus, Oh, boy.” Er… Oh boy…

I like the way the author talks in this book, kind of entertaining in a way.

He said to open your favorite text editor, because he doesn’t want code hinting and autocomplete features to get in the way. What? How did you think I finished a game in XNA without little knowledge in XNA, and completely zero knowledge in C#?! Code hinting and autocomplete, seriously.

My favorite text editor - TextEdit, because it comes bundled with a Mac. if I were on my PC laptop, I’d say Notepad, because that’s bundled there. I used to write websites in Notepad, those were the days… Yah, still stalling.

C++ syntax. Okay, so far, apprehensive.

Instantiation and Memory Management. Two words, no ARC. “so Objective-C developers who have forgotten memory management might have a problem here.” Uh oh.

The rule regarding memory management with C++ is very simple: if you new, you must delete.” Okay, I get that. And it supposedly has some other options and commands that’s similar to Objective C without ARC, okay.

 And then he continues with how to instantiate stuff. Okay, so far so good. And a little about the Cocos2dx equivalent of Objective C stuff. Okay, understood.

And summary. He says, “hopefully non C++ developers have learned that there is nothing to fear”. Um.. so far, not completely convinced, but I think I can manage.

He ends this chapter with “and furthermore Cocos2dx is awesome!” (fan boy) and “So let’s create a game already!”. 

Yes, lets. But maybe I’ll continue reading this tomorrow.

Filed under cocos2dx packt book review thoughts c++ development resource cocos2d ios android

0 notes

Creating Games with Cocos2d for iPhone 2

Packt Publishing recently released a new book called “Creating Games with Cocos2d for iPhone 2”, written by Paul Nygard.

The name is a bit confusing to me, the 2 in the book title refers to the book being the second Cocos2d book from Packt or 2 as in Cocos2d version 2.0?

Anyway, the book in detail from their website:

Cocos2d for iPhone is a simple (but powerful) 2D framework that makes it easy to create games for the iPhone. There are thousands of games in the App Store already using cocos2d. Game development has never been this approachable and easy to get started.

"Creating Games with cocos2d for iPhone 2" takes you through the entire process of designing and building nine complete games for the iPhone, iPod Touch, or iPad using cocos2d 2.0. The projects start simply and gradually increase in complexity, building on the lessons learned in previous chapters. Good design practices are emphasized throughout.

From a simple match game to an endless runner, you will learn how to build a wide variety of game styles.

You will learn how to implement animation, actions, create “artificial randomness”, use the Box2D physics engine, create tile maps, and even use Bluetooth to play between two devices.

"Creating games with cocos2d for iPhone 2" will take your game building skills to the next level.

You will learn:

  • Control sprites with touch, joysticks, and tilt controls
  • Use sprite sheets, particles, and plists effectively
  • Learn multiple approaches to solve common challenges
  • Integrate cocos2d with the Box2D physics engine
  • Use third-party programs for joystick control, tile maps, and more
  • Implement Bluetooth to play across multiple devices
  • Learn game-specific A.I. design methodologies

Looking at the book’s Table of Contents, I see that there are 9 different games that will be taught in the book. Like all other Packt books, Source Codes are included.

There is a memory game, “Thanks for the Memories” (which reminds me of the Fall Out Boy song). It’s basically a memory card game. A Match 3 game, Whack-a-Mole, Snake, a breakout game, "Light Cycles of TRON" game, pool, a scrolling shooter, and an endless runner. They are pretty run-the-mill games.

This book is aimed at readers with an understanding of Objective-C and some familiarity with the cocos2d for iPhone 2.0 framework.

I’m not through reading the book yet, so this is it for now. Sorry >.< I’ll write the review as soon as I’m done with it.

You can get the book on the Packt website: http://www.packtpub.com/creating-games-with-cocos2d-for-iphone-2/book

Filed under cocos2d book packt iphone development review

10 notes

Ultimate List of Purplelilgirl Tutorials

Throughout the year(s) I have accumulated a number of mini tutorials, code bits and links, but they are just scattered in this blog like.. um.. sprinkles? And they need to be organized. So here, I am going to attempt to create a link list:

Unity-related:

Cocos2D-related:

Mac-related:

Misc. iOS and game development-related:

Book reviews and overviews:

Games, apps reviews and self-promotions:

Gamasutra blogs and reblogs:

Filed under tutorials links ios cocos2d unity facebook

2 notes

How to create physics objects in Cocos2D with just one click? (well, more or less one click)

Answer: PhysicsEditor

The PhysicsEditor is a shape editor for physics engines like Box2D and Chipmunk.

Before when I was making physics objects in Cocos2D, I used VertexHelper (Johannes Fahrenkrug), which is great and all, but there were a lot of things that you had to consider, such as you had to define the vertices yourself (meaning: ‘click “around” each sprite to define it’s vertices’) and you have to make sure that you don’t accidentally create any concave polygons (what are concave polygons again? check Wikipedia), and then you have to copy paste the generated code into your project. VertexHelper served me well and all, and it was free.

But PhysicsEditor did make me life a whole lot easier.

Andreas Loew wrote tutorials on his blog on how to use PhysicsEditor with Cocos2D:

Filed under physicseditor cocos2d box2d

3 notes

Review: Cocos2d for iPhone 1 Game Development Cookbook

"Cocos2d for iPhone 1 Game Development Cookbook" is written by Nathan Burba (@nathanburba).

Cocos2d for iPhone 1 Game Development Cookbook
According to the description, it has “over 90 recipes for iOS 2D game development using cocos2d”. and just by looking at it’s Table of Contents, you’d see that this book covers a lot of topics (some advanced techniques that other cocos2d books have not covered). It also provides solutions to some common problems that we developers might encounter during Cocos2d iOS development.

Like in Chapter 1, it covers graphics, but unlike other books that would only teach you how to make sprites and spritesheets, this book even teaches you how to use apply mipmapping so that that when you scale up or down a sprite it wouldn’t look pixelated. It also has a recipe for a cool technique by swapping palettes so that even with limited amount of art, you can create various versions of a sprite (a single baseball player texture can have be used to create different baseball players with different colored shirts and pants etc). Chapter 1 also answers some questions that you might encounter while working on your game, such as how to I play a video clip of my company’s logo or my game’s cutscene (playing video files recipe). It also covers how to render 3D objects, drawing OpenGL primitives, particles, etc.

Chapter 2 is all about User Input on iOS devices, including the usual (tap, hold, drag), making virtual buttons (creating an analog stick recipe and directional pad recipe) and using the accelerometer. One really cool (for me) recipe that’s also included is gestures (you’d be able to tell what shape the user drew on the screen)!

Chapter 3 is about Files and Data. In making games, we’d need ways to store data (just us score, or level design, etc) and this chapter covers different ways for us to do this. This chapter has recipes for reading plist, json, xml data files, it also includes recipes about archiving objects, saving data using plist, SQLite, Core Data, etc.

Chapter 4 is about physics. Cocos2d has two physics engines that we can use Box2d and Chipmunk. This book only covers Box2d (which is the engine that Angry Birds used), it includes detailed explanations and recipes on how to set up your Box2d environment and simulating physics properties. it even includes a recipe on how to make a car drive up a bumpy hill road!

Chapter 5 is about Scenes and Menus. It also includes how to create buttons and labels (with fancy shadow effects even)! It also has a recipe for wrapping the UIKIT and using it in our Cocos2d game.

Chapter 6 is all about Audio: how to play background sound effects, play music, using the iPod music library. But the really fun bits about this chapter is it even teaches you how to record audio, create a MIDI synthesizer, and to top it all off, it even covers spech recognition and text to speech! Imagine all the games and apps that you can make with those things.

Chapter 7 covers AI, including waypoints, flocking using boids and A* pathfinding. it also teaches you how to run lua scripts and use lua scripts for dialog trees.

Chapter 8 is called Tips, Tools and Ports, and sure enough it includes information about tools that can be used for our Cocos2d game development. Best part, it also includes detailed step by step instructions of how to put your game on the AppStore!

Overall this is a good book with a lot of useful and varied information that have not been covered in other books (and are often lacking in online tutorials). Also
the best thing about this book is it comes with complete working code and detailed explanations on how the code works.

Except some of the topics covered in this book are a bit advanced, so this book is not recommended for beginners, basic Objective C and Cocos2d knowledge is required.

Also the author, Nathan is also very active in the Cocos2d forums, if you have any questions about the book you can just ask him, and he almost always responds immediately.

So if you’re interested to learn new things about Cocos2d iOS development, do check it out! Also if you are interested in this book, I am holding a giveaway contest (where I am giving away 3-4 copies of the book), join now (it’s only until this Wednesday). For more details read my previous blog post (http://purplelilgirl.tumblr.com/post/15713172087/cocos2d-for-iphone-1-game-development-cookbook-giveaway)

Filed under cocos2d packt ios game development

6 notes

Cocos2d for iPhone 1 Game Development Cookbook Giveaway

UPDATE: This contest is now closed

Like I mentioned in my previous post, Packt published a new Cocos2d book and they asked me to hold a giveaway contest. I’m holding it both here and in the Cocos2d forums (http://www.cocos2d-iphone.org/forum/topic/28099).

So here it is, rules, rules:

  • I will select a winner using random.org :)
  • Contest ends on 12 Noon Pacific Standard Time January 18th.

There, pretty simple right? :)

Also ManiacDev is also holding a book giveaway contest, he is giving away Unity3D and iOS books. If you guys are interested you can check out his blog: http://maniacdev.com/2012/01/giveaway-get-a-unity-3d-or-ios-book-there-will-be-6-winners-enter-here/

That’s about it :)

Filed under giveaway books packt cocos2d

3 notes

Cocos2d for iPhone 1 Game Development Cookbook

Packt recently released a new Cocos2d book: “Cocos2d for iPhone 1 Game Development Cookbook” by Nathan Burba.

Cocos2d for iPhone 1 Game Development Cookbook

Overview of Cocos2d for iPhone 1 Game Development Cookbook

  • Discover advanced Cocos2d, OpenGL ES, and iOS techniques spanning all areas of the game development process
  • Learn how to create top-down isometric games, side-scrolling platformers, and games with realistic lighting
  • Full of fun and engaging recipes with modular libraries that can be plugged into your project
  • Over 90 recipes for iOS 2D game development using cocos2d

Link: http://www.packtpub.com/cocos2d-for-iphone-1-game-development-cookbook/book

Filed under cocos2d iphone ios game development packt

23 notes

Mini Tutorial: How to capture video of iPhone app in Cocos2D? with audio

Okay, so I figured out how to add audio to my video.

In my previous blog post (http://purplelilgirl.tumblr.com/post/10974345146/mini-tutorial-how-to-capture-video-of-iphone-app-in), I managed to take a video of my app and save it into a file. However I am just stringing together screenshots of my app taken at every 0.1 second, so it doesn’t capture the audio.

So I have a different function that is capturing my audio (AVAudioRecorder), and saving that into a file.

Now, to combine the files together. Since iOS 4.1, AVFoundation included this thing called AVMutableComposition, and with that you can make composites of stuff, like combine video and audio files together to make a new video file that has audio.

So code bits (I found bits of the code in StackOverflow):

-(void) processVideo: (NSURL*) videoUrl
{  
    AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL: videoUrl options:nil];
   
    AVMutableComposition* mixComposition = [AVMutableComposition composition];
   
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
   
    NSError * error = nil;
   
    for (NSMutableDictionary * audioInfo in appDelegate.audioInfoArray)
    {
        NSString *pathString = [[NSHomeDirectory() stringByAppendingString:@”/Documents/”] stringByAppendingString: [audioInfo objectForKey: @”fileName”]];
       
        AVURLAsset * urlAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:pathString] options:nil];
       
        AVAssetTrack * audioAssetTrack = [[urlAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
        AVMutableCompositionTrack *compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
                                                                                       preferredTrackID: kCMPersistentTrackID_Invalid];
       
        NSLog(@”%lf”, [[audioInfo objectForKey: @”startTime”] doubleValue]);
       
        CMTime audioStartTime = CMTimeMake(([[audioInfo objectForKey: @”startTime”] doubleValue]*TIME_SCALE), TIME_SCALE);
       
        [compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero,urlAsset.duration) ofTrack:audioAssetTrack atTime:audioStartTime error:&error];     
    }
   
   
    AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                                   preferredTrackID:kCMPersistentTrackID_Invalid];
    [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
                                   ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]
                                    atTime:kCMTimeZero error:nil];
   
    AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition
                                                                          presetName:AVAssetExportPresetPassthrough];  
   
    NSString* videoName = @”export.mov”;
   
    NSString *exportPath = [[self pathToDocumentsDirectory] stringByAppendingPathComponent:videoName];
    NSURL    *exportUrl = [NSURL fileURLWithPath:exportPath];
   
    if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
    }
   
    _assetExport.outputFileType = @”com.apple.quicktime-movie”;
    NSLog(@”file type %@”,_assetExport.outputFileType);
    _assetExport.outputURL = exportUrl;
    _assetExport.shouldOptimizeForNetworkUse = YES;
   
    [_assetExport exportAsynchronouslyWithCompletionHandler:
     ^(void ) {
         switch (_assetExport.status)
         {
             case AVAssetExportSessionStatusCompleted:
                 //export complete
                 NSLog(@”Export Complete”);
                 //[self uploadToYouTube];
                
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@”Export Failed”);
                 NSLog(@”ExportSessionError: %@”, [_assetExport.error localizedDescription]);
                 //export error (see exportSession.error) 
                 break;
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@”Export Failed”);
                 NSLog(@”ExportSessionError: %@”, [_assetExport.error localizedDescription]);
                 //export cancelled 
                 break;
         }
     }];   
}

I have more than one audio file that I want to combine with my video, so I created a array file that contains information for each of the audio files (such as where the file is located and when to play that audio).

And that’s it :) You have a video of your app :) with audio :)

Filed under app audio avfoundation talking tutorial video cocos2d iphone development app

42 notes

Mini Tutorial: How to capture video of iPhone app in Cocos2D?

Someone asked me before if I knew how to do record the screen in Cocos2d as a video. I didn’t know how to record a video, so this guy sent me some codes, but his problem is that his code is recording the screen (taking screenshots) as a UIWindow. So my idea for him was to replace his screenshot code with AWScreenshot (by Manucorporat, search the Cocos2d forums for his code).

And here are the code bits:

#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVAssetWriter.h>
#import <CoreVideo/CVPixelBuffer.h>
#import <CoreMedia/CMTime.h>


#import “AWScreenshot.h”

#define FRAME_WIDTH 320
#define FRAME_HEIGHT 480
#define TIME_SCALE 60 // frames per second

-(void) startScreenRecording
{  
    NSLog(@”start screen recording”);
   
    // create the AVAssetWriter
    NSString *moviePath = [[self pathToDocumentsDirectory] stringByAppendingPathComponent: @”video.mov”];
    if ([[NSFileManager defaultManager] fileExistsAtPath:moviePath])
    {   [[NSFileManager defaultManager] removeItemAtPath:moviePath error:nil];
    }
   
    NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
    NSError *movieError = nil;
   
    [assetWriter release];
    assetWriter = [[AVAssetWriter alloc] initWithURL:movieURL
                                            fileType: AVFileTypeQuickTimeMovie
                                               error: &movieError];
    NSDictionary *assetWriterInputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                              AVVideoCodecH264, AVVideoCodecKey,
                                              [NSNumber numberWithInt:FRAME_WIDTH], AVVideoWidthKey,
                                              [NSNumber numberWithInt:FRAME_HEIGHT], AVVideoHeightKey,
                                              nil];
    assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType: AVMediaTypeVideo
                                                          outputSettings:assetWriterInputSettings];
    assetWriterInput.expectsMediaDataInRealTime = YES;
    [assetWriter addInput:assetWriterInput];
   
    [assetWriterPixelBufferAdaptor release];
    assetWriterPixelBufferAdaptor =  [[AVAssetWriterInputPixelBufferAdaptor  alloc]
                                     initWithAssetWriterInput:assetWriterInput
                                     sourcePixelBufferAttributes:nil];
    [assetWriter startWriting];
   
    firstFrameWallClockTime = CFAbsoluteTimeGetCurrent();
    [assetWriter startSessionAtSourceTime: CMTimeMake(0, TIME_SCALE)];
   
    // start writing samples to it
    [assetWriterTimer release];
    assetWriterTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                        target:self
                                                      selector:@selector (writeSample:)
                                                      userInfo:nil
                                                       repeats:YES] ;
   
}

-(void) stopScreenRecording
{   [assetWriterTimer invalidate];
    assetWriterTimer = nil;
   
    [assetWriter finishWriting];
    NSLog (@”finished writing”);
}

As you can see startScreenRecording is calls writeSample.

-(void) writeSample: (NSTimer*) _timer
{   if (assetWriterInput.readyForMoreMediaData)
    {
        CVReturn cvErr = kCVReturnSuccess;
       
        // get screenshot image!
        CGImageRef image = (CGImageRef) [[self createARGBImageFromRGBAImage:[self screenshot]] CGImage];
       
        // prepare the pixel buffer
        CVPixelBufferRef pixelBuffer = NULL;
        CFDataRef imageData= CGDataProviderCopyData(CGImageGetDataProvider(image));
        cvErr = CVPixelBufferCreateWithBytes(kCFAllocatorDefault,
                                             FRAME_WIDTH,
                                             FRAME_HEIGHT,
                                             kCVPixelFormatType_32ARGB,
                                             (void*)CFDataGetBytePtr(imageData),
                                             CGImageGetBytesPerRow(image),
                                             NULL,
                                             NULL,
                                             NULL,
                                             &pixelBuffer);
       
        // calculate the time
        CFAbsoluteTime thisFrameWallClockTime = CFAbsoluteTimeGetCurrent();
        CFTimeInterval elapsedTime = thisFrameWallClockTime - firstFrameWallClockTime;
        //NSLog (@”elapsedTime: %f”, elapsedTime);
        CMTime presentationTime =  CMTimeMake (elapsedTime * TIME_SCALE, TIME_SCALE);
       
        // write the sample
        BOOL appended = [assetWriterPixelBufferAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:presentationTime];
   
        if (appended)
        {   NSLog (@”appended sample at time %lf”, CMTimeGetSeconds(presentationTime));
        } else
        {   NSLog (@”failed to append”);
            [self stopScreenRecording];
        }
    }
}

And the code I used to take screenshot:

- (UIImage*)screenshot
{   return [AWScreenshot takeAsImage];
}

Notice how I called [[self createARGBImageFromRGBAImage: [self screenshot]], it’s because my UIImage is a RGBAImage, while the CVPixelBuffer’s format type is kCVPixelFormatType_32ARGB, so I had to fix thing so they match or else, my video would come up in weird tints.

I found the Googled for the createARGBImageFromRGBAImage code, and here it is:

-(UIImage *) createARGBImageFromRGBAImage: (UIImage*)image
{   CGSize dimensions = [image size];
   
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * dimensions.width;
    NSUInteger bitsPerComponent = 8;
   
    unsigned char *rgba = malloc(bytesPerPixel * dimensions.width * dimensions.height);
    unsigned char *argb = malloc(bytesPerPixel * dimensions.width * dimensions.height);
   
    CGColorSpaceRef colorSpace = NULL;
    CGContextRef context = NULL;
   
    colorSpace = CGColorSpaceCreateDeviceRGB();
    context = CGBitmapContextCreate(rgba, dimensions.width, dimensions.height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault); // kCGBitmapByteOrder32Big
    CGContextDrawImage(context, CGRectMake(0, 0, dimensions.width, dimensions.height), [image CGImage]);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
   
    for (int x = 0; x < dimensions.width; x++) {
        for (int y = 0; y < dimensions.height; y++) {
            NSUInteger offset = ((dimensions.width * y) + x) * bytesPerPixel;
            argb[offset + 0] = rgba[offset + 3];
            argb[offset + 1] = rgba[offset + 0];
            argb[offset + 2] = rgba[offset + 1];
            argb[offset + 3] = rgba[offset + 2];
        }
    }
   
    colorSpace = CGColorSpaceCreateDeviceRGB();
    context = CGBitmapContextCreate(argb, dimensions.width, dimensions.height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrderDefault); // kCGBitmapByteOrder32Big
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    image = [UIImage imageWithCGImage: imageRef];
    CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
   
    free(rgba);
    free(argb);
   
    return image;
}

And there we go, I managed to record the screen of my Cocos2d app and then save it as a video file.

My next problem is, how do I add audio to my video?

Filed under capture video iphone app development cocos2d tutorial video iphone app

8 notes

Mini Tutorial: How to add Facebook to your iOS Cocos2d game

So you want to add Facebook integration to your iOS Cocos2d game (allow players to upload screenshots, videos or post stuff to their wall, like how awesome your game is). First off, hop to the Facebook Developers website and check out the Mobile part, there should be a Getting Started page, this page:

Getting Started Mobile Apps

https://developers.facebook.com/docs/guides/mobile/

Follow the steps. Once you’re done with that, you pretty much already know how to post the the player’s Facebook wall.

Next question, how to upload a photo or a video. For videos, just check out a how-to blog post by Christine Abernathy. Link:

How-To: Use the Graph API to Upload a Video (iOS)

https://developers.facebook.com/blog/post/532/

Just follow that tutorial.

For photos, just replace the video code to:

UIImage *img = [UIImage imageWithContentsOfFile: @”img.jpg”];
   
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: img, @”picture”, nil];
   
[delegate.facebook requestWithGraphPath:@”me/photos”
                                  andParams:params
                              andHttpMethod:@”POST”
                                andDelegate:self];

But, but, but the samples are not for a Cocos2d project.

For a Cocos2d project it’s more or less the same.

So your AppDelegate.h will look something like this:

#import <UIKit/UIKit.h>
#import “FBConnect.h”

@interface AppDelegate : NSObject <UIApplicationDelegate, FBSessionDelegate, FBRequestDelegate>
{    UIWindow *window;
   
    Facebook *facebook;
}

@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) Facebook *facebook;
@property (nonatomic, retain) NSString *appId;

@end

Just take note of the Facebook related stuff. I also added a NSString appId, which will store our app’s id.

Somewhere in AppDelegate.m applicationDidFinishLaunching (before you run your game scene):

facebook = [[Facebook alloc] initWithAppId: @”<APPID>”];
   
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@”FBAccessTokenKey”]
        && [defaults objectForKey:@”FBExpirationDateKey”])
{   facebook.accessToken = [defaults objectForKey:@”FBAccessTokenKey”];
        facebook.expirationDate = [defaults objectForKey:@”FBExpirationDateKey”];
}

And then as mentioned in the previous examples, add this to code as well:

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{   return [facebook handleOpenURL:url];
}

When I ran my app on my device I encountered this error:

sgx error: background gpu access not permitted

So I Googled and found this link:

http://dougdiego.com/2010/10/01/sgx-error-background-gpu-access-not-permitted/

And it said add these lines of codes to the AppDelegate code:

- (void)applicationDidEnterBackground:(UIApplication *)application
{   [[CCDirector sharedDirector] stopAnimation];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{   [[CCDirector sharedDirector] startAnimation];
}

- (void)applicationWillResignActive:(UIApplication *)application
{   [[CCDirector sharedDirector] pause];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{  [[CCDirector sharedDirector] resume];
}

Now in your game scene, or wherever in your game that needs some Facebook thingamajigie, like when the player clicks on an upload screenshot to Facebook button: (These codes are based on the upload video tutorial)

-(void) uploadToFacebookTapped: (id) sender

{  AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (![delegate.facebook isSessionValid])
    {  
        NSArray* permissions =  [[NSArray arrayWithObjects:
                                  @”publish_stream”, @”user_photos”, nil] retain];
       
        [delegate.facebook authorize:permissions delegate: self];
    }   else
    {   [self uploadScreenshot];
    }

}

- (void)fbDidLogin
{   [self uploadScreenshot];
}

-(void)fbDidNotLogin:(BOOL)cancelled
{    NSLog(@”fbDidNotLogin”);
}

-(void) uploadScreenshot
{   AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent: @”screenshot.png”];
   
    UIImage *img = [UIImage imageWithContentsOfFile: path];
   
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   img, @”picture”,
                                   nil];
   
    [delegate.facebook requestWithGraphPath:@”me/photos”
                                  andParams:params
                              andHttpMethod:@”POST”
                                andDelegate:self];
}

So what happens is, if your player is not logged into Facebook and is using the Facebook function for your app for the first time (for that session), it will redirect the player to the Facebook app, or a web browser to allow the player to login and authorize your app. Once that is done, the fbLogin function will be called. And then uploadScreenshot.

And the call back code:

- (void)request:(FBRequest *)request didLoad:(id)result
{    if ([result isKindOfClass:[NSArray class]])
    {   result = [result objectAtIndex:0];
    }
   
    NSLog(@”Result of API call: %@”, result);
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{   NSLog(@”Failed with error: %@”, [error localizedDescription]);
}

After the screenshot has been upload, request didLoad will be called, if there is some kind of error along the way, request didFailWithError will be called.

And that’s it :)

Filed under facebook ios cocos2d graph api