From 2ff76eefa3a64c86e7bad538d4e7fa11da72b5c9 Mon Sep 17 00:00:00 2001 From: Ngo Duc Hiep Date: Mon, 21 May 2012 20:04:00 +0700 Subject: [PATCH 1/6] cocos2d 2.x support --- Example/Classes/GameConfig.h | 28 ----- Example/Classes/HelloWorldLayer.h | 23 ++++ Example/Classes/HelloWorldLayer.m | 131 ++++++++++++++++++++ Example/Classes/HelloWorldScene.h | 22 ---- Example/Classes/HelloWorldScene.m | 64 ---------- Example/Classes/RootViewController.h | 16 --- Example/Classes/RootViewController.m | 152 ------------------------ Example/Resources/fps_images-hd.png | Bin 0 -> 23443 bytes Example/Resources/fps_images-ipadhd.png | Bin 0 -> 23443 bytes Example/Resources/fps_images.png | Bin 6203 -> 6953 bytes 10 files changed, 154 insertions(+), 282 deletions(-) delete mode 100644 Example/Classes/GameConfig.h create mode 100644 Example/Classes/HelloWorldLayer.h create mode 100644 Example/Classes/HelloWorldLayer.m delete mode 100644 Example/Classes/HelloWorldScene.h delete mode 100644 Example/Classes/HelloWorldScene.m delete mode 100644 Example/Classes/RootViewController.h delete mode 100644 Example/Classes/RootViewController.m create mode 100644 Example/Resources/fps_images-hd.png create mode 100644 Example/Resources/fps_images-ipadhd.png diff --git a/Example/Classes/GameConfig.h b/Example/Classes/GameConfig.h deleted file mode 100644 index b41a513..0000000 --- a/Example/Classes/GameConfig.h +++ /dev/null @@ -1,28 +0,0 @@ -// -// GameConfig.h -// Example -// -// Created by Ngo Duc Hiep on 5/4/11. -// Copyright __MyCompanyName__ 2011. All rights reserved. -// - -#ifndef __GAME_CONFIG_H -#define __GAME_CONFIG_H - -// -// Supported Autorotations: -// None, -// UIViewController, -// CCDirector -// -#define kGameAutorotationNone 0 -#define kGameAutorotationCCDirector 1 -#define kGameAutorotationUIViewController 2 - -// -// Define here the type of autorotation that you want for your game -// -#define GAME_AUTOROTATION kGameAutorotationCCDirector - - -#endif // __GAME_CONFIG_H \ No newline at end of file diff --git a/Example/Classes/HelloWorldLayer.h b/Example/Classes/HelloWorldLayer.h new file mode 100644 index 0000000..ecac96e --- /dev/null +++ b/Example/Classes/HelloWorldLayer.h @@ -0,0 +1,23 @@ +// +// HelloWorldLayer.h +// CCBladev2 +// +// Created by sales on 5/20/12. +// Copyright __MyCompanyName__ 2012. All rights reserved. +// + + +#import + +// When you import this file, you import all the cocos2d classes +#import "cocos2d.h" + +// HelloWorldLayer +@interface HelloWorldLayer : CCLayer +{ +} + +// returns a CCScene that contains the HelloWorldLayer as the only child ++(CCScene *) scene; + +@end diff --git a/Example/Classes/HelloWorldLayer.m b/Example/Classes/HelloWorldLayer.m new file mode 100644 index 0000000..bf6ac72 --- /dev/null +++ b/Example/Classes/HelloWorldLayer.m @@ -0,0 +1,131 @@ +// +// HelloWorldLayer.m +// CCBladev2 +// +// Created by sales on 5/20/12. +// Copyright __MyCompanyName__ 2012. All rights reserved. +// + + +// Import the interfaces +#import "HelloWorldLayer.h" + +// Needed to obtain the Navigation Controller +#import "AppDelegate.h" + +#pragma mark - HelloWorldLayer + +// HelloWorldLayer implementation +@implementation HelloWorldLayer + +// Helper class method that creates a Scene with the HelloWorldLayer as the only child. ++(CCScene *) scene +{ + // 'scene' is an autorelease object. + CCScene *scene = [CCScene node]; + + // 'layer' is an autorelease object. + HelloWorldLayer *layer = [HelloWorldLayer node]; + + // add layer as a child to scene + [scene addChild: layer]; + + // return the scene + return scene; +} + +// on "init" you need to initialize your instance +-(id) init +{ + // always call "super" init + // Apple recommends to re-assign "self" with the "super's" return value + if( (self=[super init])) { + + // create and initialize a Label + CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello World" fontName:@"Marker Felt" fontSize:64]; + + // ask director the the window size + CGSize size = [[CCDirector sharedDirector] winSize]; + + // position the label on the center of the screen + label.position = ccp( size.width /2 , size.height/2 ); + + // add the label as a child to this Layer + [self addChild: label]; + + + + // + // Leaderboards and Achievements + // + + // Default font size will be 28 points. + [CCMenuItemFont setFontSize:28]; + + // Achievement Menu Item using blocks + CCMenuItem *itemAchievement = [CCMenuItemFont itemWithString:@"Achievements" block:^(id sender) { + + + GKAchievementViewController *achivementViewController = [[GKAchievementViewController alloc] init]; + achivementViewController.achievementDelegate = self; + + AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; + + [[app navController] presentModalViewController:achivementViewController animated:YES]; + + [achivementViewController release]; + } + ]; + + // Leaderboard Menu Item using blocks + CCMenuItem *itemLeaderboard = [CCMenuItemFont itemWithString:@"Leaderboard" block:^(id sender) { + + + GKLeaderboardViewController *leaderboardViewController = [[GKLeaderboardViewController alloc] init]; + leaderboardViewController.leaderboardDelegate = self; + + AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; + + [[app navController] presentModalViewController:leaderboardViewController animated:YES]; + + [leaderboardViewController release]; + } + ]; + + CCMenu *menu = [CCMenu menuWithItems:itemAchievement, itemLeaderboard, nil]; + + [menu alignItemsHorizontallyWithPadding:20]; + [menu setPosition:ccp( size.width/2, size.height/2 - 50)]; + + // Add the menu to the layer + [self addChild:menu]; + + } + return self; +} + +// on "dealloc" you need to release all your retained objects +- (void) dealloc +{ + // in case you have something to dealloc, do it in this method + // in this particular example nothing needs to be released. + // cocos2d will automatically release all the children (Label) + + // don't forget to call "super dealloc" + [super dealloc]; +} + +#pragma mark GameKit delegate + +-(void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController +{ + AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; + [[app navController] dismissModalViewControllerAnimated:YES]; +} + +-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController +{ + AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; + [[app navController] dismissModalViewControllerAnimated:YES]; +} +@end diff --git a/Example/Classes/HelloWorldScene.h b/Example/Classes/HelloWorldScene.h deleted file mode 100644 index 14d8b7e..0000000 --- a/Example/Classes/HelloWorldScene.h +++ /dev/null @@ -1,22 +0,0 @@ -// -// HelloWorldLayer.h -// Example -// -// Created by Ngo Duc Hiep on 5/4/11. -// Copyright __MyCompanyName__ 2011. All rights reserved. -// - - -// When you import this file, you import all the cocos2d classes -#import "cocos2d.h" - -// HelloWorld Layer -@interface HelloWorld : CCLayer -{ - -} - -// returns a Scene that contains the HelloWorld as the only child -+(id) scene; - -@end diff --git a/Example/Classes/HelloWorldScene.m b/Example/Classes/HelloWorldScene.m deleted file mode 100644 index a2ca2c1..0000000 --- a/Example/Classes/HelloWorldScene.m +++ /dev/null @@ -1,64 +0,0 @@ -// -// HelloWorldLayer.m -// Example -// -// Created by Ngo Duc Hiep on 5/4/11. -// Copyright __MyCompanyName__ 2011. All rights reserved. -// - -// Import the interfaces -#import "HelloWorldScene.h" -#import "TouchTrailLayer.h" - -// HelloWorld implementation -@implementation HelloWorld - -+(id) scene -{ - // 'scene' is an autorelease object. - CCScene *scene = [CCScene node]; - - // 'layer' is an autorelease object. - HelloWorld *layer = [HelloWorld node]; - - // add layer as a child to scene - [scene addChild: layer]; - - // return the scene - return scene; -} - -// on "init" you need to initialize your instance --(id) init -{ - // always call "super" init - // Apple recommends to re-assign "self" with the "super" return value - if( (self=[super init] )) { - // create and initialize a Label - - // ask director the the window size - CGSize size = [[CCDirector sharedDirector] winSize]; - - CCSprite *bg = [CCSprite spriteWithFile:@"Default.png"]; - bg.position = ccp( size.width /2 , size.height/2 ); - bg.rotation = 90; - [self addChild:bg]; - - TouchTrailLayer *layer = [TouchTrailLayer node]; - [self addChild:layer]; - } - - return self; -} - -// on "dealloc" you need to release all your retained objects -- (void) dealloc -{ - // in case you have something to dealloc, do it in this method - // in this particular example nothing needs to be released. - // cocos2d will automatically release all the children (Label) - - // don't forget to call "super dealloc" - [super dealloc]; -} -@end diff --git a/Example/Classes/RootViewController.h b/Example/Classes/RootViewController.h deleted file mode 100644 index cf84f38..0000000 --- a/Example/Classes/RootViewController.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// RootViewController.h -// Example -// -// Created by Ngo Duc Hiep on 5/4/11. -// Copyright __MyCompanyName__ 2011. All rights reserved. -// - -#import - - -@interface RootViewController : UIViewController { - -} - -@end diff --git a/Example/Classes/RootViewController.m b/Example/Classes/RootViewController.m deleted file mode 100644 index f15fd14..0000000 --- a/Example/Classes/RootViewController.m +++ /dev/null @@ -1,152 +0,0 @@ -// -// RootViewController.m -// Example -// -// Created by Ngo Duc Hiep on 5/4/11. -// Copyright __MyCompanyName__ 2011. All rights reserved. -// - -// -// RootViewController + iAd -// If you want to support iAd, use this class as the controller of your iAd -// - -#import "cocos2d.h" - -#import "RootViewController.h" -#import "GameConfig.h" - -@implementation RootViewController - -/* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { - // Custom initialization - } - return self; - } - */ - -/* - // Implement loadView to create a view hierarchy programmatically, without using a nib. - - (void)loadView { - } - */ - -/* - // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - - (void)viewDidLoad { - [super viewDidLoad]; - } - */ - - -// Override to allow orientations other than the default portrait orientation. -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - - // - // There are 2 ways to support auto-rotation: - // - The OpenGL / cocos2d way - // - Faster, but doesn't rotate the UIKit objects - // - The ViewController way - // - A bit slower, but the UiKit objects are placed in the right place - // - -#if GAME_AUTOROTATION==kGameAutorotationNone - // - // EAGLView won't be autorotated. - // Since this method should return YES in at least 1 orientation, - // we return YES only in the Portrait orientation - // - return ( interfaceOrientation == UIInterfaceOrientationPortrait ); - -#elif GAME_AUTOROTATION==kGameAutorotationCCDirector - // - // EAGLView will be rotated by cocos2d - // - // Sample: Autorotate only in landscape mode - // - if( interfaceOrientation == UIInterfaceOrientationLandscapeLeft ) { - [[CCDirector sharedDirector] setDeviceOrientation: kCCDeviceOrientationLandscapeRight]; - } else if( interfaceOrientation == UIInterfaceOrientationLandscapeRight) { - [[CCDirector sharedDirector] setDeviceOrientation: kCCDeviceOrientationLandscapeLeft]; - } - - // Since this method should return YES in at least 1 orientation, - // we return YES only in the Portrait orientation - return ( interfaceOrientation == UIInterfaceOrientationPortrait ); - -#elif GAME_AUTOROTATION == kGameAutorotationUIViewController - // - // EAGLView will be rotated by the UIViewController - // - // Sample: Autorotate only in landscpe mode - // - // return YES for the supported orientations - - return ( UIInterfaceOrientationIsLandscape( interfaceOrientation ) ); - -#else -#error Unknown value in GAME_AUTOROTATION - -#endif // GAME_AUTOROTATION - - - // Shold not happen - return NO; -} - -// -// This callback only will be called when GAME_AUTOROTATION == kGameAutorotationUIViewController -// -#if GAME_AUTOROTATION == kGameAutorotationUIViewController --(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration -{ - // - // Assuming that the main window has the size of the screen - // BUG: This won't work if the EAGLView is not fullscreen - /// - CGRect screenRect = [[UIScreen mainScreen] bounds]; - CGRect rect; - - if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) - rect = screenRect; - - else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) - rect.size = CGSizeMake( screenRect.size.height, screenRect.size.width ); - - CCDirector *director = [CCDirector sharedDirector]; - EAGLView *glView = [director openGLView]; - float contentScaleFactor = [director contentScaleFactor]; - - if( contentScaleFactor != 1 ) { - rect.size.width *= contentScaleFactor; - rect.size.height *= contentScaleFactor; - } - glView.frame = rect; -} -#endif // GAME_AUTOROTATION == kGameAutorotationUIViewController - - -- (void)didReceiveMemoryWarning { - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; - - // Release any cached data, images, etc that aren't in use. -} - -- (void)viewDidUnload { - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end - diff --git a/Example/Resources/fps_images-hd.png b/Example/Resources/fps_images-hd.png new file mode 100644 index 0000000000000000000000000000000000000000..54a299ed918917d64a4cab5bce0fba2c1035354c GIT binary patch literal 23443 zcmXtg1z1&G*X^cLP^6I(1f;u5T11d;knZkAr5h>f7LgX|mhO`728ly=+{OF-SD&MJ z;Otm?#+YM_W#|Wa=_lyK=nw=wc`GBK1VQlNOGp$I8T@J8GTZ_|=;9XQ;ve3Mi&NM; z+L>Bdn?R8JY`U_WM%)Fy@Y00|wwl=VVMUVlC+H23K&77xSA%lRYIHH|_A?Rwj zc+b*gR69OTpv$C(tY*>Gn!O1N(F#}9;XNRqFR1eIgzfL&Ox-kYrET2~c?@IwKf|Gk z-ORCs_>=+#`KQUF6=XVkoBZMNWR?*ro^JO4F+=KvphE-?cVFjnkz2SjJ8;SN6U@{& z-761Y>Oat^Llm*l@=Kg847eC2sE1jl2N&uggvymGjnScaa91AQVlSbePoTZix57x! zbYa{)0W_WSq7W5|goBdlq^aRW8=#M>pOhHkTmL{=#iB2n5nD^){57lDrQ!XXkRaD6 zjTmgvkC1<|7~=p$!3z(GlRY0qppZkzVjXK)F4VUVtd)U-TKf|QlirPS;MOLL5W5{8 zF0WFq{;{qQGaz{V)D&&~Wm-}y)pMCG1i2wh2qL~3ZM)|ciP_p*U)eO>vWA^@=G*O{a1$BO{{C-!VerPcFW*HWdZ zt$su?HrtCWs{8Ihzq_c{qpO@1I*fQ>M;f8EA6~xi_NY^em7wfRSjE}#V?QEKyhDp~ zdjb^)DYVL0qg3@j|&KjYq^RRWq^YQlk(Oe zsBxQ6=SMt&To)rn_*4ve-Twu8Heuo$ zB9&JDX~e2>1mdh`DJxHZx3Td)*;>ZY`Lt_Kfc%j#;}2nD5E|l}9@OUsl>8yj45OxB z4xthxMS$jA*#6MIjQgSR`;{loRfoGFe?^RjR58r~B^hPLD?M7Q=lXFn)L6Y= z*X7YEU&XM$#dvEaGbh88r<^A|_S7Oxj%GK;rgw22^_PD!MN(`{40epd*PGt<^%`9M z&X83(v>a-sym%a0E)$Ur#QaQlvE;0uii3q2e^Gyi@MmhhwaIe*z@i*n_?*)v<<(#+ zzIcBgQ|`n_iiMfQg*nTPb3NL^7c$ADk)$!JZIqp@oiC?um`{S9eCd`kq$9E-@**lA ztRZ4amivx0o|N39!aBuHl5F-3`Z({iv4eKjcZRjIFe-g!bDDcb@DDZ#8ztvqGtO7_jo=S-*LGY=?R7=-XV{TAG7kvo$Vv0%6l)yBCJVoQo#&R)PkG z7VL9*9eJJW&94XJtx`kPxDmMSzl*+XS@Af= zKaxlK2-gO;0oU}2_){f<6#_Y8GGaao7g8ir12PMyFrFAD+7nH3$2hxIf@6{^BaV49 z#*|UKKGbwPEs|^20U9~7$!AeP!>CJ7eeJ$q$?XhOqlPR?TZhz=TM#7^T>0R>rf2`j z{7><>va^Hp1>?a$gz?!lLmM@cx& z&#BS&L)SZ|JA^{loZz>tQ#jJrQ&bY2jY>D>bLt2-cZT{i+yphbG-JGZ1Ha)U{Sw*u zLLv5ng-~Im!1g`q^W%WjKn2O>oX8x-ikezk!LOU?Y6<7O3j#jk*XBVAQZ8K_XbMUU z9!?oNt4T~Q77x!j%rNoAr^Tn`Dm}4C{LL`MT0>W(V9LM{_hj8;)25FkF1YVv zo$AWzWDd_dP;NB$w^Hc`EPOeZ9}Mo=gxc=4GEFjCe>s*+@Bdv2qc~cJO&2 zn%Iz}zGc&Qp;p>Wp)(`eE8h#{ToSfx>1<~`U)Iv{3(ZD}JCaO>-+m+2-)=T_KgF%e zUW*><&zp@l+NJN_UTYt=vxnN}+Xt7D{c6rocV#>n#`s%YikWh4vV^jmVA~P7>7;t3 z(#>U{csS6~!2 z?ssk3I^i^RImN7->Cpu1+9Rp4rCE4U`>Ouz()E0wzzzLCZeG_j+P&s zzu)&2CapHhmmga{4!3J!!?4hTGw$Ob#)DVJqz9xYsHCVOqtnUBNuCfl9UBkDtrYw! zcs|_ctM=fr>r}M0bhmo*Zdl`X`ViwPe7L35qwvHLR#aHV-%Zs`-ZTV)Wrn?or|8O#TZPZ;bqHrO+<$Zt4auINHR7CV25leo44MKAm6H<)6w#ws}er z`Ry`_$YmS0??|S?tlN}f&Tvw9k%)vRs%z$J4Y6W)0y^HG~LeZB6rlYg&D5V ziKTPS1v{kci{IAg-v@`H`U#G_RNT;iWT<&Ae5zz|s3(%GWB9XXI`l?i0v6sLxzjAj~Ev~)hr{3Y&_pE|-A9c)6wnFe(bbV`Zi}Yei9d!i`|Dx_+%$+ju zEFBh+*C%y7Sez_}AKmgCn<_+I)zsfNe6HCRvBB{x;&n6gj8m=Md7l&zEFyDF~ zElGQ2`}$#cj}X0hHPkF4C)eQ*hrnB-{N@du?7Md!Fu}XiaaKaiA4Nst1_qS$3=G-h zJKpSsg(_jce{;^e&e=fzLSE-t-@gZ43}xP*(r%x5>NI;3-JI_`&8n5@H9f_{3k(QA z?C9!pB^i45>=_}SBQ=!u;|D4i7uS!HlKrucvx5ba?CfkAdHEo%k|4FB&PWoT58B${ zV`ECcfB$w)=DR-K`BGlaN=;2oK~0UQRf4~!F$=l~f$raVB-2CjBvCY0E_Y>eU-+ob2Xi zG7uhO@83TO3lA5vWe^m60WR`ss6@JB;O^Nq)}_c{D}s!y?4PCkbDn}01zFk8S|w7B zj_hLM;-mBP5&!;Ks;H~y78hfBHZ{NV&P+>-`0;}-FF&7>o<2-F&cwuoj+r@V)ciF0 z>FxpFg+z#ygoLxkR7MYj`f_OF{=wN_Wx=@#5BvB~5^n25KA2Y@N_y-?#_38w*9MMx z3Vz!3U@DK((kN%7G?_=oj-5q{l&UJ;qR)kH&xT`-51+7DOiD_a)7H?Z?-uj54hTd< zM9g!~KWAl8M34y)2V;?b?lt~5Qbx<`h2VF8l37=Maj+2n?HggVIR&DDfr0z-ClveR z^|#ae=U6R;#l;+*W&iKW_JXmBey)UUF{`}y;ypf8Pl8eK>W!<&;uFW8%+3G^Xtd3h{IG%6+$_h9XvmU(zp8dN^Hx zwnyaEt5@H6?8wB#!~{1pGg6!srm_o0R6RDp^7VN-a+|t2Z_8(#;i9;)ADJHds;@UO z=r{1=&?>8$L% z4hRa$$;$HYemXijn$8Y^$9uFMr|`$Lvaa*)Pap=Npu2qm<4r^a<{KI(Z*H5}fYVdw z=&iq+e&jxkqHXuHA|_wg#tOiVniAw(o31CR-}bH!z4-D!MIf;iNn zp`pC)hgs^pal^Z1Ee92FPx0}CUcF0n?+_Po-D_?AgwUjR|C~nd5EYidpw6FeWEWq~ zvej6LENX6UUem*%ux_J1scaVS=XO%e<6iqURA}%d!di>%qlm4d! z1i?#p2W~PlG7uz}!in}Sk+ChDrFq(7Dn}}}O&nXO!{>fAoF!|*QlRl-QrnJ_mzPjM z_$n_;ve^x$xA=K*Xs9b&JlH$TNk#_Mn4PHkYLf($khOJfA)kTggRCt2WT`Gj><=M{ zwe8VdIu@2-iI;Drq>#b zl&@c-T`YRB{Aq88gRq58pMn$MGie2YWYQCe;(RYBhr4HYxZEc1#+5$f!&fh?t*xC- zrds}yJz4NP;;|xq6Y}D|sNpahTJC3Q3FtNcQ|qwCYBuyj{%Nsx4OSAfuGpJ5pXTcD z!#j14C;9#)bC|Ij_rzfNk#kw%s+DMU9>px!c2AaQJ6s)`NJvT=^u@oHdH)^>8c5;7 zKo5jh5IjPpr>7VEW3t@(snLih<@?dy#nReX{yS7GEGacL{F>)J8wu(ZN&QD%BzCoe zwoY5F`$K#ers>fnJf+IVeM!r^XMf`aci$!RTK@e(wsBY5cax!~oGuJsdvnlG;c;Sm zu(QDCMWpxRJ;TEU^XVvvh>-ty`qas=$ndUNXBb{u z(Gp1-6%`dy$ttJ^i2aF7?dtkIfyc+kSZlKlZe>|siwl?S?d?YkZc7eJbJpCq_ZKbF zAeq-4`8bK6jE#-iZw@45C34sC>by}>!igdm8M-^)o2f*_#9TKoR4N34gOWSi(`3X+ z%w|54g=NDx_BWY9h=(UhK78qt$d3L&BNTrVRds_V1eV2}uT1qI-ua@#pR zwn81<-Clps*L&j(sT=W z$abd2i3ejHUGAOF*vrndlvU7|N?KdC zIiI>vw#E-DZgiYVDmbpL+%2q>h8Ef?7Z2`rdpk0gef0ah%#8L*xh8g~AUlJhG`_~5 zOyBDr`G(sJ@8h=zH&c3EgGQZF@`QYC>ScP8T3T8K4z2+O8J>Mi1_D+Pi2cl(td{G4 z3){c{)<`D z{t`*@G-)FY00QfXg{trKLc;G51pV#>hw<2KW;qd2P`vj4g+@nr&(}He5iAX*3mDYQ zHT{t+R5_l{@$m4Vd;R(dZ3qJ8rcOrboQ)7u*og~tLimAxRZib*SFzeK|R$6LW zjgkVaa12k5P0Igwg|u=e!fLA2g*W#Y9|Z4Vx5$00z^~CAXI=D0N;f2>LR{#Bme%Zw zc~0e15|Z!=qi)AczsnUAohHw!cCX0DNcX*pZdSj0Z^7HccK4M)g8CQl73$$d9&Vk6 zvNY-(Uq!v(TTQ@7SP%U3N9^y^l$*Q4%h*4*ti?iQx;x(0WLcy=jG7*G=K+s zdSp1cxI8B0ot-(QqRE~>yxy1g1^6D|o`*g8J&vihw6%SLPFC83*-ZLyGhV&I4|n+Y z_qDvJi)2qM`W7gppJB;zGfS7F3A z0+lAF*BF|8X(SLg{BIlGEwN}pGcB+Y?e69xc*1g@T^tt|_hVNC(Y%>i;&-Xs6}HH> zkB9E}mX?JP7XC_4|?oxE-o&-4y%aZ4jTI=+yv?A85t3w)BQODP*Fl6BGw&4 zcXxMnk+BjI60#LCg=;~!b+4td86h7uUFbogAhXm;b#~aJ>+P1BNd>t&J3FVFym*41 zkRU_f_?&3)nRTYyQY-CO#B58zAy#g$PRLdWadA7GxazgX^C)1lqMB}lbv(O`9LKUD zQt7cZ%~}cvtt9h}8#6;M*xc!#H-uj_C@(JUac!JiukP0@ZTi5re^R)GKV~^hR~-&r zY@|$IM5osNQ@@iN9_kvpcVs2)NQbcQ8wFQ1UMI9<}Cdd zU(mI>jyL-2s`p(5Ob5QLs5S+xuNyOu9H!beuP7PgJb!)!YJ}@+WKn9ImC9k^wNBgh z^>yd063`__bERXyecN^@z1M%ZR@bAD*U%uuXVmZqX?Zluoh%2Unf0J{4Qp}rmBI0P z?`P!vN)K{DcUG{>wZeLyJFn<)(c9cej~oL!IwZ&KWjx|kQ7mhZlc-It}iHZ0iO}nYoXFx;rc-8@Hy2$9)LX*mU zb}{c1{qZ)C;|(1mh_dNw8qa!N(VgW?p^Jw)`UOXQLZ; z*MXL@ZYjdDxun2%?$~8_wSN{Lh)3|Z+cw9>I3vLvfssL3qEP{lhlj`Oy#4gw?ryeH zA%ATuh$5vz2{EzH>K^9{NFWuvOLZGYYV7n6>>iOEw#e;>3C~}E^N^G&b8~VU=^c_Y zGNSU|CBZ|&*V|NN3jsRei_D&pQtjH-IH8E3__WhzdVdZILO%UBfpM|qCsIR&fr{GN z6-mMddiyOXI?Qu4ctI-kogmgQzzTR>*rtj2kvZ1ASnG;h6O;sBfQHxk+hUv_QK)yr zG5Vb=z(!_PXJxB7|U7LTnJ-nbq6y0r~zD3k5W zJX{U?9XHdKC`e!4o(y}y`0)qqJ5i09_jkq%JkW=ZE=((lz`*ziEQ&t@3YN3L5F8v_ zqhq-kTwrrGYM{>P`1ki~`L!dQk@|jj6R(}To>x82gkbTF9`5gIop+Ri>9xw5uYXG8 z-544gmYekBgP#St z`lu}36&Oc*pfMi}3BZ=uqD8t2l?&W2y}}q6?DhQaToz%ZQ+c@rp*{z7TN&~mo!&xQ zx(kt>RAu$Q#?Q|@k0%aVI0SdYeMwCW-A zp+OQGhFBGL+9!#ZpQLi%=;*vqQdVXIzzNGFK8Z#DfO~tR`Q~74z7hkUar@8*OoAw% zHVRh_D7m@ueQwSrEiLK62ht}+2m!nwR@Kqan118W{|8iNepD1QvtCfC=e+>mK)U^Y zoD-i#Z_iZ_^pABSoneuOMs2tQ^s@WA8;oPdn`RkmF>v2qoF!soh@nuv)M>?-2YGLKlylH5kvsE*=x} zfNO#Z+25#J?7)~3jAE_ed;|N|X|Jn#<7n3kGJRKZvnMPc`40ZZi<*|Z$l&0opZu#m zVGq|+E%U2#$b>?metcF;(ltPJv*rHv3y;LV+H{b(0H5bIW&`}u(UD*-m59jF29Z9% z7V6o1tDWJfPo4l=N(=*Y<_gkZT@XQRY-}9jUU z)uFW)wFocmS;^_dr2u%C%j13)kJrgV_NRy}kWMzCn;=7iti#>4%i?YQ+G`xpQqxO& zRg2UpX=soYMD94T?XoSuHph!(40))>#}pj@ERrn~n2ck=bujaoRPW1-4_z3%5wd`s zr&9h^H$XaXY-~!pJ;ngcNISgUNYYQ+96MNQAtzwg@t4Z|B$n;pY4~gasoDFA9aj0F zSLR$NmhpBC%PcI%{=Yy$Y7SsC>RKLG5ZQRWu)1oP%-i z0bd#5Y|xYVsSw$dBT}OQRRu_?Is~D7rPsq>zJC4s`SWLZ4Mu!M-FnqQdVPPVsd}DyYL8$#{F*m zQCU>fU%i3zoSo9G6`fV#So0MQnhHIhS(_3rQd}=JFU!l=5b34OP1Bl70ku1)z&Imq zvC~8uYWZ`2fU#ih;3P zZuPa-xN-I6fjzj+bXlUK$HAc7pdES9MtOI#q#dvvbcFufn2t_P0=FgE*>GrRXgXJ8 zDJjI>mn*^Y3-iX*OsT%Bn4qLuT3J$AF(Po?E;%wEf}uF5gR~kf&1|I#5iP6(|!8~g9Wud z%v%*jlsV}nY_yy&Ti0bP?hw3vIMj>$gqWIc@4I|@UpU+&S=I04S)~;@J*@#Ic~El` zy+G%BN=h0Dn9hKJfJ57+$0-I>WiWnF$*@pr04gwA_+r6LKR6eyLL&l&+&jjtXbF_# zd18COu3p~Xz&teZ#oAoIAU_c^F?j_O>Rx65F>2QK&BDS0P&vp`T~{Yt=?Augofr^c zk@uespYKj#PfScShDQscy@-sCc59&7aOBJIy|#$D=T3bBrXIJtW>3c<0WYlm(8lB6 zK5jm)-JbvcX*L!J?)Il3EcQs~pZF?tKGvaQi>Fz+a1?p0LXp*`y4=W1@yArSP(mvnTfkF2(x6XC$* zv0ID)JY+`r5rAZZv-5rrcb}b_T=%sKWLKjE4z^=tw|{EHax@BV%=q42JDf1Y_44Np z)cr|7%-&TYoiYYA9Sa@3lp6c6Q!ZPPdm11%*P7>%`=nIv51dup!{1rfcjnmtXOM z_Cp%r4AKP9p^<56FBX~G@P<}aRxZJ+xWmwq5-$57ilT6j8_XBHBUIVhqvnTzg*@_| zo1G2Im5yG$fwgplZW%E-skV4AS7Udfr6{0GrdxtYNK8CSIWca`z5@E^pY#1W2S5~J zosf`|!;Xmb<>cgo$I<{d)9JS46AWv4$f$ApXtCyw$2#H~8d5}h2B=(*{bG%Z9A$Tp zzRE}H-_@1d(b3VpftNe~Z|ZMFg~_}c#Z@7$t#nn1jJ~1_PN-2=LASG8IpZuJZdsPb zl?QfVj4$d|{5q2u0w>|&wp$z!600f$CuO3;3|vk&%UHR-J;{978)Fi%Ul!Fn$ff1Q zCS>(5%G}?pnA^8?kOxQr0OVCQUS4)Y?Xo!%gpYvQTd;-7nF~PZl!>>IXKw|Q``T+E z_Go8MfFgng-ya7rE{43=0BhdGcPp9*8y3D9u%HRyxQ+YzwcMy1t7d;|YfAu+>>y`& z$@}EJp7zPsu$zD_C5Qq|vta;lnxf(_jNgMfV0Kmuuxo9(*N0$yPgm^7=wr}l5Y;cC z)n8sk8@{gJD`!ZaPH$WyJzm6HT&Vc&or3%=Jv|b%fh1Vt$&i42S&|E`vD4-N+=y#K zT#>7lm6ZW^s>86*#q!lwX7@KXBloS$p|KSJHG_+b85?hp`{$c_W%F@d8%X)nvAUzl zyQ^*H%0Xr&@g^lEt^x?q^$7vx@UODM5xkrZ`fQ7c9ZAX>Y$I=;c>iK z@7ga={~w1LfGalX>pc)MihIGJ@bT>51h3O(#7Ec28Xwn-v>RDH7cPX>)UO>GrL_7c zubhL-8qgQ}Iu15{^n1LrNeJw^QgU=AA`j$0&?jir*plWcy#`_WxNL1X!cmXoCy>Mf zf`i2iRdNao(SRxj5S0BjNvH(SA*g{kbYQ6&mNPOvy?xBDP8kv&{za?g;BOPe6FzxB z0aPxKi&=E&K+<6)jx3+s2NItx2Qxc6d%fIvshFG`CMf5%DrDR|)rEzbC&G~|2WY(==Kv4&wr4ErZZFCO8DeF!)QYmFb`2^tMrLRK#aTI} zm-PPpNuLx{wdQ$f%5-Tsq>C2nd`@!HSMF$u63IzM>1bK}y-_SQ+kUQdCeC*{1EYiyjmCx?mQ@q!u5-S! z;huJ8M4M2FkO`E4wH)OL&65_DK+YyZihkOvG3GQAsf5A6nq8KnjvqNQeos~Ay9ec1y zhu+;hT~U5AD;xDGFAm{O^I9hKTxK>T&E36NZqD>OIY&{vj7`T#5WqB|{s=5e19mgj zT13Q}sFJb*E6*s?7Ce|WOe`rk+xGHU!X-+8MfHDP05d^q+RdbO%IvF+%Ox}zMin{5 zh;Z+NHM!a!)GRN@izy;F4-VIs=B`14OLuV;{m2JXcewi1Uod)7+r;j-tM5^STAho> z)ZkE&W6(u=QC~6nS7J3#nEeS=?V*P(A!29+GW_QH9&(1l;I@;iT_7!uH=XlD2Yn=> z&n}VKeLCP!O`192Ymu{h4Z1f6(5dkxA%6;FH!goxsA6C#5**<#Ywhkgztm(HKOHyR z2FvqpDqK-cahMw90$HM6ZxdaY_jM~r2T6Qnh9?qalxuiDz?(w4vo7ivW**%s6haiP z(h5Naj8&{Y+o)PINbw>?)A5MS+0a)avK)vI!ew*HG9g0{=fS8O&!-DhO=N81!eqh? zXhY&z#F&&B6F8M@VC9DY=F8c^Yna@UOq8-jVg6?0G-6uWv6ditM!fG}d@=2kOgCETvB z=YMBlke&VO*RguK{KYG(;(utJrY@_#-(SSH;E1C7cZ7t53<8Mr8(vgVF*fJ>cT-&( zn|)f$W_%tavnK?vjPfKP!l?!~STevoZ-JPDQ>Dc;X<2nn!ecuPU^)pHsQhd#EUtL` zcQFr&R}36*%i(W8^=jTBN4zLJ5K22AD3zZYW3ibo~VF}{xB9y~5psw(isNlrL#%|$w`Epe=R)*TOb!OvN zHeDZb>-VYMLU3#ms8-DVUBG4%S5`Zm9FVQ+rAyRkU(wRO6Biek92^{Uc5$gHsjt^k zS5rH$)GK?)U^6Es3>@@qH>W*$d%O*p-Srs&Rhz)EjKSYHO?q|>-dDfsii?Z0YilnB zaz|^E*tjJkjtp^Aj9OMt+Wl_k&v+Mg2WL(@#p!Ih{HY-$Wo2cB3<0;O?-nV|0FI}} z#ySwSeuQEN4&G9a1jSoWJ!|dB%F3#djwaLf+8&{tHD(`;`k<;R*#d?U(>k3+%#Y0e za;CKH2OnPN*gRXoS7U4Vs2aJzc{-4B79oREpnr6I&jG=Go$;p~Zz`C%z z2CNIt;36J6N7z2M#X63Ck7#QV@t*?nut~|!pE*K4z{#M2MiD+!NDmhhTHQIYl#}dm z59IMhGhl5Hic>4f52T=_4MrBV;!JUaA`IQt#m6$gP5A;|M*Gp`FiVow`zYEXL&FH$ zgNJp~y|?E`tipnVxB4fWgI0n-i?FHC;9u6))_&J=HmPkIDq)Cx__VUwkdR*n@lwBy zQ0fkfF!MMCqT1(MWhEuC;Z&YsLL3|=#APy5CW*Q=@`p9QTLtW$MeQCah6DX0h5rMO z&FpV}wHSa;dUHn2g-sCSv%XR^qKra8&}FV1P36SY)cC#K52+OAK^$^D!tSD(W7&)gGBP5F_xlX+)SiL7XoYLSG2sNS3o+Xxx5*sG(XaK|yabDXAb;8GC_0K#<%6B#Jr_)$55^ zVfjtvKDu^e=s7R|Je&a-=Q1KD9rYp`U|C;8*3XK<=mf}+KubH-%a_fwKw{Z{Vr*if z3SS$ZU5W1B@x~*F?ZngV!-o&;0RAt?i~9Ho2>}9FDpcYaxxFFnlPn?A3d9aXjT)ds z#2hd--e2z`L;ZwgPfU*pmb2#`Pve^nF6e0WNRvZW$UdCvf!YI-j4#7tb z5QtG|&uP91wRvsyB}@WihcfgXL5A{DdY$0UefPtBqqJkVyKs+_QlwOF^5KX$wnP3^ zGmyGV)QW`ub=bVCf6#Pua<;Vmw+6_2yx5u<6Em~5k!o;4$b`a$z$sYasTAGwU_Fr`uO( zy$*Y61SfNGzHihWMcM*p1~#wFy#IMJrk(lIxn941>j{L5u<4f!kDiQIalK!GDTA}D zzP>($51Ey(K9p2v)Y@8t)qf5dn@sRLR+=o9_eiV)&e4#7*}*XiVZzdd<=3gHl~vK4 zSH*jpxE@OPD4JQ*XelvZ4tUhj3sfJcMVe)xl{~VHgEVoy+_v+)SAg@95Y-Nyb=jRn z(yw>k@k2*PKSwY}6d}$KLN8awm2}w%Q%m_CIClBMq7>eK?uTM-SD99oY}@hw**JFk zlUP!LG|>Sp1hM6A`v0?Wd8{W=`5BprM2Q_C8U!!($aF8tOac@Cy_oOeStNJt*-fb;Vl!P*}$SWH}zETDt_ zo*ufAl9GIjlaT*Tm2j&_ zAYB!e4xgow5m7T!(?m9bYh0<3w;>Cv6qOCl9BgbAkBeHUTWy_uUsTroDwL^IlS(gMYDcyn{}S2y}OVAC>CDA?GJXrVPCm_*id z{?Kp2H&88ykkB3ayNj+asd^wgGJ%wz0IvjKYuNxVlL6(F*jPo*kFEYzph(i9T_f`D zjfp4chSAa}WayYxIVy|#9d!~+*4EadL#dGW3qnGTW}ul+y?xl|PqHGq@P7H0!Wu`yu1K1 zK1X9d|G=nIv#zX>KYk_!o1kv+>1K|gtCJqP^5i3&_ox3{#5*Y?F9UUQRR)8XUiHes7O#=q{ zW8W3bM zO&X3uCU;cs(Z?Y+o$d)dpNrlngY{uyVSdmL|dC{Ad5d-g-N^n5H zshzd;d{k7R7bBFyKu^C|_T$H;I5V26NR#Z}X@UFDL-z}U z&Mz-7Pe7ONAr$uJ^{>`$gNKJ-B_uAF)THqD`(SNd9MDL013DWrB*OMP8=4+4J*fb4 z=98Bm)QpUB9kso$37p=V8c+k0bnqSk7D80WuIVgMvtZof70z1;+UU^f+?<%hLwhvs z)Ry1B<4eIW!|m~bL-bUZr9SUTwg<;TbNH@YdTwsl%jpWEI**5yVDe(Xwh49Bp3f{* zb8~Z-dV=Uc&SlCkNywoS2kTq|Uuwf0+!A=z0(YB&yFRMK33UQzC5qqu)fU_yk}89G zskM;fx(v5J6($)I^CX<4Vtho2A{G=F82C6j6qzgZ#=-pnNj+#$Ct3SAAwWfdH{IHxs|`eq#}t+G_HO*VK!nf=^ub8b zUIGUW%A=lrK(Cz9QB_gF6*3>8fJA}$7>|f3dH(NTTv1f>zBe)YBEV3z1Dta|0Yn(% zWXiSBqQMUrS4ii7WfoY-Q^0DjAb^RAjZF}j)DK#17yR-Ie|po~H_+$zG|DbEHcW2h z#vls!TpQs3AUSB<4nmlq!ga+^iqiwT7@PXLL^e)tjy^QVT^11n4)Br)cn3AikcHl# zZ~>B%l7n8rd6WYr0ejF^_GYV!M1cik&IP8y4P6mM&v*$NS`*H!& zhpv&qo&hS&XEFG!WK_Vd$hA&72S6le%HXDFkVyVO19#EH&l;@~K1_XXc5l__D9N8a zIReGfpNl{CbdiO?X#nfef%o0nl=uwE!mrB8eL#5*dNk=h;LTczpr&U!O|S#Us1>l9 zTz7YLKu}I@Zl`0NV23e#Y+!yodZ3ut@h&je4h-Ln@)lq%_ypOBRJNyYSrWizf#3%*1b_8uNk;tW6d?OZ(Zs<)fCMfs zDlQi6+0y~=Nldjv=EB}NQ`pB{3$(K70Xleu6B#(dQ%@gN;56T&4+#wgTDO7nd0q!| zN^!Hgnv&A7$N&}(rp;FAqZi6=$g;|{3!+GH(gfmSTLck@M&L&tLQF36{+r2X@X9|& z&2t{rNMs;a(S@;p)=$KTza*IW`_~w}5T7*&ahycGkn^np;8YmM2}AI}RN4vLkP#6# ziDn^apgco_{J;<^K<2&-7y3W1b)CMC|=8FMkSsy*}R;pag6p z9XtD1OJGv~BWr$hbMud!97AmX=L5T>vNX@}&ZdQ#mZ!d=el(|vlg(cPs!HsC02Ims zsvSttVg@FrJ6fYGuGj{@V3*d!K5jtDk}m7e*r zKW+z6;DTPDCn3Urprxf%Xav}59RdSwU}IyW6l8{)REl@d|A2h4GagLak(!dSH!u{+ z#EAfzrpr$mvl5CPQcyC(4$-p{DnH7&y8@T;f6fGli_5ORX`TaRx9H8^5x5eboK{{ z$-jRw-8YlXsDbaKJOu9;7?dTfBqclD2EH-LyN=HDxjH%?e{Q+mU;#7^F3?MA(gi(^ zU-~oPN}j=}%j~O8C0{DafXZP8fxQX6_ooFSlJXgX$pv!eDN>;Gc7PF+1Kd`%dDZOj z=#ekN@j++|pfaL>eO3tQuTogxJw4wlz(M@mo=-Ym=k756_%sH@)b>V zQ3QByZl2@dtP(J4h+1$GtEi}a1WsX&GMzd@Mf!vsA`VkT;4ATaTG_P*27GO>Ev1Gd zsG5kh(q<2`2KxpIK}`1bVTI*9#l@u-*S|a^iTBBgcI6 zyBh92`paZFDZN=SzmRHt^Z0@q^Oux_c@(OnF&Z&-Fo` zC6&0vAe*^rBEaBa;h@jbjG%;y)EOlK!F0gue8vox0&LHoXaA7SZ;2p~E>wlGKG7k7Psz zP_x-zu!5GR)9B8&45o;yOt3BI+Y{t=v*oEK6az#$Ft_vN(Bq;%3Nl|M!|~sezH{y~ zW(V6uQuu)eatQN#xCuUoE!o-H*xY?(MK2*EY_a}l_K1=jP5KihrKF`1AW+C3t>p=X zkzIalVX7#!c&Fdad%O@*-pR@eUoAb{Elq(EVjV~G9;dsjYZZ9yFth0B{qvt-fH5F( zc6L@=t*8q6lVmd*aFO#5v`nUGk^9<|J9fbEECXXJ#(SD^%P!Fbh!9xQkRxC4eGM)W z%l?Rg9=f~`DD${k>;4NSq!)P_6B9EErqr0Ag*uzXM$Lk$U8gpd_m*ziFX;XV4GAFB z%vb}~W8H`=bx;t&A2{=oID1H6|J54xC6ZHzPu^Qza_{lPTQ7D)w2^-D{Q3g+ zFb#}vf52?`j@}RWg|Q_etmlh30uJNpPw$J(#4%fG5@ZK~I*FW2+A0S6ac2h!V$Ry& zCkmYzVyG9~VT*RXvjqj@4GetW!wFc(q~?e!BzivNSfr>1DdpItKDP^1%^j79;er6_ z1m_9@TP`~Oj*NWV0Y>jrAd4qeb{UI`LSQQXkp>dD7?{Y;P-kI2T4Sa?dH4L*myLx*0W9|fXiShl*u@h9x?~O(DgUXpkB?8NY`)Um{`n_9 zK0fqwQhay>giq%JPjCB{K!LU6fC7dhK-;n#?(4&;XvhQvrP6QdW-n#V09QuT_C41C z_$Y}e0fAschNvZnQXNyw^rn{t@Lfo#2*G%paDY))Dw@Dvbm%4>2RB&&9C_FmH;-a5 zQ0;z$v$~DoQ%^>?5;Rc_3Z#wxLPmW*4m`a4z|Zlx9R|2GLX06KZ6nuS!xxiM4FfMq&py2v~!A>AG zHI?PLY=SgRsKlS~ufQ3~VLHG{%J2MR#+>t>006-uk+iCTw{6tEA3(KX~N4` z^Wp_tzeAvnzT|H2H0N9e!%7|)HcKq4v^YUMVM~2|0)j0Z6y3jo0=a(9`u6v)>ctWFxqTM8fI5j;SFfq z#y$XiTVf0GuD2;;HNcUID< zSH}vtOO=Nq#%IdV#2q2}zI%t^ap4&~Cxxgx-LLjY;AN(Z`1wA7>T~pq1UU7@L{0`c z5?mYZn0{~AVtfyICL63OxW^pbbQQ(?`t{XeVL?Vcs2hf=^s1IXES(3eW4!gN&c`6N z=GHz2W@o-p!-{ye79%0@Vt8_X@5{p#AY?y7Xa(-)MNi;JR331Ho{EnD)@emGw3#wxOaCQVwvR?>$fbX077TPobv!Nt7^vj>+V!pW+tb_m=!=?z~_Mo z0h}iVwjZ+9HaF`9o~y{2iB2|cPnGGn3;)0Ks1y85(x|zYfmBk?Q{o@Az@O+?v3 zTwBq#k}G>t8J8&Z%}nMckti!8%3djzWQP*b@7&)%aDA@NeZS8+&-1*_Q@cjt`$g5j zmnA_re0QqGPL9PN)hJu)g1=MBpk+;%>ESUfWN@Ye5Ev3EJ4XfmgH8es3U@ma+W815 zlY4iCOmzKbMV7D2sg5qt5niRsueVk=wY9qso(Hc~ zv5}@Zy}+!FV%8oO(`#>%kXE;*lf`zuZKCr`6n3Mbl~K+BM3J`A67|YMwqDgN5F+;R z260TEyU-?HoP{{tpP?$7YBxfDid_^Uw>-BGO2QY~ZpMQ;a)i7RX*FjM2u<=ESB~sd zr^Vv!pE85C5o=pbi=q#P*T@dy#>*8D7OZmh;RRC?BFBA@ri~X@eDgC~O+_W*CqQy{ zAPgtz)D{O%Y6N$YKGK@LYVdf%N2gzf9AZj!_D{XxPLGylqlx&2*N8<JSXQ5ZOjK8{U(|x4AjoKRZZ?xsH?H1;+;x0yUyaxm9$Lcw z=`Yr%|CkhI-4y_Z+C15xaw!)Q7EYPI4jn<=)UxqX`(L?dw%S1XO@d^=(H-Fcqk3K7 zM-7QtS!%KZ~TWw2$ zutDt55ZZNzvb_omtXT`hm8zqdA(8Clud$_BM`l1BrkTqmam z{U#fUn$T~Dtd=Sri0QQxDbHTq;QHZST;#8hki|Zha&FIudsG_n51*ICi6=bbD?H{U z;>{iK!2CK8g18nWigWFsPM%|A0EoG+?iYUw&@2#|BOL1ilRU|%bM4{5{AGUey}bNs z7gO?s@za?x(m(gWdYb@*q|%QV!YoXBMx>Y(zwK-8;Ai64dDbzikf)beT4^;wk>Ekc zU}a@>$X6yt;A>hB)h^oHR>l2c!Ge0=Vx4{h=@j&yxJef?f8aY@LBK&Kr4X`Ef6!gRTGES5AQO zJbw;Cs%&7?Hd8Z+p~4EeAetkZKqFjTTbnTBSF01r6xy<7N%EfW^(dzB6DQm)h_a`o|LCt(g8kBUAQJ>5LQ@c*oopUTH4X1I8TB=<-Q-S-%wK@c$e@@s7a0|-z zHWaCclA@yackqqAlXbrS0RaJUq8$IhdtUER*QOf(QBg51z!mz6gT!>C^@{87A?64W zZ74-^e%vm2LJV?EW=MUCZz%UVHZ zk)P$PtXQ0yeks?oUX#5YH)nLO<8-N)o)X{nWyo2wCr zH@@i?!yI_ONJUvWyu0J~q8K?AY#)H9OSxZpx4t`Ol|_b-s=)cyt1zXX^2#B|a?CIl zukP>f_azni-ZvFabqm!*f)4k*9c*kSNW06%tcg-gDN`*>Od?^VrsWM}b!-VJ`U>Ke zJRXm~-NWXzPAcv5`M00Qye-0#sItb7G$bS>%mUHB10$mzVrgw13p1&7?hcJ1J4Y2l zLPADHcCSU`M~KR({KAhVMX#LbYC}QUsmVz}c0?YKRlURQ%D&(ebaKJG~uy0SVX>&g<;z2$;KYVN5Eqg?VH@eh*^j zH?XJbKt4>;M1vKR5SU_O`^F!d@rF6(OnmXCpDFeFv@6BIZ5th{QQ|z*W4{CDrq0@$o zT6sgd(ZutOS3D&&) zMK7DnNQ156)@9eQurRX7b|M4@pbOA*u009d5BmLX7YlVR$GI(JKtAd)WE1W7_h1LL zGE(FK)cK@r0+vRr%Kj;L*qndM^>px`UVAo9Fp}L(M;GR>x)nSrzYX`BjNg1W#1u?m z?Zx5sBJ-A*@beHR&crEQcawI=m=0)hhtE?f9L7+M_}ctm-;bw3-bc-s^h(_89Nw%@ zA6OI0WE$`4>T;i+kAAU`0oaf)yvYn~^zOs6sw53m1uxs$4p%ZY4$*$Lwz*_zu^nK7 zBPQS|=7Hg2tym~wFPhW)Z`C6DZiDtZz-UUC^(zwCTiVYf1a8GI3Va}OVwV1#Rtlz= z1r8DucjlQvKIpgvU57N5!L;YRk|-wI&?9=Ic`6NRojW_}#&`9r#EMc}NO3Dg!d43ZC{e&K4Hn)c3ayUR^i1jL$` ztCoFOrNR|GNedEctf!TMVJ8!cQ|+0$F?5{qe{HsqWf5{WRAdP7F;JO9IZi(hF30SA z?lJy6Z72gB91ia2VR*<^z8vEta#GTsm;X+VWbsV?fC&IKxEulNC9n@%?u4eLp|+Q2 zn|%!c;8ec^G$Y{QOP zsl>7ZTAqZh>3W?vixvH6H1nbS29thw7sx~jG7cCOnTNiEWGsR}Lpk0ROMc|i9=0od_vRD}D_&N0^&& zkO=0T{P@HKDK`=B)NOq1{3nZb87ua8J)4FIj2WDsCEmY6%*%$g5oA;dWotJa?{1wgr1;9~ zv4k7Lm`85|qgK2>B=@dA2Cw!PeA;UP0h?KehY@fiyY77-YyShcMlg~%GFsKVyXluyL&Gn0sslzc~kV(*aJ0L}|SOG;20{ya3m)7T6EM7+cI~j*kHJ+42 zVG6=)wc_;nc-%^HWNjsA;?#{V3qCy~C8P{~k|EDkeP$Z2QEv?b)IhG%YF#9WPK?;J zLWs|rKdA70mk;gK%nf+5GfjF9k#~=z1W9J(|0{r6^P4Afy}mOF)WxxyLIplP0{W8C zOAJVYJIqdNH>)QOC1z7w!y1m1hiYKGjPe*;B)e zyLQNRbN@KV|SWt9aWTR2#p8r%4*w)^w;SFR88FTn6&-tPn3R@7MZ1?t9Yuwux#{EMQM#ArvqwZ`PTB zAH?o`IaO4#*zbv)Ifh~77afcip3ct2mn8Fa1Q}!0ZwSB#oq}6OhKYscgvEzeW!)FY;3L=r$UEuaRO=Q^`^#5fSepP-Mon=B^0>QBRA0QExV7 zgt~BAyN*HY1g7F#SPIjz3&9t$&9*g3J#B5G`^G{rIE1Kh!5)qb5Q`NyXBt;@-QAZR z(r$d{+I<_lK2u+d$J;&!OcZ}#8ov954^7OQ)vej8mVW>e&B;i}Ew^-buEof*dZfjj z($cfDn;8VW^am#>a8ZQSG{c|*iKOcj<4k+WVn0D7k${kH5&|R5@Qay1zu4*+tEcmH zT#uJmJR8D@$^r=?0s{90)_|(Kw-0!4VkWy>!h5v5T2J)SE7TnPabGBEjRSs)TPV%uv8|Keu{;5?mbH_- z*WKA2?l~vpT@_^NInjJhxg#tJ%c!hUi32IS%1hk#&@?-W=I}!ra1liN%OKQ*QTtC7 z`=Hpo3w|jX_LtAg?P zUO#n{AY3(K#E4a8S3@UEMzXnE^^Fevh+Fjgs?9trSwu-JEh{YSc>~zh0$qMeC?uu0 zTf5($JbBUx&C(IOKr_pR0S(u;JoLk-=Im6w`htvRrsn3w;`atVPxv&0;d)WOY|Kp- z2PTN|ZOA<+BX8NizU!@}c%P8(%ku9zy3?hLXo&+GOH%BKIZ^u(ovd@jfCOZwrWTgk zR$B`)CR;tV{Q!BI2DrYVtaL-Ej72{q9-~M+;4Hn=Jeu?FDne$Ur?)<$#p(t)xJ(UmfxB!(o>CxQ6GBK8eZk3IA=L9eTazaE$J*~LiEZ%iFD zq@=gYUI|izjX;Py1qowo8&$1f2f3fHmR$WkyfQ_QRZ?SAB^yWm%>zB6JsJ8vnb(c8 zG#T#q8G{)O*^E8AljO7YQ|~<&+PTcI%W24F`sF&kYUeP?38qiuOjuD-DsO2NUPEJz z>O7Ej%w{Z}ejn+^b#hX; z+Z!}(c{>sR|0~ZSLG(6V<~lC<@skr9>9%&vq});T+MrrmL!+M$*0^>c9?`aZLMzgAjM^fDquk9F%3&-+ z8GA8#p_=qjRAU31ltmAgq=NHZ7^A6WI)zK=UT_Lb)JG}rW|3xHu`i@N*%_z6$XE2l zS>d}&sQzp5#V#3He4EPFD9*T`%f@j75C?`}9}M~W>sMaAlF~(Nr#O`tGIC-r8J=ccom5>w- zZnnG5V*|;hEDY|CZpC!I;$jnwIuqVEIe;%>9}if0cKYDnzwShLddkrx{@$ws+-+ii zmti~LrB!83;>ae;DgqN`mQTQ?XwnGaj@9Ud-i-BEn}>BivC5eY4x jgPfNf7LgX|mhO`728ly=+{OF-SD&MJ z;Otm?#+YM_W#|Wa=_lyK=nw=wc`GBK1VQlNOGp$I8T@J8GTZ_|=;9XQ;ve3Mi&NM; z+L>Bdn?R8JY`U_WM%)Fy@Y00|wwl=VVMUVlC+H23K&77xSA%lRYIHH|_A?Rwj zc+b*gR69OTpv$C(tY*>Gn!O1N(F#}9;XNRqFR1eIgzfL&Ox-kYrET2~c?@IwKf|Gk z-ORCs_>=+#`KQUF6=XVkoBZMNWR?*ro^JO4F+=KvphE-?cVFjnkz2SjJ8;SN6U@{& z-761Y>Oat^Llm*l@=Kg847eC2sE1jl2N&uggvymGjnScaa91AQVlSbePoTZix57x! zbYa{)0W_WSq7W5|goBdlq^aRW8=#M>pOhHkTmL{=#iB2n5nD^){57lDrQ!XXkRaD6 zjTmgvkC1<|7~=p$!3z(GlRY0qppZkzVjXK)F4VUVtd)U-TKf|QlirPS;MOLL5W5{8 zF0WFq{;{qQGaz{V)D&&~Wm-}y)pMCG1i2wh2qL~3ZM)|ciP_p*U)eO>vWA^@=G*O{a1$BO{{C-!VerPcFW*HWdZ zt$su?HrtCWs{8Ihzq_c{qpO@1I*fQ>M;f8EA6~xi_NY^em7wfRSjE}#V?QEKyhDp~ zdjb^)DYVL0qg3@j|&KjYq^RRWq^YQlk(Oe zsBxQ6=SMt&To)rn_*4ve-Twu8Heuo$ zB9&JDX~e2>1mdh`DJxHZx3Td)*;>ZY`Lt_Kfc%j#;}2nD5E|l}9@OUsl>8yj45OxB z4xthxMS$jA*#6MIjQgSR`;{loRfoGFe?^RjR58r~B^hPLD?M7Q=lXFn)L6Y= z*X7YEU&XM$#dvEaGbh88r<^A|_S7Oxj%GK;rgw22^_PD!MN(`{40epd*PGt<^%`9M z&X83(v>a-sym%a0E)$Ur#QaQlvE;0uii3q2e^Gyi@MmhhwaIe*z@i*n_?*)v<<(#+ zzIcBgQ|`n_iiMfQg*nTPb3NL^7c$ADk)$!JZIqp@oiC?um`{S9eCd`kq$9E-@**lA ztRZ4amivx0o|N39!aBuHl5F-3`Z({iv4eKjcZRjIFe-g!bDDcb@DDZ#8ztvqGtO7_jo=S-*LGY=?R7=-XV{TAG7kvo$Vv0%6l)yBCJVoQo#&R)PkG z7VL9*9eJJW&94XJtx`kPxDmMSzl*+XS@Af= zKaxlK2-gO;0oU}2_){f<6#_Y8GGaao7g8ir12PMyFrFAD+7nH3$2hxIf@6{^BaV49 z#*|UKKGbwPEs|^20U9~7$!AeP!>CJ7eeJ$q$?XhOqlPR?TZhz=TM#7^T>0R>rf2`j z{7><>va^Hp1>?a$gz?!lLmM@cx& z&#BS&L)SZ|JA^{loZz>tQ#jJrQ&bY2jY>D>bLt2-cZT{i+yphbG-JGZ1Ha)U{Sw*u zLLv5ng-~Im!1g`q^W%WjKn2O>oX8x-ikezk!LOU?Y6<7O3j#jk*XBVAQZ8K_XbMUU z9!?oNt4T~Q77x!j%rNoAr^Tn`Dm}4C{LL`MT0>W(V9LM{_hj8;)25FkF1YVv zo$AWzWDd_dP;NB$w^Hc`EPOeZ9}Mo=gxc=4GEFjCe>s*+@Bdv2qc~cJO&2 zn%Iz}zGc&Qp;p>Wp)(`eE8h#{ToSfx>1<~`U)Iv{3(ZD}JCaO>-+m+2-)=T_KgF%e zUW*><&zp@l+NJN_UTYt=vxnN}+Xt7D{c6rocV#>n#`s%YikWh4vV^jmVA~P7>7;t3 z(#>U{csS6~!2 z?ssk3I^i^RImN7->Cpu1+9Rp4rCE4U`>Ouz()E0wzzzLCZeG_j+P&s zzu)&2CapHhmmga{4!3J!!?4hTGw$Ob#)DVJqz9xYsHCVOqtnUBNuCfl9UBkDtrYw! zcs|_ctM=fr>r}M0bhmo*Zdl`X`ViwPe7L35qwvHLR#aHV-%Zs`-ZTV)Wrn?or|8O#TZPZ;bqHrO+<$Zt4auINHR7CV25leo44MKAm6H<)6w#ws}er z`Ry`_$YmS0??|S?tlN}f&Tvw9k%)vRs%z$J4Y6W)0y^HG~LeZB6rlYg&D5V ziKTPS1v{kci{IAg-v@`H`U#G_RNT;iWT<&Ae5zz|s3(%GWB9XXI`l?i0v6sLxzjAj~Ev~)hr{3Y&_pE|-A9c)6wnFe(bbV`Zi}Yei9d!i`|Dx_+%$+ju zEFBh+*C%y7Sez_}AKmgCn<_+I)zsfNe6HCRvBB{x;&n6gj8m=Md7l&zEFyDF~ zElGQ2`}$#cj}X0hHPkF4C)eQ*hrnB-{N@du?7Md!Fu}XiaaKaiA4Nst1_qS$3=G-h zJKpSsg(_jce{;^e&e=fzLSE-t-@gZ43}xP*(r%x5>NI;3-JI_`&8n5@H9f_{3k(QA z?C9!pB^i45>=_}SBQ=!u;|D4i7uS!HlKrucvx5ba?CfkAdHEo%k|4FB&PWoT58B${ zV`ECcfB$w)=DR-K`BGlaN=;2oK~0UQRf4~!F$=l~f$raVB-2CjBvCY0E_Y>eU-+ob2Xi zG7uhO@83TO3lA5vWe^m60WR`ss6@JB;O^Nq)}_c{D}s!y?4PCkbDn}01zFk8S|w7B zj_hLM;-mBP5&!;Ks;H~y78hfBHZ{NV&P+>-`0;}-FF&7>o<2-F&cwuoj+r@V)ciF0 z>FxpFg+z#ygoLxkR7MYj`f_OF{=wN_Wx=@#5BvB~5^n25KA2Y@N_y-?#_38w*9MMx z3Vz!3U@DK((kN%7G?_=oj-5q{l&UJ;qR)kH&xT`-51+7DOiD_a)7H?Z?-uj54hTd< zM9g!~KWAl8M34y)2V;?b?lt~5Qbx<`h2VF8l37=Maj+2n?HggVIR&DDfr0z-ClveR z^|#ae=U6R;#l;+*W&iKW_JXmBey)UUF{`}y;ypf8Pl8eK>W!<&;uFW8%+3G^Xtd3h{IG%6+$_h9XvmU(zp8dN^Hx zwnyaEt5@H6?8wB#!~{1pGg6!srm_o0R6RDp^7VN-a+|t2Z_8(#;i9;)ADJHds;@UO z=r{1=&?>8$L% z4hRa$$;$HYemXijn$8Y^$9uFMr|`$Lvaa*)Pap=Npu2qm<4r^a<{KI(Z*H5}fYVdw z=&iq+e&jxkqHXuHA|_wg#tOiVniAw(o31CR-}bH!z4-D!MIf;iNn zp`pC)hgs^pal^Z1Ee92FPx0}CUcF0n?+_Po-D_?AgwUjR|C~nd5EYidpw6FeWEWq~ zvej6LENX6UUem*%ux_J1scaVS=XO%e<6iqURA}%d!di>%qlm4d! z1i?#p2W~PlG7uz}!in}Sk+ChDrFq(7Dn}}}O&nXO!{>fAoF!|*QlRl-QrnJ_mzPjM z_$n_;ve^x$xA=K*Xs9b&JlH$TNk#_Mn4PHkYLf($khOJfA)kTggRCt2WT`Gj><=M{ zwe8VdIu@2-iI;Drq>#b zl&@c-T`YRB{Aq88gRq58pMn$MGie2YWYQCe;(RYBhr4HYxZEc1#+5$f!&fh?t*xC- zrds}yJz4NP;;|xq6Y}D|sNpahTJC3Q3FtNcQ|qwCYBuyj{%Nsx4OSAfuGpJ5pXTcD z!#j14C;9#)bC|Ij_rzfNk#kw%s+DMU9>px!c2AaQJ6s)`NJvT=^u@oHdH)^>8c5;7 zKo5jh5IjPpr>7VEW3t@(snLih<@?dy#nReX{yS7GEGacL{F>)J8wu(ZN&QD%BzCoe zwoY5F`$K#ers>fnJf+IVeM!r^XMf`aci$!RTK@e(wsBY5cax!~oGuJsdvnlG;c;Sm zu(QDCMWpxRJ;TEU^XVvvh>-ty`qas=$ndUNXBb{u z(Gp1-6%`dy$ttJ^i2aF7?dtkIfyc+kSZlKlZe>|siwl?S?d?YkZc7eJbJpCq_ZKbF zAeq-4`8bK6jE#-iZw@45C34sC>by}>!igdm8M-^)o2f*_#9TKoR4N34gOWSi(`3X+ z%w|54g=NDx_BWY9h=(UhK78qt$d3L&BNTrVRds_V1eV2}uT1qI-ua@#pR zwn81<-Clps*L&j(sT=W z$abd2i3ejHUGAOF*vrndlvU7|N?KdC zIiI>vw#E-DZgiYVDmbpL+%2q>h8Ef?7Z2`rdpk0gef0ah%#8L*xh8g~AUlJhG`_~5 zOyBDr`G(sJ@8h=zH&c3EgGQZF@`QYC>ScP8T3T8K4z2+O8J>Mi1_D+Pi2cl(td{G4 z3){c{)<`D z{t`*@G-)FY00QfXg{trKLc;G51pV#>hw<2KW;qd2P`vj4g+@nr&(}He5iAX*3mDYQ zHT{t+R5_l{@$m4Vd;R(dZ3qJ8rcOrboQ)7u*og~tLimAxRZib*SFzeK|R$6LW zjgkVaa12k5P0Igwg|u=e!fLA2g*W#Y9|Z4Vx5$00z^~CAXI=D0N;f2>LR{#Bme%Zw zc~0e15|Z!=qi)AczsnUAohHw!cCX0DNcX*pZdSj0Z^7HccK4M)g8CQl73$$d9&Vk6 zvNY-(Uq!v(TTQ@7SP%U3N9^y^l$*Q4%h*4*ti?iQx;x(0WLcy=jG7*G=K+s zdSp1cxI8B0ot-(QqRE~>yxy1g1^6D|o`*g8J&vihw6%SLPFC83*-ZLyGhV&I4|n+Y z_qDvJi)2qM`W7gppJB;zGfS7F3A z0+lAF*BF|8X(SLg{BIlGEwN}pGcB+Y?e69xc*1g@T^tt|_hVNC(Y%>i;&-Xs6}HH> zkB9E}mX?JP7XC_4|?oxE-o&-4y%aZ4jTI=+yv?A85t3w)BQODP*Fl6BGw&4 zcXxMnk+BjI60#LCg=;~!b+4td86h7uUFbogAhXm;b#~aJ>+P1BNd>t&J3FVFym*41 zkRU_f_?&3)nRTYyQY-CO#B58zAy#g$PRLdWadA7GxazgX^C)1lqMB}lbv(O`9LKUD zQt7cZ%~}cvtt9h}8#6;M*xc!#H-uj_C@(JUac!JiukP0@ZTi5re^R)GKV~^hR~-&r zY@|$IM5osNQ@@iN9_kvpcVs2)NQbcQ8wFQ1UMI9<}Cdd zU(mI>jyL-2s`p(5Ob5QLs5S+xuNyOu9H!beuP7PgJb!)!YJ}@+WKn9ImC9k^wNBgh z^>yd063`__bERXyecN^@z1M%ZR@bAD*U%uuXVmZqX?Zluoh%2Unf0J{4Qp}rmBI0P z?`P!vN)K{DcUG{>wZeLyJFn<)(c9cej~oL!IwZ&KWjx|kQ7mhZlc-It}iHZ0iO}nYoXFx;rc-8@Hy2$9)LX*mU zb}{c1{qZ)C;|(1mh_dNw8qa!N(VgW?p^Jw)`UOXQLZ; z*MXL@ZYjdDxun2%?$~8_wSN{Lh)3|Z+cw9>I3vLvfssL3qEP{lhlj`Oy#4gw?ryeH zA%ATuh$5vz2{EzH>K^9{NFWuvOLZGYYV7n6>>iOEw#e;>3C~}E^N^G&b8~VU=^c_Y zGNSU|CBZ|&*V|NN3jsRei_D&pQtjH-IH8E3__WhzdVdZILO%UBfpM|qCsIR&fr{GN z6-mMddiyOXI?Qu4ctI-kogmgQzzTR>*rtj2kvZ1ASnG;h6O;sBfQHxk+hUv_QK)yr zG5Vb=z(!_PXJxB7|U7LTnJ-nbq6y0r~zD3k5W zJX{U?9XHdKC`e!4o(y}y`0)qqJ5i09_jkq%JkW=ZE=((lz`*ziEQ&t@3YN3L5F8v_ zqhq-kTwrrGYM{>P`1ki~`L!dQk@|jj6R(}To>x82gkbTF9`5gIop+Ri>9xw5uYXG8 z-544gmYekBgP#St z`lu}36&Oc*pfMi}3BZ=uqD8t2l?&W2y}}q6?DhQaToz%ZQ+c@rp*{z7TN&~mo!&xQ zx(kt>RAu$Q#?Q|@k0%aVI0SdYeMwCW-A zp+OQGhFBGL+9!#ZpQLi%=;*vqQdVXIzzNGFK8Z#DfO~tR`Q~74z7hkUar@8*OoAw% zHVRh_D7m@ueQwSrEiLK62ht}+2m!nwR@Kqan118W{|8iNepD1QvtCfC=e+>mK)U^Y zoD-i#Z_iZ_^pABSoneuOMs2tQ^s@WA8;oPdn`RkmF>v2qoF!soh@nuv)M>?-2YGLKlylH5kvsE*=x} zfNO#Z+25#J?7)~3jAE_ed;|N|X|Jn#<7n3kGJRKZvnMPc`40ZZi<*|Z$l&0opZu#m zVGq|+E%U2#$b>?metcF;(ltPJv*rHv3y;LV+H{b(0H5bIW&`}u(UD*-m59jF29Z9% z7V6o1tDWJfPo4l=N(=*Y<_gkZT@XQRY-}9jUU z)uFW)wFocmS;^_dr2u%C%j13)kJrgV_NRy}kWMzCn;=7iti#>4%i?YQ+G`xpQqxO& zRg2UpX=soYMD94T?XoSuHph!(40))>#}pj@ERrn~n2ck=bujaoRPW1-4_z3%5wd`s zr&9h^H$XaXY-~!pJ;ngcNISgUNYYQ+96MNQAtzwg@t4Z|B$n;pY4~gasoDFA9aj0F zSLR$NmhpBC%PcI%{=Yy$Y7SsC>RKLG5ZQRWu)1oP%-i z0bd#5Y|xYVsSw$dBT}OQRRu_?Is~D7rPsq>zJC4s`SWLZ4Mu!M-FnqQdVPPVsd}DyYL8$#{F*m zQCU>fU%i3zoSo9G6`fV#So0MQnhHIhS(_3rQd}=JFU!l=5b34OP1Bl70ku1)z&Imq zvC~8uYWZ`2fU#ih;3P zZuPa-xN-I6fjzj+bXlUK$HAc7pdES9MtOI#q#dvvbcFufn2t_P0=FgE*>GrRXgXJ8 zDJjI>mn*^Y3-iX*OsT%Bn4qLuT3J$AF(Po?E;%wEf}uF5gR~kf&1|I#5iP6(|!8~g9Wud z%v%*jlsV}nY_yy&Ti0bP?hw3vIMj>$gqWIc@4I|@UpU+&S=I04S)~;@J*@#Ic~El` zy+G%BN=h0Dn9hKJfJ57+$0-I>WiWnF$*@pr04gwA_+r6LKR6eyLL&l&+&jjtXbF_# zd18COu3p~Xz&teZ#oAoIAU_c^F?j_O>Rx65F>2QK&BDS0P&vp`T~{Yt=?Augofr^c zk@uespYKj#PfScShDQscy@-sCc59&7aOBJIy|#$D=T3bBrXIJtW>3c<0WYlm(8lB6 zK5jm)-JbvcX*L!J?)Il3EcQs~pZF?tKGvaQi>Fz+a1?p0LXp*`y4=W1@yArSP(mvnTfkF2(x6XC$* zv0ID)JY+`r5rAZZv-5rrcb}b_T=%sKWLKjE4z^=tw|{EHax@BV%=q42JDf1Y_44Np z)cr|7%-&TYoiYYA9Sa@3lp6c6Q!ZPPdm11%*P7>%`=nIv51dup!{1rfcjnmtXOM z_Cp%r4AKP9p^<56FBX~G@P<}aRxZJ+xWmwq5-$57ilT6j8_XBHBUIVhqvnTzg*@_| zo1G2Im5yG$fwgplZW%E-skV4AS7Udfr6{0GrdxtYNK8CSIWca`z5@E^pY#1W2S5~J zosf`|!;Xmb<>cgo$I<{d)9JS46AWv4$f$ApXtCyw$2#H~8d5}h2B=(*{bG%Z9A$Tp zzRE}H-_@1d(b3VpftNe~Z|ZMFg~_}c#Z@7$t#nn1jJ~1_PN-2=LASG8IpZuJZdsPb zl?QfVj4$d|{5q2u0w>|&wp$z!600f$CuO3;3|vk&%UHR-J;{978)Fi%Ul!Fn$ff1Q zCS>(5%G}?pnA^8?kOxQr0OVCQUS4)Y?Xo!%gpYvQTd;-7nF~PZl!>>IXKw|Q``T+E z_Go8MfFgng-ya7rE{43=0BhdGcPp9*8y3D9u%HRyxQ+YzwcMy1t7d;|YfAu+>>y`& z$@}EJp7zPsu$zD_C5Qq|vta;lnxf(_jNgMfV0Kmuuxo9(*N0$yPgm^7=wr}l5Y;cC z)n8sk8@{gJD`!ZaPH$WyJzm6HT&Vc&or3%=Jv|b%fh1Vt$&i42S&|E`vD4-N+=y#K zT#>7lm6ZW^s>86*#q!lwX7@KXBloS$p|KSJHG_+b85?hp`{$c_W%F@d8%X)nvAUzl zyQ^*H%0Xr&@g^lEt^x?q^$7vx@UODM5xkrZ`fQ7c9ZAX>Y$I=;c>iK z@7ga={~w1LfGalX>pc)MihIGJ@bT>51h3O(#7Ec28Xwn-v>RDH7cPX>)UO>GrL_7c zubhL-8qgQ}Iu15{^n1LrNeJw^QgU=AA`j$0&?jir*plWcy#`_WxNL1X!cmXoCy>Mf zf`i2iRdNao(SRxj5S0BjNvH(SA*g{kbYQ6&mNPOvy?xBDP8kv&{za?g;BOPe6FzxB z0aPxKi&=E&K+<6)jx3+s2NItx2Qxc6d%fIvshFG`CMf5%DrDR|)rEzbC&G~|2WY(==Kv4&wr4ErZZFCO8DeF!)QYmFb`2^tMrLRK#aTI} zm-PPpNuLx{wdQ$f%5-Tsq>C2nd`@!HSMF$u63IzM>1bK}y-_SQ+kUQdCeC*{1EYiyjmCx?mQ@q!u5-S! z;huJ8M4M2FkO`E4wH)OL&65_DK+YyZihkOvG3GQAsf5A6nq8KnjvqNQeos~Ay9ec1y zhu+;hT~U5AD;xDGFAm{O^I9hKTxK>T&E36NZqD>OIY&{vj7`T#5WqB|{s=5e19mgj zT13Q}sFJb*E6*s?7Ce|WOe`rk+xGHU!X-+8MfHDP05d^q+RdbO%IvF+%Ox}zMin{5 zh;Z+NHM!a!)GRN@izy;F4-VIs=B`14OLuV;{m2JXcewi1Uod)7+r;j-tM5^STAho> z)ZkE&W6(u=QC~6nS7J3#nEeS=?V*P(A!29+GW_QH9&(1l;I@;iT_7!uH=XlD2Yn=> z&n}VKeLCP!O`192Ymu{h4Z1f6(5dkxA%6;FH!goxsA6C#5**<#Ywhkgztm(HKOHyR z2FvqpDqK-cahMw90$HM6ZxdaY_jM~r2T6Qnh9?qalxuiDz?(w4vo7ivW**%s6haiP z(h5Naj8&{Y+o)PINbw>?)A5MS+0a)avK)vI!ew*HG9g0{=fS8O&!-DhO=N81!eqh? zXhY&z#F&&B6F8M@VC9DY=F8c^Yna@UOq8-jVg6?0G-6uWv6ditM!fG}d@=2kOgCETvB z=YMBlke&VO*RguK{KYG(;(utJrY@_#-(SSH;E1C7cZ7t53<8Mr8(vgVF*fJ>cT-&( zn|)f$W_%tavnK?vjPfKP!l?!~STevoZ-JPDQ>Dc;X<2nn!ecuPU^)pHsQhd#EUtL` zcQFr&R}36*%i(W8^=jTBN4zLJ5K22AD3zZYW3ibo~VF}{xB9y~5psw(isNlrL#%|$w`Epe=R)*TOb!OvN zHeDZb>-VYMLU3#ms8-DVUBG4%S5`Zm9FVQ+rAyRkU(wRO6Biek92^{Uc5$gHsjt^k zS5rH$)GK?)U^6Es3>@@qH>W*$d%O*p-Srs&Rhz)EjKSYHO?q|>-dDfsii?Z0YilnB zaz|^E*tjJkjtp^Aj9OMt+Wl_k&v+Mg2WL(@#p!Ih{HY-$Wo2cB3<0;O?-nV|0FI}} z#ySwSeuQEN4&G9a1jSoWJ!|dB%F3#djwaLf+8&{tHD(`;`k<;R*#d?U(>k3+%#Y0e za;CKH2OnPN*gRXoS7U4Vs2aJzc{-4B79oREpnr6I&jG=Go$;p~Zz`C%z z2CNIt;36J6N7z2M#X63Ck7#QV@t*?nut~|!pE*K4z{#M2MiD+!NDmhhTHQIYl#}dm z59IMhGhl5Hic>4f52T=_4MrBV;!JUaA`IQt#m6$gP5A;|M*Gp`FiVow`zYEXL&FH$ zgNJp~y|?E`tipnVxB4fWgI0n-i?FHC;9u6))_&J=HmPkIDq)Cx__VUwkdR*n@lwBy zQ0fkfF!MMCqT1(MWhEuC;Z&YsLL3|=#APy5CW*Q=@`p9QTLtW$MeQCah6DX0h5rMO z&FpV}wHSa;dUHn2g-sCSv%XR^qKra8&}FV1P36SY)cC#K52+OAK^$^D!tSD(W7&)gGBP5F_xlX+)SiL7XoYLSG2sNS3o+Xxx5*sG(XaK|yabDXAb;8GC_0K#<%6B#Jr_)$55^ zVfjtvKDu^e=s7R|Je&a-=Q1KD9rYp`U|C;8*3XK<=mf}+KubH-%a_fwKw{Z{Vr*if z3SS$ZU5W1B@x~*F?ZngV!-o&;0RAt?i~9Ho2>}9FDpcYaxxFFnlPn?A3d9aXjT)ds z#2hd--e2z`L;ZwgPfU*pmb2#`Pve^nF6e0WNRvZW$UdCvf!YI-j4#7tb z5QtG|&uP91wRvsyB}@WihcfgXL5A{DdY$0UefPtBqqJkVyKs+_QlwOF^5KX$wnP3^ zGmyGV)QW`ub=bVCf6#Pua<;Vmw+6_2yx5u<6Em~5k!o;4$b`a$z$sYasTAGwU_Fr`uO( zy$*Y61SfNGzHihWMcM*p1~#wFy#IMJrk(lIxn941>j{L5u<4f!kDiQIalK!GDTA}D zzP>($51Ey(K9p2v)Y@8t)qf5dn@sRLR+=o9_eiV)&e4#7*}*XiVZzdd<=3gHl~vK4 zSH*jpxE@OPD4JQ*XelvZ4tUhj3sfJcMVe)xl{~VHgEVoy+_v+)SAg@95Y-Nyb=jRn z(yw>k@k2*PKSwY}6d}$KLN8awm2}w%Q%m_CIClBMq7>eK?uTM-SD99oY}@hw**JFk zlUP!LG|>Sp1hM6A`v0?Wd8{W=`5BprM2Q_C8U!!($aF8tOac@Cy_oOeStNJt*-fb;Vl!P*}$SWH}zETDt_ zo*ufAl9GIjlaT*Tm2j&_ zAYB!e4xgow5m7T!(?m9bYh0<3w;>Cv6qOCl9BgbAkBeHUTWy_uUsTroDwL^IlS(gMYDcyn{}S2y}OVAC>CDA?GJXrVPCm_*id z{?Kp2H&88ykkB3ayNj+asd^wgGJ%wz0IvjKYuNxVlL6(F*jPo*kFEYzph(i9T_f`D zjfp4chSAa}WayYxIVy|#9d!~+*4EadL#dGW3qnGTW}ul+y?xl|PqHGq@P7H0!Wu`yu1K1 zK1X9d|G=nIv#zX>KYk_!o1kv+>1K|gtCJqP^5i3&_ox3{#5*Y?F9UUQRR)8XUiHes7O#=q{ zW8W3bM zO&X3uCU;cs(Z?Y+o$d)dpNrlngY{uyVSdmL|dC{Ad5d-g-N^n5H zshzd;d{k7R7bBFyKu^C|_T$H;I5V26NR#Z}X@UFDL-z}U z&Mz-7Pe7ONAr$uJ^{>`$gNKJ-B_uAF)THqD`(SNd9MDL013DWrB*OMP8=4+4J*fb4 z=98Bm)QpUB9kso$37p=V8c+k0bnqSk7D80WuIVgMvtZof70z1;+UU^f+?<%hLwhvs z)Ry1B<4eIW!|m~bL-bUZr9SUTwg<;TbNH@YdTwsl%jpWEI**5yVDe(Xwh49Bp3f{* zb8~Z-dV=Uc&SlCkNywoS2kTq|Uuwf0+!A=z0(YB&yFRMK33UQzC5qqu)fU_yk}89G zskM;fx(v5J6($)I^CX<4Vtho2A{G=F82C6j6qzgZ#=-pnNj+#$Ct3SAAwWfdH{IHxs|`eq#}t+G_HO*VK!nf=^ub8b zUIGUW%A=lrK(Cz9QB_gF6*3>8fJA}$7>|f3dH(NTTv1f>zBe)YBEV3z1Dta|0Yn(% zWXiSBqQMUrS4ii7WfoY-Q^0DjAb^RAjZF}j)DK#17yR-Ie|po~H_+$zG|DbEHcW2h z#vls!TpQs3AUSB<4nmlq!ga+^iqiwT7@PXLL^e)tjy^QVT^11n4)Br)cn3AikcHl# zZ~>B%l7n8rd6WYr0ejF^_GYV!M1cik&IP8y4P6mM&v*$NS`*H!& zhpv&qo&hS&XEFG!WK_Vd$hA&72S6le%HXDFkVyVO19#EH&l;@~K1_XXc5l__D9N8a zIReGfpNl{CbdiO?X#nfef%o0nl=uwE!mrB8eL#5*dNk=h;LTczpr&U!O|S#Us1>l9 zTz7YLKu}I@Zl`0NV23e#Y+!yodZ3ut@h&je4h-Ln@)lq%_ypOBRJNyYSrWizf#3%*1b_8uNk;tW6d?OZ(Zs<)fCMfs zDlQi6+0y~=Nldjv=EB}NQ`pB{3$(K70Xleu6B#(dQ%@gN;56T&4+#wgTDO7nd0q!| zN^!Hgnv&A7$N&}(rp;FAqZi6=$g;|{3!+GH(gfmSTLck@M&L&tLQF36{+r2X@X9|& z&2t{rNMs;a(S@;p)=$KTza*IW`_~w}5T7*&ahycGkn^np;8YmM2}AI}RN4vLkP#6# ziDn^apgco_{J;<^K<2&-7y3W1b)CMC|=8FMkSsy*}R;pag6p z9XtD1OJGv~BWr$hbMud!97AmX=L5T>vNX@}&ZdQ#mZ!d=el(|vlg(cPs!HsC02Ims zsvSttVg@FrJ6fYGuGj{@V3*d!K5jtDk}m7e*r zKW+z6;DTPDCn3Urprxf%Xav}59RdSwU}IyW6l8{)REl@d|A2h4GagLak(!dSH!u{+ z#EAfzrpr$mvl5CPQcyC(4$-p{DnH7&y8@T;f6fGli_5ORX`TaRx9H8^5x5eboK{{ z$-jRw-8YlXsDbaKJOu9;7?dTfBqclD2EH-LyN=HDxjH%?e{Q+mU;#7^F3?MA(gi(^ zU-~oPN}j=}%j~O8C0{DafXZP8fxQX6_ooFSlJXgX$pv!eDN>;Gc7PF+1Kd`%dDZOj z=#ekN@j++|pfaL>eO3tQuTogxJw4wlz(M@mo=-Ym=k756_%sH@)b>V zQ3QByZl2@dtP(J4h+1$GtEi}a1WsX&GMzd@Mf!vsA`VkT;4ATaTG_P*27GO>Ev1Gd zsG5kh(q<2`2KxpIK}`1bVTI*9#l@u-*S|a^iTBBgcI6 zyBh92`paZFDZN=SzmRHt^Z0@q^Oux_c@(OnF&Z&-Fo` zC6&0vAe*^rBEaBa;h@jbjG%;y)EOlK!F0gue8vox0&LHoXaA7SZ;2p~E>wlGKG7k7Psz zP_x-zu!5GR)9B8&45o;yOt3BI+Y{t=v*oEK6az#$Ft_vN(Bq;%3Nl|M!|~sezH{y~ zW(V6uQuu)eatQN#xCuUoE!o-H*xY?(MK2*EY_a}l_K1=jP5KihrKF`1AW+C3t>p=X zkzIalVX7#!c&Fdad%O@*-pR@eUoAb{Elq(EVjV~G9;dsjYZZ9yFth0B{qvt-fH5F( zc6L@=t*8q6lVmd*aFO#5v`nUGk^9<|J9fbEECXXJ#(SD^%P!Fbh!9xQkRxC4eGM)W z%l?Rg9=f~`DD${k>;4NSq!)P_6B9EErqr0Ag*uzXM$Lk$U8gpd_m*ziFX;XV4GAFB z%vb}~W8H`=bx;t&A2{=oID1H6|J54xC6ZHzPu^Qza_{lPTQ7D)w2^-D{Q3g+ zFb#}vf52?`j@}RWg|Q_etmlh30uJNpPw$J(#4%fG5@ZK~I*FW2+A0S6ac2h!V$Ry& zCkmYzVyG9~VT*RXvjqj@4GetW!wFc(q~?e!BzivNSfr>1DdpItKDP^1%^j79;er6_ z1m_9@TP`~Oj*NWV0Y>jrAd4qeb{UI`LSQQXkp>dD7?{Y;P-kI2T4Sa?dH4L*myLx*0W9|fXiShl*u@h9x?~O(DgUXpkB?8NY`)Um{`n_9 zK0fqwQhay>giq%JPjCB{K!LU6fC7dhK-;n#?(4&;XvhQvrP6QdW-n#V09QuT_C41C z_$Y}e0fAschNvZnQXNyw^rn{t@Lfo#2*G%paDY))Dw@Dvbm%4>2RB&&9C_FmH;-a5 zQ0;z$v$~DoQ%^>?5;Rc_3Z#wxLPmW*4m`a4z|Zlx9R|2GLX06KZ6nuS!xxiM4FfMq&py2v~!A>AG zHI?PLY=SgRsKlS~ufQ3~VLHG{%J2MR#+>t>006-uk+iCTw{6tEA3(KX~N4` z^Wp_tzeAvnzT|H2H0N9e!%7|)HcKq4v^YUMVM~2|0)j0Z6y3jo0=a(9`u6v)>ctWFxqTM8fI5j;SFfq z#y$XiTVf0GuD2;;HNcUID< zSH}vtOO=Nq#%IdV#2q2}zI%t^ap4&~Cxxgx-LLjY;AN(Z`1wA7>T~pq1UU7@L{0`c z5?mYZn0{~AVtfyICL63OxW^pbbQQ(?`t{XeVL?Vcs2hf=^s1IXES(3eW4!gN&c`6N z=GHz2W@o-p!-{ye79%0@Vt8_X@5{p#AY?y7Xa(-)MNi;JR331Ho{EnD)@emGw3#wxOaCQVwvR?>$fbX077TPobv!Nt7^vj>+V!pW+tb_m=!=?z~_Mo z0h}iVwjZ+9HaF`9o~y{2iB2|cPnGGn3;)0Ks1y85(x|zYfmBk?Q{o@Az@O+?v3 zTwBq#k}G>t8J8&Z%}nMckti!8%3djzWQP*b@7&)%aDA@NeZS8+&-1*_Q@cjt`$g5j zmnA_re0QqGPL9PN)hJu)g1=MBpk+;%>ESUfWN@Ye5Ev3EJ4XfmgH8es3U@ma+W815 zlY4iCOmzKbMV7D2sg5qt5niRsueVk=wY9qso(Hc~ zv5}@Zy}+!FV%8oO(`#>%kXE;*lf`zuZKCr`6n3Mbl~K+BM3J`A67|YMwqDgN5F+;R z260TEyU-?HoP{{tpP?$7YBxfDid_^Uw>-BGO2QY~ZpMQ;a)i7RX*FjM2u<=ESB~sd zr^Vv!pE85C5o=pbi=q#P*T@dy#>*8D7OZmh;RRC?BFBA@ri~X@eDgC~O+_W*CqQy{ zAPgtz)D{O%Y6N$YKGK@LYVdf%N2gzf9AZj!_D{XxPLGylqlx&2*N8<JSXQ5ZOjK8{U(|x4AjoKRZZ?xsH?H1;+;x0yUyaxm9$Lcw z=`Yr%|CkhI-4y_Z+C15xaw!)Q7EYPI4jn<=)UxqX`(L?dw%S1XO@d^=(H-Fcqk3K7 zM-7QtS!%KZ~TWw2$ zutDt55ZZNzvb_omtXT`hm8zqdA(8Clud$_BM`l1BrkTqmam z{U#fUn$T~Dtd=Sri0QQxDbHTq;QHZST;#8hki|Zha&FIudsG_n51*ICi6=bbD?H{U z;>{iK!2CK8g18nWigWFsPM%|A0EoG+?iYUw&@2#|BOL1ilRU|%bM4{5{AGUey}bNs z7gO?s@za?x(m(gWdYb@*q|%QV!YoXBMx>Y(zwK-8;Ai64dDbzikf)beT4^;wk>Ekc zU}a@>$X6yt;A>hB)h^oHR>l2c!Ge0=Vx4{h=@j&yxJef?f8aY@LBK&Kr4X`Ef6!gRTGES5AQO zJbw;Cs%&7?Hd8Z+p~4EeAetkZKqFjTTbnTBSF01r6xy<7N%EfW^(dzB6DQm)h_a`o|LCt(g8kBUAQJ>5LQ@c*oopUTH4X1I8TB=<-Q-S-%wK@c$e@@s7a0|-z zHWaCclA@yackqqAlXbrS0RaJUq8$IhdtUER*QOf(QBg51z!mz6gT!>C^@{87A?64W zZ74-^e%vm2LJV?EW=MUCZz%UVHZ zk)P$PtXQ0yeks?oUX#5YH)nLO<8-N)o)X{nWyo2wCr zH@@i?!yI_ONJUvWyu0J~q8K?AY#)H9OSxZpx4t`Ol|_b-s=)cyt1zXX^2#B|a?CIl zukP>f_azni-ZvFabqm!*f)4k*9c*kSNW06%tcg-gDN`*>Od?^VrsWM}b!-VJ`U>Ke zJRXm~-NWXzPAcv5`M00Qye-0#sItb7G$bS>%mUHB10$mzVrgw13p1&7?hcJ1J4Y2l zLPADHcCSU`M~KR({KAhVMX#LbYC}QUsmVz}c0?YKRlURQ%D&(ebaKJG~uy0SVX>&g<;z2$;KYVN5Eqg?VH@eh*^j zH?XJbKt4>;M1vKR5SU_O`^F!d@rF6(OnmXCpDFeFv@6BIZ5th{QQ|z*W4{CDrq0@$o zT6sgd(ZutOS3D&&) zMK7DnNQ156)@9eQurRX7b|M4@pbOA*u009d5BmLX7YlVR$GI(JKtAd)WE1W7_h1LL zGE(FK)cK@r0+vRr%Kj;L*qndM^>px`UVAo9Fp}L(M;GR>x)nSrzYX`BjNg1W#1u?m z?Zx5sBJ-A*@beHR&crEQcawI=m=0)hhtE?f9L7+M_}ctm-;bw3-bc-s^h(_89Nw%@ zA6OI0WE$`4>T;i+kAAU`0oaf)yvYn~^zOs6sw53m1uxs$4p%ZY4$*$Lwz*_zu^nK7 zBPQS|=7Hg2tym~wFPhW)Z`C6DZiDtZz-UUC^(zwCTiVYf1a8GI3Va}OVwV1#Rtlz= z1r8DucjlQvKIpgvU57N5!L;YRk|-wI&?9=Ic`6NRojW_}#&`9r#EMc}NO3Dg!d43ZC{e&K4Hn)c3ayUR^i1jL$` ztCoFOrNR|GNedEctf!TMVJ8!cQ|+0$F?5{qe{HsqWf5{WRAdP7F;JO9IZi(hF30SA z?lJy6Z72gB91ia2VR*<^z8vEta#GTsm;X+VWbsV?fC&IKxEulNC9n@%?u4eLp|+Q2 zn|%!c;8ec^G$Y{QOP zsl>7ZTAqZh>3W?vixvH6H1nbS29thw7sx~jG7cCOnTNiEWGsR}Lpk0ROMc|i9=0od_vRD}D_&N0^&& zkO=0T{P@HKDK`=B)NOq1{3nZb87ua8J)4FIj2WDsCEmY6%*%$g5oA;dWotJa?{1wgr1;9~ zv4k7Lm`85|qgK2>B=@dA2Cw!PeA;UP0h?KehY@fiyY77-YyShcMlg~%GFsKVyXluyL&Gn0sslzc~kV(*aJ0L}|SOG;20{ya3m)7T6EM7+cI~j*kHJ+42 zVG6=)wc_;nc-%^HWNjsA;?#{V3qCy~C8P{~k|EDkeP$Z2QEv?b)IhG%YF#9WPK?;J zLWs|rKdA70mk;gK%nf+5GfjF9k#~=z1W9J(|0{r6^P4Afy}mOF)WxxyLIplP0{W8C zOAJVYJIqdNH>)QOC1z7w!y1m1hiYKGjPe*;B)e zyLQNRbN@KV|SWt9aWTR2#p8r%4*w)^w;SFR88FTn6&-tPn3R@7MZ1?t9Yuwux#{EMQM#ArvqwZ`PTB zAH?o`IaO4#*zbv)Ifh~77afcip3ct2mn8Fa1Q}!0ZwSB#oq}6OhKYscgvEzeW!)FY;3L=r$UEuaRO=Q^`^#5fSepP-Mon=B^0>QBRA0QExV7 zgt~BAyN*HY1g7F#SPIjz3&9t$&9*g3J#B5G`^G{rIE1Kh!5)qb5Q`NyXBt;@-QAZR z(r$d{+I<_lK2u+d$J;&!OcZ}#8ov954^7OQ)vej8mVW>e&B;i}Ew^-buEof*dZfjj z($cfDn;8VW^am#>a8ZQSG{c|*iKOcj<4k+WVn0D7k${kH5&|R5@Qay1zu4*+tEcmH zT#uJmJR8D@$^r=?0s{90)_|(Kw-0!4VkWy>!h5v5T2J)SE7TnPabGBEjRSs)TPV%uv8|Keu{;5?mbH_- z*WKA2?l~vpT@_^NInjJhxg#tJ%c!hUi32IS%1hk#&@?-W=I}!ra1liN%OKQ*QTtC7 z`=Hpo3w|jX_LtAg?P zUO#n{AY3(K#E4a8S3@UEMzXnE^^Fevh+Fjgs?9trSwu-JEh{YSc>~zh0$qMeC?uu0 zTf5($JbBUx&C(IOKr_pR0S(u;JoLk-=Im6w`htvRrsn3w;`atVPxv&0;d)WOY|Kp- z2PTN|ZOA<+BX8NizU!@}c%P8(%ku9zy3?hLXo&+GOH%BKIZ^u(ovd@jfCOZwrWTgk zR$B`)CR;tV{Q!BI2DrYVtaL-Ej72{q9-~M+;4Hn=Jeu?FDne$Ur?)<$#p(t)xJ(UmfxB!(o>CxQ6GBK8eZk3IA=L9eTazaE$J*~LiEZ%iFD zq@=gYUI|izjX;Py1qowo8&$1f2f3fHmR$WkyfQ_QRZ?SAB^yWm%>zB6JsJ8vnb(c8 zG#T#q8G{)O*^E8AljO7YQ|~<&+PTcI%W24F`sF&kYUeP?38qiuOjuD-DsO2NUPEJz z>O7Ej%w{Z}ejn+^b#hX; z+Z!}(c{>sR|0~ZSLG(6V<~lC<@skr9>9%&vq});T+MrrmL!+M$*0^>c9?`aZLMzgAjM^fDquk9F%3&-+ z8GA8#p_=qjRAU31ltmAgq=NHZ7^A6WI)zK=UT_Lb)JG}rW|3xHu`i@N*%_z6$XE2l zS>d}&sQzp5#V#3He4EPFD9*T`%f@j75C?`}9}M~W>sMaAlF~(Nr#O`tGIC-r8J=ccom5>w- zZnnG5V*|;hEDY|CZpC!I;$jnwIuqVEIe;%>9}if0cKYDnzwShLddkrx{@$ws+-+ii zmti~LrB!83;>ae;DgqN`mQTQ?XwnGaj@9Ud-i-BEn}>BivC5eY4x jgPfN_W5~ETd6b6P81`q)$X^;UVhLDhM z=^8qQ?s(_>H@xSpd)Ha#uJglvp1q&FpYxxtwi-1BI|Tp$)DZQT`TzjJF9BXM68!tR zFb@j=6v|G@%DNC`WnK?YcLygIdjRmC$}sRVNjPOum_N0rHB$PwSCQiK0pJ%XChMXz z&89;F)?suE;6LF}6h=(U^y%u*_K#x}>KRc>S;DoBFQTJfe}qw7l?T2R(o0k1hIyz#&SKf@X&C{7>fk}&LI0=n)1@6(uEw#E-C|R?L&^eG}`O{NS0*vZwgqrY-Y zySVDG=7Kx=lYQg7=gzOdw?BW=@P&W~pwk|}OA8MfZizAt(5+H`9T8z`HbX zY6&Li)Ac)RH{VkI*tH%arH5{(YXUc&;i1>DB122k73N~h(fcO<)#~zVbq3Vw$G_z3 zPFiBv2$kCBNxmje@S_HbBXls@HKf0KTreTKAcD^{Cd0k}IOI_L3p-^zK<6ke6>tgw z3C-sS@O==_my){-01fMR%nK4(H9N=v;APea(ef9hR4q)!7@G7Jt_BP%fi=lXFqI(Y zIh_&-7S2iW{Z8@=HbacuKcZjdgzQ=LX^V8#Ef1ekuPrc`f7tS1C9%4b*?OlTf}H3@ z7a5~9pIj8ZP3%AZelph7SR#IFb!j9#mv%e!bVrugkhe4~44$0rJj7njEf25B&L4WU?&A#v zN5|U2haS>6e3`U1{}QQU^`8m5P$!G+ipgUm#A917lPA8+9GFaN9GM`&XE@_FnMD{~ ztINl@I5iVZ6Xk-t+XB@L^<>86pTZut-s4Xw(5b!~$Z+27ZzER`XQEmxw9CiMmwDIX z9u1>qg1R70HxjE&!FM-K3PK5SR-aZE&o#(Z7^ZVd*A&`{bM2nPl2yWsc~j!iakOzd z$jk0FESgE~Pt=kodA6W_ZX$!mV|&FFq95O+lv1;b^!f@jN6Ct!VI( zFq<>md$#;LXg0}I%{=0fl+-T62NO~psg7T1zq&(BL{CJ6nB)I4B*`TiC50rd6&XUk zpo(JwMU;j=p|n3OjDqu2p;fxeh2*0wKgSBWpuY=cO8fQw^bxuPdX_m&me(IIY^f_F z!d0^()N>4N(H(3td@LPO_WLGE%wQS5P&$l&wi7z>PCEsfrD0>w-6g$K_ zWURjH1JQI;EbPfnrfc-`^;7r17bg@~6t5V6TjEd>Qu1UfaH?s_X2)}fWoK&&=i`w9 z&JfEumUERm^&zj9sn@Fyub=iA*i;y?-3r(sKmL16voSlQcIW3y7O13+M&I$#RB@CH}&!DZ*qnpIrnOXb|W2^AN#W^I25~c+7wIA z+0QsXx3+PTn$B&{{ex{1=}UA@bEqGx9`Ww&?Gl?Q{#V?+9VaiXr3XTVh+T z((a3Loo8BNLWm5D92>YzJ>0(9rr1u~CfSiau|Bzb;(9W`)yv7iHU7-|S&*lC8$>Uxe?VXw|z3W}h$VcV39>%RnTKHO+T3j}A>r|x+ zWsW~^?V4^kTWIWgZzZQ7Z-3FhL8#E7K=3W_TVzvS6aTz?lR(ILNNNb_Rp#Zhi=J!5 zS@UAR0n5HNu@$HVv;u1U!2Y3%(3y~jD3$03>0{y;;@>2aR0_;WROHmAJe~>e7}f)h zbK6HVj$&y;%zw!;m|t^TJm?kDGueJVCyj5WPeGU6n?3DHvP87)7P>1t&6^k?KY|wURzZA!9Vg$ zWj}?%n^BN_=Ra)wzjpcmmc0npT+$w;W77Fl#$<%>5FI;uV$ zkH~fO?+3)QA?pMVwTxbl&lL|$zMB-6O-xTr&(WuLO0K>?@c=E1)^WIhKYuu{RcC0uhTr&_;Mmxe`Cvf#eI*&Q?gTJ=Wt*Q1Z-9d0(y1t>qV1U1H$ z>(-W6{j2pi-Cy8uR{6~$@Y#UXPvRj=zuwN@X>T~V=S@##^0n@gi9Yn;ZNSVytp2Cr zA3v1ue>9d(DopI|aVtG~U1!T|on!~ay-gW2GYS=DO|mTZC@v^HD_5;uT{70T91A)Q zaGjc((?I{-*;3!i-Eu2FHEk}_Xngx(Y%pSvx`bmtW`)DjRb$Tkd*IvS*uLt%zkP&{ ztsn20_0|+mAAFa|ISI@Nh4mO+m;6LGO$tqoH_!ULKcxA@#r$jzm$=>V>%PCSbE8V| zvD@(O$5{ls4M%}OvL*i?@3Qoa9eM^-CbtNnwu-hUG-&RxYgx6R#0&F zDb!Ay-!G5XqBN~9R$A`O=LNlA)?NSJ-!{|MH=i1cJ|^2z54b-p*X&a)p5vM&|Gg2n z{v{`a%YsX-34I%ad$?@t)A<--oSBs&EWdw_{g|+vZ_4AX-( zIw}ujDzbX-YN9PqyAS8q5U{-lk0bt5o9VmgS0(bL@@gR-*Nf_9X6{?|r#(By&r7|J zw6>lN;YLC)-eShQCe9`#VBZ27aUI(nXg8r*&f2^6$7jALJFI>byP7kwK!ktURnye< zCg}z3W@z19@zCK zEaq3{GYF}e-d^7^?pf4y}1YQW^`-yY@p=Yi(ZfWkvh+|R-?xlVyjo`(Ja`Te}B zlK$ynTrIACzO#`hRrm^gqkA}XVcVHMsB@~Y7IbqZc^YTlM?!U?e zj~0itFnX_*)ut>QzKc_mi4JP3a=)7k->~ zLzAx8&k=)l07Ir98MzK2drT_iypwETcOV$_)ZPqv#8wcU{S*>G7)6pbwd0E@-QrT1 zI*+F!9%Kd+z|{dJCE+IlZ=ifH9{_EcbHFwbmMvVLvNJCy8pZ`KXprE9yP>DU(ON}C z7x7eyzTO}@A;lJ8eQhoOZJI+vFc6@KQV%`Z5_`nca5Qr%%BO};7MFQq=fQ9saQ@mY{h=?FB zD#{#_E*WzcIvVkj=NA=ydpz~aSuH6sG3b};bPWh7O?7<27p6RM`~V7FV`gH~{2UXb z;^p{7YGhd00=7HhtE|_m<@EG) z{*+5i6*nS(?3u871aQZ|#N>?U`}gk!1qDxGrltX9DOyS+(#A?ktsVa{-c!K({`TP` zS_uwVz<}&W^0ef!kGVITg}doxWo4a*hldHaeV?6dPqx*0tu^Hd|J6sbs{6(nf^r)U z{@%yco0rlcTVIix8XG%GiikjnbOpk7Dkfd{xDk%Jfq@sBy}iA^TU%RoEiDnOmO=Z= z9UUG2$)I+e5uGD83|rdurLF>3WPZog6=$W=>503@9${{m3O~r5(`-* z0^RxTwWe(Zh0=rBfs~Eg9Uzc~^XZa!nQN^I1c;gGi#k6 z&H|a+xomxVbL~eMbqU{bc(heUwo0<>+1`h zJfT-wmzTKaTX)X}=te#z2Ghy?zSp+;;dY(p3Pny%&h3(OkXT5nFi;;J5#h$yP0lEk zjugq89TlR(jHacrBkk1HyQ~4PNLrpbFp}emn;`tV)B_NPnUS%|exelS;^f2!$q>xf z`4+;CDGMSpJ8B3xERDmyl5ET+G@-C+8!s_~Aa&%AMw8F+T*R~a0`nTE7HN!F=NZS5P~x*j4EHd z9Praz!uSJ|c#g%8>)t}kd-clf?2kY)s7q2*)J9pEu&T1M=>d6BjzPZmX=Fr16B`@b zxv!laHaRLPs`)8rtd2u}dSSesgTty*Y7GaQ1pq(q>+5rIb{2ro0;_^TLgPrgfB;$0 zjQat)s?Wjf6;ew}i%6H)%4ohRSSJBH?cS^f(30_)k1x9~lJY7jD$a}ZoY;GEIcsYP zTwPy3iN|KjzbCUQGB+q4mX5&>q6hQRJ#{uVHZqBciR-VD#Wv2c2|CgVK)XLVoEjs~ zA>+aeQB_fCq~vA6l#3YTNylNMnePjK8YLrheEG7yqq0)U!QP%8(+F^r(bCRqBd2Rz z1>p1k<%!(fTv6mqwG$&Kw`<9yA72mDkk%n;}M!Rs8j+(B}lz=&d-=EFlJ_6eR|1;oEu$5|4FR z$w$;EDmg{qp@8a_GfNRq=DNDN7$Hz?PmfS2u>AAqPg5hK@d~S!kFj_P{|_ynNNE*l zcp)SOd@LK&X!j?T;TOZh`i%_@>BPjuJ5s0(YX&OZ_I(2IT%kd}|H-x~fv|M`Vcy+= zPdzD;_aH*|?mYqdhi(l2a6@Xodi679*_O<10#BXMIP6wgvo=sDm2);*VcV&W1c5;A zUGL4VTK(t)so13KBq1kT6YglelGE2Y^Rf=TU#|sCU%%D>KG{*E2d@wE*_xKWi2iuK zctSepK3Qo$e-BWCLQ$IW%65DAsJY~-lLdWXjwUAm9C%Fs<9BQr+!)EXd^lbo5D-9A zKI~968}5#7<_C#21f5HL3qF|?0uU>!s}>K$LA(2+1tdUMqxS{_q_U>ty^u{+kOep9BlhX!POwP)>14$>RxtlzNDBL{rb6+>?#0zXjg*$ah&c%Sq0XQvBtaBw(PO)3zUuQy%pUal_Tx!{(>7WGGx znJ-Kco{NWa=F@kr!bUy^ZX^r+YCOS5UPwHCsX92{=R|vODo#@P4JE6@ z(dgJ1J(wI$KA?CTlpv-l16p76c-k9sNlZkf*)uTEoQOhAlPuf?3>X+02U5q!BsIS8 zkv`bpTWm}G=*bMGhcml3oeMz@!dWfeBtNS5+kZrWd7I-wW>v#Pfji{l13Y8IZ2u;T zWMZ+{Yt$2WnagLI6w!PQBKSPall{Rb1%gyVaF0PM&CqUUVxU_2if&R~CU91^aL8V; zRo7QGV%(+R>kz6k?c)~LWiO#9t2aP6NW$=sJPjGpI_@2%4)I< zMmEHZsU_tJ+Ou+U5-~2b(28t(_pjW5MY^rnlIZE_f7F*oww(GR zsKJA|kOV2v!mkO7pMVGb{O&K*MnP$*0tk5b?p++M{}Uj%-VYaxPx41>3NRC@!_WWo zVgn`P8o06;$v{W=SC^U&R-=uZm|9=H< zQ7%Wyt=n$0w(6CmQ%4qSOA+;@=%widAItI4QFFxG-?KWgCAv&1Ab4^z3-IQUFIKrT zhJzIVwkFDM=`hSZw!(mLW8m>70l+F@4!~beo`fxyjcia!?`TBr?d@3rOEvEEH$$U^ z25LGenH_8NbYq!ib4Wo+332x)V5)?!{+eu{zh422#0U1n=}BBFFR<*lGi6`>-jF0) zk^s2+T#>@b$Y?-mWv{B*p)yiw6^EGY0rAcyg3??4&>&YJJ0?2R$LBF49_YDwdE;NW zzWEza0}|HM)^1Wqeha;k1=+o_F26iKp9L+< zV;LMJ;2*ma?xB%(zP`Sc@K9EzFqFaW+1Xi%;Q305B?HC?D9iit111%-^+xvcKCr8< zp>g4koGG^^1U1kslyE)s)n(a;1!_lna2`g(lL zSXmA7I(&I{_yq(6Zq<>drlyvuKUbf0v((da$P{;&7-Y)%L<>&N%xI?c*caam{&CW% zp`oFU#5>P?yVWfJUu^h`sbD=LBUN)nQmZHA!(=&|?iR~PyP%+}c{|J`R?vlsEk>X= zc(o5TA#8v<1Z?a|Fk=4A;t~>h=;pLMdd#;*(c>2YH>@%6aZD@f-QZe=-y9!2A6sGn z$XY~1B=j+tug0I4$g*A{0{=I7<(RLC6tuOq)d9|u7C(vcpKv{KOP_vYyFIS{&YaiJ zh3UR|$f{2R?qyNmDsJC@x8peBZOZla_35vg8jF?~#|>h5|G@LZ-f&2Qko92J3rdg} zsRwzJC750YC5~C%pP^@F{^dDdY}!mtL80HD@yxHJynL_uwVBx=lZw-*&vhCC7O?;# zByovBAZTwkf0msXL!t8bM~tg#k021pxh>w@`M@TiRn$dAoA_Ghdb3?Mph{RPYT)+A zp(;G^`TuGkHbqKGiUB6U%FfO{6&)RY<9)n2W{fw~0*LyHgL?%!-xQj8r0lw8@j9cZ z4~0HfIdQFqy2_Z{n+%=9({mYrbaQj__2I#R41tMQSS@&X<+|qpEc4_6l#2B($}) zcMF}^6|Rp)>MJWNgH-fx#1K-bfh|(+-I;(P0mO5p=lbCHn&8V5dxEEw^OA~%MMV*B z(~{GZlWRQi0uhXl+0fwNpq{z;m79UVNKaAGxO3XLSg@`klzK?I#8O{hfB$TM`I3}` zWC<^T#uOA37R2QiQ@9$Xbs0wB{0WLmVcGQ|j#UxgyHUMycIM!9Olee#x{vnf#rKC2 zunEGIFKd|Ns=dDGZ1XXn*@-}Xyrs!^N`vM7*pWe%%r5WOHn#s++4tYBw8WWq6K0u0 zq3ArPo!b4CufTb$cHGhAH1{`mE_|E^rTcU)7EY`a^eoBaf;q0yKy8t*Mip(SYu-tR zei1PS-<(#R_Q)xbJ%i+PrqFCya=6{(sa_MsST-k!-q$%PSF4+*y^A}OQ))_m3*syGgDI?rcZ231+d~4Qd haeZ2iK4aSt6_X$#O9yq^;BO%Sh>G^hQYEX8{|8hvPig=F literal 6203 zcma)AhdMLwl007ilnn*(cV9+VxrXYhp&r6Dypabls zp~gK>F~qSBU69%7XduDmf3LTg;uPo(rMsrtO8~Ai{P%`|>^H2?O>$2yJ$3S_D>O7x z*8}12lL269)tL5arY3fn&4P)45}!!#^HFipRK@!K-tdks;JB;ADT1Tm^6wxp!zN?TubuBV1nn zxkC&G+$1Wpm(6Ji7O=O2c_x|4$9{D~HK4ElafJVrsl!ZgOto@tJo|#GB|dKNSF!)N zC$9p*>pSg6JL`#`bDO+Xa4837eKaoi!!S6bdQS?cvQg33A3}7;vCBv)DP2^gr!$iW z5WQ!UyahOwJuZ>b%%Z@MMZ0)m@8X%K1yj++4JHu^y2@*YLcNrm0;{(>QWm zjWktJz>N71*G|F0HZftVH!bpD&i_*8n43&+FZ-`NZ;GSI28s@S@Wu zhrA^B@%Ly=K7*A)M8E^i0iD+@R%e;3nt=FZtJ3_C1egFlpbIz#5(LzkKh6upcB^$T z^iaJ`+D!IKiZc*QutkW;@gKJjxGl&0?sf=myzKKw(muKFKT6sd$e3~bgiz~FkY4Fv ziMU9i*5yN|KIx7R(n5ZL4xFHCXKCbPs^S&w$wZlHrLxZ-+_mEG>mG8sLoZi{a?Kh& zmgT@AAqS*clq{=qWv8Zky4}Cu#f}f$*Ygev3JM!^bR|vfS%|EA9nDNVU+2)Dt{AW} zepAiWwM?B+y{fi$A~`oVNa5~X!ZEmC<>9J0zA((NyyCSvsc2znnCw<-ZlV4#^_g@| z`Ij$W))pcWRK$!2vIkel_U;u3 zUWugPG+$Lu_n5H-5yY8)|87>cSs5A{I#)f)R)5HNLo0c}asL`n0|$n_S1$mM8|HA* zdUbi3v#+&ix5*S#;GMr=dVeWo2c9^e3*+ z)3n?4>dB??Sj9K$+;>GjsVH{CB$SAB47x5ae`=(sH^{`p z1Etv<<9~SdnPw=ap}S8hF7x)2E(T6cPSLE4g^ox(Id|7pG4qvuF2ZSL>)+B}C%cOT ze~glhfPlb^jrbcu5fOzisM)40E~=y!{|FeXqSwZ_I*aIISsmn(N8_uFjg5T*fe;ZI z8d^zUml6vLL#N4qz?TttskqZs-mNux92b+ zF!6Wf5mOqYxjlmr<7Us!eWaFTEOs;hNKWJ|A*@8>g1@korMko zn8?cQ$AJfHqk%jHeSLk}V#{hU-2v!~ho`T*+>WC5m4Cp|+M5!Dz){XTF{GB?iXD_#>b2Mj!;i!cw0t@I17@AjoXDwshhSS}|%o zCMHILr{MWaUC=;^8&5x9dYtKJmScGm>{|;|qXSX>-6-lwao{3`IT%Cn6!_qSd}IP% z_Q6&9t8-U8A0TKf8P*tt|-lWiw*#<;uR1-hK2C;GDtk#oGgE-cJJQb-}tsmn}7cK?m%XZWLhgEhNq{d zrcwX_{Wr3tZ)sE%FS!DLbw+=EvDg)-udkn8-WspUd2QNz;px*VV)P6ik00x3rO%Lp zDny}oYnqi~pB!#zVlqhqB(EZCEX5}VMENfl> z{W&TsDkuGx#Ze{%eKM?6EN%}ja=mnt8QW8oQXRhcfwymx9vA}jj&YgE>}|(^Obe)* z^efG3_%r;j+F31qidlk%`_xde8RRR?ep1C9z zzkqOXlz#E+Tq)PdSqQg=4h{}5SH`EeY$rAqZLnw@(?Y zM)lp-D=RBO*1?43mG&_5gvB(ao-lIwZKt6(cp_|99J?@A!0#$bh{XKm?%dg5PEfu$ z$(lhm-@1m?d-mWA!+KA^NiMZy&WeFwmo+mnQGDh1bPYaN-lt+x?Y{bu;TL8`MpiKY zjm5ep!*u&LxL;IUjPI9Au4EN(U~Z?zI@C=628qeZ5{WFa;=mTFOf|qQBqU_`PNNk* z?<6gB9R#N(CGCn5KeVp0;9PIt+*$SYDT1hqj!rLAeBlM@6f=p9rk&j{4<4S#j)kSn zF$Orl@Qbtg_Ar)1agqn=Y5Uz563Gg7ol)N)ObU;3hHBT%k3zZS+fEfC=wP&Fd3jm= z)~#F5rE>-e5V>!Jg@$t3cv^A>^u6oZS^r)v<|UWQnU$5L0UIFN`N%`^Xk4A*t;6w! zw^lL^i8QTvd>h(<2`YResA&Is1oC>7z#t-HtV8%fSeF@86!9nmuYk3g%Cnl_gI8-FeMrf)|MPb-m2=zRve{%9dpNPuv0~}J)dnlGzM)?aCS$QKC_3_ z)6eSY={Oa9cV2?UsYkAii#zgnH|ISXJ1v{N&xc3esbwT^DgG@{3^)qB9#a4@cIR?` zMkT3usOe~hJsnn}x!+lG5(@ecDA^&~u&YgE@UWn0b% zKdw8$$n@UG?p_oX@uxf^IrI-2g*IcCmy_$PtCMbD_RxyGL!eS&5q{T_(q9>gO8$g? z^8NdFYhIqd!NEb>gS&mN-(D*Ff!tF{fXjuJ2GU-VEsmI+=FRYZk%pWRt*m}7()s!t z$HAYEEi7F5dF1>L)^6*ohL@@g%mMnzO6$uj#igzGq!>=@6A7{1-CcwIjcY5mhg+VD zejZc~Kr~`G>u5|zEC`7lA0M|Tb0-g=GB=3uh5FihA9>1D@y9yz@VM>r+=8b7Dg+Px z#c-cRYEoj>M&I3EwMZl+&Tarh%vzX8WEHy%>dXMDPsf@@ul2DH+Yu2FO6O~Z39YV> ziY*Xq`mf)&tXghgLvl*FjJ+qPA`6>ytf_s$w!e2q*l%-}60u6Z_% zPESvZ8DvQ~?4=2tvN;ZBr{(46TYpt(!1Sp2MO@chNSC`dAQ^Hr?UV*antitCTZ2x? z0(L%0f-`a|RyYER{rJ>WLuiyYd=$lFE+BJoevDUc_FNxJQ+QX)r2uYhqr^1t;!yR? z7>uP6%$**6R0K5#aCUV~skeN6))0HYkO>e$tEI>AR?6IeY?lww`x>MnX6oIB4?-`5 z6~E4BW@bJDvc5Yu;Y4qq&xi0zOV_p8*@kAs>N22TgCUqW(PzcoPKHI8O63oyV->NG z7i22rZ}AYduuT5=vCX2ss~Hq@exa8mt=L%>RzFq$@-ytfqBW2Z2&N$U<M?^p}|ABk~)d7NG=*85za*LnhLdDO5i5X{pBGL;b!UEa11%0eon4%6vyY99)#WPq?I|29hGN(aN_g*X-P~?RV6F6I>)HKJx9Yoz(U4Ed z99;4K)@k%-wBE?rIJe1n*KQEfL2;|Y`7$QP#+D1IY+xQDxi~X3vn($DIt4OJ1L8I= zQu9v$BYLVE5u%Vq?UKuY`nh;DH_FLKemuIHOR~{WpK0 zm|yK2ZvMd2(bJDLx3shrw6?Zd*T1!9})XmSY& ziMdaem6aTK9CefXp8r zg(Citj1=kTHuWsHf02=r%Hr3{{*vvNCFQZyMTMejAY0z(}g z9Rmis=hM~8TcWrSvxKjJFHga549hy^;wOMW-++{>;0+!*zrFV`(_!CN3x8`!Y#aRb z7o>rUdHE6E`}fqYDdbA&NmP9|N{X%K6Gchd=Jiyps8uX1W~9j8LOm`|%-xOBA`4SB zK&Iy9U9bs1%IBgmBSWF4zqovNZ8^4va)%-o8K=S+`7m{nZR5o{1a=0VT` zwMl-;X~@~hZYhLe>5MEas}QGS5)d?1&Qq3c>zL!Y0KJP=$V#7&eb8Yp9CfZJD|0O^ zFPEBrCQVK^3YF&eV%mhY1Ngf&UE}m2Fdb_zAqCOzud}l=`m%|qi;C+~&|C#W`{U2M z$UX+jh3JvE+2M>YVP3Oo$^MX?KzgHD9DbsE$?p9cy6XT zn4AABz~LTa_9SgkD3l2l;Cn|0_Y?uT9YjDwLL-KxnRU-5C^oT>iy`pbxUsA{wXNA@X^AC_nh~^ z?}6IA6>b7YLm&dpIg2NUWBZuO1cecqNwO=R?wr&yCkE1i=TkPl>r#j1xA(4{$OQ}6 z@Ap*{?}?(}>WcbZw+2pZn>|c3LInxy!}lv?LhwWLlT5UaqGDmMYN)<4#)wvNSUgIf z8|nyX{-GlLM5>|b&S(J^^ztq_5oyo|@bEeb2=KF7k${``Z;ewPClmhlT4h{=A8MWY==Z zU%fGE=?UmfQy}+VVD4L`mfPtlSF-%q;38(?;n!LjqQfO^AqP2w;!>T#u%BTR4-~37 za98g3o%{IQp~*vyuir%URUMf2R0=Q*e~(k@%ZX}g%GD|%@3VMEVtlGJU-?>=Du$7% z#87>$%j?jTD)oSuHvf`di=>Gt>B=rvf From d5800b84054602bb32518665ccbbe9d84b529f4e Mon Sep 17 00:00:00 2001 From: Ngo Duc Hiep Date: Mon, 21 May 2012 20:07:51 +0700 Subject: [PATCH 2/6] Add files to branch gles2 --- Example/libs/cocos2d/CCGLProgram.h | 156 ++++ Example/libs/cocos2d/CCGLProgram.m | 395 +++++++++ Example/libs/cocos2d/CCParticleBatchNode.h | 99 +++ Example/libs/cocos2d/CCParticleBatchNode.m | 473 +++++++++++ Example/libs/cocos2d/CCShaderCache.h | 60 ++ Example/libs/cocos2d/CCShaderCache.m | 214 +++++ Example/libs/cocos2d/CCTransitionProgress.h | 62 ++ Example/libs/cocos2d/CCTransitionProgress.m | 276 ++++++ Example/libs/cocos2d/Platforms/Mac/CCGLView.h | 92 ++ Example/libs/cocos2d/Platforms/Mac/CCGLView.m | 287 +++++++ Example/libs/cocos2d/Platforms/Mac/CCWindow.h | 41 + Example/libs/cocos2d/Platforms/Mac/CCWindow.m | 69 ++ .../cocos2d/Platforms/iOS/CCES2Renderer.h | 83 ++ .../cocos2d/Platforms/iOS/CCES2Renderer.m | 248 ++++++ .../libs/cocos2d/Platforms/iOS/CCESRenderer.h | 54 ++ Example/libs/cocos2d/Platforms/iOS/CCGLView.h | 160 ++++ Example/libs/cocos2d/Platforms/iOS/CCGLView.m | 360 ++++++++ Example/libs/cocos2d/Support/CCVertex.h | 36 + Example/libs/cocos2d/Support/CCVertex.m | 138 +++ .../cocos2d/Support/NSThread+performBlock.h | 22 + .../cocos2d/Support/NSThread+performBlock.m | 76 ++ Example/libs/cocos2d/ccDeprecated.h | 219 +++++ Example/libs/cocos2d/ccDeprecated.m | 328 ++++++++ Example/libs/cocos2d/ccGLStateCache.h | 143 ++++ Example/libs/cocos2d/ccGLStateCache.m | 226 +++++ .../cocos2d/ccShader_PositionColor_frag.h | 12 + .../cocos2d/ccShader_PositionColor_vert.h | 17 + .../ccShader_PositionTextureA8Color_frag.h | 16 + .../ccShader_PositionTextureA8Color_vert.h | 21 + ...hader_PositionTextureColorAlphaTest_frag.h | 23 + .../ccShader_PositionTextureColor_frag.h | 14 + .../ccShader_PositionTextureColor_vert.h | 22 + .../cocos2d/ccShader_PositionTexture_frag.h | 13 + .../ccShader_PositionTexture_uColor_frag.h | 16 + .../ccShader_PositionTexture_uColor_vert.h | 18 + .../cocos2d/ccShader_PositionTexture_vert.h | 17 + .../cocos2d/ccShader_Position_uColor_frag.h | 12 + .../cocos2d/ccShader_Position_uColor_vert.h | 19 + Example/libs/cocos2d/ccShaders.h | 45 + Example/libs/cocos2d/ccShaders.m | 65 ++ .../kazmath/include/kazmath/GL/mat4stack.h | 51 ++ .../libs/kazmath/include/kazmath/GL/matrix.h | 58 ++ Example/libs/kazmath/include/kazmath/aabb.h | 53 ++ .../libs/kazmath/include/kazmath/kazmath.h | 39 + Example/libs/kazmath/include/kazmath/mat3.h | 75 ++ Example/libs/kazmath/include/kazmath/mat4.h | 93 +++ .../include/kazmath/neon_matrix_impl.h | 41 + Example/libs/kazmath/include/kazmath/plane.h | 70 ++ .../libs/kazmath/include/kazmath/quaternion.h | 113 +++ Example/libs/kazmath/include/kazmath/ray2.h | 50 ++ .../libs/kazmath/include/kazmath/utility.h | 74 ++ Example/libs/kazmath/include/kazmath/vec2.h | 64 ++ Example/libs/kazmath/include/kazmath/vec3.h | 68 ++ Example/libs/kazmath/include/kazmath/vec4.h | 68 ++ Example/libs/kazmath/src/CMakeLists.txt | 14 + Example/libs/kazmath/src/ChangeLog | 738 ++++++++++++++++ Example/libs/kazmath/src/GL/mat4stack.c | 74 ++ Example/libs/kazmath/src/GL/matrix.c | 191 +++++ Example/libs/kazmath/src/aabb.c | 63 ++ Example/libs/kazmath/src/mat3.c | 372 +++++++++ Example/libs/kazmath/src/mat4.c | 789 ++++++++++++++++++ Example/libs/kazmath/src/neon_matrix_impl.c | 97 +++ Example/libs/kazmath/src/plane.c | 175 ++++ Example/libs/kazmath/src/quaternion.c | 582 +++++++++++++ Example/libs/kazmath/src/ray2.c | 184 ++++ Example/libs/kazmath/src/utility.c | 59 ++ Example/libs/kazmath/src/vec2.c | 118 +++ Example/libs/kazmath/src/vec3.c | 310 +++++++ Example/libs/kazmath/src/vec4.c | 154 ++++ 69 files changed, 9484 insertions(+) create mode 100644 Example/libs/cocos2d/CCGLProgram.h create mode 100644 Example/libs/cocos2d/CCGLProgram.m create mode 100644 Example/libs/cocos2d/CCParticleBatchNode.h create mode 100644 Example/libs/cocos2d/CCParticleBatchNode.m create mode 100644 Example/libs/cocos2d/CCShaderCache.h create mode 100644 Example/libs/cocos2d/CCShaderCache.m create mode 100644 Example/libs/cocos2d/CCTransitionProgress.h create mode 100644 Example/libs/cocos2d/CCTransitionProgress.m create mode 100644 Example/libs/cocos2d/Platforms/Mac/CCGLView.h create mode 100644 Example/libs/cocos2d/Platforms/Mac/CCGLView.m create mode 100644 Example/libs/cocos2d/Platforms/Mac/CCWindow.h create mode 100644 Example/libs/cocos2d/Platforms/Mac/CCWindow.m create mode 100644 Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.h create mode 100644 Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.m create mode 100644 Example/libs/cocos2d/Platforms/iOS/CCESRenderer.h create mode 100644 Example/libs/cocos2d/Platforms/iOS/CCGLView.h create mode 100644 Example/libs/cocos2d/Platforms/iOS/CCGLView.m create mode 100644 Example/libs/cocos2d/Support/CCVertex.h create mode 100644 Example/libs/cocos2d/Support/CCVertex.m create mode 100644 Example/libs/cocos2d/Support/NSThread+performBlock.h create mode 100644 Example/libs/cocos2d/Support/NSThread+performBlock.m create mode 100644 Example/libs/cocos2d/ccDeprecated.h create mode 100644 Example/libs/cocos2d/ccDeprecated.m create mode 100644 Example/libs/cocos2d/ccGLStateCache.h create mode 100644 Example/libs/cocos2d/ccGLStateCache.m create mode 100644 Example/libs/cocos2d/ccShader_PositionColor_frag.h create mode 100644 Example/libs/cocos2d/ccShader_PositionColor_vert.h create mode 100644 Example/libs/cocos2d/ccShader_PositionTextureA8Color_frag.h create mode 100644 Example/libs/cocos2d/ccShader_PositionTextureA8Color_vert.h create mode 100644 Example/libs/cocos2d/ccShader_PositionTextureColorAlphaTest_frag.h create mode 100644 Example/libs/cocos2d/ccShader_PositionTextureColor_frag.h create mode 100644 Example/libs/cocos2d/ccShader_PositionTextureColor_vert.h create mode 100644 Example/libs/cocos2d/ccShader_PositionTexture_frag.h create mode 100644 Example/libs/cocos2d/ccShader_PositionTexture_uColor_frag.h create mode 100644 Example/libs/cocos2d/ccShader_PositionTexture_uColor_vert.h create mode 100644 Example/libs/cocos2d/ccShader_PositionTexture_vert.h create mode 100644 Example/libs/cocos2d/ccShader_Position_uColor_frag.h create mode 100644 Example/libs/cocos2d/ccShader_Position_uColor_vert.h create mode 100644 Example/libs/cocos2d/ccShaders.h create mode 100644 Example/libs/cocos2d/ccShaders.m create mode 100644 Example/libs/kazmath/include/kazmath/GL/mat4stack.h create mode 100644 Example/libs/kazmath/include/kazmath/GL/matrix.h create mode 100644 Example/libs/kazmath/include/kazmath/aabb.h create mode 100644 Example/libs/kazmath/include/kazmath/kazmath.h create mode 100644 Example/libs/kazmath/include/kazmath/mat3.h create mode 100644 Example/libs/kazmath/include/kazmath/mat4.h create mode 100644 Example/libs/kazmath/include/kazmath/neon_matrix_impl.h create mode 100644 Example/libs/kazmath/include/kazmath/plane.h create mode 100644 Example/libs/kazmath/include/kazmath/quaternion.h create mode 100644 Example/libs/kazmath/include/kazmath/ray2.h create mode 100644 Example/libs/kazmath/include/kazmath/utility.h create mode 100644 Example/libs/kazmath/include/kazmath/vec2.h create mode 100644 Example/libs/kazmath/include/kazmath/vec3.h create mode 100644 Example/libs/kazmath/include/kazmath/vec4.h create mode 100644 Example/libs/kazmath/src/CMakeLists.txt create mode 100644 Example/libs/kazmath/src/ChangeLog create mode 100644 Example/libs/kazmath/src/GL/mat4stack.c create mode 100644 Example/libs/kazmath/src/GL/matrix.c create mode 100644 Example/libs/kazmath/src/aabb.c create mode 100644 Example/libs/kazmath/src/mat3.c create mode 100644 Example/libs/kazmath/src/mat4.c create mode 100644 Example/libs/kazmath/src/neon_matrix_impl.c create mode 100644 Example/libs/kazmath/src/plane.c create mode 100644 Example/libs/kazmath/src/quaternion.c create mode 100644 Example/libs/kazmath/src/ray2.c create mode 100644 Example/libs/kazmath/src/utility.c create mode 100644 Example/libs/kazmath/src/vec2.c create mode 100644 Example/libs/kazmath/src/vec3.c create mode 100644 Example/libs/kazmath/src/vec4.c diff --git a/Example/libs/cocos2d/CCGLProgram.h b/Example/libs/cocos2d/CCGLProgram.h new file mode 100644 index 0000000..363aafd --- /dev/null +++ b/Example/libs/cocos2d/CCGLProgram.h @@ -0,0 +1,156 @@ +// +// Copyright 2011 Jeff Lamarche +// +// Copyright 2012 Goffredo Marocchi +// +// Copyright 2012 Ricardo Quesada +// +// +// Redistribution and use in source and binary forms, with or without modification, are permitted provided +// that the following conditions are met: +// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and +// the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions +// and the following disclaimer in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT +// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// + +#import +#import "ccMacros.h" + +#ifdef __CC_PLATFORM_IOS +#import +#import +#elif defined(__CC_PLATFORM_MAC) +#import +#endif // __CC_PLATFORM_MAC + +enum { + kCCVertexAttrib_Position, + kCCVertexAttrib_Color, + kCCVertexAttrib_TexCoords, + + kCCVertexAttrib_MAX, +}; + +enum { + kCCUniformMVPMatrix, + kCCUniformSampler, + + kCCUniform_MAX, +}; + +#define kCCShader_PositionTextureColor @"ShaderPositionTextureColor" +#define kCCShader_PositionTextureColorAlphaTest @"ShaderPositionTextureColorAlphaTest" +#define kCCShader_PositionColor @"ShaderPositionColor" +#define kCCShader_PositionTexture @"ShaderPositionTexture" +#define kCCShader_PositionTexture_uColor @"ShaderPositionTexture_uColor" +#define kCCShader_PositionTextureA8Color @"ShaderPositionTextureA8Color" +#define kCCShader_Position_uColor @"ShaderPosition_uColor" + +// uniform names +#define kCCUniformMVPMatrix_s "u_MVPMatrix" +#define kCCUniformSampler_s "u_texture" +#define kCCUniformAlphaTestValue "u_alpha_value" + +// Attribute names +#define kCCAttributeNameColor @"a_color" +#define kCCAttributeNamePosition @"a_position" +#define kCCAttributeNameTexCoord @"a_texCoord" + + +struct _hashUniformEntry; + +/** CCGLProgram + Class that implements a glProgram + + + @since v2.0.0 + */ +@interface CCGLProgram : NSObject +{ + struct _hashUniformEntry *hashForUniforms_; + +@public + GLuint program_, + vertShader_, + fragShader_; + + GLint uniforms_[kCCUniform_MAX]; +} + +/** Initializes the CCGLProgram with a vertex and fragment with bytes array */ +- (id)initWithVertexShaderByteArray:(const GLchar*)vShaderByteArray fragmentShaderByteArray:(const GLchar*)fShaderByteArray; + +/** Initializes the CCGLProgram with a vertex and fragment with contents of filenames */ +- (id)initWithVertexShaderFilename:(NSString *)vShaderFilename fragmentShaderFilename:(NSString *)fShaderFilename; + +/** It will add a new attribute to the shader */ +- (void)addAttribute:(NSString *)attributeName index:(GLuint)index; + +/** links the glProgram */ +- (BOOL)link; + +/** it will call glUseProgram() */ +- (void)use; + +/** It will create 3 uniforms: + - kCCUniformPMatrix + - kCCUniformMVMatrix + - kCCUniformSampler + + And it will bind "kCCUniformSampler" to 0 + */ +- (void) updateUniforms; + +/** calls glUniform1i only if the values are different than the previous call for this same shader program. */ +-(void) setUniformLocation:(NSUInteger)location withI1:(GLint)i1; + +/** calls glUniform1f only if the values are different than the previous call for this same shader program. */ +-(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1; + +/** calls glUniform2f only if the values are different than the previous call for this same shader program. */ +-(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2; + +/** calls glUniform3f only if the values are different than the previous call for this same shader program. */ +-(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 f3:(GLfloat)f3; + +/** calls glUniform4f only if the values are different than the previous call for this same shader program. */ +-(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 f3:(GLfloat)f3 f4:(GLfloat)f4; + +/** calls glUniform2fv only if the values are different than the previous call for this same shader program. */ +-(void) setUniformLocation:(NSUInteger)location with2fv:(GLfloat*)floats count:(NSUInteger)numberOfArrays; + +/** calls glUniform3fv only if the values are different than the previous call for this same shader program. */ +-(void) setUniformLocation:(NSUInteger)location with3fv:(GLfloat*)floats count:(NSUInteger)numberOfArrays; + +/** calls glUniform4fv only if the values are different than the previous call for this same shader program. */ +-(void) setUniformLocation:(NSUInteger)location with4fv:(GLvoid*)floats count:(NSUInteger)numberOfArrays; + +/** calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. */ +-(void) setUniformLocation:(NSUInteger)location withMatrix4fv:(GLvoid*)matrix_array count:(NSUInteger)numberOfMatrix; + +/** will update the MVP matrix on the MVP uniform if it is different than the previous call for this same shader program. */ +-(void) setUniformForModelViewProjectionMatrix; + +/** returns the vertexShader error log */ +- (NSString *)vertexShaderLog; + +/** returns the fragmentShader error log */ +- (NSString *)fragmentShaderLog; + +/** returns the program error log */ +- (NSString *)programLog; +@end diff --git a/Example/libs/cocos2d/CCGLProgram.m b/Example/libs/cocos2d/CCGLProgram.m new file mode 100644 index 0000000..6602945 --- /dev/null +++ b/Example/libs/cocos2d/CCGLProgram.m @@ -0,0 +1,395 @@ +// +// Copyright 2011 Jeff Lamarche +// +// Copyright 2012 Goffredo Marocchi +// +// Copyright 2012 Ricardo Quesada +// +// +// Redistribution and use in source and binary forms, with or without modification, are permitted provided +// that the following conditions are met: +// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and +// the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions +// and the following disclaimer in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT +// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +#import "CCGLProgram.h" +#import "ccGLStateCache.h" +#import "ccMacros.h" +#import "Support/CCFileUtils.h" +#import "Support/uthash.h" +#import "Support/OpenGL_Internal.h" + +// extern +#import "kazmath/GL/matrix.h" +#import "kazmath/kazmath.h" + + +typedef struct _hashUniformEntry +{ + GLvoid *value; // value + NSUInteger location; // Key + UT_hash_handle hh; // hash entry +} tHashUniformEntry; + + +#pragma mark Function Pointer Definitions +typedef void (*GLInfoFunction)(GLuint program, + GLenum pname, + GLint* params); +typedef void (*GLLogFunction) (GLuint program, + GLsizei bufsize, + GLsizei* length, + GLchar* infolog); +#pragma mark - +#pragma mark Private Extension Method Declaration + +@interface CCGLProgram() +- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type byteArray:(const GLchar*)byteArray; + +- (NSString *)logForOpenGLObject:(GLuint)object infoCallback:(GLInfoFunction)infoFunc logFunc:(GLLogFunction)logFunc; +@end + +#pragma mark - + +@implementation CCGLProgram +- (id)initWithVertexShaderByteArray:(const GLchar *)vShaderByteArray fragmentShaderByteArray:(const GLchar *)fShaderByteArray +{ + if ((self = [super init]) ) + { + program_ = glCreateProgram(); + + vertShader_ = fragShader_ = 0; + + if( vShaderByteArray ) { + + if (![self compileShader:&vertShader_ + type:GL_VERTEX_SHADER + byteArray:vShaderByteArray] ) + CCLOG(@"cocos2d: ERROR: Failed to compile vertex shader"); + } + + // Create and compile fragment shader + if( fShaderByteArray ) { + if (![self compileShader:&fragShader_ + type:GL_FRAGMENT_SHADER + byteArray:fShaderByteArray] ) + + CCLOG(@"cocos2d: ERROR: Failed to compile fragment shader"); + } + + if( vertShader_ ) + glAttachShader(program_, vertShader_); + + if( fragShader_ ) + glAttachShader(program_, fragShader_); + + hashForUniforms_ = NULL; + } + + return self; +} + +- (id)initWithVertexShaderFilename:(NSString *)vShaderFilename fragmentShaderFilename:(NSString *)fShaderFilename +{ + + const GLchar * vertexSource = (GLchar*) [[NSString stringWithContentsOfFile:[CCFileUtils fullPathFromRelativePath:vShaderFilename] encoding:NSUTF8StringEncoding error:nil] UTF8String]; + const GLchar * fragmentSource = (GLchar*) [[NSString stringWithContentsOfFile:[CCFileUtils fullPathFromRelativePath:fShaderFilename] encoding:NSUTF8StringEncoding error:nil] UTF8String]; + + return [self initWithVertexShaderByteArray:vertexSource fragmentShaderByteArray:fragmentSource]; +} + +- (NSString*) description +{ + return [NSString stringWithFormat:@"<%@ = %08X | Program = %i, VertexShader = %i, FragmentShader = %i>", [self class], self, program_, vertShader_, fragShader_]; +} + + +- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type byteArray:(const GLchar *)source +{ + GLint status; + + if (!source) + return NO; + + *shader = glCreateShader(type); + glShaderSource(*shader, 1, &source, NULL); + glCompileShader(*shader); + + glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); + + if( ! status ) { + if( type == GL_VERTEX_SHADER ) + CCLOG(@"cocos2d: %@", [self vertexShaderLog] ); + else + CCLOG(@"cocos2d: %@", [self fragmentShaderLog] ); + + } + return ( status == GL_TRUE ); +} + +#pragma mark - + +- (void)addAttribute:(NSString *)attributeName index:(GLuint)index +{ + glBindAttribLocation(program_, + index, + [attributeName UTF8String]); +} + +-(void) updateUniforms +{ + // Since sample most probably won't change, set it to 0 now. + + uniforms_[kCCUniformMVPMatrix] = glGetUniformLocation(program_, kCCUniformMVPMatrix_s); + + uniforms_[kCCUniformSampler] = glGetUniformLocation(program_, kCCUniformSampler_s); + + [self use]; + + [self setUniformLocation:uniforms_[kCCUniformSampler] withI1:0]; +} + +#pragma mark - + +- (BOOL)link +{ + glLinkProgram(program_); + +#if DEBUG + GLint status; + glValidateProgram(program_); + + glGetProgramiv(program_, GL_LINK_STATUS, &status); + if (status == GL_FALSE) { + CCLOG(@"cocos2d: ERROR: Failed to link program: %i", program_); + if( vertShader_ ) + glDeleteShader( vertShader_ ); + if( fragShader_ ) + glDeleteShader( fragShader_ ); + ccGLDeleteProgram( program_ ); + vertShader_ = fragShader_ = program_ = 0; + return NO; + } +#endif + + if (vertShader_) + glDeleteShader(vertShader_); + if (fragShader_) + glDeleteShader(fragShader_); + + vertShader_ = fragShader_ = 0; + + return YES; +} + +- (void)use +{ + ccGLUseProgram(program_); +} + +#pragma mark - + +- (NSString *)logForOpenGLObject:(GLuint)object + infoCallback:(GLInfoFunction)infoFunc + logFunc:(GLLogFunction)logFunc +{ + GLint logLength = 0, charsWritten = 0; + + infoFunc(object, GL_INFO_LOG_LENGTH, &logLength); + if (logLength < 1) + return nil; + + char *logBytes = malloc(logLength); + logFunc(object, logLength, &charsWritten, logBytes); + NSString *log = [[[NSString alloc] initWithBytes:logBytes + length:logLength + encoding:NSUTF8StringEncoding] + autorelease]; + free(logBytes); + return log; +} + +- (NSString *)vertexShaderLog +{ + return [self logForOpenGLObject:vertShader_ + infoCallback:(GLInfoFunction)&glGetShaderiv + logFunc:(GLLogFunction)&glGetShaderInfoLog]; + +} + +- (NSString *)fragmentShaderLog +{ + return [self logForOpenGLObject:fragShader_ + infoCallback:(GLInfoFunction)&glGetShaderiv + logFunc:(GLLogFunction)&glGetShaderInfoLog]; +} + +- (NSString *)programLog +{ + return [self logForOpenGLObject:program_ + infoCallback:(GLInfoFunction)&glGetProgramiv + logFunc:(GLLogFunction)&glGetProgramInfoLog]; +} + +#pragma mark - Uniform cache + +-(BOOL) updateUniformLocation:(NSUInteger)location withData:(GLvoid*)data sizeOfData:(NSUInteger)bytes +{ + BOOL updated = YES; + tHashUniformEntry *element = NULL; + HASH_FIND_INT(hashForUniforms_, &location, element); + + if( ! element ) { + + element = malloc( sizeof(*element) ); + + // key + element->location = location; + + // value + element->value = malloc( bytes ); + memcpy(element->value, data, bytes ); + + HASH_ADD_INT(hashForUniforms_, location, element); + } + else + { + if( memcmp( element->value, data, bytes) == 0 ) + updated = NO; + else + memcpy( element->value, data, bytes ); + } + + return updated; +} + +-(void) setUniformLocation:(NSUInteger)location withI1:(GLint)i1 +{ + BOOL updated = [self updateUniformLocation:location withData:&i1 sizeOfData:sizeof(i1)*1]; + + if( updated ) + glUniform1i( (GLint)location, i1); +} + +-(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 +{ + BOOL updated = [self updateUniformLocation:location withData:&f1 sizeOfData:sizeof(f1)*1]; + + if( updated ) + glUniform1f( (GLint)location, f1); +} + +-(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 +{ + GLfloat floats[2] = {f1,f2}; + BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(floats)]; + + if( updated ) + glUniform2f( (GLint)location, f1, f2); +} + +-(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 f3:(GLfloat)f3 +{ + GLfloat floats[3] = {f1,f2,f3}; + BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(floats)]; + + if( updated ) + glUniform3f( (GLint)location, f1, f2, f3); +} + +-(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 f3:(GLfloat)f3 f4:(GLfloat)f4 +{ + GLfloat floats[4] = {f1,f2,f3,f4}; + BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(floats)]; + + if( updated ) + glUniform4f( (GLint)location, f1, f2, f3,f4); +} + +-(void) setUniformLocation:(NSUInteger)location with2fv:(GLfloat*)floats count:(NSUInteger)numberOfArrays +{ + BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(float)*2*numberOfArrays]; + + if( updated ) + glUniform2fv( (GLint)location, (GLsizei)numberOfArrays, floats ); +} + +-(void) setUniformLocation:(NSUInteger)location with3fv:(GLfloat*)floats count:(NSUInteger)numberOfArrays +{ + BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(float)*3*numberOfArrays]; + + if( updated ) + glUniform3fv( (GLint)location, (GLsizei)numberOfArrays, floats ); +} + +-(void) setUniformLocation:(NSUInteger)location with4fv:(GLvoid*)floats count:(NSUInteger)numberOfArrays +{ + BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(float)*4*numberOfArrays]; + + if( updated ) + glUniform4fv( (GLint)location, (GLsizei)numberOfArrays, floats ); +} + + +-(void) setUniformLocation:(NSUInteger)location withMatrix4fv:(GLvoid*)matrixArray count:(NSUInteger)numberOfMatrices +{ + BOOL updated = [self updateUniformLocation:location withData:matrixArray sizeOfData:sizeof(float)*16*numberOfMatrices]; + + if( updated ) + glUniformMatrix4fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray); +} + +-(void) setUniformForModelViewProjectionMatrix +{ + kmMat4 matrixP; + kmMat4 matrixMV; + kmMat4 matrixMVP; + + kmGLGetMatrix(KM_GL_PROJECTION, &matrixP ); + kmGLGetMatrix(KM_GL_MODELVIEW, &matrixMV ); + + kmMat4Multiply(&matrixMVP, &matrixP, &matrixMV); + + [self setUniformLocation:uniforms_[kCCUniformMVPMatrix] withMatrix4fv:matrixMVP.mat count:1]; +} + + +#pragma mark - + +- (void)dealloc +{ + CCLOGINFO( @"cocos2d: deallocing %@", self); + + // there is no need to delete the shaders. They should have been already deleted. + NSAssert( vertShader_ == 0, @"Vertex Shaders should have been already deleted"); + NSAssert( fragShader_ == 0, @"Vertex Shaders should have been already deleted"); + + if (program_) + ccGLDeleteProgram(program_); + + tHashUniformEntry *current_element, *tmp; + + // Purge uniform hash + HASH_ITER(hh, hashForUniforms_, current_element, tmp) { + HASH_DEL(hashForUniforms_, current_element); + free(current_element->value); + free(current_element); + } + + [super dealloc]; +} +@end diff --git a/Example/libs/cocos2d/CCParticleBatchNode.h b/Example/libs/cocos2d/CCParticleBatchNode.h new file mode 100644 index 0000000..ec5e9bf --- /dev/null +++ b/Example/libs/cocos2d/CCParticleBatchNode.h @@ -0,0 +1,99 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (C) 2009 Matt Oswald + * + * Copyright (c) 2009-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Copyright (c) 2011 Marco Tillemans + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +#import "CCNode.h" +@class CCTextureAtlas; +@class CCParticleSystem; + +//don't use lazy sorting for particle systems +@interface CCNode (extension) +-(void) setZOrder:(NSUInteger) z; +@end + +/** CCParticleBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call + * (often known as "batch draw"). + * + * A CCParticleBatchNode can reference one and only one texture (one image file, one texture atlas). + * Only the CCParticleSystems that are contained in that texture can be added to the CCSpriteBatchNode. + * All CCParticleSystems added to a CCSpriteBatchNode are drawn in one OpenGL ES draw call. + * If the CCParticleSystems are not added to a CCParticleBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient. + * + * + * Limitations: + * - At the moment only CCParticleSystemQuad is supported + * - All systems need to be drawn with the same parameters, blend function, aliasing, texture + * + * Most efficient usage + * - Initialize the ParticleBatchNode with the texture and enough capacity for all the particle systems + * - Initialize all particle systems and add them as child to the batch node + * @since v1.1 + */ + +@interface CCParticleBatchNode : CCNode { + + CCTextureAtlas *textureAtlas_; + ccBlendFunc blendFunc_; +} + +/** the texture atlas used for drawing the quads */ +@property (nonatomic, retain) CCTextureAtlas* textureAtlas; +/** the blend function used for drawing the quads */ +@property (nonatomic, readwrite) ccBlendFunc blendFunc; + +/** initializes the particle system with CCTexture2D, a default capacity of 500 */ ++(id)batchNodeWithTexture:(CCTexture2D *)tex; + +/** initializes the particle system with the name of a file on disk (for a list of supported formats look at the CCTexture2D class), a default capacity of 500 particles */ ++(id)batchNodeWithFile:(NSString*) imageFile; + +/** initializes the particle system with CCTexture2D, a capacity of particles, which particle system to use */ ++(id)batchNodeWithTexture:(CCTexture2D *)tex capacity:(NSUInteger) capacity; + +/** initializes the particle system with the name of a file on disk (for a list of supported formats look at the CCTexture2D class), a capacity of particles */ ++(id)batchNodeWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity; + +/** initializes the particle system with CCTexture2D, a capacity of particles */ +-(id)initWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity; + +/** initializes the particle system with the name of a file on disk (for a list of supported formats look at the CCTexture2D class), a capacity of particles */ +-(id)initWithFile:(NSString *)fileImage capacity:(NSUInteger)capacity; + +/** Add a child into the CCParticleBatchNode */ +-(void) addChild:(CCParticleSystem*)child z:(NSInteger)z tag:(NSInteger) aTag; + +/** Inserts a child into the CCParticleBatchNode */ +-(void) insertChild:(CCParticleSystem*) pSystem inAtlasAtIndex:(NSUInteger)index; + +/** remove child from the CCParticleBatchNode */ +-(void) removeChild:(CCParticleSystem*) pSystem cleanup:(BOOL)doCleanUp; + +/** disables a particle by inserting a 0'd quad into the texture atlas */ +-(void) disableParticle:(NSUInteger) particleIndex; +@end diff --git a/Example/libs/cocos2d/CCParticleBatchNode.m b/Example/libs/cocos2d/CCParticleBatchNode.m new file mode 100644 index 0000000..f786a5c --- /dev/null +++ b/Example/libs/cocos2d/CCParticleBatchNode.m @@ -0,0 +1,473 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (C) 2009 Matt Oswald + * + * Copyright (c) 2009-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Copyright (c) 2011 Marco Tillemans + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +#import "CCParticleBatchNode.h" +#import "CCTextureCache.h" +#import "CCTextureAtlas.h" +#import "ccConfig.h" +#import "ccMacros.h" +#import "CCGrid.h" +#import "Support/CGPointExtension.h" +#import "CCParticleSystem.h" +#import "CCParticleSystem.h" +#import "CCShaderCache.h" +#import "CCGLProgram.h" +#import "ccGLStateCache.h" + +#import "Support/base64.h" +#import "Support/ZipUtils.h" +#import "Support/CCFileUtils.h" + +#import "kazmath/GL/matrix.h" + +#define kCCParticleDefaultCapacity 500 + +@interface CCNode() +-(void) _setZOrder:(NSInteger)z; +@end + +@interface CCParticleBatchNode (private) +-(void) updateAllAtlasIndexes; +-(void) increaseAtlasCapacityTo:(NSUInteger) quantity; +-(NSUInteger) searchNewPositionInChildrenForZ:(NSInteger)z; +-(void) getCurrentIndex:(NSUInteger*)oldIndex newIndex:(NSUInteger*)newIndex forChild:(CCNode*)child z:(NSInteger)z; +-(NSUInteger) addChildHelper: (CCNode*) child z:(NSInteger)z tag:(NSInteger) aTag; +@end + +@implementation CCParticleBatchNode + +@synthesize textureAtlas = textureAtlas_; +@synthesize blendFunc = blendFunc_; + +/* + * creation with CCTexture2D + */ ++(id)batchNodeWithTexture:(CCTexture2D *)tex +{ + return [[[self alloc] initWithTexture:tex capacity:kCCParticleDefaultCapacity] autorelease]; +} + ++(id)batchNodeWithTexture:(CCTexture2D *)tex capacity:(NSUInteger) capacity +{ + return [[[self alloc] initWithTexture:tex capacity:capacity] autorelease]; +} + +/* + * creation with File Image + */ ++(id)batchNodeWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity +{ + return [[[self alloc] initWithFile:fileImage capacity:capacity] autorelease]; +} + ++(id)batchNodeWithFile:(NSString*) imageFile +{ + return [[[self alloc] initWithFile:imageFile capacity:kCCParticleDefaultCapacity] autorelease]; +} + +/* + * init with CCTexture2D + */ +-(id)initWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity +{ + if (self = [super init]) + { + textureAtlas_ = [[CCTextureAtlas alloc] initWithTexture:tex capacity:capacity]; + + // no lazy alloc in this node + children_ = [[CCArray alloc] initWithCapacity:capacity]; + + blendFunc_.src = CC_BLEND_SRC; + blendFunc_.dst = CC_BLEND_DST; + + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; + } + + return self; +} + +/* + * init with FileImage + */ +-(id)initWithFile:(NSString *)fileImage capacity:(NSUInteger)capacity +{ + CCTexture2D *tex = [[CCTextureCache sharedTextureCache] addImage:fileImage]; + return [self initWithTexture:tex capacity:capacity]; +} + +-(NSString*) description +{ + return [NSString stringWithFormat:@"<%@ = %08X | Tag = %i>", [self class], self, tag_ ]; +} + +-(void)dealloc +{ + [textureAtlas_ release]; + [super dealloc]; +} + +#pragma mark CCParticleBatchNode - composition + +// override visit. +// Don't call visit on it's children +-(void) visit +{ + // CAREFUL: + // This visit is almost identical to CCNode#visit + // with the exception that it doesn't call visit on it's children + // + // The alternative is to have a void CCSprite#visit, but + // although this is less mantainable, is faster + // + if (!visible_) + return; + + kmGLPushMatrix(); + + if ( grid_ && grid_.active) { + [grid_ beforeDraw]; + [self transformAncestors]; + } + + [self transform]; + + [self draw]; + + if ( grid_ && grid_.active) + [grid_ afterDraw:self]; + + kmGLPopMatrix(); +} + +// override addChild: +-(void) addChild:(CCParticleSystem*)child z:(NSInteger)z tag:(NSInteger) aTag +{ + NSAssert( child != nil, @"Argument must be non-nil"); + NSAssert( [child isKindOfClass:[CCParticleSystem class]], @"CCParticleBatchNode only supports CCQuadParticleSystems as children"); + NSAssert( child.texture.name == textureAtlas_.texture.name, @"CCParticleSystem is not using the same texture id"); + + // If this is the 1st children, then copy blending function + if( [children_ count] == 0 ) + blendFunc_ = [child blendFunc]; + + NSAssert( blendFunc_.src == child.blendFunc.src && blendFunc_.dst == child.blendFunc.dst, @"Can't add a PaticleSystem that uses a differnt blending function"); + + //no lazy sorting, so don't call super addChild, call helper instead + NSUInteger pos = [self addChildHelper:child z:z tag:aTag]; + + //get new atlasIndex + NSUInteger atlasIndex; + + if (pos != 0) + atlasIndex = [[children_ objectAtIndex:pos-1] atlasIndex] + [[children_ objectAtIndex:pos-1] totalParticles]; + else + atlasIndex = 0; + + [self insertChild:child inAtlasAtIndex:atlasIndex]; + + // update quad info + [child setBatchNode:self]; +} + +// don't use lazy sorting, reordering the particle systems quads afterwards would be too complex +// XXX research whether lazy sorting + freeing current quads and calloc a new block with size of capacity would be faster +// XXX or possibly using vertexZ for reordering, that would be fastest +// this helper is almost equivalent to CCNode's addChild, but doesn't make use of the lazy sorting +-(NSUInteger) addChildHelper: (CCNode*) child z:(NSInteger)z tag:(NSInteger) aTag +{ + NSAssert( child != nil, @"Argument must be non-nil"); + NSAssert( child.parent == nil, @"child already added. It can't be added again"); + + if( ! children_ ) + children_ = [[CCArray alloc] initWithCapacity:4]; + + //don't use a lazy insert + NSUInteger pos = [self searchNewPositionInChildrenForZ:z]; + + [children_ insertObject:child atIndex:pos]; + + child.tag = aTag; + [child _setZOrder:z]; + + [child setParent: self]; + + if( isRunning_ ) { + [child onEnter]; + [child onEnterTransitionDidFinish]; + } + return pos; +} + +// Reorder will be done in this function, no "lazy" reorder to particles +-(void) reorderChild:(CCParticleSystem*)child z:(NSInteger)z +{ + NSAssert( child != nil, @"Child must be non-nil"); + NSAssert( [children_ containsObject:child], @"Child doesn't belong to batch" ); + + if( z == child.zOrder ) + return; + + // no reordering if only 1 child + if( [children_ count] > 1) + { + NSUInteger newIndex, oldIndex; + + [self getCurrentIndex:&oldIndex newIndex:&newIndex forChild:child z:z]; + + if( oldIndex != newIndex ) { + + // reorder children_ array + [child retain]; + [children_ removeObjectAtIndex:oldIndex]; + [children_ insertObject:child atIndex:newIndex]; + [child release]; + + // save old altasIndex + NSUInteger oldAtlasIndex = child.atlasIndex; + + // update atlas index + [self updateAllAtlasIndexes]; + + // Find new AtlasIndex + NSUInteger newAtlasIndex = 0; + for( NSUInteger i=0;i < [children_ count];i++) { + CCParticleSystem *node = [children_ objectAtIndex:i]; + if( node == child ) { + newAtlasIndex = [child atlasIndex]; + break; + } + } + + // reorder textureAtlas quads + [textureAtlas_ moveQuadsFromIndex:oldAtlasIndex amount:child.totalParticles atIndex:newAtlasIndex]; + + [child updateWithNoTime]; + } + } + + [child _setZOrder:z]; +} + +-(void) getCurrentIndex:(NSUInteger*)oldIndex newIndex:(NSUInteger*)newIndex forChild:(CCNode*)child z:(NSInteger)z +{ + BOOL foundCurrentIdx = NO; + BOOL foundNewIdx = NO; + + NSInteger minusOne = 0; + NSUInteger count = [children_ count]; + + for( NSUInteger i=0; i < count; i++ ) { + + CCNode *node = [children_ objectAtIndex:i]; + + // new index + if( node.zOrder > z && ! foundNewIdx ) { + *newIndex = i; + foundNewIdx = YES; + + if( foundCurrentIdx && foundNewIdx ) + break; + } + + // current index + if( child == node ) { + *oldIndex = i; + foundCurrentIdx = YES; + + if( ! foundNewIdx ) + minusOne = -1; + + if( foundCurrentIdx && foundNewIdx ) + break; + + } + + } + + if( ! foundNewIdx ) + *newIndex = count; + + *newIndex += minusOne; +} + +-(NSUInteger) searchNewPositionInChildrenForZ: (NSInteger) z +{ + NSUInteger count = [children_ count]; + + for( NSUInteger i=0; i < count; i++ ) { + CCNode *child = [children_ objectAtIndex:i]; + if (child.zOrder > z) + return i; + } + return count; +} + +// override removeChild: +-(void)removeChild: (CCParticleSystem*) child cleanup:(BOOL)doCleanup +{ + // explicit nil handling + if (child == nil) + return; + + NSAssert([children_ containsObject:child], @"CCParticleBatchNode doesn't contain the sprite. Can't remove it"); + + [super removeChild:child cleanup:doCleanup]; + + // remove child helper + [textureAtlas_ removeQuadsAtIndex:child.atlasIndex amount:child.totalParticles]; + + // after memmove of data, empty the quads at the end of array + [textureAtlas_ fillWithEmptyQuadsFromIndex:textureAtlas_.totalQuads amount:child.totalParticles]; + + // paticle could be reused for self rendering + [child setBatchNode:nil]; + + [self updateAllAtlasIndexes]; +} + +-(void)removeChildAtIndex:(NSUInteger)index cleanup:(BOOL) doCleanup +{ + [self removeChild:(CCParticleSystem *)[children_ objectAtIndex:index] cleanup:doCleanup]; +} + +-(void)removeAllChildrenWithCleanup:(BOOL)doCleanup +{ + [children_ makeObjectsPerformSelector:@selector(useSelfRender)]; + + [super removeAllChildrenWithCleanup:doCleanup]; + + [textureAtlas_ removeAllQuads]; +} + +#pragma mark CCParticleBatchNode - Node overrides +-(void) draw +{ + CC_PROFILER_STOP(@"CCParticleBatchNode - draw"); + + if( textureAtlas_.totalQuads == 0 ) + return; + + CC_NODE_DRAW_SETUP(); + + ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); + + [textureAtlas_ drawQuads]; + + CC_PROFILER_STOP(@"CCParticleBatchNode - draw"); +} + +#pragma mark CCParticleBatchNode - private + +-(void) increaseAtlasCapacityTo:(NSUInteger) quantity +{ + CCLOG(@"cocos2d: CCParticleBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", + (long)textureAtlas_.capacity, + (long)quantity); + + if( ! [textureAtlas_ resizeCapacity:quantity] ) { + // serious problems + CCLOG(@"cocos2d: WARNING: Not enough memory to resize the atlas"); + NSAssert(NO,@"XXX: CCParticleBatchNode #increaseAtlasCapacity SHALL handle this assert"); + } +} + +//sets a 0'd quad into the quads array +-(void) disableParticle:(NSUInteger)particleIndex +{ + ccV3F_C4B_T2F_Quad* quad = &((textureAtlas_.quads)[particleIndex]); + quad->br.vertices.x = quad->br.vertices.y = quad->tr.vertices.x = quad->tr.vertices.y = quad->tl.vertices.x = quad->tl.vertices.y = quad->bl.vertices.x = quad->bl.vertices.y = 0.0f; +} + +#pragma mark CCParticleBatchNode - add / remove / reorder helper methods + +// add child helper +-(void) insertChild:(CCParticleSystem*) pSystem inAtlasAtIndex:(NSUInteger)index +{ + pSystem.atlasIndex = index; + + if(textureAtlas_.totalQuads + pSystem.totalParticles > textureAtlas_.capacity) + { + [self increaseAtlasCapacityTo:textureAtlas_.totalQuads + pSystem.totalParticles]; + + // after a realloc empty quads of textureAtlas can be filled with gibberish (realloc doesn't perform calloc), insert empty quads to prevent it + [textureAtlas_ fillWithEmptyQuadsFromIndex:textureAtlas_.capacity - pSystem.totalParticles amount:pSystem.totalParticles]; + } + + // make room for quads, not necessary for last child + if (pSystem.atlasIndex + pSystem.totalParticles != textureAtlas_.totalQuads) + [textureAtlas_ moveQuadsFromIndex:index to:index+pSystem.totalParticles]; + + // increase totalParticles here for new particles, update method of particlesystem will fill the quads + [textureAtlas_ increaseTotalQuadsWith:pSystem.totalParticles]; + + [self updateAllAtlasIndexes]; +} + +//rebuild atlas indexes +-(void) updateAllAtlasIndexes +{ + CCParticleSystem *child; + NSUInteger index = 0; + + CCARRAY_FOREACH(children_,child) + { + child.atlasIndex = index; + index += child.totalParticles; + } +} + +#pragma mark CCParticleBatchNode - CocosNodeTexture protocol + +-(void) updateBlendFunc +{ + if( ! [textureAtlas_.texture hasPremultipliedAlpha] ) { + blendFunc_.src = GL_SRC_ALPHA; + blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; + } +} + +-(void) setTexture:(CCTexture2D*)texture +{ + textureAtlas_.texture = texture; + + // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it + if( texture && ! [texture hasPremultipliedAlpha] && ( blendFunc_.src == CC_BLEND_SRC && blendFunc_.dst == CC_BLEND_DST ) ) + { + blendFunc_.src = GL_SRC_ALPHA; + blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; + } +} + +-(CCTexture2D*) texture +{ + return textureAtlas_.texture; +} + +@end diff --git a/Example/libs/cocos2d/CCShaderCache.h b/Example/libs/cocos2d/CCShaderCache.h new file mode 100644 index 0000000..5c93a99 --- /dev/null +++ b/Example/libs/cocos2d/CCShaderCache.h @@ -0,0 +1,60 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import +#import "ccMacros.h" +#ifdef __CC_PLATFORM_IOS +#import +#endif // __CC_PLATFORM_IOS + +@class CCGLProgram; + +/** CCShaderCache + Singleton that stores manages GL shaders + @since v2.0 + */ +@interface CCShaderCache : NSObject { + + NSMutableDictionary *programs_; + +} + +/** returns the shared instance */ ++ (CCShaderCache *)sharedShaderCache; + +/** purges the cache. It releases the retained instance. */ ++(void)purgeSharedShaderCache; + +/** loads the default shaders */ +-(void) loadDefaultShaders; + +/** returns a GL program for a given key */ +-(CCGLProgram *) programForKey:(NSString*)key; + +/** adds a CCGLProgram to the cache for a given name */ +- (void) addProgram:(CCGLProgram*)program forKey:(NSString*)key; + +@end + diff --git a/Example/libs/cocos2d/CCShaderCache.m b/Example/libs/cocos2d/CCShaderCache.m new file mode 100644 index 0000000..db701cf --- /dev/null +++ b/Example/libs/cocos2d/CCShaderCache.m @@ -0,0 +1,214 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import "CCShaderCache.h" +#import "ccShaders.h" +#import "CCGLProgram.h" +#import "ccMacros.h" +#import "Support/OpenGL_Internal.h" + +static CCShaderCache *_sharedShaderCache; + +@implementation CCShaderCache + +#pragma mark CCShaderCache - Alloc, Init & Dealloc + ++ (CCShaderCache *)sharedShaderCache +{ + if (!_sharedShaderCache) + _sharedShaderCache = [[CCShaderCache alloc] init]; + + return _sharedShaderCache; +} + ++(void)purgeSharedShaderCache +{ + [_sharedShaderCache release]; + _sharedShaderCache = nil; +} + + ++(id)alloc +{ + NSAssert(_sharedShaderCache == nil, @"Attempted to allocate a second instance of a singleton."); + return [super alloc]; +} + +- (void)dealloc +{ + CCLOGINFO(@"cocos2d deallocing %@", self); + + [programs_ release]; + [super dealloc]; +} + ++(void)purgeSharedTextureCache +{ + [_sharedShaderCache release]; + _sharedShaderCache = nil; +} + +-(id) init +{ + if( (self=[super init]) ) { + programs_ = [[NSMutableDictionary alloc ] initWithCapacity: 10]; + + [self loadDefaultShaders]; + } + + return self; +} + +-(void) loadDefaultShaders +{ + // Position Texture Color shader + CCGLProgram *p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTextureColor_vert + fragmentShaderByteArray:ccPositionTextureColor_frag]; + + [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; + [p addAttribute:kCCAttributeNameColor index:kCCVertexAttrib_Color]; + [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; + + [p link]; + [p updateUniforms]; + + [programs_ setObject:p forKey:kCCShader_PositionTextureColor]; + [p release]; + + CHECK_GL_ERROR_DEBUG(); + + // Position Texture Color alpha test + p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTextureColor_vert + fragmentShaderByteArray:ccPositionTextureColorAlphaTest_frag]; + + [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; + [p addAttribute:kCCAttributeNameColor index:kCCVertexAttrib_Color]; + [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; + + [p link]; + [p updateUniforms]; + + [programs_ setObject:p forKey:kCCShader_PositionTextureColorAlphaTest]; + [p release]; + + CHECK_GL_ERROR_DEBUG(); + + // + // Position, Color shader + // + p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionColor_vert + fragmentShaderByteArray:ccPositionColor_frag]; + + [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; + [p addAttribute:kCCAttributeNameColor index:kCCVertexAttrib_Color]; + + [p link]; + [p updateUniforms]; + + [programs_ setObject:p forKey:kCCShader_PositionColor]; + [p release]; + + CHECK_GL_ERROR_DEBUG(); + + // + // Position Texture shader + // + p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTexture_vert + fragmentShaderByteArray:ccPositionTexture_frag]; + + [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; + [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; + + [p link]; + [p updateUniforms]; + + [programs_ setObject:p forKey:kCCShader_PositionTexture]; + [p release]; + + CHECK_GL_ERROR_DEBUG(); + + // + // Position, Texture attribs, 1 Color as uniform shader + // + p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTexture_uColor_vert + fragmentShaderByteArray:ccPositionTexture_uColor_frag]; + + [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; + [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; + + [p link]; + [p updateUniforms]; + + [programs_ setObject:p forKey:kCCShader_PositionTexture_uColor]; + [p release]; + + CHECK_GL_ERROR_DEBUG(); + + // + // Position Texture A8 Color shader + // + p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTextureA8Color_vert + fragmentShaderByteArray:ccPositionTextureA8Color_frag]; + + [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; + [p addAttribute:kCCAttributeNameColor index:kCCVertexAttrib_Color]; + [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; + + [p link]; + [p updateUniforms]; + + [programs_ setObject:p forKey:kCCShader_PositionTextureA8Color]; + [p release]; + + CHECK_GL_ERROR_DEBUG(); + + // + // Position and 1 color passed as a uniform (to similate glColor4ub ) + // + p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPosition_uColor_vert + fragmentShaderByteArray:ccPosition_uColor_frag]; + + [p addAttribute:@"aVertex" index:kCCVertexAttrib_Position]; + + [p link]; + [p updateUniforms]; + + [programs_ setObject:p forKey:kCCShader_Position_uColor]; + [p release]; + + CHECK_GL_ERROR_DEBUG(); +} + +-(CCGLProgram *) programForKey:(NSString*)key +{ + return [programs_ objectForKey:key]; +} + +- (void) addProgram:(CCGLProgram*)program forKey:(NSString*)key +{ + [programs_ setObject:program forKey:key]; +} + +@end diff --git a/Example/libs/cocos2d/CCTransitionProgress.h b/Example/libs/cocos2d/CCTransitionProgress.h new file mode 100644 index 0000000..241ff63 --- /dev/null +++ b/Example/libs/cocos2d/CCTransitionProgress.h @@ -0,0 +1,62 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2009 Lam Pham + * + * Copyright (c) 2012 Ricardo Quesada + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +#import "CCTransition.h" + +@interface CCTransitionProgress : CCTransitionScene +{ + float to_, from_; + CCScene *sceneToBeModified_; +} +@end + +/** CCTransitionRadialCCW transition. + A counter colock-wise radial transition to the next scene + */ +@interface CCTransitionProgressRadialCCW : CCTransitionProgress +@end + +/** CCTransitionRadialCW transition. + A counter colock-wise radial transition to the next scene +*/ +@interface CCTransitionProgressRadialCW : CCTransitionProgress +@end + +/** CCTransitionProgressHorizontal transition. + A colock-wise radial transition to the next scene + */ +@interface CCTransitionProgressHorizontal : CCTransitionProgress +@end + +@interface CCTransitionProgressVertical : CCTransitionProgress +@end + +@interface CCTransitionProgressInOut : CCTransitionProgress +@end + +@interface CCTransitionProgressOutIn : CCTransitionProgress +@end diff --git a/Example/libs/cocos2d/CCTransitionProgress.m b/Example/libs/cocos2d/CCTransitionProgress.m new file mode 100644 index 0000000..afe4de6 --- /dev/null +++ b/Example/libs/cocos2d/CCTransitionProgress.m @@ -0,0 +1,276 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2009 Lam Pham + * + * Copyright (c) 2012 Ricardo Quesada + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + + +#import "CCTransitionProgress.h" +#import "CCDirector.h" +#import "CCRenderTexture.h" +#import "CCLayer.h" +#import "CCActionInstant.h" +#import "CCProgressTimer.h" +#import "CCActionProgressTimer.h" +#import "Support/CGPointExtension.h" + +enum { + kCCSceneRadial = 0xc001, +}; + +#pragma mark - CCTransitionProgress + +@interface CCTransitionProgress() +-(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture; +-(void) setupTransition; +@end + +@implementation CCTransitionProgress +-(void) onEnter +{ + [super onEnter]; + + [self setupTransition]; + + // create a transparent color layer + // in which we are going to add our rendertextures + CGSize size = [[CCDirector sharedDirector] winSize]; + + // create the second render texture for outScene + CCRenderTexture *texture = [CCRenderTexture renderTextureWithWidth:size.width height:size.height]; + texture.sprite.anchorPoint= ccp(0.5f,0.5f); + texture.position = ccp(size.width/2, size.height/2); + texture.anchorPoint = ccp(0.5f,0.5f); + + // render outScene to its texturebuffer + [texture clear:0 g:0 b:0 a:1]; + [texture begin]; + [sceneToBeModified_ visit]; + [texture end]; + + + // Since we've passed the outScene to the texture we don't need it. + if( sceneToBeModified_ == outScene_ ) + [self hideOutShowIn]; + + // We need the texture in RenderTexture. + CCProgressTimer *node = [self progressTimerNodeWithRenderTexture:texture]; + + // create the blend action + CCActionInterval * layerAction = [CCSequence actions: + [CCProgressFromTo actionWithDuration:duration_ from:from_ to:to_], + [CCCallFunc actionWithTarget:self selector:@selector(finish)], + nil ]; + // run the blend action + [node runAction: layerAction]; + + // add the layer (which contains our two rendertextures) to the scene + [self addChild: node z:2 tag:kCCSceneRadial]; +} + +// clean up on exit +-(void) onExit +{ + // remove our layer and release all containing objects + [self removeChildByTag:kCCSceneRadial cleanup:NO]; + [super onExit]; +} + +-(void) sceneOrder +{ + inSceneOnTop_ = NO; +} + +-(void) setupTransition +{ + sceneToBeModified_ = outScene_; + from_ = 100; + to_ = 0; +} + +-(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture +{ + NSAssert(NO, @"override me - abstract class"); + + return nil; +} +@end + +#pragma mark - CCTransitionProgressRadialCCW + +@implementation CCTransitionProgressRadialCCW +-(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture +{ + CGSize size = [[CCDirector sharedDirector] winSize]; + + CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; + + // but it is flipped upside down so we flip the sprite + node.sprite.flipY = YES; + node.type = kCCProgressTimerTypeRadial; + + // Return the radial type that we want to use + node.reverseDirection = NO; + node.percentage = 100; + node.position = ccp(size.width/2, size.height/2); + node.anchorPoint = ccp(0.5f,0.5f); + + return node; +} +@end + +#pragma mark - CCTransitionProgressRadialCW + +@implementation CCTransitionProgressRadialCW +-(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture +{ + CGSize size = [[CCDirector sharedDirector] winSize]; + + CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; + + // but it is flipped upside down so we flip the sprite + node.sprite.flipY = YES; + node.type = kCCProgressTimerTypeRadial; + + // Return the radial type that we want to use + node.reverseDirection = YES; + node.percentage = 100; + node.position = ccp(size.width/2, size.height/2); + node.anchorPoint = ccp(0.5f,0.5f); + + return node; +} +@end + +#pragma mark - CCTransitionProgressHorizontal + +@implementation CCTransitionProgressHorizontal +-(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture +{ + CGSize size = [[CCDirector sharedDirector] winSize]; + + CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; + + // but it is flipped upside down so we flip the sprite + node.sprite.flipY = YES; + node.type = kCCProgressTimerTypeBar; + + node.midpoint = ccp(1, 0); + node.barChangeRate = ccp(1,0); + + node.percentage = 100; + node.position = ccp(size.width/2, size.height/2); + node.anchorPoint = ccp(0.5f,0.5f); + + return node; +} +@end + +#pragma mark - CCTransitionProgressVertical + +@implementation CCTransitionProgressVertical +-(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture +{ + CGSize size = [[CCDirector sharedDirector] winSize]; + + CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; + + // but it is flipped upside down so we flip the sprite + node.sprite.flipY = YES; + node.type = kCCProgressTimerTypeBar; + + node.midpoint = ccp(0, 0); + node.barChangeRate = ccp(0,1); + + node.percentage = 100; + node.position = ccp(size.width/2, size.height/2); + node.anchorPoint = ccp(0.5f,0.5f); + + return node; +} +@end + +#pragma mark - CCTransitionProgressInOut + +@implementation CCTransitionProgressInOut + +-(void) sceneOrder +{ + inSceneOnTop_ = NO; +} + +-(void) setupTransition +{ + sceneToBeModified_ = inScene_; + from_ = 0; + to_ = 100; +} + +-(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture +{ + CGSize size = [[CCDirector sharedDirector] winSize]; + + CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; + + // but it is flipped upside down so we flip the sprite + node.sprite.flipY = YES; + node.type = kCCProgressTimerTypeBar; + + node.midpoint = ccp(.5f, .5f); + node.barChangeRate = ccp(1, 1); + + node.percentage = 0; + node.position = ccp(size.width/2, size.height/2); + node.anchorPoint = ccp(0.5f,0.5f); + + return node; +} +@end + +#pragma mark - CCTransitionProgressOutIn + +@implementation CCTransitionProgressOutIn +-(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture +{ + CGSize size = [[CCDirector sharedDirector] winSize]; + + CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; + + // but it is flipped upside down so we flip the sprite + node.sprite.flipY = YES; + node.type = kCCProgressTimerTypeBar; + + node.midpoint = ccp(.5f, .5f); + node.barChangeRate = ccp(1, 1); + + node.percentage = 100; + node.position = ccp(size.width/2, size.height/2); + node.anchorPoint = ccp(0.5f,0.5f); + + return node; +} +@end + + + diff --git a/Example/libs/cocos2d/Platforms/Mac/CCGLView.h b/Example/libs/cocos2d/Platforms/Mac/CCGLView.h new file mode 100644 index 0000000..c178ac8 --- /dev/null +++ b/Example/libs/cocos2d/Platforms/Mac/CCGLView.h @@ -0,0 +1,92 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +// Only compile this code on Mac. These files should not be included on your iOS project. +// But in case they are included, it won't be compiled. +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_MAC + +#import + +#import "../../ccConfig.h" + +//PROTOCOLS: + +@protocol CCEventDelegate +// Mouse +- (void)mouseDown:(NSEvent *)theEvent; +- (void)mouseUp:(NSEvent *)theEvent; +- (void)mouseMoved:(NSEvent *)theEvent; +- (void)mouseDragged:(NSEvent *)theEvent; +- (void)rightMouseDown:(NSEvent*)event; +- (void)rightMouseDragged:(NSEvent*)event; +- (void)rightMouseUp:(NSEvent*)event; +- (void)otherMouseDown:(NSEvent*)event; +- (void)otherMouseDragged:(NSEvent*)event; +- (void)otherMouseUp:(NSEvent*)event; +- (void)scrollWheel:(NSEvent *)theEvent; +- (void)mouseEntered:(NSEvent *)theEvent; +- (void)mouseExited:(NSEvent *)theEvent; + + +// Keyboard +- (void)keyDown:(NSEvent *)theEvent; +- (void)keyUp:(NSEvent *)theEvent; +- (void)flagsChanged:(NSEvent *)theEvent; + +// Touches +- (void)touchesBeganWithEvent:(NSEvent *)event; +- (void)touchesMovedWithEvent:(NSEvent *)event; +- (void)touchesEndedWithEvent:(NSEvent *)event; +- (void)touchesCancelledWithEvent:(NSEvent *)event; + +@end + +/** CCGLView + + Only available for Mac OS X + */ +@interface CCGLView : NSOpenGLView { + id eventDelegate_; +} + +/** Event delegate */ +@property (nonatomic, readwrite, assign) id eventDelegate; + +/** initializes the CCGLView with a frame rect and an OpenGL context */ +- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context; + +/** uses and locks the OpenGL context */ +-(void) lockOpenGLContext; + +/** unlocks the openGL context */ +-(void) unlockOpenGLContext; + +// private ++(void) load_; +@end + +#endif // __CC_PLATFORM_MAC + diff --git a/Example/libs/cocos2d/Platforms/Mac/CCGLView.m b/Example/libs/cocos2d/Platforms/Mac/CCGLView.m new file mode 100644 index 0000000..44d56e3 --- /dev/null +++ b/Example/libs/cocos2d/Platforms/Mac/CCGLView.m @@ -0,0 +1,287 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/* + * Idea of subclassing NSOpenGLView was taken from "TextureUpload" Apple's sample + */ + +// Only compile this code on Mac. These files should not be included on your iOS project. +// But in case they are included, it won't be compiled. +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_MAC + +#import + +#import "CCGLView.h" +#import "CCDirectorMac.h" +#import "CCEventDispatcher.h" +#import "../../ccConfig.h" +#import "../../ccMacros.h" + + +@implementation CCGLView + +@synthesize eventDelegate = eventDelegate_; + ++(void) load_ +{ + CCLOG(@"%@ loaded", self); +} + +- (id) initWithFrame:(NSRect)frameRect +{ + self = [self initWithFrame:frameRect shareContext:nil]; + return self; +} + +- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context +{ + NSOpenGLPixelFormatAttribute attribs[] = + { +// NSOpenGLPFAAccelerated, +// NSOpenGLPFANoRecovery, + NSOpenGLPFADoubleBuffer, + NSOpenGLPFADepthSize, 24, + + // Must specify the 3.2 Core Profile to use OpenGL 3.2 +#if 0 + NSOpenGLPFAOpenGLProfile, + NSOpenGLProfileVersion3_2Core, +#endif + + 0 + }; + + NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; + + if (!pixelFormat) + CCLOG(@"No OpenGL pixel format"); + + if( (self = [super initWithFrame:frameRect pixelFormat:[pixelFormat autorelease]]) ) { + + if( context ) + [self setOpenGLContext:context]; + + // event delegate + eventDelegate_ = nil; + } + + return self; +} + +- (void) update +{ + // XXX: Should I do something here ? + [super update]; +} + +- (void) prepareOpenGL +{ + // XXX: Initialize OpenGL context + + [super prepareOpenGL]; + + // Make this openGL context current to the thread + // (i.e. all openGL on this thread calls will go to this context) + [[self openGLContext] makeCurrentContext]; + + // Synchronize buffer swaps with vertical refresh rate + GLint swapInt = 1; + [[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; + +// GLint order = -1; +// [[self openGLContext] setValues:&order forParameter:NSOpenGLCPSurfaceOrder]; +} + +- (void) reshape +{ + // We draw on a secondary thread through the display link + // When resizing the view, -reshape is called automatically on the main thread + // Add a mutex around to avoid the threads accessing the context simultaneously when resizing + + [self lockOpenGLContext]; + + NSRect rect = [self bounds]; + + CCDirector *director = [CCDirector sharedDirector]; + [director reshapeProjection: NSSizeToCGSize(rect.size) ]; + + // avoid flicker + [director drawScene]; +// [self setNeedsDisplay:YES]; + + [self unlockOpenGLContext]; +} + + +-(void) lockOpenGLContext +{ + NSOpenGLContext *glContext = [self openGLContext]; + NSAssert( glContext, @"FATAL: could not get openGL context"); + + [glContext makeCurrentContext]; + CGLLockContext([glContext CGLContextObj]); +} + +-(void) unlockOpenGLContext +{ + NSOpenGLContext *glContext = [self openGLContext]; + NSAssert( glContext, @"FATAL: could not get openGL context"); + + CGLUnlockContext([glContext CGLContextObj]); +} + +- (void) dealloc +{ + CCLOGINFO(@"cocos2d: deallocing %@", self); + + [super dealloc]; +} + +#define DISPATCH_EVENT(__event__, __selector__) \ + id obj = eventDelegate_; \ + CCEventObject *event = [[CCEventObject alloc] init]; \ + event->event = [__event__ retain]; \ + event->selector = __selector__; \ + [obj performSelector:@selector(dispatchEvent:) \ + onThread:[[CCDirector sharedDirector] runningThread] \ + withObject:event \ + waitUntilDone:NO]; \ + [event release]; + +#pragma mark CCGLView - Mouse events + +- (void)mouseDown:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)mouseMoved:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)mouseDragged:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)mouseUp:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)rightMouseDown:(NSEvent *)theEvent { + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)rightMouseDragged:(NSEvent *)theEvent { + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)rightMouseUp:(NSEvent *)theEvent { + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)otherMouseDown:(NSEvent *)theEvent { + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)otherMouseDragged:(NSEvent *)theEvent { + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)otherMouseUp:(NSEvent *)theEvent { + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)mouseEntered:(NSEvent *)theEvent { + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)mouseExited:(NSEvent *)theEvent { + DISPATCH_EVENT(theEvent, _cmd); +} + +-(void) scrollWheel:(NSEvent *)theEvent { + DISPATCH_EVENT(theEvent, _cmd); +} + +#pragma mark CCGLView - Key events + +-(BOOL) becomeFirstResponder +{ + return YES; +} + +-(BOOL) acceptsFirstResponder +{ + return YES; +} + +-(BOOL) resignFirstResponder +{ + return YES; +} + +- (void)keyDown:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)keyUp:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)flagsChanged:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +#pragma mark CCGLView - Touch events +- (void)touchesBeganWithEvent:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)touchesMovedWithEvent:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)touchesEndedWithEvent:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +- (void)touchesCancelledWithEvent:(NSEvent *)theEvent +{ + DISPATCH_EVENT(theEvent, _cmd); +} + +@end + +#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCWindow.h b/Example/libs/cocos2d/Platforms/Mac/CCWindow.h new file mode 100644 index 0000000..7f37d4d --- /dev/null +++ b/Example/libs/cocos2d/Platforms/Mac/CCWindow.h @@ -0,0 +1,41 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2010 Ricardo Quesada + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +// Only compile this code on Mac. These files should not be included on your iOS project. +// But in case they are included, it won't be compiled. +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_MAC + +#import + + +@interface CCWindow : NSWindow +{ +} +- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen; + +@end + + +#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCWindow.m b/Example/libs/cocos2d/Platforms/Mac/CCWindow.m new file mode 100644 index 0000000..8852a20 --- /dev/null +++ b/Example/libs/cocos2d/Platforms/Mac/CCWindow.m @@ -0,0 +1,69 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2010 Ricardo Quesada + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +// Only compile this code on Mac. These files should not be included on your iOS project. +// But in case they are included, it won't be compiled. +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_MAC + +#import "CCWindow.h" + + +@implementation CCWindow + +- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen +{ + int styleMask = fullscreen ? NSBackingStoreBuffered : ( NSTitledWindowMask | NSClosableWindowMask ); + self = [self initWithContentRect:frame + styleMask:styleMask + backing:NSBackingStoreBuffered + defer:YES]; + + if (self != nil) + { + if(fullscreen) + { + [self setLevel:NSMainMenuWindowLevel+1]; + [self setHidesOnDeactivate:YES]; + [self setHasShadow:NO]; + } + + [self setAcceptsMouseMovedEvents:NO]; + [self setOpaque:YES]; + } + return self; +} + +- (BOOL) canBecomeKeyWindow +{ + return YES; +} + +- (BOOL) canBecomeMainWindow +{ + return YES; +} +@end + +#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.h b/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.h new file mode 100644 index 0000000..9f6163b --- /dev/null +++ b/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.h @@ -0,0 +1,83 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * + * File autogenerated with Xcode. Adapted for cocos2d needs. + */ + +// Only compile this code on iOS. These files should NOT be included on your Mac project. +// But in case they are included, it won't be compiled. +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS + +#import "CCESRenderer.h" + +#import +#import + +@interface CCES2Renderer : NSObject +{ + // The pixel dimensions of the CAEAGLLayer + GLint backingWidth_; + GLint backingHeight_; + + unsigned int samplesToUse_; + BOOL multiSampling_; + + unsigned int depthFormat_; + unsigned int pixelFormat_; + + // The OpenGL ES names for the framebuffer and renderbuffer used to render to this view + GLuint defaultFramebuffer_; + GLuint colorRenderbuffer_; + GLuint depthBuffer_; + + + //buffers for MSAA + GLuint msaaFramebuffer_; + GLuint msaaColorbuffer_; + + EAGLContext *context_; +} + +/** Color Renderbuffer */ +@property (nonatomic,readonly) GLuint colorRenderbuffer; + +/** Default Renderbuffer */ +@property (nonatomic,readonly) GLuint defaultFramebuffer; + +/** MSAA Framebuffer */ +@property (nonatomic,readonly) GLuint msaaFramebuffer; + +/** MSAA Color Buffer */ +@property (nonatomic,readonly) GLuint msaaColorbuffer; + +/** EAGLContext */ +@property (nonatomic,readonly) EAGLContext* context; + +- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer; +@end + +#endif // __CC_PLATFORM_IOS + diff --git a/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.m b/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.m new file mode 100644 index 0000000..5416e5f --- /dev/null +++ b/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.m @@ -0,0 +1,248 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * + * File autogenerated with Xcode. Adapted for cocos2d needs. + */ + +// Only compile this code on iOS. These files should NOT be included on your Mac project. +// But in case they are included, it won't be compiled. +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS + +#import "CCES2Renderer.h" + +#import "../../Support/OpenGL_Internal.h" +#import "../../ccMacros.h" + +@implementation CCES2Renderer + +@synthesize context=context_; +@synthesize defaultFramebuffer=defaultFramebuffer_; +@synthesize colorRenderbuffer=colorRenderbuffer_; +@synthesize msaaColorbuffer=msaaColorbuffer_; +@synthesize msaaFramebuffer=msaaFramebuffer_; + +// Create an OpenGL ES 2.0 context +- (id) initWithDepthFormat:(unsigned int)depthFormat withPixelFormat:(unsigned int)pixelFormat withSharegroup:(EAGLSharegroup*)sharegroup withMultiSampling:(BOOL) multiSampling withNumberOfSamples:(unsigned int) requestedSamples +{ + self = [super init]; + if (self) + { + if( ! sharegroup ) + context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; + else + context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2 sharegroup:sharegroup]; + + if (!context_ || ![EAGLContext setCurrentContext:context_] ) + { + [self release]; + return nil; + } + + depthFormat_ = depthFormat; + pixelFormat_ = pixelFormat; + multiSampling_ = multiSampling; + + // Create default framebuffer object. The backing will be allocated for the current layer in -resizeFromLayer + glGenFramebuffers(1, &defaultFramebuffer_); + NSAssert( defaultFramebuffer_, @"Can't create default frame buffer"); + + glGenRenderbuffers(1, &colorRenderbuffer_); + NSAssert( colorRenderbuffer_, @"Can't create default render buffer"); + + glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer_); + glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer_); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderbuffer_); + + if (multiSampling_) + { + GLint maxSamplesAllowed; + glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamplesAllowed); + samplesToUse_ = MIN(maxSamplesAllowed,requestedSamples); + + /* Create the MSAA framebuffer (offscreen) */ + glGenFramebuffers(1, &msaaFramebuffer_); + NSAssert( msaaFramebuffer_, @"Can't create default MSAA frame buffer"); + glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer_); + + } + + CHECK_GL_ERROR_DEBUG(); + } + + return self; +} + +- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer +{ + // Allocate color buffer backing based on the current layer size + glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer_); + + if( ! [context_ renderbufferStorage:GL_RENDERBUFFER fromDrawable:layer] ) + CCLOG(@"failed to call context"); + + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth_); + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight_); + + CCLOG(@"cocos2d: surface size: %dx%d", (int)backingWidth_, (int)backingHeight_); + + if (multiSampling_) + { + if ( msaaColorbuffer_) { + glDeleteRenderbuffers(1, &msaaColorbuffer_); + msaaColorbuffer_ = 0; + } + + /* Create the offscreen MSAA color buffer. + After rendering, the contents of this will be blitted into ColorRenderbuffer */ + + //msaaFrameBuffer needs to be binded + glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer_); + glGenRenderbuffers(1, &msaaColorbuffer_); + NSAssert(msaaFramebuffer_, @"Can't create MSAA color buffer"); + + glBindRenderbuffer(GL_RENDERBUFFER, msaaColorbuffer_); + + glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samplesToUse_, pixelFormat_ , backingWidth_, backingHeight_); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msaaColorbuffer_); + + GLenum error; + if ( (error=glCheckFramebufferStatus(GL_FRAMEBUFFER)) != GL_FRAMEBUFFER_COMPLETE) + { + CCLOG(@"Failed to make complete framebuffer object 0x%X", error); + return NO; + } + } + + CHECK_GL_ERROR(); + + if (depthFormat_) + { + if( ! depthBuffer_ ) { + glGenRenderbuffers(1, &depthBuffer_); + NSAssert(depthBuffer_, @"Can't create depth buffer"); + } + + glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer_); + + if( multiSampling_ ) + glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samplesToUse_, depthFormat_,backingWidth_, backingHeight_); + else + glRenderbufferStorage(GL_RENDERBUFFER, depthFormat_, backingWidth_, backingHeight_); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer_); + + // bind color buffer + glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer_); + } + + CHECK_GL_ERROR(); + + GLenum error; + if( (error=glCheckFramebufferStatus(GL_FRAMEBUFFER)) != GL_FRAMEBUFFER_COMPLETE) + { + CCLOG(@"Failed to make complete framebuffer object 0x%X", error); + return NO; + } + + return YES; +} + +-(CGSize) backingSize +{ + return CGSizeMake( backingWidth_, backingHeight_); +} + +- (NSString*) description +{ + return [NSString stringWithFormat:@"<%@ = %08X | size = %ix%i>", [self class], self, backingWidth_, backingHeight_]; +} + +- (unsigned int) colorRenderBuffer +{ + return colorRenderbuffer_; +} + +- (unsigned int) defaultFrameBuffer +{ + return defaultFramebuffer_; +} + +- (unsigned int) msaaFrameBuffer +{ + return msaaFramebuffer_; +} + +- (unsigned int) msaaColorBuffer +{ + return msaaColorbuffer_; +} + +- (void)dealloc +{ + CCLOGINFO(@"cocos2d: deallocing %@", self); + + // Tear down GL + if (defaultFramebuffer_) { + glDeleteFramebuffers(1, &defaultFramebuffer_); + defaultFramebuffer_ = 0; + } + + if (colorRenderbuffer_) { + glDeleteRenderbuffers(1, &colorRenderbuffer_); + colorRenderbuffer_ = 0; + } + + if( depthBuffer_ ) { + glDeleteRenderbuffers(1, &depthBuffer_ ); + depthBuffer_ = 0; + } + + if ( msaaColorbuffer_) + { + glDeleteRenderbuffers(1, &msaaColorbuffer_); + msaaColorbuffer_ = 0; + } + + if ( msaaFramebuffer_) + { + glDeleteRenderbuffers(1, &msaaFramebuffer_); + msaaFramebuffer_ = 0; + } + + // Tear down context + if ([EAGLContext currentContext] == context_) + [EAGLContext setCurrentContext:nil]; + + [context_ release]; + context_ = nil; + + [super dealloc]; +} + +@end + +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCESRenderer.h b/Example/libs/cocos2d/Platforms/iOS/CCESRenderer.h new file mode 100644 index 0000000..59768f5 --- /dev/null +++ b/Example/libs/cocos2d/Platforms/iOS/CCESRenderer.h @@ -0,0 +1,54 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * + * File autogenerated with Xcode. Adapted for cocos2d needs. + */ + +// Only compile this code on iOS. These files should NOT be included on your Mac project. +// But in case they are included, it won't be compiled. +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS + +#import + +#import +#import + +@protocol CCESRenderer + +- (id) initWithDepthFormat:(unsigned int)depthFormat withPixelFormat:(unsigned int)pixelFormat withSharegroup:(EAGLSharegroup*)sharegroup withMultiSampling:(BOOL) multiSampling withNumberOfSamples:(unsigned int) requestedSamples; + +- (BOOL) resizeFromLayer:(CAEAGLLayer *)layer; + +- (EAGLContext*) context; +- (CGSize) backingSize; + +- (unsigned int) colorRenderBuffer; +- (unsigned int) defaultFrameBuffer; +- (unsigned int) msaaFrameBuffer; +- (unsigned int) msaaColorBuffer; +@end + +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCGLView.h b/Example/libs/cocos2d/Platforms/iOS/CCGLView.h new file mode 100644 index 0000000..ecac2e0 --- /dev/null +++ b/Example/libs/cocos2d/Platforms/iOS/CCGLView.h @@ -0,0 +1,160 @@ +/* + +===== IMPORTANT ===== + +This is sample code demonstrating API, technology or techniques in development. +Although this sample code has been reviewed for technical accuracy, it is not +final. Apple is supplying this information to help you plan for the adoption of +the technologies and programming interfaces described herein. This information +is subject to change, and software implemented based on this sample code should +be tested with final operating system software and final documentation. Newer +versions of this sample code may be provided with future seeds of the API or +technology. For information about updates to this and other developer +documentation, view the New & Updated sidebars in subsequent documentation +seeds. + +===================== + +File: CCGLView.h +Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a +UIView subclass. + +Version: 1.3 + +Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. +("Apple") in consideration of your agreement to the following terms, and your +use, installation, modification or redistribution of this Apple software +constitutes acceptance of these terms. If you do not agree with these terms, +please do not use, install, modify or redistribute this Apple software. + +In consideration of your agreement to abide by the following terms, and subject +to these terms, Apple grants you a personal, non-exclusive license, under +Apple's copyrights in this original Apple software (the "Apple Software"), to +use, reproduce, modify and redistribute the Apple Software, with or without +modifications, in source and/or binary forms; provided that if you redistribute +the Apple Software in its entirety and without modifications, you must retain +this notice and the following text and disclaimers in all such redistributions +of the Apple Software. +Neither the name, trademarks, service marks or logos of Apple Inc. may be used +to endorse or promote products derived from the Apple Software without specific +prior written permission from Apple. Except as expressly stated in this notice, +no other rights or licenses, express or implied, are granted by Apple herein, +including but not limited to any patent rights that may be infringed by your +derivative works or by other works in which the Apple Software may be +incorporated. + +The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO +WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED +WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN +COMBINATION WITH YOUR PRODUCTS. + +IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR +DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF +CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF +APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Copyright (C) 2008 Apple Inc. All Rights Reserved. + +*/ + +// Only compile this code on iOS. These files should NOT be included on your Mac project. +// But in case they are included, it won't be compiled. +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS + +#import +#import +#import +#import +#import + +#import "CCESRenderer.h" + +//CLASSES: + +@class CCGLView; + +//PROTOCOLS: + +@protocol CCTouchDelegate +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; +@end + +//CLASS INTERFACE: + +/** CCGLView Class. + * This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass. + * The view content is basically an EAGL surface you render your OpenGL scene into. + * Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel. + */ +@interface CCGLView : UIView +{ + id renderer_; + EAGLContext *context_; // weak ref + + NSString *pixelformat_; + GLuint depthFormat_; + BOOL preserveBackbuffer_; + + CGSize size_; + BOOL discardFramebufferSupported_; + id touchDelegate_; + + //fsaa addition + BOOL multisampling_; + unsigned int requestedSamples_; +} + +/** creates an initializes an CCGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer. */ ++ (id) viewWithFrame:(CGRect)frame; +/** creates an initializes an CCGLView with a frame, a color buffer format, and 0-bit depth buffer. */ ++ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format; +/** creates an initializes an CCGLView with a frame, a color buffer format, and a depth buffer. */ ++ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth; +/** creates an initializes an CCGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping */ ++ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples; + +/** Initializes an CCGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */ +- (id) initWithFrame:(CGRect)frame; //These also set the current context +/** Initializes an CCGLView with a frame, a color buffer format, and 0-bit depth buffer */ +- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format; +/** Initializes an CCGLView with a frame, a color buffer format, a depth buffer format, a sharegroup and multisampling support */ +- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples; + +/** pixel format: it could be RGBA8 (32-bit) or RGB565 (16-bit) */ +@property(nonatomic,readonly) NSString* pixelFormat; +/** depth format of the render buffer: 0, 16 or 24 bits*/ +@property(nonatomic,readonly) GLuint depthFormat; + +/** returns surface size in pixels */ +@property(nonatomic,readonly) CGSize surfaceSize; + +/** OpenGL context */ +@property(nonatomic,readonly) EAGLContext *context; + +@property(nonatomic,readwrite) BOOL multiSampling; + +/** touch delegate */ +@property(nonatomic,readwrite,assign) id touchDelegate; + +/** CCGLView uses double-buffer. This method swaps the buffers */ +-(void) swapBuffers; + +/** uses and locks the OpenGL context */ +-(void) lockOpenGLContext; + +/** unlocks the openGL context */ +-(void) unlockOpenGLContext; + +- (CGPoint) convertPointFromViewToSurface:(CGPoint)point; +- (CGRect) convertRectFromViewToSurface:(CGRect)rect; +@end + +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCGLView.m b/Example/libs/cocos2d/Platforms/iOS/CCGLView.m new file mode 100644 index 0000000..3347c5e --- /dev/null +++ b/Example/libs/cocos2d/Platforms/iOS/CCGLView.m @@ -0,0 +1,360 @@ +/* + +===== IMPORTANT ===== + +This is sample code demonstrating API, technology or techniques in development. +Although this sample code has been reviewed for technical accuracy, it is not +final. Apple is supplying this information to help you plan for the adoption of +the technologies and programming interfaces described herein. This information +is subject to change, and software implemented based on this sample code should +be tested with final operating system software and final documentation. Newer +versions of this sample code may be provided with future seeds of the API or +technology. For information about updates to this and other developer +documentation, view the New & Updated sidebars in subsequent documentation +seeds. + +===================== + +File: CCGLView.m +Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a +UIView subclass. + +Version: 1.3 + +Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. +("Apple") in consideration of your agreement to the following terms, and your +use, installation, modification or redistribution of this Apple software +constitutes acceptance of these terms. If you do not agree with these terms, +please do not use, install, modify or redistribute this Apple software. + +In consideration of your agreement to abide by the following terms, and subject +to these terms, Apple grants you a personal, non-exclusive license, under +Apple's copyrights in this original Apple software (the "Apple Software"), to +use, reproduce, modify and redistribute the Apple Software, with or without +modifications, in source and/or binary forms; provided that if you redistribute +the Apple Software in its entirety and without modifications, you must retain +this notice and the following text and disclaimers in all such redistributions +of the Apple Software. +Neither the name, trademarks, service marks or logos of Apple Inc. may be used +to endorse or promote products derived from the Apple Software without specific +prior written permission from Apple. Except as expressly stated in this notice, +no other rights or licenses, express or implied, are granted by Apple herein, +including but not limited to any patent rights that may be infringed by your +derivative works or by other works in which the Apple Software may be +incorporated. + +The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO +WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED +WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN +COMBINATION WITH YOUR PRODUCTS. + +IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR +DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF +CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF +APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Copyright (C) 2008 Apple Inc. All Rights Reserved. + +*/ + +/* + Modified for cocos2d project + */ + +// Only compile this code on iOS. These files should NOT be included on your Mac project. +// But in case they are included, it won't be compiled. +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS + +#import + +#import "CCGLView.h" +#import "CCES2Renderer.h" +#import "../../CCDirector.h" +#import "../../ccMacros.h" +#import "../../CCConfiguration.h" +#import "../../Support/OpenGL_Internal.h" + + +//CLASS IMPLEMENTATIONS: + +@interface CCGLView (Private) +- (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup; +- (unsigned int) convertPixelFormat:(NSString*) pixelFormat; +@end + +@implementation CCGLView + +@synthesize surfaceSize=size_; +@synthesize pixelFormat=pixelformat_, depthFormat=depthFormat_; +@synthesize touchDelegate=touchDelegate_; +@synthesize context=context_; +@synthesize multiSampling=multiSampling_; + ++ (Class) layerClass +{ + return [CAEAGLLayer class]; +} + ++ (id) viewWithFrame:(CGRect)frame +{ + return [[[self alloc] initWithFrame:frame] autorelease]; +} + ++ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format +{ + return [[[self alloc] initWithFrame:frame pixelFormat:format] autorelease]; +} + ++ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth +{ + return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0] autorelease]; +} + ++ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples +{ + return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease]; +} + +- (id) initWithFrame:(CGRect)frame +{ + return [self initWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; +} + +- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format +{ + return [self initWithFrame:frame pixelFormat:format depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; +} + +- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples +{ + if((self = [super initWithFrame:frame])) + { + pixelformat_ = format; + depthFormat_ = depth; + multiSampling_ = sampling; + requestedSamples_ = nSamples; + preserveBackbuffer_ = retained; + + if( ! [self setupSurfaceWithSharegroup:sharegroup] ) { + [self release]; + return nil; + } + + CHECK_GL_ERROR_DEBUG(); + } + + return self; +} + +-(id) initWithCoder:(NSCoder *)aDecoder +{ + if( (self = [super initWithCoder:aDecoder]) ) { + + CAEAGLLayer* eaglLayer = (CAEAGLLayer*)[self layer]; + + pixelformat_ = kEAGLColorFormatRGB565; + depthFormat_ = 0; // GL_DEPTH_COMPONENT24; + multiSampling_= NO; + requestedSamples_ = 0; + size_ = [eaglLayer bounds].size; + + if( ! [self setupSurfaceWithSharegroup:nil] ) { + [self release]; + return nil; + } + + CHECK_GL_ERROR_DEBUG(); + } + + return self; +} + +-(BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup +{ + CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; + + eaglLayer.opaque = YES; + eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: + [NSNumber numberWithBool:preserveBackbuffer_], kEAGLDrawablePropertyRetainedBacking, + pixelformat_, kEAGLDrawablePropertyColorFormat, nil]; + + // ES2 renderer only + renderer_ = [[CCES2Renderer alloc] initWithDepthFormat:depthFormat_ + withPixelFormat:[self convertPixelFormat:pixelformat_] + withSharegroup:sharegroup + withMultiSampling:multiSampling_ + withNumberOfSamples:requestedSamples_]; + + NSAssert( renderer_, @"OpenGL ES 2.0 is required"); + + if (!renderer_) + return NO; + + context_ = [renderer_ context]; + + discardFramebufferSupported_ = [[CCConfiguration sharedConfiguration] supportsDiscardFramebuffer]; + + CHECK_GL_ERROR_DEBUG(); + + return YES; +} + +- (void) dealloc +{ + CCLOGINFO(@"cocos2d: deallocing %@", self); + + [renderer_ release]; + [super dealloc]; +} + +- (void) layoutSubviews +{ + [renderer_ resizeFromLayer:(CAEAGLLayer*)self.layer]; + + size_ = [renderer_ backingSize]; + + // Issue #914 #924 + CCDirector *director = [CCDirector sharedDirector]; + [director reshapeProjection:size_]; + + // Avoid flicker. Issue #350 + NSThread *thread = [director runningThread]; + [director performSelector:@selector(drawScene) onThread:thread withObject:nil waitUntilDone:YES]; +} + +- (void) swapBuffers +{ + // IMPORTANT: + // - preconditions + // -> context_ MUST be the OpenGL context + // -> renderbuffer_ must be the the RENDER BUFFER + + if (multiSampling_) + { + /* Resolve from msaaFramebuffer to resolveFramebuffer */ + //glDisable(GL_SCISSOR_TEST); + glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, [renderer_ msaaFrameBuffer]); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, [renderer_ defaultFrameBuffer]); + glResolveMultisampleFramebufferAPPLE(); + } + + if( discardFramebufferSupported_) + { + if (multiSampling_) + { + if (depthFormat_) + { + GLenum attachments[] = {GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT}; + glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, attachments); + } + else + { + GLenum attachments[] = {GL_COLOR_ATTACHMENT0}; + glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 1, attachments); + } + + glBindRenderbuffer(GL_RENDERBUFFER, [renderer_ colorRenderBuffer]); + + } + + // not MSAA + else if (depthFormat_ ) { + GLenum attachments[] = { GL_DEPTH_ATTACHMENT}; + glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments); + } + } + + if(![context_ presentRenderbuffer:GL_RENDERBUFFER]) + CCLOG(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__); + + // We can safely re-bind the framebuffer here, since this will be the + // 1st instruction of the new main loop + if( multiSampling_ ) + glBindFramebuffer(GL_FRAMEBUFFER, [renderer_ msaaFrameBuffer]); + + CHECK_GL_ERROR_DEBUG(); +} + +-(void) lockOpenGLContext +{ + // unused on iOS +} + +-(void) unlockOpenGLContext +{ + // unused on iOS +} + +- (unsigned int) convertPixelFormat:(NSString*) pixelFormat +{ + // define the pixel format + GLenum pFormat; + + + if([pixelFormat isEqualToString:@"EAGLColorFormat565"]) + pFormat = GL_RGB565; + else + pFormat = GL_RGBA8_OES; + + return pFormat; +} + +#pragma mark CCGLView - Point conversion + +- (CGPoint) convertPointFromViewToSurface:(CGPoint)point +{ + CGRect bounds = [self bounds]; + + return CGPointMake((point.x - bounds.origin.x) / bounds.size.width * size_.width, (point.y - bounds.origin.y) / bounds.size.height * size_.height); +} + +- (CGRect) convertRectFromViewToSurface:(CGRect)rect +{ + CGRect bounds = [self bounds]; + + return CGRectMake((rect.origin.x - bounds.origin.x) / bounds.size.width * size_.width, (rect.origin.y - bounds.origin.y) / bounds.size.height * size_.height, rect.size.width / bounds.size.width * size_.width, rect.size.height / bounds.size.height * size_.height); +} + +// Pass the touches to the superview +#pragma mark CCGLView - Touch Delegate + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event +{ + if(touchDelegate_) + { + [touchDelegate_ touchesBegan:touches withEvent:event]; + } +} + +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event +{ + if(touchDelegate_) + { + [touchDelegate_ touchesMoved:touches withEvent:event]; + } +} + +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event +{ + if(touchDelegate_) + { + [touchDelegate_ touchesEnded:touches withEvent:event]; + } +} +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event +{ + if(touchDelegate_) + { + [touchDelegate_ touchesCancelled:touches withEvent:event]; + } +} + +@end + + +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Support/CCVertex.h b/Example/libs/cocos2d/Support/CCVertex.h new file mode 100644 index 0000000..671e365 --- /dev/null +++ b/Example/libs/cocos2d/Support/CCVertex.h @@ -0,0 +1,36 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2011 ForzeField Studios S.L. http://forzefield.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import "ccTypes.h" + +/** @file CCVertex.h */ + +/** converts a line to a polygon */ +void ccVertexLineToPolygon(CGPoint *points, float stroke, ccVertex2F *vertices, ccTex2F *texCoords, NSUInteger offset, NSUInteger nuPoints); + +/** returns wheter or not the line intersects */ +BOOL ccVertexLineIntersect(float Ax, float Ay, + float Bx, float By, + float Cx, float Cy, + float Dx, float Dy, float *T); diff --git a/Example/libs/cocos2d/Support/CCVertex.m b/Example/libs/cocos2d/Support/CCVertex.m new file mode 100644 index 0000000..ad7d398 --- /dev/null +++ b/Example/libs/cocos2d/Support/CCVertex.m @@ -0,0 +1,138 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2011 ForzeField Studios S.L. http://forzefield.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import "CCVertex.h" +#import "CGPointExtension.h" +#import "../ccMacros.h" + +void ccVertexLineToPolygon(CGPoint *points, float stroke, ccVertex2F *vertices, ccTex2F *texCoords, NSUInteger offset, NSUInteger nuPoints) +{ + nuPoints += offset; + if(nuPoints<=1) return; + + stroke *= 0.5f; + + NSUInteger idx; + NSUInteger nuPointsMinus = nuPoints-1; + float texDelta = 1.0f/(float)nuPointsMinus; + + for(NSUInteger i = offset; i1.0f) + fixVertex = YES; + + if(fixVertex) + { + vertices[idx1] = p4; + vertices[idx1+1] = p3; + } + } +} + +BOOL ccVertexLineIntersect(float Ax, float Ay, + float Bx, float By, + float Cx, float Cy, + float Dx, float Dy, float *T) +{ + float distAB, theCos, theSin, newX; + + // FAIL: Line undefined + if ((Ax==Bx && Ay==By) || (Cx==Dx && Cy==Dy)) return NO; + + // Translate system to make A the origin + Bx-=Ax; By-=Ay; + Cx-=Ax; Cy-=Ay; + Dx-=Ax; Dy-=Ay; + + // Length of segment AB + distAB = sqrtf(Bx*Bx+By*By); + + // Rotate the system so that point B is on the positive X axis. + theCos = Bx/distAB; + theSin = By/distAB; + newX = Cx*theCos+Cy*theSin; + Cy = Cy*theCos-Cx*theSin; Cx = newX; + newX = Dx*theCos+Dy*theSin; + Dy = Dy*theCos-Dx*theSin; Dx = newX; + + // FAIL: Lines are parallel. + if (Cy == Dy) return NO; + + // Discover the relative position of the intersection in the line AB + *T = (Dx+(Cx-Dx)*Dy/(Dy-Cy))/distAB; + + // Success. + return YES; +} diff --git a/Example/libs/cocos2d/Support/NSThread+performBlock.h b/Example/libs/cocos2d/Support/NSThread+performBlock.h new file mode 100644 index 0000000..bb5ec8d --- /dev/null +++ b/Example/libs/cocos2d/Support/NSThread+performBlock.h @@ -0,0 +1,22 @@ +/* cocos2d for iPhone + * + * http://www.cocos2d-iphone.org + * + * + * Idea taken from: http://stackoverflow.com/a/3940757 + * + */ + +#import + +@interface NSThread (sendBlockToBackground) +/** performs a block on the thread. It won't wait until it is done. */ +- (void) performBlock:(void (^)(void))block; + +/** performs a block on the thread. */ +- (void) performBlock:(void (^)(void))block waitUntilDone:(BOOL)wait; + +/** performs a block on the thread. */ +- (void) performBlock:(void (^)(id param))block withObject:(id)object waitUntilDone:(BOOL)wait; + +@end diff --git a/Example/libs/cocos2d/Support/NSThread+performBlock.m b/Example/libs/cocos2d/Support/NSThread+performBlock.m new file mode 100644 index 0000000..65d85f5 --- /dev/null +++ b/Example/libs/cocos2d/Support/NSThread+performBlock.m @@ -0,0 +1,76 @@ +/* cocos2d for iPhone + * + * http://www.cocos2d-iphone.org + * + * + * Idea taken from: http://stackoverflow.com/a/3940757 + * + */ + + +#import "NSThread+performBlock.h" +#import "../ccMacros.h" + +typedef void (^BlockWithParam)(id param); +@interface CCObjectWith2Params : NSObject +{ +@public + BlockWithParam block; + id param; +} +@property (nonatomic,copy) id block; +@property (nonatomic,readwrite,retain) id param; +@end + +@implementation CCObjectWith2Params +@synthesize block, param; +- (void)dealloc { + CCLOG(@"cocos2d: deallocing %@", self); + [block release]; + [param release]; + + [super dealloc]; +} +@end + +@implementation NSThread (sendBlockToBackground) + +- (void) performBlock: (void (^)(void))block; +{ + return [self performBlock:block waitUntilDone:NO]; +} + +- (void) performBlock:(void (^)(void))block waitUntilDone:(BOOL)wait +{ + [self performSelector:@selector(executeBlock:) + onThread:self + withObject: block + waitUntilDone: wait]; +} + +- (void) performBlock:(void (^)(id param))block withObject:(id)object waitUntilDone:(BOOL)wait +{ + CCObjectWith2Params * obj = [[CCObjectWith2Params alloc] init]; + obj.block = block; + obj.param = object; + + [obj autorelease]; + + [self performSelector:@selector(executeBlock2:) + onThread:self + withObject:obj + waitUntilDone:wait]; +} + +- (void) executeBlock: (void (^)(void))block; +{ + block(); +} + +- (void) executeBlock2:(CCObjectWith2Params*)object +{ + BlockWithParam block = object.block; + block( object.param ); +} + +@end diff --git a/Example/libs/cocos2d/ccDeprecated.h b/Example/libs/cocos2d/ccDeprecated.h new file mode 100644 index 0000000..2cf3605 --- /dev/null +++ b/Example/libs/cocos2d/ccDeprecated.h @@ -0,0 +1,219 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2012 Ricardo Quesada + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import "ccConfig.h" + +#if CC_ENABLE_DEPRECATED + +#import "ccMacros.h" +#import "CCMenu.h" +#import "CCDirector.h" +#import "CCSprite.h" +#import "CCGLProgram.h" +#import "CCAnimation.h" +#import "CCScheduler.h" +#import "CCActionManager.h" +#import "CCActionInterval.h" +#import "CCRenderTexture.h" +#import "Support/CCFileUtils.h" +#import "Platforms/Mac/CCDirectorMac.h" +#import "Platforms/iOS/CCTouchDispatcher.h" +#import "Platforms/iOS/CCDirectorIOS.h" + + +/* + * + * IMPORTANT + * + * See the ccDrepecated.m file to see the name of the new methods + * + */ + +// ccTypes.h +enum { + kCCResolutionStandard DEPRECATED_ATTRIBUTE = kCCResolutioniPhone, + kCCResolutionRetinaDisplay DEPRECATED_ATTRIBUTE = kCCResolutioniPhoneRetinaDisplay, + kCCMenuTouchPriority DEPRECATED_ATTRIBUTE = kCCMenuHandlerPriority, +}; + +// CCRenderTexture.h +enum { + kCCImageFormatJPG DEPRECATED_ATTRIBUTE = kCCImageFormatJPEG, + kCCImageFormatRawData UNAVAILABLE_ATTRIBUTE, +}; + +// Free functions +void ccGLUniformModelViewProjectionMatrix(CCGLProgram* program) DEPRECATED_ATTRIBUTE; + +// Renamed classes +DEPRECATED_ATTRIBUTE @interface EAGLView : CCGLView +@end + +DEPRECATED_ATTRIBUTE @interface MacView : CCGLView +@end + +// hack to prevent "incopatible pointer type" +#define GLProgram CCGLProgram + +// Extensions +@interface CCScheduler (Deprecated) +// new: [director scheduler] ++(CCScheduler*) sharedScheduler DEPRECATED_ATTRIBUTE; +@end + +@interface CCActionManager (Deprecated) +// new: [director actionManager] ++(CCActionManager*) sharedManager DEPRECATED_ATTRIBUTE; +@end + +#if __CC_PLATFORM_IOS +@interface CCTouchDispatcher (Deprecated) +// new: [director touchDispatcher] ++(CCTouchDispatcher*) sharedDispatcher DEPRECATED_ATTRIBUTE; +@end +#elif __CC_PLATFORM_MAC +@interface CCEventDispatcher (Deprecated) +// new: [director eventDispatcher] ++(CCEventDispatcher*) sharedDispatcher DEPRECATED_ATTRIBUTE; +@end +#endif // __CC_PLATFORM_MAC + +@interface CCDirector (Deprecated) +// new: setView: +-(void) setOpenGLView:(CCGLView*)view DEPRECATED_ATTRIBUTE; +// new: view +-(CCGLView*) openGLView DEPRECATED_ATTRIBUTE; +// new: setDisplayStats: +-(void) setDisplayFPS:(BOOL)display DEPRECATED_ATTRIBUTE; +@end + + +@interface CCSprite (Deprecated) +// new: spriteWithTexture:rect: ++(id) spriteWithBatchNode:(CCSpriteBatchNode*)node rect:(CGRect)rect DEPRECATED_ATTRIBUTE; +// new: initWithTexture:rect: +-(id) initWithBatchNode:(CCSpriteBatchNode*)node rect:(CGRect)rect DEPRECATED_ATTRIBUTE; +// displayFrame +-(CCSpriteFrame*) displayedFrame DEPRECATED_ATTRIBUTE; +@end + +@interface CCMenuItemAtlasFont (Deprecated) +// new itemWithStirng:charmapFile:itemWidth:itemHeight:startCharMap ++(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap DEPRECATED_ATTRIBUTE; +// new itemWithStirng:charmapFile:itemWidth:itemHeight:startCharMap:target:selector ++(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb DEPRECATED_ATTRIBUTE; +// new itemWithStirng:charmapFile:itemWidth:itemHeight:startCharMap:block ++(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; +// new initWithStirng:charmapFile:itemWidth:itemHeight:startCharMap:target:selector +-(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb DEPRECATED_ATTRIBUTE; +// new initWithStirng:charmapFile:itemWidth:itemHeight:startCharMap:block +-(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; +@end + + +@interface CCMenuItemFont (Deprecated) +// new: itemWithString: ++(id) itemFromString: (NSString*) value DEPRECATED_ATTRIBUTE; +// new: itemWithString:target:selector ++(id) itemFromString: (NSString*) value target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; +// new: itemWithString:block: ++(id) itemFromString: (NSString*) value block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; +// new: initWithString:target:selector +-(id) initFromString: (NSString*) value target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; +// new: initWithString:block: +-(id) initFromString: (NSString*) value block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; +@end + +@interface CCMenuItemSprite (Deprecated) ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite DEPRECATED_ATTRIBUTE; ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector DEPRECATED_ATTRIBUTE; ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector DEPRECATED_ATTRIBUTE; ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; + +-(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector DEPRECATED_ATTRIBUTE; +-(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; +@end + +@interface CCMenuItemImage (Deprecated) +// new: itemWithNormalImage:selectedImage: ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 DEPRECATED_ATTRIBUTE; +// new: itemWithNormalImage:selectedImage:target:selector ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; +// new: itemWithNormalImage:selectedImage:disabledImage:target:selector ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; +// new: itemWithNormalImage:selectedImage:block ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; +// new: itemWithNormalImage:selectedImage:disabledImage:block ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; +// new: initWithNormalImage:selectedImage:disabledImage:target:selector +-(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; +// new: initWithNormalImage:selectedImage:disabledImage:block +-(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; +@end + +@interface CCAnimation (Deprecated) ++(id) animationWithFrames:(NSArray*)arrayOfSpriteFrameNames DEPRECATED_ATTRIBUTE; ++(id) animationWithFrames:(NSArray*)arrayOfSpriteFrameNames delay:(float)delay DEPRECATED_ATTRIBUTE; +-(id) initWithFrames:(NSArray*)arrayOfSpriteFrameNames DEPRECATED_ATTRIBUTE; +-(id) initWithFrames:(NSArray *)arrayOfSpriteFrameNames delay:(float)delay DEPRECATED_ATTRIBUTE; +-(void) addFrame:(CCSpriteFrame*)frame DEPRECATED_ATTRIBUTE; +-(void) addFrameWithFilename:(NSString*)filename DEPRECATED_ATTRIBUTE; +-(void) addFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect DEPRECATED_ATTRIBUTE; +@end + +@interface CCAnimate (Deprecated) +// new: actionWithAnimation: ++(id) actionWithAnimation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame DEPRECATED_ATTRIBUTE; +// new: actiontWithAnimation: ++(id) actionWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame DEPRECATED_ATTRIBUTE; +// new: initWithAnimation: +-(id) initWithAnimation:(CCAnimation*) a restoreOriginalFrame:(BOOL)restoreOriginalFrame DEPRECATED_ATTRIBUTE; +// new: initWithAnimation: +-(id) initWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame DEPRECATED_ATTRIBUTE; +@end + +@interface CCRenderTexture (Deprecated) +// new: saveToFile: +-(BOOL)saveBuffer:(NSString*)name DEPRECATED_ATTRIBUTE; +// new: saveToFile:format: +-(BOOL)saveBuffer:(NSString*)name format:(int)format DEPRECATED_ATTRIBUTE; +// new: -- not implemented on v2.0 +-(NSData*)getUIImageAsDataFromBuffer:(int) format UNAVAILABLE_ATTRIBUTE; +#if __CC_PLATFORM_IOS +// new: getUIImage +-(UIImage *)getUIImageFromBuffer DEPRECATED_ATTRIBUTE; +#endif +@end + +#if __CC_PLATFORM_IOS +@interface CCFileUtils (Deprecated) +// new: setiPhoneRetinaDisplaySuffix ++(void) setRetinaDisplaySuffix:(NSString*)suffix DEPRECATED_ATTRIBUTE; +@end +#endif + + +#endif // CC_ENABLE_DEPRECATED + diff --git a/Example/libs/cocos2d/ccDeprecated.m b/Example/libs/cocos2d/ccDeprecated.m new file mode 100644 index 0000000..f0bec22 --- /dev/null +++ b/Example/libs/cocos2d/ccDeprecated.m @@ -0,0 +1,328 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2012 Ricardo Quesada + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import "ccDeprecated.h" + +#if CC_ENABLE_DEPRECATED + +#import "CCSpriteBatchNode.h" + +// Free functions +void ccGLUniformModelViewProjectionMatrix( CCGLProgram* program ) +{ + [program setUniformForModelViewProjectionMatrix]; +} + +@implementation CCScheduler (Deprecated) ++(CCScheduler*) sharedScheduler +{ + return [[CCDirector sharedDirector] scheduler]; +} +@end + +@implementation CCActionManager (Deprecated) ++(CCActionManager*) sharedManager +{ + return [[CCDirector sharedDirector] actionManager]; +} +@end + +#if __CC_PLATFORM_IOS +@implementation CCTouchDispatcher (Deprecated) ++(CCTouchDispatcher*) sharedDispatcher +{ + return [[CCDirector sharedDirector] touchDispatcher]; +} +@end +#elif __CC_PLATFORM_MAC +@implementation CCEventDispatcher (Deprecated) ++(CCEventDispatcher*) sharedDispatcher +{ + return [[CCDirector sharedDirector] eventDispatcher]; +} +@end +#endif // __CC_PLATFORM_MAC + +#pragma mark - CCDirector + +@implementation CCDirector (Deprecated) +-(void) setDisplayFPS:(BOOL)display +{ + [self setDisplayStats:display]; +} + +-(void) setOpenGLView:(CCGLView*)view +{ + [self setView:view]; +} + +-(CCGLView*) openGLView +{ + return (CCGLView*)view_; +} +@end + +@implementation CCSprite (Deprecated) + ++(id) spriteWithBatchNode:(CCSpriteBatchNode*)node rect:(CGRect)rect +{ + id ret = [self spriteWithTexture:node.texture rect:rect]; + [ret setBatchNode:node]; + return ret; +} + +-(id) initWithBatchNode:(CCSpriteBatchNode*)node rect:(CGRect)rect +{ + self = [self initWithTexture:node.texture rect:rect]; + [self setBatchNode:node]; + return self; +} + +-(CCSpriteFrame*) displayedFrame +{ + return [self displayedFrame]; +} +@end + +@implementation CCMenuItemAtlasFont (Deprecated) ++(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap +{ + return [self itemWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap]; +} ++(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb +{ + return [self itemWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:rec selector:cb]; +} ++(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block +{ + return [self itemWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap block:block]; +} +-(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb +{ + return [self initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:rec selector:cb]; +} +-(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block +{ + return [self initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap block:block]; +} +@end + +@implementation CCMenuItemFont (Deprecated) ++(id) itemFromString: (NSString*) value +{ + return [self itemWithString:value]; +} ++(id) itemFromString: (NSString*) value target:(id) r selector:(SEL) s +{ + return [self itemWithString:value target:r selector:s]; +} ++(id) itemFromString: (NSString*) value block:(void(^)(id sender))block +{ + return [self itemWithString:value block:block]; +} +-(id) initFromString: (NSString*) value target:(id) r selector:(SEL) s +{ + return [self initWithString:value target:r selector:s]; +} +-(id) initFromString: (NSString*) value block:(void(^)(id sender))block +{ + return [self initWithString:value block:block]; +} +@end + +@implementation CCMenuItemSprite (Deprecated) ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite +{ + return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite]; +} ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector +{ + return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite target:target selector:selector]; +} ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector +{ + return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite target:target selector:selector]; +} ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block +{ + return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite block:block]; +} ++(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block +{ + return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:block]; +} + +-(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector +{ + return [self initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite target:target selector:selector]; +} +-(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block +{ + return [self initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:block]; +} +@end + +@implementation CCMenuItemImage (Deprecated) ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 +{ + return [self itemWithNormalImage:value selectedImage:value2]; +} ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) r selector:(SEL) s +{ + return [self itemWithNormalImage:value selectedImage:value2 target:r selector:s]; +} ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s +{ + return [self itemWithNormalImage:value selectedImage:value2 disabledImage:value3 target:r selector:s]; +} ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block +{ + return [self itemWithNormalImage:value selectedImage:value2 block:block]; +} ++(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block +{ + return [self itemWithNormalImage:value selectedImage:value2 disabledImage:value3 block:block]; +} +-(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s +{ + return [self initWithNormalImage:value selectedImage:value2 disabledImage:value3 target:r selector:s]; +} +-(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block +{ + return [self initWithNormalImage:value selectedImage:value2 disabledImage:value3 block:block]; +} +@end + + +@implementation CCAnimation (Deprecated) ++(id) animationWithFrames:(NSArray*)arrayOfSpriteFrameNames +{ + return [self animationWithSpriteFrames:arrayOfSpriteFrameNames]; +} ++(id) animationWithFrames:(NSArray*)arrayOfSpriteFrameNames delay:(float)delay +{ + return [self animationWithSpriteFrames:arrayOfSpriteFrameNames delay:delay]; +} +-(id) initWithFrames:(NSArray*)arrayOfSpriteFrameNames +{ + return [self initWithSpriteFrames:arrayOfSpriteFrameNames]; +} +-(id) initWithFrames:(NSArray *)arrayOfSpriteFrameNames delay:(float)delay +{ + return [self initWithSpriteFrames:arrayOfSpriteFrameNames delay:delay]; +} +-(void) addFrame:(CCSpriteFrame*)frame +{ + [self addSpriteFrame:frame]; +} +-(void) addFrameWithFilename:(NSString*)filename +{ + [self addSpriteFrameWithFilename:filename]; +} +-(void) addFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect +{ + [self addSpriteFrameWithTexture:texture rect:rect]; +} +@end + +@implementation CCAnimate (Deprecated) ++(id) actionWithAnimation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame +{ + CCAnimation *anim = [[animation copy] autorelease]; + anim.restoreOriginalFrame = restoreOriginalFrame; + + return [[[self alloc] initWithAnimation:anim] autorelease]; +} ++(id) actionWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame +{ + CCAnimation *anim = [[animation copy] autorelease]; + anim.restoreOriginalFrame = restoreOriginalFrame; + anim.delayPerUnit = duration / animation.frames.count; + + return [[[self alloc] initWithAnimation:anim] autorelease]; +} +-(id) initWithAnimation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame +{ + CCAnimation *anim = [[animation copy] autorelease]; + anim.restoreOriginalFrame = restoreOriginalFrame; + + return [self initWithAnimation:anim]; +} +-(id) initWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame +{ + CCAnimation *anim = [[animation copy] autorelease]; + anim.restoreOriginalFrame = restoreOriginalFrame; + anim.delayPerUnit = duration / animation.frames.count; + + return [self initWithAnimation:anim]; +} +@end + + +@implementation CCRenderTexture (Deprecated) +-(BOOL)saveBuffer:(NSString*)name +{ + return [self saveToFile:name]; +} +-(BOOL)saveBuffer:(NSString*)name format:(int)format +{ + return [self saveToFile:name format:format]; +} + +-(NSData*)getUIImageAsDataFromBuffer:(int) format +{ + NSAssert(NO, @"NOT IMPLEMENTED IN V2.0"); + + return nil; +} +#if __CC_PLATFORM_IOS +-(UIImage *)getUIImageFromBuffer +{ + return [self getUIImage]; +} +#endif +@end + +#if __CC_PLATFORM_IOS +@implementation CCFileUtils (Deprecated) ++(void) setRetinaDisplaySuffix:(NSString*)suffix +{ + return [self setiPhoneRetinaDisplaySuffix:suffix]; +} +@end +#endif + + +#if __CC_PLATFORM_IOS +@implementation EAGLView +@end + +#elif __CC_PLATFORM_MAC + +@implementation MacView +@end + +#endif // __CC_PLATFORM_MAC + +#endif // CC_ENABLE_DEPRECATED diff --git a/Example/libs/cocos2d/ccGLStateCache.h b/Example/libs/cocos2d/ccGLStateCache.h new file mode 100644 index 0000000..6e15e07 --- /dev/null +++ b/Example/libs/cocos2d/ccGLStateCache.h @@ -0,0 +1,143 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import +#import "ccMacros.h" +#if __CC_PLATFORM_IOS +#import +#import +#elif __CC_PLATFORM_MAC +#import +#endif // + +@class CCGLProgram; + +/** vertex attrib flags */ +enum { + kCCVertexAttribFlag_None = 0, + + kCCVertexAttribFlag_Position = 1 << 0, + kCCVertexAttribFlag_Color = 1 << 1, + kCCVertexAttribFlag_TexCoords = 1 << 2, + + kCCVertexAttribFlag_PosColorTex = ( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_Color | kCCVertexAttribFlag_TexCoords ), +}; + +/** GL server side states */ +typedef enum { +// CC_GL_SCISSOR_TEST = 1 << 0, +// CC_GL_STENCIL_TEST = 1 << 1, +// CC_GL_DEPTH_TEST = 1 << 2, + CC_GL_BLEND = 1 << 3, +// CC_GL_DITHER = 1 << 4, + +// CC_GL_ALL = ( CC_GL_SCISSOR_TEST | CC_GL_STENCIL_TEST | CC_GL_DEPTH_TEST | CC_GL_BLEND | CC_GL_DITHER ), + CC_GL_ALL = ( CC_GL_BLEND ), + +} ccGLServerState; + +#ifdef __cplusplus +extern "C" { +#endif + +/** @file ccGLStateCache.h +*/ + +/** Invalidates the GL state cache. + If CC_ENABLE_GL_STATE_CACHE it will reset the GL state cache. + @since v2.0.0 + */ +void ccGLInvalidateStateCache( void ); + +/** Uses the GL program in case program is different than the current one. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly. + @since v2.0.0 + */ +void ccGLUseProgram( GLuint program ); + +/** Deletes the GL program. If it is the one that is being used, it invalidates it. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly. + @since v2.0.0 + */ +void ccGLDeleteProgram( GLuint program ); + +/** Uses a blending function in case it not already used. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly. + @since v2.0.0 + */ +void ccGLBlendFunc(GLenum sfactor, GLenum dfactor); + +/** sets the projection matrix as dirty + @since v2.0.0 + */ +void ccSetProjectionMatrixDirty( void ); + +/** Will enable the vertex attribs that are passed as flags. + Possible flags: + + * kCCVertexAttribFlag_Position + * kCCVertexAttribFlag_Color + * kCCVertexAttribFlag_TexCoords + + These flags can be ORed. The flags that are not present, will be disabled. + + @since v2.0.0 + */ +void ccGLEnableVertexAttribs( unsigned int flags ); + +/** If the active texture is not textureEnum, then it will active it. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glActiveTexture() directly. + @since v2.0.0 + */ +void ccGLActiveTexture(GLenum textureEnum ); + +/** Returns the active texture. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glGetIntegerv(GL_ACTIVE_TEXTURE); + @since v2.0.0 + */ +GLenum ccGLGetActiveTexture( void ); + + +/** If the texture is not already bound, it binds it. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. + @since v2.0.0 + */ +void ccGLBindTexture2D(GLuint textureId ); + +/** It will delete a given texture. If the texture was bound, it will invalidate the cached. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. + @since v2.0.0 + */ +void ccGLDeleteTexture(GLuint textureId); + +/** It will enable / disable the server side GL states. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly. + @since v2.0.0 + */ +void ccGLEnable( ccGLServerState flags ); + +#ifdef __cplusplus +} +#endif diff --git a/Example/libs/cocos2d/ccGLStateCache.m b/Example/libs/cocos2d/ccGLStateCache.m new file mode 100644 index 0000000..89e2b3f --- /dev/null +++ b/Example/libs/cocos2d/ccGLStateCache.m @@ -0,0 +1,226 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import "ccGLStateCache.h" +#import "CCGLProgram.h" +#import "CCDirector.h" +#import "ccConfig.h" + +// extern +#import "kazmath/GL/matrix.h" +#import "kazmath/kazmath.h" + +static GLuint _ccCurrentProjectionMatrix = -1; +static BOOL _vertexAttribPosition = NO; +static BOOL _vertexAttribColor = NO; +static BOOL _vertexAttribTexCoords = NO; + +#if CC_ENABLE_GL_STATE_CACHE +#define kCCMaxActiveTexture 16 +static GLuint _ccCurrentShaderProgram = -1; +static GLuint _ccCurrentBoundTexture[kCCMaxActiveTexture] = {-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, }; +static GLenum _ccCurrentActiveTexture = (GL_TEXTURE0 - GL_TEXTURE0); +static GLenum _ccBlendingSource = -1; +static GLenum _ccBlendingDest = -1; +static ccGLServerState _ccGLServerState = 0; +#endif // CC_ENABLE_GL_STATE_CACHE + +#pragma mark - GL State Cache functions + +void ccGLInvalidateStateCache( void ) +{ + kmGLFreeAll(); + + _ccCurrentProjectionMatrix = -1; + _vertexAttribPosition = NO; + _vertexAttribColor = NO; + _vertexAttribTexCoords = NO; + +#if CC_ENABLE_GL_STATE_CACHE + _ccCurrentShaderProgram = -1; + for( NSInteger i=0; i < kCCMaxActiveTexture; i++ ) + _ccCurrentBoundTexture[i] = -1; + _ccCurrentActiveTexture = (GL_TEXTURE0 - GL_TEXTURE0); + _ccBlendingSource = -1; + _ccBlendingDest = -1; + _ccGLServerState = 0; +#endif +} + +void ccGLDeleteProgram( GLuint program ) +{ +#if CC_ENABLE_GL_STATE_CACHE + if( program == _ccCurrentShaderProgram ) + _ccCurrentShaderProgram = -1; +#endif // CC_ENABLE_GL_STATE_CACHE + + glDeleteProgram( program ); +} + +void ccGLUseProgram( GLuint program ) +{ +#if CC_ENABLE_GL_STATE_CACHE + if( program != _ccCurrentShaderProgram ) { + _ccCurrentShaderProgram = program; + glUseProgram(program); + } +#else + glUseProgram(program); +#endif // CC_ENABLE_GL_STATE_CACHE +} + + +void ccGLBlendFunc(GLenum sfactor, GLenum dfactor) +{ +#if CC_ENABLE_GL_STATE_CACHE + if( sfactor != _ccBlendingSource || dfactor != _ccBlendingDest ) { + _ccBlendingSource = sfactor; + _ccBlendingDest = dfactor; + glBlendFunc( sfactor, dfactor ); + } +#else + glBlendFunc( sfactor, dfactor ); +#endif // CC_ENABLE_GL_STATE_CACHE +} + +GLenum ccGLGetActiveTexture( void ) +{ +#if CC_ENABLE_GL_STATE_CACHE + return _ccCurrentActiveTexture + GL_TEXTURE0; +#else + GLenum activeTexture; + glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&activeTexture); + return activeTexture; +#endif +} + +void ccGLActiveTexture( GLenum textureEnum ) +{ +#if CC_ENABLE_GL_STATE_CACHE + NSCAssert1( (textureEnum - GL_TEXTURE0) < kCCMaxActiveTexture, @"cocos2d ERROR: Increase kCCMaxActiveTexture to %d!", (textureEnum-GL_TEXTURE0) ); + if( (textureEnum - GL_TEXTURE0) != _ccCurrentActiveTexture ) { + _ccCurrentActiveTexture = (textureEnum - GL_TEXTURE0); + glActiveTexture( textureEnum ); + } +#else + glActiveTexture( textureEnum ); +#endif +} + +void ccGLBindTexture2D( GLuint textureId ) +{ +#if CC_ENABLE_GL_STATE_CACHE + if( _ccCurrentBoundTexture[ _ccCurrentActiveTexture ] != textureId ) + { + _ccCurrentBoundTexture[ _ccCurrentActiveTexture ] = textureId; + glBindTexture(GL_TEXTURE_2D, textureId ); + } +#else + glBindTexture(GL_TEXTURE_2D, textureId ); +#endif +} + + +void ccGLDeleteTexture( GLuint textureId ) +{ +#if CC_ENABLE_GL_STATE_CACHE + if( textureId == _ccCurrentBoundTexture[ _ccCurrentActiveTexture ] ) + _ccCurrentBoundTexture[ _ccCurrentActiveTexture ] = -1; +#endif + glDeleteTextures(1, &textureId ); +} + +void ccGLEnable( ccGLServerState flags ) +{ +#if CC_ENABLE_GL_STATE_CACHE + + BOOL enabled = NO; + + /* GL_BLEND */ + if( (enabled=(flags & CC_GL_BLEND)) != (_ccGLServerState & CC_GL_BLEND) ) { + if( enabled ) { + glEnable( GL_BLEND ); + _ccGLServerState |= CC_GL_BLEND; + } else { + glDisable( GL_BLEND ); + _ccGLServerState &= ~CC_GL_BLEND; + } + } + +#else + if( flags & CC_GL_BLEND ) + glEnable( GL_BLEND ); + else + glDisable( GL_BLEND ); +#endif +} + +#pragma mark - GL Vertex Attrib functions + +void ccGLEnableVertexAttribs( unsigned int flags ) +{ + /* Position */ + BOOL enablePosition = flags & kCCVertexAttribFlag_Position; + + if( enablePosition != _vertexAttribPosition ) { + if( enablePosition ) + glEnableVertexAttribArray( kCCVertexAttrib_Position ); + else + glDisableVertexAttribArray( kCCVertexAttrib_Position ); + + _vertexAttribPosition = enablePosition; + } + + /* Color */ + BOOL enableColor = flags & kCCVertexAttribFlag_Color; + + if( enableColor != _vertexAttribColor ) { + if( enableColor ) + glEnableVertexAttribArray( kCCVertexAttrib_Color ); + else + glDisableVertexAttribArray( kCCVertexAttrib_Color ); + + _vertexAttribColor = enableColor; + } + + /* Tex Coords */ + BOOL enableTexCoords = flags & kCCVertexAttribFlag_TexCoords; + + if( enableTexCoords != _vertexAttribTexCoords ) { + if( enableTexCoords ) + glEnableVertexAttribArray( kCCVertexAttrib_TexCoords ); + else + glDisableVertexAttribArray( kCCVertexAttrib_TexCoords ); + + _vertexAttribTexCoords = enableTexCoords; + } +} + +#pragma mark - GL Uniforms functions + +void ccSetProjectionMatrixDirty( void ) +{ + _ccCurrentProjectionMatrix = -1; +} diff --git a/Example/libs/cocos2d/ccShader_PositionColor_frag.h b/Example/libs/cocos2d/ccShader_PositionColor_frag.h new file mode 100644 index 0000000..2c28489 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionColor_frag.h @@ -0,0 +1,12 @@ +" \n\ +#ifdef GL_ES \n\ +precision lowp float; \n\ +#endif \n\ + \n\ +varying vec4 v_fragmentColor; \n\ + \n\ +void main() \n\ +{ \n\ + gl_FragColor = v_fragmentColor; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionColor_vert.h b/Example/libs/cocos2d/ccShader_PositionColor_vert.h new file mode 100644 index 0000000..815e161 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionColor_vert.h @@ -0,0 +1,17 @@ +" \n\ +attribute vec4 a_position; \n\ +attribute vec4 a_color; \n\ +uniform mat4 u_MVPMatrix; \n\ + \n\ +#ifdef GL_ES \n\ +varying lowp vec4 v_fragmentColor; \n\ +#else \n\ +varying vec4 v_fragmentColor; \n\ +#endif \n\ + \n\ +void main() \n\ +{ \n\ + gl_Position = u_MVPMatrix * a_position; \n\ + v_fragmentColor = a_color; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureA8Color_frag.h b/Example/libs/cocos2d/ccShader_PositionTextureA8Color_frag.h new file mode 100644 index 0000000..0b6cd10 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionTextureA8Color_frag.h @@ -0,0 +1,16 @@ +" \n\ +#ifdef GL_ES \n\ +precision lowp float; \n\ +#endif \n\ + \n\ +varying vec4 v_fragmentColor; \n\ +varying vec2 v_texCoord; \n\ +uniform sampler2D u_texture; \n\ + \n\ +void main() \n\ +{ \n\ + gl_FragColor = vec4( v_fragmentColor.rgb, // RGB from uniform \n\ + v_fragmentColor.a * texture2D(u_texture, v_texCoord).a // A from texture & uniform \n\ + ); \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureA8Color_vert.h b/Example/libs/cocos2d/ccShader_PositionTextureA8Color_vert.h new file mode 100644 index 0000000..b844932 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionTextureA8Color_vert.h @@ -0,0 +1,21 @@ +" \n\ +attribute vec4 a_position; \n\ +attribute vec2 a_texCoord; \n\ +attribute vec4 a_color; \n\ +uniform mat4 u_MVPMatrix; \n\ + \n\ +#ifdef GL_ES \n\ +varying lowp vec4 v_fragmentColor; \n\ +varying mediump vec2 v_texCoord; \n\ +#else \n\ +varying vec4 v_fragmentColor; \n\ +varying vec2 v_texCoord; \n\ +#endif \n\ + \n\ +void main() \n\ +{ \n\ + gl_Position = u_MVPMatrix * a_position; \n\ + v_fragmentColor = a_color; \n\ + v_texCoord = a_texCoord; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureColorAlphaTest_frag.h b/Example/libs/cocos2d/ccShader_PositionTextureColorAlphaTest_frag.h new file mode 100644 index 0000000..253c5e8 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionTextureColorAlphaTest_frag.h @@ -0,0 +1,23 @@ +" \n\ +#ifdef GL_ES \n\ +precision lowp float; \n\ +#endif \n\ + \n\ +varying vec4 v_fragmentColor; \n\ +varying vec2 v_texCoord; \n\ +uniform sampler2D u_texture; \n\ +uniform float u_alpha_value; \n\ + \n\ +void main() \n\ +{ \n\ + vec4 texColor = texture2D(u_texture, v_texCoord); \n\ + \n\ + // mimic: glAlphaFunc(GL_GREATER) \n\ + // pass if ( incoming_pixel >= u_alpha_value ) => fail if incoming_pixel < u_alpha_value \n\ + \n\ + if ( texColor.a <= u_alpha_value ) \n\ + discard; \n\ + \n\ + gl_FragColor = texColor * v_fragmentColor; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureColor_frag.h b/Example/libs/cocos2d/ccShader_PositionTextureColor_frag.h new file mode 100644 index 0000000..aba7e21 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionTextureColor_frag.h @@ -0,0 +1,14 @@ +" \n\ +#ifdef GL_ES \n\ +precision lowp float; \n\ +#endif \n\ + \n\ +varying vec4 v_fragmentColor; \n\ +varying vec2 v_texCoord; \n\ +uniform sampler2D u_texture; \n\ + \n\ +void main() \n\ +{ \n\ + gl_FragColor = v_fragmentColor * texture2D(u_texture, v_texCoord); \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureColor_vert.h b/Example/libs/cocos2d/ccShader_PositionTextureColor_vert.h new file mode 100644 index 0000000..cf2361d --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionTextureColor_vert.h @@ -0,0 +1,22 @@ +" \n\ +attribute vec4 a_position; \n\ +attribute vec2 a_texCoord; \n\ +attribute vec4 a_color; \n\ + \n\ +uniform mat4 u_MVPMatrix; \n\ + \n\ +#ifdef GL_ES \n\ +varying lowp vec4 v_fragmentColor; \n\ +varying mediump vec2 v_texCoord; \n\ +#else \n\ +varying vec4 v_fragmentColor; \n\ +varying vec2 v_texCoord; \n\ +#endif \n\ + \n\ +void main() \n\ +{ \n\ + gl_Position = u_MVPMatrix * a_position; \n\ + v_fragmentColor = a_color; \n\ + v_texCoord = a_texCoord; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionTexture_frag.h b/Example/libs/cocos2d/ccShader_PositionTexture_frag.h new file mode 100644 index 0000000..d7af10e --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionTexture_frag.h @@ -0,0 +1,13 @@ +" \n\ +#ifdef GL_ES \n\ +precision lowp float; \n\ +#endif \n\ + \n\ +varying vec2 v_texCoord; \n\ +uniform sampler2D u_texture; \n\ + \n\ +void main() \n\ +{ \n\ + gl_FragColor = texture2D(u_texture, v_texCoord); \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionTexture_uColor_frag.h b/Example/libs/cocos2d/ccShader_PositionTexture_uColor_frag.h new file mode 100644 index 0000000..019f2ef --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionTexture_uColor_frag.h @@ -0,0 +1,16 @@ +" \n\ +#ifdef GL_ES \n\ +precision lowp float; \n\ +#endif \n\ + \n\ +uniform vec4 u_color; \n\ + \n\ +varying vec2 v_texCoord; \n\ + \n\ +uniform sampler2D u_texture; \n\ + \n\ +void main() \n\ +{ \n\ + gl_FragColor = texture2D(u_texture, v_texCoord) * u_color; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionTexture_uColor_vert.h b/Example/libs/cocos2d/ccShader_PositionTexture_uColor_vert.h new file mode 100644 index 0000000..ca36ff0 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionTexture_uColor_vert.h @@ -0,0 +1,18 @@ +" \n\ +attribute vec4 a_position; \n\ +attribute vec2 a_texCoord; \n\ + \n\ +uniform mat4 u_MVPMatrix; \n\ + \n\ +#ifdef GL_ES \n\ +varying mediump vec2 v_texCoord; \n\ +#else \n\ +varying vec2 v_texCoord; \n\ +#endif \n\ + \n\ +void main() \n\ +{ \n\ + gl_Position = u_MVPMatrix * a_position; \n\ + v_texCoord = a_texCoord; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_PositionTexture_vert.h b/Example/libs/cocos2d/ccShader_PositionTexture_vert.h new file mode 100644 index 0000000..98ceab5 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_PositionTexture_vert.h @@ -0,0 +1,17 @@ +" \n\ +attribute vec4 a_position; \n\ +attribute vec2 a_texCoord; \n\ +uniform mat4 u_MVPMatrix; \n\ + \n\ +#ifdef GL_ES \n\ +varying mediump vec2 v_texCoord; \n\ +#else \n\ +varying vec2 v_texCoord; \n\ +#endif \n\ + \n\ +void main() \n\ +{ \n\ + gl_Position = u_MVPMatrix * a_position; \n\ + v_texCoord = a_texCoord; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_Position_uColor_frag.h b/Example/libs/cocos2d/ccShader_Position_uColor_frag.h new file mode 100644 index 0000000..48e5ae6 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_Position_uColor_frag.h @@ -0,0 +1,12 @@ +" \n\ +#ifdef GL_ES \n\ +precision lowp float; \n\ +#endif \n\ + \n\ +varying vec4 v_fragmentColor; \n\ + \n\ +void main() \n\ +{ \n\ + gl_FragColor = v_fragmentColor; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShader_Position_uColor_vert.h b/Example/libs/cocos2d/ccShader_Position_uColor_vert.h new file mode 100644 index 0000000..9f1ba38 --- /dev/null +++ b/Example/libs/cocos2d/ccShader_Position_uColor_vert.h @@ -0,0 +1,19 @@ +" \n\ +attribute vec4 a_position; \n\ +uniform mat4 u_MVPMatrix; \n\ +uniform vec4 u_color; \n\ +uniform float u_pointSize; \n\ + \n\ +#ifdef GL_ES \n\ +varying lowp vec4 v_fragmentColor; \n\ +#else \n\ +varying vec4 v_fragmentColor; \n\ +#endif \n\ + \n\ +void main() \n\ +{ \n\ + gl_Position = u_MVPMatrix * a_position; \n\ + gl_PointSize = u_pointSize; \n\ + v_fragmentColor = u_color; \n\ +} \n\ +"; diff --git a/Example/libs/cocos2d/ccShaders.h b/Example/libs/cocos2d/ccShaders.h new file mode 100644 index 0000000..84b113f --- /dev/null +++ b/Example/libs/cocos2d/ccShaders.h @@ -0,0 +1,45 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2012 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import "Platforms/CCGL.h" + +extern const GLchar * ccPosition_uColor_frag; +extern const GLchar * ccPosition_uColor_vert; + +extern const GLchar * ccPositionColor_frag; +extern const GLchar * ccPositionColor_vert; + +extern const GLchar * ccPositionTexture_frag; +extern const GLchar * ccPositionTexture_vert; + +extern const GLchar * ccPositionTextureA8Color_frag; +extern const GLchar * ccPositionTextureA8Color_vert; + +extern const GLchar * ccPositionTextureColor_frag; +extern const GLchar * ccPositionTextureColor_vert; + +extern const GLchar * ccPositionTextureColorAlphaTest_frag; + +extern const GLchar * ccPositionTexture_uColor_frag; +extern const GLchar * ccPositionTexture_uColor_vert; diff --git a/Example/libs/cocos2d/ccShaders.m b/Example/libs/cocos2d/ccShaders.m new file mode 100644 index 0000000..36ca949 --- /dev/null +++ b/Example/libs/cocos2d/ccShaders.m @@ -0,0 +1,65 @@ +/* + * cocos2d for iPhone: http://www.cocos2d-iphone.org + * + * Copyright (c) 2012 Zynga Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#import "ccShaders.h" + +// +const GLchar * ccPosition_uColor_frag = +#import "ccShader_Position_uColor_frag.h" +const GLchar * ccPosition_uColor_vert = +#import "ccShader_Position_uColor_vert.h" + +// +const GLchar * ccPositionColor_frag = +#import "ccShader_PositionColor_frag.h" +const GLchar * ccPositionColor_vert = +#import "ccShader_PositionColor_vert.h" + +// +const GLchar * ccPositionTexture_frag = +#import "ccShader_PositionTexture_frag.h" +const GLchar * ccPositionTexture_vert = +#import "ccShader_PositionTexture_vert.h" + +// +const GLchar * ccPositionTextureA8Color_frag = +#import "ccShader_PositionTextureA8Color_frag.h" +const GLchar * ccPositionTextureA8Color_vert = +#import "ccShader_PositionTextureA8Color_vert.h" + +// +const GLchar * ccPositionTextureColor_frag = +#import "ccShader_PositionTextureColor_frag.h" +const GLchar * ccPositionTextureColor_vert = +#import "ccShader_PositionTextureColor_vert.h" + +// +const GLchar * ccPositionTextureColorAlphaTest_frag = +#import "ccShader_PositionTextureColorAlphaTest_frag.h" + +// +const GLchar * ccPositionTexture_uColor_frag = +#import "ccShader_PositionTexture_uColor_frag.h" +const GLchar * ccPositionTexture_uColor_vert = +#import "ccShader_PositionTexture_uColor_vert.h" diff --git a/Example/libs/kazmath/include/kazmath/GL/mat4stack.h b/Example/libs/kazmath/include/kazmath/GL/mat4stack.h new file mode 100644 index 0000000..7de12aa --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/GL/mat4stack.h @@ -0,0 +1,51 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef C_STACK_H_INCLUDED +#define C_STACK_H_INCLUDED + +#include "../mat4.h" + +typedef struct km_mat4_stack { + int capacity; //The total item capacity + int item_count; //The number of items + kmMat4* top; + kmMat4* stack; +} km_mat4_stack; + +#ifdef __cplusplus +extern "C" { +#endif + +void km_mat4_stack_initialize(km_mat4_stack* stack); +void km_mat4_stack_push(km_mat4_stack* stack, const kmMat4* item); +void km_mat4_stack_pop(km_mat4_stack* stack, kmMat4* pOut); +void km_mat4_stack_release(km_mat4_stack* stack); + +#ifdef __cplusplus +} +#endif + +#endif // C_STACK_H_INCLUDED diff --git a/Example/libs/kazmath/include/kazmath/GL/matrix.h b/Example/libs/kazmath/include/kazmath/GL/matrix.h new file mode 100644 index 0000000..1fa0267 --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/GL/matrix.h @@ -0,0 +1,58 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef KM_GL_MATRIX_H_INCLUDED +#define KM_GL_MATRIX_H_INCLUDED + +#define KM_GL_MODELVIEW 0x1700 +#define KM_GL_PROJECTION 0x1701 +#define KM_GL_TEXTURE 0x1702 + +typedef unsigned int kmGLEnum; + +#include "../mat4.h" +#include "../vec3.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void kmGLFreeAll(void); +void kmGLPushMatrix(void); +void kmGLPopMatrix(void); +void kmGLMatrixMode(kmGLEnum mode); +void kmGLLoadIdentity(void); +void kmGLLoadMatrix(const kmMat4* pIn); +void kmGLMultMatrix(const kmMat4* pIn); +void kmGLTranslatef(float x, float y, float z); +void kmGLRotatef(float angle, float x, float y, float z); +void kmGLScalef(float x, float y, float z); +void kmGLGetMatrix(kmGLEnum mode, kmMat4* pOut); + +#ifdef __cplusplus +} +#endif + +#endif // MATRIX_H_INCLUDED diff --git a/Example/libs/kazmath/include/kazmath/aabb.h b/Example/libs/kazmath/include/kazmath/aabb.h new file mode 100644 index 0000000..0e78a04 --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/aabb.h @@ -0,0 +1,53 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef KAZMATH_AABB_H_INCLUDED +#define KAZMATH_AABB_H_INCLUDED + +#include "vec3.h" +#include "utility.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A struture that represents an axis-aligned + * bounding box. + */ +typedef struct kmAABB { + kmVec3 min; /** The max corner of the box */ + kmVec3 max; /** The min corner of the box */ +} kmAABB; + +const int kmAABBContainsPoint(const kmVec3* pPoint, const kmAABB* pBox); +kmAABB* const kmAABBAssign(kmAABB* pOut, const kmAABB* pIn); +kmAABB* const kmAABBScale(kmAABB* pOut, const kmAABB* pIn, kmScalar s); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Example/libs/kazmath/include/kazmath/kazmath.h b/Example/libs/kazmath/include/kazmath/kazmath.h new file mode 100644 index 0000000..ef09870 --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/kazmath.h @@ -0,0 +1,39 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef KAZMATH_H_INCLUDED +#define KAZMATH_H_INCLUDED + +#include "vec2.h" +#include "vec3.h" +#include "mat3.h" +#include "mat4.h" +#include "utility.h" +#include "quaternion.h" +#include "plane.h" +#include "aabb.h" +#include "ray2.h" + +#endif // KAZMATH_H_INCLUDED diff --git a/Example/libs/kazmath/include/kazmath/mat3.h b/Example/libs/kazmath/include/kazmath/mat3.h new file mode 100644 index 0000000..f0de423 --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/mat3.h @@ -0,0 +1,75 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +#ifndef MAT3_H_INCLUDED +#define MAT3_H_INCLUDED + +#include "utility.h" + +struct kmVec3; +struct kmQuaternion; + +typedef struct kmMat3{ + kmScalar mat[9]; +} kmMat3; + +#ifdef __cplusplus +extern "C" { +#endif + +kmMat3* const kmMat3Fill(kmMat3* pOut, const kmScalar* pMat); +kmMat3* const kmMat3Adjugate(kmMat3* pOut, const kmMat3* pIn); +kmMat3* const kmMat3Identity(kmMat3* pOut); +kmMat3* const kmMat3Inverse(kmMat3* pOut, const kmScalar pDeterminate, const kmMat3* pM); +const int kmMat3IsIdentity(const kmMat3* pIn); +kmMat3* const kmMat3Transpose(kmMat3* pOut, const kmMat3* pIn); +const kmScalar kmMat3Determinant(const kmMat3* pIn); +kmMat3* const kmMat3Multiply(kmMat3* pOut, const kmMat3* pM1, const kmMat3* pM2); +kmMat3* const kmMat3ScalarMultiply(kmMat3* pOut, const kmMat3* pM, const kmScalar pFactor); + +kmMat3* const kmMat3RotationAxisAngle(kmMat3* pOut, const struct kmVec3* axis, kmScalar radians); +struct kmVec3* const kmMat3RotationToAxisAngle(struct kmVec3* pAxis, kmScalar* radians, const kmMat3* pIn); + +kmMat3* const kmMat3Assign(kmMat3* pOut, const kmMat3* pIn); +const int kmMat3AreEqual(const kmMat3* pM1, const kmMat3* pM2); + +kmMat3* const kmMat3RotationX(kmMat3* pOut, const kmScalar radians); +kmMat3* const kmMat3RotationY(kmMat3* pOut, const kmScalar radians); +kmMat3* const kmMat3RotationZ(kmMat3* pOut, const kmScalar radians); + +kmMat3* const kmMat3Rotation(kmMat3* pOut, const kmScalar radians); +kmMat3* const kmMat3Scaling(kmMat3* pOut, const kmScalar x, const kmScalar y); +kmMat3* const kmMat3Translation(kmMat3* pOut, const kmScalar x, const kmScalar y); + +kmMat3* const kmMat3RotationQuaternion(kmMat3* pOut, const struct kmQuaternion* pIn); +kmMat3* const kmMat3RotationAxisAngle(kmMat3* pOut, const struct kmVec3* axis, kmScalar radians); +struct kmVec3* const kmMat3RotationToAxisAngle(struct kmVec3* pAxis, kmScalar* radians, const kmMat3* pIn); + +#ifdef __cplusplus +} +#endif +#endif // MAT3_H_INCLUDED + diff --git a/Example/libs/kazmath/include/kazmath/mat4.h b/Example/libs/kazmath/include/kazmath/mat4.h new file mode 100644 index 0000000..38008ba --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/mat4.h @@ -0,0 +1,93 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef MAT4_H_INCLUDED +#define MAT4_H_INCLUDED + +#include "utility.h" + +struct kmVec3; +struct kmMat3; +struct kmQuaternion; +struct kmPlane; + +/* +A 4x4 matrix + + | 0 4 8 12 | +mat = | 1 5 9 13 | + | 2 6 10 14 | + | 3 7 11 15 | +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct kmMat4 { + kmScalar mat[16]; +} kmMat4; + +kmMat4* const kmMat4Fill(kmMat4* pOut, const kmScalar* pMat); + + +kmMat4* const kmMat4Identity(kmMat4* pOut); + +kmMat4* const kmMat4Inverse(kmMat4* pOut, const kmMat4* pM); + + +const int kmMat4IsIdentity(const kmMat4* pIn); + +kmMat4* const kmMat4Transpose(kmMat4* pOut, const kmMat4* pIn); +kmMat4* const kmMat4Multiply(kmMat4* pOut, const kmMat4* pM1, const kmMat4* pM2); + +kmMat4* const kmMat4Assign(kmMat4* pOut, const kmMat4* pIn); +const int kmMat4AreEqual(const kmMat4* pM1, const kmMat4* pM2); + +kmMat4* const kmMat4RotationX(kmMat4* pOut, const kmScalar radians); +kmMat4* const kmMat4RotationY(kmMat4* pOut, const kmScalar radians); +kmMat4* const kmMat4RotationZ(kmMat4* pOut, const kmScalar radians); +kmMat4* const kmMat4RotationPitchYawRoll(kmMat4* pOut, const kmScalar pitch, const kmScalar yaw, const kmScalar roll); +kmMat4* const kmMat4RotationQuaternion(kmMat4* pOut, const struct kmQuaternion* pQ); +kmMat4* const kmMat4RotationTranslation(kmMat4* pOut, const struct kmMat3* rotation, const struct kmVec3* translation); +kmMat4* const kmMat4Scaling(kmMat4* pOut, const kmScalar x, const kmScalar y, const kmScalar z); +kmMat4* const kmMat4Translation(kmMat4* pOut, const kmScalar x, const kmScalar y, const kmScalar z); + +struct kmVec3* const kmMat4GetUpVec3(struct kmVec3* pOut, const kmMat4* pIn); +struct kmVec3* const kmMat4GetRightVec3(struct kmVec3* pOut, const kmMat4* pIn); +struct kmVec3* const kmMat4GetForwardVec3(struct kmVec3* pOut, const kmMat4* pIn); + +kmMat4* const kmMat4PerspectiveProjection(kmMat4* pOut, kmScalar fovY, kmScalar aspect, kmScalar zNear, kmScalar zFar); +kmMat4* const kmMat4OrthographicProjection(kmMat4* pOut, kmScalar left, kmScalar right, kmScalar bottom, kmScalar top, kmScalar nearVal, kmScalar farVal); +kmMat4* const kmMat4LookAt(kmMat4* pOut, const struct kmVec3* pEye, const struct kmVec3* pCenter, const struct kmVec3* pUp); + +kmMat4* const kmMat4RotationAxisAngle(kmMat4* pOut, const struct kmVec3* axis, kmScalar radians); +struct kmMat3* const kmMat4ExtractRotation(struct kmMat3* pOut, const kmMat4* pIn); +struct kmPlane* const kmMat4ExtractPlane(struct kmPlane* pOut, const kmMat4* pIn, const kmEnum plane); +struct kmVec3* const kmMat4RotationToAxisAngle(struct kmVec3* pAxis, kmScalar* radians, const kmMat4* pIn); +#ifdef __cplusplus +} +#endif +#endif /* MAT4_H_INCLUDED */ diff --git a/Example/libs/kazmath/include/kazmath/neon_matrix_impl.h b/Example/libs/kazmath/include/kazmath/neon_matrix_impl.h new file mode 100644 index 0000000..3fcf3e4 --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/neon_matrix_impl.h @@ -0,0 +1,41 @@ +/* + NEON math library for the iPhone / iPod touch + + Copyright (c) 2009 Justin Saunders + + This software is provided 'as-is', without any express or implied warranty. + In no event will the authors be held liable for any damages arising + from the use of this software. + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it freely, + subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product documentation + would be appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef __NEON_MATRIX_IMPL_H__ +#define __NEON_MATRIX_IMPL_H__ + +#ifdef __arm__ +#include "arm/arch.h" +#endif + +// Matrixes are assumed to be stored in column major format according to OpenGL +// specification. + +// Multiplies two 4x4 matrices (a,b) outputing a 4x4 matrix (output) +void NEON_Matrix4Mul(const float* a, const float* b, float* output ); + +// Multiplies a 4x4 matrix (m) with a vector 4 (v), outputing a vector 4 +void NEON_Matrix4Vector4Mul(const float* m, const float* v, float* output); + + +#endif // __NEON_MATRIX_IMPL_H__ diff --git a/Example/libs/kazmath/include/kazmath/plane.h b/Example/libs/kazmath/include/kazmath/plane.h new file mode 100644 index 0000000..4270a8a --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/plane.h @@ -0,0 +1,70 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef PLANE_H_INCLUDED +#define PLANE_H_INCLUDED + +#define KM_PLANE_LEFT 0 +#define KM_PLANE_RIGHT 1 +#define KM_PLANE_BOTTOM 2 +#define KM_PLANE_TOP 3 +#define KM_PLANE_NEAR 4 +#define KM_PLANE_FAR 5 + +#include "utility.h" + +struct kmVec3; +struct kmVec4; +struct kmMat4; + +typedef struct kmPlane { + kmScalar a, b, c, d; +} kmPlane; + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum POINT_CLASSIFICATION { + POINT_INFRONT_OF_PLANE = 0, + POINT_BEHIND_PLANE, + POINT_ON_PLANE, +} POINT_CLASSIFICATION; + +const kmScalar kmPlaneDot(const kmPlane* pP, const struct kmVec4* pV); +const kmScalar kmPlaneDotCoord(const kmPlane* pP, const struct kmVec3* pV); +const kmScalar kmPlaneDotNormal(const kmPlane* pP, const struct kmVec3* pV); +kmPlane* const kmPlaneFromPointNormal(kmPlane* pOut, const struct kmVec3* pPoint, const struct kmVec3* pNormal); +kmPlane* const kmPlaneFromPoints(kmPlane* pOut, const struct kmVec3* p1, const struct kmVec3* p2, const struct kmVec3* p3); +kmVec3* const kmPlaneIntersectLine(struct kmVec3* pOut, const kmPlane* pP, const struct kmVec3* pV1, const struct kmVec3* pV2); +kmPlane* const kmPlaneNormalize(kmPlane* pOut, const kmPlane* pP); +kmPlane* const kmPlaneScale(kmPlane* pOut, const kmPlane* pP, kmScalar s); +const POINT_CLASSIFICATION kmPlaneClassifyPoint(const kmPlane* pIn, const kmVec3* pP); /** Classifys a point against a plane */ + +#ifdef __cplusplus +} +#endif + +#endif // PLANE_H_INCLUDED diff --git a/Example/libs/kazmath/include/kazmath/quaternion.h b/Example/libs/kazmath/include/kazmath/quaternion.h new file mode 100644 index 0000000..81ff547 --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/quaternion.h @@ -0,0 +1,113 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef QUATERNION_H_INCLUDED +#define QUATERNION_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +#include "utility.h" + +struct kmMat4; +struct kmMat3; +struct kmVec3; + +typedef struct kmQuaternion { + kmScalar x; + kmScalar y; + kmScalar z; + kmScalar w; +} kmQuaternion; + +kmQuaternion* const kmQuaternionConjugate(kmQuaternion* pOut, const kmQuaternion* pIn); ///< Returns pOut, sets pOut to the conjugate of pIn + +const kmScalar kmQuaternionDot(const kmQuaternion* q1, const kmQuaternion* q2); ///< Returns the dot product of the 2 quaternions + +kmQuaternion* kmQuaternionExp(kmQuaternion* pOut, const kmQuaternion* pIn); ///< Returns the exponential of the quaternion + +///< Makes the passed quaternion an identity quaternion + +kmQuaternion* kmQuaternionIdentity(kmQuaternion* pOut); + +///< Returns the inverse of the passed Quaternion + +kmQuaternion* kmQuaternionInverse(kmQuaternion* pOut, + const kmQuaternion* pIn); + +///< Returns true if the quaternion is an identity quaternion + +int kmQuaternionIsIdentity(const kmQuaternion* pIn); + +///< Returns the length of the quaternion + +kmScalar kmQuaternionLength(const kmQuaternion* pIn); + +///< Returns the length of the quaternion squared (prevents a sqrt) + +kmScalar kmQuaternionLengthSq(const kmQuaternion* pIn); + +///< Returns the natural logarithm + +kmQuaternion* kmQuaternionLn(kmQuaternion* pOut, const kmQuaternion* pIn); + +///< Multiplies 2 quaternions together + +kmQuaternion* kmQuaternionMultiply(kmQuaternion* pOut, const kmQuaternion* q1, const kmQuaternion* q2); + +///< Normalizes a quaternion + +kmQuaternion* kmQuaternionNormalize(kmQuaternion* pOut, const kmQuaternion* pIn); + +///< Rotates a quaternion around an axis + +kmQuaternion* kmQuaternionRotationAxis(kmQuaternion* pOut, const struct kmVec3* pV, kmScalar angle); + +///< Creates a quaternion from a rotation matrix + +kmQuaternion* kmQuaternionRotationMatrix(kmQuaternion* pOut, const struct kmMat3* pIn); + +///< Create a quaternion from yaw, pitch and roll + +kmQuaternion* kmQuaternionRotationYawPitchRoll(kmQuaternion* pOut, kmScalar yaw, kmScalar pitch, kmScalar roll); +///< Interpolate between 2 quaternions +kmQuaternion* kmQuaternionSlerp(kmQuaternion* pOut, const kmQuaternion* q1, const kmQuaternion* q2, kmScalar t); + +///< Get the axis and angle of rotation from a quaternion +void kmQuaternionToAxisAngle(const kmQuaternion* pIn, struct kmVec3* pVector, kmScalar* pAngle); + +///< Scale a quaternion +kmQuaternion* kmQuaternionScale(kmQuaternion* pOut, const kmQuaternion* pIn, kmScalar s); +kmQuaternion* kmQuaternionAssign(kmQuaternion* pOut, const kmQuaternion* pIn); +kmQuaternion* kmQuaternionAdd(kmQuaternion* pOut, const kmQuaternion* pQ1, const kmQuaternion* pQ2); +kmQuaternion* kmQuaternionRotationBetweenVec3(kmQuaternion* pOut, const struct kmVec3* vec1, const struct kmVec3* vec2, const struct kmVec3* fallback); +struct kmVec3* kmQuaternionMultiplyVec3(struct kmVec3* pOut, const kmQuaternion* q, const struct kmVec3* v); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Example/libs/kazmath/include/kazmath/ray2.h b/Example/libs/kazmath/include/kazmath/ray2.h new file mode 100644 index 0000000..609e6e5 --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/ray2.h @@ -0,0 +1,50 @@ +/* +Copyright (c) 2011, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef RAY_2_H +#define RAY_2_H + +#include "utility.h" +#include "vec2.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct kmRay2 { + kmVec2 start; + kmVec2 dir; +} kmRay2; + +void kmRay2Fill(kmRay2* ray, kmScalar px, kmScalar py, kmScalar vx, kmScalar vy); +kmBool kmRay2IntersectLineSegment(const kmRay2* ray, const kmVec2* p1, const kmVec2* p2, kmVec2* intersection); +kmBool kmRay2IntersectTriangle(const kmRay2* ray, const kmVec2* p1, const kmVec2* p2, const kmVec2* p3, kmVec2* intersection, kmVec2* normal_out); +kmBool kmRay2IntersectCircle(const kmRay2* ray, const kmVec2 centre, const kmScalar radius, kmVec2* intersection); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Example/libs/kazmath/include/kazmath/utility.h b/Example/libs/kazmath/include/kazmath/utility.h new file mode 100644 index 0000000..14d66dc --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/utility.h @@ -0,0 +1,74 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef UTILITY_H_INCLUDED +#define UTILITY_H_INCLUDED + +#include + +#ifndef kmScalar +#define kmScalar float +#endif + +#ifndef kmBool +#define kmBool unsigned char +#endif + +#ifndef kmEnum +#define kmEnum unsigned int +#endif + +#ifndef KM_FALSE +#define KM_FALSE 0 +#endif + +#ifndef KM_TRUE +#define KM_TRUE 1 +#endif + +#define kmPI 3.141592f +#define kmPIOver180 0.017453f // PI / 180 +#define kmPIUnder180 57.295779f // 180 / PI +#define kmEpsilon 1.0 / 64.0 + + + +#ifdef __cplusplus +extern "C" { +#endif + +extern kmScalar kmSQR(kmScalar s); +extern kmScalar kmDegreesToRadians(kmScalar degrees); +extern kmScalar kmRadiansToDegrees(kmScalar radians); + +extern kmScalar min(kmScalar lhs, kmScalar rhs); +extern kmScalar max(kmScalar lhs, kmScalar rhs); +extern kmBool kmAlmostEqual(kmScalar lhs, kmScalar rhs); + +#ifdef __cplusplus +} +#endif + +#endif /* UTILITY_H_INCLUDED */ diff --git a/Example/libs/kazmath/include/kazmath/vec2.h b/Example/libs/kazmath/include/kazmath/vec2.h new file mode 100644 index 0000000..3ca56b3 --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/vec2.h @@ -0,0 +1,64 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef VEC2_H_INCLUDED +#define VEC2_H_INCLUDED + +struct kmMat3; + +#ifndef kmScalar +#define kmScalar float +#endif + +#pragma pack(push) /* push current alignment to stack */ +#pragma pack(1) /* set alignment to 1 byte boundary */ +typedef struct kmVec2 { + kmScalar x; + kmScalar y; +} kmVec2; + +#pragma pack(pop) + +#ifdef __cplusplus +extern "C" { +#endif +kmVec2* kmVec2Fill(kmVec2* pOut, kmScalar x, kmScalar y); +kmScalar kmVec2Length(const kmVec2* pIn); ///< Returns the length of the vector +kmScalar kmVec2LengthSq(const kmVec2* pIn); ///< Returns the square of the length of the vector +kmVec2* kmVec2Normalize(kmVec2* pOut, const kmVec2* pIn); ///< Returns the vector passed in set to unit length +kmVec2* kmVec2Add(kmVec2* pOut, const kmVec2* pV1, const kmVec2* pV2); ///< Adds 2 vectors and returns the result +kmScalar kmVec2Dot(const kmVec2* pV1, const kmVec2* pV2); /** Returns the Dot product which is the cosine of the angle between the two vectors multiplied by their lengths */ +kmVec2* kmVec2Subtract(kmVec2* pOut, const kmVec2* pV1, const kmVec2* pV2); ///< Subtracts 2 vectors and returns the result +kmVec2* kmVec2Transform(kmVec2* pOut, const kmVec2* pV1, const struct kmMat3* pM); /** Transform the Vector */ +kmVec2* kmVec2TransformCoord(kmVec2* pOut, const kmVec2* pV, const struct kmMat3* pM); /// + +#ifndef kmScalar +#define kmScalar float +#endif + +struct kmMat4; + +typedef struct kmVec3 { + kmScalar x; + kmScalar y; + kmScalar z; +} kmVec3; + +#ifdef __cplusplus +extern "C" { +#endif + +kmVec3* kmVec3Fill(kmVec3* pOut, kmScalar x, kmScalar y, kmScalar z); +kmScalar kmVec3Length(const kmVec3* pIn); /** Returns the length of the vector */ +kmScalar kmVec3LengthSq(const kmVec3* pIn); /** Returns the square of the length of the vector */ +kmVec3* kmVec3Normalize(kmVec3* pOut, const kmVec3* pIn); /** Returns the vector passed in set to unit length */ +kmVec3* kmVec3Cross(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2); /** Returns a vector perpendicular to 2 other vectors */ +kmScalar kmVec3Dot(const kmVec3* pV1, const kmVec3* pV2); /** Returns the cosine of the angle between 2 vectors */ +kmVec3* kmVec3Add(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2); /** Adds 2 vectors and returns the result */ +kmVec3* kmVec3Subtract(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2); /** Subtracts 2 vectors and returns the result */ +kmVec3* kmVec3Transform(kmVec3* pOut, const kmVec3* pV1, const struct kmMat4* pM); /** Transforms a vector (assuming w=1) by a given matrix */ +kmVec3* kmVec3TransformNormal(kmVec3* pOut, const kmVec3* pV, const struct kmMat4* pM);/**Transforms a 3D normal by a given matrix */ +kmVec3* kmVec3TransformCoord(kmVec3* pOut, const kmVec3* pV, const struct kmMat4* pM); /**Transforms a 3D vector by a given matrix, projecting the result back into w = 1. */ +kmVec3* kmVec3Scale(kmVec3* pOut, const kmVec3* pIn, const kmScalar s); /** Scales a vector to length s */ +int kmVec3AreEqual(const kmVec3* p1, const kmVec3* p2); +kmVec3* kmVec3InverseTransform(kmVec3* pOut, const kmVec3* pV, const struct kmMat4* pM); +kmVec3* kmVec3InverseTransformNormal(kmVec3* pOut, const kmVec3* pVect, const struct kmMat4* pM); +kmVec3* kmVec3Assign(kmVec3* pOut, const kmVec3* pIn); +kmVec3* kmVec3Zero(kmVec3* pOut); + +#ifdef __cplusplus +} +#endif +#endif /* VEC3_H_INCLUDED */ diff --git a/Example/libs/kazmath/include/kazmath/vec4.h b/Example/libs/kazmath/include/kazmath/vec4.h new file mode 100644 index 0000000..7507ea3 --- /dev/null +++ b/Example/libs/kazmath/include/kazmath/vec4.h @@ -0,0 +1,68 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef VEC4_H_INCLUDED +#define VEC4_H_INCLUDED + +#include "utility.h" + +struct kmMat4; + +#pragma pack(push) /* push current alignment to stack */ +#pragma pack(1) /* set alignment to 1 byte boundary */ + +typedef struct kmVec4 { + kmScalar x; + kmScalar y; + kmScalar z; + kmScalar w; +} kmVec4; + +#pragma pack(pop) + +#ifdef __cplusplus +extern "C" { +#endif + +kmVec4* kmVec4Fill(kmVec4* pOut, kmScalar x, kmScalar y, kmScalar z, kmScalar w); +kmVec4* kmVec4Add(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2); +kmScalar kmVec4Dot(const kmVec4* pV1, const kmVec4* pV2); +kmScalar kmVec4Length(const kmVec4* pIn); +kmScalar kmVec4LengthSq(const kmVec4* pIn); +kmVec4* kmVec4Lerp(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2, kmScalar t); +kmVec4* kmVec4Normalize(kmVec4* pOut, const kmVec4* pIn); +kmVec4* kmVec4Scale(kmVec4* pOut, const kmVec4* pIn, const kmScalar s); ///< Scales a vector to length s +kmVec4* kmVec4Subtract(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2); +kmVec4* kmVec4Transform(kmVec4* pOut, const kmVec4* pV, const struct kmMat4* pM); +kmVec4* kmVec4TransformArray(kmVec4* pOut, unsigned int outStride, + const kmVec4* pV, unsigned int vStride, const struct kmMat4* pM, unsigned int count); +int kmVec4AreEqual(const kmVec4* p1, const kmVec4* p2); +kmVec4* kmVec4Assign(kmVec4* pOut, const kmVec4* pIn); + +#ifdef __cplusplus +} +#endif + +#endif // VEC4_H_INCLUDED diff --git a/Example/libs/kazmath/src/CMakeLists.txt b/Example/libs/kazmath/src/CMakeLists.txt new file mode 100644 index 0000000..a389466 --- /dev/null +++ b/Example/libs/kazmath/src/CMakeLists.txt @@ -0,0 +1,14 @@ + +#ADD_LIBRARY(Kazmath STATIC ${KAZMATH_SRCS}) +#INSTALL(TARGETS Kazmath ARCHIVE DESTINATION lib) + +INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/include ) + +ADD_LIBRARY(kazmath STATIC ${KAZMATH_SOURCES}) +INSTALL(TARGETS kazmath ARCHIVE DESTINATION lib) + +#ADD_LIBRARY(KazmathGL STATIC ${GL_UTILS_SRCS}) +#INSTALL(TARGETS KazmathGL ARCHIVE DESTINATION lib) + +INSTALL(FILES ${KAZMATH_HEADERS} DESTINATION include/kazmath) +INSTALL(FILES ${GL_UTILS_HEADERS} DESTINATION include/kazmath/GL) diff --git a/Example/libs/kazmath/src/ChangeLog b/Example/libs/kazmath/src/ChangeLog new file mode 100644 index 0000000..f13b823 --- /dev/null +++ b/Example/libs/kazmath/src/ChangeLog @@ -0,0 +1,738 @@ +------------------------------------------------------------ +revno: 111 +committer: Kazade +branch nick: kazmath +timestamp: Thu 2010-08-19 12:07:29 +0100 +message: + Fix #620352. Fix a reference to kmMat4RotationAxisAngle +------------------------------------------------------------ +revno: 110 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Wed 2010-04-21 12:55:39 +0200 +message: + applied the change to the header files as well +------------------------------------------------------------ +revno: 109 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Wed 2010-04-21 12:54:06 +0200 +message: + fixed kmMat4RotationAxis +------------------------------------------------------------ +revno: 108 [merge] +committer: Carsten Haubld +branch nick: kazmath +timestamp: Wed 2010-04-21 12:27:53 +0200 +message: + fixed CMake in kazmathxx due to missing utility.h +------------------------------------------------------------ +revno: 107 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Wed 2010-04-21 12:22:40 +0200 +message: + fixed mat4 rotation axis by normalizing the axis first +------------------------------------------------------------ +revno: 106 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2010-01-09 16:56:04 +0000 +message: + Add cmake module +------------------------------------------------------------ +revno: 105 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2010-01-09 16:23:31 +0000 +message: + Remove kazmodel - it really should belong in its own repo +------------------------------------------------------------ +revno: 104 +committer: Luke Benstead +branch nick: kazmath +timestamp: Fri 2010-01-08 23:03:13 +0000 +message: + Reorganize the headers so that the tests can compile in place +------------------------------------------------------------ +revno: 103 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Mon 2009-08-31 11:21:42 +0200 +message: + Operators now inline, constructors fixed +------------------------------------------------------------ +revno: 102 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Sat 2009-08-29 11:42:59 +0200 +message: + fixed some compilation errors - still how do we define operators in headers correctly?? +------------------------------------------------------------ +revno: 101 +committer: Luke Benstead +branch nick: kazmath +timestamp: Wed 2009-08-26 10:37:52 +0100 +message: + Added the header defines +------------------------------------------------------------ +revno: 100 +committer: Luke Benstead +branch nick: kazmath +timestamp: Wed 2009-08-26 09:38:47 +0100 +message: + Added a V2 for kazmathxx +------------------------------------------------------------ +revno: 99 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-08-02 08:08:26 +0100 +message: + Added missing header file to one of the tests +------------------------------------------------------------ +revno: 98 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Sat 2009-08-01 12:05:25 +0200 +message: + No longer doing self assignment in kmMat4Inverse +------------------------------------------------------------ +revno: 97 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Sat 2009-08-01 11:15:36 +0200 +message: + Fixed kmMat4Inverse +------------------------------------------------------------ +revno: 96 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2009-08-01 09:20:33 +0100 +message: + Fixed some whitespace issues in plane.c +------------------------------------------------------------ +revno: 95 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2009-08-01 09:17:01 +0100 +message: + Rename kmAABBPointInBox to kmAABBContainsPoint +------------------------------------------------------------ +revno: 94 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2009-08-01 09:16:28 +0100 +message: + Implement kmAABBPointInBox +------------------------------------------------------------ +revno: 93 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2009-08-01 09:14:00 +0100 +message: + Implement kmAABBAssign +------------------------------------------------------------ +revno: 92 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2009-08-01 09:10:36 +0100 +message: + Fixed some whitespace and added some comments +------------------------------------------------------------ +revno: 91 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2009-08-01 08:56:13 +0100 +message: + Implemented (untested) kmMat4RotationTranslation to construct a 4x4 matrix from a 3x3 + vec3 +------------------------------------------------------------ +revno: 90 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-07-05 07:55:45 +0100 +message: + Added kmMat3RotationX, kmMat3RotationY and kmMat3RotationZ +------------------------------------------------------------ +revno: 89 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Sat 2009-06-27 09:38:20 +0200 +message: + Fixed a crash? +------------------------------------------------------------ +revno: 88 +committer: Luke Benstead +branch nick: kazmath +timestamp: Tue 2009-04-28 09:52:57 +0100 +message: + Added a test for kmMat4Transpose +------------------------------------------------------------ +revno: 87 +committer: Luke Benstead +branch nick: kazmath +timestamp: Tue 2009-04-28 08:49:59 +0100 +message: + Added a commented test for kmMat4Inverse, however kmMat4Adjugate and kmMat4Determinate need implementing +------------------------------------------------------------ +revno: 86 +committer: Luke Benstead +branch nick: kazmath +timestamp: Tue 2009-04-28 08:46:03 +0100 +message: + Fixed bug in kmQuaternionRotationMatrix +------------------------------------------------------------ +revno: 85 +committer: Luke Benstead +branch nick: kazmath +timestamp: Tue 2009-04-28 08:41:27 +0100 +message: + Added missing include to test_mat3.cpp +------------------------------------------------------------ +revno: 84 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Mon 2009-04-27 22:59:08 +0200 +message: + fixed CMakeLists.txt for the tests +------------------------------------------------------------ +revno: 83 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 21:34:20 +0100 +message: + Added a test for kmMat3Translation +------------------------------------------------------------ +revno: 82 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 21:32:19 +0100 +message: + Fixed bugs in kmMat3Scaling and kmMat3Translation, added test for kmMat3Scaling +------------------------------------------------------------ +revno: 81 [merge] +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 19:04:56 +0100 +message: + Merge from upstream. Fixed mismatching prototype in quaternion.c +------------------------------------------------------------ +revno: 80 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 19:01:35 +0100 +message: + Added a test for kmMat3AreEqual. Fixed a bug in kmMat3AreEqual +------------------------------------------------------------ +revno: 79 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 18:57:28 +0100 +message: + Added a test for kmMat3IsIdentity +------------------------------------------------------------ +revno: 78 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 18:54:48 +0100 +message: + Added a test for kmMat3Identity +------------------------------------------------------------ +revno: 77 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 18:52:14 +0100 +message: + Added a test for kmMat3Fill +------------------------------------------------------------ +revno: 76 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 18:46:30 +0100 +message: + Added some mat3 unit tests. Fixed a bug in kmMat3AreEqual +------------------------------------------------------------ +revno: 75 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 11:08:43 +0100 +message: + Added mat4 test stub +------------------------------------------------------------ +revno: 74 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 11:06:12 +0100 +message: + Enabled unit testing in cmake +------------------------------------------------------------ +revno: 73 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 10:44:37 +0100 +message: + Added cmakelists.txt to the tests subfolder +------------------------------------------------------------ +revno: 72 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 10:37:34 +0100 +message: + Added stub mat3 test file +------------------------------------------------------------ +revno: 71 +committer: Luke Benstead +branch nick: kazmath +timestamp: Mon 2009-04-27 10:35:48 +0100 +message: + Added tests folder for new boost::unit based tests +------------------------------------------------------------ +revno: 70 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Sun 2009-04-26 14:25:48 +0200 +message: + Fixed the new quaternion -> Matrix -> AngleAxis methods and added them to mat4 +------------------------------------------------------------ +revno: 69 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-04-26 12:40:08 +0100 +message: + Added kazmodel to the kazlibs repo +------------------------------------------------------------ +revno: 68 [merge] +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-04-26 12:34:27 +0100 +message: + Merge from upstream +------------------------------------------------------------ +revno: 67 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-04-26 12:33:43 +0100 +message: + Reorganized bzr +------------------------------------------------------------ +revno: 66 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-04-26 10:00:18 +0100 +message: + Renamed kmMat3RotationAxis to kmMat3RotationAxisAngle to be more accurate +------------------------------------------------------------ +revno: 65 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-04-26 09:57:19 +0100 +message: + Fixed some compilation errors +------------------------------------------------------------ +revno: 64 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-04-26 09:54:12 +0100 +message: + Added untested implementation of kmMat3RotationToAxisAngle +------------------------------------------------------------ +revno: 63 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-04-26 09:49:17 +0100 +message: + Added stub for kmMat3RotationToAxisAngle() +------------------------------------------------------------ +revno: 62 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-04-26 09:45:58 +0100 +message: + Corrected a typo +------------------------------------------------------------ +revno: 61 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sun 2009-04-26 09:44:39 +0100 +message: + Fixed broken Quaternion functions + Added (untested) kmMat3RotationAxis() +------------------------------------------------------------ +revno: 60 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2009-04-18 08:55:29 +0100 +message: + Fixed some errors in the quaternion header. + Changed kmQuaternionRotationMatrix to accept a kmMat3 instead of kmMat4 +------------------------------------------------------------ +revno: 59 +committer: Luke Benstead +branch nick: kazmath +timestamp: Sat 2009-04-18 08:42:38 +0100 +message: + Added kmMat3RotationQuaternion +------------------------------------------------------------ +revno: 58 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Sun 2009-04-05 11:58:29 +0200 +message: + Added mat3 +------------------------------------------------------------ +revno: 57 [merge] +committer: Carsten Haubld +branch nick: kazmath +timestamp: Sun 2009-04-05 11:54:15 +0200 +message: + Implemented mat4 and vec4 for kazmathxx +------------------------------------------------------------ +revno: 56 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Sun 2009-04-05 11:53:07 +0200 +message: + Implemented mat4 and vec4 for kazmathxx +------------------------------------------------------------ +revno: 55 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Fri 2009-03-13 16:46:26 +0100 +message: + added km::vec3 to kazmathxx +------------------------------------------------------------ +revno: 54 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Fri 2009-03-13 16:14:51 +0100 +message: + Fixed: kmVec2 is no longer transformed by kmMat4\nAdded km::vec2 +------------------------------------------------------------ +revno: 53 +committer: Carsten Haubld +branch nick: kazmath +timestamp: Fri 2009-03-13 15:38:53 +0100 +message: + Added folder for kazmathxx +------------------------------------------------------------ +revno: 52 [merge] +committer: Luke Benstead +branch nick: trunk +timestamp: Fri 2009-03-13 14:04:32 +0000 +message: + Merge from upstream +------------------------------------------------------------ +revno: 51 +committer: Luke Benstead +branch nick: trunk +timestamp: Fri 2009-03-13 14:00:14 +0000 +message: + Fixed for C89 +------------------------------------------------------------ +revno: 50 +committer: Carsten Haubold +timestamp: Tue 2008-12-30 12:45:23 +0100 +message: + fixed kmGLTranslate +------------------------------------------------------------ +revno: 49 +committer: Carsten Haubold +timestamp: Tue 2008-12-30 12:15:27 +0100 +message: + fixed some stack memory leaks +------------------------------------------------------------ +revno: 48 +committer: Carsten Haubold +timestamp: Tue 2008-12-30 11:01:35 +0100 +message: + The GL matrix stacks now work as expected - matrix multiplication was the wrong way round +------------------------------------------------------------ +revno: 47 +committer: Carsten Haubold +timestamp: Tue 2008-12-30 10:52:28 +0100 +message: + Debug output +------------------------------------------------------------ +revno: 46 +committer: Carsten Haubold +timestamp: Mon 2008-12-29 18:32:13 +0100 +message: + Fixed some compiler errors +------------------------------------------------------------ +revno: 45 +committer: Luke +timestamp: Wed 2008-11-19 08:36:47 +0000 +message: + Added kmGLTranslatef, kmGLScalef and kmGLRotatef +------------------------------------------------------------ +revno: 44 +committer: Luke +timestamp: Tue 2008-11-04 20:57:30 +0000 +message: + Fixed up kazmathxx +------------------------------------------------------------ +revno: 43 +committer: Luke +timestamp: Wed 2008-10-29 09:24:32 +0000 +message: + Started implementing C++ operators in kazmathxx.h +------------------------------------------------------------ +revno: 42 +committer: Luke +timestamp: Tue 2008-10-28 18:21:16 +0000 +message: + Added kazmathxx.h for C++ usage +------------------------------------------------------------ +revno: 41 +committer: Luke +timestamp: Tue 2008-10-28 11:00:41 +0000 +message: + Added Doxygen documentation +------------------------------------------------------------ +revno: 40 +committer: Luke +timestamp: Tue 2008-10-28 08:46:19 +0000 +message: + Began documenting the kmPlane functions. + Changed some assert(0)s to include a not implemented message +------------------------------------------------------------ +revno: 39 +committer: Luke +timestamp: Tue 2008-10-28 08:42:24 +0000 +message: + - Wrote stubs for the AABB functions which raise assertions if used. + - Documented the AABB functions + - Changed the definition of kmAABBPointInBox so that it actually makes sense +------------------------------------------------------------ +revno: 38 +committer: Luke +timestamp: Tue 2008-10-28 08:38:48 +0000 +message: + - Documented utility.c +------------------------------------------------------------ +revno: 37 +committer: Luke +timestamp: Tue 2008-10-28 08:36:30 +0000 +message: + - Documented vec3.c in detail. + - Fixed up a not-implemented assertion. + - Changed existing doc strings to C style - /** */ +------------------------------------------------------------ +revno: 36 +committer: Luke +timestamp: Tue 2008-10-28 08:30:00 +0000 +message: + Removed uneccessary files from git +------------------------------------------------------------ +revno: 35 +committer: Luke +timestamp: Tue 2008-10-28 08:28:49 +0000 +message: + - Documented all the functions in mat4.c + - Fixed up all asserts in mat4.c to include a message + - Tidied up the code. Mat4.c is now done. +------------------------------------------------------------ +revno: 34 +committer: Luke +timestamp: Mon 2008-10-27 21:52:33 +0000 +message: + Added potential 0.1 release binary +------------------------------------------------------------ +revno: 33 +committer: Luke Benstead +timestamp: Mon 2008-10-27 21:46:55 +0000 +message: + Changed the README to include the BSD license +------------------------------------------------------------ +revno: 32 +committer: Luke Benstead +timestamp: Mon 2008-10-27 21:45:51 +0000 +message: + Added the modified BSD license to all source files +------------------------------------------------------------ +revno: 31 +committer: Luke Benstead +timestamp: Mon 2008-10-27 21:11:51 +0000 +message: + Fixed the installation of header files in CMake +------------------------------------------------------------ +revno: 30 +committer: Luke +timestamp: Mon 2008-10-27 21:05:51 +0000 +message: + Added kazmath project files +------------------------------------------------------------ +revno: 29 [merge] +committer: Luke +timestamp: Mon 2008-10-27 21:03:22 +0000 +message: + Merge branch 'master' of git@github.com:Kazade/kazmath +------------------------------------------------------------ +revno: 28 +committer: Luke +timestamp: Mon 2008-10-27 21:02:04 +0000 +message: + Finally got kazmath compiling on VC++, man that compiler sucks! Have MS not heard of C99? +------------------------------------------------------------ +revno: 27 +committer: Luke Benstead +timestamp: Sun 2008-10-26 21:35:24 +0000 +message: + Changed the readme slightly, we need to change the license everywhere +------------------------------------------------------------ +revno: 26 +committer: Luke Benstead +timestamp: Sun 2008-10-26 21:21:47 +0000 +message: + Implemented the stacks test, fixed the undefined references I was getting +------------------------------------------------------------ +revno: 25 +committer: Luke Benstead +timestamp: Sun 2008-10-26 20:59:34 +0000 +message: + Removed the old matrix stack stuff +------------------------------------------------------------ +revno: 24 +committer: Luke Benstead +timestamp: Sun 2008-10-26 20:11:58 +0000 +message: + Started implementing the matrix stack tests +------------------------------------------------------------ +revno: 23 +committer: Luke Benstead +timestamp: Sun 2008-10-26 10:56:51 +0000 +message: + Started new implementation of the GL matrix stack +------------------------------------------------------------ +revno: 22 +committer: Carsten Haubold +timestamp: Thu 2008-08-28 12:37:41 +0200 +message: + Added kmGLRotation +------------------------------------------------------------ +revno: 21 +committer: Luke Benstead +timestamp: Thu 2008-08-28 09:24:00 +0100 +message: + We now have a working matrix stack +------------------------------------------------------------ +revno: 20 +committer: Luke Benstead +timestamp: Wed 2008-08-27 13:34:49 +0100 +message: + Fixed the stack memory constants +------------------------------------------------------------ +revno: 19 +committer: Luke Benstead +timestamp: Wed 2008-08-27 13:33:12 +0100 +message: + Added the initial gl_utils implementation for replacing the matrix functionality deprecated in OpenGL 3.0 +------------------------------------------------------------ +revno: 18 +committer: Carsten Haubold +timestamp: Mon 2008-08-25 12:46:16 +0200 +message: + Fixed a bug in kmMat4LookAt +------------------------------------------------------------ +revno: 17 [merge] +committer: Carsten Haubold +timestamp: Sun 2008-08-24 22:07:49 +0200 +message: + Merge branch 'master' of git@github.com:Kazade/kazmath +------------------------------------------------------------ +revno: 16 +committer: Carsten Haubold +timestamp: Sun 2008-08-24 22:06:45 +0200 +message: + Added kmMat4LookAt +------------------------------------------------------------ +revno: 15 +committer: Carsten Haubold +timestamp: Wed 2008-08-20 11:18:10 +0200 +message: + Added Fill methods for all Vec and Mat structs +------------------------------------------------------------ +revno: 14 +committer: Carsten Haubold +timestamp: Tue 2008-08-19 22:31:55 +0200 +message: + Added UnitTests, changed bool to int and fixed some minor bugs +------------------------------------------------------------ +revno: 13 +committer: Carsten Haubold +timestamp: Sun 2008-08-17 23:19:21 +0200 +message: + removed .svn entries which did not belong here +------------------------------------------------------------ +revno: 12 +committer: Carsten Haubold +timestamp: Sun 2008-08-17 23:17:07 +0200 +message: + some tweaks on matrices and first test-app, PerspectiveProjection is correct ! +------------------------------------------------------------ +revno: 11 +committer: Carsten Haubold +timestamp: Sun 2008-08-17 16:04:09 +0200 +message: + Renamed cotangent to cotangens +------------------------------------------------------------ +revno: 10 +committer: Luke Benstead +timestamp: Sat 2008-08-16 21:51:22 +0100 +message: + Added kmMat4PerspectiveProjection and kmMat4OrthographicProjection +------------------------------------------------------------ +revno: 9 +committer: Luke Benstead +timestamp: Thu 2008-08-14 21:15:45 +0100 +message: + Added the aabb struct +------------------------------------------------------------ +revno: 8 +committer: Luke Benstead +timestamp: Thu 2008-08-14 17:57:43 +0100 +message: + Added the kmAABB structure +------------------------------------------------------------ +revno: 7 +committer: Luke Benstead +timestamp: Thu 2008-08-14 14:32:24 +0100 +message: + Fixed broken kmMat3Transpose +------------------------------------------------------------ +revno: 6 +committer: Luke Benstead +timestamp: Thu 2008-08-14 14:21:04 +0100 +message: + Fixed broken kmMat4Translation, w component was not set +------------------------------------------------------------ +revno: 5 +committer: Luke Benstead +timestamp: Thu 2008-08-14 14:01:47 +0100 +message: + Added mat3.c and mat3.h to the cmake file +------------------------------------------------------------ +revno: 4 +committer: Luke Benstead +timestamp: Thu 2008-08-14 13:56:26 +0100 +message: + Added the authors section to the readme +------------------------------------------------------------ +revno: 3 +committer: Luke Benstead +timestamp: Thu 2008-08-14 13:55:41 +0100 +message: + Updated the readme file +------------------------------------------------------------ +revno: 2 +committer: Luke Benstead +timestamp: Thu 2008-08-14 13:53:26 +0100 +message: + Added kazmath to git +------------------------------------------------------------ +revno: 1 +committer: Luke Benstead +timestamp: Thu 2008-08-14 13:47:51 +0100 +message: + First commit +------------------------------------------------------------ +Use --include-merges or -n0 to see merged revisions. diff --git a/Example/libs/kazmath/src/GL/mat4stack.c b/Example/libs/kazmath/src/GL/mat4stack.c new file mode 100644 index 0000000..f2ffe57 --- /dev/null +++ b/Example/libs/kazmath/src/GL/mat4stack.c @@ -0,0 +1,74 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include +#include + +#define INITIAL_SIZE 30 +#define INCREMENT 50 + +#include "kazmath/GL/mat4stack.h" + +void km_mat4_stack_initialize(km_mat4_stack* stack) { + stack->stack = (kmMat4*) malloc(sizeof(kmMat4) * INITIAL_SIZE); //allocate the memory + stack->capacity = INITIAL_SIZE; //Set the capacity to 10 + stack->top = NULL; //Set the top to NULL + stack->item_count = 0; +}; + +void km_mat4_stack_push(km_mat4_stack* stack, const kmMat4* item) +{ + stack->top = &stack->stack[stack->item_count]; + kmMat4Assign(stack->top, item); + stack->item_count++; + + if(stack->item_count >= stack->capacity) + { + kmMat4* temp = NULL; + stack->capacity += INCREMENT; + temp = stack->stack; + stack->stack = (kmMat4*) malloc(stack->capacity*sizeof(kmMat4)); + memcpy(stack->stack, temp, sizeof(kmMat4)*(stack->capacity - INCREMENT)); + free(temp); + stack->top = &stack->stack[stack->item_count - 1]; + } +} + +void km_mat4_stack_pop(km_mat4_stack* stack, kmMat4* pOut) +{ + assert(stack->item_count && "Cannot pop an empty stack"); + + stack->item_count--; + stack->top = &stack->stack[stack->item_count - 1]; +} + +void km_mat4_stack_release(km_mat4_stack* stack) { + free(stack->stack); + stack->top = NULL; + stack->item_count = 0; + stack->capacity = 0; +} diff --git a/Example/libs/kazmath/src/GL/matrix.c b/Example/libs/kazmath/src/GL/matrix.c new file mode 100644 index 0000000..f63cf14 --- /dev/null +++ b/Example/libs/kazmath/src/GL/matrix.c @@ -0,0 +1,191 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include + +#include "kazmath/GL/matrix.h" +#include "kazmath/GL/mat4stack.h" + +km_mat4_stack modelview_matrix_stack; +km_mat4_stack projection_matrix_stack; +km_mat4_stack texture_matrix_stack; + +km_mat4_stack* current_stack = NULL; + +static unsigned char initialized = 0; + +void lazyInitialize() +{ + + if (!initialized) { + kmMat4 identity; //Temporary identity matrix + + //Initialize all 3 stacks + //modelview_matrix_stack = (km_mat4_stack*) malloc(sizeof(km_mat4_stack)); + km_mat4_stack_initialize(&modelview_matrix_stack); + + //projection_matrix_stack = (km_mat4_stack*) malloc(sizeof(km_mat4_stack)); + km_mat4_stack_initialize(&projection_matrix_stack); + + //texture_matrix_stack = (km_mat4_stack*) malloc(sizeof(km_mat4_stack)); + km_mat4_stack_initialize(&texture_matrix_stack); + + current_stack = &modelview_matrix_stack; + initialized = 1; + + kmMat4Identity(&identity); + + //Make sure that each stack has the identity matrix + km_mat4_stack_push(&modelview_matrix_stack, &identity); + km_mat4_stack_push(&projection_matrix_stack, &identity); + km_mat4_stack_push(&texture_matrix_stack, &identity); + } +} + +void kmGLMatrixMode(kmGLEnum mode) +{ + lazyInitialize(); + + switch(mode) + { + case KM_GL_MODELVIEW: + current_stack = &modelview_matrix_stack; + break; + case KM_GL_PROJECTION: + current_stack = &projection_matrix_stack; + break; + case KM_GL_TEXTURE: + current_stack = &texture_matrix_stack; + break; + default: + assert(0 && "Invalid matrix mode specified"); //TODO: Proper error handling + break; + } +} + +void kmGLPushMatrix(void) +{ + kmMat4 top; + + lazyInitialize(); //Initialize the stacks if they haven't been already + + //Duplicate the top of the stack (i.e the current matrix) + kmMat4Assign(&top, current_stack->top); + km_mat4_stack_push(current_stack, &top); +} + +void kmGLPopMatrix(void) +{ + assert(initialized && "Cannot Pop empty matrix stack"); + //No need to lazy initialize, you shouldnt be popping first anyway! + km_mat4_stack_pop(current_stack, NULL); +} + +void kmGLLoadIdentity() +{ + lazyInitialize(); + + kmMat4Identity(current_stack->top); //Replace the top matrix with the identity matrix +} + +void kmGLFreeAll() +{ + //Clear the matrix stacks + km_mat4_stack_release(&modelview_matrix_stack); + km_mat4_stack_release(&projection_matrix_stack); + km_mat4_stack_release(&texture_matrix_stack); + + //Delete the matrices + initialized = 0; //Set to uninitialized + + current_stack = NULL; //Set the current stack to point nowhere +} + +void kmGLMultMatrix(const kmMat4* pIn) +{ + lazyInitialize(); + kmMat4Multiply(current_stack->top, current_stack->top, pIn); +} + +void kmGLLoadMatrix(const kmMat4* pIn) +{ + lazyInitialize(); + kmMat4Assign(current_stack->top, pIn); +} + +void kmGLGetMatrix(kmGLEnum mode, kmMat4* pOut) +{ + lazyInitialize(); + + switch(mode) + { + case KM_GL_MODELVIEW: + kmMat4Assign(pOut, modelview_matrix_stack.top); + break; + case KM_GL_PROJECTION: + kmMat4Assign(pOut, projection_matrix_stack.top); + break; + case KM_GL_TEXTURE: + kmMat4Assign(pOut, texture_matrix_stack.top); + break; + default: + assert(1 && "Invalid matrix mode specified"); //TODO: Proper error handling + break; + } +} + +void kmGLTranslatef(float x, float y, float z) +{ + kmMat4 translation; + + //Create a rotation matrix using the axis and the angle + kmMat4Translation(&translation,x,y,z); + + //Multiply the rotation matrix by the current matrix + kmMat4Multiply(current_stack->top, current_stack->top, &translation); +} + +void kmGLRotatef(float angle, float x, float y, float z) +{ + kmVec3 axis; + kmMat4 rotation; + + //Create an axis vector + kmVec3Fill(&axis, x, y, z); + + //Create a rotation matrix using the axis and the angle + kmMat4RotationAxisAngle(&rotation, &axis, kmDegreesToRadians(angle)); + + //Multiply the rotation matrix by the current matrix + kmMat4Multiply(current_stack->top, current_stack->top, &rotation); +} + +void kmGLScalef(float x, float y, float z) +{ + kmMat4 scaling; + kmMat4Scaling(&scaling, x, y, z); + kmMat4Multiply(current_stack->top, current_stack->top, &scaling); +} diff --git a/Example/libs/kazmath/src/aabb.c b/Example/libs/kazmath/src/aabb.c new file mode 100644 index 0000000..ea334a3 --- /dev/null +++ b/Example/libs/kazmath/src/aabb.c @@ -0,0 +1,63 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "kazmath/aabb.h" + +/** + * Returns KM_TRUE if point is in the specified AABB, returns + * KM_FALSE otherwise. + */ +const int kmAABBContainsPoint(const kmVec3* pPoint, const kmAABB* pBox) +{ + if(pPoint->x >= pBox->min.x && pPoint->x <= pBox->max.x && + pPoint->y >= pBox->min.y && pPoint->y <= pBox->max.y && + pPoint->z >= pBox->min.z && pPoint->z <= pBox->max.z) { + return KM_TRUE; + } + + return KM_FALSE; +} + +/** + * Assigns pIn to pOut, returns pOut. + */ +kmAABB* const kmAABBAssign(kmAABB* pOut, const kmAABB* pIn) +{ + kmVec3Assign(&pOut->min, &pIn->min); + kmVec3Assign(&pOut->max, &pIn->max); + return pOut; +} + +/** + * Scales pIn by s, stores the resulting AABB in pOut. Returns pOut + */ +kmAABB* const kmAABBScale(kmAABB* pOut, const kmAABB* pIn, kmScalar s) +{ + assert(0 && "Not implemented"); + return 0; +} + + + diff --git a/Example/libs/kazmath/src/mat3.c b/Example/libs/kazmath/src/mat3.c new file mode 100644 index 0000000..6847caa --- /dev/null +++ b/Example/libs/kazmath/src/mat3.c @@ -0,0 +1,372 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include + +#include "kazmath/utility.h" +#include "kazmath/vec3.h" +#include "kazmath/mat3.h" +#include "kazmath/quaternion.h" + +kmMat3* const kmMat3Fill(kmMat3* pOut, const kmScalar* pMat) +{ + memcpy(pOut->mat, pMat, sizeof(kmScalar) * 9); + return pOut; +} + +/** Sets pOut to an identity matrix returns pOut*/ +kmMat3* const kmMat3Identity(kmMat3* pOut) +{ + memset(pOut->mat, 0, sizeof(float) * 9); + pOut->mat[0] = pOut->mat[4] = pOut->mat[8] = 1.0f; + return pOut; +} + +const kmScalar kmMat3Determinant(const kmMat3* pIn) +{ + kmScalar output; + /* + calculating the determinant following the rule of sarus, + | 0 3 6 | 0 3 | + m = | 1 4 7 | 1 4 | + | 2 5 8 | 2 5 | + now sum up the products of the diagonals going to the right (i.e. 0,4,8) + and substract the products of the other diagonals (i.e. 2,4,6) + */ + + output = pIn->mat[0] * pIn->mat[4] * pIn->mat[8] + pIn->mat[1] * pIn->mat[5] * pIn->mat[6] + pIn->mat[2] * pIn->mat[3] * pIn->mat[7]; + output -= pIn->mat[2] * pIn->mat[4] * pIn->mat[6] + pIn->mat[0] * pIn->mat[5] * pIn->mat[7] + pIn->mat[1] * pIn->mat[3] * pIn->mat[8]; + + return output; +} + + +kmMat3* const kmMat3Adjugate(kmMat3* pOut, const kmMat3* pIn) +{ + pOut->mat[0] = pIn->mat[4] * pIn->mat[8] - pIn->mat[5] * pIn->mat[7]; + pOut->mat[1] = pIn->mat[2] * pIn->mat[7] - pIn->mat[1] * pIn->mat[8]; + pOut->mat[2] = pIn->mat[1] * pIn->mat[5] - pIn->mat[2] * pIn->mat[4]; + pOut->mat[3] = pIn->mat[5] * pIn->mat[6] - pIn->mat[3] * pIn->mat[8]; + pOut->mat[4] = pIn->mat[0] * pIn->mat[8] - pIn->mat[2] * pIn->mat[6]; + pOut->mat[5] = pIn->mat[2] * pIn->mat[3] - pIn->mat[0] * pIn->mat[5]; + pOut->mat[6] = pIn->mat[3] * pIn->mat[7] - pIn->mat[4] * pIn->mat[6]; + + // XXX: pIn->mat[9] is invalid! +// pOut->mat[7] = pIn->mat[1] * pIn->mat[6] - pIn->mat[9] * pIn->mat[7]; + pOut->mat[8] = pIn->mat[0] * pIn->mat[4] - pIn->mat[1] * pIn->mat[3]; + + return pOut; +} + +kmMat3* const kmMat3Inverse(kmMat3* pOut, const kmScalar pDeterminate, const kmMat3* pM) +{ + kmScalar detInv; + kmMat3 adjugate; + + if(pDeterminate == 0.0) + { + return NULL; + } + + detInv = 1.0 / pDeterminate; + + kmMat3Adjugate(&adjugate, pM); + kmMat3ScalarMultiply(pOut, &adjugate, detInv); + + return pOut; +} + +/** Returns true if pIn is an identity matrix */ +const int kmMat3IsIdentity(const kmMat3* pIn) +{ + static const float identity [] = { 1.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 1.0f}; + + return (memcmp(identity, pIn->mat, sizeof(float) * 9) == 0); +} + +/** Sets pOut to the transpose of pIn, returns pOut */ +kmMat3* const kmMat3Transpose(kmMat3* pOut, const kmMat3* pIn) +{ + int z, x; + for (z = 0; z < 3; ++z) { + for (x = 0; x < 3; ++x) { + pOut->mat[(z * 3) + x] = pIn->mat[(x * 3) + z]; + } + } + + return pOut; +} + +/* Multiplies pM1 with pM2, stores the result in pOut, returns pOut */ +kmMat3* const kmMat3Multiply(kmMat3* pOut, const kmMat3* pM1, const kmMat3* pM2) +{ + float mat[9]; + + const float *m1 = pM1->mat, *m2 = pM2->mat; + + mat[0] = m1[0] * m2[0] + m1[3] * m2[1] + m1[6] * m2[2]; + mat[1] = m1[1] * m2[0] + m1[4] * m2[1] + m1[7] * m2[2]; + mat[2] = m1[2] * m2[0] + m1[5] * m2[1] + m1[8] * m2[2]; + + mat[3] = m1[0] * m2[3] + m1[3] * m2[4] + m1[6] * m2[5]; + mat[4] = m1[1] * m2[3] + m1[4] * m2[4] + m1[7] * m2[5]; + mat[5] = m1[2] * m2[3] + m1[5] * m2[4] + m1[8] * m2[5]; + + mat[6] = m1[0] * m2[6] + m1[3] * m2[7] + m1[6] * m2[8]; + mat[7] = m1[1] * m2[6] + m1[4] * m2[7] + m1[7] * m2[8]; + mat[8] = m1[2] * m2[6] + m1[5] * m2[7] + m1[8] * m2[8]; + + memcpy(pOut->mat, mat, sizeof(float)*9); + + return pOut; +} + +kmMat3* const kmMat3ScalarMultiply(kmMat3* pOut, const kmMat3* pM, const kmScalar pFactor) +{ + float mat[9]; + int i; + + for(i = 0; i < 9; i++) + { + mat[i] = pM->mat[i] * pFactor; + } + + memcpy(pOut->mat, mat, sizeof(float)*9); + + return pOut; +} + +/** Assigns the value of pIn to pOut */ +kmMat3* const kmMat3Assign(kmMat3* pOut, const kmMat3* pIn) +{ + assert(pOut != pIn); //You have tried to self-assign!! + + memcpy(pOut->mat, pIn->mat, sizeof(float)*9); + + return pOut; +} + +/** Returns true if the 2 matrices are equal (approximately) */ +const int kmMat3AreEqual(const kmMat3* pMat1, const kmMat3* pMat2) +{ + int i; + if (pMat1 == pMat2) { + return KM_TRUE; + } + + for (i = 0; i < 9; ++i) { + if (!(pMat1->mat[i] + kmEpsilon > pMat2->mat[i] && + pMat1->mat[i] - kmEpsilon < pMat2->mat[i])) { + return KM_FALSE; + } + } + + return KM_TRUE; +} + +/* Rotation around the z axis so everything stays planar in XY */ +kmMat3* const kmMat3Rotation(kmMat3* pOut, const float radians) +{ + /* + | cos(A) -sin(A) 0 | + M = | sin(A) cos(A) 0 | + | 0 0 1 | + */ + + pOut->mat[0] = cosf(radians); + pOut->mat[1] = sinf(radians); + pOut->mat[2] = 0.0f; + + pOut->mat[3] = -sinf(radians);; + pOut->mat[4] = cosf(radians); + pOut->mat[5] = 0.0f; + + pOut->mat[6] = 0.0f; + pOut->mat[7] = 0.0f; + pOut->mat[8] = 1.0f; + + return pOut; +} + +/** Builds a scaling matrix */ +kmMat3* const kmMat3Scaling(kmMat3* pOut, const kmScalar x, const kmScalar y) +{ +// memset(pOut->mat, 0, sizeof(float) * 9); + kmMat3Identity(pOut); + pOut->mat[0] = x; + pOut->mat[4] = y; + + return pOut; +} + +kmMat3* const kmMat3Translation(kmMat3* pOut, const kmScalar x, const kmScalar y) +{ +// memset(pOut->mat, 0, sizeof(float) * 9); + kmMat3Identity(pOut); + pOut->mat[6] = x; + pOut->mat[7] = y; +// pOut->mat[8] = 1.0; + + return pOut; +} + + +kmMat3* const kmMat3RotationQuaternion(kmMat3* pOut, const kmQuaternion* pIn) +{ + if (!pIn || !pOut) { + return NULL; + } + + // First row + pOut->mat[0] = 1.0f - 2.0f * (pIn->y * pIn->y + pIn->z * pIn->z); + pOut->mat[1] = 2.0f * (pIn->x * pIn->y - pIn->w * pIn->z); + pOut->mat[2] = 2.0f * (pIn->x * pIn->z + pIn->w * pIn->y); + + // Second row + pOut->mat[3] = 2.0f * (pIn->x * pIn->y + pIn->w * pIn->z); + pOut->mat[4] = 1.0f - 2.0f * (pIn->x * pIn->x + pIn->z * pIn->z); + pOut->mat[5] = 2.0f * (pIn->y * pIn->z - pIn->w * pIn->x); + + // Third row + pOut->mat[6] = 2.0f * (pIn->x * pIn->z - pIn->w * pIn->y); + pOut->mat[7] = 2.0f * (pIn->y * pIn->z + pIn->w * pIn->x); + pOut->mat[8] = 1.0f - 2.0f * (pIn->x * pIn->x + pIn->y * pIn->y); + + return pOut; +} + +kmMat3* const kmMat3RotationAxisAngle(kmMat3* pOut, const struct kmVec3* axis, kmScalar radians) +{ + float rcos = cosf(radians); + float rsin = sinf(radians); + + pOut->mat[0] = rcos + axis->x * axis->x * (1 - rcos); + pOut->mat[1] = axis->z * rsin + axis->y * axis->x * (1 - rcos); + pOut->mat[2] = -axis->y * rsin + axis->z * axis->x * (1 - rcos); + + pOut->mat[3] = -axis->z * rsin + axis->x * axis->y * (1 - rcos); + pOut->mat[4] = rcos + axis->y * axis->y * (1 - rcos); + pOut->mat[5] = axis->x * rsin + axis->z * axis->y * (1 - rcos); + + pOut->mat[6] = axis->y * rsin + axis->x * axis->z * (1 - rcos); + pOut->mat[7] = -axis->x * rsin + axis->y * axis->z * (1 - rcos); + pOut->mat[8] = rcos + axis->z * axis->z * (1 - rcos); + + return pOut; +} + +kmVec3* const kmMat3RotationToAxisAngle(kmVec3* pAxis, kmScalar* radians, const kmMat3* pIn) +{ + /*Surely not this easy?*/ + kmQuaternion temp; + kmQuaternionRotationMatrix(&temp, pIn); + kmQuaternionToAxisAngle(&temp, pAxis, radians); + return pAxis; +} + +/** + * Builds an X-axis rotation matrix and stores it in pOut, returns pOut + */ +kmMat3* const kmMat3RotationX(kmMat3* pOut, const float radians) +{ + /* + | 1 0 0 | + M = | 0 cos(A) -sin(A) | + | 0 sin(A) cos(A) | + + */ + + pOut->mat[0] = 1.0f; + pOut->mat[1] = 0.0f; + pOut->mat[2] = 0.0f; + + pOut->mat[3] = 0.0f; + pOut->mat[4] = cosf(radians); + pOut->mat[5] = sinf(radians); + + pOut->mat[6] = 0.0f; + pOut->mat[7] = -sinf(radians); + pOut->mat[8] = cosf(radians); + + return pOut; +} + +/** + * Builds a rotation matrix using the rotation around the Y-axis + * The result is stored in pOut, pOut is returned. + */ +kmMat3* const kmMat3RotationY(kmMat3* pOut, const float radians) +{ + /* + | cos(A) 0 sin(A) | + M = | 0 1 0 | + | -sin(A) 0 cos(A) | + */ + + pOut->mat[0] = cosf(radians); + pOut->mat[1] = 0.0f; + pOut->mat[2] = -sinf(radians); + + pOut->mat[3] = 0.0f; + pOut->mat[4] = 1.0f; + pOut->mat[5] = 0.0f; + + pOut->mat[6] = sinf(radians); + pOut->mat[7] = 0.0f; + pOut->mat[8] = cosf(radians); + + return pOut; +} + +/** + * Builds a rotation matrix around the Z-axis. The resulting + * matrix is stored in pOut. pOut is returned. + */ +kmMat3* const kmMat3RotationZ(kmMat3* pOut, const float radians) +{ + /* + | cos(A) -sin(A) 0 | + M = | sin(A) cos(A) 0 | + | 0 0 1 | + */ + + pOut->mat[0] = cosf(radians); + pOut->mat[1] =-sinf(radians); + pOut->mat[2] = 0.0f; + + pOut->mat[3] = sinf(radians);; + pOut->mat[4] = cosf(radians); + pOut->mat[5] = 0.0f; + + pOut->mat[6] = 0.0f; + pOut->mat[7] = 0.0f; + pOut->mat[8] = 1.0f; + + return pOut; +} diff --git a/Example/libs/kazmath/src/mat4.c b/Example/libs/kazmath/src/mat4.c new file mode 100644 index 0000000..c55f5fd --- /dev/null +++ b/Example/libs/kazmath/src/mat4.c @@ -0,0 +1,789 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * @file mat4.c + */ +#include +#include +#include + +#include "kazmath/utility.h" +#include "kazmath/vec3.h" +#include "kazmath/mat4.h" +#include "kazmath/mat3.h" +#include "kazmath/quaternion.h" +#include "kazmath/plane.h" + +#include "kazmath/neon_matrix_impl.h" + +/** + * Fills a kmMat4 structure with the values from a 16 + * element array of floats + * @Params pOut - A pointer to the destination matrix + * pMat - A 16 element array of floats + * @Return Returns pOut so that the call can be nested + */ +kmMat4* const kmMat4Fill(kmMat4* pOut, const kmScalar* pMat) +{ + memcpy(pOut->mat, pMat, sizeof(kmScalar) * 16); + return pOut; +} + +/** + * Sets pOut to an identity matrix returns pOut + * @Params pOut - A pointer to the matrix to set to identity + * @Return Returns pOut so that the call can be nested + */ +kmMat4* const kmMat4Identity(kmMat4* pOut) +{ + memset(pOut->mat, 0, sizeof(float) * 16); + pOut->mat[0] = pOut->mat[5] = pOut->mat[10] = pOut->mat[15] = 1.0f; + return pOut; +} + + +float get(const kmMat4 * pIn, int row, int col) +{ + return pIn->mat[row + 4*col]; +} + +void set(kmMat4 * pIn, int row, int col, float value) +{ + pIn->mat[row + 4*col] = value; +} + +void swap(kmMat4 * pIn, int r1, int c1, int r2, int c2) +{ + float tmp = get(pIn,r1,c1); + set(pIn,r1,c1,get(pIn,r2,c2)); + set(pIn,r2,c2, tmp); +} + +//Returns an upper and a lower triangular matrix which are L and R in the Gauss algorithm +int gaussj(kmMat4 *a, kmMat4 *b) +{ + int i, icol = 0, irow = 0, j, k, l, ll, n = 4, m = 4; + float big, dum, pivinv; + int indxc[n]; + int indxr[n]; + int ipiv[n]; + + for (j = 0; j < n; j++) { + ipiv[j] = 0; + } + + for (i = 0; i < n; i++) { + big = 0.0f; + for (j = 0; j < n; j++) { + if (ipiv[j] != 1) { + for (k = 0; k < n; k++) { + if (ipiv[k] == 0) { + if (abs(get(a,j, k)) >= big) { + big = abs(get(a,j, k)); + irow = j; + icol = k; + } + } + } + } + } + ++(ipiv[icol]); + if (irow != icol) { + for (l = 0; l < n; l++) { + swap(a,irow, l, icol, l); + } + for (l = 0; l < m; l++) { + swap(b,irow, l, icol, l); + } + } + indxr[i] = irow; + indxc[i] = icol; + if (get(a,icol, icol) == 0.0) { + return KM_FALSE; + } + pivinv = 1.0f / get(a,icol, icol); + set(a,icol, icol, 1.0f); + for (l = 0; l < n; l++) { + set(a,icol, l, get(a,icol, l) * pivinv); + } + for (l = 0; l < m; l++) { + set(b,icol, l, get(b,icol, l) * pivinv); + } + + for (ll = 0; ll < n; ll++) { + if (ll != icol) { + dum = get(a,ll, icol); + set(a,ll, icol, 0.0f); + for (l = 0; l < n; l++) { + set(a,ll, l, get(a,ll, l) - get(a,icol, l) * dum); + } + for (l = 0; l < m; l++) { + set(b,ll, l, get(a,ll, l) - get(b,icol, l) * dum); + } + } + } + } +// This is the end of the main loop over columns of the reduction. It only remains to unscram- +// ble the solution in view of the column interchanges. We do this by interchanging pairs of +// columns in the reverse order that the permutation was built up. + for (l = n - 1; l >= 0; l--) { + if (indxr[l] != indxc[l]) { + for (k = 0; k < n; k++) { + swap(a,k, indxr[l], k, indxc[l]); + } + } + } + return KM_TRUE; +} + +/** + * Calculates the inverse of pM and stores the result in + * pOut. + * @Return Returns NULL if there is no inverse, else pOut + */ +kmMat4* const kmMat4Inverse(kmMat4* pOut, const kmMat4* pM) +{ + kmMat4 inv; + kmMat4Assign(&inv, pM); + + kmMat4 tmp; + kmMat4Identity(&tmp); + + if(gaussj(&inv, &tmp) == KM_FALSE) { + return NULL; + } + + kmMat4Assign(pOut, &inv); + return pOut; +} +/** + * Returns KM_TRUE if pIn is an identity matrix + * KM_FALSE otherwise + */ +const int kmMat4IsIdentity(const kmMat4* pIn) +{ + static const float identity [] = { 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + }; + + return (memcmp(identity, pIn->mat, sizeof(float) * 16) == 0); +} + +/** + * Sets pOut to the transpose of pIn, returns pOut + */ +kmMat4* const kmMat4Transpose(kmMat4* pOut, const kmMat4* pIn) +{ + int x, z; + + for (z = 0; z < 4; ++z) { + for (x = 0; x < 4; ++x) { + pOut->mat[(z * 4) + x] = pIn->mat[(x * 4) + z]; + } + } + + return pOut; +} + +/** + * Multiplies pM1 with pM2, stores the result in pOut, returns pOut + */ +kmMat4* const kmMat4Multiply(kmMat4* pOut, const kmMat4* pM1, const kmMat4* pM2) +{ +#if defined(__ARM_NEON__) + + float mat[16]; + + // Invert column-order with row-order + NEON_Matrix4Mul( &pM2->mat[0], &pM1->mat[0], &mat[0] ); + +#else + float mat[16]; + + const float *m1 = pM1->mat, *m2 = pM2->mat; + + mat[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]; + mat[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]; + mat[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]; + mat[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]; + + mat[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]; + mat[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]; + mat[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]; + mat[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]; + + mat[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]; + mat[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]; + mat[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]; + mat[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]; + + mat[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]; + mat[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]; + mat[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]; + mat[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]; + +#endif + + memcpy(pOut->mat, mat, sizeof(float)*16); + + return pOut; +} + +/** + * Assigns the value of pIn to pOut + */ +kmMat4* const kmMat4Assign(kmMat4* pOut, const kmMat4* pIn) +{ + assert(pOut != pIn && "You have tried to self-assign!!"); + + memcpy(pOut->mat, pIn->mat, sizeof(float)*16); + + return pOut; +} + +/** + * Returns KM_TRUE if the 2 matrices are equal (approximately) + */ +const int kmMat4AreEqual(const kmMat4* pMat1, const kmMat4* pMat2) +{ + int i = 0; + + assert(pMat1 != pMat2 && "You are comparing the same thing!"); + + for (i = 0; i < 16; ++i) + { + if (!(pMat1->mat[i] + kmEpsilon > pMat2->mat[i] && + pMat1->mat[i] - kmEpsilon < pMat2->mat[i])) { + return KM_FALSE; + } + } + + return KM_TRUE; +} + +/** + * Build a rotation matrix from an axis and an angle. Result is stored in pOut. + * pOut is returned. + */ +kmMat4* const kmMat4RotationAxisAngle(kmMat4* pOut, const kmVec3* axis, kmScalar radians) +{ + float rcos = cosf(radians); + float rsin = sinf(radians); + + kmVec3 normalizedAxis; + kmVec3Normalize(&normalizedAxis, axis); + + pOut->mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos); + pOut->mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos); + pOut->mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos); + pOut->mat[3] = 0.0f; + + pOut->mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos); + pOut->mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos); + pOut->mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos); + pOut->mat[7] = 0.0f; + + pOut->mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos); + pOut->mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos); + pOut->mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos); + pOut->mat[11] = 0.0f; + + pOut->mat[12] = 0.0f; + pOut->mat[13] = 0.0f; + pOut->mat[14] = 0.0f; + pOut->mat[15] = 1.0f; + + return pOut; +} + +/** + * Builds an X-axis rotation matrix and stores it in pOut, returns pOut + */ +kmMat4* const kmMat4RotationX(kmMat4* pOut, const float radians) +{ + /* + | 1 0 0 0 | + M = | 0 cos(A) -sin(A) 0 | + | 0 sin(A) cos(A) 0 | + | 0 0 0 1 | + + */ + + pOut->mat[0] = 1.0f; + pOut->mat[1] = 0.0f; + pOut->mat[2] = 0.0f; + pOut->mat[3] = 0.0f; + + pOut->mat[4] = 0.0f; + pOut->mat[5] = cosf(radians); + pOut->mat[6] = sinf(radians); + pOut->mat[7] = 0.0f; + + pOut->mat[8] = 0.0f; + pOut->mat[9] = -sinf(radians); + pOut->mat[10] = cosf(radians); + pOut->mat[11] = 0.0f; + + pOut->mat[12] = 0.0f; + pOut->mat[13] = 0.0f; + pOut->mat[14] = 0.0f; + pOut->mat[15] = 1.0f; + + return pOut; +} + +/** + * Builds a rotation matrix using the rotation around the Y-axis + * The result is stored in pOut, pOut is returned. + */ +kmMat4* const kmMat4RotationY(kmMat4* pOut, const float radians) +{ + /* + | cos(A) 0 sin(A) 0 | + M = | 0 1 0 0 | + | -sin(A) 0 cos(A) 0 | + | 0 0 0 1 | + */ + + pOut->mat[0] = cosf(radians); + pOut->mat[1] = 0.0f; + pOut->mat[2] = -sinf(radians); + pOut->mat[3] = 0.0f; + + pOut->mat[4] = 0.0f; + pOut->mat[5] = 1.0f; + pOut->mat[6] = 0.0f; + pOut->mat[7] = 0.0f; + + pOut->mat[8] = sinf(radians); + pOut->mat[9] = 0.0f; + pOut->mat[10] = cosf(radians); + pOut->mat[11] = 0.0f; + + pOut->mat[12] = 0.0f; + pOut->mat[13] = 0.0f; + pOut->mat[14] = 0.0f; + pOut->mat[15] = 1.0f; + + return pOut; +} + +/** + * Builds a rotation matrix around the Z-axis. The resulting + * matrix is stored in pOut. pOut is returned. + */ +kmMat4* const kmMat4RotationZ(kmMat4* pOut, const float radians) +{ + /* + | cos(A) -sin(A) 0 0 | + M = | sin(A) cos(A) 0 0 | + | 0 0 1 0 | + | 0 0 0 1 | + */ + + pOut->mat[0] = cosf(radians); + pOut->mat[1] = sinf(radians); + pOut->mat[2] = 0.0f; + pOut->mat[3] = 0.0f; + + pOut->mat[4] = -sinf(radians);; + pOut->mat[5] = cosf(radians); + pOut->mat[6] = 0.0f; + pOut->mat[7] = 0.0f; + + pOut->mat[8] = 0.0f; + pOut->mat[9] = 0.0f; + pOut->mat[10] = 1.0f; + pOut->mat[11] = 0.0f; + + pOut->mat[12] = 0.0f; + pOut->mat[13] = 0.0f; + pOut->mat[14] = 0.0f; + pOut->mat[15] = 1.0f; + + return pOut; +} + +/** + * Builds a rotation matrix from pitch, yaw and roll. The resulting + * matrix is stored in pOut and pOut is returned + */ +kmMat4* const kmMat4RotationPitchYawRoll(kmMat4* pOut, const kmScalar pitch, const kmScalar yaw, const kmScalar roll) +{ + double cr = cos(pitch); + double sr = sin(pitch); + double cp = cos(yaw); + double sp = sin(yaw); + double cy = cos(roll); + double sy = sin(roll); + double srsp = sr * sp; + double crsp = cr * sp; + + pOut->mat[0] = (kmScalar) cp * cy; + pOut->mat[4] = (kmScalar) cp * sy; + pOut->mat[8] = (kmScalar) - sp; + + pOut->mat[1] = (kmScalar) srsp * cy - cr * sy; + pOut->mat[5] = (kmScalar) srsp * sy + cr * cy; + pOut->mat[9] = (kmScalar) sr * cp; + + pOut->mat[2] = (kmScalar) crsp * cy + sr * sy; + pOut->mat[6] = (kmScalar) crsp * sy - sr * cy; + pOut->mat[10] = (kmScalar) cr * cp; + + pOut->mat[3] = pOut->mat[7] = pOut->mat[11] = 0.0; + pOut->mat[15] = 1.0; + + return pOut; +} + +/** Converts a quaternion to a rotation matrix, + * the result is stored in pOut, returns pOut + */ +kmMat4* const kmMat4RotationQuaternion(kmMat4* pOut, const kmQuaternion* pQ) +{ + pOut->mat[0] = 1.0f - 2.0f * (pQ->y * pQ->y + pQ->z * pQ->z ); + pOut->mat[1] = 2.0f * (pQ->x * pQ->y + pQ->z * pQ->w); + pOut->mat[2] = 2.0f * (pQ->x * pQ->z - pQ->y * pQ->w); + pOut->mat[3] = 0.0f; + + // Second row + pOut->mat[4] = 2.0f * ( pQ->x * pQ->y - pQ->z * pQ->w ); + pOut->mat[5] = 1.0f - 2.0f * ( pQ->x * pQ->x + pQ->z * pQ->z ); + pOut->mat[6] = 2.0f * (pQ->z * pQ->y + pQ->x * pQ->w ); + pOut->mat[7] = 0.0f; + + // Third row + pOut->mat[8] = 2.0f * ( pQ->x * pQ->z + pQ->y * pQ->w ); + pOut->mat[9] = 2.0f * ( pQ->y * pQ->z - pQ->x * pQ->w ); + pOut->mat[10] = 1.0f - 2.0f * ( pQ->x * pQ->x + pQ->y * pQ->y ); + pOut->mat[11] = 0.0f; + + // Fourth row + pOut->mat[12] = 0; + pOut->mat[13] = 0; + pOut->mat[14] = 0; + pOut->mat[15] = 1.0f; + + return pOut; +} + +/** Builds a scaling matrix */ +kmMat4* const kmMat4Scaling(kmMat4* pOut, const kmScalar x, const kmScalar y, + const kmScalar z) +{ + memset(pOut->mat, 0, sizeof(float) * 16); + pOut->mat[0] = x; + pOut->mat[5] = y; + pOut->mat[10] = z; + pOut->mat[15] = 1.0f; + + return pOut; +} + +/** + * Builds a translation matrix. All other elements in the matrix + * will be set to zero except for the diagonal which is set to 1.0 + */ +kmMat4* const kmMat4Translation(kmMat4* pOut, const kmScalar x, + const kmScalar y, const kmScalar z) +{ + //FIXME: Write a test for this + memset(pOut->mat, 0, sizeof(float) * 16); + + pOut->mat[0] = 1.0f; + pOut->mat[5] = 1.0f; + pOut->mat[10] = 1.0f; + + pOut->mat[12] = x; + pOut->mat[13] = y; + pOut->mat[14] = z; + pOut->mat[15] = 1.0f; + + return pOut; +} + +/** + * Get the up vector from a matrix. pIn is the matrix you + * wish to extract the vector from. pOut is a pointer to the + * kmVec3 structure that should hold the resulting vector + */ +kmVec3* const kmMat4GetUpVec3(kmVec3* pOut, const kmMat4* pIn) +{ + pOut->x = pIn->mat[4]; + pOut->y = pIn->mat[5]; + pOut->z = pIn->mat[6]; + + kmVec3Normalize(pOut, pOut); + + return pOut; +} + +/** Extract the right vector from a 4x4 matrix. The result is + * stored in pOut. Returns pOut. + */ +kmVec3* const kmMat4GetRightVec3(kmVec3* pOut, const kmMat4* pIn) +{ + pOut->x = pIn->mat[0]; + pOut->y = pIn->mat[1]; + pOut->z = pIn->mat[2]; + + kmVec3Normalize(pOut, pOut); + + return pOut; +} + +/** + * Extract the forward vector from a 4x4 matrix. The result is + * stored in pOut. Returns pOut. + */ +kmVec3* const kmMat4GetForwardVec3(kmVec3* pOut, const kmMat4* pIn) +{ + pOut->x = pIn->mat[8]; + pOut->y = pIn->mat[9]; + pOut->z = pIn->mat[10]; + + kmVec3Normalize(pOut, pOut); + + return pOut; +} + +/** + * Creates a perspective projection matrix in the + * same way as gluPerspective + */ +kmMat4* const kmMat4PerspectiveProjection(kmMat4* pOut, kmScalar fovY, + kmScalar aspect, kmScalar zNear, + kmScalar zFar) +{ + kmScalar r = kmDegreesToRadians(fovY / 2); + kmScalar deltaZ = zFar - zNear; + kmScalar s = sin(r); + kmScalar cotangent = 0; + + if (deltaZ == 0 || s == 0 || aspect == 0) { + return NULL; + } + + //cos(r) / sin(r) = cot(r) + cotangent = cos(r) / s; + + kmMat4Identity(pOut); + pOut->mat[0] = cotangent / aspect; + pOut->mat[5] = cotangent; + pOut->mat[10] = -(zFar + zNear) / deltaZ; + pOut->mat[11] = -1; + pOut->mat[14] = -2 * zNear * zFar / deltaZ; + pOut->mat[15] = 0; + + return pOut; +} + +/** Creates an orthographic projection matrix like glOrtho */ +kmMat4* const kmMat4OrthographicProjection(kmMat4* pOut, kmScalar left, + kmScalar right, kmScalar bottom, + kmScalar top, kmScalar nearVal, + kmScalar farVal) +{ + kmScalar tx = -((right + left) / (right - left)); + kmScalar ty = -((top + bottom) / (top - bottom)); + kmScalar tz = -((farVal + nearVal) / (farVal - nearVal)); + + kmMat4Identity(pOut); + pOut->mat[0] = 2 / (right - left); + pOut->mat[5] = 2 / (top - bottom); + pOut->mat[10] = -2 / (farVal - nearVal); + pOut->mat[12] = tx; + pOut->mat[13] = ty; + pOut->mat[14] = tz; + + return pOut; +} + +/** + * Builds a translation matrix in the same way as gluLookAt() + * the resulting matrix is stored in pOut. pOut is returned. + */ +kmMat4* const kmMat4LookAt(kmMat4* pOut, const kmVec3* pEye, + const kmVec3* pCenter, const kmVec3* pUp) +{ + kmVec3 f, up, s, u; + kmMat4 translate; + + kmVec3Subtract(&f, pCenter, pEye); + kmVec3Normalize(&f, &f); + + kmVec3Assign(&up, pUp); + kmVec3Normalize(&up, &up); + + kmVec3Cross(&s, &f, &up); + kmVec3Normalize(&s, &s); + + kmVec3Cross(&u, &s, &f); + kmVec3Normalize(&s, &s); + + kmMat4Identity(pOut); + + pOut->mat[0] = s.x; + pOut->mat[4] = s.y; + pOut->mat[8] = s.z; + + pOut->mat[1] = u.x; + pOut->mat[5] = u.y; + pOut->mat[9] = u.z; + + pOut->mat[2] = -f.x; + pOut->mat[6] = -f.y; + pOut->mat[10] = -f.z; + + kmMat4Translation(&translate, -pEye->x, -pEye->y, -pEye->z); + kmMat4Multiply(pOut, pOut, &translate); + + return pOut; +} + +/** + * Extract a 3x3 rotation matrix from the input 4x4 transformation. + * Stores the result in pOut, returns pOut + */ +kmMat3* const kmMat4ExtractRotation(kmMat3* pOut, const kmMat4* pIn) +{ + pOut->mat[0] = pIn->mat[0]; + pOut->mat[1] = pIn->mat[1]; + pOut->mat[2] = pIn->mat[2]; + + pOut->mat[3] = pIn->mat[4]; + pOut->mat[4] = pIn->mat[5]; + pOut->mat[5] = pIn->mat[6]; + + pOut->mat[6] = pIn->mat[8]; + pOut->mat[7] = pIn->mat[9]; + pOut->mat[8] = pIn->mat[10]; + + return pOut; +} + +/** + * Take the rotation from a 4x4 transformation matrix, and return it as an axis and an angle (in radians) + * returns the output axis. + */ +kmVec3* const kmMat4RotationToAxisAngle(kmVec3* pAxis, kmScalar* radians, const kmMat4* pIn) +{ + /*Surely not this easy?*/ + kmQuaternion temp; + kmMat3 rotation; + kmMat4ExtractRotation(&rotation, pIn); + kmQuaternionRotationMatrix(&temp, &rotation); + kmQuaternionToAxisAngle(&temp, pAxis, radians); + return pAxis; +} + +/** Build a 4x4 OpenGL transformation matrix using a 3x3 rotation matrix, + * and a 3d vector representing a translation. Assign the result to pOut, + * pOut is also returned. + */ +kmMat4* const kmMat4RotationTranslation(kmMat4* pOut, const kmMat3* rotation, const kmVec3* translation) +{ + pOut->mat[0] = rotation->mat[0]; + pOut->mat[1] = rotation->mat[1]; + pOut->mat[2] = rotation->mat[2]; + pOut->mat[3] = 0.0f; + + pOut->mat[4] = rotation->mat[3]; + pOut->mat[5] = rotation->mat[4]; + pOut->mat[6] = rotation->mat[5]; + pOut->mat[7] = 0.0f; + + pOut->mat[8] = rotation->mat[6]; + pOut->mat[9] = rotation->mat[7]; + pOut->mat[10] = rotation->mat[8]; + pOut->mat[11] = 0.0f; + + pOut->mat[12] = translation->x; + pOut->mat[13] = translation->y; + pOut->mat[14] = translation->z; + pOut->mat[15] = 1.0f; + + return pOut; +} + +kmPlane* const kmMat4ExtractPlane(kmPlane* pOut, const kmMat4* pIn, const kmEnum plane) +{ + float t = 1.0f; + + switch(plane) { + case KM_PLANE_RIGHT: + pOut->a = pIn->mat[3] - pIn->mat[0]; + pOut->b = pIn->mat[7] - pIn->mat[4]; + pOut->c = pIn->mat[11] - pIn->mat[8]; + pOut->d = pIn->mat[15] - pIn->mat[12]; + break; + case KM_PLANE_LEFT: + pOut->a = pIn->mat[3] + pIn->mat[0]; + pOut->b = pIn->mat[7] + pIn->mat[4]; + pOut->c = pIn->mat[11] + pIn->mat[8]; + pOut->d = pIn->mat[15] + pIn->mat[12]; + break; + case KM_PLANE_BOTTOM: + pOut->a = pIn->mat[3] + pIn->mat[1]; + pOut->b = pIn->mat[7] + pIn->mat[5]; + pOut->c = pIn->mat[11] + pIn->mat[9]; + pOut->d = pIn->mat[15] + pIn->mat[13]; + break; + case KM_PLANE_TOP: + pOut->a = pIn->mat[3] - pIn->mat[1]; + pOut->b = pIn->mat[7] - pIn->mat[5]; + pOut->c = pIn->mat[11] - pIn->mat[9]; + pOut->d = pIn->mat[15] - pIn->mat[13]; + break; + case KM_PLANE_FAR: + pOut->a = pIn->mat[3] - pIn->mat[2]; + pOut->b = pIn->mat[7] - pIn->mat[6]; + pOut->c = pIn->mat[11] - pIn->mat[10]; + pOut->d = pIn->mat[15] - pIn->mat[14]; + break; + case KM_PLANE_NEAR: + pOut->a = pIn->mat[3] + pIn->mat[2]; + pOut->b = pIn->mat[7] + pIn->mat[6]; + pOut->c = pIn->mat[11] + pIn->mat[10]; + pOut->d = pIn->mat[15] + pIn->mat[14]; + break; + default: + assert(0 && "Invalid plane index"); + } + + t = sqrtf(pOut->a * pOut->a + + pOut->b * pOut->b + + pOut->c * pOut->c); + pOut->a /= t; + pOut->b /= t; + pOut->c /= t; + pOut->d /= t; + + return pOut; +} diff --git a/Example/libs/kazmath/src/neon_matrix_impl.c b/Example/libs/kazmath/src/neon_matrix_impl.c new file mode 100644 index 0000000..a00f771 --- /dev/null +++ b/Example/libs/kazmath/src/neon_matrix_impl.c @@ -0,0 +1,97 @@ +/* + NEON math library for the iPhone / iPod touch + + Copyright (c) 2009 Justin Saunders + + This software is provided 'as-is', without any express or implied warranty. + In no event will the authors be held liable for any damages arising + from the use of this software. + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it freely, + subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product documentation + would be appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "kazmath/neon_matrix_impl.h" + +#if defined(__ARM_NEON__) + +void NEON_Matrix4Mul(const float* a, const float* b, float* output ) +{ + __asm__ volatile + ( + // Store A & B leaving room for q4-q7, which should be preserved + "vldmia %1, { q0-q3 } \n\t" + "vldmia %2, { q8-q11 }\n\t" + + // result = first column of B x first row of A + "vmul.f32 q12, q8, d0[0]\n\t" + "vmul.f32 q13, q8, d2[0]\n\t" + "vmul.f32 q14, q8, d4[0]\n\t" + "vmul.f32 q15, q8, d6[0]\n\t" + + // result += second column of B x second row of A + "vmla.f32 q12, q9, d0[1]\n\t" + "vmla.f32 q13, q9, d2[1]\n\t" + "vmla.f32 q14, q9, d4[1]\n\t" + "vmla.f32 q15, q9, d6[1]\n\t" + + // result += third column of B x third row of A + "vmla.f32 q12, q10, d1[0]\n\t" + "vmla.f32 q13, q10, d3[0]\n\t" + "vmla.f32 q14, q10, d5[0]\n\t" + "vmla.f32 q15, q10, d7[0]\n\t" + + // result += last column of B x last row of A + "vmla.f32 q12, q11, d1[1]\n\t" + "vmla.f32 q13, q11, d3[1]\n\t" + "vmla.f32 q14, q11, d5[1]\n\t" + "vmla.f32 q15, q11, d7[1]\n\t" + + // output = result registers + "vstmia %0, { q12-q15 }" + : // no output + : "r" (output), "r" (a), "r" (b) // input - note *value* of pointer doesn't change + : "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" //clobber + ); +} + +void NEON_Matrix4Vector4Mul(const float* m, const float* v, float* output) +{ + __asm__ volatile + ( + // Store m & v - avoiding q4-q7 which need to be preserved - q0 = result + "vldmia %1, { q8-q11 } \n\t" // q8-q11 = m + "vldmia %2, { q1 } \n\t" // q1 = v + + // result = first column of A x V.x + "vmul.f32 q0, q8, d2[0]\n\t" + + // result += second column of A x V.y + "vmla.f32 q0, q9, d2[1]\n\t" + + // result += third column of A x V.z + "vmla.f32 q0, q10, d3[0]\n\t" + + // result += last column of A x V.w + "vmla.f32 q0, q11, d3[1]\n\t" + + // output = result registers + "vstmia %0, { q0 }" + + : // no output + : "r" (output), "r" (m), "r" (v) // input - note *value* of pointer doesn't change + : "memory", "q0", "q1", "q8", "q9", "q10", "q11" //clobber + ); +} + +#endif diff --git a/Example/libs/kazmath/src/plane.c b/Example/libs/kazmath/src/plane.c new file mode 100644 index 0000000..f8dc02f --- /dev/null +++ b/Example/libs/kazmath/src/plane.c @@ -0,0 +1,175 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include + +#include "kazmath/vec3.h" +#include "kazmath/vec4.h" +#include "kazmath/plane.h" + +const kmScalar kmPlaneDot(const kmPlane* pP, const kmVec4* pV) +{ + //a*x + b*y + c*z + d*w + + return (pP->a * pV->x + + pP->b * pV->y + + pP->c * pV->z + + pP->d * pV->w); +} + +const kmScalar kmPlaneDotCoord(const kmPlane* pP, const kmVec3* pV) +{ + return (pP->a * pV->x + + pP->b * pV->y + + pP->c * pV->z + pP->d); +} + +const kmScalar kmPlaneDotNormal(const kmPlane* pP, const kmVec3* pV) +{ + return (pP->a * pV->x + + pP->b * pV->y + + pP->c * pV->z); +} + +kmPlane* const kmPlaneFromPointNormal(kmPlane* pOut, const kmVec3* pPoint, const kmVec3* pNormal) +{ + /* + Planea = Nx + Planeb = Ny + Planec = Nz + Planed = −N⋅P + */ + + + pOut->a = pNormal->x; + pOut->b = pNormal->y; + pOut->c = pNormal->z; + pOut->d = -kmVec3Dot(pNormal, pPoint); + + return pOut; +} + +/** + * Creates a plane from 3 points. The result is stored in pOut. + * pOut is returned. + */ +kmPlane* const kmPlaneFromPoints(kmPlane* pOut, const kmVec3* p1, const kmVec3* p2, const kmVec3* p3) +{ + /* + v = (B − A) × (C − A) + n = 1⁄|v| v + Outa = nx + Outb = ny + Outc = nz + Outd = −n⋅A + */ + + kmVec3 n, v1, v2; + kmVec3Subtract(&v1, p2, p1); //Create the vectors for the 2 sides of the triangle + kmVec3Subtract(&v2, p3, p1); + kmVec3Cross(&n, &v1, &v2); //Use the cross product to get the normal + + kmVec3Normalize(&n, &n); //Normalize it and assign to pOut->m_N + + pOut->a = n.x; + pOut->b = n.y; + pOut->c = n.z; + pOut->d = kmVec3Dot(kmVec3Scale(&n, &n, -1.0), p1); + + return pOut; +} + +kmVec3* const kmPlaneIntersectLine(kmVec3* pOut, const kmPlane* pP, const kmVec3* pV1, const kmVec3* pV2) +{ + /* + n = (Planea, Planeb, Planec) + d = V − U + Out = U − d⋅(Pd + n⋅U)⁄(d⋅n) [iff d⋅n ≠ 0] + */ + kmVec3 d; + assert(0 && "Not implemented"); + + + kmVec3Subtract(&d, pV2, pV1); //Get the direction vector + + + //TODO: Continue here! + /*if (fabs(kmVec3Dot(&pP->m_N, &d)) > kmEpsilon) + { + //If we get here then the plane and line are parallel (i.e. no intersection) + pOut = nullptr; //Set to nullptr + + return pOut; + } */ + + return NULL; +} + +kmPlane* const kmPlaneNormalize(kmPlane* pOut, const kmPlane* pP) +{ + kmVec3 n; + kmScalar l = 0; + + n.x = pP->a; + n.y = pP->b; + n.z = pP->c; + + l = 1.0f / kmVec3Length(&n); //Get 1/length + kmVec3Normalize(&n, &n); //Normalize the vector and assign to pOut + + pOut->a = n.x; + pOut->b = n.y; + pOut->c = n.z; + + pOut->d = pP->d * l; //Scale the D value and assign to pOut + + return pOut; +} + +kmPlane* const kmPlaneScale(kmPlane* pOut, const kmPlane* pP, kmScalar s) +{ + assert(0 && "Not implemented"); + return NULL; +} + +/** + * Returns POINT_INFRONT_OF_PLANE if pP is infront of pIn. Returns + * POINT_BEHIND_PLANE if it is behind. Returns POINT_ON_PLANE otherwise + */ +const POINT_CLASSIFICATION kmPlaneClassifyPoint(const kmPlane* pIn, const kmVec3* pP) +{ + // This function will determine if a point is on, in front of, or behind + // the plane. First we store the dot product of the plane and the point. + float distance = pIn->a * pP->x + pIn->b * pP->y + pIn->c * pP->z + pIn->d; + + // Simply put if the dot product is greater than 0 then it is infront of it. + // If it is less than 0 then it is behind it. And if it is 0 then it is on it. + if(distance > 0.001) return POINT_INFRONT_OF_PLANE; + if(distance < -0.001) return POINT_BEHIND_PLANE; + + return POINT_ON_PLANE; +} + diff --git a/Example/libs/kazmath/src/quaternion.c b/Example/libs/kazmath/src/quaternion.c new file mode 100644 index 0000000..c5bf58e --- /dev/null +++ b/Example/libs/kazmath/src/quaternion.c @@ -0,0 +1,582 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +#include +#include + +#include "kazmath/utility.h" +#include "kazmath/mat3.h" +#include "kazmath/vec3.h" +#include "kazmath/quaternion.h" + +///< Returns pOut, sets pOut to the conjugate of pIn +kmQuaternion* const kmQuaternionConjugate(kmQuaternion* pOut, const kmQuaternion* pIn) +{ + pOut->x = -pIn->x; + pOut->y = -pIn->y; + pOut->z = -pIn->z; + pOut->w = pIn->w; + + return pOut; +} + +///< Returns the dot product of the 2 quaternions +const kmScalar kmQuaternionDot(const kmQuaternion* q1, const kmQuaternion* q2) +{ + // A dot B = B dot A = AtBt + AxBx + AyBy + AzBz + + return (q1->w * q2->w + + q1->x * q2->x + + q1->y * q2->y + + q1->z * q2->z); +} + +///< Returns the exponential of the quaternion +kmQuaternion* kmQuaternionExp(kmQuaternion* pOut, const kmQuaternion* pIn) +{ + assert(0); + + return pOut; +} + +///< Makes the passed quaternion an identity quaternion +kmQuaternion* kmQuaternionIdentity(kmQuaternion* pOut) +{ + pOut->x = 0.0; + pOut->y = 0.0; + pOut->z = 0.0; + pOut->w = 1.0; + + return pOut; +} + +///< Returns the inverse of the passed Quaternion +kmQuaternion* kmQuaternionInverse(kmQuaternion* pOut, + const kmQuaternion* pIn) +{ + kmScalar l = kmQuaternionLength(pIn); + kmQuaternion tmp; + + if (fabs(l) > kmEpsilon) + { + pOut->x = 0.0; + pOut->y = 0.0; + pOut->z = 0.0; + pOut->w = 0.0; + + return pOut; + } + + + + ///Get the conjugute and divide by the length + kmQuaternionScale(pOut, + kmQuaternionConjugate(&tmp, pIn), 1.0f / l); + + return pOut; +} + +///< Returns true if the quaternion is an identity quaternion +int kmQuaternionIsIdentity(const kmQuaternion* pIn) +{ + return (pIn->x == 0.0 && pIn->y == 0.0 && pIn->z == 0.0 && + pIn->w == 1.0); +} + +///< Returns the length of the quaternion +kmScalar kmQuaternionLength(const kmQuaternion* pIn) +{ + return sqrtf(kmQuaternionLengthSq(pIn)); +} + +///< Returns the length of the quaternion squared (prevents a sqrt) +kmScalar kmQuaternionLengthSq(const kmQuaternion* pIn) +{ + return pIn->x * pIn->x + pIn->y * pIn->y + + pIn->z * pIn->z + pIn->w * pIn->w; +} + +///< Returns the natural logarithm +kmQuaternion* kmQuaternionLn(kmQuaternion* pOut, + const kmQuaternion* pIn) +{ + /* + A unit quaternion, is defined by: + Q == (cos(theta), sin(theta) * v) where |v| = 1 + The natural logarithm of Q is, ln(Q) = (0, theta * v) + */ + + assert(0); + + return pOut; +} + +///< Multiplies 2 quaternions together +extern +kmQuaternion* kmQuaternionMultiply(kmQuaternion* pOut, + const kmQuaternion* q1, + const kmQuaternion* q2) +{ + pOut->w = q1->w * q2->w - q1->x * q2->x - q1->y * q2->y - q1->z * q2->z; + pOut->x = q1->w * q2->x + q1->x * q2->w + q1->y * q2->z - q1->z * q2->y; + pOut->y = q1->w * q2->y + q1->y * q2->w + q1->z * q2->x - q1->x * q2->z; + pOut->z = q1->w * q2->z + q1->z * q2->w + q1->x * q2->y - q1->y * q2->x; + + return pOut; +} + +///< Normalizes a quaternion +kmQuaternion* kmQuaternionNormalize(kmQuaternion* pOut, + const kmQuaternion* pIn) +{ + kmScalar length = kmQuaternionLength(pIn); + assert(fabs(length) > kmEpsilon); + kmQuaternionScale(pOut, pIn, 1.0f / length); + + return pOut; +} + +///< Rotates a quaternion around an axis +kmQuaternion* kmQuaternionRotationAxis(kmQuaternion* pOut, + const kmVec3* pV, + kmScalar angle) +{ + kmScalar rad = angle * 0.5f; + kmScalar scale = sinf(rad); + + pOut->w = cosf(rad); + pOut->x = pV->x * scale; + pOut->y = pV->y * scale; + pOut->z = pV->z * scale; + + return pOut; +} + +///< Creates a quaternion from a rotation matrix +kmQuaternion* kmQuaternionRotationMatrix(kmQuaternion* pOut, + const kmMat3* pIn) +{ +/* +Note: The OpenGL matrices are transposed from the description below +taken from the Matrix and Quaternion FAQ + + if ( mat[0] > mat[5] && mat[0] > mat[10] ) { // Column 0: + S = sqrt( 1.0 + mat[0] - mat[5] - mat[10] ) * 2; + X = 0.25 * S; + Y = (mat[4] + mat[1] ) / S; + Z = (mat[2] + mat[8] ) / S; + W = (mat[9] - mat[6] ) / S; + } else if ( mat[5] > mat[10] ) { // Column 1: + S = sqrt( 1.0 + mat[5] - mat[0] - mat[10] ) * 2; + X = (mat[4] + mat[1] ) / S; + Y = 0.25 * S; + Z = (mat[9] + mat[6] ) / S; + W = (mat[2] - mat[8] ) / S; + } else { // Column 2: + S = sqrt( 1.0 + mat[10] - mat[0] - mat[5] ) * 2; + X = (mat[2] + mat[8] ) / S; + Y = (mat[9] + mat[6] ) / S; + Z = 0.25 * S; + W = (mat[4] - mat[1] ) / S; + } +*/ + + float x, y, z, w; + float *pMatrix = NULL; + float m4x4[16] = {0}; + float scale = 0.0f; + float diagonal = 0.0f; + + if(!pIn) { + return NULL; + } + +/* 0 3 6 + 1 4 7 + 2 5 8 + + 0 1 2 3 + 4 5 6 7 + 8 9 10 11 + 12 13 14 15*/ + + m4x4[0] = pIn->mat[0]; + m4x4[1] = pIn->mat[3]; + m4x4[2] = pIn->mat[6]; + m4x4[4] = pIn->mat[1]; + m4x4[5] = pIn->mat[4]; + m4x4[6] = pIn->mat[7]; + m4x4[8] = pIn->mat[2]; + m4x4[9] = pIn->mat[5]; + m4x4[10] = pIn->mat[8]; + m4x4[15] = 1; + pMatrix = &m4x4[0]; + + diagonal = pMatrix[0] + pMatrix[5] + pMatrix[10] + 1; + + if(diagonal > kmEpsilon) { + // Calculate the scale of the diagonal + scale = (float)sqrt(diagonal ) * 2; + + // Calculate the x, y, x and w of the quaternion through the respective equation + x = ( pMatrix[9] - pMatrix[6] ) / scale; + y = ( pMatrix[2] - pMatrix[8] ) / scale; + z = ( pMatrix[4] - pMatrix[1] ) / scale; + w = 0.25f * scale; + } + else + { + // If the first element of the diagonal is the greatest value + if ( pMatrix[0] > pMatrix[5] && pMatrix[0] > pMatrix[10] ) + { + // Find the scale according to the first element, and double that value + scale = (float)sqrt( 1.0f + pMatrix[0] - pMatrix[5] - pMatrix[10] ) * 2.0f; + + // Calculate the x, y, x and w of the quaternion through the respective equation + x = 0.25f * scale; + y = (pMatrix[4] + pMatrix[1] ) / scale; + z = (pMatrix[2] + pMatrix[8] ) / scale; + w = (pMatrix[9] - pMatrix[6] ) / scale; + } + // Else if the second element of the diagonal is the greatest value + else if (pMatrix[5] > pMatrix[10]) + { + // Find the scale according to the second element, and double that value + scale = (float)sqrt( 1.0f + pMatrix[5] - pMatrix[0] - pMatrix[10] ) * 2.0f; + + // Calculate the x, y, x and w of the quaternion through the respective equation + x = (pMatrix[4] + pMatrix[1] ) / scale; + y = 0.25f * scale; + z = (pMatrix[9] + pMatrix[6] ) / scale; + w = (pMatrix[2] - pMatrix[8] ) / scale; + } + // Else the third element of the diagonal is the greatest value + else + { + // Find the scale according to the third element, and double that value + scale = (float)sqrt( 1.0f + pMatrix[10] - pMatrix[0] - pMatrix[5] ) * 2.0f; + + // Calculate the x, y, x and w of the quaternion through the respective equation + x = (pMatrix[2] + pMatrix[8] ) / scale; + y = (pMatrix[9] + pMatrix[6] ) / scale; + z = 0.25f * scale; + w = (pMatrix[4] - pMatrix[1] ) / scale; + } + } + + pOut->x = x; + pOut->y = y; + pOut->z = z; + pOut->w = w; + + return pOut; + +#if 0 + kmScalar T = pIn->mat[0] + pIn->mat[5] + pIn->mat[10]; + + if (T > kmEpsilon) { + //If the trace is greater than zero we always use this calculation: + /* S = sqrt(T) * 2; + X = ( mat[9] - mat[6] ) / S; + Y = ( mat[2] - mat[8] ) / S; + Z = ( mat[4] - mat[1] ) / S; + W = 0.25 * S;*/ + +/* kmScalar s = sqrtf(T) * 2; + pOut->x = (pIn->mat[9] - pIn->mat[6]) / s; + pOut->y = (pIn->mat[8] - pIn->mat[2]) / s; + pOut->z = (pIn->mat[1] - pIn->mat[4]) / s; + pOut->w = 0.25f * s; + + kmQuaternionNormalize(pOut, pOut); + return pOut; + } + + //Otherwise the calculation depends on which major diagonal element has the greatest value. + + if (pIn->mat[0] > pIn->mat[5] && pIn->mat[0] > pIn->mat[10]) { + kmScalar s = sqrtf(1 + pIn->mat[0] - pIn->mat[5] - pIn->mat[10]) * 2; + pOut->x = 0.25f * s; + pOut->y = (pIn->mat[1] + pIn->mat[4]) / s; + pOut->z = (pIn->mat[8] + pIn->mat[2]) / s; + pOut->w = (pIn->mat[9] - pIn->mat[6]) / s; + } + else if (pIn->mat[5] > pIn->mat[10]) { + kmScalar s = sqrtf(1 + pIn->mat[5] - pIn->mat[0] - pIn->mat[10]) * 2; + pOut->x = (pIn->mat[1] + pIn->mat[4]) / s; + pOut->y = 0.25f * s; + pOut->z = (pIn->mat[9] + pIn->mat[6]) / s; + pOut->w = (pIn->mat[8] - pIn->mat[2]) / s; + } + else { + kmScalar s = sqrt(1.0f + pIn->mat[10] - pIn->mat[0] - pIn->mat[5]) * 2.0f; + pOut->x = (pIn->mat[8] + pIn->mat[2] ) / s; + pOut->y = (pIn->mat[6] + pIn->mat[9] ) / s; + pOut->z = 0.25f * s; + pOut->w = (pIn->mat[1] - pIn->mat[4] ) / s; + } + + kmQuaternionNormalize(pOut, pOut); + return pOut;*/ +#endif // 0 +} + +///< Create a quaternion from yaw, pitch and roll +kmQuaternion* kmQuaternionRotationYawPitchRoll(kmQuaternion* pOut, + kmScalar yaw, + kmScalar pitch, + kmScalar roll) +{ + kmScalar ex, ey, ez; // temp half euler angles + kmScalar cr, cp, cy, sr, sp, sy, cpcy, spsy; // temp vars in roll,pitch yaw + + ex = kmDegreesToRadians(pitch) / 2.0f; // convert to rads and half them + ey = kmDegreesToRadians(yaw) / 2.0f; + ez = kmDegreesToRadians(roll) / 2.0f; + + cr = cosf(ex); + cp = cosf(ey); + cy = cosf(ez); + + sr = sinf(ex); + sp = sinf(ey); + sy = sinf(ez); + + cpcy = cp * cy; + spsy = sp * sy; + + pOut->w = cr * cpcy + sr * spsy; + + pOut->x = sr * cpcy - cr * spsy; + pOut->y = cr * sp * cy + sr * cp * sy; + pOut->z = cr * cp * sy - sr * sp * cy; + + kmQuaternionNormalize(pOut, pOut); + + return pOut; +} + +///< Interpolate between 2 quaternions +kmQuaternion* kmQuaternionSlerp(kmQuaternion* pOut, + const kmQuaternion* q1, + const kmQuaternion* q2, + kmScalar t) +{ + + /*float CosTheta = Q0.DotProd(Q1); + float Theta = acosf(CosTheta); + float SinTheta = sqrtf(1.0f-CosTheta*CosTheta); + + float Sin_T_Theta = sinf(T*Theta)/SinTheta; + float Sin_OneMinusT_Theta = sinf((1.0f-T)*Theta)/SinTheta; + + Quaternion Result = Q0*Sin_OneMinusT_Theta; + Result += (Q1*Sin_T_Theta); + + return Result;*/ + + if (q1->x == q2->x && + q1->y == q2->y && + q1->z == q2->z && + q1->w == q2->w) { + + pOut->x = q1->x; + pOut->y = q1->y; + pOut->z = q1->z; + pOut->w = q1->w; + + return pOut; + } + + kmScalar ct = kmQuaternionDot(q1, q2); + kmScalar theta = acosf(ct); + kmScalar st = sqrtf(1.0 - kmSQR(ct)); + + kmScalar stt = sinf(t * theta) / st; + kmScalar somt = sinf((1.0 - t) * theta) / st; + + kmQuaternion temp, temp2; + kmQuaternionScale(&temp, q1, somt); + kmQuaternionScale(&temp2, q2, stt); + kmQuaternionAdd(pOut, &temp, &temp2); + + return pOut; +} + +///< Get the axis and angle of rotation from a quaternion +void kmQuaternionToAxisAngle(const kmQuaternion* pIn, + kmVec3* pAxis, + kmScalar* pAngle) +{ + kmScalar tempAngle; // temp angle + kmScalar scale; // temp vars + + tempAngle = acosf(pIn->w); + scale = sqrtf(kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z)); + + if (((scale > -kmEpsilon) && scale < kmEpsilon) + || (scale < 2*kmPI + kmEpsilon && scale > 2*kmPI - kmEpsilon)) // angle is 0 or 360 so just simply set axis to 0,0,1 with angle 0 + { + *pAngle = 0.0f; + + pAxis->x = 0.0f; + pAxis->y = 0.0f; + pAxis->z = 1.0f; + } + else + { + *pAngle = tempAngle * 2.0f; // angle in radians + + pAxis->x = pIn->x / scale; + pAxis->y = pIn->y / scale; + pAxis->z = pIn->z / scale; + kmVec3Normalize(pAxis, pAxis); + } +} + +kmQuaternion* kmQuaternionScale(kmQuaternion* pOut, + const kmQuaternion* pIn, + kmScalar s) +{ + pOut->x = pIn->x * s; + pOut->y = pIn->y * s; + pOut->z = pIn->z * s; + pOut->w = pIn->w * s; + + return pOut; +} + +kmQuaternion* kmQuaternionAssign(kmQuaternion* pOut, const kmQuaternion* pIn) +{ + memcpy(pOut, pIn, sizeof(float) * 4); + + return pOut; +} + +kmQuaternion* kmQuaternionAdd(kmQuaternion* pOut, const kmQuaternion* pQ1, const kmQuaternion* pQ2) +{ + pOut->x = pQ1->x + pQ2->x; + pOut->y = pQ1->y + pQ2->y; + pOut->z = pQ1->z + pQ2->z; + pOut->w = pQ1->w + pQ2->w; + + return pOut; +} + +/** Adapted from the OGRE engine! + + Gets the shortest arc quaternion to rotate this vector to the destination + vector. +@remarks + If you call this with a dest vector that is close to the inverse + of this vector, we will rotate 180 degrees around the 'fallbackAxis' + (if specified, or a generated axis if not) since in this case + ANY axis of rotation is valid. +*/ + +kmQuaternion* kmQuaternionRotationBetweenVec3(kmQuaternion* pOut, const kmVec3* vec1, const kmVec3* vec2, const kmVec3* fallback) { + + kmVec3 v1, v2; + kmScalar a; + + kmVec3Assign(&v1, vec1); + kmVec3Assign(&v2, vec2); + + kmVec3Normalize(&v1, &v1); + kmVec3Normalize(&v2, &v2); + + a = kmVec3Dot(&v1, &v2); + + if (a >= 1.0) { + kmQuaternionIdentity(pOut); + return pOut; + } + + if (a < (1e-6f - 1.0f)) { + if (fabs(kmVec3LengthSq(fallback)) < kmEpsilon) { + kmQuaternionRotationAxis(pOut, fallback, kmPI); + } else { + kmVec3 axis; + kmVec3 X; + X.x = 1.0; + X.y = 0.0; + X.z = 0.0; + + + kmVec3Cross(&axis, &X, vec1); + + //If axis is zero + if (fabs(kmVec3LengthSq(&axis)) < kmEpsilon) { + kmVec3 Y; + Y.x = 0.0; + Y.y = 1.0; + Y.z = 0.0; + + kmVec3Cross(&axis, &Y, vec1); + } + + kmVec3Normalize(&axis, &axis); + + kmQuaternionRotationAxis(pOut, &axis, kmPI); + } + } else { + kmScalar s = sqrtf((1+a) * 2); + kmScalar invs = 1 / s; + + kmVec3 c; + kmVec3Cross(&c, &v1, &v2); + + pOut->x = c.x * invs; + pOut->y = c.y * invs; + pOut->z = c.z * invs; + pOut->w = s * 0.5f; + + kmQuaternionNormalize(pOut, pOut); + } + + return pOut; + +} + +kmVec3* kmQuaternionMultiplyVec3(kmVec3* pOut, const kmQuaternion* q, const kmVec3* v) { + kmVec3 uv, uuv, qvec; + + qvec.x = q->x; + qvec.y = q->y; + qvec.z = q->z; + + kmVec3Cross(&uv, &qvec, v); + kmVec3Cross(&uuv, &qvec, &uv); + + kmVec3Scale(&uv, &uv, (2.0f * q->w)); + kmVec3Scale(&uuv, &uuv, 2.0f); + + kmVec3Add(pOut, v, &uv); + kmVec3Add(pOut, pOut, &uuv); + + return pOut; +} + diff --git a/Example/libs/kazmath/src/ray2.c b/Example/libs/kazmath/src/ray2.c new file mode 100644 index 0000000..514752f --- /dev/null +++ b/Example/libs/kazmath/src/ray2.c @@ -0,0 +1,184 @@ +#include +#include +#include "kazmath/ray2.h" + +void kmRay2Fill(kmRay2* ray, kmScalar px, kmScalar py, kmScalar vx, kmScalar vy) { + ray->start.x = px; + ray->start.y = py; + ray->dir.x = vx; + ray->dir.y = vy; +} + +kmBool kmRay2IntersectLineSegment(const kmRay2* ray, const kmVec2* p1, const kmVec2* p2, kmVec2* intersection) { + + float x1 = ray->start.x; + float y1 = ray->start.y; + float x2 = ray->start.x + ray->dir.x; + float y2 = ray->start.y + ray->dir.y; + float x3 = p1->x; + float y3 = p1->y; + float x4 = p2->x; + float y4 = p2->y; + + float denom = (y4 -y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + + //If denom is zero, the lines are parallel + if(denom > -kmEpsilon && denom < kmEpsilon) { + return KM_FALSE; + } + + float ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom; +// float ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom; + + float x = x1 + ua * (x2 - x1); + float y = y1 + ua * (y2 - y1); + + if(x < min(p1->x, p2->x) - kmEpsilon || + x > max(p1->x, p2->x) + kmEpsilon || + y < min(p1->y, p2->y) - kmEpsilon || + y > max(p1->y, p2->y) + kmEpsilon) { + //Outside of line + //printf("Outside of line, %f %f (%f %f)(%f, %f)\n", x, y, p1->x, p1->y, p2->x, p2->y); + return KM_FALSE; + } + + if(x < min(x1, x2) - kmEpsilon || + x > max(x1, x2) + kmEpsilon || + y < min(y1, y2) - kmEpsilon || + y > max(y1, y2) + kmEpsilon) { + //printf("Outside of ray, %f %f (%f %f)(%f, %f)\n", x, y, x1, y1, x2, y2); + return KM_FALSE; + } + + intersection->x = x; + intersection->y = y; + + return KM_TRUE; + + +/* + kmScalar A1, B1, C1; + kmScalar A2, B2, C2; + + A1 = ray->dir.y; + B1 = ray->dir.x; + C1 = A1 * ray->start.x + B1 * ray->start.y; + + A2 = p2->y - p1->y; + B2 = p2->x - p1->x; + C2 = A2 * p1->x + B2 * p1->y; + + double det = (A1 * B2) - (A2 * B1); + if(det == 0) { + printf("Parallel\n"); + return KM_FALSE; + } + + double x = (B2*C1 - B1*C2) / det; + double y = (A1*C2 - A2*C1) / det; + + if(x < min(p1->x, p2->x) - kmEpsilon || + x > max(p1->x, p2->x) + kmEpsilon || + y < min(p1->y, p2->y) - kmEpsilon || + y > max(p1->y, p2->y) + kmEpsilon) { + //Outside of line + printf("Outside of line, %f %f (%f %f)(%f, %f)\n", x, y, p1->x, p1->y, p2->x, p2->y); + return KM_FALSE; + } + + kmScalar x1 = ray->start.x; + kmScalar x2 = ray->start.x + ray->dir.x; + + kmScalar y1 = ray->start.y; + kmScalar y2 = ray->start.y + ray->dir.y; + + if(x < min(x1, x2) - kmEpsilon || + x > max(x1, x2) + kmEpsilon || + y < min(y1, y2) - kmEpsilon || + y > max(y1, y2) + kmEpsilon) { + printf("Outside of ray, %f %f (%f %f)(%f, %f)\n", x, y, x1, y1, x2, y2); + return KM_FALSE; + } + + intersection->x = x; + intersection->y = y; + + return KM_TRUE;*/ +} + +void calculate_line_normal(kmVec2 p1, kmVec2 p2, kmVec2* normal_out) { + kmVec2 tmp; + kmVec2Subtract(&tmp, &p2, &p1); //Get direction vector + + normal_out->x = -tmp.y; + normal_out->y = tmp.x; + kmVec2Normalize(normal_out, normal_out); + + //TODO: should check that the normal is pointing out of the triangle +} + +kmBool kmRay2IntersectTriangle(const kmRay2* ray, const kmVec2* p1, const kmVec2* p2, const kmVec2* p3, kmVec2* intersection, kmVec2* normal_out) { + kmVec2 intersect; + kmVec2 final_intersect; + kmVec2 normal; + kmScalar distance = 10000.0f; + kmBool intersected = KM_FALSE; + + if(kmRay2IntersectLineSegment(ray, p1, p2, &intersect)) { + intersected = KM_TRUE; + + kmVec2 tmp; + kmScalar this_distance = kmVec2Length(kmVec2Subtract(&tmp, &intersect, &ray->start)); + if(this_distance < distance) { + final_intersect.x = intersect.x; + final_intersect.y = intersect.y; + distance = this_distance; + + calculate_line_normal(*p1, *p2, &normal); + } + } + + if(kmRay2IntersectLineSegment(ray, p2, p3, &intersect)) { + intersected = KM_TRUE; + + kmVec2 tmp; + kmScalar this_distance = kmVec2Length(kmVec2Subtract(&tmp, &intersect, &ray->start)); + if(this_distance < distance) { + final_intersect.x = intersect.x; + final_intersect.y = intersect.y; + distance = this_distance; + + calculate_line_normal(*p2, *p3, &normal); + } + } + + if(kmRay2IntersectLineSegment(ray, p3, p1, &intersect)) { + intersected = KM_TRUE; + + kmVec2 tmp; + kmScalar this_distance = kmVec2Length(kmVec2Subtract(&tmp, &intersect, &ray->start)); + if(this_distance < distance) { + final_intersect.x = intersect.x; + final_intersect.y = intersect.y; + distance = this_distance; + + calculate_line_normal(*p3, *p1, &normal); + } + } + + if(intersected) { + intersection->x = final_intersect.x; + intersection->y = final_intersect.y; + if(normal_out) { + normal_out->x = normal.x; + normal_out->y = normal.y; + } + } + + return intersected; +} + +kmBool kmRay2IntersectCircle(const kmRay2* ray, const kmVec2 centre, const kmScalar radius, kmVec2* intersection) { + assert(0 && "Not implemented"); + return 0; +} diff --git a/Example/libs/kazmath/src/utility.c b/Example/libs/kazmath/src/utility.c new file mode 100644 index 0000000..1d89aca --- /dev/null +++ b/Example/libs/kazmath/src/utility.c @@ -0,0 +1,59 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "kazmath/utility.h" + +/** + * Returns the square of s (e.g. s*s) + */ +kmScalar kmSQR(kmScalar s) { + return s*s; +} + +/** + * Returns degrees as radians. + */ +kmScalar kmDegreesToRadians(kmScalar degrees) { + return degrees * kmPIOver180; +} + +/** + * Returns radians as degrees + */ +kmScalar kmRadiansToDegrees(kmScalar radians) { + return radians * kmPIUnder180; +} + +kmScalar min(kmScalar lhs, kmScalar rhs) { + return (lhs < rhs)? lhs : rhs; +} + +kmScalar max(kmScalar lhs, kmScalar rhs) { + return (lhs > rhs)? lhs : rhs; +} + +kmBool kmAlmostEqual(kmScalar lhs, kmScalar rhs) { + return (lhs + kmEpsilon > rhs && lhs - kmEpsilon < rhs); +} diff --git a/Example/libs/kazmath/src/vec2.c b/Example/libs/kazmath/src/vec2.c new file mode 100644 index 0000000..1a9511e --- /dev/null +++ b/Example/libs/kazmath/src/vec2.c @@ -0,0 +1,118 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include + +#include "kazmath/mat3.h" +#include "kazmath/vec2.h" +#include "kazmath/utility.h" + +kmVec2* kmVec2Fill(kmVec2* pOut, kmScalar x, kmScalar y) +{ + pOut->x = x; + pOut->y = y; + return pOut; +} + +kmScalar kmVec2Length(const kmVec2* pIn) +{ + return sqrtf(kmSQR(pIn->x) + kmSQR(pIn->y)); +} + +kmScalar kmVec2LengthSq(const kmVec2* pIn) +{ + return kmSQR(pIn->x) + kmSQR(pIn->y); +} + +kmVec2* kmVec2Normalize(kmVec2* pOut, const kmVec2* pIn) +{ + kmScalar l = 1.0f / kmVec2Length(pIn); + + kmVec2 v; + v.x = pIn->x * l; + v.y = pIn->y * l; + + pOut->x = v.x; + pOut->y = v.y; + + return pOut; +} + +kmVec2* kmVec2Add(kmVec2* pOut, const kmVec2* pV1, const kmVec2* pV2) +{ + pOut->x = pV1->x + pV2->x; + pOut->y = pV1->y + pV2->y; + + return pOut; +} + +kmScalar kmVec2Dot(const kmVec2* pV1, const kmVec2* pV2) +{ + return pV1->x * pV2->x + pV1->y * pV2->y; +} + +kmVec2* kmVec2Subtract(kmVec2* pOut, const kmVec2* pV1, const kmVec2* pV2) +{ + pOut->x = pV1->x - pV2->x; + pOut->y = pV1->y - pV2->y; + + return pOut; +} + +kmVec2* kmVec2Transform(kmVec2* pOut, const kmVec2* pV, const kmMat3* pM) +{ + kmVec2 v; + + v.x = pV->x * pM->mat[0] + pV->y * pM->mat[3] + pM->mat[6]; + v.y = pV->x * pM->mat[1] + pV->y * pM->mat[4] + pM->mat[7]; + + pOut->x = v.x; + pOut->y = v.y; + + return pOut; +} + +kmVec2* kmVec2TransformCoord(kmVec2* pOut, const kmVec2* pV, const kmMat3* pM) +{ + assert(0); + return NULL; +} + +kmVec2* kmVec2Scale(kmVec2* pOut, const kmVec2* pIn, const kmScalar s) +{ + pOut->x = pIn->x * s; + pOut->y = pIn->y * s; + + return pOut; +} + +int kmVec2AreEqual(const kmVec2* p1, const kmVec2* p2) +{ + return ( + (p1->x < p2->x + kmEpsilon && p1->x > p2->x - kmEpsilon) && + (p1->y < p2->y + kmEpsilon && p1->y > p2->y - kmEpsilon) + ); +} diff --git a/Example/libs/kazmath/src/vec3.c b/Example/libs/kazmath/src/vec3.c new file mode 100644 index 0000000..c520900 --- /dev/null +++ b/Example/libs/kazmath/src/vec3.c @@ -0,0 +1,310 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * @file vec3.c + */ + +#include +#include + +#include "kazmath/utility.h" +#include "kazmath/vec4.h" +#include "kazmath/mat4.h" +#include "kazmath/vec3.h" + +/** + * Fill a kmVec3 structure using 3 floating point values + * The result is store in pOut, returns pOut + */ +kmVec3* kmVec3Fill(kmVec3* pOut, kmScalar x, kmScalar y, kmScalar z) +{ + pOut->x = x; + pOut->y = y; + pOut->z = z; + return pOut; +} + + +/** + * Returns the length of the vector + */ +kmScalar kmVec3Length(const kmVec3* pIn) +{ + return sqrtf(kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z)); +} + +/** + * Returns the square of the length of the vector + */ +kmScalar kmVec3LengthSq(const kmVec3* pIn) +{ + return kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z); +} + + /** + * Returns the vector passed in set to unit length + * the result is stored in pOut. + */ +kmVec3* kmVec3Normalize(kmVec3* pOut, const kmVec3* pIn) +{ + kmScalar l = 1.0f / kmVec3Length(pIn); + + kmVec3 v; + v.x = pIn->x * l; + v.y = pIn->y * l; + v.z = pIn->z * l; + + pOut->x = v.x; + pOut->y = v.y; + pOut->z = v.z; + + return pOut; +} + +/** + * Returns a vector perpendicular to 2 other vectors. + * The result is stored in pOut. + */ +kmVec3* kmVec3Cross(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2) +{ + + kmVec3 v; + + v.x = (pV1->y * pV2->z) - (pV1->z * pV2->y); + v.y = (pV1->z * pV2->x) - (pV1->x * pV2->z); + v.z = (pV1->x * pV2->y) - (pV1->y * pV2->x); + + pOut->x = v.x; + pOut->y = v.y; + pOut->z = v.z; + + return pOut; +} + +/** + * Returns the cosine of the angle between 2 vectors + */ +kmScalar kmVec3Dot(const kmVec3* pV1, const kmVec3* pV2) +{ + return ( pV1->x * pV2->x + + pV1->y * pV2->y + + pV1->z * pV2->z ); +} + +/** + * Adds 2 vectors and returns the result. The resulting + * vector is stored in pOut. + */ +kmVec3* kmVec3Add(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2) +{ + kmVec3 v; + + v.x = pV1->x + pV2->x; + v.y = pV1->y + pV2->y; + v.z = pV1->z + pV2->z; + + pOut->x = v.x; + pOut->y = v.y; + pOut->z = v.z; + + return pOut; +} + + /** + * Subtracts 2 vectors and returns the result. The result is stored in + * pOut. + */ +kmVec3* kmVec3Subtract(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2) +{ + kmVec3 v; + + v.x = pV1->x - pV2->x; + v.y = pV1->y - pV2->y; + v.z = pV1->z - pV2->z; + + pOut->x = v.x; + pOut->y = v.y; + pOut->z = v.z; + + return pOut; +} + + /** + * Transforms vector (x, y, z, 1) by a given matrix. The result + * is stored in pOut. pOut is returned. + */ +kmVec3* kmVec3Transform(kmVec3* pOut, const kmVec3* pV, const kmMat4* pM) +{ + /* + a = (Vx, Vy, Vz, 1) + b = (a×M)T + Out = (bx, by, bz) + */ + + kmVec3 v; + + v.x = pV->x * pM->mat[0] + pV->y * pM->mat[4] + pV->z * pM->mat[8] + pM->mat[12]; + v.y = pV->x * pM->mat[1] + pV->y * pM->mat[5] + pV->z * pM->mat[9] + pM->mat[13]; + v.z = pV->x * pM->mat[2] + pV->y * pM->mat[6] + pV->z * pM->mat[10] + pM->mat[14]; + + pOut->x = v.x; + pOut->y = v.y; + pOut->z = v.z; + + return pOut; +} + +kmVec3* kmVec3InverseTransform(kmVec3* pOut, const kmVec3* pVect, const kmMat4* pM) +{ + kmVec3 v1, v2; + + v1.x = pVect->x - pM->mat[12]; + v1.y = pVect->y - pM->mat[13]; + v1.z = pVect->z - pM->mat[14]; + + v2.x = v1.x * pM->mat[0] + v1.y * pM->mat[1] + v1.z * pM->mat[2]; + v2.y = v1.x * pM->mat[4] + v1.y * pM->mat[5] + v1.z * pM->mat[6]; + v2.z = v1.x * pM->mat[8] + v1.y * pM->mat[9] + v1.z * pM->mat[10]; + + pOut->x = v2.x; + pOut->y = v2.y; + pOut->z = v2.z; + + return pOut; +} + +kmVec3* kmVec3InverseTransformNormal(kmVec3* pOut, const kmVec3* pVect, const kmMat4* pM) +{ + kmVec3 v; + + v.x = pVect->x * pM->mat[0] + pVect->y * pM->mat[1] + pVect->z * pM->mat[2]; + v.y = pVect->x * pM->mat[4] + pVect->y * pM->mat[5] + pVect->z * pM->mat[6]; + v.z = pVect->x * pM->mat[8] + pVect->y * pM->mat[9] + pVect->z * pM->mat[10]; + + pOut->x = v.x; + pOut->y = v.y; + pOut->z = v.z; + + return pOut; +} + + +kmVec3* kmVec3TransformCoord(kmVec3* pOut, const kmVec3* pV, const kmMat4* pM) +{ + /* + a = (Vx, Vy, Vz, 1) + b = (a×M)T + Out = 1⁄bw(bx, by, bz) + */ + + kmVec4 v; + kmVec4 inV; + kmVec4Fill(&inV, pV->x, pV->y, pV->z, 1.0); + + kmVec4Transform(&v, &inV,pM); + + pOut->x = v.x / v.w; + pOut->y = v.y / v.w; + pOut->z = v.z / v.w; + + return pOut; +} + +kmVec3* kmVec3TransformNormal(kmVec3* pOut, const kmVec3* pV, const kmMat4* pM) +{ +/* + a = (Vx, Vy, Vz, 0) + b = (a×M)T + Out = (bx, by, bz) +*/ + //Omits the translation, only scaling + rotating + kmVec3 v; + + v.x = pV->x * pM->mat[0] + pV->y * pM->mat[4] + pV->z * pM->mat[8]; + v.y = pV->x * pM->mat[1] + pV->y * pM->mat[5] + pV->z * pM->mat[9]; + v.z = pV->x * pM->mat[2] + pV->y * pM->mat[6] + pV->z * pM->mat[10]; + + pOut->x = v.x; + pOut->y = v.y; + pOut->z = v.z; + + return pOut; + +} + +/** + * Scales a vector to length s. Does not normalize first, + * you should do that! + */ +kmVec3* kmVec3Scale(kmVec3* pOut, const kmVec3* pIn, const kmScalar s) +{ + pOut->x = pIn->x * s; + pOut->y = pIn->y * s; + pOut->z = pIn->z * s; + + return pOut; +} + +/** + * Returns KM_TRUE if the 2 vectors are approximately equal + */ +int kmVec3AreEqual(const kmVec3* p1, const kmVec3* p2) +{ + if ((p1->x < (p2->x + kmEpsilon) && p1->x > (p2->x - kmEpsilon)) && + (p1->y < (p2->y + kmEpsilon) && p1->y > (p2->y - kmEpsilon)) && + (p1->z < (p2->z + kmEpsilon) && p1->z > (p2->z - kmEpsilon))) { + return 1; + } + + return 0; +} + +/** + * Assigns pIn to pOut. Returns pOut. If pIn and pOut are the same + * then nothing happens but pOut is still returned + */ +kmVec3* kmVec3Assign(kmVec3* pOut, const kmVec3* pIn) { + if (pOut == pIn) { + return pOut; + } + + pOut->x = pIn->x; + pOut->y = pIn->y; + pOut->z = pIn->z; + + return pOut; +} + +/** + * Sets all the elements of pOut to zero. Returns pOut. + */ +kmVec3* kmVec3Zero(kmVec3* pOut) { + pOut->x = 0.0f; + pOut->y = 0.0f; + pOut->z = 0.0f; + + return pOut; +} diff --git a/Example/libs/kazmath/src/vec4.c b/Example/libs/kazmath/src/vec4.c new file mode 100644 index 0000000..4842e46 --- /dev/null +++ b/Example/libs/kazmath/src/vec4.c @@ -0,0 +1,154 @@ +/* +Copyright (c) 2008, Luke Benstead. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +#include +#include + +#include "kazmath/utility.h" +#include "kazmath/vec4.h" +#include "kazmath/mat4.h" + + +kmVec4* kmVec4Fill(kmVec4* pOut, kmScalar x, kmScalar y, kmScalar z, kmScalar w) +{ + pOut->x = x; + pOut->y = y; + pOut->z = z; + pOut->w = w; + return pOut; +} + + +/// Adds 2 4D vectors together. The result is store in pOut, the function returns +/// pOut so that it can be nested in another function. +kmVec4* kmVec4Add(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2) { + pOut->x = pV1->x + pV2->x; + pOut->y = pV1->y + pV2->y; + pOut->z = pV1->z + pV2->z; + pOut->w = pV1->w + pV2->w; + + return pOut; +} + +/// Returns the dot product of 2 4D vectors +kmScalar kmVec4Dot(const kmVec4* pV1, const kmVec4* pV2) { + return ( pV1->x * pV2->x + + pV1->y * pV2->y + + pV1->z * pV2->z + + pV1->w * pV2->w ); +} + +/// Returns the length of a 4D vector, this uses a sqrt so if the squared length will do use +/// kmVec4LengthSq +kmScalar kmVec4Length(const kmVec4* pIn) { + return sqrtf(kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z) + kmSQR(pIn->w)); +} + +/// Returns the length of the 4D vector squared. +kmScalar kmVec4LengthSq(const kmVec4* pIn) { + return kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z) + kmSQR(pIn->w); +} + +/// Returns the interpolation of 2 4D vectors based on t. Currently not implemented! +kmVec4* kmVec4Lerp(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2, kmScalar t) { + assert(0); + return pOut; +} + +/// Normalizes a 4D vector. The result is stored in pOut. pOut is returned +kmVec4* kmVec4Normalize(kmVec4* pOut, const kmVec4* pIn) { + kmScalar l = 1.0f / kmVec4Length(pIn); + + pOut->x *= l; + pOut->y *= l; + pOut->z *= l; + pOut->w *= l; + + return pOut; +} + +/// Scales a vector to the required length. This performs a Normalize before multiplying by S. +kmVec4* kmVec4Scale(kmVec4* pOut, const kmVec4* pIn, const kmScalar s) { + kmVec4Normalize(pOut, pIn); + + pOut->x *= s; + pOut->y *= s; + pOut->z *= s; + pOut->w *= s; + return pOut; +} + +/// Subtracts one 4D pV2 from pV1. The result is stored in pOut. pOut is returned +kmVec4* kmVec4Subtract(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2) { + pOut->x = pV1->x - pV2->x; + pOut->y = pV1->y - pV2->y; + pOut->z = pV1->z - pV2->z; + pOut->w = pV1->w - pV2->w; + + return pOut; +} + +/// Transforms a 4D vector by a matrix, the result is stored in pOut, and pOut is returned. +kmVec4* kmVec4Transform(kmVec4* pOut, const kmVec4* pV, const kmMat4* pM) { + pOut->x = pV->x * pM->mat[0] + pV->y * pM->mat[4] + pV->z * pM->mat[8] + pV->w * pM->mat[12]; + pOut->y = pV->x * pM->mat[1] + pV->y * pM->mat[5] + pV->z * pM->mat[9] + pV->w * pM->mat[13]; + pOut->z = pV->x * pM->mat[2] + pV->y * pM->mat[6] + pV->z * pM->mat[10] + pV->w * pM->mat[14]; + pOut->w = pV->x * pM->mat[3] + pV->y * pM->mat[7] + pV->z * pM->mat[11] + pV->w * pM->mat[15]; + return pOut; +} + +/// Loops through an input array transforming each vec4 by the matrix. +kmVec4* kmVec4TransformArray(kmVec4* pOut, unsigned int outStride, + const kmVec4* pV, unsigned int vStride, const kmMat4* pM, unsigned int count) { + unsigned int i = 0; + //Go through all of the vectors + while (i < count) { + const kmVec4* in = pV + (i * vStride); //Get a pointer to the current input + kmVec4* out = pOut + (i * outStride); //and the current output + kmVec4Transform(out, in, pM); //Perform transform on it + ++i; + } + + return pOut; +} + +int kmVec4AreEqual(const kmVec4* p1, const kmVec4* p2) { + return ( + (p1->x < p2->x + kmEpsilon && p1->x > p2->x - kmEpsilon) && + (p1->y < p2->y + kmEpsilon && p1->y > p2->y - kmEpsilon) && + (p1->z < p2->z + kmEpsilon && p1->z > p2->z - kmEpsilon) && + (p1->w < p2->w + kmEpsilon && p1->w > p2->w - kmEpsilon) + ); +} + +kmVec4* kmVec4Assign(kmVec4* pOut, const kmVec4* pIn) { + assert(pOut != pIn); + + memcpy(pOut, pIn, sizeof(float) * 4); + + return pOut; +} + From a541bce0af8048fcd5403faca0d11a04a5b951f4 Mon Sep 17 00:00:00 2001 From: Ngo Duc Hiep Date: Mon, 21 May 2012 20:20:48 +0700 Subject: [PATCH 3/6] Add files to gles2 branch --- CCBlade.h | 16 +- CCBlade.m | 71 +- Example/Classes/ExampleAppDelegate.h | 14 +- Example/Classes/ExampleAppDelegate.m | 220 +-- Example/Classes/HelloWorldLayer.m | 10 +- Example/Example.xcodeproj/project.pbxproj | 1705 ++++++++++------- Example/libs/cocos2d/CCAction.h | 45 +- Example/libs/cocos2d/CCAction.m | 95 +- Example/libs/cocos2d/CCActionCamera.h | 15 +- Example/libs/cocos2d/CCActionCamera.m | 29 +- Example/libs/cocos2d/CCActionEase.h | 4 +- Example/libs/cocos2d/CCActionEase.m | 52 +- Example/libs/cocos2d/CCActionGrid.h | 18 +- Example/libs/cocos2d/CCActionGrid.m | 90 +- Example/libs/cocos2d/CCActionGrid3D.h | 11 +- Example/libs/cocos2d/CCActionGrid3D.m | 119 +- Example/libs/cocos2d/CCActionInstant.h | 42 +- Example/libs/cocos2d/CCActionInstant.m | 112 +- Example/libs/cocos2d/CCActionInterval.h | 209 +- Example/libs/cocos2d/CCActionInterval.m | 925 +++++---- Example/libs/cocos2d/CCActionManager.h | 53 +- Example/libs/cocos2d/CCActionManager.m | 127 +- Example/libs/cocos2d/CCActionPageTurn3D.h | 6 +- Example/libs/cocos2d/CCActionPageTurn3D.m | 24 +- Example/libs/cocos2d/CCActionProgressTimer.h | 4 +- Example/libs/cocos2d/CCActionProgressTimer.m | 8 +- Example/libs/cocos2d/CCActionTiledGrid.h | 8 +- Example/libs/cocos2d/CCActionTiledGrid.m | 134 +- Example/libs/cocos2d/CCActionTween.h | 20 +- Example/libs/cocos2d/CCActionTween.m | 12 +- Example/libs/cocos2d/CCAnimation.h | 144 +- Example/libs/cocos2d/CCAnimation.m | 158 +- Example/libs/cocos2d/CCAnimationCache.h | 23 +- Example/libs/cocos2d/CCAnimationCache.m | 166 +- Example/libs/cocos2d/CCAtlasNode.h | 36 +- Example/libs/cocos2d/CCAtlasNode.m | 100 +- Example/libs/cocos2d/CCBlockSupport.h | 51 - Example/libs/cocos2d/CCBlockSupport.m | 46 - Example/libs/cocos2d/CCCamera.h | 24 +- Example/libs/cocos2d/CCCamera.m | 72 +- Example/libs/cocos2d/CCCompatibility.h | 224 --- Example/libs/cocos2d/CCCompatibility.m | 596 ------ Example/libs/cocos2d/CCConfiguration.h | 46 +- Example/libs/cocos2d/CCConfiguration.m | 99 +- Example/libs/cocos2d/CCDirector.h | 174 +- Example/libs/cocos2d/CCDirector.m | 361 ++-- Example/libs/cocos2d/CCDrawingPrimitives.h | 43 +- Example/libs/cocos2d/CCDrawingPrimitives.m | 352 ++-- Example/libs/cocos2d/CCGrabber.h | 9 +- Example/libs/cocos2d/CCGrabber.m | 48 +- Example/libs/cocos2d/CCGrid.h | 13 +- Example/libs/cocos2d/CCGrid.m | 347 ++-- Example/libs/cocos2d/CCLabelAtlas.h | 30 +- Example/libs/cocos2d/CCLabelAtlas.m | 132 +- Example/libs/cocos2d/CCLabelBMFont.h | 128 +- Example/libs/cocos2d/CCLabelBMFont.m | 563 ++++-- Example/libs/cocos2d/CCLabelTTF.h | 33 +- Example/libs/cocos2d/CCLabelTTF.m | 131 +- Example/libs/cocos2d/CCLayer.h | 147 +- Example/libs/cocos2d/CCLayer.m | 358 ++-- Example/libs/cocos2d/CCMenu.h | 39 +- Example/libs/cocos2d/CCMenu.m | 262 +-- Example/libs/cocos2d/CCMenuItem.h | 254 ++- Example/libs/cocos2d/CCMenuItem.m | 564 +++--- Example/libs/cocos2d/CCMotionStreak.h | 85 +- Example/libs/cocos2d/CCMotionStreak.m | 268 ++- Example/libs/cocos2d/CCNode.h | 299 +-- Example/libs/cocos2d/CCNode.m | 772 ++++---- Example/libs/cocos2d/CCParallaxNode.h | 13 +- Example/libs/cocos2d/CCParallaxNode.m | 39 +- Example/libs/cocos2d/CCParticleExamples.h | 13 +- Example/libs/cocos2d/CCParticleExamples.m | 281 +-- Example/libs/cocos2d/CCParticleSystem.h | 103 +- Example/libs/cocos2d/CCParticleSystem.m | 633 +++--- Example/libs/cocos2d/CCParticleSystemPoint.h | 64 - Example/libs/cocos2d/CCParticleSystemPoint.m | 207 -- Example/libs/cocos2d/CCParticleSystemQuad.h | 21 +- Example/libs/cocos2d/CCParticleSystemQuad.m | 436 +++-- Example/libs/cocos2d/CCProgressTimer.h | 71 +- Example/libs/cocos2d/CCProgressTimer.m | 572 +++--- Example/libs/cocos2d/CCProtocols.h | 30 +- Example/libs/cocos2d/CCRenderTexture.h | 59 +- Example/libs/cocos2d/CCRenderTexture.m | 380 ++-- Example/libs/cocos2d/CCRibbon.h | 117 -- Example/libs/cocos2d/CCRibbon.m | 381 ---- Example/libs/cocos2d/CCScene.h | 11 +- Example/libs/cocos2d/CCScene.m | 11 +- Example/libs/cocos2d/CCScheduler.h | 78 +- Example/libs/cocos2d/CCScheduler.m | 357 ++-- Example/libs/cocos2d/CCSprite.h | 167 +- Example/libs/cocos2d/CCSprite.m | 805 ++++---- Example/libs/cocos2d/CCSpriteBatchNode.h | 53 +- Example/libs/cocos2d/CCSpriteBatchNode.m | 478 +++-- Example/libs/cocos2d/CCSpriteFrame.h | 55 +- Example/libs/cocos2d/CCSpriteFrame.m | 124 +- Example/libs/cocos2d/CCSpriteFrameCache.h | 36 +- Example/libs/cocos2d/CCSpriteFrameCache.m | 197 +- Example/libs/cocos2d/CCSpriteSheet.h | 61 - Example/libs/cocos2d/CCSpriteSheet.m | 37 - Example/libs/cocos2d/CCTMXLayer.h | 79 +- Example/libs/cocos2d/CCTMXLayer.m | 454 +++-- Example/libs/cocos2d/CCTMXObjectGroup.h | 12 +- Example/libs/cocos2d/CCTMXObjectGroup.m | 15 +- Example/libs/cocos2d/CCTMXTiledMap.h | 37 +- Example/libs/cocos2d/CCTMXTiledMap.m | 129 +- Example/libs/cocos2d/CCTMXXMLParser.h | 82 +- Example/libs/cocos2d/CCTMXXMLParser.m | 353 ++-- Example/libs/cocos2d/CCTexture2D.h | 116 +- Example/libs/cocos2d/CCTexture2D.m | 769 ++++---- Example/libs/cocos2d/CCTextureAtlas.h | 70 +- Example/libs/cocos2d/CCTextureAtlas.m | 392 +++- Example/libs/cocos2d/CCTextureCache.h | 55 +- Example/libs/cocos2d/CCTextureCache.m | 581 +++--- Example/libs/cocos2d/CCTexturePVR.h | 23 +- Example/libs/cocos2d/CCTexturePVR.m | 216 ++- Example/libs/cocos2d/CCTileMapAtlas.h | 21 +- Example/libs/cocos2d/CCTileMapAtlas.m | 74 +- Example/libs/cocos2d/CCTransition.h | 15 +- Example/libs/cocos2d/CCTransition.m | 228 +-- Example/libs/cocos2d/CCTransitionPageTurn.h | 14 +- Example/libs/cocos2d/CCTransitionPageTurn.m | 14 +- Example/libs/cocos2d/CCTransitionRadial.h | 40 - Example/libs/cocos2d/CCTransitionRadial.m | 115 -- Example/libs/cocos2d/Platforms/CCGL.h | 63 +- Example/libs/cocos2d/Platforms/CCNS.h | 28 +- .../cocos2d/Platforms/Mac/CCDirectorMac.h | 37 +- .../cocos2d/Platforms/Mac/CCDirectorMac.m | 464 +++-- .../cocos2d/Platforms/Mac/CCEventDispatcher.h | 98 +- .../cocos2d/Platforms/Mac/CCEventDispatcher.m | 352 ++-- .../libs/cocos2d/Platforms/Mac/MacGLView.h | 88 - .../libs/cocos2d/Platforms/Mac/MacGLView.m | 241 --- .../cocos2d/Platforms/iOS/CCDirectorIOS.h | 270 +-- .../cocos2d/Platforms/iOS/CCDirectorIOS.m | 887 +++------ .../Platforms/iOS/CCTouchDelegateProtocol.h | 18 +- .../cocos2d/Platforms/iOS/CCTouchDispatcher.h | 28 +- .../cocos2d/Platforms/iOS/CCTouchDispatcher.m | 169 +- .../cocos2d/Platforms/iOS/CCTouchHandler.h | 10 +- .../cocos2d/Platforms/iOS/CCTouchHandler.m | 20 +- Example/libs/cocos2d/Platforms/iOS/EAGLView.h | 155 -- Example/libs/cocos2d/Platforms/iOS/EAGLView.m | 342 ---- .../libs/cocos2d/Platforms/iOS/ES1Renderer.h | 71 - .../libs/cocos2d/Platforms/iOS/ES1Renderer.m | 252 --- .../libs/cocos2d/Platforms/iOS/ESRenderer.h | 53 - Example/libs/cocos2d/Platforms/iOS/glu.c | 113 -- Example/libs/cocos2d/Platforms/iOS/glu.h | 29 - Example/libs/cocos2d/Support/CCArray.h | 38 +- Example/libs/cocos2d/Support/CCArray.m | 137 +- Example/libs/cocos2d/Support/CCFileUtils.h | 109 +- Example/libs/cocos2d/Support/CCFileUtils.m | 319 ++- Example/libs/cocos2d/Support/CCProfiling.h | 60 +- Example/libs/cocos2d/Support/CCProfiling.m | 145 +- .../libs/cocos2d/Support/CGPointExtension.h | 59 +- .../libs/cocos2d/Support/CGPointExtension.m | 123 +- .../libs/cocos2d/Support/OpenGL_Internal.h | 8 +- Example/libs/cocos2d/Support/TGAlib.h | 6 +- Example/libs/cocos2d/Support/TGAlib.m | 82 +- Example/libs/cocos2d/Support/TransformUtils.h | 14 +- Example/libs/cocos2d/Support/TransformUtils.m | 9 +- Example/libs/cocos2d/Support/ZipUtils.h | 33 +- Example/libs/cocos2d/Support/ZipUtils.m | 100 +- Example/libs/cocos2d/Support/base64.c | 18 +- Example/libs/cocos2d/Support/base64.h | 12 +- Example/libs/cocos2d/Support/ccCArray.h | 168 +- Example/libs/cocos2d/Support/ccUtils.c | 4 +- Example/libs/cocos2d/Support/ccUtils.h | 13 +- Example/libs/cocos2d/Support/uthash.h | 124 +- Example/libs/cocos2d/Support/utlist.h | 71 +- Example/libs/cocos2d/ccConfig.h | 324 ++-- Example/libs/cocos2d/ccMacros.h | 261 ++- Example/libs/cocos2d/ccTypes.h | 89 +- Example/libs/cocos2d/cocos2d.h | 51 +- Example/libs/cocos2d/cocos2d.m | 13 +- TouchTrailLayer.h | 1 + TouchTrailLayer.m | 28 +- 174 files changed, 13824 insertions(+), 13572 deletions(-) delete mode 100644 Example/libs/cocos2d/CCBlockSupport.h delete mode 100644 Example/libs/cocos2d/CCBlockSupport.m delete mode 100644 Example/libs/cocos2d/CCCompatibility.h delete mode 100644 Example/libs/cocos2d/CCCompatibility.m delete mode 100644 Example/libs/cocos2d/CCParticleSystemPoint.h delete mode 100644 Example/libs/cocos2d/CCParticleSystemPoint.m delete mode 100644 Example/libs/cocos2d/CCRibbon.h delete mode 100644 Example/libs/cocos2d/CCRibbon.m delete mode 100644 Example/libs/cocos2d/CCSpriteSheet.h delete mode 100644 Example/libs/cocos2d/CCSpriteSheet.m delete mode 100644 Example/libs/cocos2d/CCTransitionRadial.h delete mode 100644 Example/libs/cocos2d/CCTransitionRadial.m delete mode 100644 Example/libs/cocos2d/Platforms/Mac/MacGLView.h delete mode 100644 Example/libs/cocos2d/Platforms/Mac/MacGLView.m delete mode 100644 Example/libs/cocos2d/Platforms/iOS/EAGLView.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/EAGLView.m delete mode 100644 Example/libs/cocos2d/Platforms/iOS/ES1Renderer.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/ES1Renderer.m delete mode 100644 Example/libs/cocos2d/Platforms/iOS/ESRenderer.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/glu.c delete mode 100644 Example/libs/cocos2d/Platforms/iOS/glu.h diff --git a/CCBlade.h b/CCBlade.h index a7b9fb7..a5de4eb 100644 --- a/CCBlade.h +++ b/CCBlade.h @@ -1,5 +1,5 @@ /* - * cocos2d+ext for iPhone + * CCBlade for iPhone * * Copyright (c) 2011 - Ngo Duc Hiep * @@ -41,23 +41,19 @@ inline void f1(CGPoint p1, CGPoint p2, float d, CGPoint *o1, CGPoint *o2); int count; CGPoint *vertices; CGPoint *coordinates; - BOOL reset; - CCTexture2D *_texture; + CCTexture2D *texture; float width; - BOOL _finish; - BOOL _willPop; + BOOL finish; + BOOL willPop; } -@property (readonly)unsigned int pointLimit; +@property (readonly) unsigned int pointLimit; @property(retain) CCTexture2D *texture; @property(nonatomic) float width; -@property (nonatomic, assign) BOOL autoDim; +@property (nonatomic) BOOL autoDim; + (id) bladeWithMaximumPoint:(int) limit; - (id) initWithMaximumPoint:(int) limit; - (void) push:(CGPoint) v; - (void) pop:(int) n; -- (void) clear; -- (void) reset; -- (void) dim:(BOOL) dim; - (void) finish; @end diff --git a/CCBlade.m b/CCBlade.m index 137c066..c5c62dd 100644 --- a/CCBlade.m +++ b/CCBlade.m @@ -1,5 +1,5 @@ /* - * cocos2d+ext for iPhone + * CCBlade for iPhone * * Copyright (c) 2011 - Ngo Duc Hiep * @@ -71,7 +71,10 @@ + (id) bladeWithMaximumPoint:(int) limit{ - (id) initWithMaximumPoint:(int) limit{ self = [super init]; - + + // shader program + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTexture]; + pointLimit = limit; self.width = 5; @@ -79,10 +82,10 @@ - (id) initWithMaximumPoint:(int) limit{ coordinates = (CGPoint *)calloc(2*limit+5, sizeof(coordinates[0])); CGPointSet(coordinates+0, 0.00, 0.5); - reset = NO; + finish = NO; path = [[NSMutableArray alloc] init]; - + return self; } @@ -129,28 +132,27 @@ - (void) shift{ } - (void) setWidth:(float)width_{ - width = width_ * CC_CONTENT_SCALE_FACTOR(); + width = width_ ;//* CC_CONTENT_SCALE_FACTOR(); } #define DISTANCE_TO_INTERPOLATE 10 -- (void) push:(CGPoint) v{ - _willPop = NO; - - if (reset) { +- (void) push:(CGPoint) v{ + if (finish) { return; } if (CC_CONTENT_SCALE_FACTOR() != 1.0f) { - v = ccpMult(v, CC_CONTENT_SCALE_FACTOR()); + //v = ccpMult(v, CC_CONTENT_SCALE_FACTOR()); } - + #if USE_LAGRANGE - + if ([path count] == 0) { [path insertObject:[NSValue valueWithCGPoint:v] atIndex:0]; return; } + willPop = NO; CGPoint first = [[path objectAtIndex:0] CGPointValue]; if (ccpDistance(v, first) < DISTANCE_TO_INTERPOLATE) { [path insertObject:[NSValue valueWithCGPoint:v] atIndex:0]; @@ -173,7 +175,7 @@ - (void) push:(CGPoint) v{ path.pop_back(); } #endif // !USE_LAGRANGE - + [self populateVertices]; } @@ -191,46 +193,41 @@ - (void) pop:(int) n{ - (void) clear{ [path removeAllObjects]; - reset = NO; - if (_finish) - [self removeFromParentAndCleanup:YES]; + } -- (void) reset{ - reset = TRUE; -} - -- (void) dim:(BOOL) dim{ - reset = dim; -} - - (void) draw{ - if ((reset && [path count] > 0) || (self.autoDim && _willPop)) { + if (finish || (self.autoDim && willPop)) { [self pop:1]; - if ([path count] < 3) { - [self clear]; - } } if ([path count] < 3) { + if (finish) { + [self removeFromParentAndCleanup:NO]; + } + return; } - _willPop = YES; - - glDisableClientState(GL_COLOR_ARRAY); - NSAssert(_texture, @"NO TEXTURE SET"); + willPop = YES; + CC_NODE_DRAW_SETUP(); + ccGLEnableVertexAttribs(kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords); + + ccGLBindTexture2D( [_texture name] ); + ccGLBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); + + glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices); + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, coordinates); + - glBindTexture(GL_TEXTURE_2D, _texture.name); - glVertexPointer(2, GL_FLOAT, 0, vertices); - glTexCoordPointer(2, GL_FLOAT, 0, coordinates); glDrawArrays(GL_TRIANGLE_STRIP, 0, 2*[path count]-2); - glEnableClientState(GL_COLOR_ARRAY); + + CC_INCREMENT_GL_DRAWS(1); } - (void) finish { - _finish = YES; + finish = YES; } @end diff --git a/Example/Classes/ExampleAppDelegate.h b/Example/Classes/ExampleAppDelegate.h index 5374867..5e91569 100644 --- a/Example/Classes/ExampleAppDelegate.h +++ b/Example/Classes/ExampleAppDelegate.h @@ -8,13 +8,17 @@ #import -@class RootViewController; - -@interface ExampleAppDelegate : NSObject { - UIWindow *window; - RootViewController *viewController; +@interface ExampleAppDelegate : NSObject +{ + UIWindow *window_; + UINavigationController *navController_; + + CCDirectorIOS *director_; // weak ref } @property (nonatomic, retain) UIWindow *window; +@property (readonly) UINavigationController *navController; +@property (readonly) CCDirectorIOS *director; @end + diff --git a/Example/Classes/ExampleAppDelegate.m b/Example/Classes/ExampleAppDelegate.m index 31d1438..4cb64a5 100644 --- a/Example/Classes/ExampleAppDelegate.m +++ b/Example/Classes/ExampleAppDelegate.m @@ -9,151 +9,139 @@ #import "cocos2d.h" #import "ExampleAppDelegate.h" -#import "GameConfig.h" -#import "HelloWorldScene.h" -#import "RootViewController.h" +#import "HelloWorldLayer.h" +#import "TouchTrailLayer.h" @implementation ExampleAppDelegate -@synthesize window; +@synthesize window=window_, navController=navController_, director=director_; -- (void) removeStartupFlicker +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - // - // THIS CODE REMOVES THE STARTUP FLICKER - // - // Uncomment the following code if you Application only supports landscape mode - // -#if GAME_AUTOROTATION == kGameAutorotationUIViewController - -// CC_ENABLE_DEFAULT_GL_STATES(); -// CCDirector *director = [CCDirector sharedDirector]; -// CGSize size = [director winSize]; -// CCSprite *sprite = [CCSprite spriteWithFile:@"Default.png"]; -// sprite.position = ccp(size.width/2, size.height/2); -// sprite.rotation = -90; -// [sprite visit]; -// [[director openGLView] swapBuffers]; -// CC_ENABLE_DEFAULT_GL_STATES(); - -#endif // GAME_AUTOROTATION == kGameAutorotationUIViewController -} -- (void) applicationDidFinishLaunching:(UIApplication*)application -{ - // Init the window - window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; - - // Try to use CADisplayLink director - // if it fails (SDK < 3.1) use the default director - if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] ) - [CCDirector setDirectorType:kCCDirectorTypeDefault]; - - - CCDirector *director = [CCDirector sharedDirector]; - - // Init the View Controller - viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; - viewController.wantsFullScreenLayout = YES; - - // - // Create the EAGLView manually - // 1. Create a RGB565 format. Alternative: RGBA8 - // 2. depth format of 0 bit. Use 16 or 24 bit for 3d effects, like CCPageTurnTransition - // - // - - EAGLView *glView = [EAGLView viewWithFrame:[window bounds] - pixelFormat:kEAGLColorFormatRGB565 // kEAGLColorFormatRGBA8 - depthFormat:0 // GL_DEPTH_COMPONENT16_OES - ]; - + // Create the main window + window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; + + + // Create an CCGLView with a RGB565 color buffer, and a depth buffer of 0-bits + CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds] + pixelFormat:kEAGLColorFormatRGB565 //kEAGLColorFormatRGBA8 + depthFormat:0 //GL_DEPTH_COMPONENT24_OES + preserveBackbuffer:NO + sharegroup:nil + multiSampling:NO + numberOfSamples:0]; + + director_ = (CCDirectorIOS*) [CCDirector sharedDirector]; + + director_.wantsFullScreenLayout = YES; + + // Display FSP and SPF + [director_ setDisplayStats:YES]; + + // set FPS at 60 + [director_ setAnimationInterval:1.0/60]; + // attach the openglView to the director - [director setOpenGLView:glView]; - -// // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices - if( ! [director enableRetinaDisplay:YES] ) + [director_ setView:glView]; + + // for rotation and other messages + [director_ setDelegate:self]; + + // 2D projection + [director_ setProjection:kCCDirectorProjection2D]; + // [director setProjection:kCCDirectorProjection3D]; + + // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices + if( ! [director_ enableRetinaDisplay:YES] ) CCLOG(@"Retina Display Not supported"); - - // - // VERY IMPORTANT: - // If the rotation is going to be controlled by a UIViewController - // then the device orientation should be "Portrait". - // - // IMPORTANT: - // By default, this template only supports Landscape orientations. - // Edit the RootViewController.m file to edit the supported orientations. - // -#if GAME_AUTOROTATION == kGameAutorotationUIViewController - [director setDeviceOrientation:kCCDeviceOrientationPortrait]; -#else - [director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft]; -#endif - - [director setAnimationInterval:1.0/60]; - [director setDisplayFPS:YES]; - - - // make the OpenGLView a child of the view controller - [viewController setView:glView]; - - // make the View Controller a child of the main window - [window addSubview: viewController.view]; - - [window makeKeyAndVisible]; - + + // Create a Navigation Controller with the Director + navController_ = [[UINavigationController alloc] initWithRootViewController:director_]; + navController_.navigationBarHidden = YES; + + // set the Navigation Controller as the root view controller + // [window_ setRootViewController:rootViewController_]; + [window_ addSubview:navController_.view]; + + // make main window visible + [window_ makeKeyAndVisible]; + // Default texture format for PNG/BMP/TIFF/JPEG/GIF images // It can be RGBA8888, RGBA4444, RGB5_A1, RGB565 // You can change anytime. [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888]; - [glView setMultipleTouchEnabled:YES]; - - // Removes the startup flicker - [self removeStartupFlicker]; - - // Run the intro Scene - [[CCDirector sharedDirector] runWithScene: [HelloWorld scene]]; + + // When in iPhone RetinaDisplay, iPad, iPad RetinaDisplay mode, CCFileUtils will append the "-hd", "-ipad", "-ipadhd" to all loaded files + // If the -hd, -ipad, -ipadhd files are not found, it will load the non-suffixed version + [CCFileUtils setiPhoneRetinaDisplaySuffix:@"-hd"]; // Default on iPhone RetinaDisplay is "-hd" + [CCFileUtils setiPadSuffix:@"-ipad"]; // Default on iPad is "" (empty string) + [CCFileUtils setiPadRetinaDisplaySuffix:@"-ipadhd"]; // Default on iPad RetinaDisplay is "-ipadhd" + + // Assume that PVR images have premultiplied alpha + [CCTexture2D PVRImagesHavePremultipliedAlpha:YES]; + + // and add the scene to the stack. The director will run it when it automatically when the view is displayed. + [director_ pushScene: [TouchTrailLayer scene]]; + + return YES; +} + +// Supported orientations: Landscape. Customize it for your own needs +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation +{ + return UIInterfaceOrientationIsLandscape(interfaceOrientation); } -- (void)applicationWillResignActive:(UIApplication *)application { - [[CCDirector sharedDirector] pause]; +// getting a call, pause the game +-(void) applicationWillResignActive:(UIApplication *)application +{ + if( [navController_ visibleViewController] == director_ ) + [director_ pause]; } -- (void)applicationDidBecomeActive:(UIApplication *)application { - [[CCDirector sharedDirector] resume]; +// call got rejected +-(void) applicationDidBecomeActive:(UIApplication *)application +{ + if( [navController_ visibleViewController] == director_ ) + [director_ resume]; } -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - [[CCDirector sharedDirector] purgeCachedData]; +-(void) applicationDidEnterBackground:(UIApplication*)application +{ + if( [navController_ visibleViewController] == director_ ) + [director_ stopAnimation]; } --(void) applicationDidEnterBackground:(UIApplication*)application { - [[CCDirector sharedDirector] stopAnimation]; +-(void) applicationWillEnterForeground:(UIApplication*)application +{ + if( [navController_ visibleViewController] == director_ ) + [director_ startAnimation]; } --(void) applicationWillEnterForeground:(UIApplication*)application { - [[CCDirector sharedDirector] startAnimation]; +// application will be killed +- (void)applicationWillTerminate:(UIApplication *)application +{ + CC_DIRECTOR_END(); } -- (void)applicationWillTerminate:(UIApplication *)application { - CCDirector *director = [CCDirector sharedDirector]; - - [[director openGLView] removeFromSuperview]; - - [viewController release]; - - [window release]; - - [director end]; +// purge memory +- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application +{ + [[CCDirector sharedDirector] purgeCachedData]; } -- (void)applicationSignificantTimeChange:(UIApplication *)application { +// next delta time will be zero +-(void) applicationSignificantTimeChange:(UIApplication *)application +{ [[CCDirector sharedDirector] setNextDeltaTimeZero:YES]; } -- (void)dealloc { - [[CCDirector sharedDirector] release]; - [window release]; +- (void) dealloc +{ + [window_ release]; + [navController_ release]; + [super dealloc]; } diff --git a/Example/Classes/HelloWorldLayer.m b/Example/Classes/HelloWorldLayer.m index bf6ac72..6e69819 100644 --- a/Example/Classes/HelloWorldLayer.m +++ b/Example/Classes/HelloWorldLayer.m @@ -11,7 +11,7 @@ #import "HelloWorldLayer.h" // Needed to obtain the Navigation Controller -#import "AppDelegate.h" +#import "ExampleAppDelegate.h" #pragma mark - HelloWorldLayer @@ -69,7 +69,7 @@ -(id) init GKAchievementViewController *achivementViewController = [[GKAchievementViewController alloc] init]; achivementViewController.achievementDelegate = self; - AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; + ExampleAppDelegate *app = (ExampleAppDelegate*) [[UIApplication sharedApplication] delegate]; [[app navController] presentModalViewController:achivementViewController animated:YES]; @@ -84,7 +84,7 @@ -(id) init GKLeaderboardViewController *leaderboardViewController = [[GKLeaderboardViewController alloc] init]; leaderboardViewController.leaderboardDelegate = self; - AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; + ExampleAppDelegate *app = (ExampleAppDelegate*) [[UIApplication sharedApplication] delegate]; [[app navController] presentModalViewController:leaderboardViewController animated:YES]; @@ -119,13 +119,13 @@ - (void) dealloc -(void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController { - AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; + ExampleAppDelegate *app = (ExampleAppDelegate*) [[UIApplication sharedApplication] delegate]; [[app navController] dismissModalViewControllerAnimated:YES]; } -(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController { - AppController *app = (AppController*) [[UIApplication sharedApplication] delegate]; + ExampleAppDelegate *app = (ExampleAppDelegate*) [[UIApplication sharedApplication] delegate]; [[app navController] dismissModalViewControllerAnimated:YES]; } @end diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index ecbd930..f48cde7 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -9,6 +9,223 @@ /* Begin PBXBuildFile section */ 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; 1F3B9A2D0EF2145700286867 /* ExampleAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1F3B9A2B0EF2145700286867 /* ExampleAppDelegate.m */; }; + 473FCB47156A52A3007DD659 /* CCAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA8A156A52A3007DD659 /* CCAction.h */; }; + 473FCB48156A52A3007DD659 /* CCAction.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA8B156A52A3007DD659 /* CCAction.m */; }; + 473FCB49156A52A3007DD659 /* CCActionCamera.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA8C156A52A3007DD659 /* CCActionCamera.h */; }; + 473FCB4A156A52A3007DD659 /* CCActionCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA8D156A52A3007DD659 /* CCActionCamera.m */; }; + 473FCB4B156A52A3007DD659 /* CCActionEase.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA8E156A52A3007DD659 /* CCActionEase.h */; }; + 473FCB4C156A52A3007DD659 /* CCActionEase.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA8F156A52A3007DD659 /* CCActionEase.m */; }; + 473FCB4D156A52A3007DD659 /* CCActionGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA90156A52A3007DD659 /* CCActionGrid.h */; }; + 473FCB4E156A52A3007DD659 /* CCActionGrid.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA91156A52A3007DD659 /* CCActionGrid.m */; }; + 473FCB4F156A52A3007DD659 /* CCActionGrid3D.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA92156A52A3007DD659 /* CCActionGrid3D.h */; }; + 473FCB50156A52A3007DD659 /* CCActionGrid3D.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA93156A52A3007DD659 /* CCActionGrid3D.m */; }; + 473FCB51156A52A3007DD659 /* CCActionInstant.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA94156A52A3007DD659 /* CCActionInstant.h */; }; + 473FCB52156A52A3007DD659 /* CCActionInstant.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA95156A52A3007DD659 /* CCActionInstant.m */; }; + 473FCB53156A52A3007DD659 /* CCActionInterval.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA96156A52A3007DD659 /* CCActionInterval.h */; }; + 473FCB54156A52A3007DD659 /* CCActionInterval.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA97156A52A3007DD659 /* CCActionInterval.m */; }; + 473FCB55156A52A3007DD659 /* CCActionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA98156A52A3007DD659 /* CCActionManager.h */; }; + 473FCB56156A52A3007DD659 /* CCActionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA99156A52A3007DD659 /* CCActionManager.m */; }; + 473FCB57156A52A3007DD659 /* CCActionPageTurn3D.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA9A156A52A3007DD659 /* CCActionPageTurn3D.h */; }; + 473FCB58156A52A3007DD659 /* CCActionPageTurn3D.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA9B156A52A3007DD659 /* CCActionPageTurn3D.m */; }; + 473FCB59156A52A3007DD659 /* CCActionProgressTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA9C156A52A3007DD659 /* CCActionProgressTimer.h */; }; + 473FCB5A156A52A3007DD659 /* CCActionProgressTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA9D156A52A3007DD659 /* CCActionProgressTimer.m */; }; + 473FCB5B156A52A3007DD659 /* CCActionTiledGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA9E156A52A3007DD659 /* CCActionTiledGrid.h */; }; + 473FCB5C156A52A3007DD659 /* CCActionTiledGrid.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA9F156A52A3007DD659 /* CCActionTiledGrid.m */; }; + 473FCB5D156A52A3007DD659 /* CCActionTween.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA0156A52A3007DD659 /* CCActionTween.h */; }; + 473FCB5E156A52A3007DD659 /* CCActionTween.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA1156A52A3007DD659 /* CCActionTween.m */; }; + 473FCB5F156A52A3007DD659 /* CCAnimation.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA2156A52A3007DD659 /* CCAnimation.h */; }; + 473FCB60156A52A3007DD659 /* CCAnimation.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA3156A52A3007DD659 /* CCAnimation.m */; }; + 473FCB61156A52A3007DD659 /* CCAnimationCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA4156A52A3007DD659 /* CCAnimationCache.h */; }; + 473FCB62156A52A3007DD659 /* CCAnimationCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA5156A52A3007DD659 /* CCAnimationCache.m */; }; + 473FCB63156A52A3007DD659 /* CCAtlasNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA6156A52A3007DD659 /* CCAtlasNode.h */; }; + 473FCB64156A52A3007DD659 /* CCAtlasNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA7156A52A3007DD659 /* CCAtlasNode.m */; }; + 473FCB65156A52A3007DD659 /* CCCamera.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA8156A52A3007DD659 /* CCCamera.h */; }; + 473FCB66156A52A3007DD659 /* CCCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA9156A52A3007DD659 /* CCCamera.m */; }; + 473FCB67156A52A3007DD659 /* ccConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAAA156A52A3007DD659 /* ccConfig.h */; }; + 473FCB68156A52A3007DD659 /* CCConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAAB156A52A3007DD659 /* CCConfiguration.h */; }; + 473FCB69156A52A3007DD659 /* CCConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAAC156A52A3007DD659 /* CCConfiguration.m */; }; + 473FCB6A156A52A3007DD659 /* ccDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAAD156A52A3007DD659 /* ccDeprecated.h */; }; + 473FCB6B156A52A3007DD659 /* ccDeprecated.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAAE156A52A3007DD659 /* ccDeprecated.m */; }; + 473FCB6C156A52A3007DD659 /* CCDirector.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAAF156A52A3007DD659 /* CCDirector.h */; }; + 473FCB6D156A52A3007DD659 /* CCDirector.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB0156A52A3007DD659 /* CCDirector.m */; }; + 473FCB6E156A52A3007DD659 /* CCDrawingPrimitives.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB1156A52A3007DD659 /* CCDrawingPrimitives.h */; }; + 473FCB6F156A52A3007DD659 /* CCDrawingPrimitives.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB2156A52A3007DD659 /* CCDrawingPrimitives.m */; }; + 473FCB70156A52A3007DD659 /* CCGLProgram.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB3156A52A3007DD659 /* CCGLProgram.h */; }; + 473FCB71156A52A3007DD659 /* CCGLProgram.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB4156A52A3007DD659 /* CCGLProgram.m */; }; + 473FCB72156A52A3007DD659 /* ccGLStateCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB5156A52A3007DD659 /* ccGLStateCache.h */; }; + 473FCB73156A52A3007DD659 /* ccGLStateCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB6156A52A3007DD659 /* ccGLStateCache.m */; }; + 473FCB74156A52A3007DD659 /* CCGrabber.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB7156A52A3007DD659 /* CCGrabber.h */; }; + 473FCB75156A52A3007DD659 /* CCGrabber.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB8156A52A3007DD659 /* CCGrabber.m */; }; + 473FCB76156A52A3007DD659 /* CCGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB9156A52A3007DD659 /* CCGrid.h */; }; + 473FCB77156A52A3007DD659 /* CCGrid.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCABA156A52A3007DD659 /* CCGrid.m */; }; + 473FCB78156A52A3007DD659 /* CCLabelAtlas.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCABB156A52A3007DD659 /* CCLabelAtlas.h */; }; + 473FCB79156A52A3007DD659 /* CCLabelAtlas.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCABC156A52A3007DD659 /* CCLabelAtlas.m */; }; + 473FCB7A156A52A3007DD659 /* CCLabelBMFont.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCABD156A52A3007DD659 /* CCLabelBMFont.h */; }; + 473FCB7B156A52A3007DD659 /* CCLabelBMFont.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCABE156A52A3007DD659 /* CCLabelBMFont.m */; }; + 473FCB7C156A52A3007DD659 /* CCLabelTTF.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCABF156A52A3007DD659 /* CCLabelTTF.h */; }; + 473FCB7D156A52A3007DD659 /* CCLabelTTF.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC0156A52A3007DD659 /* CCLabelTTF.m */; }; + 473FCB7E156A52A3007DD659 /* CCLayer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC1156A52A3007DD659 /* CCLayer.h */; }; + 473FCB7F156A52A3007DD659 /* CCLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC2156A52A3007DD659 /* CCLayer.m */; }; + 473FCB80156A52A3007DD659 /* ccMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC3156A52A3007DD659 /* ccMacros.h */; }; + 473FCB81156A52A3007DD659 /* CCMenu.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC4156A52A3007DD659 /* CCMenu.h */; }; + 473FCB82156A52A3007DD659 /* CCMenu.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC5156A52A3007DD659 /* CCMenu.m */; }; + 473FCB83156A52A3007DD659 /* CCMenuItem.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC6156A52A3007DD659 /* CCMenuItem.h */; }; + 473FCB84156A52A3007DD659 /* CCMenuItem.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC7156A52A3007DD659 /* CCMenuItem.m */; }; + 473FCB85156A52A3007DD659 /* CCMotionStreak.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC8156A52A3007DD659 /* CCMotionStreak.h */; }; + 473FCB86156A52A3007DD659 /* CCMotionStreak.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC9156A52A3007DD659 /* CCMotionStreak.m */; }; + 473FCB87156A52A3007DD659 /* CCNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCACA156A52A3007DD659 /* CCNode.h */; }; + 473FCB88156A52A3007DD659 /* CCNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCACB156A52A3007DD659 /* CCNode.m */; }; + 473FCB89156A52A3007DD659 /* CCParallaxNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCACC156A52A3007DD659 /* CCParallaxNode.h */; }; + 473FCB8A156A52A3007DD659 /* CCParallaxNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCACD156A52A3007DD659 /* CCParallaxNode.m */; }; + 473FCB8B156A52A3007DD659 /* CCParticleBatchNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCACE156A52A3007DD659 /* CCParticleBatchNode.h */; }; + 473FCB8C156A52A3007DD659 /* CCParticleBatchNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCACF156A52A3007DD659 /* CCParticleBatchNode.m */; }; + 473FCB8D156A52A3007DD659 /* CCParticleExamples.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD0156A52A3007DD659 /* CCParticleExamples.h */; }; + 473FCB8E156A52A3007DD659 /* CCParticleExamples.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAD1156A52A3007DD659 /* CCParticleExamples.m */; }; + 473FCB8F156A52A3007DD659 /* CCParticleSystem.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD2156A52A3007DD659 /* CCParticleSystem.h */; }; + 473FCB90156A52A3007DD659 /* CCParticleSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAD3156A52A3007DD659 /* CCParticleSystem.m */; }; + 473FCB91156A52A3007DD659 /* CCParticleSystemQuad.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD4156A52A3007DD659 /* CCParticleSystemQuad.h */; }; + 473FCB92156A52A3007DD659 /* CCParticleSystemQuad.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAD5156A52A3007DD659 /* CCParticleSystemQuad.m */; }; + 473FCB93156A52A3007DD659 /* CCProgressTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD6156A52A3007DD659 /* CCProgressTimer.h */; }; + 473FCB94156A52A3007DD659 /* CCProgressTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAD7156A52A3007DD659 /* CCProgressTimer.m */; }; + 473FCB95156A52A3007DD659 /* CCProtocols.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD8156A52A3007DD659 /* CCProtocols.h */; }; + 473FCB96156A52A3007DD659 /* CCRenderTexture.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD9156A52A3007DD659 /* CCRenderTexture.h */; }; + 473FCB97156A52A3007DD659 /* CCRenderTexture.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCADA156A52A3007DD659 /* CCRenderTexture.m */; }; + 473FCB98156A52A3007DD659 /* CCScene.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCADB156A52A3007DD659 /* CCScene.h */; }; + 473FCB99156A52A3007DD659 /* CCScene.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCADC156A52A3007DD659 /* CCScene.m */; }; + 473FCB9A156A52A3007DD659 /* CCScheduler.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCADD156A52A3007DD659 /* CCScheduler.h */; }; + 473FCB9B156A52A3007DD659 /* CCScheduler.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCADE156A52A3007DD659 /* CCScheduler.m */; }; + 473FCB9C156A52A3007DD659 /* ccShader_Position_uColor_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCADF156A52A3007DD659 /* ccShader_Position_uColor_frag.h */; }; + 473FCB9D156A52A3007DD659 /* ccShader_Position_uColor_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE0156A52A3007DD659 /* ccShader_Position_uColor_vert.h */; }; + 473FCB9E156A52A3007DD659 /* ccShader_PositionColor_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE1156A52A3007DD659 /* ccShader_PositionColor_frag.h */; }; + 473FCB9F156A52A3007DD659 /* ccShader_PositionColor_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE2156A52A3007DD659 /* ccShader_PositionColor_vert.h */; }; + 473FCBA0156A52A3007DD659 /* ccShader_PositionTexture_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE3156A52A3007DD659 /* ccShader_PositionTexture_frag.h */; }; + 473FCBA1156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE4156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h */; }; + 473FCBA2156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE5156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h */; }; + 473FCBA3156A52A3007DD659 /* ccShader_PositionTexture_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE6156A52A3007DD659 /* ccShader_PositionTexture_vert.h */; }; + 473FCBA4156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE7156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h */; }; + 473FCBA5156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE8156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h */; }; + 473FCBA6156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE9156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h */; }; + 473FCBA7156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAEA156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h */; }; + 473FCBA8156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAEB156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h */; }; + 473FCBA9156A52A3007DD659 /* CCShaderCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAEC156A52A3007DD659 /* CCShaderCache.h */; }; + 473FCBAA156A52A3007DD659 /* CCShaderCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAED156A52A3007DD659 /* CCShaderCache.m */; }; + 473FCBAB156A52A3007DD659 /* ccShaders.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAEE156A52A3007DD659 /* ccShaders.h */; }; + 473FCBAC156A52A3007DD659 /* ccShaders.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAEF156A52A3007DD659 /* ccShaders.m */; }; + 473FCBAD156A52A3007DD659 /* CCSprite.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF0156A52A3007DD659 /* CCSprite.h */; }; + 473FCBAE156A52A3007DD659 /* CCSprite.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF1156A52A3007DD659 /* CCSprite.m */; }; + 473FCBAF156A52A3007DD659 /* CCSpriteBatchNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF2156A52A3007DD659 /* CCSpriteBatchNode.h */; }; + 473FCBB0156A52A3007DD659 /* CCSpriteBatchNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF3156A52A3007DD659 /* CCSpriteBatchNode.m */; }; + 473FCBB1156A52A3007DD659 /* CCSpriteFrame.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF4156A52A3007DD659 /* CCSpriteFrame.h */; }; + 473FCBB2156A52A3007DD659 /* CCSpriteFrame.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF5156A52A3007DD659 /* CCSpriteFrame.m */; }; + 473FCBB3156A52A3007DD659 /* CCSpriteFrameCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF6156A52A3007DD659 /* CCSpriteFrameCache.h */; }; + 473FCBB4156A52A3007DD659 /* CCSpriteFrameCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF7156A52A3007DD659 /* CCSpriteFrameCache.m */; }; + 473FCBB5156A52A3007DD659 /* CCTexture2D.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF8156A52A3007DD659 /* CCTexture2D.h */; }; + 473FCBB6156A52A3007DD659 /* CCTexture2D.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF9156A52A3007DD659 /* CCTexture2D.m */; }; + 473FCBB7156A52A3007DD659 /* CCTextureAtlas.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAFA156A52A3007DD659 /* CCTextureAtlas.h */; }; + 473FCBB8156A52A3007DD659 /* CCTextureAtlas.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAFB156A52A3007DD659 /* CCTextureAtlas.m */; }; + 473FCBB9156A52A3007DD659 /* CCTextureCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAFC156A52A3007DD659 /* CCTextureCache.h */; }; + 473FCBBA156A52A3007DD659 /* CCTextureCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAFD156A52A3007DD659 /* CCTextureCache.m */; }; + 473FCBBB156A52A3007DD659 /* CCTexturePVR.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAFE156A52A3007DD659 /* CCTexturePVR.h */; }; + 473FCBBC156A52A3007DD659 /* CCTexturePVR.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAFF156A52A3007DD659 /* CCTexturePVR.m */; }; + 473FCBBD156A52A3007DD659 /* CCTileMapAtlas.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB00156A52A3007DD659 /* CCTileMapAtlas.h */; }; + 473FCBBE156A52A3007DD659 /* CCTileMapAtlas.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB01156A52A3007DD659 /* CCTileMapAtlas.m */; }; + 473FCBBF156A52A3007DD659 /* CCTMXLayer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB02156A52A3007DD659 /* CCTMXLayer.h */; }; + 473FCBC0156A52A3007DD659 /* CCTMXLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB03156A52A3007DD659 /* CCTMXLayer.m */; }; + 473FCBC1156A52A3007DD659 /* CCTMXObjectGroup.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB04156A52A3007DD659 /* CCTMXObjectGroup.h */; }; + 473FCBC2156A52A3007DD659 /* CCTMXObjectGroup.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB05156A52A3007DD659 /* CCTMXObjectGroup.m */; }; + 473FCBC3156A52A3007DD659 /* CCTMXTiledMap.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB06156A52A3007DD659 /* CCTMXTiledMap.h */; }; + 473FCBC4156A52A3007DD659 /* CCTMXTiledMap.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB07156A52A3007DD659 /* CCTMXTiledMap.m */; }; + 473FCBC5156A52A3007DD659 /* CCTMXXMLParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB08156A52A3007DD659 /* CCTMXXMLParser.h */; }; + 473FCBC6156A52A3007DD659 /* CCTMXXMLParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB09156A52A3007DD659 /* CCTMXXMLParser.m */; }; + 473FCBC7156A52A3007DD659 /* CCTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB0A156A52A3007DD659 /* CCTransition.h */; }; + 473FCBC8156A52A3007DD659 /* CCTransition.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB0B156A52A3007DD659 /* CCTransition.m */; }; + 473FCBC9156A52A3007DD659 /* CCTransitionPageTurn.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB0C156A52A3007DD659 /* CCTransitionPageTurn.h */; }; + 473FCBCA156A52A3007DD659 /* CCTransitionPageTurn.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB0D156A52A3007DD659 /* CCTransitionPageTurn.m */; }; + 473FCBCB156A52A3007DD659 /* CCTransitionProgress.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB0E156A52A3007DD659 /* CCTransitionProgress.h */; }; + 473FCBCC156A52A3007DD659 /* CCTransitionProgress.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB0F156A52A3007DD659 /* CCTransitionProgress.m */; }; + 473FCBCD156A52A3007DD659 /* ccTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB10156A52A3007DD659 /* ccTypes.h */; }; + 473FCBCE156A52A3007DD659 /* cocos2d.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB11156A52A3007DD659 /* cocos2d.h */; }; + 473FCBCF156A52A3007DD659 /* cocos2d.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB12156A52A3007DD659 /* cocos2d.m */; }; + 473FCBD0156A52A3007DD659 /* CCGL.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB14156A52A3007DD659 /* CCGL.h */; }; + 473FCBD1156A52A3007DD659 /* CCNS.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB15156A52A3007DD659 /* CCNS.h */; }; + 473FCBD2156A52A3007DD659 /* CCDirectorIOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB17156A52A3007DD659 /* CCDirectorIOS.h */; }; + 473FCBD3156A52A3007DD659 /* CCDirectorIOS.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB18156A52A3007DD659 /* CCDirectorIOS.m */; }; + 473FCBD4156A52A3007DD659 /* CCES2Renderer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB19156A52A3007DD659 /* CCES2Renderer.h */; }; + 473FCBD5156A52A3007DD659 /* CCES2Renderer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB1A156A52A3007DD659 /* CCES2Renderer.m */; }; + 473FCBD6156A52A3007DD659 /* CCESRenderer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB1B156A52A3007DD659 /* CCESRenderer.h */; }; + 473FCBD7156A52A3007DD659 /* CCGLView.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB1C156A52A3007DD659 /* CCGLView.h */; }; + 473FCBD8156A52A3007DD659 /* CCGLView.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB1D156A52A3007DD659 /* CCGLView.m */; }; + 473FCBD9156A52A3007DD659 /* CCTouchDelegateProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB1E156A52A3007DD659 /* CCTouchDelegateProtocol.h */; }; + 473FCBDA156A52A3007DD659 /* CCTouchDispatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB1F156A52A3007DD659 /* CCTouchDispatcher.h */; }; + 473FCBDB156A52A3007DD659 /* CCTouchDispatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB20156A52A3007DD659 /* CCTouchDispatcher.m */; }; + 473FCBDC156A52A3007DD659 /* CCTouchHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB21156A52A3007DD659 /* CCTouchHandler.h */; }; + 473FCBDD156A52A3007DD659 /* CCTouchHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB22156A52A3007DD659 /* CCTouchHandler.m */; }; + 473FCBDE156A52A3007DD659 /* CCDirectorMac.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB24156A52A3007DD659 /* CCDirectorMac.h */; }; + 473FCBDF156A52A3007DD659 /* CCDirectorMac.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB25156A52A3007DD659 /* CCDirectorMac.m */; }; + 473FCBE0156A52A3007DD659 /* CCEventDispatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB26156A52A3007DD659 /* CCEventDispatcher.h */; }; + 473FCBE1156A52A3007DD659 /* CCEventDispatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB27156A52A3007DD659 /* CCEventDispatcher.m */; }; + 473FCBE2156A52A3007DD659 /* CCGLView.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB28156A52A3007DD659 /* CCGLView.h */; }; + 473FCBE3156A52A3007DD659 /* CCGLView.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB29156A52A3007DD659 /* CCGLView.m */; }; + 473FCBE4156A52A3007DD659 /* CCWindow.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB2A156A52A3007DD659 /* CCWindow.h */; }; + 473FCBE5156A52A3007DD659 /* CCWindow.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB2B156A52A3007DD659 /* CCWindow.m */; }; + 473FCBE6156A52A3007DD659 /* base64.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB2D156A52A3007DD659 /* base64.c */; }; + 473FCBE7156A52A3007DD659 /* base64.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB2E156A52A3007DD659 /* base64.h */; }; + 473FCBE8156A52A3007DD659 /* CCArray.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB2F156A52A3007DD659 /* CCArray.h */; }; + 473FCBE9156A52A3007DD659 /* CCArray.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB30156A52A3007DD659 /* CCArray.m */; }; + 473FCBEA156A52A3007DD659 /* ccCArray.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB31156A52A3007DD659 /* ccCArray.h */; }; + 473FCBEB156A52A3007DD659 /* CCFileUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB32156A52A3007DD659 /* CCFileUtils.h */; }; + 473FCBEC156A52A3007DD659 /* CCFileUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB33156A52A3007DD659 /* CCFileUtils.m */; }; + 473FCBED156A52A3007DD659 /* CCProfiling.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB34156A52A3007DD659 /* CCProfiling.h */; }; + 473FCBEE156A52A3007DD659 /* CCProfiling.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB35156A52A3007DD659 /* CCProfiling.m */; }; + 473FCBEF156A52A3007DD659 /* ccUtils.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB36156A52A3007DD659 /* ccUtils.c */; }; + 473FCBF0156A52A3007DD659 /* ccUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB37156A52A3007DD659 /* ccUtils.h */; }; + 473FCBF1156A52A3007DD659 /* CCVertex.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB38156A52A3007DD659 /* CCVertex.h */; }; + 473FCBF2156A52A3007DD659 /* CCVertex.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB39156A52A3007DD659 /* CCVertex.m */; }; + 473FCBF3156A52A3007DD659 /* CGPointExtension.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB3A156A52A3007DD659 /* CGPointExtension.h */; }; + 473FCBF4156A52A3007DD659 /* CGPointExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB3B156A52A3007DD659 /* CGPointExtension.m */; }; + 473FCBF5156A52A3007DD659 /* NSThread+performBlock.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB3C156A52A3007DD659 /* NSThread+performBlock.h */; }; + 473FCBF6156A52A3007DD659 /* NSThread+performBlock.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB3D156A52A3007DD659 /* NSThread+performBlock.m */; }; + 473FCBF7156A52A3007DD659 /* OpenGL_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB3E156A52A3007DD659 /* OpenGL_Internal.h */; }; + 473FCBF8156A52A3007DD659 /* TGAlib.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB3F156A52A3007DD659 /* TGAlib.h */; }; + 473FCBF9156A52A3007DD659 /* TGAlib.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB40156A52A3007DD659 /* TGAlib.m */; }; + 473FCBFA156A52A3007DD659 /* TransformUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB41156A52A3007DD659 /* TransformUtils.h */; }; + 473FCBFB156A52A3007DD659 /* TransformUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB42156A52A3007DD659 /* TransformUtils.m */; }; + 473FCBFC156A52A3007DD659 /* uthash.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB43156A52A3007DD659 /* uthash.h */; }; + 473FCBFD156A52A3007DD659 /* utlist.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB44156A52A3007DD659 /* utlist.h */; }; + 473FCBFE156A52A3007DD659 /* ZipUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB45156A52A3007DD659 /* ZipUtils.h */; }; + 473FCBFF156A52A3007DD659 /* ZipUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB46156A52A3007DD659 /* ZipUtils.m */; }; + 473FCC23156A52FF007DD659 /* aabb.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC03156A52FF007DD659 /* aabb.h */; }; + 473FCC24156A52FF007DD659 /* mat4stack.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC05156A52FF007DD659 /* mat4stack.h */; }; + 473FCC25156A52FF007DD659 /* matrix.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC06156A52FF007DD659 /* matrix.h */; }; + 473FCC26156A52FF007DD659 /* kazmath.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC07156A52FF007DD659 /* kazmath.h */; }; + 473FCC27156A52FF007DD659 /* mat3.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC08156A52FF007DD659 /* mat3.h */; }; + 473FCC28156A52FF007DD659 /* mat4.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC09156A52FF007DD659 /* mat4.h */; }; + 473FCC29156A52FF007DD659 /* neon_matrix_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0A156A52FF007DD659 /* neon_matrix_impl.h */; }; + 473FCC2A156A52FF007DD659 /* plane.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0B156A52FF007DD659 /* plane.h */; }; + 473FCC2B156A52FF007DD659 /* quaternion.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0C156A52FF007DD659 /* quaternion.h */; }; + 473FCC2C156A52FF007DD659 /* ray2.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0D156A52FF007DD659 /* ray2.h */; }; + 473FCC2D156A52FF007DD659 /* utility.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0E156A52FF007DD659 /* utility.h */; }; + 473FCC2E156A52FF007DD659 /* vec2.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0F156A52FF007DD659 /* vec2.h */; }; + 473FCC2F156A52FF007DD659 /* vec3.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC10156A52FF007DD659 /* vec3.h */; }; + 473FCC30156A52FF007DD659 /* vec4.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC11156A52FF007DD659 /* vec4.h */; }; + 473FCC31156A52FF007DD659 /* aabb.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC13156A52FF007DD659 /* aabb.c */; }; + 473FCC32156A52FF007DD659 /* mat4stack.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC17156A52FF007DD659 /* mat4stack.c */; }; + 473FCC33156A52FF007DD659 /* matrix.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC18156A52FF007DD659 /* matrix.c */; }; + 473FCC34156A52FF007DD659 /* mat3.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC19156A52FF007DD659 /* mat3.c */; }; + 473FCC35156A52FF007DD659 /* mat4.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1A156A52FF007DD659 /* mat4.c */; }; + 473FCC36156A52FF007DD659 /* neon_matrix_impl.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1B156A52FF007DD659 /* neon_matrix_impl.c */; }; + 473FCC37156A52FF007DD659 /* plane.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1C156A52FF007DD659 /* plane.c */; }; + 473FCC38156A52FF007DD659 /* quaternion.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1D156A52FF007DD659 /* quaternion.c */; }; + 473FCC39156A52FF007DD659 /* ray2.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1E156A52FF007DD659 /* ray2.c */; }; + 473FCC3A156A52FF007DD659 /* utility.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1F156A52FF007DD659 /* utility.c */; }; + 473FCC3B156A52FF007DD659 /* vec2.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC20156A52FF007DD659 /* vec2.c */; }; + 473FCC3C156A52FF007DD659 /* vec3.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC21156A52FF007DD659 /* vec3.c */; }; + 473FCC3D156A52FF007DD659 /* vec4.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC22156A52FF007DD659 /* vec4.c */; }; + 473FCC44156A6B03007DD659 /* HelloWorldLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC43156A6B03007DD659 /* HelloWorldLayer.m */; }; + 473FCC46156A6BCE007DD659 /* GameKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 473FCC45156A6BCE007DD659 /* GameKit.framework */; }; + 473FCC4C156A6DC4007DD659 /* fps_images.png in Resources */ = {isa = PBXBuildFile; fileRef = 473FCC49156A6DC4007DD659 /* fps_images.png */; }; + 473FCC4D156A6DC4007DD659 /* fps_images-hd.png in Resources */ = {isa = PBXBuildFile; fileRef = 473FCC4A156A6DC4007DD659 /* fps_images-hd.png */; }; + 473FCC4E156A6DC4007DD659 /* fps_images-ipadhd.png in Resources */ = {isa = PBXBuildFile; fileRef = 473FCC4B156A6DC4007DD659 /* fps_images-ipadhd.png */; }; 47B71D60137130530008113A /* CCBlade.m in Sources */ = {isa = PBXBuildFile; fileRef = 47B71D5D137130530008113A /* CCBlade.m */; }; 47B71D61137130530008113A /* TouchTrailLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 47B71D5F137130530008113A /* TouchTrailLayer.m */; }; 47B71D65137130680008113A /* streak1.png in Resources */ = {isa = PBXBuildFile; fileRef = 47B71D62137130680008113A /* streak1.png */; }; @@ -36,7 +253,6 @@ 50674855107A3AF30090963A /* ZAttributedStringPrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 50674852107A3AF30090963A /* ZAttributedStringPrivate.h */; }; 506EDB88102F4C4000A389B3 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EDB87102F4C4000A389B3 /* libz.dylib */; }; 506EDBA5102F4C9F00A389B3 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */; }; - 506EDC31102F528A00A389B3 /* HelloWorldScene.m in Sources */ = {isa = PBXBuildFile; fileRef = 506EDC30102F528A00A389B3 /* HelloWorldScene.m */; }; 506EE1A91030508200A389B3 /* libcocos2d libraries.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EE05E10304ED200A389B3 /* libcocos2d libraries.a */; }; 507ED63C11C638C6002ED3FC /* CDAudioManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 507ED63311C638C6002ED3FC /* CDAudioManager.h */; }; 507ED63D11C638C6002ED3FC /* CDAudioManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 507ED63411C638C6002ED3FC /* CDAudioManager.m */; }; @@ -72,7 +288,6 @@ 50F41342106926B2002A0D5E /* CJSONSerializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F41322106926B2002A0D5E /* CJSONSerializer.h */; }; 50F41343106926B2002A0D5E /* CJSONSerializer.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F41323106926B2002A0D5E /* CJSONSerializer.m */; }; 50F414F01069373D002A0D5E /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 50F414EC1069373D002A0D5E /* Default.png */; }; - 50F414F11069373D002A0D5E /* fps_images.png in Resources */ = {isa = PBXBuildFile; fileRef = 50F414ED1069373D002A0D5E /* fps_images.png */; }; 50F414F21069373D002A0D5E /* Icon.png in Resources */ = {isa = PBXBuildFile; fileRef = 50F414EE1069373D002A0D5E /* Icon.png */; }; DC6640030F83B3EA000B3E49 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */; }; DC6640050F83B3EA000B3E49 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC6640040F83B3EA000B3E49 /* OpenAL.framework */; }; @@ -87,173 +302,6 @@ E02BB507126CA50F006E46A2 /* Icon-Small-50.png in Resources */ = {isa = PBXBuildFile; fileRef = E02BB501126CA50F006E46A2 /* Icon-Small-50.png */; }; E02BB508126CA50F006E46A2 /* Icon-72.png in Resources */ = {isa = PBXBuildFile; fileRef = E02BB502126CA50F006E46A2 /* Icon-72.png */; }; E02BB763126CC1E0006E46A2 /* iTunesArtwork in Resources */ = {isa = PBXBuildFile; fileRef = E02BB762126CC1E0006E46A2 /* iTunesArtwork */; }; - E02BB80F126CC224006E46A2 /* CCAction.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB765126CC223006E46A2 /* CCAction.h */; }; - E02BB810126CC224006E46A2 /* CCAction.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB766126CC223006E46A2 /* CCAction.m */; }; - E02BB811126CC224006E46A2 /* CCActionCamera.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB767126CC223006E46A2 /* CCActionCamera.h */; }; - E02BB812126CC224006E46A2 /* CCActionCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB768126CC223006E46A2 /* CCActionCamera.m */; }; - E02BB813126CC224006E46A2 /* CCActionEase.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB769126CC223006E46A2 /* CCActionEase.h */; }; - E02BB814126CC224006E46A2 /* CCActionEase.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB76A126CC223006E46A2 /* CCActionEase.m */; }; - E02BB815126CC224006E46A2 /* CCActionGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB76B126CC223006E46A2 /* CCActionGrid.h */; }; - E02BB816126CC224006E46A2 /* CCActionGrid.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB76C126CC223006E46A2 /* CCActionGrid.m */; }; - E02BB817126CC224006E46A2 /* CCActionGrid3D.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB76D126CC223006E46A2 /* CCActionGrid3D.h */; }; - E02BB818126CC224006E46A2 /* CCActionGrid3D.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB76E126CC223006E46A2 /* CCActionGrid3D.m */; }; - E02BB819126CC224006E46A2 /* CCActionInstant.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB76F126CC223006E46A2 /* CCActionInstant.h */; }; - E02BB81A126CC224006E46A2 /* CCActionInstant.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB770126CC223006E46A2 /* CCActionInstant.m */; }; - E02BB81B126CC224006E46A2 /* CCActionInterval.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB771126CC223006E46A2 /* CCActionInterval.h */; }; - E02BB81C126CC224006E46A2 /* CCActionInterval.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB772126CC223006E46A2 /* CCActionInterval.m */; }; - E02BB81D126CC224006E46A2 /* CCActionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB773126CC223006E46A2 /* CCActionManager.h */; }; - E02BB81E126CC224006E46A2 /* CCActionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB774126CC223006E46A2 /* CCActionManager.m */; }; - E02BB81F126CC224006E46A2 /* CCActionPageTurn3D.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB775126CC223006E46A2 /* CCActionPageTurn3D.h */; }; - E02BB820126CC224006E46A2 /* CCActionPageTurn3D.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB776126CC223006E46A2 /* CCActionPageTurn3D.m */; }; - E02BB821126CC224006E46A2 /* CCActionProgressTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB777126CC223006E46A2 /* CCActionProgressTimer.h */; }; - E02BB822126CC224006E46A2 /* CCActionProgressTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB778126CC223006E46A2 /* CCActionProgressTimer.m */; }; - E02BB823126CC224006E46A2 /* CCActionTiledGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB779126CC223006E46A2 /* CCActionTiledGrid.h */; }; - E02BB824126CC224006E46A2 /* CCActionTiledGrid.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB77A126CC223006E46A2 /* CCActionTiledGrid.m */; }; - E02BB825126CC224006E46A2 /* CCActionTween.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB77B126CC223006E46A2 /* CCActionTween.h */; }; - E02BB826126CC224006E46A2 /* CCActionTween.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB77C126CC223006E46A2 /* CCActionTween.m */; }; - E02BB827126CC224006E46A2 /* CCAnimation.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB77D126CC223006E46A2 /* CCAnimation.h */; }; - E02BB828126CC224006E46A2 /* CCAnimation.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB77E126CC223006E46A2 /* CCAnimation.m */; }; - E02BB829126CC224006E46A2 /* CCAnimationCache.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB77F126CC223006E46A2 /* CCAnimationCache.h */; }; - E02BB82A126CC224006E46A2 /* CCAnimationCache.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB780126CC223006E46A2 /* CCAnimationCache.m */; }; - E02BB82B126CC224006E46A2 /* CCAtlasNode.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB781126CC223006E46A2 /* CCAtlasNode.h */; }; - E02BB82C126CC224006E46A2 /* CCAtlasNode.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB782126CC223006E46A2 /* CCAtlasNode.m */; }; - E02BB82D126CC224006E46A2 /* CCBlockSupport.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB783126CC223006E46A2 /* CCBlockSupport.h */; }; - E02BB82E126CC224006E46A2 /* CCBlockSupport.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB784126CC223006E46A2 /* CCBlockSupport.m */; }; - E02BB82F126CC224006E46A2 /* CCCamera.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB785126CC223006E46A2 /* CCCamera.h */; }; - E02BB830126CC224006E46A2 /* CCCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB786126CC223006E46A2 /* CCCamera.m */; }; - E02BB831126CC224006E46A2 /* CCCompatibility.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB787126CC223006E46A2 /* CCCompatibility.h */; }; - E02BB832126CC224006E46A2 /* CCCompatibility.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB788126CC223006E46A2 /* CCCompatibility.m */; }; - E02BB833126CC224006E46A2 /* ccConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB789126CC223006E46A2 /* ccConfig.h */; }; - E02BB834126CC224006E46A2 /* CCConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB78A126CC223006E46A2 /* CCConfiguration.h */; }; - E02BB835126CC224006E46A2 /* CCConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB78B126CC223006E46A2 /* CCConfiguration.m */; }; - E02BB836126CC224006E46A2 /* CCDirector.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB78C126CC223006E46A2 /* CCDirector.h */; }; - E02BB837126CC224006E46A2 /* CCDirector.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB78D126CC223006E46A2 /* CCDirector.m */; }; - E02BB838126CC224006E46A2 /* CCDrawingPrimitives.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB78E126CC223006E46A2 /* CCDrawingPrimitives.h */; }; - E02BB839126CC224006E46A2 /* CCDrawingPrimitives.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB78F126CC223006E46A2 /* CCDrawingPrimitives.m */; }; - E02BB83A126CC224006E46A2 /* CCGrabber.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB790126CC223006E46A2 /* CCGrabber.h */; }; - E02BB83B126CC224006E46A2 /* CCGrabber.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB791126CC223006E46A2 /* CCGrabber.m */; }; - E02BB83C126CC224006E46A2 /* CCGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB792126CC223006E46A2 /* CCGrid.h */; }; - E02BB83D126CC224006E46A2 /* CCGrid.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB793126CC223006E46A2 /* CCGrid.m */; }; - E02BB83E126CC224006E46A2 /* CCLabelAtlas.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB794126CC223006E46A2 /* CCLabelAtlas.h */; }; - E02BB83F126CC224006E46A2 /* CCLabelAtlas.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB795126CC223006E46A2 /* CCLabelAtlas.m */; }; - E02BB840126CC224006E46A2 /* CCLabelBMFont.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB796126CC223006E46A2 /* CCLabelBMFont.h */; }; - E02BB841126CC224006E46A2 /* CCLabelBMFont.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB797126CC223006E46A2 /* CCLabelBMFont.m */; }; - E02BB842126CC224006E46A2 /* CCLabelTTF.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB798126CC223006E46A2 /* CCLabelTTF.h */; }; - E02BB843126CC224006E46A2 /* CCLabelTTF.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB799126CC223006E46A2 /* CCLabelTTF.m */; }; - E02BB844126CC224006E46A2 /* CCLayer.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB79A126CC223006E46A2 /* CCLayer.h */; }; - E02BB845126CC224006E46A2 /* CCLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB79B126CC223006E46A2 /* CCLayer.m */; }; - E02BB846126CC224006E46A2 /* ccMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB79C126CC223006E46A2 /* ccMacros.h */; }; - E02BB847126CC224006E46A2 /* CCMenu.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB79D126CC223006E46A2 /* CCMenu.h */; }; - E02BB848126CC224006E46A2 /* CCMenu.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB79E126CC223006E46A2 /* CCMenu.m */; }; - E02BB849126CC224006E46A2 /* CCMenuItem.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB79F126CC224006E46A2 /* CCMenuItem.h */; }; - E02BB84A126CC224006E46A2 /* CCMenuItem.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7A0126CC224006E46A2 /* CCMenuItem.m */; }; - E02BB84B126CC224006E46A2 /* CCMotionStreak.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7A1126CC224006E46A2 /* CCMotionStreak.h */; }; - E02BB84C126CC224006E46A2 /* CCMotionStreak.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7A2126CC224006E46A2 /* CCMotionStreak.m */; }; - E02BB84D126CC224006E46A2 /* CCNode.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7A3126CC224006E46A2 /* CCNode.h */; }; - E02BB84E126CC224006E46A2 /* CCNode.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7A4126CC224006E46A2 /* CCNode.m */; }; - E02BB84F126CC224006E46A2 /* CCParallaxNode.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7A5126CC224006E46A2 /* CCParallaxNode.h */; }; - E02BB850126CC224006E46A2 /* CCParallaxNode.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7A6126CC224006E46A2 /* CCParallaxNode.m */; }; - E02BB851126CC224006E46A2 /* CCParticleExamples.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7A7126CC224006E46A2 /* CCParticleExamples.h */; }; - E02BB852126CC224006E46A2 /* CCParticleExamples.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7A8126CC224006E46A2 /* CCParticleExamples.m */; }; - E02BB853126CC224006E46A2 /* CCParticleSystem.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7A9126CC224006E46A2 /* CCParticleSystem.h */; }; - E02BB854126CC224006E46A2 /* CCParticleSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7AA126CC224006E46A2 /* CCParticleSystem.m */; }; - E02BB855126CC224006E46A2 /* CCParticleSystemPoint.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7AB126CC224006E46A2 /* CCParticleSystemPoint.h */; }; - E02BB856126CC224006E46A2 /* CCParticleSystemPoint.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7AC126CC224006E46A2 /* CCParticleSystemPoint.m */; }; - E02BB857126CC224006E46A2 /* CCParticleSystemQuad.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7AD126CC224006E46A2 /* CCParticleSystemQuad.h */; }; - E02BB858126CC224006E46A2 /* CCParticleSystemQuad.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7AE126CC224006E46A2 /* CCParticleSystemQuad.m */; }; - E02BB859126CC224006E46A2 /* CCProgressTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7AF126CC224006E46A2 /* CCProgressTimer.h */; }; - E02BB85A126CC224006E46A2 /* CCProgressTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7B0126CC224006E46A2 /* CCProgressTimer.m */; }; - E02BB85B126CC224006E46A2 /* CCProtocols.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7B1126CC224006E46A2 /* CCProtocols.h */; }; - E02BB85C126CC224006E46A2 /* CCRenderTexture.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7B2126CC224006E46A2 /* CCRenderTexture.h */; }; - E02BB85D126CC224006E46A2 /* CCRenderTexture.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7B3126CC224006E46A2 /* CCRenderTexture.m */; }; - E02BB85E126CC224006E46A2 /* CCRibbon.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7B4126CC224006E46A2 /* CCRibbon.h */; }; - E02BB85F126CC224006E46A2 /* CCRibbon.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7B5126CC224006E46A2 /* CCRibbon.m */; }; - E02BB860126CC224006E46A2 /* CCScene.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7B6126CC224006E46A2 /* CCScene.h */; }; - E02BB861126CC224006E46A2 /* CCScene.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7B7126CC224006E46A2 /* CCScene.m */; }; - E02BB862126CC224006E46A2 /* CCScheduler.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7B8126CC224006E46A2 /* CCScheduler.h */; }; - E02BB863126CC224006E46A2 /* CCScheduler.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7B9126CC224006E46A2 /* CCScheduler.m */; }; - E02BB864126CC224006E46A2 /* CCSprite.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7BA126CC224006E46A2 /* CCSprite.h */; }; - E02BB865126CC224006E46A2 /* CCSprite.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7BB126CC224006E46A2 /* CCSprite.m */; }; - E02BB866126CC224006E46A2 /* CCSpriteBatchNode.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7BC126CC224006E46A2 /* CCSpriteBatchNode.h */; }; - E02BB867126CC224006E46A2 /* CCSpriteBatchNode.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7BD126CC224006E46A2 /* CCSpriteBatchNode.m */; }; - E02BB868126CC224006E46A2 /* CCSpriteFrame.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7BE126CC224006E46A2 /* CCSpriteFrame.h */; }; - E02BB869126CC224006E46A2 /* CCSpriteFrame.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7BF126CC224006E46A2 /* CCSpriteFrame.m */; }; - E02BB86A126CC224006E46A2 /* CCSpriteFrameCache.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7C0126CC224006E46A2 /* CCSpriteFrameCache.h */; }; - E02BB86B126CC224006E46A2 /* CCSpriteFrameCache.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7C1126CC224006E46A2 /* CCSpriteFrameCache.m */; }; - E02BB86C126CC224006E46A2 /* CCSpriteSheet.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7C2126CC224006E46A2 /* CCSpriteSheet.h */; }; - E02BB86D126CC224006E46A2 /* CCSpriteSheet.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7C3126CC224006E46A2 /* CCSpriteSheet.m */; }; - E02BB86E126CC224006E46A2 /* CCTexture2D.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7C4126CC224006E46A2 /* CCTexture2D.h */; }; - E02BB86F126CC224006E46A2 /* CCTexture2D.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7C5126CC224006E46A2 /* CCTexture2D.m */; }; - E02BB870126CC224006E46A2 /* CCTextureAtlas.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7C6126CC224006E46A2 /* CCTextureAtlas.h */; }; - E02BB871126CC224006E46A2 /* CCTextureAtlas.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7C7126CC224006E46A2 /* CCTextureAtlas.m */; }; - E02BB872126CC224006E46A2 /* CCTextureCache.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7C8126CC224006E46A2 /* CCTextureCache.h */; }; - E02BB873126CC224006E46A2 /* CCTextureCache.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7C9126CC224006E46A2 /* CCTextureCache.m */; }; - E02BB874126CC224006E46A2 /* CCTexturePVR.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7CA126CC224006E46A2 /* CCTexturePVR.h */; }; - E02BB875126CC224006E46A2 /* CCTexturePVR.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7CB126CC224006E46A2 /* CCTexturePVR.m */; }; - E02BB876126CC224006E46A2 /* CCTileMapAtlas.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7CC126CC224006E46A2 /* CCTileMapAtlas.h */; }; - E02BB877126CC224006E46A2 /* CCTileMapAtlas.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7CD126CC224006E46A2 /* CCTileMapAtlas.m */; }; - E02BB878126CC224006E46A2 /* CCTMXLayer.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7CE126CC224006E46A2 /* CCTMXLayer.h */; }; - E02BB879126CC224006E46A2 /* CCTMXLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7CF126CC224006E46A2 /* CCTMXLayer.m */; }; - E02BB87A126CC224006E46A2 /* CCTMXObjectGroup.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7D0126CC224006E46A2 /* CCTMXObjectGroup.h */; }; - E02BB87B126CC224006E46A2 /* CCTMXObjectGroup.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7D1126CC224006E46A2 /* CCTMXObjectGroup.m */; }; - E02BB87C126CC224006E46A2 /* CCTMXTiledMap.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7D2126CC224006E46A2 /* CCTMXTiledMap.h */; }; - E02BB87D126CC224006E46A2 /* CCTMXTiledMap.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7D3126CC224006E46A2 /* CCTMXTiledMap.m */; }; - E02BB87E126CC224006E46A2 /* CCTMXXMLParser.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7D4126CC224006E46A2 /* CCTMXXMLParser.h */; }; - E02BB87F126CC224006E46A2 /* CCTMXXMLParser.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7D5126CC224006E46A2 /* CCTMXXMLParser.m */; }; - E02BB880126CC224006E46A2 /* CCTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7D6126CC224006E46A2 /* CCTransition.h */; }; - E02BB881126CC224006E46A2 /* CCTransition.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7D7126CC224006E46A2 /* CCTransition.m */; }; - E02BB882126CC224006E46A2 /* CCTransitionPageTurn.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7D8126CC224006E46A2 /* CCTransitionPageTurn.h */; }; - E02BB883126CC224006E46A2 /* CCTransitionPageTurn.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7D9126CC224006E46A2 /* CCTransitionPageTurn.m */; }; - E02BB884126CC224006E46A2 /* CCTransitionRadial.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7DA126CC224006E46A2 /* CCTransitionRadial.h */; }; - E02BB885126CC224006E46A2 /* CCTransitionRadial.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7DB126CC224006E46A2 /* CCTransitionRadial.m */; }; - E02BB886126CC224006E46A2 /* ccTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7DC126CC224006E46A2 /* ccTypes.h */; }; - E02BB887126CC224006E46A2 /* cocos2d.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7DD126CC224006E46A2 /* cocos2d.h */; }; - E02BB888126CC224006E46A2 /* cocos2d.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7DE126CC224006E46A2 /* cocos2d.m */; }; - E02BB889126CC224006E46A2 /* CCGL.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7E0126CC224006E46A2 /* CCGL.h */; }; - E02BB88A126CC224006E46A2 /* CCNS.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7E1126CC224006E46A2 /* CCNS.h */; }; - E02BB88B126CC224006E46A2 /* CCDirectorIOS.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7E3126CC224006E46A2 /* CCDirectorIOS.h */; }; - E02BB88C126CC224006E46A2 /* CCDirectorIOS.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7E4126CC224006E46A2 /* CCDirectorIOS.m */; }; - E02BB88D126CC224006E46A2 /* CCTouchDelegateProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7E5126CC224006E46A2 /* CCTouchDelegateProtocol.h */; }; - E02BB88E126CC224006E46A2 /* CCTouchDispatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7E6126CC224006E46A2 /* CCTouchDispatcher.h */; }; - E02BB88F126CC224006E46A2 /* CCTouchDispatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7E7126CC224006E46A2 /* CCTouchDispatcher.m */; }; - E02BB890126CC224006E46A2 /* CCTouchHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7E8126CC224006E46A2 /* CCTouchHandler.h */; }; - E02BB891126CC224006E46A2 /* CCTouchHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7E9126CC224006E46A2 /* CCTouchHandler.m */; }; - E02BB892126CC224006E46A2 /* EAGLView.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7EA126CC224006E46A2 /* EAGLView.h */; }; - E02BB893126CC224006E46A2 /* EAGLView.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7EB126CC224006E46A2 /* EAGLView.m */; }; - E02BB894126CC224006E46A2 /* ES1Renderer.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7EC126CC224006E46A2 /* ES1Renderer.h */; }; - E02BB895126CC224006E46A2 /* ES1Renderer.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7ED126CC224006E46A2 /* ES1Renderer.m */; }; - E02BB896126CC224006E46A2 /* ESRenderer.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7EE126CC224006E46A2 /* ESRenderer.h */; }; - E02BB897126CC224006E46A2 /* glu.c in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7EF126CC224006E46A2 /* glu.c */; }; - E02BB898126CC224006E46A2 /* glu.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7F0126CC224006E46A2 /* glu.h */; }; - E02BB899126CC224006E46A2 /* CCDirectorMac.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7F2126CC224006E46A2 /* CCDirectorMac.h */; }; - E02BB89A126CC224006E46A2 /* CCDirectorMac.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7F3126CC224006E46A2 /* CCDirectorMac.m */; }; - E02BB89B126CC224006E46A2 /* CCEventDispatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7F4126CC224006E46A2 /* CCEventDispatcher.h */; }; - E02BB89C126CC224006E46A2 /* CCEventDispatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7F5126CC224006E46A2 /* CCEventDispatcher.m */; }; - E02BB89D126CC224006E46A2 /* MacGLView.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7F6126CC224006E46A2 /* MacGLView.h */; }; - E02BB89E126CC224006E46A2 /* MacGLView.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7F7126CC224006E46A2 /* MacGLView.m */; }; - E02BB89F126CC224006E46A2 /* base64.c in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7F9126CC224006E46A2 /* base64.c */; }; - E02BB8A0126CC224006E46A2 /* base64.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7FA126CC224006E46A2 /* base64.h */; }; - E02BB8A1126CC224006E46A2 /* CCArray.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7FB126CC224006E46A2 /* CCArray.h */; }; - E02BB8A2126CC224006E46A2 /* CCArray.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7FC126CC224006E46A2 /* CCArray.m */; }; - E02BB8A3126CC224006E46A2 /* ccCArray.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7FD126CC224006E46A2 /* ccCArray.h */; }; - E02BB8A4126CC224006E46A2 /* CCFileUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB7FE126CC224006E46A2 /* CCFileUtils.h */; }; - E02BB8A5126CC224006E46A2 /* CCFileUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB7FF126CC224006E46A2 /* CCFileUtils.m */; }; - E02BB8A6126CC224006E46A2 /* CCProfiling.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB800126CC224006E46A2 /* CCProfiling.h */; }; - E02BB8A7126CC224006E46A2 /* CCProfiling.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB801126CC224006E46A2 /* CCProfiling.m */; }; - E02BB8A8126CC224006E46A2 /* ccUtils.c in Sources */ = {isa = PBXBuildFile; fileRef = E02BB802126CC224006E46A2 /* ccUtils.c */; }; - E02BB8A9126CC224006E46A2 /* ccUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB803126CC224006E46A2 /* ccUtils.h */; }; - E02BB8AA126CC224006E46A2 /* CGPointExtension.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB804126CC224006E46A2 /* CGPointExtension.h */; }; - E02BB8AB126CC224006E46A2 /* CGPointExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB805126CC224006E46A2 /* CGPointExtension.m */; }; - E02BB8AC126CC224006E46A2 /* OpenGL_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB806126CC224006E46A2 /* OpenGL_Internal.h */; }; - E02BB8AD126CC224006E46A2 /* TGAlib.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB807126CC224006E46A2 /* TGAlib.h */; }; - E02BB8AE126CC224006E46A2 /* TGAlib.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB808126CC224006E46A2 /* TGAlib.m */; }; - E02BB8AF126CC224006E46A2 /* TransformUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB809126CC224006E46A2 /* TransformUtils.h */; }; - E02BB8B0126CC224006E46A2 /* TransformUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB80A126CC224006E46A2 /* TransformUtils.m */; }; - E02BB8B1126CC224006E46A2 /* uthash.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB80B126CC224006E46A2 /* uthash.h */; }; - E02BB8B2126CC224006E46A2 /* utlist.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB80C126CC224006E46A2 /* utlist.h */; }; - E02BB8B3126CC224006E46A2 /* ZipUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = E02BB80D126CC224006E46A2 /* ZipUtils.h */; }; - E02BB8B4126CC224006E46A2 /* ZipUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = E02BB80E126CC224006E46A2 /* ZipUtils.m */; }; - E0F80F60120A0182005866B8 /* RootViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = E0F80F5F120A0182005866B8 /* RootViewController.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -267,11 +315,231 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 1D6058910D05DD3D006BFB54 /* Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Example.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 1D6058910D05DD3D006BFB54 /* CCBlade.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CCBlade.app; sourceTree = BUILT_PRODUCTS_DIR; }; 1F3B9A2B0EF2145700286867 /* ExampleAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ExampleAppDelegate.m; path = Classes/ExampleAppDelegate.m; sourceTree = SOURCE_ROOT; }; 1F3B9A2C0EF2145700286867 /* ExampleAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ExampleAppDelegate.h; path = Classes/ExampleAppDelegate.h; sourceTree = SOURCE_ROOT; }; 1F3B9A820EF2151B00286867 /* Example_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Example_Prefix.pch; sourceTree = SOURCE_ROOT; }; 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + 473FCA8A156A52A3007DD659 /* CCAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAction.h; sourceTree = ""; }; + 473FCA8B156A52A3007DD659 /* CCAction.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAction.m; sourceTree = ""; }; + 473FCA8C156A52A3007DD659 /* CCActionCamera.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionCamera.h; sourceTree = ""; }; + 473FCA8D156A52A3007DD659 /* CCActionCamera.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionCamera.m; sourceTree = ""; }; + 473FCA8E156A52A3007DD659 /* CCActionEase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionEase.h; sourceTree = ""; }; + 473FCA8F156A52A3007DD659 /* CCActionEase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionEase.m; sourceTree = ""; }; + 473FCA90156A52A3007DD659 /* CCActionGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionGrid.h; sourceTree = ""; }; + 473FCA91156A52A3007DD659 /* CCActionGrid.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionGrid.m; sourceTree = ""; }; + 473FCA92156A52A3007DD659 /* CCActionGrid3D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionGrid3D.h; sourceTree = ""; }; + 473FCA93156A52A3007DD659 /* CCActionGrid3D.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionGrid3D.m; sourceTree = ""; }; + 473FCA94156A52A3007DD659 /* CCActionInstant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionInstant.h; sourceTree = ""; }; + 473FCA95156A52A3007DD659 /* CCActionInstant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionInstant.m; sourceTree = ""; }; + 473FCA96156A52A3007DD659 /* CCActionInterval.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionInterval.h; sourceTree = ""; }; + 473FCA97156A52A3007DD659 /* CCActionInterval.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionInterval.m; sourceTree = ""; }; + 473FCA98156A52A3007DD659 /* CCActionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionManager.h; sourceTree = ""; }; + 473FCA99156A52A3007DD659 /* CCActionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionManager.m; sourceTree = ""; }; + 473FCA9A156A52A3007DD659 /* CCActionPageTurn3D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionPageTurn3D.h; sourceTree = ""; }; + 473FCA9B156A52A3007DD659 /* CCActionPageTurn3D.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionPageTurn3D.m; sourceTree = ""; }; + 473FCA9C156A52A3007DD659 /* CCActionProgressTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionProgressTimer.h; sourceTree = ""; }; + 473FCA9D156A52A3007DD659 /* CCActionProgressTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionProgressTimer.m; sourceTree = ""; }; + 473FCA9E156A52A3007DD659 /* CCActionTiledGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionTiledGrid.h; sourceTree = ""; }; + 473FCA9F156A52A3007DD659 /* CCActionTiledGrid.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionTiledGrid.m; sourceTree = ""; }; + 473FCAA0156A52A3007DD659 /* CCActionTween.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionTween.h; sourceTree = ""; }; + 473FCAA1156A52A3007DD659 /* CCActionTween.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionTween.m; sourceTree = ""; }; + 473FCAA2156A52A3007DD659 /* CCAnimation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAnimation.h; sourceTree = ""; }; + 473FCAA3156A52A3007DD659 /* CCAnimation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAnimation.m; sourceTree = ""; }; + 473FCAA4156A52A3007DD659 /* CCAnimationCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAnimationCache.h; sourceTree = ""; }; + 473FCAA5156A52A3007DD659 /* CCAnimationCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAnimationCache.m; sourceTree = ""; }; + 473FCAA6156A52A3007DD659 /* CCAtlasNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAtlasNode.h; sourceTree = ""; }; + 473FCAA7156A52A3007DD659 /* CCAtlasNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAtlasNode.m; sourceTree = ""; }; + 473FCAA8156A52A3007DD659 /* CCCamera.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCCamera.h; sourceTree = ""; }; + 473FCAA9156A52A3007DD659 /* CCCamera.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCCamera.m; sourceTree = ""; }; + 473FCAAA156A52A3007DD659 /* ccConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccConfig.h; sourceTree = ""; }; + 473FCAAB156A52A3007DD659 /* CCConfiguration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCConfiguration.h; sourceTree = ""; }; + 473FCAAC156A52A3007DD659 /* CCConfiguration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCConfiguration.m; sourceTree = ""; }; + 473FCAAD156A52A3007DD659 /* ccDeprecated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccDeprecated.h; sourceTree = ""; }; + 473FCAAE156A52A3007DD659 /* ccDeprecated.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ccDeprecated.m; sourceTree = ""; }; + 473FCAAF156A52A3007DD659 /* CCDirector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDirector.h; sourceTree = ""; }; + 473FCAB0156A52A3007DD659 /* CCDirector.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDirector.m; sourceTree = ""; }; + 473FCAB1156A52A3007DD659 /* CCDrawingPrimitives.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDrawingPrimitives.h; sourceTree = ""; }; + 473FCAB2156A52A3007DD659 /* CCDrawingPrimitives.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDrawingPrimitives.m; sourceTree = ""; }; + 473FCAB3156A52A3007DD659 /* CCGLProgram.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGLProgram.h; sourceTree = ""; }; + 473FCAB4156A52A3007DD659 /* CCGLProgram.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGLProgram.m; sourceTree = ""; }; + 473FCAB5156A52A3007DD659 /* ccGLStateCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccGLStateCache.h; sourceTree = ""; }; + 473FCAB6156A52A3007DD659 /* ccGLStateCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ccGLStateCache.m; sourceTree = ""; }; + 473FCAB7156A52A3007DD659 /* CCGrabber.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGrabber.h; sourceTree = ""; }; + 473FCAB8156A52A3007DD659 /* CCGrabber.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGrabber.m; sourceTree = ""; }; + 473FCAB9156A52A3007DD659 /* CCGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGrid.h; sourceTree = ""; }; + 473FCABA156A52A3007DD659 /* CCGrid.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGrid.m; sourceTree = ""; }; + 473FCABB156A52A3007DD659 /* CCLabelAtlas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLabelAtlas.h; sourceTree = ""; }; + 473FCABC156A52A3007DD659 /* CCLabelAtlas.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLabelAtlas.m; sourceTree = ""; }; + 473FCABD156A52A3007DD659 /* CCLabelBMFont.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLabelBMFont.h; sourceTree = ""; }; + 473FCABE156A52A3007DD659 /* CCLabelBMFont.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLabelBMFont.m; sourceTree = ""; }; + 473FCABF156A52A3007DD659 /* CCLabelTTF.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLabelTTF.h; sourceTree = ""; }; + 473FCAC0156A52A3007DD659 /* CCLabelTTF.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLabelTTF.m; sourceTree = ""; }; + 473FCAC1156A52A3007DD659 /* CCLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLayer.h; sourceTree = ""; }; + 473FCAC2156A52A3007DD659 /* CCLayer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLayer.m; sourceTree = ""; }; + 473FCAC3156A52A3007DD659 /* ccMacros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccMacros.h; sourceTree = ""; }; + 473FCAC4156A52A3007DD659 /* CCMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCMenu.h; sourceTree = ""; }; + 473FCAC5156A52A3007DD659 /* CCMenu.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCMenu.m; sourceTree = ""; }; + 473FCAC6156A52A3007DD659 /* CCMenuItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCMenuItem.h; sourceTree = ""; }; + 473FCAC7156A52A3007DD659 /* CCMenuItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCMenuItem.m; sourceTree = ""; }; + 473FCAC8156A52A3007DD659 /* CCMotionStreak.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCMotionStreak.h; sourceTree = ""; }; + 473FCAC9156A52A3007DD659 /* CCMotionStreak.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCMotionStreak.m; sourceTree = ""; }; + 473FCACA156A52A3007DD659 /* CCNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCNode.h; sourceTree = ""; }; + 473FCACB156A52A3007DD659 /* CCNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCNode.m; sourceTree = ""; }; + 473FCACC156A52A3007DD659 /* CCParallaxNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParallaxNode.h; sourceTree = ""; }; + 473FCACD156A52A3007DD659 /* CCParallaxNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParallaxNode.m; sourceTree = ""; }; + 473FCACE156A52A3007DD659 /* CCParticleBatchNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleBatchNode.h; sourceTree = ""; }; + 473FCACF156A52A3007DD659 /* CCParticleBatchNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleBatchNode.m; sourceTree = ""; }; + 473FCAD0156A52A3007DD659 /* CCParticleExamples.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleExamples.h; sourceTree = ""; }; + 473FCAD1156A52A3007DD659 /* CCParticleExamples.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleExamples.m; sourceTree = ""; }; + 473FCAD2156A52A3007DD659 /* CCParticleSystem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleSystem.h; sourceTree = ""; }; + 473FCAD3156A52A3007DD659 /* CCParticleSystem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleSystem.m; sourceTree = ""; }; + 473FCAD4156A52A3007DD659 /* CCParticleSystemQuad.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleSystemQuad.h; sourceTree = ""; }; + 473FCAD5156A52A3007DD659 /* CCParticleSystemQuad.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleSystemQuad.m; sourceTree = ""; }; + 473FCAD6156A52A3007DD659 /* CCProgressTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCProgressTimer.h; sourceTree = ""; }; + 473FCAD7156A52A3007DD659 /* CCProgressTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCProgressTimer.m; sourceTree = ""; }; + 473FCAD8156A52A3007DD659 /* CCProtocols.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCProtocols.h; sourceTree = ""; }; + 473FCAD9156A52A3007DD659 /* CCRenderTexture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCRenderTexture.h; sourceTree = ""; }; + 473FCADA156A52A3007DD659 /* CCRenderTexture.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCRenderTexture.m; sourceTree = ""; }; + 473FCADB156A52A3007DD659 /* CCScene.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCScene.h; sourceTree = ""; }; + 473FCADC156A52A3007DD659 /* CCScene.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCScene.m; sourceTree = ""; }; + 473FCADD156A52A3007DD659 /* CCScheduler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCScheduler.h; sourceTree = ""; }; + 473FCADE156A52A3007DD659 /* CCScheduler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCScheduler.m; sourceTree = ""; }; + 473FCADF156A52A3007DD659 /* ccShader_Position_uColor_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_Position_uColor_frag.h; sourceTree = ""; }; + 473FCAE0156A52A3007DD659 /* ccShader_Position_uColor_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_Position_uColor_vert.h; sourceTree = ""; }; + 473FCAE1156A52A3007DD659 /* ccShader_PositionColor_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionColor_frag.h; sourceTree = ""; }; + 473FCAE2156A52A3007DD659 /* ccShader_PositionColor_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionColor_vert.h; sourceTree = ""; }; + 473FCAE3156A52A3007DD659 /* ccShader_PositionTexture_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTexture_frag.h; sourceTree = ""; }; + 473FCAE4156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTexture_uColor_frag.h; sourceTree = ""; }; + 473FCAE5156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTexture_uColor_vert.h; sourceTree = ""; }; + 473FCAE6156A52A3007DD659 /* ccShader_PositionTexture_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTexture_vert.h; sourceTree = ""; }; + 473FCAE7156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureA8Color_frag.h; sourceTree = ""; }; + 473FCAE8156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureA8Color_vert.h; sourceTree = ""; }; + 473FCAE9156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureColor_frag.h; sourceTree = ""; }; + 473FCAEA156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureColor_vert.h; sourceTree = ""; }; + 473FCAEB156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureColorAlphaTest_frag.h; sourceTree = ""; }; + 473FCAEC156A52A3007DD659 /* CCShaderCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCShaderCache.h; sourceTree = ""; }; + 473FCAED156A52A3007DD659 /* CCShaderCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCShaderCache.m; sourceTree = ""; }; + 473FCAEE156A52A3007DD659 /* ccShaders.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShaders.h; sourceTree = ""; }; + 473FCAEF156A52A3007DD659 /* ccShaders.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ccShaders.m; sourceTree = ""; }; + 473FCAF0156A52A3007DD659 /* CCSprite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSprite.h; sourceTree = ""; }; + 473FCAF1156A52A3007DD659 /* CCSprite.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSprite.m; sourceTree = ""; }; + 473FCAF2156A52A3007DD659 /* CCSpriteBatchNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteBatchNode.h; sourceTree = ""; }; + 473FCAF3156A52A3007DD659 /* CCSpriteBatchNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteBatchNode.m; sourceTree = ""; }; + 473FCAF4156A52A3007DD659 /* CCSpriteFrame.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteFrame.h; sourceTree = ""; }; + 473FCAF5156A52A3007DD659 /* CCSpriteFrame.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteFrame.m; sourceTree = ""; }; + 473FCAF6156A52A3007DD659 /* CCSpriteFrameCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteFrameCache.h; sourceTree = ""; }; + 473FCAF7156A52A3007DD659 /* CCSpriteFrameCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteFrameCache.m; sourceTree = ""; }; + 473FCAF8156A52A3007DD659 /* CCTexture2D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTexture2D.h; sourceTree = ""; }; + 473FCAF9156A52A3007DD659 /* CCTexture2D.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTexture2D.m; sourceTree = ""; }; + 473FCAFA156A52A3007DD659 /* CCTextureAtlas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTextureAtlas.h; sourceTree = ""; }; + 473FCAFB156A52A3007DD659 /* CCTextureAtlas.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTextureAtlas.m; sourceTree = ""; }; + 473FCAFC156A52A3007DD659 /* CCTextureCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTextureCache.h; sourceTree = ""; }; + 473FCAFD156A52A3007DD659 /* CCTextureCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTextureCache.m; sourceTree = ""; }; + 473FCAFE156A52A3007DD659 /* CCTexturePVR.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTexturePVR.h; sourceTree = ""; }; + 473FCAFF156A52A3007DD659 /* CCTexturePVR.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTexturePVR.m; sourceTree = ""; }; + 473FCB00156A52A3007DD659 /* CCTileMapAtlas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTileMapAtlas.h; sourceTree = ""; }; + 473FCB01156A52A3007DD659 /* CCTileMapAtlas.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTileMapAtlas.m; sourceTree = ""; }; + 473FCB02156A52A3007DD659 /* CCTMXLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXLayer.h; sourceTree = ""; }; + 473FCB03156A52A3007DD659 /* CCTMXLayer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXLayer.m; sourceTree = ""; }; + 473FCB04156A52A3007DD659 /* CCTMXObjectGroup.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXObjectGroup.h; sourceTree = ""; }; + 473FCB05156A52A3007DD659 /* CCTMXObjectGroup.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXObjectGroup.m; sourceTree = ""; }; + 473FCB06156A52A3007DD659 /* CCTMXTiledMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXTiledMap.h; sourceTree = ""; }; + 473FCB07156A52A3007DD659 /* CCTMXTiledMap.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXTiledMap.m; sourceTree = ""; }; + 473FCB08156A52A3007DD659 /* CCTMXXMLParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXXMLParser.h; sourceTree = ""; }; + 473FCB09156A52A3007DD659 /* CCTMXXMLParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXXMLParser.m; sourceTree = ""; }; + 473FCB0A156A52A3007DD659 /* CCTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTransition.h; sourceTree = ""; }; + 473FCB0B156A52A3007DD659 /* CCTransition.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTransition.m; sourceTree = ""; }; + 473FCB0C156A52A3007DD659 /* CCTransitionPageTurn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTransitionPageTurn.h; sourceTree = ""; }; + 473FCB0D156A52A3007DD659 /* CCTransitionPageTurn.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTransitionPageTurn.m; sourceTree = ""; }; + 473FCB0E156A52A3007DD659 /* CCTransitionProgress.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTransitionProgress.h; sourceTree = ""; }; + 473FCB0F156A52A3007DD659 /* CCTransitionProgress.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTransitionProgress.m; sourceTree = ""; }; + 473FCB10156A52A3007DD659 /* ccTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccTypes.h; sourceTree = ""; }; + 473FCB11156A52A3007DD659 /* cocos2d.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = cocos2d.h; sourceTree = ""; }; + 473FCB12156A52A3007DD659 /* cocos2d.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = cocos2d.m; sourceTree = ""; }; + 473FCB14156A52A3007DD659 /* CCGL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGL.h; sourceTree = ""; }; + 473FCB15156A52A3007DD659 /* CCNS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCNS.h; sourceTree = ""; }; + 473FCB17156A52A3007DD659 /* CCDirectorIOS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDirectorIOS.h; sourceTree = ""; }; + 473FCB18156A52A3007DD659 /* CCDirectorIOS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDirectorIOS.m; sourceTree = ""; }; + 473FCB19156A52A3007DD659 /* CCES2Renderer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCES2Renderer.h; sourceTree = ""; }; + 473FCB1A156A52A3007DD659 /* CCES2Renderer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCES2Renderer.m; sourceTree = ""; }; + 473FCB1B156A52A3007DD659 /* CCESRenderer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCESRenderer.h; sourceTree = ""; }; + 473FCB1C156A52A3007DD659 /* CCGLView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGLView.h; sourceTree = ""; }; + 473FCB1D156A52A3007DD659 /* CCGLView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGLView.m; sourceTree = ""; }; + 473FCB1E156A52A3007DD659 /* CCTouchDelegateProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTouchDelegateProtocol.h; sourceTree = ""; }; + 473FCB1F156A52A3007DD659 /* CCTouchDispatcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTouchDispatcher.h; sourceTree = ""; }; + 473FCB20156A52A3007DD659 /* CCTouchDispatcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTouchDispatcher.m; sourceTree = ""; }; + 473FCB21156A52A3007DD659 /* CCTouchHandler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTouchHandler.h; sourceTree = ""; }; + 473FCB22156A52A3007DD659 /* CCTouchHandler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTouchHandler.m; sourceTree = ""; }; + 473FCB24156A52A3007DD659 /* CCDirectorMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDirectorMac.h; sourceTree = ""; }; + 473FCB25156A52A3007DD659 /* CCDirectorMac.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDirectorMac.m; sourceTree = ""; }; + 473FCB26156A52A3007DD659 /* CCEventDispatcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCEventDispatcher.h; sourceTree = ""; }; + 473FCB27156A52A3007DD659 /* CCEventDispatcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCEventDispatcher.m; sourceTree = ""; }; + 473FCB28156A52A3007DD659 /* CCGLView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGLView.h; sourceTree = ""; }; + 473FCB29156A52A3007DD659 /* CCGLView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGLView.m; sourceTree = ""; }; + 473FCB2A156A52A3007DD659 /* CCWindow.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCWindow.h; sourceTree = ""; }; + 473FCB2B156A52A3007DD659 /* CCWindow.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCWindow.m; sourceTree = ""; }; + 473FCB2D156A52A3007DD659 /* base64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = base64.c; sourceTree = ""; }; + 473FCB2E156A52A3007DD659 /* base64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = base64.h; sourceTree = ""; }; + 473FCB2F156A52A3007DD659 /* CCArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCArray.h; sourceTree = ""; }; + 473FCB30156A52A3007DD659 /* CCArray.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCArray.m; sourceTree = ""; }; + 473FCB31156A52A3007DD659 /* ccCArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccCArray.h; sourceTree = ""; }; + 473FCB32156A52A3007DD659 /* CCFileUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCFileUtils.h; sourceTree = ""; }; + 473FCB33156A52A3007DD659 /* CCFileUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCFileUtils.m; sourceTree = ""; }; + 473FCB34156A52A3007DD659 /* CCProfiling.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCProfiling.h; sourceTree = ""; }; + 473FCB35156A52A3007DD659 /* CCProfiling.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCProfiling.m; sourceTree = ""; }; + 473FCB36156A52A3007DD659 /* ccUtils.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ccUtils.c; sourceTree = ""; }; + 473FCB37156A52A3007DD659 /* ccUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccUtils.h; sourceTree = ""; }; + 473FCB38156A52A3007DD659 /* CCVertex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCVertex.h; sourceTree = ""; }; + 473FCB39156A52A3007DD659 /* CCVertex.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCVertex.m; sourceTree = ""; }; + 473FCB3A156A52A3007DD659 /* CGPointExtension.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CGPointExtension.h; sourceTree = ""; }; + 473FCB3B156A52A3007DD659 /* CGPointExtension.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CGPointExtension.m; sourceTree = ""; }; + 473FCB3C156A52A3007DD659 /* NSThread+performBlock.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSThread+performBlock.h"; sourceTree = ""; }; + 473FCB3D156A52A3007DD659 /* NSThread+performBlock.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSThread+performBlock.m"; sourceTree = ""; }; + 473FCB3E156A52A3007DD659 /* OpenGL_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OpenGL_Internal.h; sourceTree = ""; }; + 473FCB3F156A52A3007DD659 /* TGAlib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TGAlib.h; sourceTree = ""; }; + 473FCB40156A52A3007DD659 /* TGAlib.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TGAlib.m; sourceTree = ""; }; + 473FCB41156A52A3007DD659 /* TransformUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TransformUtils.h; sourceTree = ""; }; + 473FCB42156A52A3007DD659 /* TransformUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TransformUtils.m; sourceTree = ""; }; + 473FCB43156A52A3007DD659 /* uthash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = uthash.h; sourceTree = ""; }; + 473FCB44156A52A3007DD659 /* utlist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utlist.h; sourceTree = ""; }; + 473FCB45156A52A3007DD659 /* ZipUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZipUtils.h; sourceTree = ""; }; + 473FCB46156A52A3007DD659 /* ZipUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZipUtils.m; sourceTree = ""; }; + 473FCC03156A52FF007DD659 /* aabb.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = aabb.h; sourceTree = ""; }; + 473FCC05156A52FF007DD659 /* mat4stack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mat4stack.h; sourceTree = ""; }; + 473FCC06156A52FF007DD659 /* matrix.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = matrix.h; sourceTree = ""; }; + 473FCC07156A52FF007DD659 /* kazmath.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = kazmath.h; sourceTree = ""; }; + 473FCC08156A52FF007DD659 /* mat3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mat3.h; sourceTree = ""; }; + 473FCC09156A52FF007DD659 /* mat4.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mat4.h; sourceTree = ""; }; + 473FCC0A156A52FF007DD659 /* neon_matrix_impl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = neon_matrix_impl.h; sourceTree = ""; }; + 473FCC0B156A52FF007DD659 /* plane.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = plane.h; sourceTree = ""; }; + 473FCC0C156A52FF007DD659 /* quaternion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = quaternion.h; sourceTree = ""; }; + 473FCC0D156A52FF007DD659 /* ray2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ray2.h; sourceTree = ""; }; + 473FCC0E156A52FF007DD659 /* utility.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utility.h; sourceTree = ""; }; + 473FCC0F156A52FF007DD659 /* vec2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vec2.h; sourceTree = ""; }; + 473FCC10156A52FF007DD659 /* vec3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vec3.h; sourceTree = ""; }; + 473FCC11156A52FF007DD659 /* vec4.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vec4.h; sourceTree = ""; }; + 473FCC13156A52FF007DD659 /* aabb.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = aabb.c; sourceTree = ""; }; + 473FCC14156A52FF007DD659 /* ChangeLog */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ChangeLog; sourceTree = ""; }; + 473FCC15156A52FF007DD659 /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 473FCC17156A52FF007DD659 /* mat4stack.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mat4stack.c; sourceTree = ""; }; + 473FCC18156A52FF007DD659 /* matrix.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = matrix.c; sourceTree = ""; }; + 473FCC19156A52FF007DD659 /* mat3.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mat3.c; sourceTree = ""; }; + 473FCC1A156A52FF007DD659 /* mat4.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mat4.c; sourceTree = ""; }; + 473FCC1B156A52FF007DD659 /* neon_matrix_impl.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = neon_matrix_impl.c; sourceTree = ""; }; + 473FCC1C156A52FF007DD659 /* plane.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = plane.c; sourceTree = ""; }; + 473FCC1D156A52FF007DD659 /* quaternion.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = quaternion.c; sourceTree = ""; }; + 473FCC1E156A52FF007DD659 /* ray2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ray2.c; sourceTree = ""; }; + 473FCC1F156A52FF007DD659 /* utility.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = utility.c; sourceTree = ""; }; + 473FCC20156A52FF007DD659 /* vec2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vec2.c; sourceTree = ""; }; + 473FCC21156A52FF007DD659 /* vec3.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vec3.c; sourceTree = ""; }; + 473FCC22156A52FF007DD659 /* vec4.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vec4.c; sourceTree = ""; }; + 473FCC42156A6B03007DD659 /* HelloWorldLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HelloWorldLayer.h; sourceTree = ""; }; + 473FCC43156A6B03007DD659 /* HelloWorldLayer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HelloWorldLayer.m; sourceTree = ""; }; + 473FCC45156A6BCE007DD659 /* GameKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GameKit.framework; path = System/Library/Frameworks/GameKit.framework; sourceTree = SDKROOT; }; + 473FCC49156A6DC4007DD659 /* fps_images.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = fps_images.png; sourceTree = ""; }; + 473FCC4A156A6DC4007DD659 /* fps_images-hd.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "fps_images-hd.png"; sourceTree = ""; }; + 473FCC4B156A6DC4007DD659 /* fps_images-ipadhd.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "fps_images-ipadhd.png"; sourceTree = ""; }; 47B71D5C137130530008113A /* CCBlade.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCBlade.h; path = ../../CCBlade.h; sourceTree = ""; }; 47B71D5D137130530008113A /* CCBlade.m */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; name = CCBlade.m; path = ../../CCBlade.m; sourceTree = ""; }; 47B71D5E137130530008113A /* TouchTrailLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TouchTrailLayer.h; path = ../../TouchTrailLayer.h; sourceTree = ""; }; @@ -296,8 +564,6 @@ 50674852107A3AF30090963A /* ZAttributedStringPrivate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZAttributedStringPrivate.h; sourceTree = ""; }; 506EDB87102F4C4000A389B3 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; 506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; - 506EDC2F102F528A00A389B3 /* HelloWorldScene.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HelloWorldScene.h; sourceTree = ""; }; - 506EDC30102F528A00A389B3 /* HelloWorldScene.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HelloWorldScene.m; sourceTree = ""; }; 506EE05E10304ED200A389B3 /* libcocos2d libraries.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libcocos2d libraries.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 507ED63311C638C6002ED3FC /* CDAudioManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDAudioManager.h; sourceTree = ""; }; 507ED63411C638C6002ED3FC /* CDAudioManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDAudioManager.m; sourceTree = ""; }; @@ -333,7 +599,6 @@ 50F41322106926B2002A0D5E /* CJSONSerializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CJSONSerializer.h; sourceTree = ""; }; 50F41323106926B2002A0D5E /* CJSONSerializer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CJSONSerializer.m; sourceTree = ""; }; 50F414EC1069373D002A0D5E /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = ""; }; - 50F414ED1069373D002A0D5E /* fps_images.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = fps_images.png; sourceTree = ""; }; 50F414EE1069373D002A0D5E /* Icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Icon.png; sourceTree = ""; }; 50F414EF1069373D002A0D5E /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; @@ -349,175 +614,6 @@ E02BB501126CA50F006E46A2 /* Icon-Small-50.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-Small-50.png"; sourceTree = ""; }; E02BB502126CA50F006E46A2 /* Icon-72.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-72.png"; sourceTree = ""; }; E02BB762126CC1E0006E46A2 /* iTunesArtwork */ = {isa = PBXFileReference; lastKnownFileType = file; path = iTunesArtwork; sourceTree = ""; }; - E02BB765126CC223006E46A2 /* CCAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAction.h; sourceTree = ""; }; - E02BB766126CC223006E46A2 /* CCAction.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAction.m; sourceTree = ""; }; - E02BB767126CC223006E46A2 /* CCActionCamera.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionCamera.h; sourceTree = ""; }; - E02BB768126CC223006E46A2 /* CCActionCamera.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionCamera.m; sourceTree = ""; }; - E02BB769126CC223006E46A2 /* CCActionEase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionEase.h; sourceTree = ""; }; - E02BB76A126CC223006E46A2 /* CCActionEase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionEase.m; sourceTree = ""; }; - E02BB76B126CC223006E46A2 /* CCActionGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionGrid.h; sourceTree = ""; }; - E02BB76C126CC223006E46A2 /* CCActionGrid.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionGrid.m; sourceTree = ""; }; - E02BB76D126CC223006E46A2 /* CCActionGrid3D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionGrid3D.h; sourceTree = ""; }; - E02BB76E126CC223006E46A2 /* CCActionGrid3D.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionGrid3D.m; sourceTree = ""; }; - E02BB76F126CC223006E46A2 /* CCActionInstant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionInstant.h; sourceTree = ""; }; - E02BB770126CC223006E46A2 /* CCActionInstant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionInstant.m; sourceTree = ""; }; - E02BB771126CC223006E46A2 /* CCActionInterval.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionInterval.h; sourceTree = ""; }; - E02BB772126CC223006E46A2 /* CCActionInterval.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionInterval.m; sourceTree = ""; }; - E02BB773126CC223006E46A2 /* CCActionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionManager.h; sourceTree = ""; }; - E02BB774126CC223006E46A2 /* CCActionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionManager.m; sourceTree = ""; }; - E02BB775126CC223006E46A2 /* CCActionPageTurn3D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionPageTurn3D.h; sourceTree = ""; }; - E02BB776126CC223006E46A2 /* CCActionPageTurn3D.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionPageTurn3D.m; sourceTree = ""; }; - E02BB777126CC223006E46A2 /* CCActionProgressTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionProgressTimer.h; sourceTree = ""; }; - E02BB778126CC223006E46A2 /* CCActionProgressTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionProgressTimer.m; sourceTree = ""; }; - E02BB779126CC223006E46A2 /* CCActionTiledGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionTiledGrid.h; sourceTree = ""; }; - E02BB77A126CC223006E46A2 /* CCActionTiledGrid.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionTiledGrid.m; sourceTree = ""; }; - E02BB77B126CC223006E46A2 /* CCActionTween.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionTween.h; sourceTree = ""; }; - E02BB77C126CC223006E46A2 /* CCActionTween.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionTween.m; sourceTree = ""; }; - E02BB77D126CC223006E46A2 /* CCAnimation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAnimation.h; sourceTree = ""; }; - E02BB77E126CC223006E46A2 /* CCAnimation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAnimation.m; sourceTree = ""; }; - E02BB77F126CC223006E46A2 /* CCAnimationCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAnimationCache.h; sourceTree = ""; }; - E02BB780126CC223006E46A2 /* CCAnimationCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAnimationCache.m; sourceTree = ""; }; - E02BB781126CC223006E46A2 /* CCAtlasNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAtlasNode.h; sourceTree = ""; }; - E02BB782126CC223006E46A2 /* CCAtlasNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAtlasNode.m; sourceTree = ""; }; - E02BB783126CC223006E46A2 /* CCBlockSupport.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCBlockSupport.h; sourceTree = ""; }; - E02BB784126CC223006E46A2 /* CCBlockSupport.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCBlockSupport.m; sourceTree = ""; }; - E02BB785126CC223006E46A2 /* CCCamera.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCCamera.h; sourceTree = ""; }; - E02BB786126CC223006E46A2 /* CCCamera.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCCamera.m; sourceTree = ""; }; - E02BB787126CC223006E46A2 /* CCCompatibility.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCCompatibility.h; sourceTree = ""; }; - E02BB788126CC223006E46A2 /* CCCompatibility.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCCompatibility.m; sourceTree = ""; }; - E02BB789126CC223006E46A2 /* ccConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccConfig.h; sourceTree = ""; }; - E02BB78A126CC223006E46A2 /* CCConfiguration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCConfiguration.h; sourceTree = ""; }; - E02BB78B126CC223006E46A2 /* CCConfiguration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCConfiguration.m; sourceTree = ""; }; - E02BB78C126CC223006E46A2 /* CCDirector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDirector.h; sourceTree = ""; }; - E02BB78D126CC223006E46A2 /* CCDirector.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDirector.m; sourceTree = ""; }; - E02BB78E126CC223006E46A2 /* CCDrawingPrimitives.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDrawingPrimitives.h; sourceTree = ""; }; - E02BB78F126CC223006E46A2 /* CCDrawingPrimitives.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDrawingPrimitives.m; sourceTree = ""; }; - E02BB790126CC223006E46A2 /* CCGrabber.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGrabber.h; sourceTree = ""; }; - E02BB791126CC223006E46A2 /* CCGrabber.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGrabber.m; sourceTree = ""; }; - E02BB792126CC223006E46A2 /* CCGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGrid.h; sourceTree = ""; }; - E02BB793126CC223006E46A2 /* CCGrid.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGrid.m; sourceTree = ""; }; - E02BB794126CC223006E46A2 /* CCLabelAtlas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLabelAtlas.h; sourceTree = ""; }; - E02BB795126CC223006E46A2 /* CCLabelAtlas.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLabelAtlas.m; sourceTree = ""; }; - E02BB796126CC223006E46A2 /* CCLabelBMFont.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLabelBMFont.h; sourceTree = ""; }; - E02BB797126CC223006E46A2 /* CCLabelBMFont.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLabelBMFont.m; sourceTree = ""; }; - E02BB798126CC223006E46A2 /* CCLabelTTF.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLabelTTF.h; sourceTree = ""; }; - E02BB799126CC223006E46A2 /* CCLabelTTF.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLabelTTF.m; sourceTree = ""; }; - E02BB79A126CC223006E46A2 /* CCLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLayer.h; sourceTree = ""; }; - E02BB79B126CC223006E46A2 /* CCLayer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLayer.m; sourceTree = ""; }; - E02BB79C126CC223006E46A2 /* ccMacros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccMacros.h; sourceTree = ""; }; - E02BB79D126CC223006E46A2 /* CCMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCMenu.h; sourceTree = ""; }; - E02BB79E126CC223006E46A2 /* CCMenu.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCMenu.m; sourceTree = ""; }; - E02BB79F126CC224006E46A2 /* CCMenuItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCMenuItem.h; sourceTree = ""; }; - E02BB7A0126CC224006E46A2 /* CCMenuItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCMenuItem.m; sourceTree = ""; }; - E02BB7A1126CC224006E46A2 /* CCMotionStreak.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCMotionStreak.h; sourceTree = ""; }; - E02BB7A2126CC224006E46A2 /* CCMotionStreak.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCMotionStreak.m; sourceTree = ""; }; - E02BB7A3126CC224006E46A2 /* CCNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCNode.h; sourceTree = ""; }; - E02BB7A4126CC224006E46A2 /* CCNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCNode.m; sourceTree = ""; }; - E02BB7A5126CC224006E46A2 /* CCParallaxNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParallaxNode.h; sourceTree = ""; }; - E02BB7A6126CC224006E46A2 /* CCParallaxNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParallaxNode.m; sourceTree = ""; }; - E02BB7A7126CC224006E46A2 /* CCParticleExamples.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleExamples.h; sourceTree = ""; }; - E02BB7A8126CC224006E46A2 /* CCParticleExamples.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleExamples.m; sourceTree = ""; }; - E02BB7A9126CC224006E46A2 /* CCParticleSystem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleSystem.h; sourceTree = ""; }; - E02BB7AA126CC224006E46A2 /* CCParticleSystem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleSystem.m; sourceTree = ""; }; - E02BB7AB126CC224006E46A2 /* CCParticleSystemPoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleSystemPoint.h; sourceTree = ""; }; - E02BB7AC126CC224006E46A2 /* CCParticleSystemPoint.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleSystemPoint.m; sourceTree = ""; }; - E02BB7AD126CC224006E46A2 /* CCParticleSystemQuad.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleSystemQuad.h; sourceTree = ""; }; - E02BB7AE126CC224006E46A2 /* CCParticleSystemQuad.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleSystemQuad.m; sourceTree = ""; }; - E02BB7AF126CC224006E46A2 /* CCProgressTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCProgressTimer.h; sourceTree = ""; }; - E02BB7B0126CC224006E46A2 /* CCProgressTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCProgressTimer.m; sourceTree = ""; }; - E02BB7B1126CC224006E46A2 /* CCProtocols.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCProtocols.h; sourceTree = ""; }; - E02BB7B2126CC224006E46A2 /* CCRenderTexture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCRenderTexture.h; sourceTree = ""; }; - E02BB7B3126CC224006E46A2 /* CCRenderTexture.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCRenderTexture.m; sourceTree = ""; }; - E02BB7B4126CC224006E46A2 /* CCRibbon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCRibbon.h; sourceTree = ""; }; - E02BB7B5126CC224006E46A2 /* CCRibbon.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCRibbon.m; sourceTree = ""; }; - E02BB7B6126CC224006E46A2 /* CCScene.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCScene.h; sourceTree = ""; }; - E02BB7B7126CC224006E46A2 /* CCScene.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCScene.m; sourceTree = ""; }; - E02BB7B8126CC224006E46A2 /* CCScheduler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCScheduler.h; sourceTree = ""; }; - E02BB7B9126CC224006E46A2 /* CCScheduler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCScheduler.m; sourceTree = ""; }; - E02BB7BA126CC224006E46A2 /* CCSprite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSprite.h; sourceTree = ""; }; - E02BB7BB126CC224006E46A2 /* CCSprite.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSprite.m; sourceTree = ""; }; - E02BB7BC126CC224006E46A2 /* CCSpriteBatchNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteBatchNode.h; sourceTree = ""; }; - E02BB7BD126CC224006E46A2 /* CCSpriteBatchNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteBatchNode.m; sourceTree = ""; }; - E02BB7BE126CC224006E46A2 /* CCSpriteFrame.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteFrame.h; sourceTree = ""; }; - E02BB7BF126CC224006E46A2 /* CCSpriteFrame.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteFrame.m; sourceTree = ""; }; - E02BB7C0126CC224006E46A2 /* CCSpriteFrameCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteFrameCache.h; sourceTree = ""; }; - E02BB7C1126CC224006E46A2 /* CCSpriteFrameCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteFrameCache.m; sourceTree = ""; }; - E02BB7C2126CC224006E46A2 /* CCSpriteSheet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteSheet.h; sourceTree = ""; }; - E02BB7C3126CC224006E46A2 /* CCSpriteSheet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteSheet.m; sourceTree = ""; }; - E02BB7C4126CC224006E46A2 /* CCTexture2D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTexture2D.h; sourceTree = ""; }; - E02BB7C5126CC224006E46A2 /* CCTexture2D.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTexture2D.m; sourceTree = ""; }; - E02BB7C6126CC224006E46A2 /* CCTextureAtlas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTextureAtlas.h; sourceTree = ""; }; - E02BB7C7126CC224006E46A2 /* CCTextureAtlas.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTextureAtlas.m; sourceTree = ""; }; - E02BB7C8126CC224006E46A2 /* CCTextureCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTextureCache.h; sourceTree = ""; }; - E02BB7C9126CC224006E46A2 /* CCTextureCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTextureCache.m; sourceTree = ""; }; - E02BB7CA126CC224006E46A2 /* CCTexturePVR.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTexturePVR.h; sourceTree = ""; }; - E02BB7CB126CC224006E46A2 /* CCTexturePVR.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTexturePVR.m; sourceTree = ""; }; - E02BB7CC126CC224006E46A2 /* CCTileMapAtlas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTileMapAtlas.h; sourceTree = ""; }; - E02BB7CD126CC224006E46A2 /* CCTileMapAtlas.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTileMapAtlas.m; sourceTree = ""; }; - E02BB7CE126CC224006E46A2 /* CCTMXLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXLayer.h; sourceTree = ""; }; - E02BB7CF126CC224006E46A2 /* CCTMXLayer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXLayer.m; sourceTree = ""; }; - E02BB7D0126CC224006E46A2 /* CCTMXObjectGroup.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXObjectGroup.h; sourceTree = ""; }; - E02BB7D1126CC224006E46A2 /* CCTMXObjectGroup.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXObjectGroup.m; sourceTree = ""; }; - E02BB7D2126CC224006E46A2 /* CCTMXTiledMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXTiledMap.h; sourceTree = ""; }; - E02BB7D3126CC224006E46A2 /* CCTMXTiledMap.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXTiledMap.m; sourceTree = ""; }; - E02BB7D4126CC224006E46A2 /* CCTMXXMLParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXXMLParser.h; sourceTree = ""; }; - E02BB7D5126CC224006E46A2 /* CCTMXXMLParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXXMLParser.m; sourceTree = ""; }; - E02BB7D6126CC224006E46A2 /* CCTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTransition.h; sourceTree = ""; }; - E02BB7D7126CC224006E46A2 /* CCTransition.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTransition.m; sourceTree = ""; }; - E02BB7D8126CC224006E46A2 /* CCTransitionPageTurn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTransitionPageTurn.h; sourceTree = ""; }; - E02BB7D9126CC224006E46A2 /* CCTransitionPageTurn.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTransitionPageTurn.m; sourceTree = ""; }; - E02BB7DA126CC224006E46A2 /* CCTransitionRadial.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTransitionRadial.h; sourceTree = ""; }; - E02BB7DB126CC224006E46A2 /* CCTransitionRadial.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTransitionRadial.m; sourceTree = ""; }; - E02BB7DC126CC224006E46A2 /* ccTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccTypes.h; sourceTree = ""; }; - E02BB7DD126CC224006E46A2 /* cocos2d.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = cocos2d.h; sourceTree = ""; }; - E02BB7DE126CC224006E46A2 /* cocos2d.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = cocos2d.m; sourceTree = ""; }; - E02BB7E0126CC224006E46A2 /* CCGL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGL.h; sourceTree = ""; }; - E02BB7E1126CC224006E46A2 /* CCNS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCNS.h; sourceTree = ""; }; - E02BB7E3126CC224006E46A2 /* CCDirectorIOS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDirectorIOS.h; sourceTree = ""; }; - E02BB7E4126CC224006E46A2 /* CCDirectorIOS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDirectorIOS.m; sourceTree = ""; }; - E02BB7E5126CC224006E46A2 /* CCTouchDelegateProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTouchDelegateProtocol.h; sourceTree = ""; }; - E02BB7E6126CC224006E46A2 /* CCTouchDispatcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTouchDispatcher.h; sourceTree = ""; }; - E02BB7E7126CC224006E46A2 /* CCTouchDispatcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTouchDispatcher.m; sourceTree = ""; }; - E02BB7E8126CC224006E46A2 /* CCTouchHandler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTouchHandler.h; sourceTree = ""; }; - E02BB7E9126CC224006E46A2 /* CCTouchHandler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTouchHandler.m; sourceTree = ""; }; - E02BB7EA126CC224006E46A2 /* EAGLView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EAGLView.h; sourceTree = ""; }; - E02BB7EB126CC224006E46A2 /* EAGLView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = EAGLView.m; sourceTree = ""; }; - E02BB7EC126CC224006E46A2 /* ES1Renderer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ES1Renderer.h; sourceTree = ""; }; - E02BB7ED126CC224006E46A2 /* ES1Renderer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ES1Renderer.m; sourceTree = ""; }; - E02BB7EE126CC224006E46A2 /* ESRenderer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ESRenderer.h; sourceTree = ""; }; - E02BB7EF126CC224006E46A2 /* glu.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = glu.c; sourceTree = ""; }; - E02BB7F0126CC224006E46A2 /* glu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = glu.h; sourceTree = ""; }; - E02BB7F2126CC224006E46A2 /* CCDirectorMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDirectorMac.h; sourceTree = ""; }; - E02BB7F3126CC224006E46A2 /* CCDirectorMac.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDirectorMac.m; sourceTree = ""; }; - E02BB7F4126CC224006E46A2 /* CCEventDispatcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCEventDispatcher.h; sourceTree = ""; }; - E02BB7F5126CC224006E46A2 /* CCEventDispatcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCEventDispatcher.m; sourceTree = ""; }; - E02BB7F6126CC224006E46A2 /* MacGLView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MacGLView.h; sourceTree = ""; }; - E02BB7F7126CC224006E46A2 /* MacGLView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MacGLView.m; sourceTree = ""; }; - E02BB7F9126CC224006E46A2 /* base64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = base64.c; sourceTree = ""; }; - E02BB7FA126CC224006E46A2 /* base64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = base64.h; sourceTree = ""; }; - E02BB7FB126CC224006E46A2 /* CCArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCArray.h; sourceTree = ""; }; - E02BB7FC126CC224006E46A2 /* CCArray.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCArray.m; sourceTree = ""; }; - E02BB7FD126CC224006E46A2 /* ccCArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccCArray.h; sourceTree = ""; }; - E02BB7FE126CC224006E46A2 /* CCFileUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCFileUtils.h; sourceTree = ""; }; - E02BB7FF126CC224006E46A2 /* CCFileUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCFileUtils.m; sourceTree = ""; }; - E02BB800126CC224006E46A2 /* CCProfiling.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCProfiling.h; sourceTree = ""; }; - E02BB801126CC224006E46A2 /* CCProfiling.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCProfiling.m; sourceTree = ""; }; - E02BB802126CC224006E46A2 /* ccUtils.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ccUtils.c; sourceTree = ""; }; - E02BB803126CC224006E46A2 /* ccUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccUtils.h; sourceTree = ""; }; - E02BB804126CC224006E46A2 /* CGPointExtension.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CGPointExtension.h; sourceTree = ""; }; - E02BB805126CC224006E46A2 /* CGPointExtension.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CGPointExtension.m; sourceTree = ""; }; - E02BB806126CC224006E46A2 /* OpenGL_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OpenGL_Internal.h; sourceTree = ""; }; - E02BB807126CC224006E46A2 /* TGAlib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TGAlib.h; sourceTree = ""; }; - E02BB808126CC224006E46A2 /* TGAlib.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TGAlib.m; sourceTree = ""; }; - E02BB809126CC224006E46A2 /* TransformUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TransformUtils.h; sourceTree = ""; }; - E02BB80A126CC224006E46A2 /* TransformUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TransformUtils.m; sourceTree = ""; }; - E02BB80B126CC224006E46A2 /* uthash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = uthash.h; sourceTree = ""; }; - E02BB80C126CC224006E46A2 /* utlist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utlist.h; sourceTree = ""; }; - E02BB80D126CC224006E46A2 /* ZipUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZipUtils.h; sourceTree = ""; }; - E02BB80E126CC224006E46A2 /* ZipUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZipUtils.m; sourceTree = ""; }; - E0F80F5D120A0182005866B8 /* GameConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameConfig.h; sourceTree = ""; }; - E0F80F5E120A0182005866B8 /* RootViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RootViewController.h; sourceTree = ""; }; - E0F80F5F120A0182005866B8 /* RootViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RootViewController.m; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -525,6 +621,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 473FCC46156A6BCE007DD659 /* GameKit.framework in Frameworks */, DCCBF1B70F6022AE0040855A /* CoreGraphics.framework in Frameworks */, DCCBF1B90F6022AE0040855A /* Foundation.framework in Frameworks */, DCCBF1BB0F6022AE0040855A /* OpenGLES.framework in Frameworks */, @@ -558,7 +655,7 @@ 19C28FACFE9D520D11CA2CBB /* Products */ = { isa = PBXGroup; children = ( - 1D6058910D05DD3D006BFB54 /* Example.app */, + 1D6058910D05DD3D006BFB54 /* CCBlade.app */, 506EE05E10304ED200A389B3 /* libcocos2d libraries.a */, ); name = Products; @@ -567,6 +664,7 @@ 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { isa = PBXGroup; children = ( + 473FCC45156A6BCE007DD659 /* GameKit.framework */, 504DFC6810AF1739006D82FE /* LICENSE.cocos2d */, 504DFC6910AF1739006D82FE /* LICENSE.cocosdenshion */, 506EDAA3102F461B00A389B3 /* cocos2d Sources */, @@ -607,21 +705,320 @@ 2D500B1D0D5A766B00DBA0E3 /* Classes */ = { isa = PBXGroup; children = ( + 473FCC42156A6B03007DD659 /* HelloWorldLayer.h */, + 473FCC43156A6B03007DD659 /* HelloWorldLayer.m */, 47B71D5C137130530008113A /* CCBlade.h */, 47B71D5D137130530008113A /* CCBlade.m */, 47B71D5E137130530008113A /* TouchTrailLayer.h */, 47B71D5F137130530008113A /* TouchTrailLayer.m */, - E0F80F5D120A0182005866B8 /* GameConfig.h */, - 506EDC2F102F528A00A389B3 /* HelloWorldScene.h */, - 506EDC30102F528A00A389B3 /* HelloWorldScene.m */, - E0F80F5E120A0182005866B8 /* RootViewController.h */, - E0F80F5F120A0182005866B8 /* RootViewController.m */, 1F3B9A2C0EF2145700286867 /* ExampleAppDelegate.h */, 1F3B9A2B0EF2145700286867 /* ExampleAppDelegate.m */, ); path = Classes; sourceTree = ""; }; + 473FCA89156A52A3007DD659 /* cocos2d */ = { + isa = PBXGroup; + children = ( + 473FCA8A156A52A3007DD659 /* CCAction.h */, + 473FCA8B156A52A3007DD659 /* CCAction.m */, + 473FCA8C156A52A3007DD659 /* CCActionCamera.h */, + 473FCA8D156A52A3007DD659 /* CCActionCamera.m */, + 473FCA8E156A52A3007DD659 /* CCActionEase.h */, + 473FCA8F156A52A3007DD659 /* CCActionEase.m */, + 473FCA90156A52A3007DD659 /* CCActionGrid.h */, + 473FCA91156A52A3007DD659 /* CCActionGrid.m */, + 473FCA92156A52A3007DD659 /* CCActionGrid3D.h */, + 473FCA93156A52A3007DD659 /* CCActionGrid3D.m */, + 473FCA94156A52A3007DD659 /* CCActionInstant.h */, + 473FCA95156A52A3007DD659 /* CCActionInstant.m */, + 473FCA96156A52A3007DD659 /* CCActionInterval.h */, + 473FCA97156A52A3007DD659 /* CCActionInterval.m */, + 473FCA98156A52A3007DD659 /* CCActionManager.h */, + 473FCA99156A52A3007DD659 /* CCActionManager.m */, + 473FCA9A156A52A3007DD659 /* CCActionPageTurn3D.h */, + 473FCA9B156A52A3007DD659 /* CCActionPageTurn3D.m */, + 473FCA9C156A52A3007DD659 /* CCActionProgressTimer.h */, + 473FCA9D156A52A3007DD659 /* CCActionProgressTimer.m */, + 473FCA9E156A52A3007DD659 /* CCActionTiledGrid.h */, + 473FCA9F156A52A3007DD659 /* CCActionTiledGrid.m */, + 473FCAA0156A52A3007DD659 /* CCActionTween.h */, + 473FCAA1156A52A3007DD659 /* CCActionTween.m */, + 473FCAA2156A52A3007DD659 /* CCAnimation.h */, + 473FCAA3156A52A3007DD659 /* CCAnimation.m */, + 473FCAA4156A52A3007DD659 /* CCAnimationCache.h */, + 473FCAA5156A52A3007DD659 /* CCAnimationCache.m */, + 473FCAA6156A52A3007DD659 /* CCAtlasNode.h */, + 473FCAA7156A52A3007DD659 /* CCAtlasNode.m */, + 473FCAA8156A52A3007DD659 /* CCCamera.h */, + 473FCAA9156A52A3007DD659 /* CCCamera.m */, + 473FCAAA156A52A3007DD659 /* ccConfig.h */, + 473FCAAB156A52A3007DD659 /* CCConfiguration.h */, + 473FCAAC156A52A3007DD659 /* CCConfiguration.m */, + 473FCAAD156A52A3007DD659 /* ccDeprecated.h */, + 473FCAAE156A52A3007DD659 /* ccDeprecated.m */, + 473FCAAF156A52A3007DD659 /* CCDirector.h */, + 473FCAB0156A52A3007DD659 /* CCDirector.m */, + 473FCAB1156A52A3007DD659 /* CCDrawingPrimitives.h */, + 473FCAB2156A52A3007DD659 /* CCDrawingPrimitives.m */, + 473FCAB3156A52A3007DD659 /* CCGLProgram.h */, + 473FCAB4156A52A3007DD659 /* CCGLProgram.m */, + 473FCAB5156A52A3007DD659 /* ccGLStateCache.h */, + 473FCAB6156A52A3007DD659 /* ccGLStateCache.m */, + 473FCAB7156A52A3007DD659 /* CCGrabber.h */, + 473FCAB8156A52A3007DD659 /* CCGrabber.m */, + 473FCAB9156A52A3007DD659 /* CCGrid.h */, + 473FCABA156A52A3007DD659 /* CCGrid.m */, + 473FCABB156A52A3007DD659 /* CCLabelAtlas.h */, + 473FCABC156A52A3007DD659 /* CCLabelAtlas.m */, + 473FCABD156A52A3007DD659 /* CCLabelBMFont.h */, + 473FCABE156A52A3007DD659 /* CCLabelBMFont.m */, + 473FCABF156A52A3007DD659 /* CCLabelTTF.h */, + 473FCAC0156A52A3007DD659 /* CCLabelTTF.m */, + 473FCAC1156A52A3007DD659 /* CCLayer.h */, + 473FCAC2156A52A3007DD659 /* CCLayer.m */, + 473FCAC3156A52A3007DD659 /* ccMacros.h */, + 473FCAC4156A52A3007DD659 /* CCMenu.h */, + 473FCAC5156A52A3007DD659 /* CCMenu.m */, + 473FCAC6156A52A3007DD659 /* CCMenuItem.h */, + 473FCAC7156A52A3007DD659 /* CCMenuItem.m */, + 473FCAC8156A52A3007DD659 /* CCMotionStreak.h */, + 473FCAC9156A52A3007DD659 /* CCMotionStreak.m */, + 473FCACA156A52A3007DD659 /* CCNode.h */, + 473FCACB156A52A3007DD659 /* CCNode.m */, + 473FCACC156A52A3007DD659 /* CCParallaxNode.h */, + 473FCACD156A52A3007DD659 /* CCParallaxNode.m */, + 473FCACE156A52A3007DD659 /* CCParticleBatchNode.h */, + 473FCACF156A52A3007DD659 /* CCParticleBatchNode.m */, + 473FCAD0156A52A3007DD659 /* CCParticleExamples.h */, + 473FCAD1156A52A3007DD659 /* CCParticleExamples.m */, + 473FCAD2156A52A3007DD659 /* CCParticleSystem.h */, + 473FCAD3156A52A3007DD659 /* CCParticleSystem.m */, + 473FCAD4156A52A3007DD659 /* CCParticleSystemQuad.h */, + 473FCAD5156A52A3007DD659 /* CCParticleSystemQuad.m */, + 473FCAD6156A52A3007DD659 /* CCProgressTimer.h */, + 473FCAD7156A52A3007DD659 /* CCProgressTimer.m */, + 473FCAD8156A52A3007DD659 /* CCProtocols.h */, + 473FCAD9156A52A3007DD659 /* CCRenderTexture.h */, + 473FCADA156A52A3007DD659 /* CCRenderTexture.m */, + 473FCADB156A52A3007DD659 /* CCScene.h */, + 473FCADC156A52A3007DD659 /* CCScene.m */, + 473FCADD156A52A3007DD659 /* CCScheduler.h */, + 473FCADE156A52A3007DD659 /* CCScheduler.m */, + 473FCADF156A52A3007DD659 /* ccShader_Position_uColor_frag.h */, + 473FCAE0156A52A3007DD659 /* ccShader_Position_uColor_vert.h */, + 473FCAE1156A52A3007DD659 /* ccShader_PositionColor_frag.h */, + 473FCAE2156A52A3007DD659 /* ccShader_PositionColor_vert.h */, + 473FCAE3156A52A3007DD659 /* ccShader_PositionTexture_frag.h */, + 473FCAE4156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h */, + 473FCAE5156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h */, + 473FCAE6156A52A3007DD659 /* ccShader_PositionTexture_vert.h */, + 473FCAE7156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h */, + 473FCAE8156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h */, + 473FCAE9156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h */, + 473FCAEA156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h */, + 473FCAEB156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h */, + 473FCAEC156A52A3007DD659 /* CCShaderCache.h */, + 473FCAED156A52A3007DD659 /* CCShaderCache.m */, + 473FCAEE156A52A3007DD659 /* ccShaders.h */, + 473FCAEF156A52A3007DD659 /* ccShaders.m */, + 473FCAF0156A52A3007DD659 /* CCSprite.h */, + 473FCAF1156A52A3007DD659 /* CCSprite.m */, + 473FCAF2156A52A3007DD659 /* CCSpriteBatchNode.h */, + 473FCAF3156A52A3007DD659 /* CCSpriteBatchNode.m */, + 473FCAF4156A52A3007DD659 /* CCSpriteFrame.h */, + 473FCAF5156A52A3007DD659 /* CCSpriteFrame.m */, + 473FCAF6156A52A3007DD659 /* CCSpriteFrameCache.h */, + 473FCAF7156A52A3007DD659 /* CCSpriteFrameCache.m */, + 473FCAF8156A52A3007DD659 /* CCTexture2D.h */, + 473FCAF9156A52A3007DD659 /* CCTexture2D.m */, + 473FCAFA156A52A3007DD659 /* CCTextureAtlas.h */, + 473FCAFB156A52A3007DD659 /* CCTextureAtlas.m */, + 473FCAFC156A52A3007DD659 /* CCTextureCache.h */, + 473FCAFD156A52A3007DD659 /* CCTextureCache.m */, + 473FCAFE156A52A3007DD659 /* CCTexturePVR.h */, + 473FCAFF156A52A3007DD659 /* CCTexturePVR.m */, + 473FCB00156A52A3007DD659 /* CCTileMapAtlas.h */, + 473FCB01156A52A3007DD659 /* CCTileMapAtlas.m */, + 473FCB02156A52A3007DD659 /* CCTMXLayer.h */, + 473FCB03156A52A3007DD659 /* CCTMXLayer.m */, + 473FCB04156A52A3007DD659 /* CCTMXObjectGroup.h */, + 473FCB05156A52A3007DD659 /* CCTMXObjectGroup.m */, + 473FCB06156A52A3007DD659 /* CCTMXTiledMap.h */, + 473FCB07156A52A3007DD659 /* CCTMXTiledMap.m */, + 473FCB08156A52A3007DD659 /* CCTMXXMLParser.h */, + 473FCB09156A52A3007DD659 /* CCTMXXMLParser.m */, + 473FCB0A156A52A3007DD659 /* CCTransition.h */, + 473FCB0B156A52A3007DD659 /* CCTransition.m */, + 473FCB0C156A52A3007DD659 /* CCTransitionPageTurn.h */, + 473FCB0D156A52A3007DD659 /* CCTransitionPageTurn.m */, + 473FCB0E156A52A3007DD659 /* CCTransitionProgress.h */, + 473FCB0F156A52A3007DD659 /* CCTransitionProgress.m */, + 473FCB10156A52A3007DD659 /* ccTypes.h */, + 473FCB11156A52A3007DD659 /* cocos2d.h */, + 473FCB12156A52A3007DD659 /* cocos2d.m */, + 473FCB13156A52A3007DD659 /* Platforms */, + 473FCB2C156A52A3007DD659 /* Support */, + ); + name = cocos2d; + path = libs/cocos2d; + sourceTree = ""; + }; + 473FCB13156A52A3007DD659 /* Platforms */ = { + isa = PBXGroup; + children = ( + 473FCB14156A52A3007DD659 /* CCGL.h */, + 473FCB15156A52A3007DD659 /* CCNS.h */, + 473FCB16156A52A3007DD659 /* iOS */, + 473FCB23156A52A3007DD659 /* Mac */, + ); + path = Platforms; + sourceTree = ""; + }; + 473FCB16156A52A3007DD659 /* iOS */ = { + isa = PBXGroup; + children = ( + 473FCB17156A52A3007DD659 /* CCDirectorIOS.h */, + 473FCB18156A52A3007DD659 /* CCDirectorIOS.m */, + 473FCB19156A52A3007DD659 /* CCES2Renderer.h */, + 473FCB1A156A52A3007DD659 /* CCES2Renderer.m */, + 473FCB1B156A52A3007DD659 /* CCESRenderer.h */, + 473FCB1C156A52A3007DD659 /* CCGLView.h */, + 473FCB1D156A52A3007DD659 /* CCGLView.m */, + 473FCB1E156A52A3007DD659 /* CCTouchDelegateProtocol.h */, + 473FCB1F156A52A3007DD659 /* CCTouchDispatcher.h */, + 473FCB20156A52A3007DD659 /* CCTouchDispatcher.m */, + 473FCB21156A52A3007DD659 /* CCTouchHandler.h */, + 473FCB22156A52A3007DD659 /* CCTouchHandler.m */, + ); + path = iOS; + sourceTree = ""; + }; + 473FCB23156A52A3007DD659 /* Mac */ = { + isa = PBXGroup; + children = ( + 473FCB24156A52A3007DD659 /* CCDirectorMac.h */, + 473FCB25156A52A3007DD659 /* CCDirectorMac.m */, + 473FCB26156A52A3007DD659 /* CCEventDispatcher.h */, + 473FCB27156A52A3007DD659 /* CCEventDispatcher.m */, + 473FCB28156A52A3007DD659 /* CCGLView.h */, + 473FCB29156A52A3007DD659 /* CCGLView.m */, + 473FCB2A156A52A3007DD659 /* CCWindow.h */, + 473FCB2B156A52A3007DD659 /* CCWindow.m */, + ); + path = Mac; + sourceTree = ""; + }; + 473FCB2C156A52A3007DD659 /* Support */ = { + isa = PBXGroup; + children = ( + 473FCB2D156A52A3007DD659 /* base64.c */, + 473FCB2E156A52A3007DD659 /* base64.h */, + 473FCB2F156A52A3007DD659 /* CCArray.h */, + 473FCB30156A52A3007DD659 /* CCArray.m */, + 473FCB31156A52A3007DD659 /* ccCArray.h */, + 473FCB32156A52A3007DD659 /* CCFileUtils.h */, + 473FCB33156A52A3007DD659 /* CCFileUtils.m */, + 473FCB34156A52A3007DD659 /* CCProfiling.h */, + 473FCB35156A52A3007DD659 /* CCProfiling.m */, + 473FCB36156A52A3007DD659 /* ccUtils.c */, + 473FCB37156A52A3007DD659 /* ccUtils.h */, + 473FCB38156A52A3007DD659 /* CCVertex.h */, + 473FCB39156A52A3007DD659 /* CCVertex.m */, + 473FCB3A156A52A3007DD659 /* CGPointExtension.h */, + 473FCB3B156A52A3007DD659 /* CGPointExtension.m */, + 473FCB3C156A52A3007DD659 /* NSThread+performBlock.h */, + 473FCB3D156A52A3007DD659 /* NSThread+performBlock.m */, + 473FCB3E156A52A3007DD659 /* OpenGL_Internal.h */, + 473FCB3F156A52A3007DD659 /* TGAlib.h */, + 473FCB40156A52A3007DD659 /* TGAlib.m */, + 473FCB41156A52A3007DD659 /* TransformUtils.h */, + 473FCB42156A52A3007DD659 /* TransformUtils.m */, + 473FCB43156A52A3007DD659 /* uthash.h */, + 473FCB44156A52A3007DD659 /* utlist.h */, + 473FCB45156A52A3007DD659 /* ZipUtils.h */, + 473FCB46156A52A3007DD659 /* ZipUtils.m */, + ); + path = Support; + sourceTree = ""; + }; + 473FCC00156A52FF007DD659 /* kazmath */ = { + isa = PBXGroup; + children = ( + 473FCC01156A52FF007DD659 /* include */, + 473FCC12156A52FF007DD659 /* src */, + ); + name = kazmath; + path = libs/kazmath; + sourceTree = ""; + }; + 473FCC01156A52FF007DD659 /* include */ = { + isa = PBXGroup; + children = ( + 473FCC02156A52FF007DD659 /* kazmath */, + ); + path = include; + sourceTree = ""; + }; + 473FCC02156A52FF007DD659 /* kazmath */ = { + isa = PBXGroup; + children = ( + 473FCC03156A52FF007DD659 /* aabb.h */, + 473FCC04156A52FF007DD659 /* GL */, + 473FCC07156A52FF007DD659 /* kazmath.h */, + 473FCC08156A52FF007DD659 /* mat3.h */, + 473FCC09156A52FF007DD659 /* mat4.h */, + 473FCC0A156A52FF007DD659 /* neon_matrix_impl.h */, + 473FCC0B156A52FF007DD659 /* plane.h */, + 473FCC0C156A52FF007DD659 /* quaternion.h */, + 473FCC0D156A52FF007DD659 /* ray2.h */, + 473FCC0E156A52FF007DD659 /* utility.h */, + 473FCC0F156A52FF007DD659 /* vec2.h */, + 473FCC10156A52FF007DD659 /* vec3.h */, + 473FCC11156A52FF007DD659 /* vec4.h */, + ); + path = kazmath; + sourceTree = ""; + }; + 473FCC04156A52FF007DD659 /* GL */ = { + isa = PBXGroup; + children = ( + 473FCC05156A52FF007DD659 /* mat4stack.h */, + 473FCC06156A52FF007DD659 /* matrix.h */, + ); + path = GL; + sourceTree = ""; + }; + 473FCC12156A52FF007DD659 /* src */ = { + isa = PBXGroup; + children = ( + 473FCC13156A52FF007DD659 /* aabb.c */, + 473FCC14156A52FF007DD659 /* ChangeLog */, + 473FCC15156A52FF007DD659 /* CMakeLists.txt */, + 473FCC16156A52FF007DD659 /* GL */, + 473FCC19156A52FF007DD659 /* mat3.c */, + 473FCC1A156A52FF007DD659 /* mat4.c */, + 473FCC1B156A52FF007DD659 /* neon_matrix_impl.c */, + 473FCC1C156A52FF007DD659 /* plane.c */, + 473FCC1D156A52FF007DD659 /* quaternion.c */, + 473FCC1E156A52FF007DD659 /* ray2.c */, + 473FCC1F156A52FF007DD659 /* utility.c */, + 473FCC20156A52FF007DD659 /* vec2.c */, + 473FCC21156A52FF007DD659 /* vec3.c */, + 473FCC22156A52FF007DD659 /* vec4.c */, + ); + path = src; + sourceTree = ""; + }; + 473FCC16156A52FF007DD659 /* GL */ = { + isa = PBXGroup; + children = ( + 473FCC17156A52FF007DD659 /* mat4stack.c */, + 473FCC18156A52FF007DD659 /* matrix.c */, + ); + path = GL; + sourceTree = ""; + }; 504DFBC710AF12E9006D82FE /* cocoslive */ = { isa = PBXGroup; children = ( @@ -639,7 +1036,8 @@ 506EDAA3102F461B00A389B3 /* cocos2d Sources */ = { isa = PBXGroup; children = ( - E02BB764126CC223006E46A2 /* cocos2d */, + 473FCC00156A52FF007DD659 /* kazmath */, + 473FCA89156A52A3007DD659 /* cocos2d */, 507ED63211C638C6002ED3FC /* CocosDenshion */, 504DFBC710AF12E9006D82FE /* cocoslive */, 50F41306106926B2002A0D5E /* FontLabel */, @@ -727,6 +1125,9 @@ 50F414EB1069373D002A0D5E /* Resources */ = { isa = PBXGroup; children = ( + 473FCC49156A6DC4007DD659 /* fps_images.png */, + 473FCC4A156A6DC4007DD659 /* fps_images-hd.png */, + 473FCC4B156A6DC4007DD659 /* fps_images-ipadhd.png */, 47B802CF13F26A4C006B0B98 /* Default-hd.png */, 47B802C913F269D9006B0B98 /* streak1-hd.png */, 47B802CA13F269D9006B0B98 /* streak2-hd.png */, @@ -741,219 +1142,12 @@ E02BB501126CA50F006E46A2 /* Icon-Small-50.png */, E02BB502126CA50F006E46A2 /* Icon-72.png */, 50F414EC1069373D002A0D5E /* Default.png */, - 50F414ED1069373D002A0D5E /* fps_images.png */, 50F414EE1069373D002A0D5E /* Icon.png */, 50F414EF1069373D002A0D5E /* Info.plist */, ); path = Resources; sourceTree = ""; }; - E02BB764126CC223006E46A2 /* cocos2d */ = { - isa = PBXGroup; - children = ( - E02BB765126CC223006E46A2 /* CCAction.h */, - E02BB766126CC223006E46A2 /* CCAction.m */, - E02BB767126CC223006E46A2 /* CCActionCamera.h */, - E02BB768126CC223006E46A2 /* CCActionCamera.m */, - E02BB769126CC223006E46A2 /* CCActionEase.h */, - E02BB76A126CC223006E46A2 /* CCActionEase.m */, - E02BB76B126CC223006E46A2 /* CCActionGrid.h */, - E02BB76C126CC223006E46A2 /* CCActionGrid.m */, - E02BB76D126CC223006E46A2 /* CCActionGrid3D.h */, - E02BB76E126CC223006E46A2 /* CCActionGrid3D.m */, - E02BB76F126CC223006E46A2 /* CCActionInstant.h */, - E02BB770126CC223006E46A2 /* CCActionInstant.m */, - E02BB771126CC223006E46A2 /* CCActionInterval.h */, - E02BB772126CC223006E46A2 /* CCActionInterval.m */, - E02BB773126CC223006E46A2 /* CCActionManager.h */, - E02BB774126CC223006E46A2 /* CCActionManager.m */, - E02BB775126CC223006E46A2 /* CCActionPageTurn3D.h */, - E02BB776126CC223006E46A2 /* CCActionPageTurn3D.m */, - E02BB777126CC223006E46A2 /* CCActionProgressTimer.h */, - E02BB778126CC223006E46A2 /* CCActionProgressTimer.m */, - E02BB779126CC223006E46A2 /* CCActionTiledGrid.h */, - E02BB77A126CC223006E46A2 /* CCActionTiledGrid.m */, - E02BB77B126CC223006E46A2 /* CCActionTween.h */, - E02BB77C126CC223006E46A2 /* CCActionTween.m */, - E02BB77D126CC223006E46A2 /* CCAnimation.h */, - E02BB77E126CC223006E46A2 /* CCAnimation.m */, - E02BB77F126CC223006E46A2 /* CCAnimationCache.h */, - E02BB780126CC223006E46A2 /* CCAnimationCache.m */, - E02BB781126CC223006E46A2 /* CCAtlasNode.h */, - E02BB782126CC223006E46A2 /* CCAtlasNode.m */, - E02BB783126CC223006E46A2 /* CCBlockSupport.h */, - E02BB784126CC223006E46A2 /* CCBlockSupport.m */, - E02BB785126CC223006E46A2 /* CCCamera.h */, - E02BB786126CC223006E46A2 /* CCCamera.m */, - E02BB787126CC223006E46A2 /* CCCompatibility.h */, - E02BB788126CC223006E46A2 /* CCCompatibility.m */, - E02BB789126CC223006E46A2 /* ccConfig.h */, - E02BB78A126CC223006E46A2 /* CCConfiguration.h */, - E02BB78B126CC223006E46A2 /* CCConfiguration.m */, - E02BB78C126CC223006E46A2 /* CCDirector.h */, - E02BB78D126CC223006E46A2 /* CCDirector.m */, - E02BB78E126CC223006E46A2 /* CCDrawingPrimitives.h */, - E02BB78F126CC223006E46A2 /* CCDrawingPrimitives.m */, - E02BB790126CC223006E46A2 /* CCGrabber.h */, - E02BB791126CC223006E46A2 /* CCGrabber.m */, - E02BB792126CC223006E46A2 /* CCGrid.h */, - E02BB793126CC223006E46A2 /* CCGrid.m */, - E02BB794126CC223006E46A2 /* CCLabelAtlas.h */, - E02BB795126CC223006E46A2 /* CCLabelAtlas.m */, - E02BB796126CC223006E46A2 /* CCLabelBMFont.h */, - E02BB797126CC223006E46A2 /* CCLabelBMFont.m */, - E02BB798126CC223006E46A2 /* CCLabelTTF.h */, - E02BB799126CC223006E46A2 /* CCLabelTTF.m */, - E02BB79A126CC223006E46A2 /* CCLayer.h */, - E02BB79B126CC223006E46A2 /* CCLayer.m */, - E02BB79C126CC223006E46A2 /* ccMacros.h */, - E02BB79D126CC223006E46A2 /* CCMenu.h */, - E02BB79E126CC223006E46A2 /* CCMenu.m */, - E02BB79F126CC224006E46A2 /* CCMenuItem.h */, - E02BB7A0126CC224006E46A2 /* CCMenuItem.m */, - E02BB7A1126CC224006E46A2 /* CCMotionStreak.h */, - E02BB7A2126CC224006E46A2 /* CCMotionStreak.m */, - E02BB7A3126CC224006E46A2 /* CCNode.h */, - E02BB7A4126CC224006E46A2 /* CCNode.m */, - E02BB7A5126CC224006E46A2 /* CCParallaxNode.h */, - E02BB7A6126CC224006E46A2 /* CCParallaxNode.m */, - E02BB7A7126CC224006E46A2 /* CCParticleExamples.h */, - E02BB7A8126CC224006E46A2 /* CCParticleExamples.m */, - E02BB7A9126CC224006E46A2 /* CCParticleSystem.h */, - E02BB7AA126CC224006E46A2 /* CCParticleSystem.m */, - E02BB7AB126CC224006E46A2 /* CCParticleSystemPoint.h */, - E02BB7AC126CC224006E46A2 /* CCParticleSystemPoint.m */, - E02BB7AD126CC224006E46A2 /* CCParticleSystemQuad.h */, - E02BB7AE126CC224006E46A2 /* CCParticleSystemQuad.m */, - E02BB7AF126CC224006E46A2 /* CCProgressTimer.h */, - E02BB7B0126CC224006E46A2 /* CCProgressTimer.m */, - E02BB7B1126CC224006E46A2 /* CCProtocols.h */, - E02BB7B2126CC224006E46A2 /* CCRenderTexture.h */, - E02BB7B3126CC224006E46A2 /* CCRenderTexture.m */, - E02BB7B4126CC224006E46A2 /* CCRibbon.h */, - E02BB7B5126CC224006E46A2 /* CCRibbon.m */, - E02BB7B6126CC224006E46A2 /* CCScene.h */, - E02BB7B7126CC224006E46A2 /* CCScene.m */, - E02BB7B8126CC224006E46A2 /* CCScheduler.h */, - E02BB7B9126CC224006E46A2 /* CCScheduler.m */, - E02BB7BA126CC224006E46A2 /* CCSprite.h */, - E02BB7BB126CC224006E46A2 /* CCSprite.m */, - E02BB7BC126CC224006E46A2 /* CCSpriteBatchNode.h */, - E02BB7BD126CC224006E46A2 /* CCSpriteBatchNode.m */, - E02BB7BE126CC224006E46A2 /* CCSpriteFrame.h */, - E02BB7BF126CC224006E46A2 /* CCSpriteFrame.m */, - E02BB7C0126CC224006E46A2 /* CCSpriteFrameCache.h */, - E02BB7C1126CC224006E46A2 /* CCSpriteFrameCache.m */, - E02BB7C2126CC224006E46A2 /* CCSpriteSheet.h */, - E02BB7C3126CC224006E46A2 /* CCSpriteSheet.m */, - E02BB7C4126CC224006E46A2 /* CCTexture2D.h */, - E02BB7C5126CC224006E46A2 /* CCTexture2D.m */, - E02BB7C6126CC224006E46A2 /* CCTextureAtlas.h */, - E02BB7C7126CC224006E46A2 /* CCTextureAtlas.m */, - E02BB7C8126CC224006E46A2 /* CCTextureCache.h */, - E02BB7C9126CC224006E46A2 /* CCTextureCache.m */, - E02BB7CA126CC224006E46A2 /* CCTexturePVR.h */, - E02BB7CB126CC224006E46A2 /* CCTexturePVR.m */, - E02BB7CC126CC224006E46A2 /* CCTileMapAtlas.h */, - E02BB7CD126CC224006E46A2 /* CCTileMapAtlas.m */, - E02BB7CE126CC224006E46A2 /* CCTMXLayer.h */, - E02BB7CF126CC224006E46A2 /* CCTMXLayer.m */, - E02BB7D0126CC224006E46A2 /* CCTMXObjectGroup.h */, - E02BB7D1126CC224006E46A2 /* CCTMXObjectGroup.m */, - E02BB7D2126CC224006E46A2 /* CCTMXTiledMap.h */, - E02BB7D3126CC224006E46A2 /* CCTMXTiledMap.m */, - E02BB7D4126CC224006E46A2 /* CCTMXXMLParser.h */, - E02BB7D5126CC224006E46A2 /* CCTMXXMLParser.m */, - E02BB7D6126CC224006E46A2 /* CCTransition.h */, - E02BB7D7126CC224006E46A2 /* CCTransition.m */, - E02BB7D8126CC224006E46A2 /* CCTransitionPageTurn.h */, - E02BB7D9126CC224006E46A2 /* CCTransitionPageTurn.m */, - E02BB7DA126CC224006E46A2 /* CCTransitionRadial.h */, - E02BB7DB126CC224006E46A2 /* CCTransitionRadial.m */, - E02BB7DC126CC224006E46A2 /* ccTypes.h */, - E02BB7DD126CC224006E46A2 /* cocos2d.h */, - E02BB7DE126CC224006E46A2 /* cocos2d.m */, - E02BB7DF126CC224006E46A2 /* Platforms */, - E02BB7F8126CC224006E46A2 /* Support */, - ); - name = cocos2d; - path = libs/cocos2d; - sourceTree = ""; - }; - E02BB7DF126CC224006E46A2 /* Platforms */ = { - isa = PBXGroup; - children = ( - E02BB7E0126CC224006E46A2 /* CCGL.h */, - E02BB7E1126CC224006E46A2 /* CCNS.h */, - E02BB7E2126CC224006E46A2 /* iOS */, - E02BB7F1126CC224006E46A2 /* Mac */, - ); - path = Platforms; - sourceTree = ""; - }; - E02BB7E2126CC224006E46A2 /* iOS */ = { - isa = PBXGroup; - children = ( - E02BB7E3126CC224006E46A2 /* CCDirectorIOS.h */, - E02BB7E4126CC224006E46A2 /* CCDirectorIOS.m */, - E02BB7E5126CC224006E46A2 /* CCTouchDelegateProtocol.h */, - E02BB7E6126CC224006E46A2 /* CCTouchDispatcher.h */, - E02BB7E7126CC224006E46A2 /* CCTouchDispatcher.m */, - E02BB7E8126CC224006E46A2 /* CCTouchHandler.h */, - E02BB7E9126CC224006E46A2 /* CCTouchHandler.m */, - E02BB7EA126CC224006E46A2 /* EAGLView.h */, - E02BB7EB126CC224006E46A2 /* EAGLView.m */, - E02BB7EC126CC224006E46A2 /* ES1Renderer.h */, - E02BB7ED126CC224006E46A2 /* ES1Renderer.m */, - E02BB7EE126CC224006E46A2 /* ESRenderer.h */, - E02BB7EF126CC224006E46A2 /* glu.c */, - E02BB7F0126CC224006E46A2 /* glu.h */, - ); - path = iOS; - sourceTree = ""; - }; - E02BB7F1126CC224006E46A2 /* Mac */ = { - isa = PBXGroup; - children = ( - E02BB7F2126CC224006E46A2 /* CCDirectorMac.h */, - E02BB7F3126CC224006E46A2 /* CCDirectorMac.m */, - E02BB7F4126CC224006E46A2 /* CCEventDispatcher.h */, - E02BB7F5126CC224006E46A2 /* CCEventDispatcher.m */, - E02BB7F6126CC224006E46A2 /* MacGLView.h */, - E02BB7F7126CC224006E46A2 /* MacGLView.m */, - ); - path = Mac; - sourceTree = ""; - }; - E02BB7F8126CC224006E46A2 /* Support */ = { - isa = PBXGroup; - children = ( - E02BB7F9126CC224006E46A2 /* base64.c */, - E02BB7FA126CC224006E46A2 /* base64.h */, - E02BB7FB126CC224006E46A2 /* CCArray.h */, - E02BB7FC126CC224006E46A2 /* CCArray.m */, - E02BB7FD126CC224006E46A2 /* ccCArray.h */, - E02BB7FE126CC224006E46A2 /* CCFileUtils.h */, - E02BB7FF126CC224006E46A2 /* CCFileUtils.m */, - E02BB800126CC224006E46A2 /* CCProfiling.h */, - E02BB801126CC224006E46A2 /* CCProfiling.m */, - E02BB802126CC224006E46A2 /* ccUtils.c */, - E02BB803126CC224006E46A2 /* ccUtils.h */, - E02BB804126CC224006E46A2 /* CGPointExtension.h */, - E02BB805126CC224006E46A2 /* CGPointExtension.m */, - E02BB806126CC224006E46A2 /* OpenGL_Internal.h */, - E02BB807126CC224006E46A2 /* TGAlib.h */, - E02BB808126CC224006E46A2 /* TGAlib.m */, - E02BB809126CC224006E46A2 /* TransformUtils.h */, - E02BB80A126CC224006E46A2 /* TransformUtils.m */, - E02BB80B126CC224006E46A2 /* uthash.h */, - E02BB80C126CC224006E46A2 /* utlist.h */, - E02BB80D126CC224006E46A2 /* ZipUtils.h */, - E02BB80E126CC224006E46A2 /* ZipUtils.m */, - ); - path = Support; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -983,95 +1177,125 @@ 507ED63F11C638C6002ED3FC /* CDOpenALSupport.h in Headers */, 507ED64111C638C6002ED3FC /* CocosDenshion.h in Headers */, 507ED64311C638C6002ED3FC /* SimpleAudioEngine.h in Headers */, - E02BB80F126CC224006E46A2 /* CCAction.h in Headers */, - E02BB811126CC224006E46A2 /* CCActionCamera.h in Headers */, - E02BB813126CC224006E46A2 /* CCActionEase.h in Headers */, - E02BB815126CC224006E46A2 /* CCActionGrid.h in Headers */, - E02BB817126CC224006E46A2 /* CCActionGrid3D.h in Headers */, - E02BB819126CC224006E46A2 /* CCActionInstant.h in Headers */, - E02BB81B126CC224006E46A2 /* CCActionInterval.h in Headers */, - E02BB81D126CC224006E46A2 /* CCActionManager.h in Headers */, - E02BB81F126CC224006E46A2 /* CCActionPageTurn3D.h in Headers */, - E02BB821126CC224006E46A2 /* CCActionProgressTimer.h in Headers */, - E02BB823126CC224006E46A2 /* CCActionTiledGrid.h in Headers */, - E02BB825126CC224006E46A2 /* CCActionTween.h in Headers */, - E02BB827126CC224006E46A2 /* CCAnimation.h in Headers */, - E02BB829126CC224006E46A2 /* CCAnimationCache.h in Headers */, - E02BB82B126CC224006E46A2 /* CCAtlasNode.h in Headers */, - E02BB82D126CC224006E46A2 /* CCBlockSupport.h in Headers */, - E02BB82F126CC224006E46A2 /* CCCamera.h in Headers */, - E02BB831126CC224006E46A2 /* CCCompatibility.h in Headers */, - E02BB833126CC224006E46A2 /* ccConfig.h in Headers */, - E02BB834126CC224006E46A2 /* CCConfiguration.h in Headers */, - E02BB836126CC224006E46A2 /* CCDirector.h in Headers */, - E02BB838126CC224006E46A2 /* CCDrawingPrimitives.h in Headers */, - E02BB83A126CC224006E46A2 /* CCGrabber.h in Headers */, - E02BB83C126CC224006E46A2 /* CCGrid.h in Headers */, - E02BB83E126CC224006E46A2 /* CCLabelAtlas.h in Headers */, - E02BB840126CC224006E46A2 /* CCLabelBMFont.h in Headers */, - E02BB842126CC224006E46A2 /* CCLabelTTF.h in Headers */, - E02BB844126CC224006E46A2 /* CCLayer.h in Headers */, - E02BB846126CC224006E46A2 /* ccMacros.h in Headers */, - E02BB847126CC224006E46A2 /* CCMenu.h in Headers */, - E02BB849126CC224006E46A2 /* CCMenuItem.h in Headers */, - E02BB84B126CC224006E46A2 /* CCMotionStreak.h in Headers */, - E02BB84D126CC224006E46A2 /* CCNode.h in Headers */, - E02BB84F126CC224006E46A2 /* CCParallaxNode.h in Headers */, - E02BB851126CC224006E46A2 /* CCParticleExamples.h in Headers */, - E02BB853126CC224006E46A2 /* CCParticleSystem.h in Headers */, - E02BB855126CC224006E46A2 /* CCParticleSystemPoint.h in Headers */, - E02BB857126CC224006E46A2 /* CCParticleSystemQuad.h in Headers */, - E02BB859126CC224006E46A2 /* CCProgressTimer.h in Headers */, - E02BB85B126CC224006E46A2 /* CCProtocols.h in Headers */, - E02BB85C126CC224006E46A2 /* CCRenderTexture.h in Headers */, - E02BB85E126CC224006E46A2 /* CCRibbon.h in Headers */, - E02BB860126CC224006E46A2 /* CCScene.h in Headers */, - E02BB862126CC224006E46A2 /* CCScheduler.h in Headers */, - E02BB864126CC224006E46A2 /* CCSprite.h in Headers */, - E02BB866126CC224006E46A2 /* CCSpriteBatchNode.h in Headers */, - E02BB868126CC224006E46A2 /* CCSpriteFrame.h in Headers */, - E02BB86A126CC224006E46A2 /* CCSpriteFrameCache.h in Headers */, - E02BB86C126CC224006E46A2 /* CCSpriteSheet.h in Headers */, - E02BB86E126CC224006E46A2 /* CCTexture2D.h in Headers */, - E02BB870126CC224006E46A2 /* CCTextureAtlas.h in Headers */, - E02BB872126CC224006E46A2 /* CCTextureCache.h in Headers */, - E02BB874126CC224006E46A2 /* CCTexturePVR.h in Headers */, - E02BB876126CC224006E46A2 /* CCTileMapAtlas.h in Headers */, - E02BB878126CC224006E46A2 /* CCTMXLayer.h in Headers */, - E02BB87A126CC224006E46A2 /* CCTMXObjectGroup.h in Headers */, - E02BB87C126CC224006E46A2 /* CCTMXTiledMap.h in Headers */, - E02BB87E126CC224006E46A2 /* CCTMXXMLParser.h in Headers */, - E02BB880126CC224006E46A2 /* CCTransition.h in Headers */, - E02BB882126CC224006E46A2 /* CCTransitionPageTurn.h in Headers */, - E02BB884126CC224006E46A2 /* CCTransitionRadial.h in Headers */, - E02BB886126CC224006E46A2 /* ccTypes.h in Headers */, - E02BB887126CC224006E46A2 /* cocos2d.h in Headers */, - E02BB889126CC224006E46A2 /* CCGL.h in Headers */, - E02BB88A126CC224006E46A2 /* CCNS.h in Headers */, - E02BB88B126CC224006E46A2 /* CCDirectorIOS.h in Headers */, - E02BB88D126CC224006E46A2 /* CCTouchDelegateProtocol.h in Headers */, - E02BB88E126CC224006E46A2 /* CCTouchDispatcher.h in Headers */, - E02BB890126CC224006E46A2 /* CCTouchHandler.h in Headers */, - E02BB892126CC224006E46A2 /* EAGLView.h in Headers */, - E02BB894126CC224006E46A2 /* ES1Renderer.h in Headers */, - E02BB896126CC224006E46A2 /* ESRenderer.h in Headers */, - E02BB898126CC224006E46A2 /* glu.h in Headers */, - E02BB899126CC224006E46A2 /* CCDirectorMac.h in Headers */, - E02BB89B126CC224006E46A2 /* CCEventDispatcher.h in Headers */, - E02BB89D126CC224006E46A2 /* MacGLView.h in Headers */, - E02BB8A0126CC224006E46A2 /* base64.h in Headers */, - E02BB8A1126CC224006E46A2 /* CCArray.h in Headers */, - E02BB8A3126CC224006E46A2 /* ccCArray.h in Headers */, - E02BB8A4126CC224006E46A2 /* CCFileUtils.h in Headers */, - E02BB8A6126CC224006E46A2 /* CCProfiling.h in Headers */, - E02BB8A9126CC224006E46A2 /* ccUtils.h in Headers */, - E02BB8AA126CC224006E46A2 /* CGPointExtension.h in Headers */, - E02BB8AC126CC224006E46A2 /* OpenGL_Internal.h in Headers */, - E02BB8AD126CC224006E46A2 /* TGAlib.h in Headers */, - E02BB8AF126CC224006E46A2 /* TransformUtils.h in Headers */, - E02BB8B1126CC224006E46A2 /* uthash.h in Headers */, - E02BB8B2126CC224006E46A2 /* utlist.h in Headers */, - E02BB8B3126CC224006E46A2 /* ZipUtils.h in Headers */, + 473FCB47156A52A3007DD659 /* CCAction.h in Headers */, + 473FCB49156A52A3007DD659 /* CCActionCamera.h in Headers */, + 473FCB4B156A52A3007DD659 /* CCActionEase.h in Headers */, + 473FCB4D156A52A3007DD659 /* CCActionGrid.h in Headers */, + 473FCB4F156A52A3007DD659 /* CCActionGrid3D.h in Headers */, + 473FCB51156A52A3007DD659 /* CCActionInstant.h in Headers */, + 473FCB53156A52A3007DD659 /* CCActionInterval.h in Headers */, + 473FCB55156A52A3007DD659 /* CCActionManager.h in Headers */, + 473FCB57156A52A3007DD659 /* CCActionPageTurn3D.h in Headers */, + 473FCB59156A52A3007DD659 /* CCActionProgressTimer.h in Headers */, + 473FCB5B156A52A3007DD659 /* CCActionTiledGrid.h in Headers */, + 473FCB5D156A52A3007DD659 /* CCActionTween.h in Headers */, + 473FCB5F156A52A3007DD659 /* CCAnimation.h in Headers */, + 473FCB61156A52A3007DD659 /* CCAnimationCache.h in Headers */, + 473FCB63156A52A3007DD659 /* CCAtlasNode.h in Headers */, + 473FCB65156A52A3007DD659 /* CCCamera.h in Headers */, + 473FCB67156A52A3007DD659 /* ccConfig.h in Headers */, + 473FCB68156A52A3007DD659 /* CCConfiguration.h in Headers */, + 473FCB6A156A52A3007DD659 /* ccDeprecated.h in Headers */, + 473FCB6C156A52A3007DD659 /* CCDirector.h in Headers */, + 473FCB6E156A52A3007DD659 /* CCDrawingPrimitives.h in Headers */, + 473FCB70156A52A3007DD659 /* CCGLProgram.h in Headers */, + 473FCB72156A52A3007DD659 /* ccGLStateCache.h in Headers */, + 473FCB74156A52A3007DD659 /* CCGrabber.h in Headers */, + 473FCB76156A52A3007DD659 /* CCGrid.h in Headers */, + 473FCB78156A52A3007DD659 /* CCLabelAtlas.h in Headers */, + 473FCB7A156A52A3007DD659 /* CCLabelBMFont.h in Headers */, + 473FCB7C156A52A3007DD659 /* CCLabelTTF.h in Headers */, + 473FCB7E156A52A3007DD659 /* CCLayer.h in Headers */, + 473FCB80156A52A3007DD659 /* ccMacros.h in Headers */, + 473FCB81156A52A3007DD659 /* CCMenu.h in Headers */, + 473FCB83156A52A3007DD659 /* CCMenuItem.h in Headers */, + 473FCB85156A52A3007DD659 /* CCMotionStreak.h in Headers */, + 473FCB87156A52A3007DD659 /* CCNode.h in Headers */, + 473FCB89156A52A3007DD659 /* CCParallaxNode.h in Headers */, + 473FCB8B156A52A3007DD659 /* CCParticleBatchNode.h in Headers */, + 473FCB8D156A52A3007DD659 /* CCParticleExamples.h in Headers */, + 473FCB8F156A52A3007DD659 /* CCParticleSystem.h in Headers */, + 473FCB91156A52A3007DD659 /* CCParticleSystemQuad.h in Headers */, + 473FCB93156A52A3007DD659 /* CCProgressTimer.h in Headers */, + 473FCB95156A52A3007DD659 /* CCProtocols.h in Headers */, + 473FCB96156A52A3007DD659 /* CCRenderTexture.h in Headers */, + 473FCB98156A52A3007DD659 /* CCScene.h in Headers */, + 473FCB9A156A52A3007DD659 /* CCScheduler.h in Headers */, + 473FCB9C156A52A3007DD659 /* ccShader_Position_uColor_frag.h in Headers */, + 473FCB9D156A52A3007DD659 /* ccShader_Position_uColor_vert.h in Headers */, + 473FCB9E156A52A3007DD659 /* ccShader_PositionColor_frag.h in Headers */, + 473FCB9F156A52A3007DD659 /* ccShader_PositionColor_vert.h in Headers */, + 473FCBA0156A52A3007DD659 /* ccShader_PositionTexture_frag.h in Headers */, + 473FCBA1156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h in Headers */, + 473FCBA2156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h in Headers */, + 473FCBA3156A52A3007DD659 /* ccShader_PositionTexture_vert.h in Headers */, + 473FCBA4156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h in Headers */, + 473FCBA5156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h in Headers */, + 473FCBA6156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h in Headers */, + 473FCBA7156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h in Headers */, + 473FCBA8156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h in Headers */, + 473FCBA9156A52A3007DD659 /* CCShaderCache.h in Headers */, + 473FCBAB156A52A3007DD659 /* ccShaders.h in Headers */, + 473FCBAD156A52A3007DD659 /* CCSprite.h in Headers */, + 473FCBAF156A52A3007DD659 /* CCSpriteBatchNode.h in Headers */, + 473FCBB1156A52A3007DD659 /* CCSpriteFrame.h in Headers */, + 473FCBB3156A52A3007DD659 /* CCSpriteFrameCache.h in Headers */, + 473FCBB5156A52A3007DD659 /* CCTexture2D.h in Headers */, + 473FCBB7156A52A3007DD659 /* CCTextureAtlas.h in Headers */, + 473FCBB9156A52A3007DD659 /* CCTextureCache.h in Headers */, + 473FCBBB156A52A3007DD659 /* CCTexturePVR.h in Headers */, + 473FCBBD156A52A3007DD659 /* CCTileMapAtlas.h in Headers */, + 473FCBBF156A52A3007DD659 /* CCTMXLayer.h in Headers */, + 473FCBC1156A52A3007DD659 /* CCTMXObjectGroup.h in Headers */, + 473FCBC3156A52A3007DD659 /* CCTMXTiledMap.h in Headers */, + 473FCBC5156A52A3007DD659 /* CCTMXXMLParser.h in Headers */, + 473FCBC7156A52A3007DD659 /* CCTransition.h in Headers */, + 473FCBC9156A52A3007DD659 /* CCTransitionPageTurn.h in Headers */, + 473FCBCB156A52A3007DD659 /* CCTransitionProgress.h in Headers */, + 473FCBCD156A52A3007DD659 /* ccTypes.h in Headers */, + 473FCBCE156A52A3007DD659 /* cocos2d.h in Headers */, + 473FCBD0156A52A3007DD659 /* CCGL.h in Headers */, + 473FCBD1156A52A3007DD659 /* CCNS.h in Headers */, + 473FCBD2156A52A3007DD659 /* CCDirectorIOS.h in Headers */, + 473FCBD4156A52A3007DD659 /* CCES2Renderer.h in Headers */, + 473FCBD6156A52A3007DD659 /* CCESRenderer.h in Headers */, + 473FCBD7156A52A3007DD659 /* CCGLView.h in Headers */, + 473FCBD9156A52A3007DD659 /* CCTouchDelegateProtocol.h in Headers */, + 473FCBDA156A52A3007DD659 /* CCTouchDispatcher.h in Headers */, + 473FCBDC156A52A3007DD659 /* CCTouchHandler.h in Headers */, + 473FCBDE156A52A3007DD659 /* CCDirectorMac.h in Headers */, + 473FCBE0156A52A3007DD659 /* CCEventDispatcher.h in Headers */, + 473FCBE2156A52A3007DD659 /* CCGLView.h in Headers */, + 473FCBE4156A52A3007DD659 /* CCWindow.h in Headers */, + 473FCBE7156A52A3007DD659 /* base64.h in Headers */, + 473FCBE8156A52A3007DD659 /* CCArray.h in Headers */, + 473FCBEA156A52A3007DD659 /* ccCArray.h in Headers */, + 473FCBEB156A52A3007DD659 /* CCFileUtils.h in Headers */, + 473FCBED156A52A3007DD659 /* CCProfiling.h in Headers */, + 473FCBF0156A52A3007DD659 /* ccUtils.h in Headers */, + 473FCBF1156A52A3007DD659 /* CCVertex.h in Headers */, + 473FCBF3156A52A3007DD659 /* CGPointExtension.h in Headers */, + 473FCBF5156A52A3007DD659 /* NSThread+performBlock.h in Headers */, + 473FCBF7156A52A3007DD659 /* OpenGL_Internal.h in Headers */, + 473FCBF8156A52A3007DD659 /* TGAlib.h in Headers */, + 473FCBFA156A52A3007DD659 /* TransformUtils.h in Headers */, + 473FCBFC156A52A3007DD659 /* uthash.h in Headers */, + 473FCBFD156A52A3007DD659 /* utlist.h in Headers */, + 473FCBFE156A52A3007DD659 /* ZipUtils.h in Headers */, + 473FCC23156A52FF007DD659 /* aabb.h in Headers */, + 473FCC24156A52FF007DD659 /* mat4stack.h in Headers */, + 473FCC25156A52FF007DD659 /* matrix.h in Headers */, + 473FCC26156A52FF007DD659 /* kazmath.h in Headers */, + 473FCC27156A52FF007DD659 /* mat3.h in Headers */, + 473FCC28156A52FF007DD659 /* mat4.h in Headers */, + 473FCC29156A52FF007DD659 /* neon_matrix_impl.h in Headers */, + 473FCC2A156A52FF007DD659 /* plane.h in Headers */, + 473FCC2B156A52FF007DD659 /* quaternion.h in Headers */, + 473FCC2C156A52FF007DD659 /* ray2.h in Headers */, + 473FCC2D156A52FF007DD659 /* utility.h in Headers */, + 473FCC2E156A52FF007DD659 /* vec2.h in Headers */, + 473FCC2F156A52FF007DD659 /* vec3.h in Headers */, + 473FCC30156A52FF007DD659 /* vec4.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1093,7 +1317,7 @@ ); name = Example; productName = Example; - productReference = 1D6058910D05DD3D006BFB54 /* Example.app */; + productReference = 1D6058910D05DD3D006BFB54 /* CCBlade.app */; productType = "com.apple.product-type.application"; }; 506EE05D10304ED200A389B3 /* cocos2d libraries */ = { @@ -1144,7 +1368,6 @@ buildActionMask = 2147483647; files = ( 50F414F01069373D002A0D5E /* Default.png in Resources */, - 50F414F11069373D002A0D5E /* fps_images.png in Resources */, 50F414F21069373D002A0D5E /* Icon.png in Resources */, E02BB504126CA50F006E46A2 /* Icon@2x.png in Resources */, E02BB505126CA50F006E46A2 /* Icon-Small@2x.png in Resources */, @@ -1159,6 +1382,9 @@ 47B802CD13F269D9006B0B98 /* streak2-hd.png in Resources */, 47B802CE13F269D9006B0B98 /* streak3-hd.png in Resources */, 47B802D013F26A4C006B0B98 /* Default-hd.png in Resources */, + 473FCC4C156A6DC4007DD659 /* fps_images.png in Resources */, + 473FCC4D156A6DC4007DD659 /* fps_images-hd.png in Resources */, + 473FCC4E156A6DC4007DD659 /* fps_images-ipadhd.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1171,10 +1397,9 @@ files = ( 1D60589B0D05DD56006BFB54 /* main.m in Sources */, 1F3B9A2D0EF2145700286867 /* ExampleAppDelegate.m in Sources */, - 506EDC31102F528A00A389B3 /* HelloWorldScene.m in Sources */, - E0F80F60120A0182005866B8 /* RootViewController.m in Sources */, 47B71D60137130530008113A /* CCBlade.m in Sources */, 47B71D61137130530008113A /* TouchTrailLayer.m in Sources */, + 473FCC44156A6B03007DD659 /* HelloWorldLayer.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1202,83 +1427,99 @@ 507ED64011C638C6002ED3FC /* CDOpenALSupport.m in Sources */, 507ED64211C638C6002ED3FC /* CocosDenshion.m in Sources */, 507ED64411C638C6002ED3FC /* SimpleAudioEngine.m in Sources */, - E02BB810126CC224006E46A2 /* CCAction.m in Sources */, - E02BB812126CC224006E46A2 /* CCActionCamera.m in Sources */, - E02BB814126CC224006E46A2 /* CCActionEase.m in Sources */, - E02BB816126CC224006E46A2 /* CCActionGrid.m in Sources */, - E02BB818126CC224006E46A2 /* CCActionGrid3D.m in Sources */, - E02BB81A126CC224006E46A2 /* CCActionInstant.m in Sources */, - E02BB81C126CC224006E46A2 /* CCActionInterval.m in Sources */, - E02BB81E126CC224006E46A2 /* CCActionManager.m in Sources */, - E02BB820126CC224006E46A2 /* CCActionPageTurn3D.m in Sources */, - E02BB822126CC224006E46A2 /* CCActionProgressTimer.m in Sources */, - E02BB824126CC224006E46A2 /* CCActionTiledGrid.m in Sources */, - E02BB826126CC224006E46A2 /* CCActionTween.m in Sources */, - E02BB828126CC224006E46A2 /* CCAnimation.m in Sources */, - E02BB82A126CC224006E46A2 /* CCAnimationCache.m in Sources */, - E02BB82C126CC224006E46A2 /* CCAtlasNode.m in Sources */, - E02BB82E126CC224006E46A2 /* CCBlockSupport.m in Sources */, - E02BB830126CC224006E46A2 /* CCCamera.m in Sources */, - E02BB832126CC224006E46A2 /* CCCompatibility.m in Sources */, - E02BB835126CC224006E46A2 /* CCConfiguration.m in Sources */, - E02BB837126CC224006E46A2 /* CCDirector.m in Sources */, - E02BB839126CC224006E46A2 /* CCDrawingPrimitives.m in Sources */, - E02BB83B126CC224006E46A2 /* CCGrabber.m in Sources */, - E02BB83D126CC224006E46A2 /* CCGrid.m in Sources */, - E02BB83F126CC224006E46A2 /* CCLabelAtlas.m in Sources */, - E02BB841126CC224006E46A2 /* CCLabelBMFont.m in Sources */, - E02BB843126CC224006E46A2 /* CCLabelTTF.m in Sources */, - E02BB845126CC224006E46A2 /* CCLayer.m in Sources */, - E02BB848126CC224006E46A2 /* CCMenu.m in Sources */, - E02BB84A126CC224006E46A2 /* CCMenuItem.m in Sources */, - E02BB84C126CC224006E46A2 /* CCMotionStreak.m in Sources */, - E02BB84E126CC224006E46A2 /* CCNode.m in Sources */, - E02BB850126CC224006E46A2 /* CCParallaxNode.m in Sources */, - E02BB852126CC224006E46A2 /* CCParticleExamples.m in Sources */, - E02BB854126CC224006E46A2 /* CCParticleSystem.m in Sources */, - E02BB856126CC224006E46A2 /* CCParticleSystemPoint.m in Sources */, - E02BB858126CC224006E46A2 /* CCParticleSystemQuad.m in Sources */, - E02BB85A126CC224006E46A2 /* CCProgressTimer.m in Sources */, - E02BB85D126CC224006E46A2 /* CCRenderTexture.m in Sources */, - E02BB85F126CC224006E46A2 /* CCRibbon.m in Sources */, - E02BB861126CC224006E46A2 /* CCScene.m in Sources */, - E02BB863126CC224006E46A2 /* CCScheduler.m in Sources */, - E02BB865126CC224006E46A2 /* CCSprite.m in Sources */, - E02BB867126CC224006E46A2 /* CCSpriteBatchNode.m in Sources */, - E02BB869126CC224006E46A2 /* CCSpriteFrame.m in Sources */, - E02BB86B126CC224006E46A2 /* CCSpriteFrameCache.m in Sources */, - E02BB86D126CC224006E46A2 /* CCSpriteSheet.m in Sources */, - E02BB86F126CC224006E46A2 /* CCTexture2D.m in Sources */, - E02BB871126CC224006E46A2 /* CCTextureAtlas.m in Sources */, - E02BB873126CC224006E46A2 /* CCTextureCache.m in Sources */, - E02BB875126CC224006E46A2 /* CCTexturePVR.m in Sources */, - E02BB877126CC224006E46A2 /* CCTileMapAtlas.m in Sources */, - E02BB879126CC224006E46A2 /* CCTMXLayer.m in Sources */, - E02BB87B126CC224006E46A2 /* CCTMXObjectGroup.m in Sources */, - E02BB87D126CC224006E46A2 /* CCTMXTiledMap.m in Sources */, - E02BB87F126CC224006E46A2 /* CCTMXXMLParser.m in Sources */, - E02BB881126CC224006E46A2 /* CCTransition.m in Sources */, - E02BB883126CC224006E46A2 /* CCTransitionPageTurn.m in Sources */, - E02BB885126CC224006E46A2 /* CCTransitionRadial.m in Sources */, - E02BB888126CC224006E46A2 /* cocos2d.m in Sources */, - E02BB88C126CC224006E46A2 /* CCDirectorIOS.m in Sources */, - E02BB88F126CC224006E46A2 /* CCTouchDispatcher.m in Sources */, - E02BB891126CC224006E46A2 /* CCTouchHandler.m in Sources */, - E02BB893126CC224006E46A2 /* EAGLView.m in Sources */, - E02BB895126CC224006E46A2 /* ES1Renderer.m in Sources */, - E02BB897126CC224006E46A2 /* glu.c in Sources */, - E02BB89A126CC224006E46A2 /* CCDirectorMac.m in Sources */, - E02BB89C126CC224006E46A2 /* CCEventDispatcher.m in Sources */, - E02BB89E126CC224006E46A2 /* MacGLView.m in Sources */, - E02BB89F126CC224006E46A2 /* base64.c in Sources */, - E02BB8A2126CC224006E46A2 /* CCArray.m in Sources */, - E02BB8A5126CC224006E46A2 /* CCFileUtils.m in Sources */, - E02BB8A7126CC224006E46A2 /* CCProfiling.m in Sources */, - E02BB8A8126CC224006E46A2 /* ccUtils.c in Sources */, - E02BB8AB126CC224006E46A2 /* CGPointExtension.m in Sources */, - E02BB8AE126CC224006E46A2 /* TGAlib.m in Sources */, - E02BB8B0126CC224006E46A2 /* TransformUtils.m in Sources */, - E02BB8B4126CC224006E46A2 /* ZipUtils.m in Sources */, + 473FCB48156A52A3007DD659 /* CCAction.m in Sources */, + 473FCB4A156A52A3007DD659 /* CCActionCamera.m in Sources */, + 473FCB4C156A52A3007DD659 /* CCActionEase.m in Sources */, + 473FCB4E156A52A3007DD659 /* CCActionGrid.m in Sources */, + 473FCB50156A52A3007DD659 /* CCActionGrid3D.m in Sources */, + 473FCB52156A52A3007DD659 /* CCActionInstant.m in Sources */, + 473FCB54156A52A3007DD659 /* CCActionInterval.m in Sources */, + 473FCB56156A52A3007DD659 /* CCActionManager.m in Sources */, + 473FCB58156A52A3007DD659 /* CCActionPageTurn3D.m in Sources */, + 473FCB5A156A52A3007DD659 /* CCActionProgressTimer.m in Sources */, + 473FCB5C156A52A3007DD659 /* CCActionTiledGrid.m in Sources */, + 473FCB5E156A52A3007DD659 /* CCActionTween.m in Sources */, + 473FCB60156A52A3007DD659 /* CCAnimation.m in Sources */, + 473FCB62156A52A3007DD659 /* CCAnimationCache.m in Sources */, + 473FCB64156A52A3007DD659 /* CCAtlasNode.m in Sources */, + 473FCB66156A52A3007DD659 /* CCCamera.m in Sources */, + 473FCB69156A52A3007DD659 /* CCConfiguration.m in Sources */, + 473FCB6B156A52A3007DD659 /* ccDeprecated.m in Sources */, + 473FCB6D156A52A3007DD659 /* CCDirector.m in Sources */, + 473FCB6F156A52A3007DD659 /* CCDrawingPrimitives.m in Sources */, + 473FCB71156A52A3007DD659 /* CCGLProgram.m in Sources */, + 473FCB73156A52A3007DD659 /* ccGLStateCache.m in Sources */, + 473FCB75156A52A3007DD659 /* CCGrabber.m in Sources */, + 473FCB77156A52A3007DD659 /* CCGrid.m in Sources */, + 473FCB79156A52A3007DD659 /* CCLabelAtlas.m in Sources */, + 473FCB7B156A52A3007DD659 /* CCLabelBMFont.m in Sources */, + 473FCB7D156A52A3007DD659 /* CCLabelTTF.m in Sources */, + 473FCB7F156A52A3007DD659 /* CCLayer.m in Sources */, + 473FCB82156A52A3007DD659 /* CCMenu.m in Sources */, + 473FCB84156A52A3007DD659 /* CCMenuItem.m in Sources */, + 473FCB86156A52A3007DD659 /* CCMotionStreak.m in Sources */, + 473FCB88156A52A3007DD659 /* CCNode.m in Sources */, + 473FCB8A156A52A3007DD659 /* CCParallaxNode.m in Sources */, + 473FCB8C156A52A3007DD659 /* CCParticleBatchNode.m in Sources */, + 473FCB8E156A52A3007DD659 /* CCParticleExamples.m in Sources */, + 473FCB90156A52A3007DD659 /* CCParticleSystem.m in Sources */, + 473FCB92156A52A3007DD659 /* CCParticleSystemQuad.m in Sources */, + 473FCB94156A52A3007DD659 /* CCProgressTimer.m in Sources */, + 473FCB97156A52A3007DD659 /* CCRenderTexture.m in Sources */, + 473FCB99156A52A3007DD659 /* CCScene.m in Sources */, + 473FCB9B156A52A3007DD659 /* CCScheduler.m in Sources */, + 473FCBAA156A52A3007DD659 /* CCShaderCache.m in Sources */, + 473FCBAC156A52A3007DD659 /* ccShaders.m in Sources */, + 473FCBAE156A52A3007DD659 /* CCSprite.m in Sources */, + 473FCBB0156A52A3007DD659 /* CCSpriteBatchNode.m in Sources */, + 473FCBB2156A52A3007DD659 /* CCSpriteFrame.m in Sources */, + 473FCBB4156A52A3007DD659 /* CCSpriteFrameCache.m in Sources */, + 473FCBB6156A52A3007DD659 /* CCTexture2D.m in Sources */, + 473FCBB8156A52A3007DD659 /* CCTextureAtlas.m in Sources */, + 473FCBBA156A52A3007DD659 /* CCTextureCache.m in Sources */, + 473FCBBC156A52A3007DD659 /* CCTexturePVR.m in Sources */, + 473FCBBE156A52A3007DD659 /* CCTileMapAtlas.m in Sources */, + 473FCBC0156A52A3007DD659 /* CCTMXLayer.m in Sources */, + 473FCBC2156A52A3007DD659 /* CCTMXObjectGroup.m in Sources */, + 473FCBC4156A52A3007DD659 /* CCTMXTiledMap.m in Sources */, + 473FCBC6156A52A3007DD659 /* CCTMXXMLParser.m in Sources */, + 473FCBC8156A52A3007DD659 /* CCTransition.m in Sources */, + 473FCBCA156A52A3007DD659 /* CCTransitionPageTurn.m in Sources */, + 473FCBCC156A52A3007DD659 /* CCTransitionProgress.m in Sources */, + 473FCBCF156A52A3007DD659 /* cocos2d.m in Sources */, + 473FCBD3156A52A3007DD659 /* CCDirectorIOS.m in Sources */, + 473FCBD5156A52A3007DD659 /* CCES2Renderer.m in Sources */, + 473FCBD8156A52A3007DD659 /* CCGLView.m in Sources */, + 473FCBDB156A52A3007DD659 /* CCTouchDispatcher.m in Sources */, + 473FCBDD156A52A3007DD659 /* CCTouchHandler.m in Sources */, + 473FCBDF156A52A3007DD659 /* CCDirectorMac.m in Sources */, + 473FCBE1156A52A3007DD659 /* CCEventDispatcher.m in Sources */, + 473FCBE3156A52A3007DD659 /* CCGLView.m in Sources */, + 473FCBE5156A52A3007DD659 /* CCWindow.m in Sources */, + 473FCBE6156A52A3007DD659 /* base64.c in Sources */, + 473FCBE9156A52A3007DD659 /* CCArray.m in Sources */, + 473FCBEC156A52A3007DD659 /* CCFileUtils.m in Sources */, + 473FCBEE156A52A3007DD659 /* CCProfiling.m in Sources */, + 473FCBEF156A52A3007DD659 /* ccUtils.c in Sources */, + 473FCBF2156A52A3007DD659 /* CCVertex.m in Sources */, + 473FCBF4156A52A3007DD659 /* CGPointExtension.m in Sources */, + 473FCBF6156A52A3007DD659 /* NSThread+performBlock.m in Sources */, + 473FCBF9156A52A3007DD659 /* TGAlib.m in Sources */, + 473FCBFB156A52A3007DD659 /* TransformUtils.m in Sources */, + 473FCBFF156A52A3007DD659 /* ZipUtils.m in Sources */, + 473FCC31156A52FF007DD659 /* aabb.c in Sources */, + 473FCC32156A52FF007DD659 /* mat4stack.c in Sources */, + 473FCC33156A52FF007DD659 /* matrix.c in Sources */, + 473FCC34156A52FF007DD659 /* mat3.c in Sources */, + 473FCC35156A52FF007DD659 /* mat4.c in Sources */, + 473FCC36156A52FF007DD659 /* neon_matrix_impl.c in Sources */, + 473FCC37156A52FF007DD659 /* plane.c in Sources */, + 473FCC38156A52FF007DD659 /* quaternion.c in Sources */, + 473FCC39156A52FF007DD659 /* ray2.c in Sources */, + 473FCC3A156A52FF007DD659 /* utility.c in Sources */, + 473FCC3B156A52FF007DD659 /* vec2.c in Sources */, + 473FCC3C156A52FF007DD659 /* vec3.c in Sources */, + 473FCC3D156A52FF007DD659 /* vec4.c in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1306,12 +1547,14 @@ GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = Example_Prefix.pch; GCC_TREAT_WARNINGS_AS_ERRORS = NO; + GCC_VERSION = com.apple.compilers.llvm.clang.1_0; + HEADER_SEARCH_PATHS = "\"libs/kazmath/include\""; INFOPLIST_FILE = Resources/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 3.1; ONLY_ACTIVE_ARCH = YES; OTHER_LDFLAGS = ""; PREBINDING = NO; - PRODUCT_NAME = Example; + PRODUCT_NAME = CCBlade; "PROVISIONING_PROFILE[sdk=iphoneos*]" = "9FC23DC7-CB28-4671-9494-EB7B1F3ABCBE"; TARGETED_DEVICE_FAMILY = 1; WARNING_CFLAGS = "-Wall"; @@ -1329,6 +1572,8 @@ GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = Example_Prefix.pch; GCC_TREAT_WARNINGS_AS_ERRORS = NO; + GCC_VERSION = com.apple.compilers.llvm.clang.1_0; + HEADER_SEARCH_PATHS = "\"libs/kazmath/include\""; INFOPLIST_FILE = Resources/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 3.1; ONLY_ACTIVE_ARCH = NO; @@ -1337,7 +1582,7 @@ "-ObjC", ); PREBINDING = NO; - PRODUCT_NAME = Example; + PRODUCT_NAME = CCBlade; "PROVISIONING_PROFILE[sdk=iphoneos*]" = "9FC23DC7-CB28-4671-9494-EB7B1F3ABCBE"; TARGETED_DEVICE_FAMILY = 1; WARNING_CFLAGS = "-Wall"; @@ -1352,6 +1597,8 @@ GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_TREAT_WARNINGS_AS_ERRORS = NO; + GCC_VERSION = com.apple.compilers.llvm.clang.1_0; + HEADER_SEARCH_PATHS = "\"libs/kazmath/include\""; PREBINDING = NO; PRODUCT_NAME = "cocos2d libraries"; }; @@ -1365,6 +1612,8 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_ENABLE_FIX_AND_CONTINUE = NO; GCC_TREAT_WARNINGS_AS_ERRORS = NO; + GCC_VERSION = com.apple.compilers.llvm.clang.1_0; + HEADER_SEARCH_PATHS = "\"libs/kazmath/include\""; PREBINDING = NO; PRODUCT_NAME = "cocos2d libraries"; ZERO_LINK = NO; diff --git a/Example/libs/cocos2d/CCAction.h b/Example/libs/cocos2d/CCAction.h index 327a251..f1da6b8 100644 --- a/Example/libs/cocos2d/CCAction.h +++ b/Example/libs/cocos2d/CCAction.h @@ -2,6 +2,7 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -9,10 +10,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -51,7 +52,7 @@ enum { @property (nonatomic,readonly,assign) id target; /** The original target, since target can be nil. - Is the target that were used to run the action. Unless you are doing something complex, like ActionManager, you should NOT call this method. + Is the target that were used to run the action. Unless you are doing something complex, like CCActionManager, you should NOT call this method. @since v0.8.2 */ @property (nonatomic,readonly,assign) id originalTarget; @@ -75,10 +76,10 @@ enum { //! called after the action has finished. It will set the 'target' to nil. //! IMPORTANT: You should never call "[action stop]" manually. Instead, use: "[target stopAction:action];" -(void) stop; -//! called every frame with it's delta time. DON'T override unless you know what you are doing. +//! called every frame with its delta time. DON'T override unless you know what you are doing. -(void) step: (ccTime) dt; //! called once per frame. time a value between 0 and 1 -//! For example: +//! For example: //! * 0 means that the action just started //! * 0.5 means that the action is in the middle //! * 1 means that the action is over @@ -112,38 +113,44 @@ enum { */ @interface CCRepeatForever : CCAction { - CCActionInterval *other; + CCActionInterval *innerAction_; } +/** Inner action */ +@property (nonatomic, readwrite, retain) CCActionInterval *innerAction; + /** creates the action */ +(id) actionWithAction: (CCActionInterval*) action; /** initializes the action */ -(id) initWithAction: (CCActionInterval*) action; @end -/** Changes the speed of an action, making it take longer (speed>1) - or less (speed<1) time. +/** Changes the speed of an action, making it take longer (speed<1) + or less (speed>1) time. Useful to simulate 'slow motion' or 'fast forward' effect. - @warning This action can't be Sequenceable because it is not an IntervalAction + @warning This action can't be Sequenceable because it is not an CCIntervalAction */ @interface CCSpeed : CCAction { - CCActionInterval *other; - float speed; + CCActionInterval *innerAction_; + float speed_; } /** alter the speed of the inner function in runtime */ @property (nonatomic,readwrite) float speed; +/** Inner action of CCSpeed */ +@property (nonatomic, readwrite, retain) CCActionInterval *innerAction; + /** creates the action */ -+(id) actionWithAction: (CCActionInterval*) action speed:(float)rate; ++(id) actionWithAction: (CCActionInterval*) action speed:(float)value; /** initializes the action */ --(id) initWithAction: (CCActionInterval*) action speed:(float)rate; +-(id) initWithAction: (CCActionInterval*) action speed:(float)value; @end @class CCNode; /** CCFollow is an action that "follows" a node. - + Eg: [layer runAction: [CCFollow actionWithTarget:hero]]; - + Instead of using CCCamera as a "follower", use this action instead. @since v0.99.2 */ @@ -151,17 +158,17 @@ enum { { /* node to follow */ CCNode *followedNode_; - + /* whether camera should be limited to certain area */ BOOL boundarySet; - + /* if screensize is bigger than the boundary - update not needed */ BOOL boundaryFullyCovered; - + /* fast access to the screen dimensions */ CGPoint halfScreenSize; CGPoint fullScreenSize; - + /* world boundaries */ float leftBoundary; float rightBoundary; diff --git a/Example/libs/cocos2d/CCAction.m b/Example/libs/cocos2d/CCAction.m index 8fc3b4c..a1765da 100644 --- a/Example/libs/cocos2d/CCAction.m +++ b/Example/libs/cocos2d/CCAction.m @@ -2,6 +2,7 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -9,10 +10,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,8 +25,6 @@ */ - -#import #import "CCDirector.h" #import "ccMacros.h" #import "CCAction.h" @@ -48,7 +47,7 @@ +(id) action -(id) init { - if( (self=[super init]) ) { + if( (self=[super init]) ) { originalTarget_ = target_ = nil; tag_ = kCCActionTagInvalid; } @@ -90,12 +89,12 @@ -(BOOL) isDone -(void) step: (ccTime) dt { - NSLog(@"[Action step]. override me"); + CCLOG(@"[Action step]. override me"); } -(void) update: (ccTime) time { - NSLog(@"[Action update]. override me"); + CCLOG(@"[Action update]. override me"); } @end @@ -121,6 +120,7 @@ - (CCFiniteTimeAction*) reverse #pragma mark - #pragma mark RepeatForever @implementation CCRepeatForever +@synthesize innerAction=innerAction_; +(id) actionWithAction: (CCActionInterval*) action { return [[[self alloc] initWithAction: action] autorelease]; @@ -128,39 +128,40 @@ +(id) actionWithAction: (CCActionInterval*) action -(id) initWithAction: (CCActionInterval*) action { - if( (self=[super init]) ) - other = [action retain]; + if( (self=[super init]) ) + self.innerAction = action; return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithAction:[[other copy] autorelease] ]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithAction:[[innerAction_ copy] autorelease] ]; return copy; } -(void) dealloc { - [other release]; + [innerAction_ release]; [super dealloc]; } -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - [other startWithTarget:target_]; + [innerAction_ startWithTarget:target_]; } -(void) step:(ccTime) dt { - [other step: dt]; - if( [other isDone] ) { - ccTime diff = dt + other.duration - other.elapsed; - [other startWithTarget:target_]; - - // to prevent jerk. issue #390 - [other step: diff]; + [innerAction_ step: dt]; + if( [innerAction_ isDone] ) { + ccTime diff = innerAction_.elapsed - innerAction_.duration; + [innerAction_ startWithTarget:target_]; + + // to prevent jerk. issue #390, 1247 + [innerAction_ step: 0.0f]; + [innerAction_ step: diff]; } } @@ -172,9 +173,8 @@ -(BOOL) isDone - (CCActionInterval *) reverse { - return [CCRepeatForever actionWithAction:[other reverse]]; + return [CCRepeatForever actionWithAction:[innerAction_ reverse]]; } - @end // @@ -183,59 +183,60 @@ - (CCActionInterval *) reverse #pragma mark - #pragma mark Speed @implementation CCSpeed -@synthesize speed; +@synthesize speed=speed_; +@synthesize innerAction=innerAction_; -+(id) actionWithAction: (CCActionInterval*) action speed:(float)r ++(id) actionWithAction: (CCActionInterval*) action speed:(float)value { - return [[[self alloc] initWithAction: action speed:r] autorelease]; + return [[[self alloc] initWithAction: action speed:value] autorelease]; } --(id) initWithAction: (CCActionInterval*) action speed:(float)r +-(id) initWithAction: (CCActionInterval*) action speed:(float)value { if( (self=[super init]) ) { - other = [action retain]; - speed = r; + self.innerAction = action; + speed_ = value; } return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithAction:[[other copy] autorelease] speed:speed]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithAction:[[innerAction_ copy] autorelease] speed:speed_]; return copy; } -(void) dealloc { - [other release]; + [innerAction_ release]; [super dealloc]; } -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - [other startWithTarget:target_]; + [innerAction_ startWithTarget:target_]; } -(void) stop { - [other stop]; + [innerAction_ stop]; [super stop]; } -(void) step:(ccTime) dt { - [other step: dt * speed]; + [innerAction_ step: dt * speed_]; } -(BOOL) isDone { - return [other isDone]; + return [innerAction_ isDone]; } - (CCActionInterval *) reverse { - return [CCSpeed actionWithAction:[other reverse] speed:speed]; + return [CCSpeed actionWithAction:[innerAction_ reverse] speed:speed_]; } @end @@ -261,36 +262,36 @@ +(id) actionWithTarget:(CCNode *) fNode worldBoundary:(CGRect)rect -(id) initWithTarget:(CCNode *)fNode { if( (self=[super init]) ) { - + followedNode_ = [fNode retain]; boundarySet = FALSE; boundaryFullyCovered = FALSE; - + CGSize s = [[CCDirector sharedDirector] winSize]; fullScreenSize = CGPointMake(s.width, s.height); halfScreenSize = ccpMult(fullScreenSize, .5f); } - + return self; } -(id) initWithTarget:(CCNode *)fNode worldBoundary:(CGRect)rect { if( (self=[super init]) ) { - + followedNode_ = [fNode retain]; boundarySet = TRUE; boundaryFullyCovered = FALSE; - + CGSize winSize = [[CCDirector sharedDirector] winSize]; fullScreenSize = CGPointMake(winSize.width, winSize.height); halfScreenSize = ccpMult(fullScreenSize, .5f); - + leftBoundary = -((rect.origin.x+rect.size.width) - fullScreenSize.x); rightBoundary = -rect.origin.x ; topBoundary = -rect.origin.y; bottomBoundary = -((rect.origin.y+rect.size.height) - fullScreenSize.y); - + if(rightBoundary < leftBoundary) { // screen width is larger than world's boundary width @@ -303,11 +304,11 @@ -(id) initWithTarget:(CCNode *)fNode worldBoundary:(CGRect)rect //set both in the middle of the world topBoundary = bottomBoundary = (topBoundary + bottomBoundary) / 2; } - + if( (topBoundary == bottomBoundary) && (leftBoundary == rightBoundary) ) boundaryFullyCovered = TRUE; } - + return self; } @@ -320,21 +321,17 @@ -(id) copyWithZone: (NSZone*) zone -(void) step:(ccTime) dt { -#define CLAMP(x,y,z) MIN(MAX(x,y),z) - if(boundarySet) { // whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased if(boundaryFullyCovered) return; - + CGPoint tempPos = ccpSub( halfScreenSize, followedNode_.position); - [target_ setPosition:ccp(CLAMP(tempPos.x,leftBoundary,rightBoundary), CLAMP(tempPos.y,bottomBoundary,topBoundary))]; + [target_ setPosition:ccp(clampf(tempPos.x,leftBoundary,rightBoundary), clampf(tempPos.y,bottomBoundary,topBoundary))]; } else [target_ setPosition:ccpSub( halfScreenSize, followedNode_.position )]; - -#undef CLAMP } diff --git a/Example/libs/cocos2d/CCActionCamera.h b/Example/libs/cocos2d/CCActionCamera.h index 131c084..3c3934c 100644 --- a/Example/libs/cocos2d/CCActionCamera.h +++ b/Example/libs/cocos2d/CCActionCamera.h @@ -2,6 +2,7 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -9,10 +10,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,15 +31,15 @@ /** Base class for CCCamera actions */ @interface CCActionCamera : CCActionInterval -{ +{ float centerXOrig_; float centerYOrig_; float centerZOrig_; - + float eyeXOrig_; float eyeYOrig_; float eyeZOrig_; - + float upXOrig_; float upYOrig_; float upZOrig_; @@ -56,12 +57,12 @@ float deltaAngleZ_; float angleX_; float deltaAngleX_; - + float radZ_; float radDeltaZ_; float radX_; float radDeltaX_; - + } /** creates a CCOrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX */ +(id) actionWithDuration:(float) t radius:(float)r deltaRadius:(float) dr angleZ:(float)z deltaAngleZ:(float)dz angleX:(float)x deltaAngleX:(float)dx; diff --git a/Example/libs/cocos2d/CCActionCamera.m b/Example/libs/cocos2d/CCActionCamera.m index 5134c6f..c46f239 100644 --- a/Example/libs/cocos2d/CCActionCamera.m +++ b/Example/libs/cocos2d/CCActionCamera.m @@ -2,6 +2,7 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -9,10 +10,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -64,7 +65,7 @@ -(id) copyWithZone: (NSZone*) zone -(id) initWithDuration:(float)t radius:(float)r deltaRadius:(float) dr angleZ:(float)z deltaAngleZ:(float)dz angleX:(float)x deltaAngleX:(float)dx { if((self=[super initWithDuration:t]) ) { - + radius_ = r; deltaRadius_ = dr; angleZ_ = z; @@ -75,7 +76,7 @@ -(id) initWithDuration:(float)t radius:(float)r deltaRadius:(float) dr angleZ:(f radDeltaZ_ = (CGFloat)CC_DEGREES_TO_RADIANS(dz); radDeltaX_ = (CGFloat)CC_DEGREES_TO_RADIANS(dx); } - + return self; } @@ -83,16 +84,16 @@ -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; float r, zenith, azimuth; - + [self sphericalRadius: &r zenith:&zenith azimuth:&azimuth]; - + #if 0 // isnan() is not supported on the simulator, and isnan() always returns false. if( isnan(radius_) ) radius_ = r; - + if( isnan( angleZ_) ) angleZ_ = (CGFloat)CC_RADIANS_TO_DEGREES(zenith); - + if( isnan( angleX_ ) ) angleX_ = (CGFloat)CC_RADIANS_TO_DEGREES(azimuth); #endif @@ -111,7 +112,7 @@ -(void) update: (ccTime) dt float j = sinf(za) * sinf(xa) * r + centerYOrig_; float k = cosf(za) * r + centerZOrig_; - [[target_ camera] setEyeX:i eyeY:j eyeZ:k]; + [[target_ camera] setEyeX:i eyeY:j eyeZ:k]; } -(void) sphericalRadius:(float*) newRadius zenith:(float*) zenith azimuth:(float*) azimuth @@ -119,15 +120,15 @@ -(void) sphericalRadius:(float*) newRadius zenith:(float*) zenith azimuth:(float float ex, ey, ez, cx, cy, cz, x, y, z; float r; // radius float s; - + CCCamera *camera = [target_ camera]; [camera eyeX:&ex eyeY:&ey eyeZ:&ez]; [camera centerX:&cx centerY:&cy centerZ:&cz]; - + x = ex-cx; y = ey-cy; z = ez-cz; - + r = sqrtf( x*x + y*y + z*z); s = sqrtf( x*x + y*y); if(s==0.0f) @@ -140,7 +141,7 @@ -(void) sphericalRadius:(float*) newRadius zenith:(float*) zenith azimuth:(float *azimuth = (float)M_PI - asinf(y/s); else *azimuth = asinf(y/s); - - *newRadius = r / [CCCamera getZEye]; + + *newRadius = r / [CCCamera getZEye]; } @end diff --git a/Example/libs/cocos2d/CCActionEase.h b/Example/libs/cocos2d/CCActionEase.h index fced701..4c91e56 100644 --- a/Example/libs/cocos2d/CCActionEase.h +++ b/Example/libs/cocos2d/CCActionEase.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Example/libs/cocos2d/CCActionEase.m b/Example/libs/cocos2d/CCActionEase.m index f28be11..25b1cf0 100644 --- a/Example/libs/cocos2d/CCActionEase.m +++ b/Example/libs/cocos2d/CCActionEase.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -52,10 +52,10 @@ +(id) actionWithAction: (CCActionInterval*) action -(id) initWithAction: (CCActionInterval*) action { NSAssert( action!=nil, @"Ease: arguments must be non-nil"); - + if( (self=[super initWithDuration: action.duration]) ) other = [action retain]; - + return self; } @@ -112,7 +112,7 @@ -(id) initWithAction: (CCActionInterval*) action rate:(float)aRate { if( (self=[super initWithAction:action ]) ) self.rate = aRate; - + return self; } @@ -158,16 +158,14 @@ -(void) update: (ccTime) t // @implementation CCEaseInOut -(void) update: (ccTime) t -{ - int sign =1; - int r = (int) rate; - if (r % 2 == 0) - sign = -1; +{ t *= 2; - if (t < 1) + if (t < 1) { [other update: 0.5f * powf (t, rate)]; - else - [other update: sign*0.5f * (powf (t-2, rate) + sign*2)]; + } + else { + [other update: 1.0f - 0.5f * powf(2-t, rate)]; + } } // InOut and OutIn are symmetrical @@ -222,7 +220,7 @@ -(void) update: (ccTime) t t = 0.5f * powf(2, 10 * (t - 1)); else t = 0.5f * (-powf(2, -10 * (t -1) ) + 2); - + [other update:t]; } @end @@ -300,7 +298,7 @@ -(id) initWithAction: (CCActionInterval*) action period:(float)period { if( (self=[super initWithAction:action]) ) period_ = period; - + return self; } @@ -324,11 +322,11 @@ -(CCActionInterval*) reverse @implementation CCEaseElasticIn -(void) update: (ccTime) t -{ +{ ccTime newT = 0; if (t == 0 || t == 1) newT = t; - + else { float s = period_ / 4; t = t - 1; @@ -350,11 +348,11 @@ - (CCActionInterval*) reverse @implementation CCEaseElasticOut -(void) update: (ccTime) t -{ +{ ccTime newT = 0; if (t == 0 || t == 1) { newT = t; - + } else { float s = period_ / 4; newT = powf(2, -10 * t) * sinf( (t-s) *M_PI_X_2 / period_) + 1; @@ -376,7 +374,7 @@ @implementation CCEaseElasticInOut -(void) update: (ccTime) t { ccTime newT = 0; - + if( t == 0 || t == 1 ) newT = t; else { @@ -384,14 +382,14 @@ -(void) update: (ccTime) t if(! period_ ) period_ = 0.3f * 1.5f; ccTime s = period_ / 4; - + t = t -1; if( t < 0 ) newT = -0.5f * powf(2, 10 * t) * sinf((t - s) * M_PI_X_2 / period_); else newT = powf(2, -10 * t) * sinf((t - s) * M_PI_X_2 / period_) * 0.5f + 1; } - [other update:newT]; + [other update:newT]; } - (CCActionInterval*) reverse @@ -435,7 +433,7 @@ @implementation CCEaseBounceIn -(void) update: (ccTime) t { - ccTime newT = 1 - [self bounceTime:1-t]; + ccTime newT = 1 - [self bounceTime:1-t]; [other update:newT]; } @@ -450,7 +448,7 @@ @implementation CCEaseBounceOut -(void) update: (ccTime) t { - ccTime newT = [self bounceTime:t]; + ccTime newT = [self bounceTime:t]; [other update:newT]; } @@ -471,7 +469,7 @@ -(void) update: (ccTime) t newT = (1 - [self bounceTime:1-t] ) * 0.5f; } else newT = [self bounceTime:t * 2 - 1] * 0.5f + 0.5f; - + [other update:newT]; } @end @@ -503,7 +501,7 @@ @implementation CCEaseBackOut -(void) update: (ccTime) t { ccTime overshoot = 1.70158f; - + t = t - 1; [other update: t * t * ((overshoot + 1) * t + overshoot) + 1]; } @@ -522,7 +520,7 @@ @implementation CCEaseBackInOut -(void) update: (ccTime) t { ccTime overshoot = 1.70158f * 1.525f; - + t = t * 2; if (t < 1) [other update: (t * t * ((overshoot + 1) * t - overshoot)) / 2]; diff --git a/Example/libs/cocos2d/CCActionGrid.h b/Example/libs/cocos2d/CCActionGrid.h index 13b6bc7..244ee79 100644 --- a/Example/libs/cocos2d/CCActionGrid.h +++ b/Example/libs/cocos2d/CCActionGrid.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -87,8 +87,8 @@ /** CCAccelDeccelAmplitude action */ @interface CCAccelDeccelAmplitude : CCActionInterval { - float rate; - CCActionInterval *other; + float rate_; + CCActionInterval *other_; } /** amplitude rate */ @@ -106,8 +106,8 @@ /** CCAccelAmplitude action */ @interface CCAccelAmplitude : CCActionInterval { - float rate; - CCActionInterval *other; + float rate_; + CCActionInterval *other_; } /** amplitude rate */ @@ -125,8 +125,8 @@ /** CCDeccelAmplitude action */ @interface CCDeccelAmplitude : CCActionInterval { - float rate; - CCActionInterval *other; + float rate_; + CCActionInterval *other_; } /** amplitude rate */ @@ -156,7 +156,7 @@ /** CCReuseGrid action */ @interface CCReuseGrid : CCActionInstant { - int t; + int t_; } /** creates an action with the number of times that the current grid will be reused */ +(id) actionWithTimes: (int) times; diff --git a/Example/libs/cocos2d/CCActionGrid.m b/Example/libs/cocos2d/CCActionGrid.m index b2d8f98..fd87ac8 100644 --- a/Example/libs/cocos2d/CCActionGrid.m +++ b/Example/libs/cocos2d/CCActionGrid.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -45,19 +45,19 @@ -(id) initWithSize:(ccGridSize)gSize duration:(ccTime)d { gridSize_ = gSize; } - + return self; } --(void)startWithTarget:(id)aTarget +-(void)startWithTarget:(id)target { - [super startWithTarget:aTarget]; + [super startWithTarget:target]; CCGridBase *newgrid = [self grid]; - - CCNode *t = (CCNode*) target_; + + CCNode *t = (CCNode*) target; CCGridBase *targetGrid = [t grid]; - + if ( targetGrid && targetGrid.reuseGrid > 0 ) { if ( targetGrid.active && targetGrid.gridSize.x == gridSize_.x && targetGrid.gridSize.y == gridSize_.y && [targetGrid isKindOfClass:[newgrid class]] ) @@ -69,10 +69,10 @@ -(void)startWithTarget:(id)aTarget { if ( targetGrid && targetGrid.active ) targetGrid.active = NO; - - t.grid = newgrid; + + [t setGrid: newgrid]; t.grid.active = YES; - } + } } -(CCGridBase *)grid @@ -120,7 +120,7 @@ -(ccVertex3F)originalVertex:(ccGridSize)pos -(void)setVertex:(ccGridSize)pos vertex:(ccVertex3F)vertex { CCGrid3D *g = (CCGrid3D *)[target_ grid]; - return [g setVertex:pos vertex:vertex]; + [g setVertex:pos vertex:vertex]; } @end @@ -183,7 +183,7 @@ -(CGFloat)getAmplitudeRate @implementation CCAccelDeccelAmplitude -@synthesize rate; +@synthesize rate=rate_; +(id)actionWithAction:(CCAction*)action duration:(ccTime)d { @@ -194,42 +194,42 @@ -(id)initWithAction:(CCAction *)action duration:(ccTime)d { if ( (self = [super initWithDuration:d]) ) { - rate = 1.0f; - other = [action retain]; + rate_ = 1.0f; + other_ = (CCActionInterval*)[action retain]; } - + return self; } -(void)dealloc { - [other release]; + [other_ release]; [super dealloc]; } -(void)startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - [other startWithTarget:target_]; + [other_ startWithTarget:target_]; } -(void) update: (ccTime) time { float f = time*2; - + if (f > 1) { f -= 1; f = 1 - f; } - - [other setAmplitudeRate:powf(f, rate)]; - [other update:time]; + + [other_ setAmplitudeRate:powf(f, rate_)]; + [other_ update:time]; } - (CCActionInterval*) reverse { - return [CCAccelDeccelAmplitude actionWithAction:[other reverse] duration:duration_]; + return [CCAccelDeccelAmplitude actionWithAction:[other_ reverse] duration:duration_]; } @end @@ -241,7 +241,7 @@ - (CCActionInterval*) reverse @implementation CCAccelAmplitude -@synthesize rate; +@synthesize rate=rate_; +(id)actionWithAction:(CCAction*)action duration:(ccTime)d { @@ -252,34 +252,34 @@ -(id)initWithAction:(CCAction *)action duration:(ccTime)d { if ( (self = [super initWithDuration:d]) ) { - rate = 1.0f; - other = [action retain]; + rate_ = 1.0f; + other_ = (CCActionInterval*)[action retain]; } - + return self; } -(void)dealloc { - [other release]; + [other_ release]; [super dealloc]; } -(void)startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - [other startWithTarget:target_]; + [other_ startWithTarget:target_]; } -(void) update: (ccTime) time { - [other setAmplitudeRate:powf(time, rate)]; - [other update:time]; + [other_ setAmplitudeRate:powf(time, rate_)]; + [other_ update:time]; } - (CCActionInterval*) reverse { - return [CCAccelAmplitude actionWithAction:[other reverse] duration:self.duration]; + return [CCAccelAmplitude actionWithAction:[other_ reverse] duration:self.duration]; } @end @@ -291,7 +291,7 @@ - (CCActionInterval*) reverse @implementation CCDeccelAmplitude -@synthesize rate; +@synthesize rate=rate_; +(id)actionWithAction:(CCAction*)action duration:(ccTime)d { @@ -302,34 +302,34 @@ -(id)initWithAction:(CCAction *)action duration:(ccTime)d { if ( (self = [super initWithDuration:d]) ) { - rate = 1.0f; - other = [action retain]; + rate_ = 1.0f; + other_ = (CCActionInterval*)[action retain]; } - + return self; } -(void)dealloc { - [other release]; + [other_ release]; [super dealloc]; } -(void)startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - [other startWithTarget:target_]; + [other_ startWithTarget:target_]; } -(void) update: (ccTime) time { - [other setAmplitudeRate:powf((1-time), rate)]; - [other update:time]; + [other_ setAmplitudeRate:powf((1-time), rate_)]; + [other_ update:time]; } - (CCActionInterval*) reverse { - return [CCDeccelAmplitude actionWithAction:[other reverse] duration:self.duration]; + return [CCDeccelAmplitude actionWithAction:[other_ reverse] duration:self.duration]; } @end @@ -347,7 +347,7 @@ -(void)startWithTarget:(id)aTarget if ( [[self target] grid] && [[[self target] grid] active] ) { [[[self target] grid] setActive: NO]; - + // [[self target] setGrid: nil]; } } @@ -369,8 +369,8 @@ +(id)actionWithTimes:(int)times -(id)initWithTimes:(int)times { if ( (self = [super init]) ) - t = times; - + t_ = times; + return self; } @@ -380,7 +380,7 @@ -(void)startWithTarget:(id)aTarget CCNode *myTarget = (CCNode*) [self target]; if ( myTarget.grid && myTarget.grid.active ) - myTarget.grid.reuseGrid += t; + myTarget.grid.reuseGrid += t_; } @end diff --git a/Example/libs/cocos2d/CCActionGrid3D.h b/Example/libs/cocos2d/CCActionGrid3D.h index a8003f4..7e1c40e 100644 --- a/Example/libs/cocos2d/CCActionGrid3D.h +++ b/Example/libs/cocos2d/CCActionGrid3D.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -73,7 +73,6 @@ @interface CCLens3D : CCGrid3DAction { CGPoint position_; - CGPoint positionInPixels_; float radius_; float lensEffect_; BOOL dirty_; @@ -97,7 +96,6 @@ @interface CCRipple3D : CCGrid3DAction { CGPoint position_; - CGPoint positionInPixels_; float radius_; int waves_; float amplitude_; @@ -123,7 +121,7 @@ /** CCShaky3D action */ @interface CCShaky3D : CCGrid3DAction { - int randrange; + int randrange; BOOL shakeZ; } @@ -142,7 +140,7 @@ int waves; float amplitude; float amplitudeRate; - + } /** amplitude */ @@ -187,7 +185,6 @@ @interface CCTwirl : CCGrid3DAction { CGPoint position_; - CGPoint positionInPixels_; int twirls_; float amplitude_; float amplitudeRate_; diff --git a/Example/libs/cocos2d/CCActionGrid3D.m b/Example/libs/cocos2d/CCActionGrid3D.m index 1d4a783..e9fb707 100644 --- a/Example/libs/cocos2d/CCActionGrid3D.m +++ b/Example/libs/cocos2d/CCActionGrid3D.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -49,7 +49,7 @@ -(id)initWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gSize duration amplitude = amp; amplitudeRate = 1.0f; } - + return self; } @@ -63,7 +63,7 @@ -(id) copyWithZone: (NSZone*) zone -(void)update:(ccTime)time { int i, j; - + for( i = 0; i < (gridSize_.x+1); i++ ) { for( j = 0; j < (gridSize_.y+1); j++ ) @@ -99,7 +99,7 @@ -(id)initWithSize:(ccGridSize)gSize duration:(ccTime)d { [NSException raise:@"FlipX3D" format:@"Grid size must be (1,1)"]; } - + return [super initWithSize:gSize duration:d]; } @@ -116,17 +116,17 @@ -(void)update:(ccTime)time CGFloat mz = sinf( angle ); angle = angle / 2.0f; // x calculates degrees from 0 to 90 CGFloat mx = cosf( angle ); - + ccVertex3F v0, v1, v, diff; - + v0 = [self originalVertex:ccg(1,1)]; v1 = [self originalVertex:ccg(0,0)]; - + CGFloat x0 = v0.x; CGFloat x1 = v1.x; CGFloat x; ccGridSize a, b, c, d; - + if ( x0 > x1 ) { // Normal Grid @@ -145,28 +145,28 @@ -(void)update:(ccTime)time b = ccg(1,1); x = x1; } - + diff.x = ( x - x * mx ); diff.z = fabsf( floorf( (x * mz) / 4.0f ) ); - + // bottom-left v = [self originalVertex:a]; v.x = diff.x; v.z += diff.z; [self setVertex:a vertex:v]; - + // upper-left v = [self originalVertex:b]; v.x = diff.x; v.z += diff.z; [self setVertex:b vertex:v]; - + // bottom-right v = [self originalVertex:c]; v.x -= diff.x; v.z -= diff.z; [self setVertex:c vertex:v]; - + // upper-right v = [self originalVertex:d]; v.x -= diff.x; @@ -189,17 +189,17 @@ -(void)update:(ccTime)time CGFloat mz = sinf( angle ); angle = angle / 2.0f; // x calculates degrees from 0 to 90 CGFloat my = cosf( angle ); - + ccVertex3F v0, v1, v, diff; - + v0 = [self originalVertex:ccg(1,1)]; v1 = [self originalVertex:ccg(0,0)]; - + CGFloat y0 = v0.y; CGFloat y1 = v1.y; CGFloat y; ccGridSize a, b, c, d; - + if ( y0 > y1 ) { // Normal Grid @@ -218,28 +218,28 @@ -(void)update:(ccTime)time c = ccg(1,1); y = y1; } - + diff.y = y - y * my; diff.z = fabsf( floorf( (y * mz) / 4.0f ) ); - + // bottom-left v = [self originalVertex:a]; v.y = diff.y; v.z += diff.z; [self setVertex:a vertex:v]; - + // upper-left v = [self originalVertex:b]; v.y -= diff.y; v.z -= diff.z; [self setVertex:b vertex:v]; - + // bottom-right v = [self originalVertex:c]; v.y = diff.y; v.z += diff.z; [self setVertex:c vertex:v]; - + // upper-right v = [self originalVertex:d]; v.y -= diff.y; @@ -273,7 +273,7 @@ -(id)initWithPosition:(CGPoint)pos radius:(float)r grid:(ccGridSize)gSize durati lensEffect_ = 0.7f; dirty_ = YES; } - + return self; } @@ -287,9 +287,6 @@ -(void) setPosition:(CGPoint)pos { if( ! CGPointEqualToPoint(pos, position_) ) { position_ = pos; - positionInPixels_.x = pos.x * CC_CONTENT_SCALE_FACTOR(); - positionInPixels_.y = pos.y * CC_CONTENT_SCALE_FACTOR(); - dirty_ = YES; } } @@ -298,21 +295,21 @@ -(CGPoint) position { return position_; } - + -(void)update:(ccTime)time { if ( dirty_ ) { int i, j; - + for( i = 0; i < gridSize_.x+1; i++ ) { for( j = 0; j < gridSize_.y+1; j++ ) { ccVertex3F v = [self originalVertex:ccg(i,j)]; - CGPoint vect = ccpSub(positionInPixels_, ccp(v.x,v.y)); + CGPoint vect = ccpSub(position_, ccp(v.x,v.y)); CGFloat r = ccpLength(vect); - + if ( r < radius_ ) { r = radius_ - r; @@ -320,7 +317,7 @@ -(void)update:(ccTime)time if ( pre_log == 0 ) pre_log = 0.001f; float l = logf(pre_log) * lensEffect_; float new_r = expf( l ) * radius_; - + if ( ccpLength(vect) > 0 ) { vect = ccpNormalize(vect); @@ -328,11 +325,11 @@ -(void)update:(ccTime)time v.z += ccpLength(new_vect) * lensEffect_; } } - + [self setVertex:ccg(i,j) vertex:v]; } } - + dirty_ = NO; } } @@ -364,7 +361,7 @@ -(id)initWithPosition:(CGPoint)pos radius:(float)r waves:(int)wav amplitude:(flo amplitude_ = amp; amplitudeRate_ = 1.0f; } - + return self; } @@ -376,8 +373,6 @@ -(CGPoint) position -(void) setPosition:(CGPoint)pos { position_ = pos; - positionInPixels_.x = pos.x * CC_CONTENT_SCALE_FACTOR(); - positionInPixels_.y = pos.y * CC_CONTENT_SCALE_FACTOR(); } -(id) copyWithZone: (NSZone*) zone @@ -390,22 +385,22 @@ -(id) copyWithZone: (NSZone*) zone -(void)update:(ccTime)time { int i, j; - + for( i = 0; i < (gridSize_.x+1); i++ ) { for( j = 0; j < (gridSize_.y+1); j++ ) { ccVertex3F v = [self originalVertex:ccg(i,j)]; - CGPoint vect = ccpSub(positionInPixels_, ccp(v.x,v.y)); + CGPoint vect = ccpSub(position_, ccp(v.x,v.y)); CGFloat r = ccpLength(vect); - + if ( r < radius_ ) { r = radius_ - r; CGFloat rate = powf( r / radius_, 2); v.z += (sinf( time*(CGFloat)M_PI*waves_*2 + r * 0.1f) * amplitude_ * amplitudeRate_ * rate ); } - + [self setVertex:ccg(i,j) vertex:v]; } } @@ -432,7 +427,7 @@ -(id)initWithRange:(int)range shakeZ:(BOOL)sz grid:(ccGridSize)gSize duration:(c randrange = range; shakeZ = sz; } - + return self; } @@ -445,7 +440,7 @@ -(id) copyWithZone: (NSZone*) zone -(void)update:(ccTime)time { int i, j; - + for( i = 0; i < (gridSize_.x+1); i++ ) { for( j = 0; j < (gridSize_.y+1); j++ ) @@ -455,7 +450,7 @@ -(void)update:(ccTime)time v.y += ( rand() % (randrange*2) ) - randrange; if( shakeZ ) v.z += ( rand() % (randrange*2) ) - randrange; - + [self setVertex:ccg(i,j) vertex:v]; } } @@ -486,14 +481,14 @@ -(id)initWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gSize duration amplitude = amp; amplitudeRate = 1.0f; } - + return self; } -(void)update:(ccTime)time { int i, j; - + for( i = 1; i < gridSize_.x; i++ ) { for( j = 1; j < gridSize_.y; j++ ) @@ -504,7 +499,7 @@ -(void)update:(ccTime)time [self setVertex:ccg(i,j) vertex:v]; } } -} +} -(id) copyWithZone: (NSZone*) zone { @@ -539,26 +534,26 @@ -(id)initWithWaves:(int)wav amplitude:(float)amp horizontal:(BOOL)h vertical:(BO horizontal = h; vertical = v; } - + return self; } -(void)update:(ccTime)time { int i, j; - + for( i = 0; i < (gridSize_.x+1); i++ ) { for( j = 0; j < (gridSize_.y+1); j++ ) { ccVertex3F v = [self originalVertex:ccg(i,j)]; - + if ( vertical ) v.x = (v.x + (sinf(time*(CGFloat)M_PI*waves*2 + v.y * .01f) * amplitude * amplitudeRate)); - + if ( horizontal ) v.y = (v.y + (sinf(time*(CGFloat)M_PI*waves*2 + v.x * .01f) * amplitude * amplitudeRate)); - + [self setVertex:ccg(i,j) vertex:v]; } } @@ -596,15 +591,13 @@ -(id)initWithPosition:(CGPoint)pos twirls:(int)t amplitude:(float)amp grid:(ccGr amplitude_ = amp; amplitudeRate_ = 1.0f; } - + return self; } -(void) setPosition:(CGPoint)pos { position_ = pos; - positionInPixels_.x = pos.x * CC_CONTENT_SCALE_FACTOR(); - positionInPixels_.y = pos.y * CC_CONTENT_SCALE_FACTOR(); } -(CGPoint) position @@ -615,31 +608,31 @@ -(CGPoint) position -(void)update:(ccTime)time { int i, j; - CGPoint c = positionInPixels_; - + CGPoint c = position_; + for( i = 0; i < (gridSize_.x+1); i++ ) { for( j = 0; j < (gridSize_.y+1); j++ ) { ccVertex3F v = [self originalVertex:ccg(i,j)]; - + CGPoint avg = ccp(i-(gridSize_.x/2.0f), j-(gridSize_.y/2.0f)); CGFloat r = ccpLength( avg ); - + CGFloat amp = 0.1f * amplitude_ * amplitudeRate_; CGFloat a = r * cosf( (CGFloat)M_PI/2.0f + time * (CGFloat)M_PI * twirls_ * 2 ) * amp; - + float cosA = cosf(a); float sinA = sinf(a); - + CGPoint d = { sinA * (v.y-c.y) + cosA * (v.x-c.x), cosA * (v.y-c.y) - sinA * (v.x-c.x) }; - + v.x = c.x + d.x; v.y = c.y + d.y; - + [self setVertex:ccg(i,j) vertex:v]; } } diff --git a/Example/libs/cocos2d/CCActionInstant.h b/Example/libs/cocos2d/CCActionInstant.h index 40eb15f..928732b 100644 --- a/Example/libs/cocos2d/CCActionInstant.h +++ b/Example/libs/cocos2d/CCActionInstant.h @@ -2,6 +2,7 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -9,10 +10,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,7 +29,7 @@ /** Instant actions are immediate actions. They don't have a duration like the CCIntervalAction actions. -*/ +*/ @interface CCActionInstant : CCFiniteTimeAction { } @@ -96,6 +97,10 @@ id targetCallback_; SEL selector_; } + +/** Target that will be called */ +@property (nonatomic, readwrite, retain) id targetCallback; + /** creates the action with the callback */ +(id) actionWithTarget: (id) t selector:(SEL) s; /** initializes the action with the callback */ @@ -139,6 +144,9 @@ typedef void (*CC_CALLBACK_ND)(id, SEL, id, void *); { id object_; } +/** object to be passed as argument */ +@property (nonatomic, readwrite, retain) id object; + /** creates the action with the callback and the object to pass as an argument */ +(id) actionWithTarget: (id) t selector:(SEL) s object:(id)object; /** initializes the action with the callback and the object to pass as an argument */ @@ -148,8 +156,6 @@ typedef void (*CC_CALLBACK_ND)(id, SEL, id, void *); #pragma mark Blocks Support -#if NS_BLOCKS_AVAILABLE - /** Executes a callback using a block. */ @interface CCCallBlock : CCActionInstant @@ -194,4 +200,28 @@ typedef void (*CC_CALLBACK_ND)(id, SEL, id, void *); -(void) execute; @end -#endif +/** Executes a callback using a block with a single NSObject parameter. + @since v2.0 + */ +@interface CCCallBlockO : CCActionInstant +{ + void (^block_)(id object); + id object_; +} + +/** object to be passed to the block */ +@property (nonatomic,retain) id object; + +/** creates the action with the specified block, to be used as a callback. + The block will be "copied". + */ ++(id) actionWithBlock:(void(^)(id object))block object:(id)object; + +/** initialized the action with the specified block, to be used as a callback. + The block will be "copied". + */ +-(id) initWithBlock:(void(^)(id object))block object:(id)object; + +/** executes the callback */ +-(void) execute; +@end diff --git a/Example/libs/cocos2d/CCActionInstant.m b/Example/libs/cocos2d/CCActionInstant.m index 2b9072c..90a82c9 100644 --- a/Example/libs/cocos2d/CCActionInstant.m +++ b/Example/libs/cocos2d/CCActionInstant.m @@ -2,6 +2,7 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -9,10 +10,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,7 +25,6 @@ */ -#import "CCBlockSupport.h" #import "CCActionInstant.h" #import "CCNode.h" #import "CCSprite.h" @@ -39,9 +39,9 @@ @implementation CCActionInstant -(id) init { - if( (self=[super init]) ) + if( (self=[super init]) ) duration_ = 0; - + return self; } @@ -63,7 +63,7 @@ -(void) step: (ccTime) dt -(void) update: (ccTime) t { - // ignore + // nothing } -(CCFiniteTimeAction*) reverse @@ -78,9 +78,8 @@ -(CCFiniteTimeAction*) reverse #pragma mark CCShow @implementation CCShow --(void) startWithTarget:(id)aTarget +-(void) update:(ccTime)time { - [super startWithTarget:aTarget]; ((CCNode *)target_).visible = YES; } @@ -96,9 +95,8 @@ -(CCFiniteTimeAction*) reverse #pragma mark CCHide @implementation CCHide --(void) startWithTarget:(id)aTarget +-(void) update:(ccTime)time { - [super startWithTarget:aTarget]; ((CCNode *)target_).visible = NO; } @@ -114,9 +112,8 @@ -(CCFiniteTimeAction*) reverse #pragma mark CCToggleVisibility @implementation CCToggleVisibility --(void) startWithTarget:(id)aTarget +-(void) update:(ccTime)time { - [super startWithTarget:aTarget]; ((CCNode *)target_).visible = !((CCNode *)target_).visible; } @end @@ -136,14 +133,13 @@ -(id) initWithFlipX:(BOOL)x { if(( self=[super init])) flipX = x; - + return self; } --(void) startWithTarget:(id)aTarget +-(void) update:(ccTime)time { - [super startWithTarget:aTarget]; - [(CCSprite*)aTarget setFlipX:flipX]; + [(CCSprite*)target_ setFlipX:flipX]; } -(CCFiniteTimeAction*) reverse @@ -173,14 +169,13 @@ -(id) initWithFlipY:(BOOL)y { if(( self=[super init])) flipY = y; - + return self; } --(void) startWithTarget:(id)aTarget +-(void) update:(ccTime)time { - [super startWithTarget:aTarget]; - [(CCSprite*)aTarget setFlipY:flipY]; + [(CCSprite*)target_ setFlipY:flipY]; } -(CCFiniteTimeAction*) reverse @@ -211,7 +206,7 @@ -(id) initWithPosition: (CGPoint) pos { if( (self=[super init]) ) position = pos; - + return self; } @@ -221,9 +216,8 @@ -(id) copyWithZone: (NSZone*) zone return copy; } --(void) startWithTarget:(id)aTarget +-(void) update:(ccTime)time { - [super startWithTarget:aTarget]; ((CCNode *)target_).position = position; } @@ -235,6 +229,9 @@ -(void) startWithTarget:(id)aTarget #pragma mark CCCallFunc @implementation CCCallFunc + +@synthesize targetCallback = targetCallback_; + +(id) actionWithTarget: (id) t selector:(SEL) s { return [[[self alloc] initWithTarget: t selector: s] autorelease]; @@ -243,7 +240,7 @@ +(id) actionWithTarget: (id) t selector:(SEL) s -(id) initWithTarget: (id) t selector:(SEL) s { if( (self=[super init]) ) { - targetCallback_ = [t retain]; + self.targetCallback = t; selector_ = s; } return self; @@ -272,9 +269,8 @@ -(id) copyWithZone: (NSZone*) zone return copy; } --(void) startWithTarget:(id)aTarget +-(void) update:(ccTime)time { - [super startWithTarget:aTarget]; [self execute]; } @@ -344,6 +340,7 @@ -(void) execute @end @implementation CCCallFuncO +@synthesize object = object_; +(id) actionWithTarget: (id) t selector:(SEL) s object:(id)object { @@ -353,8 +350,8 @@ +(id) actionWithTarget: (id) t selector:(SEL) s object:(id)object -(id) initWithTarget:(id) t selector:(SEL) s object:(id)object { if( (self=[super initWithTarget:t selector:s] ) ) - object_ = [object retain]; - + self.object = object; + return self; } @@ -382,8 +379,6 @@ -(void) execute #pragma mark - #pragma mark Blocks -#if NS_BLOCKS_AVAILABLE - #pragma mark CCCallBlock @implementation CCCallBlock @@ -397,7 +392,7 @@ -(id) initWithBlock:(void(^)())block { if ((self = [super init])) block_ = [block copy]; - + return self; } @@ -407,9 +402,8 @@ -(id) copyWithZone: (NSZone*) zone return copy; } --(void) startWithTarget:(id)aTarget +-(void) update:(ccTime)time { - [super startWithTarget:aTarget]; [self execute]; } @@ -439,7 +433,7 @@ -(id) initWithBlock:(void(^)(CCNode *node))block { if ((self = [super init])) block_ = [block copy]; - + return self; } @@ -449,9 +443,8 @@ -(id) copyWithZone: (NSZone*) zone return copy; } --(void) startWithTarget:(id)aTarget +-(void) update:(ccTime)time { - [super startWithTarget:aTarget]; [self execute]; } @@ -468,5 +461,50 @@ -(void) dealloc @end +#pragma mark CCCallBlockO + +@implementation CCCallBlockO + +@synthesize object=object_; + ++(id) actionWithBlock:(void(^)(id object))block object:(id)object +{ + return [[[self alloc] initWithBlock:block object:object] autorelease]; +} + +-(id) initWithBlock:(void(^)(id object))block object:(id)object +{ + if ((self = [super init])) { + block_ = [block copy]; + object_ = [object retain]; + } + + return self; +} + +-(id) copyWithZone: (NSZone*) zone +{ + CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithBlock:block_]; + return copy; +} + +-(void) update:(ccTime)time +{ + [self execute]; +} + +-(void) execute +{ + block_(object_); +} + +-(void) dealloc +{ + [object_ release]; + [block_ release]; + + [super dealloc]; +} + +@end -#endif // NS_BLOCKS_AVAILABLE diff --git a/Example/libs/cocos2d/CCActionInterval.h b/Example/libs/cocos2d/CCActionInterval.h index 035bd50..6356768 100644 --- a/Example/libs/cocos2d/CCActionInterval.h +++ b/Example/libs/cocos2d/CCActionInterval.h @@ -1,7 +1,8 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2008-2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -9,10 +10,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -43,7 +44,7 @@ For example, you can simulate a Ping Pong effect running the action normally and then running it again in Reverse mode. Example: - + CCAction * pingPongAction = [CCSequence actions: action, [action reverse], nil]; */ @interface CCActionInterval: CCFiniteTimeAction @@ -69,12 +70,14 @@ then running it again in Reverse mode. */ @interface CCSequence : CCActionInterval { - CCFiniteTimeAction *actions[2]; - ccTime split; - int last; + CCFiniteTimeAction *actions_[2]; + ccTime split_; + int last_; } /** helper contructor to create an array of sequenceable actions */ +(id) actions: (CCFiniteTimeAction*) action1, ... NS_REQUIRES_NIL_TERMINATION; +/** helper contructor to create an array of sequenceable actions given an array */ ++(id) actionsWithArray: (NSArray*) actions; /** creates the action */ +(id) actionOne:(CCFiniteTimeAction*)actionOne two:(CCFiniteTimeAction*)actionTwo; /** initializes the action */ @@ -87,25 +90,34 @@ then running it again in Reverse mode. */ @interface CCRepeat : CCActionInterval { - unsigned int times_; - unsigned int total_; - CCFiniteTimeAction *other_; + NSUInteger times_; + NSUInteger total_; + ccTime nextDt_; + BOOL isActionInstant_; + CCFiniteTimeAction *innerAction_; } -/** creates a CCRepeat action. Times is an unsigned integer between 1 and pow(2,30) */ -+(id) actionWithAction:(CCFiniteTimeAction*)action times: (unsigned int)times; -/** initializes a CCRepeat action. Times is an unsigned integer between 1 and pow(2,30) */ --(id) initWithAction:(CCFiniteTimeAction*)action times: (unsigned int)times; + +/** Inner action */ +@property (nonatomic,readwrite,retain) CCFiniteTimeAction *innerAction; + +/** creates a CCRepeat action. Times is an unsigned integer between 1 and MAX_UINT. + */ ++(id) actionWithAction:(CCFiniteTimeAction*)action times: (NSUInteger)times; +/** initializes a CCRepeat action. Times is an unsigned integer between 1 and MAX_UINT */ +-(id) initWithAction:(CCFiniteTimeAction*)action times: (NSUInteger)times; @end /** Spawn a new action immediately */ @interface CCSpawn : CCActionInterval { - CCFiniteTimeAction *one; - CCFiniteTimeAction *two; + CCFiniteTimeAction *one_; + CCFiniteTimeAction *two_; } /** helper constructor to create an array of spawned actions */ +(id) actions: (CCFiniteTimeAction*) action1, ... NS_REQUIRES_NIL_TERMINATION; +/** helper contructor to create an array of spawned actions given an array */ ++(id) actionsWithArray: (NSArray*) actions; /** creates the Spawn action */ +(id) actionOne: (CCFiniteTimeAction*) one two:(CCFiniteTimeAction*) two; /** initializes the Spawn action with the 2 actions to spawn */ @@ -115,12 +127,12 @@ then running it again in Reverse mode. /** Rotates a CCNode object to a certain angle by modifying it's rotation attribute. The direction will be decided by the shortest angle. -*/ +*/ @interface CCRotateTo : CCActionInterval { - float dstAngle; - float startAngle; - float diffAngle; + float dstAngle_; + float startAngle_; + float diffAngle_; } /** creates the action */ +(id) actionWithDuration:(ccTime)duration angle:(float)angle; @@ -128,12 +140,12 @@ then running it again in Reverse mode. -(id) initWithDuration:(ccTime)duration angle:(float)angle; @end -/** Rotates a CCNode object clockwise a number of degrees by modiying it's rotation attribute. +/** Rotates a CCNode object clockwise a number of degrees by modiying its rotation attribute. */ @interface CCRotateBy : CCActionInterval { - float angle; - float startAngle; + float angle_; + float startAngle_; } /** creates the action */ +(id) actionWithDuration:(ccTime)duration angle:(float)deltaAngle; @@ -141,13 +153,13 @@ then running it again in Reverse mode. -(id) initWithDuration:(ccTime)duration angle:(float)deltaAngle; @end -/** Moves a CCNode object to the position x,y. x and y are absolute coordinates by modifying it's position attribute. +/** Moves a CCNode object to the position x,y. x and y are absolute coordinates by modifying its position attribute. */ @interface CCMoveTo : CCActionInterval { - CGPoint endPosition; - CGPoint startPosition; - CGPoint delta; + CGPoint endPosition_; + CGPoint startPosition_; + CGPoint delta_; } /** creates the action */ +(id) actionWithDuration:(ccTime)duration position:(CGPoint)position; @@ -155,10 +167,10 @@ then running it again in Reverse mode. -(id) initWithDuration:(ccTime)duration position:(CGPoint)position; @end -/** Moves a CCNode object x,y pixels by modifying it's position attribute. +/** Moves a CCNode object x,y pixels by modifying its position attribute. x and y are relative to the position of the object. Duration is is seconds. -*/ +*/ @interface CCMoveBy : CCMoveTo { } @@ -168,23 +180,51 @@ then running it again in Reverse mode. -(id) initWithDuration: (ccTime)duration position:(CGPoint)deltaPosition; @end -/** Moves a CCNode object simulating a parabolic jump movement by modifying it's position attribute. +/** Skews a CCNode object to given angles by modifying its skewX and skewY attributes + @since v1.0 + */ +@interface CCSkewTo : CCActionInterval +{ + float skewX_; + float skewY_; + float startSkewX_; + float startSkewY_; + float endSkewX_; + float endSkewY_; + float deltaX_; + float deltaY_; +} +/** creates the action */ ++(id) actionWithDuration:(ccTime)t skewX:(float)sx skewY:(float)sy; +/** initializes the action */ +-(id) initWithDuration:(ccTime)t skewX:(float)sx skewY:(float)sy; +@end + +/** Skews a CCNode object by skewX and skewY degrees + @since v1.0 + */ +@interface CCSkewBy : CCSkewTo +{ +} +@end + +/** Moves a CCNode object simulating a parabolic jump movement by modifying its position attribute. */ @interface CCJumpBy : CCActionInterval { - CGPoint startPosition; - CGPoint delta; - ccTime height; - int jumps; + CGPoint startPosition_; + CGPoint delta_; + ccTime height_; + NSUInteger jumps_; } /** creates the action */ -+(id) actionWithDuration: (ccTime)duration position:(CGPoint)position height:(ccTime)height jumps:(int)jumps; ++(id) actionWithDuration: (ccTime)duration position:(CGPoint)position height:(ccTime)height jumps:(NSUInteger)jumps; /** initializes the action */ --(id) initWithDuration: (ccTime)duration position:(CGPoint)position height:(ccTime)height jumps:(int)jumps; +-(id) initWithDuration: (ccTime)duration position:(CGPoint)position height:(ccTime)height jumps:(NSUInteger)jumps; @end -/** Moves a CCNode object to a parabolic position simulating a jump movement by modifying it's position attribute. -*/ +/** Moves a CCNode object to a parabolic position simulating a jump movement by modifying its position attribute. +*/ @interface CCJumpTo : CCJumpBy { } @@ -205,8 +245,8 @@ typedef struct _ccBezierConfig { */ @interface CCBezierBy : CCActionInterval { - ccBezierConfig config; - CGPoint startPosition; + ccBezierConfig config_; + CGPoint startPosition_; } /** creates the action with a duration and a bezier configuration */ @@ -224,19 +264,19 @@ typedef struct _ccBezierConfig { } @end -/** Scales a CCNode object to a zoom factor by modifying it's scale attribute. +/** Scales a CCNode object to a zoom factor by modifying its scale attribute. @warning This action doesn't support "reverse" */ @interface CCScaleTo : CCActionInterval { - float scaleX; - float scaleY; - float startScaleX; - float startScaleY; - float endScaleX; - float endScaleY; - float deltaX; - float deltaY; + float scaleX_; + float scaleY_; + float startScaleX_; + float startScaleY_; + float endScaleX_; + float endScaleY_; + float deltaX_; + float deltaY_; } /** creates the action with the same scale factor for X and Y */ +(id) actionWithDuration: (ccTime)duration scale:(float) s; @@ -248,23 +288,23 @@ typedef struct _ccBezierConfig { -(id) initWithDuration: (ccTime)duration scaleX:(float) sx scaleY:(float)sy; @end -/** Scales a CCNode object a zoom factor by modifying it's scale attribute. +/** Scales a CCNode object a zoom factor by modifying its scale attribute. */ @interface CCScaleBy : CCScaleTo { } @end -/** Blinks a CCNode object by modifying it's visible attribute +/** Blinks a CCNode object by modifying its visible attribute */ @interface CCBlink : CCActionInterval { - int times; + NSUInteger times_; } /** creates the action */ -+(id) actionWithDuration: (ccTime)duration blinks:(unsigned int)blinks; ++(id) actionWithDuration: (ccTime)duration blinks:(NSUInteger)blinks; /** initilizes the action */ --(id) initWithDuration: (ccTime)duration blinks:(unsigned int)blinks; +-(id) initWithDuration: (ccTime)duration blinks:(NSUInteger)blinks; @end /** Fades In an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 0 to 255. @@ -288,8 +328,8 @@ typedef struct _ccBezierConfig { */ @interface CCFadeTo : CCActionInterval { - GLubyte toOpacity; - GLubyte fromOpacity; + GLubyte toOpacity_; + GLubyte fromOpacity_; } /** creates an action with duration and opactiy */ +(id) actionWithDuration:(ccTime)duration opacity:(GLubyte)opactiy; @@ -303,8 +343,8 @@ typedef struct _ccBezierConfig { */ @interface CCTintTo : CCActionInterval { - ccColor3B to; - ccColor3B from; + ccColor3B to_; + ccColor3B from_; } /** creates an action with duration and color */ +(id) actionWithDuration:(ccTime)duration red:(GLubyte)red green:(GLubyte)green blue:(GLubyte)blue; @@ -317,8 +357,8 @@ typedef struct _ccBezierConfig { */ @interface CCTintBy : CCActionInterval { - GLshort deltaR, deltaG, deltaB; - GLshort fromR, fromG, fromB; + GLshort deltaR_, deltaG_, deltaB_; + GLshort fromR_, fromG_, fromB_; } /** creates an action with duration and color */ +(id) actionWithDuration:(ccTime)duration red:(GLshort)deltaRed green:(GLshort)deltaGreen blue:(GLshort)deltaBlue; @@ -334,7 +374,7 @@ typedef struct _ccBezierConfig { @end /** Executes an action in reverse order, from time=duration to time=0 - + @warning Use this action carefully. This action is not sequenceable. Use it as the default "reversed" method of your own actions, but using it outside the "reversed" @@ -342,7 +382,7 @@ typedef struct _ccBezierConfig { */ @interface CCReverseTime : CCActionInterval { - CCFiniteTimeAction * other; + CCFiniteTimeAction * other_; } /** creates the action */ +(id) actionWithAction: (CCFiniteTimeAction*) action; @@ -356,29 +396,36 @@ typedef struct _ccBezierConfig { /** Animates a sprite given the name of an Animation */ @interface CCAnimate : CCActionInterval { - CCAnimation *animation_; - id origFrame; - BOOL restoreOriginalFrame; + NSMutableArray *splitTimes_; + NSInteger nextFrame_; + CCAnimation *animation_; + id origFrame_; + NSUInteger executedLoops_; } /** animation used for the animage */ @property (readwrite,nonatomic,retain) CCAnimation * animation; /** creates the action with an Animation and will restore the original frame when the animation is over */ -+(id) actionWithAnimation:(CCAnimation*) a; ++(id) actionWithAnimation:(CCAnimation*)animation; /** initializes the action with an Animation and will restore the original frame when the animtion is over */ --(id) initWithAnimation:(CCAnimation*) a; -/** creates the action with an Animation */ -+(id) actionWithAnimation:(CCAnimation*) a restoreOriginalFrame:(BOOL)b; -/** initializes the action with an Animation */ --(id) initWithAnimation:(CCAnimation*) a restoreOriginalFrame:(BOOL)b; -/** creates an action with a duration, animation and depending of the restoreOriginalFrame, it will restore the original frame or not. - The 'delay' parameter of the animation will be overrided by the duration parameter. - @since v0.99.0 - */ -+(id) actionWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)b; -/** initializes an action with a duration, animation and depending of the restoreOriginalFrame, it will restore the original frame or not. - The 'delay' parameter of the animation will be overrided by the duration parameter. - @since v0.99.0 +-(id) initWithAnimation:(CCAnimation*)animation; +@end + +/** Overrides the target of an action so that it always runs on the target + * specified at action creation rather than the one specified by runAction. */ --(id) initWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)b; -@end \ No newline at end of file +@interface CCTargetedAction : CCActionInterval +{ + id forcedTarget_; + CCFiniteTimeAction* action_; +} +/** This is the target that the action will be forced to run with */ +@property(readwrite,nonatomic,retain) id forcedTarget; + +/** Create an action with the specified action and forced target */ ++ (id) actionWithTarget:(id) target action:(CCFiniteTimeAction*) action; + +/** Init an action with the specified action and forced target */ +- (id) initWithTarget:(id) target action:(CCFiniteTimeAction*) action; + +@end diff --git a/Example/libs/cocos2d/CCActionInterval.m b/Example/libs/cocos2d/CCActionInterval.m index 148bb0a..60c886d 100644 --- a/Example/libs/cocos2d/CCActionInterval.m +++ b/Example/libs/cocos2d/CCActionInterval.m @@ -1,7 +1,8 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2008-2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -9,10 +10,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,6 +27,7 @@ #import "CCActionInterval.h" +#import "CCActionInstant.h" #import "CCSprite.h" #import "CCSpriteFrame.h" #import "CCAnimation.h" @@ -35,8 +37,7 @@ // // IntervalAction // -#pragma mark - -#pragma mark IntervalAction +#pragma mark - CCIntervalAction @implementation CCActionInterval @synthesize elapsed = elapsed_; @@ -57,7 +58,7 @@ -(id) initWithDuration: (ccTime) d { if( (self=[super init]) ) { duration_ = d; - + // prevent division by 0 // This comparison could be in step:, but it might decrease the performance // by 3% in heavy based action games. @@ -88,7 +89,13 @@ -(void) step: (ccTime) dt } else elapsed_ += dt; - [self update: MIN(1, elapsed_/duration_)]; + + [self update: MAX(0, // needed for rewind. elapsed could be negative + MIN(1, elapsed_/ + MAX(duration_,FLT_EPSILON) // division by 0 + ) + ) + ]; } -(void) startWithTarget:(id)aTarget @@ -108,14 +115,8 @@ - (CCActionInterval*) reverse // // Sequence // -#pragma mark - -#pragma mark Sequence +#pragma mark - CCSequence @implementation CCSequence -+(id) actionOne: (CCFiniteTimeAction*) one two: (CCFiniteTimeAction*) two -{ - return [[[self alloc] initOne:one two:two ] autorelease]; -} - +(id) actions: (CCFiniteTimeAction*) action1, ... { va_list params; @@ -135,47 +136,68 @@ +(id) actions: (CCFiniteTimeAction*) action1, ... return prev; } --(id) initOne: (CCFiniteTimeAction*) one_ two: (CCFiniteTimeAction*) two_ ++(id) actionsWithArray: (NSArray*) actions { - NSAssert( one_!=nil, @"Sequence: argument one must be non-nil"); - NSAssert( two_!=nil, @"Sequence: argument two must be non-nil"); + CCFiniteTimeAction *prev = [actions objectAtIndex:0]; + + for (NSUInteger i = 1; i < [actions count]; i++) + prev = [self actionOne:prev two:[actions objectAtIndex:i]]; + + return prev; +} - CCFiniteTimeAction *one = one_; - CCFiniteTimeAction *two = two_; - ++(id) actionOne: (CCFiniteTimeAction*) one two: (CCFiniteTimeAction*) two +{ + return [[[self alloc] initOne:one two:two ] autorelease]; +} + +-(id) initOne: (CCFiniteTimeAction*) one two: (CCFiniteTimeAction*) two +{ + NSAssert( one!=nil && two!=nil, @"Sequence: arguments must be non-nil"); + NSAssert( one!=actions_[0] && one!=actions_[1], @"Sequence: re-init using the same parameters is not supported"); + NSAssert( two!=actions_[1] && two!=actions_[0], @"Sequence: re-init using the same parameters is not supported"); + ccTime d = [one duration] + [two duration]; - [super initWithDuration: d]; - actions[0] = [one retain]; - actions[1] = [two retain]; + if( (self=[super initWithDuration: d]) ) { + + // XXX: Supports re-init without leaking. Fails if one==one_ || two==two_ + [actions_[0] release]; + [actions_[1] release]; + + actions_[0] = [one retain]; + actions_[1] = [two retain]; + } return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone:zone] initOne:[[actions[0] copy] autorelease] two:[[actions[1] copy] autorelease] ]; + CCAction *copy = [[[self class] allocWithZone:zone] initOne:[[actions_[0] copy] autorelease] two:[[actions_[1] copy] autorelease] ]; return copy; } -(void) dealloc { - [actions[0] release]; - [actions[1] release]; + [actions_[0] release]; + [actions_[1] release]; [super dealloc]; } -(void) startWithTarget:(id)aTarget { - [super startWithTarget:aTarget]; - split = [actions[0] duration] / duration_; - last = -1; + [super startWithTarget:aTarget]; + split_ = [actions_[0] duration] / MAX(duration_, FLT_EPSILON); + last_ = -1; } -(void) stop { - [actions[0] stop]; - [actions[1] stop]; + // Issue #1305 + if( last_ != - 1) + [actions_[last_] stop]; + [super stop]; } @@ -184,62 +206,76 @@ -(void) update: (ccTime) t int found = 0; ccTime new_t = 0.0f; - if( t >= split ) { - found = 1; - if ( split == 1 ) - new_t = 1; - else - new_t = (t-split) / (1 - split ); - } else { + if( t < split_ ) { + // action[0] found = 0; - if( split != 0 ) - new_t = t / split; + if( split_ != 0 ) + new_t = t / split_; else new_t = 1; + + } else { + // action[1] + found = 1; + if ( split_ == 1 ) + new_t = 1; + else + new_t = (t-split_) / (1 - split_ ); } - if (last == -1 && found==1) { - [actions[0] startWithTarget:target_]; - [actions[0] update:1.0f]; - [actions[0] stop]; - } - - if (last != found ) { - if( last != -1 ) { - [actions[last] update: 1.0f]; - [actions[last] stop]; + if ( found==1 ) { + + if( last_ == -1 ) { + // action[0] was skipped, execute it. + [actions_[0] startWithTarget:target_]; + [actions_[0] update:1.0f]; + [actions_[0] stop]; + } + else if( last_ == 0 ) + { + // switching to action 1. stop action 0. + [actions_[0] update: 1.0f]; + [actions_[0] stop]; } - [actions[found] startWithTarget:target_]; } - [actions[found] update: new_t]; - last = found; + + // New action. Start it. + if( found != last_ ) + [actions_[found] startWithTarget:target_]; + + [actions_[found] update: new_t]; + last_ = found; } - (CCActionInterval *) reverse { - return [[self class] actionOne: [actions[1] reverse] two: [actions[0] reverse ] ]; + return [[self class] actionOne: [actions_[1] reverse] two: [actions_[0] reverse ] ]; } @end // // Repeat // -#pragma mark - -#pragma mark CCRepeat +#pragma mark - CCRepeat @implementation CCRepeat -+(id) actionWithAction:(CCFiniteTimeAction*)action times:(unsigned int)times +@synthesize innerAction=innerAction_; + ++(id) actionWithAction:(CCFiniteTimeAction*)action times:(NSUInteger)times { return [[[self alloc] initWithAction:action times:times] autorelease]; } --(id) initWithAction:(CCFiniteTimeAction*)action times:(unsigned int)times +-(id) initWithAction:(CCFiniteTimeAction*)action times:(NSUInteger)times { ccTime d = [action duration] * times; if( (self=[super initWithDuration: d ]) ) { times_ = times; - other_ = [action retain]; + self.innerAction = action; + isActionInstant_ = ([action isKindOfClass:[CCActionInstant class]]) ? YES : NO; + //a instant action needs to be executed one time less in the update method since it uses startWithTarget to execute the action + if (isActionInstant_) times_ -=1; total_ = 0; } return self; @@ -247,62 +283,72 @@ -(id) initWithAction:(CCFiniteTimeAction*)action times:(unsigned int)times -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone:zone] initWithAction:[[other_ copy] autorelease] times:times_]; + CCAction *copy = [[[self class] allocWithZone:zone] initWithAction:[[innerAction_ copy] autorelease] times:times_]; return copy; } -(void) dealloc { - [other_ release]; + [innerAction_ release]; [super dealloc]; } -(void) startWithTarget:(id)aTarget { total_ = 0; + nextDt_ = [innerAction_ duration]/duration_; [super startWithTarget:aTarget]; - [other_ startWithTarget:aTarget]; + [innerAction_ startWithTarget:aTarget]; } -(void) stop -{ - [other_ stop]; +{ + [innerAction_ stop]; [super stop]; } -// issue #80. Instead of hooking step:, hook update: since it can be called by any -// container action like Repeat, Sequence, AccelDeccel, etc.. +// issue #80. Instead of hooking step:, hook update: since it can be called by any +// container action like CCRepeat, CCSequence, CCEase, etc.. -(void) update:(ccTime) dt { - ccTime t = dt * times_; - if( t > total_+1 ) { - [other_ update:1.0f]; - total_++; - [other_ stop]; - [other_ startWithTarget:target_]; - - // repeat is over ? - if( total_== times_ ) - // so, set it in the original position - [other_ update:0]; - else { - // no ? start next repeat with the right update - // to prevent jerk (issue #390) - [other_ update: t-total_]; - } + if (dt >= nextDt_) + { + while (dt > nextDt_ && total_ < times_) + { - } else { + [innerAction_ update:1.0f]; + total_++; + + [innerAction_ stop]; + [innerAction_ startWithTarget:target_]; + nextDt_ += [innerAction_ duration]/duration_; + } - float r = fmodf(t, 1.0f); + // fix for issue #1288, incorrect end value of repeat + if(dt >= 1.0f && total_ < times_) + { + total_++; + } - // fix last repeat position - // else it could be 0. - if( dt== 1.0f) { - r = 1.0f; - total_++; // this is the added line + // don't set a instantaction back or update it, it has no use because it has no duration + if (!isActionInstant_) + { + if (total_ == times_) + { + [innerAction_ update:1]; + [innerAction_ stop]; + } + else + { + // issue #390 prevent jerk, use right update + [innerAction_ update:dt - (nextDt_ - innerAction_.duration/duration_)]; + } } - [other_ update: MIN(r,1)]; + } + else + { + [innerAction_ update:fmodf(dt * times_,1.0f)]; } } @@ -313,25 +359,24 @@ -(BOOL) isDone - (CCActionInterval *) reverse { - return [[self class] actionWithAction:[other_ reverse] times:times_]; + return [[self class] actionWithAction:[innerAction_ reverse] times:times_]; } @end // // Spawn // -#pragma mark - -#pragma mark Spawn +#pragma mark - CCSpawn @implementation CCSpawn +(id) actions: (CCFiniteTimeAction*) action1, ... { va_list params; va_start(params,action1); - + CCFiniteTimeAction *now; CCFiniteTimeAction *prev = action1; - + while( action1 ) { now = va_arg(params,CCFiniteTimeAction*); if ( now ) @@ -343,118 +388,133 @@ +(id) actions: (CCFiniteTimeAction*) action1, ... return prev; } ++(id) actionsWithArray: (NSArray*) actions +{ + CCFiniteTimeAction *prev = [actions objectAtIndex:0]; + + for (NSUInteger i = 1; i < [actions count]; i++) + prev = [self actionOne:prev two:[actions objectAtIndex:i]]; + + return prev; +} + +(id) actionOne: (CCFiniteTimeAction*) one two: (CCFiniteTimeAction*) two -{ +{ return [[[self alloc] initOne:one two:two ] autorelease]; } --(id) initOne: (CCFiniteTimeAction*) one_ two: (CCFiniteTimeAction*) two_ +-(id) initOne: (CCFiniteTimeAction*) one two: (CCFiniteTimeAction*) two { - NSAssert( one_!=nil, @"Spawn: argument one must be non-nil"); - NSAssert( two_!=nil, @"Spawn: argument two must be non-nil"); + NSAssert( one!=nil && two!=nil, @"Spawn: arguments must be non-nil"); + NSAssert( one!=one_ && one!=two_, @"Spawn: reinit using same parameters is not supported"); + NSAssert( two!=two_ && two!=one_, @"Spawn: reinit using same parameters is not supported"); - ccTime d1 = [one_ duration]; - ccTime d2 = [two_ duration]; - - [super initWithDuration: fmaxf(d1,d2)]; + ccTime d1 = [one duration]; + ccTime d2 = [two duration]; - one = one_; - two = two_; + if( (self=[super initWithDuration: MAX(d1,d2)] ) ) { - if( d1 > d2 ) - two = [CCSequence actionOne: two_ two:[CCDelayTime actionWithDuration: (d1-d2)] ]; - else if( d1 < d2) - one = [CCSequence actionOne: one_ two: [CCDelayTime actionWithDuration: (d2-d1)] ]; - - [one retain]; - [two retain]; + // XXX: Supports re-init without leaking. Fails if one==one_ || two==two_ + [one_ release]; + [two_ release]; + + one_ = one; + two_ = two; + + if( d1 > d2 ) + two_ = [CCSequence actionOne:two two:[CCDelayTime actionWithDuration: (d1-d2)] ]; + else if( d1 < d2) + one_ = [CCSequence actionOne:one two: [CCDelayTime actionWithDuration: (d2-d1)] ]; + + [one_ retain]; + [two_ retain]; + } return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initOne: [[one copy] autorelease] two: [[two copy] autorelease] ]; + CCAction *copy = [[[self class] allocWithZone: zone] initOne: [[one_ copy] autorelease] two: [[two_ copy] autorelease] ]; return copy; } -(void) dealloc { - [one release]; - [two release]; + [one_ release]; + [two_ release]; [super dealloc]; } -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - [one startWithTarget:target_]; - [two startWithTarget:target_]; + [one_ startWithTarget:target_]; + [two_ startWithTarget:target_]; } -(void) stop { - [one stop]; - [two stop]; + [one_ stop]; + [two_ stop]; [super stop]; } -(void) update: (ccTime) t { - [one update:t]; - [two update:t]; + [one_ update:t]; + [two_ update:t]; } - (CCActionInterval *) reverse { - return [[self class] actionOne: [one reverse] two: [two reverse ] ]; + return [[self class] actionOne: [one_ reverse] two: [two_ reverse ] ]; } @end // // RotateTo // -#pragma mark - -#pragma mark RotateTo +#pragma mark - CCRotateTo @implementation CCRotateTo +(id) actionWithDuration: (ccTime) t angle:(float) a -{ +{ return [[[self alloc] initWithDuration:t angle:a ] autorelease]; } -(id) initWithDuration: (ccTime) t angle:(float) a { if( (self=[super initWithDuration: t]) ) - dstAngle = a; - + dstAngle_ = a; + return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] angle: dstAngle]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] angle:dstAngle_]; return copy; } -(void) startWithTarget:(CCNode *)aTarget { [super startWithTarget:aTarget]; - - startAngle = [target_ rotation]; - if (startAngle > 0) - startAngle = fmodf(startAngle, 360.0f); + + startAngle_ = [target_ rotation]; + if (startAngle_ > 0) + startAngle_ = fmodf(startAngle_, 360.0f); else - startAngle = fmodf(startAngle, -360.0f); - - diffAngle = dstAngle - startAngle; - if (diffAngle > 180) - diffAngle -= 360; - if (diffAngle < -180) - diffAngle += 360; + startAngle_ = fmodf(startAngle_, -360.0f); + + diffAngle_ =dstAngle_ - startAngle_; + if (diffAngle_ > 180) + diffAngle_ -= 360; + if (diffAngle_ < -180) + diffAngle_ += 360; } -(void) update: (ccTime) t { - [target_ setRotation: startAngle + diffAngle * t]; + [target_ setRotation: startAngle_ + diffAngle_ * t]; } @end @@ -462,44 +522,43 @@ -(void) update: (ccTime) t // // RotateBy // -#pragma mark - -#pragma mark RotateBy +#pragma mark - CCRotateBy @implementation CCRotateBy +(id) actionWithDuration: (ccTime) t angle:(float) a -{ +{ return [[[self alloc] initWithDuration:t angle:a ] autorelease]; } -(id) initWithDuration: (ccTime) t angle:(float) a { if( (self=[super initWithDuration: t]) ) - angle = a; - + angle_ = a; + return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] angle: angle]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] angle: angle_]; return copy; } -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - startAngle = [target_ rotation]; + startAngle_ = [target_ rotation]; } -(void) update: (ccTime) t -{ +{ // XXX: shall I add % 360 - [target_ setRotation: (startAngle + angle * t )]; + [target_ setRotation: (startAngle_ +angle_ * t )]; } -(CCActionInterval*) reverse { - return [[self class] actionWithDuration:duration_ angle:-angle]; + return [[self class] actionWithDuration:duration_ angle:-angle_]; } @end @@ -507,113 +566,214 @@ -(CCActionInterval*) reverse // // MoveTo // -#pragma mark - -#pragma mark MoveTo +#pragma mark - CCMoveTo @implementation CCMoveTo +(id) actionWithDuration: (ccTime) t position: (CGPoint) p -{ +{ return [[[self alloc] initWithDuration:t position:p ] autorelease]; } -(id) initWithDuration: (ccTime) t position: (CGPoint) p { if( (self=[super initWithDuration: t]) ) - endPosition = p; - + endPosition_ = p; + return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] position: endPosition]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] position: endPosition_]; return copy; } -(void) startWithTarget:(CCNode *)aTarget { [super startWithTarget:aTarget]; - startPosition = [(CCNode*)target_ position]; - delta = ccpSub( endPosition, startPosition ); + startPosition_ = [(CCNode*)target_ position]; + delta_ = ccpSub( endPosition_, startPosition_ ); } -(void) update: (ccTime) t -{ - [target_ setPosition: ccp( (startPosition.x + delta.x * t ), (startPosition.y + delta.y * t ) )]; +{ + [target_ setPosition: ccp( (startPosition_.x + delta_.x * t ), (startPosition_.y + delta_.y * t ) )]; } @end // // MoveBy // -#pragma mark - -#pragma mark MoveBy +#pragma mark - CCMoveBy @implementation CCMoveBy +(id) actionWithDuration: (ccTime) t position: (CGPoint) p -{ +{ return [[[self alloc] initWithDuration:t position:p ] autorelease]; } -(id) initWithDuration: (ccTime) t position: (CGPoint) p { if( (self=[super initWithDuration: t]) ) - delta = p; - + delta_ = p; + return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] position: delta]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] position: delta_]; return copy; } -(void) startWithTarget:(CCNode *)aTarget { - CGPoint dTmp = delta; + CGPoint dTmp = delta_; + [super startWithTarget:aTarget]; + delta_ = dTmp; +} + +-(CCActionInterval*) reverse +{ + return [[self class] actionWithDuration:duration_ position:ccp( -delta_.x, -delta_.y)]; +} +@end + + +// +// SkewTo +// +#pragma mark - CCSkewTo + +@implementation CCSkewTo ++(id) actionWithDuration:(ccTime)t skewX:(float)sx skewY:(float)sy +{ + return [[[self alloc] initWithDuration: t skewX:sx skewY:sy] autorelease]; +} + +-(id) initWithDuration:(ccTime)t skewX:(float)sx skewY:(float)sy +{ + if( (self=[super initWithDuration:t]) ) { + endSkewX_ = sx; + endSkewY_ = sy; + } + return self; +} + +-(id) copyWithZone: (NSZone*) zone +{ + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] skewX:endSkewX_ skewY:endSkewY_]; + return copy; +} + +-(void) startWithTarget:(CCNode *)aTarget +{ + [super startWithTarget:aTarget]; + + startSkewX_ = [target_ skewX]; + + if (startSkewX_ > 0) + startSkewX_ = fmodf(startSkewX_, 180.0f); + else + startSkewX_ = fmodf(startSkewX_, -180.0f); + + deltaX_ = endSkewX_ - startSkewX_; + + if ( deltaX_ > 180 ) { + deltaX_ -= 360; + } + if ( deltaX_ < -180 ) { + deltaX_ += 360; + } + + startSkewY_ = [target_ skewY]; + + if (startSkewY_ > 0) + startSkewY_ = fmodf(startSkewY_, 360.0f); + else + startSkewY_ = fmodf(startSkewY_, -360.0f); + + deltaY_ = endSkewY_ - startSkewY_; + + if ( deltaY_ > 180 ) { + deltaY_ -= 360; + } + if ( deltaY_ < -180 ) { + deltaY_ += 360; + } +} + +-(void) update: (ccTime) t +{ + [target_ setSkewX: (startSkewX_ + deltaX_ * t ) ]; + [target_ setSkewY: (startSkewY_ + deltaY_ * t ) ]; +} + +@end + +// +// CCSkewBy +// +#pragma mark - CCSkewBy + +@implementation CCSkewBy + +-(id) initWithDuration:(ccTime)t skewX:(float)deltaSkewX skewY:(float)deltaSkewY +{ + if( (self=[super initWithDuration:t skewX:deltaSkewX skewY:deltaSkewY]) ) { + skewX_ = deltaSkewX; + skewY_ = deltaSkewY; + } + return self; +} + +-(void) startWithTarget:(CCNode *)aTarget +{ [super startWithTarget:aTarget]; - delta = dTmp; + deltaX_ = skewX_; + deltaY_ = skewY_; + endSkewX_ = startSkewX_ + deltaX_; + endSkewY_ = startSkewY_ + deltaY_; } -(CCActionInterval*) reverse { - return [[self class] actionWithDuration:duration_ position:ccp( -delta.x, -delta.y)]; + return [[self class] actionWithDuration:duration_ skewX:-skewX_ skewY:-skewY_]; } @end + // // JumpBy // -#pragma mark - -#pragma mark JumpBy +#pragma mark - CCJumpBy @implementation CCJumpBy -+(id) actionWithDuration: (ccTime) t position: (CGPoint) pos height: (ccTime) h jumps:(int)j ++(id) actionWithDuration: (ccTime) t position: (CGPoint) pos height: (ccTime) h jumps:(NSUInteger)j { return [[[self alloc] initWithDuration: t position: pos height: h jumps:j] autorelease]; } --(id) initWithDuration: (ccTime) t position: (CGPoint) pos height: (ccTime) h jumps:(int)j +-(id) initWithDuration: (ccTime) t position: (CGPoint) pos height: (ccTime) h jumps:(NSUInteger)j { if( (self=[super initWithDuration:t]) ) { - delta = pos; - height = h; - jumps = j; + delta_ = pos; + height_ = h; + jumps_ = j; } return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] position: delta height:height jumps:jumps]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] position:delta_ height:height_ jumps:jumps_]; return copy; } -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - startPosition = [(CCNode*)target_ position]; + startPosition_ = [(CCNode*)target_ position]; } -(void) update: (ccTime) t @@ -622,49 +782,47 @@ -(void) update: (ccTime) t // ccTime y = height * fabsf( sinf(t * (CGFloat)M_PI * jumps ) ); // y += delta.y * t; // ccTime x = delta.x * t; -// [target setPosition: ccp( startPosition.x + x, startPosition.y + y )]; - +// [target setPosition: ccp( startPosition.x + x, startPosition.y + y )]; + // parabolic jump (since v0.8.2) - ccTime frac = fmodf( t * jumps, 1.0f ); - ccTime y = height * 4 * frac * (1 - frac); - y += delta.y * t; - ccTime x = delta.x * t; - [target_ setPosition: ccp( startPosition.x + x, startPosition.y + y )]; - + ccTime frac = fmodf( t * jumps_, 1.0f ); + ccTime y = height_ * 4 * frac * (1 - frac); + y += delta_.y * t; + ccTime x = delta_.x * t; + [target_ setPosition: ccp( startPosition_.x + x, startPosition_.y + y )]; + } -(CCActionInterval*) reverse { - return [[self class] actionWithDuration:duration_ position: ccp(-delta.x,-delta.y) height: height jumps:jumps]; + return [[self class] actionWithDuration:duration_ position: ccp(-delta_.x,-delta_.y) height:height_ jumps:jumps_]; } @end // // JumpTo // -#pragma mark - -#pragma mark JumpTo +#pragma mark - CCJumpTo @implementation CCJumpTo -(void) startWithTarget:(CCNode *)aTarget { [super startWithTarget:aTarget]; - delta = ccp( delta.x - startPosition.x, delta.y - startPosition.y ); + delta_ = ccp( delta_.x - startPosition_.x, delta_.y - startPosition_.y ); } @end -#pragma mark - -#pragma mark BezierBy +#pragma mark - CCBezierBy // Bezier cubic formula: -// ((1 - t) + t)3 = 1 -// Expands to… -// (1 - t)3 + 3t(1-t)2 + 3t2(1 - t) + t3 = 1 +// ((1 - t) + t)3 = 1 +// Expands to… +// (1 - t)3 + 3t(1-t)2 + 3t2(1 - t) + t3 = 1 static inline float bezierat( float a, float b, float c, float d, ccTime t ) { - return (powf(1-t,3) * a + - 3*t*(powf(1-t,2))*b + + return (powf(1-t,3) * a + + 3*t*(powf(1-t,2))*b + 3*powf(t,2)*(1-t)*c + powf(t,3)*d ); } @@ -674,55 +832,55 @@ static inline float bezierat( float a, float b, float c, float d, ccTime t ) // @implementation CCBezierBy +(id) actionWithDuration: (ccTime) t bezier:(ccBezierConfig) c -{ +{ return [[[self alloc] initWithDuration:t bezier:c ] autorelease]; } -(id) initWithDuration: (ccTime) t bezier:(ccBezierConfig) c { if( (self=[super initWithDuration: t]) ) { - config = c; + config_ = c; } return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] bezier: config]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] bezier:config_]; return copy; } -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - startPosition = [(CCNode*)target_ position]; + startPosition_ = [(CCNode*)target_ position]; } -(void) update: (ccTime) t { float xa = 0; - float xb = config.controlPoint_1.x; - float xc = config.controlPoint_2.x; - float xd = config.endPosition.x; - + float xb = config_.controlPoint_1.x; + float xc = config_.controlPoint_2.x; + float xd = config_.endPosition.x; + float ya = 0; - float yb = config.controlPoint_1.y; - float yc = config.controlPoint_2.y; - float yd = config.endPosition.y; - + float yb = config_.controlPoint_1.y; + float yc = config_.controlPoint_2.y; + float yd = config_.endPosition.y; + float x = bezierat(xa, xb, xc, xd, t); float y = bezierat(ya, yb, yc, yd, t); - [target_ setPosition: ccpAdd( startPosition, ccp(x,y))]; + [target_ setPosition: ccpAdd( startPosition_, ccp(x,y))]; } - (CCActionInterval*) reverse { ccBezierConfig r; - r.endPosition = ccpNeg(config.endPosition); - r.controlPoint_1 = ccpAdd(config.controlPoint_2, ccpNeg(config.endPosition)); - r.controlPoint_2 = ccpAdd(config.controlPoint_1, ccpNeg(config.endPosition)); - + r.endPosition = ccpNeg(config_.endPosition); + r.controlPoint_1 = ccpAdd(config_.controlPoint_2, ccpNeg(config_.endPosition)); + r.controlPoint_2 = ccpAdd(config_.controlPoint_1, ccpNeg(config_.endPosition)); + CCBezierBy *action = [[self class] actionWithDuration:[self duration] bezier:r]; return action; } @@ -731,15 +889,14 @@ - (CCActionInterval*) reverse // // BezierTo // -#pragma mark - -#pragma mark BezierTo +#pragma mark - CCBezierTo @implementation CCBezierTo -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - config.controlPoint_1 = ccpSub(config.controlPoint_1, startPosition); - config.controlPoint_2 = ccpSub(config.controlPoint_2, startPosition); - config.endPosition = ccpSub(config.endPosition, startPosition); + config_.controlPoint_1 = ccpSub(config_.controlPoint_1, startPosition_); + config_.controlPoint_2 = ccpSub(config_.controlPoint_2, startPosition_); + config_.endPosition = ccpSub(config_.endPosition, startPosition_); } @end @@ -747,8 +904,7 @@ -(void) startWithTarget:(id)aTarget // // ScaleTo // -#pragma mark - -#pragma mark ScaleTo +#pragma mark - CCScaleTo @implementation CCScaleTo +(id) actionWithDuration: (ccTime) t scale:(float) s { @@ -758,96 +914,94 @@ +(id) actionWithDuration: (ccTime) t scale:(float) s -(id) initWithDuration: (ccTime) t scale:(float) s { if( (self=[super initWithDuration: t]) ) { - endScaleX = s; - endScaleY = s; + endScaleX_ = s; + endScaleY_ = s; } return self; } -+(id) actionWithDuration: (ccTime) t scaleX:(float)sx scaleY:(float)sy ++(id) actionWithDuration: (ccTime) t scaleX:(float)sx scaleY:(float)sy { return [[[self alloc] initWithDuration: t scaleX:sx scaleY:sy] autorelease]; } -(id) initWithDuration: (ccTime) t scaleX:(float)sx scaleY:(float)sy { - if( (self=[super initWithDuration: t]) ) { - endScaleX = sx; - endScaleY = sy; + if( (self=[super initWithDuration: t]) ) { + endScaleX_ = sx; + endScaleY_ = sy; } return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] scaleX:endScaleX scaleY:endScaleY]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] scaleX:endScaleX_ scaleY:endScaleY_]; return copy; } -(void) startWithTarget:(CCNode *)aTarget { [super startWithTarget:aTarget]; - startScaleX = [target_ scaleX]; - startScaleY = [target_ scaleY]; - deltaX = endScaleX - startScaleX; - deltaY = endScaleY - startScaleY; + startScaleX_ = [target_ scaleX]; + startScaleY_ = [target_ scaleY]; + deltaX_ = endScaleX_ - startScaleX_; + deltaY_ = endScaleY_ - startScaleY_; } -(void) update: (ccTime) t { - [target_ setScaleX: (startScaleX + deltaX * t ) ]; - [target_ setScaleY: (startScaleY + deltaY * t ) ]; + [target_ setScaleX: (startScaleX_ + deltaX_ * t ) ]; + [target_ setScaleY: (startScaleY_ + deltaY_ * t ) ]; } @end // // ScaleBy // -#pragma mark - -#pragma mark ScaleBy +#pragma mark - CCScaleBy @implementation CCScaleBy -(void) startWithTarget:(CCNode *)aTarget { [super startWithTarget:aTarget]; - deltaX = startScaleX * endScaleX - startScaleX; - deltaY = startScaleY * endScaleY - startScaleY; + deltaX_ = startScaleX_ * endScaleX_ - startScaleX_; + deltaY_ = startScaleY_ * endScaleY_ - startScaleY_; } -(CCActionInterval*) reverse { - return [[self class] actionWithDuration:duration_ scaleX: 1/endScaleX scaleY:1/endScaleY]; + return [[self class] actionWithDuration:duration_ scaleX:1/endScaleX_ scaleY:1/endScaleY_]; } @end // // Blink // -#pragma mark - -#pragma mark Blink +#pragma mark - CCBlink @implementation CCBlink -+(id) actionWithDuration: (ccTime) t blinks: (unsigned int) b ++(id) actionWithDuration: (ccTime) t blinks: (NSUInteger) b { return [[[ self alloc] initWithDuration: t blinks: b] autorelease]; } --(id) initWithDuration: (ccTime) t blinks: (unsigned int) b +-(id) initWithDuration: (ccTime) t blinks: (NSUInteger) b { if( (self=[super initWithDuration: t] ) ) - times = b; - + times_ = b; + return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] blinks: times]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] blinks: times_]; return copy; } -(void) update: (ccTime) t { if( ! [self isDone] ) { - ccTime slice = 1.0f / times; + ccTime slice = 1.0f / times_; ccTime m = fmodf(t, slice); [target_ setVisible: (m > slice/2) ? YES : NO]; } @@ -856,15 +1010,14 @@ -(void) update: (ccTime) t -(CCActionInterval*) reverse { // return 'self' - return [[self class] actionWithDuration:duration_ blinks: times]; + return [[self class] actionWithDuration:duration_ blinks: times_]; } @end // // FadeIn // -#pragma mark - -#pragma mark FadeIn +#pragma mark - CCFadeIn @implementation CCFadeIn -(void) update: (ccTime) t { @@ -880,8 +1033,7 @@ -(CCActionInterval*) reverse // // FadeOut // -#pragma mark - -#pragma mark FadeOut +#pragma mark - CCFadeOut @implementation CCFadeOut -(void) update: (ccTime) t { @@ -897,8 +1049,7 @@ -(CCActionInterval*) reverse // // FadeTo // -#pragma mark - -#pragma mark FadeTo +#pragma mark - CCFadeTo @implementation CCFadeTo +(id) actionWithDuration: (ccTime) t opacity: (GLubyte) o { @@ -908,34 +1059,33 @@ +(id) actionWithDuration: (ccTime) t opacity: (GLubyte) o -(id) initWithDuration: (ccTime) t opacity: (GLubyte) o { if( (self=[super initWithDuration: t] ) ) - toOpacity = o; - + toOpacity_ = o; + return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] opacity: toOpacity]; + CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] opacity:toOpacity_]; return copy; } -(void) startWithTarget:(CCNode *)aTarget { [super startWithTarget:aTarget]; - fromOpacity = [(id)target_ opacity]; + fromOpacity_ = [(id)target_ opacity]; } -(void) update: (ccTime) t { - [(id)target_ setOpacity: fromOpacity + ( toOpacity - fromOpacity ) * t]; + [(id)target_ setOpacity:fromOpacity_ + ( toOpacity_ - fromOpacity_ ) * t]; } @end // // TintTo // -#pragma mark - -#pragma mark TintTo +#pragma mark - CCTintTo @implementation CCTintTo +(id) actionWithDuration:(ccTime)t red:(GLubyte)r green:(GLubyte)g blue:(GLubyte)b { @@ -944,38 +1094,37 @@ +(id) actionWithDuration:(ccTime)t red:(GLubyte)r green:(GLubyte)g blue:(GLubyte -(id) initWithDuration: (ccTime) t red:(GLubyte)r green:(GLubyte)g blue:(GLubyte)b { - if( (self=[super initWithDuration: t] ) ) - to = ccc3(r,g,b); - + if( (self=[super initWithDuration:t] ) ) + to_ = ccc3(r,g,b); + return self; } -(id) copyWithZone: (NSZone*) zone { - CCAction *copy = [(CCTintTo*)[[self class] allocWithZone: zone] initWithDuration: [self duration] red:to.r green:to.g blue:to.b]; + CCAction *copy = [(CCTintTo*)[[self class] allocWithZone: zone] initWithDuration:[self duration] red:to_.r green:to_.g blue:to_.b]; return copy; } -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - + id tn = (id) target_; - from = [tn color]; + from_ = [tn color]; } -(void) update: (ccTime) t { id tn = (id) target_; - [tn setColor:ccc3(from.r + (to.r - from.r) * t, from.g + (to.g - from.g) * t, from.b + (to.b - from.b) * t)]; + [tn setColor:ccc3(from_.r + (to_.r - from_.r) * t, from_.g + (to_.g - from_.g) * t, from_.b + (to_.b - from_.b) * t)]; } @end // // TintBy // -#pragma mark - -#pragma mark TintBy +#pragma mark - CCTintBy @implementation CCTintBy +(id) actionWithDuration:(ccTime)t red:(GLshort)r green:(GLshort)g blue:(GLshort)b { @@ -985,46 +1134,45 @@ +(id) actionWithDuration:(ccTime)t red:(GLshort)r green:(GLshort)g blue:(GLshort -(id) initWithDuration:(ccTime)t red:(GLshort)r green:(GLshort)g blue:(GLshort)b { if( (self=[super initWithDuration: t] ) ) { - deltaR = r; - deltaG = g; - deltaB = b; + deltaR_ = r; + deltaG_ = g; + deltaB_ = b; } return self; } -(id) copyWithZone: (NSZone*) zone { - return[(CCTintBy*)[[self class] allocWithZone: zone] initWithDuration: [self duration] red:deltaR green:deltaG blue:deltaB]; + return[(CCTintBy*)[[self class] allocWithZone: zone] initWithDuration: [self duration] red:deltaR_ green:deltaG_ blue:deltaB_]; } -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - + id tn = (id) target_; ccColor3B color = [tn color]; - fromR = color.r; - fromG = color.g; - fromB = color.b; + fromR_ = color.r; + fromG_ = color.g; + fromB_ = color.b; } -(void) update: (ccTime) t { id tn = (id) target_; - [tn setColor:ccc3( fromR + deltaR * t, fromG + deltaG * t, fromB + deltaB * t)]; + [tn setColor:ccc3( fromR_ + deltaR_ * t, fromG_ + deltaG_ * t, fromB_ + deltaB_ * t)]; } - (CCActionInterval*) reverse { - return [CCTintBy actionWithDuration:duration_ red:-deltaR green:-deltaG blue:-deltaB]; + return [CCTintBy actionWithDuration:duration_ red:-deltaR_ green:-deltaG_ blue:-deltaB_]; } @end // // DelayTime // -#pragma mark - -#pragma mark DelayTime +#pragma mark - CCDelayTime @implementation CCDelayTime -(void) update: (ccTime) t { @@ -1040,55 +1188,60 @@ -(id)reverse // // ReverseTime // -#pragma mark - -#pragma mark ReverseTime +#pragma mark - CCReverseTime @implementation CCReverseTime +(id) actionWithAction: (CCFiniteTimeAction*) action { // casting to prevent warnings - CCReverseTime *a = [super alloc]; + CCReverseTime *a = [self alloc]; return [[a initWithAction:action] autorelease]; } -(id) initWithAction: (CCFiniteTimeAction*) action { - if( (self=[super initWithDuration: [action duration]]) ) - other = [action retain]; - + NSAssert(action != nil, @"CCReverseTime: action should not be nil"); + NSAssert(action != other_, @"CCReverseTime: re-init doesn't support using the same arguments"); + + if( (self=[super initWithDuration: [action duration]]) ) { + // Don't leak if action is reused + [other_ release]; + other_ = [action retain]; + } + return self; } -(id) copyWithZone: (NSZone*) zone { - return [[[self class] allocWithZone: zone] initWithAction:[[other copy] autorelease] ]; + return [[[self class] allocWithZone: zone] initWithAction:[[other_ copy] autorelease] ]; } -(void) dealloc { - [other release]; + [other_ release]; [super dealloc]; } -(void) startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - [other startWithTarget:target_]; + [other_ startWithTarget:target_]; } -(void) stop { - [other stop]; + [other_ stop]; [super stop]; } -(void) update:(ccTime)t { - [other update:1-t]; + [other_ update:1-t]; } -(CCActionInterval*) reverse { - return [[other copy] autorelease]; + return [[other_ copy] autorelease]; } @end @@ -1096,55 +1249,42 @@ -(CCActionInterval*) reverse // Animate // -#pragma mark - -#pragma mark Animate +#pragma mark - CCAnimate @implementation CCAnimate @synthesize animation = animation_; +(id) actionWithAnimation: (CCAnimation*)anim { - return [[[self alloc] initWithAnimation:anim restoreOriginalFrame:YES] autorelease]; -} - -+(id) actionWithAnimation: (CCAnimation*)anim restoreOriginalFrame:(BOOL)b -{ - return [[[self alloc] initWithAnimation:anim restoreOriginalFrame:b] autorelease]; + return [[[self alloc] initWithAnimation:anim] autorelease]; } -+(id) actionWithDuration:(ccTime)duration animation: (CCAnimation*)anim restoreOriginalFrame:(BOOL)b -{ - return [[[self alloc] initWithDuration:duration animation:anim restoreOriginalFrame:b] autorelease]; -} - --(id) initWithAnimation: (CCAnimation*)anim -{ - NSAssert( anim!=nil, @"Animate: argument Animation must be non-nil"); - return [self initWithAnimation:anim restoreOriginalFrame:YES]; -} - --(id) initWithAnimation: (CCAnimation*)anim restoreOriginalFrame:(BOOL) b +// delegate initializer +-(id) initWithAnimation:(CCAnimation*)anim { NSAssert( anim!=nil, @"Animate: argument Animation must be non-nil"); + + float singleDuration = anim.duration; - if( (self=[super initWithDuration: [[anim frames] count] * [anim delay]]) ) { + if( (self=[super initWithDuration:singleDuration * anim.loops] ) ) { - restoreOriginalFrame = b; + nextFrame_ = 0; self.animation = anim; - origFrame = nil; - } - return self; -} - --(id) initWithDuration:(ccTime)aDuration animation: (CCAnimation*)anim restoreOriginalFrame:(BOOL) b -{ - NSAssert( anim!=nil, @"Animate: argument Animation must be non-nil"); - - if( (self=[super initWithDuration:aDuration] ) ) { + origFrame_ = nil; + executedLoops_ = 0; - restoreOriginalFrame = b; - self.animation = anim; - origFrame = nil; + splitTimes_ = [[NSMutableArray alloc] initWithCapacity:anim.frames.count]; + + float accumUnitsOfTime = 0; + float newUnitOfTimeValue = singleDuration / anim.totalDelayUnits; + + for( CCAnimationFrame *frame in anim.frames ) { + + NSNumber *value = [NSNumber numberWithFloat: (accumUnitsOfTime * newUnitOfTimeValue) / singleDuration]; + accumUnitsOfTime += frame.delayUnits; + + [splitTimes_ addObject:value]; + } } return self; } @@ -1152,13 +1292,14 @@ -(id) initWithDuration:(ccTime)aDuration animation: (CCAnimation*)anim restoreOr -(id) copyWithZone: (NSZone*) zone { - return [[[self class] allocWithZone: zone] initWithDuration:duration_ animation:animation_ restoreOriginalFrame:restoreOriginalFrame]; + return [[[self class] allocWithZone: zone] initWithAnimation:[[animation_ copy]autorelease] ]; } -(void) dealloc { + [splitTimes_ release]; [animation_ release]; - [origFrame release]; + [origFrame_ release]; [super dealloc]; } @@ -1167,35 +1308,64 @@ -(void) startWithTarget:(id)aTarget [super startWithTarget:aTarget]; CCSprite *sprite = target_; - [origFrame release]; + [origFrame_ release]; - if( restoreOriginalFrame ) - origFrame = [[sprite displayedFrame] retain]; + if( animation_.restoreOriginalFrame ) + origFrame_ = [[sprite displayFrame] retain]; + + nextFrame_ = 0; + executedLoops_ = 0; } -(void) stop { - if( restoreOriginalFrame ) { + if( animation_.restoreOriginalFrame ) { CCSprite *sprite = target_; - [sprite setDisplayFrame:origFrame]; + [sprite setDisplayFrame:origFrame_]; } - + [super stop]; } -(void) update: (ccTime) t { + + // if t==1, ignore. Animation should finish with t==1 + if( t < 1.0f ) { + t *= animation_.loops; + + // new loop? If so, reset frame counter + NSUInteger loopNumber = (NSUInteger)t; + if( loopNumber > executedLoops_ ) { + nextFrame_ = 0; + executedLoops_++; + } + + // new t for animations + t = fmodf(t, 1.0f); + } + NSArray *frames = [animation_ frames]; NSUInteger numberOfFrames = [frames count]; - - NSUInteger idx = t * numberOfFrames; + CCSpriteFrame *frameToDisplay = nil; - if( idx >= numberOfFrames ) - idx = numberOfFrames -1; - - CCSprite *sprite = target_; - if (! [sprite isFrameDisplayed: [frames objectAtIndex: idx]] ) - [sprite setDisplayFrame: [frames objectAtIndex:idx]]; + for( NSUInteger i=nextFrame_; i < numberOfFrames; i++ ) { + NSNumber *splitTime = [splitTimes_ objectAtIndex:i]; + + if( [splitTime floatValue] <= t ) { + CCAnimationFrame *frame = [frames objectAtIndex:i]; + frameToDisplay = [frame spriteFrame]; + [(CCSprite*)target_ setDisplayFrame: frameToDisplay]; + + NSDictionary *dict = [frame userInfo]; + if( dict ) + [[NSNotificationCenter defaultCenter] postNotificationName:CCAnimationFrameDisplayedNotification object:target_ userInfo:dict]; + + nextFrame_ = i+1; + + break; + } + } } - (CCActionInterval *) reverse @@ -1205,9 +1375,68 @@ - (CCActionInterval *) reverse NSEnumerator *enumerator = [oldArray reverseObjectEnumerator]; for (id element in enumerator) [newArray addObject:[[element copy] autorelease]]; - - CCAnimation *newAnim = [CCAnimation animationWithFrames:newArray delay:animation_.delay]; - return [[self class] actionWithDuration:duration_ animation:newAnim restoreOriginalFrame:restoreOriginalFrame]; + + CCAnimation *newAnim = [CCAnimation animationWithAnimationFrames:newArray delayPerUnit:animation_.delayPerUnit loops:animation_.loops]; + newAnim.restoreOriginalFrame = animation_.restoreOriginalFrame; + return [[self class] actionWithAnimation:newAnim]; +} +@end + + +#pragma mark - CCTargetedAction + +@implementation CCTargetedAction + +@synthesize forcedTarget = forcedTarget_; + ++ (id) actionWithTarget:(id) target action:(CCFiniteTimeAction*) action +{ + return [[ (CCTargetedAction*)[self alloc] initWithTarget:target action:action] autorelease]; +} + +- (id) initWithTarget:(id) targetIn action:(CCFiniteTimeAction*) actionIn +{ + if((self = [super initWithDuration:actionIn.duration])) + { + forcedTarget_ = [targetIn retain]; + action_ = [actionIn retain]; + } + return self; +} + +-(id) copyWithZone: (NSZone*) zone +{ + CCAction *copy = [ (CCTargetedAction*) [[self class] allocWithZone: zone] initWithTarget:target_ action:[[action_ copy] autorelease]]; + return copy; +} + +- (void) dealloc +{ + [forcedTarget_ release]; + [action_ release]; + [super dealloc]; +} + +//- (void) updateDuration:(id)aTarget +//{ +// [action updateDuration:forcedTarget]; +// duration_ = action.duration; +//} + +- (void) startWithTarget:(id)aTarget +{ + [super startWithTarget:forcedTarget_]; + [action_ startWithTarget:forcedTarget_]; +} + +- (void) stop +{ + [action_ stop]; +} + +- (void) update:(ccTime) time +{ + [action_ update:time]; } @end diff --git a/Example/libs/cocos2d/CCActionManager.h b/Example/libs/cocos2d/CCActionManager.h index 476390b..33a32eb 100644 --- a/Example/libs/cocos2d/CCActionManager.h +++ b/Example/libs/cocos2d/CCActionManager.h @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada * Copyright (c) 2009 Valentin Milea * + * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,29 +28,32 @@ #import "CCAction.h" +#import "ccMacros.h" #import "Support/ccCArray.h" #import "Support/uthash.h" +#define kCCActionManagerPriority 0 + typedef struct _hashElement { struct ccArray *actions; - id target; - unsigned int actionIndex; - CCAction *currentAction; + NSUInteger actionIndex; BOOL currentActionSalvaged; - BOOL paused; + BOOL paused; UT_hash_handle hh; + + CC_ARC_UNSAFE_RETAINED id target; + CC_ARC_UNSAFE_RETAINED CCAction *currentAction; } tHashElement; -/** CCActionManager is a singleton that manages all the actions. - Normally you won't need to use this singleton directly. 99% of the cases you will use the CCNode interface, - which uses this singleton. - But there are some cases where you might need to use this singleton. +/** CCActionManager the object that manages all the actions. + Normally you won't need to use this API directly. 99% of the cases you will use the CCNode interface, which uses this object. + But there are some cases where you might need to use this API dirctly: Examples: - - When you want to run an action where the target is different from a CCNode. + - When you want to run an action where the target is different from a CCNode. - When you want to pause / resume the actions - + @since v0.8 */ @interface CCActionManager : NSObject @@ -58,13 +63,6 @@ typedef struct _hashElement BOOL currentTargetSalvaged; } -/** returns a shared instance of the CCActionManager */ -+ (CCActionManager *)sharedManager; - -/** purges the shared action manager. It releases the retained instance. - @since v0.99.0 - */ -+(void)purgeSharedManager; // actions @@ -86,17 +84,17 @@ typedef struct _hashElement */ -(void) removeAction: (CCAction*) action; /** Removes an action given its tag and the target */ --(void) removeActionByTag:(int)tag target:(id)target; +-(void) removeActionByTag:(NSInteger)tag target:(id)target; /** Gets an action given its tag an a target @return the Action the with the given tag */ --(CCAction*) getActionByTag:(int) tag target:(id)target; +-(CCAction*) getActionByTag:(NSInteger) tag target:(id)target; /** Returns the numbers of actions that are running in a certain target * Composable actions are counted as 1 action. Example: * If you are running 1 Sequence of 7 actions, it will return 1. * If you are running 7 Sequences of 2 actions, it will return 7. */ --(int) numberOfRunningActionsInTarget:(id)target; +-(NSUInteger) numberOfRunningActionsInTarget:(id)target; /** Pauses the target: all running actions and newly added actions will be paused. */ @@ -105,14 +103,5 @@ typedef struct _hashElement */ -(void) resumeTarget:(id)target; -/** Resumes the target. All queued actions will be resumed. - @deprecated Use resumeTarget: instead. Will be removed in v1.0. - */ --(void) resumeAllActionsForTarget:(id)target DEPRECATED_ATTRIBUTE; -/** Pauses the target: all running actions and newly added actions will be paused. - */ --(void) pauseAllActionsForTarget:(id)target DEPRECATED_ATTRIBUTE; - - @end diff --git a/Example/libs/cocos2d/CCActionManager.m b/Example/libs/cocos2d/CCActionManager.m index 9a6376f..79e2203 100644 --- a/Example/libs/cocos2d/CCActionManager.m +++ b/Example/libs/cocos2d/CCActionManager.m @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada * Copyright (c) 2009 Valentin Milea * + * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,12 +31,6 @@ #import "CCScheduler.h" #import "ccMacros.h" - -// -// singleton stuff -// -static CCActionManager *sharedManager_ = nil; - @interface CCActionManager (Private) -(void) removeActionAtIndex:(NSUInteger)index hashElement:(tHashElement*)element; -(void) deleteHashElement:(tHashElement*)element; @@ -44,45 +40,25 @@ -(void) actionAllocWithHashElement:(tHashElement*)element; @implementation CCActionManager -#pragma mark ActionManager - init -+ (CCActionManager *)sharedManager -{ - if (!sharedManager_) - sharedManager_ = [[self alloc] init]; - - return sharedManager_; -} - -+(id)alloc -{ - NSAssert(sharedManager_ == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; -} - -+(void)purgeSharedManager -{ - [[CCScheduler sharedScheduler] unscheduleUpdateForTarget:self]; - [sharedManager_ release]; - sharedManager_ = nil; -} - -(id) init { if ((self=[super init]) ) { - [[CCScheduler sharedScheduler] scheduleUpdateForTarget:self priority:0 paused:NO]; targets = NULL; } - + return self; } +- (NSString*) description +{ + return [NSString stringWithFormat:@"<%@ = %08X>", [self class], self]; +} + - (void) dealloc { CCLOGINFO( @"cocos2d: deallocing %@", self); - - [self removeAllActions]; - sharedManager_ = nil; + [self removeAllActions]; [super dealloc]; } @@ -104,24 +80,24 @@ -(void) actionAllocWithHashElement:(tHashElement*)element if( element->actions == nil ) element->actions = ccArrayNew(4); else if( element->actions->num == element->actions->max ) - ccArrayDoubleCapacity(element->actions); + ccArrayDoubleCapacity(element->actions); } -(void) removeActionAtIndex:(NSUInteger)index hashElement:(tHashElement*)element -{ +{ id action = element->actions->arr[index]; if( action == element->currentAction && !element->currentActionSalvaged ) { [element->currentAction retain]; element->currentActionSalvaged = YES; } - + ccArrayRemoveObjectAtIndex(element->actions, index); // update actionIndex in case we are in tick:, looping over the actions if( element->actionIndex >= index ) element->actionIndex--; - + if( element->actions->num == 0 ) { if( currentTarget == element ) currentTargetSalvaged = YES; @@ -132,12 +108,6 @@ -(void) removeActionAtIndex:(NSUInteger)index hashElement:(tHashElement*)element #pragma mark ActionManager - Pause / Resume -// XXX DEPRECATED. REMOVE IN 1.0 --(void) pauseAllActionsForTarget:(id)target -{ - [self pauseTarget:target]; -} - -(void) pauseTarget:(id)target { tHashElement *element = NULL; @@ -148,12 +118,6 @@ -(void) pauseTarget:(id)target // CCLOG(@"cocos2d: pauseAllActions: Target not found"); } -// XXX DEPRECATED. REMOVE IN 1.0 --(void) resumeAllActionsForTarget:(id)target -{ - [self resumeTarget:target]; -} - -(void) resumeTarget:(id)target { tHashElement *element = NULL; @@ -169,8 +133,8 @@ -(void) resumeTarget:(id)target -(void) addAction:(CCAction*)action target:(id)target paused:(BOOL)paused { NSAssert( action != nil, @"Argument action must be non-nil"); - NSAssert( target != nil, @"Argument target must be non-nil"); - + NSAssert( target != nil, @"Argument target must be non-nil"); + tHashElement *element = NULL; HASH_FIND_INT(targets, &target, element); if( ! element ) { @@ -181,12 +145,12 @@ -(void) addAction:(CCAction*)action target:(id)target paused:(BOOL)paused // CCLOG(@"cocos2d: ---- buckets: %d/%d - %@", targets->entries, targets->size, element->target); } - + [self actionAllocWithHashElement:element]; - NSAssert( !ccArrayContainsObject(element->actions, action), @"runAction: Action already running"); + NSAssert( !ccArrayContainsObject(element->actions, action), @"runAction: Action already running"); ccArrayAppendObject(element->actions, action); - + [action startWithTarget:target]; } @@ -194,7 +158,7 @@ -(void) addAction:(CCAction*)action target:(id)target paused:(BOOL)paused -(void) removeAllActions { - for(tHashElement *element=targets; element != NULL; ) { + for(tHashElement *element=targets; element != NULL; ) { id target = element->target; element = element->hh.next; [self removeAllActionsFromTarget:target]; @@ -205,7 +169,7 @@ -(void) removeAllActionsFromTarget:(id)target // explicit nil handling if( target == nil ) return; - + tHashElement *element = NULL; HASH_FIND_INT(targets, &target, element); if( element ) { @@ -229,7 +193,7 @@ -(void) removeAction: (CCAction*) action // explicit nil handling if (action == nil) return; - + tHashElement *element = NULL; id target = [action originalTarget]; HASH_FIND_INT(targets, &target, element ); @@ -243,32 +207,31 @@ -(void) removeAction: (CCAction*) action // } } --(void) removeActionByTag:(int) aTag target:(id)target +-(void) removeActionByTag:(NSInteger)aTag target:(id)target { NSAssert( aTag != kCCActionTagInvalid, @"Invalid tag"); NSAssert( target != nil, @"Target should be ! nil"); - + tHashElement *element = NULL; HASH_FIND_INT(targets, &target, element); - + if( element ) { NSUInteger limit = element->actions->num; for( NSUInteger i = 0; i < limit; i++) { CCAction *a = element->actions->arr[i]; - - if( a.tag == aTag && [a originalTarget]==target) - return [self removeActionAtIndex:i hashElement:element]; + + if( a.tag == aTag && [a originalTarget]==target) { + [self removeActionAtIndex:i hashElement:element]; + break; + } } -// CCLOG(@"cocos2d: removeActionByTag: Action not found!"); + } -// else { -// CCLOG(@"cocos2d: removeActionByTag: Target not found!"); -// } } #pragma mark ActionManager - get --(CCAction*) getActionByTag:(int)aTag target:(id)target +-(CCAction*) getActionByTag:(NSInteger)aTag target:(id)target { NSAssert( aTag != kCCActionTagInvalid, @"Invalid tag"); @@ -280,9 +243,9 @@ -(CCAction*) getActionByTag:(int)aTag target:(id)target NSUInteger limit = element->actions->num; for( NSUInteger i = 0; i < limit; i++) { CCAction *a = element->actions->arr[i]; - + if( a.tag == aTag ) - return a; + return a; } } // CCLOG(@"cocos2d: getActionByTag: Action not found"); @@ -293,7 +256,7 @@ -(CCAction*) getActionByTag:(int)aTag target:(id)target return nil; } --(int) numberOfRunningActionsInTarget:(id) target +-(NSUInteger) numberOfRunningActionsInTarget:(id) target { tHashElement *element = NULL; HASH_FIND_INT(targets, &target, element); @@ -308,18 +271,18 @@ -(int) numberOfRunningActionsInTarget:(id) target -(void) update: (ccTime) dt { - for(tHashElement *elt = targets; elt != NULL; ) { + for(tHashElement *elt = targets; elt != NULL; ) { currentTarget = elt; currentTargetSalvaged = NO; - + if( ! currentTarget->paused ) { - + // The 'actions' ccArray may change while inside this loop. for( currentTarget->actionIndex = 0; currentTarget->actionIndex < currentTarget->actions->num; currentTarget->actionIndex++) { currentTarget->currentAction = currentTarget->actions->arr[currentTarget->actionIndex]; currentTarget->currentActionSalvaged = NO; - + [currentTarget->currentAction step: dt]; if( currentTarget->currentActionSalvaged ) { @@ -330,13 +293,13 @@ -(void) update: (ccTime) dt } else if( [currentTarget->currentAction isDone] ) { [currentTarget->currentAction stop]; - + CCAction *a = currentTarget->currentAction; // Make currentAction nil to prevent removeAction from salvaging it. currentTarget->currentAction = nil; [self removeAction:a]; } - + currentTarget->currentAction = nil; } } @@ -344,12 +307,12 @@ -(void) update: (ccTime) dt // elt, at this moment, is still valid // so it is safe to ask this here (issue #490) elt = elt->hh.next; - + // only delete currentTarget if no actions were scheduled during the cycle (issue #481) if( currentTargetSalvaged && currentTarget->actions->num == 0 ) [self deleteHashElement:currentTarget]; } - + // issue #635 currentTarget = nil; } diff --git a/Example/libs/cocos2d/CCActionPageTurn3D.h b/Example/libs/cocos2d/CCActionPageTurn3D.h index 39eb31d..6199aff 100644 --- a/Example/libs/cocos2d/CCActionPageTurn3D.h +++ b/Example/libs/cocos2d/CCActionPageTurn3D.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,7 +32,7 @@ * * Based on an original paper by L Hong et al. * http://www.parc.com/publication/1638/turning-pages-of-3d-electronic-books.html - * + * * @since v0.8.2 */ @interface CCPageTurn3D : CCGrid3DAction diff --git a/Example/libs/cocos2d/CCActionPageTurn3D.m b/Example/libs/cocos2d/CCActionPageTurn3D.m index ee59500..cff9bc2 100644 --- a/Example/libs/cocos2d/CCActionPageTurn3D.m +++ b/Example/libs/cocos2d/CCActionPageTurn3D.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,26 +36,26 @@ -(void)update:(ccTime)time float tt = MAX( 0, time - 0.25f ); float deltaAy = ( tt * tt * 500); float ay = -100 - deltaAy; - + float deltaTheta = - (float) M_PI_2 * sqrtf( time) ; float theta = /*0.01f*/ + (float) M_PI_2 +deltaTheta; - + float sinTheta = sinf(theta); float cosTheta = cosf(theta); - + for( int i = 0; i <=gridSize_.x; i++ ) { for( int j = 0; j <= gridSize_.y; j++ ) { // Get original vertex ccVertex3F p = [self originalVertex:ccg(i,j)]; - + float R = sqrtf(p.x*p.x + (p.y - ay) * (p.y - ay)); float r = R * sinTheta; float alpha = asinf( p.x / R ); float beta = alpha / sinTheta; float cosBeta = cosf( beta ); - + // If beta > PI then we've wrapped around the cone // Reduce the radius to stop these points interfering with others if( beta <= M_PI) @@ -66,18 +66,18 @@ -(void)update:(ccTime)time // points p.x = 0; } - + p.y = ( R + ay - ( r*(1 - cosBeta)*sinTheta)); - + // We scale z here to avoid the animation being // too much bigger than the screen due to perspectve transform p.z = (r * ( 1 - cosBeta ) * cosTheta) / 7; // "100" didn't work for - + // Stop z coord from dropping beneath underlying page in a transition - // issue #751 + // issue #751 if( p.z<0.5f ) p.z = 0.5f; - + // Set new coords [self setVertex:ccg(i,j) vertex:p]; } diff --git a/Example/libs/cocos2d/CCActionProgressTimer.h b/Example/libs/cocos2d/CCActionProgressTimer.h index 500631b..2b9e771 100644 --- a/Example/libs/cocos2d/CCActionProgressTimer.h +++ b/Example/libs/cocos2d/CCActionProgressTimer.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/Example/libs/cocos2d/CCActionProgressTimer.m b/Example/libs/cocos2d/CCActionProgressTimer.m index c242570..d5e2993 100644 --- a/Example/libs/cocos2d/CCActionProgressTimer.m +++ b/Example/libs/cocos2d/CCActionProgressTimer.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,7 +38,7 @@ -(id) initWithDuration: (ccTime) t percent: (float) v { if( (self=[super initWithDuration: t] ) ) to_ = v; - + return self; } @@ -52,7 +52,7 @@ -(void) startWithTarget:(id) aTarget; { [super startWithTarget:aTarget]; from_ = [(kProgressTimerCast)target_ percentage]; - + // XXX: Is this correct ? // Adding it to support CCRepeat if( from_ == 100) diff --git a/Example/libs/cocos2d/CCActionTiledGrid.h b/Example/libs/cocos2d/CCActionTiledGrid.h index 5d88b16..42b23a6 100644 --- a/Example/libs/cocos2d/CCActionTiledGrid.h +++ b/Example/libs/cocos2d/CCActionTiledGrid.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -64,7 +64,7 @@ @interface CCShuffleTiles : CCTiledGrid3DAction { int seed; - int tilesCount; + NSUInteger tilesCount; int *tilesOrder; void *tiles; } @@ -124,7 +124,7 @@ @interface CCTurnOffTiles : CCTiledGrid3DAction { int seed; - int tilesCount; + NSUInteger tilesCount; int *tilesOrder; } diff --git a/Example/libs/cocos2d/CCActionTiledGrid.m b/Example/libs/cocos2d/CCActionTiledGrid.m index 4513866..f8d6a2d 100644 --- a/Example/libs/cocos2d/CCActionTiledGrid.m +++ b/Example/libs/cocos2d/CCActionTiledGrid.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -53,7 +53,7 @@ -(id)initWithRange:(int)range shakeZ:(BOOL)sz grid:(ccGridSize)gSize duration:(c randrange = range; shakeZ = sz; } - + return self; } @@ -67,7 +67,7 @@ -(id) copyWithZone: (NSZone*) zone -(void)update:(ccTime)time { int i, j; - + for( i = 0; i < gridSize_.x; i++ ) { for( j = 0; j < gridSize_.y; j++ ) @@ -92,7 +92,7 @@ -(void)update:(ccTime)time coords.tl.z += ( rand() % (randrange*2) ) - randrange; coords.tr.z += ( rand() % (randrange*2) ) - randrange; } - + [self setTile:ccg(i,j) coords:coords]; } } @@ -120,7 +120,7 @@ -(id)initWithRange:(int)range shatterZ:(BOOL)sz grid:(ccGridSize)gSize duration: randrange = range; shatterZ = sz; } - + return self; } @@ -134,7 +134,7 @@ -(id) copyWithZone: (NSZone*) zone -(void)update:(ccTime)time { int i, j; - + if ( once == NO ) { for( i = 0; i < gridSize_.x; i++ ) @@ -142,13 +142,13 @@ -(void)update:(ccTime)time for( j = 0; j < gridSize_.y; j++ ) { ccQuad3 coords = [self originalTile:ccg(i,j)]; - + // X coords.bl.x += ( rand() % (randrange*2) ) - randrange; coords.br.x += ( rand() % (randrange*2) ) - randrange; coords.tl.x += ( rand() % (randrange*2) ) - randrange; coords.tr.x += ( rand() % (randrange*2) ) - randrange; - + // Y coords.bl.y += ( rand() % (randrange*2) ) - randrange; coords.br.y += ( rand() % (randrange*2) ) - randrange; @@ -157,15 +157,15 @@ -(void)update:(ccTime)time if( shatterZ ) { coords.bl.z += ( rand() % (randrange*2) ) - randrange; - coords.br.z += ( rand() % (randrange*2) ) - randrange; + coords.br.z += ( rand() % (randrange*2) ) - randrange; coords.tl.z += ( rand() % (randrange*2) ) - randrange; coords.tr.z += ( rand() % (randrange*2) ) - randrange; } - + [self setTile:ccg(i,j) coords:coords]; } } - + once = YES; } } @@ -192,7 +192,7 @@ -(id)initWithSeed:(int)s grid:(ccGridSize)gSize duration:(ccTime)d tilesOrder = nil; tiles = nil; } - + return self; } @@ -210,12 +210,12 @@ -(void)dealloc [super dealloc]; } --(void)shuffle:(int*)array count:(int)len +-(void)shuffle:(int*)array count:(NSUInteger)len { - int i; + NSInteger i; for( i = len - 1; i >= 0; i-- ) { - int j = rand() % (i+1); + NSInteger j = rand() % (i+1); int v = array[i]; array[i] = array[j]; array[j] = v; @@ -225,19 +225,19 @@ -(void)shuffle:(int*)array count:(int)len -(ccGridSize)getDelta:(ccGridSize)pos { CGPoint pos2; - - int idx = pos.x * gridSize_.y + pos.y; - + + NSInteger idx = pos.x * gridSize_.y + pos.y; + pos2.x = tilesOrder[idx] / (int)gridSize_.y; pos2.y = tilesOrder[idx] % (int)gridSize_.y; - + return ccg(pos2.x - pos.x, pos2.y - pos.y); } -(void)placeTile:(ccGridSize)pos tile:(Tile)t { ccQuad3 coords = [self originalTile:pos]; - + CGPoint step = [[target_ grid] step]; coords.bl.x += (int)(t.position.x * step.x); coords.bl.y += (int)(t.position.y * step.y); @@ -257,22 +257,22 @@ -(void)placeTile:(ccGridSize)pos tile:(Tile)t -(void)startWithTarget:(id)aTarget { [super startWithTarget:aTarget]; - + if ( seed != -1 ) srand(seed); - + tilesCount = gridSize_.x * gridSize_.y; tilesOrder = (int*)malloc(tilesCount*sizeof(int)); int i, j; - + for( i = 0; i < tilesCount; i++ ) tilesOrder[i] = i; - + [self shuffle:tilesOrder count:tilesCount]; - + tiles = malloc(tilesCount*sizeof(Tile)); Tile *tileArray = (Tile*)tiles; - + for( i = 0; i < gridSize_.x; i++ ) { for( j = 0; j < gridSize_.y; j++ ) @@ -288,9 +288,9 @@ -(void)startWithTarget:(id)aTarget -(void)update:(ccTime)time { int i, j; - + Tile *tileArray = (Tile*)tiles; - + for( i = 0; i < gridSize_.x; i++ ) { for( j = 0; j < gridSize_.y; j++ ) @@ -316,7 +316,7 @@ -(float)testFunc:(ccGridSize)pos time:(ccTime)time CGPoint n = ccpMult( ccp(gridSize_.x,gridSize_.y), time); if ( (n.x+n.y) == 0.0f ) return 1.0f; - + return powf( (pos.x+pos.y) / (n.x+n.y), 6 ); } @@ -327,7 +327,7 @@ -(void)turnOnTile:(ccGridSize)pos -(void)turnOffTile:(ccGridSize)pos { - ccQuad3 coords; + ccQuad3 coords; bzero(&coords, sizeof(ccQuad3)); [self setTile:pos coords:coords]; } @@ -336,7 +336,7 @@ -(void)transformTile:(ccGridSize)pos distance:(float)distance { ccQuad3 coords = [self originalTile:pos]; CGPoint step = [[target_ grid] step]; - + coords.bl.x += (step.x / 2) * (1.0f - distance); coords.bl.y += (step.y / 2) * (1.0f - distance); @@ -355,7 +355,7 @@ -(void)transformTile:(ccGridSize)pos distance:(float)distance -(void)update:(ccTime)time { int i, j; - + for( i = 0; i < gridSize_.x; i++ ) { for( j = 0; j < gridSize_.y; j++ ) @@ -385,7 +385,7 @@ -(float)testFunc:(ccGridSize)pos time:(ccTime)time CGPoint n = ccpMult(ccp(gridSize_.x, gridSize_.y), (1.0f-time)); if ( (pos.x+pos.y) == 0 ) return 1.0f; - + return powf( (n.x+n.y) / (pos.x+pos.y), 6 ); } @@ -403,7 +403,7 @@ -(float)testFunc:(ccGridSize)pos time:(ccTime)time CGPoint n = ccpMult(ccp(gridSize_.x, gridSize_.y), time); if ( n.y == 0 ) return 1.0f; - + return powf( pos.y / n.y, 6 ); } @@ -411,12 +411,12 @@ -(void)transformTile:(ccGridSize)pos distance:(float)distance { ccQuad3 coords = [self originalTile:pos]; CGPoint step = [[target_ grid] step]; - + coords.bl.y += (step.y / 2) * (1.0f - distance); coords.br.y += (step.y / 2) * (1.0f - distance); coords.tl.y -= (step.y / 2) * (1.0f - distance); coords.tr.y -= (step.y / 2) * (1.0f - distance); - + [self setTile:pos coords:coords]; } @@ -434,7 +434,7 @@ -(float)testFunc:(ccGridSize)pos time:(ccTime)time CGPoint n = ccpMult(ccp(gridSize_.x,gridSize_.y), (1.0f - time)); if ( pos.y == 0 ) return 1.0f; - + return powf( n.y / pos.y, 6 ); } @@ -459,7 +459,7 @@ -(id)initWithSeed:(int)s grid:(ccGridSize)gSize duration:(ccTime)d seed = s; tilesOrder = nil; } - + return self; } @@ -475,12 +475,12 @@ -(void)dealloc [super dealloc]; } --(void)shuffle:(int*)array count:(int)len +-(void)shuffle:(int*)array count:(NSUInteger)len { - int i; + NSInteger i; for( i = len - 1; i >= 0; i-- ) { - int j = rand() % (i+1); + NSInteger j = rand() % (i+1); int v = array[i]; array[i] = array[j]; array[j] = v; @@ -495,7 +495,7 @@ -(void)turnOnTile:(ccGridSize)pos -(void)turnOffTile:(ccGridSize)pos { ccQuad3 coords; - + bzero(&coords, sizeof(ccQuad3)); [self setTile:pos coords:coords]; } @@ -503,32 +503,32 @@ -(void)turnOffTile:(ccGridSize)pos -(void)startWithTarget:(id)aTarget { int i; - + [super startWithTarget:aTarget]; - + if ( seed != -1 ) srand(seed); - + tilesCount = gridSize_.x * gridSize_.y; tilesOrder = (int*)malloc(tilesCount*sizeof(int)); for( i = 0; i < tilesCount; i++ ) tilesOrder[i] = i; - + [self shuffle:tilesOrder count:tilesCount]; } -(void)update:(ccTime)time { int i, l, t; - + l = (int)(time * (float)tilesCount); - + for( i = 0; i < tilesCount; i++ ) { t = tilesOrder[i]; ccGridSize tilePos = ccg( t / gridSize_.y, t % gridSize_.y ); - + if ( i < l ) [self turnOffTile:tilePos]; else @@ -561,7 +561,7 @@ -(id)initWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gSize duration amplitude = amp; amplitudeRate = 1.0f; } - + return self; } @@ -575,18 +575,18 @@ -(id) copyWithZone: (NSZone*) zone -(void)update:(ccTime)time { int i, j; - + for( i = 0; i < gridSize_.x; i++ ) { for( j = 0; j < gridSize_.y; j++ ) { ccQuad3 coords = [self originalTile:ccg(i,j)]; - + coords.bl.z = (sinf(time*(CGFloat)M_PI*waves*2 + (coords.bl.y+coords.bl.x) * .01f) * amplitude * amplitudeRate ); coords.br.z = coords.bl.z; coords.tl.z = coords.bl.z; coords.tr.z = coords.bl.z; - + [self setTile:ccg(i,j) coords:coords]; } } @@ -616,7 +616,7 @@ -(id)initWithJumps:(int)j amplitude:(float)amp grid:(ccGridSize)gSize duration:( amplitude = amp; amplitudeRate = 1.0f; } - + return self; } @@ -630,16 +630,16 @@ -(id) copyWithZone: (NSZone*) zone -(void)update:(ccTime)time { int i, j; - + float sinz = (sinf((CGFloat)M_PI*time*jumps*2) * amplitude * amplitudeRate ); float sinz2 = (sinf((CGFloat)M_PI*(time*jumps*2 + 1)) * amplitude * amplitudeRate ); - + for( i = 0; i < gridSize_.x; i++ ) { for( j = 0; j < gridSize_.y; j++ ) { ccQuad3 coords = [self originalTile:ccg(i,j)]; - + if ( ((i+j) % 2) == 0 ) { coords.bl.z += sinz; @@ -654,7 +654,7 @@ -(void)update:(ccTime)time coords.tl.z += sinz2; coords.tr.z += sinz2; } - + [self setTile:ccg(i,j) coords:coords]; } } @@ -694,20 +694,20 @@ -(void)startWithTarget:(id)aTarget -(void)update:(ccTime)time { int j; - + for( j = 0; j < gridSize_.y; j++ ) { ccQuad3 coords = [self originalTile:ccg(0,j)]; float direction = 1; - + if ( (j % 2 ) == 0 ) direction = -1; - + coords.bl.x += direction * winSize.width * time; coords.br.x += direction * winSize.width * time; coords.tl.x += direction * winSize.width * time; coords.tr.x += direction * winSize.width * time; - + [self setTile:ccg(0,j) coords:coords]; } } @@ -747,20 +747,20 @@ -(void)startWithTarget:(id)aTarget -(void)update:(ccTime)time { int i; - + for( i = 0; i < gridSize_.x; i++ ) { ccQuad3 coords = [self originalTile:ccg(i,0)]; float direction = 1; - + if ( (i % 2 ) == 0 ) direction = -1; - + coords.bl.y += direction * winSize.height * time; coords.br.y += direction * winSize.height * time; coords.tl.y += direction * winSize.height * time; coords.tr.y += direction * winSize.height * time; - + [self setTile:ccg(i,0) coords:coords]; } } diff --git a/Example/libs/cocos2d/CCActionTween.h b/Example/libs/cocos2d/CCActionTween.h index 69fdea5..378a828 100644 --- a/Example/libs/cocos2d/CCActionTween.h +++ b/Example/libs/cocos2d/CCActionTween.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,27 +28,27 @@ #import "CCActionInterval.h" /** CCActionTween - + CCActionTween is an action that lets you update any property of an object. - For example, if you want to modify the "width" property of a target from 200 to 300 in 2 senconds, then: - + For example, if you want to modify the "width" property of a target from 200 to 300 in 2 seconds, then: + id modifyWidth = [CCActionTween actionWithDuration:2 key:@"width" from:200 to:300]; [target runAction:modifyWidth]; - + Another example: CCScaleTo action could be rewriten using CCPropertyAction: - + // scaleA and scaleB are equivalents id scaleA = [CCScaleTo actionWithDuration:2 scale:3]; id scaleB = [CCActionTween actionWithDuration:2 key:@"scale" from:1 to:3]; - + @since v0.99.2 */ @interface CCActionTween : CCActionInterval { NSString *key_; - + float from_, to_; float delta_; } @@ -58,5 +58,5 @@ /** initializes the action with the property name (key), and the from and to parameters. */ - (id)initWithDuration:(ccTime)aDuration key:(NSString *)key from:(float)from to:(float)to; - + @end diff --git a/Example/libs/cocos2d/CCActionTween.m b/Example/libs/cocos2d/CCActionTween.m index 95ae572..a119d72 100644 --- a/Example/libs/cocos2d/CCActionTween.m +++ b/Example/libs/cocos2d/CCActionTween.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,15 +34,15 @@ + (id)actionWithDuration:(ccTime)aDuration key:(NSString *)aKey from:(float)aFro } - (id)initWithDuration:(ccTime)aDuration key:(NSString *)key from:(float)from to:(float)to { - + if ((self = [super initWithDuration:aDuration])) { - + key_ = [key copy]; to_ = to; from_ = from; } - + return self; } @@ -59,7 +59,7 @@ - (void)startWithTarget:aTarget } - (void) update:(ccTime) dt -{ +{ [target_ setValue:[NSNumber numberWithFloat:to_ - delta_ * (1 - dt)] forKey:key_]; } diff --git a/Example/libs/cocos2d/CCAnimation.h b/Example/libs/cocos2d/CCAnimation.h index 86c089c..a20def3 100644 --- a/Example/libs/cocos2d/CCAnimation.h +++ b/Example/libs/cocos2d/CCAnimation.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,109 +25,126 @@ */ #import +#ifdef __CC_PLATFORM_IOS +#import +#endif // IPHONE @class CCSpriteFrame; @class CCTexture2D; +@class CCSpriteFrame; -/** A CCAnimation object is used to perform animations on the CCSprite objects. +/** CCAnimationFrame + A frame of the animation. It contains information like: + - sprite frame name + - # of delay units. + - offset - The CCAnimation object contains CCSpriteFrame objects, and a possible delay between the frames. + @since v2.0 + */ +@interface CCAnimationFrame : NSObject +{ + CCSpriteFrame* spriteFrame_; + float delayUnits_; + NSDictionary *userInfo_; +} +/** CCSpriteFrameName to be used */ +@property (nonatomic, readwrite, retain) CCSpriteFrame* spriteFrame; + +/** how many units of time the frame takes */ +@property (nonatomic, readwrite) float delayUnits; + +/** A CCAnimationFrameDisplayedNotification notification will be broadcasted when the frame is displayed with this dictionary as UserInfo. If UserInfo is nil, then no notification will be broadcasted. */ +@property (nonatomic, readwrite, retain) NSDictionary *userInfo; + +/** initializes the animation frame with a spriteframe, number of delay units and a notification user info */ +-(id) initWithSpriteFrame:(CCSpriteFrame*)spriteFrame delayUnits:(float)delayUnits userInfo:(NSDictionary*)userInfo; +@end + +/** A CCAnimation object is used to perform animations on the CCSprite objects. + + The CCAnimation object contains CCAnimationFrame objects, and a possible delay between the frames. You can animate a CCAnimation object by using the CCAnimate action. Example: - + [sprite runAction:[CCAnimate actionWithAnimation:animation]]; - + */ -@interface CCAnimation : NSObject +@interface CCAnimation : NSObject { - NSString *name_; - float delay_; - NSMutableArray *frames_; + NSMutableArray *frames_; + float totalDelayUnits_; + float delayPerUnit_; + BOOL restoreOriginalFrame_; + NSUInteger loops_; } -/** name of the animation */ -@property (nonatomic,readwrite,retain) NSString *name; -/** delay between frames in seconds. */ -@property (nonatomic,readwrite,assign) float delay; -/** array of frames */ +/** total Delay units of the CCAnimation. */ +@property (nonatomic, readonly) float totalDelayUnits; +/** Delay in seconds of the "delay unit" */ +@property (nonatomic, readwrite) float delayPerUnit; +/** duration in seconds of the whole animation. It is the result of totalDelayUnits * delayPerUnit */ +@property (nonatomic,readonly) float duration; +/** array of CCAnimationFrames */ @property (nonatomic,readwrite,retain) NSMutableArray *frames; +/** whether or not it shall restore the original frame when the animation finishes */ +@property (nonatomic,readwrite) BOOL restoreOriginalFrame; +/** how many times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ... */ +@property (nonatomic, readwrite) NSUInteger loops; /** Creates an animation @since v0.99.5 */ +(id) animation; -/** Creates an animation with frames. +/** Creates an animation with an array of CCSpriteFrame. + The frames will be created with one "delay unit". @since v0.99.5 */ -+(id) animationWithFrames:(NSArray*)frames; ++(id) animationWithSpriteFrames:(NSArray*)arrayOfSpriteFrameNames; -/* Creates an animation with frames and a delay between frames. +/* Creates an animation with an array of CCSpriteFrame and a delay between frames in seconds. + The frames will be added with one "delay unit". @since v0.99.5 */ -+(id) animationWithFrames:(NSArray*)frames delay:(float)delay; - -/** Creates a CCAnimation with a name - @since v0.99.3 - @deprecated Will be removed in 1.0.1. Use "animation" instead. - */ -+(id) animationWithName:(NSString*)name DEPRECATED_ATTRIBUTE; ++(id) animationWithSpriteFrames:(NSArray*)arrayOfSpriteFrameNames delay:(float)delay; -/** Creates a CCAnimation with a name and frames - @since v0.99.3 - @deprecated Will be removed in 1.0.1. Use "animationWithFrames" instead. +/* Creates an animation with an array of CCAnimationFrame, the delay per units in seconds and and how many times it should be executed. + @since v2.0 */ -+(id) animationWithName:(NSString*)name frames:(NSArray*)frames DEPRECATED_ATTRIBUTE; ++(id) animationWithAnimationFrames:(NSArray*)arrayOfAnimationFrames delayPerUnit:(float)delayPerUnit loops:(NSUInteger)loops; -/** Creates a CCAnimation with a name and delay between frames. */ -+(id) animationWithName:(NSString*)name delay:(float)delay DEPRECATED_ATTRIBUTE; -/** Creates a CCAnimation with a name, delay and an array of CCSpriteFrames. */ -+(id) animationWithName:(NSString*)name delay:(float)delay frames:(NSArray*)frames DEPRECATED_ATTRIBUTE; - - -/** Initializes a CCAnimation with frames. +/** Initializes a CCAnimation with an array of CCSpriteFrame. + The frames will be added with one "delay unit". @since v0.99.5 */ --(id) initWithFrames:(NSArray*)frames; +-(id) initWithSpriteFrames:(NSArray*)arrayOfSpriteFrameNames; -/** Initializes a CCAnimation with frames and a delay between frames +/** Initializes a CCAnimation with an array of CCSpriteFrames and a delay between frames in seconds. + The frames will be added with one "delay unit". @since v0.99.5 */ --(id) initWithFrames:(NSArray *)frames delay:(float)delay; - -/** Initializes a CCAnimation with a name - @since v0.99.3 - @deprecated Will be removed in 1.0.1. Use "init" instead. - */ --(id) initWithName:(NSString*)name DEPRECATED_ATTRIBUTE; +-(id) initWithSpriteFrames:(NSArray *)arrayOfSpriteFrameNames delay:(float)delay; -/** Initializes a CCAnimation with a name and frames - @since v0.99.3 - @deprecated Will be removed in 1.0.1. Use "initWithFrames" instead. +/* Initializes an animation with an array of CCAnimationFrame and the delay per units in seconds. + @since v2.0 */ --(id) initWithName:(NSString*)name frames:(NSArray*)frames DEPRECATED_ATTRIBUTE; +-(id) initWithAnimationFrames:(NSArray*)arrayOfAnimationFrames delayPerUnit:(float)delayPerUnit loops:(NSUInteger)loops; -/** Initializes a CCAnimation with a name and delay between frames. - @deprecated Will be removed in 1.0.1. Use "initWithFrames:nil delay:delay" instead. +/** Adds a CCSpriteFrame to a CCAnimation. + The frame will be added with one "delay unit". */ --(id) initWithName:(NSString*)name delay:(float)delay DEPRECATED_ATTRIBUTE; - -/** Initializes a CCAnimation with a name, delay and an array of CCSpriteFrames. - @deprecated Will be removed in 1.0.1. Use "initWithFrames:frames delay:delay" instead. -*/ --(id) initWithName:(NSString*)name delay:(float)delay frames:(NSArray*)frames DEPRECATED_ATTRIBUTE; - -/** Adds a frame to a CCAnimation. */ --(void) addFrame:(CCSpriteFrame*)frame; +-(void) addSpriteFrame:(CCSpriteFrame*)frame; /** Adds a frame with an image filename. Internally it will create a CCSpriteFrame and it will add it. + The frame will be added with one "delay unit". Added to facilitate the migration from v0.8 to v0.9. */ --(void) addFrameWithFilename:(NSString*)filename; +-(void) addSpriteFrameWithFilename:(NSString*)filename; /** Adds a frame with a texture and a rect. Internally it will create a CCSpriteFrame and it will add it. + The frame will be added with one "delay unit". Added to facilitate the migration from v0.8 to v0.9. */ --(void) addFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; +-(void) addSpriteFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; @end diff --git a/Example/libs/cocos2d/CCAnimation.m b/Example/libs/cocos2d/CCAnimation.m index bb8480c..7426349 100644 --- a/Example/libs/cocos2d/CCAnimation.m +++ b/Example/libs/cocos2d/CCAnimation.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,124 +30,171 @@ #import "CCTexture2D.h" #import "CCTextureCache.h" -@implementation CCAnimation -@synthesize name = name_, delay = delay_, frames = frames_; +#pragma mark - CCAnimationFrame +@implementation CCAnimationFrame -+(id) animation +@synthesize spriteFrame = spriteFrame_, delayUnits = delayUnits_, userInfo=userInfo_; + +-(id) initWithSpriteFrame:(CCSpriteFrame *)spriteFrame delayUnits:(float)delayUnits userInfo:(NSDictionary*)userInfo { - return [[[self alloc] init] autorelease]; + if( (self=[super init]) ) { + self.spriteFrame = spriteFrame; + self.delayUnits = delayUnits; + self.userInfo = userInfo; + } + + return self; +} + +-(void) dealloc +{ + CCLOGINFO( @"cocos2d: deallocing %@", self); + + [spriteFrame_ release]; + [userInfo_ release]; + + [super dealloc]; } -+(id) animationWithFrames:(NSArray*)frames +-(id) copyWithZone: (NSZone*) zone { - return [[[self alloc] initWithFrames:frames] autorelease]; + CCAnimationFrame *copy = [[[self class] allocWithZone: zone] initWithSpriteFrame:[[spriteFrame_ copy] autorelease] delayUnits:delayUnits_ userInfo:[[userInfo_ copy] autorelease] ]; + return copy; } -+(id) animationWithFrames:(NSArray*)frames delay:(float)delay +-(NSString*) description { - return [[[self alloc] initWithFrames:frames delay:delay] autorelease]; + return [NSString stringWithFormat:@"<%@ = %08X | SpriteFrame = %08X, delayUnits = %0.2f >", [self class], self, spriteFrame_, delayUnits_ ]; } +@end + -+(id) animationWithName:(NSString*)name +#pragma mark - CCAnimation + +@implementation CCAnimation +@synthesize frames = frames_, totalDelayUnits=totalDelayUnits_, delayPerUnit=delayPerUnit_, restoreOriginalFrame=restoreOriginalFrame_, loops=loops_; + ++(id) animation { - return [[[self alloc] initWithName:name] autorelease]; + return [[[self alloc] init] autorelease]; } -+(id) animationWithName:(NSString*)name frames:(NSArray*)frames ++(id) animationWithSpriteFrames:(NSArray*)frames { - return [[[self alloc] initWithName:name frames:frames] autorelease]; + return [[[self alloc] initWithSpriteFrames:frames] autorelease]; } -+(id) animationWithName:(NSString*)aname delay:(float)d frames:(NSArray*)array ++(id) animationWithSpriteFrames:(NSArray*)frames delay:(float)delay { - return [[[self alloc] initWithName:aname delay:d frames:array] autorelease]; + return [[[self alloc] initWithSpriteFrames:frames delay:delay] autorelease]; } -+(id) animationWithName:(NSString*)aname delay:(float)d ++(id) animationWithAnimationFrames:(NSArray*)arrayOfAnimationFrames delayPerUnit:(float)delayPerUnit loops:(NSUInteger)loops { - return [[[self alloc] initWithName:aname delay:d] autorelease]; + return [[[self alloc] initWithAnimationFrames:arrayOfAnimationFrames delayPerUnit:delayPerUnit loops:loops] autorelease]; } -(id) init { - return [self initWithFrames:nil delay:0]; + return [self initWithSpriteFrames:nil delay:0]; } --(id) initWithFrames:(NSArray*)frames +-(id) initWithSpriteFrames:(NSArray*)frames { - return [self initWithFrames:frames delay:0]; + return [self initWithSpriteFrames:frames delay:0]; } --(id) initWithFrames:(NSArray*)array delay:(float)delay +-(id) initWithSpriteFrames:(NSArray*)array delay:(float)delay { - if( (self=[super init]) ) { + if( (self=[super init]) ) + { + loops_ = 1; + delayPerUnit_ = delay; + + self.frames = [NSMutableArray arrayWithCapacity:[array count]]; + + for( CCSpriteFrame *frame in array ) { + CCAnimationFrame *animFrame = [[CCAnimationFrame alloc] initWithSpriteFrame:frame delayUnits:1 userInfo:nil]; + + [self.frames addObject:animFrame]; + [animFrame release]; + totalDelayUnits_++; + } - delay_ = delay; - self.frames = [NSMutableArray arrayWithArray:array]; } return self; } --(id) initWithName:(NSString*)name +-(id) initWithAnimationFrames:(NSArray*)arrayOfAnimationFrames delayPerUnit:(float)delayPerUnit loops:(NSUInteger)loops { - return [self initWithName:name delay:0 frames:nil]; -} + if( ( self=[super init]) ) + { + delayPerUnit_ = delayPerUnit; + loops_ = loops; --(id) initWithName:(NSString*)name frames:(NSArray*)frames -{ - return [self initWithName:name delay:0 frames:frames]; -} + self.frames = [NSMutableArray arrayWithArray:arrayOfAnimationFrames]; --(id) initWithName:(NSString*)t delay:(float)d -{ - return [self initWithName:t delay:d frames:nil]; -} - --(id) initWithName:(NSString*)name delay:(float)delay frames:(NSArray*)array -{ - if( (self=[super init]) ) { - - delay_ = delay; - self.name = name; - self.frames = [NSMutableArray arrayWithArray:array]; + for( CCAnimationFrame *animFrame in frames_ ) + totalDelayUnits_ += animFrame.delayUnits; } return self; } - (NSString*) description { - return [NSString stringWithFormat:@"<%@ = %08X | frames=%d, delay:%f>", [self class], self, + return [NSString stringWithFormat:@"<%@ = %08X | frames=%d, totalDelayUnits=%d, delayPerUnit=%f, loops=%d>", [self class], self, [frames_ count], - delay_ + totalDelayUnits_, + delayPerUnit_, + loops_ ]; } +-(float) duration +{ + return totalDelayUnits_ * delayPerUnit_; +} + +- (id)copyWithZone:(NSZone *)zone +{ + CCAnimation *animation = [[[self class] allocWithZone: zone] initWithAnimationFrames:frames_ delayPerUnit:delayPerUnit_ loops:loops_]; + animation.restoreOriginalFrame = restoreOriginalFrame_; + + return animation; +} + -(void) dealloc { CCLOGINFO( @"cocos2d: deallocing %@",self); - [name_ release]; + [frames_ release]; [super dealloc]; } --(void) addFrame:(CCSpriteFrame*)frame +-(void) addSpriteFrame:(CCSpriteFrame*)frame { - [frames_ addObject:frame]; + CCAnimationFrame *animFrame = [[CCAnimationFrame alloc] initWithSpriteFrame:frame delayUnits:1 userInfo:nil]; + [frames_ addObject:animFrame]; + [animFrame release]; + + // update duration + totalDelayUnits_++; } --(void) addFrameWithFilename:(NSString*)filename +-(void) addSpriteFrameWithFilename:(NSString*)filename { CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:filename]; CGRect rect = CGRectZero; rect.size = texture.contentSize; - CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:texture rect:rect]; - [frames_ addObject:frame]; + CCSpriteFrame *spriteFrame = [CCSpriteFrame frameWithTexture:texture rect:rect]; + + [self addSpriteFrame:spriteFrame]; } --(void) addFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect +-(void) addSpriteFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect { CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:texture rect:rect]; - [frames_ addObject:frame]; + [self addSpriteFrame:frame]; } @end diff --git a/Example/libs/cocos2d/CCAnimationCache.h b/Example/libs/cocos2d/CCAnimationCache.h index 3a9b8ae..5488e8a 100644 --- a/Example/libs/cocos2d/CCAnimationCache.h +++ b/Example/libs/cocos2d/CCAnimationCache.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,11 +28,9 @@ @class CCAnimation; -/** Singleton that manages the Animations. +/** Singleton that manages the CCAnimation objects. It saves in a cache the animations. You should use this class if you want to save your animations in a cache. - Before v0.99.5, the recommend way was to save them on the CCSprite. Since v0.99.5, you should use this class instead. - @since v0.99.5 */ @interface CCAnimationCache : NSObject @@ -60,4 +59,16 @@ */ -(CCAnimation*) animationByName:(NSString*)name; +/** Adds an animation from an NSDictionary + Make sure that the frames were previously loaded in the CCSpriteFrameCache. + @since v1.1 + */ +-(void)addAnimationsWithDictionary:(NSDictionary *)dictionary; + +/** Adds an animation from a plist file. + Make sure that the frames were previously loaded in the CCSpriteFrameCache. + @since v1.1 + */ +-(void)addAnimationsWithFile:(NSString *)plist; + @end diff --git a/Example/libs/cocos2d/CCAnimationCache.m b/Example/libs/cocos2d/CCAnimationCache.m index 003bc63..f57cd33 100644 --- a/Example/libs/cocos2d/CCAnimationCache.m +++ b/Example/libs/cocos2d/CCAnimationCache.m @@ -2,17 +2,21 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * + * Copyright (c) 2011 John Wordsworth + * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,10 +27,12 @@ * */ -#import "ccMacros.h" #import "CCAnimationCache.h" +#import "ccMacros.h" +#import "CCSpriteFrameCache.h" #import "CCAnimation.h" #import "CCSprite.h" +#import "Support/CCFileUtils.h" @implementation CCAnimationCache @@ -39,7 +45,7 @@ + (CCAnimationCache *)sharedAnimationCache { if (!sharedAnimationCache_) sharedAnimationCache_ = [[CCAnimationCache alloc] init]; - + return sharedAnimationCache_; } @@ -60,7 +66,7 @@ -(id) init if( (self=[super init]) ) { animations_ = [[NSMutableDictionary alloc] initWithCapacity: 20]; } - + return self; } @@ -72,7 +78,7 @@ - (NSString*) description -(void) dealloc { CCLOGINFO(@"cocos2d: deallocing %@", self); - + [animations_ release]; [super dealloc]; } @@ -88,7 +94,7 @@ -(void) removeAnimationByName:(NSString*)name { if( ! name ) return; - + [animations_ removeObjectForKey:name]; } @@ -97,4 +103,148 @@ -(CCAnimation*) animationByName:(NSString*)name return [animations_ objectForKey:name]; } +#pragma mark CCAnimationCache - from file + +-(void) parseVersion1:(NSDictionary*)animations +{ + NSArray* animationNames = [animations allKeys]; + CCSpriteFrameCache *frameCache = [CCSpriteFrameCache sharedSpriteFrameCache]; + + for( NSString *name in animationNames ) { + NSDictionary* animationDict = [animations objectForKey:name]; + NSArray *frameNames = [animationDict objectForKey:@"frames"]; + NSNumber *delay = [animationDict objectForKey:@"delay"]; + CCAnimation* animation = nil; + + if ( frameNames == nil ) { + CCLOG(@"cocos2d: CCAnimationCache: Animation '%@' found in dictionary without any frames - cannot add to animation cache.", name); + continue; + } + + NSMutableArray *frames = [NSMutableArray arrayWithCapacity:[frameNames count]]; + + for( NSString *frameName in frameNames ) { + CCSpriteFrame *spriteFrame = [frameCache spriteFrameByName:frameName]; + + if ( ! spriteFrame ) { + CCLOG(@"cocos2d: CCAnimationCache: Animation '%@' refers to frame '%@' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.", name, frameName); + + continue; + } + + CCAnimationFrame *animFrame = [[CCAnimationFrame alloc] initWithSpriteFrame:spriteFrame delayUnits:1 userInfo:nil]; + [frames addObject:animFrame]; + [animFrame release]; + } + + if ( [frames count] == 0 ) { + CCLOG(@"cocos2d: CCAnimationCache: None of the frames for animation '%@' were found in the CCSpriteFrameCache. Animation is not being added to the Animation Cache.", name); + continue; + } else if ( [frames count] != [frameNames count] ) { + CCLOG(@"cocos2d: CCAnimationCache: An animation in your dictionary refers to a frame which is not in the CCSpriteFrameCache. Some or all of the frames for the animation '%@' may be missing.", name); + } + + animation = [CCAnimation animationWithAnimationFrames:frames delayPerUnit:[delay floatValue] loops:1 ]; + + [[CCAnimationCache sharedAnimationCache] addAnimation:animation name:name]; + } +} + +-(void) parseVersion2:(NSDictionary*)animations +{ + NSArray* animationNames = [animations allKeys]; + CCSpriteFrameCache *frameCache = [CCSpriteFrameCache sharedSpriteFrameCache]; + + for( NSString *name in animationNames ) + { + NSDictionary* animationDict = [animations objectForKey:name]; + + NSNumber *loops = [animationDict objectForKey:@"loops"]; + BOOL restoreOriginalFrame = [[animationDict objectForKey:@"restoreOriginalFrame"] boolValue]; + NSArray *frameArray = [animationDict objectForKey:@"frames"]; + + + if ( frameArray == nil ) { + CCLOG(@"cocos2d: CCAnimationCache: Animation '%@' found in dictionary without any frames - cannot add to animation cache.", name); + continue; + } + + // Array of AnimationFrames + NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[frameArray count]]; + + for( NSDictionary *entry in frameArray ) { + NSString *spriteFrameName = [entry objectForKey:@"spriteframe"]; + CCSpriteFrame *spriteFrame = [frameCache spriteFrameByName:spriteFrameName]; + + if( ! spriteFrame ) { + CCLOG(@"cocos2d: CCAnimationCache: Animation '%@' refers to frame '%@' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.", name, spriteFrameName); + + continue; + } + + float delayUnits = [[entry objectForKey:@"delayUnits"] floatValue]; + NSDictionary *userInfo = [entry objectForKey:@"notification"]; + + CCAnimationFrame *animFrame = [[CCAnimationFrame alloc] initWithSpriteFrame:spriteFrame delayUnits:delayUnits userInfo:userInfo]; + + [array addObject:animFrame]; + [animFrame release]; + } + + float delayPerUnit = [[animationDict objectForKey:@"delayPerUnit"] floatValue]; + CCAnimation *animation = [[CCAnimation alloc] initWithAnimationFrames:array delayPerUnit:delayPerUnit loops:(loops?[loops intValue]:1)]; + [array release]; + + [animation setRestoreOriginalFrame:restoreOriginalFrame]; + + [[CCAnimationCache sharedAnimationCache] addAnimation:animation name:name]; + [animation release]; + } +} + +-(void)addAnimationsWithDictionary:(NSDictionary *)dictionary +{ + NSDictionary *animations = [dictionary objectForKey:@"animations"]; + + if ( animations == nil ) { + CCLOG(@"cocos2d: CCAnimationCache: No animations were found in provided dictionary."); + return; + } + + NSUInteger version = 1; + NSDictionary *properties = [dictionary objectForKey:@"properties"]; + if( properties ) + version = [[properties objectForKey:@"format"] intValue]; + + NSArray *spritesheets = [properties objectForKey:@"spritesheets"]; + for( NSString *name in spritesheets ) + [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:name]; + + switch (version) { + case 1: + [self parseVersion1:animations]; + break; + case 2: + [self parseVersion2:animations]; + break; + default: + NSAssert(NO, @"Invalid animation format"); + } +} + + +/** Read an NSDictionary from a plist file and parse it automatically for animations */ +-(void)addAnimationsWithFile:(NSString *)plist +{ + NSAssert( plist, @"Invalid texture file name"); + + NSString *path = [CCFileUtils fullPathFromRelativePath:plist]; + NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; + + NSAssert1( dict, @"CCAnimationCache: File could not be found: %@", plist); + + + [self addAnimationsWithDictionary:dict]; +} + @end diff --git a/Example/libs/cocos2d/CCAtlasNode.h b/Example/libs/cocos2d/CCAtlasNode.h index 145586f..5360e54 100644 --- a/Example/libs/cocos2d/CCAtlasNode.h +++ b/Example/libs/cocos2d/CCAtlasNode.h @@ -2,17 +2,19 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,10 +31,10 @@ /** CCAtlasNode is a subclass of CCNode that implements the CCRGBAProtocol and CCTextureProtocol protocol - + It knows how to render a TextureAtlas object. If you are going to render a TextureAtlas consider subclassing CCAtlasNode (or a subclass of CCAtlasNode) - + All features from CCNode are valid, plus the following features: - opacity and RGB colors */ @@ -42,23 +44,29 @@ CCTextureAtlas *textureAtlas_; // chars per row - int itemsPerRow_; + NSUInteger itemsPerRow_; // chars per column - int itemsPerColumn_; - + NSUInteger itemsPerColumn_; + // width of each char - int itemWidth_; + NSUInteger itemWidth_; // height of each char - int itemHeight_; + NSUInteger itemHeight_; + + // quads to draw + NSUInteger quadsToDraw_; // blend function ccBlendFunc blendFunc_; - // texture RGBA. + // texture RGBA. GLubyte opacity_; ccColor3B color_; ccColor3B colorUnmodified_; BOOL opacityModifyRGB_; + + // color uniform + GLint uniformColor_; } /** conforms to CCTextureProtocol protocol */ @@ -72,12 +80,14 @@ /** conforms to CCRGBAProtocol protocol */ @property (nonatomic,readwrite) ccColor3B color; +/** how many quads to draw */ +@property (nonatomic,readwrite) NSUInteger quadsToDraw; /** creates a CCAtlasNode with an Atlas file the width and height of each item measured in points and the quantity of items to render*/ -+(id) atlasWithTileFile:(NSString*)tile tileWidth:(int)w tileHeight:(int)h itemsToRender: (int) c; ++(id) atlasWithTileFile:(NSString*)tile tileWidth:(NSUInteger)w tileHeight:(NSUInteger)h itemsToRender: (NSUInteger) c; /** initializes an CCAtlasNode with an Atlas file the width and height of each item measured in points and the quantity of items to render*/ --(id) initWithTileFile:(NSString*)tile tileWidth:(int)w tileHeight:(int)h itemsToRender: (int) c; +-(id) initWithTileFile:(NSString*)tile tileWidth:(NSUInteger)w tileHeight:(NSUInteger)h itemsToRender: (NSUInteger) c; /** updates the Atlas (indexed vertex array). * Shall be overriden in subclasses diff --git a/Example/libs/cocos2d/CCAtlasNode.m b/Example/libs/cocos2d/CCAtlasNode.m index 840fead..bb083c1 100644 --- a/Example/libs/cocos2d/CCAtlasNode.m +++ b/Example/libs/cocos2d/CCAtlasNode.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,6 +26,14 @@ #import "CCAtlasNode.h" #import "ccMacros.h" +#import "CCGLProgram.h" +#import "CCShaderCache.h" +#import "ccGLStateCache.h" +#import "CCDirector.h" +#import "Support/TransformUtils.h" + +// external +#import "kazmath/GL/matrix.h" @interface CCAtlasNode () @@ -37,43 +46,54 @@ @implementation CCAtlasNode @synthesize textureAtlas = textureAtlas_; @synthesize blendFunc = blendFunc_; +@synthesize quadsToDraw = quadsToDraw_; #pragma mark CCAtlasNode - Creation & Init -+(id) atlasWithTileFile:(NSString*)tile tileWidth:(int)w tileHeight:(int)h itemsToRender: (int) c +- (id) init +{ + NSAssert( NO, @"Not supported - Use initWtihTileFile instead"); + return self; +} + ++(id) atlasWithTileFile:(NSString*)tile tileWidth:(NSUInteger)w tileHeight:(NSUInteger)h itemsToRender: (NSUInteger) c { return [[[self alloc] initWithTileFile:tile tileWidth:w tileHeight:h itemsToRender:c] autorelease]; } --(id) initWithTileFile:(NSString*)tile tileWidth:(int)w tileHeight:(int)h itemsToRender: (int) c +-(id) initWithTileFile:(NSString*)tile tileWidth:(NSUInteger)w tileHeight:(NSUInteger)h itemsToRender: (NSUInteger) c { if( (self=[super init]) ) { - - itemWidth_ = w * CC_CONTENT_SCALE_FACTOR(); - itemHeight_ = h * CC_CONTENT_SCALE_FACTOR(); + + itemWidth_ = w; + itemHeight_ = h; opacity_ = 255; color_ = colorUnmodified_ = ccWHITE; opacityModifyRGB_ = YES; - + blendFunc_.src = CC_BLEND_SRC; blendFunc_.dst = CC_BLEND_DST; - - // double retain to avoid the autorelease pool - // also, using: self.textureAtlas supports re-initialization without leaking - self.textureAtlas = [[CCTextureAtlas alloc] initWithFile:tile capacity:c]; - [textureAtlas_ release]; - + + CCTextureAtlas * newAtlas = [[CCTextureAtlas alloc] initWithFile:tile capacity:c]; + self.textureAtlas = newAtlas; + [newAtlas release]; + if( ! textureAtlas_ ) { CCLOG(@"cocos2d: Could not initialize CCAtlasNode. Invalid Texture"); [self release]; return nil; } - + [self updateBlendFunc]; [self updateOpacityModifyRGB]; - + [self calculateMaxItems]; - + + self.quadsToDraw = c; + + // shader stuff + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTexture_uColor]; + uniformColor_ = glGetUniformLocation( shaderProgram_->program_, "u_color"); } return self; } @@ -81,7 +101,7 @@ -(id) initWithTileFile:(NSString*)tile tileWidth:(int)w tileHeight:(int)h itemsT -(void) dealloc { [textureAtlas_ release]; - + [super dealloc]; } @@ -89,7 +109,7 @@ -(void) dealloc -(void) calculateMaxItems { - CGSize s = [[textureAtlas_ texture] contentSizeInPixels]; + CGSize s = [[textureAtlas_ texture] contentSize]; itemsPerColumn_ = s.height / itemHeight_; itemsPerRow_ = s.width / itemWidth_; } @@ -102,30 +122,14 @@ -(void) updateAtlasValues #pragma mark CCAtlasNode - draw - (void) draw { - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: GL_COLOR_ARRAY - glDisableClientState(GL_COLOR_ARRAY); - - glColor4ub( color_.r, color_.g, color_.b, opacity_); - - BOOL newBlend = blendFunc_.src != CC_BLEND_SRC || blendFunc_.dst != CC_BLEND_DST; - if( newBlend ) - glBlendFunc( blendFunc_.src, blendFunc_.dst ); - - [textureAtlas_ drawQuads]; - - if( newBlend ) - glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); - - // is this chepear than saving/restoring color state ? - // XXX: There is no need to restore the color to (255,255,255,255). Objects should use the color - // XXX: that they need -// glColor4ub( 255, 255, 255, 255); + CC_NODE_DRAW_SETUP(); - // restore default GL state - glEnableClientState(GL_COLOR_ARRAY); + ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); + + GLfloat colors[4] = {color_.r / 255.0f, color_.g / 255.0f, color_.b / 255.0f, opacity_ / 255.0f}; + [shaderProgram_ setUniformLocation:uniformColor_ with4fv:colors count:1]; + [textureAtlas_ drawNumberOfQuads:quadsToDraw_ fromIndex:0]; } #pragma mark CCAtlasNode - RGBA protocol @@ -134,19 +138,19 @@ - (ccColor3B) color { if(opacityModifyRGB_) return colorUnmodified_; - + return color_; } -(void) setColor:(ccColor3B)color3 { color_ = colorUnmodified_ = color3; - + if( opacityModifyRGB_ ){ color_.r = color3.r * opacity_/255; color_.g = color3.g * opacity_/255; color_.b = color3.b * opacity_/255; - } + } } -(GLubyte) opacity @@ -157,10 +161,10 @@ -(GLubyte) opacity -(void) setOpacity:(GLubyte) anOpacity { opacity_ = anOpacity; - + // special opacity for premultiplied textures if( opacityModifyRGB_ ) - [self setColor: colorUnmodified_]; + [self setColor: colorUnmodified_]; } -(void) setOpacityModifyRGB:(BOOL)modify @@ -180,7 +184,7 @@ -(void) updateOpacityModifyRGB opacityModifyRGB_ = [textureAtlas_.texture hasPremultipliedAlpha]; } -#pragma mark CCAtlasNode - CocosNodeTexture protocol +#pragma mark CCAtlasNode - CCNodeTexture protocol -(void) updateBlendFunc { diff --git a/Example/libs/cocos2d/CCBlockSupport.h b/Example/libs/cocos2d/CCBlockSupport.h deleted file mode 100644 index 339d5aa..0000000 --- a/Example/libs/cocos2d/CCBlockSupport.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Stuart Carnie - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import - -/** @file - cocos2d blocks support - */ - -// To comply with Apple Objective C runtime (this is defined in NSObjCRuntime.h) -#if !defined(NS_BLOCKS_AVAILABLE) - #if __BLOCKS__ - #define NS_BLOCKS_AVAILABLE 1 - #else - #define NS_BLOCKS_AVAILABLE 0 - #endif -#endif - -#if NS_BLOCKS_AVAILABLE - -@interface NSObject(CCBlocksAdditions) - -- (void)ccCallbackBlock; -- (void)ccCallbackBlockWithSender:(id)sender; - -@end - -#endif // NS_BLOCKS_AVAILABLE diff --git a/Example/libs/cocos2d/CCBlockSupport.m b/Example/libs/cocos2d/CCBlockSupport.m deleted file mode 100644 index 9ac99b3..0000000 --- a/Example/libs/cocos2d/CCBlockSupport.m +++ /dev/null @@ -1,46 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Stuart Carnie - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCBlockSupport.h" - -#if NS_BLOCKS_AVAILABLE - -@implementation NSObject(CCBlocksAdditions) - -- (void)ccCallbackBlock { - void (^block)(void) = (id)self; - block(); -} - -- (void)ccCallbackBlockWithSender:(id)sender { - void (^block)(id) = (id)self; - block(sender); -} - - -@end - -#endif diff --git a/Example/libs/cocos2d/CCCamera.h b/Example/libs/cocos2d/CCCamera.h index 387c854..415caf7 100644 --- a/Example/libs/cocos2d/CCCamera.h +++ b/Example/libs/cocos2d/CCCamera.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,8 +26,9 @@ #import "CCNode.h" +#import "kazmath/mat4.h" -/** +/** A CCCamera is used in every CCNode. Useful to look at the object from different views. The OpenGL gluLookAt() function is used to locate the @@ -34,19 +36,19 @@ If the object is transformed by any of the scale, rotation or position attributes, then they will override the camera. - + IMPORTANT: Either your use the camera or the rotation/scale/position properties. You can't use both. World coordinates won't work if you use the camera. Limitations: - + - Some nodes, like CCParallaxNode, CCParticle uses world node coordinates, and they won't work properly if you move them (or any of their ancestors) using the camera. - + - It doesn't work on batched nodes like CCSprite objects when they are parented to a CCSpriteBatchNode object. - + - It is recommended to use it ONLY if you are going to create 3D effects. For 2D effecs, use the action CCFollow or position/scale/rotate. - + */ @interface CCCamera : NSObject @@ -62,8 +64,10 @@ float upX_; float upY_; float upZ_; - + BOOL dirty_; + + kmMat4 lookupMatrix_; } /** whether of not the camera is dirty */ diff --git a/Example/libs/cocos2d/CCCamera.m b/Example/libs/cocos2d/CCCamera.m index 3841ab3..ff90496 100644 --- a/Example/libs/cocos2d/CCCamera.m +++ b/Example/libs/cocos2d/CCCamera.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,6 +28,7 @@ #import "CCCamera.h" #import "ccMacros.h" #import "CCDrawingPrimitives.h" +#import "kazmath/GL/matrix.h" @implementation CCCamera @@ -36,7 +38,7 @@ -(id) init { if( (self=[super init]) ) [self restore]; - + return self; } @@ -56,45 +58,60 @@ -(void) restore { eyeX_ = eyeY_ = 0; eyeZ_ = [CCCamera getZEye]; - + centerX_ = centerY_ = centerZ_ = 0; - + upX_ = 0.0f; upY_ = 1.0f; upZ_ = 0.0f; - + + kmMat4Identity( &lookupMatrix_ ); + dirty_ = NO; } -(void) locate { - if( dirty_ ) - gluLookAt( eyeX_, eyeY_, eyeZ_, - centerX_, centerY_, centerZ_, - upX_, upY_, upZ_ - ); + if( dirty_ ) { + + kmVec3 eye, center, up; + + kmVec3Fill( &eye, eyeX_, eyeY_ , eyeZ_ ); + kmVec3Fill( ¢er, centerX_, centerY_, centerZ_ ); + + kmVec3Fill( &up, upX_, upY_, upZ_); + kmMat4LookAt( &lookupMatrix_, &eye, ¢er, &up); + + dirty_ = NO; + + } + + kmGLMultMatrix( &lookupMatrix_ ); + } +(float) getZEye { return FLT_EPSILON; -// CGSize s = [[CCDirector sharedDirector] displaySize]; -// return ( s.height / 1.1566f ); + // CGSize s = [[CCDirector sharedDirector] displaySize]; + // return ( s.height / 1.1566f ); } -(void) setEyeX: (float)x eyeY:(float)y eyeZ:(float)z { - eyeX_ = x * CC_CONTENT_SCALE_FACTOR(); - eyeY_ = y * CC_CONTENT_SCALE_FACTOR(); - eyeZ_ = z * CC_CONTENT_SCALE_FACTOR(); - dirty_ = YES; + eyeX_ = x; + eyeY_ = y; + eyeZ_ = z; + + dirty_ = YES; } -(void) setCenterX: (float)x centerY:(float)y centerZ:(float)z { - centerX_ = x * CC_CONTENT_SCALE_FACTOR(); - centerY_ = y * CC_CONTENT_SCALE_FACTOR(); - centerZ_ = z * CC_CONTENT_SCALE_FACTOR(); + centerX_ = x; + centerY_ = y; + centerZ_ = z; + dirty_ = YES; } @@ -103,21 +120,22 @@ -(void) setUpX: (float)x upY:(float)y upZ:(float)z upX_ = x; upY_ = y; upZ_ = z; + dirty_ = YES; } -(void) eyeX: (float*)x eyeY:(float*)y eyeZ:(float*)z { - *x = eyeX_ / CC_CONTENT_SCALE_FACTOR(); - *y = eyeY_ / CC_CONTENT_SCALE_FACTOR(); - *z = eyeZ_ / CC_CONTENT_SCALE_FACTOR(); + *x = eyeX_; + *y = eyeY_; + *z = eyeZ_; } -(void) centerX: (float*)x centerY:(float*)y centerZ:(float*)z { - *x = centerX_ / CC_CONTENT_SCALE_FACTOR(); - *y = centerY_ / CC_CONTENT_SCALE_FACTOR(); - *z = centerZ_ / CC_CONTENT_SCALE_FACTOR(); + *x = centerX_; + *y = centerY_; + *z = centerZ_; } -(void) upX: (float*)x upY:(float*)y upZ:(float*)z diff --git a/Example/libs/cocos2d/CCCompatibility.h b/Example/libs/cocos2d/CCCompatibility.h deleted file mode 100644 index b1b578e..0000000 --- a/Example/libs/cocos2d/CCCompatibility.h +++ /dev/null @@ -1,224 +0,0 @@ - -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -// AUTOMATICALLY GENERATED. DO NOT EDIT - - -#import -#import "cocos2d.h" - -#if CC_COMPATIBILITY_WITH_0_8 - -DEPRECATED_ATTRIBUTE @interface AccelAmplitude : CCAccelAmplitude {} @end -DEPRECATED_ATTRIBUTE @interface AccelDeccelAmplitude : CCAccelDeccelAmplitude {} @end -DEPRECATED_ATTRIBUTE @interface Action : CCAction {} @end -DEPRECATED_ATTRIBUTE @interface ActionManager : CCActionManager {} @end -DEPRECATED_ATTRIBUTE @interface Animate : CCAnimate {} @end -DEPRECATED_ATTRIBUTE @interface Animation : CCAnimation {} @end -DEPRECATED_ATTRIBUTE @interface AtlasAnimation : CCAnimation {} @end -DEPRECATED_ATTRIBUTE @interface AtlasNode : CCAtlasNode {} @end -DEPRECATED_ATTRIBUTE @interface AtlasSprite : CCSprite {} @end -DEPRECATED_ATTRIBUTE @interface AtlasSpriteFrame : CCSpriteFrame {} @end -DEPRECATED_ATTRIBUTE @interface AtlasSpriteManager : CCSpriteSheet {} @end -DEPRECATED_ATTRIBUTE @interface BezierBy : CCBezierBy {} @end -DEPRECATED_ATTRIBUTE @interface BezierTo : CCBezierTo {} @end -DEPRECATED_ATTRIBUTE @interface BitmapFontAtlas : CCBitmapFontAtlas {} @end -DEPRECATED_ATTRIBUTE @interface BitmapFontConfiguration : CCBitmapFontConfiguration {} @end -DEPRECATED_ATTRIBUTE @interface Blink : CCBlink {} @end -DEPRECATED_ATTRIBUTE @interface CallFunc : CCCallFunc {} @end -DEPRECATED_ATTRIBUTE @interface CallFuncN : CCCallFuncN {} @end -DEPRECATED_ATTRIBUTE @interface CallFuncND : CCCallFuncND {} @end -DEPRECATED_ATTRIBUTE @interface Camera : CCCamera {} @end -DEPRECATED_ATTRIBUTE @interface CameraAction : CCCameraAction {} @end -DEPRECATED_ATTRIBUTE @interface CocosNode : CCNode {} @end -DEPRECATED_ATTRIBUTE @interface ColorLayer : CCColorLayer {} @end -DEPRECATED_ATTRIBUTE @interface DeccelAmplitude : CCDeccelAmplitude {} @end -DEPRECATED_ATTRIBUTE @interface DelayTime : CCDelayTime {} @end -DEPRECATED_ATTRIBUTE @interface Director : CCDirector {} @end -DEPRECATED_ATTRIBUTE @interface DisplayLinkDirector : CCDisplayLinkDirector {} @end -DEPRECATED_ATTRIBUTE @interface EaseAction : CCEaseAction {} @end -DEPRECATED_ATTRIBUTE @interface EaseBackIn : CCEaseBackIn {} @end -DEPRECATED_ATTRIBUTE @interface EaseBackInOut : CCEaseBackInOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseBackOut : CCEaseBackOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseBounce : CCEaseBounce {} @end -DEPRECATED_ATTRIBUTE @interface EaseBounceIn : CCEaseBounceIn {} @end -DEPRECATED_ATTRIBUTE @interface EaseBounceInOut : CCEaseBounceInOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseBounceOut : CCEaseBounceOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseElastic : CCEaseElastic {} @end -DEPRECATED_ATTRIBUTE @interface EaseElasticIn : CCEaseElasticIn {} @end -DEPRECATED_ATTRIBUTE @interface EaseElasticInOut : CCEaseElasticInOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseElasticOut : CCEaseElasticOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseExponentialIn : CCEaseExponentialIn {} @end -DEPRECATED_ATTRIBUTE @interface EaseExponentialInOut : CCEaseExponentialInOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseExponentialOut : CCEaseExponentialOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseIn : CCEaseIn {} @end -DEPRECATED_ATTRIBUTE @interface EaseInOut : CCEaseInOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseOut : CCEaseOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseRateAction : CCEaseRateAction {} @end -DEPRECATED_ATTRIBUTE @interface EaseSineIn : CCEaseSineIn {} @end -DEPRECATED_ATTRIBUTE @interface EaseSineInOut : CCEaseSineInOut {} @end -DEPRECATED_ATTRIBUTE @interface EaseSineOut : CCEaseSineOut {} @end -DEPRECATED_ATTRIBUTE @interface FadeBLTransition : CCTransitionFadeBL {} @end -DEPRECATED_ATTRIBUTE @interface FadeDownTransition : CCTransitionFadeDown {} @end -DEPRECATED_ATTRIBUTE @interface FadeIn : CCFadeIn {} @end -DEPRECATED_ATTRIBUTE @interface FadeOut : CCFadeOut {} @end -DEPRECATED_ATTRIBUTE @interface FadeOutBLTiles : CCFadeOutBLTiles {} @end -DEPRECATED_ATTRIBUTE @interface FadeOutDownTiles : CCFadeOutDownTiles {} @end -DEPRECATED_ATTRIBUTE @interface FadeOutTRTiles : CCFadeOutTRTiles {} @end -DEPRECATED_ATTRIBUTE @interface FadeOutUpTiles : CCFadeOutUpTiles {} @end -DEPRECATED_ATTRIBUTE @interface FadeTRTransition : CCTransitionFadeTR {} @end -DEPRECATED_ATTRIBUTE @interface FadeTo : CCFadeTo {} @end -DEPRECATED_ATTRIBUTE @interface FadeTransition : CCTransitionFade {} @end -DEPRECATED_ATTRIBUTE @interface FadeUpTransition : CCTransitionFadeUp {} @end -DEPRECATED_ATTRIBUTE @interface FastDirector : CCFastDirector {} @end -DEPRECATED_ATTRIBUTE @interface FiniteTimeAction : CCFiniteTimeAction {} @end -DEPRECATED_ATTRIBUTE @interface FlipAngularTransition : CCTransitionFlipAngular {} @end -DEPRECATED_ATTRIBUTE @interface FlipX3D : CCFlipX3D {} @end -DEPRECATED_ATTRIBUTE @interface FlipXTransition : CCTransitionFlipX {} @end -DEPRECATED_ATTRIBUTE @interface FlipY3D : CCFlipY3D {} @end -DEPRECATED_ATTRIBUTE @interface FlipYTransition : CCTransitionFlipY {} @end -DEPRECATED_ATTRIBUTE @interface Grabber : CCGrabber {} @end -DEPRECATED_ATTRIBUTE @interface Grid3D : CCGrid3D {} @end -DEPRECATED_ATTRIBUTE @interface Grid3DAction : CCGrid3DAction {} @end -DEPRECATED_ATTRIBUTE @interface GridAction : CCGridAction {} @end -DEPRECATED_ATTRIBUTE @interface GridBase : CCGridBase {} @end -DEPRECATED_ATTRIBUTE @interface Hide : CCHide {} @end -DEPRECATED_ATTRIBUTE @interface InstantAction : CCInstantAction {} @end -DEPRECATED_ATTRIBUTE @interface IntervalAction : CCIntervalAction {} @end -DEPRECATED_ATTRIBUTE @interface JumpBy : CCJumpBy {} @end -DEPRECATED_ATTRIBUTE @interface JumpTiles3D : CCJumpTiles3D {} @end -DEPRECATED_ATTRIBUTE @interface JumpTo : CCJumpTo {} @end -DEPRECATED_ATTRIBUTE @interface JumpZoomTransition : CCTransitionJumpZoom {} @end -DEPRECATED_ATTRIBUTE @interface Label : CCLabel {} @end -DEPRECATED_ATTRIBUTE @interface LabelAtlas : CCLabelAtlas {} @end -DEPRECATED_ATTRIBUTE @interface Layer : CCLayer {} @end -DEPRECATED_ATTRIBUTE @interface Lens3D : CCLens3D {} @end -DEPRECATED_ATTRIBUTE @interface Liquid : CCLiquid {} @end -DEPRECATED_ATTRIBUTE @interface Menu : CCMenu {} @end -DEPRECATED_ATTRIBUTE @interface MenuItem : CCMenuItem {} @end -DEPRECATED_ATTRIBUTE @interface MenuItemAtlasFont : CCMenuItemAtlasFont {} @end -DEPRECATED_ATTRIBUTE @interface MenuItemFont : CCMenuItemFont {} @end -DEPRECATED_ATTRIBUTE @interface MenuItemImage : CCMenuItemImage {} @end -DEPRECATED_ATTRIBUTE @interface MenuItemLabel : CCMenuItemLabel {} @end -DEPRECATED_ATTRIBUTE @interface MenuItemSprite : CCMenuItemSprite {} @end -DEPRECATED_ATTRIBUTE @interface MenuItemToggle : CCMenuItemToggle {} @end -DEPRECATED_ATTRIBUTE @interface MotionStreak : CCMotionStreak {} @end -DEPRECATED_ATTRIBUTE @interface MoveBy : CCMoveBy {} @end -DEPRECATED_ATTRIBUTE @interface MoveInBTransition : CCTransitionMoveInB {} @end -DEPRECATED_ATTRIBUTE @interface MoveInLTransition : CCTransitionMoveInL {} @end -DEPRECATED_ATTRIBUTE @interface MoveInRTransition : CCTransitionMoveInR {} @end -DEPRECATED_ATTRIBUTE @interface MoveInTTransition : CCTransitionMoveInT {} @end -DEPRECATED_ATTRIBUTE @interface MoveTo : CCMoveTo {} @end -DEPRECATED_ATTRIBUTE @interface MultiplexLayer : CCMultiplexLayer {} @end -DEPRECATED_ATTRIBUTE @interface OrbitCamera : CCOrbitCamera {} @end -DEPRECATED_ATTRIBUTE @interface OrientedTransitionScene : CCTransitionSceneOriented {} @end -DEPRECATED_ATTRIBUTE @interface PVRTexture : CCPVRTexture {} @end -DEPRECATED_ATTRIBUTE @interface PageTurn3D : CCPageTurn3D {} @end -DEPRECATED_ATTRIBUTE @interface PageTurnTransition : CCPageTurnTransition {} @end -DEPRECATED_ATTRIBUTE @interface ParallaxNode : CCParallaxNode {} @end -DEPRECATED_ATTRIBUTE @interface ParticleExplosion : CCParticleExplosion {} @end -DEPRECATED_ATTRIBUTE @interface ParticleFire : CCParticleFire {} @end -DEPRECATED_ATTRIBUTE @interface ParticleFireworks : CCParticleFireworks {} @end -DEPRECATED_ATTRIBUTE @interface ParticleFlower : CCParticleFlower {} @end -DEPRECATED_ATTRIBUTE @interface ParticleGalaxy : CCParticleGalaxy {} @end -DEPRECATED_ATTRIBUTE @interface ParticleMeteor : CCParticleMeteor {} @end -DEPRECATED_ATTRIBUTE @interface ParticleRain : CCParticleRain {} @end -DEPRECATED_ATTRIBUTE @interface ParticleSmoke : CCParticleSmoke {} @end -DEPRECATED_ATTRIBUTE @interface ParticleSnow : CCParticleSnow {} @end -DEPRECATED_ATTRIBUTE @interface ParticleSpiral : CCParticleSpiral {} @end -DEPRECATED_ATTRIBUTE @interface ParticleSun : CCParticleSun {} @end -DEPRECATED_ATTRIBUTE @interface ParticleSystem : CCParticleSystem {} @end -DEPRECATED_ATTRIBUTE @interface Place : CCPlace {} @end -DEPRECATED_ATTRIBUTE @interface PointParticleSystem : CCPointParticleSystem {} @end -DEPRECATED_ATTRIBUTE @interface QuadParticleSystem : CCQuadParticleSystem {} @end -DEPRECATED_ATTRIBUTE @interface RenderTexture : CCRenderTexture {} @end -DEPRECATED_ATTRIBUTE @interface Repeat : CCRepeat {} @end -DEPRECATED_ATTRIBUTE @interface RepeatForever : CCRepeatForever {} @end -DEPRECATED_ATTRIBUTE @interface ReuseGrid : CCReuseGrid {} @end -DEPRECATED_ATTRIBUTE @interface ReverseTime : CCReverseTime {} @end -DEPRECATED_ATTRIBUTE @interface Ribbon : CCRibbon {} @end -DEPRECATED_ATTRIBUTE @interface RibbonSegment : CCRibbonSegment {} @end -DEPRECATED_ATTRIBUTE @interface Ripple3D : CCRipple3D {} @end -DEPRECATED_ATTRIBUTE @interface RotateBy : CCRotateBy {} @end -DEPRECATED_ATTRIBUTE @interface RotateTo : CCRotateTo {} @end -DEPRECATED_ATTRIBUTE @interface RotoZoomTransition : CCTransitionRotoZoom {} @end -DEPRECATED_ATTRIBUTE @interface ScaleBy : CCScaleBy {} @end -DEPRECATED_ATTRIBUTE @interface ScaleTo : CCScaleTo {} @end -DEPRECATED_ATTRIBUTE @interface Scene : CCScene {} @end -DEPRECATED_ATTRIBUTE @interface Scheduler : CCScheduler {} @end -DEPRECATED_ATTRIBUTE @interface Sequence : CCSequence {} @end -DEPRECATED_ATTRIBUTE @interface Shaky3D : CCShaky3D {} @end -DEPRECATED_ATTRIBUTE @interface ShakyTiles3D : CCShakyTiles3D {} @end -DEPRECATED_ATTRIBUTE @interface ShatteredTiles3D : CCShatteredTiles3D {} @end -DEPRECATED_ATTRIBUTE @interface Show : CCShow {} @end -DEPRECATED_ATTRIBUTE @interface ShrinkGrowTransition : CCTransitionShrinkGrow {} @end -DEPRECATED_ATTRIBUTE @interface ShuffleTiles : CCShuffleTiles {} @end -DEPRECATED_ATTRIBUTE @interface SlideInBTransition : CCTransitionSlideInB {} @end -DEPRECATED_ATTRIBUTE @interface SlideInLTransition : CCTransitionSlideInL {} @end -DEPRECATED_ATTRIBUTE @interface SlideInRTransition : CCTransitionSlideInR {} @end -DEPRECATED_ATTRIBUTE @interface SlideInTTransition : CCTransitionSlideInT {} @end -DEPRECATED_ATTRIBUTE @interface Spawn : CCSpawn {} @end -DEPRECATED_ATTRIBUTE @interface Speed : CCSpeed {} @end -DEPRECATED_ATTRIBUTE @interface SplitCols : CCSplitCols {} @end -DEPRECATED_ATTRIBUTE @interface SplitColsTransition : CCTransitionSplitCols {} @end -DEPRECATED_ATTRIBUTE @interface SplitRows : CCSplitRows {} @end -DEPRECATED_ATTRIBUTE @interface SplitRowsTransition : CCTransitionSplitRows {} @end -DEPRECATED_ATTRIBUTE @interface Sprite : CCSprite {} @end -DEPRECATED_ATTRIBUTE @interface StandardTouchHandler : CCStandardTouchHandler {} @end -DEPRECATED_ATTRIBUTE @interface StopGrid : CCStopGrid {} @end -DEPRECATED_ATTRIBUTE @interface TMXLayer : CCTMXLayer {} @end -DEPRECATED_ATTRIBUTE @interface TMXLayerInfo : CCTMXLayerInfo {} @end -DEPRECATED_ATTRIBUTE @interface TMXMapInfo : CCTMXMapInfo {} @end -DEPRECATED_ATTRIBUTE @interface TMXTiledMap : CCTMXTiledMap {} @end -DEPRECATED_ATTRIBUTE @interface TMXTilesetInfo : CCTMXTilesetInfo {} @end -DEPRECATED_ATTRIBUTE @interface TargetedTouchHandler : CCTargetedTouchHandler {} @end -DEPRECATED_ATTRIBUTE @interface Texture2D : CCTexture2D {} @end -DEPRECATED_ATTRIBUTE @interface TextureAtlas : CCTextureAtlas {} @end -DEPRECATED_ATTRIBUTE @interface TextureMgr : CCTextureCache {} @end -DEPRECATED_ATTRIBUTE @interface TextureNode : CCSprite {} @end -DEPRECATED_ATTRIBUTE @interface ThreadedFastDirector : CCThreadedFastDirector {} @end -DEPRECATED_ATTRIBUTE @interface TileMapAtlas : CCTileMapAtlas {} @end -DEPRECATED_ATTRIBUTE @interface TiledGrid3D : CCTiledGrid3D {} @end -DEPRECATED_ATTRIBUTE @interface TiledGrid3DAction : CCTiledGrid3DAction {} @end -DEPRECATED_ATTRIBUTE @interface Timer : CCTimer {} @end -DEPRECATED_ATTRIBUTE @interface TimerDirector : CCTimerDirector {} @end -DEPRECATED_ATTRIBUTE @interface TintBy : CCTintBy {} @end -DEPRECATED_ATTRIBUTE @interface TintTo : CCTintTo {} @end -DEPRECATED_ATTRIBUTE @interface ToggleVisibility : CCToggleVisibility {} @end -DEPRECATED_ATTRIBUTE @interface TouchDispatcher : CCTouchDispatcher {} @end -DEPRECATED_ATTRIBUTE @interface TouchHandler : CCTouchHandler {} @end -DEPRECATED_ATTRIBUTE @interface TransitionScene : CCTransitionScene {} @end -DEPRECATED_ATTRIBUTE @interface TurnOffTiles : CCTurnOffTiles {} @end -DEPRECATED_ATTRIBUTE @interface TurnOffTilesTransition : CCTransitionTurnOffTiles {} @end -DEPRECATED_ATTRIBUTE @interface Twirl : CCTwirl {} @end -DEPRECATED_ATTRIBUTE @interface Waves : CCWaves {} @end -DEPRECATED_ATTRIBUTE @interface Waves3D : CCWaves3D {} @end -DEPRECATED_ATTRIBUTE @interface WavesTiles3D : CCWavesTiles3D {} @end -DEPRECATED_ATTRIBUTE @interface ZoomFlipAngularTransition : CCTransitionZoomFlipAngular {} @end -DEPRECATED_ATTRIBUTE @interface ZoomFlipXTransition : CCTransitionZoomFlipX {} @end -DEPRECATED_ATTRIBUTE @interface ZoomFlipYTransition : CCTransitionZoomFlipY {} @end - -#endif // CC_COMPATIBILITY_WITH_0_8 diff --git a/Example/libs/cocos2d/CCCompatibility.m b/Example/libs/cocos2d/CCCompatibility.m deleted file mode 100644 index 93d0e53..0000000 --- a/Example/libs/cocos2d/CCCompatibility.m +++ /dev/null @@ -1,596 +0,0 @@ - -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -// AUTOMATICALLY GENERATED. DO NOT EDIT - -#include "CCCompatibility.h" -#if CC_COMPATIBILITY_WITH_0_8 -@implementation AccelAmplitude -@end - -@implementation AccelDeccelAmplitude -@end - -@implementation Action -@end - -@implementation ActionManager -@end - -@implementation Animate -@end - -@implementation Animation -@end - -@implementation AtlasAnimation -@end - -@implementation AtlasNode -@end - -@implementation AtlasSprite -@end - -@implementation AtlasSpriteFrame -@end - -@implementation AtlasSpriteManager -@end - -@implementation BezierBy -@end - -@implementation BezierTo -@end - -@implementation BitmapFontAtlas -@end - -@implementation BitmapFontConfiguration -@end - -@implementation Blink -@end - -@implementation CallFunc -@end - -@implementation CallFuncN -@end - -@implementation CallFuncND -@end - -@implementation Camera -@end - -@implementation CameraAction -@end - -@implementation CocosNode -@end - -@implementation ColorLayer -@end - -@implementation DeccelAmplitude -@end - -@implementation DelayTime -@end - -@implementation Director -@end - -@implementation DisplayLinkDirector -@end - -@implementation EaseAction -@end - -@implementation EaseBackIn -@end - -@implementation EaseBackInOut -@end - -@implementation EaseBackOut -@end - -@implementation EaseBounce -@end - -@implementation EaseBounceIn -@end - -@implementation EaseBounceInOut -@end - -@implementation EaseBounceOut -@end - -@implementation EaseElastic -@end - -@implementation EaseElasticIn -@end - -@implementation EaseElasticInOut -@end - -@implementation EaseElasticOut -@end - -@implementation EaseExponentialIn -@end - -@implementation EaseExponentialInOut -@end - -@implementation EaseExponentialOut -@end - -@implementation EaseIn -@end - -@implementation EaseInOut -@end - -@implementation EaseOut -@end - -@implementation EaseRateAction -@end - -@implementation EaseSineIn -@end - -@implementation EaseSineInOut -@end - -@implementation EaseSineOut -@end - -@implementation FadeBLTransition -@end - -@implementation FadeDownTransition -@end - -@implementation FadeIn -@end - -@implementation FadeOut -@end - -@implementation FadeOutBLTiles -@end - -@implementation FadeOutDownTiles -@end - -@implementation FadeOutTRTiles -@end - -@implementation FadeOutUpTiles -@end - -@implementation FadeTRTransition -@end - -@implementation FadeTo -@end - -@implementation FadeTransition -@end - -@implementation FadeUpTransition -@end - -@implementation FastDirector -@end - -@implementation FiniteTimeAction -@end - -@implementation FlipAngularTransition -@end - -@implementation FlipX3D -@end - -@implementation FlipXTransition -@end - -@implementation FlipY3D -@end - -@implementation FlipYTransition -@end - -@implementation Grabber -@end - -@implementation Grid3D -@end - -@implementation Grid3DAction -@end - -@implementation GridAction -@end - -@implementation GridBase -@end - -@implementation Hide -@end - -@implementation InstantAction -@end - -@implementation IntervalAction -@end - -@implementation JumpBy -@end - -@implementation JumpTiles3D -@end - -@implementation JumpTo -@end - -@implementation JumpZoomTransition -@end - -@implementation Label -@end - -@implementation LabelAtlas -@end - -@implementation Layer -@end - -@implementation Lens3D -@end - -@implementation Liquid -@end - -@implementation Menu -@end - -@implementation MenuItem -@end - -@implementation MenuItemAtlasFont -@end - -@implementation MenuItemFont -@end - -@implementation MenuItemImage -@end - -@implementation MenuItemLabel -@end - -@implementation MenuItemSprite -@end - -@implementation MenuItemToggle -@end - -@implementation MotionStreak -@end - -@implementation MoveBy -@end - -@implementation MoveInBTransition -@end - -@implementation MoveInLTransition -@end - -@implementation MoveInRTransition -@end - -@implementation MoveInTTransition -@end - -@implementation MoveTo -@end - -@implementation MultiplexLayer -@end - -@implementation OrbitCamera -@end - -@implementation OrientedTransitionScene -@end - -@implementation PVRTexture -@end - -@implementation PageTurn3D -@end - -@implementation PageTurnTransition -@end - -@implementation ParallaxNode -@end - -@implementation ParticleExplosion -@end - -@implementation ParticleFire -@end - -@implementation ParticleFireworks -@end - -@implementation ParticleFlower -@end - -@implementation ParticleGalaxy -@end - -@implementation ParticleMeteor -@end - -@implementation ParticleRain -@end - -@implementation ParticleSmoke -@end - -@implementation ParticleSnow -@end - -@implementation ParticleSpiral -@end - -@implementation ParticleSun -@end - -@implementation ParticleSystem -@end - -@implementation Place -@end - -@implementation PointParticleSystem -@end - -@implementation QuadParticleSystem -@end - -@implementation RenderTexture -@end - -@implementation Repeat -@end - -@implementation RepeatForever -@end - -@implementation ReuseGrid -@end - -@implementation ReverseTime -@end - -@implementation Ribbon -@end - -@implementation RibbonSegment -@end - -@implementation Ripple3D -@end - -@implementation RotateBy -@end - -@implementation RotateTo -@end - -@implementation RotoZoomTransition -@end - -@implementation ScaleBy -@end - -@implementation ScaleTo -@end - -@implementation Scene -@end - -@implementation Scheduler -@end - -@implementation Sequence -@end - -@implementation Shaky3D -@end - -@implementation ShakyTiles3D -@end - -@implementation ShatteredTiles3D -@end - -@implementation Show -@end - -@implementation ShrinkGrowTransition -@end - -@implementation ShuffleTiles -@end - -@implementation SlideInBTransition -@end - -@implementation SlideInLTransition -@end - -@implementation SlideInRTransition -@end - -@implementation SlideInTTransition -@end - -@implementation Spawn -@end - -@implementation Speed -@end - -@implementation SplitCols -@end - -@implementation SplitColsTransition -@end - -@implementation SplitRows -@end - -@implementation SplitRowsTransition -@end - -@implementation Sprite -@end - -@implementation StandardTouchHandler -@end - -@implementation StopGrid -@end - -@implementation TMXLayer -@end - -@implementation TMXLayerInfo -@end - -@implementation TMXMapInfo -@end - -@implementation TMXTiledMap -@end - -@implementation TMXTilesetInfo -@end - -@implementation TargetedTouchHandler -@end - -@implementation Texture2D -@end - -@implementation TextureAtlas -@end - -@implementation TextureMgr -@end - -@implementation TextureNode -@end - -@implementation ThreadedFastDirector -@end - -@implementation TileMapAtlas -@end - -@implementation TiledGrid3D -@end - -@implementation TiledGrid3DAction -@end - -@implementation Timer -@end - -@implementation TimerDirector -@end - -@implementation TintBy -@end - -@implementation TintTo -@end - -@implementation ToggleVisibility -@end - -@implementation TouchDispatcher -@end - -@implementation TouchHandler -@end - -@implementation TransitionScene -@end - -@implementation TurnOffTiles -@end - -@implementation TurnOffTilesTransition -@end - -@implementation Twirl -@end - -@implementation Waves -@end - -@implementation Waves3D -@end - -@implementation WavesTiles3D -@end - -@implementation ZoomFlipAngularTransition -@end - -@implementation ZoomFlipXTransition -@end - -@implementation ZoomFlipYTransition -@end - - -#endif // CC_COMPATIBILITY_WITH_0_8 diff --git a/Example/libs/cocos2d/CCConfiguration.h b/Example/libs/cocos2d/CCConfiguration.h index 11bd120..9bae614 100644 --- a/Example/libs/cocos2d/CCConfiguration.h +++ b/Example/libs/cocos2d/CCConfiguration.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,20 +30,23 @@ /** OS version definitions. Includes both iOS and Mac OS versions */ enum { - kCCiOSVersion_3_0 = 0x03000000, - kCCiOSVersion_3_1 = 0x03010000, - kCCiOSVersion_3_1_1 = 0x03010100, - kCCiOSVersion_3_1_2 = 0x03010200, - kCCiOSVersion_3_1_3 = 0x03010300, - kCCiOSVersion_3_2 = 0x03020000, - kCCiOSVersion_3_2_1 = 0x03020100, kCCiOSVersion_4_0 = 0x04000000, kCCiOSVersion_4_0_1 = 0x04000100, kCCiOSVersion_4_1 = 0x04010000, - - kCCMacVersion_10_5 = 0x0a050000, + kCCiOSVersion_4_2 = 0x04020000, + kCCiOSVersion_4_2_1 = 0x04020100, + kCCiOSVersion_4_3 = 0x04030000, + kCCiOSVersion_4_3_1 = 0x04030100, + kCCiOSVersion_4_3_2 = 0x04030200, + kCCiOSVersion_4_3_3 = 0x04030300, + kCCiOSVersion_4_3_4 = 0x04030400, + kCCiOSVersion_4_3_5 = 0x04030500, + kCCiOSVersion_5_0 = 0x05000000, + kCCiOSVersion_5_0_1 = 0x05000100, + kCCMacVersion_10_6 = 0x0a060000, kCCMacVersion_10_7 = 0x0a070000, + kCCMacVersion_10_8 = 0x0a080000, }; /** @@ -59,6 +63,7 @@ enum { BOOL supportsDiscardFramebuffer_; unsigned int OSVersion_; GLint maxSamplesAllowed_; + GLint maxTextureUnits_; } /** OpenGL Max texture size. */ @@ -67,11 +72,14 @@ enum { /** OpenGL Max Modelview Stack Depth. */ @property (nonatomic, readonly) GLint maxModelviewStackDepth; +/** returns the maximum texture units + @since v2.0.0 + */ +@property (nonatomic, readonly) GLint maxTextureUnits; + /** Whether or not the GPU supports NPOT (Non Power Of Two) textures. - NPOT textures have the following limitations: - - They can't have mipmaps - - They only accept GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T} - + OpenGL ES 2.0 already supports NPOT (iOS). + @since v0.99.2 */ @property (nonatomic, readonly) BOOL supportsNPOT; @@ -80,13 +88,13 @@ enum { @property (nonatomic, readonly) BOOL supportsPVRTC; /** Whether or not BGRA8888 textures are supported. - + @since v0.99.2 */ @property (nonatomic, readonly) BOOL supportsBGRA8888; /** Whether or not glDiscardFramebufferEXT is supported - + @since v0.99.2 */ @property (nonatomic, readonly) BOOL supportsDiscardFramebuffer; @@ -94,7 +102,7 @@ enum { /** returns the OS version. - On iOS devices it returns the firmware version. - On Mac returns the OS version - + @since v0.99.5 */ @property (nonatomic, readonly) unsigned int OSVersion; diff --git a/Example/libs/cocos2d/CCConfiguration.m b/Example/libs/cocos2d/CCConfiguration.m index e70bed1..24b2cae 100644 --- a/Example/libs/cocos2d/CCConfiguration.m +++ b/Example/libs/cocos2d/CCConfiguration.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,14 +23,13 @@ * THE SOFTWARE. */ -#import +#import "ccMacros.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import // Needed for UIDevice #endif #import "Platforms/CCGL.h" -#import "CCBlockSupport.h" #import "CCConfiguration.h" #import "ccMacros.h" #import "ccConfig.h" @@ -37,7 +37,7 @@ @implementation CCConfiguration -@synthesize maxTextureSize = maxTextureSize_; +@synthesize maxTextureSize = maxTextureSize_, maxTextureUnits=maxTextureUnits_; @synthesize supportsPVRTC = supportsPVRTC_; @synthesize maxModelviewStackDepth = maxModelviewStackDepth_; @synthesize supportsNPOT = supportsNPOT_; @@ -67,105 +67,85 @@ +(id)alloc } -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#ifdef __CC_PLATFORM_IOS +#elif defined(__CC_PLATFORM_MAC) - (NSString*)getMacVersion { SInt32 versionMajor, versionMinor, versionBugFix; Gestalt(gestaltSystemVersionMajor, &versionMajor); Gestalt(gestaltSystemVersionMinor, &versionMinor); Gestalt(gestaltSystemVersionBugFix, &versionBugFix); - + return [NSString stringWithFormat:@"%d.%d.%d", versionMajor, versionMinor, versionBugFix]; } -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_MAC -(id) init { if( (self=[super init])) { - + // Obtain iOS version OSVersion_ = 0; -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS NSString *OSVer = [[UIDevice currentDevice] systemVersion]; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) NSString *OSVer = [self getMacVersion]; #endif - NSArray *arr = [OSVer componentsSeparatedByString:@"."]; - int idx=0x01000000; + NSArray *arr = [OSVer componentsSeparatedByString:@"."]; + int idx = 0x01000000; for( NSString *str in arr ) { int value = [str intValue]; OSVersion_ += value * idx; idx = idx >> 8; } CCLOG(@"cocos2d: OS version: %@ (0x%08x)", OSVer, OSVersion_); - + CCLOG(@"cocos2d: GL_VENDOR: %s", glGetString(GL_VENDOR) ); CCLOG(@"cocos2d: GL_RENDERER: %s", glGetString ( GL_RENDERER ) ); CCLOG(@"cocos2d: GL_VERSION: %s", glGetString ( GL_VERSION ) ); - + glExtensions = (char*) glGetString(GL_EXTENSIONS); - + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize_); - glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, &maxModelviewStackDepth_); -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED + glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits_ ); + +#ifdef __CC_PLATFORM_IOS if( OSVersion_ >= kCCiOSVersion_4_0 ) glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamplesAllowed_); else maxSamplesAllowed_ = 0; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) glGetIntegerv(GL_MAX_SAMPLES, &maxSamplesAllowed_); #endif - + supportsPVRTC_ = [self checkForGLExtension:@"GL_IMG_texture_compression_pvrtc"]; -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - supportsNPOT_ = [self checkForGLExtension:@"GL_APPLE_texture_2D_limited_npot"]; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#ifdef __CC_PLATFORM_IOS + supportsNPOT_ = YES; +#elif defined(__CC_PLATFORM_MAC) supportsNPOT_ = [self checkForGLExtension:@"GL_ARB_texture_non_power_of_two"]; #endif // It seems that somewhere between firmware iOS 3.0 and 4.2 Apple renamed // GL_IMG_... to GL_APPLE.... So we should check both names - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED + +#ifdef __CC_PLATFORM_IOS BOOL bgra8a = [self checkForGLExtension:@"GL_IMG_texture_format_BGRA8888"]; BOOL bgra8b = [self checkForGLExtension:@"GL_APPLE_texture_format_BGRA8888"]; supportsBGRA8888_ = bgra8a | bgra8b; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) supportsBGRA8888_ = [self checkForGLExtension:@"GL_EXT_bgra"]; #endif - + supportsDiscardFramebuffer_ = [self checkForGLExtension:@"GL_EXT_discard_framebuffer"]; CCLOG(@"cocos2d: GL_MAX_TEXTURE_SIZE: %d", maxTextureSize_); - CCLOG(@"cocos2d: GL_MAX_MODELVIEW_STACK_DEPTH: %d",maxModelviewStackDepth_); + CCLOG(@"cocos2d: GL_MAX_TEXTURE_UNITS: %d", maxTextureUnits_); CCLOG(@"cocos2d: GL_MAX_SAMPLES: %d", maxSamplesAllowed_); CCLOG(@"cocos2d: GL supports PVRTC: %s", (supportsPVRTC_ ? "YES" : "NO") ); CCLOG(@"cocos2d: GL supports BGRA8888 textures: %s", (supportsBGRA8888_ ? "YES" : "NO") ); CCLOG(@"cocos2d: GL supports NPOT textures: %s", (supportsNPOT_ ? "YES" : "NO") ); CCLOG(@"cocos2d: GL supports discard_framebuffer: %s", (supportsDiscardFramebuffer_ ? "YES" : "NO") ); - CCLOG(@"cocos2d: compiled with NPOT support: %s", -#if CC_TEXTURE_NPOT_SUPPORT - "YES" -#else - "NO" -#endif - ); - CCLOG(@"cocos2d: compiled with VBO support in TextureAtlas : %s", -#if CC_USES_VBO - "YES" -#else - "NO" -#endif - ); - CCLOG(@"cocos2d: compiled with Affine Matrix transformation in CCNode : %s", -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - "YES" -#else - "NO" -#endif - ); - + CCLOG(@"cocos2d: compiled with Profiling Support: %s", #if CC_ENABLE_PROFILERS @@ -174,10 +154,17 @@ -(id) init "NO" #endif ); - - CHECK_GL_ERROR(); + } - + +#if CC_ENABLE_GL_STATE_CACHE == 0 + printf("\n"); + NSLog(@"cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it by editing ccConfig.h"); + printf("\n"); +#endif + + CHECK_GL_ERROR_DEBUG(); + return self; } diff --git a/Example/libs/cocos2d/CCDirector.h b/Example/libs/cocos2d/CCDirector.h index fd36364..1fda4c0 100644 --- a/Example/libs/cocos2d/CCDirector.h +++ b/Example/libs/cocos2d/CCDirector.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,10 +26,11 @@ #import "ccConfig.h" #import "ccTypes.h" +#import "ccMacros.h" -// OpenGL related -#import "Platforms/CCGL.h" #import "CCProtocols.h" +#import "Platforms/CCGL.h" +#import "kazmath/mat4.h" /** @typedef ccDirectorProjection Possible OpenGL projections used by director @@ -36,109 +38,117 @@ typedef enum { /// sets a 2D projection (orthogonal projection). kCCDirectorProjection2D, - + /// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500. kCCDirectorProjection3D, - + /// it calls "updateProjection" on the projection delegate. kCCDirectorProjectionCustom, - + /// Detault projection is 3D projection kCCDirectorProjectionDefault = kCCDirectorProjection3D, - - // backward compatibility stuff - CCDirectorProjection2D = kCCDirectorProjection2D, - CCDirectorProjection3D = kCCDirectorProjection3D, - CCDirectorProjectionCustom = kCCDirectorProjectionCustom, } ccDirectorProjection; @class CCLabelAtlas; @class CCScene; +@class CCScheduler; +@class CCActionManager; + + +#ifdef __CC_PLATFORM_IOS +#define CC_VIEWCONTROLLER UIViewController +#elif defined(__CC_PLATFORM_MAC) +#define CC_VIEWCONTROLLER NSObject +#endif /**Class that creates and handle the main Window and manages how and when to execute the Scenes. - + The CCDirector is also resposible for: - initializing the OpenGL ES context - setting the OpenGL pixel format (default on is RGB565) - setting the OpenGL buffer depth (default one is 0-bit) - setting the projection (default one is 3D) - - setting the orientation (default one is Protrait) - + Since the CCDirector is a singleton, the standard way to use it is by calling: - [[CCDirector sharedDirector] methodName]; - + The CCDirector also sets the default OpenGL context: - GL_TEXTURE_2D is enabled - GL_VERTEX_ARRAY is enabled - GL_COLOR_ARRAY is enabled - GL_TEXTURE_COORD_ARRAY is enabled */ -@interface CCDirector : NSObject +@interface CCDirector : CC_VIEWCONTROLLER { - CC_GLVIEW *openGLView_; - // internal timer NSTimeInterval animationInterval_; - NSTimeInterval oldAnimationInterval_; - - /* display FPS ? */ - BOOL displayFPS_; + NSTimeInterval oldAnimationInterval_; + + /* stats */ + BOOL displayStats_; NSUInteger frames_; - ccTime accumDt_; - ccTime frameRate_; -#if CC_DIRECTOR_FAST_FPS + NSUInteger totalFrames_; + ccTime secondsPerFrame_; + + ccTime accumDt_; + ccTime frameRate_; CCLabelAtlas *FPSLabel_; -#endif - + CCLabelAtlas *SPFLabel_; + CCLabelAtlas *drawsLabel_; + /* is the running scene paused */ BOOL isPaused_; - + /* The running scene */ CCScene *runningScene_; - + /* This object will be visited after the scene. Useful to hook a notification node */ id notificationNode_; - + /* will be the next 'runningScene' in the next frame nextScene is a weak reference. */ CCScene *nextScene_; - + /* If YES, then "old" scene will receive the cleanup message */ BOOL sendCleanupToScene_; /* scheduled scenes */ NSMutableArray *scenesStack_; - + /* last time the main loop was updated */ struct timeval lastUpdate_; /* delta time since last tick to main loop */ ccTime dt; /* whether or not the next delta time will be zero */ BOOL nextDeltaTimeZero_; - + /* projection used */ ccDirectorProjection projection_; - - /* Projection protocol delegate */ - id projectionDelegate_; + + /* CCDirector delegate */ + id delegate_; /* window size in points */ CGSize winSizeInPoints_; - + /* window size in pixels */ CGSize winSizeInPixels_; /* the cocos2d running thread */ NSThread *runningThread_; - // profiler -#if CC_ENABLE_PROFILERS - ccTime accumDtForProfiler_; -#endif + /* scheduler associated with this director */ + CCScheduler *scheduler_; + + /* action manager associated with this director */ + CCActionManager *actionManager_; + + /* OpenGLView. On iOS it is a copy of self.view */ + CCGLView *view_; } /** returns the cocos2d thread. @@ -151,18 +161,18 @@ and when to execute the Scenes. @property (nonatomic,readonly) CCScene* runningScene; /** The FPS value */ @property (nonatomic,readwrite, assign) NSTimeInterval animationInterval; -/** Whether or not to display the FPS on the bottom-left corner */ -@property (nonatomic,readwrite, assign) BOOL displayFPS; -/** The OpenGLView, where everything is rendered */ -@property (nonatomic,readwrite,retain) CC_GLVIEW *openGLView; +/** Whether or not to display director statistics */ +@property (nonatomic, readwrite, assign) BOOL displayStats; /** whether or not the next delta time will be zero */ @property (nonatomic,readwrite,assign) BOOL nextDeltaTimeZero; /** Whether or not the Director is paused */ @property (nonatomic,readonly) BOOL isPaused; -/** Sets an OpenGL projection - @since v0.8.2 - */ +/** Sets an OpenGL projection */ @property (nonatomic,readwrite) ccDirectorProjection projection; +/** How many frames were called since the director started */ +@property (nonatomic,readonly) NSUInteger totalFrames; +/** seconds per frame */ +@property (nonatomic, readonly) ccTime secondsPerFrame; /** Whether or not the replaced scene will receive the cleanup message. If the new scene is pushed, then the old scene won't receive the "cleanup" message. @@ -178,32 +188,36 @@ and when to execute the Scenes. */ @property (nonatomic, readwrite, retain) id notificationNode; -/** This object will be called when the OpenGL projection is udpated and only when the kCCDirectorProjectionCustom projection is used. +/** CCDirector delegate. It shall implemente the CCDirectorDelegate protocol @since v0.99.5 */ -@property (nonatomic, readwrite, retain) id projectionDelegate; +@property (nonatomic, readwrite, retain) id delegate; -/** returns a shared instance of the director */ -+(CCDirector *)sharedDirector; +/** CCScheduler associated with this director + @since v2.0 + */ +@property (nonatomic,readwrite,retain) CCScheduler *scheduler; +/** CCActionManager associated with this director + @since v2.0 + */ +@property (nonatomic,readwrite,retain) CCActionManager *actionManager; +/** returns a shared instance of the director */ ++(CCDirector*)sharedDirector; -// Window size -/** returns the size of the OpenGL view in points. - It takes into account any possible rotation (device orientation) of the window - */ +#pragma mark Director - Stats + +#pragma mark Director - Win Size +/** returns the size of the OpenGL view in points */ - (CGSize) winSize; /** returns the size of the OpenGL view in pixels. - It takes into account any possible rotation (device orientation) of the window. On Mac winSize and winSizeInPixels return the same value. */ - (CGSize) winSizeInPixels; -/** returns the display size of the OpenGL view in pixels. - It doesn't take into account any possible rotation of the window. - */ --(CGSize) displaySizeInPixels; + /** changes the projection size */ -(void) reshapeProjection:(CGSize)newWindowSize; @@ -219,17 +233,19 @@ and when to execute the Scenes. /// XXX: missing description -(float) getZEye; -// Scene Management +#pragma mark Director - Scene Management -/**Enters the Director's main loop with the given Scene. +/**Enters the Director's main loop with the given Scene. * Call it to run only your FIRST scene. * Don't call it if there is already a running scene. + * + * It will call pushScene: and then it will call startAnimation */ - (void) runWithScene:(CCScene*) scene; /**Suspends the execution of the running scene, pushing it on the stack of suspended scenes. * The new scene will be executed. - * Try to avoid big stacks of pushed scenes to reduce memory allocation. + * Try to avoid big stacks of pushed scenes to reduce memory allocation. * ONLY call it if there is a running scene. */ - (void) pushScene:(CCScene*) scene; @@ -279,26 +295,38 @@ and when to execute the Scenes. */ -(void) drawScene; -// Memory Helper + +// XXX: Hack. Should be placed on CCDirectorMac.h. Refactoring needed +#if defined(__CC_PLATFORM_MAC) +/** sets the openGL view */ +-(void) setView:(CCGLView*)view; + +/** returns the OpenGL view */ +-(CCGLView*) view; +#endif + +#pragma mark Director - Memory Helper /** Removes all the cocos2d data that was cached automatically. - It will purge the CCTextureCache, CCBitmapFont cache. + It will purge the CCTextureCache, CCLabelBMFont cache. IMPORTANT: The CCSpriteFrameCache won't be purged. If you want to purge it, you have to purge it manually. @since v0.99.3 */ --(void) purgeCachedData; +-(void) purgeCachedData; // OpenGL Helper /** sets the OpenGL default values */ -(void) setGLDefaultValues; - /** enables/disables OpenGL alpha blending */ - (void) setAlphaBlending: (BOOL) on; /** enables/disables OpenGL depth test */ - (void) setDepthTest: (BOOL) on; -// Profiler --(void) showProfilers; - +// helper +/** creates the Stats labels */ +-(void) createStatsLabel; @end + +// optimization. Should only be used to read it. Never to write it. +extern NSUInteger __ccNumberOfDraws; diff --git a/Example/libs/cocos2d/CCDirector.m b/Example/libs/cocos2d/CCDirector.m index 35425fe..7134942 100644 --- a/Example/libs/cocos2d/CCDirector.m +++ b/Example/libs/cocos2d/CCDirector.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,7 +28,6 @@ */ #import -#import // cocos2d imports #import "CCDirector.h" @@ -43,6 +43,8 @@ #import "CCTexture2D.h" #import "CCLabelBMFont.h" #import "CCLayer.h" +#import "ccGLStateCache.h" +#import "CCShaderCache.h" // support imports #import "Platforms/CCGL.h" @@ -50,41 +52,53 @@ #import "Support/OpenGL_Internal.h" #import "Support/CGPointExtension.h" +#import "Support/CCProfiling.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import "Platforms/iOS/CCDirectorIOS.h" -#define CC_DIRECTOR_DEFAULT CCDirectorTimer -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#define CC_DIRECTOR_DEFAULT CCDirectorDisplayLink +#elif defined(__CC_PLATFORM_MAC) #import "Platforms/Mac/CCDirectorMac.h" #define CC_DIRECTOR_DEFAULT CCDirectorDisplayLink #endif -#import "Support/CCProfiling.h" + +#pragma mark - +#pragma mark Director - global variables (optimization) + +// XXX it shoul be a Director ivar. Move it there once support for multiple directors is added +NSUInteger __ccNumberOfDraws = 0; #define kDefaultFPS 60.0 // 60 frames per second extern NSString * cocos2dVersion(void); - @interface CCDirector (Private) -(void) setNextScene; -// shows the FPS in the screen --(void) showFPS; +// shows the statistics +-(void) showStats; // calculates delta time since last time it was called -(void) calculateDeltaTime; +// calculates the milliseconds per frame from the start of the frame +-(void) calculateMPF; @end @implementation CCDirector @synthesize animationInterval = animationInterval_; @synthesize runningScene = runningScene_; -@synthesize displayFPS = displayFPS_; +@synthesize displayStats = displayStats_; @synthesize nextDeltaTimeZero = nextDeltaTimeZero_; @synthesize isPaused = isPaused_; @synthesize sendCleanupToScene = sendCleanupToScene_; @synthesize runningThread = runningThread_; @synthesize notificationNode = notificationNode_; -@synthesize projectionDelegate = projectionDelegate_; +@synthesize delegate = delegate_; +@synthesize totalFrames = totalFrames_; +@synthesize secondsPerFrame = secondsPerFrame_; +@synthesize scheduler = scheduler_; +@synthesize actionManager = actionManager_; + // // singleton stuff // @@ -95,14 +109,14 @@ + (CCDirector *)sharedDirector if (!_sharedDirector) { // - // Default Director is TimerDirector - // + // Default Director is DisplayLink + // if( [ [CCDirector class] isEqual:[self class]] ) _sharedDirector = [[CC_DIRECTOR_DEFAULT alloc] init]; else _sharedDirector = [[self alloc] init]; } - + return _sharedDirector; } @@ -113,102 +127,106 @@ +(id)alloc } - (id) init -{ +{ CCLOG(@"cocos2d: %@", cocos2dVersion() ); - if( (self=[super init]) ) { + if( (self=[super init] ) ) { CCLOG(@"cocos2d: Using Director Type:%@", [self class]); - + // scenes runningScene_ = nil; nextScene_ = nil; - + notificationNode_ = nil; - + oldAnimationInterval_ = animationInterval_ = 1.0 / kDefaultFPS; scenesStack_ = [[NSMutableArray alloc] initWithCapacity:10]; - + // Set default projection (3D) projection_ = kCCDirectorProjectionDefault; // projection delegate if "Custom" projection is used - projectionDelegate_ = nil; + delegate_ = nil; // FPS - displayFPS_ = NO; - frames_ = 0; - + displayStats_ = NO; + totalFrames_ = frames_ = 0; + // paused ? isPaused_ = NO; - + // running thread runningThread_ = nil; - + + // scheduler + scheduler_ = [[CCScheduler alloc] init]; + + // action manager + actionManager_ = [[CCActionManager alloc] init]; + [scheduler_ scheduleUpdateForTarget:actionManager_ priority:kCCActionManagerPriority paused:NO]; + winSizeInPixels_ = winSizeInPoints_ = CGSizeZero; } return self; } +- (NSString*) description +{ + return [NSString stringWithFormat:@"<%@ = %08X | Size: %0.f x %0.f, view = %@>", [self class], self, winSizeInPoints_.width, winSizeInPoints_.height, view_]; +} + - (void) dealloc { CCLOGINFO(@"cocos2d: deallocing %@", self); -#if CC_DIRECTOR_FAST_FPS [FPSLabel_ release]; -#endif + [SPFLabel_ release]; + [drawsLabel_ release]; [runningScene_ release]; [notificationNode_ release]; [scenesStack_ release]; - - [projectionDelegate_ release]; - + [scheduler_ release]; + [actionManager_ release]; + [delegate_ release]; + _sharedDirector = nil; - + [super dealloc]; } -(void) setGLDefaultValues { - // This method SHOULD be called only after openGLView_ was initialized - NSAssert( openGLView_, @"openGLView_ must be initialized"); + // This method SHOULD be called only after view_ was initialized + NSAssert( view_, @"view_ must be initialized"); [self setAlphaBlending: YES]; [self setDepthTest: YES]; [self setProjection: projection_]; - + // set other opengl default values glClearColor(0.0f, 0.0f, 0.0f, 1.0f); - -#if CC_DIRECTOR_FAST_FPS - if (!FPSLabel_) { - CCTexture2DPixelFormat currentFormat = [CCTexture2D defaultAlphaPixelFormat]; - [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA4444]; - FPSLabel_ = [[CCLabelAtlas labelWithString:@"00.0" charMapFile:@"fps_images.png" itemWidth:16 itemHeight:24 startCharMap:'.'] retain]; - [CCTexture2D setDefaultAlphaPixelFormat:currentFormat]; - } -#endif // CC_DIRECTOR_FAST_FPS } // // Draw the Scene // - (void) drawScene -{ +{ // Override me } -(void) calculateDeltaTime { struct timeval now; - + if( gettimeofday( &now, NULL) != 0 ) { CCLOG(@"cocos2d: error in gettimeofday"); dt = 0; return; } - + // new delta time if( nextDeltaTimeZero_ ) { dt = 0; @@ -217,16 +235,22 @@ -(void) calculateDeltaTime dt = (now.tv_sec - lastUpdate_.tv_sec) + (now.tv_usec - lastUpdate_.tv_usec) / 1000000.0f; dt = MAX(0,dt); } - - lastUpdate_ = now; + +#ifdef DEBUG + // If we are debugging our code, prevent big delta time + if( dt > 0.2f ) + dt = 1/60.0f; +#endif + + lastUpdate_ = now; } #pragma mark Director - Memory Helper -(void) purgeCachedData { - [CCLabelBMFont purgeCachedData]; - [CCTextureCache purgeSharedTextureCache]; + [CCLabelBMFont purgeCachedData]; + [[CCTextureCache sharedTextureCache] removeUnusedTextures]; } #pragma mark Director - Scene OpenGL Helper @@ -249,46 +273,62 @@ -(void) setProjection:(ccDirectorProjection)projection - (void) setAlphaBlending: (BOOL) on { if (on) { - glEnable(GL_BLEND); - glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); - + ccGLEnable(CC_GL_BLEND); + ccGLBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); + } else glDisable(GL_BLEND); + + CHECK_GL_ERROR_DEBUG(); } - (void) setDepthTest: (BOOL) on { if (on) { - ccglClearDepth(1.0f); + glClearDepth(1.0f); + glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); - glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); +// glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } else glDisable( GL_DEPTH_TEST ); + + CHECK_GL_ERROR_DEBUG(); } #pragma mark Director Integration with a UIKit view --(CC_GLVIEW*) openGLView +-(void) setView:(CCGLView*)view { - return openGLView_; -} +// NSAssert( view, @"OpenGLView must be non-nil"); --(void) setOpenGLView:(CC_GLVIEW *)view -{ - NSAssert( view, @"OpenGLView must be non-nil"); + if( view != view_ ) { + +#ifdef __CC_PLATFORM_IOS + [super setView:view]; +#endif + [view_ release]; + view_ = [view retain]; - if( view != openGLView_ ) { - [openGLView_ release]; - openGLView_ = [view retain]; - // set size - winSizeInPixels_ = winSizeInPoints_ = CCNSSizeToCGSize( [view bounds].size ); + winSizeInPixels_ = winSizeInPoints_ = CCNSSizeToCGSize( [view_ bounds].size ); - [self setGLDefaultValues]; + [self createStatsLabel]; + + // it could be nil + if( view ) + [self setGLDefaultValues]; + + CHECK_GL_ERROR_DEBUG(); } } +-(CCGLView*) view +{ + return view_; +} + + #pragma mark Director Scene Landscape -(CGPoint)convertToGL:(CGPoint)uiPoint @@ -313,11 +353,6 @@ -(CGSize)winSizeInPixels return winSizeInPixels_; } --(CGSize)displaySizeInPixels -{ - return winSizeInPixels_; -} - -(void) reshapeProjection:(CGSize)newWindowSize { winSizeInPixels_ = winSizeInPoints_ = newWindowSize; @@ -329,10 +364,9 @@ -(void) reshapeProjection:(CGSize)newWindowSize - (void)runWithScene:(CCScene*) scene { NSAssert( scene != nil, @"Argument must be non-nil"); - NSAssert( runningScene_ == nil, @"You can't run an scene if another Scene is running. Use replaceScene or pushScene instead"); - + [self pushScene:scene]; - [self startAnimation]; + [self startAnimation]; } -(void) replaceScene: (CCScene*) scene @@ -340,7 +374,7 @@ -(void) replaceScene: (CCScene*) scene NSAssert( scene != nil, @"Argument must be non-nil"); NSUInteger index = [scenesStack_ count]; - + sendCleanupToScene_ = YES; [scenesStack_ replaceObjectAtIndex:index-1 withObject:scene]; nextScene_ = scene; // nextScene_ is a weak ref @@ -357,12 +391,12 @@ - (void) pushScene: (CCScene*) scene } -(void) popScene -{ +{ NSAssert( runningScene_ != nil, @"A running Scene is needed"); [scenesStack_ removeLastObject]; NSUInteger c = [scenesStack_ count]; - + if( c == 0 ) [self end]; else { @@ -379,40 +413,43 @@ -(void) end runningScene_ = nil; nextScene_ = nil; - + // remove all objects, but don't release it. // runWithScene might be executed after 'end'. [scenesStack_ removeAllObjects]; - + [self stopAnimation]; - -#if CC_DIRECTOR_FAST_FPS + [FPSLabel_ release]; - FPSLabel_ = nil; -#endif + [SPFLabel_ release]; + [drawsLabel_ release]; + FPSLabel_ = nil, SPFLabel_=nil, drawsLabel_=nil; + + [delegate_ release]; + delegate_ = nil; - [projectionDelegate_ release]; - projectionDelegate_ = nil; + [self setView:nil]; // Purge bitmap cache [CCLabelBMFont purgeCachedData]; - // Purge all managers + // Purge all managers / caches [CCAnimationCache purgeSharedAnimationCache]; [CCSpriteFrameCache purgeSharedSpriteFrameCache]; - [CCScheduler purgeSharedScheduler]; - [CCActionManager purgeSharedManager]; [CCTextureCache purgeSharedTextureCache]; - - + [CCShaderCache purgeSharedShaderCache]; + // OpenGL view - + // Since the director doesn't attach the openglview to the window // it shouldn't remove it from the window too. // [openGLView_ removeFromSuperview]; - [openGLView_ release]; - openGLView_ = nil; + + // Invalidate GL state cache + ccGLInvalidateStateCache(); + + CHECK_GL_ERROR(); } -(void) setNextScene @@ -432,7 +469,7 @@ -(void) setNextScene } [runningScene_ release]; - + runningScene_ = [nextScene_ retain]; nextScene_ = nil; @@ -448,24 +485,30 @@ -(void) pause return; oldAnimationInterval_ = animationInterval_; - + // when paused, don't consume CPU [self setAnimationInterval:1/4.0]; + + [self willChangeValueForKey:@"isPaused"]; isPaused_ = YES; + [self didChangeValueForKey:@"isPaused"]; } -(void) resume { if( ! isPaused_ ) return; - + [self setAnimationInterval: oldAnimationInterval_]; if( gettimeofday( &lastUpdate_, NULL) != 0 ) { CCLOG(@"cocos2d: Director: Error in gettimeofday"); } - + + [self willChangeValueForKey:@"isPaused"]; isPaused_ = NO; + [self didChangeValueForKey:@"isPaused"]; + dt = 0; } @@ -484,73 +527,79 @@ - (void)setAnimationInterval:(NSTimeInterval)interval CCLOG(@"cocos2d: Director#setAnimationInterval. Override me"); } -#if CC_DIRECTOR_FAST_FPS -// display the FPS using a LabelAtlas -// updates the FPS every frame --(void) showFPS +// display statistics +-(void) showStats { frames_++; accumDt_ += dt; - - if ( accumDt_ > CC_DIRECTOR_FPS_INTERVAL) { - frameRate_ = frames_/accumDt_; - frames_ = 0; - accumDt_ = 0; - -// sprintf(format,"%.1f",frameRate); -// [FPSLabel setCString:format]; - NSString *str = [[NSString alloc] initWithFormat:@"%.1f", frameRate_]; - [FPSLabel_ setString:str]; - [str release]; + if( displayStats_ ) { + // Ms per Frame + + if( accumDt_ > CC_DIRECTOR_STATS_INTERVAL) + { + NSString *spfstr = [[NSString alloc] initWithFormat:@"%.3f", secondsPerFrame_]; + [SPFLabel_ setString:spfstr]; + [spfstr release]; + + frameRate_ = frames_/accumDt_; + frames_ = 0; + accumDt_ = 0; + +// sprintf(format,"%.1f",frameRate); +// [FPSLabel setCString:format]; + + NSString *fpsstr = [[NSString alloc] initWithFormat:@"%.1f", frameRate_]; + [FPSLabel_ setString:fpsstr]; + [fpsstr release]; + + NSString *draws = [[NSString alloc] initWithFormat:@"%4d", __ccNumberOfDraws]; + [drawsLabel_ setString:draws]; + [draws release]; + } + + [drawsLabel_ visit]; + [FPSLabel_ visit]; + [SPFLabel_ visit]; } - - [FPSLabel_ draw]; + + __ccNumberOfDraws = 0; } -#else -// display the FPS using a manually generated Texture (very slow) -// updates the FPS 3 times per second aprox. --(void) showFPS + +-(void) calculateMPF { - frames_++; - accumDt_ += dt; - - if ( accumDt_ > CC_DIRECTOR_FPS_INTERVAL) { - frameRate_ = frames_/accumDt_; - frames_ = 0; - accumDt_ = 0; - } - - NSString *str = [NSString stringWithFormat:@"%.2f",frameRate_]; - CCTexture2D *texture = [[CCTexture2D alloc] initWithString:str dimensions:CGSizeMake(100,30) alignment:UITextAlignmentLeft fontName:@"Arial" fontSize:24]; + struct timeval now; + gettimeofday( &now, NULL); - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: GL_COLOR_ARRAY - glDisableClientState(GL_COLOR_ARRAY); - - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - glColor4ub(224,224,244,200); - [texture drawAtPoint: ccp(5,2)]; - [texture release]; - - glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); - - // restore default GL state - glEnableClientState(GL_COLOR_ARRAY); + secondsPerFrame_ = (now.tv_sec - lastUpdate_.tv_sec) + (now.tv_usec - lastUpdate_.tv_usec) / 1000000.0f; } -#endif -- (void) showProfilers { -#if CC_ENABLE_PROFILERS - accumDtForProfiler_ += dt; - if (accumDtForProfiler_ > 1.0f) { - accumDtForProfiler_ = 0; - [[CCProfiler sharedProfiler] displayTimers]; +#pragma mark Director - Helper + +-(void) createStatsLabel +{ + if( FPSLabel_ && SPFLabel_ ) { + CCTexture2D *texture = [FPSLabel_ texture]; + + [FPSLabel_ release]; + [SPFLabel_ release]; + [[CCTextureCache sharedTextureCache ] removeTexture:texture]; + FPSLabel_ = nil; + SPFLabel_ = nil; } -#endif // CC_ENABLE_PROFILERS + + CCTexture2DPixelFormat currentFormat = [CCTexture2D defaultAlphaPixelFormat]; + [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA4444]; + FPSLabel_ = [[CCLabelAtlas alloc] initWithString:@"00.0" charMapFile:@"fps_images.png" itemWidth:12 itemHeight:32 startCharMap:'.']; + SPFLabel_ = [[CCLabelAtlas alloc] initWithString:@"0.000" charMapFile:@"fps_images.png" itemWidth:12 itemHeight:32 startCharMap:'.']; + drawsLabel_ = [[CCLabelAtlas alloc] initWithString:@"000" charMapFile:@"fps_images.png" itemWidth:12 itemHeight:32 startCharMap:'.']; + + [CCTexture2D setDefaultAlphaPixelFormat:currentFormat]; + + [drawsLabel_ setPosition: ccpAdd( ccp(0,34), CC_DIRECTOR_STATS_POSITION ) ]; + [SPFLabel_ setPosition: ccpAdd( ccp(0,17), CC_DIRECTOR_STATS_POSITION ) ]; + [FPSLabel_ setPosition: CC_DIRECTOR_STATS_POSITION ]; } @end diff --git a/Example/libs/cocos2d/CCDrawingPrimitives.h b/Example/libs/cocos2d/CCDrawingPrimitives.h index 1dbd9a5..2be4042 100644 --- a/Example/libs/cocos2d/CCDrawingPrimitives.h +++ b/Example/libs/cocos2d/CCDrawingPrimitives.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,18 +27,20 @@ #ifndef __CC_DRAWING_PRIMITIVES_H #define __CC_DRAWING_PRIMITIVES_H -#import #import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#import "ccTypes.h" +#import "ccMacros.h" + +#ifdef __CC_PLATFORM_IOS #import // for CGPoint #endif #ifdef __cplusplus extern "C" { -#endif - +#endif + /** @file Drawing OpenGL ES primitives. @@ -49,11 +52,11 @@ extern "C" { - ccDrawCubicBezier You can change the color, width and other property by calling the - glColor4ub(), glLineWitdh(), glPointSize(). - + glColor4ub(), glLineWidth(), glPointSize(). + @warning These functions draws the Line, Point, Polygon, immediately. They aren't batched. If you are going to make a game that depends on these primitives, I suggest creating a batch. */ - + /** draws a point given x and y coordinate measured in points. */ void ccDrawPoint( CGPoint point ); @@ -71,6 +74,10 @@ void ccDrawLine( CGPoint origin, CGPoint destination ); */ void ccDrawPoly( const CGPoint *vertices, NSUInteger numOfVertices, BOOL closePolygon ); +/** draws a filled polygon given a pointer to CGPoint coordiantes, the number of vertices measured in points, and a color. + */ +void ccDrawFilledPoly( const CGPoint *poli, NSUInteger numberOfPoints, ccColor4F color ); + /** draws a circle given the center, radius and number of segments measured in points */ void ccDrawCircle( CGPoint center, float radius, float angle, NSUInteger segments, BOOL drawLineToCenter); @@ -84,6 +91,22 @@ void ccDrawQuadBezier(CGPoint origin, CGPoint control, CGPoint destination, NSUI */ void ccDrawCubicBezier(CGPoint origin, CGPoint control1, CGPoint control2, CGPoint destination, NSUInteger segments); +/** set the drawing color with 4 unsigned bytes + @since v2.0 + */ +void ccDrawColor4B( GLubyte r, GLubyte g, GLubyte b, GLubyte a ); + +/** set the drawing color with 4 floats + @since v2.0 + */ +void ccDrawColor4F( GLfloat r, GLfloat g, GLfloat b, GLfloat a ); + +/** set the point size in points. Default 1. + @since v2.0 + */ +void ccPointSize( GLfloat pointSize ); + + #ifdef __cplusplus } #endif diff --git a/Example/libs/cocos2d/CCDrawingPrimitives.m b/Example/libs/cocos2d/CCDrawingPrimitives.m index 1e26a6f..5f70223 100644 --- a/Example/libs/cocos2d/CCDrawingPrimitives.m +++ b/Example/libs/cocos2d/CCDrawingPrimitives.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,245 +28,284 @@ #import #import "CCDrawingPrimitives.h" -#import "ccTypes.h" #import "ccMacros.h" #import "Platforms/CCGL.h" +#import "ccGLStateCache.h" +#import "CCShaderCache.h" +#import "CCGLProgram.h" +#import "Support/OpenGL_Internal.h" + + +static BOOL initialized = NO; +static CCGLProgram *shader_ = nil; +static int colorLocation_ = -1; +static ccColor4F color_ = {1,1,1,1}; +static int pointSizeLocation_ = -1; +static GLfloat pointSize_ = 1; + +static void lazy_init( void ) +{ + if( ! initialized ) { + + // + // Position and 1 color passed as a uniform (to similate glColor4ub ) + // + shader_ = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_Position_uColor]; + + colorLocation_ = glGetUniformLocation( shader_->program_, "u_color"); + pointSizeLocation_ = glGetUniformLocation( shader_->program_, "u_pointSize"); + + initialized = YES; + } + +} void ccDrawPoint( CGPoint point ) { - ccVertex2F p = (ccVertex2F) {point.x * CC_CONTENT_SCALE_FACTOR(), point.y * CC_CONTENT_SCALE_FACTOR() }; - - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_VERTEX_ARRAY, - // Unneeded states: GL_TEXTURE_2D, GL_TEXTURE_COORD_ARRAY, GL_COLOR_ARRAY - glDisable(GL_TEXTURE_2D); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisableClientState(GL_COLOR_ARRAY); - - glVertexPointer(2, GL_FLOAT, 0, &p); - glDrawArrays(GL_POINTS, 0, 1); + lazy_init(); + + ccVertex2F p = (ccVertex2F) {point.x, point.y}; + + ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position ); - // restore default state - glEnableClientState(GL_COLOR_ARRAY); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glEnable(GL_TEXTURE_2D); + [shader_ use]; + [shader_ setUniformForModelViewProjectionMatrix]; + + [shader_ setUniformLocation:colorLocation_ with4fv:(GLfloat*) &color_.r count:1]; + [shader_ setUniformLocation:pointSizeLocation_ withF1:pointSize_]; + + glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, &p); + + glDrawArrays(GL_POINTS, 0, 1); + + CC_INCREMENT_GL_DRAWS(1); } void ccDrawPoints( const CGPoint *points, NSUInteger numberOfPoints ) { - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_VERTEX_ARRAY, - // Unneeded states: GL_TEXTURE_2D, GL_TEXTURE_COORD_ARRAY, GL_COLOR_ARRAY - glDisable(GL_TEXTURE_2D); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisableClientState(GL_COLOR_ARRAY); + lazy_init(); - ccVertex2F newPoints[numberOfPoints]; + ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position ); - // iPhone and 32-bit machines optimization - if( sizeof(CGPoint) == sizeof(ccVertex2F) ) { + [shader_ use]; + [shader_ setUniformForModelViewProjectionMatrix]; + [shader_ setUniformLocation:colorLocation_ with4fv:(GLfloat*) &color_.r count:1]; + [shader_ setUniformLocation:pointSizeLocation_ withF1:pointSize_]; - // points ? - if( CC_CONTENT_SCALE_FACTOR() != 1 ) { - for( NSUInteger i=0; i - #import "ccMacros.h" #import "CCGrid.h" #import "CCTexture2D.h" #import "CCDirector.h" #import "CCGrabber.h" +#import "CCGLProgram.h" +#import "CCShaderCache.h" +#import "ccGLStateCache.h" #import "Platforms/CCGL.h" #import "Support/CGPointExtension.h" #import "Support/ccUtils.h" +#import "Support/TransformUtils.h" +#import "Support/OpenGL_Internal.h" + +#import "kazmath/kazmath.h" +#import "kazmath/GL/matrix.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import "Platforms/iOS/CCDirectorIOS.h" -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_IOS #pragma mark - #pragma mark CCGridBase @@ -50,6 +56,7 @@ @implementation CCGridBase @synthesize grabber = grabber_; @synthesize gridSize = gridSize_; @synthesize step = step_; +@synthesize shaderProgram = shaderProgram_; +(id) gridWithSize:(ccGridSize)gridSize texture:(CCTexture2D*)texture flippedTexture:(BOOL)flipped { @@ -64,21 +71,23 @@ +(id) gridWithSize:(ccGridSize)gridSize -(id) initWithSize:(ccGridSize)gridSize texture:(CCTexture2D*)texture flippedTexture:(BOOL)flipped { if( (self=[super init]) ) { - + active_ = NO; reuseGrid_ = 0; gridSize_ = gridSize; self.texture = texture; isTextureFlipped_ = flipped; - - CGSize texSize = [texture_ contentSizeInPixels]; + + CGSize texSize = [texture_ contentSize]; step_.x = texSize.width / gridSize_.x; step_.y = texSize.height / gridSize_.y; - + grabber_ = [[CCGrabber alloc] init]; [grabber_ grab:texture_]; - + + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTexture]; + [self calculateVertexPoints]; } return self; @@ -88,26 +97,29 @@ -(id)initWithSize:(ccGridSize)gSize { CCDirector *director = [CCDirector sharedDirector]; CGSize s = [director winSizeInPixels]; - - unsigned int POTWide = ccNextPOT(s.width); - unsigned int POTHigh = ccNextPOT(s.height); - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - EAGLView *glview = [[CCDirector sharedDirector] openGLView]; + + + unsigned long POTWide = ccNextPOT(s.width); + unsigned long POTHigh = ccNextPOT(s.height); + +#ifdef __CC_PLATFORM_IOS + CCGLView *glview = (CCGLView*)[[CCDirector sharedDirector] view]; NSString *pixelFormat = [glview pixelFormat]; CCTexture2DPixelFormat format = [pixelFormat isEqualToString: kEAGLColorFormatRGB565] ? kCCTexture2DPixelFormat_RGB565 : kCCTexture2DPixelFormat_RGBA8888; -#else +#elif defined(__CC_PLATFORM_MAC) CCTexture2DPixelFormat format = kCCTexture2DPixelFormat_RGBA8888; #endif - - void *data = calloc((int)(POTWide * POTHigh * 4), 1); + + int bpp = ( format == kCCTexture2DPixelFormat_RGB565 ? 2 : 4 ); + + void *data = calloc((size_t)(POTWide * POTHigh * bpp), 1); if( ! data ) { CCLOG(@"cocos2d: CCGrid: not enough memory"); [self release]; return nil; } - + CCTexture2D *texture = [[CCTexture2D alloc] initWithData:data pixelFormat:format pixelsWide:POTWide pixelsHigh:POTHigh contentSize:s]; free( data ); @@ -116,11 +128,11 @@ -(id)initWithSize:(ccGridSize)gSize [self release]; return nil; } - + self = [self initWithSize:gSize texture:texture flippedTexture:NO]; - + [texture release]; - + return self; } - (NSString*) description @@ -132,7 +144,7 @@ - (void) dealloc { CCLOGINFO(@"cocos2d: deallocing %@", self); - [self setActive: NO]; +// [self setActive: NO]; [texture_ release]; [grabber_ release]; @@ -168,104 +180,68 @@ -(void) setIsTextureFlipped:(BOOL)flipped } } -// This routine can be merged with Director -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED --(void)applyLandscape -{ +-(void)set2DProjection +{ CCDirector *director = [CCDirector sharedDirector]; - - CGSize winSize = [director displaySizeInPixels]; - float w = winSize.width / 2; - float h = winSize.height / 2; - - ccDeviceOrientation orientation = [director deviceOrientation]; - - switch (orientation) { - case CCDeviceOrientationLandscapeLeft: - glTranslatef(w,h,0); - glRotatef(-90,0,0,1); - glTranslatef(-h,-w,0); - break; - case CCDeviceOrientationLandscapeRight: - glTranslatef(w,h,0); - glRotatef(90,0,0,1); - glTranslatef(-h,-w,0); - break; - case CCDeviceOrientationPortraitUpsideDown: - glTranslatef(w,h,0); - glRotatef(180,0,0,1); - glTranslatef(-w,-h,0); - break; - default: - break; - } -} -#endif --(void)set2DProjection -{ - CGSize winSize = [[CCDirector sharedDirector] winSizeInPixels]; + CGSize size = [director winSizeInPixels]; - glLoadIdentity(); - glViewport(0, 0, winSize.width, winSize.height); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - ccglOrtho(0, winSize.width, 0, winSize.height, -1024, 1024); - glMatrixMode(GL_MODELVIEW); -} - -// This routine can be merged with Director --(void)set3DProjection -{ - CCDirector *director = [CCDirector sharedDirector]; + glViewport(0, 0, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); + kmGLMatrixMode(KM_GL_PROJECTION); + kmGLLoadIdentity(); - CGSize winSize = [director displaySizeInPixels]; + kmMat4 orthoMatrix; + kmMat4OrthographicProjection(&orthoMatrix, 0, size.width * CC_CONTENT_SCALE_FACTOR(), 0, size.height * CC_CONTENT_SCALE_FACTOR(), -1, 1); + kmGLMultMatrix( &orthoMatrix ); - glViewport(0, 0, winSize.width, winSize.height); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - gluPerspective(60, (GLfloat)winSize.width/winSize.height, 0.5f, 1500.0f); + kmGLMatrixMode(KM_GL_MODELVIEW); + kmGLLoadIdentity(); + - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - gluLookAt( winSize.width/2, winSize.height/2, [director getZEye], - winSize.width/2, winSize.height/2, 0, - 0.0f, 1.0f, 0.0f - ); + ccSetProjectionMatrixDirty(); } -(void)beforeDraw { + // save projection + CCDirector *director = [CCDirector sharedDirector]; + directorProjection_ = [director projection]; + + // 2d projection +// [director setProjection:kCCDirectorProjection2D]; [self set2DProjection]; + + [grabber_ beforeRender:texture_]; } + -(void)afterDraw:(CCNode *)target { [grabber_ afterRender:texture_]; - - [self set3DProjection]; -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - [self applyLandscape]; -#endif + + // restore projection + CCDirector *director = [CCDirector sharedDirector]; + [director setProjection: directorProjection_]; if( target.camera.dirty ) { - CGPoint offset = [target anchorPointInPixels]; + CGPoint offset = [target anchorPointInPoints]; // // XXX: Camera should be applied in the AnchorPoint // - ccglTranslate(offset.x, offset.y, 0); + kmGLTranslatef(offset.x, offset.y, 0); [target.camera locate]; - ccglTranslate(-offset.x, -offset.y, 0); + kmGLTranslatef(-offset.x, -offset.y, 0); } - - glBindTexture(GL_TEXTURE_2D, texture_.name); + + ccGLBindTexture2D( texture_.name ); [self blit]; } + -(void)blit { [NSException raise:@"GridBase" format:@"Abstract class needs implementation"]; @@ -300,19 +276,25 @@ -(void)dealloc -(void)blit { - int n = gridSize_.x * gridSize_.y; - - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: GL_COLOR_ARRAY - glDisableClientState(GL_COLOR_ARRAY); - - glVertexPointer(3, GL_FLOAT, 0, vertices); - glTexCoordPointer(2, GL_FLOAT, 0, texCoordinates); - glDrawElements(GL_TRIANGLES, n*6, GL_UNSIGNED_SHORT, indices); + NSInteger n = gridSize_.x * gridSize_.y; + + ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords ); + [shaderProgram_ use]; + [shaderProgram_ setUniformForModelViewProjectionMatrix]; + + // + // Attributes + // + + // position + glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, vertices); + + // texCoods + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, texCoordinates); + + glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, indices); - // restore GL default state - glEnableClientState(GL_COLOR_ARRAY); + CC_INCREMENT_GL_DRAWS(1); } -(void)calculateVertexPoints @@ -320,55 +302,62 @@ -(void)calculateVertexPoints float width = (float)texture_.pixelsWide; float height = (float)texture_.pixelsHigh; float imageH = texture_.contentSizeInPixels.height; - + int x, y, i; + + if (vertices) free(vertices); + if (originalVertices) free(originalVertices); + if (texCoordinates) free(texCoordinates); + if (indices) free(indices); - vertices = malloc((gridSize_.x+1)*(gridSize_.y+1)*sizeof(ccVertex3F)); - originalVertices = malloc((gridSize_.x+1)*(gridSize_.y+1)*sizeof(ccVertex3F)); - texCoordinates = malloc((gridSize_.x+1)*(gridSize_.y+1)*sizeof(CGPoint)); - indices = malloc(gridSize_.x*gridSize_.y*sizeof(GLushort)*6); + NSUInteger numOfPoints = (gridSize_.x+1) * (gridSize_.y+1); - float *vertArray = (float*)vertices; - float *texArray = (float*)texCoordinates; + vertices = malloc(numOfPoints * sizeof(ccVertex3F)); + originalVertices = malloc(numOfPoints * sizeof(ccVertex3F)); + texCoordinates = malloc(numOfPoints * sizeof(ccVertex2F)); + indices = malloc( (gridSize_.x * gridSize_.y) * sizeof(GLushort)*6); + + GLfloat *vertArray = (GLfloat*)vertices; + GLfloat *texArray = (GLfloat*)texCoordinates; GLushort *idxArray = (GLushort *)indices; - + for( x = 0; x < gridSize_.x; x++ ) { for( y = 0; y < gridSize_.y; y++ ) { - int idx = (y * gridSize_.x) + x; - - float x1 = x * step_.x; - float x2 = x1 + step_.x; - float y1 = y * step_.y; - float y2 = y1 + step_.y; - + NSInteger idx = (y * gridSize_.x) + x; + + GLfloat x1 = x * step_.x; + GLfloat x2 = x1 + step_.x; + GLfloat y1 = y * step_.y; + GLfloat y2 = y1 + step_.y; + GLushort a = x * (gridSize_.y+1) + y; GLushort b = (x+1) * (gridSize_.y+1) + y; GLushort c = (x+1) * (gridSize_.y+1) + (y+1); GLushort d = x * (gridSize_.y+1) + (y+1); - + GLushort tempidx[6] = { a, b, d, b, c, d }; - + memcpy(&idxArray[6*idx], tempidx, 6*sizeof(GLushort)); - + int l1[4] = { a*3, b*3, c*3, d*3 }; ccVertex3F e = {x1,y1,0}; ccVertex3F f = {x2,y1,0}; ccVertex3F g = {x2,y2,0}; ccVertex3F h = {x1,y2,0}; - + ccVertex3F l2[4] = { e, f, g, h }; - + int tex1[4] = { a*2, b*2, c*2, d*2 }; CGPoint tex2[4] = { ccp(x1, y1), ccp(x2, y1), ccp(x2, y2), ccp(x1, y2) }; - + for( i = 0; i < 4; i++ ) { vertArray[ l1[i] ] = l2[i].x; vertArray[ l1[i] + 1 ] = l2[i].y; vertArray[ l1[i] + 2 ] = l2[i].z; - + texArray[ tex1[i] ] = tex2[i].x / width; if( isTextureFlipped_ ) texArray[ tex1[i] + 1 ] = (imageH - tex2[i].y) / height; @@ -377,33 +366,33 @@ -(void)calculateVertexPoints } } } - + memcpy(originalVertices, vertices, (gridSize_.x+1)*(gridSize_.y+1)*sizeof(ccVertex3F)); } -(ccVertex3F)vertex:(ccGridSize)pos { - int index = (pos.x * (gridSize_.y+1) + pos.y) * 3; + NSInteger index = (pos.x * (gridSize_.y+1) + pos.y) * 3; float *vertArray = (float *)vertices; - + ccVertex3F vert = { vertArray[index], vertArray[index+1], vertArray[index+2] }; - + return vert; } -(ccVertex3F)originalVertex:(ccGridSize)pos { - int index = (pos.x * (gridSize_.y+1) + pos.y) * 3; + NSInteger index = (pos.x * (gridSize_.y+1) + pos.y) * 3; float *vertArray = (float *)originalVertices; - + ccVertex3F vert = { vertArray[index], vertArray[index+1], vertArray[index+2] }; - + return vert; } -(void)setVertex:(ccGridSize)pos vertex:(ccVertex3F)vertex { - int index = (pos.x * (gridSize_.y+1) + pos.y) * 3; + NSInteger index = (pos.x * (gridSize_.y+1) + pos.y) * 3; float *vertArray = (float *)vertices; vertArray[index] = vertex.x; vertArray[index+1] = vertex.y; @@ -439,19 +428,26 @@ -(void)dealloc -(void)blit { - int n = gridSize_.x * gridSize_.y; - - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: GL_COLOR_ARRAY - glDisableClientState(GL_COLOR_ARRAY); - - glVertexPointer(3, GL_FLOAT, 0, vertices); - glTexCoordPointer(2, GL_FLOAT, 0, texCoordinates); - glDrawElements(GL_TRIANGLES, n*6, GL_UNSIGNED_SHORT, indices); + NSInteger n = gridSize_.x * gridSize_.y; + + [shaderProgram_ use]; + [shaderProgram_ setUniformForModelViewProjectionMatrix]; + + + // + // Attributes + // + ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords ); + + // position + glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, vertices); + + // texCoods + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, texCoordinates); - // restore default GL state - glEnableClientState(GL_COLOR_ARRAY); + glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, indices); + + CC_INCREMENT_GL_DRAWS(1); } -(void)calculateVertexPoints @@ -459,20 +455,25 @@ -(void)calculateVertexPoints float width = (float)texture_.pixelsWide; float height = (float)texture_.pixelsHigh; float imageH = texture_.contentSizeInPixels.height; - - int numQuads = gridSize_.x * gridSize_.y; - - vertices = malloc(numQuads*12*sizeof(GLfloat)); - originalVertices = malloc(numQuads*12*sizeof(GLfloat)); - texCoordinates = malloc(numQuads*8*sizeof(GLfloat)); + + NSInteger numQuads = gridSize_.x * gridSize_.y; + + if (vertices) free(vertices); + if (originalVertices) free(originalVertices); + if (texCoordinates) free(texCoordinates); + if (indices) free(indices); + + vertices = malloc(numQuads*4*sizeof(ccVertex3F)); + originalVertices = malloc(numQuads*4*sizeof(ccVertex3F)); + texCoordinates = malloc(numQuads*4*sizeof(ccVertex2F)); indices = malloc(numQuads*6*sizeof(GLushort)); - - float *vertArray = (float*)vertices; - float *texArray = (float*)texCoordinates; + + GLfloat *vertArray = (GLfloat*)vertices; + GLfloat *texArray = (GLfloat*)texCoordinates; GLushort *idxArray = (GLushort *)indices; - + int x, y; - + for( x = 0; x < gridSize_.x; x++ ) { for( y = 0; y < gridSize_.y; y++ ) @@ -481,7 +482,7 @@ -(void)calculateVertexPoints float x2 = x1 + step_.x; float y1 = y * step_.y; float y2 = y1 + step_.y; - + *vertArray++ = x1; *vertArray++ = y1; *vertArray++ = 0; @@ -494,10 +495,10 @@ -(void)calculateVertexPoints *vertArray++ = x2; *vertArray++ = y2; *vertArray++ = 0; - + float newY1 = y1; float newY2 = y2; - + if( isTextureFlipped_ ) { newY1 = imageH - y1; newY2 = imageH - y2; @@ -513,47 +514,47 @@ -(void)calculateVertexPoints *texArray++ = newY2 / height; } } - + for( x = 0; x < numQuads; x++) { idxArray[x*6+0] = x*4+0; idxArray[x*6+1] = x*4+1; idxArray[x*6+2] = x*4+2; - + idxArray[x*6+3] = x*4+1; idxArray[x*6+4] = x*4+2; idxArray[x*6+5] = x*4+3; } - + memcpy(originalVertices, vertices, numQuads*12*sizeof(GLfloat)); } -(void)setTile:(ccGridSize)pos coords:(ccQuad3)coords { - int idx = (gridSize_.y * pos.x + pos.y) * 4 * 3; + NSInteger idx = (gridSize_.y * pos.x + pos.y) * 4 * 3; float *vertArray = (float*)vertices; memcpy(&vertArray[idx], &coords, sizeof(ccQuad3)); } -(ccQuad3)originalTile:(ccGridSize)pos { - int idx = (gridSize_.y * pos.x + pos.y) * 4 * 3; + NSInteger idx = (gridSize_.y * pos.x + pos.y) * 4 * 3; float *vertArray = (float*)originalVertices; - + ccQuad3 ret; memcpy(&ret, &vertArray[idx], sizeof(ccQuad3)); - + return ret; } -(ccQuad3)tile:(ccGridSize)pos { - int idx = (gridSize_.y * pos.x + pos.y) * 4 * 3; + NSInteger idx = (gridSize_.y * pos.x + pos.y) * 4 * 3; float *vertArray = (float*)vertices; - + ccQuad3 ret; memcpy(&ret, &vertArray[idx], sizeof(ccQuad3)); - + return ret; } @@ -561,8 +562,8 @@ -(void)reuse { if ( reuseGrid_ > 0 ) { - int numQuads = gridSize_.x * gridSize_.y; - + NSInteger numQuads = gridSize_.x * gridSize_.y; + memcpy(originalVertices, vertices, numQuads*12*sizeof(GLfloat)); reuseGrid_--; } diff --git a/Example/libs/cocos2d/CCLabelAtlas.h b/Example/libs/cocos2d/CCLabelAtlas.h index d30fb38..63f1c15 100644 --- a/Example/libs/cocos2d/CCLabelAtlas.h +++ b/Example/libs/cocos2d/CCLabelAtlas.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,34 +29,29 @@ #import "CCTextureAtlas.h" /** CCLabelAtlas is a subclass of CCAtlasNode. - + It can be as a replacement of CCLabel since it is MUCH faster. - + CCLabelAtlas versus CCLabel: - CCLabelAtlas is MUCH faster than CCLabel - CCLabelAtlas "characters" have a fixed height and width - CCLabelAtlas "characters" can be anything you want since they are taken from an image file - - A more flexible class is CCBitmapFontAtlas. It supports variable width characters and it also has a nice editor. + + A more flexible class is CCLabelBMFont. It supports variable width characters and it also has a nice editor. */ @interface CCLabelAtlas : CCAtlasNode -{ +{ // string to render NSString *string_; - + // the first char in the charmap - char mapStartChar; + unsigned char mapStartChar_; } /** creates the CCLabelAtlas with a string, a char map file(the atlas), the width and height of each element in points and the starting char of the atlas */ -+(id) labelWithString:(NSString*) string charMapFile: (NSString*) charmapfile itemWidth:(int)w itemHeight:(int)h startCharMap:(char)c; - -/** creates the CCLabelAtlas with a string, a char map file(the atlas), the width and height of each element in points and the starting char of the atlas. - @deprecated Will be removed in 1.0.1. Use "labelWithString:" instead - */ -+(id) labelAtlasWithString:(NSString*) string charMapFile: (NSString*) charmapfile itemWidth:(int)w itemHeight:(int)h startCharMap:(char)c DEPRECATED_ATTRIBUTE; ++(id) labelWithString:(NSString*) string charMapFile: (NSString*) charmapfile itemWidth:(NSUInteger)w itemHeight:(NSUInteger)h startCharMap:(unsigned char)c; /** initializes the CCLabelAtlas with a string, a char map file(the atlas), the width and height in points of each element and the starting char of the atlas */ --(id) initWithString:(NSString*) string charMapFile: (NSString*) charmapfile itemWidth:(int)w itemHeight:(int)h startCharMap:(char)c; +-(id) initWithString:(NSString*) string charMapFile: (NSString*) charmapfile itemWidth:(NSUInteger)w itemHeight:(NSUInteger)h startCharMap:(unsigned char)c; @end diff --git a/Example/libs/cocos2d/CCLabelAtlas.m b/Example/libs/cocos2d/CCLabelAtlas.m index 98ba04e..e16ebde 100644 --- a/Example/libs/cocos2d/CCLabelAtlas.m +++ b/Example/libs/cocos2d/CCLabelAtlas.m @@ -1,18 +1,19 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2008-2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,31 +29,30 @@ #import "ccMacros.h" #import "CCDrawingPrimitives.h" #import "CCLabelAtlas.h" +#import "CCShaderCache.h" +#import "CCGLProgram.h" +#import "ccGLStateCache.h" +#import "CCDirector.h" #import "Support/CGPointExtension.h" +#import "Support/TransformUtils.h" - +// external +#import "kazmath/GL/matrix.h" @implementation CCLabelAtlas #pragma mark CCLabelAtlas - Creation & Init -+(id) labelWithString:(NSString*)string charMapFile:(NSString*)charmapfile itemWidth:(int)w itemHeight:(int)h startCharMap:(char)c ++(id) labelWithString:(NSString*)string charMapFile:(NSString*)charmapfile itemWidth:(NSUInteger)w itemHeight:(NSUInteger)h startCharMap:(unsigned char)c { return [[[self alloc] initWithString:string charMapFile:charmapfile itemWidth:w itemHeight:h startCharMap:c] autorelease]; } -// XXX DEPRECATED. Remove it in 1.0.1 -+(id) labelAtlasWithString:(NSString*) string charMapFile: (NSString*) charmapfile itemWidth:(int)w itemHeight:(int)h startCharMap:(char)c -{ - return [self labelWithString:string charMapFile:charmapfile itemWidth:w itemHeight:h startCharMap:c]; -} - - --(id) initWithString:(NSString*) theString charMapFile: (NSString*) charmapfile itemWidth:(int)w itemHeight:(int)h startCharMap:(char)c +-(id) initWithString:(NSString*) theString charMapFile: (NSString*) charmapfile itemWidth:(NSUInteger)w itemHeight:(NSUInteger)h startCharMap:(unsigned char)c { if ((self=[super initWithTileFile:charmapfile tileWidth:w tileHeight:h itemsToRender:[theString length] ]) ) { - mapStartChar = c; + mapStartChar_ = c; [self setString: theString]; } @@ -70,34 +70,38 @@ -(void) dealloc -(void) updateAtlasValues { - int n = [string_ length]; - + NSUInteger n = [string_ length]; + ccV3F_C4B_T2F_Quad quad; - const char *s = [string_ UTF8String]; + const unsigned char *s = (unsigned char*) [string_ UTF8String]; CCTexture2D *texture = [textureAtlas_ texture]; float textureWide = [texture pixelsWide]; float textureHigh = [texture pixelsHigh]; + float itemWidthInPixels = itemWidth_ * CC_CONTENT_SCALE_FACTOR(); + float itemHeightInPixels = itemHeight_ * CC_CONTENT_SCALE_FACTOR(); - for( NSUInteger i=0; i textureAtlas_.totalQuads ) - [textureAtlas_ resizeCapacity: newString.length]; + if( newString == string_ ) + return; - [string_ release]; - string_ = [newString copy]; - [self updateAtlasValues]; + if( [newString hash] != [string_ hash] ) { + + NSUInteger len = [newString length]; + if( len > textureAtlas_.capacity ) + [textureAtlas_ resizeCapacity:len]; + + [string_ release]; + string_ = [newString copy]; + [self updateAtlasValues]; + + CGSize s = CGSizeMake(len * itemWidth_, itemHeight_); + [self setContentSize:s]; - CGSize s; - s.width = [string_ length] * itemWidth_; - s.height = itemHeight_; - [self setContentSizeInPixels:s]; + self.quadsToDraw = len; + } } -(NSString*) string @@ -146,44 +162,20 @@ -(NSString*) string return string_; } -#pragma mark CCLabelAtlas - draw +#pragma mark CCLabelAtlas - DebugDraw -// XXX: overriding draw from AtlasNode +#if CC_LABELATLAS_DEBUG_DRAW - (void) draw { - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: GL_COLOR_ARRAY - glDisableClientState(GL_COLOR_ARRAY); - - glColor4ub( color_.r, color_.g, color_.b, opacity_); - - BOOL newBlend = blendFunc_.src != CC_BLEND_SRC || blendFunc_.dst != CC_BLEND_DST; - if( newBlend ) - glBlendFunc( blendFunc_.src, blendFunc_.dst ); - - [textureAtlas_ drawNumberOfQuads: string_.length]; - - if( newBlend ) - glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); - - // is this chepear than saving/restoring color state ? - // XXX: There is no need to restore the color to (255,255,255,255). Objects should use the color - // XXX: that they need -// glColor4ub( 255, 255, 255, 255); - - // Restore Default GL state. Enable GL_COLOR_ARRAY - glEnableClientState(GL_COLOR_ARRAY); - - -#if CC_LABELATLAS_DEBUG_DRAW + [super draw]; + CGSize s = [self contentSize]; CGPoint vertices[4]={ ccp(0,0),ccp(s.width,0), ccp(s.width,s.height),ccp(0,s.height), }; ccDrawPoly(vertices, 4, YES); +} #endif // CC_LABELATLAS_DEBUG_DRAW -} @end diff --git a/Example/libs/cocos2d/CCLabelBMFont.h b/Example/libs/cocos2d/CCLabelBMFont.h index 38b32dc..0aaea60 100644 --- a/Example/libs/cocos2d/CCLabelBMFont.h +++ b/Example/libs/cocos2d/CCLabelBMFont.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,17 +25,21 @@ * Portions of this code are based and inspired on: * http://www.71squared.co.uk/2009/04/iphone-game-programming-tutorial-4-bitmap-font-class * by Michael Daley - - * Use any of these editors to generate bitmap font atlas: - * http://www.n4te.com/hiero/hiero.jnlp - * http://slick.cokeandcode.com/demos/hiero.jnlp - * http://www.angelcode.com/products/bmfont/ * + * Use any of these editors to generate BMFonts: + * http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) + * http://www.n4te.com/hiero/hiero.jnlp (Free, Java) + * http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) + * http://www.angelcode.com/products/bmfont/ (Free, Windows only) */ #import "CCSpriteBatchNode.h" #import "Support/uthash.h" +enum { + kCCLabelAutomaticWidth = -1, +}; + struct _KerningHashElement; /** @struct ccBMFontDef @@ -42,15 +47,15 @@ struct _KerningHashElement; */ typedef struct _BMFontDef { //! ID of the character - unsigned int charID; + unichar charID; //! origin and size of the font CGRect rect; //! The X amount the image should be offset when drawing the image (in pixels) - int xOffset; + short xOffset; //! The Y amount the image should be offset when drawing the image (in pixels) - int yOffset; + short yOffset; //! The amount to move the current position after drawing the character (in pixels) - int xAdvance; + short xAdvance; } ccBMFontDef; /** @struct ccBMFontPadding @@ -68,27 +73,24 @@ typedef struct _BMFontPadding { int bottom; } ccBMFontPadding; -enum { - // how many characters are supported - kCCBMFontMaxChars = 2048, //256, -}; /** CCBMFontConfiguration has parsed configuration of the the .fnt file @since v0.8 */ @interface CCBMFontConfiguration : NSObject { -// XXX: Creating a public interface so that the bitmapFontArray[] is accesible + // XXX: Creating a public interface so that the bitmapFontArray[] is accesible @public - // The characters building up the font - ccBMFontDef BMFontArray_[kCCBMFontMaxChars]; - + + // BMFont definitions + struct _FontDefHashElement *fontDefDictionary_; + // FNTConfig: Common Height NSUInteger commonHeight_; - + // Padding ccBMFontPadding padding_; - + // atlas name NSString *atlasName_; @@ -104,31 +106,33 @@ enum { /** CCLabelBMFont is a subclass of CCSpriteBatchNode - + Features: - Treats each character like a CCSprite. This means that each individual character can be: - - rotated - - scaled - - translated - - tinted - - chage the opacity + - rotated + - scaled + - translated + - tinted + - chage the opacity - It can be used as part of a menu item. - anchorPoint can be used to align the "label" - Supports AngelCode text format - + Limitations: - - All inner characters are using an anchorPoint of (0.5f, 0.5f) and it is not recommend to change it - because it might affect the rendering - + - All inner characters are using an anchorPoint of (0.5f, 0.5f) and it is not recommend to change it + because it might affect the rendering + CCLabelBMFont implements the protocol CCLabelProtocol, like CCLabel and CCLabelAtlas. CCLabelBMFont has the flexibility of CCLabel, the speed of CCLabelAtlas and all the features of CCSprite. If in doubt, use CCLabelBMFont instead of CCLabelAtlas / CCLabel. - + Supported editors: - - http://www.n4te.com/hiero/hiero.jnlp - - http://slick.cokeandcode.com/demos/hiero.jnlp - - http://www.angelcode.com/products/bmfont/ - + - http://glyphdesigner.71squared.com/ + - http://www.bmglyph.com/ + - http://www.n4te.com/hiero/hiero.jnlp + - http://slick.cokeandcode.com/demos/hiero.jnlp + - http://www.angelcode.com/products/bmfont/ + @since v0.8 */ @@ -136,13 +140,26 @@ enum { { // string to render NSString *string_; - + + // name of fntFile + NSString *fntFile_; + + // initial string without line breaks + NSString *initialString_; + // max width until a line break is added + float width_; + // alignment of all lines + CCTextAlignment alignment_; + CCBMFontConfiguration *configuration_; // texture RGBA GLubyte opacity_; ccColor3B color_; BOOL opacityModifyRGB_; + + // offset of the texture atlas + CGPoint imageOffset_; } /** Purges the cached data. @@ -151,39 +168,46 @@ enum { */ +(void) purgeCachedData; +/** alignment used for the label */ +@property (nonatomic,assign,readonly) CCTextAlignment alignment; +/** fntFile used for the font */ +@property (nonatomic,retain) NSString* fntFile; /** conforms to CCRGBAProtocol protocol */ @property (nonatomic,readwrite) GLubyte opacity; /** conforms to CCRGBAProtocol protocol */ @property (nonatomic,readwrite) ccColor3B color; -/** creates a BMFont label with an initial string and the FNT file */ +/** creates a BMFont label with an initial string and the FNT file. */ +(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile; - -/** creates a BMFont label with an initial string and the FNT file - @deprecated Will be removed in 1.0.1. Use "labelWithString" instead. - */ -+(id) bitmapFontAtlasWithString:(NSString*)string fntFile:(NSString*)fntFile DEPRECATED_ATTRIBUTE; +/** creates a BMFont label with an initial string, the FNT file, width, and alignment option */ ++(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment; +/** creates a BMFont label with an initial string, the FNT file, width, alignment option and the offset of where the glpyhs start on the .PNG image */ ++(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment imageOffset:(CGPoint)offset; /** init a BMFont label with an initial string and the FNT file */ -(id) initWithString:(NSString*)string fntFile:(NSString*)fntFile; +/** init a BMFont label with an initial string and the FNT file, width, and alignment option*/ +-(id) initWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment; +/** init a BMFont label with an initial string and the FNT file, width, alignment option and the offset of where the glyphs start on the .PNG image */ +-(id) initWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment imageOffset:(CGPoint)offset; /** updates the font chars based on the string to render */ -(void) createFontChars; + +/** set label width */ +- (void)setWidth:(float)width; + +/** set label alignment */ +- (void)setAlignment:(CCTextAlignment)alignment; + @end /** Free function that parses a FNT file a place it on the cache -*/ + */ CCBMFontConfiguration * FNTConfigLoadFile( NSString *file ); /** Purges the FNT config cache */ void FNTConfigRemoveCache( void ); - -/** CCBitmapFontAtlas - @deprecated Use CCLabelBMFont instead. Will be removed 1.0.1 - */ -DEPRECATED_ATTRIBUTE @interface CCBitmapFontAtlas : CCLabelBMFont -@end - diff --git a/Example/libs/cocos2d/CCLabelBMFont.m b/Example/libs/cocos2d/CCLabelBMFont.m index 67e168e..a91e4e3 100644 --- a/Example/libs/cocos2d/CCLabelBMFont.m +++ b/Example/libs/cocos2d/CCLabelBMFont.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,17 +27,20 @@ * by Michael Daley * * - * Use any of these editors to generate bitmap font atlas: - * http://www.n4te.com/hiero/hiero.jnlp - * http://slick.cokeandcode.com/demos/hiero.jnlp - * http://www.angelcode.com/products/bmfont/ + * Use any of these editors to generate BMFonts: + * http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) + * http://www.n4te.com/hiero/hiero.jnlp (Free, Java) + * http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) + * http://www.angelcode.com/products/bmfont/ (Free, Windows only) */ #import "ccConfig.h" +#import "ccMacros.h" #import "CCLabelBMFont.h" #import "CCSprite.h" #import "CCDrawingPrimitives.h" #import "CCConfiguration.h" +#import "CCTextureCache.h" #import "Support/CCFileUtils.h" #import "Support/CGPointExtension.h" #import "Support/uthash.h" @@ -48,16 +52,16 @@ CCBMFontConfiguration* FNTConfigLoadFile( NSString *fntFile) { CCBMFontConfiguration *ret = nil; - + if( configurations == nil ) configurations = [[NSMutableDictionary dictionaryWithCapacity:3] retain]; - + ret = [configurations objectForKey:fntFile]; if( ret == nil ) { ret = [CCBMFontConfiguration configurationWithFNTFile:fntFile]; [configurations setObject:ret forKey:fntFile]; } - + return ret; } @@ -70,17 +74,25 @@ void FNTConfigRemoveCache( void ) // Equal function for targetSet. typedef struct _KerningHashElement -{ +{ int key; // key for the hash. 16-bit for 1st element, 16-bit for 2nd element int amount; UT_hash_handle hh; } tKerningHashElement; + #pragma mark - #pragma mark BitmapFontConfiguration +typedef struct _FontDefHashElement +{ + NSUInteger key; // key. Font Unicode value + ccBMFontDef fontDef; // font definition + UT_hash_handle hh; +} tFontDefHashElement; -@interface CCBMFontConfiguration (Private) + +@interface CCBMFontConfiguration () -(void) parseConfigFile:(NSString*)controlFile; -(void) parseCharacterDefinition:(NSString*)line charDef:(ccBMFontDef*)characterDefinition; -(void) parseInfoArguments:(NSString*)line; @@ -89,8 +101,12 @@ -(void) parseImageFileName:(NSString*)line fntFile:(NSString*)fntFile; -(void) parseKerningCapacity:(NSString*)line; -(void) parseKerningEntry:(NSString*)line; -(void) purgeKerningDictionary; +-(void) purgeFontDefDictionary; @end +#pragma mark - +#pragma mark CCBMFontConfiguration + @implementation CCBMFontConfiguration +(id) configurationWithFNTFile:(NSString*)FNTfile @@ -101,8 +117,9 @@ +(id) configurationWithFNTFile:(NSString*)FNTfile -(id) initWithFNTfile:(NSString*)fntFile { if((self=[super init])) { - + kerningDictionary_ = NULL; + fontDefDictionary_ = NULL; [self parseConfigFile:fntFile]; } @@ -112,6 +129,7 @@ -(id) initWithFNTfile:(NSString*)fntFile - (void) dealloc { CCLOGINFO( @"cocos2d: deallocing %@", self); + [self purgeFontDefDictionary]; [self purgeKerningDictionary]; [atlasName_ release]; [super dealloc]; @@ -119,45 +137,59 @@ - (void) dealloc - (NSString*) description { - return [NSString stringWithFormat:@"<%@ = %08X | Kernings:%d | Image = %@>", [self class], self, + return [NSString stringWithFormat:@"<%@ = %08X | Glphys:%d Kernings:%d | Image = %@>", [self class], self, + HASH_COUNT(fontDefDictionary_), HASH_COUNT(kerningDictionary_), atlasName_]; } +-(void) purgeFontDefDictionary +{ + tFontDefHashElement *current, *tmp; + + HASH_ITER(hh, fontDefDictionary_, current, tmp) { + HASH_DEL(fontDefDictionary_, current); + free(current); + } +} + -(void) purgeKerningDictionary { tKerningHashElement *current; - + while(kerningDictionary_) { - current = kerningDictionary_; + current = kerningDictionary_; HASH_DEL(kerningDictionary_,current); free(current); } } - (void)parseConfigFile:(NSString*)fntFile -{ +{ NSString *fullpath = [CCFileUtils fullPathFromRelativePath:fntFile]; - NSString *contents = [NSString stringWithContentsOfFile:fullpath encoding:NSUTF8StringEncoding error:nil]; - - + NSError *error; + NSString *contents = [NSString stringWithContentsOfFile:fullpath encoding:NSUTF8StringEncoding error:&error]; + + NSAssert1( contents, @"cocos2d: Error parsing FNTfile: %@", error); + + // Move all lines in the string, which are denoted by \n, into an array NSArray *lines = [[NSArray alloc] initWithArray:[contents componentsSeparatedByString:@"\n"]]; - + // Create an enumerator which we can use to move through the lines read from the control file NSEnumerator *nse = [lines objectEnumerator]; - + // Create a holder for each line we are going to work with NSString *line; - + // Loop through all the lines in the lines array processing each one while( (line = [nse nextObject]) ) { // parse spacing / padding if([line hasPrefix:@"info face"]) { // XXX: info parsing is incomplete // Not needed for the Hiero editors, but needed for the AngelCode editor -// [self parseInfoArguments:line]; + // [self parseInfoArguments:line]; } // Check to see if the start of the line is something we are interested in else if([line hasPrefix:@"common lineHeight"]) { @@ -171,11 +203,12 @@ - (void)parseConfigFile:(NSString*)fntFile } else if([line hasPrefix:@"char"]) { // Parse the current line and create a new CharDef - ccBMFontDef characterDefinition; - [self parseCharacterDefinition:line charDef:&characterDefinition]; - - // Add the CharDef returned to the charArray - BMFontArray_[ characterDefinition.charID ] = characterDefinition; + tFontDefHashElement *element = malloc( sizeof(*element) ); + + [self parseCharacterDefinition:line charDef:&element->fontDef]; + + element->key = element->fontDef.charID; + HASH_ADD_INT(fontDefDictionary_, key, element); } else if([line hasPrefix:@"kernings count"]) { [self parseKerningCapacity:line]; @@ -194,23 +227,23 @@ -(void) parseImageFileName:(NSString*)line fntFile:(NSString*)fntFile // Break the values for this line up using = NSArray *values = [line componentsSeparatedByString:@"="]; - + // Get the enumerator for the array of components which has been created NSEnumerator *nse = [values objectEnumerator]; - + // We need to move past the first entry in the array before we start assigning values [nse nextObject]; - + // page ID. Sanity check propertyValue = [nse nextObject]; - NSAssert( [propertyValue intValue] == 0, @"XXX: BitmapFontAtlas only supports 1 page"); - - // file + NSAssert( [propertyValue intValue] == 0, @"XXX: LabelBMFont only supports 1 page"); + + // file propertyValue = [nse nextObject]; NSArray *array = [propertyValue componentsSeparatedByString:@"\""]; propertyValue = [array objectAtIndex:1]; - NSAssert(propertyValue,@"BitmapFontAtlas file could not be found"); - + NSAssert(propertyValue,@"LabelBMFont file could not be found"); + // Supports subdirectories NSString *dir = [fntFile stringByDeletingLastPathComponent]; atlasName_ = [dir stringByAppendingPathComponent:propertyValue]; @@ -226,15 +259,15 @@ -(void) parseInfoArguments:(NSString*)line // info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 // NSArray *values = [line componentsSeparatedByString:@"="]; - NSEnumerator *nse = [values objectEnumerator]; + NSEnumerator *nse = [values objectEnumerator]; NSString *propertyValue = nil; - + // We need to move past the first entry in the array before we start assigning values [nse nextObject]; - + // face (ignore) [nse nextObject]; - + // size (ignore) [nse nextObject]; @@ -243,7 +276,7 @@ -(void) parseInfoArguments:(NSString*)line // italic (ignore) [nse nextObject]; - + // charset (ignore) [nse nextObject]; @@ -255,20 +288,20 @@ -(void) parseInfoArguments:(NSString*)line // smooth (ignore) [nse nextObject]; - + // aa (ignore) [nse nextObject]; - + // padding (ignore) propertyValue = [nse nextObject]; { - + NSArray *paddingValues = [propertyValue componentsSeparatedByString:@","]; NSEnumerator *paddingEnum = [paddingValues objectEnumerator]; // padding top propertyValue = [paddingEnum nextObject]; padding_.top = [propertyValue intValue]; - + // padding right propertyValue = [paddingEnum nextObject]; padding_.right = [propertyValue intValue]; @@ -276,16 +309,16 @@ -(void) parseInfoArguments:(NSString*)line // padding bottom propertyValue = [paddingEnum nextObject]; padding_.bottom = [propertyValue intValue]; - + // padding left propertyValue = [paddingEnum nextObject]; padding_.left = [propertyValue intValue]; - + CCLOG(@"cocos2d: padding: %d,%d,%d,%d", padding_.left, padding_.top, padding_.right, padding_.bottom); } // spacing (ignore) - [nse nextObject]; + [nse nextObject]; } -(void) parseCommonArguments:(NSString*)line @@ -295,49 +328,48 @@ -(void) parseCommonArguments:(NSString*)line // common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0 // NSArray *values = [line componentsSeparatedByString:@"="]; - NSEnumerator *nse = [values objectEnumerator]; + NSEnumerator *nse = [values objectEnumerator]; NSString *propertyValue = nil; - + // We need to move past the first entry in the array before we start assigning values [nse nextObject]; - + // Character ID propertyValue = [nse nextObject]; commonHeight_ = [propertyValue intValue]; - + // base (ignore) [nse nextObject]; - - + + // scaleW. sanity check - propertyValue = [nse nextObject]; + propertyValue = [nse nextObject]; NSAssert( [propertyValue intValue] <= [[CCConfiguration sharedConfiguration] maxTextureSize], @"CCLabelBMFont: page can't be larger than supported"); - + // scaleH. sanity check propertyValue = [nse nextObject]; NSAssert( [propertyValue intValue] <= [[CCConfiguration sharedConfiguration] maxTextureSize], @"CCLabelBMFont: page can't be larger than supported"); - + // pages. sanity check propertyValue = [nse nextObject]; NSAssert( [propertyValue intValue] == 1, @"CCBitfontAtlas: only supports 1 page"); - + // packed (ignore) What does this mean ?? } - (void)parseCharacterDefinition:(NSString*)line charDef:(ccBMFontDef*)characterDefinition -{ +{ // Break the values for this line up using = NSArray *values = [line componentsSeparatedByString:@"="]; - NSEnumerator *nse = [values objectEnumerator]; + NSEnumerator *nse = [values objectEnumerator]; NSString *propertyValue; - + // We need to move past the first entry in the array before we start assigning values [nse nextObject]; - + // Character ID propertyValue = [nse nextObject]; propertyValue = [propertyValue substringToIndex: [propertyValue rangeOfString: @" "].location]; characterDefinition->charID = [propertyValue intValue]; - NSAssert(characterDefinition->charID < kCCBMFontMaxChars, @"BitmpaFontAtlas: CharID bigger than supported"); // Character x propertyValue = [nse nextObject]; @@ -366,41 +398,41 @@ -(void) parseKerningCapacity:(NSString*) line { // When using uthash there is not need to parse the capacity. -// NSAssert(!kerningDictionary, @"dictionary already initialized"); -// -// // Break the values for this line up using = -// NSArray *values = [line componentsSeparatedByString:@"="]; -// NSEnumerator *nse = [values objectEnumerator]; -// NSString *propertyValue; -// -// // We need to move past the first entry in the array before we start assigning values -// [nse nextObject]; -// -// // count -// propertyValue = [nse nextObject]; -// int capacity = [propertyValue intValue]; -// -// if( capacity != -1 ) -// kerningDictionary = ccHashSetNew(capacity, targetSetEql); + // NSAssert(!kerningDictionary, @"dictionary already initialized"); + // + // // Break the values for this line up using = + // NSArray *values = [line componentsSeparatedByString:@"="]; + // NSEnumerator *nse = [values objectEnumerator]; + // NSString *propertyValue; + // + // // We need to move past the first entry in the array before we start assigning values + // [nse nextObject]; + // + // // count + // propertyValue = [nse nextObject]; + // int capacity = [propertyValue intValue]; + // + // if( capacity != -1 ) + // kerningDictionary = ccHashSetNew(capacity, targetSetEql); } -(void) parseKerningEntry:(NSString*) line { NSArray *values = [line componentsSeparatedByString:@"="]; - NSEnumerator *nse = [values objectEnumerator]; + NSEnumerator *nse = [values objectEnumerator]; NSString *propertyValue; - + // We need to move past the first entry in the array before we start assigning values [nse nextObject]; - + // first propertyValue = [nse nextObject]; int first = [propertyValue intValue]; - + // second propertyValue = [nse nextObject]; int second = [propertyValue intValue]; - + // second propertyValue = [nse nextObject]; int amount = [propertyValue intValue]; @@ -416,59 +448,84 @@ -(void) parseKerningEntry:(NSString*) line #pragma mark - #pragma mark CCLabelBMFont -@interface CCLabelBMFont (Private) --(NSString*) atlasNameFromFntFile:(NSString*)fntFile; +@interface CCLabelBMFont () -(int) kerningAmountForFirst:(unichar)first second:(unichar)second; +-(void) updateLabel; +-(void) setString:(NSString*) newString updateLabel:(BOOL)update; @end +#pragma mark - +#pragma mark CCLabelBMFont + @implementation CCLabelBMFont +@synthesize alignment = alignment_; @synthesize opacity = opacity_, color = color_; -#pragma mark BitmapFontAtlas - Purge Cache + +#pragma mark LabelBMFont - Purge Cache +(void) purgeCachedData { FNTConfigRemoveCache(); } -#pragma mark BitmapFontAtlas - Creation & Init +#pragma mark LabelBMFont - Creation & Init +(id) labelWithString:(NSString *)string fntFile:(NSString *)fntFile { - return [[[self alloc] initWithString:string fntFile:fntFile] autorelease]; + return [[[self alloc] initWithString:string fntFile:fntFile width:kCCLabelAutomaticWidth alignment:CCTextAlignmentLeft imageOffset:CGPointZero] autorelease]; +} + ++(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment +{ + return [[[self alloc] initWithString:string fntFile:fntFile width:width alignment:alignment imageOffset:CGPointZero] autorelease]; } -// XXX - deprecated - Will be removed in 1.0.1 -+(id) bitmapFontAtlasWithString:(NSString*)string fntFile:(NSString*)fntFile ++(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment imageOffset:(CGPoint)offset { - return [self labelWithString:string fntFile:fntFile]; + return [[[self alloc] initWithString:string fntFile:fntFile width:width alignment:alignment imageOffset:offset] autorelease]; } -(id) initWithString:(NSString*)theString fntFile:(NSString*)fntFile -{ - - [configuration_ release]; // allow re-init +{ + return [self initWithString:theString fntFile:fntFile width:kCCLabelAutomaticWidth alignment:CCTextAlignmentLeft]; +} + +-(id) initWithString:(NSString*)theString fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment +{ + return [self initWithString:theString fntFile:fntFile width:width alignment:alignment imageOffset:CGPointZero]; +} + +-(id) initWithString:(NSString*)theString fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment imageOffset:(CGPoint)offset +{ + NSAssert(!configuration_, @"re-init is no longer supported"); configuration_ = FNTConfigLoadFile(fntFile); [configuration_ retain]; + + fntFile_ = [fntFile retain]; - NSAssert( configuration_, @"Error creating config for BitmapFontAtlas"); + NSAssert( configuration_, @"Error creating config for LabelBMFont"); - if ((self=[super initWithFile:configuration_->atlasName_ capacity:[theString length]])) { + width_ = width; + alignment_ = alignment; + opacity_ = 255; color_ = ccWHITE; contentSize_ = CGSizeZero; - + opacityModifyRGB_ = [[textureAtlas_ texture] hasPremultipliedAlpha]; anchorPoint_ = ccp(0.5f, 0.5f); - [self setString:theString]; + imageOffset_ = offset; + + [self setString:theString updateLabel:YES]; } return self; @@ -477,40 +534,186 @@ -(id) initWithString:(NSString*)theString fntFile:(NSString*)fntFile -(void) dealloc { [string_ release]; + [initialString_ release]; [configuration_ release]; + [fntFile_ release]; + [super dealloc]; } -#pragma mark BitmapFontAtlas - Atlas generation +#pragma mark LabelBMFont - Alignment + +- (void)updateLabel +{ + [self setString:initialString_ updateLabel:NO]; + + if (width_ > 0){ + //Step 1: Make multiline + + NSString *multilineString = @"", *lastWord = @""; + int line = 1, i = 0; + NSUInteger stringLength = [self.string length]; + float startOfLine = -1, startOfWord = -1; + int skip = 0; + //Go through each character and insert line breaks as necessary + for (int j = 0; j < [children_ count]; j++) { + CCSprite *characterSprite; + + while(!(characterSprite = (CCSprite *)[self getChildByTag:j+skip])) + skip++; + + if (!characterSprite.visible) continue; + + if (i >= stringLength || i < 0) + break; + + unichar character = [self.string characterAtIndex:i]; + + if (startOfWord == -1) + startOfWord = characterSprite.position.x - characterSprite.contentSize.width/2; + if (startOfLine == -1) + startOfLine = startOfWord; + + //Character is a line break + //Put lastWord on the current line and start a new line + //Reset lastWord + if ([[NSCharacterSet newlineCharacterSet] characterIsMember:character]) { + lastWord = [[lastWord stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] stringByAppendingFormat:@"%C", character]; + multilineString = [multilineString stringByAppendingString:lastWord]; + lastWord = @""; + startOfWord = -1; + line++; + startOfLine = -1; + i++; + + //CCLabelBMFont do not have a character for new lines, so do NOT "continue;" in the for loop. Process the next character + if (i >= stringLength || i < 0) + break; + character = [self.string characterAtIndex:i]; + + if (startOfWord == -1) + startOfWord = characterSprite.position.x - characterSprite.contentSize.width/2; + if (startOfLine == -1) + startOfLine = startOfWord; + } + + //Character is a whitespace + //Put lastWord on current line and continue on current line + //Reset lastWord + if ([[NSCharacterSet whitespaceCharacterSet] characterIsMember:character]) { + lastWord = [lastWord stringByAppendingFormat:@"%C", character]; + multilineString = [multilineString stringByAppendingString:lastWord]; + lastWord = @""; + startOfWord = -1; + i++; + continue; + } + + //Character is out of bounds + //Do not put lastWord on current line. Add "\n" to current line to start a new line + //Append to lastWord + if (characterSprite.position.x + characterSprite.contentSize.width/2 - startOfLine > width_) { + lastWord = [lastWord stringByAppendingFormat:@"%C", character]; + NSString *trimmedString = [multilineString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; + multilineString = [trimmedString stringByAppendingString:@"\n"]; + line++; + startOfLine = -1; + i++; + continue; + } else { + //Character is normal + //Append to lastWord + lastWord = [lastWord stringByAppendingFormat:@"%C", character]; + i++; + continue; + } + } + + multilineString = [multilineString stringByAppendingFormat:@"%@", lastWord]; + + [self setString:multilineString updateLabel:NO]; + } + + //Step 2: Make alignment + + if (self.alignment != CCTextAlignmentLeft) { + + int i = 0; + //Number of spaces skipped + int lineNumber = 0; + //Go through line by line + for (NSString *lineString in [string_ componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) { + int lineWidth = 0; + + //Find index of last character in this line + NSInteger index = i + [lineString length] - 1 + lineNumber; + if (index < 0) + continue; + + //Find position of last character on the line + CCSprite *lastChar = (CCSprite *)[self getChildByTag:index]; + + lineWidth = lastChar.position.x + lastChar.contentSize.width/2; + + //Figure out how much to shift each character in this line horizontally + float shift = 0; + switch (self.alignment) { + case CCTextAlignmentCenter: + shift = self.contentSize.width/2 - lineWidth/2; + break; + case CCTextAlignmentRight: + shift = self.contentSize.width - lineWidth; + default: + break; + } + + if (shift != 0) { + int j = 0; + //For each character, shift it so that the line is center aligned + for (j = 0; j < [lineString length]; j++) { + index = i + j + lineNumber; + if (index < 0) + continue; + CCSprite *characterSprite = (CCSprite *)[self getChildByTag:index]; + characterSprite.position = ccpAdd(characterSprite.position, ccp(shift, 0)); + } + } + i += [lineString length]; + lineNumber++; + } + } +} + +#pragma mark LabelBMFont - Atlas generation -(int) kerningAmountForFirst:(unichar)first second:(unichar)second { int ret = 0; unsigned int key = (first<<16) | (second & 0xffff); - + if( configuration_->kerningDictionary_ ) { tKerningHashElement *element = NULL; - HASH_FIND_INT(configuration_->kerningDictionary_, &key, element); + HASH_FIND_INT(configuration_->kerningDictionary_, &key, element); if(element) ret = element->amount; } - + return ret; } -(void) createFontChars { - int nextFontPositionX = 0; - int nextFontPositionY = 0; + NSInteger nextFontPositionX = 0; + NSInteger nextFontPositionY = 0; unichar prev = -1; - int kerningAmount = 0; - + NSInteger kerningAmount = 0; + CGSize tmpSize = CGSizeZero; - int longestLine = 0; - int totalHeight = 0; - - int quantityOfLines = 1; + NSInteger longestLine = 0; + NSUInteger totalHeight = 0; + + NSUInteger quantityOfLines = 1; NSUInteger stringLen = [string_ length]; if( ! stringLen ) @@ -523,14 +726,13 @@ -(void) createFontChars if( c=='\n') quantityOfLines++; } - + totalHeight = configuration_->commonHeight_ * quantityOfLines; nextFontPositionY = -(configuration_->commonHeight_ - configuration_->commonHeight_*quantityOfLines); - - for(NSUInteger i=0; icommonHeight_; @@ -538,34 +740,47 @@ -(void) createFontChars } kerningAmount = [self kerningAmountForFirst:prev second:c]; + - ccBMFontDef fontDef = configuration_->BMFontArray_[c]; + tFontDefHashElement *element = NULL; + // unichar is a short, and an int is needed on HASH_FIND_INT + NSUInteger key = (NSUInteger)c; + HASH_FIND_INT(configuration_->fontDefDictionary_ , &key, element); + NSAssert(element, @"FontDefinition could not be found!"); + + ccBMFontDef fontDef = element->fontDef; + CGRect rect = fontDef.rect; + rect = CC_RECT_PIXELS_TO_POINTS(rect); + rect.origin.x += imageOffset_.x; + rect.origin.y += imageOffset_.y; + CCSprite *fontChar; - + fontChar = (CCSprite*) [self getChildByTag:i]; if( ! fontChar ) { - fontChar = [[CCSprite alloc] initWithBatchNode:self rectInPixels:rect]; + fontChar = [[CCSprite alloc] initWithTexture:textureAtlas_.texture rect:rect]; [self addChild:fontChar z:0 tag:i]; [fontChar release]; } else { // reusing fonts - [fontChar setTextureRectInPixels:rect rotated:NO untrimmedSize:rect.size]; - + [fontChar setTextureRect:rect rotated:NO untrimmedSize:rect.size]; + // restore to default in case they were modified fontChar.visible = YES; fontChar.opacity = 255; } - + float yOffset = configuration_->commonHeight_ - fontDef.yOffset; - fontChar.positionInPixels = ccp( (float)nextFontPositionX + fontDef.xOffset + fontDef.rect.size.width*0.5f + kerningAmount, - (float)nextFontPositionY + yOffset - rect.size.height*0.5f ); + CGPoint fontPos = ccp( (float)nextFontPositionX + fontDef.xOffset + fontDef.rect.size.width*0.5f + kerningAmount, + (float)nextFontPositionY + yOffset - rect.size.height*0.5f * CC_CONTENT_SCALE_FACTOR() ); + fontChar.position = CC_POINT_PIXELS_TO_POINTS(fontPos); // update kerning - nextFontPositionX += configuration_->BMFontArray_[c].xAdvance + kerningAmount; + nextFontPositionX += fontDef.xAdvance + kerningAmount; prev = c; // Apply label properties @@ -585,22 +800,10 @@ -(void) createFontChars tmpSize.width = longestLine; tmpSize.height = totalHeight; - [self setContentSizeInPixels:tmpSize]; -} - -#pragma mark BitmapFontAtlas - CCLabelProtocol protocol -- (void) setString:(NSString*) newString -{ - [string_ release]; - string_ = [newString copy]; - - CCNode *child; - CCARRAY_FOREACH(children_, child) - child.visible = NO; - - [self createFontChars]; + [self setContentSize:CC_SIZE_PIXELS_TO_POINTS(tmpSize)]; } +#pragma mark LabelBMFont - CCLabelProtocol protocol -(NSString*) string { return string_; @@ -608,18 +811,43 @@ -(NSString*) string -(void) setCString:(char*)label { - [self setString:[NSString stringWithUTF8String:label]]; + [self setString:[NSString stringWithUTF8String:label] ]; } -#pragma mark BitmapFontAtlas - CCRGBAProtocol protocol +- (void) setString:(NSString*)newString +{ + [self setString:newString updateLabel:YES]; +} + +- (void) setString:(NSString*) newString updateLabel:(BOOL)update +{ + if( !update ) { + [string_ release]; + string_ = [newString copy]; + } else { + [initialString_ release]; + initialString_ = [newString copy]; + } + + CCSprite *child; + CCARRAY_FOREACH(children_, child) + child.visible = NO; + + [self createFontChars]; + + if (update) + [self updateLabel]; +} + +#pragma mark LabelBMFont - CCRGBAProtocol protocol -(void) setColor:(ccColor3B)color { color_ = color; - + CCSprite *child; CCARRAY_FOREACH(children_, child) - [child setColor:color_]; + [child setColor:color_]; } -(void) setOpacity:(GLubyte)opacity @@ -628,15 +856,15 @@ -(void) setOpacity:(GLubyte)opacity id child; CCARRAY_FOREACH(children_, child) - [child setOpacity:opacity_]; + [child setOpacity:opacity_]; } -(void) setOpacityModifyRGB:(BOOL)modify { opacityModifyRGB_ = modify; - + id child; CCARRAY_FOREACH(children_, child) - [child setOpacityModifyRGB:modify]; + [child setOpacityModifyRGB:modify]; } -(BOOL) doesOpacityModifyRGB @@ -644,7 +872,7 @@ -(BOOL) doesOpacityModifyRGB return opacityModifyRGB_; } -#pragma mark BitmapFontAtlas - AnchorPoint +#pragma mark LabelBMFont - AnchorPoint -(void) setAnchorPoint:(CGPoint)point { if( ! CGPointEqualToPoint(point, anchorPoint_) ) { @@ -653,11 +881,44 @@ -(void) setAnchorPoint:(CGPoint)point } } -#pragma mark BitmapFontAtlas - Debug draw -#if CC_BITMAPFONTATLAS_DEBUG_DRAW +#pragma mark LabelBMFont - Alignment +- (void)setWidth:(float)width { + width_ = width; + [self updateLabel]; +} + +- (void)setAlignment:(CCTextAlignment)alignment { + alignment_ = alignment; + [self updateLabel]; +} + +#pragma mark LabelBMFont - FntFile +- (void) setFntFile:(NSString*) fntFile +{ + if( fntFile != fntFile_ ) { + [fntFile_ release]; + fntFile_ = [fntFile retain]; + + [configuration_ release]; + configuration_ = FNTConfigLoadFile(fntFile); + [configuration_ retain]; + + [self setTexture:[[CCTextureCache sharedTextureCache] addImage:configuration_->atlasName_]]; + [self createFontChars]; + } +} + +- (NSString*) fntFile +{ + return fntFile_; +} + +#pragma mark LabelBMFont - Debug draw +#if CC_LABELBMFONT_DEBUG_DRAW -(void) draw { [super draw]; + CGSize s = [self contentSize]; CGPoint vertices[4]={ ccp(0,0),ccp(s.width,0), @@ -665,5 +926,5 @@ -(void) draw }; ccDrawPoly(vertices, 4, YES); } -#endif // CC_BITMAPFONTATLAS_DEBUG_DRAW +#endif // CC_LABELBMFONT_DEBUG_DRAW @end diff --git a/Example/libs/cocos2d/CCLabelTTF.h b/Example/libs/cocos2d/CCLabelTTF.h index 66cdda7..fcbd1dc 100644 --- a/Example/libs/cocos2d/CCLabelTTF.h +++ b/Example/libs/cocos2d/CCLabelTTF.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,7 +34,7 @@ * * All features from CCTextureNode are valid in CCLabel * - * CCLabel objects are slow. Consider using CCLabelAtlas or CCBitmapFontAtlas instead. + * CCLabel objects are slow. Consider using CCLabelAtlas or CCLabelBMFont instead. */ @interface CCLabelTTF : CCSprite @@ -42,13 +43,35 @@ CCTextAlignment alignment_; NSString * fontName_; CGFloat fontSize_; + CCLineBreakMode lineBreakMode_; NSString *string_; } +/** Font name used in the label */ +@property (nonatomic,retain) NSString* fontName; +/** Font size of the label */ +@property (nonatomic,assign) float fontSize; +/** Dimensions of the label in Points */ +@property (nonatomic,assign) CGSize dimensions; + +/** creates a CCLabel from a fontname, alignment, dimension in points, line break mode, and font size in points. + Supported lineBreakModes: + - iOS: all UILineBreakMode supported modes + - Mac: Only NSLineBreakByWordWrapping is supported. + @since v1.0 + */ ++ (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size; /** creates a CCLabel from a fontname, alignment, dimension in points and font size in points*/ + (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size; /** creates a CCLabel from a fontname and font size in points*/ + (id) labelWithString:(NSString*)string fontName:(NSString*)name fontSize:(CGFloat)size; +/** initializes the CCLabel with a font name, alignment, dimension in points, line brea mode and font size in points. + Supported lineBreakModes: + - iOS: all UILineBreakMode supported modes + - Mac: Only NSLineBreakByWordWrapping is supported. + @since v1.0 + */ +- (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size; /** initializes the CCLabel with a font name, alignment, dimension in points and font size in points */ - (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size; /** initializes the CCLabel with a font name and font size in points */ @@ -59,4 +82,6 @@ */ - (void) setString:(NSString*)str; + + @end diff --git a/Example/libs/cocos2d/CCLabelTTF.m b/Example/libs/cocos2d/CCLabelTTF.m index 5760a20..75dcedc 100644 --- a/Example/libs/cocos2d/CCLabelTTF.m +++ b/Example/libs/cocos2d/CCLabelTTF.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,23 +25,32 @@ */ -#import - #import "CCLabelTTF.h" #import "Support/CGPointExtension.h" #import "ccMacros.h" +#import "CCShaderCache.h" +#import "CCGLProgram.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import "Platforms/iOS/CCDirectorIOS.h" #endif +#if CC_USE_LA88_LABELS +#define SHADER_PROGRAM kCCShader_PositionTextureColor +#else +#define SHADER_PROGRAM kCCShader_PositionTextureA8Color +#endif + @implementation CCLabelTTF - (id) init { - NSAssert(NO, @"CCLabelTTF: Init not supported. Use initWithString"); - [self release]; - return nil; + return [self initWithString:@"" fontName:@"Helvetica" fontSize:12]; +} + ++ (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size; +{ + return [[[self alloc] initWithString: string dimensions:dimensions alignment:alignment lineBreakMode:lineBreakMode fontName:name fontSize:size]autorelease]; } + (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size @@ -54,28 +64,40 @@ + (id) labelWithString:(NSString*)string fontName:(NSString*)name fontSize:(CGFl } -- (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size +- (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size { if( (self=[super init]) ) { - dimensions_ = CGSizeMake( dimensions.width * CC_CONTENT_SCALE_FACTOR(), dimensions.height * CC_CONTENT_SCALE_FACTOR() ); + // shader program + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:SHADER_PROGRAM]; + + dimensions_ = CGSizeMake( dimensions.width, dimensions.height ); alignment_ = alignment; fontName_ = [name retain]; - fontSize_ = size * CC_CONTENT_SCALE_FACTOR(); - + fontSize_ = size; + lineBreakMode_ = lineBreakMode; + [self setString:str]; } return self; } +- (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size +{ + return [self initWithString:str dimensions:dimensions alignment:alignment lineBreakMode:CCLineBreakModeWordWrap fontName:name fontSize:size]; +} + - (id) initWithString:(NSString*)str fontName:(NSString*)name fontSize:(CGFloat)size { if( (self=[super init]) ) { - + + // shader program + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:SHADER_PROGRAM]; + dimensions_ = CGSizeZero; fontName_ = [name retain]; - fontSize_ = size * CC_CONTENT_SCALE_FACTOR(); - + fontSize_ = size; + [self setString:str]; } return self; @@ -90,13 +112,32 @@ - (void) setString:(NSString*)str if( CGSizeEqualToSize( dimensions_, CGSizeZero ) ) tex = [[CCTexture2D alloc] initWithString:str fontName:fontName_ - fontSize:fontSize_]; + fontSize:fontSize_ * CC_CONTENT_SCALE_FACTOR()]; else tex = [[CCTexture2D alloc] initWithString:str - dimensions:dimensions_ + dimensions:CC_SIZE_POINTS_TO_PIXELS(dimensions_) alignment:alignment_ + lineBreakMode:lineBreakMode_ fontName:fontName_ - fontSize:fontSize_]; + fontSize:fontSize_ * CC_CONTENT_SCALE_FACTOR()]; + +#ifdef __CC_PLATFORM_IOS + // iPad ? + if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) { + if( CC_CONTENT_SCALE_FACTOR() == 2 ) + [tex setResolutionType:kCCResolutioniPadRetinaDisplay]; + else + [tex setResolutionType:kCCResolutioniPad]; + } + // iPhone ? + else + { + if( CC_CONTENT_SCALE_FACTOR() == 2 ) + [tex setResolutionType:kCCResolutioniPhoneRetinaDisplay]; + else + [tex setResolutionType:kCCResolutioniPhone]; + } +#endif [self setTexture:tex]; [tex release]; @@ -111,15 +152,65 @@ -(NSString*) string return string_; } +- (void)setFontName:(NSString*)fontName +{ + if( fontName != fontName_ ) { + [fontName_ release]; + fontName_ = [fontName retain]; + + // Force update + [self setString:[self string]]; + } +} + +- (NSString*)fontName +{ + return fontName_; +} + +- (void) setFontSize:(float)fontSize +{ + if( fontSize != fontSize_ ) { + fontSize_ = fontSize; + + // Force update + [self setString:[self string]]; + } +} + +- (float) fontSize +{ + return fontSize_; +} + +-(void) setDimensions:(CGSize) dim +{ + if( dim.width != dimensions_.width || dim.height != dimensions_.height) + { + dimensions_ = dim; + + // Force update + [self setString:[self string]]; + } +} + +-(CGSize) dimensions +{ + return dimensions_; +} + - (void) dealloc { [string_ release]; [fontName_ release]; + [super dealloc]; } - (NSString*) description { - return [NSString stringWithFormat:@"<%@ = %08X | FontName = %@, FontSize = %.1f>", [self class], self, fontName_, fontSize_]; + // XXX: string_, fontName_ can't be displayed here, since they might be already released + + return [NSString stringWithFormat:@"<%@ = %08X | FontSize = %.1f>", [self class], self, fontSize_]; } @end diff --git a/Example/libs/cocos2d/CCLayer.h b/Example/libs/cocos2d/CCLayer.h index 9c02f37..a2b08f5 100644 --- a/Example/libs/cocos2d/CCLayer.h +++ b/Example/libs/cocos2d/CCLayer.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,27 +26,28 @@ -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#import // Needed for UIAccelerometerDelegate +#import "ccMacros.h" + +#ifdef __CC_PLATFORM_IOS +#import // Needed for UIAccelerometerDelegate #import "Platforms/iOS/CCTouchDelegateProtocol.h" // Touches only supported on iOS -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) #import "Platforms/Mac/CCEventDispatcher.h" #endif #import "CCProtocols.h" #import "CCNode.h" -// -// CCLayer -// -/** CCLayer is a subclass of CCNode that implements the TouchEventsDelegate protocol. - +#pragma mark - +#pragma mark CCLayer + +/** CCLayer is a subclass of CCNode that implements the CCTouchEventsDelegate protocol. + All features from CCNode are valid, plus the following new features: - It can receive iPhone Touches - It can receive Accelerometer input */ -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS @interface CCLayer : CCNode { BOOL isTouchEnabled_; @@ -53,84 +55,99 @@ } /** If isTouchEnabled, this method is called onEnter. Override it to change the way CCLayer receives touch events. - ( Default: [[TouchDispatcher sharedDispatcher] addStandardDelegate:self priority:0] ) + ( Default: [touchDispatcher addStandardDelegate:self priority:0] ) Example: -(void) registerWithTouchDispatcher { - [[TouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:INT_MIN+1 swallowsTouches:YES]; + [touchDispatcher addTargetedDelegate:self priority:INT_MIN+1 swallowsTouches:YES]; } - + Valid only on iOS. Not valid on Mac. - + @since v0.8.0 */ -(void) registerWithTouchDispatcher; /** whether or not it will receive Touch events. You can enable / disable touch events with this property. - Only the touches of this node will be affected. This "method" is not propagated to it's children. - - Valid only on iOS. Not valid on Mac. + Only the touches of this node will be affected. This "method" is not propagated to its children. + + Valid on iOS and Mac OS X v10.6 and later. @since v0.8.1 */ @property(nonatomic,assign) BOOL isTouchEnabled; /** whether or not it will receive Accelerometer events You can enable / disable accelerometer events with this property. - + Valid only on iOS. Not valid on Mac. @since v0.8.1 */ @property(nonatomic,assign) BOOL isAccelerometerEnabled; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) -@interface CCLayer : CCNode +@interface CCLayer : CCNode { BOOL isMouseEnabled_; BOOL isKeyboardEnabled_; + BOOL isTouchEnabled_; } /** whether or not it will receive mouse events. - + Valind only Mac. Not valid on iOS */ @property (nonatomic, readwrite) BOOL isMouseEnabled; /** whether or not it will receive keyboard events. - + Valind only Mac. Not valid on iOS */ @property (nonatomic, readwrite) BOOL isKeyboardEnabled; +/** whether or not it will receive touch events. + + Valid on iOS and Mac OS X v10.6 and later. + */ +@property (nonatomic, readwrite) BOOL isTouchEnabled; + /** priority of the mouse event delegate. Default 0. Override this method to set another priority. - - Valind only Mac. Not valid on iOS + + Valind only Mac. Not valid on iOS */ -(NSInteger) mouseDelegatePriority; /** priority of the keyboard event delegate. Default 0. Override this method to set another priority. - - Valind only Mac. Not valid on iOS + + Valind only Mac. Not valid on iOS */ -(NSInteger) keyboardDelegatePriority; +/** priority of the touch event delegate. + Default 0. + Override this method to set another priority. + + Valind only Mac. Not valid on iOS + */ +-(NSInteger) touchDelegatePriority; + #endif // mac @end -// -// CCLayerColor -// +#pragma mark - +#pragma mark CCLayerColor + /** CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol. - + All features from CCLayer are valid, plus the following new features: - opacity - RGB colors @@ -138,10 +155,10 @@ @interface CCLayerColor : CCLayer { GLubyte opacity_; - ccColor3B color_; - GLfloat squareVertices[4 * 2]; - GLubyte squareColors[4 * 4]; - + ccColor3B color_; + ccVertex2F squareVertices_[4]; + ccColor4F squareColors_[4]; + ccBlendFunc blendFunc_; } @@ -150,7 +167,9 @@ /** creates a CCLayer with color. Width and height are the window size. */ + (id) layerWithColor: (ccColor4B)color; -/** initializes a CCLayer with color, width and height in Points */ +/** initializes a CCLayer with color, width and height in Points. + This is the designated initializer. + */ - (id) initWithColor:(ccColor4B)color width:(GLfloat)w height:(GLfloat)h; /** initializes a CCLayer with color. Width and height are the window size. */ - (id) initWithColor:(ccColor4B)color; @@ -172,34 +191,27 @@ @property (nonatomic,readwrite) ccBlendFunc blendFunc; @end -/** CCColorLayer - It is the same as CCLayerColor. - - @deprecated Use CCLayerColor instead. This class will be removed in v1.0.1 - */ -DEPRECATED_ATTRIBUTE @interface CCColorLayer : CCLayerColor -@end - +#pragma mark - +#pragma mark CCLayerGradient -// -// CCLayerGradient -// /** CCLayerGradient is a subclass of CCLayerColor that draws gradients across the background. All features from CCLayerColor are valid, plus the following new features: - direction - final color - + - interpolation mode + Color is interpolated between the startColor and endColor along the given vector (starting at the origin, ending at the terminus). If no vector is supplied, it defaults to (0, -1) -- a fade from top to bottom. - - Given the nature of - the interpolation, you will not see either the start or end color for + + If 'compressedInterpolation' is disabled, you will not see either the start or end color for non-cardinal vectors; a smooth gradient implying both end points will be still be drawn, however. - + + If ' compressedInterpolation' is enabled (default mode) you will see both the start and end colors of the gradient. + @since v0.99.5 */ @interface CCLayerGradient : CCLayerColor @@ -208,6 +220,7 @@ the background. GLubyte startOpacity_; GLubyte endOpacity_; CGPoint vector_; + BOOL compressedInterpolation_; } /** Creates a full-screen CCLayer with a gradient between start and end. */ @@ -221,9 +234,7 @@ the background. - (id) initWithColor: (ccColor4B) start fadingTo: (ccColor4B) end alongVector: (CGPoint) v; /** The starting color. */ -- (ccColor3B) startColor; -- (void) setStartColor:(ccColor3B)colors; - +@property (nonatomic, readwrite) ccColor3B startColor; /** The ending color. */ @property (nonatomic, readwrite) ccColor3B endColor; /** The starting opacity. */ @@ -232,30 +243,38 @@ the background. @property (nonatomic, readwrite) GLubyte endOpacity; /** The vector along which to fade color. */ @property (nonatomic, readwrite) CGPoint vector; +/** Whether or not the interpolation will be compressed in order to display all the colors of the gradient both in canonical and non canonical vectors + Default: YES + */ +@property (nonatomic, readwrite) BOOL compressedInterpolation; @end -/** CCMultipleLayer is a CCLayer with the ability to multiplex it's children. +#pragma mark - +#pragma mark CCLayerMultiplex + +/** CCLayerMultiplex is a CCLayer with the ability to multiplex its children. Features: - It supports one or more children - Only one children will be active a time */ -@interface CCMultiplexLayer : CCLayer +@interface CCLayerMultiplex : CCLayer { - unsigned int enabledLayer; - NSMutableArray *layers; + unsigned int enabledLayer_; + NSMutableArray *layers_; } /** creates a CCMultiplexLayer with one or more layers using a variable argument list. */ +(id) layerWithLayers: (CCLayer*) layer, ... NS_REQUIRES_NIL_TERMINATION; /** initializes a MultiplexLayer with one or more layers using a variable argument list. */ -(id) initWithLayers: (CCLayer*) layer vaList:(va_list) params; -/** switches to a certain layer indexed by n. - The current (old) layer will be removed from it's parent with 'cleanup:YES'. +/** switches to a certain layer indexed by n. + The current (old) layer will be removed from its parent with 'cleanup:YES'. */ -(void) switchTo: (unsigned int) n; /** release the current layer and switches to another layer indexed by n. - The current (old) layer will be removed from it's parent with 'cleanup:YES'. + The current (old) layer will be removed from its parent with 'cleanup:YES'. */ -(void) switchToAndReleaseMe: (unsigned int) n; @end + diff --git a/Example/libs/cocos2d/CCLayer.m b/Example/libs/cocos2d/CCLayer.m index 6604bb8..277f99d 100644 --- a/Example/libs/cocos2d/CCLayer.m +++ b/Example/libs/cocos2d/CCLayer.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,15 +32,23 @@ #import "CCLayer.h" #import "CCDirector.h" #import "ccMacros.h" +#import "CCShaderCache.h" +#import "CCGLProgram.h" +#import "ccGLStateCache.h" +#import "Support/TransformUtils.h" #import "Support/CGPointExtension.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import "Platforms/iOS/CCTouchDispatcher.h" #import "Platforms/iOS/CCDirectorIOS.h" -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) #import "Platforms/Mac/CCEventDispatcher.h" +#import "Platforms/Mac/CCDirectorMac.h" #endif +// extern +#import "kazmath/GL/matrix.h" + #pragma mark - #pragma mark Layer @@ -49,30 +58,32 @@ @implementation CCLayer -(id) init { if( (self=[super init]) ) { - + CGSize s = [[CCDirector sharedDirector] winSize]; anchorPoint_ = ccp(0.5f, 0.5f); [self setContentSize:s]; self.isRelativeAnchorPoint = NO; -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED isTouchEnabled_ = NO; + +#ifdef __CC_PLATFORM_IOS isAccelerometerEnabled_ = NO; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) isMouseEnabled_ = NO; isKeyboardEnabled_ = NO; #endif } - + return self; } #pragma mark Layer - Touch and Accelerometer related -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS -(void) registerWithTouchDispatcher { - [[CCTouchDispatcher sharedDispatcher] addStandardDelegate:self priority:0]; + CCDirector *director = [CCDirector sharedDirector]; + [[director touchDispatcher] addStandardDelegate:self priority:0]; } -(BOOL) isAccelerometerEnabled @@ -105,15 +116,17 @@ -(void) setIsTouchEnabled:(BOOL)enabled if( isRunning_ ) { if( enabled ) [self registerWithTouchDispatcher]; - else - [[CCTouchDispatcher sharedDispatcher] removeDelegate:self]; + else { + CCDirector *director = [CCDirector sharedDirector]; + [[director touchDispatcher] removeDelegate:self]; + } } } } -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) -#pragma mark CCLayer - Mouse & Keyboard events +#pragma mark CCLayer - Mouse, Keyboard & Touch events -(NSInteger) mouseDelegatePriority { @@ -129,12 +142,13 @@ -(void) setIsMouseEnabled:(BOOL)enabled { if( isMouseEnabled_ != enabled ) { isMouseEnabled_ = enabled; - + if( isRunning_ ) { + CCDirector *director = [CCDirector sharedDirector]; if( enabled ) - [[CCEventDispatcher sharedDispatcher] addMouseDelegate:self priority:[self mouseDelegatePriority]]; + [[director eventDispatcher] addMouseDelegate:self priority:[self mouseDelegatePriority]]; else - [[CCEventDispatcher sharedDispatcher] removeMouseDelegate:self]; + [[director eventDispatcher] removeMouseDelegate:self]; } } } @@ -153,12 +167,37 @@ -(void) setIsKeyboardEnabled:(BOOL)enabled { if( isKeyboardEnabled_ != enabled ) { isKeyboardEnabled_ = enabled; - + if( isRunning_ ) { + CCDirector *director = [CCDirector sharedDirector]; if( enabled ) - [[CCEventDispatcher sharedDispatcher] addKeyboardDelegate:self priority:[self keyboardDelegatePriority] ]; + [[director eventDispatcher] addKeyboardDelegate:self priority:[self keyboardDelegatePriority] ]; else - [[CCEventDispatcher sharedDispatcher] removeKeyboardDelegate:self]; + [[director eventDispatcher] removeKeyboardDelegate:self]; + } + } +} + +-(NSInteger) touchDelegatePriority +{ + return 0; +} + +-(BOOL) isTouchEnabled +{ + return isTouchEnabled_; +} + +-(void) setIsTouchEnabled:(BOOL)enabled +{ + if( isTouchEnabled_ != enabled ) { + isTouchEnabled_ = enabled; + if( isRunning_ ) { + CCDirector *director = [CCDirector sharedDirector]; + if( enabled ) + [[director eventDispatcher] addTouchDelegate:self priority:[self touchDelegatePriority]]; + else + [[director eventDispatcher] removeTouchDelegate:self]; } } } @@ -170,20 +209,27 @@ -(void) setIsKeyboardEnabled:(BOOL)enabled #pragma mark Layer - Callbacks -(void) onEnter { -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS // register 'parent' nodes first // since events are propagated in reverse order if (isTouchEnabled_) [self registerWithTouchDispatcher]; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) + CCDirector *director = [CCDirector sharedDirector]; + CCEventDispatcher *eventDispatcher = [director eventDispatcher]; + if( isMouseEnabled_ ) - [[CCEventDispatcher sharedDispatcher] addMouseDelegate:self priority:[self mouseDelegatePriority]]; - + [eventDispatcher addMouseDelegate:self priority:[self mouseDelegatePriority]]; + if( isKeyboardEnabled_) - [[CCEventDispatcher sharedDispatcher] addKeyboardDelegate:self priority:[self keyboardDelegatePriority]]; + [eventDispatcher addKeyboardDelegate:self priority:[self keyboardDelegatePriority]]; + + if( isTouchEnabled_) + [eventDispatcher addTouchDelegate:self priority:[self touchDelegatePriority]]; + #endif - + // then iterate over all the children [super onEnter]; } @@ -192,36 +238,43 @@ -(void) onEnter // Can't register mouse, touches here because of #issue #1018, and #1021 -(void) onEnterTransitionDidFinish { -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS if( isAccelerometerEnabled_ ) [[UIAccelerometer sharedAccelerometer] setDelegate:self]; #endif - + [super onEnterTransitionDidFinish]; } -(void) onExit { -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED + CCDirector *director = [CCDirector sharedDirector]; + +#ifdef __CC_PLATFORM_IOS if( isTouchEnabled_ ) - [[CCTouchDispatcher sharedDispatcher] removeDelegate:self]; - + [[director touchDispatcher] removeDelegate:self]; + if( isAccelerometerEnabled_ ) [[UIAccelerometer sharedAccelerometer] setDelegate:nil]; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) + CCEventDispatcher *eventDispatcher = [director eventDispatcher]; if( isMouseEnabled_ ) - [[CCEventDispatcher sharedDispatcher] removeMouseDelegate:self]; - + [eventDispatcher removeMouseDelegate:self]; + if( isKeyboardEnabled_ ) - [[CCEventDispatcher sharedDispatcher] removeKeyboardDelegate:self]; + [eventDispatcher removeKeyboardDelegate:self]; + + if( isTouchEnabled_ ) + [eventDispatcher removeTouchDelegate:self]; + #endif - + [super onExit]; } -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS -(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { NSAssert(NO, @"Layer#ccTouchBegan override me"); @@ -254,23 +307,34 @@ + (id) layerWithColor:(ccColor4B)color return [[(CCLayerColor*)[self alloc] initWithColor:color] autorelease]; } +-(id) init +{ + CGSize s = [[CCDirector sharedDirector] winSize]; + return [self initWithColor:ccc4(0,0,0,0) width:s.width height:s.height]; +} + +// Designated initializer - (id) initWithColor:(ccColor4B)color width:(GLfloat)w height:(GLfloat) h { if( (self=[super init]) ) { - + // default blend function - blendFunc_ = (ccBlendFunc) { CC_BLEND_SRC, CC_BLEND_DST }; + blendFunc_ = (ccBlendFunc) { GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA }; color_.r = color.r; color_.g = color.g; color_.b = color.b; opacity_ = color.a; - - for (NSUInteger i = 0; i -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import "Platforms/iOS/CCDirectorIOS.h" #import "Platforms/iOS/CCTouchDispatcher.h" -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) -#import "Platforms/Mac/MacGLView.h" +#elif defined(__CC_PLATFORM_MAC) +#import "Platforms/Mac/CCGLView.h" #import "Platforms/Mac/CCDirectorMac.h" #endif @@ -43,39 +43,59 @@ kDefaultPadding = 5, }; +#pragma mark - CCMenu + @implementation CCMenu -@synthesize opacity = opacity_, color = color_; +@synthesize opacity = opacity_, color = color_, enabled=enabled_; -- (id) init ++(id) menuWithArray:(NSArray *)arrayOfItems { - NSAssert(NO, @"CCMenu: Init not supported."); - [self release]; - return nil; + return [[[self alloc] initWithArray:arrayOfItems] autorelease]; } +(id) menuWithItems: (CCMenuItem*) item, ... { va_list args; va_start(args,item); - + id s = [[[self alloc] initWithItems: item vaList:args] autorelease]; - + va_end(args); return s; } +-(id) init +{ + return [self initWithArray:nil]; +} + -(id) initWithItems: (CCMenuItem*) item vaList: (va_list) args { - if( (self=[super init]) ) { + NSMutableArray *array = nil; + if( item ) { + array = [NSMutableArray arrayWithObject:item]; + CCMenuItem *i = va_arg(args, CCMenuItem*); + while(i) { + [array addObject:i]; + i = va_arg(args, CCMenuItem*); + } + } + + return [self initWithArray:array]; +} -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +-(id) initWithArray:(NSArray *)arrayOfItems +{ + if( (self=[super init]) ) { +#ifdef __CC_PLATFORM_IOS self.isTouchEnabled = YES; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) self.isMouseEnabled = YES; #endif + enabled_ = YES; - // menu in the center of the screen + // by default, menu in the center of the screen CGSize s = [[CCDirector sharedDirector] winSize]; self.isRelativeAnchorPoint = NO; @@ -84,28 +104,20 @@ -(id) initWithItems: (CCMenuItem*) item vaList: (va_list) args // XXX: in v0.7, winSize should return the visible size // XXX: so the bar calculation should be done there -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS CGRect r = [[UIApplication sharedApplication] statusBarFrame]; - ccDeviceOrientation orientation = [[CCDirector sharedDirector] deviceOrientation]; - if( orientation == CCDeviceOrientationLandscapeLeft || orientation == CCDeviceOrientationLandscapeRight ) - s.height -= r.size.width; - else - s.height -= r.size.height; + s.height -= r.size.height; #endif self.position = ccp(s.width/2, s.height/2); - + int z=0; - if (item) { + for( CCMenuItem *item in arrayOfItems) { [self addChild: item z:z]; - CCMenuItem *i = va_arg(args, CCMenuItem*); - while(i) { - z++; - [self addChild: i z:z]; - i = va_arg(args, CCMenuItem*); - } + z++; } - // [self alignItemsVertically]; + +// [self alignItemsVertically]; selectedItem_ = nil; state_ = kCCMenuStateWaiting; @@ -122,7 +134,7 @@ -(void) dealloc /* * override add: */ --(void) addChild:(CCMenuItem*)child z:(int)z tag:(int) aTag +-(void) addChild:(CCMenuItem*)child z:(NSInteger)z tag:(NSInteger) aTag { NSAssert( [child isKindOfClass:[CCMenuItem class]], @"Menu only supports MenuItem objects as children"); [super addChild:child z:z tag:aTag]; @@ -132,35 +144,51 @@ - (void) onExit { if(state_ == kCCMenuStateTrackingTouch) { - [selectedItem_ unselected]; + [selectedItem_ unselected]; state_ = kCCMenuStateWaiting; selectedItem_ = nil; } [super onExit]; } - -#pragma mark Menu - Touches -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#pragma mark Menu - Events + +-(void) setHandlerPriority:(NSInteger)newPriority +{ +#ifdef __CC_PLATFORM_IOS + CCTouchDispatcher *dispatcher = [[CCDirector sharedDirector] touchDispatcher]; + [dispatcher setPriority:newPriority forDelegate:self]; + +#elif defined(__CC_PLATFORM_MAC) + CCEventDispatcher *dispatcher = [[CCDirector sharedDirector] eventDispatcher]; + [dispatcher removeMouseDelegate:self]; + [dispatcher addMouseDelegate:self priority:newPriority]; +#endif +} + +#pragma mark Menu - Events Touches + +#ifdef __CC_PLATFORM_IOS -(void) registerWithTouchDispatcher { - [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:kCCMenuTouchPriority swallowsTouches:YES]; + CCDirector *director = [CCDirector sharedDirector]; + [[director touchDispatcher] addTargetedDelegate:self priority:kCCMenuHandlerPriority swallowsTouches:YES]; } -(CCMenuItem *) itemForTouch: (UITouch *) touch { CGPoint touchLocation = [touch locationInView: [touch view]]; touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation]; - + CCMenuItem* item; CCARRAY_FOREACH(children_, item){ // ignore invisible and disabled items: issue #779, #866 if ( [item visible] && [item isEnabled] ) { - + CGPoint local = [item convertToNodeSpace:touchLocation]; CGRect r = [item rect]; r.origin = CGPointZero; - + if( CGRectContainsPoint( r, local ) ) return item; } @@ -170,12 +198,16 @@ -(CCMenuItem *) itemForTouch: (UITouch *) touch -(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { - if( state_ != kCCMenuStateWaiting || !visible_ ) + if( state_ != kCCMenuStateWaiting || !visible_ || ! enabled_) return NO; - + + for( CCNode *c = self.parent; c != nil; c = c.parent ) + if( c.visible == NO ) + return NO; + selectedItem_ = [self itemForTouch:touch]; [selectedItem_ selected]; - + if( selectedItem_ ) { state_ = kCCMenuStateTrackingTouch; return YES; @@ -186,28 +218,28 @@ -(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event -(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { NSAssert(state_ == kCCMenuStateTrackingTouch, @"[Menu ccTouchEnded] -- invalid state"); - + [selectedItem_ unselected]; [selectedItem_ activate]; - + state_ = kCCMenuStateWaiting; } -(void) ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event { NSAssert(state_ == kCCMenuStateTrackingTouch, @"[Menu ccTouchCancelled] -- invalid state"); - + [selectedItem_ unselected]; - + state_ = kCCMenuStateWaiting; } -(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event { NSAssert(state_ == kCCMenuStateTrackingTouch, @"[Menu ccTouchMoved] -- invalid state"); - + CCMenuItem *currentItem = [self itemForTouch:touch]; - + if (currentItem != selectedItem_) { [selectedItem_ unselected]; selectedItem_ = currentItem; @@ -215,29 +247,29 @@ -(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event } } -#pragma mark Menu - Mouse +#pragma mark Menu - Events Mouse -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) -(NSInteger) mouseDelegatePriority { - return NSIntegerMin+1; + return kCCMenuHandlerPriority+1; } -(CCMenuItem *) itemForMouseEvent: (NSEvent *) event { - CGPoint location = [(CCDirectorMac*)[CCDirector sharedDirector] convertEventToGL:event]; - + CGPoint location = [[CCDirector sharedDirector] convertEventToGL:event]; + CCMenuItem* item; CCARRAY_FOREACH(children_, item){ // ignore invisible and disabled items: issue #779, #866 if ( [item visible] && [item isEnabled] ) { - + CGPoint local = [item convertToNodeSpace:location]; - + CGRect r = [item rect]; r.origin = CGPointZero; - + if( CGRectContainsPoint( r, local ) ) return item; } @@ -246,24 +278,27 @@ -(CCMenuItem *) itemForMouseEvent: (NSEvent *) event } -(BOOL) ccMouseUp:(NSEvent *)event -{ - if( selectedItem_ ) { - [selectedItem_ unselected]; - [selectedItem_ activate]; - +{ + if( ! visible_ || ! enabled_) + return NO; + + if(state_ == kCCMenuStateTrackingTouch) { + if( selectedItem_ ) { + [selectedItem_ unselected]; + [selectedItem_ activate]; + } state_ = kCCMenuStateWaiting; return YES; } - return NO; } -(BOOL) ccMouseDown:(NSEvent *)event { - if( ! visible_ ) + if( ! visible_ || ! enabled_) return NO; - + selectedItem_ = [self itemForMouseEvent:event]; [selectedItem_ selected]; @@ -272,22 +307,25 @@ -(BOOL) ccMouseDown:(NSEvent *)event return YES; } - return NO; + return NO; } -(BOOL) ccMouseDragged:(NSEvent *)event { - CCMenuItem *currentItem = [self itemForMouseEvent:event]; - - if (currentItem != selectedItem_) { - [selectedItem_ unselected]; - selectedItem_ = currentItem; - [selectedItem_ selected]; - } - - // swallows event ? - if( currentItem && state_ == kCCMenuStateTrackingTouch ) + if( ! visible_ || ! enabled_) + return NO; + + if(state_ == kCCMenuStateTrackingTouch) { + CCMenuItem *currentItem = [self itemForMouseEvent:event]; + + if (currentItem != selectedItem_) { + [selectedItem_ unselected]; + selectedItem_ = currentItem; + [selectedItem_ selected]; + } + return YES; + } return NO; } @@ -296,18 +334,18 @@ -(BOOL) ccMouseDragged:(NSEvent *)event #pragma mark Menu - Alignment -(void) alignItemsVertically { - return [self alignItemsVerticallyWithPadding:kDefaultPadding]; + [self alignItemsVerticallyWithPadding:kDefaultPadding]; } -(void) alignItemsVerticallyWithPadding:(float)padding { float height = -padding; - + CCMenuItem *item; CCARRAY_FOREACH(children_, item) height += item.contentSize.height * item.scaleY + padding; float y = height / 2.0f; - + CCARRAY_FOREACH(children_, item) { CGSize itemSize = item.contentSize; [item setPosition:ccp(0, y - itemSize.height * item.scaleY / 2.0f)]; @@ -317,19 +355,19 @@ -(void) alignItemsVerticallyWithPadding:(float)padding -(void) alignItemsHorizontally { - return [self alignItemsHorizontallyWithPadding:kDefaultPadding]; + [self alignItemsHorizontallyWithPadding:kDefaultPadding]; } -(void) alignItemsHorizontallyWithPadding:(float)padding { - + float width = -padding; CCMenuItem *item; CCARRAY_FOREACH(children_, item) width += item.contentSize.width * item.scaleX + padding; float x = -width / 2.0f; - + CCARRAY_FOREACH(children_, item){ CGSize itemSize = item.contentSize; [item setPosition:ccp(x + itemSize.width * item.scaleX / 2.0f, 0)]; @@ -341,9 +379,9 @@ -(void) alignItemsInColumns: (NSNumber *) columns, ... { va_list args; va_start(args, columns); - + [self alignItemsInColumns:columns vaList:args]; - + va_end(args); } @@ -355,19 +393,19 @@ -(void) alignItemsInColumns: (NSNumber *) columns vaList: (va_list) args [rows addObject:columns]; columns = va_arg(args, NSNumber*); } - + int height = -5; NSUInteger row = 0, rowHeight = 0, columnsOccupied = 0, rowColumns; CCMenuItem *item; CCARRAY_FOREACH(children_, item){ NSAssert( row < [rows count], @"Too many menu items for the amount of rows/columns."); - + rowColumns = [(NSNumber *) [rows objectAtIndex:row] unsignedIntegerValue]; NSAssert( rowColumns, @"Can't have zero columns on a row"); - + rowHeight = fmaxf(rowHeight, item.contentSize.height); ++columnsOccupied; - + if(columnsOccupied >= rowColumns) { height += rowHeight + 5; @@ -379,7 +417,7 @@ -(void) alignItemsInColumns: (NSNumber *) columns vaList: (va_list) args NSAssert( !columnsOccupied, @"Too many rows/columns for available menu items." ); CGSize winSize = [[CCDirector sharedDirector] winSize]; - + row = 0; rowHeight = 0; rowColumns = 0; float w, x, y = height / 2; CCARRAY_FOREACH(children_, item) { @@ -393,13 +431,13 @@ -(void) alignItemsInColumns: (NSNumber *) columns vaList: (va_list) args rowHeight = fmaxf(rowHeight, itemSize.height); [item setPosition:ccp(x - winSize.width / 2, y - itemSize.height / 2)]; - - x += w + 10; + + x += w; ++columnsOccupied; - + if(columnsOccupied >= rowColumns) { y -= rowHeight + 5; - + columnsOccupied = 0; rowColumns = 0; rowHeight = 0; @@ -414,9 +452,9 @@ -(void) alignItemsInRows: (NSNumber *) rows, ... { va_list args; va_start(args, rows); - + [self alignItemsInRows:rows vaList:args]; - + va_end(args); } @@ -431,26 +469,26 @@ -(void) alignItemsInRows: (NSNumber *) rows vaList: (va_list) args NSMutableArray *columnWidths = [[NSMutableArray alloc] init]; NSMutableArray *columnHeights = [[NSMutableArray alloc] init]; - + int width = -10, columnHeight = -5; NSUInteger column = 0, columnWidth = 0, rowsOccupied = 0, columnRows; CCMenuItem *item; CCARRAY_FOREACH(children_, item){ NSAssert( column < [columns count], @"Too many menu items for the amount of rows/columns."); - + columnRows = [(NSNumber *) [columns objectAtIndex:column] unsignedIntegerValue]; NSAssert( columnRows, @"Can't have zero rows on a column"); - + CGSize itemSize = item.contentSize; columnWidth = fmaxf(columnWidth, itemSize.width); columnHeight += itemSize.height + 5; ++rowsOccupied; - + if(rowsOccupied >= columnRows) { [columnWidths addObject:[NSNumber numberWithUnsignedInteger:columnWidth]]; [columnHeights addObject:[NSNumber numberWithUnsignedInteger:columnHeight]]; width += columnWidth + 10; - + rowsOccupied = 0; columnWidth = 0; columnHeight = -5; @@ -458,36 +496,36 @@ -(void) alignItemsInRows: (NSNumber *) rows vaList: (va_list) args } } NSAssert( !rowsOccupied, @"Too many rows/columns for available menu items."); - + CGSize winSize = [[CCDirector sharedDirector] winSize]; - + column = 0; columnWidth = 0; columnRows = 0; float x = -width / 2, y; - + CCARRAY_FOREACH(children_, item){ if(columnRows == 0) { columnRows = [(NSNumber *) [columns objectAtIndex:column] unsignedIntegerValue]; y = ([(NSNumber *) [columnHeights objectAtIndex:column] intValue] + winSize.height) / 2; } - + CGSize itemSize = item.contentSize; columnWidth = fmaxf(columnWidth, itemSize.width); [item setPosition:ccp(x + [(NSNumber *) [columnWidths objectAtIndex:column] unsignedIntegerValue] / 2, y - winSize.height / 2)]; - + y -= itemSize.height + 10; ++rowsOccupied; - + if(rowsOccupied >= columnRows) { x += columnWidth + 5; - + rowsOccupied = 0; columnRows = 0; columnWidth = 0; ++column; } } - + [columns release]; [columnWidths release]; [columnHeights release]; @@ -499,7 +537,7 @@ -(void) alignItemsInRows: (NSNumber *) rows vaList: (va_list) args - (void) setOpacity:(GLubyte)newOpacity { opacity_ = newOpacity; - + id item; CCARRAY_FOREACH(children_, item) [item setOpacity:opacity_]; @@ -508,7 +546,7 @@ - (void) setOpacity:(GLubyte)newOpacity -(void) setColor:(ccColor3B)color { color_ = color; - + id item; CCARRAY_FOREACH(children_, item) [item setColor:color_]; diff --git a/Example/libs/cocos2d/CCMenuItem.h b/Example/libs/cocos2d/CCMenuItem.h index ca07b5e..6336534 100644 --- a/Example/libs/cocos2d/CCMenuItem.h +++ b/Example/libs/cocos2d/CCMenuItem.h @@ -1,18 +1,19 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2008-2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,27 +24,25 @@ * */ -#import "CCBlockSupport.h" - #import "CCNode.h" #import "CCProtocols.h" @class CCSprite; +@class CCSpriteFrame; -#define kItemSize 32 +#define kCCItemSize 32 +#pragma mark - +#pragma mark CCMenuItem /** CCMenuItem base class * * Subclass CCMenuItem (or any subclass) to create your custom CCMenuItem objects. */ @interface CCMenuItem : CCNode { - NSInvocation *invocation; -#if NS_BLOCKS_AVAILABLE // used for menu items using a block void (^block_)(id sender); -#endif - + BOOL isEnabled_; BOOL isSelected_; } @@ -53,23 +52,24 @@ */ @property (nonatomic,readonly) BOOL isSelected; -/** Creates a CCMenuItem with a target/selector */ +/** Creates a CCMenuItem with a target/selector. + target/selector will be implemented using blocks. + "target" won't be retained. + */ +(id) itemWithTarget:(id)target selector:(SEL)selector; -/** Initializes a CCMenuItem with a target/selector */ --(id) initWithTarget:(id)target selector:(SEL)selector; - -#if NS_BLOCKS_AVAILABLE /** Creates a CCMenuItem with the specified block. The block will be "copied". */ +(id) itemWithBlock:(void(^)(id sender))block; +/** Initializes a CCMenuItem with a target/selector */ +-(id) initWithTarget:(id)target selector:(SEL)selector; + /** Initializes a CCMenuItem with the specified block. The block will be "copied". */ -(id) initWithBlock:(void(^)(id sender))block; -#endif /** Returns the outside box in points */ -(CGRect) rect; @@ -85,11 +85,30 @@ /** Enable or disabled the CCMenuItem */ -(void) setIsEnabled:(BOOL)enabled; + /** Returns whether or not the CCMenuItem is enabled */ -(BOOL) isEnabled; + +/** Sets the block that is called when the item is tapped. + The block will be "copied". + */ +-(void) setBlock:(void(^)(id sender))block; + +/** Sets the target and selector that is called when the item is tapped. + target/selector will be implemented using blocks. + "target" won't be retained. + */ +-(void) setTarget:(id)target selector:(SEL)selector; + +/** cleanup event. It will release the block and call [super cleanup] */ +-(void) cleanup; + @end -/** An abstract class for "label" CCMenuItemLabel items +#pragma mark - +#pragma mark CCMenuItemLabel + +/** An abstract class for "label" CCMenuItemLabel items Any CCNode that supports the CCLabelProtocol protocol can be added. Supported nodes: - CCLabelBMFont @@ -110,23 +129,30 @@ /** Label that is rendered. It can be any CCNode that implements the CCLabelProtocol */ @property (nonatomic,readwrite,assign) CCNode* label; -/** creates a CCMenuItemLabel with a Label, target and selector */ -+(id) itemWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector; +/** creates a CCMenuItemLabel with a Label. Block will benil */ ++(id) itemWithLabel:(CCNode*)label; -/** initializes a CCMenuItemLabel with a Label, target and selector */ --(id) initWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector; +/** creates a CCMenuItemLabel with a Label, target and selector. + The "target" won't be retained. + */ ++(id) itemWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector; -#if NS_BLOCKS_AVAILABLE /** creates a CCMenuItemLabel with a Label and a block to execute. The block will be "copied". */ +(id) itemWithLabel:(CCNode*)label block:(void(^)(id sender))block; +/** initializes a CCMenuItemLabel with a Label, target and selector. + Internally it will create a block that executes the target/selector. + The "target" won't be retained. + */ +-(id) initWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector; + /** initializes a CCMenuItemLabel with a Label and a block to execute. The block will be "copied". + This is the designated initializer. */ -(id) initWithLabel:(CCNode*)label block:(void(^)(id sender))block; -#endif /** sets a new string to the inner label */ -(void) setString:(NSString*)label; @@ -137,82 +163,110 @@ -(void) setIsEnabled: (BOOL)enabled; @end +#pragma mark - +#pragma mark CCMenuItemAtlasFont + /** A CCMenuItemAtlasFont - Helper class that creates a MenuItemLabel class with a LabelAtlas + Helper class that creates a CCMenuItemLabel class with a CCLabelAtlas */ @interface CCMenuItemAtlasFont : CCMenuItemLabel { } /** creates a menu item from a string and atlas with a target/selector */ -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap; ++(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap; -/** creates a menu item from a string and atlas. Use it with MenuItemToggle */ -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb; +/** creates a menu item from a string and atlas. Use it with CCMenuItemToggle. + The "target" won't be retained. + */ ++(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id)target selector:(SEL)selector; -/** initializes a menu item from a string and atlas with a target/selector */ --(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb; +/** initializes a menu item from a string and atlas with a target/selector. + The "target" won't be retained. + */ +-(id) initWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id)target selector:(SEL)selector; -#if NS_BLOCKS_AVAILABLE -/** creates a menu item from a string and atlas. Use it with MenuItemToggle. +/** creates a menu item from a string and atlas. Use it with CCMenuItemToggle. The block will be "copied". */ -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block; ++(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block; /** initializes a menu item from a string and atlas with a block. The block will be "copied". */ --(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block; -#endif +-(id) initWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block; @end +#pragma mark - +#pragma mark CCMenuItemFont + /** A CCMenuItemFont Helper class that creates a CCMenuItemLabel class with a Label */ @interface CCMenuItemFont : CCMenuItemLabel { + NSUInteger fontSize_; + NSString *fontName_; } -/** set font size */ -+(void) setFontSize: (int) s; +/** set default font size */ ++(void) setFontSize: (NSUInteger) s; -/** get font size */ -+(int) fontSize; +/** get default font size */ ++(NSUInteger) fontSize; -/** set the font name */ +/** set default font name */ +(void) setFontName: (NSString*) n; -/** get the font name */ +/** get default font name */ +(NSString*) fontName; /** creates a menu item from a string without target/selector. To be used with CCMenuItemToggle */ -+(id) itemFromString: (NSString*) value; - -/** creates a menu item from a string with a target/selector */ -+(id) itemFromString: (NSString*) value target:(id) r selector:(SEL) s; ++(id) itemWithString: (NSString*) value; -/** initializes a menu item from a string with a target/selector */ --(id) initFromString: (NSString*) value target:(id) r selector:(SEL) s; +/** creates a menu item from a string with a target/selector. + The "target" won't be retained. + */ ++(id) itemWithString: (NSString*) value target:(id) r selector:(SEL) s; -#if NS_BLOCKS_AVAILABLE /** creates a menu item from a string with the specified block. The block will be "copied". */ -+(id) itemFromString: (NSString*) value block:(void(^)(id sender))block; ++(id) itemWithString: (NSString*) value block:(void(^)(id sender))block; + +/** initializes a menu item from a string with a target/selector + The "target" won't be retained. + */ +-(id) initWithString: (NSString*) value target:(id) r selector:(SEL) s; + +/** set font size */ +-(void) setFontSize: (NSUInteger) s; + +/** get font size */ +-(NSUInteger) fontSize; + +/** set the font name */ +-(void) setFontName: (NSString*) n; + +/** get the font name */ +-(NSString*) fontName; /** initializes a menu item from a string with the specified block. The block will be "copied". */ --(id) initFromString: (NSString*) value block:(void(^)(id sender))block; -#endif +-(id) initWithString: (NSString*) value block:(void(^)(id sender))block; + @end +#pragma mark - +#pragma mark CCMenuItemSprite + /** CCMenuItemSprite accepts CCNode objects as items. The images has 3 different states: - unselected image - selected image - disabled image - + @since v0.8.0 */ @interface CCMenuItemSprite : CCMenuItem @@ -230,37 +284,48 @@ @property (nonatomic,readwrite,assign) CCNode *disabledImage; /** creates a menu item with a normal and selected image*/ -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite; -/** creates a menu item with a normal and selected image with target/selector */ -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector; -/** creates a menu item with a normal,selected and disabled image with target/selector */ -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector; -/** initializes a menu item with a normal, selected and disabled image with target/selector */ --(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector; ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite; +/** creates a menu item with a normal and selected image with target/selector. + The "target" won't be retained. + */ ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector; + +/** creates a menu item with a normal,selected and disabled image with target/selector. + The "target" won't be retained. + */ ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector; -#if NS_BLOCKS_AVAILABLE /** creates a menu item with a normal and selected image with a block. The block will be "copied". */ -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block; ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block; + /** creates a menu item with a normal,selected and disabled image with a block. The block will be "copied". */ -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block; ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block; + +/** initializes a menu item with a normal, selected and disabled image with target/selector. + The "target" won't be retained. + */ +-(id) initWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector; + /** initializes a menu item with a normal, selected and disabled image with a block. The block will be "copied". */ --(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block; -#endif +-(id) initWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block; @end +#pragma mark - +#pragma mark CCMenuItemImage + /** CCMenuItemImage accepts images as items. The images has 3 different states: - unselected image - selected image - disabled image - + For best results try that all images are of the same size */ @interface CCMenuItemImage : CCMenuItemSprite @@ -268,33 +333,52 @@ } /** creates a menu item with a normal and selected image*/ -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2; ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2; + /** creates a menu item with a normal and selected image with target/selector */ -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) r selector:(SEL) s; -/** creates a menu item with a normal,selected and disabled image with target/selector */ -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s; -/** initializes a menu item with a normal, selected and disabled image with target/selector */ --(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s; -#if NS_BLOCKS_AVAILABLE ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) r selector:(SEL) s; + +/** creates a menu item with a normal,selected and disabled image with target/selector. + The "target" won't be retained. + */ ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s; + /** creates a menu item with a normal and selected image with a block. The block will be "copied". */ -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block; ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block; + /** creates a menu item with a normal,selected and disabled image with a block. The block will be "copied". */ -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block; ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block; + +/** initializes a menu item with a normal, selected and disabled image with target/selector. + The "target" won't be retained. + */ +-(id) initWithNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s; + /** initializes a menu item with a normal, selected and disabled image with a block. The block will be "copied". */ --(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block; -#endif -@end +-(id) initWithNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block; + +/** sets the sprite frame for the normal image */ +- (void) setNormalSpriteFrame:(CCSpriteFrame*)frame; + +/** sets the sprite frame for the selected image */ +- (void) setSelectedSpriteFrame:(CCSpriteFrame*)frame; +/** sets the sprite frame for the disabled image */ +- (void) setDisabledSpriteFrame:(CCSpriteFrame*)frame; + +@end +#pragma mark - +#pragma mark CCMenuItemToggle /** A CCMenuItemToggle - A simple container class that "toggles" it's inner items + A simple container class that "toggles" its inner items The inner itmes can be any MenuItem */ @interface CCMenuItemToggle : CCMenuItem @@ -318,22 +402,20 @@ @property (nonatomic,readwrite,retain) NSMutableArray *subItems; /** creates a menu item from a list of items with a target/selector */ -+(id) itemWithTarget:(id)t selector:(SEL)s items:(CCMenuItem*) item, ... NS_REQUIRES_NIL_TERMINATION; ++(id) itemWithTarget:(id)target selector:(SEL)selector items:(CCMenuItem*) item, ... NS_REQUIRES_NIL_TERMINATION; -/** initializes a menu item from a list of items with a target selector */ --(id) initWithTarget:(id)t selector:(SEL)s items:(CCMenuItem*) item vaList:(va_list) args; - -#if NS_BLOCKS_AVAILABLE /** creates a menu item from a list of items and executes the given block when the item is selected. The block will be "copied". */ -+(id) itemWithBlock:(void(^)(id sender))block items:(CCMenuItem*)item, ... NS_REQUIRES_NIL_TERMINATION; ++(id) itemWithItems:(NSArray*)arrayOfItems block:(void(^)(id sender))block; + +/** initializes a menu item from a list of items with a target selector */ +-(id) initWithTarget:(id)target selector:(SEL)selector items:(CCMenuItem*) item vaList:(va_list) args; /** initializes a menu item from a list of items with a block. The block will be "copied". */ --(id) initWithBlock:(void (^)(id))block items:(CCMenuItem*)item vaList:(va_list)args; -#endif +-(id) initWithItems:(NSArray*)arrayOfItems block:(void (^)(id))block; /** return the selected item */ -(CCMenuItem*) selectedItem; diff --git a/Example/libs/cocos2d/CCMenuItem.m b/Example/libs/cocos2d/CCMenuItem.m index 304702e..de7fe40 100644 --- a/Example/libs/cocos2d/CCMenuItem.m +++ b/Example/libs/cocos2d/CCMenuItem.m @@ -1,18 +1,19 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2008-2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,18 +31,13 @@ #import "CCSprite.h" #import "Support/CGPointExtension.h" -static int _fontSize = kItemSize; +static NSUInteger _fontSize = kCCItemSize; static NSString *_fontName = @"Marker Felt"; static BOOL _fontNameRelease = NO; -enum { - kCurrentItem = 0xc0c05001, -}; - -enum { - kZoomActionTag = 0xc0c05002, -}; +const NSInteger kCCCurrentItemTag = 0xc0c05001; +const NSInteger kCCZoomActionTag = 0xc0c05002; #pragma mark - @@ -50,69 +46,61 @@ @implementation CCMenuItem @synthesize isSelected=isSelected_; ++(id) itemWithTarget:(id) r selector:(SEL) s +{ + return [[[self alloc] initWithTarget:r selector:s] autorelease]; +} + ++(id) itemWithBlock:(void(^)(id sender))block { + return [[[self alloc] initWithBlock:block] autorelease]; +} + -(id) init { - NSAssert(NO, @"MenuItemInit: Init not supported."); - [self release]; - return nil; + return [self initWithBlock:nil]; } -+(id) itemWithTarget:(id) r selector:(SEL) s +-(id) initWithTarget:(id)target selector:(SEL)selector { - return [[[self alloc] initWithTarget:r selector:s] autorelease]; + // avoid retain cycle + __block id t = target; + return [self initWithBlock:^(id sender) { + + [t performSelector:selector withObject:sender]; + }]; + } --(id) initWithTarget:(id) rec selector:(SEL) cb + +// Designated initializer +-(id) initWithBlock:(void (^)(id))block { if((self=[super init]) ) { - + + if( block ) + block_ = [block copy]; + anchorPoint_ = ccp(0.5f, 0.5f); - NSMethodSignature * sig = nil; - - if( rec && cb ) { - sig = [rec methodSignatureForSelector:cb]; - - invocation = nil; - invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setTarget:rec]; - [invocation setSelector:cb]; -#if NS_BLOCKS_AVAILABLE - if ([sig numberOfArguments] == 3) -#endif - [invocation setArgument:&self atIndex:2]; - - [invocation retain]; - } - isEnabled_ = YES; isSelected_ = NO; + } - return self; } -#if NS_BLOCKS_AVAILABLE - -+(id) itemWithBlock:(void(^)(id sender))block { - return [[[self alloc] initWithBlock:block] autorelease]; -} +-(void) dealloc +{ + [block_ release]; --(id) initWithBlock:(void(^)(id sender))block { - block_ = [block copy]; - return [self initWithTarget:block_ selector:@selector(ccCallbackBlockWithSender:)]; + [super dealloc]; } -#endif // NS_BLOCKS_AVAILABLE - --(void) dealloc +-(void) cleanup { - [invocation release]; - -#if NS_BLOCKS_AVAILABLE [block_ release]; -#endif - - [super dealloc]; + block_ = nil; + + [super cleanup]; } -(void) selected @@ -127,8 +115,8 @@ -(void) unselected -(void) activate { - if(isEnabled_) - [invocation invoke]; + if(isEnabled_&& block_ ) + block_(self); } -(void) setIsEnabled: (BOOL)enabled @@ -145,7 +133,21 @@ -(CGRect) rect { return CGRectMake( position_.x - contentSize_.width*anchorPoint_.x, position_.y - contentSize_.height*anchorPoint_.y, - contentSize_.width, contentSize_.height); + contentSize_.width, contentSize_.height); +} + +-(void) setBlock:(void(^)(id sender))block +{ + [block_ release]; + block_ = [block copy]; +} + +-(void) setTarget:(id)target selector:(SEL)selector +{ + [self setBlock:^(id sender) { + + [target performSelector:selector withObject:sender]; + }]; } @end @@ -158,36 +160,48 @@ @implementation CCMenuItemLabel @synthesize disabledColor = disabledColor_; ++(id) itemWithLabel:(CCNode*)label +{ + return [[[self alloc] initWithLabel:label block:nil] autorelease]; +} + +(id) itemWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector { return [[[self alloc] initWithLabel:label target:target selector:selector] autorelease]; } ++(id) itemWithLabel:(CCNode*)label block:(void(^)(id sender))block { + return [[[self alloc] initWithLabel:label block:block] autorelease]; +} + + -(id) initWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector { - if( (self=[super initWithTarget:target selector:selector]) ) { + // avoid retain cycle + __block id t = target; + + self = [self initWithLabel:label block: ^(id sender) { + [t performSelector:selector withObject:sender]; + } + ]; + return self; +} + +// +// Designated initializer +// +-(id) initWithLabel:(CCNode *)label block:(void (^)(id))block +{ + if( (self=[self initWithBlock:block]) ) { originalScale_ = 1; colorBackup = ccWHITE; disabledColor_ = ccc3( 126,126,126); self.label = label; - } - return self; -} - -#if NS_BLOCKS_AVAILABLE -+(id) itemWithLabel:(CCNode*)label block:(void(^)(id sender))block { - return [[[self alloc] initWithLabel:label block:block] autorelease]; -} - --(id) initWithLabel:(CCNode*)label block:(void(^)(id sender))block { - block_ = [block copy]; - return [self initWithLabel:label target:block_ selector:@selector(ccCallbackBlockWithSender:)]; + return self; } -#endif // NS_BLOCKS_AVAILABLE - -(CCNode*) label { return label_; @@ -197,7 +211,7 @@ -(void) setLabel:(CCNode*) label if( label != label_ ) { [self removeChild:label_ cleanup:YES]; [self addChild:label]; - + label_ = label; label_.anchorPoint = ccp(0,0); @@ -214,9 +228,9 @@ -(void) setString:(NSString *)string -(void) activate { if(isEnabled_) { [self stopAllActions]; - + self.scale = originalScale_; - + [super activate]; } } @@ -224,12 +238,17 @@ -(void) activate { -(void) selected { // subclass to change the default action - if(isEnabled_) { + if(isEnabled_) { [super selected]; - [self stopActionByTag:kZoomActionTag]; - originalScale_ = self.scale; + + CCAction *action = [self getActionByTag:kCCZoomActionTag]; + if( action ) + [self stopAction:action]; + else + originalScale_ = self.scale; + CCAction *zoomAction = [CCScaleTo actionWithDuration:0.1f scale:originalScale_ * 1.2f]; - zoomAction.tag = kZoomActionTag; + zoomAction.tag = kCCZoomActionTag; [self runAction:zoomAction]; } } @@ -239,9 +258,9 @@ -(void) unselected // subclass to change the default action if(isEnabled_) { [super unselected]; - [self stopActionByTag:kZoomActionTag]; + [self stopActionByTag:kCCZoomActionTag]; CCAction *zoomAction = [CCScaleTo actionWithDuration:0.1f scale:originalScale_]; - zoomAction.tag = kZoomActionTag; + zoomAction.tag = kCCZoomActionTag; [self runAction:zoomAction]; } } @@ -256,7 +275,7 @@ -(void) setIsEnabled: (BOOL)enabled else [label_ setColor:colorBackup]; } - + [super setIsEnabled:enabled]; } @@ -278,45 +297,51 @@ -(ccColor3B) color } @end -#pragma mark - -#pragma mark CCMenuItemAtlasFont +#pragma mark - CCMenuItemAtlasFont @implementation CCMenuItemAtlasFont -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap ++(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap { - return [CCMenuItemAtlasFont itemFromString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:nil selector:nil]; + return [CCMenuItemAtlasFont itemWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:nil selector:nil]; } -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb ++(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id)target selector:(SEL)selector { - return [[[self alloc] initFromString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:rec selector:cb] autorelease]; + return [[[self alloc] initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:target selector:selector] autorelease]; } --(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb ++(id) itemWithString:(NSString*)value charMapFile:(NSString*)charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block { - NSAssert( [value length] != 0, @"value length must be greater than 0"); - - CCLabelAtlas *label = [[CCLabelAtlas alloc] initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap]; - [label autorelease]; - - if((self=[super initWithLabel:label target:rec selector:cb]) ) { - // do something ? - } - - return self; + return [[[self alloc] initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap block:block] autorelease]; } -#if NS_BLOCKS_AVAILABLE -+(id) itemFromString:(NSString*)value charMapFile:(NSString*)charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block { - return [[[self alloc] initFromString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap block:block] autorelease]; +-(id) initWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id)target selector:(SEL)selector +{ + // avoid retain cycle + __block id t = target; + + return [self initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap block:^(id sender) { + [t performSelector:selector withObject:sender]; + } ]; } --(id) initFromString:(NSString*)value charMapFile:(NSString*)charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block { - block_ = [block copy]; - return [self initFromString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:block_ selector:@selector(ccCallbackBlockWithSender:)]; +// +// Designated initializer +// +-(id) initWithString:(NSString*)value charMapFile:(NSString*)charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block +{ + NSAssert( [value length] > 0, @"value length must be greater than 0"); + + CCLabelAtlas *label = [[CCLabelAtlas alloc] initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap]; + + id ret = [self initWithLabel:label block:block]; + + [label release]; + + return ret; + } -#endif // NS_BLOCKS_AVAILABLE -(void) dealloc { @@ -325,17 +350,16 @@ -(void) dealloc @end -#pragma mark - -#pragma mark CCMenuItemFont +#pragma mark - CCMenuItemFont @implementation CCMenuItemFont -+(void) setFontSize: (int) s ++(void) setFontSize: (NSUInteger) s { _fontSize = s; } -+(int) fontSize ++(NSUInteger) fontSize { return _fontSize; } @@ -344,7 +368,7 @@ +(void) setFontName: (NSString*) n { if( _fontNameRelease ) [_fontName release]; - + _fontName = [n retain]; _fontNameRelease = YES; } @@ -354,99 +378,152 @@ +(NSString*) fontName return _fontName; } -+(id) itemFromString: (NSString*) value target:(id) r selector:(SEL) s ++(id) itemWithString: (NSString*) value target:(id) r selector:(SEL) s { - return [[[self alloc] initFromString: value target:r selector:s] autorelease]; + return [[[self alloc] initWithString: value target:r selector:s] autorelease]; } -+(id) itemFromString: (NSString*) value ++(id) itemWithString: (NSString*) value { - return [[[self alloc] initFromString: value target:nil selector:nil] autorelease]; + return [[[self alloc] initWithString: value target:nil selector:nil] autorelease]; } --(id) initFromString: (NSString*) value target:(id) rec selector:(SEL) cb ++(id) itemWithString: (NSString*) value block:(void(^)(id sender))block { - NSAssert( [value length] != 0, @"Value length must be greater than 0"); - - CCLabelTTF *label = [CCLabelTTF labelWithString:value fontName:_fontName fontSize:_fontSize]; + return [[[self alloc] initWithString:value block:block] autorelease]; +} + +-(id) initWithString: (NSString*) value target:(id)target selector:(SEL)selector +{ + // avoid retain cycle + __block id t = target; + + return [self initWithString:value block:^(id sender) { + [t performSelector:selector withObject:sender]; + }]; +} + +// +// Designated initializer +// +-(id) initWithString: (NSString*)string block:(void(^)(id sender))block +{ + NSAssert( [string length] > 0, @"Value length must be greater than 0"); + + fontName_ = [_fontName copy]; + fontSize_ = _fontSize; - if((self=[super initWithLabel:label target:rec selector:cb]) ) { + CCLabelTTF *label = [CCLabelTTF labelWithString:string fontName:fontName_ fontSize:fontSize_]; + + if((self=[super initWithLabel:label block:block]) ) { // do something ? } - + return self; } -#if NS_BLOCKS_AVAILABLE -+(id) itemFromString: (NSString*) value block:(void(^)(id sender))block { - return [[[self alloc] initFromString:value block:block] autorelease]; +-(void) recreateLabel +{ + CCLabelTTF *label = [[CCLabelTTF alloc] initWithString:[label_ string] fontName:fontName_ fontSize:fontSize_]; + self.label = label; + [label release]; +} + +-(void) setFontSize: (NSUInteger) size +{ + fontSize_ = size; + [self recreateLabel]; +} + +-(NSUInteger) fontSize +{ + return fontSize_; } --(id) initFromString: (NSString*) value block:(void(^)(id sender))block { - block_ = [block copy]; - return [self initFromString:value target:block_ selector:@selector(ccCallbackBlockWithSender:)]; +-(void) setFontName: (NSString*) fontName +{ + if (fontName_) + [fontName_ release]; + + fontName_ = [fontName copy]; + [self recreateLabel]; } -#endif // NS_BLOCKS_AVAILABLE +-(NSString*) fontName +{ + return fontName_; +} @end -#pragma mark - -#pragma mark CCMenuItemSprite +#pragma mark - CCMenuItemSprite + @implementation CCMenuItemSprite @synthesize normalImage=normalImage_, selectedImage=selectedImage_, disabledImage=disabledImage_; -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite { - return [self itemFromNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:nil target:nil selector:nil]; + return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:nil target:nil selector:nil]; } -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector + ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector { - return [self itemFromNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:nil target:target selector:selector]; + return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:nil target:target selector:selector]; } -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector + ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector { - return [[[self alloc] initFromNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite target:target selector:selector] autorelease]; + return [[[self alloc] initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite target:target selector:selector] autorelease]; } --(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector + ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block { - if( (self=[super initWithTarget:target selector:selector]) ) { - - self.normalImage = normalSprite; - self.selectedImage = selectedSprite; - self.disabledImage = disabledSprite; - - [self setContentSize: [normalImage_ contentSize]]; - } - return self; + return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:nil block:block]; } -#if NS_BLOCKS_AVAILABLE -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block { - return [self itemFromNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:nil block:block]; ++(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block +{ + return [[[self alloc] initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:block] autorelease]; } -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block { - return [[[self alloc] initFromNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:block] autorelease]; -} +-(id) initWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector +{ + // avoid retain cycle + __block id t = target; --(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block { - block_ = [block copy]; - return [self initFromNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite target:block_ selector:@selector(ccCallbackBlockWithSender:)]; + return [self initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:^(id sender) { + [t performSelector:selector withObject:sender]; + } ]; } -#endif // NS_BLOCKS_AVAILABLE +// +// Designated initializer +// +-(id) initWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block +{ + if ( (self = [super initWithBlock:block] ) ) { + + self.normalImage = normalSprite; + self.selectedImage = selectedSprite; + self.disabledImage = disabledSprite; + + [self setContentSize: [normalImage_ contentSize]]; + } + return self; +} -(void) setNormalImage:(CCNode *)image { if( image != normalImage_ ) { image.anchorPoint = ccp(0,0); image.visible = YES; - + [self removeChild:normalImage_ cleanup:YES]; [self addChild:image]; - + normalImage_ = image; + + [self setContentSize: [normalImage_ contentSize]]; } } @@ -455,10 +532,10 @@ -(void) setSelectedImage:(CCNode *)image if( image != selectedImage_ ) { image.anchorPoint = ccp(0,0); image.visible = NO; - + [self removeChild:selectedImage_ cleanup:YES]; [self addChild:image]; - + selectedImage_ = image; } } @@ -468,15 +545,16 @@ -(void) setDisabledImage:(CCNode *)image if( image != disabledImage_ ) { image.anchorPoint = ccp(0,0); image.visible = NO; - + [self removeChild:disabledImage_ cleanup:YES]; [self addChild:image]; - + disabledImage_ = image; } } -#pragma mark CCMenuItemImage - CCRGBAProtocol protocol +#pragma mark CCMenuItemSprite - CCRGBAProtocol protocol + - (void) setOpacity: (GLubyte)opacity { [normalImage_ setOpacity:opacity]; @@ -488,7 +566,7 @@ -(void) setColor:(ccColor3B)color { [normalImage_ setColor:color]; [selectedImage_ setColor:color]; - [disabledImage_ setColor:color]; + [disabledImage_ setColor:color]; } -(GLubyte) opacity @@ -509,12 +587,12 @@ -(void) selected [normalImage_ setVisible:NO]; [selectedImage_ setVisible:YES]; [disabledImage_ setVisible:NO]; - + } else { // there is not selected image - + [normalImage_ setVisible:YES]; [selectedImage_ setVisible:NO]; - [disabledImage_ setVisible:NO]; + [disabledImage_ setVisible:NO]; } } @@ -539,7 +617,7 @@ -(void) setIsEnabled:(BOOL)enabled if( disabledImage_ ) { [normalImage_ setVisible:NO]; [selectedImage_ setVisible:NO]; - [disabledImage_ setVisible:YES]; + [disabledImage_ setVisible:YES]; } else { [normalImage_ setVisible:YES]; [selectedImage_ setVisible:NO]; @@ -550,66 +628,89 @@ -(void) setIsEnabled:(BOOL)enabled @end -#pragma mark - -#pragma mark CCMenuItemImage +#pragma mark - CCMenuItemImage @implementation CCMenuItemImage -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 +{ + return [self itemWithNormalImage:value selectedImage:value2 disabledImage: nil target:nil selector:nil]; +} + ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) t selector:(SEL) s +{ + return [self itemWithNormalImage:value selectedImage:value2 disabledImage: nil target:t selector:s]; +} + ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage: (NSString*) value3 { - return [self itemFromNormalImage:value selectedImage:value2 disabledImage: nil target:nil selector:nil]; + return [[[self alloc] initWithNormalImage:value selectedImage:value2 disabledImage:value3 target:nil selector:nil] autorelease]; } -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) t selector:(SEL) s ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage: (NSString*) value3 target:(id) t selector:(SEL) s { - return [self itemFromNormalImage:value selectedImage:value2 disabledImage: nil target:t selector:s]; + return [[[self alloc] initWithNormalImage:value selectedImage:value2 disabledImage:value3 target:t selector:s] autorelease]; } -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage: (NSString*) value3 ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block { - return [[[self alloc] initFromNormalImage:value selectedImage:value2 disabledImage:value3 target:nil selector:nil] autorelease]; + return [self itemWithNormalImage:value selectedImage:value2 disabledImage:nil block:block]; } -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage: (NSString*) value3 target:(id) t selector:(SEL) s ++(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block { - return [[[self alloc] initFromNormalImage:value selectedImage:value2 disabledImage:value3 target:t selector:s] autorelease]; + return [[[self alloc] initWithNormalImage:value selectedImage:value2 disabledImage:value3 block:block] autorelease]; } --(id) initFromNormalImage: (NSString*) normalI selectedImage:(NSString*)selectedI disabledImage: (NSString*) disabledI target:(id)t selector:(SEL)sel +-(id) initWithNormalImage: (NSString*) normalI selectedImage:(NSString*)selectedI disabledImage: (NSString*) disabledI target:(id)target selector:(SEL)selector +{ + // avoid retain cycle + __block id t = target; + + return [self initWithNormalImage:normalI selectedImage:selectedI disabledImage:disabledI block:^(id sender) { + [t performSelector:selector withObject:sender]; + }]; +} + + +// +// Designated initializer +// +-(id) initWithNormalImage:(NSString*)normalI selectedImage:(NSString*)selectedI disabledImage:(NSString*)disabledI block:(void(^)(id sender))block { CCNode *normalImage = [CCSprite spriteWithFile:normalI]; CCNode *selectedImage = nil; CCNode *disabledImage = nil; if( selectedI ) - selectedImage = [CCSprite spriteWithFile:selectedI]; + selectedImage = [CCSprite spriteWithFile:selectedI]; if(disabledI) disabledImage = [CCSprite spriteWithFile:disabledI]; - return [self initFromNormalSprite:normalImage selectedSprite:selectedImage disabledSprite:disabledImage target:t selector:sel]; + return [super initWithNormalSprite:normalImage selectedSprite:selectedImage disabledSprite:disabledImage block:block]; } -#if NS_BLOCKS_AVAILABLE - -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block { - return [self itemFromNormalImage:value selectedImage:value2 disabledImage:nil block:block]; +// +// Setter of sprite frames +// +-(void) setNormalSpriteFrame:(CCSpriteFrame *)frame +{ + [self setNormalImage:[CCSprite spriteWithSpriteFrame:frame]]; } -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block { - return [[[self alloc] initFromNormalImage:value selectedImage:value2 disabledImage:value3 block:block] autorelease]; +-(void) setSelectedSpriteFrame:(CCSpriteFrame *)frame +{ + [self setSelectedImage:[CCSprite spriteWithSpriteFrame:frame]]; } --(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block { - block_ = [block copy]; - return [self initFromNormalImage:value selectedImage:value2 disabledImage:value3 target:block_ selector:@selector(ccCallbackBlockWithSender:)]; +-(void) setDisabledSpriteFrame:(CCSpriteFrame *)frame +{ + [self setDisabledImage:[CCSprite spriteWithSpriteFrame:frame]]; } -#endif // NS_BLOCKS_AVAILABLE - @end -#pragma mark - -#pragma mark CCMenuItemToggle +#pragma mark - CCMenuItemToggle // // MenuItemToggle @@ -623,52 +724,51 @@ +(id) itemWithTarget: (id)t selector: (SEL)sel items: (CCMenuItem*) item, ... { va_list args; va_start(args, item); - + id s = [[[self alloc] initWithTarget: t selector:sel items: item vaList:args] autorelease]; - + va_end(args); return s; } --(id) initWithTarget: (id)t selector: (SEL)sel items:(CCMenuItem*) item vaList: (va_list) args ++(id) itemWithItems:(NSArray*)arrayOfItems block:(void(^)(id))block { - if( (self=[super initWithTarget:t selector:sel]) ) { - - self.subItems = [NSMutableArray arrayWithCapacity:2]; - - int z = 0; - CCMenuItem *i = item; - while(i) { - z++; - [subItems_ addObject:i]; - i = va_arg(args, CCMenuItem*); - } + return [[[self alloc] initWithItems:arrayOfItems block:block] autorelease]; +} - selectedIndex_ = NSUIntegerMax; - [self setSelectedIndex:0]; +-(id) initWithTarget:(id)target selector:(SEL)selector items:(CCMenuItem*) item vaList: (va_list) args +{ + NSMutableArray *array = [NSMutableArray arrayWithCapacity:2]; + + int z = 0; + CCMenuItem *i = item; + while(i) { + z++; + [array addObject:i]; + i = va_arg(args, CCMenuItem*); } - - return self; -} -#if NS_BLOCKS_AVAILABLE - -+(id) itemWithBlock:(void(^)(id sender))block items:(CCMenuItem*)item, ... { - va_list args; - va_start(args, item); - - id s = [[[self alloc] initWithBlock:block items:item vaList:args] autorelease]; - - va_end(args); - return s; -} + // avoid retain cycle + __block id t = target; --(id) initWithBlock:(void (^)(id))block items:(CCMenuItem*)item vaList:(va_list)args { - block_ = [block copy]; - return [self initWithTarget:block_ selector:@selector(ccCallbackBlockWithSender:) items:item vaList:args]; + return [self initWithItems:array block:^(id sender) { + [t performSelector:selector withObject:sender]; + } + ]; } -#endif // NS_BLOCKS_AVAILABLE +-(id) initWithItems:(NSArray*)arrayOfItems block:(void(^)(id sender))block +{ + if( (self=[super initWithBlock:block] ) ) { + + self.subItems = [NSMutableArray arrayWithArray:arrayOfItems]; + + selectedIndex_ = NSUIntegerMax; + [self setSelectedIndex:0]; + } + + return self; +} -(void) dealloc { @@ -680,11 +780,13 @@ -(void)setSelectedIndex:(NSUInteger)index { if( index != selectedIndex_ ) { selectedIndex_=index; - [self removeChildByTag:kCurrentItem cleanup:NO]; + CCMenuItem *currentItem = (CCMenuItem*)[self getChildByTag:kCCCurrentItemTag]; + if( currentItem ) + [currentItem removeFromParentAndCleanup:NO]; CCMenuItem *item = [subItems_ objectAtIndex:selectedIndex_]; - [self addChild:item z:0 tag:kCurrentItem]; - + [self addChild:item z:0 tag:kCCCurrentItemTag]; + CGSize s = [item contentSize]; [self setContentSize: s]; item.position = ccp( s.width/2, s.height/2 ); diff --git a/Example/libs/cocos2d/CCMotionStreak.h b/Example/libs/cocos2d/CCMotionStreak.h index e017124..cf8a627 100644 --- a/Example/libs/cocos2d/CCMotionStreak.h +++ b/Example/libs/cocos2d/CCMotionStreak.h @@ -1,18 +1,18 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008, 2009 Jason Booth - * + * Copyright (c) 2011 ForzeField Studios S.L. http://forzefield.com + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,45 +23,62 @@ * */ + #import +#import "CCTexture2D.h" +#import "ccTypes.h" #import "CCNode.h" -#import "CCRibbon.h" -/** - * CCMotionStreak manages a Ribbon based on it's motion in absolute space. - * You construct it with a fadeTime, minimum segment size, texture path, texture - * length and color. The fadeTime controls how long it takes each vertex in - * the streak to fade out, the minimum segment size it how many pixels the - * streak will move before adding a new ribbon segement, and the texture - * length is the how many pixels the texture is stretched across. The texture - * is vertically aligned along the streak segemnts. - * - * Limitations: - * CCMotionStreak, by default, will use the GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA blending function. - * This blending function might not be the correct one for certain textures. - * But you can change it by using: - * [obj setBlendFunc: (ccBlendfunc) {new_src_blend_func, new_dst_blend_func}]; - * - * @since v0.8.1 +/** MotionStreak. + Creates a trailing path. */ -@interface CCMotionStreak : CCNode +@interface CCMotionStreak : CCNode { - CCRibbon* ribbon_; - float segThreshold_; - float width_; - CGPoint lastLocation_; + CCTexture2D *texture_; + CGPoint positionR_; + ccColor3B color_; + ccBlendFunc blendFunc_; + float stroke_; + float fadeDelta_; + float minSeg_; + + NSUInteger maxPoints_; + NSUInteger nuPoints_; + + /** Pointers */ + CGPoint *pointVertexes_; + float *pointState_; + + // Opengl + ccVertex2F *vertices_; + unsigned char *colorPointer_; + ccTex2F *texCoords_; + + BOOL fastMode_; } +/** blending function */ +@property (nonatomic, readwrite, assign) ccBlendFunc blendFunc; + +/** When fast mode is enbled, new points are added faster but with lower precision */ +@property (nonatomic, readwrite, assign, getter = isFastMode) BOOL fastMode; + +/** texture used for the motion streak */ +@property (nonatomic, retain) CCTexture2D *texture; -/** Ribbon used by MotionStreak (weak reference) */ -@property (nonatomic,readonly) CCRibbon *ribbon; +/** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename */ ++ (id) streakWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color textureFilename:(NSString*)path; +/** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture */ ++ (id) streakWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color texture:(CCTexture2D*)texture; -/** creates the a MotionStreak. The image will be loaded using the TextureMgr. */ -+(id)streakWithFade:(float)fade minSeg:(float)seg image:(NSString*)path width:(float)width length:(float)length color:(ccColor4B)color; +/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ +- (id) initWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color textureFilename:(NSString*)path; +/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ +- (id) initWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color texture:(CCTexture2D*)texture; -/** initializes a MotionStreak. The file will be loaded using the TextureMgr. */ --(id)initWithFade:(float)fade minSeg:(float)seg image:(NSString*)path width:(float)width length:(float)length color:(ccColor4B)color; +/** color used for the tint */ +- (void) tintWithColor:(ccColor3B)colors; -/** polling function */ --(void)update:(ccTime)delta; +/** Remove all living segments of the ribbon */ +- (void) reset; @end diff --git a/Example/libs/cocos2d/CCMotionStreak.m b/Example/libs/cocos2d/CCMotionStreak.m index 698cc59..1350005 100644 --- a/Example/libs/cocos2d/CCMotionStreak.m +++ b/Example/libs/cocos2d/CCMotionStreak.m @@ -1,18 +1,18 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008, 2009 Jason Booth - * + * Copyright (c) 2011 ForzeField Studios S.L. http://forzefield.com + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,84 +21,252 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * - ********************************************************* - * - * Motion Streak manages a Ribbon based on it's motion in absolute space. - * You construct it with a fadeTime, minimum segment size, texture path, texture - * length and color. The fadeTime controls how long it takes each vertex in - * the streak to fade out, the minimum segment size it how many pixels the - * streak will move before adding a new ribbon segement, and the texture - * length is the how many pixels the texture is stretched across. The texture - * is vertically aligned along the streak segemnts. */ #import "CCMotionStreak.h" +#import "CCTextureCache.h" +#import "ccGLStateCache.h" +#import "CCGLProgram.h" +#import "CCShaderCache.h" +#import "ccMacros.h" + +#import "Support/CCVertex.h" #import "Support/CGPointExtension.h" + @implementation CCMotionStreak +@synthesize texture = texture_; +@synthesize blendFunc = blendFunc_; +@synthesize fastMode = fastMode_; + ++ (id) streakWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color textureFilename:(NSString*)path +{ + return [[[self alloc] initWithFade:fade minSeg:minSeg width:stroke color:color textureFilename:path] autorelease]; +} + ++ (id) streakWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color texture:(CCTexture2D*)texture +{ + return [[[self alloc] initWithFade:fade minSeg:minSeg width:stroke color:color texture:texture] autorelease]; +} + +- (id) initWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color textureFilename:(NSString*)path +{ + NSAssert(path != nil, @"Invalid filename"); + + CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:path]; + return [self initWithFade:fade minSeg:minSeg width:stroke color:color texture:texture]; +} + +- (id) initWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color texture:(CCTexture2D*)texture +{ + self = [super init]; + if (self) + { + [super setPosition:CGPointZero]; + [self setAnchorPoint:CGPointZero]; + [self setIsRelativeAnchorPoint:NO]; + + positionR_ = CGPointZero; + fastMode_ = YES; + minSeg_ = (minSeg == -1.0f) ? stroke/5.0f : minSeg; + minSeg_ *= minSeg_; + + stroke_ = stroke; + fadeDelta_ = 1.0f/fade; + + maxPoints_ = (int)(fade*60.0f)+2; + nuPoints_ = 0; + pointState_ = malloc(sizeof(float) * maxPoints_); + pointVertexes_ = malloc(sizeof(CGPoint) * maxPoints_); + + vertices_ = malloc(sizeof(ccVertex2F) * maxPoints_ * 2); + texCoords_ = malloc(sizeof(ccTex2F) * maxPoints_ * 2); + colorPointer_ = malloc(sizeof(GLubyte) * maxPoints_ * 2 * 4); + + // Set blend mode + blendFunc_.src = GL_SRC_ALPHA; + blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; + + // shader program + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; + + [self setTexture:texture]; + [self setColor:color]; + [self scheduleUpdate]; + } + return self; +} + +#pragma mark - -@synthesize ribbon = ribbon_; +- (void) setPosition:(CGPoint)position +{ + positionR_ = position; +} -+(id)streakWithFade:(float)fade minSeg:(float)seg image:(NSString*)path width:(float)width length:(float)length color:(ccColor4B)color +- (void) tintWithColor:(ccColor3B)colors { - return [[[self alloc] initWithFade:(float)fade minSeg:seg image:path width:width length:length color:color] autorelease]; + [self setColor:colors]; + + // Fast assignation + for(int i = 0; i segThreshold_) - { - [ribbon_ addPointAt:location width:width_]; - lastLocation_ = location; - } - [ribbon_ update:delta]; + return color_; } +- (void) setOpacity:(GLubyte)opacity +{ + NSAssert(NO, @"Set opacity no supported"); +} --(void)dealloc +- (GLubyte) opacity { - [super dealloc]; + NSAssert(NO, @"Opacity no supported"); + return 0; } -#pragma mark MotionStreak - CocosNodeTexture protocol +#pragma mark - --(void) setTexture:(CCTexture2D*) texture +- (void) update:(ccTime)delta { - [ribbon_ setTexture: texture]; + delta *= fadeDelta_; + + NSUInteger newIdx, newIdx2, i, i2; + NSUInteger mov = 0; + + // Update current points + for(i = 0; i0) + { + // Move data + pointState_[newIdx] = pointState_[i]; + + // Move point + pointVertexes_[newIdx] = pointVertexes_[i]; + + // Move vertices + i2 = i*2; + newIdx2 = newIdx*2; + vertices_[newIdx2] = vertices_[i2]; + vertices_[newIdx2+1] = vertices_[i2+1]; + + // Move color + i2 *= 4; + newIdx2 *= 4; + colorPointer_[newIdx2+0] = colorPointer_[i2+0]; + colorPointer_[newIdx2+1] = colorPointer_[i2+1]; + colorPointer_[newIdx2+2] = colorPointer_[i2+2]; + colorPointer_[newIdx2+4] = colorPointer_[i2+4]; + colorPointer_[newIdx2+5] = colorPointer_[i2+5]; + colorPointer_[newIdx2+6] = colorPointer_[i2+6]; + }else + newIdx2 = newIdx*8; + + const GLubyte op = pointState_[newIdx] * 255.0f; + colorPointer_[newIdx2+3] = op; + colorPointer_[newIdx2+7] = op; + } + } + nuPoints_-=mov; + + // Append new point + BOOL appendNewPoint = YES; + if(nuPoints_ >= maxPoints_) + appendNewPoint = NO; + + else if(nuPoints_>0) + { + BOOL a1 = ccpDistanceSQ(pointVertexes_[nuPoints_-1], positionR_) < minSeg_; + BOOL a2 = (nuPoints_ == 1) ? NO : (ccpDistanceSQ(pointVertexes_[nuPoints_-2], positionR_) < (minSeg_ * 2.0f)); + if(a1 || a2) + appendNewPoint = NO; + } + + if(appendNewPoint) + { + pointVertexes_[nuPoints_] = positionR_; + pointState_[nuPoints_] = 1.0f; + + // Color asignation + const NSUInteger offset = nuPoints_*8; + *((ccColor3B*)(colorPointer_ + offset)) = color_; + *((ccColor3B*)(colorPointer_ + offset+4)) = color_; + + // Opacity + colorPointer_[offset+3] = 255; + colorPointer_[offset+7] = 255; + + // Generate polygon + if(nuPoints_ > 0 && fastMode_ ) + { + if(nuPoints_ > 1) + ccVertexLineToPolygon(pointVertexes_, stroke_, vertices_, texCoords_, nuPoints_, 1); + else + ccVertexLineToPolygon(pointVertexes_, stroke_, vertices_, texCoords_, 0, 2); + } + + nuPoints_ ++; + } + + if( ! fastMode_ ) + ccVertexLineToPolygon(pointVertexes_, stroke_, vertices_, texCoords_, 0, nuPoints_); } --(CCTexture2D*) texture +- (void) reset { - return [ribbon_ texture]; + nuPoints_ = 0; } --(ccBlendFunc) blendFunc +- (void) draw { - return [ribbon_ blendFunc]; + if(nuPoints_ <= 1) + return; + + CC_NODE_DRAW_SETUP(); + + ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex ); + ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); + + ccGLBindTexture2D( [texture_ name] ); + + glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices_); + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, texCoords_); + glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colorPointer_); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)nuPoints_*2); + + CC_INCREMENT_GL_DRAWS(1); } --(void) setBlendFunc:(ccBlendFunc)blendFunc +- (void)dealloc { - [ribbon_ setBlendFunc:blendFunc]; + [texture_ release]; + + free(pointState_); + free(pointVertexes_); + free(vertices_); + free(colorPointer_); + free(texCoords_); + + [super dealloc]; } @end diff --git a/Example/libs/cocos2d/CCNode.h b/Example/libs/cocos2d/CCNode.h index d6faaf5..028c285 100644 --- a/Example/libs/cocos2d/CCNode.h +++ b/Example/libs/cocos2d/CCNode.h @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada * Copyright (c) 2009 Valentin Milea - * + * + * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,15 +25,13 @@ * THE SOFTWARE. */ -#import - #import "Platforms/CCGL.h" -#import "CCAction.h" #import "ccTypes.h" -#import "CCTexture2D.h" #import "CCProtocols.h" #import "ccConfig.h" +#import "ccGLStateCache.h" #import "Support/CCArray.h" +#import "kazmath/kazmath.h" enum { kCCNodeTagInvalid = -1, @@ -39,22 +39,26 @@ enum { @class CCCamera; @class CCGridBase; +@class CCGLProgram; +@class CCScheduler; +@class CCActionManager; +@class CCAction; /** CCNode is the main element. Anything thats gets drawn or contains things that get drawn is a CCNode. The most popular CCNodes are: CCScene, CCLayer, CCSprite, CCMenu. - + The main features of a CCNode are: - They can contain other CCNode nodes (addChild, getChildByTag, removeChild, etc) - They can schedule periodic callback (schedule, unschedule, etc) - They can execute actions (runAction, stopAction, etc) - + Some CCNode nodes provide extra functionality for them or their children. - + Subclassing a CCNode usually means (one/all) of: - overriding init to initialize resources and schedule callbacks - create callbacks to handle the advancement of time - overriding draw to render the node - + Features of CCNode: - position - scale (x, y) @@ -66,105 +70,119 @@ enum { - visible - z-order - openGL z position - + Default values: - rotation: 0 - position: (x=0,y=0) - scale: (x=1,y=1) - contentSize: (x=0,y=0) - anchorPoint: (x=0,y=0) - + Limitations: - A CCNode is a "void" object. It doesn't have a texture - + Order in transformations with grid disabled -# The node will be translated (position) -# The node will be rotated (rotation) - -# The node will be scaled (scale) + -# The node will be skewed (skewX, skewY) + -# The node will be scaled (scale, scaleX, scaleY) -# The node will be moved according to the camera values (camera) - + Order in transformations with grid enabled -# The node will be translated (position) -# The node will be rotated (rotation) - -# The node will be scaled (scale) + -# The node will be skewed (skewX, skewY) + -# The node will be scaled (scale, scaleX, scaleY) -# The grid will capture the screen -# The node will be moved according to the camera values (camera) -# The grid will render the captured screen - + Camera: - Each node has a camera. By default it points to the center of the CCNode. - */ + */ @interface CCNode : NSObject -{ +{ // rotation angle - float rotation_; - + float rotation_; + // scaling factors float scaleX_, scaleY_; - + + // openGL real Z vertex + float vertexZ_; + // position of the node CGPoint position_; - CGPoint positionInPixels_; - // is visible - BOOL visible_; - - // anchor point in pixels - CGPoint anchorPointInPixels_; - // anchor point normalized - CGPoint anchorPoint_; - // If YES the transformtions will be relative to (-transform.x, -transform.y). - // Sprites, Labels and any other "small" object uses it. - // Scenes, Layers and other "whole screen" object don't use it. - BOOL isRelativeAnchorPoint_; - + // skew angles + float skewX_, skewY_; + + // anchor point in points + CGPoint anchorPointInPoints_; + // anchor point normalized (NOT in points) + CGPoint anchorPoint_; + // untransformed size of the node CGSize contentSize_; - CGSize contentSizeInPixels_; - + // transform CGAffineTransform transform_, inverse_; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - GLfloat transformGL_[16]; -#endif - // openGL real Z vertex - float vertexZ_; - // a Camera CCCamera *camera_; - + // a Grid CCGridBase *grid_; - + // z-order value NSInteger zOrder_; - + // array of children CCArray *children_; - + // weakref to parent CCNode *parent_; - + // a tag. any number you want to assign to the node NSInteger tag_; - + // user data field void *userData_; + id userObject_; + + // Shader + CCGLProgram *shaderProgram_; + + // Server side state + ccGLServerState glServerState_; + + // used to preserve sequence while sorting children with the same zOrder + NSUInteger orderOfArrival_; + + // scheduler used to schedule timers and updates + CCScheduler *scheduler_; + + // ActionManager used to handle all the actions + CCActionManager *actionManager_; // Is running BOOL isRunning_; - // To reduce memory, place BOOLs that are not properties here: - BOOL isTransformDirty_:1; - BOOL isInverseDirty_:1; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - BOOL isTransformGLDirty_:1; -#endif + BOOL isTransformDirty_; + BOOL isInverseDirty_; + + // is visible + BOOL visible_; + // If YES the transformtions will be relative to (-transform.x, -transform.y). + // Sprites, Labels and any other "small" object uses it. + // Scenes, Layers and other "whole screen" object don't use it. + BOOL isRelativeAnchorPoint_; + + BOOL isReorderChildDirty_; } -/** The z order of the node relative to it's "brothers": children of the same parent */ -@property(nonatomic,readonly) NSInteger zOrder; +/** The z order of the node relative to its "siblings": children of the same parent */ +@property(nonatomic,assign) NSInteger zOrder; /** The real openGL Z vertex. Differences between openGL Z vertex and cocos2d Z order: - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children @@ -174,6 +192,20 @@ enum { @since v0.8 */ @property (nonatomic,readwrite) float vertexZ; + +/** The X skew angle of the node in degrees. + This angle describes the shear distortion in the X direction. + Thus, it is the angle between the Y axis and the left edge of the shape + The default skewX angle is 0. Positive values distort the node in a CW direction. + */ +@property(nonatomic,readwrite,assign) float skewX; + +/** The Y skew angle of the node in degrees. + This angle describes the shear distortion in the Y direction. + Thus, it is the angle between the X axis and the bottom edge of the shape + The default skewY angle is 0. Positive values distort the node in a CCW direction. + */ +@property(nonatomic,readwrite,assign) float skewY; /** The rotation (angle) of the node in degrees. 0 is the default rotation angle. Positive values rotate node CW. */ @property(nonatomic,readwrite,assign) float rotation; /** The scale factor of the node. 1.0 is the default scale factor. It modifies the X and Y scale at the same time. */ @@ -184,10 +216,7 @@ enum { @property(nonatomic,readwrite,assign) float scaleY; /** Position (x,y) of the node in points. (0,0) is the left-bottom corner. */ @property(nonatomic,readwrite,assign) CGPoint position; -/** Position (x,y) of the node in points. (0,0) is the left-bottom corner. */ -@property(nonatomic,readwrite,assign) CGPoint positionInPixels; -/** A CCCamera object that lets you move the node using a gluLookAt -*/ +/** A CCCamera object that lets you move the node using a gluLookAt */ @property(nonatomic,readonly) CCCamera* camera; /** Array of children */ @property(nonatomic,readonly) CCArray *children; @@ -206,7 +235,7 @@ enum { /** The anchorPoint in absolute pixels. Since v0.8 you can only read it. If you wish to modify it, use anchorPoint instead */ -@property(nonatomic,readonly) CGPoint anchorPointInPixels; +@property(nonatomic,readonly) CGPoint anchorPointInPoints; /** The untransformed size of the node in Points The contentSize remains the same no matter the node is scaled or rotated. @@ -215,18 +244,11 @@ enum { */ @property (nonatomic,readwrite) CGSize contentSize; -/** The untransformed size of the node in Pixels - The contentSize remains the same no matter the node is scaled or rotated. - All nodes has a size. Layer and Scene has the same size of the screen. - @since v0.8 - */ -@property (nonatomic,readwrite) CGSize contentSizeInPixels; - /** whether or not the node is running */ @property(nonatomic,readonly) BOOL isRunning; /** A weak reference to the parent */ @property(nonatomic,readwrite,assign) CCNode* parent; -/** If YES the transformtions will be relative to it's anchor point. +/** If YES the transformtions will be relative to its anchor point. * Sprites, Labels and any other sizeble object use it have it enabled by default. * Scenes, Layers and other "whole screen" object don't use it, have it disabled by default. */ @@ -234,7 +256,34 @@ enum { /** A tag used to identify the node easily */ @property(nonatomic,readwrite,assign) NSInteger tag; /** A custom user data pointer */ -@property(nonatomic,readwrite,assign) void *userData; +@property(nonatomic,readwrite,assign) void* userData; +/** Similar to userData, but instead of holding a void* it holds an id */ +@property(nonatomic,readwrite,retain) id userObject; + +/** Shader Program + @since v2.0 + */ +@property(nonatomic,readwrite,retain) CCGLProgram *shaderProgram; + +/** used internally for zOrder sorting, don't change this manually */ +@property(nonatomic,readwrite) NSUInteger orderOfArrival; + +/** GL server side state + @since v2.0 +*/ +@property (nonatomic, readwrite) ccGLServerState glServerState; + +/** CCActionManager used by all the actions. + IMPORTANT: If you set a new CCActionManager, then previously created actions are going to be removed. + @since v2.0 + */ +@property (nonatomic, readwrite, retain) CCActionManager *actionManager; + +/** CCScheduler used to schedule all "updates" and timers. + IMPORTANT: If you set a new CCScheduler, then previously created timers/update are going to be removed. + @since v2.0 + */ +@property (nonatomic, readwrite, retain) CCScheduler *scheduler; // initializators /** allocates and initializes a node. @@ -247,22 +296,31 @@ enum { // scene managment -/** callback that is called every time the CCNode enters the 'stage'. - If the CCNode enters the 'stage' with a transition, this callback is called when the transition starts. - During onEnter you can't a "sister/brother" node. +/** Event that is called every time the CCNode enters the 'stage'. + If the CCNode enters the 'stage' with a transition, this event is called when the transition starts. + During onEnter you can't access a sibling node. + If you override onEnter, you shall call [super onEnter]. */ -(void) onEnter; -/** callback that is called when the CCNode enters in the 'stage'. - If the CCNode enters the 'stage' with a transition, this callback is called when the transition finishes. + +/** Event that is called when the CCNode enters in the 'stage'. + If the CCNode enters the 'stage' with a transition, this event is called when the transition finishes. + If you override onEnterTransitionDidFinish, you shall call [super onEnterTransitionDidFinish]. @since v0.8 */ -(void) onEnterTransitionDidFinish; -/** callback that is called every time the CCNode leaves the 'stage'. - If the CCNode leaves the 'stage' with a transition, this callback is called when the transition finishes. - During onExit you can't a "sister/brother" node. + +/** Event that is called every time the CCNode leaves the 'stage'. + If the CCNode leaves the 'stage' with a transition, this event is called when the transition finishes. + During onExit you can't access a sibling node. + If you override onExit, you shall call [super onExit]. */ -(void) onExit; +/** callback that is called every time the CCNode leaves the 'stage'. + If the CCNode leaves the 'stage' with a transition, this callback is called when the transition starts. + */ +-(void) onExitTransitionDidStart; // composition: ADD @@ -276,13 +334,13 @@ enum { If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. @since v0.7.1 */ --(void) addChild: (CCNode*)node z:(int)z; +-(void) addChild: (CCNode*)node z:(NSInteger)z; /** Adds a child to the container with z order and tag. If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. @since v0.7.1 */ --(void) addChild: (CCNode*)node z:(int)z tag:(int)tag; +-(void) addChild: (CCNode*)node z:(NSInteger)z tag:(NSInteger)tag; // composition: REMOVE @@ -300,7 +358,7 @@ enum { /** Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter @since v0.7.1 */ --(void) removeChildByTag:(int) tag cleanup:(BOOL)cleanup; +-(void) removeChildByTag:(NSInteger) tag cleanup:(BOOL)cleanup; /** Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter. @since v0.7.1 @@ -312,14 +370,21 @@ enum { @return returns a CCNode object @since v0.7.1 */ --(CCNode*) getChildByTag:(int) tag; +-(CCNode*) getChildByTag:(NSInteger) tag; /** Reorders a child according to a new z value. * The child MUST be already added. */ --(void) reorderChild:(CCNode*)child z:(int)zOrder; +-(void) reorderChild:(CCNode*)child z:(NSInteger)zOrder; + +/** performance improvement, Sort the children array once before drawing, instead of every time when a child is added or reordered + don't call this manually unless a child added needs to be removed in the same frame */ +- (void) sortAllChildren; -/** Stops all running actions and schedulers +/** Event that is called when the running node is no longer running (eg: its CCScene is being removed from the "stage" ). + On cleanup you should break any possible circular references. + CCNode's cleanup removes any possible scheduled timer and/or any possible action. + If you override cleanup, you shall call [super cleanup] @since v0.8 */ -(void) cleanup; @@ -327,17 +392,12 @@ enum { // draw /** Override this method to draw your own node. - The following GL states will be enabled by default: - - glEnableClientState(GL_VERTEX_ARRAY); - - glEnableClientState(GL_COLOR_ARRAY); - - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - - glEnable(GL_TEXTURE_2D); - - AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE - - But if you enable any other GL state, you should disable it after drawing your node. + You should use cocos2d's GL API to enable/disable the GL state / shaders. + For further info, please see ccGLstate.h. + You shall NOT call [super draw]; */ -(void) draw; + /** recursive method that visit its children and draw them */ -(void) visit; @@ -346,9 +406,8 @@ enum { /** performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes. */ -(void) transform; -/** performs OpenGL view-matrix transformation of it's ancestors. - Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO) - it's necessary to transform the ancestors again. +/** performs OpenGL view-matrix transformation of its ancestors. + Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO) it is necessary to transform the ancestors again. @since v0.7.2 */ -(void) transformAncestors; @@ -356,20 +415,11 @@ enum { /** returns a "local" axis aligned bounding box of the node in points. The returned box is relative only to its parent. The returned box is in Points. - + @since v0.8.2 */ - (CGRect) boundingBox; -/** returns a "local" axis aligned bounding box of the node in pixels. - The returned box is relative only to its parent. - The returned box is in Points. - - @since v0.99.5 - */ -- (CGRect) boundingBoxInPixels; - - // actions /** Executes an action, and returns the action that is executed. @@ -386,18 +436,18 @@ enum { /** Removes an action from the running action list given its tag @since v0.7.1 */ --(void) stopActionByTag:(int) tag; +-(void) stopActionByTag:(NSInteger) tag; /** Gets an action from the running action list given its tag @since v0.7.1 @return the Action the with the given tag */ --(CCAction*) getActionByTag:(int) tag; -/** Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays). +-(CCAction*) getActionByTag:(NSInteger) tag; +/** Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays). * Composable actions are counted as 1 action. Example: * If you are running 1 Sequence of 7 actions, it will return 1. * If you are running 7 Sequences of 2 actions, it will return 7. */ --(int) numberOfRunningActions; +-(NSUInteger) numberOfRunningActions; // timers @@ -407,7 +457,7 @@ enum { /** schedules the "update" method. It will use the order number 0. This method will be called every frame. Scheduled methods with a lower order value will be called before the ones that have a higher order value. Only one "udpate" method could be scheduled per node. - + @since v0.99.3 */ -(void) scheduleUpdate; @@ -418,10 +468,10 @@ enum { @since v0.99.3 */ --(void) scheduleUpdateWithPriority:(int)priority; +-(void) scheduleUpdateWithPriority:(NSInteger)priority; /* unschedules the "update" method. - + @since v0.99.3 */ -(void) unscheduleUpdate; @@ -434,10 +484,21 @@ enum { /** schedules a custom selector with an interval time in seconds. If time is 0 it will be ticked every frame. If time is 0, it is recommended to use 'scheduleUpdate' instead. - + If the selector is already scheduled, then the interval parameter will be updated without scheduling it again. */ -(void) schedule: (SEL) s interval:(ccTime)seconds; +/** + repeat will execute the action repeat + 1 times, for a continues action use kCCRepeatForever + delay is the amount of time the action will wait before execution + */ +-(void) schedule:(SEL)selector interval:(ccTime)interval repeat: (uint) repeat delay:(ccTime) delay; + +/** + Schedules a selector that runs only once, with a delay of 0 or larger +*/ +- (void) scheduleOnce:(SEL) selector delay:(ccTime) delay; + /** unschedules a custom selector.*/ -(void) unschedule: (SEL) s; @@ -496,7 +557,7 @@ enum { */ - (CGPoint)convertToWorldSpaceAR:(CGPoint)nodePoint; -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS /** Converts a UITouch to node (local) space coordinates. The result is in Points. @since v0.7.1 */ @@ -506,5 +567,5 @@ enum { @since v0.7.1 */ - (CGPoint)convertTouchToNodeSpaceAR:(UITouch *)touch; -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_IOS @end diff --git a/Example/libs/cocos2d/CCNode.m b/Example/libs/cocos2d/CCNode.m index 5392905..9a70409 100644 --- a/Example/libs/cocos2d/CCNode.m +++ b/Example/libs/cocos2d/CCNode.m @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada * Copyright (c) 2009 Valentin Milea - * + * + * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -35,31 +37,38 @@ #import "Support/ccCArray.h" #import "Support/TransformUtils.h" #import "ccMacros.h" +#import "CCGLProgram.h" -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +// externals +#import "kazmath/GL/matrix.h" + +#ifdef __CC_PLATFORM_IOS #import "Platforms/iOS/CCDirectorIOS.h" #endif -#if CC_COCOSNODE_RENDER_SUBPIXEL +#if CC_NODE_RENDER_SUBPIXEL #define RENDER_IN_SUBPIXEL #else #define RENDER_IN_SUBPIXEL (NSInteger) #endif + @interface CCNode () // lazy allocs -(void) childrenAlloc; // helper that reorder a child --(void) insertChild:(CCNode*)child z:(int)z; +-(void) insertChild:(CCNode*)child z:(NSInteger)z; // used internally to alter the zOrder variable. DON'T call this method manually --(void) _setZOrder:(int) z; +-(void) _setZOrder:(NSInteger) z; -(void) detachChild:(CCNode *)child cleanup:(BOOL)doCleanup; @end @implementation CCNode +// XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. +static NSUInteger globalOrderOfArrival = 1; + @synthesize children = children_; @synthesize visible = visible_; @synthesize parent = parent_; @@ -68,91 +77,171 @@ @implementation CCNode @synthesize tag = tag_; @synthesize vertexZ = vertexZ_; @synthesize isRunning = isRunning_; -@synthesize userData = userData_; +@synthesize userData = userData_, userObject = userObject_; +@synthesize shaderProgram = shaderProgram_; +@synthesize orderOfArrival = orderOfArrival_; +@synthesize glServerState = glServerState_; #pragma mark CCNode - Transform related properties @synthesize rotation = rotation_, scaleX = scaleX_, scaleY = scaleY_; -@synthesize position = position_, positionInPixels = positionInPixels_; -@synthesize anchorPoint = anchorPoint_, anchorPointInPixels = anchorPointInPixels_; -@synthesize contentSize = contentSize_, contentSizeInPixels = contentSizeInPixels_; +@synthesize position = position_; +@synthesize anchorPoint = anchorPoint_, anchorPointInPoints = anchorPointInPoints_; +@synthesize contentSize = contentSize_; @synthesize isRelativeAnchorPoint = isRelativeAnchorPoint_; +@synthesize skewX = skewX_, skewY = skewY_; + +#pragma mark CCNode - Init & cleanup + ++(id) node +{ + return [[[self alloc] init] autorelease]; +} + +-(id) init +{ + if ((self=[super init]) ) { + + isRunning_ = NO; + + skewX_ = skewY_ = 0.0f; + rotation_ = 0.0f; + scaleX_ = scaleY_ = 1.0f; + position_ = CGPointZero; + contentSize_ = CGSizeZero; + anchorPointInPoints_ = anchorPoint_ = CGPointZero; + + + // "whole screen" objects. like Scenes and Layers, should set isRelativeAnchorPoint to NO + isRelativeAnchorPoint_ = YES; + + isTransformDirty_ = isInverseDirty_ = YES; + + vertexZ_ = 0; + + grid_ = nil; + + visible_ = YES; + + tag_ = kCCNodeTagInvalid; + + zOrder_ = 0; + + // lazy alloc + camera_ = nil; + + // children (lazy allocs) + children_ = nil; + + // userData is always inited as nil + userData_ = NULL; + userObject_ = nil; + + //initialize parent to nil + parent_ = nil; + + shaderProgram_ = nil; + + orderOfArrival_ = 0; + + glServerState_ = CC_GL_BLEND; + + // set default scheduler and actionManager + CCDirector *director = [CCDirector sharedDirector]; + self.actionManager = [director actionManager]; + self.scheduler = [director scheduler]; + } + + return self; +} + +- (void)cleanup +{ + // actions + [self stopAllActions]; + [self unscheduleAllSelectors]; + + // timers + [children_ makeObjectsPerformSelector:@selector(cleanup)]; +} + +- (NSString*) description +{ + return [NSString stringWithFormat:@"<%@ = %08X | Tag = %i>", [self class], self, tag_]; +} + +- (void) dealloc +{ + CCLOGINFO( @"cocos2d: deallocing %@", self); + + [actionManager_ release]; + [scheduler_ release]; + [camera_ release]; + [grid_ release]; + [shaderProgram_ release]; + [userObject_ release]; + + // children + CCNode *child; + CCARRAY_FOREACH(children_, child) + child.parent = nil; + + [children_ release]; + + [super dealloc]; +} + +#pragma mark Setters // getters synthesized, setters explicit -(void) setRotation: (float)newRotation { rotation_ = newRotation; isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif } -(void) setScaleX: (float)newScaleX { scaleX_ = newScaleX; isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif } -(void) setScaleY: (float)newScaleY { scaleY_ = newScaleY; isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif } --(void) setPosition: (CGPoint)newPosition +-(void) setSkewX:(float)newSkewX { - position_ = newPosition; - if( CC_CONTENT_SCALE_FACTOR() == 1 ) - positionInPixels_ = position_; - else - positionInPixels_ = ccpMult( newPosition, CC_CONTENT_SCALE_FACTOR() ); - + skewX_ = newSkewX; isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif } --(void) setPositionInPixels:(CGPoint)newPosition +-(void) setSkewY:(float)newSkewY { - positionInPixels_ = newPosition; + skewY_ = newSkewY; + isTransformDirty_ = isInverseDirty_ = YES; +} - if( CC_CONTENT_SCALE_FACTOR() == 1 ) - position_ = positionInPixels_; - else - position_ = ccpMult( newPosition, 1/CC_CONTENT_SCALE_FACTOR() ); - +-(void) setPosition: (CGPoint)newPosition +{ + position_ = newPosition; isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif } -(void) setIsRelativeAnchorPoint: (BOOL)newValue { isRelativeAnchorPoint_ = newValue; isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif } -(void) setAnchorPoint:(CGPoint)point { if( ! CGPointEqualToPoint(point, anchorPoint_) ) { anchorPoint_ = point; - anchorPointInPixels_ = ccp( contentSizeInPixels_.width * anchorPoint_.x, contentSizeInPixels_.height * anchorPoint_.y ); + anchorPointInPoints_ = ccp( contentSize_.width * anchorPoint_.x, contentSize_.height * anchorPoint_.y ); isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif } } @@ -160,53 +249,21 @@ -(void) setContentSize:(CGSize)size { if( ! CGSizeEqualToSize(size, contentSize_) ) { contentSize_ = size; - - if( CC_CONTENT_SCALE_FACTOR() == 1 ) - contentSizeInPixels_ = contentSize_; - else - contentSizeInPixels_ = CGSizeMake( size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); - - anchorPointInPixels_ = ccp( contentSizeInPixels_.width * anchorPoint_.x, contentSizeInPixels_.height * anchorPoint_.y ); - isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif - } -} - --(void) setContentSizeInPixels:(CGSize)size -{ - if( ! CGSizeEqualToSize(size, contentSizeInPixels_) ) { - contentSizeInPixels_ = size; - if( CC_CONTENT_SCALE_FACTOR() == 1 ) - contentSize_ = contentSizeInPixels_; - else - contentSize_ = CGSizeMake( size.width / CC_CONTENT_SCALE_FACTOR(), size.height / CC_CONTENT_SCALE_FACTOR() ); - - anchorPointInPixels_ = ccp( contentSizeInPixels_.width * anchorPoint_.x, contentSizeInPixels_.height * anchorPoint_.y ); + anchorPointInPoints_ = ccp( contentSize_.width * anchorPoint_.x, contentSize_.height * anchorPoint_.y ); isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif } } - (CGRect) boundingBox { - CGRect ret = [self boundingBoxInPixels]; - return CC_RECT_PIXELS_TO_POINTS( ret ); -} - -- (CGRect) boundingBoxInPixels -{ - CGRect rect = CGRectMake(0, 0, contentSizeInPixels_.width, contentSizeInPixels_.height); + CGRect rect = CGRectMake(0, 0, contentSize_.width, contentSize_.height); return CGRectApplyAffineTransform(rect, [self nodeToParentTransform]); } -(void) setVertexZ:(float)vertexZ { - vertexZ_ = vertexZ * CC_CONTENT_SCALE_FACTOR(); + vertexZ_ = vertexZ; } -(float) scale @@ -219,97 +276,14 @@ -(void) setScale:(float) s { scaleX_ = scaleY_ = s; isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif } -#pragma mark CCNode - Init & cleanup - -+(id) node +- (void) setZOrder:(NSInteger)zOrder { - return [[[self alloc] init] autorelease]; -} + [self _setZOrder:zOrder]; --(id) init -{ - if ((self=[super init]) ) { - - isRunning_ = NO; - - rotation_ = 0.0f; - scaleX_ = scaleY_ = 1.0f; - positionInPixels_ = position_ = CGPointZero; - anchorPointInPixels_ = anchorPoint_ = CGPointZero; - contentSizeInPixels_ = contentSize_ = CGSizeZero; - - - // "whole screen" objects. like Scenes and Layers, should set isRelativeAnchorPoint to NO - isRelativeAnchorPoint_ = YES; - - isTransformDirty_ = isInverseDirty_ = YES; -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - isTransformGLDirty_ = YES; -#endif - - vertexZ_ = 0; - - grid_ = nil; - - visible_ = YES; - - tag_ = kCCNodeTagInvalid; - - zOrder_ = 0; - - // lazy alloc - camera_ = nil; - - // children (lazy allocs) - children_ = nil; - - // userData is always inited as nil - userData_ = nil; - - //initialize parent to nil - parent_ = nil; - } - - return self; -} - -- (void)cleanup -{ - // actions - [self stopAllActions]; - [self unscheduleAllSelectors]; - - // timers - [children_ makeObjectsPerformSelector:@selector(cleanup)]; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Tag = %i>", [self class], self, tag_]; -} - -- (void) dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@", self); - - // attributes - [camera_ release]; - - [grid_ release]; - - // children - CCNode *child; - CCARRAY_FOREACH(children_, child) - child.parent = nil; - - [children_ release]; - - [super dealloc]; + if (parent_) + [parent_ reorderChild:self z:zOrder]; } #pragma mark CCNode Composition @@ -324,23 +298,22 @@ -(CCCamera*) camera { if( ! camera_ ) { camera_ = [[CCCamera alloc] init]; - + // by default, center camera at the Sprite's anchor point - // [camera_ setCenterX:anchorPointInPixels_.x centerY:anchorPointInPixels_.y centerZ:0]; - // [camera_ setEyeX:anchorPointInPixels_.x eyeY:anchorPointInPixels_.y eyeZ:1]; - - // [camera_ setCenterX:0 centerY:0 centerZ:0]; - // [camera_ setEyeX:0 eyeY:0 eyeZ:1]; - +// [camera_ setCenterX:anchorPointInPoints_.x centerY:anchorPointInPoints_.y centerZ:0]; +// [camera_ setEyeX:anchorPointInPoints_.x eyeY:anchorPointInPoints_.y eyeZ:1]; + +// [camera_ setCenterX:0 centerY:0 centerZ:0]; +// [camera_ setEyeX:0 eyeY:0 eyeZ:1]; } - + return camera_; } --(CCNode*) getChildByTag:(int) aTag +-(CCNode*) getChildByTag:(NSInteger) aTag { NSAssert( aTag != kCCNodeTagInvalid, @"Invalid tag"); - + CCNode *node; CCARRAY_FOREACH(children_, node){ if( node.tag == aTag ) @@ -354,27 +327,29 @@ -(CCNode*) getChildByTag:(int) aTag * If a class want's to extend the 'addChild' behaviour it only needs * to override this method */ --(void) addChild: (CCNode*) child z:(int)z tag:(int) aTag -{ +-(void) addChild: (CCNode*) child z:(NSInteger)z tag:(NSInteger) aTag +{ NSAssert( child != nil, @"Argument must be non-nil"); NSAssert( child.parent == nil, @"child already added. It can't be added again"); - + if( ! children_ ) [self childrenAlloc]; - + [self insertChild:child z:z]; - + child.tag = aTag; - + [child setParent: self]; - + + [child setOrderOfArrival: globalOrderOfArrival++]; + if( isRunning_ ) { [child onEnter]; [child onEnterTransitionDidFinish]; } } --(void) addChild: (CCNode*) child z:(int)z +-(void) addChild: (CCNode*) child z:(NSInteger)z { NSAssert( child != nil, @"Argument must be non-nil"); [self addChild:child z:z tag:child.tag]; @@ -400,17 +375,17 @@ -(void) removeChild: (CCNode*)child cleanup:(BOOL)cleanup // explicit nil handling if (child == nil) return; - + if ( [children_ containsObject:child] ) [self detachChild:child cleanup:cleanup]; } --(void) removeChildByTag:(int)aTag cleanup:(BOOL)cleanup +-(void) removeChildByTag:(NSInteger)aTag cleanup:(BOOL)cleanup { NSAssert( aTag != kCCNodeTagInvalid, @"Invalid tag"); - + CCNode *child = [self getChildByTag:aTag]; - + if (child == nil) CCLOG(@"cocos2d: removeChildByTag: child not found!"); else @@ -427,15 +402,18 @@ -(void) removeAllChildrenWithCleanup:(BOOL)cleanup // -1st do onExit // -2nd cleanup if (isRunning_) + { + [c onExitTransitionDidStart]; [c onExit]; - + } + if (cleanup) [c cleanup]; - + // set parent nil at the end (issue #476) [c setParent:nil]; } - + [children_ removeAllObjects]; } @@ -445,89 +423,102 @@ -(void) detachChild:(CCNode *)child cleanup:(BOOL)doCleanup // -1st do onExit // -2nd cleanup if (isRunning_) + { + [child onExitTransitionDidStart]; [child onExit]; - + } + // If you don't do cleanup, the child's actions will not get removed and the // its scheduledSelectors_ dict will not get released! if (doCleanup) [child cleanup]; - + // set parent nil at the end (issue #476) [child setParent:nil]; - + [children_ removeObject:child]; } // used internally to alter the zOrder variable. DON'T call this method manually --(void) _setZOrder:(int) z +-(void) _setZOrder:(NSInteger) z { zOrder_ = z; } // helper used by reorderChild & add --(void) insertChild:(CCNode*)child z:(int)z -{ - NSUInteger index=0; - CCNode *a = [children_ lastObject]; - - // quick comparison to improve performance - if (!a || a.zOrder <= z) - [children_ addObject:child]; - - else - { - CCARRAY_FOREACH(children_, a) { - if ( a.zOrder > z ) { - [children_ insertObject:child atIndex:index]; - break; - } - index++; - } - } - +-(void) insertChild:(CCNode*)child z:(NSInteger)z +{ + isReorderChildDirty_=YES; + + ccArrayAppendObjectWithResize(children_->data, child); [child _setZOrder:z]; } --(void) reorderChild:(CCNode*) child z:(int)z +-(void) reorderChild:(CCNode*) child z:(NSInteger)z { NSAssert( child != nil, @"Child must be non-nil"); - - [child retain]; - [children_ removeObject:child]; - - [self insertChild:child z:z]; - - [child release]; + + isReorderChildDirty_ = YES; + + [child setOrderOfArrival: globalOrderOfArrival++]; + [child _setZOrder:z]; +} + +- (void) sortAllChildren +{ + if (isReorderChildDirty_) + { + NSInteger i,j,length = children_->data->num; + CCNode ** x = children_->data->arr; + CCNode *tempItem; + + // insertion sort + for(i=1; i=0 && ( tempItem.zOrder < x[j].zOrder || ( tempItem.zOrder== x[j].zOrder && tempItem.orderOfArrival < x[j].orderOfArrival ) ) ) + { + x[j+1] = x[j]; + j = j-1; + } + x[j+1] = tempItem; + } + + //don't need to check children recursively, that's done in visit of each child + + isReorderChildDirty_ = NO; + } } #pragma mark CCNode Draw -(void) draw { - // override me - // Only use this function to draw your staff. - // DON'T draw your stuff outside this method } -(void) visit { - // quick return if not visible + // quick return if not visible. children won't be drawn. if (!visible_) return; - - glPushMatrix(); - - if ( grid_ && grid_.active) { + + kmGLPushMatrix(); + + if ( grid_ && grid_.active) [grid_ beforeDraw]; - [self transformAncestors]; - } [self transform]; - + if(children_) { + + [self sortAllChildren]; + ccArray *arrayData = children_->data; NSUInteger i = 0; - + // draw children zOrder < 0 for( ; i < arrayData->num; i++ ) { CCNode *child = arrayData->arr[i]; @@ -536,10 +527,10 @@ -(void) visit else break; } - + // self draw [self draw]; - + // draw children zOrder >= 0 for( ; i < arrayData->num; i++ ) { CCNode *child = arrayData->arr[i]; @@ -548,11 +539,14 @@ -(void) visit } else [self draw]; - + + // reset for next frame + orderOfArrival_ = 0; + if ( grid_ && grid_.active) [grid_ afterDraw:self]; - - glPopMatrix(); + + kmGLPopMatrix(); } #pragma mark CCNode - Transformations @@ -566,79 +560,41 @@ -(void) transformAncestors } -(void) transform -{ - // transformations - -#if CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - // BEGIN alternative -- using cached transform - // - if( isTransformGLDirty_ ) { - CGAffineTransform t = [self nodeToParentTransform]; - CGAffineToGL(&t, transformGL_); - isTransformGLDirty_ = NO; - } - - glMultMatrixf(transformGL_); - if( vertexZ_ ) - glTranslatef(0, 0, vertexZ_); - +{ + kmMat4 transfrom4x4; + + // Convert 3x3 into 4x4 matrix + CGAffineTransform tmpAffine = [self nodeToParentTransform]; + CGAffineToGL(&tmpAffine, transfrom4x4.mat); + + // Update Z vertex manually + transfrom4x4.mat[14] = vertexZ_; + + kmGLMultMatrix( &transfrom4x4 ); + + // XXX: Expensive calls. Camera should be integrated into the cached affine matrix if ( camera_ && !(grid_ && grid_.active) ) { - BOOL translate = (anchorPointInPixels_.x != 0.0f || anchorPointInPixels_.y != 0.0f); - + BOOL translate = (anchorPointInPoints_.x != 0.0f || anchorPointInPoints_.y != 0.0f); + if( translate ) - ccglTranslate(RENDER_IN_SUBPIXEL(anchorPointInPixels_.x), RENDER_IN_SUBPIXEL(anchorPointInPixels_.y), 0); - + kmGLTranslatef(RENDER_IN_SUBPIXEL(anchorPointInPoints_.x), RENDER_IN_SUBPIXEL(anchorPointInPoints_.y), 0 ); + [camera_ locate]; - + if( translate ) - ccglTranslate(RENDER_IN_SUBPIXEL(-anchorPointInPixels_.x), RENDER_IN_SUBPIXEL(-anchorPointInPixels_.y), 0); + kmGLTranslatef(RENDER_IN_SUBPIXEL(-anchorPointInPoints_.x), RENDER_IN_SUBPIXEL(-anchorPointInPoints_.y), 0 ); } - - - // END alternative - -#else - // BEGIN original implementation - // - // translate - if ( isRelativeAnchorPoint_ && (anchorPointInPixels_.x != 0 || anchorPointInPixels_.y != 0 ) ) - glTranslatef( RENDER_IN_SUBPIXEL(-anchorPointInPixels_.x), RENDER_IN_SUBPIXEL(-anchorPointInPixels_.y), 0); - - if (anchorPointInPixels_.x != 0 || anchorPointInPixels_.y != 0) - glTranslatef( RENDER_IN_SUBPIXEL(positionInPixels_.x + anchorPointInPixels_.x), RENDER_IN_SUBPIXEL(positionInPixels_.y + anchorPointInPixels_.y), vertexZ_); - else if ( positionInPixels_.x !=0 || positionInPixels_.y !=0 || vertexZ_ != 0) - glTranslatef( RENDER_IN_SUBPIXEL(positionInPixels_.x), RENDER_IN_SUBPIXEL(positionInPixels_.y), vertexZ_ ); - - // rotate - if (rotation_ != 0.0f ) - glRotatef( -rotation_, 0.0f, 0.0f, 1.0f ); - - // scale - if (scaleX_ != 1.0f || scaleY_ != 1.0f) - glScalef( scaleX_, scaleY_, 1.0f ); - - if ( camera_ && !(grid_ && grid_.active) ) - [camera_ locate]; - - // restore and re-position point - if (anchorPointInPixels_.x != 0.0f || anchorPointInPixels_.y != 0.0f) - glTranslatef(RENDER_IN_SUBPIXEL(-anchorPointInPixels_.x), RENDER_IN_SUBPIXEL(-anchorPointInPixels_.y), 0); - - // - // END original implementation -#endif - } #pragma mark CCNode SceneManagement -(void) onEnter { - [children_ makeObjectsPerformSelector:@selector(onEnter)]; + [children_ makeObjectsPerformSelector:@selector(onEnter)]; [self resumeSchedulerAndActions]; - + isRunning_ = YES; } @@ -647,79 +603,124 @@ -(void) onEnterTransitionDidFinish [children_ makeObjectsPerformSelector:@selector(onEnterTransitionDidFinish)]; } +-(void) onExitTransitionDidStart +{ + [children_ makeObjectsPerformSelector:@selector(onExitTransitionDidStart)]; +} + -(void) onExit { [self pauseSchedulerAndActions]; - isRunning_ = NO; - + isRunning_ = NO; + [children_ makeObjectsPerformSelector:@selector(onExit)]; } #pragma mark CCNode Actions +-(void) setActionManager:(CCActionManager *)actionManager +{ + if( actionManager != actionManager_ ) { + [self stopAllActions]; + [actionManager_ release]; + + actionManager_ = [actionManager retain]; + } +} + +-(CCActionManager*) actionManager +{ + return actionManager_; +} + -(CCAction*) runAction:(CCAction*) action { NSAssert( action != nil, @"Argument must be non-nil"); - - [[CCActionManager sharedManager] addAction:action target:self paused:!isRunning_]; + + [actionManager_ addAction:action target:self paused:!isRunning_]; return action; } -(void) stopAllActions { - [[CCActionManager sharedManager] removeAllActionsFromTarget:self]; + [actionManager_ removeAllActionsFromTarget:self]; } -(void) stopAction: (CCAction*) action { - [[CCActionManager sharedManager] removeAction:action]; + [actionManager_ removeAction:action]; } --(void) stopActionByTag:(int)aTag +-(void) stopActionByTag:(NSInteger)aTag { NSAssert( aTag != kCCActionTagInvalid, @"Invalid tag"); - [[CCActionManager sharedManager] removeActionByTag:aTag target:self]; + [actionManager_ removeActionByTag:aTag target:self]; } --(CCAction*) getActionByTag:(int) aTag +-(CCAction*) getActionByTag:(NSInteger) aTag { NSAssert( aTag != kCCActionTagInvalid, @"Invalid tag"); - return [[CCActionManager sharedManager] getActionByTag:aTag target:self]; + return [actionManager_ getActionByTag:aTag target:self]; } --(int) numberOfRunningActions +-(NSUInteger) numberOfRunningActions { - return [[CCActionManager sharedManager] numberOfRunningActionsInTarget:self]; + return [actionManager_ numberOfRunningActionsInTarget:self]; } #pragma mark CCNode - Scheduler +-(void) setScheduler:(CCScheduler *)scheduler +{ + if( scheduler != scheduler_ ) { + [self unscheduleAllSelectors]; + [scheduler_ release]; + + scheduler_ = [scheduler retain]; + } +} + +-(CCScheduler*) scheduler +{ + return scheduler_; +} + -(void) scheduleUpdate { [self scheduleUpdateWithPriority:0]; } --(void) scheduleUpdateWithPriority:(int)priority +-(void) scheduleUpdateWithPriority:(NSInteger)priority { - [[CCScheduler sharedScheduler] scheduleUpdateForTarget:self priority:priority paused:!isRunning_]; + [scheduler_ scheduleUpdateForTarget:self priority:priority paused:!isRunning_]; } -(void) unscheduleUpdate { - [[CCScheduler sharedScheduler] unscheduleUpdateForTarget:self]; + [scheduler_ unscheduleUpdateForTarget:self]; } -(void) schedule:(SEL)selector { - [self schedule:selector interval:0]; + [self schedule:selector interval:0 repeat:kCCRepeatForever delay:0]; } -(void) schedule:(SEL)selector interval:(ccTime)interval +{ + [self schedule:selector interval:interval repeat:kCCRepeatForever delay:0]; +} + +-(void) schedule:(SEL)selector interval:(ccTime)interval repeat: (uint) repeat delay:(ccTime) delay { NSAssert( selector != nil, @"Argument must be non-nil"); NSAssert( interval >=0, @"Arguemnt must be positive"); - - [[CCScheduler sharedScheduler] scheduleSelector:selector forTarget:self interval:interval paused:!isRunning_]; + + [scheduler_ scheduleSelector:selector forTarget:self interval:interval paused:!isRunning_ repeat:repeat delay:delay]; +} + +- (void) scheduleOnce:(SEL) selector delay:(ccTime) delay +{ + [self schedule:selector interval:0.f repeat:0 delay:delay]; } -(void) unschedule:(SEL)selector @@ -727,24 +728,24 @@ -(void) unschedule:(SEL)selector // explicit nil handling if (selector == nil) return; - - [[CCScheduler sharedScheduler] unscheduleSelector:selector forTarget:self]; + + [scheduler_ unscheduleSelector:selector forTarget:self]; } -(void) unscheduleAllSelectors { - [[CCScheduler sharedScheduler] unscheduleAllSelectorsForTarget:self]; + [scheduler_ unscheduleAllSelectorsForTarget:self]; } - (void) resumeSchedulerAndActions { - [[CCScheduler sharedScheduler] resumeTarget:self]; - [[CCActionManager sharedManager] resumeTarget:self]; + [scheduler_ resumeTarget:self]; + [actionManager_ resumeTarget:self]; } - (void) pauseSchedulerAndActions { - [[CCScheduler sharedScheduler] pauseTarget:self]; - [[CCActionManager sharedManager] pauseTarget:self]; + [scheduler_ pauseTarget:self]; + [actionManager_ pauseTarget:self]; } #pragma mark CCNode Transform @@ -752,27 +753,56 @@ - (void) pauseSchedulerAndActions - (CGAffineTransform)nodeToParentTransform { if ( isTransformDirty_ ) { - - transform_ = CGAffineTransformIdentity; - - if ( !isRelativeAnchorPoint_ && !CGPointEqualToPoint(anchorPointInPixels_, CGPointZero) ) - transform_ = CGAffineTransformTranslate(transform_, anchorPointInPixels_.x, anchorPointInPixels_.y); - - if( ! CGPointEqualToPoint(positionInPixels_, CGPointZero) ) - transform_ = CGAffineTransformTranslate(transform_, positionInPixels_.x, positionInPixels_.y); - - if( rotation_ != 0 ) - transform_ = CGAffineTransformRotate(transform_, -CC_DEGREES_TO_RADIANS(rotation_)); - - if( ! (scaleX_ == 1 && scaleY_ == 1) ) - transform_ = CGAffineTransformScale(transform_, scaleX_, scaleY_); - - if( ! CGPointEqualToPoint(anchorPointInPixels_, CGPointZero) ) - transform_ = CGAffineTransformTranslate(transform_, -anchorPointInPixels_.x, -anchorPointInPixels_.y); - + + // Translate values + float x = position_.x; + float y = position_.y; + + if ( !isRelativeAnchorPoint_ ) { + x += anchorPointInPoints_.x; + y += anchorPointInPoints_.y; + } + + // Rotation values + float c = 1, s = 0; + if( rotation_ ) { + float radians = -CC_DEGREES_TO_RADIANS(rotation_); + c = cosf(radians); + s = sinf(radians); + } + + BOOL needsSkewMatrix = ( skewX_ || skewY_ ); + + + // optimization: + // inline anchor point calculation if skew is not needed + if( !needsSkewMatrix && !CGPointEqualToPoint(anchorPointInPoints_, CGPointZero) ) { + x += c * -anchorPointInPoints_.x * scaleX_ + -s * -anchorPointInPoints_.y * scaleY_; + y += s * -anchorPointInPoints_.x * scaleX_ + c * -anchorPointInPoints_.y * scaleY_; + } + + + // Build Transform Matrix + transform_ = CGAffineTransformMake( c * scaleX_, s * scaleX_, + -s * scaleY_, c * scaleY_, + x, y ); + + // XXX: Try to inline skew + // If skew is needed, apply skew and then anchor point + if( needsSkewMatrix ) { + CGAffineTransform skewMatrix = CGAffineTransformMake(1.0f, tanf(CC_DEGREES_TO_RADIANS(skewY_)), + tanf(CC_DEGREES_TO_RADIANS(skewX_)), 1.0f, + 0.0f, 0.0f ); + transform_ = CGAffineTransformConcat(skewMatrix, transform_); + + // adjust anchor point + if( ! CGPointEqualToPoint(anchorPointInPoints_, CGPointZero) ) + transform_ = CGAffineTransformTranslate(transform_, -anchorPointInPoints_.x, -anchorPointInPoints_.y); + } + isTransformDirty_ = NO; } - + return transform_; } @@ -782,17 +812,17 @@ - (CGAffineTransform)parentToNodeTransform inverse_ = CGAffineTransformInvert([self nodeToParentTransform]); isInverseDirty_ = NO; } - + return inverse_; } - (CGAffineTransform)nodeToWorldTransform { CGAffineTransform t = [self nodeToParentTransform]; - + for (CCNode *p = parent_; p != nil; p = p.parent) t = CGAffineTransformConcat(t, [p nodeToParentTransform]); - + return t; } @@ -803,53 +833,25 @@ - (CGAffineTransform)worldToNodeTransform - (CGPoint)convertToNodeSpace:(CGPoint)worldPoint { - CGPoint ret; - if( CC_CONTENT_SCALE_FACTOR() == 1 ) - ret = CGPointApplyAffineTransform(worldPoint, [self worldToNodeTransform]); - else { - ret = ccpMult( worldPoint, CC_CONTENT_SCALE_FACTOR() ); - ret = CGPointApplyAffineTransform(ret, [self worldToNodeTransform]); - ret = ccpMult( ret, 1/CC_CONTENT_SCALE_FACTOR() ); - } - + CGPoint ret = CGPointApplyAffineTransform(worldPoint, [self worldToNodeTransform]); return ret; } - (CGPoint)convertToWorldSpace:(CGPoint)nodePoint { - CGPoint ret; - if( CC_CONTENT_SCALE_FACTOR() == 1 ) - ret = CGPointApplyAffineTransform(nodePoint, [self nodeToWorldTransform]); - else { - ret = ccpMult( nodePoint, CC_CONTENT_SCALE_FACTOR() ); - ret = CGPointApplyAffineTransform(ret, [self nodeToWorldTransform]); - ret = ccpMult( ret, 1/CC_CONTENT_SCALE_FACTOR() ); - } - + CGPoint ret = CGPointApplyAffineTransform(nodePoint, [self nodeToWorldTransform]); return ret; } - (CGPoint)convertToNodeSpaceAR:(CGPoint)worldPoint { CGPoint nodePoint = [self convertToNodeSpace:worldPoint]; - CGPoint anchorInPoints; - if( CC_CONTENT_SCALE_FACTOR() == 1 ) - anchorInPoints = anchorPointInPixels_; - else - anchorInPoints = ccpMult( anchorPointInPixels_, 1/CC_CONTENT_SCALE_FACTOR() ); - - return ccpSub(nodePoint, anchorInPoints); + return ccpSub(nodePoint, anchorPointInPoints_); } - (CGPoint)convertToWorldSpaceAR:(CGPoint)nodePoint { - CGPoint anchorInPoints; - if( CC_CONTENT_SCALE_FACTOR() == 1 ) - anchorInPoints = anchorPointInPixels_; - else - anchorInPoints = ccpMult( anchorPointInPixels_, 1/CC_CONTENT_SCALE_FACTOR() ); - - nodePoint = ccpAdd(nodePoint, anchorInPoints); + nodePoint = ccpAdd(nodePoint, anchorPointInPoints_); return [self convertToWorldSpace:nodePoint]; } @@ -861,7 +863,7 @@ - (CGPoint)convertToWindowSpace:(CGPoint)nodePoint // convenience methods which take a UITouch instead of CGPoint -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS - (CGPoint)convertTouchToNodeSpace:(UITouch *)touch { @@ -877,7 +879,7 @@ - (CGPoint)convertTouchToNodeSpaceAR:(UITouch *)touch return [self convertToNodeSpaceAR:point]; } -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_IOS @end diff --git a/Example/libs/cocos2d/CCParallaxNode.h b/Example/libs/cocos2d/CCParallaxNode.h index c41b304..9f3eac3 100644 --- a/Example/libs/cocos2d/CCParallaxNode.h +++ b/Example/libs/cocos2d/CCParallaxNode.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,9 +28,9 @@ #import "Support/ccCArray.h" /** CCParallaxNode: A node that simulates a parallax scroller - + The children will be moved faster / slower than the parent according the the parallax ratio. - + */ @interface CCParallaxNode : CCNode { @@ -44,6 +45,6 @@ It returns self, so you can chain several addChilds. @since v0.8 */ --(void) addChild: (CCNode*)node z:(int)z parallaxRatio:(CGPoint)c positionOffset:(CGPoint)positionOffset; +-(void) addChild: (CCNode*)node z:(NSInteger)z parallaxRatio:(CGPoint)c positionOffset:(CGPoint)positionOffset; @end diff --git a/Example/libs/cocos2d/CCParallaxNode.m b/Example/libs/cocos2d/CCParallaxNode.m index 20f573c..d30486c 100644 --- a/Example/libs/cocos2d/CCParallaxNode.m +++ b/Example/libs/cocos2d/CCParallaxNode.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,9 +34,9 @@ @interface CGPointObject : NSObject CGPoint offset_; CCNode *child_; // weak ref } -@property (readwrite) CGPoint ratio; -@property (readwrite) CGPoint offset; -@property (readwrite,assign) CCNode *child; +@property (nonatomic,readwrite) CGPoint ratio; +@property (nonatomic,readwrite) CGPoint offset; +@property (nonatomic,readwrite,assign) CCNode *child; +(id) pointWithCGPoint:(CGPoint)point offset:(CGPoint)offset; -(id) initWithCGPoint:(CGPoint)point offset:(CGPoint)offset; @end @@ -65,7 +66,7 @@ @implementation CCParallaxNode -(id) init { if( (self=[super init]) ) { - parallaxArray_ = ccArrayNew(5); + parallaxArray_ = ccArrayNew(5); lastPosition = CGPointMake(-100,-100); } return self; @@ -80,23 +81,23 @@ - (void) dealloc [super dealloc]; } --(void) addChild:(CCNode*)child z:(int)z tag:(int)tag +-(void) addChild:(CCNode*)child z:(NSInteger)z tag:(NSInteger)tag { NSAssert(NO,@"ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); } --(void) addChild: (CCNode*) child z:(int)z parallaxRatio:(CGPoint)ratio positionOffset:(CGPoint)offset +-(void) addChild: (CCNode*) child z:(NSInteger)z parallaxRatio:(CGPoint)ratio positionOffset:(CGPoint)offset { NSAssert( child != nil, @"Argument must be non-nil"); CGPointObject *obj = [CGPointObject pointWithCGPoint:ratio offset:offset]; obj.child = child; ccArrayAppendObjectWithResize(parallaxArray_, obj); - + CGPoint pos = self.position; pos.x = pos.x * ratio.x + offset.x; pos.y = pos.y * ratio.y + offset.y; child.position = pos; - + [super addChild: child z:z tag:child.tag]; } @@ -121,21 +122,21 @@ -(void) removeAllChildrenWithCleanup:(BOOL)cleanup -(CGPoint) absolutePosition_ { CGPoint ret = position_; - + CCNode *cn = self; - + while (cn.parent != nil) { cn = cn.parent; ret = ccpAdd( ret, cn.position ); } - + return ret; } /* The positions are updated at visit because: - using a timer is not guaranteed that it will called after all the positions were updated - - overriding "draw" will only precise if the children have a z > 0 + - overriding "draw" will only be precise if the children have a z > 0 */ -(void) visit { @@ -143,18 +144,18 @@ -(void) visit // CGPoint pos = [self convertToWorldSpace:CGPointZero]; CGPoint pos = [self absolutePosition_]; if( ! CGPointEqualToPoint(pos, lastPosition) ) { - + for(unsigned int i=0; i < parallaxArray_->num; i++ ) { CGPointObject *point = parallaxArray_->arr[i]; float x = -pos.x + pos.x * point.ratio.x + point.offset.x; - float y = -pos.y + pos.y * point.ratio.y + point.offset.y; + float y = -pos.y + pos.y * point.ratio.y + point.offset.y; point.child.position = ccp(x,y); } - + lastPosition = pos; } - + [super visit]; } @end diff --git a/Example/libs/cocos2d/CCParticleExamples.h b/Example/libs/cocos2d/CCParticleExamples.h index b28fca9..9952726 100644 --- a/Example/libs/cocos2d/CCParticleExamples.h +++ b/Example/libs/cocos2d/CCParticleExamples.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,15 +25,13 @@ */ -#import - -#import "CCParticleSystemPoint.h" +#import "ccMacros.h" #import "CCParticleSystemQuad.h" // build each architecture with the optimal particle system // ARMv7, Mac or Simulator use "Quad" particle -#if defined(__ARM_NEON__) || defined(__MAC_OS_X_VERSION_MAX_ALLOWED) || TARGET_IPHONE_SIMULATOR +#if defined(__ARM_NEON__) || defined(__CC_PLATFORM_MAC) || TARGET_IPHONE_SIMULATOR #define ARCH_OPTIMAL_PARTICLE_SYSTEM CCParticleSystemQuad // ARMv6 use "Point" particle diff --git a/Example/libs/cocos2d/CCParticleExamples.m b/Example/libs/cocos2d/CCParticleExamples.m index c3b8f8f..c21cf83 100644 --- a/Example/libs/cocos2d/CCParticleExamples.m +++ b/Example/libs/cocos2d/CCParticleExamples.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,7 +40,7 @@ -(id) init return [self initWithTotalParticles:1500]; } --(id) initWithTotalParticles:(int)p +-(id) initWithTotalParticles:(NSUInteger)p { if( (self=[super initWithTotalParticles:p]) ) { // duration @@ -50,7 +51,7 @@ -(id) initWithTotalParticles:(int)p // Gravity Mode: gravity self.gravity = ccp(0,-90); - + // Gravity Mode: radial self.radialAccel = 0; self.radialAccelVar = 0; @@ -58,22 +59,22 @@ -(id) initWithTotalParticles:(int)p // Gravity Mode: speed of particles self.speed = 180; self.speedVar = 50; - + // emitter position CGSize winSize = [[CCDirector sharedDirector] winSize]; self.position = ccp(winSize.width/2, winSize.height/2); - + // angle angle = 90; angleVar = 20; - + // life of particles life = 3.5f; lifeVar = 1; - + // emits per frame emissionRate = totalParticles/life; - + // color of particles startColor.r = 0.5f; startColor.g = 0.5f; @@ -91,7 +92,7 @@ -(id) initWithTotalParticles:(int)p endColorVar.g = 0.1f; endColorVar.b = 0.1f; endColorVar.a = 0.2f; - + // size, in pixels startSize = 8.0f; startSizeVar = 2.0f; @@ -102,7 +103,7 @@ -(id) initWithTotalParticles:(int)p // additive self.blendAdditive = NO; } - + return self; } @end @@ -116,7 +117,7 @@ -(id) init return [self initWithTotalParticles:250]; } --(id) initWithTotalParticles:(int) p +-(id) initWithTotalParticles:(NSUInteger) p { if( (self=[super initWithTotalParticles:p]) ) { @@ -128,29 +129,29 @@ -(id) initWithTotalParticles:(int) p // Gravity Mode: gravity self.gravity = ccp(0,0); - + // Gravity Mode: radial acceleration self.radialAccel = 0; self.radialAccelVar = 0; - + // Gravity Mode: speed of particles self.speed = 60; - self.speedVar = 20; - + self.speedVar = 20; + // starting angle angle = 90; angleVar = 10; - + // emitter position CGSize winSize = [[CCDirector sharedDirector] winSize]; self.position = ccp(winSize.width/2, 60); posVar = ccp(40, 20); - + // life of particles life = 3; lifeVar = 0.25f; - - + + // size, in pixels startSize = 54.0f; startSizeVar = 10.0f; @@ -158,7 +159,7 @@ -(id) initWithTotalParticles:(int) p // emits per frame emissionRate = totalParticles/life; - + // color of particles startColor.r = 0.76f; startColor.g = 0.25f; @@ -176,13 +177,13 @@ -(id) initWithTotalParticles:(int) p endColorVar.g = 0.0f; endColorVar.b = 0.0f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - + // additive self.blendAdditive = YES; } - + return self; } @end @@ -196,44 +197,44 @@ -(id) init return [self initWithTotalParticles:350]; } --(id) initWithTotalParticles:(int) p +-(id) initWithTotalParticles:(NSUInteger) p { if( (self=[super initWithTotalParticles:p]) ) { // additive self.blendAdditive = YES; - + // duration duration = kCCParticleDurationInfinity; - + // Gravity Mode self.emitterMode = kCCParticleModeGravity; - + // Gravity Mode: gravity self.gravity = ccp(0,0); - + // Gravity mode: radial acceleration self.radialAccel = 0; self.radialAccelVar = 0; - + // Gravity mode: speed of particles self.speed = 20; self.speedVar = 5; - - + + // angle angle = 90; angleVar = 360; - + // emitter position CGSize winSize = [[CCDirector sharedDirector] winSize]; self.position = ccp(winSize.width/2, winSize.height/2); posVar = CGPointZero; - + // life of particles life = 1; lifeVar = 0.5f; - + // size, in pixels startSize = 30.0f; startSizeVar = 10.0f; @@ -241,7 +242,7 @@ -(id) initWithTotalParticles:(int) p // emits per seconds emissionRate = totalParticles/life; - + // color of particles startColor.r = 0.76f; startColor.g = 0.25f; @@ -259,10 +260,10 @@ -(id) initWithTotalParticles:(int) p endColorVar.g = 0.0f; endColorVar.b = 0.0f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; } - + return self; } @end @@ -276,7 +277,7 @@ -(id) init return [self initWithTotalParticles:200]; } --(id) initWithTotalParticles:(int)p +-(id) initWithTotalParticles:(NSUInteger)p { if( (self=[super initWithTotalParticles:p]) ) { @@ -288,40 +289,40 @@ -(id) initWithTotalParticles:(int)p // Gravity Mode: gravity self.gravity = ccp(0,0); - + // Gravity Mode: speed of particles self.speed = 60; self.speedVar = 10; - + // Gravity Mode: radial self.radialAccel = -80; self.radialAccelVar = 0; - + // Gravity Mode: tagential self.tangentialAccel = 80; self.tangentialAccelVar = 0; - + // angle angle = 90; angleVar = 360; - + // emitter position CGSize winSize = [[CCDirector sharedDirector] winSize]; self.position = ccp(winSize.width/2, winSize.height/2); posVar = CGPointZero; - + // life of particles life = 4; lifeVar = 1; - + // size, in pixels startSize = 37.0f; startSizeVar = 10.0f; endSize = kCCParticleStartSizeEqualToEndSize; - + // emits per second emissionRate = totalParticles/life; - + // color of particles startColor.r = 0.12f; startColor.g = 0.25f; @@ -339,13 +340,13 @@ -(id) initWithTotalParticles:(int)p endColorVar.g = 0.0f; endColorVar.b = 0.0f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; // additive self.blendAdditive = YES; } - + return self; } @end @@ -359,10 +360,10 @@ -(id) init return [self initWithTotalParticles:250]; } --(id) initWithTotalParticles:(int) p +-(id) initWithTotalParticles:(NSUInteger) p { if( (self=[super initWithTotalParticles:p]) ) { - + // duration duration = kCCParticleDurationInfinity; @@ -371,15 +372,15 @@ -(id) initWithTotalParticles:(int) p // Gravity Mode: gravity self.gravity = ccp(0,0); - + // Gravity Mode: speed of particles self.speed = 80; self.speedVar = 10; - + // Gravity Mode: radial self.radialAccel = -60; self.radialAccelVar = 0; - + // Gravity Mode: tagential self.tangentialAccel = 15; self.tangentialAccelVar = 0; @@ -387,16 +388,16 @@ -(id) initWithTotalParticles:(int) p // angle angle = 90; angleVar = 360; - + // emitter position CGSize winSize = [[CCDirector sharedDirector] winSize]; self.position = ccp(winSize.width/2, winSize.height/2); posVar = CGPointZero; - + // life of particles life = 4; lifeVar = 1; - + // size, in pixels startSize = 30.0f; startSizeVar = 10.0f; @@ -404,7 +405,7 @@ -(id) initWithTotalParticles:(int) p // emits per second emissionRate = totalParticles/life; - + // color of particles startColor.r = 0.50f; startColor.g = 0.50f; @@ -422,13 +423,13 @@ -(id) initWithTotalParticles:(int) p endColorVar.g = 0.0f; endColorVar.b = 0.0f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; // additive self.blendAdditive = YES; } - + return self; } @end @@ -442,13 +443,13 @@ -(id) init return [self initWithTotalParticles:150]; } --(id) initWithTotalParticles:(int) p +-(id) initWithTotalParticles:(NSUInteger) p { if( (self=[super initWithTotalParticles:p]) ) { // duration duration = kCCParticleDurationInfinity; - + // Gravity Mode self.emitterMode = kCCParticleModeGravity; @@ -458,28 +459,28 @@ -(id) initWithTotalParticles:(int) p // Gravity Mode: speed of particles self.speed = 15; self.speedVar = 5; - + // Gravity Mode: radial self.radialAccel = 0; self.radialAccelVar = 0; - + // Gravity Mode: tagential self.tangentialAccel = 0; self.tangentialAccelVar = 0; - + // angle angle = 90; angleVar = 360; - + // emitter position CGSize winSize = [[CCDirector sharedDirector] winSize]; self.position = ccp(winSize.width/2, winSize.height/2); posVar = CGPointZero; - + // life of particles life = 2; lifeVar = 1; - + // size, in pixels startSize = 60.0f; startSizeVar = 10.0f; @@ -487,7 +488,7 @@ -(id) initWithTotalParticles:(int) p // emits per second emissionRate = totalParticles/life; - + // color of particles startColor.r = 0.2f; startColor.g = 0.4f; @@ -505,13 +506,13 @@ -(id) initWithTotalParticles:(int) p endColorVar.g = 0.0f; endColorVar.b = 0.0f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - + // additive self.blendAdditive = YES; } - + return self; } @end @@ -525,44 +526,44 @@ -(id) init return [self initWithTotalParticles:500]; } --(id) initWithTotalParticles:(int) p +-(id) initWithTotalParticles:(NSUInteger) p { if( (self=[super initWithTotalParticles:p]) ) { - + // duration duration = kCCParticleDurationInfinity; // Gravity Mode self.emitterMode = kCCParticleModeGravity; - + // Gravity Mode: gravity self.gravity = ccp(0,0); - + // Gravity Mode: speed of particles self.speed = 150; self.speedVar = 0; - + // Gravity Mode: radial self.radialAccel = -380; self.radialAccelVar = 0; - + // Gravity Mode: tagential self.tangentialAccel = 45; self.tangentialAccelVar = 0; - + // angle angle = 90; angleVar = 0; - + // emitter position CGSize winSize = [[CCDirector sharedDirector] winSize]; self.position = ccp(winSize.width/2, winSize.height/2); posVar = CGPointZero; - + // life of particles life = 12; lifeVar = 0; - + // size, in pixels startSize = 20.0f; startSizeVar = 0.0f; @@ -570,7 +571,7 @@ -(id) initWithTotalParticles:(int) p // emits per second emissionRate = totalParticles/life; - + // color of particles startColor.r = 0.5f; startColor.g = 0.5f; @@ -588,13 +589,13 @@ -(id) initWithTotalParticles:(int) p endColorVar.g = 0.5f; endColorVar.b = 0.5f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; // additive self.blendAdditive = NO; } - + return self; } @end @@ -608,43 +609,43 @@ -(id) init return [self initWithTotalParticles:700]; } --(id) initWithTotalParticles:(int)p +-(id) initWithTotalParticles:(NSUInteger)p { if( (self=[super initWithTotalParticles:p]) ) { - + // duration duration = 0.1f; - + self.emitterMode = kCCParticleModeGravity; // Gravity Mode: gravity self.gravity = ccp(0,0); - + // Gravity Mode: speed of particles self.speed = 70; self.speedVar = 40; - + // Gravity Mode: radial self.radialAccel = 0; self.radialAccelVar = 0; - + // Gravity Mode: tagential self.tangentialAccel = 0; self.tangentialAccelVar = 0; - + // angle angle = 90; angleVar = 360; - + // emitter position CGSize winSize = [[CCDirector sharedDirector] winSize]; self.position = ccp(winSize.width/2, winSize.height/2); posVar = CGPointZero; - + // life of particles life = 5.0f; lifeVar = 2; - + // size, in pixels startSize = 15.0f; startSizeVar = 10.0f; @@ -652,7 +653,7 @@ -(id) initWithTotalParticles:(int)p // emits per second emissionRate = totalParticles/duration; - + // color of particles startColor.r = 0.7f; startColor.g = 0.1f; @@ -670,13 +671,13 @@ -(id) initWithTotalParticles:(int)p endColorVar.g = 0.5f; endColorVar.b = 0.5f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; // additive self.blendAdditive = NO; } - + return self; } @end @@ -690,40 +691,40 @@ -(id) init return [self initWithTotalParticles:200]; } --(id) initWithTotalParticles:(int) p +-(id) initWithTotalParticles:(NSUInteger) p { if( (self=[super initWithTotalParticles:p]) ) { - + // duration duration = kCCParticleDurationInfinity; - + // Emitter mode: Gravity Mode self.emitterMode = kCCParticleModeGravity; - + // Gravity Mode: gravity self.gravity = ccp(0,0); // Gravity Mode: radial acceleration self.radialAccel = 0; self.radialAccelVar = 0; - + // Gravity Mode: speed of particles self.speed = 25; self.speedVar = 10; - + // angle angle = 90; angleVar = 5; - + // emitter position CGSize winSize = [[CCDirector sharedDirector] winSize]; self.position = ccp(winSize.width/2, 0); posVar = ccp(20, 0); - + // life of particles life = 4; lifeVar = 1; - + // size, in pixels startSize = 60.0f; startSizeVar = 10.0f; @@ -731,7 +732,7 @@ -(id) initWithTotalParticles:(int) p // emits per frame emissionRate = totalParticles/life; - + // color of particles startColor.r = 0.8f; startColor.g = 0.8f; @@ -749,13 +750,13 @@ -(id) initWithTotalParticles:(int) p endColorVar.g = 0.0f; endColorVar.b = 0.0f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - + // additive self.blendAdditive = NO; } - + return self; } @end @@ -766,38 +767,38 @@ -(id) init return [self initWithTotalParticles:700]; } --(id) initWithTotalParticles:(int)p +-(id) initWithTotalParticles:(NSUInteger)p { if( (self=[super initWithTotalParticles:p]) ) { - + // duration duration = kCCParticleDurationInfinity; - + // set gravity mode. self.emitterMode = kCCParticleModeGravity; // Gravity Mode: gravity self.gravity = ccp(0,-1); - + // Gravity Mode: speed of particles self.speed = 5; self.speedVar = 1; - + // Gravity Mode: radial self.radialAccel = 0; self.radialAccelVar = 1; - + // Gravity mode: tagential self.tangentialAccel = 0; self.tangentialAccelVar = 1; - + // emitter position self.position = (CGPoint) { [[CCDirector sharedDirector] winSize].width / 2, [[CCDirector sharedDirector] winSize].height + 10 }; posVar = ccp( [[CCDirector sharedDirector] winSize].width / 2, 0 ); - + // angle angle = -90; angleVar = 5; @@ -805,7 +806,7 @@ -(id) initWithTotalParticles:(int)p // life of particles life = 45; lifeVar = 15; - + // size, in pixels startSize = 10.0f; startSizeVar = 5.0f; @@ -813,7 +814,7 @@ -(id) initWithTotalParticles:(int)p // emits per second emissionRate = 10; - + // color of particles startColor.r = 1.0f; startColor.g = 1.0f; @@ -831,13 +832,13 @@ -(id) initWithTotalParticles:(int)p endColorVar.g = 0.0f; endColorVar.b = 0.0f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - + // additive self.blendAdditive = NO; } - + return self; } @end @@ -848,22 +849,22 @@ -(id) init return [self initWithTotalParticles:1000]; } --(id) initWithTotalParticles:(int)p +-(id) initWithTotalParticles:(NSUInteger)p { if( (self=[super initWithTotalParticles:p]) ) { - + // duration duration = kCCParticleDurationInfinity; - + self.emitterMode = kCCParticleModeGravity; // Gravity Mode: gravity self.gravity = ccp(10,-10); - + // Gravity Mode: radial self.radialAccel = 0; self.radialAccelVar = 1; - + // Gravity Mode: tagential self.tangentialAccel = 0; self.tangentialAccelVar = 1; @@ -871,23 +872,23 @@ -(id) initWithTotalParticles:(int)p // Gravity Mode: speed of particles self.speed = 130; self.speedVar = 30; - + // angle angle = -90; angleVar = 5; - - + + // emitter position self.position = (CGPoint) { [[CCDirector sharedDirector] winSize].width / 2, [[CCDirector sharedDirector] winSize].height }; posVar = ccp( [[CCDirector sharedDirector] winSize].width / 2, 0 ); - + // life of particles life = 4.5f; lifeVar = 0; - + // size, in pixels startSize = 4.0f; startSizeVar = 2.0f; @@ -895,7 +896,7 @@ -(id) initWithTotalParticles:(int)p // emits per second emissionRate = 20; - + // color of particles startColor.r = 0.7f; startColor.g = 0.8f; @@ -913,13 +914,13 @@ -(id) initWithTotalParticles:(int)p endColorVar.g = 0.0f; endColorVar.b = 0.0f; endColorVar.a = 0.0f; - + self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - + // additive self.blendAdditive = NO; } - + return self; } @end diff --git a/Example/libs/cocos2d/CCParticleSystem.h b/Example/libs/cocos2d/CCParticleSystem.h index e87961d..82c70d0 100644 --- a/Example/libs/cocos2d/CCParticleSystem.h +++ b/Example/libs/cocos2d/CCParticleSystem.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,9 +30,7 @@ #import "ccTypes.h" #import "ccConfig.h" -#if CC_ENABLE_PROFILERS -@class CCProfilingTimer; -#endif +@class CCParticleBatchNode; //* @enum enum { @@ -40,7 +39,7 @@ enum { /** The starting size of the particle is equal to the ending size */ kCCParticleStartSizeEqualToEndSize = -1, - + /** The starting radius of the particle is equal to the ending radius */ kCCParticleStartRadiusEqualToEndRadius = -1, @@ -53,9 +52,9 @@ enum { enum { /** Gravity mode (A mode) */ kCCParticleModeGravity, - + /** Radius mode (B mode) */ - kCCParticleModeRadius, + kCCParticleModeRadius, }; @@ -70,7 +69,7 @@ typedef enum { Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite. */ kCCPositionTypeRelative, - + /** Living particles are attached to the emitter and are translated along with it. */ kCCPositionTypeGrouped, }tCCPositionType; @@ -79,7 +78,7 @@ typedef enum { enum { kPositionTypeFree = kCCPositionTypeFree, kPositionTypeGrouped = kCCPositionTypeGrouped, -}; +}; /** @struct tCCParticle Structure that contains the values of each particle @@ -99,6 +98,8 @@ typedef struct sCCParticle { ccTime timeToLive; + NSUInteger atlasIndex; + union { // Mode A: gravity, direction, radial accel, tangential accel struct { @@ -106,7 +107,7 @@ typedef struct sCCParticle { float radialAccel; float tangentialAccel; } A; - + // Mode B: radius mode struct { float angle; @@ -149,43 +150,43 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/). 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, - cocos2d uses a another approach, but the results are almost identical. - + cocos2d uses a another approach, but the results are almost identical. + cocos2d supports all the variables used by Particle Designer plus a bit more: - spinning particles (supported when using CCParticleSystemQuad) - tangential acceleration (Gravity mode) - radial acceleration (Gravity mode) - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only) - + It is possible to customize any of the above mentioned properties in runtime. Example: - + @code emitter.radialAccel = 15; emitter.startSpin = 0; @endcode - + */ @interface CCParticleSystem : CCNode -{ +{ // is the particle system active ? BOOL active; // duration in seconds of the system. -1 is infinity float duration; // time elapsed since the start of the system (in seconds) float elapsed; - + // position is from "superclass" CocosNode CGPoint sourcePosition; // Position variance CGPoint posVar; - + // The angle (direction) of the particles measured in degrees float angle; // Angle variance measured in degrees; float angleVar; - + // Different modes - + NSInteger emitterMode_; union { // Mode A:Gravity + Tangential Accel + Radial Accel @@ -211,7 +212,7 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); // Mode B: circular movement (gravity, radial accel and tangential accel don't are not used in this mode) struct { - + // The starting radius of the particles float startRadius; // The starting radius variance of the particles @@ -219,14 +220,14 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); // The ending radius of the particles float endRadius; // The ending radius variance of the particles - float endRadiusVar; + float endRadiusVar; // Number of degress to rotate a particle around the source pos per second float rotatePerSecond; // Variance in degrees for rotatePerSecond float rotatePerSecondVar; } B; } mode; - + // start ize of the particles float startSize; // start Size variance @@ -235,12 +236,12 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); float endSize; // end size of variance float endSizeVar; - + // How many seconds will the particle live float life; // Life variance float lifeVar; - + // Start color of the particles ccColor4F startColor; // Start color variance @@ -249,7 +250,7 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); ccColor4F endColor; // End color variance ccColor4F endColorVar; - + // start angle of the particles float startSpin; // start angle variance @@ -258,22 +259,20 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); float endSpin; // end angle ariance float endSpinVar; - - + // Array of particles tCCParticle *particles; // Maximum particles NSUInteger totalParticles; // Count of active particles NSUInteger particleCount; - - // color modulate -// BOOL colorModulate; - + // Number of allocated particles + NSUInteger allocatedParticles; + // How many particles can be emitted per second float emissionRate; float emitCounter; - + // Texture of the particles CCTexture2D *texture_; // blend function @@ -287,15 +286,19 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); // particle idx NSUInteger particleIdx; - + // Optimization CC_UPDATE_PARTICLE_IMP updateParticleImp; SEL updateParticleSel; - -// profiling -#if CC_ENABLE_PROFILERS - CCProfilingTimer* _profilingTimer; -#endif + + // for batching. If nil, then it won't be batched + CCParticleBatchNode *batchNode_; + + // index of system in batch node array + NSUInteger atlasIndex_; + + //YES if scaled or rotated + BOOL transformSystemDirty_; } /** Is the emitter active */ @@ -339,7 +342,7 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); /** The ending radius of the particles. Only available in 'Radius' mode. */ @property (nonatomic,readwrite,assign) float endRadius; /** The ending radius variance of the particles. Only available in 'Radius' mode. */ -@property (nonatomic,readwrite,assign) float endRadiusVar; +@property (nonatomic,readwrite,assign) float endRadiusVar; /** Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. */ @property (nonatomic,readwrite,assign) float rotatePerSecond; /** Variance in degrees for rotatePerSecond. Only available in 'Radius' mode. */ @@ -400,6 +403,11 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); */ @property (nonatomic,readwrite) NSInteger emitterMode; +/** weak reference to the CCSpriteBatchNode that renders the CCSprite */ +@property (nonatomic,readwrite,assign) CCParticleBatchNode *batchNode; + +@property (nonatomic,readwrite) NSUInteger atlasIndex; + /** creates an initializes a CCParticleSystem from a plist file. This plist files can be creted manually or with Particle Designer: http://particledesigner.71squared.com/ @@ -414,17 +422,13 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); */ -(id) initWithFile:(NSString*) plistFile; -/** initializes a CCQuadParticleSystem from a NSDictionary. +/** initializes a particle system from a NSDictionary. @since v0.99.3 */ -(id) initWithDictionary:(NSDictionary*)dictionary; //! Initializes a system with a fixed number of particles --(id) initWithTotalParticles:(int) numberOfParticles; -//! Add a particle to the emitter --(BOOL) addParticle; -//! Initializes a particle --(void) initParticle: (tCCParticle*) particle; +-(id) initWithTotalParticles:(NSUInteger) numberOfParticles; //! stop emitting particles. Running particles will continue to run until they die -(void) stopSystem; //! Kill all living particles. @@ -440,5 +444,6 @@ typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); //! called in every loop. -(void) update: (ccTime) dt; -@end +-(void) updateWithNoTime; +@end diff --git a/Example/libs/cocos2d/CCParticleSystem.m b/Example/libs/cocos2d/CCParticleSystem.m index 1ee46da..6146ffd 100644 --- a/Example/libs/cocos2d/CCParticleSystem.m +++ b/Example/libs/cocos2d/CCParticleSystem.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,7 +39,7 @@ // // IMPORTANT: Particle Designer is supported by cocos2d, but // 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, -// cocos2d uses a another approach, but the results are almost identical. +// cocos2d uses a another approach, but the results are almost identical. // // opengl @@ -46,12 +47,12 @@ // cocos2d #import "ccConfig.h" -#if CC_ENABLE_PROFILERS -#import "Support/CCProfiling.h" -#endif #import "CCParticleSystem.h" +#import "CCParticleBatchNode.h" #import "CCTextureCache.h" +#import "CCTextureAtlas.h" #import "ccMacros.h" +#import "Support/CCProfiling.h" // support #import "Support/OpenGL_Internal.h" @@ -69,14 +70,13 @@ @implementation CCParticleSystem @synthesize startColor, startColorVar, endColor, endColorVar; @synthesize startSpin, startSpinVar, endSpin, endSpinVar; @synthesize emissionRate; -@synthesize totalParticles; @synthesize startSize, startSizeVar; @synthesize endSize, endSizeVar; @synthesize blendFunc = blendFunc_; @synthesize positionType = positionType_; @synthesize autoRemoveOnFinish = autoRemoveOnFinish_; @synthesize emitterMode = emitterMode_; - +@synthesize atlasIndex = atlasIndex_; +(id) particleWithFile:(NSString*) plistFile { @@ -84,79 +84,82 @@ +(id) particleWithFile:(NSString*) plistFile } -(id) init { - NSAssert(NO, @"CCParticleSystem: Init not supported."); - [self release]; - return nil; + return [self initWithTotalParticles:150]; } -(id) initWithFile:(NSString *)plistFile { NSString *path = [CCFileUtils fullPathFromRelativePath:plistFile]; NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - + NSAssert( dict != nil, @"Particles: file not found"); return [self initWithDictionary:dict]; } -(id) initWithDictionary:(NSDictionary *)dictionary { - NSUInteger maxParticles = [[dictionary valueForKey:@"maxParticles"] intValue]; + NSUInteger maxParticles = [[dictionary valueForKey:@"maxParticles"] integerValue]; // self, not super - if ((self=[self initWithTotalParticles:maxParticles] ) ) { - + + if ((self=[self initWithTotalParticles:maxParticles] ) ) + { // angle angle = [[dictionary valueForKey:@"angle"] floatValue]; angleVar = [[dictionary valueForKey:@"angleVariance"] floatValue]; - + // duration duration = [[dictionary valueForKey:@"duration"] floatValue]; - - // blend function + + // blend function blendFunc_.src = [[dictionary valueForKey:@"blendFuncSource"] intValue]; blendFunc_.dst = [[dictionary valueForKey:@"blendFuncDestination"] intValue]; - + // color float r,g,b,a; - + r = [[dictionary valueForKey:@"startColorRed"] floatValue]; g = [[dictionary valueForKey:@"startColorGreen"] floatValue]; b = [[dictionary valueForKey:@"startColorBlue"] floatValue]; a = [[dictionary valueForKey:@"startColorAlpha"] floatValue]; startColor = (ccColor4F) {r,g,b,a}; - + r = [[dictionary valueForKey:@"startColorVarianceRed"] floatValue]; g = [[dictionary valueForKey:@"startColorVarianceGreen"] floatValue]; b = [[dictionary valueForKey:@"startColorVarianceBlue"] floatValue]; a = [[dictionary valueForKey:@"startColorVarianceAlpha"] floatValue]; startColorVar = (ccColor4F) {r,g,b,a}; - + r = [[dictionary valueForKey:@"finishColorRed"] floatValue]; g = [[dictionary valueForKey:@"finishColorGreen"] floatValue]; b = [[dictionary valueForKey:@"finishColorBlue"] floatValue]; a = [[dictionary valueForKey:@"finishColorAlpha"] floatValue]; endColor = (ccColor4F) {r,g,b,a}; - + r = [[dictionary valueForKey:@"finishColorVarianceRed"] floatValue]; g = [[dictionary valueForKey:@"finishColorVarianceGreen"] floatValue]; b = [[dictionary valueForKey:@"finishColorVarianceBlue"] floatValue]; a = [[dictionary valueForKey:@"finishColorVarianceAlpha"] floatValue]; endColorVar = (ccColor4F) {r,g,b,a}; - + // particle size startSize = [[dictionary valueForKey:@"startParticleSize"] floatValue]; startSizeVar = [[dictionary valueForKey:@"startParticleSizeVariance"] floatValue]; endSize = [[dictionary valueForKey:@"finishParticleSize"] floatValue]; endSizeVar = [[dictionary valueForKey:@"finishParticleSizeVariance"] floatValue]; - - + // position float x = [[dictionary valueForKey:@"sourcePositionx"] floatValue]; float y = [[dictionary valueForKey:@"sourcePositiony"] floatValue]; self.position = ccp(x,y); posVar.x = [[dictionary valueForKey:@"sourcePositionVariancex"] floatValue]; posVar.y = [[dictionary valueForKey:@"sourcePositionVariancey"] floatValue]; - - + + // Spinning + startSpin = [[dictionary valueForKey:@"rotationStart"] floatValue]; + startSpinVar = [[dictionary valueForKey:@"rotationStartVariance"] floatValue]; + endSpin = [[dictionary valueForKey:@"rotationEnd"] floatValue]; + endSpinVar = [[dictionary valueForKey:@"rotationEndVariance"] floatValue]; + emitterMode_ = [[dictionary valueForKey:@"emitterType"] intValue]; // Mode A: Gravity + tangential accel + radial accel @@ -164,34 +167,33 @@ -(id) initWithDictionary:(NSDictionary *)dictionary // gravity mode.A.gravity.x = [[dictionary valueForKey:@"gravityx"] floatValue]; mode.A.gravity.y = [[dictionary valueForKey:@"gravityy"] floatValue]; - + // // speed mode.A.speed = [[dictionary valueForKey:@"speed"] floatValue]; mode.A.speedVar = [[dictionary valueForKey:@"speedVariance"] floatValue]; - - // radial acceleration + + // radial acceleration NSString *tmp = [dictionary valueForKey:@"radialAcceleration"]; mode.A.radialAccel = tmp ? [tmp floatValue] : 0; - + tmp = [dictionary valueForKey:@"radialAccelVariance"]; mode.A.radialAccelVar = tmp ? [tmp floatValue] : 0; - + // tangential acceleration tmp = [dictionary valueForKey:@"tangentialAcceleration"]; mode.A.tangentialAccel = tmp ? [tmp floatValue] : 0; - + tmp = [dictionary valueForKey:@"tangentialAccelVariance"]; mode.A.tangentialAccelVar = tmp ? [tmp floatValue] : 0; } - - + // or Mode B: radius movement else if( emitterMode_ == kCCParticleModeRadius ) { float maxRadius = [[dictionary valueForKey:@"maxRadius"] floatValue]; float maxRadiusVar = [[dictionary valueForKey:@"maxRadiusVariance"] floatValue]; float minRadius = [[dictionary valueForKey:@"minRadius"] floatValue]; - + mode.B.startRadius = maxRadius; mode.B.startRadiusVar = maxRadiusVar; mode.B.endRadius = minRadius; @@ -202,102 +204,109 @@ -(id) initWithDictionary:(NSDictionary *)dictionary } else { NSAssert( NO, @"Invalid emitterType in config file"); } - + // life span life = [[dictionary valueForKey:@"particleLifespan"] floatValue]; - lifeVar = [[dictionary valueForKey:@"particleLifespanVariance"] floatValue]; - + lifeVar = [[dictionary valueForKey:@"particleLifespanVariance"] floatValue]; + // emission Rate emissionRate = totalParticles/life; - // texture + //don't get the internal texture if a batchNode is used + if (!batchNode_) + { + // texture // Try to get the texture from the cache - NSString *textureName = [dictionary valueForKey:@"textureFileName"]; - - self.texture = [[CCTextureCache sharedTextureCache] addImage:textureName]; - - NSString *textureData = [dictionary valueForKey:@"textureImageData"]; - - if ( ! texture_ && textureData) { - - // if it fails, try to get it from the base64-gzipped data - unsigned char *buffer = NULL; - NSUInteger len = base64Decode((unsigned char*)[textureData UTF8String], [textureData length], &buffer); - NSAssert( buffer != NULL, @"CCParticleSystem: error decoding textureImageData"); - - unsigned char *deflated = NULL; - NSUInteger deflatedLen = ccInflateMemory(buffer, len, &deflated); - free( buffer ); - - NSAssert( deflated != NULL, @"CCParticleSystem: error ungzipping textureImageData"); - NSData *data = [[NSData alloc] initWithBytes:deflated length:deflatedLen]; - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - UIImage *image = [[UIImage alloc] initWithData:data]; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) - NSBitmapImageRep *image = [[NSBitmapImageRep alloc] initWithData:data]; + NSString *textureName = [dictionary valueForKey:@"textureFileName"]; + + CCTexture2D *tex = [[CCTextureCache sharedTextureCache] addImage:textureName]; + + if( tex ) + [self setTexture:tex]; + else { + + NSString *textureData = [dictionary valueForKey:@"textureImageData"]; + NSAssert( textureData, @"CCParticleSystem: Couldn't load texture"); + + // if it fails, try to get it from the base64-gzipped data + unsigned char *buffer = NULL; + int len = base64Decode((unsigned char*)[textureData UTF8String], (unsigned int)[textureData length], &buffer); + NSAssert( buffer != NULL, @"CCParticleSystem: error decoding textureImageData"); + + unsigned char *deflated = NULL; + NSUInteger deflatedLen = ccInflateMemory(buffer, len, &deflated); + free( buffer ); + + NSAssert( deflated != NULL, @"CCParticleSystem: error ungzipping textureImageData"); + NSData *data = [[NSData alloc] initWithBytes:deflated length:deflatedLen]; + +#ifdef __CC_PLATFORM_IOS + UIImage *image = [[UIImage alloc] initWithData:data]; +#elif defined(__CC_PLATFORM_MAC) + NSBitmapImageRep *image = [[NSBitmapImageRep alloc] initWithData:data]; #endif - - free(deflated); deflated = NULL; - self.texture = [[CCTextureCache sharedTextureCache] addCGImage:[image CGImage] forKey:textureName]; - [data release]; - [image release]; + free(deflated); deflated = NULL; + + [self setTexture: [ [CCTextureCache sharedTextureCache] addCGImage:[image CGImage] forKey:textureName]]; + [data release]; + [image release]; + } + + NSAssert( [self texture] != NULL, @"CCParticleSystem: error loading the texture"); } - - NSAssert( [self texture] != NULL, @"CCParticleSystem: error loading the texture"); - } - + return self; } --(id) initWithTotalParticles:(int) numberOfParticles +-(id) initWithTotalParticles:(NSUInteger) numberOfParticles { if( (self=[super init]) ) { totalParticles = numberOfParticles; - + particles = calloc( totalParticles, sizeof(tCCParticle) ); if( ! particles ) { - NSLog(@"Particle system: not enough memory"); + CCLOG(@"Particle system: not enough memory"); [self release]; return nil; } - + allocatedParticles = numberOfParticles; + + if (batchNode_) + { + for (int i = 0; i < totalParticles; i++) + { + particles[i].atlasIndex=i; + } + } + // default, active active = YES; - + // default blend function blendFunc_ = (ccBlendFunc) { CC_BLEND_SRC, CC_BLEND_DST }; - + // default movement type; positionType_ = kCCPositionTypeFree; - + // by default be in mode A: emitterMode_ = kCCParticleModeGravity; - - // default: modulate - // XXX: not used - // colorModulate = YES; - + autoRemoveOnFinish_ = NO; - // profiling -#if CC_ENABLE_PROFILERS - _profilingTimer = [[CCProfiler timerWithName:@"particle system" andInstance:self] retain]; -#endif - // Optimization: compile udpateParticle method updateParticleSel = @selector(updateQuadWithParticle:newPosition:); updateParticleImp = (CC_UPDATE_PARTICLE_IMP) [self methodForSelector:updateParticleSel]; + //for batchNode + transformSystemDirty_ = NO; + // udpate after action in run! [self scheduleUpdateWithPriority:1]; - } - return self; } @@ -306,130 +315,116 @@ -(void) dealloc free( particles ); [texture_ release]; - // profiling -#if CC_ENABLE_PROFILERS - [CCProfiler releaseTimer:_profilingTimer]; -#endif - - [super dealloc]; -} --(BOOL) addParticle -{ - if( [self isFull] ) - return NO; - - tCCParticle * particle = &particles[ particleCount ]; - - [self initParticle: particle]; - particleCount++; - - return YES; + [super dealloc]; } -(void) initParticle: (tCCParticle*) particle { - + //CGPoint currentPosition = position_; // timeToLive // no negative life. prevent division by 0 - particle->timeToLive = MAX(0, life + lifeVar * CCRANDOM_MINUS1_1() ); + particle->timeToLive = life + lifeVar * CCRANDOM_MINUS1_1(); + particle->timeToLive = MAX(0, particle->timeToLive); // position particle->pos.x = sourcePosition.x + posVar.x * CCRANDOM_MINUS1_1(); - particle->pos.x *= CC_CONTENT_SCALE_FACTOR(); particle->pos.y = sourcePosition.y + posVar.y * CCRANDOM_MINUS1_1(); - particle->pos.y *= CC_CONTENT_SCALE_FACTOR(); - + // Color ccColor4F start; - start.r = MIN(1, MAX(0, startColor.r + startColorVar.r * CCRANDOM_MINUS1_1() ) ); - start.g = MIN(1, MAX(0, startColor.g + startColorVar.g * CCRANDOM_MINUS1_1() ) ); - start.b = MIN(1, MAX(0, startColor.b + startColorVar.b * CCRANDOM_MINUS1_1() ) ); - start.a = MIN(1, MAX(0, startColor.a + startColorVar.a * CCRANDOM_MINUS1_1() ) ); - + start.r = clampf( startColor.r + startColorVar.r * CCRANDOM_MINUS1_1(), 0, 1); + start.g = clampf( startColor.g + startColorVar.g * CCRANDOM_MINUS1_1(), 0, 1); + start.b = clampf( startColor.b + startColorVar.b * CCRANDOM_MINUS1_1(), 0, 1); + start.a = clampf( startColor.a + startColorVar.a * CCRANDOM_MINUS1_1(), 0, 1); + ccColor4F end; - end.r = MIN(1, MAX(0, endColor.r + endColorVar.r * CCRANDOM_MINUS1_1() ) ); - end.g = MIN(1, MAX(0, endColor.g + endColorVar.g * CCRANDOM_MINUS1_1() ) ); - end.b = MIN(1, MAX(0, endColor.b + endColorVar.b * CCRANDOM_MINUS1_1() ) ); - end.a = MIN(1, MAX(0, endColor.a + endColorVar.a * CCRANDOM_MINUS1_1() ) ); - + end.r = clampf( endColor.r + endColorVar.r * CCRANDOM_MINUS1_1(), 0, 1); + end.g = clampf( endColor.g + endColorVar.g * CCRANDOM_MINUS1_1(), 0, 1); + end.b = clampf( endColor.b + endColorVar.b * CCRANDOM_MINUS1_1(), 0, 1); + end.a = clampf( endColor.a + endColorVar.a * CCRANDOM_MINUS1_1(), 0, 1); + particle->color = start; particle->deltaColor.r = (end.r - start.r) / particle->timeToLive; particle->deltaColor.g = (end.g - start.g) / particle->timeToLive; particle->deltaColor.b = (end.b - start.b) / particle->timeToLive; particle->deltaColor.a = (end.a - start.a) / particle->timeToLive; - + // size - float startS = MAX(0, startSize + startSizeVar * CCRANDOM_MINUS1_1() ); // no negative size - startS *= CC_CONTENT_SCALE_FACTOR(); - + float startS = startSize + startSizeVar * CCRANDOM_MINUS1_1(); + startS = MAX(0, startS); // No negative value + particle->size = startS; if( endSize == kCCParticleStartSizeEqualToEndSize ) particle->deltaSize = 0; else { float endS = endSize + endSizeVar * CCRANDOM_MINUS1_1(); - endS = MAX(0, endS); - endS *= CC_CONTENT_SCALE_FACTOR(); + endS = MAX(0, endS); // No negative values particle->deltaSize = (endS - startS) / particle->timeToLive; } - + // rotation float startA = startSpin + startSpinVar * CCRANDOM_MINUS1_1(); float endA = endSpin + endSpinVar * CCRANDOM_MINUS1_1(); particle->rotation = startA; particle->deltaRotation = (endA - startA) / particle->timeToLive; - + // position - if( positionType_ == kCCPositionTypeFree ) { - CGPoint p = [self convertToWorldSpace:CGPointZero]; - particle->startPos = ccpMult( p, CC_CONTENT_SCALE_FACTOR() ); - } - else if( positionType_ == kCCPositionTypeRelative ) { - particle->startPos = ccpMult( position_, CC_CONTENT_SCALE_FACTOR() ); - } - + if( positionType_ == kCCPositionTypeFree ) + particle->startPos = [self convertToWorldSpace:CGPointZero]; + + else if( positionType_ == kCCPositionTypeRelative ) + particle->startPos = position_; + + // direction - float a = CC_DEGREES_TO_RADIANS( angle + angleVar * CCRANDOM_MINUS1_1() ); - + float a = CC_DEGREES_TO_RADIANS( angle + angleVar * CCRANDOM_MINUS1_1() ); + // Mode Gravity: A if( emitterMode_ == kCCParticleModeGravity ) { CGPoint v = {cosf( a ), sinf( a )}; float s = mode.A.speed + mode.A.speedVar * CCRANDOM_MINUS1_1(); - s *= CC_CONTENT_SCALE_FACTOR(); - + // direction particle->mode.A.dir = ccpMult( v, s ); - + // radial accel particle->mode.A.radialAccel = mode.A.radialAccel + mode.A.radialAccelVar * CCRANDOM_MINUS1_1(); - particle->mode.A.radialAccel *= CC_CONTENT_SCALE_FACTOR(); - + // tangential accel particle->mode.A.tangentialAccel = mode.A.tangentialAccel + mode.A.tangentialAccelVar * CCRANDOM_MINUS1_1(); - particle->mode.A.tangentialAccel *= CC_CONTENT_SCALE_FACTOR(); - } - + // Mode Radius: B else { // Set the default diameter of the particle from the source position float startRadius = mode.B.startRadius + mode.B.startRadiusVar * CCRANDOM_MINUS1_1(); float endRadius = mode.B.endRadius + mode.B.endRadiusVar * CCRANDOM_MINUS1_1(); - startRadius *= CC_CONTENT_SCALE_FACTOR(); - endRadius *= CC_CONTENT_SCALE_FACTOR(); - particle->mode.B.radius = startRadius; if( mode.B.endRadius == kCCParticleStartRadiusEqualToEndRadius ) particle->mode.B.deltaRadius = 0; else particle->mode.B.deltaRadius = (endRadius - startRadius) / particle->timeToLive; - + particle->mode.B.angle = a; particle->mode.B.degreesPerSecond = CC_DEGREES_TO_RADIANS(mode.B.rotatePerSecond + mode.B.rotatePerSecondVar * CCRANDOM_MINUS1_1()); - } + } +} + +-(BOOL) addParticle +{ + if( [self isFull] ) + return NO; + + tCCParticle * particle = &particles[ particleCount ]; + + [self initParticle: particle]; + particleCount++; + + return YES; } -(void) stopSystem @@ -447,6 +442,7 @@ -(void) resetSystem tCCParticle *p = &particles[particleIdx]; p->timeToLive = 0; } + } -(BOOL) isFull @@ -457,137 +453,158 @@ -(BOOL) isFull #pragma mark ParticleSystem - MainLoop -(void) update: (ccTime) dt { + CC_PROFILER_START_CATEGORY(kCCProfilerCategoryParticles , @"CCParticleSystem - update"); + if( active && emissionRate ) { float rate = 1.0f / emissionRate; - emitCounter += dt; + + //issue #1201, prevent bursts of particles, due to too high emitCounter + if (particleCount < totalParticles) + emitCounter += dt; + while( particleCount < totalParticles && emitCounter > rate ) { [self addParticle]; emitCounter -= rate; } - + elapsed += dt; + if(duration != -1 && duration < elapsed) [self stopSystem]; } - + particleIdx = 0; - - -#if CC_ENABLE_PROFILERS - CCProfilingBeginTimingBlock(_profilingTimer); -#endif - - + CGPoint currentPosition = CGPointZero; - if( positionType_ == kCCPositionTypeFree ) { + if( positionType_ == kCCPositionTypeFree ) currentPosition = [self convertToWorldSpace:CGPointZero]; - currentPosition.x *= CC_CONTENT_SCALE_FACTOR(); - currentPosition.y *= CC_CONTENT_SCALE_FACTOR(); - } - else if( positionType_ == kCCPositionTypeRelative ) { + + else if( positionType_ == kCCPositionTypeRelative ) currentPosition = position_; - currentPosition.x *= CC_CONTENT_SCALE_FACTOR(); - currentPosition.y *= CC_CONTENT_SCALE_FACTOR(); - } - - while( particleIdx < particleCount ) + + if (visible_) { - tCCParticle *p = &particles[particleIdx]; - - // life - p->timeToLive -= dt; - - if( p->timeToLive > 0 ) { - - // Mode A: gravity, direction, tangential accel & radial accel - if( emitterMode_ == kCCParticleModeGravity ) { - CGPoint tmp, radial, tangential; - - radial = CGPointZero; - // radial acceleration - if(p->pos.x || p->pos.y) - radial = ccpNormalize(p->pos); - - tangential = radial; - radial = ccpMult(radial, p->mode.A.radialAccel); - - // tangential acceleration - float newy = tangential.x; - tangential.x = -tangential.y; - tangential.y = newy; - tangential = ccpMult(tangential, p->mode.A.tangentialAccel); - - // (gravity + radial + tangential) * dt - tmp = ccpAdd( ccpAdd( radial, tangential), mode.A.gravity); - tmp = ccpMult( tmp, dt); - p->mode.A.dir = ccpAdd( p->mode.A.dir, tmp); - tmp = ccpMult(p->mode.A.dir, dt); - p->pos = ccpAdd( p->pos, tmp ); - } - - // Mode B: radius movement - else { - // Update the angle and radius of the particle. - p->mode.B.angle += p->mode.B.degreesPerSecond * dt; - p->mode.B.radius += p->mode.B.deltaRadius * dt; - - p->pos.x = - cosf(p->mode.B.angle) * p->mode.B.radius; - p->pos.y = - sinf(p->mode.B.angle) * p->mode.B.radius; + while( particleIdx < particleCount ) + { + tCCParticle *p = &particles[particleIdx]; + + // life + p->timeToLive -= dt; + + if( p->timeToLive > 0 ) { + + // Mode A: gravity, direction, tangential accel & radial accel + if( emitterMode_ == kCCParticleModeGravity ) { + CGPoint tmp, radial, tangential; + + radial = CGPointZero; + // radial acceleration + if(p->pos.x || p->pos.y) + radial = ccpNormalize(p->pos); + + tangential = radial; + radial = ccpMult(radial, p->mode.A.radialAccel); + + // tangential acceleration + float newy = tangential.x; + tangential.x = -tangential.y; + tangential.y = newy; + tangential = ccpMult(tangential, p->mode.A.tangentialAccel); + + // (gravity + radial + tangential) * dt + tmp = ccpAdd( ccpAdd( radial, tangential), mode.A.gravity); + tmp = ccpMult( tmp, dt); + p->mode.A.dir = ccpAdd( p->mode.A.dir, tmp); + tmp = ccpMult(p->mode.A.dir, dt); + p->pos = ccpAdd( p->pos, tmp ); + } + + // Mode B: radius movement + else { + // Update the angle and radius of the particle. + p->mode.B.angle += p->mode.B.degreesPerSecond * dt; + p->mode.B.radius += p->mode.B.deltaRadius * dt; + + p->pos.x = - cosf(p->mode.B.angle) * p->mode.B.radius; + p->pos.y = - sinf(p->mode.B.angle) * p->mode.B.radius; + } + + // color + p->color.r += (p->deltaColor.r * dt); + p->color.g += (p->deltaColor.g * dt); + p->color.b += (p->deltaColor.b * dt); + p->color.a += (p->deltaColor.a * dt); + + // size + p->size += (p->deltaSize * dt); + p->size = MAX( 0, p->size ); + + // angle + p->rotation += (p->deltaRotation * dt); + + // + // update values in quad + // + + CGPoint newPos; + + if( positionType_ == kCCPositionTypeFree || positionType_ == kCCPositionTypeRelative ) + { + CGPoint diff = ccpSub( currentPosition, p->startPos ); + newPos = ccpSub(p->pos, diff); + } else + newPos = p->pos; + + // translate newPos to correct position, since matrix transform isn't performed in batchnode + // don't update the particle with the new position information, it will interfere with the radius and tangential calculations + if (batchNode_) + { + newPos.x+=position_.x; + newPos.y+=position_.y; + } + + updateParticleImp(self, updateParticleSel, p, newPos); + + // update particle counter + particleIdx++; + + } else { + // life < 0 + NSInteger currentIndex = p->atlasIndex; + + if( particleIdx != particleCount-1 ) + particles[particleIdx] = particles[particleCount-1]; + + if (batchNode_) + { + //disable the switched particle + [batchNode_ disableParticle:(atlasIndex_+currentIndex)]; + + //switch indexes + particles[particleCount-1].atlasIndex = currentIndex; + } + + particleCount--; + + if( particleCount == 0 && autoRemoveOnFinish_ ) { + [self unscheduleUpdate]; + [parent_ removeChild:self cleanup:YES]; + return; + } } - - // color - p->color.r += (p->deltaColor.r * dt); - p->color.g += (p->deltaColor.g * dt); - p->color.b += (p->deltaColor.b * dt); - p->color.a += (p->deltaColor.a * dt); - - // size - p->size += (p->deltaSize * dt); - p->size = MAX( 0, p->size ); - - // angle - p->rotation += (p->deltaRotation * dt); - - // - // update values in quad - // - - CGPoint newPos; - - if( positionType_ == kCCPositionTypeFree || positionType_ == kCCPositionTypeRelative ) { - CGPoint diff = ccpSub( currentPosition, p->startPos ); - newPos = ccpSub(p->pos, diff); - - } else - newPos = p->pos; - - - updateParticleImp(self, updateParticleSel, p, newPos); - - // update particle counter - particleIdx++; - - } else { - // life < 0 - if( particleIdx != particleCount-1 ) - particles[particleIdx] = particles[particleCount-1]; - particleCount--; - - if( particleCount == 0 && autoRemoveOnFinish_ ) { - [self unscheduleUpdate]; - [parent_ removeChild:self cleanup:YES]; - return; - } - } + }//while + transformSystemDirty_ = NO; } - -#if CC_ENABLE_PROFILERS - CCProfilingEndTimingBlock(_profilingTimer); -#endif - -#ifdef CC_USES_VBO - [self postStep]; -#endif + + if (!batchNode_) + [self postStep]; + + CC_PROFILER_STOP_CATEGORY(kCCProfilerCategoryParticles , @"CCParticleSystem - update"); +} + +-(void) updateWithNoTime +{ + [self update:0.0f]; } -(void) updateQuadWithParticle:(tCCParticle*)particle newPosition:(CGPoint)pos; @@ -604,13 +621,12 @@ -(void) postStep -(void) setTexture:(CCTexture2D*) texture { - [texture_ release]; texture_ = [texture retain]; // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it - if( texture_ && ! [texture hasPremultipliedAlpha] && + if( texture_ && ! [texture hasPremultipliedAlpha] && ( blendFunc_.src == CC_BLEND_SRC && blendFunc_.dst == CC_BLEND_DST ) ) { - + blendFunc_.src = GL_SRC_ALPHA; blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; } @@ -629,7 +645,7 @@ -(void) setBlendAdditive:(BOOL)additive blendFunc_.dst = GL_ONE; } else { - + if( texture_ && ! [texture_ hasPremultipliedAlpha] ) { blendFunc_.src = GL_SRC_ALPHA; blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; @@ -645,7 +661,20 @@ -(BOOL) blendAdditive return( blendFunc_.src == GL_SRC_ALPHA && blendFunc_.dst == GL_ONE); } -#pragma mark ParticleSystem - Properties of Gravity Mode +#pragma mark ParticleSystem - Total Particles Property + +- (void) setTotalParticles:(NSUInteger)tp +{ + NSAssert( tp <= allocatedParticles, @"Particle: resizing particle array only supported for quads"); + totalParticles = tp; +} + +- (NSUInteger) totalParticles +{ + return totalParticles; +} + +#pragma mark ParticleSystem - Properties of Gravity Mode -(void) setTangentialAccel:(float)t { NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); @@ -790,6 +819,54 @@ -(float) rotatePerSecondVar NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); return mode.B.rotatePerSecondVar; } -@end + +#pragma mark ParticleSystem - methods for batchNode rendering + +-(CCParticleBatchNode*) batchNode +{ + return batchNode_; +} + +-(void) setBatchNode:(CCParticleBatchNode*) batchNode +{ + if( batchNode_ != batchNode ) { + + batchNode_ = batchNode; // weak reference + + if( batchNode ) { + //each particle needs a unique index + for (int i = 0; i < totalParticles; i++) + { + particles[i].atlasIndex=i; + } + } + } +} + +//don't use a transform matrix, this is faster +-(void) setScale:(float) s +{ + transformSystemDirty_ = YES; + [super setScale:s]; +} + +-(void) setRotation: (float)newRotation +{ + transformSystemDirty_ = YES; + [super setRotation:newRotation]; +} + +-(void) setScaleX: (float)newScaleX +{ + transformSystemDirty_ = YES; + [super setScaleX:newScaleX]; +} + +-(void) setScaleY: (float)newScaleY +{ + transformSystemDirty_ = YES; + [super setScaleY:newScaleY]; +} +@end diff --git a/Example/libs/cocos2d/CCParticleSystemPoint.h b/Example/libs/cocos2d/CCParticleSystemPoint.h deleted file mode 100644 index 029ad41..0000000 --- a/Example/libs/cocos2d/CCParticleSystemPoint.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import -#import "CCParticleSystem.h" - -#define CC_MAX_PARTICLE_SIZE 64 - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - -/** CCParticleSystemPoint is a subclass of CCParticleSystem - Attributes of a Particle System: - * All the attributes of Particle System - - Features: - * consumes small memory: uses 1 vertex (x,y) per particle, no need to assign tex coordinates - * size can't be bigger than 64 - * the system can't be scaled since the particles are rendered using GL_POINT_SPRITE - - Limitations: - * On 3rd gen iPhone devices and iPads, this node performs MUCH slower than CCParticleSystemQuad. - */ -@interface CCParticleSystemPoint : CCParticleSystem -{ - // Array of (x,y,size) - ccPointSprite *vertices; - // vertices buffer id -#if CC_USES_VBO - GLuint verticesID; -#endif -} -@end - -#elif __MAC_OS_X_VERSION_MAX_ALLOWED - -#import "CCParticleSystemQuad.h" - -@interface CCParticleSystemPoint : CCParticleSystemQuad -@end - -#endif diff --git a/Example/libs/cocos2d/CCParticleSystemPoint.m b/Example/libs/cocos2d/CCParticleSystemPoint.m deleted file mode 100644 index f789f04..0000000 --- a/Example/libs/cocos2d/CCParticleSystemPoint.m +++ /dev/null @@ -1,207 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import -#import "CCParticleSystemPoint.h" - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - -// opengl -#import "Platforms/CCGL.h" - -// cocos2d -#import "CCTextureCache.h" -#import "ccMacros.h" - -// support -#import "Support/OpenGL_Internal.h" -#import "Support/CGPointExtension.h" - -@implementation CCParticleSystemPoint - --(id) initWithTotalParticles:(int) numberOfParticles -{ - if( (self=[super initWithTotalParticles:numberOfParticles]) ) { - - vertices = malloc( sizeof(ccPointSprite) * totalParticles ); - - if( ! vertices ) { - NSLog(@"cocos2d: Particle system: not enough memory"); - [self release]; - return nil; - } - -#if CC_USES_VBO - glGenBuffers(1, &verticesID); - - // initial binding - glBindBuffer(GL_ARRAY_BUFFER, verticesID); - glBufferData(GL_ARRAY_BUFFER, sizeof(ccPointSprite)*totalParticles, vertices, GL_DYNAMIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); -#endif - } - - return self; -} - --(void) dealloc -{ - free(vertices); -#if CC_USES_VBO - glDeleteBuffers(1, &verticesID); -#endif - - [super dealloc]; -} - --(void) updateQuadWithParticle:(tCCParticle*)p newPosition:(CGPoint)newPos -{ - // place vertices and colos in array - vertices[particleIdx].pos = (ccVertex2F) {newPos.x, newPos.y}; - vertices[particleIdx].size = p->size; - vertices[particleIdx].colors = p->color; -} - --(void) postStep -{ -#if CC_USES_VBO - glBindBuffer(GL_ARRAY_BUFFER, verticesID); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(ccPointSprite)*particleCount, vertices); - glBindBuffer(GL_ARRAY_BUFFER, 0); -#endif -} - --(void) draw -{ - if (particleIdx==0) - return; - - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY - // Unneeded states: GL_TEXTURE_COORD_ARRAY - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - - glBindTexture(GL_TEXTURE_2D, texture_.name); - - glEnable(GL_POINT_SPRITE_OES); - glTexEnvi( GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE ); - -#define kPointSize sizeof(vertices[0]) - -#if CC_USES_VBO - glBindBuffer(GL_ARRAY_BUFFER, verticesID); - - glVertexPointer(2,GL_FLOAT, kPointSize, 0); - - glColorPointer(4, GL_FLOAT, kPointSize, (GLvoid*) offsetof(ccPointSprite, colors) ); - - glEnableClientState(GL_POINT_SIZE_ARRAY_OES); - glPointSizePointerOES(GL_FLOAT, kPointSize, (GLvoid*) offsetof(ccPointSprite, size) ); -#else // Uses Vertex Array List - int offset = (int)vertices; - glVertexPointer(2,GL_FLOAT, kPointSize, (GLvoid*) offset); - - int diff = offsetof(ccPointSprite, colors); - glColorPointer(4, GL_FLOAT, kPointSize, (GLvoid*) (offset+diff)); - - glEnableClientState(GL_POINT_SIZE_ARRAY_OES); - diff = offsetof(ccPointSprite, size); - glPointSizePointerOES(GL_FLOAT, kPointSize, (GLvoid*) (offset+diff)); -#endif - - BOOL newBlend = blendFunc_.src != CC_BLEND_SRC || blendFunc_.dst != CC_BLEND_DST; - if( newBlend ) - glBlendFunc( blendFunc_.src, blendFunc_.dst ); - - - glDrawArrays(GL_POINTS, 0, particleIdx); - - // restore blend state - if( newBlend ) - glBlendFunc( CC_BLEND_SRC, CC_BLEND_DST); - - -#if CC_USES_VBO - // unbind VBO buffer - glBindBuffer(GL_ARRAY_BUFFER, 0); -#endif - - glDisableClientState(GL_POINT_SIZE_ARRAY_OES); - glDisable(GL_POINT_SPRITE_OES); - - // restore GL default state - glEnableClientState(GL_TEXTURE_COORD_ARRAY); -} - -#pragma mark Non supported properties - -// -// SPIN IS NOT SUPPORTED -// --(void) setStartSpin:(float)a -{ - NSAssert(a == 0, @"PointParticleSystem doesn't support spinning"); - [super setStartSpin:a]; -} --(void) setStartSpinVar:(float)a -{ - NSAssert(a == 0, @"PointParticleSystem doesn't support spinning"); - [super setStartSpin:a]; -} --(void) setEndSpin:(float)a -{ - NSAssert(a == 0, @"PointParticleSystem doesn't support spinning"); - [super setStartSpin:a]; -} --(void) setEndSpinVar:(float)a -{ - NSAssert(a == 0, @"PointParticleSystem doesn't support spinning"); - [super setStartSpin:a]; -} - -// -// SIZE > 64 IS NOT SUPPORTED -// --(void) setStartSize:(float)size -{ - NSAssert(size >= 0 && size <= CC_MAX_PARTICLE_SIZE, @"PointParticleSystem only supports 0 <= size <= 64"); - [super setStartSize:size]; -} - --(void) setEndSize:(float)size -{ - NSAssert( (size == kCCParticleStartSizeEqualToEndSize) || - ( size >= 0 && size <= CC_MAX_PARTICLE_SIZE), @"PointParticleSystem only supports 0 <= size <= 64"); - [super setEndSize:size]; -} -@end - -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) -@implementation CCParticleSystemPoint -@end - -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED - - diff --git a/Example/libs/cocos2d/CCParticleSystemQuad.h b/Example/libs/cocos2d/CCParticleSystemQuad.h index eea9edd..c515ca8 100644 --- a/Example/libs/cocos2d/CCParticleSystemQuad.h +++ b/Example/libs/cocos2d/CCParticleSystemQuad.h @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada * Copyright (c) 2009 Leonardo Kasperavičius - * + * + * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,8 +35,8 @@ /** CCParticleSystemQuad is a subclass of CCParticleSystem It includes all the features of ParticleSystem. - - Special features and Limitations: + + Special features and Limitations: - Particle size can be any float number. - The system can be scaled - The particles can be rotated @@ -46,11 +48,10 @@ */ @interface CCParticleSystemQuad : CCParticleSystem { - ccV2F_C4F_T2F_Quad *quads_; // quads to be rendered + ccV3F_C4B_T2F_Quad *quads_; // quads to be rendered GLushort *indices_; // indices -#if CC_USES_VBO - GLuint quadsID_; // VBO id -#endif + GLuint VAOname_; + GLuint buffersVBO_[2]; //0: vertex 1: indices } /** initialices the indices for the vertices */ diff --git a/Example/libs/cocos2d/CCParticleSystemQuad.m b/Example/libs/cocos2d/CCParticleSystemQuad.m index 219f2cc..3a67a7b 100644 --- a/Example/libs/cocos2d/CCParticleSystemQuad.m +++ b/Example/libs/cocos2d/CCParticleSystemQuad.m @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada * Copyright (c) 2009 Leonardo Kasperavičius - * + * + * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,72 +33,188 @@ // cocos2d #import "ccConfig.h" #import "CCParticleSystemQuad.h" +#import "CCParticleBatchNode.h" +#import "CCTextureAtlas.h" #import "CCTextureCache.h" #import "ccMacros.h" #import "CCSpriteFrame.h" +#import "CCDirector.h" +#import "CCShaderCache.h" +#import "ccGLStateCache.h" +#import "CCGLProgram.h" // support #import "Support/OpenGL_Internal.h" #import "Support/CGPointExtension.h" +#import "Support/TransformUtils.h" -@implementation CCParticleSystemQuad +// extern +#import "kazmath/GL/matrix.h" + +@interface CCParticleSystemQuad () +-(void) initVAO; +-(BOOL) allocMemory; +@end +@implementation CCParticleSystemQuad // overriding the init method --(id) initWithTotalParticles:(int) numberOfParticles +-(id) initWithTotalParticles:(NSUInteger) numberOfParticles { // base initialization if( (self=[super initWithTotalParticles:numberOfParticles]) ) { - + // allocating data space - quads_ = calloc( sizeof(quads_[0]) * totalParticles, 1 ); - indices_ = calloc( sizeof(indices_[0]) * totalParticles * 6, 1 ); - - if( !quads_ || !indices_) { - NSLog(@"cocos2d: Particle system: not enough memory"); - if( quads_ ) - free( quads_ ); - if(indices_) - free(indices_); - + if( ! [self allocMemory] ) { [self release]; return nil; } - - // initialize only once the texCoords and the indices - [self initTexCoordsWithRect:CGRectMake(0, 0, [texture_ pixelsWide], [texture_ pixelsHigh])]; + + // Don't initialize the texCoords yet since there are not textures +// [self initTexCoordsWithRect:CGRectMake(0, 0, [texture_ pixelsWide], [texture_ pixelsHigh])]; + [self initIndices]; + [self initVAO]; -#if CC_USES_VBO - // create the VBO buffer - glGenBuffers(1, &quadsID_); - - // initial binding - glBindBuffer(GL_ARRAY_BUFFER, quadsID_); - glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0])*totalParticles, quads_,GL_DYNAMIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); -#endif + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; } - + return self; } +-(BOOL) allocMemory +{ + NSAssert( ( !quads_ && !indices_), @"Memory already alloced"); + NSAssert( !batchNode_, @"Memory should not be alloced when not using batchNode"); + + quads_ = calloc( sizeof(quads_[0]) * totalParticles, 1 ); + indices_ = calloc( sizeof(indices_[0]) * totalParticles * 6, 1 ); + + if( !quads_ || !indices_) { + CCLOG(@"cocos2d: Particle system: not enough memory"); + if( quads_ ) + free( quads_ ); + if(indices_) + free(indices_); + + return NO; + } + + return YES; +} + +- (void) setTotalParticles:(NSUInteger)tp +{ + // If we are setting the total numer of particles to a number higher + // than what is allocated, we need to allocate new arrays + if( tp > allocatedParticles ) + { + // Allocate new memory + size_t particlesSize = tp * sizeof(tCCParticle); + size_t quadsSize = sizeof(quads_[0]) * tp * 1; + size_t indicesSize = sizeof(indices_[0]) * tp * 6 * 1; + + tCCParticle* particlesNew = realloc(particles, particlesSize); + ccV3F_C4B_T2F_Quad *quadsNew = realloc(quads_, quadsSize); + GLushort* indicesNew = realloc(indices_, indicesSize); + + if (particlesNew && quadsNew && indicesNew) + { + // Assign pointers + particles = particlesNew; + quads_ = quadsNew; + indices_ = indicesNew; + + // Clear the memory + memset(particles, 0, particlesSize); + memset(quads_, 0, quadsSize); + memset(indices_, 0, indicesSize); + + allocatedParticles = tp; + } + else + { + // Out of memory, failed to resize some array + if (particlesNew) particles = particlesNew; + if (quadsNew) quads_ = quadsNew; + if (indicesNew) indices_ = indicesNew; + + CCLOG(@"Particle system: out of memory"); + return; + } + + totalParticles = tp; + + // Init particles + if (batchNode_) + { + for (int i = 0; i < totalParticles; i++) + { + particles[i].atlasIndex=i; + } + } + + [self initIndices]; + [self initVAO]; + } + else + { + totalParticles = tp; + } +} + +-(void) initVAO +{ + glGenVertexArrays(1, &VAOname_); + glBindVertexArray(VAOname_); + +#define kQuadSize sizeof(quads_[0].bl) + + glGenBuffers(2, &buffersVBO_[0]); + + glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); + glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * totalParticles, quads_, GL_DYNAMIC_DRAW); + + // vertices + glEnableVertexAttribArray(kCCVertexAttrib_Position); + glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, vertices)); + + // colors + glEnableVertexAttribArray(kCCVertexAttrib_Color); + glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, colors)); + + // tex coords + glEnableVertexAttribArray(kCCVertexAttrib_TexCoords); + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, texCoords)); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffersVBO_[1]); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices_[0]) * totalParticles * 6, indices_, GL_STATIC_DRAW); + + glBindVertexArray(0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + CHECK_GL_ERROR_DEBUG(); +} + -(void) dealloc { - free(quads_); - free(indices_); -#if CC_USES_VBO - glDeleteBuffers(1, &quadsID_); -#endif - + if( ! batchNode_ ) { + free(quads_); + free(indices_); + + glDeleteBuffers(2, &buffersVBO_[0]); + glDeleteVertexArrays(1, &VAOname_); + } + [super dealloc]; } -// rect is in Points coordinates. +// pointRect is in Points coordinates. -(void) initTexCoordsWithRect:(CGRect)pointRect { - // convert to Tex coords - + // convert to Tex coords + CGRect rect = CGRectMake( pointRect.origin.x * CC_CONTENT_SCALE_FACTOR(), pointRect.origin.y * CC_CONTENT_SCALE_FACTOR(), @@ -117,23 +235,82 @@ -(void) initTexCoordsWithRect:(CGRect)pointRect GLfloat right = left + rect.size.width / wide; GLfloat top = bottom + rect.size.height / high; #endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - + // Important. Texture in cocos2d are inverted, so the Y component should be inverted +//<<<<<<< HEAD CC_SWAP( top, bottom); - - for(NSUInteger i=0; i>>>>>> develop } } @@ -142,15 +319,14 @@ -(void) setTexture:(CCTexture2D *)texture withRect:(CGRect)rect // Only update the texture if is different from the current one if( [texture name] != [texture_ name] ) [super setTexture:texture]; - + [self initTexCoordsWithRect:rect]; } -(void) setTexture:(CCTexture2D *)texture { - [self setTexture:texture withRect:CGRectMake(0,0, - [texture pixelsWide] / CC_CONTENT_SCALE_FACTOR(), - [texture pixelsHigh] / CC_CONTENT_SCALE_FACTOR() )]; + CGSize s = [texture contentSize]; + [self setTexture:texture withRect:CGRectMake(0,0, s.width, s.height)]; } -(void) setDisplayFrame:(CCSpriteFrame *)spriteFrame @@ -160,18 +336,18 @@ -(void) setDisplayFrame:(CCSpriteFrame *)spriteFrame // update texture before updating texture rect if ( spriteFrame.texture.name != texture_.name ) - [self setTexture: spriteFrame.texture]; + [self setTexture: spriteFrame.texture]; } -(void) initIndices { - for( NSUInteger i=0;i< totalParticles;i++) { - const int i6 = i*6; - const int i4 = i*4; + for( NSUInteger i = 0; i < totalParticles; i++) { + const NSUInteger i6 = i*6; + const NSUInteger i4 = i*4; indices_[i6+0] = (GLushort) i4+0; indices_[i6+1] = (GLushort) i4+1; indices_[i6+2] = (GLushort) i4+2; - + indices_[i6+5] = (GLushort) i4+1; indices_[i6+4] = (GLushort) i4+2; indices_[i6+3] = (GLushort) i4+3; @@ -180,24 +356,33 @@ -(void) initIndices -(void) updateQuadWithParticle:(tCCParticle*)p newPosition:(CGPoint)newPos { - // colors - ccV2F_C4F_T2F_Quad *quad = &(quads_[particleIdx]); - quad->bl.colors = p->color; - quad->br.colors = p->color; - quad->tl.colors = p->color; - quad->tr.colors = p->color; - + ccV3F_C4B_T2F_Quad *quad; + + if (batchNode_) + { + ccV3F_C4B_T2F_Quad *batchQuads = [[batchNode_ textureAtlas] quads]; + quad = &(batchQuads[atlasIndex_+p->atlasIndex]); + } + else + quad = &(quads_[particleIdx]); + + ccColor4B color = { p->color.r*255, p->color.g*255, p->color.b*255, p->color.a*255}; + quad->bl.colors = color; + quad->br.colors = color; + quad->tl.colors = color; + quad->tr.colors = color; + // vertices GLfloat size_2 = p->size/2; if( p->rotation ) { GLfloat x1 = -size_2; GLfloat y1 = -size_2; - + GLfloat x2 = size_2; GLfloat y2 = size_2; GLfloat x = newPos.x; GLfloat y = newPos.y; - + GLfloat r = (GLfloat)-CC_DEGREES_TO_RADIANS(p->rotation); GLfloat cr = cosf(r); GLfloat sr = sinf(r); @@ -209,19 +394,19 @@ -(void) updateQuadWithParticle:(tCCParticle*)p newPosition:(CGPoint)newPos GLfloat cy = x2 * sr + y2 * cr + y; GLfloat dx = x1 * cr - y2 * sr + x; GLfloat dy = x1 * sr + y2 * cr + y; - + // bottom-left quad->bl.vertices.x = ax; quad->bl.vertices.y = ay; - + // bottom-right vertex: quad->br.vertices.x = bx; quad->br.vertices.y = by; - + // top-left vertex: quad->tl.vertices.x = dx; quad->tl.vertices.y = dy; - + // top-right vertex: quad->tr.vertices.x = cx; quad->tr.vertices.y = cy; @@ -229,86 +414,89 @@ -(void) updateQuadWithParticle:(tCCParticle*)p newPosition:(CGPoint)newPos // bottom-left vertex: quad->bl.vertices.x = newPos.x - size_2; quad->bl.vertices.y = newPos.y - size_2; - + // bottom-right vertex: quad->br.vertices.x = newPos.x + size_2; quad->br.vertices.y = newPos.y - size_2; - + // top-left vertex: quad->tl.vertices.x = newPos.x - size_2; quad->tl.vertices.y = newPos.y + size_2; - + // top-right vertex: quad->tr.vertices.x = newPos.x + size_2; - quad->tr.vertices.y = newPos.y + size_2; + quad->tr.vertices.y = newPos.y + size_2; } } -(void) postStep { -#if CC_USES_VBO - glBindBuffer(GL_ARRAY_BUFFER, quadsID_); + glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0] ); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(quads_[0])*particleCount, quads_); glBindBuffer(GL_ARRAY_BUFFER, 0); -#endif + + CHECK_GL_ERROR_DEBUG(); } // overriding draw method -(void) draw -{ - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: - - - glBindTexture(GL_TEXTURE_2D, [texture_ name]); +{ + NSAssert(!batchNode_,@"draw should not be called when added to a particleBatchNode"); -#define kQuadSize sizeof(quads_[0].bl) + CC_NODE_DRAW_SETUP(); -#if CC_USES_VBO - glBindBuffer(GL_ARRAY_BUFFER, quadsID_); + ccGLBindTexture2D( [texture_ name] ); + ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); - glVertexPointer(2,GL_FLOAT, kQuadSize, 0); + NSAssert( particleIdx == particleCount, @"Abnormal error in particle quad"); - glColorPointer(4, GL_FLOAT, kQuadSize, (GLvoid*) offsetof(ccV2F_C4F_T2F,colors) ); - - glTexCoordPointer(2, GL_FLOAT, kQuadSize, (GLvoid*) offsetof(ccV2F_C4F_T2F,texCoords) ); -#else // vertex array list + glBindVertexArray( VAOname_ ); - NSUInteger offset = (NSUInteger) quads_; + glDrawElements(GL_TRIANGLES, (GLsizei) particleIdx*6, GL_UNSIGNED_SHORT, 0); - // vertex - NSUInteger diff = offsetof( ccV2F_C4F_T2F, vertices); - glVertexPointer(2,GL_FLOAT, kQuadSize, (GLvoid*) (offset+diff) ); - - // color - diff = offsetof( ccV2F_C4F_T2F, colors); - glColorPointer(4, GL_FLOAT, kQuadSize, (GLvoid*)(offset + diff)); - - // tex coords - diff = offsetof( ccV2F_C4F_T2F, texCoords); - glTexCoordPointer(2, GL_FLOAT, kQuadSize, (GLvoid*)(offset + diff)); - -#endif // ! CC_USES_VBO - - BOOL newBlend = blendFunc_.src != CC_BLEND_SRC || blendFunc_.dst != CC_BLEND_DST; - if( newBlend ) - glBlendFunc( blendFunc_.src, blendFunc_.dst ); - - NSAssert( particleIdx == particleCount, @"Abnormal error in particle quad"); - glDrawElements(GL_TRIANGLES, particleIdx*6, GL_UNSIGNED_SHORT, indices_); - - // restore blend state - if( newBlend ) - glBlendFunc( CC_BLEND_SRC, CC_BLEND_DST ); + glBindVertexArray( 0 ); -#if CC_USES_VBO - glBindBuffer(GL_ARRAY_BUFFER, 0); -#endif + CC_INCREMENT_GL_DRAWS(1); - // restore GL default state - // - + CHECK_GL_ERROR_DEBUG(); } -@end +-(void) setBatchNode:(CCParticleBatchNode *)batchNode +{ + if( batchNode_ != batchNode ) { + + CCParticleBatchNode *oldBatch = batchNode_; + [super setBatchNode:batchNode]; + // NEW: is self render ? + if( ! batchNode ) { + [self allocMemory]; + [self initIndices]; + [self setTexture:[oldBatch texture]]; + [self initVAO]; + } + + // OLD: was it self render ? cleanup + else if( ! oldBatch ) + { + // copy current state to batch + ccV3F_C4B_T2F_Quad *batchQuads = [[batchNode_ textureAtlas] quads]; + ccV3F_C4B_T2F_Quad *quad = &(batchQuads[atlasIndex_] ); + memcpy( quad, quads_, totalParticles * sizeof(quads_[0]) ); + + if (quads_) + free(quads_); + quads_ = NULL; + + if (indices_) + free(indices_); + indices_ = NULL; + + glDeleteBuffers(2, &buffersVBO_[0]); + glDeleteVertexArrays(1, &VAOname_); + } + } +} + +@end diff --git a/Example/libs/cocos2d/CCProgressTimer.h b/Example/libs/cocos2d/CCProgressTimer.h index 6661a6f..ce058d9 100644 --- a/Example/libs/cocos2d/CCProgressTimer.h +++ b/Example/libs/cocos2d/CCProgressTimer.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,18 +30,10 @@ @since v0.99.1 */ typedef enum { - /// Radial Counter-Clockwise - kCCProgressTimerTypeRadialCCW, - /// Radial ClockWise - kCCProgressTimerTypeRadialCW, - /// Horizontal Left-Right - kCCProgressTimerTypeHorizontalBarLR, - /// Horizontal Right-Left - kCCProgressTimerTypeHorizontalBarRL, - /// Vertical Bottom-top - kCCProgressTimerTypeVerticalBarBT, - /// Vertical Top-Bottom - kCCProgressTimerTypeVerticalBarTB, + /// Radial Counter-Clockwise + kCCProgressTimerTypeRadial, + /// Bar + kCCProgressTimerTypeBar, } CCProgressTimerType; /** @@ -50,18 +42,44 @@ typedef enum { The progress can be Radial, Horizontal or vertical. @since v0.99.1 */ -@interface CCProgressTimer : CCNode -{ +@interface CCProgressTimer : CCNode { CCProgressTimerType type_; float percentage_; CCSprite *sprite_; - + int vertexDataCount_; - ccV2F_C4F_T2F *vertexData_; + ccV2F_C4B_T2F *vertexData_; + CGPoint midpoint_; + CGPoint barChangeRate_; + BOOL reverseDirection_; } - +@property (nonatomic) ccColor3B color; +@property (nonatomic) GLubyte opacity; /** Change the percentage to change progress. */ @property (nonatomic, readwrite) CCProgressTimerType type; +@property (nonatomic, readwrite) BOOL reverseDirection; +@property (nonatomic, readonly) ccV2F_C4B_T2F *vertexData; +@property (nonatomic, readonly) int vertexDataCount; + +/** + * Midpoint is used to modify the progress start position. + * If you're using radials type then the midpoint changes the center point + * If you're using bar type the the midpoint changes the bar growth + * it expands from the center but clamps to the sprites edge so: + * you want a left to right then set the midpoint all the way to ccp(0,y) + * you want a right to left then set the midpoint all the way to ccp(1,y) + * you want a bottom to top then set the midpoint all the way to ccp(x,0) + * you want a top to bottom then set the midpoint all the way to ccp(x,1) + */ +@property (nonatomic, readwrite) CGPoint midpoint; + +/** + * This allows the bar type to move the component at a specific rate + * Set the component to 0 to make sure it stays at 100%. + * For example you want a left to right bar but not have the height stay 100% + * Set the rate to be ccp(0,1); and set the midpoint to = ccp(0,.5f); + */ +@property (nonatomic, readwrite) CGPoint barChangeRate; /** Percentages are from 0 to 100 */ @property (nonatomic, readwrite) float percentage; @@ -69,15 +87,8 @@ typedef enum { /** The image to show the progress percentage */ @property (nonatomic, readwrite, retain) CCSprite *sprite; - -/** Creates a progress timer with an image filename as the shape the timer goes through */ -+ (id) progressWithFile:(NSString*) filename; -/** Initializes a progress timer with an image filename as the shape the timer goes through */ -- (id) initWithFile:(NSString*) filename; - -/** Creates a progress timer with the texture as the shape the timer goes through */ -+ (id) progressWithTexture:(CCTexture2D*) texture; -/** Creates a progress timer with the texture as the shape the timer goes through */ -- (id) initWithTexture:(CCTexture2D*) texture; - +/** Creates a progress timer with the sprite as the shape the timer goes through */ ++ (id) progressWithSprite:(CCSprite*) sprite; +/** Initializes a progress timer with the sprite as the shape the timer goes through */ +- (id) initWithSprite:(CCSprite*) sprite; @end diff --git a/Example/libs/cocos2d/CCProgressTimer.m b/Example/libs/cocos2d/CCProgressTimer.m index 20c66c6..084b0c6 100644 --- a/Example/libs/cocos2d/CCProgressTimer.m +++ b/Example/libs/cocos2d/CCProgressTimer.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,15 +27,22 @@ #import "ccMacros.h" #import "CCTextureCache.h" +#import "CCGLProgram.h" +#import "CCShaderCache.h" +#import "ccGLStateCache.h" +#import "CCDirector.h" #import "Support/CGPointExtension.h" +#import "Support/TransformUtils.h" +#import "CCDrawingPrimitives.h" - +// extern +#import "kazmath/GL/matrix.h" #define kProgressTextureCoordsCount 4 -// kProgressTextureCoords holds points {0,0} {0,1} {1,1} {1,0} we can represent it as bits -const char kProgressTextureCoords = 0x1e; +// kProgressTextureCoords holds points {0,1} {0,0} {1,0} {1,1} we can represent it as bits +const char kCCProgressTextureCoords = 0x4b; -@interface CCProgressTimer (Internal) +@interface CCProgressTimer () -(void)updateProgress; -(void)updateBar; @@ -49,61 +56,66 @@ @implementation CCProgressTimer @synthesize percentage = percentage_; @synthesize sprite = sprite_; @synthesize type = type_; +@synthesize reverseDirection = reverseDirection_; +@synthesize midpoint = midpoint_; +@synthesize barChangeRate = barChangeRate_; +@synthesize vertexData = vertexData_; +@synthesize vertexDataCount = vertexDataCount_; -+(id)progressWithFile:(NSString*) filename ++(id)progressWithSprite:(CCSprite*) sprite { - return [[[self alloc]initWithFile:filename] autorelease]; -} --(id)initWithFile:(NSString*) filename -{ - return [self initWithTexture:[[CCTextureCache sharedTextureCache] addImage: filename]]; + return [[[self alloc]initWithSprite:sprite] autorelease]; } -+(id)progressWithTexture:(CCTexture2D*) texture +-(id) init { - return [[[self alloc]initWithTexture:texture] autorelease]; + return [self initWithSprite:nil]; } --(id)initWithTexture:(CCTexture2D*) texture + +// designated initializer +-(id)initWithSprite:(CCSprite*) sprite { if(( self = [super init] )){ - self.sprite = [CCSprite spriteWithTexture:texture]; percentage_ = 0.f; vertexData_ = NULL; vertexDataCount_ = 0; - self.anchorPoint = ccp(.5f,.5f); - self.contentSize = sprite_.contentSize; - self.type = kCCProgressTimerTypeRadialCCW; + self.anchorPoint = ccp(0.5f,0.5f); + self.type = kCCProgressTimerTypeRadial; + self.reverseDirection = NO; + self.midpoint = ccp(.5f, .5f); + self.barChangeRate = ccp(1,1); + self.sprite = sprite; + + // shader program + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; } return self; } + -(void)dealloc { - if(vertexData_) + if(vertexData_){ free(vertexData_); - + } [sprite_ release]; [super dealloc]; } -(void)setPercentage:(float) percentage { - if(percentage_ != percentage){ - if(percentage_ < 0.f) - percentage_ = 0.f; - else if(percentage > 100.0f) - percentage_ = 100.f; - else - percentage_ = percentage; - + if(percentage_ != percentage) { + percentage_ = clampf( percentage, 0, 100); [self updateProgress]; } } + -(void)setSprite:(CCSprite *)newSprite { if(sprite_ != newSprite){ - [sprite_ release]; + [sprite_ release]; sprite_ = [newSprite retain]; - + self.contentSize = sprite_.contentSize; + // Everytime we set a new sprite, we free the current vertex data if(vertexData_){ free(vertexData_); @@ -112,10 +124,11 @@ -(void)setSprite:(CCSprite *)newSprite } } } + -(void)setType:(CCProgressTimerType)newType { if (newType != type_) { - + // release all previous information if(vertexData_){ free(vertexData_); @@ -125,43 +138,83 @@ -(void)setType:(CCProgressTimerType)newType type_ = newType; } } -@end -@implementation CCProgressTimer(Internal) +-(void)setReverseProgress:(BOOL)reverse +{ + if( reverseDirection_ != reverse ) { + reverseDirection_ = reverse; + + // release all previous information + if(vertexData_){ + free(vertexData_); + vertexData_ = NULL; + vertexDataCount_ = 0; + } + } +} + +-(void)setColor:(ccColor3B)c +{ + sprite_.color = c; + [self updateColor]; +} + +-(ccColor3B)color +{ + return sprite_.color; +} + +-(void)setOpacity:(GLubyte)o +{ + sprite_.opacity = o; + [self updateColor]; +} + +-(GLubyte)opacity +{ + return sprite_.opacity; +} + +#pragma mark ProgressTimer Internal /// // @returns the vertex position from the texture coordinate /// --(ccVertex2F)vertexFromTexCoord:(CGPoint) texCoord +-(ccTex2F)textureCoordFromAlphaPoint:(CGPoint) alpha { - CGPoint tmp; - ccVertex2F ret; - if (sprite_.texture) { - CCTexture2D *texture = [sprite_ texture]; - CGSize texSize = [texture contentSizeInPixels]; - tmp = ccp(texSize.width * texCoord.x/texture.maxS, - texSize.height * (1 - (texCoord.y/texture.maxT))); - } else - tmp = CGPointZero; - - ret.x = tmp.x; - ret.y = tmp.y; - return ret; + if (!sprite_) { + return (ccTex2F){0,0}; + } + ccV3F_C4B_T2F_Quad quad = sprite_.quad; + CGPoint min = (CGPoint){quad.bl.texCoords.u,quad.bl.texCoords.v}; + CGPoint max = (CGPoint){quad.tr.texCoords.u,quad.tr.texCoords.v}; + // Fix bug #1303 so that progress timer handles sprite frame texture rotation + if (sprite_.textureRectRotated) { + CC_SWAP(alpha.x, alpha.y); + } + return (ccTex2F){min.x * (1.f - alpha.x) + max.x * alpha.x, min.y * (1.f - alpha.y) + max.y * alpha.y}; } --(void)updateColor { - ccColor4F color = ccc4FFromccc3B(sprite_.color); - if([sprite_.texture hasPremultipliedAlpha]){ - float op = sprite_.opacity/255.f; - color.r *= op; - color.g *= op; - color.b *= op; - color.a = op; - } else - color.a = sprite_.opacity/255.f; - + +-(ccVertex2F)vertexFromAlphaPoint:(CGPoint) alpha +{ + if (!sprite_) { + return (ccVertex2F){0.f, 0.f}; + } + ccV3F_C4B_T2F_Quad quad = sprite_.quad; + CGPoint min = (CGPoint){quad.bl.vertices.x,quad.bl.vertices.y}; + CGPoint max = (CGPoint){quad.tr.vertices.x,quad.tr.vertices.y}; + return (ccVertex2F){min.x * (1.f - alpha.x) + max.x * alpha.x, min.y * (1.f - alpha.y) + max.y * alpha.y}; +} + +-(void)updateColor +{ + if (!sprite_) { + return; + } if(vertexData_){ + ccColor4B sc = sprite_.quad.tl.colors; for (int i=0; i < vertexDataCount_; ++i) { - vertexData_[i].colors = color; + vertexData_[i].colors = sc; } } } @@ -169,14 +222,10 @@ -(void)updateColor { -(void)updateProgress { switch (type_) { - case kCCProgressTimerTypeRadialCW: - case kCCProgressTimerTypeRadialCCW: + case kCCProgressTimerTypeRadial: [self updateRadial]; break; - case kCCProgressTimerTypeHorizontalBarLR: - case kCCProgressTimerTypeHorizontalBarRL: - case kCCProgressTimerTypeVerticalBarBT: - case kCCProgressTimerTypeVerticalBarTB: + case kCCProgressTimerTypeBar: [self updateBar]; break; default: @@ -184,38 +233,50 @@ -(void)updateProgress } } +-(void)setAnchorPoint:(CGPoint)anchorPoint +{ + [super setAnchorPoint:anchorPoint]; +} + +-(CGPoint) midpoint +{ + return midpoint_; +} + +-(void)setMidpoint:(CGPoint)midPoint +{ + midpoint_ = ccpClamp(midPoint, CGPointZero, ccp(1,1)); +} + /// // Update does the work of mapping the texture onto the triangles // It now doesn't occur the cost of free/alloc data every update cycle. // It also only changes the percentage point but no other points if they have not // been modified. -// +// // It now deals with flipped texture. If you run into this problem, just use the // sprite property and enable the methods flipX, flipY. /// -(void)updateRadial -{ - // Texture Max is the actual max coordinates to deal with non-power of 2 textures - CGPoint tMax = ccp(sprite_.texture.maxS,sprite_.texture.maxT); - - // Grab the midpoint - CGPoint midpoint = ccpCompMult(self.anchorPoint, tMax); - +{ + if (!sprite_) { + return; + } + float alpha = percentage_ / 100.f; - - // Otherwise we can get the angle from the alpha - float angle = 2.f*((float)M_PI) * ( type_ == kCCProgressTimerTypeRadialCW? alpha : 1.f - alpha); - + + float angle = 2.f*((float)M_PI) * ( reverseDirection_ == YES ? alpha : 1.f - alpha); + // We find the vector to do a hit detection based on the percentage - // We know the first vector is the one @ 12 o'clock (top,mid) so we rotate - // from that by the progress angle around the midpoint pivot - CGPoint topMid = ccp(midpoint.x, 0.f); - CGPoint percentagePt = ccpRotateByAngle(topMid, midpoint, angle); - - + // We know the first vector is the one @ 12 o'clock (top,mid) so we rotate + // from that by the progress angle around the midpoint_ pivot + CGPoint topMid = ccp(midpoint_.x, 1.f); + CGPoint percentagePt = ccpRotateByAngle(topMid, midpoint_, angle); + + int index = 0; CGPoint hit = CGPointZero; - + if (alpha == 0.f) { // More efficient since we don't always need to check intersection // If the alpha is zero then the hit point is top mid and the index is 0. @@ -230,28 +291,28 @@ -(void)updateRadial // We run a for loop checking the edges of the texture to find the // intersection point // We loop through five points since the top is split in half - + float min_t = FLT_MAX; - + for (int i = 0; i <= kProgressTextureCoordsCount; ++i) { int pIndex = (i + (kProgressTextureCoordsCount - 1))%kProgressTextureCoordsCount; - - CGPoint edgePtA = ccpCompMult([self boundaryTexCoord:i % kProgressTextureCoordsCount],tMax); - CGPoint edgePtB = ccpCompMult([self boundaryTexCoord:pIndex],tMax); - + + CGPoint edgePtA = [self boundaryTexCoord:i % kProgressTextureCoordsCount]; + CGPoint edgePtB = [self boundaryTexCoord:pIndex]; + // Remember that the top edge is split in half for the 12 o'clock position // Let's deal with that here by finding the correct endpoints if(i == 0){ - edgePtB = ccpLerp(edgePtA,edgePtB,.5f); + edgePtB = ccpLerp(edgePtA, edgePtB, 1 - midpoint_.x); } else if(i == 4){ - edgePtA = ccpLerp(edgePtA,edgePtB,.5f); + edgePtA = ccpLerp(edgePtA, edgePtB, 1 - midpoint_.x); } - + // s and t are returned by ccpLineIntersect float s = 0, t = 0; - if(ccpLineIntersect(edgePtA, edgePtB, midpoint, percentagePt, &s, &t)) + if(ccpLineIntersect(edgePtA, edgePtB, midpoint_, percentagePt, &s, &t)) { - + // Since our hit test is on rays we have to deal with the top edge // being in split in half so we have to test as a segment if ((i == 0 || i == 4)) { @@ -260,8 +321,8 @@ -(void)updateRadial continue; } } - // As long as our t isn't negative we are at least finding a - // correct hitpoint from midpoint to percentagePt. + // As long as our t isn't negative we are at least finding a + // correct hitpoint from midpoint_ to percentagePt. if (t >= 0.f) { // Because the percentage line and all the texture edges are // rays we should only account for the shortest intersection @@ -272,16 +333,16 @@ -(void)updateRadial } } } - + // Now that we have the minimum magnitude we can use that to find our intersection - hit = ccpAdd(midpoint, ccpMult(ccpSub(percentagePt, midpoint),min_t)); - + hit = ccpAdd(midpoint_, ccpMult(ccpSub(percentagePt, midpoint_),min_t)); + } - - + + // The size of the vertex data is the index from the hitpoint - // the 3 is for the midpoint, 12 o'clock point and hitpoint position. - + // the 3 is for the midpoint_, 12 o'clock point and hitpoint position. + BOOL sameIndexCount = YES; if(vertexDataCount_ != index + 3){ sameIndexCount = NO; @@ -291,58 +352,35 @@ -(void)updateRadial vertexDataCount_ = 0; } } - - + + if(!vertexData_) { vertexDataCount_ = index + 3; - vertexData_ = malloc(vertexDataCount_ * sizeof(ccV2F_C4F_T2F)); + vertexData_ = malloc(vertexDataCount_ * sizeof(ccV2F_C4B_T2F)); NSAssert( vertexData_, @"CCProgressTimer. Not enough memory"); - - [self updateColor]; } - + [self updateColor]; + if (!sameIndexCount) { - - // First we populate the array with the midpoint, then all + + // First we populate the array with the midpoint_, then all // vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint - vertexData_[0].texCoords = (ccTex2F){midpoint.x, midpoint.y}; - vertexData_[0].vertices = [self vertexFromTexCoord:midpoint]; - - vertexData_[1].texCoords = (ccTex2F){midpoint.x, 0.f}; - vertexData_[1].vertices = [self vertexFromTexCoord:ccp(midpoint.x, 0.f)]; - + vertexData_[0].texCoords = [self textureCoordFromAlphaPoint:midpoint_]; + vertexData_[0].vertices = [self vertexFromAlphaPoint:midpoint_]; + + vertexData_[1].texCoords = [self textureCoordFromAlphaPoint:topMid]; + vertexData_[1].vertices = [self vertexFromAlphaPoint:topMid]; + for(int i = 0; i < index; ++i){ - CGPoint texCoords = ccpCompMult([self boundaryTexCoord:i], tMax); - - vertexData_[i+2].texCoords = (ccTex2F){texCoords.x, texCoords.y}; - vertexData_[i+2].vertices = [self vertexFromTexCoord:texCoords]; - } - - // Flip the texture coordinates if set - if (sprite_.flipY || sprite_.flipX) { - for(int i = 0; i < vertexDataCount_ - 1; ++i){ - if (sprite_.flipX) { - vertexData_[i].texCoords.u = tMax.x - vertexData_[i].texCoords.u; - } - if(sprite_.flipY){ - vertexData_[i].texCoords.v = tMax.y - vertexData_[i].texCoords.v; - } - } + CGPoint alphaPoint = [self boundaryTexCoord:i]; + vertexData_[i+2].texCoords = [self textureCoordFromAlphaPoint:alphaPoint]; + vertexData_[i+2].vertices = [self vertexFromAlphaPoint:alphaPoint]; } } - + // hitpoint will go last - vertexData_[vertexDataCount_ - 1].texCoords = (ccTex2F){hit.x, hit.y}; - vertexData_[vertexDataCount_ - 1].vertices = [self vertexFromTexCoord:hit]; - - if (sprite_.flipY || sprite_.flipX) { - if (sprite_.flipX) { - vertexData_[vertexDataCount_ - 1].texCoords.u = tMax.x - vertexData_[vertexDataCount_ - 1].texCoords.u; - } - if(sprite_.flipY){ - vertexData_[vertexDataCount_ - 1].texCoords.v = tMax.y - vertexData_[vertexDataCount_ - 1].texCoords.v; - } - } + vertexData_[vertexDataCount_ - 1].texCoords = [self textureCoordFromAlphaPoint:hit]; + vertexData_[vertexDataCount_ - 1].vertices = [self vertexFromAlphaPoint:hit]; } /// @@ -350,145 +388,153 @@ -(void)updateRadial // It now doesn't occur the cost of free/alloc data every update cycle. // It also only changes the percentage point but no other points if they have not // been modified. -// +// // It now deals with flipped texture. If you run into this problem, just use the // sprite property and enable the methods flipX, flipY. /// -(void)updateBar -{ - +{ + if (!sprite_) { + return; + } float alpha = percentage_ / 100.f; - - CGPoint tMax = ccp(sprite_.texture.maxS,sprite_.texture.maxT); - - unsigned char vIndexes[2] = {0,0}; - - // We know vertex data is always equal to the 4 corners - // If we don't have vertex data then we create it here and populate - // the side of the bar vertices that won't ever change. - if (!vertexData_) { - vertexDataCount_ = kProgressTextureCoordsCount; - vertexData_ = malloc(vertexDataCount_ * sizeof(ccV2F_C4F_T2F)); - NSAssert( vertexData_, @"CCProgressTimer. Not enough memory"); - - if(type_ == kCCProgressTimerTypeHorizontalBarLR){ - vertexData_[vIndexes[0] = 0].texCoords = (ccTex2F){0,0}; - vertexData_[vIndexes[1] = 1].texCoords = (ccTex2F){0, tMax.y}; - }else if (type_ == kCCProgressTimerTypeHorizontalBarRL) { - vertexData_[vIndexes[0] = 2].texCoords = (ccTex2F){tMax.x, tMax.y}; - vertexData_[vIndexes[1] = 3].texCoords = (ccTex2F){tMax.x, 0.f}; - }else if (type_ == kCCProgressTimerTypeVerticalBarBT) { - vertexData_[vIndexes[0] = 1].texCoords = (ccTex2F){0, tMax.y}; - vertexData_[vIndexes[1] = 3].texCoords = (ccTex2F){tMax.x, tMax.y}; - }else if (type_ == kCCProgressTimerTypeVerticalBarTB) { - vertexData_[vIndexes[0] = 0].texCoords = (ccTex2F){0, 0}; - vertexData_[vIndexes[1] = 2].texCoords = (ccTex2F){tMax.x, 0}; - } - - unsigned char index = vIndexes[0]; - vertexData_[index].vertices = [self vertexFromTexCoord:ccp(vertexData_[index].texCoords.u, vertexData_[index].texCoords.v)]; - - index = vIndexes[1]; - vertexData_[index].vertices = [self vertexFromTexCoord:ccp(vertexData_[index].texCoords.u, vertexData_[index].texCoords.v)]; - - if (sprite_.flipY || sprite_.flipX) { - if (sprite_.flipX) { - unsigned char index = vIndexes[0]; - vertexData_[index].texCoords.u = tMax.x - vertexData_[index].texCoords.u; - index = vIndexes[1]; - vertexData_[index].texCoords.u = tMax.x - vertexData_[index].texCoords.u; - } - if(sprite_.flipY){ - unsigned char index = vIndexes[0]; - vertexData_[index].texCoords.v = tMax.y - vertexData_[index].texCoords.v; - index = vIndexes[1]; - vertexData_[index].texCoords.v = tMax.y - vertexData_[index].texCoords.v; - } - } - - [self updateColor]; + CGPoint alphaOffset = ccpMult(ccp(1.f * (1.f - barChangeRate_.x) + alpha * barChangeRate_.x, 1.f * (1.f - barChangeRate_.y) + alpha * barChangeRate_.y), .5f); + CGPoint min = ccpSub(midpoint_, alphaOffset); + CGPoint max = ccpAdd(midpoint_, alphaOffset); + + if (min.x < 0.f) { + max.x += -min.x; + min.x = 0.f; + } + + if (max.x > 1.f) { + min.x -= max.x - 1.f; + max.x = 1.f; + } + + if (min.y < 0.f) { + max.y += -min.y; + min.y = 0.f; } - - if(type_ == kCCProgressTimerTypeHorizontalBarLR){ - vertexData_[vIndexes[0] = 3].texCoords = (ccTex2F){tMax.x*alpha, tMax.y}; - vertexData_[vIndexes[1] = 2].texCoords = (ccTex2F){tMax.x*alpha, 0}; - }else if (type_ == kCCProgressTimerTypeHorizontalBarRL) { - vertexData_[vIndexes[0] = 1].texCoords = (ccTex2F){tMax.x*(1.f - alpha), 0}; - vertexData_[vIndexes[1] = 0].texCoords = (ccTex2F){tMax.x*(1.f - alpha), tMax.y}; - }else if (type_ == kCCProgressTimerTypeVerticalBarBT) { - vertexData_[vIndexes[0] = 0].texCoords = (ccTex2F){0, tMax.y*(1.f - alpha)}; - vertexData_[vIndexes[1] = 2].texCoords = (ccTex2F){tMax.x, tMax.y*(1.f - alpha)}; - }else if (type_ == kCCProgressTimerTypeVerticalBarTB) { - vertexData_[vIndexes[0] = 1].texCoords = (ccTex2F){0, tMax.y*alpha}; - vertexData_[vIndexes[1] = 3].texCoords = (ccTex2F){tMax.x, tMax.y*alpha}; + + if (max.y > 1.f) { + min.y -= max.y - 1.f; + max.y = 1.f; } - - unsigned char index = vIndexes[0]; - vertexData_[index].vertices = [self vertexFromTexCoord:ccp(vertexData_[index].texCoords.u, vertexData_[index].texCoords.v)]; - index = vIndexes[1]; - vertexData_[index].vertices = [self vertexFromTexCoord:ccp(vertexData_[index].texCoords.u, vertexData_[index].texCoords.v)]; - - if (sprite_.flipY || sprite_.flipX) { - if (sprite_.flipX) { - unsigned char index = vIndexes[0]; - vertexData_[index].texCoords.u = tMax.x - vertexData_[index].texCoords.u; - index = vIndexes[1]; - vertexData_[index].texCoords.u = tMax.x - vertexData_[index].texCoords.u; + + + if (!reverseDirection_) { + if(!vertexData_) { + vertexDataCount_ = 4; + vertexData_ = malloc(vertexDataCount_ * sizeof(ccV2F_C4B_T2F)); + NSAssert( vertexData_, @"CCProgressTimer. Not enough memory"); } - if(sprite_.flipY){ - unsigned char index = vIndexes[0]; - vertexData_[index].texCoords.v = tMax.y - vertexData_[index].texCoords.v; - index = vIndexes[1]; - vertexData_[index].texCoords.v = tMax.y - vertexData_[index].texCoords.v; + // TOPLEFT + vertexData_[0].texCoords = [self textureCoordFromAlphaPoint:ccp(min.x,max.y)]; + vertexData_[0].vertices = [self vertexFromAlphaPoint:ccp(min.x,max.y)]; + + // BOTLEFT + vertexData_[1].texCoords = [self textureCoordFromAlphaPoint:ccp(min.x,min.y)]; + vertexData_[1].vertices = [self vertexFromAlphaPoint:ccp(min.x,min.y)]; + + // TOPRIGHT + vertexData_[2].texCoords = [self textureCoordFromAlphaPoint:ccp(max.x,max.y)]; + vertexData_[2].vertices = [self vertexFromAlphaPoint:ccp(max.x,max.y)]; + + // BOTRIGHT + vertexData_[3].texCoords = [self textureCoordFromAlphaPoint:ccp(max.x,min.y)]; + vertexData_[3].vertices = [self vertexFromAlphaPoint:ccp(max.x,min.y)]; + } else { + if(!vertexData_) { + vertexDataCount_ = 8; + vertexData_ = malloc(vertexDataCount_ * sizeof(ccV2F_C4B_T2F)); + NSAssert( vertexData_, @"CCProgressTimer. Not enough memory"); + // TOPLEFT 1 + vertexData_[0].texCoords = [self textureCoordFromAlphaPoint:ccp(0,1)]; + vertexData_[0].vertices = [self vertexFromAlphaPoint:ccp(0,1)]; + + // BOTLEFT 1 + vertexData_[1].texCoords = [self textureCoordFromAlphaPoint:ccp(0,0)]; + vertexData_[1].vertices = [self vertexFromAlphaPoint:ccp(0,0)]; + + // TOPRIGHT 2 + vertexData_[6].texCoords = [self textureCoordFromAlphaPoint:ccp(1,1)]; + vertexData_[6].vertices = [self vertexFromAlphaPoint:ccp(1,1)]; + + // BOTRIGHT 2 + vertexData_[7].texCoords = [self textureCoordFromAlphaPoint:ccp(1,0)]; + vertexData_[7].vertices = [self vertexFromAlphaPoint:ccp(1,0)]; } + + // TOPRIGHT 1 + vertexData_[2].texCoords = [self textureCoordFromAlphaPoint:ccp(min.x,max.y)]; + vertexData_[2].vertices = [self vertexFromAlphaPoint:ccp(min.x,max.y)]; + + // BOTRIGHT 1 + vertexData_[3].texCoords = [self textureCoordFromAlphaPoint:ccp(min.x,min.y)]; + vertexData_[3].vertices = [self vertexFromAlphaPoint:ccp(min.x,min.y)]; + + // TOPLEFT 2 + vertexData_[4].texCoords = [self textureCoordFromAlphaPoint:ccp(max.x,max.y)]; + vertexData_[4].vertices = [self vertexFromAlphaPoint:ccp(max.x,max.y)]; + + // BOTLEFT 2 + vertexData_[5].texCoords = [self textureCoordFromAlphaPoint:ccp(max.x,min.y)]; + vertexData_[5].vertices = [self vertexFromAlphaPoint:ccp(max.x,min.y)]; } - + [self updateColor]; } -(CGPoint)boundaryTexCoord:(char)index { if (index < kProgressTextureCoordsCount) { - switch (type_) { - case kCCProgressTimerTypeRadialCW: - return ccp((kProgressTextureCoords>>((index<<1)+1))&1,(kProgressTextureCoords>>(index<<1))&1); - case kCCProgressTimerTypeRadialCCW: - return ccp((kProgressTextureCoords>>(7-(index<<1)))&1,(kProgressTextureCoords>>(7-((index<<1)+1)))&1); - default: - break; + if (reverseDirection_) { + return ccp((kCCProgressTextureCoords>>(7-(index<<1)))&1,(kCCProgressTextureCoords>>(7-((index<<1)+1)))&1); + } else { + return ccp((kCCProgressTextureCoords>>((index<<1)+1))&1,(kCCProgressTextureCoords>>(index<<1))&1); } } return CGPointZero; } --(void)draw +-(void) draw { - if(!vertexData_)return; - if(!sprite_)return; - ccBlendFunc blendFunc = sprite_.blendFunc; - BOOL newBlend = blendFunc.src != CC_BLEND_SRC || blendFunc.dst != CC_BLEND_DST; - if( newBlend ) - glBlendFunc( blendFunc.src, blendFunc.dst ); - - /// ======================================================================== - // Replaced [texture_ drawAtPoint:CGPointZero] with my own vertexData - // Everything above me and below me is copied from CCTextureNode's draw - glBindTexture(GL_TEXTURE_2D, sprite_.texture.name); - glVertexPointer(2, GL_FLOAT, sizeof(ccV2F_C4F_T2F), &vertexData_[0].vertices); - glTexCoordPointer(2, GL_FLOAT, sizeof(ccV2F_C4F_T2F), &vertexData_[0].texCoords); - glColorPointer(4, GL_FLOAT, sizeof(ccV2F_C4F_T2F), &vertexData_[0].colors); - if(type_ == kCCProgressTimerTypeRadialCCW || type_ == kCCProgressTimerTypeRadialCW){ + if( ! vertexData_ || ! sprite_) + return; + + CC_NODE_DRAW_SETUP(); + + ccGLBlendFunc( sprite_.blendFunc.src, sprite_.blendFunc.dst ); + + ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex ); + + ccGLBindTexture2D( sprite_.texture.name ); + + glVertexAttribPointer( kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(vertexData_[0]) , &vertexData_[0].vertices); + glVertexAttribPointer( kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(vertexData_[0]), &vertexData_[0].texCoords); + glVertexAttribPointer( kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(vertexData_[0]), &vertexData_[0].colors); + + if(type_ == kCCProgressTimerTypeRadial) + { glDrawArrays(GL_TRIANGLE_FAN, 0, vertexDataCount_); - } else if (type_ == kCCProgressTimerTypeHorizontalBarLR || - type_ == kCCProgressTimerTypeHorizontalBarRL || - type_ == kCCProgressTimerTypeVerticalBarBT || - type_ == kCCProgressTimerTypeVerticalBarTB) { - glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexDataCount_); + } + else if (type_ == kCCProgressTimerTypeBar) + { + if (!reverseDirection_) + { + glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexDataCount_); + } + else + { + glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexDataCount_/2); + glDrawArrays(GL_TRIANGLE_STRIP, 4, vertexDataCount_/2); + + // 2 draw calls + CC_INCREMENT_GL_DRAWS(1); + } } - //glDrawElements(GL_TRIANGLES, indicesCount_, GL_UNSIGNED_BYTE, indices_); - /// ======================================================================== - - if( newBlend ) - glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); + CC_INCREMENT_GL_DRAWS(1); + } @end diff --git a/Example/libs/cocos2d/CCProtocols.h b/Example/libs/cocos2d/CCProtocols.h index f40c1ab..e55ec92 100644 --- a/Example/libs/cocos2d/CCProtocols.h +++ b/Example/libs/cocos2d/CCProtocols.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,7 +23,7 @@ * THE SOFTWARE. */ - +#import "ccMacros.h" #import "ccTypes.h" #import "CCTexture2D.h" @@ -114,11 +115,18 @@ #pragma mark - -#pragma mark CCProjectionProtocol -/** OpenGL projection protocol */ -@protocol CCProjectionProtocol -/** Called by CCDirector when the porjection is updated, and "custom" projection is used - @since v0.99.5 - */ +#pragma mark CCDirectorDelegate +/** CCDirector delegate */ +@protocol CCDirectorDelegate + +@optional +/** Called by CCDirector when the porjection is updated, and "custom" projection is used */ -(void) updateProjection; -@end \ No newline at end of file + +#ifdef __CC_PLATFORM_IOS +/** Returns a Boolean value indicating whether the CCDirector supports the specified orientation. Default value is YES (supports all possible orientations) */ +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; + +#endif // __CC_PLATFORM_IOS + +@end diff --git a/Example/libs/cocos2d/CCRenderTexture.h b/Example/libs/cocos2d/CCRenderTexture.h index 10500f4..d71d19c 100644 --- a/Example/libs/cocos2d/CCRenderTexture.h +++ b/Example/libs/cocos2d/CCRenderTexture.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,43 +24,42 @@ */ #import + +#import "ccMacros.h" #import "CCNode.h" #import "CCSprite.h" #import "Support/OpenGL_Internal.h" +#import "kazmath/mat4.h" -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import #endif // iPHone -enum +typedef enum { - kCCImageFormatJPG = 0, + kCCImageFormatJPEG = 0, kCCImageFormatPNG = 1, - kCCImageFormatRawData =2 -}; +} tCCImageFormat; /** CCRenderTexture is a generic rendering target. To render things into it, - simply construct a render target, call begin on it, call visit on any cocos + simply construct a render target, call begin on it, call visit on any cocos2d scenes or objects to render them, and call end. For convienience, render texture - adds a sprite as it's display child with the results, so you can simply add - the render texture to your scene and treat it like any other CocosNode. + adds a sprite as its display child with the results, so you can simply add + the render texture to your scene and treat it like any other CCNode. There are also functions for saving the render texture to disk in PNG or JPG format. - + @since v0.8.1 */ -@interface CCRenderTexture : CCNode +@interface CCRenderTexture : CCNode { GLuint fbo_; GLint oldFBO_; CCTexture2D* texture_; CCSprite* sprite_; - - GLenum pixelFormat_; - GLfloat clearColor_[4]; + GLenum pixelFormat_; } /** The CCSprite being used. @@ -92,17 +91,27 @@ enum /** clears the texture with a color */ -(void)clear:(float)r g:(float)g b:(float)b a:(float)a; -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +/* creates a new CGImage from with the texture's data. + Caller is responsible for releasing it by calling CGImageRelease(). + */ +-(CGImageRef) newCGImage; -/** saves the texture into a file */ --(BOOL)saveBuffer:(NSString*)name; -/** saves the texture into a file. The format can be JPG or PNG */ --(BOOL)saveBuffer:(NSString*)name format:(int)format; -/* get buffer as UIImage, can only save a render buffer which has a RGBA8888 pixel format */ --(NSData*)getUIImageAsDataFromBuffer:(int) format; +/** saves the texture into a file using JPEG format. The file will be saved in the Documents folder. + Returns YES if the operation is successful. + */ +-(BOOL)saveToFile:(NSString*)name; -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +/** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder. + Returns YES if the operation is successful. + */ +-(BOOL)saveToFile:(NSString*)name format:(tCCImageFormat)format; -@end +#ifdef __CC_PLATFORM_IOS +/* returns an autoreleased UIImage from the texture */ +-(UIImage *) getUIImage; + +#endif // __CC_PLATFORM_IOS + +@end diff --git a/Example/libs/cocos2d/CCRenderTexture.m b/Example/libs/cocos2d/CCRenderTexture.m index 42e5f7b..9af0374 100644 --- a/Example/libs/cocos2d/CCRenderTexture.m +++ b/Example/libs/cocos2d/CCRenderTexture.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,23 +23,27 @@ * */ -#import #import "CCRenderTexture.h" #import "CCDirector.h" #import "ccMacros.h" +#import "CCGLProgram.h" +#import "ccGLStateCache.h" +#import "CCConfiguration.h" #import "Support/ccUtils.h" +#import "Support/CCFileUtils.h" -@interface CCRenderTexture (private) +#if __CC_PLATFORM_MAC +#import +#endif -- (void) saveGLstate; -- (void) restoreGLstate; -@end +// extern +#import "kazmath/GL/matrix.h" @implementation CCRenderTexture @synthesize sprite=sprite_; -// issue #994 +// issue #994 +(id)renderTextureWithWidth:(int)w height:(int)h pixelFormat:(CCTexture2DPixelFormat) format { return [[[self alloc] initWithWidth:w height:h pixelFormat:format] autorelease]; @@ -47,10 +51,10 @@ +(id)renderTextureWithWidth:(int)w height:(int)h pixelFormat:(CCTexture2DPixelFo +(id)renderTextureWithWidth:(int)w height:(int)h { - return [[[self alloc] initWithWidth:w height:h pixelFormat:kCCTexture2DPixelFormat_RGBA8888] autorelease]; + return [[[self alloc] initWithWidth:w height:h pixelFormat:kCCTexture2DPixelFormat_RGBA8888] autorelease]; } --(id)initWithWidth:(int)w height:(int)h +-(id)initWithWidth:(int)w height:(int)h { return [self initWithWidth:w height:h pixelFormat:kCCTexture2DPixelFormat_RGBA8888]; } @@ -60,40 +64,52 @@ -(id)initWithWidth:(int)w height:(int)h pixelFormat:(CCTexture2DPixelFormat) for if ((self = [super init])) { NSAssert(format != kCCTexture2DPixelFormat_A8,@"only RGB and RGBA formats are valid for a render texture"); + + CCDirector *director = [CCDirector sharedDirector]; + + // XXX multithread + if( [director runningThread] != [NSThread currentThread] ) + CCLOG(@"cocos2d: WARNING. CCRenderTexture is running on its own thread. Make sure that an OpenGL context is being used on this thread!"); + w *= CC_CONTENT_SCALE_FACTOR(); h *= CC_CONTENT_SCALE_FACTOR(); - glGetIntegerv(CC_GL_FRAMEBUFFER_BINDING, &oldFBO_); - + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFBO_); + // textures must be power of two - NSUInteger powW = ccNextPOT(w); - NSUInteger powH = ccNextPOT(h); - + NSUInteger powW; + NSUInteger powH; + + if( [[CCConfiguration sharedConfiguration] supportsNPOT] ) { + powW = w; + powH = h; + } else { + powW = ccNextPOT(w); + powH = ccNextPOT(h); + } + void *data = malloc((int)(powW * powH * 4)); memset(data, 0, (int)(powW * powH * 4)); - pixelFormat_=format; - + pixelFormat_=format; + texture_ = [[CCTexture2D alloc] initWithData:data pixelFormat:pixelFormat_ pixelsWide:powW pixelsHigh:powH contentSize:CGSizeMake(w, h)]; free( data ); - + // generate FBO - ccglGenFramebuffers(1, &fbo_); - ccglBindFramebuffer(CC_GL_FRAMEBUFFER, fbo_); - + glGenFramebuffers(1, &fbo_); + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); + // associate texture with FBO - ccglFramebufferTexture2D(CC_GL_FRAMEBUFFER, CC_GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_.name, 0); - + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_.name, 0); + // check if it worked (probably worth doing :) ) - GLuint status = ccglCheckFramebufferStatus(CC_GL_FRAMEBUFFER); - if (status != CC_GL_FRAMEBUFFER_COMPLETE) - { - [NSException raise:@"Render Texture" format:@"Could not attach texture to framebuffer"]; - } + NSAssert( glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, @"Could not attach texture to framebuffer"); + [texture_ setAliasTexParameters]; - + sprite_ = [CCSprite spriteWithTexture:texture_]; - + [texture_ release]; [sprite_ setScaleY:-1]; [self addChild:sprite_]; @@ -101,208 +117,240 @@ -(id)initWithWidth:(int)w height:(int)h pixelFormat:(CCTexture2DPixelFormat) for // issue #937 [sprite_ setBlendFunc:(ccBlendFunc){GL_ONE, GL_ONE_MINUS_SRC_ALPHA}]; - ccglBindFramebuffer(CC_GL_FRAMEBUFFER, oldFBO_); + glBindFramebuffer(GL_FRAMEBUFFER, oldFBO_); } return self; } -(void)dealloc { -// [self removeAllChildrenWithCleanup:YES]; - ccglDeleteFramebuffers(1, &fbo_); + glDeleteFramebuffers(1, &fbo_); + [super dealloc]; } - -(void)begin { - // issue #878 save opengl state - [self saveGLstate]; - - CC_DISABLE_DEFAULT_GL_STATES(); - // Save the current matrix - glPushMatrix(); + CCDirector *director = [CCDirector sharedDirector]; + // Save the current matrix + kmGLPushMatrix(); + CGSize texSize = [texture_ contentSizeInPixels]; + // Calculate the adjustment ratios based on the old and new projections - CGSize size = [[CCDirector sharedDirector] displaySizeInPixels]; + CGSize size = [director winSizeInPixels]; float widthRatio = size.width / texSize.width; float heightRatio = size.height / texSize.height; - // Adjust the orthographic propjection and viewport - ccglOrtho((float)-1.0 / widthRatio, (float)1.0 / widthRatio, (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1); - glViewport(0, 0, texSize.width, texSize.height); - glGetIntegerv(CC_GL_FRAMEBUFFER_BINDING, &oldFBO_); - ccglBindFramebuffer(CC_GL_FRAMEBUFFER, fbo_);//Will direct drawing to the frame buffer created above - - CC_ENABLE_DEFAULT_GL_STATES(); -} + // Adjust the orthographic projection and viewport + glViewport(0, 0, texSize.width * CC_CONTENT_SCALE_FACTOR(), texSize.height * CC_CONTENT_SCALE_FACTOR() ); --(void)beginWithClear:(float)r g:(float)g b:(float)b a:(float)a -{ - // issue #878 save opengl state - [self saveGLstate]; - - CC_DISABLE_DEFAULT_GL_STATES(); - // Save the current matrix - glPushMatrix(); - - CGSize texSize = [texture_ contentSizeInPixels]; - - // Calculate the adjustment ratios based on the old and new projections - CGSize size = [[CCDirector sharedDirector] displaySizeInPixels]; - float widthRatio = size.width / texSize.width; - float heightRatio = size.height / texSize.height; - - // Adjust the orthographic propjection and viewport - ccglOrtho((float)-1.0 / widthRatio, (float)1.0 / widthRatio, (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1); - glViewport(0, 0, texSize.width, texSize.height); - - glGetIntegerv(CC_GL_FRAMEBUFFER_BINDING, &oldFBO_); - ccglBindFramebuffer(CC_GL_FRAMEBUFFER, fbo_);//Will direct drawing to the frame buffer created above - - glClearColor(r, g, b, a); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - CC_ENABLE_DEFAULT_GL_STATES(); -} + // special viewport for 3d projection + retina display + if ( director.projection == kCCDirectorProjection3D && CC_CONTENT_SCALE_FACTOR() != 1 ) + glViewport(-texSize.width/2, -texSize.height/2, texSize.width * CC_CONTENT_SCALE_FACTOR(), texSize.height * CC_CONTENT_SCALE_FACTOR() ); --(void)end -{ - ccglBindFramebuffer(CC_GL_FRAMEBUFFER, oldFBO_); - // Restore the original matrix and viewport - glPopMatrix(); - CGSize size = [[CCDirector sharedDirector] displaySizeInPixels]; - glViewport(0, 0, size.width, size.height); - [self restoreGLstate]; + kmMat4 orthoMatrix; + kmMat4OrthographicProjection(&orthoMatrix, (float)-1.0 / widthRatio, (float)1.0 / widthRatio, + (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 ); + kmGLMultMatrix(&orthoMatrix); + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFBO_); + glBindFramebuffer(GL_FRAMEBUFFER, fbo_); } --(void)clear:(float)r g:(float)g b:(float)b a:(float)a +-(void)beginWithClear:(float)r g:(float)g b:(float)b a:(float)a { [self begin]; + + // save clear color + GLfloat clearColor[4]; + glGetFloatv(GL_COLOR_CLEAR_VALUE,clearColor); + glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - [self end]; + // restore clear color + glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } --(void) saveGLstate +-(void)end { - glGetFloatv(GL_COLOR_CLEAR_VALUE,clearColor_); -} + CCDirector *director = [CCDirector sharedDirector]; + + glBindFramebuffer(GL_FRAMEBUFFER, oldFBO_); -- (void) restoreGLstate -{ - glClearColor(clearColor_[0], clearColor_[1], clearColor_[2], clearColor_[3]); -} + kmGLPopMatrix(); -#pragma mark RenderTexture - Save Image + CGSize size = [director winSizeInPixels]; -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED --(BOOL)saveBuffer:(NSString*)name -{ - return [self saveBuffer:name format:kCCImageFormatJPG]; + // restore viewport + glViewport(0, 0, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); + + // special viewport for 3d projection + retina display + if ( director.projection == kCCDirectorProjection3D && CC_CONTENT_SCALE_FACTOR() != 1 ) + glViewport(-size.width/2, -size.height/2, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); + + [director setProjection:director.projection]; } --(BOOL)saveBuffer:(NSString*)fileName format:(int)format +-(void)clear:(float)r g:(float)g b:(float)b a:(float)a { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *documentsDirectory = [paths objectAtIndex:0]; - NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName]; - - NSData *data = [self getUIImageAsDataFromBuffer:format]; - - return [data writeToFile:fullPath atomically:YES]; + [self beginWithClear:r g:g b:b a:a]; + [self end]; } +#pragma mark RenderTexture - Save Image --(NSData*)getUIImageAsDataFromBuffer:(int) format +-(CGImageRef) newCGImage { - NSAssert(pixelFormat_ == kCCTexture2DPixelFormat_RGBA8888,@"only RGBA8888 can be saved as image"); + NSAssert(pixelFormat_ == kCCTexture2DPixelFormat_RGBA8888,@"only RGBA8888 can be saved as image"); + CGSize s = [texture_ contentSizeInPixels]; int tx = s.width; int ty = s.height; - int bitsPerComponent=8; - int bitsPerPixel=32; - - int bytesPerRow = (bitsPerPixel/8) * tx; + int bitsPerComponent = 8; + int bitsPerPixel = 32; + int bytesPerPixel = (bitsPerComponent * 4)/8; + int bytesPerRow = bytesPerPixel * tx; NSInteger myDataLength = bytesPerRow * ty; - GLubyte *buffer = malloc(sizeof(GLubyte)*myDataLength); - GLubyte *pixels = malloc(sizeof(GLubyte)*myDataLength); + GLubyte *buffer = calloc(myDataLength,1); + GLubyte *pixels = calloc(myDataLength,1); + if( ! (buffer && pixels) ) { - CCLOG(@"cocos2d: CCRenderTexture#getUIImageFromBuffer: not enough memory"); + CCLOG(@"cocos2d: CCRenderTexture#getCGImageFromBuffer: not enough memory"); free(buffer); free(pixels); return nil; } [self begin]; + + glReadPixels(0,0,tx,ty,GL_RGBA,GL_UNSIGNED_BYTE, buffer); + [self end]; - int x,y; + // make data provider with data. - for(y = 0; y -{ - NSMutableArray* segments_; - NSMutableArray* deletedSegments_; - - CGPoint lastPoint1_; - CGPoint lastPoint2_; - CGPoint lastLocation_; - int vertCount_; - float texVPos_; - float curTime_; - float fadeTime_; - float delta_; - float lastWidth_; - float lastSign_; - BOOL pastFirstPoint_; - - // Texture used - CCTexture2D* texture_; - - // texture length - float textureLength_; - - // RGBA protocol - ccColor4B color_; - - // blend func - ccBlendFunc blendFunc_; -} - -/** Texture used by the ribbon. Conforms to CCTextureProtocol protocol */ -@property (nonatomic,readwrite,retain) CCTexture2D* texture; - -/** Texture lengths in pixels */ -@property (nonatomic,readwrite) float textureLength; - -/** GL blendind function */ -@property (nonatomic,readwrite,assign) ccBlendFunc blendFunc; - -/** color used by the Ribbon (RGBA) */ -@property (nonatomic,readwrite) ccColor4B color; - -/** creates the ribbon */ -+(id)ribbonWithWidth:(float)w image:(NSString*)path length:(float)l color:(ccColor4B)color fade:(float)fade; -/** init the ribbon */ --(id)initWithWidth:(float)w image:(NSString*)path length:(float)l color:(ccColor4B)color fade:(float)fade; -/** add a point to the ribbon */ --(void)addPointAt:(CGPoint)location width:(float)w; -/** polling function */ --(void)update:(ccTime)delta; -/** determine side of line */ --(float)sideOfLine:(CGPoint)p l1:(CGPoint)l1 l2:(CGPoint)l2; - -@end - -/** object to hold ribbon segment data */ -@interface CCRibbonSegment : NSObject -{ -@public - GLfloat verts[50*6]; - GLfloat coords[50*4]; - GLubyte colors[50*8]; - float creationTime[50]; - BOOL finished; - uint end; - uint begin; -} --(id)init; --(void)reset; --(void)draw:(float)curTime fadeTime:(float)fadeTime color:(ccColor4B)color; -@end diff --git a/Example/libs/cocos2d/CCRibbon.m b/Example/libs/cocos2d/CCRibbon.m deleted file mode 100644 index 9555455..0000000 --- a/Example/libs/cocos2d/CCRibbon.m +++ /dev/null @@ -1,381 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008, 2009 Jason Booth - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* - * A ribbon is a dynamically generated list of polygons drawn as a single or series - * of triangle strips. The primary use of Ribbon is as the drawing class of Motion Streak, - * but it is quite useful on it's own. When manually drawing a ribbon, you can call addPointAt - * and pass in the parameters for the next location in the ribbon. The system will automatically - * generate new polygons, texture them accourding to your texture width, etc, etc. - * - * Ribbon data is stored in a RibbonSegment class. This class statically allocates enough verticies and - * texture coordinates for 50 locations (100 verts or 48 triangles). The ribbon class will allocate - * new segments when they are needed, and reuse old ones if available. The idea is to avoid constantly - * allocating new memory and prefer a more static method. However, since there is no way to determine - * the maximum size of some ribbons (motion streaks), a truely static allocation is not possible. - * - */ - - -#import "CCRibbon.h" -#import "CCTextureCache.h" -#import "Support/CGPointExtension.h" -#import "ccMacros.h" - -// -// Ribbon -// -@implementation CCRibbon -@synthesize blendFunc=blendFunc_; -@synthesize color=color_; -@synthesize textureLength = textureLength_; - -+(id)ribbonWithWidth:(float)w image:(NSString*)path length:(float)l color:(ccColor4B)color fade:(float)fade -{ - self = [[[self alloc] initWithWidth:w image:path length:l color:color fade:fade] autorelease]; - return self; -} - --(id)initWithWidth:(float)w image:(NSString*)path length:(float)l color:(ccColor4B)color fade:(float)fade -{ - self = [super init]; - if (self) - { - - segments_ = [[NSMutableArray alloc] init]; - deletedSegments_ = [[NSMutableArray alloc] init]; - - /* 1 initial segment */ - CCRibbonSegment* seg = [[CCRibbonSegment alloc] init]; - [segments_ addObject:seg]; - [seg release]; - - textureLength_ = l; - - color_ = color; - fadeTime_ = fade; - lastLocation_ = CGPointZero; - lastWidth_ = w/2; - texVPos_ = 0.0f; - - curTime_ = 0; - pastFirstPoint_ = NO; - - /* XXX: - Ribbon, by default uses this blend function, which might not be correct - if you are using premultiplied alpha images, - but 99% you might want to use this blending function regarding of the texture - */ - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; - - self.texture = [[CCTextureCache sharedTextureCache] addImage:path]; - - /* default texture parameter */ - ccTexParams params = { GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT }; - [texture_ setTexParameters:¶ms]; - } - return self; -} - --(void)dealloc -{ - [segments_ release]; - [deletedSegments_ release]; - [texture_ release]; - [super dealloc]; -} - -// rotates a point around 0, 0 --(CGPoint)rotatePoint:(CGPoint)vec rotation:(float)a -{ - float xtemp = (vec.x * cosf(a)) - (vec.y * sinf(a)); - vec.y = (vec.x * sinf(a)) + (vec.y * cosf(a)); - vec.x = xtemp; - return vec; -} - --(void)update:(ccTime)delta -{ - curTime_+= delta; - delta_ = delta; -} - --(float)sideOfLine:(CGPoint)p l1:(CGPoint)l1 l2:(CGPoint)l2 -{ - CGPoint vp = ccpPerp(ccpSub(l1, l2)); - CGPoint vx = ccpSub(p, l1); - return ccpDot(vx, vp); -} - -// adds a new segment to the ribbon --(void)addPointAt:(CGPoint)location width:(float)w -{ - location.x *= CC_CONTENT_SCALE_FACTOR(); - location.y *= CC_CONTENT_SCALE_FACTOR(); - - w = w*0.5f; - // if this is the first point added, cache it and return - if (!pastFirstPoint_) - { - lastWidth_ = w; - lastLocation_ = location; - pastFirstPoint_ = YES; - return; - } - - CGPoint sub = ccpSub(lastLocation_, location); - float r = ccpToAngle(sub) + (float)M_PI_2; - CGPoint p1 = ccpAdd([self rotatePoint:ccp(-w, 0) rotation:r], location); - CGPoint p2 = ccpAdd([self rotatePoint:ccp(w, 0) rotation:r], location); - float len = sqrtf(powf(lastLocation_.x - location.x, 2) + powf(lastLocation_.y - location.y, 2)); - float tend = texVPos_ + len/textureLength_; - CCRibbonSegment* seg; - // grab last segment - seg = [segments_ lastObject]; - // lets kill old segments - for (CCRibbonSegment* seg2 in segments_) - { - if (seg2 != seg && seg2->finished) - { - [deletedSegments_ addObject:seg2]; - } - } - [segments_ removeObjectsInArray:deletedSegments_]; - // is the segment full? - if (seg->end >= 50) - [segments_ removeObjectsInArray:deletedSegments_]; - // grab last segment and append to it if it's not full - seg = [segments_ lastObject]; - // is the segment full? - if (seg->end >= 50) - { - CCRibbonSegment* newSeg; - // grab it from the cache if we can - if ([deletedSegments_ count] > 0) - { - newSeg = [deletedSegments_ objectAtIndex:0]; - [newSeg retain]; // will be released later - [deletedSegments_ removeObject:newSeg]; - [newSeg reset]; - } - else - { - newSeg = [[CCRibbonSegment alloc] init]; // will be released later - } - - newSeg->creationTime[0] = seg->creationTime[seg->end - 1]; - int v = (seg->end-1)*6; - int c = (seg->end-1)*4; - newSeg->verts[0] = seg->verts[v]; - newSeg->verts[1] = seg->verts[v+1]; - newSeg->verts[2] = seg->verts[v+2]; - newSeg->verts[3] = seg->verts[v+3]; - newSeg->verts[4] = seg->verts[v+4]; - newSeg->verts[5] = seg->verts[v+5]; - - newSeg->coords[0] = seg->coords[c]; - newSeg->coords[1] = seg->coords[c+1]; - newSeg->coords[2] = seg->coords[c+2]; - newSeg->coords[3] = seg->coords[c+3]; - newSeg->end++; - seg = newSeg; - [segments_ addObject:seg]; - [newSeg release]; // it was retained before - - } - if (seg->end == 0) - { - // first edge has to get rotation from the first real polygon - CGPoint lp1 = ccpAdd([self rotatePoint:ccp(-lastWidth_, 0) rotation:r], lastLocation_); - CGPoint lp2 = ccpAdd([self rotatePoint:ccp(+lastWidth_, 0) rotation:r], lastLocation_); - seg->creationTime[0] = curTime_ - delta_; - seg->verts[0] = lp1.x; - seg->verts[1] = lp1.y; - seg->verts[2] = 0.0f; - seg->verts[3] = lp2.x; - seg->verts[4] = lp2.y; - seg->verts[5] = 0.0f; - seg->coords[0] = 0.0f; - seg->coords[1] = texVPos_; - seg->coords[2] = 1.0f; - seg->coords[3] = texVPos_; - seg->end++; - } - - int v = seg->end*6; - int c = seg->end*4; - // add new vertex - seg->creationTime[seg->end] = curTime_; - seg->verts[v] = p1.x; - seg->verts[v+1] = p1.y; - seg->verts[v+2] = 0.0f; - seg->verts[v+3] = p2.x; - seg->verts[v+4] = p2.y; - seg->verts[v+5] = 0.0f; - - - seg->coords[c] = 0.0f; - seg->coords[c+1] = tend; - seg->coords[c+2] = 1.0f; - seg->coords[c+3] = tend; - - texVPos_ = tend; - lastLocation_ = location; - lastPoint1_ = p1; - lastPoint2_ = p2; - lastWidth_ = w; - seg->end++; -} - --(void) draw -{ - if ([segments_ count] > 0) - { - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: GL_COLOR_ARRAY - glDisableClientState(GL_COLOR_ARRAY); - - glBindTexture(GL_TEXTURE_2D, [texture_ name]); - - BOOL newBlend = blendFunc_.src != CC_BLEND_SRC || blendFunc_.dst != CC_BLEND_DST; - if( newBlend ) - glBlendFunc( blendFunc_.src, blendFunc_.dst ); - - for (CCRibbonSegment* seg in segments_) - [seg draw:curTime_ fadeTime:fadeTime_ color:color_]; - - if( newBlend ) - glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); - - // restore default GL state - glEnableClientState( GL_COLOR_ARRAY ); - } -} - -#pragma mark Ribbon - CocosNodeTexture protocol --(void) setTexture:(CCTexture2D*) texture -{ - [texture_ release]; - texture_ = [texture retain]; - [self setContentSizeInPixels: texture.contentSizeInPixels]; - /* XXX Don't update blending function in Ribbons */ -} - --(CCTexture2D*) texture -{ - return texture_; -} - -@end - - -#pragma mark - -#pragma mark RibbonSegment - -@implementation CCRibbonSegment - --(id)init -{ - self = [super init]; - if (self) - { - [self reset]; - } - return self; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | end = %i, begin = %i>", [self class], self, end, begin]; -} - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - [super dealloc]; -} - --(void)reset -{ - end = 0; - begin = 0; - finished = NO; -} - --(void)draw:(float)curTime fadeTime:(float)fadeTime color:(ccColor4B)color -{ - GLubyte r = color.r; - GLubyte g = color.g; - GLubyte b = color.b; - GLubyte a = color.a; - - if (begin < 50) - { - // the motion streak class will call update and cause time to change, thus, if curTime_ != 0 - // we have to generate alpha for the ribbon each frame. - if (curTime == 0) - { - // no alpha over time, so just set the color - glColor4ub(r,g,b,a); - } - else - { - // generate alpha/color for each point - glEnableClientState(GL_COLOR_ARRAY); - uint i = begin; - for (; i < end; ++i) - { - int idx = i*8; - colors[idx] = r; - colors[idx+1] = g; - colors[idx+2] = b; - colors[idx+4] = r; - colors[idx+5] = g; - colors[idx+6] = b; - float alive = ((curTime - creationTime[i]) / fadeTime); - if (alive > 1) - { - begin++; - colors[idx+3] = 0; - colors[idx+7] = 0; - } - else - { - colors[idx+3] = (GLubyte)(255.f - (alive * 255.f)); - colors[idx+7] = colors[idx+3]; - } - } - glColorPointer(4, GL_UNSIGNED_BYTE, 0, &colors[begin*8]); - } - glVertexPointer(3, GL_FLOAT, 0, &verts[begin*6]); - glTexCoordPointer(2, GL_FLOAT, 0, &coords[begin*4]); - glDrawArrays(GL_TRIANGLE_STRIP, 0, (end - begin) * 2); - } - else - finished = YES; -} -@end - diff --git a/Example/libs/cocos2d/CCScene.h b/Example/libs/cocos2d/CCScene.h index eedc985..36b9085 100644 --- a/Example/libs/cocos2d/CCScene.h +++ b/Example/libs/cocos2d/CCScene.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,8 +28,8 @@ #import "CCNode.h" /** CCScene is a subclass of CCNode that is used only as an abstract concept. - - CCScene an CCNode are almost identical with the difference that CCScene has it's + + CCScene an CCNode are almost identical with the difference that CCScene has its anchor point (by default) at the center of the screen. For the moment CCScene has no other logic than that, but in future releases it might have diff --git a/Example/libs/cocos2d/CCScene.m b/Example/libs/cocos2d/CCScene.m index e1716bb..8c0f4a5 100644 --- a/Example/libs/cocos2d/CCScene.m +++ b/Example/libs/cocos2d/CCScene.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -36,9 +37,9 @@ -(id) init CGSize s = [[CCDirector sharedDirector] winSize]; self.isRelativeAnchorPoint = NO; anchorPoint_ = ccp(0.5f, 0.5f); - [self setContentSize:s]; + [self setContentSize:s]; } - + return self; } @end diff --git a/Example/libs/cocos2d/CCScheduler.h b/Example/libs/cocos2d/CCScheduler.h index 94e381f..32ca9ca 100644 --- a/Example/libs/cocos2d/CCScheduler.h +++ b/Example/libs/cocos2d/CCScheduler.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,14 +38,18 @@ typedef void (*TICK_IMP)(id, SEL, ccTime); { id target; TICK_IMP impMethod; - + ccTime elapsed; + BOOL runForever; + BOOL useDelay; + uint nTimesExecuted; + uint repeat; //0 = once, 1 is 2 x executed + ccTime delay; @public // optimization ccTime interval; SEL selector; } - /** interval in seconds */ @property (nonatomic,readwrite,assign) ccTime interval; @@ -60,9 +65,9 @@ typedef void (*TICK_IMP)(id, SEL, ccTime); */ -(id) initWithTarget:(id) t selector:(SEL)s; -/** Initializes a timer with a target, a selector and an interval in seconds. +/** Initializes a timer with a target, a selector, an interval in seconds, repeat in number of times to repeat, delay in seconds */ --(id) initWithTarget:(id) t selector:(SEL)s interval:(ccTime)seconds; +-(id) initWithTarget:(id)t selector:(SEL)s interval:(ccTime) seconds repeat:(uint) r delay:(ccTime) d; /** triggers the timer */ @@ -74,14 +79,14 @@ typedef void (*TICK_IMP)(id, SEL, ccTime); // // CCScheduler // -/** Scheduler is responsible of triggering the scheduled callbacks. +/** CCScheduler is responsible of triggering the scheduled callbacks. You should not use NSTimer. Instead use this class. - + There are 2 different types of callbacks (selectors): - update selector: the 'update' selector will be called every frame. You can customize the priority. - custom selector: A custom selector will be called every frame, or with a custom interval of time - + The 'custom selectors' should be avoided when possible. It is faster, and consumes less memory to use the 'update selector'. */ @@ -91,9 +96,9 @@ struct _hashSelectorEntry; struct _hashUpdateEntry; @interface CCScheduler : NSObject -{ +{ ccTime timeScale_; - + // // "updates with priority" stuff // @@ -101,15 +106,17 @@ struct _hashUpdateEntry; struct _listEntry *updates0; // list priority == 0 struct _listEntry *updatesPos; // list priority > 0 struct _hashUpdateEntry *hashForUpdates; // hash used to fetch quickly the list entries for pause,delete,etc. - + // Used for "selectors with interval" struct _hashSelectorEntry *hashForSelectors; struct _hashSelectorEntry *currentTarget; BOOL currentTargetSalvaged; - + // Optimization TICK_IMP impMethod; SEL updateSelector; + + BOOL updateHashLocked; // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. } /** Modifies the time of all scheduled callbacks. @@ -121,26 +128,23 @@ struct _hashUpdateEntry; */ @property (nonatomic,readwrite) ccTime timeScale; -/** returns a shared instance of the Scheduler */ -+(CCScheduler *)sharedScheduler; - -/** purges the shared scheduler. It releases the retained instance. - @since v0.99.0 - */ -+(void)purgeSharedScheduler; - -/** 'tick' the scheduler. +/** 'update' the scheduler. You should NEVER call this method, unless you know what you are doing. */ --(void) tick:(ccTime)dt; +-(void) update:(ccTime)dt; /** The scheduled method will be called every 'interval' seconds. If paused is YES, then it won't be called until it is resumed. If 'interval' is 0, it will be called every frame, but if so, it recommened to use 'scheduleUpdateForTarget:' instead. If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again. + repeat let the action be repeated repeat + 1 times, use kCCRepeatForever to let the action run continiously + delay is the amount of time the action will wait before it'll start - @since v0.99.3 + @since v0.99.3, repeat and delay added in v1.1 */ +-(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused repeat: (uint) repeat delay: (ccTime) delay; + +/** calls scheduleSelector with kCCRepeatForever and a 0 delay */ -(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused; /** Schedules the 'update' selector for a given target with a given priority. @@ -148,7 +152,7 @@ struct _hashUpdateEntry; The lower the priority, the earlier it is called. @since v0.99.3 */ --(void) scheduleUpdateForTarget:(id)target priority:(int)priority paused:(BOOL)paused; +-(void) scheduleUpdateForTarget:(id)target priority:(NSInteger)priority paused:(BOOL)paused; /** Unshedules a selector for a given target. If you want to unschedule the "update", use unscheudleUpdateForTarget. @@ -188,25 +192,9 @@ struct _hashUpdateEntry; */ -(void) resumeTarget:(id)target; - -/** schedules a Timer. - It will be fired in every frame. - - @deprecated Use scheduleSelector:forTarget:interval:paused instead. Will be removed in 1.0 +/** Returns whether or not the target is paused + @since v1.0.0 */ --(void) scheduleTimer: (CCTimer*) timer DEPRECATED_ATTRIBUTE; +-(BOOL) isTargetPaused:(id)target; -/** unschedules an already scheduled Timer - - @deprecated Use unscheduleSelector:forTarget. Will be removed in v1.0 - */ --(void) unscheduleTimer: (CCTimer*) timer DEPRECATED_ATTRIBUTE; - -/** unschedule all timers. - You should NEVER call this method, unless you know what you are doing. - - @deprecated Use scheduleAllSelectors instead. Will be removed in 1.0 - @since v0.8 - */ --(void) unscheduleAllTimers DEPRECATED_ATTRIBUTE; @end diff --git a/Example/libs/cocos2d/CCScheduler.m b/Example/libs/cocos2d/CCScheduler.m index 8111ffb..73c8eac 100644 --- a/Example/libs/cocos2d/CCScheduler.m +++ b/Example/libs/cocos2d/CCScheduler.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,6 +27,7 @@ // cocos2d imports #import "CCScheduler.h" #import "ccMacros.h" +#import "CCDirector.h" #import "Support/uthash.h" #import "Support/utlist.h" #import "Support/ccCArray.h" @@ -40,11 +42,11 @@ typedef struct _listEntry { struct _listEntry *prev, *next; - TICK_IMP impMethod; - id target; // not retained (retained by hashUpdateEntry) - int priority; - BOOL paused; - + TICK_IMP impMethod; + id target; // not retained (retained by hashUpdateEntry) + NSInteger priority; + BOOL paused; + BOOL markedForDeletion; // selector will no longer be called and entry will be removed at end of the next tick } tListEntry; typedef struct _hashUpdateEntry @@ -88,37 +90,43 @@ -(id) init +(id) timerWithTarget:(id)t selector:(SEL)s { - return [[[self alloc] initWithTarget:t selector:s] autorelease]; + return [[[self alloc] initWithTarget:t selector:s interval:0 repeat:kCCRepeatForever delay:0] autorelease]; } +(id) timerWithTarget:(id)t selector:(SEL)s interval:(ccTime) i { - return [[[self alloc] initWithTarget:t selector:s interval:i] autorelease]; + return [[[self alloc] initWithTarget:t selector:s interval:i repeat:kCCRepeatForever delay:0] autorelease]; } -(id) initWithTarget:(id)t selector:(SEL)s { - return [self initWithTarget:t selector:s interval:0]; + return [self initWithTarget:t selector:s interval:0 repeat:kCCRepeatForever delay: 0]; } --(id) initWithTarget:(id)t selector:(SEL)s interval:(ccTime) seconds +-(id) initWithTarget:(id)t selector:(SEL)s interval:(ccTime) seconds repeat:(uint) r delay:(ccTime) d { if( (self=[super init]) ) { #if COCOS2D_DEBUG NSMethodSignature *sig = [t methodSignatureForSelector:s]; NSAssert(sig !=0 , @"Signature not found for selector - does it have the following form? -(void) name: (ccTime) dt"); #endif - + // target is not retained. It is retained in the hash structure target = t; selector = s; impMethod = (TICK_IMP) [t methodForSelector:s]; elapsed = -1; interval = seconds; + repeat = r; + delay = d; + useDelay = (delay > 0) ? YES : NO; + repeat = r; + runForever = (repeat == kCCRepeatForever) ? YES : NO; } return self; } + - (NSString*) description { return [NSString stringWithFormat:@"<%@ = %08X | target:%@ selector:(%@)>", [self class], self, [target class], NSStringFromSelector(selector)]; @@ -133,12 +141,50 @@ -(void) dealloc -(void) update: (ccTime) dt { if( elapsed == - 1) + { elapsed = 0; + nTimesExecuted = 0; + } else - elapsed += dt; - if( elapsed >= interval ) { - impMethod(target, selector, elapsed); - elapsed = 0; + { + if (runForever && !useDelay) + {//standard timer usage + elapsed += dt; + if( elapsed >= interval ) { + impMethod(target, selector, elapsed); + elapsed = 0; + + } + } + else + {//advanced usage + elapsed += dt; + if (useDelay) + { + if( elapsed >= delay ) + { + impMethod(target, selector, elapsed); + elapsed = elapsed - delay; + nTimesExecuted+=1; + useDelay = NO; + } + } + else + { + if (elapsed >= interval) + { + impMethod(target, selector, elapsed); + elapsed = 0; + nTimesExecuted += 1; + + } + } + + if (nTimesExecuted > repeat) + { //unschedule timer + [[[CCDirector sharedDirector] scheduler] unscheduleSelector:selector forTarget:target]; + } + } } } @end @@ -155,33 +201,11 @@ -(void) removeHashElement:(tHashSelectorEntry*)element; @implementation CCScheduler -static CCScheduler *sharedScheduler; - @synthesize timeScale = timeScale_; -+ (CCScheduler *)sharedScheduler -{ - if (!sharedScheduler) - sharedScheduler = [[CCScheduler alloc] init]; - - return sharedScheduler; -} - -+(id)alloc -{ - NSAssert(sharedScheduler == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; -} - -+(void)purgeSharedScheduler -{ - [sharedScheduler release]; - sharedScheduler = nil; -} - - (id) init { - if( (self=[super init]) ) { + if( (self=[super init]) ) { timeScale_ = 1.0f; // used to trigger CCTimer#update @@ -193,24 +217,28 @@ - (id) init updatesNeg = NULL; updatesPos = NULL; hashForUpdates = NULL; - + // selectors with interval currentTarget = nil; currentTargetSalvaged = NO; hashForSelectors = nil; + updateHashLocked = NO; } return self; } +- (NSString*) description +{ + return [NSString stringWithFormat:@"<%@ = %08X | timeScale = %0.2f >", [self class], self, timeScale_]; +} + - (void) dealloc { CCLOG(@"cocos2d: deallocing %@", self); [self unscheduleAllSelectors]; - sharedScheduler = nil; - [super dealloc]; } @@ -225,41 +253,31 @@ -(void) removeHashElement:(tHashSelectorEntry*)element free(element); } --(void) scheduleTimer: (CCTimer*) t -{ - NSAssert(NO, @"Not implemented. Use scheduleSelector:forTarget:"); -} - --(void) unscheduleTimer: (CCTimer*) t -{ - NSAssert(NO, @"Not implemented. Use unscheduleSelector:forTarget:"); -} - --(void) unscheduleAllTimers +-(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused { - NSAssert(NO, @"Not implemented. Use unscheduleAllSelectors"); + [self scheduleSelector:selector forTarget:target interval:interval paused:paused repeat:kCCRepeatForever delay:0.0f]; } --(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused +-(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused repeat:(uint) repeat delay:(ccTime) delay { NSAssert( selector != nil, @"Argument selector must be non-nil"); - NSAssert( target != nil, @"Argument target must be non-nil"); - + NSAssert( target != nil, @"Argument target must be non-nil"); + tHashSelectorEntry *element = NULL; HASH_FIND_INT(hashForSelectors, &target, element); - + if( ! element ) { element = calloc( sizeof( *element ), 1 ); element->target = [target retain]; HASH_ADD_INT( hashForSelectors, target, element ); - + // Is this the 1st element ? Then set the pause level to all the selectors of this target element->paused = paused; - + } else NSAssert( element->paused == paused, @"CCScheduler. Trying to schedule a selector with a pause value different than the target"); - - + + if( element->timers == nil ) element->timers = ccArrayNew(10); else @@ -274,8 +292,8 @@ -(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)int } ccArrayEnsureExtraCapacity(element->timers, 1); } - - CCTimer *timer = [[CCTimer alloc] initWithTarget:target selector:selector interval:interval]; + + CCTimer *timer = [[CCTimer alloc] initWithTarget:target selector:selector interval:interval repeat:repeat delay:delay]; ccArrayAppendObject(element->timers, timer); [timer release]; } @@ -285,28 +303,28 @@ -(void) unscheduleSelector:(SEL)selector forTarget:(id)target // explicity handle nil arguments when removing an object if( target==nil && selector==NULL) return; - + NSAssert( target != nil, @"Target MUST not be nil"); NSAssert( selector != NULL, @"Selector MUST not be NULL"); - + tHashSelectorEntry *element = NULL; HASH_FIND_INT(hashForSelectors, &target, element); - + if( element ) { - + for( unsigned int i=0; i< element->timers->num; i++ ) { CCTimer *timer = element->timers->arr[i]; - - + + if( selector == timer->selector ) { - + if( timer == element->currentTimer && !element->currentTimerSalvaged ) { [element->currentTimer retain]; element->currentTimerSalvaged = YES; } ccArrayRemoveObjectAtIndex(element->timers, i ); - + // update timerIndex in case we are in tick:, looping over the actions if( element->timerIndex >= i ) element->timerIndex--; @@ -321,7 +339,7 @@ -(void) unscheduleSelector:(SEL)selector forTarget:(id)target } } } - + // Not Found // NSLog(@"CCScheduler#unscheduleSelector:forTarget: selector not found: %@", selString); @@ -329,7 +347,7 @@ -(void) unscheduleSelector:(SEL)selector forTarget:(id)target #pragma mark CCScheduler - Update Specific --(void) priorityIn:(tListEntry**)list target:(id)target priority:(int)priority paused:(BOOL)paused +-(void) priorityIn:(tListEntry**)list target:(id)target priority:(NSInteger)priority paused:(BOOL)paused { tListEntry *listElement = malloc( sizeof(*listElement) ); @@ -338,18 +356,18 @@ -(void) priorityIn:(tListEntry**)list target:(id)target priority:(int)priority p listElement->paused = paused; listElement->impMethod = (TICK_IMP) [target methodForSelector:updateSelector]; listElement->next = listElement->prev = NULL; - - + listElement->markedForDeletion = NO; + // empty list ? if( ! *list ) { DL_APPEND( *list, listElement ); - + } else { - BOOL added = NO; - + BOOL added = NO; + for( tListEntry *elem = *list; elem ; elem = elem->next ) { if( priority < elem->priority ) { - + if( elem == *list ) DL_PREPEND(*list, listElement); else { @@ -359,17 +377,17 @@ -(void) priorityIn:(tListEntry**)list target:(id)target priority:(int)priority p elem->prev->next = listElement; elem->prev = listElement; } - + added = YES; break; } } - + // Not added? priority has the higher value. Append it. if( !added ) DL_APPEND(*list, listElement); } - + // update hash entry for quicker access tHashUpdateEntry *hashElement = calloc( sizeof(*hashElement), 1 ); hashElement->target = [target retain]; @@ -381,30 +399,38 @@ -(void) priorityIn:(tListEntry**)list target:(id)target priority:(int)priority p -(void) appendIn:(tListEntry**)list target:(id)target paused:(BOOL)paused { tListEntry *listElement = malloc( sizeof( * listElement ) ); - + listElement->target = target; listElement->paused = paused; + listElement->markedForDeletion = NO; listElement->impMethod = (TICK_IMP) [target methodForSelector:updateSelector]; - + DL_APPEND(*list, listElement); - + // update hash entry for quicker access tHashUpdateEntry *hashElement = calloc( sizeof(*hashElement), 1 ); hashElement->target = [target retain]; hashElement->list = list; hashElement->entry = listElement; - HASH_ADD_INT(hashForUpdates, target, hashElement ); + HASH_ADD_INT(hashForUpdates, target, hashElement ); } --(void) scheduleUpdateForTarget:(id)target priority:(int)priority paused:(BOOL)paused +-(void) scheduleUpdateForTarget:(id)target priority:(NSInteger)priority paused:(BOOL)paused { -#if COCOS2D_DEBUG >= 1 tHashUpdateEntry * hashElement = NULL; HASH_FIND_INT(hashForUpdates, &target, hashElement); - NSAssert( hashElement == NULL, @"CCScheduler: You can't re-schedule an 'update' selector'. Unschedule it first"); -#endif - + if(hashElement) + { +#if COCOS2D_DEBUG >= 1 + NSAssert( hashElement->entry->markedForDeletion, @"CCScheduler: You can't re-schedule an 'update' selector'. Unschedule it first"); +#endif + // TODO : check if priority has changed! + + hashElement->entry->markedForDeletion = NO; + return; + } + // most of the updates are going to be 0, that's way there // is an special list for updates with priority 0 if( priority == 0 ) @@ -417,23 +443,44 @@ -(void) scheduleUpdateForTarget:(id)target priority:(int)priority paused:(BOOL)p [self priorityIn:&updatesPos target:target priority:priority paused:paused]; } +- (void) removeUpdateFromHash:(tListEntry*)entry +{ + tHashUpdateEntry * element = NULL; + + HASH_FIND_INT(hashForUpdates, &entry->target, element); + if( element ) { + // list entry + DL_DELETE( *element->list, element->entry ); + free( element->entry ); + + // hash entry + [element->target release]; + HASH_DEL( hashForUpdates, element); + free(element); + } +} + -(void) unscheduleUpdateForTarget:(id)target { if( target == nil ) return; - + tHashUpdateEntry * element = NULL; HASH_FIND_INT(hashForUpdates, &target, element); if( element ) { - - // list entry - DL_DELETE( *element->list, element->entry ); - free( element->entry ); - - // hash entry - [element->target release]; - HASH_DEL( hashForUpdates, element); - free(element); + if(updateHashLocked) + element->entry->markedForDeletion = YES; + else + [self removeUpdateFromHash:element->entry]; + +// // list entry +// DL_DELETE( *element->list, element->entry ); +// free( element->entry ); +// +// // hash entry +// [element->target release]; +// HASH_DEL( hashForUpdates, element); +// free(element); } } @@ -442,7 +489,7 @@ -(void) unscheduleUpdateForTarget:(id)target -(void) unscheduleAllSelectors { // Custom Selectors - for(tHashSelectorEntry *element=hashForSelectors; element != NULL; ) { + for(tHashSelectorEntry *element=hashForSelectors; element != NULL; ) { id target = element->target; element=element->hh.next; [self unscheduleAllSelectorsForTarget:target]; @@ -459,7 +506,7 @@ -(void) unscheduleAllSelectors DL_FOREACH_SAFE( updatesPos, entry, tmp ) { [self unscheduleUpdateForTarget:entry->target]; } - + } -(void) unscheduleAllSelectorsForTarget:(id)target @@ -467,11 +514,11 @@ -(void) unscheduleAllSelectorsForTarget:(id)target // explicit nil handling if( target == nil ) return; - + // Custom Selectors tHashSelectorEntry *element = NULL; HASH_FIND_INT(hashForSelectors, &target, element); - + if( element ) { if( ccArrayContainsObject(element->timers, element->currentTimer) && !element->currentTimerSalvaged ) { [element->currentTimer retain]; @@ -483,7 +530,7 @@ -(void) unscheduleAllSelectorsForTarget:(id)target else [self removeHashElement:element]; } - + // Update Selector [self unscheduleUpdateForTarget:target]; } @@ -491,32 +538,32 @@ -(void) unscheduleAllSelectorsForTarget:(id)target -(void) resumeTarget:(id)target { NSAssert( target != nil, @"target must be non nil" ); - + // Custom Selectors tHashSelectorEntry *element = NULL; HASH_FIND_INT(hashForSelectors, &target, element); if( element ) element->paused = NO; - + // Update selector tHashUpdateEntry * elementUpdate = NULL; HASH_FIND_INT(hashForUpdates, &target, elementUpdate); if( elementUpdate ) { NSAssert( elementUpdate->entry != NULL, @"resumeTarget: unknown error"); elementUpdate->entry->paused = NO; - } + } } -(void) pauseTarget:(id)target { NSAssert( target != nil, @"target must be non nil" ); - + // Custom selectors tHashSelectorEntry *element = NULL; HASH_FIND_INT(hashForSelectors, &target, element); if( element ) element->paused = YES; - + // Update selector tHashUpdateEntry * elementUpdate = NULL; HASH_FIND_INT(hashForUpdates, &target, elementUpdate); @@ -524,74 +571,118 @@ -(void) pauseTarget:(id)target NSAssert( elementUpdate->entry != NULL, @"pauseTarget: unknown error"); elementUpdate->entry->paused = YES; } - + +} + +-(BOOL) isTargetPaused:(id)target +{ + NSAssert( target != nil, @"target must be non nil" ); + + // Custom selectors + tHashSelectorEntry *element = NULL; + HASH_FIND_INT(hashForSelectors, &target, element); + if( element ) + { + return element->paused; + } + return NO; // should never get here + } #pragma mark CCScheduler - Main Loop --(void) tick: (ccTime) dt +-(void) update: (ccTime) dt { + updateHashLocked = YES; + if( timeScale_ != 1.0f ) dt *= timeScale_; - + // Iterate all over the Updates selectors tListEntry *entry, *tmp; // updates with priority < 0 DL_FOREACH_SAFE( updatesNeg, entry, tmp ) { - if( ! entry->paused ) + if( ! entry->paused && !entry->markedForDeletion ) entry->impMethod( entry->target, updateSelector, dt ); } // updates with priority == 0 DL_FOREACH_SAFE( updates0, entry, tmp ) { - if( ! entry->paused ) + if( ! entry->paused && !entry->markedForDeletion ) + { entry->impMethod( entry->target, updateSelector, dt ); + } } - + // updates with priority > 0 DL_FOREACH_SAFE( updatesPos, entry, tmp ) { - if( ! entry->paused ) + if( ! entry->paused && !entry->markedForDeletion ) entry->impMethod( entry->target, updateSelector, dt ); } - + // Iterate all over the custome selectors - for(tHashSelectorEntry *elt=hashForSelectors; elt != NULL; ) { - + for(tHashSelectorEntry *elt=hashForSelectors; elt != NULL; ) { + currentTarget = elt; currentTargetSalvaged = NO; if( ! currentTarget->paused ) { - + // The 'timers' ccArray may change while inside this loop. for( elt->timerIndex = 0; elt->timerIndex < elt->timers->num; elt->timerIndex++) { elt->currentTimer = elt->timers->arr[elt->timerIndex]; elt->currentTimerSalvaged = NO; impMethod( elt->currentTimer, updateSelector, dt); - + if( elt->currentTimerSalvaged ) { // The currentTimer told the remove itself. To prevent the timer from // accidentally deallocating itself before finishing its step, we retained - // it. Now that step is done, it's safe to release it. + // it. Now that step is done, it is safe to release it. [elt->currentTimer release]; } - + elt->currentTimer = nil; - } + } } - + // elt, at this moment, is still valid // so it is safe to ask this here (issue #490) elt = elt->hh.next; - + // only delete currentTarget if no actions were scheduled during the cycle (issue #481) if( currentTargetSalvaged && currentTarget->timers->num == 0 ) - [self removeHashElement:currentTarget]; + [self removeHashElement:currentTarget]; + } + + // delete all updates that are morked for deletion + // updates with priority < 0 + DL_FOREACH_SAFE( updatesNeg, entry, tmp ) { + if(entry->markedForDeletion ) + { + [self removeUpdateFromHash:entry]; + } + } + + // updates with priority == 0 + DL_FOREACH_SAFE( updates0, entry, tmp ) { + if(entry->markedForDeletion ) + { + [self removeUpdateFromHash:entry]; + } + } + + // updates with priority > 0 + DL_FOREACH_SAFE( updatesPos, entry, tmp ) { + if(entry->markedForDeletion ) + { + [self removeUpdateFromHash:entry]; + } } - + + updateHashLocked = NO; currentTarget = nil; } - @end diff --git a/Example/libs/cocos2d/CCSprite.h b/Example/libs/cocos2d/CCSprite.h index 8b35176..497ce22 100644 --- a/Example/libs/cocos2d/CCSprite.h +++ b/Example/libs/cocos2d/CCSprite.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,36 +30,13 @@ #import "CCTextureAtlas.h" @class CCSpriteBatchNode; -@class CCSpriteSheet; -@class CCSpriteSheetInternalOnly; @class CCSpriteFrame; @class CCAnimation; #pragma mark CCSprite -enum { - /// CCSprite invalid index on the CCSpriteBatchode - CCSpriteIndexNotInitialized = 0xffffffff, -}; - -/** - Whether or not an CCSprite will rotate, scale or translate with it's parent. - Useful in health bars, when you want that the health bar translates with it's parent but you don't - want it to rotate with its parent. - @since v0.99.0 - */ -typedef enum { - //! Translate with it's parent - CC_HONOR_PARENT_TRANSFORM_TRANSLATE = 1 << 0, - //! Rotate with it's parent - CC_HONOR_PARENT_TRANSFORM_ROTATE = 1 << 1, - //! Scale with it's parent - CC_HONOR_PARENT_TRANSFORM_SCALE = 1 << 2, - - //! All possible transformation enabled. Default value. - CC_HONOR_PARENT_TRANSFORM_ALL = CC_HONOR_PARENT_TRANSFORM_TRANSLATE | CC_HONOR_PARENT_TRANSFORM_ROTATE | CC_HONOR_PARENT_TRANSFORM_SCALE, +#define CCSpriteIndexNotInitialized 0xffffffff /// CCSprite invalid index on the CCSpriteBatchode -} ccHonorParentTransform; /** CCSprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) * @@ -84,18 +62,19 @@ typedef enum { */ @interface CCSprite : CCNode { - + // // Data used when the sprite is rendered using a CCSpriteBatchNode // CCTextureAtlas *textureAtlas_; // Sprite Sheet texture atlas (weak reference) NSUInteger atlasIndex_; // Absolute (real) Index on the batch node CCSpriteBatchNode *batchNode_; // Used batch node (weak reference) - ccHonorParentTransform honorParentTransform_; // whether or not to transform according to its parent transformations + CGAffineTransform transformToBatch_; // BOOL dirty_; // Sprite needs to be updated BOOL recursiveDirty_; // Subchildren needs to be updated BOOL hasChildren_; // optimization to check if it contain children - + BOOL shouldBeHidden_; // should not be drawn because one of the ancestors is not visible + // // Data used when the sprite is self-rendered // @@ -106,55 +85,45 @@ typedef enum { // Shared data // - // whether or not it's parent is a CCSpriteBatchNode - BOOL usesBatchNode_; + // sprite rectangle + CGRect rect_; // texture - CGRect rect_; - CGRect rectInPixels_; BOOL rectRotated_; - + // Offset Position (used by Zwoptex) - CGPoint offsetPositionInPixels_; + CGPoint offsetPosition_; CGPoint unflippedOffsetPositionFromCenter_; // vertex coords, texture coords and color info ccV3F_C4B_T2F_Quad quad_; - + // opacity and RGB protocol GLubyte opacity_; ccColor3B color_; ccColor3B colorUnmodified_; BOOL opacityModifyRGB_; - + // image is flipped BOOL flipX_; BOOL flipY_; - - - // Animations that belong to the sprite - NSMutableDictionary *animations_; - -@public - // used internally. - void (*updateMethod)(id, SEL); } /** whether or not the Sprite needs to be updated in the Atlas */ @property (nonatomic,readwrite) BOOL dirty; /** the quad (tex coords, vertex coords and color) information */ @property (nonatomic,readonly) ccV3F_C4B_T2F_Quad quad; -/** The index used on the TextureATlas. Don't modify this value unless you know what you are doing */ +/** The index used on the TextureAtlas. Don't modify this value unless you know what you are doing */ @property (nonatomic,readwrite) NSUInteger atlasIndex; -/** returns the rect of the CCSprite in points */ +/** returns the texture rect of the CCSprite in points */ @property (nonatomic,readonly) CGRect textureRect; /** returns whether or not the texture rectangle is rotated */ @property (nonatomic,readonly) BOOL textureRectRotated; -/** whether or not the sprite is flipped horizontally. +/** whether or not the sprite is flipped horizontally. It only flips the texture of the sprite, and not the texture of the sprite's children. Also, flipping the texture doesn't alter the anchorPoint. If you want to flip the anchorPoint too, and/or to flip the children too use: - + sprite.scaleX *= -1; */ @property (nonatomic,readwrite) BOOL flipX; @@ -162,7 +131,7 @@ typedef enum { It only flips the texture of the sprite, and not the texture of the sprite's children. Also, flipping the texture doesn't alter the anchorPoint. If you want to flip the anchorPoint too, and/or to flip the children too use: - + sprite.scaleY *= -1; */ @property (nonatomic,readwrite) BOOL flipY; @@ -170,22 +139,14 @@ typedef enum { @property (nonatomic,readwrite) GLubyte opacity; /** RGB colors: conforms to CCRGBAProtocol protocol */ @property (nonatomic,readwrite) ccColor3B color; -/** whether or not the Sprite is rendered using a CCSpriteBatchNode */ -@property (nonatomic,readwrite) BOOL usesBatchNode; /** weak reference of the CCTextureAtlas used when the sprite is rendered using a CCSpriteBatchNode */ @property (nonatomic,readwrite,assign) CCTextureAtlas *textureAtlas; /** weak reference to the CCSpriteBatchNode that renders the CCSprite */ @property (nonatomic,readwrite,assign) CCSpriteBatchNode *batchNode; -/** whether or not to transform according to its parent transfomrations. - Useful for health bars. eg: Don't rotate the health bar, even if the parent rotates. - IMPORTANT: Only valid if it is rendered using an CCSpriteBatchNode. - @since v0.99.0 - */ -@property (nonatomic,readwrite) ccHonorParentTransform honorParentTransform; -/** offset position in pixels of the sprite in points. Calculated automatically by editors like Zwoptex. +/** offset position in points of the sprite in points. Calculated automatically by editors like Zwoptex. @since v0.99.0 */ -@property (nonatomic,readonly) CGPoint offsetPositionInPixels; +@property (nonatomic,readonly) CGPoint offsetPosition; /** conforms to CCTextureProtocol protocol */ @property (nonatomic,readwrite) ccBlendFunc blendFunc; @@ -224,38 +185,32 @@ typedef enum { */ +(id) spriteWithFile:(NSString*)filename rect:(CGRect)rect; -/** Creates an sprite with a CGImageRef. - @deprecated Use spriteWithCGImage:key: instead. Will be removed in v1.0 final - */ -+(id) spriteWithCGImage: (CGImageRef)image DEPRECATED_ATTRIBUTE; - /** Creates an sprite with a CGImageRef and a key. The key is used by the CCTextureCache to know if a texture was already created with this CGImage. For example, a valid key is: @"sprite_frame_01". - If key is nil, then a new texture will be created each time by the CCTextureCache. + If key is nil, then a new texture will be created each time by the CCTextureCache. @since v0.99.0 */ +(id) spriteWithCGImage: (CGImageRef)image key:(NSString*)key; - -/** Creates an sprite with an CCBatchNode and a rect - */ -+(id) spriteWithBatchNode:(CCSpriteBatchNode*)batchNode rect:(CGRect)rect; - -+(id) spriteWithSpriteSheet:(CCSpriteSheetInternalOnly*)spritesheet rect:(CGRect)rect DEPRECATED_ATTRIBUTE; - - /** Initializes an sprite with a texture. The rect used will be the size of the texture. The offset will be (0,0). */ -(id) initWithTexture:(CCTexture2D*)texture; -/** Initializes an sprite with a texture and a rect in points. +/** Initializes an sprite with a texture and a rect in points (unrotated) The offset will be (0,0). */ -(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; +/** Initializes an sprite with a texture and a rect in points, optionally rotated. + The offset will be (0,0). + IMPORTANT: This is the designated initializer. + */ +- (id)initWithTexture:(CCTexture2D *)texture rect:(CGRect)rect rotated:(BOOL)rotated; + + /** Initializes an sprite with an sprite frame. */ -(id) initWithSpriteFrame:(CCSpriteFrame*)spriteFrame; @@ -278,54 +233,37 @@ typedef enum { */ -(id) initWithFile:(NSString*)filename rect:(CGRect)rect; -/** Initializes an sprite with a CGImageRef - @deprecated Use spriteWithCGImage:key: instead. Will be removed in v1.0 final - */ --(id) initWithCGImage: (CGImageRef)image DEPRECATED_ATTRIBUTE; - /** Initializes an sprite with a CGImageRef and a key The key is used by the CCTextureCache to know if a texture was already created with this CGImage. For example, a valid key is: @"sprite_frame_01". - If key is nil, then a new texture will be created each time by the CCTextureCache. + If key is nil, then a new texture will be created each time by the CCTextureCache. @since v0.99.0 */ -(id) initWithCGImage:(CGImageRef)image key:(NSString*)key; -/** Initializes an sprite with an CCSpriteSheet and a rect in points - */ --(id) initWithBatchNode:(CCSpriteBatchNode*)batchNode rect:(CGRect)rect; --(id) initWithSpriteSheet:(CCSpriteSheetInternalOnly*)spritesheet rect:(CGRect)rect DEPRECATED_ATTRIBUTE; - -/** Initializes an sprite with an CCSpriteSheet and a rect in pixels - @since v0.99.5 - */ --(id) initWithBatchNode:(CCSpriteBatchNode*)batchNode rectInPixels:(CGRect)rect; - - - #pragma mark CCSprite - BatchNode methods /** updates the quad according the the rotation, position, scale values. */ -(void)updateTransform; -/** updates the texture rect of the CCSprite in points. +#pragma mark CCSprite - Texture methods + +/** set the texture rect of the CCSprite in points. + It will call setTextureRect:rotated:untrimmedSize with rotated = NO, and utrimmedSize = rect.size. */ -(void) setTextureRect:(CGRect) rect; -/** updates the texture rect, rectRotated and untrimmed size of the CCSprite in pixels - */ --(void) setTextureRectInPixels:(CGRect)rect rotated:(BOOL)rotated untrimmedSize:(CGSize)size; -/** tell the sprite to use self-render. - @since v0.99.0 +/** set the texture rect, rectRotated and untrimmed size of the CCSprite in points. + It will update the texture coordinates and the vertex rectangle. */ --(void) useSelfRender; +-(void) setTextureRect:(CGRect)rect rotated:(BOOL)rotated untrimmedSize:(CGSize)size; -/** tell the sprite to use sprite batch node - @since v0.99.0 +/** set the vertex rect. + It will be called internally by setTextureRect. Useful if you want to create 2x images from SD images in Retina Display. + Do not call it manually. Use setTextureRect instead. */ --(void) useBatchNode:(CCSpriteBatchNode*)batchNode; --(void) useSpriteSheetRender:(CCSpriteSheetInternalOnly*)spriteSheet DEPRECATED_ATTRIBUTE; +-(void)setVertexRect:(CGRect)rect; #pragma mark CCSprite - Frames @@ -337,31 +275,14 @@ typedef enum { -(BOOL) isFrameDisplayed:(CCSpriteFrame*)frame; /** returns the current displayed frame. */ --(CCSpriteFrame*) displayedFrame; +-(CCSpriteFrame*) displayFrame; #pragma mark CCSprite - Animation -/** changes the display frame based on an animation and an index. - @deprecated Will be removed in 1.0.1. Use setDisplayFrameWithAnimationName:index instead - */ --(void) setDisplayFrame: (NSString*) animationName index:(int) frameIndex DEPRECATED_ATTRIBUTE; - /** changes the display frame with animation name and index. The animation name will be get from the CCAnimationCache @since v0.99.5 */ -(void) setDisplayFrameWithAnimationName:(NSString*)animationName index:(int) frameIndex; -/** returns an Animation given it's name. - - @deprecated Use CCAnimationCache instead. Will be removed in 1.0.1 - */ --(CCAnimation*)animationByName: (NSString*) animationName DEPRECATED_ATTRIBUTE; - -/** adds an Animation to the Sprite. - - @deprecated Use CCAnimationCache instead. Will be removed in 1.0.1 - */ --(void) addAnimation: (CCAnimation*) animation DEPRECATED_ATTRIBUTE; - @end diff --git a/Example/libs/cocos2d/CCSprite.m b/Example/libs/cocos2d/CCSprite.m index 7875782..a19ed22 100644 --- a/Example/libs/cocos2d/CCSprite.m +++ b/Example/libs/cocos2d/CCSprite.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,19 +24,26 @@ * */ -#import - #import "ccConfig.h" #import "CCSpriteBatchNode.h" -#import "CCSpriteSheet.h" #import "CCSprite.h" #import "CCSpriteFrame.h" #import "CCSpriteFrameCache.h" #import "CCAnimation.h" #import "CCAnimationCache.h" #import "CCTextureCache.h" -#import "Support/CGPointExtension.h" #import "CCDrawingPrimitives.h" +#import "CCShaderCache.h" +#import "ccGLStateCache.h" +#import "CCGLProgram.h" +#import "CCDirector.h" +#import "Support/CGPointExtension.h" +#import "Support/TransformUtils.h" +#import "Support/CCProfiling.h" +#import "Support/OpenGL_Internal.h" + +// external +#import "kazmath/GL/matrix.h" #pragma mark - #pragma mark CCSprite @@ -46,20 +54,11 @@ #define RENDER_IN_SUBPIXEL(__A__) ( (int)(__A__)) #endif -// XXX: Optmization -struct transformValues_ { - CGPoint pos; // position x and y - CGPoint scale; // scale x and y - float rotation; - CGPoint ap; // anchor point in pixels - BOOL visible; -}; - -@interface CCSprite (Private) --(void)updateTextureCoords:(CGRect)rect; --(void)updateBlendFunc; --(void) initAnimationDictionary; --(void) getTransformValues:(struct transformValues_*)tv; // optimization + +@interface CCSprite () +-(void) setTextureCoords:(CGRect)rect; +-(void) updateBlendFunc; +-(void) setReorderChildDirtyRecursively; @end @implementation CCSprite @@ -70,11 +69,8 @@ @implementation CCSprite @synthesize textureRect = rect_; @synthesize textureRectRotated = rectRotated_; @synthesize blendFunc = blendFunc_; -@synthesize usesBatchNode = usesBatchNode_; @synthesize textureAtlas = textureAtlas_; -@synthesize batchNode = batchNode_; -@synthesize honorParentTransform = honorParentTransform_; -@synthesize offsetPositionInPixels = offsetPositionInPixels_; +@synthesize offsetPosition = offsetPosition_; +(id)spriteWithTexture:(CCTexture2D*)texture @@ -105,13 +101,9 @@ +(id)spriteWithSpriteFrame:(CCSpriteFrame*)spriteFrame +(id)spriteWithSpriteFrameName:(NSString*)spriteFrameName { CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:spriteFrameName]; - return [self spriteWithSpriteFrame:frame]; -} -// XXX: deprecated -+(id)spriteWithCGImage:(CGImageRef)image -{ - return [[[self alloc] initWithCGImage:image] autorelease]; + NSAssert1(frame!=nil, @"Invalid spriteFrameName: %@", spriteFrameName); + return [self spriteWithSpriteFrame:frame]; } +(id)spriteWithCGImage:(CGImageRef)image key:(NSString*)key @@ -119,82 +111,64 @@ +(id)spriteWithCGImage:(CGImageRef)image key:(NSString*)key return [[[self alloc] initWithCGImage:image key:key] autorelease]; } -+(id) spriteWithBatchNode:(CCSpriteBatchNode*)batchNode rect:(CGRect)rect -{ - return [[[self alloc] initWithBatchNode:batchNode rect:rect] autorelease]; -} -+(id) spriteWithSpriteSheet:(CCSpriteSheetInternalOnly*)spritesheet rect:(CGRect)rect // XXX DEPRECATED +-(id) init { - return [self spriteWithBatchNode:spritesheet rect:rect]; + return [self initWithTexture:nil rect:CGRectZero]; } --(id) init +// designated initializer +-(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect rotated:(BOOL)rotated { - if( (self=[super init]) ) { + if( (self = [super init]) ) + { + // shader program + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; + dirty_ = recursiveDirty_ = NO; - - // by default use "Self Render". - // if the sprite is added to an SpriteSheet, then it will automatically switch to "SpriteSheet Render" - [self useSelfRender]; - + opacityModifyRGB_ = YES; opacity_ = 255; color_ = colorUnmodified_ = ccWHITE; - + blendFunc_.src = CC_BLEND_SRC; blendFunc_.dst = CC_BLEND_DST; - - // update texture (calls updateBlendFunc) - [self setTexture:nil]; - - // clean the Quad - bzero(&quad_, sizeof(quad_)); - + flipY_ = flipX_ = NO; - - // lazy alloc - animations_ = nil; - + // default transform anchor: center anchorPoint_ = ccp(0.5f, 0.5f); - + // zwoptex default values - offsetPositionInPixels_ = CGPointZero; - - honorParentTransform_ = CC_HONOR_PARENT_TRANSFORM_ALL; + offsetPosition_ = CGPointZero; + hasChildren_ = NO; - + batchNode_ = nil; + + // clean the Quad + bzero(&quad_, sizeof(quad_)); + // Atlas: Color ccColor4B tmpColor = {255,255,255,255}; quad_.bl.colors = tmpColor; quad_.br.colors = tmpColor; quad_.tl.colors = tmpColor; - quad_.tr.colors = tmpColor; - - // Atlas: Vertex - - // updated in "useSelfRender" - - // Atlas: TexCoords - [self setTextureRectInPixels:CGRectZero rotated:NO untrimmedSize:CGSizeZero]; - - // updateMethod selector - updateMethod = (__typeof__(updateMethod))[self methodForSelector:@selector(updateTransform)]; + quad_.tr.colors = tmpColor; + + [self setTexture:texture]; + [self setTextureRect:rect rotated:rotated untrimmedSize:rect.size]; + + + // by default use "Self Render". + // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" + [self setBatchNode:nil]; + } - return self; } -(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect { - NSAssert(texture!=nil, @"Invalid texture for sprite"); - // IMPORTANT: [self init] and not [super init]; - if( (self = [self init]) ) - { - [self setTexture:texture]; - [self setTextureRect:rect]; - } - return self; + return [self initWithTexture:texture rect:rect rotated:NO]; } -(id) initWithTexture:(CCTexture2D*)texture @@ -208,7 +182,7 @@ -(id) initWithTexture:(CCTexture2D*)texture -(id) initWithFile:(NSString*)filename { - NSAssert(filename!=nil, @"Invalid filename for sprite"); + NSAssert(filename != nil, @"Invalid filename for sprite"); CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage: filename]; if( texture ) { @@ -250,54 +224,17 @@ -(id)initWithSpriteFrameName:(NSString*)spriteFrameName return [self initWithSpriteFrame:frame]; } -// XXX: deprecated -- (id) initWithCGImage: (CGImageRef)image +- (id) initWithCGImage:(CGImageRef)image key:(NSString*)key { NSAssert(image!=nil, @"Invalid CGImageRef for sprite"); // XXX: possible bug. See issue #349. New API should be added - NSString *key = [NSString stringWithFormat:@"%08X",(unsigned long)image]; CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addCGImage:image forKey:key]; - - CGRect rect = CGRectZero; - rect.size = texture.contentSize; - - return [self initWithTexture:texture rect:rect]; -} -- (id) initWithCGImage:(CGImageRef)image key:(NSString*)key -{ - NSAssert(image!=nil, @"Invalid CGImageRef for sprite"); - - // XXX: possible bug. See issue #349. New API should be added - CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addCGImage:image forKey:key]; - CGRect rect = CGRectZero; rect.size = texture.contentSize; - - return [self initWithTexture:texture rect:rect]; -} --(id) initWithBatchNode:(CCSpriteBatchNode*)batchNode rect:(CGRect)rect -{ - id ret = [self initWithTexture:batchNode.texture rect:rect]; - [self useBatchNode:batchNode]; - - return ret; -} - --(id) initWithBatchNode:(CCSpriteBatchNode*)batchNode rectInPixels:(CGRect)rect -{ - id ret = [self initWithTexture:batchNode.texture]; - [self setTextureRectInPixels:rect rotated:NO untrimmedSize:rect.size]; - [self useBatchNode:batchNode]; - - return ret; -} - --(id) initWithSpriteSheet:(CCSpriteSheetInternalOnly*)spritesheet rect:(CGRect)rect // XXX DEPRECATED -{ - return [self initWithBatchNode:spritesheet rect:rect]; + return [self initWithTexture:texture rect:rect]; } - (NSString*) description @@ -312,73 +249,69 @@ - (NSString*) description - (void) dealloc { [texture_ release]; - [animations_ release]; [super dealloc]; } --(void) useSelfRender +-(CCSpriteBatchNode*) batchNode { - atlasIndex_ = CCSpriteIndexNotInitialized; - usesBatchNode_ = NO; - textureAtlas_ = nil; - batchNode_ = nil; - dirty_ = recursiveDirty_ = NO; - - float x1 = 0 + offsetPositionInPixels_.x; - float y1 = 0 + offsetPositionInPixels_.y; - float x2 = x1 + rectInPixels_.size.width; - float y2 = y1 + rectInPixels_.size.height; - quad_.bl.vertices = (ccVertex3F) { x1, y1, 0 }; - quad_.br.vertices = (ccVertex3F) { x2, y1, 0 }; - quad_.tl.vertices = (ccVertex3F) { x1, y2, 0 }; - quad_.tr.vertices = (ccVertex3F) { x2, y2, 0 }; + return batchNode_; } --(void) useBatchNode:(CCSpriteBatchNode*)batchNode -{ - usesBatchNode_ = YES; - textureAtlas_ = [batchNode textureAtlas]; // weak ref - batchNode_ = batchNode; // weak ref -} --(void) useSpriteSheetRender:(CCSpriteSheetInternalOnly*)spriteSheet // XXX DEPRECATED +-(void) setBatchNode:(CCSpriteBatchNode *)batchNode { - [self useBatchNode:spriteSheet]; -} + batchNode_ = batchNode; // weak reference --(void) initAnimationDictionary -{ - animations_ = [[NSMutableDictionary alloc] initWithCapacity:2]; + // self render + if( ! batchNode ) { + atlasIndex_ = CCSpriteIndexNotInitialized; + textureAtlas_ = nil; + dirty_ = recursiveDirty_ = NO; + + float x1 = offsetPosition_.x; + float y1 = offsetPosition_.y; + float x2 = x1 + rect_.size.width; + float y2 = y1 + rect_.size.height; + quad_.bl.vertices = (ccVertex3F) { x1, y1, 0 }; + quad_.br.vertices = (ccVertex3F) { x2, y1, 0 }; + quad_.tl.vertices = (ccVertex3F) { x1, y2, 0 }; + quad_.tr.vertices = (ccVertex3F) { x2, y2, 0 }; + + } else { + + // using batch + transformToBatch_ = CGAffineTransformIdentity; + textureAtlas_ = [batchNode textureAtlas]; // weak ref + } } --(void)setTextureRect:(CGRect)rect +-(void) setTextureRect:(CGRect)rect { - CGRect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect ); - [self setTextureRectInPixels:rectInPixels rotated:NO untrimmedSize:rectInPixels.size]; + [self setTextureRect:rect rotated:NO untrimmedSize:rect.size]; } --(void)setTextureRectInPixels:(CGRect)rect rotated:(BOOL)rotated untrimmedSize:(CGSize)untrimmedSize +-(void) setTextureRect:(CGRect)rect rotated:(BOOL)rotated untrimmedSize:(CGSize)untrimmedSize { - rectInPixels_ = rect; - rect_ = CC_RECT_PIXELS_TO_POINTS( rect ); rectRotated_ = rotated; - [self setContentSizeInPixels:untrimmedSize]; - [self updateTextureCoords:rectInPixels_]; + [self setContentSize:untrimmedSize]; + [self setVertexRect:rect]; + [self setTextureCoords:rect]; + + CGPoint relativeOffset = unflippedOffsetPositionFromCenter_; - CGPoint relativeOffsetInPixels = unflippedOffsetPositionFromCenter_; - // issue #732 if( flipX_ ) - relativeOffsetInPixels.x = -relativeOffsetInPixels.x; + relativeOffset.x = -relativeOffset.x; if( flipY_ ) - relativeOffsetInPixels.y = -relativeOffsetInPixels.y; - - offsetPositionInPixels_.x = relativeOffsetInPixels.x + (contentSizeInPixels_.width - rectInPixels_.size.width) / 2; - offsetPositionInPixels_.y = relativeOffsetInPixels.y + (contentSizeInPixels_.height - rectInPixels_.size.height) / 2; - - - // rendering using SpriteSheet - if( usesBatchNode_ ) { + relativeOffset.y = -relativeOffset.y; + + + offsetPosition_.x = relativeOffset.x + (contentSize_.width - rect_.size.width) / 2; + offsetPosition_.y = relativeOffset.y + (contentSize_.height - rect_.size.height) / 2; + + + // rendering using batch node + if( batchNode_ ) { // update dirty_, don't update recursiveDirty_ dirty_ = YES; } @@ -387,31 +320,40 @@ -(void)setTextureRectInPixels:(CGRect)rect rotated:(BOOL)rotated untrimmedSize:( else { // Atlas: Vertex - float x1 = 0 + offsetPositionInPixels_.x; - float y1 = 0 + offsetPositionInPixels_.y; - float x2 = x1 + rectInPixels_.size.width; - float y2 = y1 + rectInPixels_.size.height; - + float x1 = offsetPosition_.x; + float y1 = offsetPosition_.y; + float x2 = x1 + rect_.size.width; + float y2 = y1 + rect_.size.height; + // Don't update Z. quad_.bl.vertices = (ccVertex3F) { x1, y1, 0 }; quad_.br.vertices = (ccVertex3F) { x2, y1, 0 }; quad_.tl.vertices = (ccVertex3F) { x1, y2, 0 }; - quad_.tr.vertices = (ccVertex3F) { x2, y2, 0 }; - } + quad_.tr.vertices = (ccVertex3F) { x2, y2, 0 }; + } +} + +// override this method to generate "double scale" sprites +-(void) setVertexRect:(CGRect)rect +{ + rect_ = rect; } --(void)updateTextureCoords:(CGRect)rect +-(void) setTextureCoords:(CGRect)rect { - CCTexture2D *tex = (usesBatchNode_)?[textureAtlas_ texture]:texture_; + rect = CC_RECT_POINTS_TO_PIXELS(rect); + + CCTexture2D *tex = (batchNode_) ? [textureAtlas_ texture] : texture_; if(!tex) return; - + float atlasWidth = (float)tex.pixelsWide; float atlasHeight = (float)tex.pixelsHigh; - - float left,right,top,bottom; - - if(rectRotated_){ + + float left, right ,top , bottom; + + if(rectRotated_) + { #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL left = (2*rect.origin.x+1)/(2*atlasWidth); right = left+(rect.size.height*2-2)/(2*atlasWidth); @@ -423,12 +365,12 @@ -(void)updateTextureCoords:(CGRect)rect top = rect.origin.y/atlasHeight; bottom = top+(rect.size.width/atlasHeight); #endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - + if( flipX_) CC_SWAP(top,bottom); if( flipY_) CC_SWAP(left,right); - + quad_.bl.texCoords.u = left; quad_.bl.texCoords.v = top; quad_.br.texCoords.u = left; @@ -449,12 +391,12 @@ -(void)updateTextureCoords:(CGRect)rect top = rect.origin.y/atlasHeight; bottom = top + rect.size.height/atlasHeight; #endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - + if( flipX_) CC_SWAP(left,right); if( flipY_) CC_SWAP(top,bottom); - + quad_.bl.texCoords.u = left; quad_.bl.texCoords.v = bottom; quad_.br.texCoords.u = right; @@ -468,199 +410,177 @@ -(void)updateTextureCoords:(CGRect)rect -(void)updateTransform { - NSAssert( usesBatchNode_, @"updateTransform is only valid when CCSprite is being renderd using an CCSpriteBatchNode"); + NSAssert( batchNode_, @"updateTransform is only valid when CCSprite is being rendered using an CCSpriteBatchNode"); + + // recaculate matrix only if it is dirty + if( self.dirty ) { + + // If it is not visible, or one of its ancestors is not visible, then do nothing: + if( !visible_ || ( parent_ && parent_ != batchNode_ && ((CCSprite*)parent_)->shouldBeHidden_) ) { + quad_.br.vertices = quad_.tl.vertices = quad_.tr.vertices = quad_.bl.vertices = (ccVertex3F){0,0,0}; + shouldBeHidden_ = YES; + } + + else { + + shouldBeHidden_ = NO; + + if( ! parent_ || parent_ == batchNode_ ) + transformToBatch_ = [self nodeToParentTransform]; + + else { + NSAssert( [parent_ isKindOfClass:[CCSprite class]], @"Logic error in CCSprite. Parent must be a CCSprite"); + + transformToBatch_ = CGAffineTransformConcat( [self nodeToParentTransform] , ((CCSprite*)parent_)->transformToBatch_ ); + } + + // + // calculate the Quad based on the Affine Matrix + // + + CGSize size = rect_.size; + + float x1 = offsetPosition_.x; + float y1 = offsetPosition_.y; + + float x2 = x1 + size.width; + float y2 = y1 + size.height; + float x = transformToBatch_.tx; + float y = transformToBatch_.ty; + + float cr = transformToBatch_.a; + float sr = transformToBatch_.b; + float cr2 = transformToBatch_.d; + float sr2 = -transformToBatch_.c; + float ax = x1 * cr - y1 * sr2 + x; + float ay = x1 * sr + y1 * cr2 + y; + + float bx = x2 * cr - y1 * sr2 + x; + float by = x2 * sr + y1 * cr2 + y; + + float cx = x2 * cr - y2 * sr2 + x; + float cy = x2 * sr + y2 * cr2 + y; + + float dx = x1 * cr - y2 * sr2 + x; + float dy = x1 * sr + y2 * cr2 + y; + + quad_.bl.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), vertexZ_ }; + quad_.br.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), vertexZ_ }; + quad_.tl.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), vertexZ_ }; + quad_.tr.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), vertexZ_ }; + } - // optimization. Quick return if not dirty - if( ! dirty_ ) - return; - - CGAffineTransform matrix; - - // Optimization: if it is not visible, then do nothing - if( ! visible_ ) { - quad_.br.vertices = quad_.tl.vertices = quad_.tr.vertices = quad_.bl.vertices = (ccVertex3F){0,0,0}; [textureAtlas_ updateQuad:&quad_ atIndex:atlasIndex_]; dirty_ = recursiveDirty_ = NO; - return ; } - - - // Optimization: If parent is batchnode, or parent is nil - // build Affine transform manually - if( ! parent_ || parent_ == batchNode_ ) { - - float radians = -CC_DEGREES_TO_RADIANS(rotation_); - float c = cosf(radians); - float s = sinf(radians); - - matrix = CGAffineTransformMake( c * scaleX_, s * scaleX_, - -s * scaleY_, c * scaleY_, - positionInPixels_.x, positionInPixels_.y); - matrix = CGAffineTransformTranslate(matrix, -anchorPointInPixels_.x, -anchorPointInPixels_.y); - - - } else { // parent_ != batchNode_ - - // else do affine transformation according to the HonorParentTransform - - matrix = CGAffineTransformIdentity; - ccHonorParentTransform prevHonor = CC_HONOR_PARENT_TRANSFORM_ALL; - - for (CCNode *p = self ; p && p != batchNode_ ; p = p.parent) { - - // Might happen. Issue #1053 - NSAssert( [p isKindOfClass:[CCSprite class]], @"CCSprite should be a CCSprite subclass. Probably you initialized an sprite with a batchnode, but you didn't add it to the batch node." ); - - struct transformValues_ tv; - [(CCSprite*)p getTransformValues: &tv]; - - // If any of the parents are not visible, then don't draw this node - if( ! tv.visible ) { - quad_.br.vertices = quad_.tl.vertices = quad_.tr.vertices = quad_.bl.vertices = (ccVertex3F){0,0,0}; - [textureAtlas_ updateQuad:&quad_ atIndex:atlasIndex_]; - dirty_ = recursiveDirty_ = NO; - return; - } - CGAffineTransform newMatrix = CGAffineTransformIdentity; - - // 2nd: Translate, Rotate, Scale - if( prevHonor & CC_HONOR_PARENT_TRANSFORM_TRANSLATE ) - newMatrix = CGAffineTransformTranslate(newMatrix, tv.pos.x, tv.pos.y); - if( prevHonor & CC_HONOR_PARENT_TRANSFORM_ROTATE ) - newMatrix = CGAffineTransformRotate(newMatrix, -CC_DEGREES_TO_RADIANS(tv.rotation)); - if( prevHonor & CC_HONOR_PARENT_TRANSFORM_SCALE ) { - newMatrix = CGAffineTransformScale(newMatrix, tv.scale.x, tv.scale.y); - } - - // 3rd: Translate anchor point - newMatrix = CGAffineTransformTranslate(newMatrix, -tv.ap.x, -tv.ap.y); - - // 4th: Matrix multiplication - matrix = CGAffineTransformConcat( matrix, newMatrix); - - prevHonor = [(CCSprite*)p honorParentTransform]; - } - } - - - // - // calculate the Quad based on the Affine Matrix - // - - CGSize size = rectInPixels_.size; - - float x1 = offsetPositionInPixels_.x; - float y1 = offsetPositionInPixels_.y; - - float x2 = x1 + size.width; - float y2 = y1 + size.height; - float x = matrix.tx; - float y = matrix.ty; - - float cr = matrix.a; - float sr = matrix.b; - float cr2 = matrix.d; - float sr2 = -matrix.c; - float ax = x1 * cr - y1 * sr2 + x; - float ay = x1 * sr + y1 * cr2 + y; - - float bx = x2 * cr - y1 * sr2 + x; - float by = x2 * sr + y1 * cr2 + y; - - float cx = x2 * cr - y2 * sr2 + x; - float cy = x2 * sr + y2 * cr2 + y; - - float dx = x1 * cr - y2 * sr2 + x; - float dy = x1 * sr + y2 * cr2 + y; - - quad_.bl.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), vertexZ_ }; - quad_.br.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), vertexZ_ }; - quad_.tl.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), vertexZ_ }; - quad_.tr.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), vertexZ_ }; - - [textureAtlas_ updateQuad:&quad_ atIndex:atlasIndex_]; - dirty_ = recursiveDirty_ = NO; -} - -// XXX: Optimization: instead of calling 5 times the parent sprite to obtain: position, scale.x, scale.y, anchorpoint and rotation, -// this fuction return the 5 values in 1 single call --(void) getTransformValues:(struct transformValues_*) tv -{ - tv->pos = positionInPixels_; - tv->scale.x = scaleX_; - tv->scale.y = scaleY_; - tv->rotation = rotation_; - tv->ap = anchorPointInPixels_; - tv->visible = visible_; + + // recursively iterate over children + if( hasChildren_ ) + [children_ makeObjectsPerformSelector:@selector(updateTransform)]; + +#if CC_SPRITE_DEBUG_DRAW + // draw bounding box + CGPoint vertices[4] = { + ccp( quad_.bl.vertices.x, quad_.bl.vertices.y ), + ccp( quad_.br.vertices.x, quad_.br.vertices.y ), + ccp( quad_.tr.vertices.x, quad_.tr.vertices.y ), + ccp( quad_.tl.vertices.x, quad_.tl.vertices.y ), + }; + ccDrawPoly(vertices, 4, YES); +#endif // CC_SPRITE_DEBUG_DRAW + } #pragma mark CCSprite - draw -(void) draw { - NSAssert(!usesBatchNode_, @"If CCSprite is being rendered by CCSpriteBatchNode, CCSprite#draw SHOULD NOT be called"); + CC_PROFILER_START_CATEGORY(kCCProfilerCategorySprite, @"CCSprite - draw"); + + NSAssert(!batchNode_, @"If CCSprite is being rendered by CCSpriteBatchNode, CCSprite#draw SHOULD NOT be called"); + + CC_NODE_DRAW_SETUP(); + + ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: - + ccGLBindTexture2D( [texture_ name] ); - BOOL newBlend = blendFunc_.src != CC_BLEND_SRC || blendFunc_.dst != CC_BLEND_DST; - if( newBlend ) - glBlendFunc( blendFunc_.src, blendFunc_.dst ); + // + // Attributes + // + + ccGLEnableVertexAttribs( kCCVertexAttribFlag_PosColorTex ); #define kQuadSize sizeof(quad_.bl) - glBindTexture(GL_TEXTURE_2D, [texture_ name]); - long offset = (long)&quad_; - + // vertex NSInteger diff = offsetof( ccV3F_C4B_T2F, vertices); - glVertexPointer(3, GL_FLOAT, kQuadSize, (void*) (offset + diff) ); - + glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff)); + + // texCoods + diff = offsetof( ccV3F_C4B_T2F, texCoords); + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff)); + // color diff = offsetof( ccV3F_C4B_T2F, colors); - glColorPointer(4, GL_UNSIGNED_BYTE, kQuadSize, (void*)(offset + diff)); - - // tex coords - diff = offsetof( ccV3F_C4B_T2F, texCoords); - glTexCoordPointer(2, GL_FLOAT, kQuadSize, (void*)(offset + diff)); - + glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff)); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - - if( newBlend ) - glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); - -#if CC_SPRITE_DEBUG_DRAW - CGSize s = [self contentSize]; + + CHECK_GL_ERROR_DEBUG(); + + +#if CC_SPRITE_DEBUG_DRAW == 1 + // draw bounding box CGPoint vertices[4]={ - ccp(0,0),ccp(s.width,0), - ccp(s.width,s.height),ccp(0,s.height), + ccp(quad_.tl.vertices.x,quad_.tl.vertices.y), + ccp(quad_.bl.vertices.x,quad_.bl.vertices.y), + ccp(quad_.br.vertices.x,quad_.br.vertices.y), + ccp(quad_.tr.vertices.x,quad_.tr.vertices.y), + }; + ccDrawPoly(vertices, 4, YES); +#elif CC_SPRITE_DEBUG_DRAW == 2 + // draw texture box + CGSize s = self.textureRect.size; + CGPoint offsetPix = self.offsetPosition; + CGPoint vertices[4] = { + ccp(offsetPix.x,offsetPix.y), ccp(offsetPix.x+s.width,offsetPix.y), + ccp(offsetPix.x+s.width,offsetPix.y+s.height), ccp(offsetPix.x,offsetPix.y+s.height) }; ccDrawPoly(vertices, 4, YES); -#endif // CC_TEXTURENODE_DEBUG_DRAW - +#endif // CC_SPRITE_DEBUG_DRAW + + CC_INCREMENT_GL_DRAWS(1); + + CC_PROFILER_STOP_CATEGORY(kCCProfilerCategorySprite, @"CCSprite - draw"); } #pragma mark CCSprite - CCNode overrides --(void) addChild:(CCSprite*)child z:(int)z tag:(int) aTag +-(void) addChild:(CCSprite*)child z:(NSInteger)z tag:(NSInteger) aTag { NSAssert( child != nil, @"Argument must be non-nil"); - - [super addChild:child z:z tag:aTag]; - - if( usesBatchNode_ ) { + + if( batchNode_ ) { NSAssert( [child isKindOfClass:[CCSprite class]], @"CCSprite only supports CCSprites as children when using CCSpriteBatchNode"); NSAssert( child.texture.name == textureAtlas_.texture.name, @"CCSprite is not using the same texture id"); - - NSUInteger index = [batchNode_ atlasIndexForChild:child atZ:z]; - [batchNode_ insertChild:child inAtlasAtIndex:index]; + + //put it in descendants array of batch node + [batchNode_ appendChild:child]; + + if (!isReorderChildDirty_) + [self setReorderChildDirtyRecursively]; } - + + //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check + [super addChild:child z:z tag:aTag]; + hasChildren_ = YES; } --(void) reorderChild:(CCSprite*)child z:(int)z +-(void) reorderChild:(CCSprite*)child z:(NSInteger)z { NSAssert( child != nil, @"Child must be non-nil"); NSAssert( [children_ containsObject:child], @"Child doesn't belong to Sprite" ); @@ -668,47 +588,89 @@ -(void) reorderChild:(CCSprite*)child z:(int)z if( z == child.zOrder ) return; - if( usesBatchNode_ ) { - // XXX: Instead of removing/adding, it is more efficient to reorder manually - [child retain]; - [self removeChild:child cleanup:NO]; - [self addChild:child z:z]; - [child release]; + if( batchNode_ && ! isReorderChildDirty_) + { + [self setReorderChildDirtyRecursively]; + [batchNode_ reorderBatch:YES]; } - else - [super reorderChild:child z:z]; + [super reorderChild:child z:z]; } -(void)removeChild: (CCSprite *)sprite cleanup:(BOOL)doCleanup { - if( usesBatchNode_ ) + if( batchNode_ ) [batchNode_ removeSpriteFromAtlas:sprite]; [super removeChild:sprite cleanup:doCleanup]; - + hasChildren_ = ( [children_ count] > 0 ); } -(void)removeAllChildrenWithCleanup:(BOOL)doCleanup { - if( usesBatchNode_ ) { + if( batchNode_ ) { CCSprite *child; CCARRAY_FOREACH(children_, child) [batchNode_ removeSpriteFromAtlas:child]; } - + [super removeAllChildrenWithCleanup:doCleanup]; - + hasChildren_ = NO; } +- (void) sortAllChildren +{ + if (isReorderChildDirty_) + { + NSInteger i,j,length = children_->data->num; + CCNode** x = children_->data->arr; + CCNode *tempItem; + + // insertion sort + for(i=1; i=0 && ( tempItem.zOrder < x[j].zOrder || ( tempItem.zOrder == x[j].zOrder && tempItem.orderOfArrival < x[j].orderOfArrival ) ) ) + { + x[j+1] = x[j]; + j = j-1; + } + x[j+1] = tempItem; + } + + if ( batchNode_) + [children_ makeObjectsPerformSelector:@selector(sortAllChildren)]; + + isReorderChildDirty_=NO; + } +} + // // CCNode property overloads // used only when parent is CCSpriteBatchNode // #pragma mark CCSprite - property overloads +-(void) setReorderChildDirtyRecursively +{ + //only set parents flag the first time + + if ( ! isReorderChildDirty_ ) + { + isReorderChildDirty_ = YES; + CCNode* node = (CCNode*) parent_; + while (node && node != batchNode_) + { + [(CCSprite*)node setReorderChildDirtyRecursively]; + node=node.parent; + } + } +} -(void) setDirtyRecursively:(BOOL)b { @@ -723,7 +685,7 @@ -(void) setDirtyRecursively:(BOOL)b // XXX HACK: optimization #define SET_DIRTY_RECURSIVELY() { \ - if( usesBatchNode_ && ! recursiveDirty_ ) { \ + if( batchNode_ && ! recursiveDirty_ ) { \ dirty_ = recursiveDirty_ = YES; \ if( hasChildren_) \ [self setDirtyRecursively:YES]; \ @@ -736,15 +698,21 @@ -(void)setPosition:(CGPoint)pos SET_DIRTY_RECURSIVELY(); } --(void)setPositionInPixels:(CGPoint)pos +-(void)setRotation:(float)rot { - [super setPositionInPixels:pos]; + [super setRotation:rot]; SET_DIRTY_RECURSIVELY(); } --(void)setRotation:(float)rot +-(void)setSkewX:(float)sx { - [super setRotation:rot]; + [super setSkewX:sx]; + SET_DIRTY_RECURSIVELY(); +} + +-(void)setSkewY:(float)sy +{ + [super setSkewY:sy]; SET_DIRTY_RECURSIVELY(); } @@ -780,7 +748,7 @@ -(void)setAnchorPoint:(CGPoint)anchor -(void)setIsRelativeAnchorPoint:(BOOL)relative { - NSAssert( ! usesBatchNode_, @"relativeTransformAnchor is invalid in CCSprite"); + NSAssert( ! batchNode_, @"relativeTransformAnchor is invalid in CCSprite"); [super setIsRelativeAnchorPoint:relative]; } @@ -794,7 +762,7 @@ -(void)setFlipX:(BOOL)b { if( flipX_ != b ) { flipX_ = b; - [self setTextureRectInPixels:rectInPixels_ rotated:rectRotated_ untrimmedSize:rectInPixels_.size]; + [self setTextureRect:rect_ rotated:rectRotated_ untrimmedSize:contentSize_]; } } -(BOOL) flipX @@ -805,9 +773,9 @@ -(BOOL) flipX -(void) setFlipY:(BOOL)b { if( flipY_ != b ) { - flipY_ = b; - [self setTextureRectInPixels:rectInPixels_ rotated:rectRotated_ untrimmedSize:rectInPixels_.size]; - } + flipY_ = b; + [self setTextureRect:rect_ rotated:rectRotated_ untrimmedSize:contentSize_]; + } } -(BOOL) flipY { @@ -820,15 +788,15 @@ -(BOOL) flipY #pragma mark CCSprite - RGBA protocol -(void) updateColor { - ccColor4B color4 = {color_.r, color_.g, color_.b, opacity_ }; - + ccColor4B color4 = {color_.r, color_.g, color_.b, opacity_}; + quad_.bl.colors = color4; quad_.br.colors = color4; quad_.tl.colors = color4; quad_.tr.colors = color4; - - // renders using Sprite Manager - if( usesBatchNode_ ) { + + // renders using batch node + if( batchNode_ ) { if( atlasIndex_ != CCSpriteIndexNotInitialized) [textureAtlas_ updateQuad:&quad_ atIndex:atlasIndex_]; else @@ -852,7 +820,7 @@ -(void) setOpacity:(GLubyte) anOpacity // special opacity for premultiplied textures if( opacityModifyRGB_ ) [self setColor: colorUnmodified_]; - + [self updateColor]; } @@ -860,20 +828,20 @@ - (ccColor3B) color { if(opacityModifyRGB_) return colorUnmodified_; - + return color_; } -(void) setColor:(ccColor3B)color3 { color_ = colorUnmodified_ = color3; - + if( opacityModifyRGB_ ){ - color_.r = color3.r * opacity_/255; - color_.g = color3.g * opacity_/255; - color_.b = color3.b * opacity_/255; + color_.r = color3.r * opacity_/255.0f; + color_.g = color3.g * opacity_/255.0f; + color_.b = color3.b * opacity_/255.0f; } - + [self updateColor]; } @@ -896,82 +864,59 @@ -(BOOL) doesOpacityModifyRGB -(void) setDisplayFrame:(CCSpriteFrame*)frame { - unflippedOffsetPositionFromCenter_ = frame.offsetInPixels; + unflippedOffsetPositionFromCenter_ = frame.offset; CCTexture2D *newTexture = [frame texture]; // update texture before updating texture rect if ( newTexture.name != texture_.name ) [self setTexture: newTexture]; - + // update rect rectRotated_ = frame.rotated; - [self setTextureRectInPixels:frame.rectInPixels rotated:frame.rotated untrimmedSize:frame.originalSizeInPixels]; -} -// XXX deprecated --(void) setDisplayFrame: (NSString*) animationName index:(int) frameIndex -{ - if( ! animations_ ) - [self initAnimationDictionary]; - - CCAnimation *a = [animations_ objectForKey: animationName]; - CCSpriteFrame *frame = [[a frames] objectAtIndex:frameIndex]; - - NSAssert( frame, @"CCSprite#setDisplayFrame. Invalid frame"); - - [self setDisplayFrame:frame]; + [self setTextureRect:frame.rect rotated:rectRotated_ untrimmedSize:frame.originalSize]; } -(void) setDisplayFrameWithAnimationName: (NSString*) animationName index:(int) frameIndex { NSAssert( animationName, @"CCSprite#setDisplayFrameWithAnimationName. animationName must not be nil"); - + CCAnimation *a = [[CCAnimationCache sharedAnimationCache] animationByName:animationName]; - + NSAssert( a, @"CCSprite#setDisplayFrameWithAnimationName: Frame not found"); - - CCSpriteFrame *frame = [[a frames] objectAtIndex:frameIndex]; - + + CCAnimationFrame *frame = [[a frames] objectAtIndex:frameIndex]; + NSAssert( frame, @"CCSprite#setDisplayFrame. Invalid frame"); - - [self setDisplayFrame:frame]; + + [self setDisplayFrame:frame.spriteFrame]; } --(BOOL) isFrameDisplayed:(CCSpriteFrame*)frame +-(BOOL) isFrameDisplayed:(CCSpriteFrame*)frame { CGRect r = [frame rect]; return ( CGRectEqualToRect(r, rect_) && - frame.texture.name == self.texture.name ); -} - --(CCSpriteFrame*) displayedFrame -{ - return [CCSpriteFrame frameWithTexture:self.texture rect:rect_]; -} - --(void) addAnimation: (CCAnimation*) anim -{ - // lazy alloc - if( ! animations_ ) - [self initAnimationDictionary]; - - [animations_ setObject:anim forKey:[anim name]]; + frame.texture.name == self.texture.name && + CGPointEqualToPoint( frame.offset, unflippedOffsetPositionFromCenter_ ) ); } --(CCAnimation*)animationByName: (NSString*) animationName +-(CCSpriteFrame*) displayFrame { - NSAssert( animationName != nil, @"animationName parameter must be non nil"); - return [animations_ objectForKey:animationName]; + return [CCSpriteFrame frameWithTexture:texture_ + rectInPixels:CC_RECT_POINTS_TO_PIXELS(rect_) + rotated:rectRotated_ + offset:unflippedOffsetPositionFromCenter_ + originalSize:CC_SIZE_POINTS_TO_PIXELS(contentSize_)]; } #pragma mark CCSprite - CocosNodeTexture protocol -(void) updateBlendFunc { - NSAssert( ! usesBatchNode_, @"CCSprite: updateBlendFunc doesn't work when the sprite is rendered using a CCSpriteBatchNode"); + NSAssert( ! batchNode_, @"CCSprite: updateBlendFunc doesn't work when the sprite is rendered using a CCSpriteBatchNode"); - // it's possible to have an untextured sprite + // it is possible to have an untextured sprite if( !texture_ || ! [texture_ hasPremultipliedAlpha] ) { blendFunc_.src = GL_SRC_ALPHA; blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; @@ -985,15 +930,17 @@ -(void) updateBlendFunc -(void) setTexture:(CCTexture2D*)texture { - NSAssert( ! usesBatchNode_, @"CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteBatchNode"); - + NSAssert( ! batchNode_, @"CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteBatchNode"); + // accept texture==nil as argument NSAssert( !texture || [texture isKindOfClass:[CCTexture2D class]], @"setTexture expects a CCTexture2D. Invalid argument"); - [texture_ release]; - texture_ = [texture retain]; - - [self updateBlendFunc]; + if( texture_ != texture ) { + [texture_ release]; + texture_ = [texture retain]; + + [self updateBlendFunc]; + } } -(CCTexture2D*) texture diff --git a/Example/libs/cocos2d/CCSpriteBatchNode.h b/Example/libs/cocos2d/CCSpriteBatchNode.h index 61111c2..ca13ef0 100644 --- a/Example/libs/cocos2d/CCSpriteBatchNode.h +++ b/Example/libs/cocos2d/CCSpriteBatchNode.h @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2009-2010 Ricardo Quesada * Copyright (C) 2009 Matt Oswald - * + * + * Copyright (c) 2009-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -46,7 +48,7 @@ * Limitations: * - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is CCSprite or any subclass of CCSprite. eg: particles, labels and layer can't be added to a CCSpriteBatchNode. * - Either all its children are Aliased or Antialiased. It can't be a mix. This is because "alias" is a property of the texture, and all the sprites share the same texture. - * + * * @since v0.7.1 */ @interface CCSpriteBatchNode : CCNode @@ -71,27 +73,23 @@ The capacity will be increased in 33% in runtime if it run out of space. */ +(id)batchNodeWithTexture:(CCTexture2D *)tex; -+(id)spriteSheetWithTexture:(CCTexture2D *)tex DEPRECATED_ATTRIBUTE; /** creates a CCSpriteBatchNode with a texture2d and capacity of children. The capacity will be increased in 33% in runtime if it run out of space. */ +(id)batchNodeWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity; -+(id)spriteSheetWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity DEPRECATED_ATTRIBUTE; /** creates a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) with a default capacity of 29 children. The capacity will be increased in 33% in runtime if it run out of space. The file will be loaded using the TextureMgr. */ +(id)batchNodeWithFile:(NSString*) fileImage; -+(id)spriteSheetWithFile:(NSString*) fileImage DEPRECATED_ATTRIBUTE; /** creates a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and capacity of children. The capacity will be increased in 33% in runtime if it run out of space. The file will be loaded using the TextureMgr. */ +(id)batchNodeWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity; -+(id)spriteSheetWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity DEPRECATED_ATTRIBUTE; /** initializes a CCSpriteBatchNode with a texture2d and capacity of children. The capacity will be increased in 33% in runtime if it run out of space. @@ -105,25 +103,6 @@ -(void) increaseAtlasCapacity; -/** creates an sprite with a rect in the CCSpriteBatchNode. - It's the same as: - - create an standard CCSsprite - - set the usingSpriteSheet = YES - - set the textureAtlas to the same texture Atlas as the CCSpriteBatchNode - @deprecated Use [CCSprite spriteWithBatchNode:rect:] instead; - */ --(CCSprite*) createSpriteWithRect:(CGRect)rect DEPRECATED_ATTRIBUTE; - -/** initializes a previously created sprite with a rect. This sprite will have the same texture as the CCSpriteBatchNode. - It's the same as: - - initialize an standard CCSsprite - - set the usingBatchNode = YES - - set the textureAtlas to the same texture Atlas as the CCSpriteBatchNode - @since v0.99.0 - @deprecated Use [CCSprite initWithBatchNode:rect:] instead; -*/ --(void) initSprite:(CCSprite*)sprite rect:(CGRect)rect DEPRECATED_ATTRIBUTE; - /** removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter. @warning Removing a child from a CCSpriteBatchNode is very slow */ @@ -135,9 +114,25 @@ -(void)removeChild: (CCSprite *)sprite cleanup:(BOOL)doCleanup; -(void) insertChild:(CCSprite*)child inAtlasAtIndex:(NSUInteger)index; +-(void) appendChild:(CCSprite*)sprite; -(void) removeSpriteFromAtlas:(CCSprite*)sprite; -(NSUInteger) rebuildIndexInOrder:(CCSprite*)parent atlasIndex:(NSUInteger)index; --(NSUInteger) atlasIndexForChild:(CCSprite*)sprite atZ:(int)z; +-(NSUInteger) atlasIndexForChild:(CCSprite*)sprite atZ:(NSInteger)z; +/* Sprites use this to start sortChildren, don't call this manually */ +- (void) reorderBatch:(BOOL) reorder; + +@end +@interface CCSpriteBatchNode (QuadExtensions) +/** Adds a quad into the texture atlas but it won't be added into the children array. + This method should be called only when you are dealing with very big AtlasSrite and when most of the CCSprite won't be updated. + For example: a tile map (CCTMXMap) or a label with lots of characgers (CCLabelBMFont) + */ +-(id) addSpriteWithoutQuad:(CCSprite*)child z:(NSUInteger)z tag:(NSInteger)aTag; + +/* This is the opposite of "addQuadFromSprite". + It adds the sprite to the children and descendants array, but it doesn't add it to the texture atlas. + */ +-(void) addQuadFromSprite:(CCSprite*)sprite quadIndex:(NSUInteger)index; @end diff --git a/Example/libs/cocos2d/CCSpriteBatchNode.m b/Example/libs/cocos2d/CCSpriteBatchNode.m index 28fb082..fe17956 100644 --- a/Example/libs/cocos2d/CCSpriteBatchNode.m +++ b/Example/libs/cocos2d/CCSpriteBatchNode.m @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2009-2010 Ricardo Quesada * Copyright (C) 2009 Matt Oswald - * + * + * Copyright (c) 2009-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,16 +33,25 @@ #import "CCGrid.h" #import "CCDrawingPrimitives.h" #import "CCTextureCache.h" +#import "CCShaderCache.h" +#import "CCGLProgram.h" +#import "ccGLStateCache.h" +#import "CCDirector.h" #import "Support/CGPointExtension.h" +#import "Support/TransformUtils.h" +#import "Support/CCProfiling.h" + +// external +#import "kazmath/GL/matrix.h" const NSUInteger defaultCapacity = 29; #pragma mark - #pragma mark CCSpriteBatchNode -static SEL selUpdate = NULL; - @interface CCSpriteBatchNode (private) +-(void) updateAtlasIndex:(CCSprite*) sprite currentIndex:(NSInteger*) curIndex; +-(void) swap:(NSInteger) oldIndex withNewIndex:(NSInteger) newIndex; -(void) updateBlendFunc; @end @@ -51,12 +62,6 @@ @implementation CCSpriteBatchNode @synthesize descendants = descendants_; -+(void) initialize -{ - if ( self == [CCSpriteBatchNode class] ) { - selUpdate = @selector(updateTransform); - } -} /* * creation with CCTexture2D */ @@ -64,19 +69,11 @@ +(id)batchNodeWithTexture:(CCTexture2D *)tex { return [[[self alloc] initWithTexture:tex capacity:defaultCapacity] autorelease]; } -+(id)spriteSheetWithTexture:(CCTexture2D *)tex // XXX DEPRECATED -{ - return [self batchNodeWithTexture:tex]; -} +(id)batchNodeWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity { return [[[self alloc] initWithTexture:tex capacity:capacity] autorelease]; } -+(id)spriteSheetWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity // XXX DEPRECATED -{ - return [self batchNodeWithTexture:tex capacity:capacity]; -} /* * creation with File Image @@ -85,20 +82,11 @@ +(id)batchNodeWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity { return [[[self alloc] initWithFile:fileImage capacity:capacity] autorelease]; } -+(id)spriteSheetWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity // XXX DEPRECATED -{ - return [self batchNodeWithFile:fileImage capacity:capacity]; -} +(id)batchNodeWithFile:(NSString*) imageFile { return [[[self alloc] initWithFile:imageFile capacity:defaultCapacity] autorelease]; } -+(id)spriteSheetWithFile:(NSString*) imageFile // XXX DEPRECATED -{ - return [self batchNodeWithFile:imageFile]; -} - /* * init with CCTexture2D @@ -106,18 +94,20 @@ +(id)spriteSheetWithFile:(NSString*) imageFile // XXX DEPRECATED -(id)initWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity { if( (self=[super init])) { - + blendFunc_.src = CC_BLEND_SRC; blendFunc_.dst = CC_BLEND_DST; textureAtlas_ = [[CCTextureAtlas alloc] initWithTexture:tex capacity:capacity]; - + [self updateBlendFunc]; - + // no lazy alloc in this node children_ = [[CCArray alloc] initWithCapacity:capacity]; descendants_ = [[CCArray alloc] initWithCapacity:capacity]; + + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; } - + return self; } @@ -136,90 +126,77 @@ - (NSString*) description } -(void)dealloc -{ +{ [textureAtlas_ release]; [descendants_ release]; - + [super dealloc]; } #pragma mark CCSpriteBatchNode - composition // override visit. -// Don't call visit on it's children +// Don't call visit on its children -(void) visit { - + CC_PROFILER_START_CATEGORY(kCCProfilerCategoryBatchSprite, @"CCSpriteBatchNode - visit"); + + NSAssert(parent_ != nil, @"CCSpriteBatchNode should NOT be root node"); + // CAREFUL: - // This visit is almost identical to CocosNode#visit - // with the exception that it doesn't call visit on it's children + // This visit is almost identical to CCNode#visit + // with the exception that it doesn't call visit on its children // // The alternative is to have a void CCSprite#visit, but // although this is less mantainable, is faster // if (!visible_) return; - - glPushMatrix(); - + + kmGLPushMatrix(); + if ( grid_ && grid_.active) { [grid_ beforeDraw]; [self transformAncestors]; } - + + [self sortAllChildren]; [self transform]; - [self draw]; - + if ( grid_ && grid_.active) [grid_ afterDraw:self]; - - glPopMatrix(); -} -// XXX deprecated --(CCSprite*) createSpriteWithRect:(CGRect)rect -{ - CCSprite *sprite = [CCSprite spriteWithTexture:textureAtlas_.texture rect:rect]; - [sprite useBatchNode:self]; - - return sprite; -} + kmGLPopMatrix(); -// XXX deprecated --(void) initSprite:(CCSprite*)sprite rect:(CGRect)rect -{ - [sprite initWithTexture:textureAtlas_.texture rect:rect]; - [sprite useBatchNode:self]; + orderOfArrival_ = 0; + + CC_PROFILER_STOP_CATEGORY(kCCProfilerCategoryBatchSprite, @"CCSpriteBatchNode - visit"); } // override addChild: --(void) addChild:(CCSprite*)child z:(int)z tag:(int) aTag +-(void) addChild:(CCSprite*)child z:(NSInteger)z tag:(NSInteger) aTag { NSAssert( child != nil, @"Argument must be non-nil"); NSAssert( [child isKindOfClass:[CCSprite class]], @"CCSpriteBatchNode only supports CCSprites as children"); NSAssert( child.texture.name == textureAtlas_.texture.name, @"CCSprite is not using the same texture id"); - + [super addChild:child z:z tag:aTag]; - - NSUInteger index = [self atlasIndexForChild:child atZ:z]; - [self insertChild:child inAtlasAtIndex:index]; + + [self appendChild:child]; } // override reorderChild --(void) reorderChild:(CCSprite*)child z:(int)z +-(void) reorderChild:(CCSprite*)child z:(NSInteger)z { NSAssert( child != nil, @"Child must be non-nil"); NSAssert( [children_ containsObject:child], @"Child doesn't belong to Sprite" ); - + if( z == child.zOrder ) return; - - // XXX: Instead of removing/adding, it is more efficient to reorder manually - [child retain]; - [self removeChild:child cleanup:NO]; - [self addChild:child z:z]; - [child release]; + + //set the z-order and sort later + [super reorderChild:child z:z]; } // override removeChild: @@ -228,12 +205,12 @@ -(void)removeChild: (CCSprite *)sprite cleanup:(BOOL)doCleanup // explicit nil handling if (sprite == nil) return; - + NSAssert([children_ containsObject:sprite], @"CCSpriteBatchNode doesn't contain the sprite. Can't remove it"); - + // cleanup before removing [self removeSpriteFromAtlas:sprite]; - + [super removeChild:sprite cleanup:doCleanup]; } @@ -245,80 +222,181 @@ -(void)removeChildAtIndex:(NSUInteger)index cleanup:(BOOL)doCleanup -(void)removeAllChildrenWithCleanup:(BOOL)doCleanup { // Invalidate atlas index. issue #569 - [children_ makeObjectsPerformSelector:@selector(useSelfRender)]; - + // useSelfRender should be performed on all descendants. issue #1216 + [descendants_ makeObjectsPerformSelector:@selector(setBatchNode:) withObject:nil]; + [super removeAllChildrenWithCleanup:doCleanup]; - + [descendants_ removeAllObjects]; [textureAtlas_ removeAllQuads]; } +//override sortAllChildren +- (void) sortAllChildren +{ + if (isReorderChildDirty_) + { + NSInteger i,j,length = children_->data->num; + CCNode ** x = children_->data->arr; + CCNode *tempItem; + CCSprite *child; + + //insertion sort + for(i=1; i=0 && ( tempItem.zOrder < x[j].zOrder || ( tempItem.zOrder == x[j].zOrder && tempItem.orderOfArrival < x[j].orderOfArrival ) ) ) + { + x[j+1] = x[j]; + j--; + } + + x[j+1] = tempItem; + } + + //sorted now check all children + if ([children_ count] > 0) + { + //first sort all children recursively based on zOrder + [children_ makeObjectsPerformSelector:@selector(sortAllChildren)]; + + NSInteger index=0; + + //fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact) + // and at the same time reorder descedants and the quads to the right index + CCARRAY_FOREACH(children_, child) + [self updateAtlasIndex:child currentIndex:&index]; + } + + isReorderChildDirty_=NO; + } +} + +-(void) updateAtlasIndex:(CCSprite*) sprite currentIndex:(NSInteger*) curIndex +{ + CCArray *array = [sprite children]; + NSUInteger count = [array count]; + NSInteger oldIndex; + + if( count == 0 ) + { + oldIndex = sprite.atlasIndex; + sprite.atlasIndex = *curIndex; + sprite.orderOfArrival = 0; + if (oldIndex != *curIndex) + [self swap:oldIndex withNewIndex:*curIndex]; + (*curIndex)++; + } + else + { + BOOL needNewIndex=YES; + + if (((CCSprite*) (array->data->arr[0])).zOrder >= 0) + { + //all children are in front of the parent + oldIndex = sprite.atlasIndex; + sprite.atlasIndex = *curIndex; + sprite.orderOfArrival = 0; + if (oldIndex != *curIndex) + [self swap:oldIndex withNewIndex:*curIndex]; + (*curIndex)++; + + needNewIndex = NO; + } + + CCSprite* child; + CCARRAY_FOREACH(array,child) + { + if (needNewIndex && child.zOrder >= 0) + { + oldIndex = sprite.atlasIndex; + sprite.atlasIndex = *curIndex; + sprite.orderOfArrival = 0; + if (oldIndex != *curIndex) + [self swap:oldIndex withNewIndex:*curIndex]; + (*curIndex)++; + needNewIndex = NO; + + } + + [self updateAtlasIndex:child currentIndex:curIndex]; + } + + if (needNewIndex) + {//all children have a zOrder < 0) + oldIndex=sprite.atlasIndex; + sprite.atlasIndex=*curIndex; + sprite.orderOfArrival=0; + if (oldIndex!=*curIndex) + [self swap:oldIndex withNewIndex:*curIndex]; + (*curIndex)++; + } + } +} + +- (void) swap:(NSInteger) oldIndex withNewIndex:(NSInteger) newIndex +{ + id* x = descendants_->data->arr; + ccV3F_C4B_T2F_Quad* quads = textureAtlas_.quads; + + id tempItem = x[oldIndex]; + ccV3F_C4B_T2F_Quad tempItemQuad=quads[oldIndex]; + + //update the index of other swapped item + ((CCSprite*) x[newIndex]).atlasIndex=oldIndex; + + x[oldIndex]=x[newIndex]; + quads[oldIndex]=quads[newIndex]; + x[newIndex]=tempItem; + quads[newIndex]=tempItemQuad; +} + +- (void) reorderBatch:(BOOL) reorder +{ + isReorderChildDirty_=reorder; +} + #pragma mark CCSpriteBatchNode - draw -(void) draw { - // Optimization: Fast Dispatch + CC_PROFILER_START(@"CCSpriteBatchNode - draw"); + + // Optimization: Fast Dispatch if( textureAtlas_.totalQuads == 0 ) - return; - - CCSprite *child; - ccArray *array = descendants_->data; - - NSUInteger i = array->num; - id *arr = array->arr; - - if( i > 0 ) { - - while (i-- > 0) { - child = *arr++; - - // fast dispatch - child->updateMethod(child, selUpdate); - -#if CC_SPRITEBATCHNODE_DEBUG_DRAW - //Issue #528 - CGRect rect = [child boundingBox]; - CGPoint vertices[4]={ - ccp(rect.origin.x,rect.origin.y), - ccp(rect.origin.x+rect.size.width,rect.origin.y), - ccp(rect.origin.x+rect.size.width,rect.origin.y+rect.size.height), - ccp(rect.origin.x,rect.origin.y+rect.size.height), - }; - ccDrawPoly(vertices, 4, YES); -#endif // CC_SPRITEBATCHNODE_DEBUG_DRAW - } - } - - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: - - - BOOL newBlend = blendFunc_.src != CC_BLEND_SRC || blendFunc_.dst != CC_BLEND_DST; - if( newBlend ) - glBlendFunc( blendFunc_.src, blendFunc_.dst ); - + return; + + CC_NODE_DRAW_SETUP(); + + [children_ makeObjectsPerformSelector:@selector(updateTransform)]; + + ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); + [textureAtlas_ drawQuads]; - if( newBlend ) - glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); + + CC_PROFILER_STOP(@"CCSpriteBatchNode - draw"); } #pragma mark CCSpriteBatchNode - private -(void) increaseAtlasCapacity { - // if we're going beyond the current TextureAtlas's capacity, + // if we're going beyond the current CCTextureAtlas's capacity, // all the previously initialized sprites will need to redo their texture coords // this is likely computationally expensive NSUInteger quantity = (textureAtlas_.capacity + 1) * 4 / 3; - - CCLOG(@"cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from [%u] to [%u].", - (unsigned int)textureAtlas_.capacity, - (unsigned int)quantity); - - + + CCLOG(@"cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", + (long)textureAtlas_.capacity, + (long)quantity); + + if( ! [textureAtlas_ resizeCapacity:quantity] ) { // serious problems CCLOG(@"cocos2d: WARNING: Not enough memory to resize the atlas"); - NSAssert(NO,@"XXX: SpriteSheet#increaseAtlasCapacity SHALL handle this assert"); - } + NSAssert(NO,@"XXX: CCSpriteBatchNode#increaseAtlasCapacity SHALL handle this assert"); + } } @@ -331,18 +409,18 @@ -(NSUInteger) rebuildIndexInOrder:(CCSprite*)node atlasIndex:(NSUInteger)index if( sprite.zOrder < 0 ) index = [self rebuildIndexInOrder:sprite atlasIndex:index]; } - + // ignore self (batch node) if( ! [node isEqual:self]) { node.atlasIndex = index; index++; } - + CCARRAY_FOREACH(node.children, sprite){ if( sprite.zOrder >= 0 ) index = [self rebuildIndexInOrder:sprite atlasIndex:index]; } - + return index; } @@ -367,17 +445,17 @@ -(NSUInteger) lowestAtlasIndexInChild:(CCSprite*)sprite } --(NSUInteger)atlasIndexForChild:(CCSprite*)sprite atZ:(int)z +-(NSUInteger)atlasIndexForChild:(CCSprite*)sprite atZ:(NSInteger)z { CCArray *brothers = [[sprite parent] children]; NSUInteger childIndex = [brothers indexOfObject:sprite]; - + // ignore parent Z if parent is batchnode BOOL ignoreParent = ( sprite.parent == self ); CCSprite *previous = nil; if( childIndex > 0 ) previous = [brothers objectAtIndex:childIndex-1]; - + // first child of the sprite sheet if( ignoreParent ) { if( childIndex == 0 ) @@ -385,30 +463,30 @@ -(NSUInteger)atlasIndexForChild:(CCSprite*)sprite atZ:(int)z // else return [self highestAtlasIndexInChild: previous] + 1; } - + // parent is a CCSprite, so, it must be taken into account - + // first child of an CCSprite ? if( childIndex == 0 ) { CCSprite *p = (CCSprite*) sprite.parent; - + // less than parent and brothers if( z < 0 ) return p.atlasIndex; else return p.atlasIndex+1; - + } else { // previous & sprite belong to the same branch if( ( previous.zOrder < 0 && z < 0 )|| (previous.zOrder >= 0 && z >= 0) ) return [self highestAtlasIndexInChild:previous] + 1; - + // else (previous < 0 and sprite >= 0 ) CCSprite *p = (CCSprite*) sprite.parent; return p.atlasIndex + 1; } - + NSAssert( NO, @"Should not happen. Error calculating Z on Batch Node"); return 0; } @@ -417,20 +495,20 @@ -(NSUInteger)atlasIndexForChild:(CCSprite*)sprite atZ:(int)z // add child helper -(void) insertChild:(CCSprite*)sprite inAtlasAtIndex:(NSUInteger)index { - [sprite useBatchNode:self]; + [sprite setBatchNode:self]; [sprite setAtlasIndex:index]; [sprite setDirty: YES]; - + if(textureAtlas_.totalQuads == textureAtlas_.capacity) [self increaseAtlasCapacity]; - + ccV3F_C4B_T2F_Quad quad = [sprite quad]; [textureAtlas_ insertQuad:&quad atIndex:index]; - + ccArray *descendantsData = descendants_->data; - + ccArrayInsertObjectAtIndex(descendantsData, sprite, index); - + // update indices NSUInteger i = index+1; CCSprite *child; @@ -438,38 +516,66 @@ -(void) insertChild:(CCSprite*)sprite inAtlasAtIndex:(NSUInteger)index child = descendantsData->arr[i]; child.atlasIndex = child.atlasIndex + 1; } - + // add children recursively CCARRAY_FOREACH(sprite.children, child){ - NSUInteger index = [self atlasIndexForChild:child atZ: child.zOrder]; - [self insertChild:child inAtlasAtIndex:index]; + NSUInteger idx = [self atlasIndexForChild:child atZ: child.zOrder]; + [self insertChild:child inAtlasAtIndex:idx]; } } +// addChild helper, faster than insertChild +-(void) appendChild:(CCSprite*)sprite +{ + isReorderChildDirty_=YES; + [sprite setBatchNode:self]; + [sprite setDirty: YES]; + + if(textureAtlas_.totalQuads == textureAtlas_.capacity) + [self increaseAtlasCapacity]; + + ccArray *descendantsData = descendants_->data; + + ccArrayAppendObjectWithResize(descendantsData, sprite); + + NSUInteger index=descendantsData->num-1; + + sprite.atlasIndex=index; + + ccV3F_C4B_T2F_Quad quad = [sprite quad]; + [textureAtlas_ insertQuad:&quad atIndex:index]; + + // add children recursively + CCSprite* child; + CCARRAY_FOREACH(sprite.children, child) + [self appendChild:child]; +} + + // remove child helper -(void) removeSpriteFromAtlas:(CCSprite*)sprite { // remove from TextureAtlas [textureAtlas_ removeQuadAtIndex:sprite.atlasIndex]; - + // Cleanup sprite. It might be reused (issue #569) - [sprite useSelfRender]; - + [sprite setBatchNode:nil]; + ccArray *descendantsData = descendants_->data; NSUInteger index = ccArrayGetIndexOfObject(descendantsData, sprite); if( index != NSNotFound ) { ccArrayRemoveObjectAtIndex(descendantsData, index); - + // update all sprites beyond this one NSUInteger count = descendantsData->num; - + for(; index < count; index++) { CCSprite *s = descendantsData->arr[index]; s.atlasIndex = s.atlasIndex - 1; } } - + // remove children recursively CCSprite *child; CCARRAY_FOREACH(sprite.children, child) @@ -497,3 +603,61 @@ -(CCTexture2D*) texture return textureAtlas_.texture; } @end + +#pragma mark - CCSpriteBatchNode Extension + + +@implementation CCSpriteBatchNode (QuadExtension) + +-(void) addQuadFromSprite:(CCSprite*)sprite quadIndex:(NSUInteger)index +{ + NSAssert( sprite != nil, @"Argument must be non-nil"); + NSAssert( [sprite isKindOfClass:[CCSprite class]], @"CCSpriteBatchNode only supports CCSprites as children"); + + + while(index >= textureAtlas_.capacity || textureAtlas_.capacity == textureAtlas_.totalQuads ) + [self increaseAtlasCapacity]; + + // + // update the quad directly. Don't add the sprite to the scene graph + // + + [sprite setBatchNode:self]; + [sprite setAtlasIndex:index]; + + ccV3F_C4B_T2F_Quad quad = [sprite quad]; + [textureAtlas_ insertQuad:&quad atIndex:index]; + + // XXX: updateTransform will update the textureAtlas too using updateQuad. + // XXX: so, it should be AFTER the insertQuad + [sprite setDirty:YES]; + [sprite updateTransform]; +} + +-(id) addSpriteWithoutQuad:(CCSprite*)child z:(NSUInteger)z tag:(NSInteger)aTag +{ + NSAssert( child != nil, @"Argument must be non-nil"); + NSAssert( [child isKindOfClass:[CCSprite class]], @"CCSpriteBatchNode only supports CCSprites as children"); + + // quad index is Z + [child setAtlasIndex:z]; + + // XXX: optimize with a binary search + int i=0; + for( CCSprite *c in descendants_ ) { + if( c.atlasIndex >= z ) + break; + i++; + } + [descendants_ insertObject:child atIndex:i]; + + + // IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array + [super addChild:child z:z tag:aTag]; + + //#issue 1262 don't use lazy sorting, tiles are added as quads not as sprites, so sprites need to be added in order + [self reorderBatch:NO]; + return self; +} +@end + diff --git a/Example/libs/cocos2d/CCSpriteFrame.h b/Example/libs/cocos2d/CCSpriteFrame.h index ce8c1cf..fcc8084 100644 --- a/Example/libs/cocos2d/CCSpriteFrame.h +++ b/Example/libs/cocos2d/CCSpriteFrame.h @@ -1,18 +1,19 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2008-2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,7 +34,7 @@ You can modify the frame of a CCSprite by doing: - + CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:texture rect:rect offset:offset]; [sprite setDisplayFrame:frame]; */ @@ -42,48 +43,84 @@ CGRect rect_; CGRect rectInPixels_; BOOL rotated_; + CGPoint offset_; CGPoint offsetInPixels_; + CGSize originalSize_; CGSize originalSizeInPixels_; CCTexture2D *texture_; + NSString *textureFilename_; } -/** rect of the frame in points */ +/** rect of the frame in points. If it is updated, then rectInPixels will be updated too. */ @property (nonatomic,readwrite) CGRect rect; -/** rect of the frame in pixels */ +/** rect of the frame in pixels. If it is updated, then rect (points) will be udpated too. */ @property (nonatomic,readwrite) CGRect rectInPixels; /** whether or not the rect of the frame is rotated ( x = x+width, y = y+height, width = height, height = width ) */ @property (nonatomic,readwrite) BOOL rotated; +/** offset of the frame in points */ +@property (nonatomic,readwrite) CGPoint offset; + /** offset of the frame in pixels */ @property (nonatomic,readwrite) CGPoint offsetInPixels; +/** original size of the trimmed image in points */ +@property (nonatomic,readwrite) CGSize originalSize; + /** original size of the trimmed image in pixels */ @property (nonatomic,readwrite) CGSize originalSizeInPixels; /** texture of the frame */ @property (nonatomic, retain, readwrite) CCTexture2D *texture; +/** texture file name of the frame */ +@property (nonatomic, retain, readonly) NSString *textureFilename; + /** Create a CCSpriteFrame with a texture, rect in points. It is assumed that the frame was not trimmed. */ +(id) frameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; +/** Create a CCSpriteFrame with a texture filename, rect in points. + It is assumed that the frame was not trimmed. + */ ++(id) frameWithTextureFilename:(NSString*)filename rect:(CGRect)rect; + /** Create a CCSpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. - The originalSize is the size in points of the frame before being trimmed. + The originalSize is the size in pixels of the frame before being trimmed. */ +(id) frameWithTexture:(CCTexture2D*)texture rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize; +/** Create a CCSpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels. + The originalSize is the size in pixels of the frame before being trimmed. + */ ++(id) frameWithTextureFilename:(NSString*)filename rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize; + + /** Initializes a CCSpriteFrame with a texture, rect in points; It is assumed that the frame was not trimmed. */ -(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; +/** Initializes a CCSpriteFrame with a texture filename, rect in points; + It is assumed that the frame was not trimmed. + */ +-(id) initWithTextureFilename:(NSString*)filename rect:(CGRect)rect; + + /** Initializes a CCSpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. - The originalSize is the size in points of the frame before being trimmed. + The originalSize is the size in pixels of the frame before being trimmed. */ -(id) initWithTexture:(CCTexture2D*)texture rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize; +/** Initializes a CCSpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. + The originalSize is the size in pixels of the frame before being trimmed. + + @since v1.1 + */ +-(id) initWithTextureFilename:(NSString*)filename rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize; + @end diff --git a/Example/libs/cocos2d/CCSpriteFrame.m b/Example/libs/cocos2d/CCSpriteFrame.m index 952d9aa..d9174dc 100644 --- a/Example/libs/cocos2d/CCSpriteFrame.m +++ b/Example/libs/cocos2d/CCSpriteFrame.m @@ -1,18 +1,19 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2008-2011 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,59 +30,154 @@ #import "ccMacros.h" @implementation CCSpriteFrame -@synthesize rect = rect_, rectInPixels=rectInPixels_; -@synthesize rotated = rotated_, offsetInPixels = offsetInPixels_, texture = texture_; -@synthesize originalSizeInPixels=originalSizeInPixels_; +@synthesize offsetInPixels = offsetInPixels_, offset = offset_; +@synthesize originalSize = originalSize_, originalSizeInPixels = originalSizeInPixels_; +@synthesize textureFilename = textureFilename_; +@synthesize rotated = rotated_; +(id) frameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect { return [[[self alloc] initWithTexture:texture rect:rect] autorelease]; } ++(id) frameWithTextureFilename:(NSString*)filename rect:(CGRect)rect +{ + return [[[self alloc] initWithTextureFilename:filename rect:rect] autorelease]; +} + +(id) frameWithTexture:(CCTexture2D*)texture rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize { return [[[self alloc] initWithTexture:texture rectInPixels:rect rotated:rotated offset:offset originalSize:originalSize] autorelease]; } ++(id) frameWithTextureFilename:(NSString*)filename rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize +{ + return [[[self alloc] initWithTextureFilename:filename rectInPixels:rect rotated:rotated offset:offset originalSize:originalSize] autorelease]; +} + -(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect { CGRect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect ); return [self initWithTexture:texture rectInPixels:rectInPixels rotated:NO offset:CGPointZero originalSize:rectInPixels.size]; } +-(id) initWithTextureFilename:(NSString*)filename rect:(CGRect)rect +{ + CGRect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect ); + return [self initWithTextureFilename:filename rectInPixels:rectInPixels rotated:NO offset:CGPointZero originalSize:rectInPixels.size]; +} + -(id) initWithTexture:(CCTexture2D*)texture rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize { - if( (self=[super init]) ) { + if( (self=[super init]) ) + { self.texture = texture; rectInPixels_ = rect; rect_ = CC_RECT_PIXELS_TO_POINTS( rect ); - rotated_ = rotated; offsetInPixels_ = offset; + offset_ = CC_POINT_PIXELS_TO_POINTS( offsetInPixels_ ); + originalSizeInPixels_ = originalSize; + originalSize_ = CC_SIZE_PIXELS_TO_POINTS( originalSizeInPixels_ ); + rotated_ = rotated; + } + return self; +} + +-(id) initWithTextureFilename:(NSString *)filename rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize +{ + if( (self=[super init]) ) + { + texture_ = nil; + textureFilename_ = [filename copy]; + rectInPixels_ = rect; + rect_ = CC_RECT_PIXELS_TO_POINTS( rect ); + offsetInPixels_ = offset; + offset_ = CC_POINT_PIXELS_TO_POINTS( offsetInPixels_ ); originalSizeInPixels_ = originalSize; + originalSize_ = CC_SIZE_PIXELS_TO_POINTS( originalSizeInPixels_ ); + rotated_ = rotated; } - return self; + return self; } - (NSString*) description { - return [NSString stringWithFormat:@"<%@ = %08X | TextureName=%d, Rect = (%.2f,%.2f,%.2f,%.2f)>", [self class], self, - texture_.name, + return [NSString stringWithFormat:@"<%@ = %08X | Texture=%@, Rect = (%.2f,%.2f,%.2f,%.2f)> rotated:%d", [self class], self, + textureFilename_, rect_.origin.x, rect_.origin.y, rect_.size.width, - rect_.size.height]; + rect_.size.height, + rotated_ + ]; } - (void) dealloc { CCLOGINFO( @"cocos2d: deallocing %@",self); [texture_ release]; + [textureFilename_ release]; [super dealloc]; } -(id) copyWithZone: (NSZone*) zone { - CCSpriteFrame *copy = [[[self class] allocWithZone: zone] initWithTexture:texture_ rectInPixels:rectInPixels_ rotated:rotated_ offset:offsetInPixels_ originalSize:originalSizeInPixels_]; + CCSpriteFrame *copy = [[[self class] allocWithZone: zone] initWithTextureFilename:textureFilename_ rectInPixels:rectInPixels_ rotated:rotated_ offset:offsetInPixels_ originalSize:originalSizeInPixels_]; + copy.texture = texture_; return copy; } + +-(CGRect) rect +{ + return rect_; +} + +-(CGRect) rectInPixels +{ + return rectInPixels_; +} + +-(void) setRect:(CGRect)rect +{ + rect_ = rect; + rectInPixels_ = CC_RECT_POINTS_TO_PIXELS( rect_ ); +} + +-(void) setRectInPixels:(CGRect)rectInPixels +{ + rectInPixels_ = rectInPixels; + rect_ = CC_RECT_PIXELS_TO_POINTS( rectInPixels_ ); +} + +-(void) setOffset:(CGPoint)offsets +{ + offset_ = offsets; + offsetInPixels_ = CC_POINT_POINTS_TO_PIXELS( offset_ ); +} + +-(void) setOffsetInPixels:(CGPoint)offsetInPixels +{ + offsetInPixels_ = offsetInPixels; + offset_ = CC_POINT_PIXELS_TO_POINTS( offsetInPixels_ ); +} + +-(void) setTexture:(CCTexture2D *)texture +{ + if( texture_ != texture ) { + [texture_ release]; + texture_ = [texture retain]; + } +} + +-(CCTexture2D*) texture +{ + if( texture_ ) + return texture_; + + if( textureFilename_ ) + return [[CCTextureCache sharedTextureCache] addImage:textureFilename_]; + + // no texture or texture filename + return nil; +} @end diff --git a/Example/libs/cocos2d/CCSpriteFrameCache.h b/Example/libs/cocos2d/CCSpriteFrameCache.h index b50a6a0..23507e4 100644 --- a/Example/libs/cocos2d/CCSpriteFrameCache.h +++ b/Example/libs/cocos2d/CCSpriteFrameCache.h @@ -1,20 +1,24 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada * Copyright (c) 2009 Jason Booth + * * Copyright (c) 2009 Robert J Payne - * + * + * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,9 +38,9 @@ #import #import "CCSpriteFrame.h" -#import "CCTexture2D.h" @class CCSprite; +@class CCTexture2D; /** Singleton that handles the loading of the sprite frames. It saves in a cache the sprite frames. @@ -56,24 +60,27 @@ +(void)purgeSharedSpriteFrameCache; +/** Adds multiple Sprite Frames with a dictionary. The texture filename will be associated with the created sprite frames. + */ +-(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary textureFilename:(NSString*)filename; + /** Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. */ --(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary texture:(CCTexture2D*)texture; +-(void) addSpriteFramesWithDictionary:(NSDictionary *)dictionary texture:(CCTexture2D *)texture; /** Adds multiple Sprite Frames from a plist file. - * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png + * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png . * If you want to use another texture, you should use the addSpriteFramesWithFile:texture method. */ -(void) addSpriteFramesWithFile:(NSString*)plist; -/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. +/** Adds multiple Sprite Frames from a plist file. The texture filename will be associated with the created sprite frames. */ --(void) addSpriteFramesWithFile:(NSString*)plist texture:(CCTexture2D*)texture; +-(void) addSpriteFramesWithFile:(NSString*)plist textureFilename:(NSString*)filename; /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. - @since v0.99.5 */ --(void) addSpriteFramesWithFile:(NSString*)plist textureFile:(NSString*)textureFileName; +-(void) addSpriteFramesWithFile:(NSString*)plist texture:(CCTexture2D*)texture; /** Adds an sprite frame with a given name. If the name already exists, then the contents of the old name will be replaced with the new one. @@ -123,11 +130,4 @@ */ -(CCSpriteFrame*) spriteFrameByName:(NSString*)name; -/** Creates an sprite with the name of an sprite frame. - The created sprite will contain the texture, rect and offset of the sprite frame. - It returns an autorelease object. - @deprecated use [CCSprite spriteWithSpriteFrameName:name]. This method will be removed on final v0.9 - */ --(CCSprite*) createSpriteWithFrameName:(NSString*)name DEPRECATED_ATTRIBUTE; - @end diff --git a/Example/libs/cocos2d/CCSpriteFrameCache.m b/Example/libs/cocos2d/CCSpriteFrameCache.m index 514ab97..e0ab1a8 100644 --- a/Example/libs/cocos2d/CCSpriteFrameCache.m +++ b/Example/libs/cocos2d/CCSpriteFrameCache.m @@ -1,20 +1,23 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2008-2010 Ricardo Quesada * Copyright (c) 2009 Jason Booth + * * Copyright (c) 2009 Robert J Payne - * + * + * Copyright (c) 2008-2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,8 +29,10 @@ */ /* - * To create sprite frames and texture atlas, use this tool: - * http://zwoptex.zwopple.com/ + * To create sprite frames and texture atlas, use any of these tools: + * http://zwoptexapp.com/ + * http://www.texturepacker.com/ + * */ #import "Platforms/CCNS.h" @@ -49,7 +54,7 @@ + (CCSpriteFrameCache *)sharedSpriteFrameCache { if (!sharedSpriteFrameCache_) sharedSpriteFrameCache_ = [[CCSpriteFrameCache alloc] init]; - + return sharedSpriteFrameCache_; } @@ -71,7 +76,7 @@ -(id) init spriteFrames_ = [[NSMutableDictionary alloc] initWithCapacity: 100]; spriteFramesAliases_ = [[NSMutableDictionary alloc] initWithCapacity:10]; } - + return self; } @@ -83,7 +88,7 @@ - (NSString*) description -(void) dealloc { CCLOGINFO(@"cocos2d: deallocing %@", self); - + [spriteFrames_ release]; [spriteFramesAliases_ release]; [super dealloc]; @@ -91,7 +96,7 @@ -(void) dealloc #pragma mark CCSpriteFrameCache - loading sprite frames --(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary texture:(CCTexture2D*)texture +-(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary textureReference:(id)textureReference { /* Supported Zwoptex Formats: @@ -104,19 +109,24 @@ -(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary texture:(CCTextu NSDictionary *framesDict = [dictionary objectForKey:@"frames"]; int format = 0; - + // get the format if(metadataDict != nil) format = [[metadataDict objectForKey:@"format"] intValue]; - + // check the format - NSAssert( format >= 0 && format <= 3, @"cocos2d: WARNING: format is not supported for CCSpriteFrameCache addSpriteFramesWithDictionary:texture:"); - - + NSAssert( format >= 0 && format <= 3, @"cocos2d: WARNING: format is not supported for CCSpriteFrameCache addSpriteFramesWithDictionary:textureFilename:"); + + // SpriteFrame info + CGRect rectInPixels; + BOOL isRotated; + CGPoint frameOffset; + CGSize originalSize; + // add real frames for(NSString *frameDictKey in framesDict) { NSDictionary *frameDict = [framesDict objectForKey:frameDictKey]; - CCSpriteFrame *spriteFrame; + CCSpriteFrame *spriteFrame=nil; if(format == 0) { float x = [[frameDict objectForKey:@"x"] floatValue]; float y = [[frameDict objectForKey:@"y"] floatValue]; @@ -129,34 +139,32 @@ -(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary texture:(CCTextu // check ow/oh if(!ow || !oh) CCLOG(@"cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist"); - + // abs ow/oh ow = abs(ow); oh = abs(oh); - // create frame - - spriteFrame = [[CCSpriteFrame alloc] initWithTexture:texture - rectInPixels:CGRectMake(x, y, w, h) - rotated:NO - offset:CGPointMake(ox, oy) - originalSize:CGSizeMake(ow, oh)]; + + // set frame info + rectInPixels = CGRectMake(x, y, w, h); + isRotated = NO; + frameOffset = CGPointMake(ox, oy); + originalSize = CGSizeMake(ow, oh); } else if(format == 1 || format == 2) { CGRect frame = CCRectFromString([frameDict objectForKey:@"frame"]); BOOL rotated = NO; - + // rotation if(format == 2) rotated = [[frameDict objectForKey:@"rotated"] boolValue]; - + CGPoint offset = CCPointFromString([frameDict objectForKey:@"offset"]); CGSize sourceSize = CCSizeFromString([frameDict objectForKey:@"sourceSize"]); - - // create frame - spriteFrame = [[CCSpriteFrame alloc] initWithTexture:texture - rectInPixels:frame - rotated:rotated - offset:offset - originalSize:sourceSize]; + + // set frame info + rectInPixels = frame; + isRotated = rotated; + frameOffset = offset; + originalSize = sourceSize; } else if(format == 3) { // get values CGSize spriteSize = CCSizeFromString([frameDict objectForKey:@"spriteSize"]); @@ -164,22 +172,42 @@ -(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary texture:(CCTextu CGSize spriteSourceSize = CCSizeFromString([frameDict objectForKey:@"spriteSourceSize"]); CGRect textureRect = CCRectFromString([frameDict objectForKey:@"textureRect"]); BOOL textureRotated = [[frameDict objectForKey:@"textureRotated"] boolValue]; - + // get aliases NSArray *aliases = [frameDict objectForKey:@"aliases"]; for(NSString *alias in aliases) { if( [spriteFramesAliases_ objectForKey:alias] ) CCLOG(@"cocos2d: WARNING: an alias with name %@ already exists",alias); - + [spriteFramesAliases_ setObject:frameDictKey forKey:alias]; } - - // create frame - spriteFrame = [[CCSpriteFrame alloc] initWithTexture:texture - rectInPixels:CGRectMake(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height) - rotated:textureRotated - offset:spriteOffset - originalSize:spriteSourceSize]; + + // set frame info + rectInPixels = CGRectMake(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height); + isRotated = textureRotated; + frameOffset = spriteOffset; + originalSize = spriteSourceSize; + } + + NSString *textureFileName = nil; + CCTexture2D * texture = nil; + + if ( [textureReference isKindOfClass:[NSString class]] ) + { + textureFileName = textureReference; + } + else if ( [textureReference isKindOfClass:[CCTexture2D class]] ) + { + texture = textureReference; + } + + if ( textureFileName ) + { + spriteFrame = [[CCSpriteFrame alloc] initWithTextureFilename:textureFileName rectInPixels:rectInPixels rotated:isRotated offset:frameOffset originalSize:originalSize]; + } + else + { + spriteFrame = [[CCSpriteFrame alloc] initWithTexture:texture rectInPixels:rectInPixels rotated:isRotated offset:frameOffset originalSize:originalSize]; } // add sprite frame @@ -188,37 +216,52 @@ -(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary texture:(CCTextu } } --(void) addSpriteFramesWithFile:(NSString*)plist texture:(CCTexture2D*)texture +-(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary textureFilename:(NSString*)textureFilename { + return [self addSpriteFramesWithDictionary:dictionary textureReference:textureFilename]; +} + +-(void) addSpriteFramesWithDictionary:(NSDictionary *)dictionary texture:(CCTexture2D *)texture +{ + return [self addSpriteFramesWithDictionary:dictionary textureReference:texture]; +} + +-(void) addSpriteFramesWithFile:(NSString*)plist textureReference:(id)textureReference +{ + NSAssert(textureReference, @"textureReference should not be nil"); + NSAssert(plist, @"plist filename should not be nil"); + NSString *path = [CCFileUtils fullPathFromRelativePath:plist]; NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - return [self addSpriteFramesWithDictionary:dict texture:texture]; + [self addSpriteFramesWithDictionary:dict textureReference:textureReference]; +} + +-(void) addSpriteFramesWithFile:(NSString*)plist textureFilename:(NSString*)textureFilename +{ + return [self addSpriteFramesWithFile:plist textureReference:textureFilename]; } --(void) addSpriteFramesWithFile:(NSString*)plist textureFile:(NSString*)textureFileName +-(void) addSpriteFramesWithFile:(NSString*)plist texture:(CCTexture2D*)texture { - NSAssert( textureFileName, @"Invalid texture file name"); - CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:textureFileName]; - - if( texture ) - [self addSpriteFramesWithFile:plist texture:texture]; - else - CCLOG(@"cocos2d: CCSpriteFrameCache: couldn't load texture file. File not found: %@", textureFileName); + return [self addSpriteFramesWithFile:plist textureReference:texture]; } + -(void) addSpriteFramesWithFile:(NSString*)plist { + NSAssert(plist, @"plist filename should not be nil"); + NSString *path = [CCFileUtils fullPathFromRelativePath:plist]; NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - + NSString *texturePath = nil; NSDictionary *metadataDict = [dict objectForKey:@"metadata"]; if( metadataDict ) // try to read texture file name from meta data texturePath = [metadataDict objectForKey:@"textureFileName"]; - - + + if( texturePath ) { // build texture path relative to plist file @@ -228,17 +271,12 @@ -(void) addSpriteFramesWithFile:(NSString*)plist // build texture path by replacing file extension texturePath = [plist stringByDeletingPathExtension]; texturePath = [texturePath stringByAppendingPathExtension:@"png"]; - - CCLOG(@"cocos2d: CCSpriteFrameCache: Trying to use file '%@' as texture", texturePath); + + CCLOG(@"cocos2d: CCSpriteFrameCache: Trying to use file '%@' as texture", texturePath); } - - CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:texturePath]; - - if( texture ) - [self addSpriteFramesWithDictionary:dict texture:texture]; - - else - CCLOG(@"cocos2d: CCSpriteFrameCache: Couldn't load texture"); + + + [self addSpriteFramesWithDictionary:dict textureFilename:texturePath]; } -(void) addSpriteFrame:(CCSpriteFrame*)frame name:(NSString*)frameName @@ -258,12 +296,12 @@ -(void) removeUnusedSpriteFrames { NSArray *keys = [spriteFrames_ allKeys]; for( id key in keys ) { - id value = [spriteFrames_ objectForKey:key]; + id value = [spriteFrames_ objectForKey:key]; if( [value retainCount] == 1 ) { CCLOG(@"cocos2d: CCSpriteFrameCache: removing unused frame: %@", key); [spriteFrames_ removeObjectForKey:key]; } - } + } } -(void) removeSpriteFrameByName:(NSString*)name @@ -271,10 +309,10 @@ -(void) removeSpriteFrameByName:(NSString*)name // explicit nil handling if( ! name ) return; - + // Is this an alias ? NSString *key = [spriteFramesAliases_ objectForKey:name]; - + if( key ) { [spriteFrames_ removeObjectForKey:key]; [spriteFramesAliases_ removeObjectForKey:name]; @@ -287,7 +325,7 @@ - (void) removeSpriteFramesFromFile:(NSString*) plist { NSString *path = [CCFileUtils fullPathFromRelativePath:plist]; NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - + [self removeSpriteFramesFromDictionary:dict]; } @@ -295,7 +333,7 @@ - (void) removeSpriteFramesFromDictionary:(NSDictionary*) dictionary { NSDictionary *framesDict = [dictionary objectForKey:@"frames"]; NSMutableArray *keysToRemove=[NSMutableArray array]; - + for(NSString *frameDictKey in framesDict) { if ([spriteFrames_ objectForKey:frameDictKey]!=nil) @@ -307,12 +345,12 @@ - (void) removeSpriteFramesFromDictionary:(NSDictionary*) dictionary - (void) removeSpriteFramesFromTexture:(CCTexture2D*) texture { NSMutableArray *keysToRemove=[NSMutableArray array]; - + for (NSString *spriteFrameKey in spriteFrames_) { - if ([[spriteFrames_ valueForKey:spriteFrameKey] texture] == texture) + if ([[spriteFrames_ valueForKey:spriteFrameKey] texture] == texture) [keysToRemove addObject:spriteFrameKey]; - + } [spriteFrames_ removeObjectsForKeys:keysToRemove]; } @@ -326,19 +364,12 @@ -(CCSpriteFrame*) spriteFrameByName:(NSString*)name // try alias dictionary NSString *key = [spriteFramesAliases_ objectForKey:name]; frame = [spriteFrames_ objectForKey:key]; - + if( ! frame ) CCLOG(@"cocos2d: CCSpriteFrameCache: Frame '%@' not found", name); } - + return frame; } -#pragma mark CCSpriteFrameCache - sprite creation - --(CCSprite*) createSpriteWithFrameName:(NSString*)name -{ - CCSpriteFrame *frame = [spriteFrames_ objectForKey:name]; - return [CCSprite spriteWithSpriteFrame:frame]; -} @end diff --git a/Example/libs/cocos2d/CCSpriteSheet.h b/Example/libs/cocos2d/CCSpriteSheet.h deleted file mode 100644 index c55f534..0000000 --- a/Example/libs/cocos2d/CCSpriteSheet.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (C) 2009 Matt Oswald - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCSpriteBatchNode.h" - -#pragma mark CCSpriteSheet - - -/* Added only to prevent GCC compile warnings - Will be removed in v1.1 - */ -@interface CCSpriteSheetInternalOnly : CCSpriteBatchNode -{ -} -@end - -/** CCSpriteSheet is like a batch node: if it contains children, it will draw them in 1 single OpenGL call - * (often known as "batch draw"). - * - * A CCSpriteSheet can reference one and only one texture (one image file, one texture atlas). - * Only the CCSprites that are contained in that texture can be added to the CCSpriteSheet. - * All CCSprites added to a CCSpriteSheet are drawn in one OpenGL ES draw call. - * If the CCSprites are not added to a CCSpriteSheet then an OpenGL ES draw call will be needed for each one, which is less efficient. - * - * - * Limitations: - * - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is CCSprite or any subclass of CCSprite. eg: particles, labels and layer can't be added to a CCSpriteSheet. - * - Either all its children are Aliased or Antialiased. It can't be a mix. This is because "alias" is a property of the texture, and all the sprites share the same texture. - * - * @since v0.7.1 - * - * @deprecated Use CCSpriteBatchNode instead. This class will be removed in v1.1 - */ -DEPRECATED_ATTRIBUTE @interface CCSpriteSheet : CCSpriteSheetInternalOnly -{ -} -@end diff --git a/Example/libs/cocos2d/CCSpriteSheet.m b/Example/libs/cocos2d/CCSpriteSheet.m deleted file mode 100644 index fccc143..0000000 --- a/Example/libs/cocos2d/CCSpriteSheet.m +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (C) 2009 Matt Oswald - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCSpriteSheet.h" - -#pragma mark - -#pragma mark CCSpriteSheet - -@implementation CCSpriteSheetInternalOnly -@end - -@implementation CCSpriteSheet -@end diff --git a/Example/libs/cocos2d/CCTMXLayer.h b/Example/libs/cocos2d/CCTMXLayer.h index b7dc2ab..ed1f4f1 100644 --- a/Example/libs/cocos2d/CCTMXLayer.h +++ b/Example/libs/cocos2d/CCTMXLayer.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,36 +31,35 @@ #import "CCAtlasNode.h" #import "CCSpriteBatchNode.h" - +#import "CCTMXXMLParser.h" @class CCTMXMapInfo; @class CCTMXLayerInfo; @class CCTMXTilesetInfo; + /** CCTMXLayer represents the TMX layer. - - It is a subclass of CCSpriteSheet. By default the tiles are rendered using a CCTextureAtlas. + + It is a subclass of CCSpriteBatchNode. By default the tiles are rendered using a CCTextureAtlas. If you mofify a tile on runtime, then, that tile will become a CCSprite, otherwise no CCSprite objects are created. The benefits of using CCSprite objects as tiles are: - tiles (CCSprite) can be rotated/scaled/moved with a nice API - - If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative), - then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth. - On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value. - Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be: + cocos2d v2.0 doesn't support the cc_vertexz value. Whenever a the cc_vertexz property is found, it will raise an exception. - glAlphaFunc( GL_GREATER, value ) - "value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer. The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a differnt value, like 0.5. - + For further information, please see the programming guide: - + http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps - + @since v0.8.1 + + Tiles can have tile flags for additional properties. At the moment only flip horizontal and flip vertical are used. These bit flags are defined in CCTMXXMLParser.h. + + @since 1.1 */ @interface CCTMXLayer : CCSpriteBatchNode { @@ -67,25 +67,22 @@ NSString *layerName_; CGSize layerSize_; CGSize mapTileSize_; - unsigned int *tiles_; - int layerOrientation_; + uint32_t *tiles_; // GID are 32 bit + NSUInteger layerOrientation_; NSMutableArray *properties_; - + unsigned char opacity_; // TMX Layer supports opacity - - unsigned int minGID_; - unsigned int maxGID_; - + + NSUInteger minGID_; + NSUInteger maxGID_; + // Only used when vertexZ is used - int vertexZvalue_; + NSInteger vertexZvalue_; BOOL useAutomaticVertexZ_; - float alphaFuncValue_; - + // used for optimization CCSprite *reusedTile_; ccCArray *atlasIndexArray_; - - } /** name of the layer */ @property (nonatomic,readwrite,retain) NSString *layerName; @@ -94,11 +91,11 @@ /** size of the map's tile (could be differnt from the tile's size) */ @property (nonatomic,readwrite) CGSize mapTileSize; /** pointer to the map of tiles */ -@property (nonatomic,readwrite) unsigned int *tiles; +@property (nonatomic,readwrite) uint32_t *tiles; /** Tilset information for the layer */ @property (nonatomic,readwrite,retain) CCTMXTilesetInfo *tileset; /** Layer orientation, which is the same as the map orientation */ -@property (nonatomic,readwrite) int layerOrientation; +@property (nonatomic,readwrite) NSUInteger layerOrientation; /** properties from the layer. They can be added using Tiled */ @property (nonatomic,readwrite,retain) NSMutableArray *properties; @@ -126,18 +123,32 @@ if it returns 0, it means that the tile is empty. This method requires the the tile map has not been previously released (eg. don't call [layer releaseMap]) */ --(unsigned int) tileGIDAt:(CGPoint)tileCoordinate; +-(uint32_t) tileGIDAt:(CGPoint)tileCoordinate; + +/** returns the tile gid at a given tile coordinate. It also returns the tile flags. + This method requires the the tile map has not been previously released (eg. don't call [layer releaseMap]) + */ +-(uint32_t) tileGIDAt:(CGPoint)pos withFlags:(ccTMXTileFlags*)flags; /** sets the tile gid (gid = tile global id) at a given tile coordinate. The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1. If a tile is already placed at that position, then it will be removed. */ --(void) setTileGID:(unsigned int)gid at:(CGPoint)tileCoordinate; +-(void) setTileGID:(uint32_t)gid at:(CGPoint)tileCoordinate; + +/** sets the tile gid (gid = tile global id) at a given tile coordinate. + The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1. + If a tile is already placed at that position, then it will be removed. + + Use withFlags if the tile flags need to be changed as well + */ + +-(void) setTileGID:(uint32_t)gid at:(CGPoint)pos withFlags:(ccTMXTileFlags)flags; /** removes a tile at given tile coordinate */ -(void) removeTileAt:(CGPoint)tileCoordinate; -/** returns the position in pixels of a given tile coordinate */ +/** returns the position in points of a given tile coordinate */ -(CGPoint) positionAt:(CGPoint)tileCoordinate; /** return the value for the specific property name */ @@ -149,5 +160,5 @@ /** CCTMXLayer doesn't support adding a CCSprite manually. @warning addchild:z:tag: is not supported on CCTMXLayer. Instead of setTileGID:at:/tileAt: */ --(void) addChild: (CCNode*)node z:(int)z tag:(int)tag; +-(void) addChild: (CCNode*)node z:(NSInteger)z tag:(NSInteger)tag; @end diff --git a/Example/libs/cocos2d/CCTMXLayer.m b/Example/libs/cocos2d/CCTMXLayer.m index 887af20..6738e19 100644 --- a/Example/libs/cocos2d/CCTMXLayer.m +++ b/Example/libs/cocos2d/CCTMXLayer.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,77 +34,18 @@ #import "CCSprite.h" #import "CCSpriteBatchNode.h" #import "CCTextureCache.h" +#import "CCShaderCache.h" +#import "CCGLProgram.h" #import "Support/CGPointExtension.h" -#pragma mark - -#pragma mark CCSpriteBatchNode Extension - -/* IMPORTANT XXX IMPORTNAT: - * These 2 methods can't be part of CCTMXLayer since they call [super add...], and CCSpriteSheet#add SHALL not be called - */ -@implementation CCSpriteBatchNode (TMXTiledMapExtension) - -/* Adds a quad into the texture atlas but it won't be added into the children array. - This method should be called only when you are dealing with very big AtlasSrite and when most of the CCSprite won't be updated. - For example: a tile map (CCTMXMap) or a label with lots of characgers (BitmapFontAtlas) - */ --(void) addQuadFromSprite:(CCSprite*)sprite quadIndex:(unsigned int)index -{ - NSAssert( sprite != nil, @"Argument must be non-nil"); - NSAssert( [sprite isKindOfClass:[CCSprite class]], @"CCSpriteSheet only supports CCSprites as children"); - - - while(index >= textureAtlas_.capacity || textureAtlas_.capacity == textureAtlas_.totalQuads ) - [self increaseAtlasCapacity]; - - // - // update the quad directly. Don't add the sprite to the scene graph - // - - [sprite useBatchNode:self]; - [sprite setAtlasIndex:index]; - - ccV3F_C4B_T2F_Quad quad = [sprite quad]; - [textureAtlas_ insertQuad:&quad atIndex:index]; - - // XXX: updateTransform will update the textureAtlas too using updateQuad. - // XXX: so, it should be AFTER the insertQuad - [sprite setDirty:YES]; - [sprite updateTransform]; -} - -/* This is the opposite of "addQuadFromSprite. - It add the sprite to the children and descendants array, but it doesn't update add it to the texture atlas - */ --(id) addSpriteWithoutQuad:(CCSprite*)child z:(unsigned int)z tag:(int)aTag -{ - NSAssert( child != nil, @"Argument must be non-nil"); - NSAssert( [child isKindOfClass:[CCSprite class]], @"CCSpriteSheet only supports CCSprites as children"); - - // quad index is Z - [child setAtlasIndex:z]; - - // XXX: optimize with a binary search - int i=0; - for( CCSprite *c in descendants_ ) { - if( c.atlasIndex >= z ) - break; - i++; - } - [descendants_ insertObject:child atIndex:i]; - - - // IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array - [super addChild:child z:z tag:aTag]; - return self; -} -@end - #pragma mark - #pragma mark CCTMXLayer -@interface CCTMXLayer (Private) +int compareInts (const void * a, const void * b); + + +@interface CCTMXLayer () -(CGPoint) positionForIsoAt:(CGPoint)pos; -(CGPoint) positionForOrthoAt:(CGPoint)pos; -(CGPoint) positionForHexAt:(CGPoint)pos; @@ -111,20 +53,15 @@ -(CGPoint) positionForHexAt:(CGPoint)pos; -(CGPoint) calculateLayerOffset:(CGPoint)offset; /* optimization methos */ --(CCSprite*) appendTileForGID:(unsigned int)gid at:(CGPoint)pos; --(CCSprite*) insertTileForGID:(unsigned int)gid at:(CGPoint)pos; --(CCSprite*) updateTileForGID:(unsigned int)gid at:(CGPoint)pos; +-(CCSprite*) appendTileForGID:(uint32_t)gid at:(CGPoint)pos; +-(CCSprite*) insertTileForGID:(uint32_t)gid at:(CGPoint)pos; +-(CCSprite*) updateTileForGID:(uint32_t)gid at:(CGPoint)pos; /* The layer recognizes some special properties, like cc_vertez */ -(void) parseInternalProperties; +- (void) setupTileSprite:(CCSprite*) sprite position:(CGPoint)pos withGID:(uint32_t)gid; --(int) vertexZForPos:(CGPoint)pos; - -// adding quad from sprite --(void)addQuadFromSprite:(CCSprite*)sprite quadIndex:(unsigned int)index; - -// adds an sprite without the quad --(id)addSpriteWithoutQuad:(CCSprite*)child z:(int)z tag:(int)aTag; +-(NSInteger) vertexZForPos:(CGPoint)pos; // index -(NSUInteger) atlasIndexForExistantZ:(NSUInteger)z; @@ -146,21 +83,21 @@ +(id) layerWithTilesetInfo:(CCTMXTilesetInfo*)tilesetInfo layerInfo:(CCTMXLayerI } -(id) initWithTilesetInfo:(CCTMXTilesetInfo*)tilesetInfo layerInfo:(CCTMXLayerInfo*)layerInfo mapInfo:(CCTMXMapInfo*)mapInfo -{ +{ // XXX: is 35% a good estimate ? CGSize size = layerInfo.layerSize; float totalNumberOfTiles = size.width * size.height; float capacity = totalNumberOfTiles * 0.35f + 1; // 35 percent is occupied ? - + CCTexture2D *tex = nil; if( tilesetInfo ) tex = [[CCTextureCache sharedTextureCache] addImage:tilesetInfo.sourceImage]; - - if((self = [super initWithTexture:tex capacity:capacity])) { + + if((self = [super initWithTexture:tex capacity:capacity])) { // layerInfo self.layerName = layerInfo.name; - layerSize_ = layerInfo.layerSize; + layerSize_ = size; tiles_ = layerInfo.tiles; minGID_ = layerInfo.minGID; maxGID_ = layerInfo.maxGID; @@ -169,24 +106,23 @@ -(id) initWithTilesetInfo:(CCTMXTilesetInfo*)tilesetInfo layerInfo:(CCTMXLayerIn // tilesetInfo self.tileset = tilesetInfo; - + // mapInfo mapTileSize_ = mapInfo.tileSize; layerOrientation_ = mapInfo.orientation; - + // offset (after layer orientation is set); CGPoint offset = [self calculateLayerOffset:layerInfo.offset]; - [self setPositionInPixels:offset]; - + [self setPosition:CC_POINT_PIXELS_TO_POINTS(offset)]; + atlasIndexArray_ = ccCArrayNew(totalNumberOfTiles); - - [self setContentSizeInPixels: CGSizeMake( layerSize_.width * mapTileSize_.width, layerSize_.height * mapTileSize_.height )]; - + + [self setContentSize:CC_SIZE_PIXELS_TO_POINTS(CGSizeMake( layerSize_.width * mapTileSize_.width, layerSize_.height * mapTileSize_.height ))]; + useAutomaticVertexZ_= NO; vertexZvalue_ = 0; - alphaFuncValue_ = 0; - } + return self; } @@ -196,17 +132,17 @@ - (void) dealloc [tileset_ release]; [reusedTile_ release]; [properties_ release]; - + if( atlasIndexArray_ ) { ccCArrayFree(atlasIndexArray_); atlasIndexArray_ = NULL; } - + if( tiles_ ) { free(tiles_); tiles_ = NULL; } - + [super dealloc]; } @@ -216,7 +152,7 @@ -(void) releaseMap free( tiles_); tiles_ = NULL; } - + if( atlasIndexArray_ ) { ccCArrayFree(atlasIndexArray_); atlasIndexArray_ = NULL; @@ -225,52 +161,71 @@ -(void) releaseMap #pragma mark CCTMXLayer - setup Tiles --(void) setupTiles +-(CCSprite*) reusedTileWithRect:(CGRect)rect { + if( ! reusedTile_ ) { + reusedTile_ = [[CCSprite alloc] initWithTexture:textureAtlas_.texture rect:rect rotated:NO]; + [reusedTile_ setBatchNode:self]; + } + else + { + // XXX: should not be re-init. Potential memeory leak. Not following best practices + // XXX: it shall call directory [setRect:rect] + [reusedTile_ initWithTexture:textureAtlas_.texture rect:rect rotated:NO]; + + // Since initWithTexture resets the batchNode, we need to re add it. + // but should be removed once initWithTexture is not called again + [reusedTile_ setBatchNode:self]; + } + + return reusedTile_; +} + +-(void) setupTiles +{ // Optimization: quick hack that sets the image size on the tileset tileset_.imageSize = [textureAtlas_.texture contentSizeInPixels]; - + // By default all the tiles are aliased // pros: // - easier to render // cons: // - difficult to scale / rotate / etc. [textureAtlas_.texture setAliasTexParameters]; - - CFByteOrder o = CFByteOrderGetCurrent(); - + // Parse cocos2d properties [self parseInternalProperties]; - - for( unsigned int y=0; y < layerSize_.height; y++ ) { - for( unsigned int x=0; x < layerSize_.width; x++ ) { - - unsigned int pos = x + layerSize_.width * y; - unsigned int gid = tiles_[ pos ]; - + + for( NSUInteger y = 0; y < layerSize_.height; y++ ) { + for( NSUInteger x = 0; x < layerSize_.width; x++ ) { + + NSUInteger pos = x + layerSize_.width * y; + uint32_t gid = tiles_[ pos ]; + // gid are stored in little endian. // if host is big endian, then swap - if( o == CFByteOrderBigEndian ) - gid = CFSwapInt32( gid ); - + gid = CFSwapInt32LittleToHost( gid ); + // XXX: gid == 0 --> empty tile if( gid != 0 ) { [self appendTileForGID:gid at:ccp(x,y)]; - + // Optimization: update min and max GID rendered by the layer minGID_ = MIN(gid, minGID_); maxGID_ = MAX(gid, maxGID_); +// minGID_ = MIN((gid & kFlippedMask), minGID_); +// maxGID_ = MAX((gid & kFlippedMask), maxGID_); } } } - + NSAssert( maxGID_ >= tileset_.firstGid && - minGID_ >= tileset_.firstGid, @"TMX: Only 1 tilset per layer is supported"); + minGID_ >= tileset_.firstGid, @"TMX: Only 1 tilset per layer is supported"); } #pragma mark CCTMXLayer - Properties --(id) propertyNamed:(NSString *)propertyName +-(id) propertyNamed:(NSString *)propertyName { return [properties_ valueForKey:propertyName]; } @@ -281,14 +236,24 @@ -(void) parseInternalProperties NSString *vertexz = [self propertyNamed:@"cc_vertexz"]; if( vertexz ) { - if( [vertexz isEqualToString:@"automatic"] ) + + // If "automatic" is on, then parse the "cc_alpha_func" too + if( [vertexz isEqualToString:@"automatic"] ) { useAutomaticVertexZ_ = YES; + + NSString *alphaFuncVal = [self propertyNamed:@"cc_alpha_func"]; + float alphaFuncValue = [alphaFuncVal floatValue]; + + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColorAlphaTest]; + + GLint alphaValueLocation = glGetUniformLocation(self.shaderProgram->program_, kCCUniformAlphaTestValue); + + // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison + [self.shaderProgram setUniformLocation:alphaValueLocation withF1:alphaFuncValue]; + } else vertexZvalue_ = [vertexz intValue]; } - - NSString *alphaFuncVal = [self propertyNamed:@"cc_alpha_func"]; - alphaFuncValue_ = [alphaFuncVal floatValue]; } #pragma mark CCTMXLayer - obtaining tiles/gids @@ -297,25 +262,29 @@ -(CCSprite*) tileAt:(CGPoint)pos { NSAssert( pos.x < layerSize_.width && pos.y < layerSize_.height && pos.x >=0 && pos.y >=0, @"TMXLayer: invalid position"); NSAssert( tiles_ && atlasIndexArray_, @"TMXLayer: the tiles map has been released"); - + CCSprite *tile = nil; - unsigned int gid = [self tileGIDAt:pos]; - + uint32_t gid = [self tileGIDAt:pos]; + // if GID == 0, then no tile is present if( gid ) { int z = pos.x + pos.y * layerSize_.width; tile = (CCSprite*) [self getChildByTag:z]; - + // tile not created yet. create it if( ! tile ) { - CGRect rect = [tileset_ rectForGID:gid]; - tile = [[CCSprite alloc] initWithBatchNode:self rectInPixels:rect]; - [tile setPositionInPixels: [self positionAt:pos]]; + CGRect rect = [tileset_ rectForGID:gid]; + rect = CC_RECT_PIXELS_TO_POINTS(rect); + tile = [[CCSprite alloc] initWithTexture:self.texture rect:rect]; + [tile setBatchNode:self]; + + CGPoint p = [self positionAt:pos]; + [tile setPosition:p]; [tile setVertexZ: [self vertexZForPos:pos]]; tile.anchorPoint = CGPointZero; [tile setOpacity:opacity_]; - - unsigned int indexForZ = [self atlasIndexForExistantZ:z]; + + NSUInteger indexForZ = [self atlasIndexForExistantZ:z]; [self addSpriteWithoutQuad:tile z:indexForZ tag:z]; [tile release]; } @@ -323,101 +292,122 @@ -(CCSprite*) tileAt:(CGPoint)pos return tile; } --(unsigned int) tileGIDAt:(CGPoint)pos +-(uint32_t) tileGIDAt:(CGPoint)pos +{ + return [self tileGIDAt:pos withFlags:NULL]; +} + +-(uint32_t) tileGIDAt:(CGPoint)pos withFlags:(ccTMXTileFlags*)flags { NSAssert( pos.x < layerSize_.width && pos.y < layerSize_.height && pos.x >=0 && pos.y >=0, @"TMXLayer: invalid position"); NSAssert( tiles_ && atlasIndexArray_, @"TMXLayer: the tiles map has been released"); + + NSInteger idx = pos.x + pos.y * layerSize_.width; + + // Bits on the far end of the 32-bit global tile ID are used for tile flags + + uint32_t tile = tiles_[idx]; - int idx = pos.x + pos.y * layerSize_.width; - return tiles_[ idx ]; + // issue1264, flipped tiles can be changed dynamically + if (flags) + *flags = tile & kCCFlipedAll; + + return ( tile & kCCFlippedMask); } #pragma mark CCTMXLayer - adding helper methods --(CCSprite*) insertTileForGID:(unsigned int)gid at:(CGPoint)pos +- (void) setupTileSprite:(CCSprite*) sprite position:(CGPoint)pos withGID:(uint32_t)gid { - CGRect rect = [tileset_ rectForGID:gid]; - - NSInteger z = pos.x + pos.y * layerSize_.width; - - if( ! reusedTile_ ) - reusedTile_ = [[CCSprite alloc] initWithBatchNode:self rectInPixels:rect]; + [sprite setPosition: [self positionAt:pos]]; + [sprite setVertexZ: [self vertexZForPos:pos]]; + sprite.anchorPoint = CGPointZero; + [sprite setOpacity:opacity_]; + + //issue 1264, flip can be undone as well + if (gid & kCCTMXTileHorizontalFlag) + sprite.flipX = YES; + else + sprite.flipX = NO; + + if (gid & kCCTMXTileVerticalFlag) + sprite.flipY = YES; else - [reusedTile_ initWithBatchNode:self rectInPixels:rect]; - - [reusedTile_ setPositionInPixels: [self positionAt:pos]]; - [reusedTile_ setVertexZ: [self vertexZForPos:pos]]; - reusedTile_.anchorPoint = CGPointZero; - [reusedTile_ setOpacity:opacity_]; + sprite.flipY = NO; + if( gid & kCCTMXTileDiagonalFlag) + NSAssert(NO, @"Tiled Anti-Diagonally Flip not supported yet"); +} + +-(CCSprite*) insertTileForGID:(uint32_t)gid at:(CGPoint)pos +{ + CGRect rect = [tileset_ rectForGID:gid]; + rect = CC_RECT_PIXELS_TO_POINTS(rect); + + NSInteger z = pos.x + pos.y * layerSize_.width; + + CCSprite *tile = [self reusedTileWithRect:rect]; + + [self setupTileSprite:tile position:pos withGID:gid]; + // get atlas index NSUInteger indexForZ = [self atlasIndexForNewZ:z]; - + // Optimization: add the quad without adding a child - [self addQuadFromSprite:reusedTile_ quadIndex:indexForZ]; - + [self addQuadFromSprite:tile quadIndex:indexForZ]; + // insert it into the local atlasindex array ccCArrayInsertValueAtIndex(atlasIndexArray_, (void*)z, indexForZ); - + // update possible children CCSprite *sprite; CCARRAY_FOREACH(children_, sprite) { - unsigned int ai = [sprite atlasIndex]; + NSUInteger ai = [sprite atlasIndex]; if( ai >= indexForZ) [sprite setAtlasIndex: ai+1]; } - + tiles_[z] = gid; - - return reusedTile_; + + return tile; } --(CCSprite*) updateTileForGID:(unsigned int)gid at:(CGPoint)pos +-(CCSprite*) updateTileForGID:(uint32_t)gid at:(CGPoint)pos { CGRect rect = [tileset_ rectForGID:gid]; - + rect = CC_RECT_PIXELS_TO_POINTS(rect); + int z = pos.x + pos.y * layerSize_.width; - - if( ! reusedTile_ ) - reusedTile_ = [[CCSprite alloc] initWithBatchNode:self rectInPixels:rect]; - else - [reusedTile_ initWithBatchNode:self rectInPixels:rect]; - - [reusedTile_ setPositionInPixels: [self positionAt:pos]]; - [reusedTile_ setVertexZ: [self vertexZForPos:pos]]; - reusedTile_.anchorPoint = CGPointZero; - [reusedTile_ setOpacity:opacity_]; + + CCSprite *tile = [self reusedTileWithRect:rect]; + + [self setupTileSprite:tile position:pos withGID:gid]; // get atlas index - unsigned int indexForZ = [self atlasIndexForExistantZ:z]; + NSUInteger indexForZ = [self atlasIndexForExistantZ:z]; - [reusedTile_ setAtlasIndex:indexForZ]; - [reusedTile_ setDirty:YES]; - [reusedTile_ updateTransform]; + [tile setAtlasIndex:indexForZ]; + [tile setDirty:YES]; + [tile updateTransform]; tiles_[z] = gid; - - return reusedTile_; + + return tile; } // used only when parsing the map. useless after the map was parsed // since lot's of assumptions are no longer true --(CCSprite*) appendTileForGID:(unsigned int)gid at:(CGPoint)pos +-(CCSprite*) appendTileForGID:(uint32_t)gid at:(CGPoint)pos { CGRect rect = [tileset_ rectForGID:gid]; - + rect = CC_RECT_PIXELS_TO_POINTS(rect); + NSInteger z = pos.x + pos.y * layerSize_.width; - - if( ! reusedTile_ ) - reusedTile_ = [[CCSprite alloc] initWithBatchNode:self rectInPixels:rect]; - else - [reusedTile_ initWithBatchNode:self rectInPixels:rect]; - - [reusedTile_ setPositionInPixels: [self positionAt:pos]]; - [reusedTile_ setVertexZ: [self vertexZForPos:pos]]; - reusedTile_.anchorPoint = CGPointZero; - [reusedTile_ setOpacity:opacity_]; - + + CCSprite *tile = [self reusedTileWithRect:rect]; + + [self setupTileSprite:tile position:pos withGID:gid]; + // optimization: // The difference between appendTileForGID and insertTileforGID is that append is faster, since // it appends the tile at the end of the texture atlas @@ -425,13 +415,13 @@ -(CCSprite*) appendTileForGID:(unsigned int)gid at:(CGPoint)pos // don't add it using the "standard" way. - [self addQuadFromSprite:reusedTile_ quadIndex:indexForZ]; - - + [self addQuadFromSprite:tile quadIndex:indexForZ]; + + // append should be after addQuadFromSprite since it modifies the quantity values ccCArrayInsertValueAtIndex(atlasIndexArray_, (void*)z, indexForZ); - - return reusedTile_; + + return tile; } #pragma mark CCTMXLayer - atlasIndex and Z @@ -445,7 +435,7 @@ -(NSUInteger) atlasIndexForExistantZ:(NSUInteger)z { NSInteger key = z; NSInteger *item = bsearch((void*)&key, (void*)&atlasIndexArray_->arr[0], atlasIndexArray_->num, sizeof(void*), compareInts); - + NSAssert( item, @"TMX atlas index not found. Shall not happen"); NSUInteger index = ((NSInteger)item - (NSInteger)atlasIndexArray_->arr) / sizeof(void*); @@ -460,46 +450,59 @@ -(NSUInteger)atlasIndexForNewZ:(NSUInteger)z NSUInteger val = (NSUInteger) atlasIndexArray_->arr[i]; if( z < val ) break; - } + } return i; } #pragma mark CCTMXLayer - adding / remove tiles +-(void) setTileGID:(uint32_t)gid at:(CGPoint)pos +{ + [self setTileGID:gid at:pos withFlags:NO]; +} --(void) setTileGID:(unsigned int)gid at:(CGPoint)pos +-(void) setTileGID:(uint32_t)gid at:(CGPoint)pos withFlags:(ccTMXTileFlags)flags { NSAssert( pos.x < layerSize_.width && pos.y < layerSize_.height && pos.x >=0 && pos.y >=0, @"TMXLayer: invalid position"); NSAssert( tiles_ && atlasIndexArray_, @"TMXLayer: the tiles map has been released"); NSAssert( gid == 0 || gid >= tileset_.firstGid, @"TMXLayer: invalid gid" ); - unsigned int currentGID = [self tileGIDAt:pos]; + ccTMXTileFlags currentFlags; + uint32_t currentGID = [self tileGIDAt:pos withFlags:¤tFlags]; - if( currentGID != gid ) { - + if (currentGID != gid || currentFlags != flags ) + { + uint32_t gidAndFlags = gid | flags; + // setting gid=0 is equal to remove the tile if( gid == 0 ) [self removeTileAt:pos]; // empty tile. create a new one else if( currentGID == 0 ) - [self insertTileForGID:gid at:pos]; + [self insertTileForGID:gidAndFlags at:pos]; // modifying an existing tile with a non-empty tile else { - unsigned int z = pos.x + pos.y * layerSize_.width; - id sprite = [self getChildByTag:z]; + NSUInteger z = pos.x + pos.y * layerSize_.width; + CCSprite *sprite = (CCSprite*)[self getChildByTag:z]; if( sprite ) { CGRect rect = [tileset_ rectForGID:gid]; - [sprite setTextureRectInPixels:rect rotated:NO untrimmedSize:rect.size]; - tiles_[z] = gid; + rect = CC_RECT_PIXELS_TO_POINTS(rect); + + [sprite setTextureRect:rect rotated:NO untrimmedSize:rect.size]; + + if (flags) + [self setupTileSprite:sprite position:[sprite position] withGID:gidAndFlags]; + + tiles_[z] = gidAndFlags; } else - [self updateTileForGID:gid at:pos]; + [self updateTileForGID:gidAndFlags at:pos]; } } } --(void) addChild: (CCNode*)node z:(int)z tag:(int)tag +-(void) addChild: (CCNode*)node z:(NSInteger)z tag:(NSInteger)tag { NSAssert(NO, @"addChild: is not supported on CCTMXLayer. Instead use setTileGID:at:/tileAt:"); } @@ -511,8 +514,8 @@ -(void) removeChild:(CCSprite*)sprite cleanup:(BOOL)cleanup return; NSAssert( [children_ containsObject:sprite], @"Tile does not belong to TMXLayer"); - - unsigned int atlasIndex = [sprite atlasIndex]; + + NSUInteger atlasIndex = [sprite atlasIndex]; NSUInteger zz = (NSUInteger) atlasIndexArray_->arr[atlasIndex]; tiles_[zz] = 0; ccCArrayRemoveValueAtIndex(atlasIndexArray_, atlasIndex); @@ -524,19 +527,19 @@ -(void) removeTileAt:(CGPoint)pos NSAssert( pos.x < layerSize_.width && pos.y < layerSize_.height && pos.x >=0 && pos.y >=0, @"TMXLayer: invalid position"); NSAssert( tiles_ && atlasIndexArray_, @"TMXLayer: the tiles map has been released"); - unsigned int gid = [self tileGIDAt:pos]; - + uint32_t gid = [self tileGIDAt:pos]; + if( gid ) { - - unsigned int z = pos.x + pos.y * layerSize_.width; - unsigned atlasIndex = [self atlasIndexForExistantZ:z]; - + + NSUInteger z = pos.x + pos.y * layerSize_.width; + NSUInteger atlasIndex = [self atlasIndexForExistantZ:z]; + // remove tile from GID map tiles_[z] = 0; // remove tile from atlas position array ccCArrayRemoveValueAtIndex(atlasIndexArray_, atlasIndex); - + // remove it from sprites and/or texture atlas id sprite = [self getChildByTag:z]; if( sprite ) @@ -545,9 +548,8 @@ -(void) removeTileAt:(CGPoint)pos [textureAtlas_ removeQuadAtIndex:atlasIndex]; // update possible children - CCSprite *sprite; CCARRAY_FOREACH(children_, sprite) { - unsigned int ai = [sprite atlasIndex]; + NSUInteger ai = [sprite atlasIndex]; if( ai >= atlasIndex) { [sprite setAtlasIndex: ai-1]; } @@ -573,7 +575,7 @@ -(CGPoint) calculateLayerOffset:(CGPoint)pos NSAssert(CGPointEqualToPoint(pos, CGPointZero), @"offset for hexagonal map not implemented yet"); break; } - return ret; + return ret; } -(CGPoint) positionAt:(CGPoint)pos @@ -590,6 +592,8 @@ -(CGPoint) positionAt:(CGPoint)pos ret = [self positionForHexAt:pos]; break; } + + ret = CC_POINT_PIXELS_TO_POINTS( ret ); return ret; } @@ -616,7 +620,7 @@ -(CGPoint) positionForHexAt:(CGPoint)pos float diffY = 0; if( (int)pos.x % 2 == 1 ) diffY = -mapTileSize_.height/2 ; - + CGPoint xy = { pos.x * mapTileSize_.width*3/4, (layerSize_.height - pos.y - 1) * mapTileSize_.height + diffY @@ -624,10 +628,10 @@ -(CGPoint) positionForHexAt:(CGPoint)pos return xy; } --(int) vertexZForPos:(CGPoint)pos +-(NSInteger) vertexZForPos:(CGPoint)pos { - int ret = 0; - unsigned int maxVal = 0; + NSInteger ret = 0; + NSUInteger maxVal = 0; if( useAutomaticVertexZ_ ) { switch( layerOrientation_ ) { case CCTMXOrientationIso: @@ -646,23 +650,9 @@ -(int) vertexZForPos:(CGPoint)pos } } else ret = vertexZvalue_; - + return ret; } -#pragma mark CCTMXLayer - draw - --(void) draw -{ - if( useAutomaticVertexZ_ ) { - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, alphaFuncValue_); - } - - [super draw]; - - if( useAutomaticVertexZ_ ) - glDisable(GL_ALPHA_TEST); -} @end diff --git a/Example/libs/cocos2d/CCTMXObjectGroup.h b/Example/libs/cocos2d/CCTMXObjectGroup.h index f2a3f2c..17fa09c 100644 --- a/Example/libs/cocos2d/CCTMXObjectGroup.h +++ b/Example/libs/cocos2d/CCTMXObjectGroup.h @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2010 Ricardo Quesada * Copyright (c) 2010 Neophit - * + * + * Copyright (c) 2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,7 +30,7 @@ * */ -#import "CCSpriteSheet.h" +#import "CCNode.h" @class CCTMXObjectGroup; diff --git a/Example/libs/cocos2d/CCTMXObjectGroup.m b/Example/libs/cocos2d/CCTMXObjectGroup.m index c0c0537..970effa 100644 --- a/Example/libs/cocos2d/CCTMXObjectGroup.m +++ b/Example/libs/cocos2d/CCTMXObjectGroup.m @@ -1,19 +1,21 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2010 Ricardo Quesada * Copyright (c) 2010 Neophit - * + * + * Copyright (c) 2010 Ricardo Quesada + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,6 +32,7 @@ #import "CCTMXObjectGroup.h" #import "CCTMXXMLParser.h" +#import "ccMacros.h" #import "Support/CGPointExtension.h" @@ -57,7 +60,7 @@ -(id) init -(void) dealloc { CCLOGINFO( @"cocos2d: deallocing %@", self ); - + [groupName_ release]; [objects_ release]; [properties_ release]; @@ -75,7 +78,7 @@ -(NSMutableDictionary*) objectNamed:(NSString *)objectName return nil; } --(id) propertyNamed:(NSString *)propertyName +-(id) propertyNamed:(NSString *)propertyName { return [properties_ valueForKey:propertyName]; } diff --git a/Example/libs/cocos2d/CCTMXTiledMap.h b/Example/libs/cocos2d/CCTMXTiledMap.h index 3ae0153..084187c 100644 --- a/Example/libs/cocos2d/CCTMXTiledMap.h +++ b/Example/libs/cocos2d/CCTMXTiledMap.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,8 +28,7 @@ * */ -#import "CCSpriteSheet.h" - +#import "CCNode.h" @class CCTMXLayer; @class CCTMXObjectGroup; @@ -38,16 +38,16 @@ enum { /** Orthogonal orientation */ CCTMXOrientationOrtho, - + /** Hexagonal orientation */ CCTMXOrientationHex, - + /** Isometric orientation */ CCTMXOrientationIso, }; /** CCTMXTiledMap knows how to parse and render a TMX map. - + It adds support for the TMX tiled map format used by http://www.mapeditor.org It supports isometric, hexagonal and orthogonal tiles. It also supports object groups, objects, and properties. @@ -68,14 +68,14 @@ enum - Each object group will be treated as an NSMutableArray - Object class which will contain all the properties in a dictionary - Properties can be assigned to the Map, Layer, Object Group, and Object - + Limitations: - It only supports one tileset per layer. - Embeded images are not supported - It only supports the XML format (the JSON format is not supported) - + Technical description: - Each layer is created using an CCTMXLayer (subclass of CCSpriteSheet). If you have 5 layers, then 5 CCTMXLayer will be created, + Each layer is created using an CCTMXLayer (subclass of CCSpriteBatchNode). If you have 5 layers, then 5 CCTMXLayer will be created, unless the layer visibility is off. In that case, the layer won't be created at all. You can obtain the layers (CCTMXLayer objects) at runtime by: - [map getChildByTag: tag_number]; // 0=1st layer, 1=2nd layer, 2=3rd layer, etc... @@ -84,12 +84,12 @@ enum Each object group is created using a CCTMXObjectGroup which is a subclass of NSMutableArray. You can obtain the object groups at runtime by: - [map objectGroupNamed: name_of_the_object_group]; - + Each object is a CCTMXObject. Each property is stored as a key-value pair in an NSMutableDictionary. You can obtain the properties at runtime by: - + [map propertyNamed: name_of_the_property]; [layer propertyNamed: name_of_the_property]; [objectGroup propertyNamed: name_of_the_property]; @@ -121,20 +121,21 @@ enum /** creates a TMX Tiled Map with a TMX file.*/ +(id) tiledMapWithTMXFile:(NSString*)tmxFile; +/** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ ++(id) tiledMapWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath; + /** initializes a TMX Tiled Map with a TMX file */ -(id) initWithTMXFile:(NSString*)tmxFile; +/** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ +-(id) initWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath; + /** return the TMXLayer for the specific layer */ -(CCTMXLayer*) layerNamed:(NSString *)layerName; /** return the TMXObjectGroup for the secific group */ -(CCTMXObjectGroup*) objectGroupNamed:(NSString *)groupName; -/** return the TMXObjectGroup for the secific group - @deprecated Use map#objectGroupNamed instead - */ --(CCTMXObjectGroup*) groupNamed:(NSString *)groupName DEPRECATED_ATTRIBUTE; - /** return the value for the specific property name */ -(id) propertyNamed:(NSString *)propertyName; diff --git a/Example/libs/cocos2d/CCTMXTiledMap.m b/Example/libs/cocos2d/CCTMXTiledMap.m index 70838a2..0117b2e 100644 --- a/Example/libs/cocos2d/CCTMXTiledMap.m +++ b/Example/libs/cocos2d/CCTMXTiledMap.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,7 +33,6 @@ #import "CCTMXLayer.h" #import "CCTMXObjectGroup.h" #import "CCSprite.h" -#import "CCSpriteSheet.h" #import "CCTextureCache.h" #import "Support/CGPointExtension.h" @@ -43,6 +43,7 @@ @interface CCTMXTiledMap (Private) -(id) parseLayer:(CCTMXLayerInfo*)layer map:(CCTMXMapInfo*)mapInfo; -(CCTMXTilesetInfo*) tilesetForLayer:(CCTMXLayerInfo*)layerInfo map:(CCTMXMapInfo*)mapInfo; +-(void) buildWithMapInfo:(CCTMXMapInfo*)mapInfo; @end @implementation CCTMXTiledMap @@ -57,43 +58,67 @@ +(id) tiledMapWithTMXFile:(NSString*)tmxFile return [[[self alloc] initWithTMXFile:tmxFile] autorelease]; } ++(id) tiledMapWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath +{ + return [[[self alloc] initWithXML:tmxString resourcePath:resourcePath] autorelease]; +} + +-(void) buildWithMapInfo:(CCTMXMapInfo*)mapInfo +{ + mapSize_ = mapInfo.mapSize; + tileSize_ = mapInfo.tileSize; + mapOrientation_ = mapInfo.orientation; + objectGroups_ = [mapInfo.objectGroups retain]; + properties_ = [mapInfo.properties retain]; + tileProperties_ = [mapInfo.tileProperties retain]; + + int idx=0; + + for( CCTMXLayerInfo *layerInfo in mapInfo.layers ) { + + if( layerInfo.visible ) { + CCNode *child = [self parseLayer:layerInfo map:mapInfo]; + [self addChild:child z:idx tag:idx]; + + // update content size with the max size + CGSize childSize = [child contentSize]; + CGSize currentSize = [self contentSize]; + currentSize.width = MAX( currentSize.width, childSize.width ); + currentSize.height = MAX( currentSize.height, childSize.height ); + [self setContentSize:currentSize]; + + idx++; + } + } +} + +-(id) initWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath +{ + if ((self=[super init])) { + + [self setContentSize:CGSizeZero]; + + CCTMXMapInfo *mapInfo = [CCTMXMapInfo formatWithXML:tmxString resourcePath:resourcePath]; + + NSAssert( [mapInfo.tilesets count] != 0, @"TMXTiledMap: Map not found. Please check the filename."); + [self buildWithMapInfo:mapInfo]; + } + + return self; +} + -(id) initWithTMXFile:(NSString*)tmxFile { NSAssert(tmxFile != nil, @"TMXTiledMap: tmx file should not bi nil"); if ((self=[super init])) { - + [self setContentSize:CGSizeZero]; CCTMXMapInfo *mapInfo = [CCTMXMapInfo formatWithTMXFile:tmxFile]; - + NSAssert( [mapInfo.tilesets count] != 0, @"TMXTiledMap: Map not found. Please check the filename."); - - mapSize_ = mapInfo.mapSize; - tileSize_ = mapInfo.tileSize; - mapOrientation_ = mapInfo.orientation; - objectGroups_ = [mapInfo.objectGroups retain]; - properties_ = [mapInfo.properties retain]; - tileProperties_ = [mapInfo.tileProperties retain]; - - int idx=0; - - for( CCTMXLayerInfo *layerInfo in mapInfo.layers ) { - - if( layerInfo.visible ) { - CCNode *child = [self parseLayer:layerInfo map:mapInfo]; - [self addChild:child z:idx tag:idx]; - - // update content size with the max size - CGSize childSize = [child contentSize]; - CGSize currentSize = [self contentSize]; - currentSize.width = MAX( currentSize.width, childSize.width ); - currentSize.height = MAX( currentSize.height, childSize.height ); - [self setContentSize:currentSize]; - - idx++; - } - } + [self buildWithMapInfo:mapInfo]; } return self; @@ -117,51 +142,47 @@ -(id) parseLayer:(CCTMXLayerInfo*)layerInfo map:(CCTMXMapInfo*)mapInfo layerInfo.ownTiles = NO; [layer setupTiles]; - + return layer; } -(CCTMXTilesetInfo*) tilesetForLayer:(CCTMXLayerInfo*)layerInfo map:(CCTMXMapInfo*)mapInfo { - CCTMXTilesetInfo *tileset = nil; - CFByteOrder o = CFByteOrderGetCurrent(); - CGSize size = layerInfo.layerSize; id iter = [mapInfo.tilesets reverseObjectEnumerator]; for( CCTMXTilesetInfo* tileset in iter) { for( unsigned int y = 0; y < size.height; y++ ) { for( unsigned int x = 0; x < size.width; x++ ) { - + unsigned int pos = x + size.width * y; unsigned int gid = layerInfo.tiles[ pos ]; - + // gid are stored in little endian. // if host is big endian, then swap - if( o == CFByteOrderBigEndian ) - gid = CFSwapInt32( gid ); - + gid = CFSwapInt32LittleToHost( gid ); + // XXX: gid == 0 --> empty tile if( gid != 0 ) { - + // Optimization: quick return // if the layer is invalid (more than 1 tileset per layer) an assert will be thrown later - if( gid >= tileset.firstGid ) + if( (gid & kCCFlippedMask) >= tileset.firstGid ) return tileset; } } - } + } } - + // If all the tiles are 0, return empty tileset CCLOG(@"cocos2d: Warning: TMX Layer '%@' has no tiles", layerInfo.name); - return tileset; + return nil; } // public --(CCTMXLayer*) layerNamed:(NSString *)layerName +-(CCTMXLayer*) layerNamed:(NSString *)layerName { CCTMXLayer *layer; CCARRAY_FOREACH(children_, layer) { @@ -169,29 +190,23 @@ -(CCTMXLayer*) layerNamed:(NSString *)layerName if([layer.layerName isEqual:layerName]) return layer; } - + // layer not found return nil; } --(CCTMXObjectGroup*) objectGroupNamed:(NSString *)groupName +-(CCTMXObjectGroup*) objectGroupNamed:(NSString *)groupName { for( CCTMXObjectGroup *objectGroup in objectGroups_ ) { if( [objectGroup.groupName isEqual:groupName] ) return objectGroup; } - + // objectGroup not found return nil; } -// XXX deprecated --(CCTMXObjectGroup*) groupNamed:(NSString *)groupName -{ - return [self objectGroupNamed:groupName]; -} - --(id) propertyNamed:(NSString *)propertyName +-(id) propertyNamed:(NSString *)propertyName { return [properties_ valueForKey:propertyName]; } diff --git a/Example/libs/cocos2d/CCTMXXMLParser.h b/Example/libs/cocos2d/CCTMXXMLParser.h index 5c25a73..91628c5 100644 --- a/Example/libs/cocos2d/CCTMXXMLParser.h +++ b/Example/libs/cocos2d/CCTMXXMLParser.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,15 +35,17 @@ * since the user should not use them. * */ - -#import + #import +#import "ccMacros.h" + enum { TMXLayerAttribNone = 1 << 0, TMXLayerAttribBase64 = 1 << 1, TMXLayerAttribGzip = 1 << 2, + TMXLayerAttribZlib = 1 << 3, }; enum { @@ -54,12 +57,23 @@ enum { TMXPropertyTile }; +typedef enum ccTMXTileFlags_ { + kCCTMXTileHorizontalFlag = 0x80000000, + kCCTMXTileVerticalFlag = 0x40000000, + kCCTMXTileDiagonalFlag = 0x20000000, + + kCCFlipedAll = (kCCTMXTileHorizontalFlag|kCCTMXTileVerticalFlag|kCCTMXTileDiagonalFlag), + kCCFlippedMask = ~(kCCFlipedAll), +} ccTMXTileFlags; + +// Bits on the far end of the 32-bit global tile ID (GID's) are used for tile flags + /* CCTMXLayerInfo contains the information about the layers like: - Layer name - Layer size - Layer opacity at creation time (it can be modified at runtime) - - Whether the layer is visible (if it's not visible, then the CocosNode won't be created) - + - Whether the layer is visible (if it is not visible, then the CCNode won't be created) + This information is obtained from the TMX file. */ @interface CCTMXLayerInfo : NSObject @@ -95,8 +109,8 @@ enum { - size of the tiles - Image used for the tiles - Image size - - This information is obtained from the TMX file. + + This information is obtained from the TMX file. */ @interface CCTMXTilesetInfo : NSObject { @@ -105,10 +119,10 @@ enum { CGSize tileSize_; unsigned int spacing_; unsigned int margin_; - + // filename containing the tiles (should be spritesheet / texture atlas) NSString *sourceImage_; - + // size in pixels of the image CGSize imageSize_; } @@ -127,57 +141,60 @@ enum { - Map orientation (hexagonal, isometric or orthogonal) - Tile size - Map size - + And it also contains: - Layers (an array of TMXLayerInfo objects) - Tilesets (an array of TMXTilesetInfo objects) - ObjectGroups (an array of TMXObjectGroupInfo objects) - + This information is obtained from the TMX file. - + */ -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #if defined(__IPHONE_4_0) @interface CCTMXMapInfo : NSObject #else @interface CCTMXMapInfo : NSObject #endif -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) @interface CCTMXMapInfo : NSObject #endif -{ +{ NSMutableString *currentString; - BOOL storingCharacters; + BOOL storingCharacters; int layerAttribs; int parentElement; unsigned int parentGID_; - + // tmx filename NSString *filename_; + // tmx resource path + NSString *resources_; + // map orientation - int orientation_; - + int orientation_; + // map width & height CGSize mapSize_; - + // tiles width & height CGSize tileSize_; - + // Layers NSMutableArray *layers_; - + // tilesets NSMutableArray *tilesets_; - + // ObjectGroups NSMutableArray *objectGroups_; - + // properties NSMutableDictionary *properties_; - + // tile properties NSMutableDictionary *tileProperties_; } @@ -188,13 +205,22 @@ enum { @property (nonatomic,readwrite,retain) NSMutableArray *layers; @property (nonatomic,readwrite,retain) NSMutableArray *tilesets; @property (nonatomic,readwrite,retain) NSString *filename; +@property (nonatomic,readwrite,retain) NSString *resources; @property (nonatomic,readwrite,retain) NSMutableArray *objectGroups; @property (nonatomic,readwrite,retain) NSMutableDictionary *properties; @property (nonatomic,readwrite,retain) NSMutableDictionary *tileProperties; /** creates a TMX Format with a tmx file */ +(id) formatWithTMXFile:(NSString*)tmxFile; -/** initializes a TMX format witha tmx file */ + +/** creates a TMX Format with an XML string and a TMX resource path */ ++(id) formatWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath; + +/** initializes a TMX format with a tmx file */ -(id) initWithTMXFile:(NSString*)tmxFile; + +/** initializes a TMX format with an XML string and a TMX resource path */ +-(id) initWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath; + @end diff --git a/Example/libs/cocos2d/CCTMXXMLParser.m b/Example/libs/cocos2d/CCTMXXMLParser.m index 550f537..daf3d1b 100644 --- a/Example/libs/cocos2d/CCTMXXMLParser.m +++ b/Example/libs/cocos2d/CCTMXXMLParser.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -64,7 +65,7 @@ -(id) init - (void) dealloc { CCLOGINFO(@"cocos2d: deallocing %@",self); - + [name_ release]; [properties_ release]; @@ -95,15 +96,16 @@ -(CGRect) rectForGID:(unsigned int)gid { CGRect rect; rect.size = tileSize_; - + + gid &= kCCFlippedMask; gid = gid - firstGid_; - + int max_x = (imageSize_.width - margin_*2 + spacing_) / (tileSize_.width + spacing_); // int max_y = (imageSize.height - margin*2 + spacing) / (tileSize.height + spacing); - + rect.origin.x = (gid % max_x) * (tileSize_.width + spacing_) + margin_; rect.origin.y = (gid / max_x) * (tileSize_.height + spacing_) + margin_; - + return rect; } @end @@ -114,12 +116,15 @@ -(CGRect) rectForGID:(unsigned int)gid @interface CCTMXMapInfo (Private) /* initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ -(void) parseXMLFile:(NSString *)xmlFilename; +/* initalises parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ +- (void) parseXMLString:(NSString *)xmlString; +/* handles the work of parsing for parseXMLFile: and parseXMLString: */ +- (NSError*) parseXMLData:(NSData*)data; @end - @implementation CCTMXMapInfo -@synthesize orientation = orientation_, mapSize = mapSize_, layers = layers_, tilesets = tilesets_, tileSize = tileSize_, filename = filename_, objectGroups = objectGroups_, properties = properties_; +@synthesize orientation = orientation_, mapSize = mapSize_, layers = layers_, tilesets = tilesets_, tileSize = tileSize_, filename = filename_, resources = resources_, objectGroups = objectGroups_, properties = properties_; @synthesize tileProperties = tileProperties_; +(id) formatWithTMXFile:(NSString*)tmxFile @@ -127,33 +132,53 @@ +(id) formatWithTMXFile:(NSString*)tmxFile return [[[self alloc] initWithTMXFile:tmxFile] autorelease]; } ++(id) formatWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath +{ + return [[[self alloc] initWithXML:tmxString resourcePath:resourcePath] autorelease]; +} + +- (void) internalInit:(NSString*)tmxFileName resourcePath:(NSString*)resourcePath +{ + self.tilesets = [NSMutableArray arrayWithCapacity:4]; + self.layers = [NSMutableArray arrayWithCapacity:4]; + self.filename = tmxFileName; + self.resources = resourcePath; + self.objectGroups = [NSMutableArray arrayWithCapacity:4]; + self.properties = [NSMutableDictionary dictionaryWithCapacity:5]; + self.tileProperties = [NSMutableDictionary dictionaryWithCapacity:5]; + + // tmp vars + currentString = [[NSMutableString alloc] initWithCapacity:1024]; + storingCharacters = NO; + layerAttribs = TMXLayerAttribNone; + parentElement = TMXPropertyNone; +} + +-(id) initWithXML:(NSString *)tmxString resourcePath:(NSString*)resourcePath +{ + if( (self=[super init])) { + [self internalInit:nil resourcePath:resourcePath]; + [self parseXMLString:tmxString]; + } + return self; +} + -(id) initWithTMXFile:(NSString*)tmxFile { if( (self=[super init])) { - - self.tilesets = [NSMutableArray arrayWithCapacity:4]; - self.layers = [NSMutableArray arrayWithCapacity:4]; - self.filename = tmxFile; - self.objectGroups = [NSMutableArray arrayWithCapacity:4]; - self.properties = [NSMutableDictionary dictionaryWithCapacity:5]; - self.tileProperties = [NSMutableDictionary dictionaryWithCapacity:5]; - - // tmp vars - currentString = [[NSMutableString alloc] initWithCapacity:1024]; - storingCharacters = NO; - layerAttribs = TMXLayerAttribNone; - parentElement = TMXPropertyNone; - - [self parseXMLFile:filename_]; + [self internalInit:tmxFile resourcePath:nil]; + [self parseXMLFile:filename_]; } return self; } + - (void) dealloc { CCLOGINFO(@"cocos2d: deallocing %@", self); [tilesets_ release]; [layers_ release]; [filename_ release]; + [resources_ release]; [currentString release]; [objectGroups_ release]; [properties_ release]; @@ -161,10 +186,9 @@ - (void) dealloc [super dealloc]; } -- (void) parseXMLFile:(NSString *)xmlFilename +- (NSError*) parseXMLData:(NSData*)data { - NSURL *url = [NSURL fileURLWithPath:[CCFileUtils fullPathFromRelativePath:xmlFilename] ]; - NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url]; + NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:data] autorelease]; // we'll do the parsing [parser setDelegate:self]; @@ -173,19 +197,34 @@ - (void) parseXMLFile:(NSString *)xmlFilename [parser setShouldResolveExternalEntities:NO]; [parser parse]; - NSAssert1( ! [parser parserError], @"Error parsing file: %@.", xmlFilename ); + return [parser parserError]; +} + +- (void) parseXMLString:(NSString *)xmlString +{ + NSData* data = [xmlString dataUsingEncoding:NSUTF8StringEncoding]; + NSError* err = [self parseXMLData:data]; + (void)err; + NSAssert1( !err, @"Error parsing TMX data: %@.", [NSString stringWithCharacters:[data bytes] length:[data length]] ); +} - [parser release]; +- (void) parseXMLFile:(NSString *)xmlFilename +{ + NSURL *url = [NSURL fileURLWithPath:[CCFileUtils fullPathFromRelativePath:xmlFilename] ]; + NSData *data = [NSData dataWithContentsOfURL:url]; + NSError* err = [self parseXMLData:data]; + (void)err; + NSAssert3(!err, @"Error parsing TMX file: %@, %@ (%d).", xmlFilename, [err localizedDescription], [err code]); } // the XML parser calls here with all the elements -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict -{ +{ if([elementName isEqualToString:@"map"]) { - NSString *version = [attributeDict valueForKey:@"version"]; + NSString *version = [attributeDict objectForKey:@"version"]; if( ! [version isEqualToString:@"1.0"] ) CCLOG(@"cocos2d: TMXFormat: Unsupported TMX version: %@", version); - NSString *orientationStr = [attributeDict valueForKey:@"orientation"]; + NSString *orientationStr = [attributeDict objectForKey:@"orientation"]; if( [orientationStr isEqualToString:@"orthogonal"]) orientation_ = CCTMXOrientationOrtho; else if ( [orientationStr isEqualToString:@"isometric"]) @@ -195,35 +234,37 @@ -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName name else CCLOG(@"cocos2d: TMXFomat: Unsupported orientation: %@", orientation_); - mapSize_.width = [[attributeDict valueForKey:@"width"] intValue]; - mapSize_.height = [[attributeDict valueForKey:@"height"] intValue]; - tileSize_.width = [[attributeDict valueForKey:@"tilewidth"] intValue]; - tileSize_.height = [[attributeDict valueForKey:@"tileheight"] intValue]; + mapSize_.width = [[attributeDict objectForKey:@"width"] intValue]; + mapSize_.height = [[attributeDict objectForKey:@"height"] intValue]; + tileSize_.width = [[attributeDict objectForKey:@"tilewidth"] intValue]; + tileSize_.height = [[attributeDict objectForKey:@"tileheight"] intValue]; // The parent element is now "map" parentElement = TMXPropertyMap; } else if([elementName isEqualToString:@"tileset"]) { - + // If this is an external tileset then start parsing that - NSString *externalTilesetFilename = [attributeDict valueForKey:@"source"]; + NSString *externalTilesetFilename = [attributeDict objectForKey:@"source"]; if (externalTilesetFilename) { // Tileset file will be relative to the map file. So we need to convert it to an absolute path NSString *dir = [filename_ stringByDeletingLastPathComponent]; // Directory of map file + if (!dir) + dir = resources_; externalTilesetFilename = [dir stringByAppendingPathComponent:externalTilesetFilename]; // Append path to tileset file - + [self parseXMLFile:externalTilesetFilename]; } else { - + CCTMXTilesetInfo *tileset = [CCTMXTilesetInfo new]; - tileset.name = [attributeDict valueForKey:@"name"]; - tileset.firstGid = [[attributeDict valueForKey:@"firstgid"] intValue]; - tileset.spacing = [[attributeDict valueForKey:@"spacing"] intValue]; - tileset.margin = [[attributeDict valueForKey:@"margin"] intValue]; + tileset.name = [attributeDict objectForKey:@"name"]; + tileset.firstGid = [[attributeDict objectForKey:@"firstgid"] intValue]; + tileset.spacing = [[attributeDict objectForKey:@"spacing"] intValue]; + tileset.margin = [[attributeDict objectForKey:@"margin"] intValue]; CGSize s; - s.width = [[attributeDict valueForKey:@"tilewidth"] intValue]; - s.height = [[attributeDict valueForKey:@"tileheight"] intValue]; + s.width = [[attributeDict objectForKey:@"tilewidth"] intValue]; + s.height = [[attributeDict objectForKey:@"tileheight"] intValue]; tileset.tileSize = s; - + [tilesets_ addObject:tileset]; [tileset release]; } @@ -231,149 +272,180 @@ -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName name }else if([elementName isEqualToString:@"tile"]){ CCTMXTilesetInfo* info = [tilesets_ lastObject]; NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:3]; - parentGID_ = [info firstGid] + [[attributeDict valueForKey:@"id"] intValue]; + parentGID_ = [info firstGid] + [[attributeDict objectForKey:@"id"] intValue]; [tileProperties_ setObject:dict forKey:[NSNumber numberWithInt:parentGID_]]; - + parentElement = TMXPropertyTile; - + }else if([elementName isEqualToString:@"layer"]) { CCTMXLayerInfo *layer = [CCTMXLayerInfo new]; - layer.name = [attributeDict valueForKey:@"name"]; - + layer.name = [attributeDict objectForKey:@"name"]; + CGSize s; - s.width = [[attributeDict valueForKey:@"width"] intValue]; - s.height = [[attributeDict valueForKey:@"height"] intValue]; + s.width = [[attributeDict objectForKey:@"width"] intValue]; + s.height = [[attributeDict objectForKey:@"height"] intValue]; layer.layerSize = s; - - layer.visible = ![[attributeDict valueForKey:@"visible"] isEqualToString:@"0"]; - - if( [attributeDict valueForKey:@"opacity"] ) - layer.opacity = 255 * [[attributeDict valueForKey:@"opacity"] floatValue]; + + layer.visible = ![[attributeDict objectForKey:@"visible"] isEqualToString:@"0"]; + + if( [attributeDict objectForKey:@"opacity"] ) + layer.opacity = 255 * [[attributeDict objectForKey:@"opacity"] floatValue]; else layer.opacity = 255; - - int x = [[attributeDict valueForKey:@"x"] intValue]; - int y = [[attributeDict valueForKey:@"y"] intValue]; + + int x = [[attributeDict objectForKey:@"x"] intValue]; + int y = [[attributeDict objectForKey:@"y"] intValue]; layer.offset = ccp(x,y); - + [layers_ addObject:layer]; [layer release]; - + // The parent element is now "layer" parentElement = TMXPropertyLayer; - + } else if([elementName isEqualToString:@"objectgroup"]) { - + CCTMXObjectGroup *objectGroup = [[CCTMXObjectGroup alloc] init]; - objectGroup.groupName = [attributeDict valueForKey:@"name"]; + objectGroup.groupName = [attributeDict objectForKey:@"name"]; CGPoint positionOffset; - positionOffset.x = [[attributeDict valueForKey:@"x"] intValue] * tileSize_.width; - positionOffset.y = [[attributeDict valueForKey:@"y"] intValue] * tileSize_.height; + positionOffset.x = [[attributeDict objectForKey:@"x"] intValue] * tileSize_.width; + positionOffset.y = [[attributeDict objectForKey:@"y"] intValue] * tileSize_.height; objectGroup.positionOffset = positionOffset; - + [objectGroups_ addObject:objectGroup]; [objectGroup release]; - + // The parent element is now "objectgroup" parentElement = TMXPropertyObjectGroup; - + } else if([elementName isEqualToString:@"image"]) { CCTMXTilesetInfo *tileset = [tilesets_ lastObject]; - + // build full path - NSString *imagename = [attributeDict valueForKey:@"source"]; - NSString *path = [filename_ stringByDeletingLastPathComponent]; + NSString *imagename = [attributeDict objectForKey:@"source"]; + NSString *path = [filename_ stringByDeletingLastPathComponent]; + if (!path) + path = resources_; tileset.sourceImage = [path stringByAppendingPathComponent:imagename]; } else if([elementName isEqualToString:@"data"]) { - NSString *encoding = [attributeDict valueForKey:@"encoding"]; - NSString *compression = [attributeDict valueForKey:@"compression"]; - + NSString *encoding = [attributeDict objectForKey:@"encoding"]; + NSString *compression = [attributeDict objectForKey:@"compression"]; + if( [encoding isEqualToString:@"base64"] ) { layerAttribs |= TMXLayerAttribBase64; storingCharacters = YES; - + if( [compression isEqualToString:@"gzip"] ) layerAttribs |= TMXLayerAttribGzip; - - NSAssert( !compression || [compression isEqualToString:@"gzip"], @"TMX: unsupported compression method" ); + + else if( [compression isEqualToString:@"zlib"] ) + layerAttribs |= TMXLayerAttribZlib; + + NSAssert( !compression || [compression isEqualToString:@"gzip"] || [compression isEqualToString:@"zlib"], @"TMX: unsupported compression method" ); } - - NSAssert( layerAttribs != TMXLayerAttribNone, @"TMX tile map: Only base64 and/or gzip maps are supported" ); - + + NSAssert( layerAttribs != TMXLayerAttribNone, @"TMX tile map: Only base64 and/or gzip/zlib maps are supported" ); + } else if([elementName isEqualToString:@"object"]) { - + CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; - + // The value for "type" was blank or not a valid class name // Create an instance of TMXObjectInfo to store the object and its properties - NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:5]; + NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:10]; + + // Parse everything automatically + NSArray *array = [NSArray arrayWithObjects:@"name", @"type", @"width", @"height", @"gid", nil]; + for( NSObject *key in array ) { + NSObject *obj = [attributeDict objectForKey:key]; + if( obj ) + [dict setObject:obj forKey:key]; + } - // Set the name of the object to the value for "name" - [dict setValue:[attributeDict valueForKey:@"name"] forKey:@"name"]; + // But X and Y since they need special treatment + // X + NSString *value = [attributeDict objectForKey:@"x"]; + if( value ) { + int x = [value intValue] + objectGroup.positionOffset.x; + [dict setObject:[NSNumber numberWithInt:x] forKey:@"x"]; + } - // Assign all the attributes as key/name pairs in the properties dictionary - [dict setValue:[attributeDict valueForKey:@"type"] forKey:@"type"]; - int x = [[attributeDict valueForKey:@"x"] intValue] + objectGroup.positionOffset.x; - [dict setValue:[NSNumber numberWithInt:x] forKey:@"x"]; - int y = [[attributeDict valueForKey:@"y"] intValue] + objectGroup.positionOffset.y; - // Correct y position. (Tiled uses Flipped, cocos2d uses Standard) - y = (mapSize_.height * tileSize_.height) - y - [[attributeDict valueForKey:@"height"] intValue]; - [dict setValue:[NSNumber numberWithInt:y] forKey:@"y"]; - [dict setValue:[attributeDict valueForKey:@"width"] forKey:@"width"]; - [dict setValue:[attributeDict valueForKey:@"height"] forKey:@"height"]; + // Y + value = [attributeDict objectForKey:@"y"]; + if( value ) { + int y = [value intValue] + objectGroup.positionOffset.y; + + // Correct y position. (Tiled uses Flipped, cocos2d uses Standard) + y = (mapSize_.height * tileSize_.height) - y - [[attributeDict objectForKey:@"height"] intValue]; + [dict setObject:[NSNumber numberWithInt:y] forKey:@"y"]; + } // Add the object to the objectGroup [[objectGroup objects] addObject:dict]; [dict release]; - + // The parent element is now "object" parentElement = TMXPropertyObject; - + } else if([elementName isEqualToString:@"property"]) { - + if ( parentElement == TMXPropertyNone ) { - + CCLOG( @"TMX tile map: Parent element is unsupported. Cannot add property named '%@' with value '%@'", - [attributeDict valueForKey:@"name"], [attributeDict valueForKey:@"value"] ); - + [attributeDict objectForKey:@"name"], [attributeDict objectForKey:@"value"] ); + } else if ( parentElement == TMXPropertyMap ) { - + // The parent element is the map - [properties_ setValue:[attributeDict valueForKey:@"value"] forKey:[attributeDict valueForKey:@"name"]]; - + [properties_ setObject:[attributeDict objectForKey:@"value"] forKey:[attributeDict objectForKey:@"name"]]; + } else if ( parentElement == TMXPropertyLayer ) { - + // The parent element is the last layer CCTMXLayerInfo *layer = [layers_ lastObject]; // Add the property to the layer - [[layer properties] setValue:[attributeDict valueForKey:@"value"] forKey:[attributeDict valueForKey:@"name"]]; - + [[layer properties] setObject:[attributeDict objectForKey:@"value"] forKey:[attributeDict objectForKey:@"name"]]; + } else if ( parentElement == TMXPropertyObjectGroup ) { - + // The parent element is the last object group CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; - [[objectGroup properties] setValue:[attributeDict valueForKey:@"value"] forKey:[attributeDict valueForKey:@"name"]]; - + [[objectGroup properties] setObject:[attributeDict objectForKey:@"value"] forKey:[attributeDict objectForKey:@"name"]]; + } else if ( parentElement == TMXPropertyObject ) { - + // The parent element is the last object CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; NSMutableDictionary *dict = [[objectGroup objects] lastObject]; - - NSString *propertyName = [attributeDict valueForKey:@"name"]; - NSString *propertyValue = [attributeDict valueForKey:@"value"]; - [dict setValue:propertyValue forKey:propertyName]; + NSString *propertyName = [attributeDict objectForKey:@"name"]; + NSString *propertyValue = [attributeDict objectForKey:@"value"]; + + [dict setObject:propertyValue forKey:propertyName]; + } else if ( parentElement == TMXPropertyTile ) { - + NSMutableDictionary* dict = [tileProperties_ objectForKey:[NSNumber numberWithInt:parentGID_]]; - NSString *propertyName = [attributeDict valueForKey:@"name"]; - NSString *propertyValue = [attributeDict valueForKey:@"value"]; + NSString *propertyName = [attributeDict objectForKey:@"name"]; + NSString *propertyValue = [attributeDict objectForKey:@"value"]; [dict setObject:propertyValue forKey:propertyName]; - } + + } else if ([elementName isEqualToString:@"polygon"]) { + + // find parent object's dict and add polygon-points to it + CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; + NSMutableDictionary *dict = [[objectGroup objects] lastObject]; + [dict setObject:[attributeDict objectForKey:@"points"] forKey:@"polygonPoints"]; + + } else if ([elementName isEqualToString:@"polyline"]) { + + // find parent object's dict and add polyline-points to it + CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; + NSMutableDictionary *dict = [[objectGroup objects] lastObject]; + [dict setObject:[attributeDict objectForKey:@"points"] forKey:@"polylinePoints"]; } } @@ -383,44 +455,51 @@ - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName names if([elementName isEqualToString:@"data"] && layerAttribs&TMXLayerAttribBase64) { storingCharacters = NO; - + CCTMXLayerInfo *layer = [layers_ lastObject]; - + unsigned char *buffer; - len = base64Decode((unsigned char*)[currentString UTF8String], [currentString length], &buffer); + len = base64Decode((unsigned char*)[currentString UTF8String], (unsigned int) [currentString length], &buffer); if( ! buffer ) { CCLOG(@"cocos2d: TiledMap: decode data error"); return; } - - if( layerAttribs & TMXLayerAttribGzip ) { + + if( layerAttribs & (TMXLayerAttribGzip | TMXLayerAttribZlib) ) { unsigned char *deflated; - ccInflateMemory(buffer, len, &deflated); + CGSize s = [layer layerSize]; + int sizeHint = s.width * s.height * sizeof(uint32_t); + + int inflatedLen = ccInflateMemoryWithHint(buffer, len, &deflated, sizeHint); + NSAssert( inflatedLen == sizeHint, @"CCTMXXMLParser: Hint failed!"); + + inflatedLen = (int)&inflatedLen; // XXX: to avoid warings in compiler + free( buffer ); - + if( ! deflated ) { CCLOG(@"cocos2d: TiledMap: inflate data error"); return; } - + layer.tiles = (unsigned int*) deflated; } else layer.tiles = (unsigned int*) buffer; - + [currentString setString:@""]; - + } else if ([elementName isEqualToString:@"map"]) { // The map element has ended parentElement = TMXPropertyNone; - + } else if ([elementName isEqualToString:@"layer"]) { // The layer element has ended parentElement = TMXPropertyNone; - + } else if ([elementName isEqualToString:@"objectgroup"]) { // The objectgroup element has ended parentElement = TMXPropertyNone; - + } else if ([elementName isEqualToString:@"object"]) { // The object element has ended parentElement = TMXPropertyNone; diff --git a/Example/libs/cocos2d/CCTexture2D.h b/Example/libs/cocos2d/CCTexture2D.h index 7f606f5..e8101fd 100644 --- a/Example/libs/cocos2d/CCTexture2D.h +++ b/Example/libs/cocos2d/CCTexture2D.h @@ -60,14 +60,11 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. */ -#import - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#import // for UIImage -#endif - #import // for NSObject +#import "ccTypes.h" +#import "ccMacros.h" + #import "Platforms/CCGL.h" // OpenGL stuff #import "Platforms/CCNS.h" // Next-Step stuff @@ -82,32 +79,34 @@ typedef enum { kCCTexture2DPixelFormat_RGBA8888, //! 16-bit texture without Alpha channel kCCTexture2DPixelFormat_RGB565, + //! 24-bit texture without Alpha channel + kCCTexture2DPixelFormat_RGB888, //! 8-bit textures used as masks kCCTexture2DPixelFormat_A8, + //! 8-bit intensity texture + kCCTexture2DPixelFormat_I8, + //! 16-bit textures used as masks + kCCTexture2DPixelFormat_AI88, //! 16-bit textures: RGBA4444 kCCTexture2DPixelFormat_RGBA4444, //! 16-bit textures: RGB5A1 - kCCTexture2DPixelFormat_RGB5A1, + kCCTexture2DPixelFormat_RGB5A1, + //! 4-bit PVRTC-compressed texture: PVRTC4 + kCCTexture2DPixelFormat_PVRTC4, + //! 2-bit PVRTC-compressed texture: PVRTC2 + kCCTexture2DPixelFormat_PVRTC2, //! Default texture format: RGBA8888 kCCTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_RGBA8888, - // backward compatibility stuff - kTexture2DPixelFormat_Automatic = kCCTexture2DPixelFormat_Automatic, - kTexture2DPixelFormat_RGBA8888 = kCCTexture2DPixelFormat_RGBA8888, - kTexture2DPixelFormat_RGB565 = kCCTexture2DPixelFormat_RGB565, - kTexture2DPixelFormat_A8 = kCCTexture2DPixelFormat_A8, - kTexture2DPixelFormat_RGBA4444 = kCCTexture2DPixelFormat_RGBA4444, - kTexture2DPixelFormat_RGB5A1 = kCCTexture2DPixelFormat_RGB5A1, - kTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_Default - } CCTexture2DPixelFormat; -//CLASS INTERFACES: + +@class CCGLProgram; /** CCTexture2D class. * This class allows to easily create OpenGL 2D textures from images, text or raw data. - * The created CCTexture2D object will always have power-of-two dimensions. + * The created CCTexture2D object will always have power-of-two dimensions. * Depending on how you create the CCTexture2D object, the actual image area of the texture might be smaller than the texture dimensions i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0). * Be aware that the content of the generated textures will be upside-down! */ @@ -121,6 +120,14 @@ typedef enum { GLfloat maxS_, maxT_; BOOL hasPremultipliedAlpha_; + +#ifdef __CC_PLATFORM_IOS + ccResolutionType resolutionType_; +#endif + + // needed for drawAtRect, drawInPoint + CCGLProgram *shaderProgram_; + } /** Intializes with a texture2d with data */ - (id) initWithData:(const void*)data pixelFormat:(CCTexture2DPixelFormat)pixelFormat pixelsWide:(NSUInteger)width pixelsHigh:(NSUInteger)height contentSize:(CGSize)size; @@ -149,8 +156,25 @@ typedef enum { /** whether or not the texture has their Alpha premultiplied */ @property(nonatomic,readonly) BOOL hasPremultipliedAlpha; +/** shader program used by drawAtPoint and drawInRect */ +@property(nonatomic,readwrite,retain) CCGLProgram *shaderProgram; + +#ifdef __CC_PLATFORM_IOS +/** Returns the resolution type of the texture. + Is it a RetinaDisplay texture, an iPad texture or an standard texture ? + Only valid on iOS. Not valid on OS X. + + Should be a readonly property. It is readwrite as a hack. + + @since v1.1 + */ +@property (nonatomic, readwrite) ccResolutionType resolutionType; +#endif + /** returns the content size of the texture in points */ -(CGSize) contentSize; + + @end /** @@ -169,11 +193,11 @@ Extensions to make it easy to create a CCTexture2D object from an image file. Note that RGBA type textures will have their alpha premultiplied - use the blending mode (GL_ONE, GL_ONE_MINUS_SRC_ALPHA). */ @interface CCTexture2D (Image) -/** Initializes a texture from a UIImage object */ -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -- (id) initWithImage:(UIImage *)uiImage; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) -- (id) initWithImage:(CGImageRef)cgImage; +/** Initializes a texture from a CGImage object */ +#ifdef __CC_PLATFORM_IOS +- (id) initWithCGImage:(CGImageRef)cgImage resolutionType:(ccResolutionType)resolution; +#elif defined(__CC_PLATFORM_MAC) +- (id) initWithCGImage:(CGImageRef)cgImage; #endif @end @@ -182,6 +206,13 @@ Extensions to make it easy to create a CCTexture2D object from a string of text. Note that the generated textures are of type A8 - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). */ @interface CCTexture2D (Text) +/** Initializes a texture from a string with dimensions, alignment, line break mode, font name and font size + Supported lineBreakModes: + - iOS: all UILineBreakMode supported modes + - Mac: Only NSLineBreakByWordWrapping is supported. + @since v1.0 + */ +- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size; /** Initializes a texture from a string with dimensions, alignment, font name and font size */ - (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size; /** Initializes a texture from a string with font name and font size */ @@ -194,15 +225,8 @@ Note that the generated textures are of type A8 - use the blending mode (GL_SRC_ Note that the generated textures don't have their alpha premultiplied - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). */ @interface CCTexture2D (PVRSupport) -/** Initializes a texture from a PVR Texture Compressed (PVRTC) buffer - * - * IMPORTANT: This method is only defined on iOS. It is not supported on the Mac version. - */ -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED --(id) initWithPVRTCData: (const void*)data level:(int)level bpp:(int)bpp hasAlpha:(BOOL)hasAlpha length:(int)length; -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED /** Initializes a texture from a PVR file. - + Supported PVR formats: - BGRA 8888 - RGBA 8888 @@ -214,21 +238,21 @@ Note that the generated textures are of type A8 - use the blending mode (GL_SRC_ - AI 8 - PVRTC 2BPP - PVRTC 4BPP - + By default PVR images are treated as if they alpha channel is NOT premultiplied. You can override this behavior with this class method: - PVRImagesHavePremultipliedAlpha:(BOOL)haveAlphaPremultiplied; - + IMPORTANT: This method is only defined on iOS. It is not supported on the Mac version. - + */ -(id) initWithPVRFile: (NSString*) file; /** treats (or not) PVR files as if they have alpha premultiplied. Since it is impossible to know at runtime if the PVR images have the alpha channel premultiplied, it is possible load them as if they have (or not) the alpha channel premultiplied. - + By default it is disabled. - + @since v0.99.5 */ +(void) PVRImagesHavePremultipliedAlpha:(BOOL)haveAlphaPremultiplied; @@ -262,7 +286,7 @@ typedef struct _ccTexParams { /** sets alias texture parameters: - GL_TEXTURE_MIN_FILTER = GL_NEAREST - GL_TEXTURE_MAG_FILTER = GL_NEAREST - + @since v0.8 */ - (void) setAliasTexParameters; @@ -278,20 +302,21 @@ typedef struct _ccTexParams { @end @interface CCTexture2D (PixelFormat) -/** sets the default pixel format for UIImages that contains alpha channel. - If the UIImage contains alpha channel, then the options are: +/** sets the default pixel format for CGImages that contains alpha channel. + If the CGImage contains alpha channel, then the options are: - generate 32-bit textures: kCCTexture2DPixelFormat_RGBA8888 (default one) - generate 16-bit textures: kCCTexture2DPixelFormat_RGBA4444 - generate 16-bit textures: kCCTexture2DPixelFormat_RGB5A1 - - generate 16-bit textures: kCCTexture2DPixelFormat_RGB565 + - generate 24-bit textures: kCCTexture2DPixelFormat_RGB888 (no alpha) + - generate 16-bit textures: kCCTexture2DPixelFormat_RGB565 (no alpha) - generate 8-bit textures: kCCTexture2DPixelFormat_A8 (only use it if you use just 1 color) How does it work ? - If the image is an RGBA (with Alpha) then the default pixel format will be used (it can be a 8-bit, 16-bit or 32-bit texture) - - If the image is an RGB (without Alpha) then an RGB565 texture will be used (16-bit texture) - + - If the image is an RGB (without Alpha) then RGB888 (24-bit) or RGB565 texture will be used (16-bit texture) depending on the bpp of the orignal image + This parameter is not valid for PVR images. - + @since v0.8 */ +(void) setDefaultAlphaPixelFormat:(CCTexture2DPixelFormat)format; @@ -300,6 +325,11 @@ typedef struct _ccTexParams { @since v0.8 */ +(CCTexture2DPixelFormat) defaultAlphaPixelFormat; + +/** returns the bits-per-pixel of the in-memory OpenGL texture + @since v1.0 + */ +-(NSUInteger) bitsPerPixelForFormat; @end diff --git a/Example/libs/cocos2d/CCTexture2D.m b/Example/libs/cocos2d/CCTexture2D.m index 4fe1568..8b63f1d 100644 --- a/Example/libs/cocos2d/CCTexture2D.m +++ b/Example/libs/cocos2d/CCTexture2D.m @@ -1,97 +1,95 @@ /* -===== IMPORTANT ===== - -This is sample code demonstrating API, technology or techniques in development. -Although this sample code has been reviewed for technical accuracy, it is not -final. Apple is supplying this information to help you plan for the adoption of -the technologies and programming interfaces described herein. This information -is subject to change, and software implemented based on this sample code should -be tested with final operating system software and final documentation. Newer -versions of this sample code may be provided with future seeds of the API or -technology. For information about updates to this and other developer -documentation, view the New & Updated sidebars in subsequent documentationd -seeds. - -===================== - -File: Texture2D.m -Abstract: Creates OpenGL 2D textures from images or text. - -Version: 1.6 - -Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. -("Apple") in consideration of your agreement to the following terms, and your -use, installation, modification or redistribution of this Apple software -constitutes acceptance of these terms. If you do not agree with these terms, -please do not use, install, modify or redistribute this Apple software. - -In consideration of your agreement to abide by the following terms, and subject -to these terms, Apple grants you a personal, non-exclusive license, under -Apple's copyrights in this original Apple software (the "Apple Software"), to -use, reproduce, modify and redistribute the Apple Software, with or without -modifications, in source and/or binary forms; provided that if you redistribute -the Apple Software in its entirety and without modifications, you must retain -this notice and the following text and disclaimers in all such redistributions -of the Apple Software. -Neither the name, trademarks, service marks or logos of Apple Inc. may be used -to endorse or promote products derived from the Apple Software without specific -prior written permission from Apple. Except as expressly stated in this notice, -no other rights or licenses, express or implied, are granted by Apple herein, -including but not limited to any patent rights that may be infringed by your -derivative works or by other works in which the Apple Software may be -incorporated. - -The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN -COMBINATION WITH YOUR PRODUCTS. - -IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR -DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF -CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF -APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright (C) 2008 Apple Inc. All Rights Reserved. - -*/ + ===== IMPORTANT ===== + + This is sample code demonstrating API, technology or techniques in development. + Although this sample code has been reviewed for technical accuracy, it is not + final. Apple is supplying this information to help you plan for the adoption of + the technologies and programming interfaces described herein. This information + is subject to change, and software implemented based on this sample code should + be tested with final operating system software and final documentation. Newer + versions of this sample code may be provided with future seeds of the API or + technology. For information about updates to this and other developer + documentation, view the New & Updated sidebars in subsequent documentationd + seeds. + + ===================== + + File: Texture2D.m + Abstract: Creates OpenGL 2D textures from images or text. + + Version: 1.6 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under + Apple's copyrights in this original Apple software (the "Apple Software"), to + use, reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions + of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may be used + to endorse or promote products derived from the Apple Software without specific + prior written permission from Apple. Except as expressly stated in this notice, + no other rights or licenses, express or implied, are granted by Apple herein, + including but not limited to any patent rights that may be infringed by your + derivative works or by other works in which the Apple Software may be + incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR + DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF + CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF + APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2008 Apple Inc. All Rights Reserved. + + */ /* * Support for RGBA_4_4_4_4 and RGBA_5_5_5_1 was copied from: * https://devforums.apple.com/message/37855#37855 by a1studmuffin */ - -#import +/* + * Added many additions for cocos2d + */ #import "Platforms/CCGL.h" #import "Platforms/CCNS.h" - #import "CCTexture2D.h" #import "ccConfig.h" #import "ccMacros.h" #import "CCConfiguration.h" -#import "Support/ccUtils.h" #import "CCTexturePVR.h" +#import "CCGLProgram.h" +#import "ccGLStateCache.h" +#import "CCShaderCache.h" +#import "CCDirector.h" -#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && CC_FONT_LABEL_SUPPORT -// FontLabel support -#import "FontManager.h" -#import "FontLabelStringDrawing.h" -#endif// CC_FONT_LABEL_SUPPORT - +#import "Support/ccUtils.h" +#import "Support/CCFileUtils.h" -// For Labels use 32-bit textures on iPhone 3GS / iPads since A8 textures are very slow -#if defined(__ARM_NEON__) && CC_USE_RGBA32_LABELS_ON_NEON_ARCH -#define USE_TEXT_WITH_A8_TEXTURES 0 +#if CC_USE_LA88_LABELS +#define LABEL_PIXEL_FORMAT kCCTexture2DPixelFormat_AI88 #else -#define USE_TEXT_WITH_A8_TEXTURES 1 +#define LABEL_PIXEL_FORMAT kCCTexture2DPixelFormat_A8 #endif //CLASS IMPLEMENTATIONS: @@ -108,37 +106,50 @@ @implementation CCTexture2D @synthesize contentSizeInPixels = size_, pixelFormat = format_, pixelsWide = width_, pixelsHigh = height_, name = name_, maxS = maxS_, maxT = maxT_; @synthesize hasPremultipliedAlpha = hasPremultipliedAlpha_; +@synthesize shaderProgram = shaderProgram_; + +#ifdef __CC_PLATFORM_IOS +@synthesize resolutionType = resolutionType_; +#endif + - (id) initWithData:(const void*)data pixelFormat:(CCTexture2DPixelFormat)pixelFormat pixelsWide:(NSUInteger)width pixelsHigh:(NSUInteger)height contentSize:(CGSize)size { if((self = [super init])) { + glPixelStorei(GL_UNPACK_ALIGNMENT,1); glGenTextures(1, &name_); - glBindTexture(GL_TEXTURE_2D, name_); + ccGLBindTexture2D( name_ ); [self setAntiAliasTexParameters]; - + // Specify OpenGL texture image - + switch(pixelFormat) { case kCCTexture2DPixelFormat_RGBA8888: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) width, (GLsizei) height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); break; case kCCTexture2DPixelFormat_RGBA4444: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) width, (GLsizei) height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data); break; case kCCTexture2DPixelFormat_RGB5A1: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, data); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) width, (GLsizei) height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, data); break; case kCCTexture2DPixelFormat_RGB565: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, (GLsizei) width, (GLsizei) height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data); + break; + case kCCTexture2DPixelFormat_RGB888: + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, (GLsizei) width, (GLsizei) height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); + break; + case kCCTexture2DPixelFormat_AI88: + glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, (GLsizei) width, (GLsizei) height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, data); break; case kCCTexture2DPixelFormat_A8: - glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); + glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, (GLsizei) width, (GLsizei) height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); break; default: [NSException raise:NSInternalInconsistencyException format:@""]; - + } size_ = size; @@ -149,7 +160,12 @@ - (id) initWithData:(const void*)data pixelFormat:(CCTexture2DPixelFormat)pixelF maxT_ = size.height / (float)height; hasPremultipliedAlpha_ = NO; - } + +#ifdef __CC_PLATFORM_IOS + resolutionType_ = kCCResolutionUnknown; +#endif + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTexture]; + } return self; } @@ -168,9 +184,12 @@ - (void*) keepData:(void*)data length:(NSUInteger)length - (void) dealloc { CCLOGINFO(@"cocos2d: deallocing %@", self); - if(name_) - glDeleteTextures(1, &name_); - + + [shaderProgram_ release]; + + if( name_ ) + ccGLDeleteTexture( name_ ); + [super dealloc]; } @@ -184,24 +203,26 @@ -(CGSize) contentSize CGSize ret; ret.width = size_.width / CC_CONTENT_SCALE_FACTOR(); ret.height = size_.height / CC_CONTENT_SCALE_FACTOR(); - + return ret; } + @end #pragma mark - #pragma mark CCTexture2D - Image @implementation CCTexture2D (Image) -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -- (id) initWithImage:(UIImage *)uiImage -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) -- (id) initWithImage:(CGImageRef)CGImage + +#ifdef __CC_PLATFORM_IOS +- (id) initWithCGImage:(CGImageRef)cgImage resolutionType:(ccResolutionType)resolution +#elif defined(__CC_PLATFORM_MAC) +- (id) initWithCGImage:(CGImageRef)cgImage #endif { NSUInteger POTWide, POTHigh; CGContextRef context = nil; - void* data = nil;; + void* data = nil; CGColorSpaceRef colorSpace; void* tempData; unsigned int* inPixel32; @@ -210,98 +231,97 @@ - (id) initWithImage:(CGImageRef)CGImage CGImageAlphaInfo info; CGSize imageSize; CCTexture2DPixelFormat pixelFormat; - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - CGImageRef CGImage = uiImage.CGImage; -#endif - - if(CGImage == NULL) { - CCLOG(@"cocos2d: CCTexture2D. Can't create Texture. UIImage is nil"); + + if(cgImage == NULL) { + CCLOG(@"cocos2d: CCTexture2D. Can't create Texture. cgImage is nil"); [self release]; return nil; } - + CCConfiguration *conf = [CCConfiguration sharedConfiguration]; -#if CC_TEXTURE_NPOT_SUPPORT if( [conf supportsNPOT] ) { - POTWide = CGImageGetWidth(CGImage); - POTHigh = CGImageGetHeight(CGImage); + POTWide = CGImageGetWidth(cgImage); + POTHigh = CGImageGetHeight(cgImage); - } else -#endif + } + else { - POTWide = ccNextPOT(CGImageGetWidth(CGImage)); - POTHigh = ccNextPOT(CGImageGetHeight(CGImage)); + POTWide = ccNextPOT(CGImageGetWidth(cgImage)); + POTHigh = ccNextPOT(CGImageGetHeight(cgImage)); } - + NSUInteger maxTextureSize = [conf maxTextureSize]; if( POTHigh > maxTextureSize || POTWide > maxTextureSize ) { - CCLOG(@"cocos2d: WARNING: Image (%d x %d) is bigger than the supported %d x %d", - (unsigned int)POTWide, (unsigned int)POTHigh, - (unsigned int)maxTextureSize, (unsigned int)maxTextureSize); + CCLOG(@"cocos2d: WARNING: Image (%lu x %lu) is bigger than the supported %ld x %ld", + (long)POTWide, (long)POTHigh, + (long)maxTextureSize, (long)maxTextureSize); [self release]; return nil; } - - info = CGImageGetAlphaInfo(CGImage); + + info = CGImageGetAlphaInfo(cgImage); hasAlpha = ((info == kCGImageAlphaPremultipliedLast) || (info == kCGImageAlphaPremultipliedFirst) || (info == kCGImageAlphaLast) || (info == kCGImageAlphaFirst) ? YES : NO); - - size_t bpp = CGImageGetBitsPerComponent(CGImage); - colorSpace = CGImageGetColorSpace(CGImage); + + size_t bpp = CGImageGetBitsPerComponent(cgImage); + colorSpace = CGImageGetColorSpace(cgImage); if(colorSpace) { - if(hasAlpha || bpp >= 8) + if( hasAlpha ) { pixelFormat = defaultAlphaPixelFormat_; - else { - CCLOG(@"cocos2d: CCTexture2D: Using RGB565 texture since image has no alpha"); - pixelFormat = kCCTexture2DPixelFormat_RGB565; + info = kCGImageAlphaPremultipliedLast; + } + else + { + info = kCGImageAlphaNoneSkipLast; + + if( bpp >= 8 ) + pixelFormat = kCCTexture2DPixelFormat_RGB888; + else + pixelFormat = kCCTexture2DPixelFormat_RGB565; + + CCLOG(@"cocos2d: CCTexture2D: Using %@ texture since image has no alpha", (bpp>=8) ? @"RGBA888" : @"RGB565" ); + } } else { // NOTE: No colorspace means a mask image CCLOG(@"cocos2d: CCTexture2D: Using A8 texture since image is a mask"); pixelFormat = kCCTexture2DPixelFormat_A8; } - - imageSize = CGSizeMake(CGImageGetWidth(CGImage), CGImageGetHeight(CGImage)); + + imageSize = CGSizeMake(CGImageGetWidth(cgImage), CGImageGetHeight(cgImage)); // Create the bitmap graphics context - - switch(pixelFormat) { + + switch(pixelFormat) { case kCCTexture2DPixelFormat_RGBA8888: case kCCTexture2DPixelFormat_RGBA4444: case kCCTexture2DPixelFormat_RGB5A1: - colorSpace = CGColorSpaceCreateDeviceRGB(); - data = malloc(POTHigh * POTWide * 4); - info = hasAlpha ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNoneSkipLast; -// info = kCGImageAlphaPremultipliedLast; // issue #886. This patch breaks BMP images. - context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, info | kCGBitmapByteOrder32Big); - CGColorSpaceRelease(colorSpace); - break; - case kCCTexture2DPixelFormat_RGB565: + case kCCTexture2DPixelFormat_RGB888: colorSpace = CGColorSpaceCreateDeviceRGB(); data = malloc(POTHigh * POTWide * 4); - info = kCGImageAlphaNoneSkipLast; +// info = hasAlpha ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNoneSkipLast; +// info = kCGImageAlphaPremultipliedLast; // issue #886. This patch breaks BMP images. context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, info | kCGBitmapByteOrder32Big); CGColorSpaceRelease(colorSpace); break; case kCCTexture2DPixelFormat_A8: data = malloc(POTHigh * POTWide); - info = kCGImageAlphaOnly; + info = kCGImageAlphaOnly; context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, NULL, info); - break; + break; default: [NSException raise:NSInternalInconsistencyException format:@"Invalid pixel format"]; } - - + + CGContextClearRect(context, CGRectMake(0, 0, POTWide, POTHigh)); CGContextTranslateCTM(context, 0, POTHigh - imageSize.height); - CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(CGImage), CGImageGetHeight(CGImage)), CGImage); - + CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(cgImage), CGImageGetHeight(cgImage)), cgImage); + // Repack the pixel data into the right format - + if(pixelFormat == kCCTexture2DPixelFormat_RGB565) { //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB" tempData = malloc(POTHigh * POTWide * 2); @@ -311,24 +331,41 @@ - (id) initWithImage:(CGImageRef)CGImage *outPixel16++ = ((((*inPixel32 >> 0) & 0xFF) >> 3) << 11) | ((((*inPixel32 >> 8) & 0xFF) >> 2) << 5) | ((((*inPixel32 >> 16) & 0xFF) >> 3) << 0); free(data); data = tempData; + + } + + else if(pixelFormat == kCCTexture2DPixelFormat_RGB888) { + //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRRRRGGGGGGGGBBBBBBB" + tempData = malloc(POTHigh * POTWide * 3); + char *inData = (char*)data; + char *outData = (char*)tempData; + int j=0; + for(unsigned int i = 0; i < POTWide * POTHigh *4; i++) { + outData[j++] = inData[i++]; + outData[j++] = inData[i++]; + outData[j++] = inData[i++]; + } + free(data); + data = tempData; } + else if (pixelFormat == kCCTexture2DPixelFormat_RGBA4444) { //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA" tempData = malloc(POTHigh * POTWide * 2); inPixel32 = (unsigned int*)data; outPixel16 = (unsigned short*)tempData; for(unsigned int i = 0; i < POTWide * POTHigh; ++i, ++inPixel32) - *outPixel16++ = + *outPixel16++ = ((((*inPixel32 >> 0) & 0xFF) >> 4) << 12) | // R ((((*inPixel32 >> 8) & 0xFF) >> 4) << 8) | // G ((((*inPixel32 >> 16) & 0xFF) >> 4) << 4) | // B ((((*inPixel32 >> 24) & 0xFF) >> 4) << 0); // A - - + + free(data); data = tempData; - + } else if (pixelFormat == kCCTexture2DPixelFormat_RGB5A1) { //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA" @@ -336,24 +373,28 @@ - (id) initWithImage:(CGImageRef)CGImage inPixel32 = (unsigned int*)data; outPixel16 = (unsigned short*)tempData; for(unsigned int i = 0; i < POTWide * POTHigh; ++i, ++inPixel32) - *outPixel16++ = + *outPixel16++ = ((((*inPixel32 >> 0) & 0xFF) >> 3) << 11) | // R ((((*inPixel32 >> 8) & 0xFF) >> 3) << 6) | // G ((((*inPixel32 >> 16) & 0xFF) >> 3) << 1) | // B ((((*inPixel32 >> 24) & 0xFF) >> 7) << 0); // A - - + + free(data); data = tempData; } self = [self initWithData:data pixelFormat:pixelFormat pixelsWide:POTWide pixelsHigh:POTHigh contentSize:imageSize]; - + // should be after calling super init hasPremultipliedAlpha_ = (info == kCGImageAlphaPremultipliedLast || info == kCGImageAlphaPremultipliedFirst); - + CGContextRelease(context); [self releaseData:data]; - + +#ifdef __CC_PLATFORM_IOS + resolutionType_ = resolution; +#endif + return self; } @end @@ -363,204 +404,198 @@ - (id) initWithImage:(CGImageRef)CGImage @implementation CCTexture2D (Text) -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS -- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment font:(id)uifont +- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode font:(id)uifont { NSAssert( uifont, @"Invalid font"); - + NSUInteger POTWide = ccNextPOT(dimensions.width); NSUInteger POTHigh = ccNextPOT(dimensions.height); unsigned char* data; - + CGContextRef context; CGColorSpaceRef colorSpace; - -#if USE_TEXT_WITH_A8_TEXTURES - colorSpace = CGColorSpaceCreateDeviceGray(); - data = calloc(POTHigh, POTWide); - context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, colorSpace, kCGImageAlphaNone); + +#if CC_USE_LA88_LABELS + data = calloc(POTHigh, POTWide * 2); #else - colorSpace = CGColorSpaceCreateDeviceRGB(); - data = calloc(POTHigh, POTWide * 4); - context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); + data = calloc(POTHigh, POTWide); #endif + colorSpace = CGColorSpaceCreateDeviceGray(); + context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, colorSpace, kCGImageAlphaNone); CGColorSpaceRelease(colorSpace); - + if( ! context ) { free(data); [self release]; return nil; } - + CGContextSetGrayFillColor(context, 1.0f, 1.0f); CGContextTranslateCTM(context, 0.0f, POTHigh); CGContextScaleCTM(context, 1.0f, -1.0f); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential - + UIGraphicsPushContext(context); // normal fonts if( [uifont isKindOfClass:[UIFont class] ] ) - [string drawInRect:CGRectMake(0, 0, dimensions.width, dimensions.height) withFont:uifont lineBreakMode:UILineBreakModeWordWrap alignment:alignment]; - -#if CC_FONT_LABEL_SUPPORT - else // ZFont class - [string drawInRect:CGRectMake(0, 0, dimensions.width, dimensions.height) withZFont:uifont lineBreakMode:UILineBreakModeWordWrap alignment:alignment]; -#endif - + [string drawInRect:CGRectMake(0, 0, dimensions.width, dimensions.height) withFont:uifont lineBreakMode:lineBreakMode alignment:alignment]; + UIGraphicsPopContext(); - -#if USE_TEXT_WITH_A8_TEXTURES - self = [self initWithData:data pixelFormat:kCCTexture2DPixelFormat_A8 pixelsWide:POTWide pixelsHigh:POTHigh contentSize:dimensions]; -#else - self = [self initWithData:data pixelFormat:kCCTexture2DPixelFormat_RGBA8888 pixelsWide:POTWide pixelsHigh:POTHigh contentSize:dimensions]; + +#if CC_USE_LA88_LABELS + NSUInteger textureSize = POTWide*POTHigh; + unsigned short *la88_data = (unsigned short*)data; + for(int i = textureSize-1; i>=0; i--) //Convert A8 to AI88 + la88_data[i] = (data[i] << 8) | 0xff; + #endif + + self = [self initWithData:data pixelFormat:LABEL_PIXEL_FORMAT pixelsWide:POTWide pixelsHigh:POTHigh contentSize:dimensions]; + CGContextRelease(context); [self releaseData:data]; - + return self; } - -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) + + + +#elif defined(__CC_PLATFORM_MAC) - (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment attributedString:(NSAttributedString*)stringWithAttributes -{ - NSAssert( stringWithAttributes, @"Invalid stringWithAttributes"); +{ + NSAssert(stringWithAttributes, @"Invalid stringWithAttributes"); - NSUInteger POTWide = ccNextPOT(dimensions.width); - NSUInteger POTHigh = ccNextPOT(dimensions.height); - unsigned char* data; - + // get nearest power of two + NSSize POTSize = NSMakeSize(ccNextPOT(dimensions.width), ccNextPOT(dimensions.height)); + + // get string dimensions NSSize realDimensions = [stringWithAttributes size]; - //Alignment - float xPadding = 0; - // Mac crashes if the width or height is 0 - if( realDimensions.width > 0 && realDimensions.height > 0 ) { - switch (alignment) { - case CCTextAlignmentLeft: xPadding = 0; break; - case CCTextAlignmentCenter: xPadding = (dimensions.width-realDimensions.width)/2.0f; break; - case CCTextAlignmentRight: xPadding = dimensions.width-realDimensions.width; break; - default: break; - } - - //Disable antialias - [[NSGraphicsContext currentContext] setShouldAntialias:NO]; - - NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(POTWide, POTHigh)]; - [image lockFocus]; - - [stringWithAttributes drawAtPoint:NSMakePoint(xPadding, POTHigh-dimensions.height)]; // draw at offset position - - NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect (0.0f, 0.0f, POTWide, POTHigh)]; + if (realDimensions.width > 0 && realDimensions.height > 0) + { + // Disable antialias + [[NSGraphicsContext currentContext] setShouldAntialias:NO]; + + NSImage *image = [[NSImage alloc] initWithSize:POTSize]; + [image lockFocus]; + + [stringWithAttributes drawInRect:NSMakeRect(0, POTSize.height - dimensions.height, dimensions.width, dimensions.height)]; //POTSize.width, POTSize.height)]; + + NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0.0f, 0.0f, POTSize.width, POTSize.height)]; [image unlockFocus]; - - data = (unsigned char*) [bitmap bitmapData]; //Use the same buffer to improve the performance. - - NSUInteger textureSize = POTWide*POTHigh; - for(int i = 0; iwrapS == GL_CLAMP_TO_EDGE && texParams->wrapT == GL_CLAMP_TO_EDGE), @"GL_CLAMP_TO_EDGE should be used in NPOT textures"); - glBindTexture( GL_TEXTURE_2D, self.name ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texParams->minFilter ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texParams->magFilter ); + + ccGLBindTexture2D( name_ ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texParams->minFilter ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texParams->magFilter ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texParams->wrapS ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams->wrapT ); } @@ -750,5 +779,49 @@ +(CCTexture2DPixelFormat) defaultAlphaPixelFormat { return defaultAlphaPixelFormat_; } + +-(NSUInteger) bitsPerPixelForFormat +{ + NSUInteger ret=0; + + switch (format_) { + case kCCTexture2DPixelFormat_RGBA8888: + ret = 32; + break; + case kCCTexture2DPixelFormat_RGB565: + ret = 16; + break; + case kCCTexture2DPixelFormat_RGB888: + ret = 24; + break; + case kCCTexture2DPixelFormat_A8: + ret = 8; + break; + case kCCTexture2DPixelFormat_RGBA4444: + ret = 16; + break; + case kCCTexture2DPixelFormat_RGB5A1: + ret = 16; + break; + case kCCTexture2DPixelFormat_PVRTC4: + ret = 4; + break; + case kCCTexture2DPixelFormat_PVRTC2: + ret = 2; + break; + case kCCTexture2DPixelFormat_I8: + ret = 8; + break; + case kCCTexture2DPixelFormat_AI88: + ret = 16; + break; + default: + ret = -1; + NSAssert1(NO , @"bitsPerPixelForFormat: %ld, unrecognised pixel format", (long)format_); + CCLOG(@"bitsPerPixelForFormat: %ld, cannot give useful result", (long)format_); + break; + } + return ret; +} @end diff --git a/Example/libs/cocos2d/CCTextureAtlas.h b/Example/libs/cocos2d/CCTextureAtlas.h index 51f09ea..4a61485 100644 --- a/Example/libs/cocos2d/CCTextureAtlas.h +++ b/Example/libs/cocos2d/CCTextureAtlas.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -37,7 +38,7 @@ * The TextureAtlas capacity can be increased or decreased in runtime * OpenGL component: V3F, C4B, T2F. The quads are rendered using an OpenGL ES VBO. - To render the quads using an interleaved vertex array list, you should modify the ccConfig.h file + To render the quads using an interleaved vertex array list, you should modify the ccConfig.h file */ @interface CCTextureAtlas : NSObject { @@ -46,9 +47,13 @@ ccV3F_C4B_T2F_Quad *quads_; // quads to be rendered GLushort *indices_; CCTexture2D *texture_; -#if CC_USES_VBO + GLuint buffersVBO_[2]; //0: vertex 1: indices -#endif // CC_USES_VBO + BOOL dirty_; //indicates whether or not the array buffer of the VBO needs to be updated + +#if CC_TEXTURE_ATLAS_USE_VAO + GLuint VAOname_; +#endif } /** quantity of quads that are going to be drawn */ @@ -73,13 +78,13 @@ -(id) initWithFile: (NSString*) file capacity:(NSUInteger)capacity; /** creates a TextureAtlas with a previously initialized Texture2D object, and - * with an initial capacity for n Quads. + * with an initial capacity for n Quads. * The TextureAtlas capacity can be increased in runtime. */ +(id) textureAtlasWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity; /** initializes a TextureAtlas with a previously initialized Texture2D object, and - * with an initial capacity for Quads. + * with an initial capacity for Quads. * The TextureAtlas capacity can be increased in runtime. * * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) @@ -98,6 +103,13 @@ */ -(void) insertQuad:(ccV3F_C4B_T2F_Quad*)quad atIndex:(NSUInteger)index; +/** Inserts a c array of quads at a given index + index must be between 0 and the atlas capacity - 1 + this method doesn't enlarge the array when amount + index > totalQuads + @since v1.1 +*/ +-(void) insertQuads:(ccV3F_C4B_T2F_Quad*)quads atIndex:(NSUInteger)index amount:(NSUInteger)amount; + /** Removes the quad that is located at a certain index and inserts it at a new index This operation is faster than removing and inserting in a quad in 2 different steps @since v0.7.2 @@ -110,27 +122,65 @@ */ -(void) removeQuadAtIndex:(NSUInteger) index; +/** removes a amount of quads starting from index + @since 1.1 + */ +- (void) removeQuadsAtIndex:(NSUInteger) index amount:(NSUInteger) amount; + /** removes all Quads. The TextureAtlas capacity remains untouched. No memory is freed. The total number of quads to be drawn will be 0 @since v0.7.2 */ -(void) removeAllQuads; - -/** resize the capacity of the Texture Atlas. +/** resize the capacity of the CCTextureAtlas. * The new capacity can be lower or higher than the current one * It returns YES if the resize was successful. * If it fails to resize the capacity it will return NO with a new capacity of 0. */ -(BOOL) resizeCapacity: (NSUInteger) n; +/** + Used internally by CCParticleBatchNode + don't use this unless you know what you're doing + @since 1.1 +*/ +- (void) increaseTotalQuadsWith:(NSUInteger) amount; + +/** Moves an amount of quads from oldIndex at newIndex + @since v1.1 + */ +-(void) moveQuadsFromIndex:(NSUInteger)oldIndex amount:(NSUInteger) amount atIndex:(NSUInteger)newIndex; + +/** + Moves quads from index till totalQuads to the newIndex + Used internally by CCParticleBatchNode + This method doesn't enlarge the array if newIndex + quads to be moved > capacity + @since 1.1 +*/ +- (void) moveQuadsFromIndex:(NSUInteger) index to:(NSUInteger) newIndex; + +/** + Ensures that after a realloc quads are still empty + Used internally by CCParticleBatchNode + @since 1.1 +*/ +- (void) fillWithEmptyQuadsFromIndex:(NSUInteger) index amount:(NSUInteger) amount; /** draws n quads * n can't be greater than the capacity of the Atlas */ + -(void) drawNumberOfQuads: (NSUInteger) n; +/** draws n quads from an index (offset). + n + start can't be greater than the capacity of the atlas + + @since v1.0 + */ +-(void) drawNumberOfQuads: (NSUInteger) n fromIndex: (NSUInteger) start; + /** draws all the Atlas's Quads */ -(void) drawQuads; diff --git a/Example/libs/cocos2d/CCTextureAtlas.m b/Example/libs/cocos2d/CCTextureAtlas.m index da70593..a2b2932 100644 --- a/Example/libs/cocos2d/CCTextureAtlas.m +++ b/Example/libs/cocos2d/CCTextureAtlas.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,16 +24,26 @@ * */ - // cocos2d #import "CCTextureAtlas.h" #import "ccMacros.h" #import "CCTexture2D.h" #import "CCTextureCache.h" +#import "CCGLProgram.h" +#import "ccGLStateCache.h" +#import "Support/OpenGL_Internal.h" +@interface CCTextureAtlas () +-(void) setupIndices; +-(void) mapBuffers; -@interface CCTextureAtlas (Private) --(void) initIndices; + + +#if CC_TEXTURE_ATLAS_USE_VAO +-(void) setupVBOandVAO; +#else +-(void) setupVBO; +#endif @end //According to some tests GL_TRIANGLE_STRIP is slower, MUCH slower. Probably I'm doing something very wrong @@ -61,7 +72,7 @@ -(id) initWithFile:(NSString*)file capacity:(NSUInteger)n CCTexture2D *tex = [[CCTextureCache sharedTextureCache] addImage:file]; if( tex ) return [self initWithTexture:tex capacity:n]; - + // else { CCLOG(@"cocos2d: Could not open file: %@", file); @@ -73,37 +84,45 @@ -(id) initWithFile:(NSString*)file capacity:(NSUInteger)n -(id) initWithTexture:(CCTexture2D*)tex capacity:(NSUInteger)n { if( (self=[super init]) ) { - + capacity_ = n; totalQuads_ = 0; - + // retained in property self.texture = tex; + // Re-initialization is not allowed + NSAssert(quads_==nil && indices_==nil, @"CCTextureAtlas re-initialization is not allowed"); + quads_ = calloc( sizeof(quads_[0]) * capacity_, 1 ); indices_ = calloc( sizeof(indices_[0]) * capacity_ * 6, 1 ); - + if( ! ( quads_ && indices_) ) { CCLOG(@"cocos2d: CCTextureAtlas: not enough memory"); if( quads_ ) free(quads_); if( indices_ ) free(indices_); + + [self release]; return nil; } - -#if CC_USES_VBO - // initial binding - glGenBuffers(2, &buffersVBO_[0]); -#endif // CC_USES_VBO - [self initIndices]; + [self setupIndices]; + +#if CC_TEXTURE_ATLAS_USE_VAO + [self setupVBOandVAO]; +#else + [self setupVBO]; +#endif + + dirty_ = YES; } - + return self; } -- (NSString*) description +-(NSString*) description { return [NSString stringWithFormat:@"<%@ = %08X | totalQuads = %i>", [self class], self, totalQuads_]; } @@ -114,24 +133,26 @@ -(void) dealloc free(quads_); free(indices_); - -#if CC_USES_VBO + glDeleteBuffers(2, buffersVBO_); -#endif // CC_USES_VBO - - + +#if CC_TEXTURE_ATLAS_USE_VAO + glDeleteVertexArrays(1, &VAOname_); +#endif + [texture_ release]; [super dealloc]; } --(void) initIndices +-(void) setupIndices { - for( NSUInteger i=0;i< capacity_;i++) { + for( NSUInteger i = 0; i < capacity_;i++) + { #if CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP indices_[i*6+0] = i*4+0; indices_[i*6+1] = i*4+0; - indices_[i*6+2] = i*4+2; + indices_[i*6+2] = i*4+2; indices_[i*6+3] = i*4+1; indices_[i*6+4] = i*4+3; indices_[i*6+5] = i*4+3; @@ -143,53 +164,139 @@ -(void) initIndices // inverted index. issue #179 indices_[i*6+3] = i*4+3; indices_[i*6+4] = i*4+2; - indices_[i*6+5] = i*4+1; -// indices_[i*6+3] = i*4+2; -// indices_[i*6+4] = i*4+3; -// indices_[i*6+5] = i*4+1; -#endif + indices_[i*6+5] = i*4+1; +#endif } - -#if CC_USES_VBO +} + +#pragma mark TextureAtlas - VAO / VBO specific + +#if CC_TEXTURE_ATLAS_USE_VAO +-(void) setupVBOandVAO +{ + glGenVertexArrays(1, &VAOname_); + glBindVertexArray(VAOname_); + +#define kQuadSize sizeof(quads_[0].bl) + + glGenBuffers(2, &buffersVBO_[0]); + glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * capacity_, quads_, GL_DYNAMIC_DRAW); + + // vertices + glEnableVertexAttribArray(kCCVertexAttrib_Position); + glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, vertices)); + + // colors + glEnableVertexAttribArray(kCCVertexAttrib_Color); + glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, colors)); + + // tex coords + glEnableVertexAttribArray(kCCVertexAttrib_TexCoords); + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, texCoords)); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffersVBO_[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices_[0]) * capacity_ * 6, indices_, GL_STATIC_DRAW); + + glBindVertexArray(0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); + + CHECK_GL_ERROR_DEBUG(); +} +#else // CC_TEXTURE_ATLAS_USE_VAO +-(void) setupVBO +{ + glGenBuffers(2, &buffersVBO_[0]); + + [self mapBuffers]; +} +#endif // ! // CC_TEXTURE_ATLAS_USE_VAO + + +-(void) mapBuffers +{ + glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); + glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * capacity_, quads_, GL_DYNAMIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffersVBO_[1]); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices_[0]) * capacity_ * 6, indices_, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); -#endif // CC_USES_VBO + + CHECK_GL_ERROR_DEBUG(); } #pragma mark TextureAtlas - Update, Insert, Move & Remove +-(ccV3F_C4B_T2F_Quad *) quads +{ + //if someone accesses the quads directly, presume that changes will be made + dirty_ = YES; + return quads_; +} + -(void) updateQuad:(ccV3F_C4B_T2F_Quad*)quad atIndex:(NSUInteger) n { NSAssert(n < capacity_, @"updateQuadWithTexture: Invalid index"); - + totalQuads_ = MAX( n+1, totalQuads_); - - quads_[n] = *quad; -} + quads_[n] = *quad; + + dirty_ = YES; +} -(void) insertQuad:(ccV3F_C4B_T2F_Quad*)quad atIndex:(NSUInteger)index { NSAssert(index < capacity_, @"insertQuadWithTexture: Invalid index"); - + totalQuads_++; NSAssert( totalQuads_ <= capacity_, @"invalid totalQuads"); - + // issue #575. index can be > totalQuads NSInteger remaining = (totalQuads_-1) - index; - + // last object doesn't need to be moved if( remaining > 0) // tex coordinates memmove( &quads_[index+1],&quads_[index], sizeof(quads_[0]) * remaining ); - + quads_[index] = *quad; + + dirty_ = YES; } +-(void) insertQuads:(ccV3F_C4B_T2F_Quad*)quads atIndex:(NSUInteger)index amount:(NSUInteger) amount +{ + NSAssert(index + amount <= capacity_, @"insertQuadWithTexture: Invalid index + amount"); + + totalQuads_+= amount; + + NSAssert( totalQuads_ <= capacity_, @"invalid totalQuads"); + + // issue #575. index can be > totalQuads + NSInteger remaining = (totalQuads_-1) - index - amount; + + // last object doesn't need to be moved + if( remaining > 0) + // tex coordinates + memmove( &quads_[index+amount],&quads_[index], sizeof(quads_[0]) * remaining ); + + + + NSUInteger max = index + amount; + NSUInteger j = 0; + for (NSUInteger i = index; i < max ; i++) + { + quads_[index] = quads[j]; + index++; + j++; + } + + dirty_ = YES; +} -(void) insertQuadFromIndex:(NSUInteger)oldIndex atIndex:(NSUInteger)newIndex { @@ -199,7 +306,7 @@ -(void) insertQuadFromIndex:(NSUInteger)oldIndex atIndex:(NSUInteger)newIndex if( oldIndex == newIndex ) return; - NSUInteger howMany = abs( oldIndex - newIndex); + NSUInteger howMany = labs( oldIndex - newIndex); NSUInteger dst = oldIndex; NSUInteger src = oldIndex + 1; if( oldIndex > newIndex) { @@ -211,21 +318,67 @@ -(void) insertQuadFromIndex:(NSUInteger)oldIndex atIndex:(NSUInteger)newIndex ccV3F_C4B_T2F_Quad quadsBackup = quads_[oldIndex]; memmove( &quads_[dst],&quads_[src], sizeof(quads_[0]) * howMany ); quads_[newIndex] = quadsBackup; + + dirty_ = YES; +} + +-(void) moveQuadsFromIndex:(NSUInteger)oldIndex amount:(NSUInteger) amount atIndex:(NSUInteger)newIndex +{ + NSAssert(newIndex + amount <= totalQuads_, @"insertQuadFromIndex:atIndex: Invalid index"); + NSAssert(oldIndex < totalQuads_, @"insertQuadFromIndex:atIndex: Invalid index"); + + if( oldIndex == newIndex ) + return; + + //create buffer + size_t quadSize = sizeof(ccV3F_C4B_T2F_Quad); + ccV3F_C4B_T2F_Quad *tempQuads = malloc( quadSize * amount); + memcpy( tempQuads, &quads_[oldIndex], quadSize * amount ); + + if (newIndex < oldIndex) + { + // move quads from newIndex to newIndex + amount to make room for buffer + memmove( &quads_[newIndex], &quads_[newIndex+amount], (oldIndex-newIndex)*quadSize); + } + else + { + // move quads above back + memmove( &quads_[oldIndex], &quads_[oldIndex+amount], (newIndex-oldIndex)*quadSize); + } + memcpy( &quads_[newIndex], tempQuads, amount*quadSize); + + free(tempQuads); + + dirty_ = YES; } -(void) removeQuadAtIndex:(NSUInteger) index { NSAssert(index < totalQuads_, @"removeQuadAtIndex: Invalid index"); - + NSUInteger remaining = (totalQuads_-1) - index; - - + // last object doesn't need to be moved if( remaining ) - // tex coordinates memmove( &quads_[index],&quads_[index+1], sizeof(quads_[0]) * remaining ); - + totalQuads_--; + + dirty_ = YES; +} + +-(void) removeQuadsAtIndex:(NSUInteger) index amount:(NSUInteger) amount +{ + NSAssert(index + amount <= totalQuads_, @"removeQuadAtIndex: index + amount out of bounds"); + + NSUInteger remaining = (totalQuads_) - (index + amount); + + totalQuads_ -= amount; + + if ( remaining ) + memmove( &quads_[index], &quads_[index+amount], sizeof(quads_[0]) * remaining ); + + dirty_ = YES; } -(void) removeAllQuads @@ -246,98 +399,147 @@ -(BOOL) resizeCapacity: (NSUInteger) newCapacity void * tmpQuads = realloc( quads_, sizeof(quads_[0]) * capacity_ ); void * tmpIndices = realloc( indices_, sizeof(indices_[0]) * capacity_ * 6 ); - + if( ! ( tmpQuads && tmpIndices) ) { CCLOG(@"cocos2d: CCTextureAtlas: not enough memory"); if( tmpQuads ) free(tmpQuads); else free(quads_); - + if( tmpIndices ) free(tmpIndices); else free(indices_); - + indices_ = nil; quads_ = nil; capacity_ = totalQuads_ = 0; return NO; } - + quads_ = tmpQuads; indices_ = tmpIndices; - [self initIndices]; + // Update Indices + [self setupIndices]; + [self mapBuffers]; + + dirty_ = YES; return YES; } +#pragma mark TextureAtlas - CCParticleBatchNode Specific + +-(void) fillWithEmptyQuadsFromIndex:(NSUInteger) index amount:(NSUInteger) amount +{ + ccV3F_C4B_T2F_Quad quad; + bzero( &quad, sizeof(quad) ); + + NSUInteger to = index + amount; + for (NSInteger i = index ; i < to ; i++) + { + quads_[i] = quad; + } + +} +-(void) increaseTotalQuadsWith:(NSUInteger) amount +{ + totalQuads_ += amount; +} + +-(void) moveQuadsFromIndex:(NSUInteger) index to:(NSUInteger) newIndex +{ + NSAssert(newIndex + (totalQuads_ - index) <= capacity_, @"moveQuadsFromIndex move is out of bounds"); + + memmove(quads_ + newIndex,quads_ + index, (totalQuads_ - index) * sizeof(quads_[0])); +} + #pragma mark TextureAtlas - Drawing -(void) drawQuads { - return [self drawNumberOfQuads: totalQuads_]; + [self drawNumberOfQuads: totalQuads_ fromIndex:0]; } -(void) drawNumberOfQuads: (NSUInteger) n -{ - // Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY - // Unneeded states: - +{ + [self drawNumberOfQuads:n fromIndex:0]; +} + +-(void) drawNumberOfQuads: (NSUInteger) n fromIndex: (NSUInteger) start +{ + ccGLBindTexture2D( [texture_ name] ); + +#if CC_TEXTURE_ATLAS_USE_VAO + + // + // Using VBO and VAO + // + + // XXX: update is done in draw... perhaps it should be done in a timer + if (dirty_) { + glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); + glBufferSubData(GL_ARRAY_BUFFER, sizeof(quads_[0])*start, sizeof(quads_[0]) * n , &quads_[start] ); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + dirty_ = NO; + } + + glBindVertexArray( VAOname_ ); + +#if CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP + glDrawElements(GL_TRIANGLE_STRIP, (GLsizei) n*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(indices_[0])) ); +#else + glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(indices_[0])) ); +#endif // CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP + + glBindVertexArray(0); - glBindTexture(GL_TEXTURE_2D, [texture_ name]); -#define kQuadSize sizeof(quads_[0].bl) +#else // ! CC_TEXTURE_ATLAS_USE_VAO + + // + // Using VBO without VAO + // -#if CC_USES_VBO +#define kQuadSize sizeof(quads_[0].bl) glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); - + // XXX: update is done in draw... perhaps it should be done in a timer - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(quads_[0]) * n, quads_); - + if (dirty_) { + glBufferSubData(GL_ARRAY_BUFFER, sizeof(quads_[0])*start, sizeof(quads_[0]) * n , &quads_[start] ); + dirty_ = NO; + } + + ccGLEnableVertexAttribs( kCCVertexAttribFlag_PosColorTex ); + // vertices - glVertexPointer(3, GL_FLOAT, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, vertices)); + glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, vertices)); // colors - glColorPointer(4, GL_UNSIGNED_BYTE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, colors)); + glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, colors)); // tex coords - glTexCoordPointer(2, GL_FLOAT, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, texCoords)); - + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, texCoords)); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffersVBO_[1]); + #if CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP - glDrawElements(GL_TRIANGLE_STRIP, n*6, GL_UNSIGNED_SHORT, (GLvoid*)0); + glDrawElements(GL_TRIANGLE_STRIP, (GLsizei) n*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(indices_[0])) ); #else - glDrawElements(GL_TRIANGLES, n*6, GL_UNSIGNED_SHORT, (GLvoid*)0); + glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(indices_[0])) ); #endif // CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP - - glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - -#else // ! CC_USES_VBO - - NSUInteger offset = (NSUInteger)quads_; - // vertex - NSUInteger diff = offsetof( ccV3F_C4B_T2F, vertices); - glVertexPointer(3, GL_FLOAT, kQuadSize, (GLvoid*) (offset + diff) ); +#endif // CC_TEXTURE_ATLAS_USE_VAO - // color - diff = offsetof( ccV3F_C4B_T2F, colors); - glColorPointer(4, GL_UNSIGNED_BYTE, kQuadSize, (GLvoid*)(offset + diff)); - - // tex coords - diff = offsetof( ccV3F_C4B_T2F, texCoords); - glTexCoordPointer(2, GL_FLOAT, kQuadSize, (GLvoid*)(offset + diff)); - -#if CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP - glDrawElements(GL_TRIANGLE_STRIP, n*6, GL_UNSIGNED_SHORT, indices_); -#else - glDrawElements(GL_TRIANGLES, n*6, GL_UNSIGNED_SHORT, indices_); -#endif - -#endif // CC_USES_VBO -} + CC_INCREMENT_GL_DRAWS(1); + CHECK_GL_ERROR_DEBUG(); +} @end diff --git a/Example/libs/cocos2d/CCTextureCache.h b/Example/libs/cocos2d/CCTextureCache.h index dbf138e..18d24f0 100644 --- a/Example/libs/cocos2d/CCTextureCache.h +++ b/Example/libs/cocos2d/CCTextureCache.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,9 +24,9 @@ * */ -#import +#import "ccMacros.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import #endif @@ -40,8 +41,9 @@ @interface CCTextureCache : NSObject { NSMutableDictionary *textures_; - NSLock *dictLock_; - NSLock *contextLock_; + + dispatch_queue_t _loadingQueue; + dispatch_queue_t _dictQueue; } /** Retruns ths shared instance of the cache */ @@ -61,15 +63,25 @@ */ -(CCTexture2D*) addImage: (NSString*) fileimage; -/** Returns a Texture2D object given a file image - * If the file image was not previously loaded, it will create a new CCTexture2D object and it will return it. +/** Asynchronously, load a texture2d from a file. + * If the file image was previously loaded, it will use it. * Otherwise it will load a texture in a new thread, and when the image is loaded, the callback will be called with the Texture2D as a parameter. - * The callback will be called from the main thread, so it is safe to create any cocos2d object from the callback. + * The callback will be called in the cocos2d thread, so it is safe to create any cocos2d object from the callback. * Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr, .gif * @since v0.8 */ -(void) addImageAsync:(NSString*) filename target:(id)target selector:(SEL)selector; +/** Asynchronously, load a texture2d from a file. + * If the file image was previously loaded, it will use it. + * Otherwise it will load a texture in a new thread, and when the image is loaded, the block will be called. + * The callback will be called in the cocos2d thread, so it is safe to create any cocos2d object from the callback. + * Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr, .gif + * @since v2.0 + */ +-(void) addImageAsync:(NSString*) filename withBlock:(void(^)(CCTexture2D *tex))block; + + /** Returns a Texture2D object given an CGImageRef image * If the image was not previously loaded, it will create a new CCTexture2D object and it will return it. * Otherwise it will return a reference of a previously loaded image @@ -113,20 +125,6 @@ @interface CCTextureCache (PVRSupport) -/** Returns a Texture2D object given an PVRTC RAW filename - * If the file image was not previously loaded, it will create a new CCTexture2D - * object and it will return it. Otherwise it will return a reference of a previosly loaded image - * - * It can only load square images: width == height, and it must be a power of 2 (128,256,512...) - * bpp can only be 2 or 4. 2 means more compression but lower quality. - * hasAlpha: whether or not the image contains alpha channel - * - * IMPORTANT: This method is only defined on iOS. It is not supported on the Mac version. - */ -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED --(CCTexture2D*) addPVRTCImage:(NSString*)fileimage bpp:(int)bpp hasAlpha:(BOOL)alpha width:(int)w; -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED - /** Returns a Texture2D object given an PVR filename. * If the file image was not previously loaded, it will create a new CCTexture2D * object and it will return it. Otherwise it will return a reference of a previosly loaded image @@ -137,3 +135,12 @@ @end +@interface CCTextureCache (Debug) +/** Output to CCLOG the current contents of this CCTextureCache + * This will attempt to calculate the size of each texture, and the total texture memory in use + * + * @since v1.0 + */ +-(void) dumpCachedTextureInfo; + +@end diff --git a/Example/libs/cocos2d/CCTextureCache.m b/Example/libs/cocos2d/CCTextureCache.m index 6510497..ff1545c 100644 --- a/Example/libs/cocos2d/CCTextureCache.m +++ b/Example/libs/cocos2d/CCTextureCache.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,53 +24,33 @@ * */ -#import - +#import "ccMacros.h" #import "Platforms/CCGL.h" #import "CCTextureCache.h" #import "CCTexture2D.h" #import "CCTexturePVR.h" -#import "ccMacros.h" #import "CCConfiguration.h" -#import "Support/CCFileUtils.h" #import "CCDirector.h" #import "ccConfig.h" +#import "ccTypes.h" -// needed for CCCallFuncO in Mac-display_link version -#import "CCActionManager.h" -#import "CCActionInstant.h" - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -static EAGLContext *auxGLcontext = nil; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) -static NSOpenGLContext *auxGLcontext = nil; -#endif +#import "Support/CCFileUtils.h" +#import "Support/NSThread+performBlock.h" -@interface CCAsyncObject : NSObject -{ - SEL selector_; - id target_; - id data_; -} -@property (readwrite,assign) SEL selector; -@property (readwrite,retain) id target; -@property (readwrite,retain) id data; -@end +#ifdef __CC_PLATFORM_MAC +#import "Platforms/Mac/CCDirectorMac.h" +#endif -@implementation CCAsyncObject -@synthesize selector = selector_; -@synthesize target = target_; -@synthesize data = data_; -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - [target_ release]; - [data_ release]; - [super dealloc]; -} -@end +// needed for CCCallFuncO in Mac-display_link version +//#import "CCActionManager.h" +//#import "CCActionInstant.h" +#ifdef __CC_PLATFORM_IOS +static EAGLContext *_auxGLcontext = nil; +#elif defined(__CC_PLATFORM_MAC) +static NSOpenGLContext *_auxGLcontext = nil; +#endif @implementation CCTextureCache @@ -79,8 +60,8 @@ @implementation CCTextureCache + (CCTextureCache *)sharedTextureCache { if (!sharedTextureCache) - sharedTextureCache = [[CCTextureCache alloc] init]; - + sharedTextureCache = [[self alloc] init]; + return sharedTextureCache; } @@ -100,8 +81,29 @@ -(id) init { if( (self=[super init]) ) { textures_ = [[NSMutableDictionary dictionaryWithCapacity: 10] retain]; - dictLock_ = [[NSLock alloc] init]; - contextLock_ = [[NSLock alloc] init]; + + // init "global" stuff + _loadingQueue = dispatch_queue_create("org.cocos2d.texturecacheloading", NULL); + _dictQueue = dispatch_queue_create("org.cocos2d.texturecachedict", NULL); + + CCGLView *view = (CCGLView*)[[CCDirector sharedDirector] view]; + NSAssert(view, @"Do not initialize the TextureCache before the Director"); + +#ifdef __CC_PLATFORM_IOS + _auxGLcontext = [[EAGLContext alloc] + initWithAPI:kEAGLRenderingAPIOpenGLES2 + sharegroup:[[view context] sharegroup]]; + +#elif defined(__CC_PLATFORM_MAC) + NSOpenGLPixelFormat *pf = [view pixelFormat]; + NSOpenGLContext *share = [view openGLContext]; + + _auxGLcontext = [[NSOpenGLContext alloc] initWithFormat:pf shareContext:share]; + +#endif // __CC_PLATFORM_MAC + + NSAssert( _auxGLcontext, @"TextureCache: Could not create EAGL context"); + } return self; @@ -109,222 +111,236 @@ -(id) init - (NSString*) description { - return [NSString stringWithFormat:@"<%@ = %08X | num of textures = %i | keys: %@>", + __block NSString *desc = nil; + dispatch_sync(_dictQueue, ^{ + desc = [NSString stringWithFormat:@"<%@ = %08X | num of textures = %i | keys: %@>", [self class], self, [textures_ count], [textures_ allKeys] ]; - + }); + return desc; } -(void) dealloc { - CCLOG(@"cocos2d: deallocing %@", self); + CCLOGINFO(@"cocos2d: deallocing %@", self); - [textures_ release]; - [dictLock_ release]; - [contextLock_ release]; - [auxGLcontext release]; - auxGLcontext = nil; + dispatch_sync(_dictQueue, ^{ + [textures_ release]; + }); + [_auxGLcontext release]; + _auxGLcontext = nil; sharedTextureCache = nil; + dispatch_release(_loadingQueue); + dispatch_release(_dictQueue); + [super dealloc]; } #pragma mark TextureCache - Add Images --(void) addImageWithAsyncObject:(CCAsyncObject*)async +-(void) addImageAsync: (NSString*)path target:(id)target selector:(SEL)selector { - NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - // textures will be created on the main OpenGL context - // it seems that in SDK 2.2.x there can't be 2 threads creating textures at the same time - // the lock is used for this purpose: issue #472 - [contextLock_ lock]; - if( auxGLcontext == nil ) { - auxGLcontext = [[EAGLContext alloc] - initWithAPI:kEAGLRenderingAPIOpenGLES1 - sharegroup:[[[[CCDirector sharedDirector] openGLView] context] sharegroup]]; - - if( ! auxGLcontext ) - CCLOG(@"cocos2d: TextureCache: Could not create EAGL context"); + NSAssert(path != nil, @"TextureCache: fileimage MUST not be nill"); + NSAssert(target != nil, @"TextureCache: target can't be nil"); + NSAssert(selector != NULL, @"TextureCache: selector can't be NULL"); + + // optimization + + __block CCTexture2D * tex; + +#ifdef __CC_PLATFORM_IOS + path = [CCFileUtils removeSuffixFromFile:path]; +#endif + + dispatch_sync(_dictQueue, ^{ + tex = [textures_ objectForKey:path]; + }); + + if(tex) { + [target performSelector:selector withObject:tex]; + return; } - - if( [EAGLContext setCurrentContext:auxGLcontext] ) { + + // dispatch it serially + dispatch_async(_loadingQueue, ^{ + + CCTexture2D *texture; + +#ifdef __CC_PLATFORM_IOS + if( [EAGLContext setCurrentContext:_auxGLcontext] ) { + + // load / create the texture + texture = [self addImage:path]; + + glFlush(); + + // callback should be executed in cocos2d thread + [target performSelector:selector onThread:[[CCDirector sharedDirector] runningThread] withObject:texture waitUntilDone:NO]; + + [EAGLContext setCurrentContext:nil]; + } else { + CCLOG(@"cocos2d: ERROR: TetureCache: Could not set EAGLContext"); + } + +#elif defined(__CC_PLATFORM_MAC) + + [_auxGLcontext makeCurrentContext]; // load / create the texture - CCTexture2D *tex = [self addImage:async.data]; - - // The callback will be executed on the main thread - [async.target performSelectorOnMainThread:async.selector withObject:tex waitUntilDone:NO]; - - [EAGLContext setCurrentContext:nil]; - } else { - CCLOG(@"cocos2d: TetureCache: EAGLContext error"); - } - [contextLock_ unlock]; - - [autoreleasepool release]; + texture = [self addImage:path]; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) + glFlush(); - [contextLock_ lock]; - if( auxGLcontext == nil ) { + // callback should be executed in cocos2d thread + [target performSelector:selector onThread:[[CCDirector sharedDirector] runningThread] withObject:texture waitUntilDone:NO]; - MacGLView *view = [[CCDirector sharedDirector] openGLView]; - - NSOpenGLPixelFormat *pf = [view pixelFormat]; - NSOpenGLContext *share = [view openGLContext]; + [NSOpenGLContext clearCurrentContext]; - auxGLcontext = [[NSOpenGLContext alloc] initWithFormat:pf shareContext:share]; +#endif // __CC_PLATFORM_MAC - if( ! auxGLcontext ) - CCLOG(@"cocos2d: TextureCache: Could not create NSOpenGLContext"); - } - - [auxGLcontext makeCurrentContext]; - - // load / create the texture - CCTexture2D *tex = [self addImage:async.data]; - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - id action = [CCCallFuncO actionWithTarget:async.target selector:async.selector object:tex]; - [[CCActionManager sharedManager] addAction:action target:async.target paused:NO]; -#else - // The callback will be executed on the main thread - [async.target performSelector:async.selector - onThread:[[CCDirector sharedDirector] runningThread] - withObject:tex - waitUntilDone:NO]; -#endif - - - [NSOpenGLContext clearCurrentContext]; - - [contextLock_ unlock]; - - [autoreleasepool release]; - -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED + }); } --(void) addImageAsync: (NSString*)path target:(id)target selector:(SEL)selector +-(void) addImageAsync:(NSString*)path withBlock:(void(^)(CCTexture2D *tex))block { - NSAssert(path != nil, @"TextureCache: fileimage MUST not be nill"); + NSAssert(path != nil, @"TextureCache: fileimage MUST not be nil"); // optimization - - CCTexture2D * tex; - - path = ccRemoveHDSuffixFromFile(path); - - if( (tex=[textures_ objectForKey: path] ) ) { - [target performSelector:selector withObject:tex]; + + __block CCTexture2D * tex; + +#ifdef __CC_PLATFORM_IOS + path = [CCFileUtils removeSuffixFromFile:path]; +#endif + + dispatch_sync(_dictQueue, ^{ + tex = [textures_ objectForKey:path]; + }); + + if(tex) { + block(tex); return; } - // schedule the load - - CCAsyncObject *asyncObject = [[CCAsyncObject alloc] init]; - asyncObject.selector = selector; - asyncObject.target = target; - asyncObject.data = path; - - [NSThread detachNewThreadSelector:@selector(addImageWithAsyncObject:) toTarget:self withObject:asyncObject]; - [asyncObject release]; + // dispatch it serially + dispatch_async( _loadingQueue, ^{ + + CCTexture2D *texture; + +#ifdef __CC_PLATFORM_IOS + if( [EAGLContext setCurrentContext:_auxGLcontext] ) { + + // load / create the texture + texture = [self addImage:path]; + + glFlush(); + + // callback should be executed in cocos2d thread + NSThread *thread = [[CCDirector sharedDirector] runningThread]; + [thread performBlock:block withObject:texture waitUntilDone:NO]; + + [EAGLContext setCurrentContext:nil]; + } else { + CCLOG(@"cocos2d: ERROR: TetureCache: Could not set EAGLContext"); + } + +#elif defined(__CC_PLATFORM_MAC) + + [_auxGLcontext makeCurrentContext]; + + // load / create the texture + texture = [self addImage:path]; + + glFlush(); + + // callback should be executed in cocos2d thread + NSThread *thread = [[CCDirector sharedDirector] runningThread]; + [thread performBlock:block withObject:texture waitUntilDone:NO]; + + [NSOpenGLContext clearCurrentContext]; + +#endif // __CC_PLATFORM_MAC + + }); } -(CCTexture2D*) addImage: (NSString*) path { NSAssert(path != nil, @"TextureCache: fileimage MUST not be nill"); - CCTexture2D * tex = nil; + __block CCTexture2D * tex = nil; - // MUTEX: - // Needed since addImageAsync calls this method from a different thread - [dictLock_ lock]; - // remove possible -HD suffix to prevent caching the same image twice (issue #1040) - path = ccRemoveHDSuffixFromFile( path ); +#ifdef __CC_PLATFORM_IOS + path = [CCFileUtils removeSuffixFromFile: path]; +#endif + + dispatch_sync(_dictQueue, ^{ + tex = [textures_ objectForKey: path]; + }); - tex=[textures_ objectForKey: path]; - if( ! tex ) { - + NSString *lowerCase = [path lowercaseString]; - // all images are handled by UIImage except PVR extension that is handled by our own handler - + + // all images are handled by UIKit/AppKit except PVR extension that is handled by cocos2d's handler + if ( [lowerCase hasSuffix:@".pvr"] || [lowerCase hasSuffix:@".pvr.gz"] || [lowerCase hasSuffix:@".pvr.ccz"] ) tex = [self addPVRImage:path]; - // Only iPhone -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS - // Issue #886: TEMPORARY FIX FOR TRANSPARENT JPEGS IN IOS4 - else if ( ( [[CCConfiguration sharedConfiguration] OSVersion] >= kCCiOSVersion_4_0) && - ( [lowerCase hasSuffix:@".jpg"] || [lowerCase hasSuffix:@".jpeg"] ) - ) { - // convert jpg to png before loading the texture - - NSString *fullpath = [CCFileUtils fullPathFromRelativePath: path ]; - - UIImage *jpg = [[UIImage alloc] initWithContentsOfFile:fullpath]; - UIImage *png = [[UIImage alloc] initWithData:UIImagePNGRepresentation(jpg)]; - tex = [ [CCTexture2D alloc] initWithImage: png ]; - [png release]; - [jpg release]; - - if( tex ) - [textures_ setObject: tex forKey:path]; - else - CCLOG(@"cocos2d: Couldn't add image:%@ in CCTextureCache", path); - - [tex release]; - } - else { - - // prevents overloading the autorelease pool - NSString *fullpath = [CCFileUtils fullPathFromRelativePath: path ]; - UIImage *image = [ [UIImage alloc] initWithContentsOfFile: fullpath ]; - tex = [ [CCTexture2D alloc] initWithImage: image ]; + ccResolutionType resolution; + NSString *fullpath = [CCFileUtils fullPathFromRelativePath:path resolutionType:&resolution]; + + UIImage *image = [[UIImage alloc] initWithContentsOfFile:fullpath]; + tex = [[CCTexture2D alloc] initWithCGImage:image.CGImage resolutionType:resolution]; [image release]; - - if( tex ) - [textures_ setObject: tex forKey:path]; - else + + if( tex ){ + dispatch_sync(_dictQueue, ^{ + [textures_ setObject: tex forKey:path]; + }); + }else{ CCLOG(@"cocos2d: Couldn't add image:%@ in CCTextureCache", path); - - [tex release]; + } + + // autorelease prevents possible crash in multithreaded environments + [tex autorelease]; } - // Only in Mac -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) + +#elif defined(__CC_PLATFORM_MAC) else { NSString *fullpath = [CCFileUtils fullPathFromRelativePath: path ]; NSData *data = [[NSData alloc] initWithContentsOfFile:fullpath]; NSBitmapImageRep *image = [[NSBitmapImageRep alloc] initWithData:data]; - tex = [ [CCTexture2D alloc] initWithImage:[image CGImage]]; - + tex = [ [CCTexture2D alloc] initWithCGImage:[image CGImage]]; + [data release]; [image release]; - if( tex ) - [textures_ setObject: tex forKey:path]; - else + if( tex ){ + dispatch_sync(_dictQueue, ^{ + [textures_ setObject: tex forKey:path]; + }); + }else{ CCLOG(@"cocos2d: Couldn't add image:%@ in CCTextureCache", path); - - [tex release]; + } + + // autorelease prevents possible crash in multithreaded environments + [tex autorelease]; } -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_MAC } - - [dictLock_ unlock]; - + return tex; } @@ -332,29 +348,32 @@ -(CCTexture2D*) addImage: (NSString*) path -(CCTexture2D*) addCGImage: (CGImageRef) imageref forKey: (NSString *)key { NSAssert(imageref != nil, @"TextureCache: image MUST not be nill"); - - CCTexture2D * tex = nil; - + + __block CCTexture2D * tex = nil; + // If key is nil, then create a new texture each time - if( key && (tex=[textures_ objectForKey: key] ) ) { - return tex; + if( key ) { + dispatch_sync(_dictQueue, ^{ + tex = [textures_ objectForKey:key]; + }); + if(tex) + return tex; } - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - // prevents overloading the autorelease pool - UIImage *image = [[UIImage alloc] initWithCGImage:imageref]; - tex = [[CCTexture2D alloc] initWithImage: image]; - [image release]; - -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) - tex = [[CCTexture2D alloc] initWithImage: imageref]; + +#ifdef __CC_PLATFORM_IOS + tex = [[CCTexture2D alloc] initWithCGImage:imageref resolutionType:kCCResolutionUnknown]; +#elif __CC_PLATFORM_MAC + tex = [[CCTexture2D alloc] initWithCGImage:imageref]; #endif - - if(tex && key) - [textures_ setObject: tex forKey:key]; - else + + if(tex && key){ + dispatch_sync(_dictQueue, ^{ + [textures_ setObject: tex forKey:key]; + }); + }else{ CCLOG(@"cocos2d: Couldn't add CGImage in CCTextureCache"); - + } + return [tex autorelease]; } @@ -362,44 +381,58 @@ -(CCTexture2D*) addCGImage: (CGImageRef) imageref forKey: (NSString *)key -(void) removeAllTextures { - [textures_ removeAllObjects]; + dispatch_sync(_dictQueue, ^{ + [textures_ removeAllObjects]; + }); } -(void) removeUnusedTextures { - NSArray *keys = [textures_ allKeys]; - for( id key in keys ) { - id value = [textures_ objectForKey:key]; - if( [value retainCount] == 1 ) { - CCLOG(@"cocos2d: CCTextureCache: removing unused texture: %@", key); - [textures_ removeObjectForKey:key]; + dispatch_sync(_dictQueue, ^{ + NSArray *keys = [textures_ allKeys]; + for( id key in keys ) { + id value = [textures_ objectForKey:key]; + if( [value retainCount] == 1 ) { + CCLOG(@"cocos2d: CCTextureCache: removing unused texture: %@", key); + [textures_ removeObjectForKey:key]; + } } - } + }); } -(void) removeTexture: (CCTexture2D*) tex { if( ! tex ) return; - - NSArray *keys = [textures_ allKeysForObject:tex]; - - for( NSUInteger i = 0; i < [keys count]; i++ ) - [textures_ removeObjectForKey:[keys objectAtIndex:i]]; + + dispatch_sync(_dictQueue, ^{ + NSArray *keys = [textures_ allKeysForObject:tex]; + + for( NSUInteger i = 0; i < [keys count]; i++ ) + [textures_ removeObjectForKey:[keys objectAtIndex:i]]; + }); } -(void) removeTextureForKey:(NSString*)name { if( ! name ) return; - - [textures_ removeObjectForKey:name]; + + dispatch_sync(_dictQueue, ^{ + [textures_ removeObjectForKey:name]; + }); } #pragma mark TextureCache - Get - (CCTexture2D *)textureForKey:(NSString *)key { - return [textures_ objectForKey:key]; + __block CCTexture2D *tex = nil; + + dispatch_sync(_dictQueue, ^{ + tex = [textures_ objectForKey:key]; + }); + + return tex; } @end @@ -407,60 +440,66 @@ - (CCTexture2D *)textureForKey:(NSString *)key @implementation CCTextureCache (PVRSupport) -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED --(CCTexture2D*) addPVRTCImage:(NSString*)path bpp:(int)bpp hasAlpha:(BOOL)alpha width:(int)w +-(CCTexture2D*) addPVRImage:(NSString*)path { NSAssert(path != nil, @"TextureCache: fileimage MUST not be nill"); - NSAssert( bpp==2 || bpp==4, @"TextureCache: bpp must be either 2 or 4"); - - CCTexture2D * tex; - + + __block CCTexture2D * tex; + // remove possible -HD suffix to prevent caching the same image twice (issue #1040) - path = ccRemoveHDSuffixFromFile( path ); +#ifdef __CC_PLATFORM_IOS + path = [CCFileUtils removeSuffixFromFile: path]; +#endif - if( (tex=[textures_ objectForKey: path] ) ) { + dispatch_sync(_dictQueue, ^{ + tex = [textures_ objectForKey:path]; + }); + + if(tex) { return tex; } - - // Split up directory and filename - NSString *fullpath = [CCFileUtils fullPathFromRelativePath:path]; - - NSData *nsdata = [[NSData alloc] initWithContentsOfFile:fullpath]; - tex = [[CCTexture2D alloc] initWithPVRTCData:[nsdata bytes] level:0 bpp:bpp hasAlpha:alpha length:w]; - if( tex ) - [textures_ setObject: tex forKey:path]; - else - CCLOG(@"cocos2d: Couldn't add PVRTCImage:%@ in CCTextureCache",path); - - [nsdata release]; - + + tex = [[CCTexture2D alloc] initWithPVRFile: path]; + if( tex ){ + dispatch_sync(_dictQueue, ^{ + [textures_ setObject: tex forKey:path]; + }); + }else{ + CCLOG(@"cocos2d: Couldn't add PVRImage:%@ in CCTextureCache",path); + } + return [tex autorelease]; } -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED --(CCTexture2D*) addPVRImage:(NSString*)path -{ - NSAssert(path != nil, @"TextureCache: fileimage MUST not be nill"); - - CCTexture2D * tex; - - // remove possible -HD suffix to prevent caching the same image twice (issue #1040) - path = ccRemoveHDSuffixFromFile( path ); +@end - if( (tex=[textures_ objectForKey: path] ) ) { - return tex; - } - - // Split up directory and filename - NSString *fullpath = [CCFileUtils fullPathFromRelativePath:path]; - - tex = [[CCTexture2D alloc] initWithPVRFile: fullpath]; - if( tex ) - [textures_ setObject: tex forKey:path]; - else - CCLOG(@"cocos2d: Couldn't add PVRImage:%@ in CCTextureCache",path); - - return [tex autorelease]; + +@implementation CCTextureCache (Debug) + +-(void) dumpCachedTextureInfo +{ + __block NSUInteger count = 0; + __block NSUInteger totalBytes = 0; + + dispatch_sync(_dictQueue, ^{ + for (NSString* texKey in textures_) { + CCTexture2D* tex = [textures_ objectForKey:texKey]; + NSUInteger bpp = [tex bitsPerPixelForFormat]; + // Each texture takes up width * height * bytesPerPixel bytes. + NSUInteger bytes = tex.pixelsWide * tex.pixelsHigh * bpp / 8; + totalBytes += bytes; + count++; + NSLog( @"cocos2d: \"%@\"\trc=%lu\tid=%lu\t%lu x %lu\t@ %ld bpp =>\t%lu KB", + texKey, + (long)[tex retainCount], + (long)tex.name, + (long)tex.pixelsWide, + (long)tex.pixelsHigh, + (long)bpp, + (long)bytes / 1024 ); + } + }); + NSLog( @"cocos2d: CCTextureCache dumpDebugInfo:\t%ld textures,\tfor %lu KB (%.2f MB)", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f)); } @end diff --git a/Example/libs/cocos2d/CCTexturePVR.h b/Example/libs/cocos2d/CCTexturePVR.h index c8a8e75..6093941 100644 --- a/Example/libs/cocos2d/CCTexturePVR.h +++ b/Example/libs/cocos2d/CCTexturePVR.h @@ -48,9 +48,8 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. #import #import "Platforms/CCGL.h" -#import "CCTextureCache.h" #import "CCTexture2D.h" -#import "ccCArray.h" + #pragma mark - #pragma mark CCTexturePVR @@ -65,9 +64,9 @@ enum { }; /** CCTexturePVR - + Object that loads PVR images. - + Supported PVR formats: - RGBA8888 - BGRA8888 @@ -82,7 +81,7 @@ enum { Limitations: Pre-generated mipmaps, such as PVR textures with mipmap levels embedded in file, - are only supported if all individual sprites are of _square_ size. + are only supported if all individual sprites are of _square_ size. To use mipmaps with non-square textures, instead call CCTexture2D#generateMipmap on the sheet texture itself (and to save space, save the PVR sprite sheet without mip maps included). */ @@ -90,28 +89,38 @@ enum { { struct CCPVRMipmap mipmaps_[CC_PVRMIPMAP_MAX]; // pointer to mipmap images int numberOfMipmaps_; // number of mipmap used - + unsigned int tableFormatIndex_; uint32_t width_, height_; GLuint name_; BOOL hasAlpha_; - + // cocos2d integration BOOL retainName_; + CCTexture2DPixelFormat format_; } +/** initializes a CCTexturePVR with a path */ - (id)initWithContentsOfFile:(NSString *)path; +/** initializes a CCTexturePVR with an URL */ - (id)initWithContentsOfURL:(NSURL *)url; +/** creates and initializes a CCTexturePVR with a path */ + (id)pvrTextureWithContentsOfFile:(NSString *)path; +/** creates and initializes a CCTexturePVR with an URL */ + (id)pvrTextureWithContentsOfURL:(NSURL *)url; +/** texture id name */ @property (nonatomic,readonly) GLuint name; +/** texture width */ @property (nonatomic,readonly) uint32_t width; +/** texture height */ @property (nonatomic,readonly) uint32_t height; +/** whether or not the texture has alpha */ @property (nonatomic,readonly) BOOL hasAlpha; // cocos2d integration @property (nonatomic,readwrite) BOOL retainName; +@property (nonatomic,readonly) CCTexture2DPixelFormat format; @end diff --git a/Example/libs/cocos2d/CCTexturePVR.m b/Example/libs/cocos2d/CCTexturePVR.m index 9f0e73f..bf0ad07 100644 --- a/Example/libs/cocos2d/CCTexturePVR.m +++ b/Example/libs/cocos2d/CCTexturePVR.m @@ -57,61 +57,76 @@ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * - AI88 */ -#import - #import #import "CCTexturePVR.h" #import "ccMacros.h" #import "CCConfiguration.h" +#import "ccGLStateCache.h" #import "Support/ccUtils.h" #import "Support/CCFileUtils.h" #import "Support/ZipUtils.h" +#import "Support/OpenGL_Internal.h" #pragma mark - #pragma mark CCTexturePVR #define PVR_TEXTURE_FLAG_TYPE_MASK 0xff -#define PVR_TEXTURE_FLAG_FLIPPED_MASK 0x10000 + +// Values taken from PVRTexture.h from http://www.imgtec.com +enum { + kPVRTextureFlagMipmap = (1<<8), // has mip map levels + kPVRTextureFlagTwiddle = (1<<9), // is twiddled + kPVRTextureFlagBumpmap = (1<<10), // has normals encoded for a bump map + kPVRTextureFlagTiling = (1<<11), // is bordered for tiled pvr + kPVRTextureFlagCubemap = (1<<12), // is a cubemap/skybox + kPVRTextureFlagFalseMipCol = (1<<13), // are there false coloured MIP levels + kPVRTextureFlagVolume = (1<<14), // is this a volume texture + kPVRTextureFlagAlpha = (1<<15), // v2.1 is there transparency info in the texture + kPVRTextureFlagVerticalFlip = (1<<16), // v2.1 is the texture vertically flipped +}; + static char gPVRTexIdentifier[4] = "PVR!"; enum { - kPVRTextureFlagTypeRGBA_4444= 0x10, - kPVRTextureFlagTypeRGBA_5551, - kPVRTextureFlagTypeRGBA_8888, - kPVRTextureFlagTypeRGB_565, - kPVRTextureFlagTypeRGB_555, // unsupported - kPVRTextureFlagTypeRGB_888, // unsupported - kPVRTextureFlagTypeI_8, - kPVRTextureFlagTypeAI_88, - kPVRTextureFlagTypePVRTC_2, - kPVRTextureFlagTypePVRTC_4, - kPVRTextureFlagTypeBGRA_8888, - kPVRTextureFlagTypeA_8, + kPVRTexturePixelTypeRGBA_4444= 0x10, + kPVRTexturePixelTypeRGBA_5551, + kPVRTexturePixelTypeRGBA_8888, + kPVRTexturePixelTypeRGB_565, + kPVRTexturePixelTypeRGB_555, // unsupported + kPVRTexturePixelTypeRGB_888, + kPVRTexturePixelTypeI_8, + kPVRTexturePixelTypeAI_88, + kPVRTexturePixelTypePVRTC_2, + kPVRTexturePixelTypePVRTC_4, + kPVRTexturePixelTypeBGRA_8888, + kPVRTexturePixelTypeA_8, }; -static const uint32_t tableFormats[][6] = { - +static const uint32_t tableFormats[][7] = { + // - PVR texture format // - OpenGL internal format // - OpenGL format // - OpenGL type // - bpp // - compressed - { kPVRTextureFlagTypeRGBA_4444, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 16, NO }, - { kPVRTextureFlagTypeRGBA_5551, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 16, NO }, - { kPVRTextureFlagTypeRGBA_8888, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, NO }, - { kPVRTextureFlagTypeRGB_565, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 16, NO }, - { kPVRTextureFlagTypeI_8, GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 8, NO }, - { kPVRTextureFlagTypeAI_88, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 16, NO }, -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - { kPVRTextureFlagTypePVRTC_2, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, -1, -1, 2, YES }, - { kPVRTextureFlagTypePVRTC_4, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, -1, -1, 4, YES }, + // - Cocos2d texture format constant + { kPVRTexturePixelTypeRGBA_4444, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 16, NO, kCCTexture2DPixelFormat_RGBA4444 }, + { kPVRTexturePixelTypeRGBA_5551, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 16, NO, kCCTexture2DPixelFormat_RGB5A1 }, + { kPVRTexturePixelTypeRGBA_8888, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, NO, kCCTexture2DPixelFormat_RGBA8888 }, + { kPVRTexturePixelTypeRGB_565, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 16, NO, kCCTexture2DPixelFormat_RGB565 }, + { kPVRTexturePixelTypeRGB_888, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, 24, NO, kCCTexture2DPixelFormat_RGB888 }, + { kPVRTexturePixelTypeA_8, GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, 8, NO, kCCTexture2DPixelFormat_A8 }, + { kPVRTexturePixelTypeI_8, GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 8, NO, kCCTexture2DPixelFormat_I8 }, + { kPVRTexturePixelTypeAI_88, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 16, NO, kCCTexture2DPixelFormat_AI88 }, +#ifdef __CC_PLATFORM_IOS + { kPVRTexturePixelTypePVRTC_2, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, -1, -1, 2, YES, kCCTexture2DPixelFormat_PVRTC2 }, + { kPVRTexturePixelTypePVRTC_4, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, -1, -1, 4, YES, kCCTexture2DPixelFormat_PVRTC4 }, #endif // iphone only - { kPVRTextureFlagTypeBGRA_8888, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE, 32, NO }, - { kPVRTextureFlagTypeA_8, GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, 8, NO }, + { kPVRTexturePixelTypeBGRA_8888, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE, 32, NO, kCCTexture2DPixelFormat_RGBA8888 }, }; #define MAX_TABLE_ELEMENTS (sizeof(tableFormats) / sizeof(tableFormats[0])) @@ -122,6 +137,7 @@ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE kCCInternalOpenGLType, kCCInternalBPP, kCCInternalCompressedImage, + kCCInternalCCTexture2DPixelFormat, }; typedef struct _PVRTexHeader @@ -151,9 +167,10 @@ @implementation CCTexturePVR // cocos2d integration @synthesize retainName = retainName_; +@synthesize format = format_; -- (BOOL)unpackPVRData:(unsigned char*)data PVRLen:(unsigned int)len +- (BOOL)unpackPVRData:(unsigned char*)data PVRLen:(NSUInteger)len { BOOL success = FALSE; PVRTexHeader *header = NULL; @@ -163,9 +180,9 @@ - (BOOL)unpackPVRData:(unsigned char*)data PVRLen:(unsigned int)len uint32_t width = 0, height = 0, bpp = 4; uint8_t *bytes = NULL; uint32_t formatFlags; - + header = (PVRTexHeader *)data; - + pvrTag = CFSwapInt32LittleToHost(header->pvrTag); if ((uint32_t)gPVRTexIdentifier[0] != ((pvrTag >> 0) & 0xff) || @@ -175,51 +192,54 @@ - (BOOL)unpackPVRData:(unsigned char*)data PVRLen:(unsigned int)len { return FALSE; } - + + CCConfiguration *configuration = [CCConfiguration sharedConfiguration]; + flags = CFSwapInt32LittleToHost(header->flags); formatFlags = flags & PVR_TEXTURE_FLAG_TYPE_MASK; - BOOL flipped = flags & PVR_TEXTURE_FLAG_FLIPPED_MASK; + BOOL flipped = flags & kPVRTextureFlagVerticalFlip; if( flipped ) CCLOG(@"cocos2d: WARNING: Image is flipped. Regenerate it using PVRTexTool"); - if( header->width != ccNextPOT(header->width) || header->height != ccNextPOT(header->height) ) { - CCLOG(@"cocos2d: WARNING: PVR NPOT textures are not supported. Regenerate it."); + if( ! [configuration supportsNPOT] && + ( header->width != ccNextPOT(header->width) || header->height != ccNextPOT(header->height ) ) ) { + CCLOG(@"cocos2d: ERROR: Loding an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height); return FALSE; } - + for( tableFormatIndex_=0; tableFormatIndex_ < (unsigned int)MAX_TABLE_ELEMENTS ; tableFormatIndex_++) { if( tableFormats[tableFormatIndex_][kCCInternalPVRTextureFormat] == formatFlags ) { - + numberOfMipmaps_ = 0; - + width_ = width = CFSwapInt32LittleToHost(header->width); height_ = height = CFSwapInt32LittleToHost(header->height); - + if (CFSwapInt32LittleToHost(header->bitmaskAlpha)) hasAlpha_ = TRUE; else hasAlpha_ = FALSE; - + dataLength = CFSwapInt32LittleToHost(header->dataLength); bytes = ((uint8_t *)data) + sizeof(PVRTexHeader); - + format_ = tableFormats[tableFormatIndex_][kCCInternalCCTexture2DPixelFormat]; + bpp = tableFormats[tableFormatIndex_][kCCInternalBPP]; + // Calculate the data size for each texture level and respect the minimum number of blocks while (dataOffset < dataLength) { switch (formatFlags) { - case kPVRTextureFlagTypePVRTC_2: + case kPVRTexturePixelTypePVRTC_2: blockSize = 8 * 4; // Pixel by pixel block size for 2bpp widthBlocks = width / 8; heightBlocks = height / 4; - bpp = 2; break; - case kPVRTextureFlagTypePVRTC_4: + case kPVRTexturePixelTypePVRTC_4: blockSize = 4 * 4; // Pixel by pixel block size for 4bpp widthBlocks = width / 4; heightBlocks = height / 4; - bpp = 4; break; - case kPVRTextureFlagTypeBGRA_8888: + case kPVRTexturePixelTypeBGRA_8888: if( ! [[CCConfiguration sharedConfiguration] supportsBGRA8888] ) { CCLOG(@"cocos2d: TexturePVR. BGRA8888 not supported on this device"); return FALSE; @@ -228,10 +248,9 @@ - (BOOL)unpackPVRData:(unsigned char*)data PVRLen:(unsigned int)len blockSize = 1; widthBlocks = width; heightBlocks = height; - bpp = tableFormats[ tableFormatIndex_][ kCCInternalBPP]; break; } - + // Clamp to minimum number of blocks if (widthBlocks < 2) widthBlocks = 2; @@ -239,127 +258,130 @@ - (BOOL)unpackPVRData:(unsigned char*)data PVRLen:(unsigned int)len heightBlocks = 2; dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8); - float packetLenght = (dataLength-dataOffset); - packetLenght = packetLenght > dataSize ? dataSize : packetLenght; - + float packetLength = (dataLength-dataOffset); + packetLength = packetLength > dataSize ? dataSize : packetLength; + mipmaps_[numberOfMipmaps_].address = bytes+dataOffset; - mipmaps_[numberOfMipmaps_].len = packetLenght; + mipmaps_[numberOfMipmaps_].len = packetLength; numberOfMipmaps_++; - + NSAssert( numberOfMipmaps_ < CC_PVRMIPMAP_MAX, @"TexturePVR: Maximum number of mimpaps reached. Increate the CC_PVRMIPMAP_MAX value"); - - dataOffset += packetLenght; - + + dataOffset += packetLength; + width = MAX(width >> 1, 1); height = MAX(height >> 1, 1); } - + success = TRUE; break; } } - + if( ! success ) - CCLOG(@"cocos2d: WARNING: Unssupported PVR Pixel Format: 0x%2x", formatFlags); - + CCLOG(@"cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%2x. Re-encode it with a OpenGL pixel format variant", formatFlags); + return success; } - (BOOL)createGLTexture { - NSUInteger width = width_; - NSUInteger height = height_; + GLsizei width = width_; + GLsizei height = height_; GLenum err; - + if (numberOfMipmaps_ > 0) { if (name_ != 0) - glDeleteTextures(1, &name_); - + ccGLDeleteTexture( name_ ); + + glPixelStorei(GL_UNPACK_ALIGNMENT,1); glGenTextures(1, &name_); - glBindTexture(GL_TEXTURE_2D, name_); + ccGLBindTexture2D( name_ ); + } + CHECK_GL_ERROR(); // clean possible GL error + // Generate textures with mipmaps - for (NSUInteger i=0; i < numberOfMipmaps_; i++) + for (GLint i=0; i < numberOfMipmaps_; i++) { GLenum internalFormat = tableFormats[tableFormatIndex_][kCCInternalOpenGLInternalFormat]; GLenum format = tableFormats[tableFormatIndex_][kCCInternalOpenGLFormat]; GLenum type = tableFormats[tableFormatIndex_][kCCInternalOpenGLType]; BOOL compressed = tableFormats[tableFormatIndex_][kCCInternalCompressedImage]; - + if( compressed && ! [[CCConfiguration sharedConfiguration] supportsPVRTC] ) { CCLOG(@"cocos2d: WARNING: PVRTC images are not supported"); return FALSE; - } - + } + unsigned char *data = mipmaps_[i].address; unsigned int datalen = mipmaps_[i].len; - + if( compressed) glCompressedTexImage2D(GL_TEXTURE_2D, i, internalFormat, width, height, 0, datalen, data); - else + else glTexImage2D(GL_TEXTURE_2D, i, internalFormat, width, height, 0, format, type, data); if( i > 0 && (width != height || ccNextPOT(width) != width ) ) - CCLOG(@"cocos2d: TexturePVR. WARNING. Mipmap level %lu is not squared. Texture won't render correctly. width=%lu != height=%lu", i, width, height); - + CCLOG(@"cocos2d: TexturePVR. WARNING. Mipmap level %u is not squared. Texture won't render correctly. width=%u != height=%u", i, width, height); + err = glGetError(); if (err != GL_NO_ERROR) { - CCLOG(@"cocos2d: TexturePVR: Error uploading compressed texture level: %u . glError: 0x%04X", (unsigned int)i, err); + CCLOG(@"cocos2d: TexturePVR: Error uploading compressed texture level: %u . glError: 0x%04X", i, err); return FALSE; } - + width = MAX(width >> 1, 1); height = MAX(height >> 1, 1); } - + return TRUE; } - (id)initWithContentsOfFile:(NSString *)path { - if((self = [super init])) - { + if((self = [super init])) + { unsigned char *pvrdata = NULL; - int pvrlen = 0; - NSString *lowerCase = [path lowercaseString]; - - if ( [lowerCase hasSuffix:@".ccz"]) + NSInteger pvrlen = 0; + NSString *lowerCase = [path lowercaseString]; + + if ( [lowerCase hasSuffix:@".ccz"]) pvrlen = ccInflateCCZFile( [path UTF8String], &pvrdata ); - + else if( [lowerCase hasSuffix:@".gz"] ) pvrlen = ccInflateGZipFile( [path UTF8String], &pvrdata ); - + else pvrlen = ccLoadFileIntoMemory( [path UTF8String], &pvrdata ); - + if( pvrlen < 0 ) { [self release]; return nil; - } - + } + numberOfMipmaps_ = 0; - + name_ = 0; width_ = height_ = 0; tableFormatIndex_ = -1; hasAlpha_ = FALSE; retainName_ = NO; // cocos2d integration - + if( ! [self unpackPVRData:pvrdata PVRLen:pvrlen] || ![self createGLTexture] ) { free(pvrdata); [self release]; return nil; } - - free(pvrdata); + free(pvrdata); } return self; @@ -373,7 +395,7 @@ - (id)initWithContentsOfURL:(NSURL *)url [self release]; return nil; } - + return [self initWithContentsOfFile:[url path]]; } @@ -388,7 +410,7 @@ + (id)pvrTextureWithContentsOfURL:(NSURL *)url { if (![url isFileURL]) return nil; - + return [CCTexturePVR pvrTextureWithContentsOfFile:[url path]]; } @@ -396,10 +418,10 @@ + (id)pvrTextureWithContentsOfURL:(NSURL *)url - (void)dealloc { CCLOGINFO( @"cocos2d: deallocing %@", self); - + if (name_ != 0 && ! retainName_ ) - glDeleteTextures(1, &name_); - + ccGLDeleteTexture( name_ ); + [super dealloc]; } diff --git a/Example/libs/cocos2d/CCTileMapAtlas.h b/Example/libs/cocos2d/CCTileMapAtlas.h index e4b60e2..e8365e4 100644 --- a/Example/libs/cocos2d/CCTileMapAtlas.h +++ b/Example/libs/cocos2d/CCTileMapAtlas.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,15 +29,15 @@ #import "Support/TGAlib.h" /** CCTileMapAtlas is a subclass of CCAtlasNode. - + It knows how to render a map based of tiles. The tiles must be in a .PNG format while the map must be a .TGA file. - + For more information regarding the format, please see this post: http://www.cocos2d-iphone.org/archives/27 - + All features from CCAtlasNode are valid in CCTileMapAtlas - + IMPORTANT: This class is deprecated. It is maintained for compatibility reasons only. You SHOULD not use this class. @@ -44,13 +45,13 @@ */ @interface CCTileMapAtlas : CCAtlasNode { - + /// info about the map file tImageTGA *tgaInfo; - + /// x,y to altas dicctionary NSMutableDictionary *posToAtlasIndex; - + /// numbers of tiles to render int itemsToRender; } diff --git a/Example/libs/cocos2d/CCTileMapAtlas.m b/Example/libs/cocos2d/CCTileMapAtlas.m index 378ad03..084a11d 100644 --- a/Example/libs/cocos2d/CCTileMapAtlas.m +++ b/Example/libs/cocos2d/CCTileMapAtlas.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,7 +32,7 @@ @interface CCTileMapAtlas (Private) -(void) loadTGAfile:(NSString*)file; -(void) calculateItemsToRender; --(void) updateAtlasValueAt:(ccGridSize)pos withValue:(ccColor3B)value withIndex:(int)idx; +-(void) updateAtlasValueAt:(ccGridSize)pos withValue:(ccColor3B)value withIndex:(NSUInteger)idx; @end @@ -53,10 +54,12 @@ -(id) initWithTileFile:(NSString*)tile mapFile:(NSString*)map tileWidth:(int)w t if( (self=[super initWithTileFile:tile tileWidth:w tileHeight:h itemsToRender: itemsToRender]) ) { + color_ = ccWHITE; + posToAtlasIndex = [[NSMutableDictionary dictionaryWithCapacity:itemsToRender] retain]; [self updateAtlasValues]; - + [self setContentSize: CGSizeMake(tgaInfo->width*itemWidth_, tgaInfo->height*itemHeight_)]; } @@ -77,7 +80,7 @@ -(void) releaseMap { if( tgaInfo ) tgaDestroy(tgaInfo); - + tgaInfo = nil; [posToAtlasIndex release]; @@ -109,12 +112,12 @@ -(void) loadTGAfile:(NSString*)file // NSBundle *mainBndl = [CCDirector sharedDirector].loadingBundle; // NSString *resourcePath = [mainBndl resourcePath]; // NSString * path = [resourcePath stringByAppendingPathComponent:file]; - + tgaInfo = tgaLoad( [path UTF8String] ); #if 1 if( tgaInfo->status != TGA_OK ) [NSException raise:@"TileMapAtlasLoadTGA" format:@"TileMapAtas cannot load TGA file"]; - + #endif } @@ -127,19 +130,19 @@ -(void) setTile:(ccColor3B) tile at:(ccGridSize) pos NSAssert( pos.x < tgaInfo->width, @"Invalid position.x"); NSAssert( pos.y < tgaInfo->height, @"Invalid position.x"); NSAssert( tile.r != 0, @"R component must be non 0"); - + ccColor3B *ptr = (ccColor3B*) tgaInfo->imageData; ccColor3B value = ptr[pos.x + pos.y * tgaInfo->width]; if( value.r == 0 ) CCLOG(@"cocos2d: Value.r must be non 0."); else { ptr[pos.x + pos.y * tgaInfo->width] = tile; - + // XXX: this method consumes a lot of memory // XXX: a tree of something like that shall be impolemented NSNumber *num = [posToAtlasIndex objectForKey: [NSString stringWithFormat:@"%d,%d", pos.x, pos.y]]; [self updateAtlasValueAt:pos withValue:tile withIndex: [num integerValue]]; - } + } } -(ccColor3B) tileAt:(ccGridSize) pos @@ -147,37 +150,41 @@ -(ccColor3B) tileAt:(ccGridSize) pos NSAssert( tgaInfo != nil, @"tgaInfo must not be nil"); NSAssert( pos.x < tgaInfo->width, @"Invalid position.x"); NSAssert( pos.y < tgaInfo->height, @"Invalid position.y"); - + ccColor3B *ptr = (ccColor3B*) tgaInfo->imageData; ccColor3B value = ptr[pos.x + pos.y * tgaInfo->width]; - - return value; + + return value; } --(void) updateAtlasValueAt:(ccGridSize)pos withValue:(ccColor3B)value withIndex:(int)idx +-(void) updateAtlasValueAt:(ccGridSize)pos withValue:(ccColor3B)value withIndex:(NSUInteger)idx { ccV3F_C4B_T2F_Quad quad; - int x = pos.x; - int y = pos.y; + NSInteger x = pos.x; + NSInteger y = pos.y; float row = (value.r % itemsPerRow_); float col = (value.r / itemsPerRow_); - + float textureWide = [[textureAtlas_ texture] pixelsWide]; float textureHigh = [[textureAtlas_ texture] pixelsHigh]; + float itemWidthInPixels = itemWidth_ * CC_CONTENT_SCALE_FACTOR(); + float itemHeightInPixels = itemHeight_ * CC_CONTENT_SCALE_FACTOR(); + + #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - float left = (2*row*itemWidth_+1)/(2*textureWide); - float right = left+(itemWidth_*2-2)/(2*textureWide); - float top = (2*col*itemHeight_+1)/(2*textureHigh); - float bottom = top+(itemHeight_*2-2)/(2*textureHigh); + float left = (2*row*itemWidthInPixels+1)/(2*textureWide); + float right = left+(itemWidthInPixels*2-2)/(2*textureWide); + float top = (2*col*itemHeightInPixels+1)/(2*textureHigh); + float bottom = top+(itemHeightInPixels*2-2)/(2*textureHigh); #else - float left = (row*itemWidth_)/textureWide; - float right = left+itemWidth_/textureWide; - float top = (col*itemHeight_)/textureHigh; - float bottom = top+itemHeight_/textureHigh; + float left = (row*itemWidthInPixels)/textureWide; + float right = left+itemWidthInPixels/textureWide; + float top = (col*itemHeightInPixels)/textureHigh; + float bottom = top+itemHeightInPixels/textureHigh; #endif - + quad.tl.texCoords.u = left; quad.tl.texCoords.v = top; @@ -200,7 +207,12 @@ -(void) updateAtlasValueAt:(ccGridSize)pos withValue:(ccColor3B)value withIndex: quad.tr.vertices.x = (int)(x * itemWidth_ + itemWidth_); quad.tr.vertices.y = (int)(y * itemHeight_ + itemHeight_); quad.tr.vertices.z = 0.0f; - + + ccColor4B color = { color_.r, color_.g, color_.b, opacity_ }; + quad.tr.colors = color; + quad.tl.colors = color; + quad.br.colors = color; + quad.bl.colors = color; [textureAtlas_ updateQuad:&quad atIndex:idx]; } @@ -208,7 +220,7 @@ -(void) updateAtlasValues { NSAssert( tgaInfo != nil, @"tgaInfo must be non-nil"); - + int total = 0; for(int x = 0;x < tgaInfo->width; x++ ) { @@ -216,10 +228,10 @@ -(void) updateAtlasValues if( total < itemsToRender ) { ccColor3B *ptr = (ccColor3B*) tgaInfo->imageData; ccColor3B value = ptr[x + y * tgaInfo->width]; - + if( value.r != 0 ) { [self updateAtlasValueAt:ccg(x,y) withValue:value withIndex:total]; - + NSString *key = [NSString stringWithFormat:@"%d,%d", x,y]; NSNumber *num = [NSNumber numberWithInt:total]; [posToAtlasIndex setObject:num forKey:key]; diff --git a/Example/libs/cocos2d/CCTransition.h b/Example/libs/cocos2d/CCTransition.h index 619a8a3..f57a949 100644 --- a/Example/libs/cocos2d/CCTransition.h +++ b/Example/libs/cocos2d/CCTransition.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -86,14 +87,14 @@ typedef enum { /** CCTransitionRotoZoom: - Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming + Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming */ @interface CCTransitionRotoZoom : CCTransitionScene {} @end /** CCTransitionJumpZoom: - Zoom out and jump the outgoing scene, and then jump and zoom in the incoming + Zoom out and jump the outgoing scene, and then jump and zoom in the incoming */ @interface CCTransitionJumpZoom : CCTransitionScene {} @@ -120,7 +121,7 @@ typedef enum { /** CCTransitionMoveInT: Move in from to the top the incoming scene. */ -@interface CCTransitionMoveInT : CCTransitionMoveInL +@interface CCTransitionMoveInT : CCTransitionMoveInL {} @end @@ -145,7 +146,7 @@ typedef enum { /** CCTransitionSlideInR: Slide in the incoming scene from the right border. */ -@interface CCTransitionSlideInR : CCTransitionSlideInL +@interface CCTransitionSlideInR : CCTransitionSlideInL {} @end diff --git a/Example/libs/cocos2d/CCTransition.m b/Example/libs/cocos2d/CCTransition.m index 61f96b7..f360a29 100644 --- a/Example/libs/cocos2d/CCTransition.m +++ b/Example/libs/cocos2d/CCTransition.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,6 +28,7 @@ #import "CCTransition.h" #import "CCNode.h" +#import "CCSprite.h" #import "CCDirector.h" #import "CCActionInterval.h" #import "CCActionInstant.h" @@ -36,18 +38,19 @@ #import "CCActionTiledGrid.h" #import "CCActionEase.h" #import "CCRenderTexture.h" +#import "ccMacros.h" #import "Support/CGPointExtension.h" -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import "Platforms/iOS/CCTouchDispatcher.h" -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#import "Platforms/iOS/CCDirectorIOS.h" +#elif defined(__CC_PLATFORM_MAC) +#import "Platforms/Mac/CCDirectorMac.h" #import "Platforms/Mac/CCEventDispatcher.h" #endif -enum { - kSceneFade = 0xFADEFADE, -}; +const NSInteger kSceneFade = 0xFADEFADE; + @interface CCTransitionScene (Private) -(void) sceneOrder; @@ -63,23 +66,24 @@ +(id) transitionWithDuration:(ccTime) t scene:(CCScene*)s -(id) initWithDuration:(ccTime) t scene:(CCScene*)s { NSAssert( s != nil, @"Argument scene must be non-nil"); - + if( (self=[super init]) ) { - + duration_ = t; - + // retain inScene_ = [s retain]; outScene_ = [[CCDirector sharedDirector] runningScene]; [outScene_ retain]; - + NSAssert( inScene_ != outScene_, @"Incoming scene must be different from the outgoing scene" ); // disable events while transitions -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - [[CCTouchDispatcher sharedDispatcher] setDispatchEvents: NO]; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) - [[CCEventDispatcher sharedDispatcher] setDispatchEvents: NO]; + CCDirector *director = [CCDirector sharedDirector]; +#ifdef __CC_PLATFORM_IOS + [[director touchDispatcher] setDispatchEvents: NO]; +#elif defined(__CC_PLATFORM_MAC) + [[director eventDispatcher] setDispatchEvents: NO]; #endif [self sceneOrder]; @@ -93,6 +97,8 @@ -(void) sceneOrder -(void) draw { + [super draw]; + if( inSceneOnTop_ ) { [outScene_ visit]; [inScene_ visit]; @@ -104,42 +110,42 @@ -(void) draw -(void) finish { - /* clean up */ + /* clean up */ [inScene_ setVisible:YES]; [inScene_ setPosition:ccp(0,0)]; [inScene_ setScale:1.0f]; [inScene_ setRotation:0.0f]; [inScene_.camera restore]; - + [outScene_ setVisible:NO]; [outScene_ setPosition:ccp(0,0)]; [outScene_ setScale:1.0f]; [outScene_ setRotation:0.0f]; [outScene_.camera restore]; - + [self schedule:@selector(setNewScene:) interval:0]; } -(void) setNewScene: (ccTime) dt -{ +{ [self unschedule:_cmd]; - + CCDirector *director = [CCDirector sharedDirector]; - + // Before replacing, save the "send cleanup to scene" sendCleanupToScene_ = [director sendCleanupToScene]; - + [director replaceScene: inScene_]; // enable events while transitions -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - [[CCTouchDispatcher sharedDispatcher] setDispatchEvents: YES]; -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) - [[CCEventDispatcher sharedDispatcher] setDispatchEvents: YES]; +#ifdef __CC_PLATFORM_IOS + [[director touchDispatcher] setDispatchEvents: YES]; +#elif defined(__CC_PLATFORM_MAC) + [[director eventDispatcher] setDispatchEvents: YES]; #endif - + // issue #267 - [outScene_ setVisible:YES]; + [outScene_ setVisible:YES]; } -(void) hideOutShowIn @@ -152,8 +158,12 @@ -(void) hideOutShowIn -(void) onEnter { [super onEnter]; + + // outScene_ should not receive the onExit callback + // only the onExitTransitionDidStart + [outScene_ onExitTransitionDidStart]; + [inScene_ onEnter]; - // outScene_ should not receive the onEnter callback } // custom onExit @@ -162,7 +172,7 @@ -(void) onExit [super onExit]; [outScene_ onExit]; - // inScene_ should not receive the onExit callback + // inScene_ should not receive the onEnter callback // only the onEnterTransitionDidFinish [inScene_ onEnterTransitionDidFinish]; } @@ -171,7 +181,7 @@ -(void) onExit -(void) cleanup { [super cleanup]; - + if( sendCleanupToScene_ ) [outScene_ cleanup]; } @@ -209,21 +219,21 @@ @implementation CCTransitionRotoZoom -(void) onEnter { [super onEnter]; - + [inScene_ setScale:0.001f]; [outScene_ setScale:1.0f]; - + [inScene_ setAnchorPoint:ccp(0.5f, 0.5f)]; [outScene_ setAnchorPoint:ccp(0.5f, 0.5f)]; - + CCActionInterval *rotozoom = [CCSequence actions: [CCSpawn actions: [CCScaleBy actionWithDuration:duration_/2 scale:0.001f], [CCRotateBy actionWithDuration:duration_/2 angle:360 *2], nil], [CCDelayTime actionWithDuration:duration_/2], nil]; - - + + [outScene_ runAction: rotozoom]; [inScene_ runAction: [CCSequence actions: [rotozoom reverse], @@ -240,7 +250,7 @@ -(void) onEnter { [super onEnter]; CGSize s = [[CCDirector sharedDirector] winSize]; - + [inScene_ setScale:0.5f]; [inScene_ setPosition:ccp( s.width,0 )]; @@ -250,12 +260,12 @@ -(void) onEnter CCActionInterval *jump = [CCJumpBy actionWithDuration:duration_/4 position:ccp(-s.width,0) height:s.width/4 jumps:2]; CCActionInterval *scaleIn = [CCScaleTo actionWithDuration:duration_/4 scale:1.0f]; CCActionInterval *scaleOut = [CCScaleTo actionWithDuration:duration_/4 scale:0.5f]; - + CCActionInterval *jumpZoomOut = [CCSequence actions: scaleOut, jump, nil]; CCActionInterval *jumpZoomIn = [CCSequence actions: jump, scaleIn, nil]; - + CCActionInterval *delay = [CCDelayTime actionWithDuration:duration_/2]; - + [outScene_ runAction: jumpZoomOut]; [inScene_ runAction: [CCSequence actions: delay, jumpZoomIn, @@ -271,9 +281,9 @@ @implementation CCTransitionMoveInL -(void) onEnter { [super onEnter]; - + [self initScenes]; - + CCActionInterval *a = [self action]; [inScene_ runAction: [CCSequence actions: @@ -281,7 +291,7 @@ -(void) onEnter [CCCallFunc actionWithTarget:self selector:@selector(finish)], nil] ]; - + } -(CCActionInterval*) action { @@ -349,7 +359,7 @@ -(void) onEnter [super onEnter]; [self initScenes]; - + CCActionInterval *in = [self action]; CCActionInterval *out = [self action]; @@ -358,7 +368,7 @@ -(void) onEnter [self easeActionWithAction:out], [CCCallFunc actionWithTarget:self selector:@selector(finish)], nil]; - + [inScene_ runAction: inAction]; [outScene_ runAction: outAction]; } @@ -458,13 +468,13 @@ @implementation CCTransitionShrinkGrow -(void) onEnter { [super onEnter]; - + [inScene_ setScale:0.001f]; [outScene_ setScale:1.0f]; [inScene_ setAnchorPoint:ccp(2/3.0f,0.5f)]; - [outScene_ setAnchorPoint:ccp(1/3.0f,0.5f)]; - + [outScene_ setAnchorPoint:ccp(1/3.0f,0.5f)]; + CCActionInterval *scaleOut = [CCScaleTo actionWithDuration:duration_ scale:0.01f]; CCActionInterval *scaleIn = [CCScaleTo actionWithDuration:duration_ scale:1.0f]; @@ -488,7 +498,7 @@ @implementation CCTransitionFlipX -(void) onEnter { [super onEnter]; - + CCActionInterval *inA, *outA; [inScene_ setVisible: NO]; @@ -506,7 +516,7 @@ -(void) onEnter outDeltaZ = -90; outAngleZ = 0; } - + inA = [CCSequence actions: [CCDelayTime actionWithDuration:duration_/2], [CCShow action], @@ -516,12 +526,12 @@ -(void) onEnter outA = [CCSequence actions: [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:0 deltaAngleX:0], [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], + [CCDelayTime actionWithDuration:duration_/2], nil ]; - + [inScene_ runAction: inA]; [outScene_ runAction: outA]; - + } @end @@ -532,7 +542,7 @@ @implementation CCTransitionFlipY -(void) onEnter { [super onEnter]; - + CCActionInterval *inA, *outA; [inScene_ setVisible: NO]; @@ -559,12 +569,12 @@ -(void) onEnter outA = [CCSequence actions: [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:90 deltaAngleX:0], [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], + [CCDelayTime actionWithDuration:duration_/2], nil ]; - + [inScene_ runAction: inA]; [outScene_ runAction: outA]; - + } @end @@ -575,7 +585,7 @@ @implementation CCTransitionFlipAngular -(void) onEnter { [super onEnter]; - + CCActionInterval *inA, *outA; [inScene_ setVisible: NO]; @@ -602,7 +612,7 @@ -(void) onEnter outA = [CCSequence actions: [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:45 deltaAngleX:0], [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], + [CCDelayTime actionWithDuration:duration_/2], nil ]; [inScene_ runAction: inA]; @@ -617,13 +627,13 @@ @implementation CCTransitionZoomFlipX -(void) onEnter { [super onEnter]; - + CCActionInterval *inA, *outA; [inScene_ setVisible: NO]; - + float inDeltaZ, inAngleZ; float outDeltaZ, outAngleZ; - + if( orientation == kOrientationRightOver ) { inDeltaZ = 90; inAngleZ = 270; @@ -650,9 +660,9 @@ -(void) onEnter [CCScaleTo actionWithDuration:duration_/2 scale:0.5f], nil], [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], + [CCDelayTime actionWithDuration:duration_/2], nil ]; - + inScene_.scale = 0.5f; [inScene_ runAction: inA]; [outScene_ runAction: outA]; @@ -666,10 +676,10 @@ @implementation CCTransitionZoomFlipY -(void) onEnter { [super onEnter]; - + CCActionInterval *inA, *outA; [inScene_ setVisible: NO]; - + float inDeltaZ, inAngleZ; float outDeltaZ, outAngleZ; @@ -684,7 +694,7 @@ -(void) onEnter outDeltaZ = -90; outAngleZ = 0; } - + inA = [CCSequence actions: [CCDelayTime actionWithDuration:duration_/2], [CCSpawn actions: @@ -698,9 +708,9 @@ -(void) onEnter [CCSpawn actions: [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:90 deltaAngleX:0], [CCScaleTo actionWithDuration:duration_/2 scale:0.5f], - nil], + nil], [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], + [CCDelayTime actionWithDuration:duration_/2], nil ]; inScene_.scale = 0.5f; @@ -716,13 +726,13 @@ @implementation CCTransitionZoomFlipAngular -(void) onEnter { [super onEnter]; - + CCActionInterval *inA, *outA; [inScene_ setVisible: NO]; - + float inDeltaZ, inAngleZ; float outDeltaZ, outAngleZ; - + if( orientation == kOrientationRightOver ) { inDeltaZ = 90; inAngleZ = 270; @@ -734,14 +744,14 @@ -(void) onEnter outDeltaZ = -90; outAngleZ = 0; } - + inA = [CCSequence actions: [CCDelayTime actionWithDuration:duration_/2], [CCSpawn actions: [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:inAngleZ deltaAngleZ:inDeltaZ angleX:-45 deltaAngleX:0], [CCScaleTo actionWithDuration:duration_/2 scale:1], [CCShow action], - nil], + nil], [CCShow action], [CCCallFunc actionWithTarget:self selector:@selector(finish)], nil ]; @@ -749,11 +759,11 @@ -(void) onEnter [CCSpawn actions: [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:45 deltaAngleX:0], [CCScaleTo actionWithDuration:duration_/2 scale:0.5f], - nil], + nil], [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], + [CCDelayTime actionWithDuration:duration_/2], nil ]; - + inScene_.scale = 0.5f; [inScene_ runAction: inA]; [outScene_ runAction: outA]; @@ -777,7 +787,7 @@ -(id) initWithDuration:(ccTime)d scene:(CCScene*)s withColor:(ccColor3B)aColor color.g = aColor.g; color.b = aColor.b; } - + return self; } @@ -789,15 +799,15 @@ -(id) initWithDuration:(ccTime)d scene:(CCScene*)s -(void) onEnter { [super onEnter]; - + CCLayerColor *l = [CCLayerColor layerWithColor:color]; [inScene_ setVisible: NO]; - + [self addChild: l z:2 tag:kSceneFade]; - - + + CCNode *f = [self getChildByTag:kSceneFade]; - + CCActionInterval *a = [CCSequence actions: [CCFadeIn actionWithDuration:duration_/2], [CCCallFunc actionWithTarget:self selector:@selector(hideOutShowIn)], @@ -828,63 +838,63 @@ -(void) draw -(void) onEnter { [super onEnter]; - + // create a transparent color layer // in which we are going to add our rendertextures ccColor4B color = {0,0,0,0}; CGSize size = [[CCDirector sharedDirector] winSize]; CCLayerColor * layer = [CCLayerColor layerWithColor:color]; - + // create the first render texture for inScene_ CCRenderTexture *inTexture = [CCRenderTexture renderTextureWithWidth:size.width height:size.height]; inTexture.sprite.anchorPoint= ccp(0.5f,0.5f); inTexture.position = ccp(size.width/2, size.height/2); inTexture.anchorPoint = ccp(0.5f,0.5f); - + // render inScene_ to its texturebuffer [inTexture begin]; [inScene_ visit]; [inTexture end]; - + // create the second render texture for outScene_ CCRenderTexture *outTexture = [CCRenderTexture renderTextureWithWidth:size.width height:size.height]; outTexture.sprite.anchorPoint= ccp(0.5f,0.5f); outTexture.position = ccp(size.width/2, size.height/2); outTexture.anchorPoint = ccp(0.5f,0.5f); - + // render outScene_ to its texturebuffer [outTexture begin]; [outScene_ visit]; [outTexture end]; - + // create blend functions - + ccBlendFunc blend1 = {GL_ONE, GL_ONE}; // inScene_ will lay on background and will not be used with alpha - ccBlendFunc blend2 = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA}; // we are going to blend outScene_ via alpha - + ccBlendFunc blend2 = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA}; // we are going to blend outScene_ via alpha + // set blendfunctions [inTexture.sprite setBlendFunc:blend1]; - [outTexture.sprite setBlendFunc:blend2]; - + [outTexture.sprite setBlendFunc:blend2]; + // add render textures to the layer [layer addChild:inTexture]; [layer addChild:outTexture]; - + // initial opacity: [inTexture.sprite setOpacity:255]; [outTexture.sprite setOpacity:255]; - + // create the blend action CCActionInterval * layerAction = [CCSequence actions: [CCFadeTo actionWithDuration:duration_ opacity:0], [CCCallFunc actionWithTarget:self selector:@selector(hideOutShowIn)], [CCCallFunc actionWithTarget:self selector:@selector(finish)], nil ]; - - + + // run the blend action [outTexture.sprite runAction: layerAction]; - + // add the layer (which contains our two rendertextures) to the scene [self addChild: layer z:2 tag:kSceneFade]; } @@ -892,10 +902,10 @@ -(void) onEnter // clean up on exit -(void) onExit { - // remove our layer and release all containing objects + // remove our layer and release all containing objects [self removeChildByTag:kSceneFade cleanup:NO]; - - [super onExit]; + + [super onExit]; } @end @@ -917,7 +927,7 @@ -(void) onEnter float aspect = s.width / s.height; int x = 12 * aspect; int y = 12; - + id toff = [CCTurnOffTiles actionWithSize: ccg(x,y) duration:duration_]; id action = [self easeActionWithAction:toff]; [outScene_ runAction: [CCSequence actions: action, @@ -946,7 +956,7 @@ -(void) onEnter [super onEnter]; inScene_.visible = NO; - + id split = [self action]; id seq = [CCSequence actions: split, @@ -998,12 +1008,12 @@ -(void) sceneOrder -(void) onEnter { [super onEnter]; - + CGSize s = [[CCDirector sharedDirector] winSize]; float aspect = s.width / s.height; int x = 12 * aspect; int y = 12; - + id action = [self actionWithSize:ccg(x,y)]; [outScene_ runAction: [CCSequence actions: @@ -1022,7 +1032,7 @@ -(CCActionInterval*) actionWithSize: (ccGridSize) v -(CCActionInterval*) easeActionWithAction:(CCActionInterval*)action { return action; -// return [EaseIn actionWithAction:action rate:2.0f]; +// return [CCEaseOut actionWithAction:action rate:3.0f]; } @end diff --git a/Example/libs/cocos2d/CCTransitionPageTurn.h b/Example/libs/cocos2d/CCTransitionPageTurn.h index aacb7fc..1e83c08 100644 --- a/Example/libs/cocos2d/CCTransitionPageTurn.h +++ b/Example/libs/cocos2d/CCTransitionPageTurn.h @@ -2,17 +2,17 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009 Sindesso Pty Ltd http://www.sindesso.com/ - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,10 +30,10 @@ * A transition which peels back the bottom right hand corner of a scene * to transition to the scene beneath it simulating a page turn * - * This uses a 3DAction so it's strongly recommended that depth buffering + * This uses a 3DAction so it is strongly recommended that depth buffering * is turned on in CCDirector using: * - * [[CCDirector sharedDirector] setDepthBufferFormat:kCCDepthBuffer16]; + * [[CCDirector sharedDirector] setDepthBufferFormat:kCCDepthBuffer16]; * * @since v0.8.2 */ @@ -43,14 +43,14 @@ } /** * creates a base transition with duration and incoming scene - * if back is TRUE then the effect is reversed to appear as if the incoming + * if back is TRUE then the effect is reversed to appear as if the incoming * scene is being turned from left over the outgoing scene */ +(id) transitionWithDuration:(ccTime) t scene:(CCScene*)s backwards:(BOOL) back; /** * creates a base transition with duration and incoming scene - * if back is TRUE then the effect is reversed to appear as if the incoming + * if back is TRUE then the effect is reversed to appear as if the incoming * scene is being turned from left over the outgoing scene */ -(id) initWithDuration:(ccTime) t scene:(CCScene*)s backwards:(BOOL) back; diff --git a/Example/libs/cocos2d/CCTransitionPageTurn.m b/Example/libs/cocos2d/CCTransitionPageTurn.m index bff43a7..810284f 100644 --- a/Example/libs/cocos2d/CCTransitionPageTurn.m +++ b/Example/libs/cocos2d/CCTransitionPageTurn.m @@ -2,17 +2,17 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009 Sindesso Pty Ltd http://www.sindesso.com/ - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -58,7 +58,7 @@ -(void) sceneOrder -(void) onEnter { [super onEnter]; - + CGSize s = [[CCDirector sharedDirector] winSize]; int x, y; if( s.width > s.height) @@ -71,9 +71,9 @@ -(void) onEnter x = 12; y = 16; } - + id action = [self actionWithSize:ccg(x,y)]; - + if(! back_ ) { [outScene_ runAction: [CCSequence actions: @@ -95,7 +95,7 @@ -(void) onEnter nil] ]; } - + } -(CCActionInterval*) actionWithSize: (ccGridSize) v diff --git a/Example/libs/cocos2d/CCTransitionRadial.h b/Example/libs/cocos2d/CCTransitionRadial.h deleted file mode 100644 index 6d4a5e0..0000000 --- a/Example/libs/cocos2d/CCTransitionRadial.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Lam Pham - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCTransition.h" -#import "CCProgressTimer.h" -#import "CCActionProgressTimer.h" - -/** CCTransitionRadialCCW transition. - A counter colock-wise radial transition to the next scene - */ -@interface CCTransitionRadialCCW : CCTransitionScene -@end - -/** CCTransitionRadialCW transition. - A counter colock-wise radial transition to the next scene -*/ -@interface CCTransitionRadialCW : CCTransitionRadialCCW -@end diff --git a/Example/libs/cocos2d/CCTransitionRadial.m b/Example/libs/cocos2d/CCTransitionRadial.m deleted file mode 100644 index a892f35..0000000 --- a/Example/libs/cocos2d/CCTransitionRadial.m +++ /dev/null @@ -1,115 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Lam Pham - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - - -#import "CCDirector.h" -#import "CCTransitionRadial.h" -#import "CCRenderTexture.h" -#import "CCLayer.h" -#import "CCActionInstant.h" -#import "Support/CGPointExtension.h" - -enum { - kSceneRadial = 0xc001, -}; - -#pragma mark - -#pragma mark Transition Radial CCW - -@implementation CCTransitionRadialCCW --(void) sceneOrder -{ - inSceneOnTop_ = NO; -} - --(CCProgressTimerType) radialType -{ - return kCCProgressTimerTypeRadialCCW; -} - --(void) onEnter -{ - [super onEnter]; - // create a transparent color layer - // in which we are going to add our rendertextures - CGSize size = [[CCDirector sharedDirector] winSize]; - - // create the second render texture for outScene - CCRenderTexture *outTexture = [CCRenderTexture renderTextureWithWidth:size.width height:size.height]; - outTexture.sprite.anchorPoint= ccp(0.5f,0.5f); - outTexture.position = ccp(size.width/2, size.height/2); - outTexture.anchorPoint = ccp(0.5f,0.5f); - - // render outScene to its texturebuffer - [outTexture clear:0 g:0 b:0 a:1]; - [outTexture begin]; - [outScene_ visit]; - [outTexture end]; - - // Since we've passed the outScene to the texture we don't need it. - [self hideOutShowIn]; - - // We need the texture in RenderTexture. - CCProgressTimer *outNode = [CCProgressTimer progressWithTexture:outTexture.sprite.texture]; - // but it's flipped upside down so we flip the sprite - outNode.sprite.flipY = YES; - // Return the radial type that we want to use - outNode.type = [self radialType]; - outNode.percentage = 100.f; - outNode.position = ccp(size.width/2, size.height/2); - outNode.anchorPoint = ccp(0.5f,0.5f); - - // create the blend action - CCActionInterval * layerAction = [CCSequence actions: - [CCProgressFromTo actionWithDuration:duration_ from:100.f to:0.f], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - // run the blend action - [outNode runAction: layerAction]; - - // add the layer (which contains our two rendertextures) to the scene - [self addChild: outNode z:2 tag:kSceneRadial]; -} - -// clean up on exit --(void) onExit -{ - // remove our layer and release all containing objects - [self removeChildByTag:kSceneRadial cleanup:NO]; - [super onExit]; -} -@end - -#pragma mark - -#pragma mark Transition Radial CW - -@implementation CCTransitionRadialCW --(CCProgressTimerType) radialType -{ - return kCCProgressTimerTypeRadialCW; -} -@end - diff --git a/Example/libs/cocos2d/Platforms/CCGL.h b/Example/libs/cocos2d/Platforms/CCGL.h index 9dc3e9b..26d6dd0 100644 --- a/Example/libs/cocos2d/Platforms/CCGL.h +++ b/Example/libs/cocos2d/Platforms/CCGL.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,57 +27,33 @@ // Common layer for OpenGL stuff // -#import +#import "../ccMacros.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#import -#import +#if __CC_PLATFORM_IOS +#import +#import #import -#import "iOS/glu.h" -#import "iOS/EAGLView.h" +#import "iOS/CCGLView.h" -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif __CC_PLATFORM_MAC #import #import #import // needed for NSOpenGLView -#import "Mac/MacGLView.h" +#import "Mac/CCGLView.h" #endif // iOS -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#define CC_GLVIEW EAGLView -#define ccglOrtho glOrthof -#define ccglClearDepth glClearDepthf -#define ccglGenerateMipmap glGenerateMipmapOES -#define ccglGenFramebuffers glGenFramebuffersOES -#define ccglBindFramebuffer glBindFramebufferOES -#define ccglFramebufferTexture2D glFramebufferTexture2DOES -#define ccglDeleteFramebuffers glDeleteFramebuffersOES -#define ccglCheckFramebufferStatus glCheckFramebufferStatusOES -#define ccglTranslate glTranslatef - -#define CC_GL_FRAMEBUFFER GL_FRAMEBUFFER_OES -#define CC_GL_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING_OES -#define CC_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0_OES -#define CC_GL_FRAMEBUFFER_COMPLETE GL_FRAMEBUFFER_COMPLETE_OES +#if __CC_PLATFORM_IOS +#define glClearDepth glClearDepthf +#define glDeleteVertexArrays glDeleteVertexArraysOES +#define glGenVertexArrays glGenVertexArraysOES +#define glBindVertexArray glBindVertexArrayOES // Mac -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) -#define CC_GLVIEW MacGLView -#define ccglOrtho glOrtho -#define ccglClearDepth glClearDepth -#define ccglGenerateMipmap glGenerateMipmap -#define ccglGenFramebuffers glGenFramebuffers -#define ccglBindFramebuffer glBindFramebuffer -#define ccglFramebufferTexture2D glFramebufferTexture2D -#define ccglDeleteFramebuffers glDeleteFramebuffers -#define ccglCheckFramebufferStatus glCheckFramebufferStatus -#define ccglTranslate glTranslated - -#define CC_GL_FRAMEBUFFER GL_FRAMEBUFFER -#define CC_GL_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING -#define CC_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0 -#define CC_GL_FRAMEBUFFER_COMPLETE GL_FRAMEBUFFER_COMPLETE +#elif __CC_PLATFORM_MAC +#define glDeleteVertexArrays glDeleteVertexArraysAPPLE +#define glGenVertexArrays glGenVertexArraysAPPLE +#define glBindVertexArray glBindVertexArrayAPPLE #endif diff --git a/Example/libs/cocos2d/Platforms/CCNS.h b/Example/libs/cocos2d/Platforms/CCNS.h index a8d5e0a..4fe5535 100644 --- a/Example/libs/cocos2d/Platforms/CCNS.h +++ b/Example/libs/cocos2d/Platforms/CCNS.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,11 +27,11 @@ // Common layer for NS (Next-Step) stuff // -#import +#import "../ccMacros.h" #import // for NSObject -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #define CCRectFromString(__r__) CGRectFromString(__r__) #define CCPointFromString(__p__) CGPointFromString(__p__) @@ -42,9 +43,17 @@ #define CCTextAlignmentCenter UITextAlignmentCenter #define CCTextAlignmentLeft UITextAlignmentLeft #define CCTextAlignmentRight UITextAlignmentRight +#define CCLineBreakMode UILineBreakMode +#define CCLineBreakModeWordWrap UILineBreakModeWordWrap +#define CCLineBreakModeCharacterWrap UILineBreakModeCharacterWrap +#define CCLineBreakModeClip UILineBreakModeClip +#define CCLineBreakModeHeadTruncation UILineBreakModeHeadTruncation +#define CCLineBreakModeTailTruncation UILineBreakModeTailTruncation +#define CCLineBreakModeMiddleTruncation UILineBreakModeMiddleTruncation -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) + +#elif defined(__CC_PLATFORM_MAC) #define CCRectFromString(__r__) NSRectToCGRect( NSRectFromString(__r__) ) #define CCPointFromString(__p__) NSPointToCGPoint( NSPointFromString(__p__) ) @@ -56,6 +65,13 @@ #define CCTextAlignmentCenter NSCenterTextAlignment #define CCTextAlignmentLeft NSLeftTextAlignment #define CCTextAlignmentRight NSRightTextAlignment +#define CCLineBreakMode NSLineBreakMode +#define CCLineBreakModeWordWrap NSLineBreakByWordWrapping +#define CCLineBreakModeClip -1 +#define CCLineBreakModeHeadTruncation -1 +#define CCLineBreakModeTailTruncation -1 +#define CCLineBreakModeMiddleTruncation -1 + #endif diff --git a/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.h b/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.h index 1df12d3..63ff82f 100644 --- a/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.h +++ b/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,13 +26,14 @@ // Only compile this code on Mac. These files should not be included on your iOS project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_MAC #import #import "../../CCDirector.h" +@class CCEventDispatcher; + enum { /// If the window is resized, it won't be autoscaled kCCDirectorResize_NoScale, @@ -40,7 +42,10 @@ enum { }; @interface CCDirector (MacExtension) -/** converts an NSEvent to GL coordinates */ +/** sets the CCEventDispatcher (Mac only) */ +@property (nonatomic, readwrite, retain) CCEventDispatcher* eventDispatcher; + +/** converts an NSEvent to GL coordinates (Mac only) */ -(CGPoint) convertEventToGL:(NSEvent*)event; @end @@ -52,13 +57,17 @@ enum { BOOL isFullScreen_; int resizeMode_; CGPoint winOffset_; - CGSize originalWinSize_; - - MacGLView *fullScreenGLView_; + CGSize originalWinSize_; + NSWindow *fullScreenWindow_; - + + // Event Dispatcher + CCEventDispatcher *eventDispatcher_; + // cache - MacGLView *windowGLView_; + NSWindow *windowGLView_; + NSView *superViewGLView_; + NSRect originalWinRect_; // Original size and position } // whether or not the view is in fullscreen mode @@ -67,6 +76,8 @@ enum { // resize mode: with or without scaling @property (nonatomic, readwrite) int resizeMode; +@property (nonatomic, readwrite) CGSize originalWinSize; + /** Sets the view in fullscreen or window mode */ - (void) setFullScreen:(BOOL)fullscreen; @@ -95,5 +106,5 @@ enum { } @end -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.m b/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.m index 531646d..0f14edc 100644 --- a/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.m +++ b/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,19 +25,25 @@ // Only compile this code on Mac. These files should not be included on your iOS project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_MAC #import - + #import "CCDirectorMac.h" #import "CCEventDispatcher.h" -#import "MacGLView.h" +#import "CCGLView.h" +#import "CCWindow.h" #import "../../CCNode.h" #import "../../CCScheduler.h" #import "../../ccMacros.h" +#import "../../CCGLProgram.h" +#import "../../ccGLStateCache.h" + +// external +#import "kazmath/kazmath.h" +#import "kazmath/GL/matrix.h" #pragma mark - #pragma mark Director Mac extensions @@ -44,19 +51,30 @@ @interface CCDirector () -(void) setNextScene; --(void) showFPS; +-(void) showStats; -(void) calculateDeltaTime; +-(void) calculateMPF; @end @implementation CCDirector (MacExtension) -(CGPoint) convertEventToGL:(NSEvent*)event { - NSPoint point = [openGLView_ convertPoint:[event locationInWindow] fromView:nil]; + NSPoint point = [[self view] convertPoint:[event locationInWindow] fromView:nil]; CGPoint p = NSPointToCGPoint(point); - + return [(CCDirectorMac*)self convertToLogicalCoordinates:p]; } +-(void) setEventDispatcher:(CCEventDispatcher *)dispatcher +{ + NSAssert(NO, @"override me"); +} + +-(CCEventDispatcher *) eventDispatcher +{ + NSAssert(NO, @"override me"); + return nil; +} @end #pragma mark - @@ -65,27 +83,33 @@ -(CGPoint) convertEventToGL:(NSEvent*)event @implementation CCDirectorMac @synthesize isFullScreen = isFullScreen_; +@synthesize originalWinSize = originalWinSize_; -(id) init { if( (self = [super init]) ) { isFullScreen_ = NO; resizeMode_ = kCCDirectorResize_AutoScale; - - fullScreenGLView_ = nil; + + originalWinSize_ = CGSizeZero; fullScreenWindow_ = nil; windowGLView_ = nil; winOffset_ = CGPointZero; + + eventDispatcher_ = [[CCEventDispatcher alloc] init]; } - + return self; } - (void) dealloc { - [fullScreenGLView_ release]; + [eventDispatcher_ release]; + [view_ release]; + [superViewGLView_ release]; [fullScreenWindow_ release]; [windowGLView_ release]; + [super dealloc]; } @@ -97,71 +121,91 @@ - (void) setFullScreen:(BOOL)fullscreen // Mac OS X 10.6 and later offer a simplified mechanism to create full-screen contexts #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 - if( isFullScreen_ != fullscreen ) { + if (isFullScreen_ == fullscreen) + return; + + CCGLView *openGLview = (CCGLView*) self.view; + + if( fullscreen ) { + originalWinRect_ = [openGLview frame]; + + // Cache normal window and superview of openGLView + if(!windowGLView_) + windowGLView_ = [[openGLview window] retain]; + + [superViewGLView_ release]; + superViewGLView_ = [[openGLview superview] retain]; - isFullScreen_ = fullscreen; + + // Get screen size + NSRect displayRect = [[NSScreen mainScreen] frame]; + + // Create a screen-sized window on the display you want to take over + fullScreenWindow_ = [[CCWindow alloc] initWithFrame:displayRect fullscreen:YES]; + + // Remove glView from window + [openGLview removeFromSuperview]; + + // Set new frame + [openGLview setFrame:displayRect]; + + // Attach glView to fullscreen window + [fullScreenWindow_ setContentView:openGLview]; + + // Show the fullscreen window + [fullScreenWindow_ makeKeyAndOrderFront:self]; + [fullScreenWindow_ makeMainWindow]; + + } else { + + // Remove glView from fullscreen window + [openGLview removeFromSuperview]; + + // Release fullscreen window + [fullScreenWindow_ release]; + fullScreenWindow_ = nil; + + // Attach glView to superview + [superViewGLView_ addSubview:openGLview]; + + // Set new frame + [openGLview setFrame:originalWinRect_]; + + // Show the window + [windowGLView_ makeKeyAndOrderFront:self]; + [windowGLView_ makeMainWindow]; + } - if( fullscreen ) { - - // create the fullscreen view/window - NSRect mainDisplayRect, viewRect; - - // Create a screen-sized window on the display you want to take over - // Note, mainDisplayRect has a non-zero origin if the key window is on a secondary display - mainDisplayRect = [[NSScreen mainScreen] frame]; - fullScreenWindow_ = [[NSWindow alloc] initWithContentRect:mainDisplayRect - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:YES]; - - // Set the window level to be above the menu bar - [fullScreenWindow_ setLevel:NSMainMenuWindowLevel+1]; - - // Perform any other window configuration you desire - [fullScreenWindow_ setOpaque:YES]; - [fullScreenWindow_ setHidesOnDeactivate:YES]; - - // Create a view with a double-buffered OpenGL context and attach it to the window - // By specifying the non-fullscreen context as the shareContext, we automatically inherit the OpenGL objects (textures, etc) it has defined - viewRect = NSMakeRect(0.0, 0.0, mainDisplayRect.size.width, mainDisplayRect.size.height); - - fullScreenGLView_ = [[MacGLView alloc] initWithFrame:viewRect shareContext:[openGLView_ openGLContext]]; - - [fullScreenWindow_ setContentView:fullScreenGLView_]; - - // Show the window - [fullScreenWindow_ makeKeyAndOrderFront:self]; - - [self setOpenGLView:fullScreenGLView_]; - - } else { - - [fullScreenWindow_ release]; - [fullScreenGLView_ release]; - fullScreenWindow_ = nil; - fullScreenGLView_ = nil; - - [[windowGLView_ openGLContext] makeCurrentContext]; - [self setOpenGLView:windowGLView_]; - - } - - [openGLView_ setNeedsDisplay:YES]; - } + // issue #1189 + [windowGLView_ makeFirstResponder:openGLview]; + + isFullScreen_ = fullscreen; + + [openGLview retain]; // Retain +1 + + // re-configure glView + [self setView:openGLview]; + + [openGLview release]; // Retain -1 + + [openGLview setNeedsDisplay:YES]; #else #error Full screen is not supported for Mac OS 10.5 or older yet #error If you don't want FullScreen support, you can safely remove these 2 lines #endif } --(void) setOpenGLView:(MacGLView *)view +-(void) setView:(CCGLView *)view { - [super setOpenGLView:view]; - - // cache the NSWindow and NSOpenGLView created from the NIB - if( ! isFullScreen_ && ! windowGLView_) { - windowGLView_ = [view retain]; - originalWinSize_ = winSizeInPixels_; + if( view != view_) { + + [super setView:view]; + + // cache the NSWindow and NSOpenGLView created from the NIB + if( !isFullScreen_ && CGSizeEqualToSize(originalWinSize_, CGSizeZero)) + { + originalWinSize_ = winSizeInPixels_; + } } } @@ -173,93 +217,115 @@ -(int) resizeMode -(void) setResizeMode:(int)mode { if( mode != resizeMode_ ) { + resizeMode_ = mode; - [openGLView_ setNeedsDisplay: YES]; - - [self setProjection:projection_]; - - if( mode == kCCDirectorResize_AutoScale ) { - originalWinSize_ = winSizeInPixels_; - CCLOG(@"cocos2d: Warning. Switching back to AutoScale might break some stuff. Experimental stuff"); - } + [self setProjection:projection_]; + [self.view setNeedsDisplay: YES]; } } -(void) setProjection:(ccDirectorProjection)projection { CGSize size = winSizeInPixels_; - + CGPoint offset = CGPointZero; float widthAspect = size.width; float heightAspect = size.height; - - + + if( resizeMode_ == kCCDirectorResize_AutoScale && ! CGSizeEqualToSize(originalWinSize_, CGSizeZero ) ) { - + size = originalWinSize_; float aspect = originalWinSize_.width / originalWinSize_.height; widthAspect = winSizeInPixels_.width; heightAspect = winSizeInPixels_.width / aspect; - + if( heightAspect > winSizeInPixels_.height ) { widthAspect = winSizeInPixels_.height * aspect; - heightAspect = winSizeInPixels_.height; + heightAspect = winSizeInPixels_.height; } - + winOffset_.x = (winSizeInPixels_.width - widthAspect) / 2; winOffset_.y = (winSizeInPixels_.height - heightAspect) / 2; - + offset = winOffset_; } - + switch (projection) { case kCCDirectorProjection2D: + glViewport(offset.x, offset.y, widthAspect, heightAspect); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - ccglOrtho(0, size.width, 0, size.height, -1024, 1024); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); + kmGLMatrixMode(KM_GL_PROJECTION); + kmGLLoadIdentity(); + + kmMat4 orthoMatrix; + kmMat4OrthographicProjection(&orthoMatrix, 0, size.width, 0, size.height, -1024, 1024); + kmGLMultMatrix( &orthoMatrix ); + + kmGLMatrixMode(KM_GL_MODELVIEW); + kmGLLoadIdentity(); break; - + + case kCCDirectorProjection3D: + { + + float zeye = [self getZEye]; + glViewport(offset.x, offset.y, widthAspect, heightAspect); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - gluPerspective(60, (GLfloat)widthAspect/heightAspect, 0.1f, 1500.0f); - - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - - float eyeZ = size.height * [self getZEye] / winSizeInPixels_.height; - - gluLookAt( size.width/2, size.height/2, eyeZ, - size.width/2, size.height/2, 0, - 0.0f, 1.0f, 0.0f); + kmGLMatrixMode(KM_GL_PROJECTION); + kmGLLoadIdentity(); + + kmMat4 matrixPerspective, matrixLookup; + + // issue #1334 + kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, MAX(zeye*2,1500) ); +// kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, 1500); + + + kmGLMultMatrix(&matrixPerspective); + + + kmGLMatrixMode(KM_GL_MODELVIEW); + kmGLLoadIdentity(); + kmVec3 eye, center, up; + + float eyeZ = size.height * zeye / winSizeInPixels_.height; + + kmVec3Fill( &eye, size.width/2, size.height/2, eyeZ ); + kmVec3Fill( ¢er, size.width/2, size.height/2, 0 ); + kmVec3Fill( &up, 0, 1, 0); + kmMat4LookAt(&matrixLookup, &eye, ¢er, &up); + kmGLMultMatrix(&matrixLookup); break; - + } + case kCCDirectorProjectionCustom: - if( projectionDelegate_ ) - [projectionDelegate_ updateProjection]; + if( [delegate_ respondsToSelector:@selector(updateProjection)] ) + [delegate_ updateProjection]; break; - + default: - CCLOG(@"cocos2d: Director: unrecognized projecgtion"); + CCLOG(@"cocos2d: Director: unrecognized projection"); break; } - + projection_ = projection; + + ccSetProjectionMatrixDirty(); } + // If scaling is supported, then it should always return the original size // otherwise it should return the "real" size. -(CGSize) winSize { if( resizeMode_ == kCCDirectorResize_AutoScale ) return originalWinSize_; + return winSizeInPixels_; } @@ -271,23 +337,36 @@ -(CGSize) winSizeInPixels - (CGPoint) convertToLogicalCoordinates:(CGPoint)coords { CGPoint ret; - + if( resizeMode_ == kCCDirectorResize_NoScale ) ret = coords; - + else { - + float x_diff = originalWinSize_.width / (winSizeInPixels_.width - winOffset_.x * 2); float y_diff = originalWinSize_.height / (winSizeInPixels_.height - winOffset_.y * 2); - + float adjust_x = (winSizeInPixels_.width * x_diff - originalWinSize_.width ) / 2; float adjust_y = (winSizeInPixels_.height * y_diff - originalWinSize_.height ) / 2; - - ret = CGPointMake( (x_diff * coords.x) - adjust_x, ( y_diff * coords.y ) - adjust_y ); + + ret = CGPointMake( (x_diff * coords.x) - adjust_x, ( y_diff * coords.y ) - adjust_y ); } - + return ret; } + +-(void) setEventDispatcher:(CCEventDispatcher *)dispatcher +{ + if( dispatcher != eventDispatcher_ ) { + [eventDispatcher_ release]; + eventDispatcher_ = [dispatcher retain]; + } +} + +-(CCEventDispatcher *) eventDispatcher +{ + return eventDispatcher_; +} @end @@ -299,23 +378,23 @@ @implementation CCDirectorDisplayLink - (CVReturn) getFrameForTime:(const CVTimeStamp*)outputTime { -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD +#if (CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_DISPLAY_LINK_THREAD) if( ! runningThread_ ) runningThread_ = [NSThread currentThread]; - + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self drawScene]; - [[CCEventDispatcher sharedDispatcher] dispatchQueuedEvents]; - - [[NSRunLoop currentRunLoop] run]; - - [pool release]; + // Process timers and other events + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:nil]; + + [pool release]; + #else [self performSelector:@selector(drawScene) onThread:runningThread_ withObject:nil waitUntilDone:YES]; #endif - + return kCVReturnSuccess; } @@ -328,39 +407,47 @@ static CVReturn MyDisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTime - (void) startAnimation { -#if ! CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD + CCLOG(@"cocos2d: startAnimation"); +#if (CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_OWN_THREAD) runningThread_ = [[NSThread alloc] initWithTarget:self selector:@selector(mainLoop) object:nil]; - [runningThread_ start]; + [runningThread_ start]; +#elif (CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_MAIN_THREAD) + runningThread_ = [NSThread mainThread]; #endif - + gettimeofday( &lastUpdate_, NULL); - + // Create a display link capable of being used with all active displays CVDisplayLinkCreateWithActiveCGDisplays(&displayLink); - + // Set the renderer output callback function CVDisplayLinkSetOutputCallback(displayLink, &MyDisplayLinkCallback, self); - + // Set the display link for the current renderer - CGLContextObj cglContext = [[openGLView_ openGLContext] CGLContextObj]; - CGLPixelFormatObj cglPixelFormat = [[openGLView_ pixelFormat] CGLPixelFormatObj]; + CCGLView *openGLview = (CCGLView*) self.view; + CGLContextObj cglContext = [[openGLview openGLContext] CGLContextObj]; + CGLPixelFormatObj cglPixelFormat = [[openGLview pixelFormat] CGLPixelFormatObj]; CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, cglContext, cglPixelFormat); - + // Activate the display link CVDisplayLinkStart(displayLink); } - (void) stopAnimation { + CCLOG(@"cocos2d: stopAnimation"); + if( displayLink ) { CVDisplayLinkStop(displayLink); CVDisplayLinkRelease(displayLink); displayLink = NULL; - -#if ! CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD + +#if CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_OWN_THREAD [runningThread_ cancel]; [runningThread_ release]; runningThread_ = nil; +#elif (CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_MAIN_THREAD) + runningThread_ = nil; #endif } } @@ -383,89 +470,86 @@ -(void) mainLoop // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - + [[NSRunLoop currentRunLoop] run]; [pool release]; } } - + // // Draw the Scene // - (void) drawScene -{ +{ + /* calculate "global" dt */ + [self calculateDeltaTime]; + // We draw on a secondary thread through the display link // When resizing the view, -reshape is called automatically on the main thread // Add a mutex around to avoid the threads accessing the context simultaneously when resizing - CGLLockContext([[openGLView_ openGLContext] CGLContextObj]); - [[openGLView_ openGLContext] makeCurrentContext]; - - /* calculate "global" dt */ - [self calculateDeltaTime]; - + + [self.view lockOpenGLContext]; + /* tick before glClear: issue #533 */ - if( ! isPaused_ ) { - [[CCScheduler sharedScheduler] tick: dt]; - } - + if( ! isPaused_ ) + [scheduler_ update: dt]; + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - + /* to avoid flickr, nextScene MUST be here: after tick and before draw. XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */ if( nextScene_ ) [self setNextScene]; - - glPushMatrix(); - - - // By default enable VertexArray, ColorArray, TextureCoordArray and Texture2D - CC_ENABLE_DEFAULT_GL_STATES(); - + + kmGLPushMatrix(); + + /* draw the scene */ [runningScene_ visit]; - + /* draw the notification node */ [notificationNode_ visit]; - if( displayFPS_ ) - [self showFPS]; - -#if CC_ENABLE_PROFILERS - [self showProfilers]; -#endif - - CC_DISABLE_DEFAULT_GL_STATES(); + if( displayStats_ ) + [self showStats]; + + kmGLPopMatrix(); + + totalFrames_++; - glPopMatrix(); - - [[openGLView_ openGLContext] flushBuffer]; - CGLUnlockContext([[openGLView_ openGLContext] CGLContextObj]); + + // flush buffer + [self.view.openGLContext flushBuffer]; + + [self.view unlockOpenGLContext]; + + if( displayStats_ ) + [self calculateMPF]; } // set the event dispatcher --(void) setOpenGLView:(MacGLView *)view +-(void) setView:(CCGLView *)view { - if( view != openGLView_ ) { - - [super setOpenGLView:view]; - - CCEventDispatcher *eventDispatcher = [CCEventDispatcher sharedDispatcher]; - [openGLView_ setEventDelegate: eventDispatcher]; - [eventDispatcher setDispatchEvents: YES]; - - // Enable Touches. Default no. - [view setAcceptsTouchEvents:NO]; + [super setView:view]; + + [view setEventDelegate:eventDispatcher_]; + [eventDispatcher_ setDispatchEvents: YES]; + + // Enable Touches. Default no. + // Only available on OS X 10.6+ +#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 + [view setAcceptsTouchEvents:NO]; // [view setAcceptsTouchEvents:YES]; - +#endif - // Synchronize buffer swaps with vertical refresh rate - [[view openGLContext] makeCurrentContext]; - GLint swapInt = 1; - [[view openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; - } + + // Synchronize buffer swaps with vertical refresh rate + [[view openGLContext] makeCurrentContext]; + GLint swapInt = 1; + [[view openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; } @end -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.h b/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.h index b52f8d1..fb114bc 100644 --- a/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.h +++ b/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,13 +25,12 @@ // Only compile this code on Mac. These files should not be included on your iOS project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_MAC #import -#import "MacGLView.h" +#import "CCGLView.h" #import "../../Support/uthash.h" // hack: uthash needs to be imported before utlist to prevent warning #import "../../Support/utlist.h" #import "../../ccConfig.h" @@ -156,35 +156,77 @@ -(BOOL) ccFlagsChanged:(NSEvent*)event; @end - #pragma mark - -#pragma mark CCEventDispatcher +#pragma mark CCTouchEventDelegate + +/** CCTouchEventDelegate protocol. + Implement it in your node to receive any of touch events + */ +@protocol CCTouchEventDelegate +@optional +/** called when the "touchesBegan" event is received. + Return YES to avoid propagating the event to other delegates. + */ +- (BOOL)ccTouchesBeganWithEvent:(NSEvent *)event; + +/** called when the "touchesMoved" event is received. + Return YES to avoid propagating the event to other delegates. + */ +- (BOOL)ccTouchesMovedWithEvent:(NSEvent *)event; + +/** called when the "touchesEnded" event is received. + Return YES to avoid propagating the event to other delegates. + */ +- (BOOL)ccTouchesEndedWithEvent:(NSEvent *)event; + +/** called when the "touchesCancelled" event is received. + Return YES to avoid propagating the event to other delegates. + */ +- (BOOL)ccTouchesCancelledWithEvent:(NSEvent *)event; + +@end + +#pragma mark - CCEventObject + +@interface CCEventObject : NSObject +{ +@public + NSEvent *event; + SEL selector; +} +@end + +#pragma mark - CCEventDispatcher struct _listEntry; +struct _listDeletedEntry; +struct _listAddedEntry; /** CCEventDispatcher - + This is object is responsible for dispatching the events: - Mouse events - Keyboard events - Touch events - + Only available on Mac */ -@interface CCEventDispatcher : NSObject { +@interface CCEventDispatcher : NSObject { BOOL dispatchEvents_; - + BOOL dispatchingInProgress_; + struct _listEntry *keyboardDelegates_; struct _listEntry *mouseDelegates_; + struct _listEntry *touchDelegates_; + + struct _listDeletedEntry *delegatesToBeRemoved_; + struct _listAddedEntry *delegatesToBeAdded_; + } @property (nonatomic, readwrite) BOOL dispatchEvents; - -/** CCEventDispatcher singleton */ -+(CCEventDispatcher*) sharedDispatcher; - #pragma mark CCEventDispatcher - Mouse /** Adds a mouse delegate to the dispatcher's list. @@ -206,7 +248,7 @@ struct _listEntry; /** Adds a Keyboard delegate to the dispatcher's list. Delegates with a lower priority value will be called before higher priority values. All the events will be propgated to all the delegates, unless the one delegate returns YES. - + IMPORTANT: The delegate will be retained. */ -(void) addKeyboardDelegate:(id) delegate priority:(NSInteger)priority; @@ -219,15 +261,23 @@ struct _listEntry; #pragma mark CCEventDispatcher - Touches -// XXX +/** Adds a Touch delegate to the dispatcher's list. + Delegates with a lower priority value will be called before higher priority values. + All the events will be propgated to all the delegates, unless the one delegate returns YES. + + IMPORTANT: The delegate will be retained. + */ +- (void)addTouchDelegate:(id)delegate priority:(NSInteger)priority; + +/** Removes a touch delegate */ +- (void)removeTouchDelegate:(id) delegate; -#pragma mark CCEventDispatcher - Dispatch Events +/** Removes all touch delegates, releasing all the delegates */ +- (void)removeAllTouchDelegates; -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD --(void) dispatchQueuedEvents; -#endif +-(void) dispatchEvent:(CCEventObject*)event; @end -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.m b/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.m index b726665..b279174 100644 --- a/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.m +++ b/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,20 +25,18 @@ // Only compile this code on Mac. These files should not be included on your iOS project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_MAC #import "CCEventDispatcher.h" +#import "../../CCDirector.h" #import "../../ccConfig.h" -static CCEventDispatcher *sharedDispatcher = nil; - enum { // mouse kCCImplementsMouseDown = 1 << 0, kCCImplementsMouseMoved = 1 << 1, - kCCImplementsMouseDragged = 1 << 2, + kCCImplementsMouseDragged = 1 << 2, kCCImplementsMouseUp = 1 << 3, kCCImplementsRightMouseDown = 1 << 4, kCCImplementsRightMouseDragged = 1 << 5, @@ -48,7 +47,12 @@ kCCImplementsScrollWheel = 1 << 10, kCCImplementsMouseEntered = 1 << 11, kCCImplementsMouseExited = 1 << 12, - + + kCCImplementsTouchesBegan = 1 << 13, + kCCImplementsTouchesMoved = 1 << 14, + kCCImplementsTouchesEnded = 1 << 15, + kCCImplementsTouchesCancelled = 1 << 16, + // keyboard kCCImplementsKeyUp = 1 << 0, kCCImplementsKeyDown = 1 << 1, @@ -64,43 +68,35 @@ NSUInteger flags; } tListEntry; +typedef struct _listDeletedEntry +{ + struct _listDeletedEntry *prev, *next; + id delegate; + struct _listEntry **listToBeDeleted; -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD +} tListDeletedEntry; -#define QUEUE_EVENT_MAX 128 -struct _eventQueue { - SEL selector; - NSEvent *event; -}; +typedef struct _listAddedEntry +{ + struct _listAddedEntry *prev, *next; + id delegate; + NSInteger priority; + NSUInteger flags; + struct _listEntry **listToBeAdded; +} tListAddedEntry; -static struct _eventQueue eventQueue[QUEUE_EVENT_MAX]; -static int eventQueueCount; -#endif // CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD +#pragma mark - CCEventObject -@implementation CCEventDispatcher - -@synthesize dispatchEvents=dispatchEvents_; +@implementation CCEventObject +@end +#pragma mark - CCEventDispatcher -+(CCEventDispatcher*) sharedDispatcher -{ - @synchronized(self) { - if (sharedDispatcher == nil) - sharedDispatcher = [[self alloc] init]; // assignment not done here - } - return sharedDispatcher; -} +@implementation CCEventDispatcher -+(id) allocWithZone:(NSZone *)zone -{ - @synchronized(self) { - NSAssert(sharedDispatcher == nil, @"Attempted to allocate a second instance of a singleton."); - return [super allocWithZone:zone]; - } - return nil; // on subsequent allocation attempts return nil -} +@synthesize dispatchEvents=dispatchEvents_; -(id) init { @@ -112,12 +108,14 @@ -(id) init // delegates keyboardDelegates_ = NULL; mouseDelegates_ = NULL; + touchDelegates_ = NULL; -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - eventQueueCount = 0; -#endif + delegatesToBeAdded_ = NULL; + delegatesToBeRemoved_ = NULL; + + dispatchingInProgress_ = NO; } - + return self; } @@ -127,47 +125,70 @@ - (void) dealloc } #pragma mark CCEventDispatcher - add / remove delegates +-(void) addLaterDelegate:(id)delegate priority:(NSInteger)priority flags:(NSUInteger)flags list:(tListEntry**)list +{ + tListAddedEntry *listElement = malloc( sizeof(*listElement) ); + + listElement->delegate = [delegate retain]; + listElement->priority = priority; + listElement->flags = flags; + listElement->listToBeAdded = list; + listElement->next = listElement->prev = NULL; + + DL_APPEND( delegatesToBeAdded_, listElement ); +} -(void) addDelegate:(id)delegate priority:(NSInteger)priority flags:(NSUInteger)flags list:(tListEntry**)list { tListEntry *listElement = malloc( sizeof(*listElement) ); - + listElement->delegate = [delegate retain]; listElement->priority = priority; listElement->flags = flags; listElement->next = listElement->prev = NULL; - + // empty list ? if( ! *list ) { DL_APPEND( *list, listElement ); - + } else { - BOOL added = NO; - + BOOL added = NO; + for( tListEntry *elem = *list; elem ; elem = elem->next ) { if( priority < elem->priority ) { - + if( elem == *list ) DL_PREPEND(*list, listElement); else { listElement->next = elem; listElement->prev = elem->prev; - + elem->prev->next = listElement; elem->prev = listElement; } - + added = YES; break; } } - + // Not added? priority has the higher value. Append it. if( !added ) DL_APPEND(*list, listElement); } } +-(void) removeLaterDelegate:(id)delegate fromList:(tListEntry**)list +{ + tListDeletedEntry *listElement = malloc( sizeof(*listElement) ); + + listElement->delegate = [delegate retain]; + listElement->listToBeDeleted = list; + listElement->next = listElement->prev = NULL; + + DL_APPEND( delegatesToBeRemoved_, listElement ); +} + -(void) removeDelegate:(id)delegate fromList:(tListEntry**)list { tListEntry *entry, *tmp; @@ -185,11 +206,16 @@ -(void) removeDelegate:(id)delegate fromList:(tListEntry**)list -(void) removeAllDelegatesFromList:(tListEntry**)list { - tListEntry *entry, *tmp; + NSAssert( ! dispatchingInProgress_, @"BUG. Open a ticket. Can't call this function when processing events."); - DL_FOREACH_SAFE( *list, entry, tmp ) { - DL_DELETE( *list, entry ); - free(entry); + @synchronized(self) { + tListEntry *entry, *tmp; + + DL_FOREACH_SAFE( *list, entry, tmp ) { + DL_DELETE( *list, entry ); + [entry->delegate release]; + free(entry); + } } } @@ -197,7 +223,7 @@ -(void) removeAllDelegatesFromList:(tListEntry**)list -(void) addMouseDelegate:(id) delegate priority:(NSInteger)priority { NSUInteger flags = 0; - + flags |= ( [delegate respondsToSelector:@selector(ccMouseDown:)] ? kCCImplementsMouseDown : 0 ); flags |= ( [delegate respondsToSelector:@selector(ccMouseDragged:)] ? kCCImplementsMouseDragged : 0 ); flags |= ( [delegate respondsToSelector:@selector(ccMouseMoved:)] ? kCCImplementsMouseMoved : 0 ); @@ -216,12 +242,19 @@ -(void) addMouseDelegate:(id) delegate priority:(NSInteger flags |= ( [delegate respondsToSelector:@selector(ccScrollWheel:)] ? kCCImplementsScrollWheel : 0 ); - [self addDelegate:delegate priority:priority flags:flags list:&mouseDelegates_]; + if( dispatchingInProgress_ ) + [self addLaterDelegate:delegate priority:priority flags:flags list:&mouseDelegates_]; + else + [self addDelegate:delegate priority:priority flags:flags list:&mouseDelegates_]; + } -(void) removeMouseDelegate:(id) delegate { - [self removeDelegate:delegate fromList:&mouseDelegates_]; + if( dispatchingInProgress_ ) + [self removeLaterDelegate:delegate fromList:&mouseDelegates_]; + else + [self removeDelegate:delegate fromList:&mouseDelegates_]; } -(void) removeAllMouseDelegates @@ -232,17 +265,23 @@ -(void) removeAllMouseDelegates -(void) addKeyboardDelegate:(id) delegate priority:(NSInteger)priority { NSUInteger flags = 0; - + flags |= ( [delegate respondsToSelector:@selector(ccKeyUp:)] ? kCCImplementsKeyUp : 0 ); flags |= ( [delegate respondsToSelector:@selector(ccKeyDown:)] ? kCCImplementsKeyDown : 0 ); flags |= ( [delegate respondsToSelector:@selector(ccFlagsChanged:)] ? kCCImplementsFlagsChanged : 0 ); - - [self addDelegate:delegate priority:priority flags:flags list:&keyboardDelegates_]; + + if( dispatchingInProgress_ ) + [self addLaterDelegate:delegate priority:priority flags:flags list:&keyboardDelegates_]; + else + [self addDelegate:delegate priority:priority flags:flags list:&keyboardDelegates_]; } -(void) removeKeyboardDelegate:(id) delegate { - [self removeDelegate:delegate fromList:&keyboardDelegates_]; + if( dispatchingInProgress_ ) + [self removeLaterDelegate:delegate fromList:&keyboardDelegates_]; + else + [self removeDelegate:delegate fromList:&keyboardDelegates_]; } -(void) removeAllKeyboardDelegates @@ -250,6 +289,35 @@ -(void) removeAllKeyboardDelegates [self removeAllDelegatesFromList:&keyboardDelegates_]; } +-(void) addTouchDelegate:(id) delegate priority:(NSInteger)priority +{ + NSUInteger flags = 0; + + flags |= ( [delegate respondsToSelector:@selector(ccTouchesBeganWithEvent:)] ? kCCImplementsTouchesBegan : 0 ); + flags |= ( [delegate respondsToSelector:@selector(ccTouchesMovedWithEvent:)] ? kCCImplementsTouchesMoved : 0 ); + flags |= ( [delegate respondsToSelector:@selector(ccTouchesEndedWithEvent:)] ? kCCImplementsTouchesEnded : 0 ); + flags |= ( [delegate respondsToSelector:@selector(ccTouchesCancelledWithEvent:)] ? kCCImplementsTouchesCancelled : 0 ); + + if( dispatchingInProgress_ ) + [self addLaterDelegate:delegate priority:priority flags:flags list:&touchDelegates_]; + else + [self addDelegate:delegate priority:priority flags:flags list:&touchDelegates_]; +} + +-(void) removeTouchDelegate:(id) delegate +{ + if( dispatchingInProgress_ ) + [self removeLaterDelegate:delegate fromList:&touchDelegates_]; + else + [self removeDelegate:delegate fromList:&touchDelegates_]; +} + +-(void) removeAllTouchDelegates +{ + [self removeAllDelegatesFromList:&touchDelegates_]; +} + + #pragma mark CCEventDispatcher - Mouse events // // Mouse events @@ -277,7 +345,7 @@ - (void)mouseMoved:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsMouseMoved ) { void *swallows = [entry->delegate performSelector:@selector(ccMouseMoved:) withObject:event]; @@ -292,7 +360,7 @@ - (void)mouseDragged:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsMouseDragged ) { void *swallows = [entry->delegate performSelector:@selector(ccMouseDragged:) withObject:event]; @@ -305,14 +373,16 @@ - (void)mouseDragged:(NSEvent *)event - (void)mouseUp:(NSEvent *)event { - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseUp:) withObject:event]; - if( swallows ) - break; + @synchronized(self) { + if( dispatchEvents_ ) { + tListEntry *entry, *tmp; + + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { + if ( entry->flags & kCCImplementsMouseUp ) { + void *swallows = [entry->delegate performSelector:@selector(ccMouseUp:) withObject:event]; + if( swallows ) + break; + } } } } @@ -325,7 +395,7 @@ - (void)rightMouseDown:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsRightMouseDown ) { void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDown:) withObject:event]; @@ -340,7 +410,7 @@ - (void)rightMouseDragged:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsRightMouseDragged ) { void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDragged:) withObject:event]; @@ -355,7 +425,7 @@ - (void)rightMouseUp:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsRightMouseUp ) { void *swallows = [entry->delegate performSelector:@selector(ccRightMouseUp:) withObject:event]; @@ -373,7 +443,7 @@ - (void)otherMouseDown:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsOtherMouseDown ) { void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDown:) withObject:event]; @@ -388,7 +458,7 @@ - (void)otherMouseDragged:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsOtherMouseDragged ) { void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDragged:) withObject:event]; @@ -403,7 +473,7 @@ - (void)otherMouseUp:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsOtherMouseUp ) { void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseUp:) withObject:event]; @@ -421,7 +491,7 @@ - (void)scrollWheel:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsScrollWheel ) { void *swallows = [entry->delegate performSelector:@selector(ccScrollWheel:) withObject:event]; @@ -438,7 +508,7 @@ - (void)mouseExited:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsMouseEntered ) { void *swallows = [entry->delegate performSelector:@selector(ccMouseEntered:) withObject:event]; @@ -446,14 +516,14 @@ - (void)mouseExited:(NSEvent *)event break; } } - } + } } - (void)mouseEntered:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsMouseExited) { void *swallows = [entry->delegate performSelector:@selector(ccMouseExited:) withObject:event]; @@ -461,7 +531,7 @@ - (void)mouseEntered:(NSEvent *)event break; } } - } + } } @@ -472,7 +542,7 @@ - (void)keyDown:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsKeyDown ) { void *swallows = [entry->delegate performSelector:@selector(ccKeyDown:) withObject:event]; @@ -487,7 +557,7 @@ - (void)keyUp:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { if ( entry->flags & kCCImplementsKeyUp ) { void *swallows = [entry->delegate performSelector:@selector(ccKeyUp:) withObject:event]; @@ -502,9 +572,9 @@ - (void)flagsChanged:(NSEvent *)event { if( dispatchEvents_ ) { tListEntry *entry, *tmp; - + DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsKeyUp ) { + if ( entry->flags & kCCImplementsFlagsChanged ) { void *swallows = [entry->delegate performSelector:@selector(ccFlagsChanged:) withObject:event]; if( swallows ) break; @@ -518,61 +588,107 @@ - (void)flagsChanged:(NSEvent *)event - (void)touchesBeganWithEvent:(NSEvent *)event { - if (dispatchEvents_ ) { - NSLog(@"Touch Events: Not supported yet"); + if( dispatchEvents_ ) { + tListEntry *entry, *tmp; + + DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { + if ( entry->flags & kCCImplementsTouchesBegan) { + void *swallows = [entry->delegate performSelector:@selector(ccTouchesBeganWithEvent:) withObject:event]; + if( swallows ) + break; + } + } } } - (void)touchesMovedWithEvent:(NSEvent *)event { - if (dispatchEvents_ ) { - NSLog(@"Touch Events: Not supported yet"); + if( dispatchEvents_ ) { + tListEntry *entry, *tmp; + + DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { + if ( entry->flags & kCCImplementsTouchesMoved) { + void *swallows = [entry->delegate performSelector:@selector(ccTouchesMovedWithEvent:) withObject:event]; + if( swallows ) + break; + } + } } } - (void)touchesEndedWithEvent:(NSEvent *)event { - if (dispatchEvents_ ) { - NSLog(@"Touch Events: Not supported yet"); - } -} + if( dispatchEvents_ ) { + tListEntry *entry, *tmp; -- (void)touchesCancelledWithEvent:(NSEvent *)event -{ - if (dispatchEvents_ ) { - NSLog(@"Touch Events: Not supported yet"); + DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { + if ( entry->flags & kCCImplementsTouchesEnded) { + void *swallows = [entry->delegate performSelector:@selector(ccTouchesEndedWithEvent:) withObject:event]; + if( swallows ) + break; + } + } } } -#pragma mark CCEventDispatcher - queue events - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD --(void) queueEvent:(NSEvent*)event selector:(SEL)selector +- (void)touchesCancelledWithEvent:(NSEvent *)event { - NSAssert( eventQueueCount < QUEUE_EVENT_MAX, @"CCEventDispatcher: recompile. Increment QUEUE_EVENT_MAX value"); + if( dispatchEvents_ ) { + tListEntry *entry, *tmp; - eventQueue[eventQueueCount].selector = selector; - eventQueue[eventQueueCount].event = [event copy]; - - eventQueueCount++; + DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { + if ( entry->flags & kCCImplementsTouchesCancelled) { + void *swallows = [entry->delegate performSelector:@selector(ccTouchesCancelledWithEvent:) withObject:event]; + if( swallows ) + break; + } + } + } } --(void) dispatchQueuedEvents +- (void)dispatchEvent:(CCEventObject*)e { - for( int i=0; i < eventQueueCount; i++ ) { - SEL sel = eventQueue[i].selector; - NSEvent *event = eventQueue[i].event; + @synchronized(self) + { + NSEvent *event = e->event; + SEL selector = e->selector; + + // Dispatch events + if( dispatchEvents_ ) { + dispatchingInProgress_ = YES; + [self performSelector:selector onThread:[[CCDirector sharedDirector] runningThread] withObject:event waitUntilDone:YES]; + dispatchingInProgress_ = NO; + } - [self performSelector:sel withObject:event]; [event release]; + + // Remove possible delegates + tListDeletedEntry *dEntry, *tTmp; + DL_FOREACH_SAFE( delegatesToBeRemoved_ , dEntry, tTmp ) { + + [self removeDelegate:dEntry->delegate fromList:dEntry->listToBeDeleted]; + + DL_DELETE( delegatesToBeRemoved_, dEntry ); + [dEntry->delegate release]; + free(dEntry); + } + + // Add possible delegates + tListAddedEntry *entry, *tmp; + + DL_FOREACH_SAFE( delegatesToBeAdded_, entry, tmp ) { + + [self addDelegate:entry->delegate priority:entry->priority flags:entry->flags list:entry->listToBeAdded]; + + DL_DELETE( delegatesToBeAdded_, entry ); + [entry->delegate release]; + free(entry); + } + } - - eventQueueCount = 0; } -#endif // CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - @end -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED \ No newline at end of file +#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/MacGLView.h b/Example/libs/cocos2d/Platforms/Mac/MacGLView.h deleted file mode 100644 index 8d04b8e..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/MacGLView.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) - -#import - -#import "../../ccConfig.h" - -//PROTOCOLS: - -@protocol MacEventDelegate -// Mouse -- (void)mouseDown:(NSEvent *)theEvent; -- (void)mouseUp:(NSEvent *)theEvent; -- (void)mouseMoved:(NSEvent *)theEvent; -- (void)mouseDragged:(NSEvent *)theEvent; -- (void)rightMouseDown:(NSEvent*)event; -- (void)rightMouseDragged:(NSEvent*)event; -- (void)rightMouseUp:(NSEvent*)event; -- (void)otherMouseDown:(NSEvent*)event; -- (void)otherMouseDragged:(NSEvent*)event; -- (void)otherMouseUp:(NSEvent*)event; -- (void)scrollWheel:(NSEvent *)theEvent; -- (void)mouseEntered:(NSEvent *)theEvent; -- (void)mouseExited:(NSEvent *)theEvent; - - -// Keyboard -- (void)keyDown:(NSEvent *)theEvent; -- (void)keyUp:(NSEvent *)theEvent; -- (void)flagsChanged:(NSEvent *)theEvent; - -// Touches -- (void)touchesBeganWithEvent:(NSEvent *)event; -- (void)touchesMovedWithEvent:(NSEvent *)event; -- (void)touchesEndedWithEvent:(NSEvent *)event; -- (void)touchesCancelledWithEvent:(NSEvent *)event; - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD -- (void)queueEvent:(NSEvent*)event selector:(SEL)selector; -#endif - -@end - -/** MacGLView - - Only available for Mac OS X - */ -@interface MacGLView : NSOpenGLView { - id eventDelegate_; -} - -@property (nonatomic, readwrite, assign) id eventDelegate; - -// initializes the MacGLView with a frame rect and an OpenGL context -- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context; - -// private -+(void) load_; -@end - -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED \ No newline at end of file diff --git a/Example/libs/cocos2d/Platforms/Mac/MacGLView.m b/Example/libs/cocos2d/Platforms/Mac/MacGLView.m deleted file mode 100644 index c29045d..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/MacGLView.m +++ /dev/null @@ -1,241 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* - * Idea of subclassing NSOpenGLView was taken from "TextureUpload" Apple's sample - */ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) - -#import "MacGLView.h" -#import - -#import "CCDirectorMac.h" -#import "../../ccConfig.h" - - -@implementation MacGLView - -@synthesize eventDelegate = eventDelegate_; - -+(void) load_ -{ - NSLog(@"%@ loaded", self); -} - -- (id) initWithFrame:(NSRect)frameRect -{ - self = [self initWithFrame:frameRect shareContext:nil]; - return self; -} - -- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context -{ - NSOpenGLPixelFormatAttribute attribs[] = - { - NSOpenGLPFAAccelerated, - NSOpenGLPFANoRecovery, - NSOpenGLPFADoubleBuffer, - NSOpenGLPFADepthSize, 24, - - 0 - }; - - NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; - - if (!pixelFormat) - NSLog(@"No OpenGL pixel format"); - - if (self = [super initWithFrame:frameRect pixelFormat:[pixelFormat autorelease]]) { - - if( context ) - [self setOpenGLContext:context]; - - // Synchronize buffer swaps with vertical refresh rate - GLint swapInt = 1; - [[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; - -// GLint order = -1; -// [[self openGLContext] setValues:&order forParameter:NSOpenGLCPSurfaceOrder]; - - // event delegate - eventDelegate_ = nil; - } - - return self; -} - -- (void) reshape -{ - // We draw on a secondary thread through the display link - // When resizing the view, -reshape is called automatically on the main thread - // Add a mutex around to avoid the threads accessing the context simultaneously when resizing - CGLLockContext([[self openGLContext] CGLContextObj]); - - NSRect rect = [self bounds]; - - CCDirector *director = [CCDirector sharedDirector]; - [director reshapeProjection: NSSizeToCGSize(rect.size) ]; - - // avoid flicker - [director drawScene]; -// [self setNeedsDisplay:YES]; - - CGLUnlockContext([[self openGLContext] CGLContextObj]); -} - -- (void) dealloc -{ - - [super dealloc]; -} - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD -#define DISPATCH_EVENT(__event__, __selector__) [eventDelegate_ queueEvent:__event__ selector:__selector__]; -#else -#define DISPATCH_EVENT(__event__, __selector__) \ - id obj = eventDelegate_; \ - [obj performSelector:__selector__ \ - onThread:[(CCDirectorMac*)[CCDirector sharedDirector] runningThread] \ - withObject:__event__ \ - waitUntilDone:NO]; -#endif - -#pragma mark MacGLView - Mouse events -- (void)mouseDown:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseMoved:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseDragged:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseUp:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)rightMouseDown:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)rightMouseDragged:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)rightMouseUp:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)otherMouseDown:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)otherMouseDragged:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)otherMouseUp:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseEntered:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseExited:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - --(void) scrollWheel:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -#pragma mark MacGLView - Key events - --(BOOL) becomeFirstResponder -{ - return YES; -} - --(BOOL) acceptsFirstResponder -{ - return YES; -} - --(BOOL) resignFirstResponder -{ - return YES; -} - -- (void)keyDown:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)keyUp:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)flagsChanged:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -#pragma mark MacGLView - Touch events -- (void)touchesBeganWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesMovedWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesEndedWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesCancelledWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -@end - -#endif // __MAC_OS_X_VERSION_MAX_ALLOWED \ No newline at end of file diff --git a/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h b/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h index 7126d0d..871b251 100644 --- a/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h +++ b/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,140 +26,20 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS #import "../../CCDirector.h" +#import "kazmath/mat4.h" -/** @typedef ccDeviceOrientation - Possible device orientations - */ -typedef enum { - /// Device oriented vertically, home button on the bottom - kCCDeviceOrientationPortrait = UIDeviceOrientationPortrait, - /// Device oriented vertically, home button on the top - kCCDeviceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown, - /// Device oriented horizontally, home button on the right - kCCDeviceOrientationLandscapeLeft = UIDeviceOrientationLandscapeLeft, - /// Device oriented horizontally, home button on the left - kCCDeviceOrientationLandscapeRight = UIDeviceOrientationLandscapeRight, - - // Backward compatibility stuff - CCDeviceOrientationPortrait = kCCDeviceOrientationPortrait, - CCDeviceOrientationPortraitUpsideDown = kCCDeviceOrientationPortraitUpsideDown, - CCDeviceOrientationLandscapeLeft = kCCDeviceOrientationLandscapeLeft, - CCDeviceOrientationLandscapeRight = kCCDeviceOrientationLandscapeRight, -} ccDeviceOrientation; - -/** @typedef tPixelFormat - Possible Pixel Formats for the OpenGL View. - - @deprecated Will be removed in v1.0 - */ -typedef enum { - /** RGB565 pixel format. No alpha. 16-bit. (Default) */ - kCCPixelFormatRGB565, - /** RGBA format. 32-bit. Needed for some 3D effects. It is not as fast as the RGB565 format. */ - kCCPixelFormatRGBA8888, - /** default pixel format */ - kCCPixelFormatDefault = kCCPixelFormatRGB565, - - // backward compatibility stuff - kPixelFormatRGB565 = kCCPixelFormatRGB565, - kRGB565 = kCCPixelFormatRGB565, - kPixelFormatRGBA8888 = kCCPixelFormatRGBA8888, - kRGBA8 = kCCPixelFormatRGBA8888, -} tPixelFormat; - -/** @typedef tDepthBufferFormat - Possible DepthBuffer Formats for the OpenGLView. - Use 16 or 24 bit depth buffers if you are going to use real 3D objects. - - @deprecated Will be removed in v1.0 - */ -typedef enum { - /// A Depth Buffer of 0 bits will be used (default) - kCCDepthBufferNone, - /// A depth buffer of 16 bits will be used - kCCDepthBuffer16, - /// A depth buffer of 24 bits will be used - kCCDepthBuffer24, - - // backward compatibility stuff - kDepthBuffer16 = kCCDepthBuffer16, - kDepthBuffer24 = kCCDepthBuffer24, -} tDepthBufferFormat; - -/** @typedef ccDirectorType - Possible Director Types. - @since v0.8.2 - */ -typedef enum { - /** Will use a Director that triggers the main loop from an NSTimer object - * - * Features and Limitations: - * - Integrates OK with UIKit objects - * - It the slowest director - * - The invertal update is customizable from 1 to 60 - */ - kCCDirectorTypeNSTimer, - - /** will use a Director that triggers the main loop from a custom main loop. - * - * Features and Limitations: - * - Faster than NSTimer Director - * - It doesn't integrate well with UIKit objecgts - * - The interval update can't be customizable - */ - kCCDirectorTypeMainLoop, - - /** Will use a Director that triggers the main loop from a thread, but the main loop will be executed on the main thread. - * - * Features and Limitations: - * - Faster than NSTimer Director - * - It doesn't integrate well with UIKit objecgts - * - The interval update can't be customizable - */ - kCCDirectorTypeThreadMainLoop, - - /** Will use a Director that synchronizes timers with the refresh rate of the display. - * - * Features and Limitations: - * - Faster than NSTimer Director - * - Only available on 3.1+ - * - Scheduled timers & drawing are synchronizes with the refresh rate of the display - * - Integrates OK with UIKit objects - * - The interval update can be 1/60, 1/30, 1/15 - */ - kCCDirectorTypeDisplayLink, - - /** Default director is the NSTimer directory */ - kCCDirectorTypeDefault = kCCDirectorTypeNSTimer, - - // backward compatibility stuff - CCDirectorTypeNSTimer = kCCDirectorTypeNSTimer, - CCDirectorTypeMainLoop = kCCDirectorTypeMainLoop, - CCDirectorTypeThreadMainLoop = kCCDirectorTypeThreadMainLoop, - CCDirectorTypeDisplayLink = kCCDirectorTypeDisplayLink, - CCDirectorTypeDefault = kCCDirectorTypeDefault, - - -} ccDirectorType; +@class CCTouchDispatcher; /** CCDirector extensions for iPhone */ @interface CCDirector (iOSExtension) -// rotates the screen if an orientation differnent than Portrait is used --(void) applyOrientation; - -/** Sets the device orientation. - If the orientation is going to be controlled by an UIViewController, then the orientation should be Portrait - */ --(void) setDeviceOrientation:(ccDeviceOrientation)orientation; - -/** returns the device orientation */ --(ccDeviceOrientation) deviceOrientation; +/** sets the CCTouchDispatcher (iOS only) */ +@property (nonatomic,readwrite,retain) CCTouchDispatcher * touchDispatcher; /** The size in pixels of the surface. It could be different than the screen size. High-res devices might have a higher surface size than the screen size. @@ -173,37 +54,16 @@ typedef enum { /** Will enable Retina Display on devices that supports it. It will enable Retina Display on iPhone4 and iPod Touch 4. It will return YES, if it could enabled it, otherwise it will return NO. - + This is the recommened way to enable Retina Display. @since v0.99.5 */ --(BOOL) enableRetinaDisplay:(BOOL)yes; - +-(BOOL) enableRetinaDisplay:(BOOL)enableRetina; /** returns the content scale factor */ -(CGFloat) contentScaleFactor; @end -@interface CCDirector (iOSExtensionClassMethods) - -/** There are 4 types of Director. - - kCCDirectorTypeNSTimer (default) - - kCCDirectorTypeMainLoop - - kCCDirectorTypeThreadMainLoop - - kCCDirectorTypeDisplayLink - - Each Director has it's own benefits, limitations. - If you are using SDK 3.1 or newer it is recommed to use the DisplayLink director - - This method should be called before any other call to the director. - - It will return NO if the director type is kCCDirectorTypeDisplayLink and the running SDK is < 3.1. Otherwise it will return YES. - - @since v0.8.2 - */ -+(BOOL) setDirectorType:(ccDirectorType) directorType; -@end - #pragma mark - #pragma mark CCDirectorIOS @@ -212,94 +72,11 @@ typedef enum { */ @interface CCDirectorIOS : CCDirector { - /* orientation */ - ccDeviceOrientation deviceOrientation_; - /* contentScaleFactor could be simulated */ BOOL isContentScaleSupported_; - tPixelFormat pixelFormat_; // Deprecated. Will be removed in 1.0 - tDepthBufferFormat depthBufferFormat_; // Deprecated. Will be removed in 1.0 + CCTouchDispatcher *touchDispatcher_; } - -// iPhone Specific - -/** Pixel format used to create the context */ -@property (nonatomic,readonly) tPixelFormat pixelFormat DEPRECATED_ATTRIBUTE; - -/** Uses a new pixel format for the EAGLView. - Call this class method before attaching it to a UIView - Default pixel format: kRGB565. Supported pixel formats: kRGBA8 and kRGB565 - - @deprecated Set the pixel format when creating the EAGLView. This method will be removed in v1.0 - */ --(void) setPixelFormat: (tPixelFormat)p DEPRECATED_ATTRIBUTE; - -/** Change depth buffer format of the render buffer. - Call this class method before attaching it to a UIWindow/UIView - Default depth buffer: 0 (none). Supported: kCCDepthBufferNone, kCCDepthBuffer16, and kCCDepthBuffer24 - - @deprecated Set the depth buffer format when creating the EAGLView. This method will be removed in v1.0 - */ --(void) setDepthBufferFormat: (tDepthBufferFormat)db DEPRECATED_ATTRIBUTE; - -// Integration with UIKit -/** detach the cocos2d view from the view/window */ --(BOOL)detach DEPRECATED_ATTRIBUTE; - -/** attach in UIWindow using the full frame. - It will create a EAGLView. - - @deprecated set setOpenGLView instead. Will be removed in v1.0 - */ --(BOOL)attachInWindow:(UIWindow *)window DEPRECATED_ATTRIBUTE; - -/** attach in UIView using the full frame. - It will create a EAGLView. - - @deprecated set setOpenGLView instead. Will be removed in v1.0 - */ --(BOOL)attachInView:(UIView *)view DEPRECATED_ATTRIBUTE; - -/** attach in UIView using the given frame. - It will create a EAGLView and use it. - - @deprecated set setOpenGLView instead. Will be removed in v1.0 - */ --(BOOL)attachInView:(UIView *)view withFrame:(CGRect)frame DEPRECATED_ATTRIBUTE; - -@end - -/** FastDirector is a Director that triggers the main loop as fast as possible. - * - * Features and Limitations: - * - Faster than "normal" director - * - Consumes more battery than the "normal" director - * - It has some issues while using UIKit objects - */ -@interface CCDirectorFast : CCDirectorIOS -{ - BOOL isRunning; - - NSAutoreleasePool *autoreleasePool; -} --(void) mainLoop; -@end - -/** ThreadedFastDirector is a Director that triggers the main loop from a thread. - * - * Features and Limitations: - * - Faster than "normal" director - * - Consumes more battery than the "normal" director - * - It can be used with UIKit objects - * - * @since v0.8.2 - */ -@interface CCDirectorFastThreaded : CCDirectorIOS -{ - BOOL isRunning; -} --(void) mainLoop; @end /** DisplayLinkDirector is a Director that synchronizes timers with the refresh rate of the display. @@ -315,28 +92,13 @@ typedef enum { */ @interface CCDirectorDisplayLink : CCDirectorIOS { - id displayLink; + CADisplayLink *displayLink_; + CFTimeInterval lastDisplayTime_; } -(void) mainLoop:(id)sender; @end -/** TimerDirector is a Director that calls the main loop from an NSTimer object - * - * Features and Limitations: - * - Integrates OK with UIKit objects - * - It the slowest director - * - The invertal update is customizable from 1 to 60 - * - * It is the default Director. - */ -@interface CCDirectorTimer : CCDirectorIOS -{ - NSTimer *animationTimer; -} --(void) mainLoop; -@end - // optimization. Should only be used to read it. Never to write it. extern CGFloat __ccContentScaleFactor; -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m b/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m index a97e2e1..b39adb4 100644 --- a/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m +++ b/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,8 +26,8 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS #import @@ -39,13 +40,17 @@ #import "../../CCTextureCache.h" #import "../../ccMacros.h" #import "../../CCScene.h" +#import "../../CCGLProgram.h" +#import "../../ccGLStateCache.h" +#import "../../CCLayer.h" // support imports -#import "glu.h" #import "../../Support/OpenGL_Internal.h" #import "../../Support/CGPointExtension.h" +#import "../../Support/TransformUtils.h" -#import "CCLayer.h" +#import "kazmath/kazmath.h" +#import "kazmath/GL/matrix.h" #if CC_ENABLE_PROFILERS #import "../../Support/CCProfiling.h" @@ -58,50 +63,36 @@ CGFloat __ccContentScaleFactor = 1; #pragma mark - -#pragma mark Director iOS +#pragma mark Director @interface CCDirector () -(void) setNextScene; --(void) showFPS; +-(void) showStats; -(void) calculateDeltaTime; +-(void) calculateMPF; @end @implementation CCDirector (iOSExtensionClassMethods) +(Class) defaultDirector { - return [CCDirectorTimer class]; + return [CCDirectorDisplayLink class]; } -+ (BOOL) setDirectorType:(ccDirectorType)type +-(void) setInterfaceOrientationDelegate:(id)delegate { - if( type == CCDirectorTypeDisplayLink ) { - NSString *reqSysVer = @"3.1"; - NSString *currSysVer = [[UIDevice currentDevice] systemVersion]; - - if([currSysVer compare:reqSysVer options:NSNumericSearch] == NSOrderedAscending) - return NO; - } - switch (type) { - case CCDirectorTypeNSTimer: - [CCDirectorTimer sharedDirector]; - break; - case CCDirectorTypeDisplayLink: - [CCDirectorDisplayLink sharedDirector]; - break; - case CCDirectorTypeMainLoop: - [CCDirectorFast sharedDirector]; - break; - case CCDirectorTypeThreadMainLoop: - [CCDirectorFastThreaded sharedDirector]; - break; - default: - NSAssert(NO,@"Unknown director type"); - } - - return YES; + // override me } +-(CCTouchDispatcher*) touchDispatcher +{ + return nil; +} + +-(void) setTouchDispatcher:(CCTouchDispatcher*)touchDispatcher +{ + // +} @end @@ -110,41 +101,34 @@ + (BOOL) setDirectorType:(ccDirectorType)type #pragma mark CCDirectorIOS @interface CCDirectorIOS () --(BOOL)isOpenGLAttached; --(BOOL)initOpenGLViewWithView:(UIView *)view withFrame:(CGRect)rect; - -(void) updateContentScaleFactor; - @end @implementation CCDirectorIOS -@synthesize pixelFormat=pixelFormat_; - - (id) init -{ +{ if( (self=[super init]) ) { - - - // default values - pixelFormat_ = kCCPixelFormatDefault; // DEPRECATED. Will be removed in 1.0 - depthBufferFormat_ = 0; // DEPRECATED. Will be removed in 1.0 - - // portrait mode default - deviceOrientation_ = CCDeviceOrientationPortrait; - + __ccContentScaleFactor = 1; isContentScaleSupported_ = NO; - + + touchDispatcher_ = [[CCTouchDispatcher alloc] init]; + // running thread is main thread on iOS runningThread_ = [NSThread currentThread]; + + // Apparently it comes with a default view, and we don't want it +// [self setView:nil]; } - + return self; } - (void) dealloc -{ +{ + [touchDispatcher_ release]; + [super dealloc]; } @@ -152,264 +136,122 @@ - (void) dealloc // Draw the Scene // - (void) drawScene -{ +{ /* calculate "global" dt */ [self calculateDeltaTime]; - + + CCGLView *openGLview = (CCGLView*)[self view]; + + [EAGLContext setCurrentContext: [openGLview context]]; + /* tick before glClear: issue #533 */ - if( ! isPaused_ ) { - [[CCScheduler sharedScheduler] tick: dt]; - } - + if( ! isPaused_ ) + [scheduler_ update: dt]; + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - + /* to avoid flickr, nextScene MUST be here: after tick and before draw. XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */ if( nextScene_ ) [self setNextScene]; - - glPushMatrix(); - - [self applyOrientation]; - - // By default enable VertexArray, ColorArray, TextureCoordArray and Texture2D - CC_ENABLE_DEFAULT_GL_STATES(); - - /* draw the scene */ + + kmGLPushMatrix(); + [runningScene_ visit]; - - /* draw the notification node */ + [notificationNode_ visit]; - if( displayFPS_ ) - [self showFPS]; - -#if CC_ENABLE_PROFILERS - [self showProfilers]; -#endif - - CC_DISABLE_DEFAULT_GL_STATES(); - - glPopMatrix(); - - [openGLView_ swapBuffers]; + if( displayStats_ ) + [self showStats]; + + kmGLPopMatrix(); + + totalFrames_++; + + [openGLview swapBuffers]; + + if( displayStats_ ) + [self calculateMPF]; } -(void) setProjection:(ccDirectorProjection)projection { CGSize size = winSizeInPixels_; - + CGSize sizePoint = winSizeInPoints_; + + glViewport(0, 0, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); + switch (projection) { case kCCDirectorProjection2D: - glViewport(0, 0, size.width, size.height); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - ccglOrtho(0, size.width, 0, size.height, -1024 * CC_CONTENT_SCALE_FACTOR(), 1024 * CC_CONTENT_SCALE_FACTOR()); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); + + kmGLMatrixMode(KM_GL_PROJECTION); + kmGLLoadIdentity(); + + kmMat4 orthoMatrix; + kmMat4OrthographicProjection(&orthoMatrix, 0, size.width, 0, size.height, -1024, 1024 ); + kmGLMultMatrix( &orthoMatrix ); + + kmGLMatrixMode(KM_GL_MODELVIEW); + kmGLLoadIdentity(); break; - + case kCCDirectorProjection3D: - glViewport(0, 0, size.width, size.height); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - gluPerspective(60, (GLfloat)size.width/size.height, 0.5f, 1500.0f); - - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - gluLookAt( size.width/2, size.height/2, [self getZEye], - size.width/2, size.height/2, 0, - 0.0f, 1.0f, 0.0f); - break; - - case kCCDirectorProjectionCustom: - if( projectionDelegate_ ) - [projectionDelegate_ updateProjection]; - break; - - default: - CCLOG(@"cocos2d: Director: unrecognized projecgtion"); - break; - } - - projection_ = projection; -} + { + // reset the viewport if 3d proj & retina display + if( CC_CONTENT_SCALE_FACTOR() != 1 ) + glViewport(-size.width/2, -size.height/2, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); -#pragma mark Director Scene iPhone Specific + float zeye = [self getZEye]; --(void) setPixelFormat: (tPixelFormat) format -{ - NSAssert( ! [self isOpenGLAttached], @"Can't change the pixel format after the director was initialized" ); - pixelFormat_ = format; -} + kmMat4 matrixPerspective, matrixLookup; --(void) setDepthBufferFormat: (tDepthBufferFormat) format -{ - NSAssert( ! [self isOpenGLAttached], @"Can't change the depth buffer format after the director was initialized"); - depthBufferFormat_ = format; -} + kmGLMatrixMode(KM_GL_PROJECTION); + kmGLLoadIdentity(); -#pragma mark Director Integration with a UIKit view + // issue #1334 + kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, zeye*2); +// kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, 1500); -// is the view currently attached --(BOOL)isOpenGLAttached -{ - return ([openGLView_ superview]!=nil); -} + kmGLMultMatrix(&matrixPerspective); -// XXX: deprecated --(BOOL)detach -{ - NSAssert([self isOpenGLAttached], @"FATAL: Director: Can't detach the OpenGL View, because it is not attached. Attach it first."); - - // remove from the superview - [openGLView_ removeFromSuperview]; - - NSAssert(![self isOpenGLAttached], @"FATAL: Director: Can't detach the OpenGL View, it is still attached to the superview."); - - - return YES; -} + kmGLMatrixMode(KM_GL_MODELVIEW); + kmGLLoadIdentity(); + kmVec3 eye, center, up; + kmVec3Fill( &eye, sizePoint.width/2, sizePoint.height/2, zeye ); + kmVec3Fill( ¢er, sizePoint.width/2, sizePoint.height/2, 0 ); + kmVec3Fill( &up, 0, 1, 0); + kmMat4LookAt(&matrixLookup, &eye, ¢er, &up); + kmGLMultMatrix(&matrixLookup); + break; + } -// XXX: Deprecated method --(BOOL)attachInWindow:(UIWindow *)window -{ - if([self initOpenGLViewWithView:window withFrame:[window bounds]]) - { - return YES; - } - - return NO; -} + case kCCDirectorProjectionCustom: + if( [delegate_ respondsToSelector:@selector(updateProjection)] ) + [delegate_ updateProjection]; + break; -// XXX: Deprecated method --(BOOL)attachInView:(UIView *)view -{ - if([self initOpenGLViewWithView:view withFrame:[view bounds]]) - { - return YES; + default: + CCLOG(@"cocos2d: Director: unrecognized projection"); + break; } - - return NO; -} -// XXX: Deprecated method --(BOOL)attachInView:(UIView *)view withFrame:(CGRect)frame -{ - if([self initOpenGLViewWithView:view withFrame:frame]) - { - return YES; - } - - return NO; + projection_ = projection; + + ccSetProjectionMatrixDirty(); } -// XXX: Deprecated method --(BOOL)initOpenGLViewWithView:(UIView *)view withFrame:(CGRect)rect +#pragma mark Director - TouchDispatcher + +-(CCTouchDispatcher*) touchDispatcher { - NSAssert( ! [self isOpenGLAttached], @"FATAL: Can't re-attach the OpenGL View, because it is already attached. Detach it first"); - - // check if the view is not initialized - if(!openGLView_) - { - // define the pixel format - NSString *pFormat = nil; - GLuint depthFormat = 0; - - if(pixelFormat_==kCCPixelFormatRGBA8888) - pFormat = kEAGLColorFormatRGBA8; - else if(pixelFormat_== kCCPixelFormatRGB565) - pFormat = kEAGLColorFormatRGB565; - else { - CCLOG(@"cocos2d: Director: Unknown pixel format."); - } - - if(depthBufferFormat_ == kCCDepthBuffer16) - depthFormat = GL_DEPTH_COMPONENT16_OES; - else if(depthBufferFormat_ == kCCDepthBuffer24) - depthFormat = GL_DEPTH_COMPONENT24_OES; - else if(depthBufferFormat_ == kCCDepthBufferNone) - depthFormat = 0; - else { - CCLOG(@"cocos2d: Director: Unknown buffer depth."); - } - - // alloc and init the opengl view - openGLView_ = [[EAGLView alloc] initWithFrame:rect - pixelFormat:pFormat - depthFormat:depthFormat - preserveBackbuffer:NO - sharegroup:nil - multiSampling:NO - numberOfSamples:0]; - - // check if the view was alloced and initialized - NSAssert( openGLView_, @"FATAL: Could not alloc and init the OpenGL view. "); - - // opaque by default (faster) - openGLView_.opaque = YES; - } - else - { - // set the (new) frame of the glview - [openGLView_ setFrame:rect]; - } - - winSizeInPoints_ = rect.size; - winSizeInPixels_ = CGSizeMake(winSizeInPoints_.width * __ccContentScaleFactor, winSizeInPoints_.height * __ccContentScaleFactor); - - - // set the touch delegate of the glview to self - [openGLView_ setTouchDelegate: [CCTouchDispatcher sharedDispatcher]]; - - - // check if the superview has touchs enabled and enable it in our view - if([view isUserInteractionEnabled]) - { - [openGLView_ setUserInteractionEnabled:YES]; - [[CCTouchDispatcher sharedDispatcher] setDispatchEvents: YES]; - } - else - { - [openGLView_ setUserInteractionEnabled:NO]; - [[CCTouchDispatcher sharedDispatcher] setDispatchEvents: NO]; - } - - // check if multi touches are enabled and set them - if([view isMultipleTouchEnabled]) - { - [openGLView_ setMultipleTouchEnabled:YES]; - } - else - { - [openGLView_ setMultipleTouchEnabled:NO]; - } - - // add the glview to his (new) superview - [view addSubview:openGLView_]; - - - NSAssert( [self isOpenGLAttached], @"FATAL: Director: Could not attach OpenGL view"); - - [self setGLDefaultValues]; - return YES; + return touchDispatcher_; } --(void) setOpenGLView:(EAGLView *)view +-(void) setTouchDispatcher:(CCTouchDispatcher*)touchDispatcher { - if( view != openGLView_ ) { - - [super setOpenGLView:view]; - - // set size - winSizeInPixels_ = CGSizeMake(winSizeInPoints_.width * __ccContentScaleFactor, winSizeInPoints_.height *__ccContentScaleFactor); - - if( __ccContentScaleFactor != 1 ) - [self updateContentScaleFactor]; - - CCTouchDispatcher *touchDispatcher = [CCTouchDispatcher sharedDispatcher]; - [openGLView_ setTouchDelegate: touchDispatcher]; - [touchDispatcher setDispatchEvents: YES]; + if( touchDispatcher != touchDispatcher_ ) { + [touchDispatcher_ release]; + touchDispatcher_ = [touchDispatcher retain]; } } @@ -423,13 +265,13 @@ -(CGFloat) contentScaleFactor -(void) setContentScaleFactor:(CGFloat)scaleFactor { if( scaleFactor != __ccContentScaleFactor ) { - + __ccContentScaleFactor = scaleFactor; winSizeInPixels_ = CGSizeMake( winSizeInPoints_.width * scaleFactor, winSizeInPoints_.height * scaleFactor ); - - if( openGLView_ ) + + if( view_ ) [self updateContentScaleFactor]; - + // update projection [self setProjection:projection_]; } @@ -437,15 +279,10 @@ -(void) setContentScaleFactor:(CGFloat)scaleFactor -(void) updateContentScaleFactor { - // Based on code snippet from: http://developer.apple.com/iphone/prerelease/library/snippets/sp2010/sp28.html - if ([openGLView_ respondsToSelector:@selector(setContentScaleFactor:)]) - { - [openGLView_ setContentScaleFactor: __ccContentScaleFactor]; - - isContentScaleSupported_ = YES; - } - else - CCLOG(@"cocos2d: 'setContentScaleFactor:' is not supported on this device"); + NSAssert( [view_ respondsToSelector:@selector(setContentScaleFactor:)], @"cocos2d v2.0+ runs on iOS 4 or later"); + + [view_ setContentScaleFactor: __ccContentScaleFactor]; + isContentScaleSupported_ = YES; } -(BOOL) enableRetinaDisplay:(BOOL)enabled @@ -453,13 +290,13 @@ -(BOOL) enableRetinaDisplay:(BOOL)enabled // Already enabled ? if( enabled && __ccContentScaleFactor == 2 ) return YES; - + // Already disabled if( ! enabled && __ccContentScaleFactor == 1 ) return YES; // setContentScaleFactor is not supported - if (! [openGLView_ respondsToSelector:@selector(setContentScaleFactor:)]) + if (! [view_ respondsToSelector:@selector(setContentScaleFactor:)]) return NO; // SD device @@ -468,392 +305,153 @@ -(BOOL) enableRetinaDisplay:(BOOL)enabled float newScale = enabled ? 2 : 1; [self setContentScaleFactor:newScale]; - + + // Load Hi-Res FPS label + [self createStatsLabel]; + return YES; } // overriden, don't call super -(void) reshapeProjection:(CGSize)size { - winSizeInPoints_ = [openGLView_ bounds].size; + winSizeInPoints_ = [view_ bounds].size; winSizeInPixels_ = CGSizeMake(winSizeInPoints_.width * __ccContentScaleFactor, winSizeInPoints_.height *__ccContentScaleFactor); - + [self setProjection:projection_]; } -#pragma mark Director Scene Landscape +#pragma mark Director Point Convertion -(CGPoint)convertToGL:(CGPoint)uiPoint { CGSize s = winSizeInPoints_; float newY = s.height - uiPoint.y; - float newX = s.width - uiPoint.x; - - CGPoint ret = CGPointZero; - switch ( deviceOrientation_) { - case CCDeviceOrientationPortrait: - ret = ccp( uiPoint.x, newY ); - break; - case CCDeviceOrientationPortraitUpsideDown: - ret = ccp(newX, uiPoint.y); - break; - case CCDeviceOrientationLandscapeLeft: - ret.x = uiPoint.y; - ret.y = uiPoint.x; - break; - case CCDeviceOrientationLandscapeRight: - ret.x = newY; - ret.y = newX; - break; - } - -// if( __ccContentScaleFactor != 1 && isContentScaleSupported_ ) -// ret = ccpMult(ret, __ccContentScaleFactor); - return ret; + + return ccp( uiPoint.x, newY ); } -(CGPoint)convertToUI:(CGPoint)glPoint { CGSize winSize = winSizeInPoints_; - int oppositeX = winSize.width - glPoint.x; int oppositeY = winSize.height - glPoint.y; - CGPoint uiPoint = CGPointZero; - switch ( deviceOrientation_) { - case CCDeviceOrientationPortrait: - uiPoint = ccp(glPoint.x, oppositeY); - break; - case CCDeviceOrientationPortraitUpsideDown: - uiPoint = ccp(oppositeX, glPoint.y); - break; - case CCDeviceOrientationLandscapeLeft: - uiPoint = ccp(glPoint.y, glPoint.x); - break; - case CCDeviceOrientationLandscapeRight: - // Can't use oppositeX/Y because x/y are flipped - uiPoint = ccp(winSize.width-glPoint.y, winSize.height-glPoint.x); - break; - } - - uiPoint = ccpMult(uiPoint, 1/__ccContentScaleFactor); - return uiPoint; -} - -// get the current size of the glview --(CGSize) winSize -{ - CGSize s = winSizeInPoints_; - - if( deviceOrientation_ == CCDeviceOrientationLandscapeLeft || deviceOrientation_ == CCDeviceOrientationLandscapeRight ) { - // swap x,y in landscape mode - CGSize tmp = s; - s.width = tmp.height; - s.height = tmp.width; - } - return s; -} - --(CGSize) winSizeInPixels -{ - CGSize s = [self winSize]; - - s.width *= CC_CONTENT_SCALE_FACTOR(); - s.height *= CC_CONTENT_SCALE_FACTOR(); - - return s; -} - --(ccDeviceOrientation) deviceOrientation -{ - return deviceOrientation_; -} - -- (void) setDeviceOrientation:(ccDeviceOrientation) orientation -{ - if( deviceOrientation_ != orientation ) { - deviceOrientation_ = orientation; - switch( deviceOrientation_) { - case CCDeviceOrientationPortrait: - [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationPortrait animated:NO]; - break; - case CCDeviceOrientationPortraitUpsideDown: - [[UIApplication sharedApplication] setStatusBarOrientation: UIDeviceOrientationPortraitUpsideDown animated:NO]; - break; - case CCDeviceOrientationLandscapeLeft: - [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:NO]; - break; - case CCDeviceOrientationLandscapeRight: - [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationLandscapeLeft animated:NO]; - break; - default: - NSLog(@"Director: Unknown device orientation"); - break; - } - } -} --(void) applyOrientation -{ - CGSize s = winSizeInPixels_; - float w = s.width / 2; - float h = s.height / 2; - - // XXX it's using hardcoded values. - // What if the the screen size changes in the future? - switch ( deviceOrientation_ ) { - case CCDeviceOrientationPortrait: - // nothing - break; - case CCDeviceOrientationPortraitUpsideDown: - // upside down - glTranslatef(w,h,0); - glRotatef(180,0,0,1); - glTranslatef(-w,-h,0); - break; - case CCDeviceOrientationLandscapeRight: - glTranslatef(w,h,0); - glRotatef(90,0,0,1); - glTranslatef(-h,-w,0); - break; - case CCDeviceOrientationLandscapeLeft: - glTranslatef(w,h,0); - glRotatef(-90,0,0,1); - glTranslatef(-h,-w,0); - break; - } + return ccp(glPoint.x, oppositeY); } -(void) end { // don't release the event handlers // They are needed in case the director is run again - [[CCTouchDispatcher sharedDispatcher] removeAllDelegates]; - + [touchDispatcher_ removeAllDelegates]; + [super end]; } -@end - +#pragma mark Director - UIViewController delegate -#pragma mark - -#pragma mark Director TimerDirector -@implementation CCDirectorTimer -- (void)startAnimation +-(void) setView:(CCGLView *)view { - NSAssert( animationTimer == nil, @"animationTimer must be nil. Calling startAnimation twice?"); - - if( gettimeofday( &lastUpdate_, NULL) != 0 ) { - CCLOG(@"cocos2d: Director: Error in gettimeofday"); + if( view != view_) { + [super setView:view]; + + // set size + winSizeInPixels_ = CGSizeMake(winSizeInPoints_.width * __ccContentScaleFactor, winSizeInPoints_.height *__ccContentScaleFactor); + + if( __ccContentScaleFactor != 1 ) + [self updateContentScaleFactor]; + + [view setTouchDelegate: touchDispatcher_]; + [touchDispatcher_ setDispatchEvents: YES]; } - - animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval_ target:self selector:@selector(mainLoop) userInfo:nil repeats:YES]; - - // - // If you want to attach the opengl view into UIScrollView - // uncomment this line to prevent 'freezing'. - // It doesn't work on with the Fast Director - // - // [[NSRunLoop currentRunLoop] addTimer:animationTimer - // forMode:NSRunLoopCommonModes]; } --(void) mainLoop +// Override to allow orientations other than the default portrait orientation. +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - [self drawScene]; + BOOL ret =YES; + if( [delegate_ respondsToSelector:_cmd] ) + ret = (BOOL) [delegate_ shouldAutorotateToInterfaceOrientation:interfaceOrientation]; + + return ret; } -- (void)stopAnimation +-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { - [animationTimer invalidate]; - animationTimer = nil; + // do something ? } -- (void)setAnimationInterval:(NSTimeInterval)interval + +-(void) viewWillAppear:(BOOL)animated { - animationInterval_ = interval; - - if(animationTimer) { - [self stopAnimation]; - [self startAnimation]; - } + [super viewWillAppear:animated]; + [self startAnimation]; } --(void) dealloc +-(void) viewDidAppear:(BOOL)animated { - [animationTimer release]; - [super dealloc]; + [super viewDidAppear:animated]; +// [self startAnimation]; } -@end - -#pragma mark - -#pragma mark Director DirectorFast - -@implementation CCDirectorFast - -- (id) init +-(void) viewWillDisappear:(BOOL)animated { - if(( self = [super init] )) { - -#if CC_DIRECTOR_DISPATCH_FAST_EVENTS - CCLOG(@"cocos2d: Fast Events enabled"); -#else - CCLOG(@"cocos2d: Fast Events disabled"); -#endif - isRunning = NO; - - // XXX: - // XXX: Don't create any autorelease object before calling "fast director" - // XXX: else it will be leaked - // XXX: - autoreleasePool = [NSAutoreleasePool new]; - } +// [self stopAnimation]; - return self; + [super viewWillDisappear:animated]; } -- (void) startAnimation +-(void) viewDidDisappear:(BOOL)animated { - // XXX: - // XXX: release autorelease objects created - // XXX: between "use fast director" and "runWithScene" - // XXX: - [autoreleasePool release]; - autoreleasePool = nil; - - if ( gettimeofday( &lastUpdate_, NULL) != 0 ) { - CCLOG(@"cocos2d: Director: Error in gettimeofday"); - } - - - isRunning = YES; - - SEL selector = @selector(mainLoop); - NSMethodSignature* sig = [[[CCDirector sharedDirector] class] - instanceMethodSignatureForSelector:selector]; - NSInvocation* invocation = [NSInvocation - invocationWithMethodSignature:sig]; - [invocation setTarget:[CCDirector sharedDirector]]; - [invocation setSelector:selector]; - [invocation performSelectorOnMainThread:@selector(invokeWithTarget:) - withObject:[CCDirector sharedDirector] waitUntilDone:NO]; - -// NSInvocationOperation *loopOperation = [[[NSInvocationOperation alloc] -// initWithTarget:self selector:@selector(mainLoop) object:nil] -// autorelease]; -// -// [loopOperation performSelectorOnMainThread:@selector(start) withObject:nil -// waitUntilDone:NO]; -} - --(void) mainLoop -{ - while (isRunning) { - - NSAutoreleasePool *loopPool = [NSAutoreleasePool new]; - -#if CC_DIRECTOR_DISPATCH_FAST_EVENTS - while( CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.004f, FALSE) == kCFRunLoopRunHandledSource); -#else - while(CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource); -#endif - - if (isPaused_) { - usleep(250000); // Sleep for a quarter of a second (250,000 microseconds) so that the framerate is 4 fps. - } - - [self drawScene]; + [self stopAnimation]; -#if CC_DIRECTOR_DISPATCH_FAST_EVENTS - while( CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.004f, FALSE) == kCFRunLoopRunHandledSource); -#else - while(CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource); -#endif - - [loopPool release]; - } -} -- (void) stopAnimation -{ - isRunning = NO; + [super viewDidDisappear:animated]; } -- (void)setAnimationInterval:(NSTimeInterval)interval +- (void)didReceiveMemoryWarning { - NSLog(@"FastDirectory doesn't support setAnimationInterval, yet"); -} -@end - -#pragma mark - -#pragma mark Director DirectorThreadedFast - -@implementation CCDirectorFastThreaded + // Release any cached data, images, etc that aren't in use. + [super purgeCachedData]; -- (id) init -{ - if(( self = [super init] )) { - isRunning = NO; - } - - return self; + // Releases the view if it doesn't have a superview. + [super didReceiveMemoryWarning]; } -- (void) startAnimation +-(void) viewDidLoad { - - if ( gettimeofday( &lastUpdate_, NULL) != 0 ) { - CCLOG(@"cocos2d: ThreadedFastDirector: Error on gettimeofday"); - } - - isRunning = YES; + CCLOG(@"cocos2d: viewDidLoad"); - NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(mainLoop) object:nil]; - [thread start]; - [thread release]; + [super viewDidLoad]; } --(void) mainLoop -{ - while( ![[NSThread currentThread] isCancelled] ) { - if( isRunning ) - [self performSelectorOnMainThread:@selector(drawScene) withObject:nil waitUntilDone:YES]; - - if (isPaused_) { - usleep(250000); // Sleep for a quarter of a second (250,000 microseconds) so that the framerate is 4 fps. - } else { -// usleep(2000); - } - } -} -- (void) stopAnimation -{ - isRunning = NO; -} -- (void)setAnimationInterval:(NSTimeInterval)interval +- (void)viewDidUnload { - NSLog(@"FastDirector doesn't support setAnimationInterval, yet"); + CCLOG(@"cocos2d: viewDidUnload"); + + [super viewDidUnload]; + // Release any retained subviews of the main view. + // e.g. self.myOutlet = nil; } @end + #pragma mark - #pragma mark DirectorDisplayLink -// Allows building DisplayLinkDirector for pre-3.1 SDKS -// without getting compiler warnings. -@interface NSObject(CADisplayLink) -+ (id) displayLinkWithTarget:(id)arg1 selector:(SEL)arg2; -- (void) addToRunLoop:(id)arg1 forMode:(id)arg2; -- (void) setFrameInterval:(int)interval; -- (void) invalidate; -@end - @implementation CCDirectorDisplayLink + +-(void) mainLoop:(id)sender +{ + [self drawScene]; +} + - (void)setAnimationInterval:(NSTimeInterval)interval { animationInterval_ = interval; - if(displayLink){ + if(displayLink_){ [self stopAnimation]; [self startAnimation]; } @@ -861,37 +459,94 @@ - (void)setAnimationInterval:(NSTimeInterval)interval - (void) startAnimation { - if ( gettimeofday( &lastUpdate_, NULL) != 0 ) { - CCLOG(@"cocos2d: DisplayLinkDirector: Error on gettimeofday"); - } - + NSAssert( displayLink_ == nil, @"displayLink must be nil. Calling startAnimation twice?"); + + gettimeofday( &lastUpdate_, NULL); + // approximate frame rate // assumes device refreshes at 60 fps int frameInterval = (int) floor(animationInterval_ * 60.0f); - - CCLOG(@"cocos2d: Frame interval: %d", frameInterval); - displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(mainLoop:)]; - [displayLink setFrameInterval:frameInterval]; - [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + CCLOG(@"cocos2d: animation started with frame interval: %.2f", 60.0f/frameInterval); + + displayLink_ = [CADisplayLink displayLinkWithTarget:self selector:@selector(mainLoop:)]; + [displayLink_ setFrameInterval:frameInterval]; + +#if CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD + // + runningThread_ = [[NSThread alloc] initWithTarget:self selector:@selector(threadMainLoop) object:nil]; + [runningThread_ start]; + +#else + // setup DisplayLink in main thread + [displayLink_ addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; +#endif + + } --(void) mainLoop:(id)sender +- (void) stopAnimation { - [self drawScene]; + CCLOG(@"cocos2d: animation stopped"); + +#if CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD + [runningThread_ cancel]; + [runningThread_ release]; + runningThread_ = nil; +#endif + + [displayLink_ invalidate]; + displayLink_ = nil; } -- (void) stopAnimation +// Overriden in order to use a more stable delta time +-(void) calculateDeltaTime +{ + // New delta time + if( nextDeltaTimeZero_ ) { + dt = 0; + nextDeltaTimeZero_ = NO; + } else { + dt = displayLink_.timestamp - lastDisplayTime_; + dt = MAX(0,dt); + } + // Store this timestamp for next time + lastDisplayTime_ = displayLink_.timestamp; + + // needed for SPF + if( displayStats_ ) + gettimeofday( &lastUpdate_, NULL); + +#ifdef DEBUG + // If we are debugging our code, prevent big delta time + if( dt > 0.2f ) + dt = 1/60.0f; +#endif +} + + +#pragma mark Director Thread + +// +// Director has its own thread +// +-(void) threadMainLoop { - [displayLink invalidate]; - displayLink = nil; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + [displayLink_ addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + + // start the run loop + [[NSRunLoop currentRunLoop] run]; + + [pool release]; } -(void) dealloc { - [displayLink release]; + [displayLink_ release]; [super dealloc]; } @end -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h b/Example/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h index 20ba036..d8e254b 100644 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h +++ b/Example/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,22 +25,22 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS #import /** CCTargetedTouchDelegate. - + Using this type of delegate results in two benefits: 1. You don't need to deal with NSSets, the dispatcher does the job of splitting them. You get exactly one UITouch per call. 2. You can *claim* a UITouch by returning YES in ccTouchBegan. Updates of claimed touches are sent only to the delegate(s) that claimed them. So if you get a move/ - ended/cancelled update you're sure it's your touch. This frees you from doing a + ended/cancelled update you're sure it is your touch. This frees you from doing a lot of checks when doing multi-touch. - + (The name TargetedTouchDelegate relates to updates "targeting" their specific handler, without bothering the other handlers.) @since v0.8 @@ -60,7 +60,7 @@ /** CCStandardTouchDelegate. - + This type of delegate is the same one used by CocoaTouch. You will receive all the events (Began,Moved,Ended,Cancelled). @since v0.8 */ @@ -72,4 +72,4 @@ - (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; @end -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h b/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h index b692c6d..9995865 100644 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h +++ b/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,11 +25,11 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS #import "CCTouchDelegateProtocol.h" -#import "EAGLView.h" +#import "CCGLView.h" typedef enum @@ -47,7 +47,7 @@ enum { kCCTouchMoved, kCCTouchEnded, kCCTouchCancelled, - + kCCTouchMax, }; @@ -58,22 +58,22 @@ struct ccTouchHandlerHelperData { }; /** CCTouchDispatcher. - Singleton that handles all the touch events. + Object that handles all the touch events. The dispatcher dispatches events to the registered TouchHandlers. There are 2 different type of touch handlers: - Standard Touch Handlers - Targeted Touch Handlers - + The Standard Touch Handlers work like the CocoaTouch touch handler: a set of touches is passed to the delegate. On the other hand, the Targeted Touch Handlers only receive 1 touch at the time, and they can "swallow" touches (avoid the propagation of the event). - + Firstly, the dispatcher sends the received touches to the targeted touches. These touches can be swallowed by the Targeted Touch Handlers. If there are still remaining touches, then the remaining touches will be sent to the Standard Touch Handlers. @since v0.8.0 */ -@interface CCTouchDispatcher : NSObject +@interface CCTouchDispatcher : NSObject { NSMutableArray *targetedHandlers; NSMutableArray *standardHandlers; @@ -86,14 +86,11 @@ struct ccTouchHandlerHelperData { BOOL toQuit; BOOL dispatchEvents; - + // 4, 1 for each type of event struct ccTouchHandlerHelperData handlerHelperData[kCCTouchMax]; } -/** singleton of the CCTouchDispatcher */ -+ (CCTouchDispatcher*)sharedDispatcher; - /** Whether or not the events are going to be dispatched. Default: YES */ @property (nonatomic,readwrite, assign) BOOL dispatchEvents; @@ -117,6 +114,7 @@ struct ccTouchHandlerHelperData { the higher the priority */ -(void) setPriority:(int) priority forDelegate:(id) delegate; +NSComparisonResult sortByPriority(id first, id second, void *context); @end -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m b/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m index 46e433e..788e99d 100644 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m +++ b/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,49 +25,28 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS #import "CCTouchDispatcher.h" #import "CCTouchHandler.h" - @implementation CCTouchDispatcher @synthesize dispatchEvents; -static CCTouchDispatcher *sharedDispatcher = nil; - -+(CCTouchDispatcher*) sharedDispatcher -{ - @synchronized(self) { - if (sharedDispatcher == nil) - sharedDispatcher = [[self alloc] init]; // assignment not done here - } - return sharedDispatcher; -} - -+(id) allocWithZone:(NSZone *)zone -{ - @synchronized(self) { - NSAssert(sharedDispatcher == nil, @"Attempted to allocate a second instance of a singleton."); - return [super allocWithZone:zone]; - } - return nil; // on subsequent allocation attempts return nil -} - -(id) init { if((self = [super init])) { - + dispatchEvents = YES; targetedHandlers = [[NSMutableArray alloc] initWithCapacity:8]; standardHandlers = [[NSMutableArray alloc] initWithCapacity:4]; - + handlersToAdd = [[NSMutableArray alloc] initWithCapacity:8]; handlersToRemove = [[NSMutableArray alloc] initWithCapacity:8]; - + toRemove = NO; toAdd = NO; toQuit = NO; @@ -77,9 +56,9 @@ -(id) init handlerHelperData[kCCTouchMoved] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesMoved:withEvent:),@selector(ccTouchMoved:withEvent:),kCCTouchSelectorMovedBit}; handlerHelperData[kCCTouchEnded] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesEnded:withEvent:),@selector(ccTouchEnded:withEvent:),kCCTouchSelectorEndedBit}; handlerHelperData[kCCTouchCancelled] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesCancelled:withEvent:),@selector(ccTouchCancelled:withEvent:),kCCTouchSelectorCancelledBit}; - + } - + return self; } @@ -101,14 +80,14 @@ -(void) dealloc -(void) forceAddHandler:(CCTouchHandler*)handler array:(NSMutableArray*)array { NSUInteger i = 0; - + for( CCTouchHandler *h in array ) { if( h.priority < handler.priority ) i++; - + NSAssert( h.delegate != handler.delegate, @"Delegate already added to touch dispatcher."); } - [array insertObject:handler atIndex:i]; + [array insertObject:handler atIndex:i]; } -(void) addStandardDelegate:(id) delegate priority:(int)priority @@ -138,27 +117,27 @@ -(void) addTargetedDelegate:(id) delegate priority:(int -(void) forceRemoveDelegate:(id)delegate { // XXX: remove it from both handlers ??? - + for( CCTouchHandler *handler in targetedHandlers ) { if( handler.delegate == delegate ) { [targetedHandlers removeObject:handler]; break; } } - + for( CCTouchHandler *handler in standardHandlers ) { if( handler.delegate == delegate ) { [standardHandlers removeObject:handler]; break; } - } + } } -(void) removeDelegate:(id) delegate { if( delegate == nil ) return; - + if( ! locked ) { [self forceRemoveDelegate:delegate]; } else { @@ -184,45 +163,76 @@ -(void) removeAllDelegates #pragma mark Changing priority of added handlers --(void) setPriority:(int) priority forDelegate:(id) delegate +-(CCTouchHandler*) findHandler:(id)delegate +{ + for( CCTouchHandler *handler in targetedHandlers ) { + if( handler.delegate == delegate ) { + return handler; + } + } + + for( CCTouchHandler *handler in standardHandlers ) { + if( handler.delegate == delegate ) { + return handler; + } + } + + if (toAdd) { + for( CCTouchHandler *handler in handlersToAdd ) { + if (handler.delegate == delegate) { + return handler; + } + } + } + + return nil; +} + +NSComparisonResult sortByPriority(id first, id second, void *context) { - NSAssert(NO, @"Set priority no implemented yet. Don't forget to report this bug!"); -// if( delegate == nil ) -// [NSException raise:NSInvalidArgumentException format:@"Got nil touch delegate"]; -// -// CCTouchHandler *handler = nil; -// for( handler in touchHandlers ) -// if( handler.delegate == delegate ) break; -// -// if( handler == nil ) -// [NSException raise:NSInvalidArgumentException format:@"Touch delegate not found"]; -// -// if( handler.priority != priority ) { -// handler.priority = priority; -// -// [handler retain]; -// [touchHandlers removeObject:handler]; -// [self addHandler:handler]; -// [handler release]; -// } + if (((CCTouchHandler*)first).priority < ((CCTouchHandler*)second).priority) + return NSOrderedAscending; + else if (((CCTouchHandler*)first).priority > ((CCTouchHandler*)second).priority) + return NSOrderedDescending; + else + return NSOrderedSame; } +-(void) rearrangeHandlers:(NSMutableArray*)array +{ + [array sortUsingFunction:sortByPriority context:nil]; +} + +-(void) setPriority:(int) priority forDelegate:(id) delegate +{ + NSAssert(delegate != nil, @"Got nil touch delegate!"); + + CCTouchHandler *handler = nil; + handler = [self findHandler:delegate]; + + NSAssert(handler != nil, @"Delegate not found!"); + + handler.priority = priority; + + [self rearrangeHandlers:targetedHandlers]; + [self rearrangeHandlers:standardHandlers]; +} // // dispatch events // --(void) touches:(NSSet*)touches withEvent:(UIEvent*)event withTouchType:(unsigned int)idx; +-(void) touches:(NSSet*)touches withEvent:(UIEvent*)event withTouchType:(unsigned int)idx { NSAssert(idx < 4, @"Invalid idx value"); id mutableTouches; locked = YES; - + // optimization to prevent a mutable copy when it is not necessary unsigned int targetedHandlersCount = [targetedHandlers count]; - unsigned int standardHandlersCount = [standardHandlers count]; + unsigned int standardHandlersCount = [standardHandlers count]; BOOL needsMutableSet = (targetedHandlersCount && standardHandlersCount); - + mutableTouches = (needsMutableSet ? [touches mutableCopy] : touches); struct ccTouchHandlerHelperData helper = handlerHelperData[idx]; @@ -232,24 +242,24 @@ -(void) touches:(NSSet*)touches withEvent:(UIEvent*)event withTouchType:(unsigne if( targetedHandlersCount > 0 ) { for( UITouch *touch in touches ) { for(CCTargetedTouchHandler *handler in targetedHandlers) { - + BOOL claimed = NO; if( idx == kCCTouchBegan ) { claimed = [handler.delegate ccTouchBegan:touch withEvent:event]; if( claimed ) [handler.claimedTouches addObject:touch]; - } - + } + // else (moved, ended, cancelled) else if( [handler.claimedTouches containsObject:touch] ) { claimed = YES; if( handler.enabledSelectors & helper.type ) [handler.delegate performSelector:helper.touchSel withObject:touch withObject:event]; - + if( helper.type & (kCCTouchSelectorCancelledBit | kCCTouchSelectorEndedBit) ) [handler.claimedTouches removeObject:touch]; } - + if( claimed && handler.swallowsTouches ) { if( needsMutableSet ) [mutableTouches removeObject:touch]; @@ -258,7 +268,7 @@ -(void) touches:(NSSet*)touches withEvent:(UIEvent*)event withTouchType:(unsigne } } } - + // // process standard handlers 2nd // @@ -270,22 +280,19 @@ -(void) touches:(NSSet*)touches withEvent:(UIEvent*)event withTouchType:(unsigne } if( needsMutableSet ) [mutableTouches release]; - + // // Optimization. To prevent a [handlers copy] which is expensive // the add/removes/quit is done after the iterations // locked = NO; - if( toRemove ) { - toRemove = NO; - for( id delegate in handlersToRemove ) - [self forceRemoveDelegate:delegate]; - [handlersToRemove removeAllObjects]; - } + + //issue 1084, 1139 first add then remove if( toAdd ) { toAdd = NO; + Class targetedClass = [CCTargetedTouchHandler class]; + for( CCTouchHandler *handler in handlersToAdd ) { - Class targetedClass = [CCTargetedTouchHandler class]; if( [handler isKindOfClass:targetedClass] ) [self forceAddHandler:handler array:targetedHandlers]; else @@ -293,6 +300,14 @@ -(void) touches:(NSSet*)touches withEvent:(UIEvent*)event withTouchType:(unsigne } [handlersToAdd removeAllObjects]; } + + if( toRemove ) { + toRemove = NO; + for( id delegate in handlersToRemove ) + [self forceRemoveDelegate:delegate]; + [handlersToRemove removeAllObjects]; + } + if( toQuit ) { toQuit = NO; [self forceRemoveAllDelegates]; @@ -306,7 +321,7 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { - if( dispatchEvents ) + if( dispatchEvents ) [self touches:touches withEvent:event withTouchType:kCCTouchMoved]; } @@ -323,4 +338,4 @@ - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event } @end -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.h b/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.h index 31a3e36..c448972 100644 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.h +++ b/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.h @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,8 +25,8 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS /* * This file contains the delegates of the touches @@ -90,4 +90,4 @@ @end -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.m b/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.m index a52103b..2aec6ee 100644 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.m +++ b/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.m @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,8 +26,8 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#import "../../ccMacros.h" +#ifdef __CC_PLATFORM_IOS /* * This file contains the delegates of the touches @@ -54,13 +54,13 @@ + (id)handlerWithDelegate:(id) aDelegate priority:(int)aPriority - (id)initWithDelegate:(id) aDelegate priority:(int)aPriority { NSAssert(aDelegate != nil, @"Touch delegate may not be nil"); - + if ((self = [super init])) { self.delegate = aDelegate; priority = aPriority; enabledSelectors_ = 0; } - + return self; } @@ -108,10 +108,10 @@ + (id)handlerWithDelegate:(id)aDelegate priority:(int)priority swallowsTouches:( - (id)initWithDelegate:(id)aDelegate priority:(int)aPriority swallowsTouches:(BOOL)swallow { - if ((self = [super initWithDelegate:aDelegate priority:aPriority])) { + if ((self = [super initWithDelegate:aDelegate priority:aPriority])) { claimedTouches = [[NSMutableSet alloc] initWithCapacity:2]; swallowsTouches = swallow; - + if( [aDelegate respondsToSelector:@selector(ccTouchBegan:withEvent:)] ) enabledSelectors_ |= kCCTouchSelectorBeganBit; if( [aDelegate respondsToSelector:@selector(ccTouchMoved:withEvent:)] ) @@ -121,7 +121,7 @@ - (id)initWithDelegate:(id)aDelegate priority:(int)aPriority swallowsTouches:(BO if( [aDelegate respondsToSelector:@selector(ccTouchCancelled:withEvent:)] ) enabledSelectors_ |= kCCTouchSelectorCancelledBit; } - + return self; } @@ -132,4 +132,4 @@ - (void)dealloc { @end -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED \ No newline at end of file +#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/EAGLView.h b/Example/libs/cocos2d/Platforms/iOS/EAGLView.h deleted file mode 100644 index fd41c5e..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/EAGLView.h +++ /dev/null @@ -1,155 +0,0 @@ -/* - -===== IMPORTANT ===== - -This is sample code demonstrating API, technology or techniques in development. -Although this sample code has been reviewed for technical accuracy, it is not -final. Apple is supplying this information to help you plan for the adoption of -the technologies and programming interfaces described herein. This information -is subject to change, and software implemented based on this sample code should -be tested with final operating system software and final documentation. Newer -versions of this sample code may be provided with future seeds of the API or -technology. For information about updates to this and other developer -documentation, view the New & Updated sidebars in subsequent documentation -seeds. - -===================== - -File: EAGLView.h -Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a -UIView subclass. - -Version: 1.3 - -Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. -("Apple") in consideration of your agreement to the following terms, and your -use, installation, modification or redistribution of this Apple software -constitutes acceptance of these terms. If you do not agree with these terms, -please do not use, install, modify or redistribute this Apple software. - -In consideration of your agreement to abide by the following terms, and subject -to these terms, Apple grants you a personal, non-exclusive license, under -Apple's copyrights in this original Apple software (the "Apple Software"), to -use, reproduce, modify and redistribute the Apple Software, with or without -modifications, in source and/or binary forms; provided that if you redistribute -the Apple Software in its entirety and without modifications, you must retain -this notice and the following text and disclaimers in all such redistributions -of the Apple Software. -Neither the name, trademarks, service marks or logos of Apple Inc. may be used -to endorse or promote products derived from the Apple Software without specific -prior written permission from Apple. Except as expressly stated in this notice, -no other rights or licenses, express or implied, are granted by Apple herein, -including but not limited to any patent rights that may be infringed by your -derivative works or by other works in which the Apple Software may be -incorporated. - -The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN -COMBINATION WITH YOUR PRODUCTS. - -IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR -DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF -CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF -APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright (C) 2008 Apple Inc. All Rights Reserved. - -*/ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - -#import -#import -#import -#import -#import - -#import "ESRenderer.h" - -//CLASSES: - -@class EAGLView; -@class EAGLSharegroup; - -//PROTOCOLS: - -@protocol EAGLTouchDelegate -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; -@end - -//CLASS INTERFACE: - -/** EAGLView Class. - * This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass. - * The view content is basically an EAGL surface you render your OpenGL scene into. - * Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel. - */ -@interface EAGLView : UIView -{ - id renderer_; - EAGLContext *context_; // weak ref - - NSString *pixelformat_; - GLuint depthFormat_; - BOOL preserveBackbuffer_; - - CGSize size_; - BOOL discardFramebufferSupported_; - id touchDelegate_; - - //fsaa addition - BOOL multisampling_; - unsigned int requestedSamples_; -} - -/** creates an initializes an EAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer. */ -+ (id) viewWithFrame:(CGRect)frame; -/** creates an initializes an EAGLView with a frame, a color buffer format, and 0-bit depth buffer. */ -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format; -/** creates an initializes an EAGLView with a frame, a color buffer format, and a depth buffer. */ -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth; -/** creates an initializes an EAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping */ -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples; - -/** Initializes an EAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */ -- (id) initWithFrame:(CGRect)frame; //These also set the current context -/** Initializes an EAGLView with a frame, a color buffer format, and 0-bit depth buffer */ -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format; -/** Initializes an EAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup and multisampling support */ -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples; - -/** pixel format: it could be RGBA8 (32-bit) or RGB565 (16-bit) */ -@property(nonatomic,readonly) NSString* pixelFormat; -/** depth format of the render buffer: 0, 16 or 24 bits*/ -@property(nonatomic,readonly) GLuint depthFormat; - -/** returns surface size in pixels */ -@property(nonatomic,readonly) CGSize surfaceSize; - -/** OpenGL context */ -@property(nonatomic,readonly) EAGLContext *context; - -@property(nonatomic,readwrite) BOOL multiSampling; - -/** touch delegate */ -@property(nonatomic,readwrite,assign) id touchDelegate; - -/** EAGLView uses double-buffer. This method swaps the buffers */ --(void) swapBuffers; - -- (CGPoint) convertPointFromViewToSurface:(CGPoint)point; -- (CGRect) convertRectFromViewToSurface:(CGRect)rect; -@end - -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED \ No newline at end of file diff --git a/Example/libs/cocos2d/Platforms/iOS/EAGLView.m b/Example/libs/cocos2d/Platforms/iOS/EAGLView.m deleted file mode 100644 index 39dcdb6..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/EAGLView.m +++ /dev/null @@ -1,342 +0,0 @@ -/* - -===== IMPORTANT ===== - -This is sample code demonstrating API, technology or techniques in development. -Although this sample code has been reviewed for technical accuracy, it is not -final. Apple is supplying this information to help you plan for the adoption of -the technologies and programming interfaces described herein. This information -is subject to change, and software implemented based on this sample code should -be tested with final operating system software and final documentation. Newer -versions of this sample code may be provided with future seeds of the API or -technology. For information about updates to this and other developer -documentation, view the New & Updated sidebars in subsequent documentation -seeds. - -===================== - -File: EAGLView.m -Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a -UIView subclass. - -Version: 1.3 - -Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. -("Apple") in consideration of your agreement to the following terms, and your -use, installation, modification or redistribution of this Apple software -constitutes acceptance of these terms. If you do not agree with these terms, -please do not use, install, modify or redistribute this Apple software. - -In consideration of your agreement to abide by the following terms, and subject -to these terms, Apple grants you a personal, non-exclusive license, under -Apple's copyrights in this original Apple software (the "Apple Software"), to -use, reproduce, modify and redistribute the Apple Software, with or without -modifications, in source and/or binary forms; provided that if you redistribute -the Apple Software in its entirety and without modifications, you must retain -this notice and the following text and disclaimers in all such redistributions -of the Apple Software. -Neither the name, trademarks, service marks or logos of Apple Inc. may be used -to endorse or promote products derived from the Apple Software without specific -prior written permission from Apple. Except as expressly stated in this notice, -no other rights or licenses, express or implied, are granted by Apple herein, -including but not limited to any patent rights that may be infringed by your -derivative works or by other works in which the Apple Software may be -incorporated. - -The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN -COMBINATION WITH YOUR PRODUCTS. - -IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR -DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF -CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF -APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright (C) 2008 Apple Inc. All Rights Reserved. - -*/ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - -#import - -#import "EAGLView.h" -#import "ES1Renderer.h" -#import "../../CCDirector.h" -#import "../../ccMacros.h" -#import "../../CCConfiguration.h" -#import "../../Support/OpenGL_Internal.h" - - -//CLASS IMPLEMENTATIONS: - -@interface EAGLView (Private) -- (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup; -- (unsigned int) convertPixelFormat:(NSString*) pixelFormat; -@end - -@implementation EAGLView - -@synthesize surfaceSize=size_; -@synthesize pixelFormat=pixelformat_, depthFormat=depthFormat_; -@synthesize touchDelegate=touchDelegate_; -@synthesize context=context_; -@synthesize multiSampling=multiSampling_; - -+ (Class) layerClass -{ - return [CAEAGLLayer class]; -} - -+ (id) viewWithFrame:(CGRect)frame -{ - return [[[self alloc] initWithFrame:frame] autorelease]; -} - -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format -{ - return [[[self alloc] initWithFrame:frame pixelFormat:format] autorelease]; -} - -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth -{ - return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0] autorelease]; -} - -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples -{ - return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease]; -} - -- (id) initWithFrame:(CGRect)frame -{ - return [self initWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; -} - -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format -{ - return [self initWithFrame:frame pixelFormat:format depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; -} - -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples -{ - if((self = [super initWithFrame:frame])) - { - pixelformat_ = format; - depthFormat_ = depth; - multiSampling_ = sampling; - requestedSamples_ = nSamples; - preserveBackbuffer_ = retained; - - if( ! [self setupSurfaceWithSharegroup:sharegroup] ) { - [self release]; - return nil; - } - } - - return self; -} - --(id) initWithCoder:(NSCoder *)aDecoder -{ - if( (self = [super initWithCoder:aDecoder]) ) { - - CAEAGLLayer* eaglLayer = (CAEAGLLayer*)[self layer]; - - pixelformat_ = kEAGLColorFormatRGB565; - depthFormat_ = 0; // GL_DEPTH_COMPONENT24_OES; - multiSampling_= NO; - requestedSamples_ = 0; - size_ = [eaglLayer bounds].size; - - if( ! [self setupSurfaceWithSharegroup:nil] ) { - [self release]; - return nil; - } - } - - return self; -} - --(BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup -{ - CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; - - eaglLayer.opaque = YES; - eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:preserveBackbuffer_], kEAGLDrawablePropertyRetainedBacking, - pixelformat_, kEAGLDrawablePropertyColorFormat, nil]; - - - renderer_ = [[ES1Renderer alloc] initWithDepthFormat:depthFormat_ - withPixelFormat:[self convertPixelFormat:pixelformat_] - withSharegroup:sharegroup - withMultiSampling:multiSampling_ - withNumberOfSamples:requestedSamples_]; - if (!renderer_) - return NO; - - context_ = [renderer_ context]; - [context_ renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:eaglLayer]; - - discardFramebufferSupported_ = [[CCConfiguration sharedConfiguration] supportsDiscardFramebuffer]; - - return YES; -} - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - - [renderer_ release]; - [super dealloc]; -} - -- (void) layoutSubviews -{ - [renderer_ resizeFromLayer:(CAEAGLLayer*)self.layer]; - size_ = [renderer_ backingSize]; - - // Issue #914 #924 - CCDirector *director = [CCDirector sharedDirector]; - [director reshapeProjection:size_]; - - // Avoid flicker. Issue #350 - [director performSelectorOnMainThread:@selector(drawScene) withObject:nil waitUntilDone:YES]; -} - -- (void) swapBuffers -{ - // IMPORTANT: - // - preconditions - // -> context_ MUST be the OpenGL context - // -> renderbuffer_ must be the the RENDER BUFFER - -#ifdef __IPHONE_4_0 - - if (multiSampling_) - { - /* Resolve from msaaFramebuffer to resolveFramebuffer */ - //glDisable(GL_SCISSOR_TEST); - glBindFramebufferOES(GL_READ_FRAMEBUFFER_APPLE, [renderer_ msaaFrameBuffer]); - glBindFramebufferOES(GL_DRAW_FRAMEBUFFER_APPLE, [renderer_ defaultFrameBuffer]); - glResolveMultisampleFramebufferAPPLE(); - } - - if( discardFramebufferSupported_) - { - if (multiSampling_) - { - if (depthFormat_) - { - GLenum attachments[] = {GL_COLOR_ATTACHMENT0_OES, GL_DEPTH_ATTACHMENT_OES}; - glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, attachments); - } - else - { - GLenum attachments[] = {GL_COLOR_ATTACHMENT0_OES}; - glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 1, attachments); - } - - glBindRenderbufferOES(GL_RENDERBUFFER_OES, [renderer_ colorRenderBuffer]); - - } - - // not MSAA - else if (depthFormat_ ) { - GLenum attachments[] = { GL_DEPTH_ATTACHMENT_OES}; - glDiscardFramebufferEXT(GL_FRAMEBUFFER_OES, 1, attachments); - } - } - -#endif // __IPHONE_4_0 - - if(![context_ presentRenderbuffer:GL_RENDERBUFFER_OES]) - CCLOG(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__); - -#if COCOS2D_DEBUG - CHECK_GL_ERROR(); -#endif - - // We can safely re-bind the framebuffer here, since this will be the - // 1st instruction of the new main loop - if( multiSampling_ ) - glBindFramebufferOES(GL_FRAMEBUFFER_OES, [renderer_ msaaFrameBuffer]); -} - -- (unsigned int) convertPixelFormat:(NSString*) pixelFormat -{ - // define the pixel format - GLenum pFormat; - - - if([pixelFormat isEqualToString:@"EAGLColorFormat565"]) - pFormat = GL_RGB565_OES; - else - pFormat = GL_RGBA8_OES; - - return pFormat; -} - -#pragma mark EAGLView - Point conversion - -- (CGPoint) convertPointFromViewToSurface:(CGPoint)point -{ - CGRect bounds = [self bounds]; - - return CGPointMake((point.x - bounds.origin.x) / bounds.size.width * size_.width, (point.y - bounds.origin.y) / bounds.size.height * size_.height); -} - -- (CGRect) convertRectFromViewToSurface:(CGRect)rect -{ - CGRect bounds = [self bounds]; - - return CGRectMake((rect.origin.x - bounds.origin.x) / bounds.size.width * size_.width, (rect.origin.y - bounds.origin.y) / bounds.size.height * size_.height, rect.size.width / bounds.size.width * size_.width, rect.size.height / bounds.size.height * size_.height); -} - -// Pass the touches to the superview -#pragma mark EAGLView - Touch Delegate - -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event -{ - if(touchDelegate_) - { - [touchDelegate_ touchesBegan:touches withEvent:event]; - } -} - -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event -{ - if(touchDelegate_) - { - [touchDelegate_ touchesMoved:touches withEvent:event]; - } -} - -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event -{ - if(touchDelegate_) - { - [touchDelegate_ touchesEnded:touches withEvent:event]; - } -} -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event -{ - if(touchDelegate_) - { - [touchDelegate_ touchesCancelled:touches withEvent:event]; - } -} - -@end - -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED \ No newline at end of file diff --git a/Example/libs/cocos2d/Platforms/iOS/ES1Renderer.h b/Example/libs/cocos2d/Platforms/iOS/ES1Renderer.h deleted file mode 100644 index d5ce292..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/ES1Renderer.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * File autogenerated with Xcode. Adapted for cocos2d needs. - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - - -#import "ESRenderer.h" - -#import -#import - -@interface ES1Renderer : NSObject -{ - // The pixel dimensions of the CAEAGLLayer - GLint backingWidth_; - GLint backingHeight_; - - unsigned int samplesToUse_; - BOOL multiSampling_; - - unsigned int depthFormat_; - unsigned int pixelFormat_; - - // The OpenGL ES names for the framebuffer and renderbuffer used to render to this view - GLuint defaultFramebuffer_; - GLuint colorRenderbuffer_; - GLuint depthBuffer_; - - - //buffers for MSAA - GLuint msaaFramebuffer_; - GLuint msaaColorbuffer_; - - EAGLContext *context_; -} - -/** EAGLContext */ -@property (nonatomic,readonly) EAGLContext* context; - -- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer; - -@end - -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED diff --git a/Example/libs/cocos2d/Platforms/iOS/ES1Renderer.m b/Example/libs/cocos2d/Platforms/iOS/ES1Renderer.m deleted file mode 100644 index 73a5814..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/ES1Renderer.m +++ /dev/null @@ -1,252 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * File autogenerated with Xcode. Adapted for cocos2d needs. - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - -#import "ES1Renderer.h" -#import "../../Support/OpenGL_Internal.h" -#import "../../ccMacros.h" - - -@interface ES1Renderer (private) - -- (GLenum) convertPixelFormat:(int) pixelFormat; - -@end - - -@implementation ES1Renderer - -@synthesize context=context_; - -- (id) initWithDepthFormat:(unsigned int)depthFormat withPixelFormat:(unsigned int)pixelFormat withSharegroup:(EAGLSharegroup*)sharegroup withMultiSampling:(BOOL) multiSampling withNumberOfSamples:(unsigned int) requestedSamples -{ - if ((self = [super init])) - { - if ( sharegroup == nil ) - { - context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1]; - } - else - { - context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:sharegroup]; - } - - if (!context_ || ![EAGLContext setCurrentContext:context_]) - { - [self release]; - return nil; - } - - // Create default framebuffer object. The backing will be allocated for the current layer in -resizeFromLayer - glGenFramebuffersOES(1, &defaultFramebuffer_); - NSAssert( defaultFramebuffer_, @"Can't create default frame buffer"); - glGenRenderbuffersOES(1, &colorRenderbuffer_); - NSAssert( colorRenderbuffer_, @"Can't create default render buffer"); - - glBindFramebufferOES(GL_FRAMEBUFFER_OES, defaultFramebuffer_); - glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_); - glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorRenderbuffer_); - - depthFormat_ = depthFormat; - - if( depthFormat_ ) { -// glGenRenderbuffersOES(1, &depthBuffer_); -// glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthBuffer_); -// glRenderbufferStorageOES(GL_RENDERBUFFER_OES, depthFormat_, 100, 100); -// glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBuffer_); - - // default buffer -// glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_); - } - - pixelFormat_ = pixelFormat; - multiSampling_ = multiSampling; - if (multiSampling_) - { - GLint maxSamplesAllowed; - glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamplesAllowed); - samplesToUse_ = MIN(maxSamplesAllowed,requestedSamples); - - /* Create the MSAA framebuffer (offscreen) */ - glGenFramebuffersOES(1, &msaaFramebuffer_); - glBindFramebufferOES(GL_FRAMEBUFFER_OES, msaaFramebuffer_); - - } - - CHECK_GL_ERROR(); - } - - return self; -} - -- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer -{ - // Allocate color buffer backing based on the current layer size - - glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_); - - if (![context_ renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:layer]) - { - CCLOG(@"failed to call context"); - } - - glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth_); - glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight_); - - CCLOG(@"cocos2d: surface size: %dx%d", (int)backingWidth_, (int)backingHeight_); - - if (multiSampling_) - { - /* Create the offscreen MSAA color buffer. - After rendering, the contents of this will be blitted into ColorRenderbuffer */ - - //msaaFrameBuffer needs to be binded - glBindFramebufferOES(GL_FRAMEBUFFER_OES, msaaFramebuffer_); - glGenRenderbuffersOES(1, &msaaColorbuffer_); - glBindRenderbufferOES(GL_RENDERBUFFER_OES, msaaColorbuffer_); - glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER_OES, samplesToUse_,pixelFormat_ , backingWidth_, backingHeight_); - glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, msaaColorbuffer_); - - if (glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) - { - CCLOG(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES)); - return NO; - } - } - - if (depthFormat_) - { - if( ! depthBuffer_ ) - glGenRenderbuffersOES(1, &depthBuffer_); - - glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthBuffer_); - if( multiSampling_ ) - glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER_OES, samplesToUse_, depthFormat_,backingWidth_, backingHeight_); - else - glRenderbufferStorageOES(GL_RENDERBUFFER_OES, depthFormat_, backingWidth_, backingHeight_); - glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBuffer_); - - // bind color buffer - glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_); - } - - glBindFramebufferOES(GL_FRAMEBUFFER_OES, defaultFramebuffer_); - - if (glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) - { - CCLOG(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES)); - return NO; - } - - CHECK_GL_ERROR(); - - return YES; -} - --(CGSize) backingSize -{ - return CGSizeMake( backingWidth_, backingHeight_); -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | size = %ix%i>", [self class], self, backingWidth_, backingHeight_]; -} - - -- (void)dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - // Tear down GL - if(defaultFramebuffer_) - { - glDeleteFramebuffersOES(1, &defaultFramebuffer_); - defaultFramebuffer_ = 0; - } - - if(colorRenderbuffer_) - { - glDeleteRenderbuffersOES(1, &colorRenderbuffer_); - colorRenderbuffer_ = 0; - } - - if( depthBuffer_ ) - { - glDeleteRenderbuffersOES(1, &depthBuffer_); - depthBuffer_ = 0; - } - - if ( msaaColorbuffer_) - { - glDeleteRenderbuffersOES(1, &msaaColorbuffer_); - msaaColorbuffer_ = 0; - } - - if ( msaaFramebuffer_) - { - glDeleteRenderbuffersOES(1, &msaaFramebuffer_); - msaaFramebuffer_ = 0; - } - - // Tear down context - if ([EAGLContext currentContext] == context_) - [EAGLContext setCurrentContext:nil]; - - [context_ release]; - context_ = nil; - - [super dealloc]; -} - -- (unsigned int) colorRenderBuffer -{ - return colorRenderbuffer_; -} - -- (unsigned int) defaultFrameBuffer -{ - return defaultFramebuffer_; -} - -- (unsigned int) msaaFrameBuffer -{ - return msaaFramebuffer_; -} - -- (unsigned int) msaaColorBuffer -{ - return msaaColorbuffer_; -} - -@end - -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED diff --git a/Example/libs/cocos2d/Platforms/iOS/ESRenderer.h b/Example/libs/cocos2d/Platforms/iOS/ESRenderer.h deleted file mode 100644 index ff54ccb..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/ESRenderer.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * File autogenerated with Xcode. Adapted for cocos2d needs. - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - -#import - -#import -#import - -@protocol ESRenderer - -- (id) initWithDepthFormat:(unsigned int)depthFormat withPixelFormat:(unsigned int)pixelFormat withSharegroup:(EAGLSharegroup*)sharegroup withMultiSampling:(BOOL) multiSampling withNumberOfSamples:(unsigned int) requestedSamples; - -- (BOOL) resizeFromLayer:(CAEAGLLayer *)layer; - -- (EAGLContext*) context; -- (CGSize) backingSize; - -- (unsigned int) colorRenderBuffer; -- (unsigned int) defaultFrameBuffer; -- (unsigned int) msaaFrameBuffer; -- (unsigned int) msaaColorBuffer; -@end - -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED diff --git a/Example/libs/cocos2d/Platforms/iOS/glu.c b/Example/libs/cocos2d/Platforms/iOS/glu.c deleted file mode 100644 index 2e00d5f..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/glu.c +++ /dev/null @@ -1,113 +0,0 @@ -// -// cocos2d (incomplete) GLU implementation -// -// gluLookAt and gluPerspective from: -// http://jet.ro/creations (San Angeles Observation) -// -// - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - -#import -#import -#import "../../Support/OpenGL_Internal.h" -#include "glu.h" - -void gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar) -{ - GLfloat xmin, xmax, ymin, ymax; - - ymax = zNear * (GLfloat)tanf(fovy * (float)M_PI / 360); - ymin = -ymax; - xmin = ymin * aspect; - xmax = ymax * aspect; - - glFrustumf(xmin, xmax, - ymin, ymax, - zNear, zFar); -} - -void gluLookAt(GLfloat eyex, GLfloat eyey, GLfloat eyez, - GLfloat centerx, GLfloat centery, GLfloat centerz, - GLfloat upx, GLfloat upy, GLfloat upz) -{ - GLfloat m[16]; - GLfloat x[3], y[3], z[3]; - GLfloat mag; - - /* Make rotation matrix */ - - /* Z vector */ - z[0] = eyex - centerx; - z[1] = eyey - centery; - z[2] = eyez - centerz; - mag = (float)sqrtf(z[0] * z[0] + z[1] * z[1] + z[2] * z[2]); - if (mag) { - z[0] /= mag; - z[1] /= mag; - z[2] /= mag; - } - - /* Y vector */ - y[0] = upx; - y[1] = upy; - y[2] = upz; - - /* X vector = Y cross Z */ - x[0] = y[1] * z[2] - y[2] * z[1]; - x[1] = -y[0] * z[2] + y[2] * z[0]; - x[2] = y[0] * z[1] - y[1] * z[0]; - - /* Recompute Y = Z cross X */ - y[0] = z[1] * x[2] - z[2] * x[1]; - y[1] = -z[0] * x[2] + z[2] * x[0]; - y[2] = z[0] * x[1] - z[1] * x[0]; - - /* cross product gives area of parallelogram, which is < 1.0 for - * non-perpendicular unit-length vectors; so normalize x, y here - */ - - mag = (float)sqrtf(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]); - if (mag) { - x[0] /= mag; - x[1] /= mag; - x[2] /= mag; - } - - mag = (float)sqrtf(y[0] * y[0] + y[1] * y[1] + y[2] * y[2]); - if (mag) { - y[0] /= mag; - y[1] /= mag; - y[2] /= mag; - } - -#define M(row,col) m[col*4+row] - M(0, 0) = x[0]; - M(0, 1) = x[1]; - M(0, 2) = x[2]; - M(0, 3) = 0.0f; - M(1, 0) = y[0]; - M(1, 1) = y[1]; - M(1, 2) = y[2]; - M(1, 3) = 0.0f; - M(2, 0) = z[0]; - M(2, 1) = z[1]; - M(2, 2) = z[2]; - M(2, 3) = 0.0f; - M(3, 0) = 0.0f; - M(3, 1) = 0.0f; - M(3, 2) = 0.0f; - M(3, 3) = 1.0f; -#undef M - - glMultMatrixf(m); - - - /* Translate Eye to Origin */ - glTranslatef(-eyex, -eyey, -eyez); -} - -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED diff --git a/Example/libs/cocos2d/Platforms/iOS/glu.h b/Example/libs/cocos2d/Platforms/iOS/glu.h deleted file mode 100644 index 86dcac7..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/glu.h +++ /dev/null @@ -1,29 +0,0 @@ -// -// cocos2d GLU implementation -// -// implementation of GLU functions -// -#ifndef __COCOS2D_GLU_H -#define __COCOS2D_GLU_H - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - -#import - -/** - @file - cocos2d OpenGL GLU implementation - */ - -/** OpenGL gluLookAt implementation */ -void gluLookAt(float eyeX, float eyeY, float eyeZ, float lookAtX, float lookAtY, float lookAtZ, float upX, float upY, float upZ); -/** OpenGL gluPerspective implementation */ -void gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar); - -#endif // __IPHONE_OS_VERSION_MAX_ALLOWED - -#endif /* __COCOS2D_GLU_H */ - diff --git a/Example/libs/cocos2d/Support/CCArray.h b/Example/libs/cocos2d/Support/CCArray.h index 77c0863..c8dae99 100644 --- a/Example/libs/cocos2d/Support/CCArray.h +++ b/Example/libs/cocos2d/Support/CCArray.h @@ -1,18 +1,18 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2010 Abstraction Works. http://www.abstractionworks.com - * + * Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,9 +39,9 @@ #define CCARRAY_FOREACH(__array__, __object__) \ if (__array__ && __array__->data->num > 0) \ -for(id *arr = __array__->data->arr, *end = __array__->data->arr + __array__->data->num-1; \ - arr <= end && ((__object__ = *arr) != nil || true); \ - arr++) +for(const CC_ARC_UNSAFE_RETAINED id *__arr__ = __array__->data->arr, *end = __array__->data->arr + __array__->data->num-1; \ + __arr__ <= end && ((__object__ = *__arr__) != nil || true); \ + __arr__++) @interface CCArray : NSObject { @@ -59,22 +59,27 @@ for(id *arr = __array__->data->arr, *end = __array__->data->arr + __array__->dat - (id) initWithNSArray:(NSArray*)otherArray; +// Querying an Array + - (NSUInteger) count; - (NSUInteger) capacity; - (NSUInteger) indexOfObject:(id)object; - (id) objectAtIndex:(NSUInteger)index; -- (id) lastObject; -- (id) randomObject; - (BOOL) containsObject:(id)object; +- (id) randomObject; +- (id) lastObject; +- (NSArray*) getNSArray; + -#pragma mark Adding Objects +// Adding Objects - (void) addObject:(id)object; - (void) addObjectsFromArray:(CCArray*)otherArray; - (void) addObjectsFromNSArray:(NSArray*)otherArray; - (void) insertObject:(id)object atIndex:(NSUInteger)index; -#pragma mark Removing Objects + +// Removing Objects - (void) removeLastObject; - (void) removeObject:(id)object; @@ -84,9 +89,18 @@ for(id *arr = __array__->data->arr, *end = __array__->data->arr + __array__->dat - (void) fastRemoveObject:(id)object; - (void) fastRemoveObjectAtIndex:(NSUInteger)index; + +// Rearranging Content + +- (void) exchangeObject:(id)object1 withObject:(id)object2; +- (void) exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2; +- (void) reverseObjects; +- (void) reduceMemoryFootprint; + +// Sending Messages to Elements + - (void) makeObjectsPerformSelector:(SEL)aSelector; - (void) makeObjectsPerformSelector:(SEL)aSelector withObject:(id)object; -- (NSArray*) getNSArray; @end diff --git a/Example/libs/cocos2d/Support/CCArray.m b/Example/libs/cocos2d/Support/CCArray.m index 7866ccd..5dc38d3 100644 --- a/Example/libs/cocos2d/Support/CCArray.m +++ b/Example/libs/cocos2d/Support/CCArray.m @@ -1,18 +1,18 @@ /* * cocos2d for iPhone: http://www.cocos2d-iphone.org * - * Copyright (c) 2010 Abstraction Works. http://www.abstractionworks.com - * + * Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -81,19 +81,14 @@ - (id) initWithNSArray:(NSArray*)otherArray return self; } - - - (id) initWithCoder:(NSCoder*)coder { self = [self initWithNSArray:[coder decodeObjectForKey:@"nsarray"]]; return self; } -- (void)encodeWithCoder:(NSCoder *)coder -{ - [coder encodeObject:[self getNSArray] forKey:@"nsarray"]; -} +#pragma mark Querying an Array - (NSUInteger) count { @@ -112,13 +107,16 @@ - (NSUInteger) indexOfObject:(id)object - (id) objectAtIndex:(NSUInteger)index { - if( index >= data->num ) - [NSException raise:NSRangeException - format: @"index out of range in objectAtIndex(%d)", data->num ]; - + NSAssert2( index < data->num, @"index out of range in objectAtIndex(%d), index %i", data->num, index ); + return data->arr[index]; } +- (BOOL) containsObject:(id)object +{ + return ccArrayContainsObject(data, object); +} + - (id) lastObject { if( data->num > 0 ) @@ -132,11 +130,12 @@ - (id) randomObject return data->arr[(int)(data->num*CCRANDOM_0_1())]; } -- (BOOL) containsObject:(id)object +- (NSArray*) getNSArray { - return ccArrayContainsObject(data, object); + return [NSArray arrayWithObjects:data->arr count:data->num]; } + #pragma mark Adding Objects - (void) addObject:(id)object @@ -161,16 +160,8 @@ - (void) insertObject:(id)object atIndex:(NSUInteger)index ccArrayInsertObjectAtIndex(data, object, index); } -#pragma mark Removing Objects - -- (void) removeLastObject -{ - if( data->num == 0 ) - [NSException raise:NSRangeException - format: @"no objects added"]; - ccArrayRemoveObjectAtIndex(data, data->num-1); -} +#pragma mark Removing Objects - (void) removeObject:(id)object { @@ -182,26 +173,74 @@ - (void) removeObjectAtIndex:(NSUInteger)index ccArrayRemoveObjectAtIndex(data, index); } +- (void) fastRemoveObject:(id)object +{ + ccArrayFastRemoveObject(data, object); +} + +- (void) fastRemoveObjectAtIndex:(NSUInteger)index +{ + ccArrayFastRemoveObjectAtIndex(data, index); +} + - (void) removeObjectsInArray:(CCArray*)otherArray { ccArrayRemoveArray(data, otherArray->data); } +- (void) removeLastObject +{ + NSAssert( data->num > 0, @"no objects added" ); + + ccArrayRemoveObjectAtIndex(data, data->num-1); +} + - (void) removeAllObjects { ccArrayRemoveAllObjects(data); } -- (void) fastRemoveObjectAtIndex:(NSUInteger)index + +#pragma mark Rearranging Content + +- (void) exchangeObject:(id)object1 withObject:(id)object2 { - ccArrayFastRemoveObjectAtIndex(data, index); + NSUInteger index1 = ccArrayGetIndexOfObject(data, object1); + if(index1 == NSNotFound) return; + NSUInteger index2 = ccArrayGetIndexOfObject(data, object2); + if(index2 == NSNotFound) return; + + ccArraySwapObjectsAtIndexes(data, index1, index2); } -- (void) fastRemoveObject:(id)object +- (void) exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 { - ccArrayFastRemoveObject(data, object); + ccArraySwapObjectsAtIndexes(data, index1, index2); } +- (void) reverseObjects +{ + if (data->num > 1) + { + //floor it since in case of a oneven number the number of swaps stays the same + int count = (int) floorf(data->num/2.f); + NSUInteger maxIndex = data->num - 1; + + for (int i = 0; i < count ; i++) + { + ccArraySwapObjectsAtIndexes(data, i, maxIndex); + maxIndex--; + } + } +} + +- (void) reduceMemoryFootprint +{ + ccArrayShrink(data); +} + +#pragma mark Sending Messages to Elements + - (void) makeObjectsPerformSelector:(SEL)aSelector { ccArrayMakeObjectsPerformSelector(data, aSelector); @@ -212,34 +251,54 @@ - (void) makeObjectsPerformSelector:(SEL)aSelector withObject:(id)object ccArrayMakeObjectsPerformSelectorWithObject(data, aSelector, object); } -- (NSArray*) getNSArray -{ - return [NSArray arrayWithObjects:data->arr count:data->num]; -} + +#pragma mark CCArray - NSFastEnumeration protocol - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len { if(state->state == 1) return 0; - + state->mutationsPtr = (unsigned long *)self; state->itemsPtr = &data->arr[0]; state->state = 1; return data->num; } + +#pragma mark CCArray - NSCopying protocol + +- (id)copyWithZone:(NSZone *)zone +{ + return [(CCArray*)[[self class] allocWithZone:zone] initWithArray:self]; +} + +- (void) encodeWithCoder:(NSCoder *)coder +{ + [coder encodeObject:[self getNSArray] forKey:@"nsarray"]; +} + +#pragma mark + - (void) dealloc { + CCLOGINFO(@"cocos2d: deallocing %@", self); + ccArrayFree(data); [super dealloc]; } -#pragma mark CCArray - NSCopying protocol +#pragma mark -- (id)copyWithZone:(NSZone *)zone +- (NSString*) description { - NSArray *nsArray = [self getNSArray]; - CCArray *newArray = [[[self class] allocWithZone:zone] initWithNSArray:nsArray]; - return newArray; + NSMutableString *ret = [NSMutableString stringWithFormat:@"<%@ = %08X> = ( ", [self class], self]; + + for( id obj in self) + [ret appendFormat:@"%@, ",obj]; + + [ret appendString:@")"]; + + return ret; } @end diff --git a/Example/libs/cocos2d/Support/CCFileUtils.h b/Example/libs/cocos2d/Support/CCFileUtils.h index 4cf4218..2589ae9 100644 --- a/Example/libs/cocos2d/Support/CCFileUtils.h +++ b/Example/libs/cocos2d/Support/CCFileUtils.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +26,7 @@ #import - +#import "../ccTypes.h" /** Helper class to handle file operations */ @interface CCFileUtils : NSObject @@ -33,29 +34,99 @@ } /** Returns the fullpath of an filename. - - If this method is when Retina Display is enabled, then the - Retina Display suffix will be appended to the file (See ccConfig.h). - - If the Retina Display image doesn't exist, then it will return the "non-Retina Display" image - + + If in RetinaDisplay mode, and a RetinaDisplay file is found, it will return that path. + If in iPad mode, and an iPad file is found, it will return that path. + + Examples: + + * In iPad mode: "image.png" -> "/full/path/image-ipad.png" (in case the -ipad file exists) + * In RetinaDisplay mode: "image.png" -> "/full/path/image-hd.png" (in case the -hd file exists) + */ +(NSString*) fullPathFromRelativePath:(NSString*) relPath; -@end -/** loads a file into memory. - the caller should release the allocated buffer. - - @returns the size of the allocated buffer + +#ifdef __CC_PLATFORM_IOS + +/** Returns the fullpath of an filename including the resolution of the image. + + If in RetinaDisplay mode, and a RetinaDisplay file is found, it will return that path. + If in iPad mode, and an iPad file is found, it will return that path. + + Examples: + + * In iPad mode: "image.png" -> "/full/path/image-ipad.png" (in case the -ipad file exists) + * In RetinaDisplay mode: "image.png" -> "/full/path/image-hd.png" (in case the -hd file exists) + + If an iPad file is found, it will set resolution type to kCCResolutioniPad + If a RetinaDisplay file is found, it will set resolution type to kCCResolutionRetinaDisplay + + */ ++(NSString*) fullPathFromRelativePath:(NSString*)relPath resolutionType:(ccResolutionType*)resolutionType; + + +/** removes the suffix from a path + * On RetinaDisplay it will remove the -hd suffix + * On iPad it will remove the -ipad suffix + * On iPhone it will remove the (empty) suffix + Only valid on iOS. Not valid for OS X. + @since v0.99.5 */ -int ccLoadFileIntoMemory(const char *filename, unsigned char **out); ++(NSString *)removeSuffixFromFile:(NSString*) path; + +/** Sets the iPhone RetinaDisplay suffix to load resources. + By default it is "-hd". + Only valid on iOS. Not valid for OS X. + + @since v1.1 + */ ++(void) setiPhoneRetinaDisplaySuffix:(NSString*)suffix; +/** Sets the iPad suffix to load resources. + By default it is "". + Only valid on iOS. Not valid for OS X. -/** removes the HD suffix from a path + @since v1.1 + */ ++(void) setiPadSuffix:(NSString*)suffix; + +/** Sets the iPad Retina Display suffix to load resources. + By default it is "-ipadhd". + Only valid on iOS. Not valid for OS X. - @returns NSString * without the HD suffix + @since v1.1 + */ ++(void) setiPadRetinaDisplaySuffix:(NSString*)suffix; + +/** Returns whether or not a given filename exists with the iPad suffix. + Only available on iOS. Not supported on OS X. + @since v1.1 + */ ++(BOOL) iPadFileExistsAtPath:(NSString*)filename; + +/** Returns whether or not a given filename exists with the iPad RetinaDisplay suffix. + Only available on iOS. Not supported on OS X. + @since v2.0 + */ ++(BOOL) iPadFileExistsAtPath:(NSString*)filename; + +/** Returns whether or not a given path exists with the iPhone RetinaDisplay suffix. + Only available on iOS. Not supported on OS X. + @since v1.1 + */ ++(BOOL) iPhoneRetinaDisplayFileExistsAtPath:(NSString*)filename; + +#endif // __CC_PLATFORM_IOS + +@end + +/** loads a file into memory. + the caller should release the allocated buffer. + + @returns the size of the allocated buffer @since v0.99.5 */ -NSString *ccRemoveHDSuffixFromFile( NSString *path ); +NSInteger ccLoadFileIntoMemory(const char *filename, unsigned char **out); diff --git a/Example/libs/cocos2d/Support/CCFileUtils.m b/Example/libs/cocos2d/Support/CCFileUtils.m index d728ee3..8493dcd 100644 --- a/Example/libs/cocos2d/Support/CCFileUtils.m +++ b/Example/libs/cocos2d/Support/CCFileUtils.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,145 +25,295 @@ */ -#import #import "CCFileUtils.h" #import "../CCConfiguration.h" #import "../ccMacros.h" #import "../ccConfig.h" +#import "../ccTypes.h" static NSFileManager *__localFileManager=nil; -// -int ccLoadFileIntoMemory(const char *filename, unsigned char **out) -{ - assert( out ); - assert( &*out ); +#ifdef __CC_PLATFORM_IOS + +static NSString *__suffixiPhoneRetinaDisplay =@"-hd"; +static NSString *__suffixiPad =@"-ipad"; +static NSString *__suffixiPadRetinaDisplay =@"-ipadhd"; + +#endif // __CC_PLATFORM_IOS + + +NSString *ccRemoveSuffixFromPath( NSString *suffix, NSString *path); + +// +NSInteger ccLoadFileIntoMemory(const char *filename, unsigned char **out) +{ + NSCAssert( out, @"ccLoadFileIntoMemory: invalid 'out' parameter"); + NSCAssert( &*out, @"ccLoadFileIntoMemory: invalid 'out' parameter"); - int size = 0; + size_t size = 0; FILE *f = fopen(filename, "rb"); - if( !f ) { + if( !f ) { *out = NULL; return -1; - } - + } + fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); - + *out = malloc(size); - int read = fread(*out, 1, size, f); - if( read != size ) { + size_t read = fread(*out, 1, size, f); + if( read != size ) { free(*out); *out = NULL; return -1; } - + fclose(f); - + return size; } -NSString *ccRemoveHDSuffixFromFile( NSString *path ) + +#ifdef __CC_PLATFORM_IOS +@interface CCFileUtils() ++(NSString *) removeSuffix:(NSString*)suffix fromPath:(NSString*)path; ++(BOOL) fileExistsAtPath:(NSString*)string withSuffix:(NSString*)suffix; +@end +#endif // __CC_PLATFORM_IOS + +@implementation CCFileUtils + ++(void) initialize { -#if CC_IS_RETINA_DISPLAY_SUPPORTED - - if( CC_CONTENT_SCALE_FACTOR() == 2 ) { - - NSString *name = [path lastPathComponent]; - - // check if path already has the suffix. - if( [name rangeOfString:CC_RETINA_DISPLAY_FILENAME_SUFFIX].location != NSNotFound ) { - - CCLOG(@"cocos2d: Filename(%@) contains %@ suffix. Removing it. See cocos2d issue #1040", path, CC_RETINA_DISPLAY_FILENAME_SUFFIX); + if( self == [CCFileUtils class] ) + __localFileManager = [[NSFileManager alloc] init]; +} - NSString *newLastname = [name stringByReplacingOccurrencesOfString:CC_RETINA_DISPLAY_FILENAME_SUFFIX withString:@""]; - - NSString *pathWithoutLastname = [path stringByDeletingLastPathComponent]; - return [pathWithoutLastname stringByAppendingPathComponent:newLastname]; - } ++(NSString*) getPath:(NSString*)path forSuffix:(NSString*)suffix +{ + // quick return + if( ! suffix || [suffix length] == 0 ) + return path; + + NSString *pathWithoutExtension = [path stringByDeletingPathExtension]; + NSString *name = [pathWithoutExtension lastPathComponent]; + + // check if path already has the suffix. + if( [name rangeOfString:suffix].location != NSNotFound ) { + + CCLOG(@"cocos2d: WARNING Filename(%@) already has the suffix %@. Using it.", name, suffix); + return path; } -#endif // CC_IS_RETINA_DISPLAY_SUPPORTED - return path; + NSString *extension = [path pathExtension]; -} + if( [extension isEqualToString:@"ccz"] || [extension isEqualToString:@"gz"] ) + { + // All ccz / gz files should be in the format filename.xxx.ccz + // so we need to pull off the .xxx part of the extension as well + extension = [NSString stringWithFormat:@"%@.%@", [pathWithoutExtension pathExtension], extension]; + pathWithoutExtension = [pathWithoutExtension stringByDeletingPathExtension]; + } -@implementation CCFileUtils + NSString *newName = [pathWithoutExtension stringByAppendingString:suffix]; + newName = [newName stringByAppendingPathExtension:extension]; -+(void) initialize -{ - if( self == [CCFileUtils class] ) - __localFileManager = [[NSFileManager alloc] init]; + if( [__localFileManager fileExistsAtPath:newName] ) + return newName; + + CCLOG(@"cocos2d: CCFileUtils: Warning file not found: %@", [newName lastPathComponent] ); + + return nil; } -+(NSString*) getDoubleResolutionImage:(NSString*)path ++(NSString*) fullPathFromRelativePath:(NSString*)relPath resolutionType:(ccResolutionType*)resolutionType { -#if CC_IS_RETINA_DISPLAY_SUPPORTED + NSAssert(relPath != nil, @"CCFileUtils: Invalid path"); + + NSString *fullpath = nil; + + // only if it is not an absolute path + if( ! [relPath isAbsolutePath] ) { + + // pathForResource also searches in .lproj directories. issue #1230 + NSString *file = [relPath lastPathComponent]; + NSString *imageDirectory = [relPath stringByDeletingLastPathComponent]; - if( CC_CONTENT_SCALE_FACTOR() == 2 ) + fullpath = [[NSBundle mainBundle] pathForResource:file + ofType:nil + inDirectory:imageDirectory]; + + + } + + if (fullpath == nil) + fullpath = relPath; + +#ifdef __CC_PLATFORM_IOS + + NSString *ret = nil; + + // iPad? + if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { - - NSString *pathWithoutExtension = [path stringByDeletingPathExtension]; - NSString *name = [pathWithoutExtension lastPathComponent]; - - // check if path already has the suffix. - if( [name rangeOfString:CC_RETINA_DISPLAY_FILENAME_SUFFIX].location != NSNotFound ) { - - CCLOG(@"cocos2d: WARNING Filename(%@) already has the suffix %@. Using it.", name, CC_RETINA_DISPLAY_FILENAME_SUFFIX); - return path; + // Retina Display ? + if( CC_CONTENT_SCALE_FACTOR() == 2 ) { + ret = [self getPath:fullpath forSuffix:__suffixiPadRetinaDisplay]; + *resolutionType = kCCResolutioniPadRetinaDisplay; } - - - NSString *extension = [path pathExtension]; - - if( [extension isEqualToString:@"ccz"] || [extension isEqualToString:@"gz"] ) + else { - // All ccz / gz files should be in the format filename.xxx.ccz - // so we need to pull off the .xxx part of the extension as well - extension = [NSString stringWithFormat:@"%@.%@", [pathWithoutExtension pathExtension], extension]; - pathWithoutExtension = [pathWithoutExtension stringByDeletingPathExtension]; + ret = [self getPath:fullpath forSuffix:__suffixiPad]; + *resolutionType = kCCResolutioniPad; + + } + } + // iPhone ? + else + { + // Retina Display ? + if( CC_CONTENT_SCALE_FACTOR() == 2 ) { + ret = [self getPath:fullpath forSuffix:__suffixiPhoneRetinaDisplay]; + *resolutionType = kCCResolutioniPhoneRetinaDisplay; } - - - NSString *retinaName = [pathWithoutExtension stringByAppendingString:CC_RETINA_DISPLAY_FILENAME_SUFFIX]; - retinaName = [retinaName stringByAppendingPathExtension:extension]; + } + + // If it is iPhone Non RetinaDisplay, or if the previous "getPath" failed, then use iPhone images. + if( ret == nil ) + { + *resolutionType = kCCResolutioniPhone; + ret = fullpath; + } + + return ret; + +#elif defined(__CC_PLATFORM_MAC) + + *resolutionType = kCCResolutioniPhone; + + return fullpath; + +#endif // __CC_PLATFORM_MAC + +} + ++(NSString*) fullPathFromRelativePath:(NSString*) relPath +{ + ccResolutionType ignore; + return [self fullPathFromRelativePath:relPath resolutionType:&ignore]; +} + +#pragma mark CCFileUtils - Suffix (iOS only) + - if( [__localFileManager fileExistsAtPath:retinaName] ) - return retinaName; +#ifdef __CC_PLATFORM_IOS - CCLOG(@"cocos2d: CCFileUtils: Warning HD file not found: %@", [retinaName lastPathComponent] ); ++(NSString *) removeSuffix:(NSString*)suffix fromPath:(NSString*)path +{ + // quick return + if( ! suffix || [suffix length] == 0 ) + return path; + + NSString *name = [path lastPathComponent]; + + // check if path already has the suffix. + if( [name rangeOfString:suffix].location != NSNotFound ) { + + CCLOGINFO(@"cocos2d: Filename(%@) contains %@ suffix. Removing it. See cocos2d issue #1040", path, suffix); + + NSString *newLastname = [name stringByReplacingOccurrencesOfString:suffix withString:@""]; + + NSString *pathWithoutLastname = [path stringByDeletingLastPathComponent]; + return [pathWithoutLastname stringByAppendingPathComponent:newLastname]; } - -#endif // CC_IS_RETINA_DISPLAY_SUPPORTED - + return path; } -+(NSString*) fullPathFromRelativePath:(NSString*) relPath ++(NSString*) removeSuffixFromFile:(NSString*) path { - NSAssert(relPath != nil, @"CCFileUtils: Invalid path"); + NSString *ret = nil; - NSString *fullpath = nil; + if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) + { + if( CC_CONTENT_SCALE_FACTOR() == 2 ) + ret = [self removeSuffix:__suffixiPadRetinaDisplay fromPath:path]; + else + ret = [self removeSuffix:__suffixiPad fromPath:path]; + } + else + { + if( CC_CONTENT_SCALE_FACTOR() == 2 ) + ret = [self removeSuffix:__suffixiPhoneRetinaDisplay fromPath:path]; + else + ret = path; + } + return ret; +} + ++(void) setiPhoneRetinaDisplaySuffix:(NSString*)suffix +{ + [__suffixiPhoneRetinaDisplay release]; + __suffixiPhoneRetinaDisplay = [suffix copy]; +} + ++(void) setiPadSuffix:(NSString*)suffix +{ + [__suffixiPad release]; + __suffixiPad = [suffix copy]; +} + ++(void) setiPadRetinaDisplaySuffix:(NSString*)suffix +{ + [__suffixiPadRetinaDisplay release]; + __suffixiPadRetinaDisplay = [suffix copy]; +} + ++(BOOL) fileExistsAtPath:(NSString*)relPath withSuffix:(NSString*)suffix +{ + NSString *fullpath = nil; + // only if it is not an absolute path - if( ! [relPath isAbsolutePath] ) - { + if( ! [relPath isAbsolutePath] ) { + // pathForResource also searches in .lproj directories. issue #1230 NSString *file = [relPath lastPathComponent]; NSString *imageDirectory = [relPath stringByDeletingLastPathComponent]; - + fullpath = [[NSBundle mainBundle] pathForResource:file ofType:nil inDirectory:imageDirectory]; + } - + if (fullpath == nil) fullpath = relPath; - - fullpath = [self getDoubleResolutionImage:fullpath]; - - return fullpath; + + NSString *path = [self getPath:fullpath forSuffix:suffix]; + + return ( path != nil ); } ++(BOOL) iPhoneRetinaDisplayFileExistsAtPath:(NSString*)path +{ + return [self fileExistsAtPath:path withSuffix:__suffixiPhoneRetinaDisplay]; +} + ++(BOOL) iPadFileExistsAtPath:(NSString*)path +{ + return [self fileExistsAtPath:path withSuffix:__suffixiPad]; +} + ++(BOOL) iPadRetinaDisplayFileExistsAtPath:(NSString*)path +{ + return [self fileExistsAtPath:path withSuffix:__suffixiPadRetinaDisplay]; +} + + +#endif // __CC_PLATFORM_IOS + + @end diff --git a/Example/libs/cocos2d/Support/CCProfiling.h b/Example/libs/cocos2d/Support/CCProfiling.h index b241fb9..9b645f1 100644 --- a/Example/libs/cocos2d/Support/CCProfiling.h +++ b/Example/libs/cocos2d/Support/CCProfiling.h @@ -2,17 +2,17 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Stuart Carnie - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,25 +29,61 @@ @class CCProfilingTimer; +/** CCProfiler + cocos2d builtin profiler. + + To use it, enable set the CC_ENABLE_PROFILERS=1 in the ccConfig.h file + */ @interface CCProfiler : NSObject { - NSMutableArray* activeTimers; +@public + NSMutableDictionary* activeTimers; } +/** shared instance */ + (CCProfiler*)sharedProfiler; -+ (CCProfilingTimer*)timerWithName:(NSString*)timerName andInstance:(id)instance; -+ (void)releaseTimer:(CCProfilingTimer*)timer; + +/** Creates and adds a new timer */ +- (CCProfilingTimer*) createAndAddTimerWithName:(NSString*)timerName; + +/** releases a timer */ +- (void)releaseTimer:(NSString*)timerName; + +/** releases all timers */ +- (void) releaseAllTimers; + +/** display the timers */ - (void)displayTimers; @end - +/** CCProfilingTimer +Profiling timers used by CCProfiler + */ @interface CCProfilingTimer : NSObject { - NSString* name; - struct timeval startTime; - double averageTime; + +@public + NSString *name; + struct timeval startTime; + double averageTime; + double minTime; + double maxTime; + double totalTime; + NSUInteger numberOfCalls; } +/** resets the timer properties */ +-(void) reset; @end -extern void CCProfilingBeginTimingBlock(CCProfilingTimer* timer); -extern void CCProfilingEndTimingBlock(CCProfilingTimer* timer); +extern void CCProfilingBeginTimingBlock(NSString *timerName); +extern void CCProfilingEndTimingBlock(NSString *timerName); +extern void CCProfilingResetTimingBlock(NSString *timerName); + +/* + * cocos2d profiling categories + * used to enable / disable profilers with granularity + */ + +extern BOOL kCCProfilerCategorySprite; +extern BOOL kCCProfilerCategoryBatchSprite; +extern BOOL kCCProfilerCategoryParticles; diff --git a/Example/libs/cocos2d/Support/CCProfiling.m b/Example/libs/cocos2d/Support/CCProfiling.m index 13c8c81..057f0f5 100644 --- a/Example/libs/cocos2d/Support/CCProfiling.m +++ b/Example/libs/cocos2d/Support/CCProfiling.m @@ -2,17 +2,17 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2010 Stuart Carnie - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,94 +24,163 @@ */ #import "../ccConfig.h" - -#if CC_ENABLE_PROFILERS +#import "../ccMacros.h" #import "CCProfiling.h" +#pragma mark - Profiling Categories + +/* set to NO the categories that you don't want to profile */ +BOOL kCCProfilerCategorySprite = NO; +BOOL kCCProfilerCategoryBatchSprite = NO; +BOOL kCCProfilerCategoryParticles = NO; + + @interface CCProfilingTimer() -- (id)initWithName:(NSString*)timerName andInstance:(id)instance; +- (id)initWithName:(NSString*)timerName; @end + +#pragma mark - CCProfiler + @implementation CCProfiler static CCProfiler* g_sharedProfiler; -+ (CCProfiler*)sharedProfiler { ++ (CCProfiler*)sharedProfiler +{ if (!g_sharedProfiler) g_sharedProfiler = [[CCProfiler alloc] init]; - + return g_sharedProfiler; } -+ (CCProfilingTimer*)timerWithName:(NSString*)timerName andInstance:(id)instance { - CCProfiler* p = [CCProfiler sharedProfiler]; - CCProfilingTimer* t = [[CCProfilingTimer alloc] initWithName:timerName andInstance:instance]; - [p->activeTimers addObject:t]; +- (CCProfilingTimer*) createAndAddTimerWithName:(NSString*)timerName +{ + CCProfilingTimer* t = [[CCProfilingTimer alloc] initWithName:timerName]; + [activeTimers setObject:t forKey:timerName]; [t release]; return t; } -+ (void)releaseTimer:(CCProfilingTimer*)timer { - CCProfiler* p = [CCProfiler sharedProfiler]; - [p->activeTimers removeObject:timer]; +- (void)releaseTimer:(NSString*)timerName +{ + [activeTimers removeObjectForKey:timerName]; } -- (id)init { - if (!(self = [super init])) return nil; - - activeTimers = [[NSMutableArray alloc] init]; - +- (void) releaseAllTimers +{ + [activeTimers removeAllObjects]; +} + +- (id)init +{ + if ((self = [super init])) { + activeTimers = [[NSMutableDictionary alloc] initWithCapacity:10]; + } + return self; } -- (void)dealloc { +- (void)dealloc +{ [activeTimers release]; [super dealloc]; } -- (void)displayTimers { - for (id timer in activeTimers) { +- (void)displayTimers +{ + NSArray *values = [activeTimers allValues]; + for (CCProfilingTimer *timer in values) { printf("%s\n", [[timer description] cStringUsingEncoding:[NSString defaultCStringEncoding]]); } } @end +#pragma mark - CCProfilingTimer + + @implementation CCProfilingTimer -- (id)initWithName:(NSString*)timerName andInstance:(id)instance { - if (!(self = [super init])) return nil; - - name = [[NSString stringWithFormat:@"%@ (0x%.8x)", timerName, instance] retain]; - +- (id)initWithName:(NSString*)timerName +{ + if ((self = [super init])) { + name = [timerName copy]; + numberOfCalls = 0; + averageTime = 0; + totalTime = 0; + minTime = 10000; + maxTime = 0; + gettimeofday(&startTime, NULL); + } + return self; } -- (void)dealloc { +- (void)dealloc +{ + CCLOGINFO(@"deallocing %@", self); [name release]; [super dealloc]; } -- (NSString*)description { - return [NSString stringWithFormat:@"%@ : avg time, %fms", name, averageTime]; +- (NSString*)description +{ + return [NSString stringWithFormat:@"%@ ::\tavg: %fms,\tmin: %fms,\tmax: %fms,\ttotal: %.2fs,\tnr calls: %d", name, averageTime, minTime, maxTime, totalTime / 1000.0, numberOfCalls]; +} + +-(void) reset +{ + numberOfCalls = 0; + averageTime = 0; + totalTime = 0; + minTime = 10000; + maxTime = 0; + gettimeofday(&startTime, NULL); } -void CCProfilingBeginTimingBlock(CCProfilingTimer* timer) { +@end + + +void CCProfilingBeginTimingBlock(NSString *timerName) +{ + CCProfiler* p = [CCProfiler sharedProfiler]; + CCProfilingTimer *timer = [p->activeTimers objectForKey:timerName]; + if( ! timer ) + timer = [p createAndAddTimerWithName:timerName]; + gettimeofday(&timer->startTime, NULL); + + timer->numberOfCalls++; } -typedef unsigned int uint32; -void CCProfilingEndTimingBlock(CCProfilingTimer* timer) { +void CCProfilingEndTimingBlock(NSString *timerName) +{ + CCProfiler* p = [CCProfiler sharedProfiler]; + CCProfilingTimer *timer = [p->activeTimers objectForKey:timerName]; + + NSCAssert1(timer, @"CCProfilingTimer %@ not found", timerName); + struct timeval currentTime; gettimeofday(¤tTime, NULL); timersub(¤tTime, &timer->startTime, ¤tTime); double duration = currentTime.tv_sec * 1000.0 + currentTime.tv_usec / 1000.0; - - // return in milliseconds + + // milliseconds timer->averageTime = (timer->averageTime + duration) / 2.0f; + timer->totalTime += duration; + timer->maxTime = MAX( timer->maxTime, duration); + timer->minTime = MIN( timer->minTime, duration); + } -@end +void CCProfilingResetTimingBlock(NSString *timerName) +{ + CCProfiler* p = [CCProfiler sharedProfiler]; + CCProfilingTimer *timer = [p->activeTimers objectForKey:timerName]; -#endif + NSCAssert1(timer, @"CCProfilingTimer %@ not found", timerName); + + [timer reset]; +} diff --git a/Example/libs/cocos2d/Support/CGPointExtension.h b/Example/libs/cocos2d/Support/CGPointExtension.h index 5193d3f..90510c4 100644 --- a/Example/libs/cocos2d/Support/CGPointExtension.h +++ b/Example/libs/cocos2d/Support/CGPointExtension.h @@ -2,18 +2,19 @@ * http://www.cocos2d-iphone.org * * Copyright (c) 2007 Scott Lembcke + * * Copyright (c) 2010 Lam Pham - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -31,23 +32,23 @@ @file CGPoint extensions based on Chipmunk's cpVect file. These extensions work both with CGPoint and cpVect. - + The "ccp" prefix means: "CoCos2d Point" - + Examples: - ccpAdd( ccp(1,1), ccp(2,2) ); // preferred cocos2d way - ccpAdd( CGPointMake(1,1), CGPointMake(2,2) ); // also ok but more verbose - + - cpvadd( cpv(1,1), cpv(2,2) ); // way of the chipmunk - ccpAdd( cpv(1,1), cpv(2,2) ); // mixing chipmunk and cocos2d (avoid) - cpvadd( CGPointMake(1,1), CGPointMake(2,2) ); // mixing chipmunk and CG (avoid) */ -#import +#import "ccMacros.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#elif defined(__CC_PLATFORM_MAC) #import #endif @@ -56,7 +57,7 @@ #ifdef __cplusplus extern "C" { -#endif +#endif /** Helper macro that creates a CGPoint @return CGPoint @@ -195,6 +196,16 @@ ccpLengthSQ(const CGPoint v) return ccpDot(v, v); } +/** Calculates the square distance between two points (not calling sqrt() ) + @return CGFloat + @since v1.1 +*/ +static inline CGFloat +ccpDistanceSQ(const CGPoint p1, const CGPoint p2) +{ + return ccpLengthSQ(ccpSub(p1, p2)); +} + /** Calculates distance between point an origin @return CGFloat @since v0.7.2 @@ -292,30 +303,42 @@ float ccpAngle(CGPoint a, CGPoint b); CGPoint ccpRotateByAngle(CGPoint v, CGPoint pivot, float angle); /** A general line-line intersection test - @param p1 + @param p1 is the startpoint for the first line P1 = (p1 - p2) - @param p2 + @param p2 is the endpoint for the first line P1 = (p1 - p2) - @param p3 + @param p3 is the startpoint for the second line P2 = (p3 - p4) - @param p4 + @param p4 is the endpoint for the second line P2 = (p3 - p4) - @param s + @param s is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1)) @param t is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3)) - @return bool + @return bool indicating successful intersection of a line - note that to truly test intersection for segments we have to make + note that to truly test intersection for segments we have to make sure that s & t lie within [0..1] and for rays, make sure s & t > 0 the hit point is p3 + t * (p4 - p3); the hit point also is p1 + s * (p2 - p1); @since v0.99.1 */ -BOOL ccpLineIntersect(CGPoint p1, CGPoint p2, +BOOL ccpLineIntersect(CGPoint p1, CGPoint p2, CGPoint p3, CGPoint p4, float *s, float *t); +/* + ccpSegmentIntersect returns YES if Segment A-B intersects with segment C-D + @since v1.0.0 + */ +BOOL ccpSegmentIntersect(CGPoint A, CGPoint B, CGPoint C, CGPoint D); + +/* + ccpIntersectPoint returns the intersection point of line A-B, C-D + @since v1.0.0 + */ +CGPoint ccpIntersectPoint(CGPoint A, CGPoint B, CGPoint C, CGPoint D); + #ifdef __cplusplus } #endif diff --git a/Example/libs/cocos2d/Support/CGPointExtension.m b/Example/libs/cocos2d/Support/CGPointExtension.m index 04fff86..8343a3f 100644 --- a/Example/libs/cocos2d/Support/CGPointExtension.m +++ b/Example/libs/cocos2d/Support/CGPointExtension.m @@ -2,6 +2,7 @@ * http://www.cocos2d-iphone.org * * Copyright (c) 2007 Scott Lembcke + * * Copyright (c) 2010 Lam Pham * * Permission is hereby granted, free of charge, to any person obtaining a copy @@ -10,10 +11,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -84,7 +85,8 @@ CGPoint ccpFromSize(CGSize s) return ccp(s.width, s.height); } -CGPoint ccpCompOp(CGPoint p, float (*opFunc)(float)){ +CGPoint ccpCompOp(CGPoint p, float (*opFunc)(float)) +{ return ccp(opFunc(p.x), opFunc(p.y)); } @@ -103,59 +105,87 @@ CGPoint ccpCompMult(CGPoint a, CGPoint b) float ccpAngleSigned(CGPoint a, CGPoint b) { - CGPoint a2 = ccpNormalize(a); CGPoint b2 = ccpNormalize(b); + CGPoint a2 = ccpNormalize(a); + CGPoint b2 = ccpNormalize(b); float angle = atan2f(a2.x * b2.y - a2.y * b2.x, ccpDot(a2, b2)); if( fabs(angle) < kCGPointEpsilon ) return 0.f; return angle; } -CGPoint ccpRotateByAngle(CGPoint v, CGPoint pivot, float angle) { +CGPoint ccpRotateByAngle(CGPoint v, CGPoint pivot, float angle) +{ CGPoint r = ccpSub(v, pivot); - float t = r.x; float cosa = cosf(angle), sina = sinf(angle); - r.x = t*cosa - r.y*sina; - r.y = t*sina + r.y*cosa; - r = ccpAdd(r, pivot); + float t = r.x; + r.x = t*cosa - r.y*sina + pivot.x; + r.y = t*sina + r.y*cosa + pivot.y; return r; } -BOOL ccpLineIntersect(CGPoint p1, CGPoint p2, - CGPoint p3, CGPoint p4, - float *s, float *t){ - CGPoint p13, p43, p21; - float d1343, d4321, d1321, d4343, d2121; - float numer, denom; - - p13 = ccpSub(p1, p3); - - p43 = ccpSub(p4, p3); - - //Roughly equal to zero but with an epsilon deviation for float - //correction - if (ccpFuzzyEqual(p43, CGPointZero, kCGPointEpsilon)) - return false; - - p21 = ccpSub(p2, p1); - - //Roughly equal to zero - if (ccpFuzzyEqual(p21,CGPointZero, kCGPointEpsilon)) - return false; - - d1343 = ccpDot(p13, p43); - d4321 = ccpDot(p43, p21); - d1321 = ccpDot(p13, p21); - d4343 = ccpDot(p43, p43); - d2121 = ccpDot(p21, p21); - - denom = d2121 * d4343 - d4321 * d4321; - if (fabs(denom) < kCGPointEpsilon) - return false; - numer = d1343 * d4321 - d1321 * d4343; - - *s = numer / denom; - *t = (d1343 + d4321 *(*s)) / d4343; - - return true; + +BOOL ccpSegmentIntersect(CGPoint A, CGPoint B, CGPoint C, CGPoint D) +{ + float S, T; + + if( ccpLineIntersect(A, B, C, D, &S, &T ) + && (S >= 0.0f && S <= 1.0f && T >= 0.0f && T <= 1.0f) ) + return YES; + + return NO; +} + +CGPoint ccpIntersectPoint(CGPoint A, CGPoint B, CGPoint C, CGPoint D) +{ + float S, T; + + if( ccpLineIntersect(A, B, C, D, &S, &T) ) { + // Point of intersection + CGPoint P; + P.x = A.x + S * (B.x - A.x); + P.y = A.y + S * (B.y - A.y); + return P; + } + + return CGPointZero; +} + +BOOL ccpLineIntersect(CGPoint A, CGPoint B, + CGPoint C, CGPoint D, + float *S, float *T) +{ + // FAIL: Line undefined + if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) ) return NO; + + const float BAx = B.x - A.x; + const float BAy = B.y - A.y; + const float DCx = D.x - C.x; + const float DCy = D.y - C.y; + const float ACx = A.x - C.x; + const float ACy = A.y - C.y; + + const float denom = DCy*BAx - DCx*BAy; + + *S = DCx*ACy - DCy*ACx; + *T = BAx*ACy - BAy*ACx; + + if (denom == 0) { + if (*S == 0 || *T == 0) { + // Lines incident + return YES; + } + // Lines parallel and not incident + return NO; + } + + *S = *S / denom; + *T = *T / denom; + + // Point of intersection + // CGPoint P; + // P.x = A.x + *S * (B.x - A.x); + // P.y = A.y + *S * (B.y - A.y); + + return YES; } float ccpAngle(CGPoint a, CGPoint b) @@ -164,4 +194,3 @@ float ccpAngle(CGPoint a, CGPoint b) if( fabs(angle) < kCGPointEpsilon ) return 0.f; return angle; } - diff --git a/Example/libs/cocos2d/Support/OpenGL_Internal.h b/Example/libs/cocos2d/Support/OpenGL_Internal.h index 4789683..82dc473 100644 --- a/Example/libs/cocos2d/Support/OpenGL_Internal.h +++ b/Example/libs/cocos2d/Support/OpenGL_Internal.h @@ -67,7 +67,13 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. /* EAGL and GL functions calling wrappers that log on error */ #define CALL_EAGL_FUNCTION(__FUNC__, ...) ({ EAGLError __error = __FUNC__( __VA_ARGS__ ); if(__error != kEAGLErrorSuccess) printf("%s() called from %s returned error %i\n", #__FUNC__, __FUNCTION__, __error); (__error ? NO : YES); }) //#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) printf("OpenGL error 0x%04X in %s\n", __error, __FUNCTION__); (__error ? NO : YES); }) -#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) printf("OpenGL error 0x%04X in %s\n", __error, __FUNCTION__); }) +#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) printf("OpenGL error 0x%04X in %s %d\n", __error, __FUNCTION__, __LINE__); }) + +#if DEBUG +#define CHECK_GL_ERROR_DEBUG() ({ GLenum __error = glGetError(); if(__error) printf("OpenGL error 0x%04X in %s %d\n", __error, __FUNCTION__, __LINE__); }) +#else +#define CHECK_GL_ERROR_DEBUG() +#endif /* Optional delegate methods support */ #ifndef __DELEGATE_IVAR__ diff --git a/Example/libs/cocos2d/Support/TGAlib.h b/Example/libs/cocos2d/Support/TGAlib.h index 247084e..c52a2a5 100644 --- a/Example/libs/cocos2d/Support/TGAlib.h +++ b/Example/libs/cocos2d/Support/TGAlib.h @@ -25,13 +25,13 @@ enum { typedef struct sImageTGA { int status; unsigned char type, pixelDepth; - + /** map width */ short int width; - + /** map height */ short int height; - + /** raw data */ unsigned char *imageData; int flipped; diff --git a/Example/libs/cocos2d/Support/TGAlib.m b/Example/libs/cocos2d/Support/TGAlib.m index b574d59..c2766d4 100644 --- a/Example/libs/cocos2d/Support/TGAlib.m +++ b/Example/libs/cocos2d/Support/TGAlib.m @@ -11,6 +11,8 @@ #import "TGAlib.h" +void tgaLoadRLEImageData(FILE *file, tImageTGA *info); +void tgaFlipImage( tImageTGA *info ); // load the image header fields. We only keep those that matter! void tgaLoadHeader(FILE *file, tImageTGA *info) { @@ -34,24 +36,24 @@ void tgaLoadHeader(FILE *file, tImageTGA *info) { fread(&info->pixelDepth, sizeof(unsigned char), 1, file); fread(&cGarbage, sizeof(unsigned char), 1, file); - + info->flipped = 0; if ( cGarbage & 0x20 ) info->flipped = 1; } // loads the image pixels. You shouldn't call this function directly void tgaLoadImageData(FILE *file, tImageTGA *info) { - + int mode,total,i; unsigned char aux; - + // mode equal the number of components for each pixel mode = info->pixelDepth / 8; // total is the number of unsigned chars we'll have to read total = info->height * info->width * mode; - + fread(info->imageData,sizeof(unsigned char),total,file); - + // mode=3 or 4 implies that the image is RGB(A). However TGA // stores it as BGR(A) so we'll have to swap R and B. if (mode >= 3) @@ -68,12 +70,12 @@ void tgaLoadRLEImageData(FILE *file, tImageTGA *info) unsigned int mode,total,i, index = 0; unsigned char aux[4], runlength = 0; unsigned int skip = 0, flag = 0; - + // mode equal the number of components for each pixel mode = info->pixelDepth / 8; // total is the number of unsigned chars we'll have to read total = info->height * info->width; - + for( i = 0; i < total; i++ ) { // if we have a run length pending, run it @@ -88,32 +90,32 @@ void tgaLoadRLEImageData(FILE *file, tImageTGA *info) // otherwise, read in the run length token if ( fread(&runlength,sizeof(unsigned char),1,file) != 1 ) return; - + // see if it's a RLE encoded sequence flag = runlength & 0x80; if ( flag ) runlength -= 128; skip = 0; } - + // do we need to skip reading this pixel? if ( !skip ) { // no, read in the pixel data if ( fread(aux,sizeof(unsigned char),mode,file) != mode ) return; - + // mode=3 or 4 implies that the image is RGB(A). However TGA // stores it as BGR(A) so we'll have to swap R and B. if ( mode >= 3 ) { unsigned char tmp; - + tmp = aux[0]; aux[0] = aux[2]; aux[2] = tmp; } } - + // add the pixel to our image memcpy(&info->imageData[index], aux, mode); index += mode; @@ -127,50 +129,50 @@ void tgaFlipImage( tImageTGA *info ) int rowbytes = info->width*mode; unsigned char *row = (unsigned char *)malloc(rowbytes); int y; - + if (row == NULL) return; - + for( y = 0; y < (info->height/2); y++ ) { memcpy(row, &info->imageData[y*rowbytes],rowbytes); memcpy(&info->imageData[y*rowbytes], &info->imageData[(info->height-(y+1))*rowbytes], rowbytes); memcpy(&info->imageData[(info->height-(y+1))*rowbytes], row, rowbytes); } - + free(row); info->flipped = 0; } // this is the function to call when we want to load an image tImageTGA * tgaLoad(const char *filename) { - + FILE *file; tImageTGA *info; int mode,total; - + // allocate memory for the info struct and check! info = (tImageTGA *)malloc(sizeof(tImageTGA)); if (info == NULL) return(NULL); - - + + // open the file for reading (binary mode) file = fopen(filename, "rb"); if (file == NULL) { info->status = TGA_ERROR_FILE_OPEN; return(info); } - + // load the header tgaLoadHeader(file,info); - + // check for errors when loading the header if (ferror(file)) { info->status = TGA_ERROR_READING_FILE; fclose(file); return(info); } - + // check if the image is color indexed if (info->type == 1) { info->status = TGA_ERROR_INDEXED_COLOR; @@ -183,7 +185,7 @@ void tgaFlipImage( tImageTGA *info ) fclose(file); return(info); } - + // mode equals the number of image components mode = info->pixelDepth / 8; // total is the number of unsigned chars to read @@ -191,7 +193,7 @@ void tgaFlipImage( tImageTGA *info ) // allocate memory for image pixels info->imageData = (unsigned char *)malloc(sizeof(unsigned char) * total); - + // check to make sure we have the memory required if (info->imageData == NULL) { info->status = TGA_ERROR_MEMORY; @@ -203,7 +205,7 @@ void tgaFlipImage( tImageTGA *info ) tgaLoadRLEImageData(file, info); else tgaLoadImageData(file,info); - + // check for errors when reading the pixels if (ferror(file)) { info->status = TGA_ERROR_READING_FILE; @@ -212,48 +214,48 @@ void tgaFlipImage( tImageTGA *info ) } fclose(file); info->status = TGA_OK; - + if ( info->flipped ) { tgaFlipImage( info ); if ( info->flipped ) info->status = TGA_ERROR_MEMORY; } - + return(info); } // converts RGB to greyscale void tgaRGBtogreyscale(tImageTGA *info) { - + int mode,i,j; - + unsigned char *newImageData; - + // if the image is already greyscale do nothing if (info->pixelDepth == 8) return; - + // compute the number of actual components mode = info->pixelDepth / 8; - + // allocate an array for the new image data - newImageData = (unsigned char *)malloc(sizeof(unsigned char) * + newImageData = (unsigned char *)malloc(sizeof(unsigned char) * info->height * info->width); if (newImageData == NULL) { return; } - + // convert pixels: greyscale = o.30 * R + 0.59 * G + 0.11 * B for (i = 0,j = 0; j < info->width * info->height; i +=mode, j++) - newImageData[j] = - (unsigned char)(0.30 * info->imageData[i] + + newImageData[j] = + (unsigned char)(0.30 * info->imageData[i] + 0.59 * info->imageData[i+1] + 0.11 * info->imageData[i+2]); - - + + //free old image data free(info->imageData); - + // reassign pixelDepth and type according to the new image type info->pixelDepth = 8; info->type = 3; @@ -263,7 +265,7 @@ void tgaRGBtogreyscale(tImageTGA *info) { // releases the memory used for the image void tgaDestroy(tImageTGA *info) { - + if (info != NULL) { if (info->imageData != NULL) free(info->imageData); diff --git a/Example/libs/cocos2d/Support/TransformUtils.h b/Example/libs/cocos2d/Support/TransformUtils.h index 49fde35..ca5ff27 100644 --- a/Example/libs/cocos2d/Support/TransformUtils.h +++ b/Example/libs/cocos2d/Support/TransformUtils.h @@ -2,17 +2,17 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009 Valentin Milea - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,12 +23,12 @@ * */ -#import +#import "../ccMacros.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import -#import -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#import +#elif defined(__CC_PLATFORM_MAC) #import #import #endif diff --git a/Example/libs/cocos2d/Support/TransformUtils.m b/Example/libs/cocos2d/Support/TransformUtils.m index 9caecf0..73e132f 100644 --- a/Example/libs/cocos2d/Support/TransformUtils.m +++ b/Example/libs/cocos2d/Support/TransformUtils.m @@ -2,17 +2,17 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2009 Valentin Milea - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -32,7 +32,7 @@ void CGAffineToGL(const CGAffineTransform *t, GLfloat *m) // | m[1] m[5] m[9] m[13] | | m12 m22 m32 m42 | | b d 0 ty | // | m[2] m[6] m[10] m[14] | <=> | m13 m23 m33 m43 | <=> | 0 0 1 0 | // | m[3] m[7] m[11] m[15] | | m14 m24 m34 m44 | | 0 0 0 1 | - + m[2] = m[3] = m[6] = m[7] = m[8] = m[9] = m[11] = m[14] = 0.0f; m[10] = m[15] = 1.0f; m[0] = t->a; m[4] = t->c; m[12] = t->tx; @@ -44,3 +44,4 @@ void GLToCGAffine(const GLfloat *m, CGAffineTransform *t) t->a = m[0]; t->c = m[4]; t->tx = m[12]; t->b = m[1]; t->d = m[5]; t->ty = m[13]; } + diff --git a/Example/libs/cocos2d/Support/ZipUtils.h b/Example/libs/cocos2d/Support/ZipUtils.h index 8179e4c..99034a9 100644 --- a/Example/libs/cocos2d/Support/ZipUtils.h +++ b/Example/libs/cocos2d/Support/ZipUtils.h @@ -8,7 +8,7 @@ * * Some ideas were taken from: * http://themanaworld.org/ - * from the mapreader.cpp file + * from the mapreader.cpp file * */ @@ -19,8 +19,8 @@ #ifdef __cplusplus extern "C" { -#endif - +#endif + /* XXX: pragma pack ??? */ /** @struct CCZHeader */ @@ -31,29 +31,42 @@ extern "C" { uint32_t reserved; // Reserverd for users. uint32_t len; // size of the uncompressed file }; - + enum { CCZ_COMPRESSION_ZLIB, // zlib format. CCZ_COMPRESSION_BZIP2, // bzip2 format (not supported yet) CCZ_COMPRESSION_GZIP, // gzip format (not supported yet) CCZ_COMPRESSION_NONE, // plain (not supported yet) }; - + /** @file * Zip helper functions */ -/** +/** * Inflates either zlib or gzip deflated memory. The inflated memory is * expected to be freed by the caller. * + * It will allocate 256k for the destination buffer. If it is not enought it will multiply the previous buffer size per 2, until there is enough memory. * @returns the length of the deflated buffer * @since v0.8.1 */ int ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out); - +/** + * Inflates either zlib or gzip deflated memory. The inflated memory is + * expected to be freed by the caller. + * + * outLenghtHint is assumed to be the needed room to allocate the inflated buffer. + * + * @returns the length of the deflated buffer + * + @since v1.0.0 + */ +int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLenghtHint ); + + /** inflates a GZip file into memory * * @returns the length of the deflated buffer @@ -69,10 +82,10 @@ int ccInflateGZipFile(const char *filename, unsigned char **out); * @since v0.99.5 */ int ccInflateCCZFile(const char *filename, unsigned char **out); - + #ifdef __cplusplus } -#endif - +#endif + #endif // __CC_ZIP_UTILS_H diff --git a/Example/libs/cocos2d/Support/ZipUtils.m b/Example/libs/cocos2d/Support/ZipUtils.m index 198ab4f..d3a2379 100644 --- a/Example/libs/cocos2d/Support/ZipUtils.m +++ b/Example/libs/cocos2d/Support/ZipUtils.m @@ -11,11 +11,9 @@ * * Some ideas were taken from: * http://themanaworld.org/ - * from the mapreader.cpp file + * from the mapreader.cpp file */ -#import - #import #import #import @@ -29,35 +27,34 @@ // Should buffer factor be 1.5 instead of 2 ? #define BUFFER_INC_FACTOR (2) -static int inflateMemory_(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength) +static int inflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, unsigned int outLenghtHint ) { /* ret value */ int err = Z_OK; - - /* 256k initial decompress buffer */ - int bufferSize = 256 * 1024; + + int bufferSize = outLenghtHint; *out = (unsigned char*) malloc(bufferSize); - - z_stream d_stream; /* decompression stream */ + + z_stream d_stream; /* decompression stream */ d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; - + d_stream.next_in = in; d_stream.avail_in = inLength; d_stream.next_out = *out; d_stream.avail_out = bufferSize; - + /* window size to hold 256k */ if( (err = inflateInit2(&d_stream, 15 + 32)) != Z_OK ) return err; - + for (;;) { err = inflate(&d_stream, Z_NO_FLUSH); - + if (err == Z_STREAM_END) break; - + switch (err) { case Z_NEED_DICT: err = Z_DATA_ERROR; @@ -66,12 +63,12 @@ static int inflateMemory_(unsigned char *in, unsigned int inLength, unsigned cha inflateEnd(&d_stream); return err; } - + // not enough memory ? if (err != Z_STREAM_END) { - + unsigned char *tmp = realloc(*out, bufferSize * BUFFER_INC_FACTOR); - + /* not enough memory, ouch */ if (! tmp ) { CCLOG(@"cocos2d: ZipUtils: realloc failed"); @@ -80,24 +77,24 @@ static int inflateMemory_(unsigned char *in, unsigned int inLength, unsigned cha } /* only assign to *out if tmp is valid. it's not guaranteed that realloc will reuse the memory */ *out = tmp; - + d_stream.next_out = *out + bufferSize; d_stream.avail_out = bufferSize; bufferSize *= BUFFER_INC_FACTOR; } } - + *outLength = bufferSize - d_stream.avail_out; err = inflateEnd(&d_stream); return err; } -int ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out) +int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLengthHint ) { unsigned int outLength = 0; - int err = inflateMemory_(in, inLength, out, &outLength); - + int err = inflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint ); + if (err != Z_OK || *out == NULL) { if (err == Z_MEM_ERROR) CCLOG(@"cocos2d: ZipUtils: Out of memory while decompressing map data!"); @@ -110,39 +107,45 @@ int ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **ou else CCLOG(@"cocos2d: ZipUtils: Unknown error while decompressing map data!"); - + free(*out); *out = NULL; outLength = 0; } - + return outLength; } +int ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out) +{ + // 256k for hint + return ccInflateMemoryWithHint(in, inLength, out, 256 * 1024 ); +} + int ccInflateGZipFile(const char *path, unsigned char **out) { int len; unsigned int offset = 0; - - assert( out ); - assert( &*out ); + + NSCAssert( out, @"ccInflateGZipFile: invalid 'out' parameter"); + NSCAssert( &*out, @"ccInflateGZipFile: invalid 'out' parameter"); gzFile inFile = gzopen(path, "rb"); if( inFile == NULL ) { CCLOG(@"cocos2d: ZipUtils: error open gzip file: %s", path); return -1; } - + /* 512k initial decompress buffer */ - unsigned int bufferSize = 512 * 1024; + int bufferSize = 512 * 1024; unsigned int totalBufferSize = bufferSize; - + *out = malloc( bufferSize ); if( ! out ) { CCLOG(@"cocos2d: ZipUtils: out of memory"); return -1; } - + for (;;) { len = gzread(inFile, *out + offset, bufferSize); if (len < 0) { @@ -153,9 +156,9 @@ int ccInflateGZipFile(const char *path, unsigned char **out) } if (len == 0) break; - + offset += len; - + // finish reading the file if( len < bufferSize ) break; @@ -170,10 +173,10 @@ int ccInflateGZipFile(const char *path, unsigned char **out) *out = NULL; return -1; } - + *out = tmp; } - + if (gzclose(inFile) != Z_OK) CCLOG(@"cocos2d: ZipUtils: gzclose failed"); @@ -182,16 +185,17 @@ int ccInflateGZipFile(const char *path, unsigned char **out) int ccInflateCCZFile(const char *path, unsigned char **out) { - assert( out ); - assert( &*out ); + NSCAssert( out, @"ccInflateCCZFile: invalid 'out' parameter"); + NSCAssert( &*out, @"ccInflateCCZFile: invalid 'out' parameter"); // load file into memory unsigned char *compressed = NULL; - int fileLen = ccLoadFileIntoMemory( path, &compressed ); + NSInteger fileLen = ccLoadFileIntoMemory( path, &compressed ); if( fileLen < 0 ) { CCLOG(@"cocos2d: Error loading CCZ compressed file"); + return -1; } - + struct CCZHeader *header = (struct CCZHeader*) compressed; // verify header @@ -200,7 +204,7 @@ int ccInflateCCZFile(const char *path, unsigned char **out) free(compressed); return -1; } - + // verify header version uint16_t version = CFSwapInt16BigToHost( header->version ); if( version > 2 ) { @@ -215,9 +219,9 @@ int ccInflateCCZFile(const char *path, unsigned char **out) free(compressed); return -1; } - + uint32_t len = CFSwapInt32BigToHost( header->len ); - + *out = malloc( len ); if(! *out ) { @@ -225,14 +229,14 @@ int ccInflateCCZFile(const char *path, unsigned char **out) free(compressed); return -1; } - - + + uLongf destlen = len; uLongf source = (uLongf) compressed + sizeof(*header); int ret = uncompress(*out, &destlen, (Bytef*)source, fileLen - sizeof(*header) ); free( compressed ); - + if( ret != Z_OK ) { CCLOG(@"cocos2d: CCZ: Failed to uncompress data"); @@ -240,7 +244,7 @@ int ccInflateCCZFile(const char *path, unsigned char **out) *out = NULL; return -1; } - - + + return len; -} \ No newline at end of file +} diff --git a/Example/libs/cocos2d/Support/base64.c b/Example/libs/cocos2d/Support/base64.c index 7a8f65a..1a7df47 100644 --- a/Example/libs/cocos2d/Support/base64.c +++ b/Example/libs/cocos2d/Support/base64.c @@ -1,14 +1,18 @@ -/* +/* public domain BASE64 code - + modified for cocos2d-iphone: http://www.cocos2d-iphone.org */ #include #include +#include "base64.h" + unsigned char alphabet[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +int _base64Decode( unsigned char *input, unsigned int input_len, unsigned char *output, unsigned int *output_len ); + int _base64Decode( unsigned char *input, unsigned int input_len, unsigned char *output, unsigned int *output_len ) { static char inalphabet[256], decoder[256]; @@ -41,7 +45,7 @@ int _base64Decode( unsigned char *input, unsigned int input_len, unsigned char * bits <<= 6; } } - + if( c == '=' ) { switch (char_count) { case 1: @@ -63,7 +67,7 @@ int _base64Decode( unsigned char *input, unsigned int input_len, unsigned char * errors++; } } - + *output_len = output_idx; return errors; } @@ -71,17 +75,17 @@ int _base64Decode( unsigned char *input, unsigned int input_len, unsigned char * int base64Decode(unsigned char *in, unsigned int inLength, unsigned char **out) { unsigned int outLength = 0; - + //should be enough to store 6-bit buffers in 8-bit buffers *out = malloc( inLength * 3.0f / 4.0f + 1 ); if( *out ) { int ret = _base64Decode(in, inLength, *out, &outLength); - + if (ret > 0 ) { printf("Base64Utils: error decoding"); free(*out); - *out = NULL; + *out = NULL; outLength = 0; } } diff --git a/Example/libs/cocos2d/Support/base64.h b/Example/libs/cocos2d/Support/base64.h index d30878e..095fc98 100644 --- a/Example/libs/cocos2d/Support/base64.h +++ b/Example/libs/cocos2d/Support/base64.h @@ -1,6 +1,6 @@ -/* +/* public domain BASE64 code - + modified for cocos2d-iphone: http://www.cocos2d-iphone.org */ @@ -9,14 +9,14 @@ #ifdef __cplusplus extern "C" { -#endif - +#endif + /** @file base64 helper functions */ -/** +/** * Decodes a 64base encoded memory. The decoded memory is * expected to be freed by the caller. * @@ -28,6 +28,6 @@ int base64Decode(unsigned char *in, unsigned int inLength, unsigned char **out); #ifdef __cplusplus } -#endif +#endif #endif // __CC_BASE64_DECODE_H diff --git a/Example/libs/cocos2d/Support/ccCArray.h b/Example/libs/cocos2d/Support/ccCArray.h index 7e38976..156ba4e 100644 --- a/Example/libs/cocos2d/Support/ccCArray.h +++ b/Example/libs/cocos2d/Support/ccCArray.h @@ -1,15 +1,15 @@ /* Copyright (c) 2007 Scott Lembcke - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -19,17 +19,17 @@ * SOFTWARE. */ -/** +/** @file Based on Chipmunk cpArray. ccArray is a faster alternative to NSMutableArray, it does pretty much the same thing (stores NSObjects and retains/releases them appropriately). It's faster because: - - it uses a plain C interface so it doesn't incur Objective-c messaging overhead + - it uses a plain C interface so it doesn't incur Objective-c messaging overhead - it assumes you know what you're doing, so it doesn't spend time on safety checks (index out of bounds, required capacity etc.) - comparisons are done using pointer equality instead of isEqual - + There are 2 kind of functions: - ccArray functions that manipulates objective-c objects (retain and release are performanced) - ccCArray functions that manipulates values like if they were standard C structures (no retain/release is performed) @@ -43,30 +43,37 @@ #import #import +#import "../ccMacros.h" + #pragma mark - #pragma mark ccArray for Objects -// Easy integration +// Easy integration #define CCARRAYDATA_FOREACH(__array__, __object__) \ __object__=__array__->arr[0]; for(NSUInteger i=0, num=__array__->num; iarr[i]) \ +#if defined(__has_feature) && __has_feature(objc_arc) + typedef __strong id CCARRAY_ID; +#else + typedef id CCARRAY_ID; +#endif typedef struct ccArray { NSUInteger num, max; - id *arr; + CCARRAY_ID *arr; } ccArray; /** Allocates and initializes a new array with specified capacity */ static inline ccArray* ccArrayNew(NSUInteger capacity) { if (capacity == 0) - capacity = 1; - + capacity = 1; + ccArray *arr = (ccArray*)malloc( sizeof(ccArray) ); arr->num = 0; - arr->arr = (id*) malloc( capacity * sizeof(id) ); + arr->arr = (CCARRAY_ID *)calloc(capacity, sizeof(id)); arr->max = capacity; - + return arr; } @@ -76,9 +83,9 @@ static inline void ccArrayRemoveAllObjects(ccArray *arr); static inline void ccArrayFree(ccArray *arr) { if( arr == nil ) return; - + ccArrayRemoveAllObjects(arr); - + free(arr->arr); free(arr); } @@ -87,7 +94,10 @@ static inline void ccArrayFree(ccArray *arr) static inline void ccArrayDoubleCapacity(ccArray *arr) { arr->max *= 2; - arr->arr = (id*) realloc( arr->arr, arr->max * sizeof(id) ); + CCARRAY_ID *newArr = (CCARRAY_ID *)realloc( arr->arr, arr->max * sizeof(id) ); + // will fail when there's not enough memory + NSCAssert(newArr != NULL, @"ccArrayDoubleCapacity failed. Not enough memory"); + arr->arr = newArr; } /** Increases array capacity such that max >= num + extra. */ @@ -97,11 +107,36 @@ static inline void ccArrayEnsureExtraCapacity(ccArray *arr, NSUInteger extra) ccArrayDoubleCapacity(arr); } +/** shrinks the array so the memory footprint corresponds with the number of items */ +static inline void ccArrayShrink(ccArray *arr) +{ + NSUInteger newSize; + + //only resize when necessary + if (arr->max > arr->num && !(arr->num==0 && arr->max==1)) + { + if (arr->num!=0) + { + newSize=arr->num; + arr->max=arr->num; + } + else + {//minimum capacity of 1, with 0 elements the array would be free'd by realloc + newSize=1; + arr->max=1; + } + + arr->arr = (CCARRAY_ID *) realloc(arr->arr,newSize * sizeof(id) ); + NSCAssert(arr->arr!=NULL,@"could not reallocate the memory"); + } +} + /** Returns index of first occurence of object, NSNotFound if object not found. */ static inline NSUInteger ccArrayGetIndexOfObject(ccArray *arr, id object) { for( NSUInteger i = 0; i < arr->num; i++) if( arr->arr[i] == object ) return i; + return NSNotFound; } @@ -114,7 +149,7 @@ static inline BOOL ccArrayContainsObject(ccArray *arr, id object) /** Appends an object. Bahaviour undefined if array doesn't have enough capacity. */ static inline void ccArrayAppendObject(ccArray *arr, id object) { - arr->arr[arr->num] = [object retain]; + arr->arr[arr->num] = CC_ARC_RETAIN(object); arr->num++; } @@ -140,37 +175,50 @@ static inline void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr) ccArrayAppendArray(arr, plusArr); } +/** Inserts an object at index */ static inline void ccArrayInsertObjectAtIndex(ccArray *arr, id object, NSUInteger index) { NSCAssert(index<=arr->num, @"Invalid index. Out of bounds"); - + ccArrayEnsureExtraCapacity(arr, 1); - - int remaining = arr->num - index; + + NSUInteger remaining = arr->num - index; if( remaining > 0) - memmove(&arr->arr[index+1], &arr->arr[index], sizeof(id) * remaining ); - - arr->arr[index] = [object retain]; + memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(id) * remaining ); + + arr->arr[index] = CC_ARC_RETAIN(object); arr->num++; } +/** Swaps two objects */ +static inline void ccArraySwapObjectsAtIndexes(ccArray *arr, NSUInteger index1, NSUInteger index2) +{ + NSCAssert(index1 < arr->num, @"(1) Invalid index. Out of bounds"); + NSCAssert(index2 < arr->num, @"(2) Invalid index. Out of bounds"); + + id object1 = arr->arr[index1]; + + arr->arr[index1] = arr->arr[index2]; + arr->arr[index2] = object1; +} + /** Removes all objects from arr */ static inline void ccArrayRemoveAllObjects(ccArray *arr) { while( arr->num > 0 ) - [arr->arr[--arr->num] release]; + CC_ARC_RELEASE(arr->arr[--arr->num]); } /** Removes object at specified index and pushes back all subsequent objects. Behaviour undefined if index outside [0, num-1]. */ static inline void ccArrayRemoveObjectAtIndex(ccArray *arr, NSUInteger index) { - [arr->arr[index] release]; + CC_ARC_RELEASE(arr->arr[index]); arr->num--; - - int remaining = arr->num - index; + + NSUInteger remaining = arr->num - index; if(remaining>0) - memmove(&arr->arr[index], &arr->arr[index+1], remaining * sizeof(id)); + memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(id)); } /** Removes object at specified index and fills the gap with the last object, @@ -178,7 +226,7 @@ static inline void ccArrayRemoveObjectAtIndex(ccArray *arr, NSUInteger index) Behaviour undefined if index outside [0, num-1]. */ static inline void ccArrayFastRemoveObjectAtIndex(ccArray *arr, NSUInteger index) { - [arr->arr[index] release]; + CC_ARC_RELEASE(arr->arr[index]); NSUInteger last = --arr->num; arr->arr[index] = arr->arr[last]; } @@ -212,15 +260,15 @@ static inline void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) static inline void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) { NSUInteger back = 0; - + for( NSUInteger i = 0; i < arr->num; i++) { if( ccArrayContainsObject(minusArr, arr->arr[i]) ) { - [arr->arr[i] release]; + CC_ARC_RELEASE(arr->arr[i]); back++; } else arr->arr[i - back] = arr->arr[i]; } - + arr->num -= back; } @@ -228,13 +276,19 @@ static inline void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) static inline void ccArrayMakeObjectsPerformSelector(ccArray *arr, SEL sel) { for( NSUInteger i = 0; i < arr->num; i++) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" [arr->arr[i] performSelector:sel]; +#pragma clang diagnostic pop } static inline void ccArrayMakeObjectsPerformSelectorWithObject(ccArray *arr, SEL sel, id object) { for( NSUInteger i = 0; i < arr->num; i++) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" [arr->arr[i] performSelector:sel withObject:object]; +#pragma clang diagnostic pop } @@ -248,13 +302,13 @@ static inline void ccCArrayRemoveAllValues(ccCArray *arr); /** Allocates and initializes a new C array with specified capacity */ static inline ccCArray* ccCArrayNew(NSUInteger capacity) { if (capacity == 0) - capacity = 1; - + capacity = 1; + ccCArray *arr = (ccCArray*)malloc( sizeof(ccCArray) ); arr->num = 0; - arr->arr = (id*) malloc( capacity * sizeof(id) ); + arr->arr = (CCARRAY_ID *) malloc( capacity * sizeof(id) ); arr->max = capacity; - + return arr; } @@ -262,9 +316,9 @@ static inline ccCArray* ccCArrayNew(NSUInteger capacity) { static inline void ccCArrayFree(ccCArray *arr) { if( arr == nil ) return; - + ccCArrayRemoveAllValues(arr); - + free(arr->arr); free(arr); } @@ -272,17 +326,17 @@ static inline void ccCArrayFree(ccCArray *arr) /** Doubles C array capacity */ static inline void ccCArrayDoubleCapacity(ccCArray *arr) { - return ccArrayDoubleCapacity(arr); + ccArrayDoubleCapacity(arr); } /** Increases array capacity such that max >= num + extra. */ static inline void ccCArrayEnsureExtraCapacity(ccCArray *arr, NSUInteger extra) { - return ccArrayEnsureExtraCapacity(arr,extra); + ccArrayEnsureExtraCapacity(arr,extra); } /** Returns index of first occurence of value, NSNotFound if value not found. */ -static inline NSUInteger ccCArrayGetIndexOfValue(ccCArray *arr, void* value) +static inline NSUInteger ccCArrayGetIndexOfValue(ccCArray *arr, CCARRAY_ID value) { for( NSUInteger i = 0; i < arr->num; i++) if( arr->arr[i] == value ) return i; @@ -290,37 +344,37 @@ static inline NSUInteger ccCArrayGetIndexOfValue(ccCArray *arr, void* value) } /** Returns a Boolean value that indicates whether value is present in the C array. */ -static inline BOOL ccCArrayContainsValue(ccCArray *arr, void* value) +static inline BOOL ccCArrayContainsValue(ccCArray *arr, CCARRAY_ID value) { return ccCArrayGetIndexOfValue(arr, value) != NSNotFound; } /** Inserts a value at a certain position. Behaviour undefined if aray doesn't have enough capacity */ -static inline void ccCArrayInsertValueAtIndex( ccCArray *arr, void *value, NSUInteger index) +static inline void ccCArrayInsertValueAtIndex( ccCArray *arr, CCARRAY_ID value, NSUInteger index) { - assert( index < arr->max ); - - int remaining = arr->num - index; - + NSCAssert( index < arr->max, @"ccCArrayInsertValueAtIndex: invalid index"); + + NSUInteger remaining = arr->num - index; + // last Value doesn't need to be moved if( remaining > 0) { // tex coordinates - memmove( &arr->arr[index+1],&arr->arr[index], sizeof(void*) * remaining ); + memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(void*) * remaining ); } - - arr->num++; - arr->arr[index] = (id) value; + + arr->num++; + arr->arr[index] = value; } /** Appends an value. Bahaviour undefined if array doesn't have enough capacity. */ -static inline void ccCArrayAppendValue(ccCArray *arr, void* value) +static inline void ccCArrayAppendValue(ccCArray *arr, CCARRAY_ID value) { arr->arr[arr->num] = (id) value; arr->num++; } /** Appends an value. Capacity of arr is increased if needed. */ -static inline void ccCArrayAppendValueWithResize(ccCArray *arr, void* value) +static inline void ccCArrayAppendValueWithResize(ccCArray *arr, CCARRAY_ID value) { ccCArrayEnsureExtraCapacity(arr, 1); ccCArrayAppendValue(arr, value); @@ -352,7 +406,7 @@ static inline void ccCArrayRemoveAllValues(ccCArray *arr) @since v0.99.4 */ static inline void ccCArrayRemoveValueAtIndex(ccCArray *arr, NSUInteger index) -{ +{ for( NSUInteger last = --arr->num; index < last; index++) arr->arr[index] = arr->arr[index + 1]; } @@ -371,7 +425,7 @@ static inline void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, NSUInteger inde /** Searches for the first occurance of value and removes it. If value is not found the function has no effect. @since v0.99.4 */ -static inline void ccCArrayRemoveValue(ccCArray *arr, void* value) +static inline void ccCArrayRemoveValue(ccCArray *arr, CCARRAY_ID value) { NSUInteger index = ccCArrayGetIndexOfValue(arr, value); if (index != NSNotFound) @@ -393,14 +447,14 @@ static inline void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) static inline void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr) { NSUInteger back = 0; - + for( NSUInteger i = 0; i < arr->num; i++) { if( ccCArrayContainsValue(minusArr, arr->arr[i]) ) { back++; } else arr->arr[i - back] = arr->arr[i]; } - + arr->num -= back; } -#endif // CC_ARRAY_H \ No newline at end of file +#endif // CC_ARRAY_H diff --git a/Example/libs/cocos2d/Support/ccUtils.c b/Example/libs/cocos2d/Support/ccUtils.c index a509494..27a122d 100644 --- a/Example/libs/cocos2d/Support/ccUtils.c +++ b/Example/libs/cocos2d/Support/ccUtils.c @@ -8,7 +8,7 @@ */ #include "ccUtils.h" -unsigned int ccNextPOT(unsigned int x) +unsigned long ccNextPOT(unsigned long x) { x = x - 1; x = x | (x >> 1); @@ -17,4 +17,4 @@ unsigned int ccNextPOT(unsigned int x) x = x | (x >> 8); x = x | (x >>16); return x + 1; -} \ No newline at end of file +} diff --git a/Example/libs/cocos2d/Support/ccUtils.h b/Example/libs/cocos2d/Support/ccUtils.h index 552b268..5f84ff3 100644 --- a/Example/libs/cocos2d/Support/ccUtils.h +++ b/Example/libs/cocos2d/Support/ccUtils.h @@ -6,6 +6,10 @@ #ifndef __CC_UTILS_H #define __CC_UTILS_H +#ifdef __cplusplus +extern "C" { +#endif + /** @file ccUtils.h Misc free functions */ @@ -15,15 +19,18 @@ */ /** returns the Next Power of Two value. - + Examples: - If "value" is 15, it will return 16. - If "value" is 16, it will return 16. - If "value" is 17, it will return 32. - + @since v0.99.5 */ +unsigned long ccNextPOT( unsigned long value ); -unsigned int ccNextPOT( unsigned int value ); +#ifdef __cplusplus +} +#endif #endif // ! __CC_UTILS_H diff --git a/Example/libs/cocos2d/Support/uthash.h b/Example/libs/cocos2d/Support/uthash.h index 3a404dc..e190ef7 100644 --- a/Example/libs/cocos2d/Support/uthash.h +++ b/Example/libs/cocos2d/Support/uthash.h @@ -22,7 +22,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UTHASH_H -#define UTHASH_H +#define UTHASH_H #include /* memcmp,strlen */ #include /* ptrdiff_t */ @@ -32,7 +32,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. when compiling c++ source) this code uses whatever method is needed or, for VS2008 where neither is available, uses casting workarounds. */ #ifdef _MSC_VER /* MS compiler */ -#if _MSC_VER >= 1600 && __cplusplus /* VS2010 or newer in C++ mode */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ #define DECLTYPE(x) (decltype(x)) #else /* VS2008 or older (or VS2010 in C mode) */ #define NO_DECLTYPE @@ -48,7 +48,7 @@ do { char **_da_dst = (char**)(&(dst)); \ *_da_dst = (char*)(src); \ } while(0) -#else +#else #define DECLTYPE_ASSIGN(dst,src) \ do { \ (dst) = DECLTYPE(dst)(src); \ @@ -62,11 +62,11 @@ typedef unsigned int uint32_t; #include /* uint32_t */ #endif -#define UTHASH_VERSION 1.9 +#define UTHASH_VERSION 1.9.3 #define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ #define uthash_malloc(sz) malloc(sz) /* malloc fcn */ -#define uthash_free(ptr) free(ptr) /* free fcn */ +#define uthash_free(ptr,sz) free(ptr) /* free fcn */ #define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ #define uthash_expand_fyi(tbl) /* can be defined to log expands */ @@ -106,7 +106,7 @@ do { #define HASH_BLOOM_FREE(tbl) \ do { \ - uthash_free((tbl)->bloom_bv); \ + uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ } while (0); #define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) @@ -119,9 +119,9 @@ do { HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) #else -#define HASH_BLOOM_MAKE(tbl) -#define HASH_BLOOM_FREE(tbl) -#define HASH_BLOOM_ADD(tbl,hashv) +#define HASH_BLOOM_MAKE(tbl) +#define HASH_BLOOM_FREE(tbl) +#define HASH_BLOOM_ADD(tbl,hashv) #define HASH_BLOOM_TEST(tbl,hashv) (1) #endif @@ -146,7 +146,7 @@ do { #define HASH_ADD(hh,head,fieldname,keylen_in,add) \ HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add) - + #define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ do { \ unsigned _ha_bkt; \ @@ -194,9 +194,10 @@ do { unsigned _hd_bkt; \ struct UT_hash_handle *_hd_hh_del; \ if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ - uthash_free((head)->hh.tbl->buckets ); \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ HASH_BLOOM_FREE((head)->hh.tbl); \ - uthash_free((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ head = NULL; \ } else { \ _hd_hh_del = &((delptr)->hh); \ @@ -233,6 +234,10 @@ do { HASH_FIND(hh,head,findint,sizeof(int),out) #define HASH_ADD_INT(head,intfield,add) \ HASH_ADD(hh,head,intfield,sizeof(int),add) +#define HASH_FIND_PTR(head,findptr,out) \ + HASH_FIND(hh,head,findptr,sizeof(void *),out) +#define HASH_ADD_PTR(head,ptrfield,add) \ + HASH_ADD(hh,head,ptrfield,sizeof(void *),add) #define HASH_DEL(head,delptr) \ HASH_DELETE(hh,head,delptr) @@ -293,10 +298,10 @@ do { } \ } while (0) #else -#define HASH_FSCK(hh,head) +#define HASH_FSCK(hh,head) #endif -/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to +/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to * the descriptor to which this macro is defined for tuning the hash function. * The app can #include to get the prototype for write(2). */ #ifdef HASH_EMIT_KEYS @@ -306,12 +311,12 @@ do { write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ write(HASH_EMIT_KEYS, keyptr, fieldlen); \ } while (0) -#else -#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) +#else +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) #endif /* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ -#ifdef HASH_FUNCTION +#ifdef HASH_FUNCTION #define HASH_FCN HASH_FUNCTION #else #define HASH_FCN HASH_JEN @@ -321,19 +326,19 @@ do { #define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _hb_keylen=keylen; \ - char *_hb_key=(char*)key; \ + char *_hb_key=(char*)(key); \ (hashv) = 0; \ while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ bkt = (hashv) & (num_bkts-1); \ } while (0) -/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at +/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ #define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _sx_i; \ - char *_hs_key=(char*)key; \ + char *_hs_key=(char*)(key); \ hashv = 0; \ for(_sx_i=0; _sx_i < keylen; _sx_i++) \ hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ @@ -343,17 +348,17 @@ do { #define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _fn_i; \ - char *_hf_key=(char*)key; \ + char *_hf_key=(char*)(key); \ hashv = 2166136261UL; \ for(_fn_i=0; _fn_i < keylen; _fn_i++) \ hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ bkt = hashv & (num_bkts-1); \ } while(0); - + #define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _ho_i; \ - char *_ho_key=(char*)key; \ + char *_ho_key=(char*)(key); \ hashv = 0; \ for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ hashv += _ho_key[_ho_i]; \ @@ -382,7 +387,7 @@ do { #define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ do { \ unsigned _hj_i,_hj_j,_hj_k; \ - char *_hj_key=(char*)key; \ + char *_hj_key=(char*)(key); \ hashv = 0xfeedbeef; \ _hj_i = _hj_j = 0x9e3779b9; \ _hj_k = keylen; \ @@ -433,7 +438,7 @@ do { #endif #define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ do { \ - char *_sfh_key=(char*)key; \ + char *_sfh_key=(char*)(key); \ uint32_t _sfh_tmp, _sfh_len = keylen; \ \ int _sfh_rem = _sfh_len & 3; \ @@ -479,14 +484,14 @@ do { /* The MurmurHash exploits some CPU's (e.g. x86) tolerance for unaligned reads. * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. * So MurmurHash comes in two versions, the faster unaligned one and the slower - * aligned one. We only use the faster one on CPU's where we know it's safe. + * aligned one. We only use the faster one on CPU's where we know it's safe. * * Note the preprocessor built-in defines can be emitted using: * * gcc -m64 -dM -E - < /dev/null (on gcc) * cc -## a.c (where a.c is a simple test file) (Sun Studio) */ -#if (defined(__i386__) || defined(__x86_64__)) +#if (defined(__i386__) || defined(__x86_64__)) #define HASH_MUR HASH_MUR_UNALIGNED #else #define HASH_MUR HASH_MUR_ALIGNED @@ -498,7 +503,7 @@ do { const unsigned int _mur_m = 0x5bd1e995; \ const int _mur_r = 24; \ hashv = 0xcafebabe ^ keylen; \ - char *_mur_key = (char *)key; \ + char *_mur_key = (char *)(key); \ uint32_t _mur_tmp, _mur_len = keylen; \ \ for (;_mur_len >= 4; _mur_len-=4) { \ @@ -531,8 +536,8 @@ do { do { \ const unsigned int _mur_m = 0x5bd1e995; \ const int _mur_r = 24; \ - hashv = 0xcafebabe ^ keylen; \ - char *_mur_key = (char *)key; \ + hashv = 0xcafebabe ^ (keylen); \ + char *_mur_key = (char *)(key); \ uint32_t _mur_len = keylen; \ int _mur_align = (int)_mur_key & 3; \ \ @@ -625,7 +630,7 @@ do { #endif /* HASH_USING_NO_STRICT_ALIASING */ /* key comparison function; return 0 if keys equal */ -#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) +#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) /* iterate over items in a known bucket to find desired item */ #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ @@ -666,36 +671,36 @@ do { } \ if (hh_del->hh_next) { \ hh_del->hh_next->hh_prev = hh_del->hh_prev; \ - } + } /* Bucket expansion has the effect of doubling the number of buckets * and redistributing the items into the new buckets. Ideally the * items will distribute more or less evenly into the new buckets * (the extent to which this is true is a measure of the quality of - * the hash function as it applies to the key domain). - * + * the hash function as it applies to the key domain). + * * With the items distributed into more buckets, the chain length * (item count) in each bucket is reduced. Thus by expanding buckets - * the hash keeps a bound on the chain length. This bounded chain + * the hash keeps a bound on the chain length. This bounded chain * length is the essence of how a hash provides constant time lookup. - * + * * The calculation of tbl->ideal_chain_maxlen below deserves some * explanation. First, keep in mind that we're calculating the ideal * maximum chain length based on the *new* (doubled) bucket count. * In fractions this is just n/b (n=number of items,b=new num buckets). - * Since the ideal chain length is an integer, we want to calculate + * Since the ideal chain length is an integer, we want to calculate * ceil(n/b). We don't depend on floating point arithmetic in this * hash, so to calculate ceil(n/b) with integers we could write - * + * * ceil(n/b) = (n/b) + ((n%b)?1:0) - * + * * and in fact a previous version of this hash did just that. * But now we have improved things a bit by recognizing that b is * always a power of two. We keep its base 2 log handy (call it lb), * so now we can write this with a bit shift and logical AND: - * + * * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) - * + * */ #define HASH_EXPAND_BUCKETS(tbl) \ do { \ @@ -732,9 +737,9 @@ do { _he_thh = _he_hh_nxt; \ } \ } \ + uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ tbl->num_buckets *= 2; \ tbl->log2_num_buckets++; \ - uthash_free( tbl->buckets ); \ tbl->buckets = _he_new_buckets; \ tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ (tbl->ineff_expands+1) : 0; \ @@ -747,7 +752,7 @@ do { /* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ -/* Note that HASH_SORT assumes the hash handle name to be hh. +/* Note that HASH_SORT assumes the hash handle name to be hh. * HASH_SRT was added to allow the hash handle name to be passed in. */ #define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) #define HASH_SRT(hh,head,cmpfcn) \ @@ -829,10 +834,10 @@ do { } \ } while (0) -/* This function selects items from one hash into another hash. - * The end result is that the selected items have dual presence - * in both hashes. There is no copy of the items made; rather - * they are added into the new hash through a secondary hash +/* This function selects items from one hash into another hash. + * The end result is that the selected items have dual presence + * in both hashes. There is no copy of the items made; rather + * they are added into the new hash through a secondary hash * hash handle that must be present in the structure. */ #define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ do { \ @@ -875,15 +880,26 @@ do { #define HASH_CLEAR(hh,head) \ do { \ if (head) { \ - uthash_free((head)->hh.tbl->buckets ); \ - uthash_free((head)->hh.tbl); \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ (head)=NULL; \ } \ } while(0) +#ifdef NO_DECLTYPE +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) +#else +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL)) +#endif + /* obtain a count of items in the hash */ -#define HASH_COUNT(head) HASH_CNT(hh,head) -#define HASH_CNT(hh,head) (head?(head->hh.tbl->num_items):0) +#define HASH_COUNT(head) HASH_CNT(hh,head) +#define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0) typedef struct UT_hash_bucket { struct UT_hash_handle *hh_head; @@ -891,7 +907,7 @@ typedef struct UT_hash_bucket { /* expand_mult is normally set to 0. In this situation, the max chain length * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If - * the bucket's chain exceeds this length, bucket expansion is triggered). + * the bucket's chain exceeds this length, bucket expansion is triggered). * However, setting expand_mult to a non-zero value delays bucket expansion * (that would be triggered by additions to this particular bucket) * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. @@ -899,7 +915,7 @@ typedef struct UT_hash_bucket { * multiplier is to reduce bucket expansions, since they are expensive, in * situations where we know that a particular bucket tends to be overused. * It is better to let its chain length grow to a longer yet-still-bounded - * value, than to do an O(n) bucket expansion too often. + * value, than to do an O(n) bucket expansion too often. */ unsigned expand_mult; @@ -925,7 +941,7 @@ typedef struct UT_hash_table { * hash distribution; reaching them in a chain traversal takes >ideal steps */ unsigned nonideal_items; - /* ineffective expands occur when a bucket doubling was performed, but + /* ineffective expands occur when a bucket doubling was performed, but * afterward, more than half the items in the hash had nonideal chain * positions. If this happens on two consecutive expansions we inhibit any * further expansion, as it's not helping; this happens when the hash diff --git a/Example/libs/cocos2d/Support/utlist.h b/Example/libs/cocos2d/Support/utlist.h index 99cc6f8..b160f1a 100644 --- a/Example/libs/cocos2d/Support/utlist.h +++ b/Example/libs/cocos2d/Support/utlist.h @@ -24,9 +24,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef UTLIST_H #define UTLIST_H -#define UTLIST_VERSION 1.9 +#define UTLIST_VERSION 1.9.1 -/* +/* * This file contains macros to manipulate singly and doubly-linked lists. * * 1. LL_ macros: singly-linked lists. @@ -36,7 +36,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * To use singly-linked lists, your structure must have a "next" pointer. * To use doubly-linked lists, your structure must "prev" and "next" pointers. * Either way, the pointer to the head of the list must be initialized to NULL. - * + * * ----------------.EXAMPLE ------------------------- * struct item { * int id; @@ -61,19 +61,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. As decltype is only available in newer compilers (VS2010 or gcc 4.3+ when compiling c++ code), this code uses whatever method is needed or, for VS2008 where neither is available, uses casting workarounds. */ - -#ifndef DECLTYPE #ifdef _MSC_VER /* MS compiler */ -#if _MSC_VER >= 1600 && __cplusplus /* VS2010 and newer in C++ mode */ -#define DECLTYPE(x) decltype(x) +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define LDECLTYPE(x) decltype(x) #else /* VS2008 or older (or VS2010 in C mode) */ #define NO_DECLTYPE -#define DECLTYPE(x) char* +#define LDECLTYPE(x) char* #endif #else /* GNU, Sun and other compilers */ -#define DECLTYPE(x) __typeof(x) +#define LDECLTYPE(x) __typeof(x) #endif -#endif // DECLTYPE /* for VS2008 we use some workarounds to get around the lack of decltype, * namely, we always reassign our tmp variable to the list head if we need @@ -86,7 +83,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } #define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } #define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } -#else +#else #define _SV(elt,list) #define _NEXT(elt,list) ((elt)->next) #define _NEXTASGN(elt,list,to) ((elt)->next)=(to) @@ -102,12 +99,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #define LL_SORT(list, cmp) \ do { \ - DECLTYPE(list) _ls_p; \ - DECLTYPE(list) _ls_q; \ - DECLTYPE(list) _ls_e; \ - DECLTYPE(list) _ls_tail; \ - DECLTYPE(list) _ls_oldhead; \ - DECLTYPE(list) _tmp; \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ if (list) { \ _ls_insize = 1; \ @@ -158,12 +155,12 @@ do { #define DL_SORT(list, cmp) \ do { \ - DECLTYPE(list) _ls_p; \ - DECLTYPE(list) _ls_q; \ - DECLTYPE(list) _ls_e; \ - DECLTYPE(list) _ls_tail; \ - DECLTYPE(list) _ls_oldhead; \ - DECLTYPE(list) _tmp; \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ if (list) { \ _ls_insize = 1; \ @@ -216,13 +213,13 @@ do { #define CDL_SORT(list, cmp) \ do { \ - DECLTYPE(list) _ls_p; \ - DECLTYPE(list) _ls_q; \ - DECLTYPE(list) _ls_e; \ - DECLTYPE(list) _ls_tail; \ - DECLTYPE(list) _ls_oldhead; \ - DECLTYPE(list) _tmp; \ - DECLTYPE(list) _tmp2; \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + LDECLTYPE(list) _tmp2; \ int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ if (list) { \ _ls_insize = 1; \ @@ -295,7 +292,7 @@ do { #define LL_APPEND(head,add) \ do { \ - DECLTYPE(head) _tmp; \ + LDECLTYPE(head) _tmp; \ (add)->next=NULL; \ if (head) { \ _tmp = head; \ @@ -308,7 +305,7 @@ do { #define LL_DELETE(head,del) \ do { \ - DECLTYPE(head) _tmp; \ + LDECLTYPE(head) _tmp; \ if ((head) == (del)) { \ (head)=(head)->next; \ } else { \ @@ -372,14 +369,14 @@ do { LL_FOREACH(head,out) { \ if ((out)->field == (val)) break; \ } \ -} while(0) +} while(0) #define LL_SEARCH(head,out,elt,cmp) \ do { \ LL_FOREACH(head,out) { \ if ((cmp(out,elt))==0) break; \ } \ -} while(0) +} while(0) /****************************************************************************** * doubly linked list macros (non-circular) * @@ -468,7 +465,7 @@ do { } while (0); #define CDL_FOREACH(head,el) \ - for(el=head;el;el=(el->next==head ? 0L : el->next)) + for(el=head;el;el=(el->next==head ? 0L : el->next)) #define CDL_FOREACH_SAFE(head,el,tmp1,tmp2) \ for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL); \ @@ -480,14 +477,14 @@ do { CDL_FOREACH(head,out) { \ if ((out)->field == (val)) break; \ } \ -} while(0) +} while(0) #define CDL_SEARCH(head,out,elt,cmp) \ do { \ CDL_FOREACH(head,out) { \ if ((cmp(out,elt))==0) break; \ } \ -} while(0) +} while(0) #endif /* UTLIST_H */ diff --git a/Example/libs/cocos2d/ccConfig.h b/Example/libs/cocos2d/ccConfig.h index 5ab8e6e..5eb6683 100644 --- a/Example/libs/cocos2d/ccConfig.h +++ b/Example/libs/cocos2d/ccConfig.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,270 +23,223 @@ * THE SOFTWARE. */ - -#import - /** @file cocos2d (cc) configuration file */ +/** @def CC_ENABLE_GL_STATE_CACHE + If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches. + In order to use them, you have to use the following functions, insead of the the GL ones: + - ccGLUseProgram() instead of glUseProgram() + - ccGLDeleteProgram() instead of glDeleteProgram() + - ccGLBlendFunc() instead of glBlendFunc() + + If this functionality is disabled, then ccGLUseProgram(), ccGLDeleteProgram(), ccGLBlendFunc() will call the GL ones, without using the cache. + + It is recommened to enable it whenever possible to improve speed. + If you are migrating your code from GL ES 1.1, then keep it disabled. Once all your code works as expected, turn it on. + + Default value: Disabled by default + + @since v2.0.0 + */ +#ifndef CC_ENABLE_GL_STATE_CACHE +#define CC_ENABLE_GL_STATE_CACHE 0 +#endif + +/** @def CC_ENABLE_DEPRECATED + If enabled, cocos2d will compile all deprecated methods, classes and free functions. Also, renamed constants will be active as well. + Enable it only when migrating a v1.0 or earlier v2.0 versions to the most recent cocdos2d version. + + Default value: Enabled by default + + @since v2.0.0 + */ +#ifndef CC_ENABLE_DEPRECATED +#define CC_ENABLE_DEPRECATED 1 +#endif + + /** @def CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL If enabled, the texture coordinates will be calculated by using this formula: - texCoord.left = (rect.origin.x*2+1) / (texture.wide*2); - texCoord.right = texCoord.left + (rect.size.width*2-2)/(texture.wide*2); - + The same for bottom and top. - + This formula prevents artifacts by using 99% of the texture. The "correct" way to prevent artifacts is by using the spritesheet-artifact-fixer.py or a similar tool. - + Affected nodes: - - CCSprite / CCSpriteBatchNode and subclasses: CCBitmapFontAtlas, CCTMXTiledMap + - CCSprite / CCSpriteBatchNode and subclasses: CCLabelBMFont, CCTMXLayer - CCLabelAtlas - - CCQuadParticleSystem + - CCParticleSystemQuad - CCTileMap - + To enabled set it to 1. Disabled by default. - + @since v0.99.5 */ +#ifndef CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL #define CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL 0 - +#endif -/** @def CC_FONT_LABEL_SUPPORT - If enabled, FontLabel will be used to render .ttf files. - If the .ttf file is not found, then it will use the standard UIFont class - If disabled, the standard UIFont class will be used. - - To disable set it to 0. Enabled by default. +/** @def CC_DIRECTOR_STATS_INTERVAL + Seconds between stats updates. + 0.5 seconds, means that the stats will be updated every 0.5 seconds. + Having a bigger number means more stable stats - Only valid for cocos2d-ios. Not supported on cocos2d-mac + Default value: 0.1f */ -#define CC_FONT_LABEL_SUPPORT 1 +#ifndef CC_DIRECTOR_STATS_INTERVAL +#define CC_DIRECTOR_STATS_INTERVAL (0.1f) +#endif -/** @def CC_DIRECTOR_FAST_FPS - If enabled, then the FPS will be drawn using CCLabelAtlas (fast rendering). - You will need to add the fps_images.png to your project. - If disabled, the FPS will be rendered using CCLabel (slow rendering) - - To enable set it to a value different than 0. Enabled by default. - */ -#define CC_DIRECTOR_FAST_FPS 1 +/** @def CC_DIRECTOR_STATS_POSITION + Position of the FPS -/** @def CC_DIRECTOR_FPS_INTERVAL - Senconds between FPS updates. - 0.5 seconds, means that the FPS number will be updated every 0.5 seconds. - Having a bigger number means a more reliable FPS - - Default value: 0.1f + Default: 0,0 (bottom-left corner) */ -#define CC_DIRECTOR_FPS_INTERVAL (0.1f) +#ifndef CC_DIRECTOR_STATS_POSITION +#define CC_DIRECTOR_STATS_POSITION ccp(0,0) +#endif -/** @def CC_DIRECTOR_DISPATCH_FAST_EVENTS - If enabled, and only when it is used with CCFastDirector, the main loop will wait 0.04 seconds to - dispatch all the events, even if there are not events to dispatch. - If your game uses lot's of events (eg: touches) it might be a good idea to enable this feature. - Otherwise, it is safe to leave it disabled. - - To enable set it to 1. Disabled by default. +/** @def CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD + If enabled, cocos2d-ios will run on a background thread. If disabled cocos2d-ios will run the main thread. + + To enable set it to a 1, to disable it set to 0. Enabled by default. + + Only valid for cocos2d-ios. Not supported on cocos2d-mac. - @warning This feature is experimental + This is an EXPERIMENTAL feature. Do not use it unless you are a developer. + */ -#define CC_DIRECTOR_DISPATCH_FAST_EVENTS 0 +#ifndef CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD +#define CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD 0 +#endif -/** @def CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - If enabled, cocos2d-mac will run on the Display Link thread. If disabled cocos2d-mac will run in its own thread. - - If enabled, the images will be drawn at the "correct" time, but the events might not be very responsive. - If disabled, some frames might be skipped, but the events will be dispatched as they arrived. - - To enable set it to a 1, to disable it set to 0. Enabled by default. +#define CC_MAC_USE_DISPLAY_LINK_THREAD 0 +#define CC_MAC_USE_OWN_THREAD 1 +#define CC_MAC_USE_MAIN_THREAD 2 + +/** @def CC_DIRECTOR_MAC_THREAD + cocos2d-mac can run on its own thread, on the Display Link thread, or in the main thread. + If you are developing a game, the Display Link or Own thread are the best alternatives. + If you are developing an editor that uses AppKit, you might need to use the Main Thread (only if you are lazy and don't want to create a sync queue). + + Options: + CC_MAC_USE_DISPLAY_LINK_THREAD (default) + CC_MAC_USE_OWN_THREAD + CC_MAC_USE_MAIN_THREAD + Only valid for cocos2d-mac. Not supported on cocos2d-ios. */ -#define CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD 1 +#ifndef CC_DIRECTOR_MAC_THREAD +#define CC_DIRECTOR_MAC_THREAD CC_MAC_USE_DISPLAY_LINK_THREAD +#endif -/** @def CC_COCOSNODE_RENDER_SUBPIXEL +/** @def CC_NODE_RENDER_SUBPIXEL If enabled, the CCNode objects (CCSprite, CCLabel,etc) will be able to render in subpixels. If disabled, integer pixels will be used. - + To enable set it to 1. Enabled by default. */ -#define CC_COCOSNODE_RENDER_SUBPIXEL 1 +#ifndef CC_NODE_RENDER_SUBPIXEL +#define CC_NODE_RENDER_SUBPIXEL 1 +#endif /** @def CC_SPRITEBATCHNODE_RENDER_SUBPIXEL If enabled, the CCSprite objects rendered with CCSpriteBatchNode will be able to render in subpixels. If disabled, integer pixels will be used. - + To enable set it to 1. Enabled by default. */ +#ifndef CC_SPRITEBATCHNODE_RENDER_SUBPIXEL #define CC_SPRITEBATCHNODE_RENDER_SUBPIXEL 1 - - -#if defined(__ARM_NEON__) || TARGET_IPHONE_SIMULATOR || defined(__MAC_OS_X_VERSION_MAX_ALLOWED) -/** @def CC_USES_VBO - If enabled, batch nodes (texture atlas and particle system) will use VBO instead of vertex list (VBO is recommended by Apple) - - To enable set it to 1. - Enabled by default on iPhone with ARMv7 processors, iPhone Simulator and Mac - Disabled by default on iPhone with ARMv6 processors. - - @since v0.99.5 - */ -#define CC_USES_VBO 1 -#else -#define CC_USES_VBO 0 #endif -/** @def CC_NODE_TRANSFORM_USING_AFFINE_MATRIX - If enabled, CCNode will transform the nodes using a cached Affine matrix. - If disabled, the node will be transformed using glTranslate,glRotate,glScale. - Using the affine matrix only requires 2 GL calls. - Using the translate/rotate/scale requires 5 GL calls. - But computing the Affine matrix is relative expensive. - But according to performance tests, Affine matrix performs better. - This parameter doesn't affect SpriteSheet nodes. - - To enable set it to a value different than 0. Enabled by default. - - */ -#define CC_NODE_TRANSFORM_USING_AFFINE_MATRIX 1 - -/** @def CC_OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA - If most of your imamges have pre-multiplied alpha, set it to 1 (if you are going to use .PNG/.JPG file images). - Only set to 0 if ALL your images by-pass Apple UIImage loading system (eg: if you use libpng or PVR images) - - To enable set it to a value different than 0. Enabled by default. - - @since v0.99.5 - */ -#define CC_OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA 1 - /** @def CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP Use GL_TRIANGLE_STRIP instead of GL_TRIANGLES when rendering the texture atlas. It seems it is the recommend way, but it is much slower, so, enable it at your own risk - - To enable set it to a value different than 0. Disabled by default. - - */ -#define CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP 0 - -/** @def CC_TEXTURE_NPOT_SUPPORT - If enabled, NPOT textures will be used where available. Only 3rd gen (and newer) devices support NPOT textures. - NPOT textures have the following limitations: - - They can't have mipmaps - - They only accept GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T} - To enable set it to a value different than 0. Disabled by default. - @since v0.99.2 */ -#define CC_TEXTURE_NPOT_SUPPORT 0 +#ifndef CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP +#define CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP 0 +#endif -/** @def CC_RETINA_DISPLAY_SUPPORT - If enabled, cocos2d supports retina display. - For performance reasons, it's recommended disable it in games without retina display support, like iPad only games. +/** @def CC_TEXTURE_ATLAS_USE_VAO + By default, CCTextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects). + Apple recommends its usage but they might consume a lot of memory, specially if you use many of them. + So for certain cases, where you might need hundreds of VAO objects, it might be a good idea to disable it. - To enable set it to 1. Use 0 to disable it. Enabled by default. + To disable it set it to 0. Enabled by default. - @since v0.99.5 */ -#define CC_RETINA_DISPLAY_SUPPORT 1 +#ifndef CC_TEXTURE_ATLAS_USE_VAO +#define CC_TEXTURE_ATLAS_USE_VAO 1 +#endif -/** @def CC_RETINA_DISPLAY_FILENAME_SUFFIX - It's the suffix that will be appended to the files in order to load "retina display" images. - On an iPhone4 with Retina Display support enabled, the file @"sprite-hd.png" will be loaded instead of @"sprite.png". - If the file doesn't exist it will use the non-retina display image. - - Platforms: Only used on Retina Display devices like iPhone 4. - - @since v0.99.5 - */ -#define CC_RETINA_DISPLAY_FILENAME_SUFFIX @"-hd" +/** @def CC_USE_LA88_LABELS + If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for CCLabelTTF objects. + If it is disabled, it will use A8 (Alpha 8-bit textures). + LA88 textures are 6% faster than A8 textures, but they will consume 2x memory. + + This feature is enabled by default. -/** @def CC_USE_RGBA32_LABELS_ON_NEON_ARCH - If enabled, it will use RGBA8888 (32-bit textures) on Neon devices for CCLabelTTF objects. - If it is disabled, or if it is used on another architecture it will use A8 (8-bit textures). - On Neon devices, RGBA8888 textures are 6% faster than A8 textures, but then will consule 4x memory. - - This feature is disabled by default. - - Platforms: Only used on ARM Neon architectures like iPhone 3GS or newer and iPad. - @since v0.99.5 */ -#define CC_USE_RGBA32_LABELS_ON_NEON_ARCH 0 +#ifndef CC_USE_LA88_LABELS +#define CC_USE_LA88_LABELS 1 +#endif /** @def CC_SPRITE_DEBUG_DRAW - If enabled, all subclasses of CCSprite will draw a bounding box + If enabled, all subclasses of CCSprite will draw a bounding box. Useful for debugging purposes only. It is recommened to leave it disabled. - - To enable set it to a value different than 0. Disabled by default. + + If the CCSprite is being drawn by a CCSpriteBatchNode, the bounding box might be a bit different. + To enable set it to a value different than 0. Disabled by default: + 0 -- disabled + 1 -- draw bounding box + 2 -- draw texture box */ +#ifndef CC_SPRITE_DEBUG_DRAW #define CC_SPRITE_DEBUG_DRAW 0 +#endif -/** @def CC_SPRITEBATCHNODE_DEBUG_DRAW - If enabled, all subclasses of CCSprite that are rendered using an CCSpriteSheet draw a bounding box. - Useful for debugging purposes only. It is recommened to leave it disabled. - - To enable set it to a value different than 0. Disabled by default. - */ -#define CC_SPRITEBATCHNODE_DEBUG_DRAW 0 -/** @def CC_BITMAPFONTATLAS_DEBUG_DRAW - If enabled, all subclasses of BitmapFontAtlas will draw a bounding box +/** @def CC_LABELBMFONT_DEBUG_DRAW + If enabled, all subclasses of CCLabelBMFont will draw a bounding box Useful for debugging purposes only. It is recommened to leave it disabled. - + To enable set it to a value different than 0. Disabled by default. */ -#define CC_BITMAPFONTATLAS_DEBUG_DRAW 0 +#ifndef CC_LABELBMFONT_DEBUG_DRAW +#define CC_LABELBMFONT_DEBUG_DRAW 0 +#endif /** @def CC_LABELATLAS_DEBUG_DRAW - If enabled, all subclasses of LabeltAtlas will draw a bounding box + If enabled, all subclasses of CCLabeltAtlas will draw a bounding box Useful for debugging purposes only. It is recommened to leave it disabled. - + To enable set it to a value different than 0. Disabled by default. */ +#ifndef CC_LABELATLAS_DEBUG_DRAW #define CC_LABELATLAS_DEBUG_DRAW 0 +#endif /** @def CC_ENABLE_PROFILERS - If enabled, will activate various profilers withing cocos2d. This statistical data will be output to the console - once per second showing average time (in milliseconds) required to execute the specific routine(s). - Useful for debugging purposes only. It is recommened to leave it disabled. - - To enable set it to a value different than 0. Disabled by default. - */ -#define CC_ENABLE_PROFILERS 0 + If enabled, it will activate various profilers within cocos2d. This statistical data will be saved in the CCProfiler singleton. + In order to display saved data, you have to call the CC_PROFILER_DISPLAY_TIMERS() macro. + Useful for profiling purposes only. If unsure, leave it disabled. -/** @def CC_COMPATIBILITY_WITH_0_8 - Enable it if you want to support v0.8 compatbility. - Basically, classes without namespaces will work. - It is recommended to disable compatibility once you have migrated your game to v0.9 to avoid class name polution - To enable set it to a value different than 0. Disabled by default. */ -#define CC_COMPATIBILITY_WITH_0_8 0 - - -// -// DON'T edit this macro. -// -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - -#if CC_RETINA_DISPLAY_SUPPORT -#define CC_IS_RETINA_DISPLAY_SUPPORTED 1 -#else -#define CC_IS_RETINA_DISPLAY_SUPPORTED 0 -#endif - -#elif __MAC_OS_X_VERSION_MAX_ALLOWED - -#define CC_IS_RETINA_DISPLAY_SUPPORTED 0 - +#ifndef CC_ENABLE_PROFILERS +#define CC_ENABLE_PROFILERS 0 #endif - - diff --git a/Example/libs/cocos2d/ccMacros.h b/Example/libs/cocos2d/ccMacros.h index 117066d..4b73887 100644 --- a/Example/libs/cocos2d/ccMacros.h +++ b/Example/libs/cocos2d/ccMacros.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -34,6 +35,12 @@ cocos2d helper macros */ +#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#define __CC_PLATFORM_IOS 1 +#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) +#define __CC_PLATFORM_MAC 1 +#endif + /* * if COCOS2D_DEBUG is not defined, or if it is 0 then * all CCLOGXXX macros will be disabled @@ -46,7 +53,7 @@ * if COCOS2D_DEBUG==2 or higher then: * CCLOG() will be enabled * CCLOGERROR() will be enabled - * CCLOGINFO() will be enabled + * CCLOGINFO() will be enabled */ #if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 #define CCLOG(...) do {} while (0) @@ -93,72 +100,40 @@ simple macro that swaps 2 variables */ #define CC_RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) * 57.29577951f) // PI * 180 +#define kCCRepeatForever UINT_MAX -1 /** @def CC_BLEND_SRC default gl blend src function. Compatible with premultiplied alpha images. */ -#if CC_OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA #define CC_BLEND_SRC GL_ONE #define CC_BLEND_DST GL_ONE_MINUS_SRC_ALPHA -#else -#define CC_BLEND_SRC GL_SRC_ALPHA -#define CC_BLEND_DST GL_ONE_MINUS_SRC_ALPHA -#endif // ! CC_OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA - -/** @def CC_ENABLE_DEFAULT_GL_STATES - GL states that are enabled: - - GL_TEXTURE_2D - - GL_VERTEX_ARRAY - - GL_TEXTURE_COORD_ARRAY - - GL_COLOR_ARRAY - */ -#define CC_ENABLE_DEFAULT_GL_STATES() { \ - glEnableClientState(GL_VERTEX_ARRAY); \ - glEnableClientState(GL_COLOR_ARRAY); \ - glEnableClientState(GL_TEXTURE_COORD_ARRAY); \ - glEnable(GL_TEXTURE_2D); \ -} - -/** @def CC_DISABLE_DEFAULT_GL_STATES - Disable default GL states: - - GL_TEXTURE_2D - - GL_VERTEX_ARRAY - - GL_TEXTURE_COORD_ARRAY - - GL_COLOR_ARRAY - */ -#define CC_DISABLE_DEFAULT_GL_STATES() { \ - glDisable(GL_TEXTURE_2D); \ - glDisableClientState(GL_COLOR_ARRAY); \ - glDisableClientState(GL_TEXTURE_COORD_ARRAY); \ - glDisableClientState(GL_VERTEX_ARRAY); \ -} /** @def CC_DIRECTOR_INIT - - Initializes an EAGLView with 0-bit depth format, and RGB565 render buffer. - - The EAGLView view will have multiple touches disabled. - - It will create a UIWindow and it will assign it the 'window' variable. 'window' must be declared before calling this marcro. - - It will parent the EAGLView to the created window - - If the firmware >= 3.1 it will create a Display Link Director. Else it will create an NSTimer director. + - Initializes an CCGLView with 0-bit depth format, and RGB565 render buffer. + - The CCGLView view will have multiple touches disabled. + - It will create a UIWindow and it will assign it the 'window_' ivar. 'window_' must be declared before calling this marcro. + - It will create a UINavigationController and it will assign it the 'navigationController_' ivar. 'navController_' must be declared before using this macro. + - The director_ will be the root view controller of the navController. + - It will connect the CCGLView to the Director + - It will connect the UINavController view to the UIWindow. - It will try to run at 60 FPS. - - The FPS won't be displayed. - - The orientation will be portrait. - - It will connect the director with the EAGLView. + - It will connect the director with the CCGLView. IMPORTANT: If you want to use another type of render buffer (eg: RGBA8) or if you want to use a 16-bit or 24-bit depth buffer, you should NOT - use this macro. Instead, you should create the EAGLView manually. - + use this macro. Instead, you should create the CCGLView manually. + @since v0.99.4 */ + +#ifdef __CC_PLATFORM_IOS + #define CC_DIRECTOR_INIT() \ do { \ - window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; \ - if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] ) \ - [CCDirector setDirectorType:kCCDirectorTypeNSTimer]; \ - CCDirector *__director = [CCDirector sharedDirector]; \ - [__director setDeviceOrientation:kCCDeviceOrientationPortrait]; \ - [__director setDisplayFPS:NO]; \ - [__director setAnimationInterval:1.0/60]; \ - EAGLView *__glView = [EAGLView viewWithFrame:[window bounds] \ + window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; \ + director_ = (CCDirectorIOS*)[CCDirector sharedDirector]; \ + [director_ setDisplayStats:NO]; \ + [director_ setAnimationInterval:1.0/60]; \ + CCGLView *__glView = [CCGLView viewWithFrame:[window_ bounds] \ pixelFormat:kEAGLColorFormatRGB565 \ depthFormat:0 /* GL_DEPTH_COMPONENT24_OES */ \ preserveBackbuffer:NO \ @@ -166,27 +141,65 @@ do { \ multiSampling:NO \ numberOfSamples:0 \ ]; \ - [__director setOpenGLView:__glView]; \ - [window addSubview:__glView]; \ - [window makeKeyAndVisible]; \ + [director_ setView:__glView]; \ + [director_ setDelegate:self]; \ + director_.wantsFullScreenLayout = YES; \ + if( ! [director_ enableRetinaDisplay:YES] ) \ + CCLOG(@"Retina Display Not supported"); \ + navController_ = [[UINavigationController alloc] initWithRootViewController:director_]; \ + navController_.navigationBarHidden = YES; \ + [window_ addSubview:navController_.view]; \ + [window_ makeKeyAndVisible]; \ } while(0) - + + +#elif __CC_PLATFORM_MAC + +#define CC_DIRECTOR_INIT(__WINSIZE__) \ +do { \ + NSRect frameRect = NSMakeRect(0, 0, (__WINSIZE__).width, (__WINSIZE__).height); \ + window_ = [[CCWindow alloc] initWithFrame:frameRect fullscreen:NO]; \ + glView_ = [[CCGLView alloc] initWithFrame:frameRect shareContext:nil]; \ + [self.window setContentView:self.glView]; \ + director_ = (CCDirectorMac*) [CCDirector sharedDirector]; \ + [director_ setDisplayStats:NO]; \ + [director_ setView:self.glView]; \ + [director_ setOriginalWinSize:__WINSIZE__]; \ + [self.window makeMainWindow]; \ + [self.window makeKeyAndOrderFront:self]; \ + [self.window center]; \ +} while(0) + +#endif + +/** @def CC_NODE_DRAW_SETUP + Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix + @since v2.0 + */ +#define CC_NODE_DRAW_SETUP() \ +do { \ + ccGLEnable( glServerState_ ); \ + [shaderProgram_ use]; \ + [shaderProgram_ setUniformForModelViewProjectionMatrix]; \ +} while(0) + + /** @def CC_DIRECTOR_END Stops and removes the director from memory. - Removes the EAGLView from its parent - + Removes the CCGLView from its parent + @since v0.99.4 */ #define CC_DIRECTOR_END() \ do { \ CCDirector *__director = [CCDirector sharedDirector]; \ - CC_GLVIEW *__view = [__director openGLView]; \ - [__view removeFromSuperview]; \ [__director end]; \ } while(0) -#if CC_IS_RETINA_DISPLAY_SUPPORTED + + +#if __CC_PLATFORM_IOS /****************************/ /** RETINA DISPLAY ENABLED **/ @@ -196,25 +209,50 @@ do { \ On Mac it returns 1; On iPhone it returns 2 if RetinaDisplay is On. Otherwise it returns 1 */ -#import "Platforms/iOS/CCDirectorIOS.h" +extern float __ccContentScaleFactor; #define CC_CONTENT_SCALE_FACTOR() __ccContentScaleFactor /** @def CC_RECT_PIXELS_TO_POINTS Converts a rect in pixels to points */ -#define CC_RECT_PIXELS_TO_POINTS(__pixels__) \ - CGRectMake( (__pixels__).origin.x / CC_CONTENT_SCALE_FACTOR(), (__pixels__).origin.y / CC_CONTENT_SCALE_FACTOR(), \ - (__pixels__).size.width / CC_CONTENT_SCALE_FACTOR(), (__pixels__).size.height / CC_CONTENT_SCALE_FACTOR() ) +#define CC_RECT_PIXELS_TO_POINTS(__rect_in_pixels__) \ + CGRectMake( (__rect_in_pixels__).origin.x / CC_CONTENT_SCALE_FACTOR(), (__rect_in_pixels__).origin.y / CC_CONTENT_SCALE_FACTOR(), \ + (__rect_in_pixels__).size.width / CC_CONTENT_SCALE_FACTOR(), (__rect_in_pixels__).size.height / CC_CONTENT_SCALE_FACTOR() ) /** @def CC_RECT_POINTS_TO_PIXELS Converts a rect in points to pixels */ -#define CC_RECT_POINTS_TO_PIXELS(__points__) \ - CGRectMake( (__points__).origin.x * CC_CONTENT_SCALE_FACTOR(), (__points__).origin.y * CC_CONTENT_SCALE_FACTOR(), \ - (__points__).size.width * CC_CONTENT_SCALE_FACTOR(), (__points__).size.height * CC_CONTENT_SCALE_FACTOR() ) +#define CC_RECT_POINTS_TO_PIXELS(__rect_in_points_points__) \ + CGRectMake( (__rect_in_points_points__).origin.x * CC_CONTENT_SCALE_FACTOR(), (__rect_in_points_points__).origin.y * CC_CONTENT_SCALE_FACTOR(), \ + (__rect_in_points_points__).size.width * CC_CONTENT_SCALE_FACTOR(), (__rect_in_points_points__).size.height * CC_CONTENT_SCALE_FACTOR() ) + +/** @def CC_POINT_PIXELS_TO_POINTS + Converts a rect in pixels to points + */ +#define CC_POINT_PIXELS_TO_POINTS(__pixels__) \ +CGPointMake( (__pixels__).x / CC_CONTENT_SCALE_FACTOR(), (__pixels__).y / CC_CONTENT_SCALE_FACTOR()) + +/** @def CC_POINT_POINTS_TO_PIXELS + Converts a rect in points to pixels + */ +#define CC_POINT_POINTS_TO_PIXELS(__points__) \ +CGPointMake( (__points__).x * CC_CONTENT_SCALE_FACTOR(), (__points__).y * CC_CONTENT_SCALE_FACTOR()) + +/** @def CC_POINT_PIXELS_TO_POINTS + Converts a rect in pixels to points + */ +#define CC_SIZE_PIXELS_TO_POINTS(__size_in_pixels__) \ +CGSizeMake( (__size_in_pixels__).width / CC_CONTENT_SCALE_FACTOR(), (__size_in_pixels__).height / CC_CONTENT_SCALE_FACTOR()) + +/** @def CC_POINT_POINTS_TO_PIXELS + Converts a rect in points to pixels + */ +#define CC_SIZE_POINTS_TO_PIXELS(__size_in_points__) \ +CGSizeMake( (__size_in_points__).width * CC_CONTENT_SCALE_FACTOR(), (__size_in_points__).height * CC_CONTENT_SCALE_FACTOR()) -#else // retina disabled + +#elif defined(__CC_PLATFORM_MAC) /*****************************/ /** RETINA DISPLAY DISABLED **/ @@ -223,5 +261,82 @@ do { \ #define CC_CONTENT_SCALE_FACTOR() 1 #define CC_RECT_PIXELS_TO_POINTS(__pixels__) __pixels__ #define CC_RECT_POINTS_TO_PIXELS(__points__) __points__ +#define CC_SIZE_PIXELS_TO_POINTS(__pixels__) __pixels__ +#define CC_SIZE_POINTS_TO_PIXELS(__points__) __points__ +#define CC_POINT_PIXELS_TO_POINTS(__pixels__) __pixels__ +#define CC_POINT_POINTS_TO_PIXELS(__points__) __points__ + + +#endif // __CC_PLATFORM_MAC + + +/**********************/ +/** Profiling Macros **/ +/**********************/ +#if CC_ENABLE_PROFILERS + +#define CC_PROFILER_DISPLAY_TIMERS() [[CCProfiler sharedProfiler] displayTimers] +#define CC_PROFILER_PURGE_ALL() [[CCProfiler sharedProfiler] releaseAllTimers] + +#define CC_PROFILER_START(__name__) CCProfilingBeginTimingBlock(__name__) +#define CC_PROFILER_STOP(__name__) CCProfilingEndTimingBlock(__name__) +#define CC_PROFILER_RESET(__name__) CCProfilingResetTimingBlock(__name__) + +#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProfilingBeginTimingBlock(__name__); } while(0) +#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProfilingEndTimingBlock(__name__); } while(0) +#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProfilingResetTimingBlock(__name__); } while(0) + +#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ CCProfilingBeginTimingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); } while(0) +#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ CCProfilingEndTimingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); } while(0) +#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ CCProfilingResetTimingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); } while(0) -#endif // CC_IS_RETINA_DISPLAY_SUPPORTED + +#else + +#define CC_PROFILER_DISPLAY_TIMERS() do {} while (0) +#define CC_PROFILER_PURGE_ALL() do {} while (0) + +#define CC_PROFILER_START(__name__) do {} while (0) +#define CC_PROFILER_STOP(__name__) do {} while (0) +#define CC_PROFILER_RESET(__name__) do {} while (0) + +#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do {} while(0) +#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do {} while(0) +#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do {} while(0) + +#define CC_PROFILER_START_INSTANCE(__id__, __name__) do {} while(0) +#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do {} while(0) +#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do {} while(0) + +#endif + +/*****************/ +/** ARC Macros **/ +/*****************/ +#if defined(__has_feature) && __has_feature(objc_arc) +// ARC (used for inline functions) +#define CC_ARC_RETAIN(value) value +#define CC_ARC_RELEASE(value) value = 0 +#define CC_ARC_UNSAFE_RETAINED __unsafe_unretained + +#else +// No ARC +#define CC_ARC_RETAIN(value) [value retain] +#define CC_ARC_RELEASE(value) [value release] +#define CC_ARC_UNSAFE_RETAINED +#endif + +/** @def CC_INCREMENT_GL_DRAWS_BY_ONE + Increments the GL Draws counts by one. + The number of calls per frame are displayed on the screen when the CCDirector's stats are enabled. + */ +extern NSUInteger __ccNumberOfDraws; +#define CC_INCREMENT_GL_DRAWS(__n__) __ccNumberOfDraws += __n__ + +/*******************/ +/** Notifications **/ +/*******************/ +/** @def CCAnimationFrameDisplayedNotification + Notification name when a CCSpriteFrame is displayed + */ +#define CCAnimationFrameDisplayedNotification @"CCAnimationFrameDisplayedNotification" diff --git a/Example/libs/cocos2d/ccTypes.h b/Example/libs/cocos2d/ccTypes.h index 65a73dd..1a71cb0 100644 --- a/Example/libs/cocos2d/ccTypes.h +++ b/Example/libs/cocos2d/ccTypes.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,10 +29,10 @@ cocos2d (cc) types */ -#import #import +#import "ccMacros.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import // CGPoint #endif @@ -102,6 +103,12 @@ typedef struct _ccColor4F { GLfloat b; GLfloat a; } ccColor4F; +//! helper that creates a ccColor4f type +static inline ccColor4F +ccc4f(const GLfloat r, const GLfloat g, const GLfloat b, const GLfloat a) +{ + return (ccColor4F){r, g, b, a}; +} /** Returns a ccColor4F from a ccColor3B. Alpha will be 1. @since v0.99.1 @@ -145,7 +152,7 @@ typedef struct _ccVertex3F GLfloat y; GLfloat z; } ccVertex3F; - + /** A texcoord composed of 2 floats: u, y @since v0.8 */ @@ -154,12 +161,12 @@ typedef struct _ccTex2F { GLfloat v; } ccTex2F; - + //! Point Sprite component typedef struct _ccPointSprite { ccVertex2F pos; // 8 bytes - ccColor4F colors; // 16 bytes + ccColor4B color; // 4 bytes GLfloat size; // 4 bytes } ccPointSprite; @@ -195,6 +202,17 @@ ccg(const NSInteger x, const NSInteger y) return v; } +//! a Point with a vertex point, a tex coord point and a color 4B +typedef struct _ccV2F_C4B_T2F +{ + //! vertices (2F) + ccVertex2F vertices; + //! colors (4B) + ccColor4B colors; + //! tex coords (2F) + ccTex2F texCoords; +} ccV2F_C4B_T2F; + //! a Point with a vertex point, a tex coord point and a color 4F typedef struct _ccV2F_C4F_T2F { @@ -206,6 +224,30 @@ typedef struct _ccV2F_C4F_T2F ccTex2F texCoords; } ccV2F_C4F_T2F; +//! a Point with a vertex point, a tex coord point and a color 4F +typedef struct _ccV3F_C4F_T2F +{ + //! vertices (3F) + ccVertex3F vertices; + //! colors (4F) + ccColor4F colors; + //! tex coords (2F) + ccTex2F texCoords; +} ccV3F_C4F_T2F; + +//! 4 ccV3F_C4F_T2F +typedef struct _ccV3F_C4F_T2F_Quad +{ + //! top left + ccV3F_C4F_T2F tl; + //! bottom left + ccV3F_C4F_T2F bl; + //! top right + ccV3F_C4F_T2F tr; + //! bottom right + ccV3F_C4F_T2F br; +} ccV3F_C4F_T2F_Quad; + //! a Point with a vertex point, a tex coord point and a color 4B typedef struct _ccV3F_C4B_T2F { @@ -221,6 +263,19 @@ typedef struct _ccV3F_C4B_T2F ccTex2F texCoords; // 8 byts } ccV3F_C4B_T2F; +//! 4 ccVertex2FTex2FColor4B Quad +typedef struct _ccV2F_C4B_T2F_Quad +{ + //! bottom left + ccV2F_C4B_T2F bl; + //! bottom right + ccV2F_C4B_T2F br; + //! top left + ccV2F_C4B_T2F tl; + //! top right + ccV2F_C4B_T2F tr; +} ccV2F_C4B_T2F_Quad; + //! 4 ccVertex3FTex2FColor4B typedef struct _ccV3F_C4B_T2F_Quad { @@ -256,7 +311,25 @@ typedef struct _ccBlendFunc GLenum dst; } ccBlendFunc; +//! ccResolutionType +typedef enum +{ + //! Unknonw resolution type + kCCResolutionUnknown, + //! iPhone resolution type + kCCResolutioniPhone, + //! RetinaDisplay resolution type + kCCResolutioniPhoneRetinaDisplay, + //! iPad resolution type + kCCResolutioniPad, + //! iPad Retina Display resolution type + kCCResolutioniPadRetinaDisplay, + +} ccResolutionType; + //! delta time type //! if you want more resolution redefine it as a double typedef float ccTime; //typedef double ccTime; + +typedef float ccMat4[16]; diff --git a/Example/libs/cocos2d/cocos2d.h b/Example/libs/cocos2d/cocos2d.h index 96a0e9c..17c6a9f 100644 --- a/Example/libs/cocos2d/cocos2d.h +++ b/Example/libs/cocos2d/cocos2d.h @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -38,10 +39,9 @@ */ // 0x00 HI ME LO -// 00 00 99 05 -#define COCOS2D_VERSION 0x00009905 +// 00 02 00 00 +#define COCOS2D_VERSION 0x00020000 -#import // // all cocos2d include files @@ -66,7 +66,6 @@ #import "CCAnimationCache.h" #import "CCSprite.h" #import "CCSpriteFrame.h" -#import "CCSpriteSheet.h" #import "CCSpriteBatchNode.h" #import "CCSpriteFrameCache.h" @@ -75,9 +74,9 @@ #import "CCLabelAtlas.h" #import "CCParticleSystem.h" -#import "CCParticleSystemPoint.h" #import "CCParticleSystemQuad.h" #import "CCParticleExamples.h" +#import "CCParticleBatchNode.h" #import "CCTexture2D.h" #import "CCTexturePVR.h" @@ -86,7 +85,7 @@ #import "CCTransition.h" #import "CCTransitionPageTurn.h" -#import "CCTransitionRadial.h" +#import "CCTransitionProgress.h" #import "CCTMXTiledMap.h" #import "CCTMXLayer.h" @@ -100,7 +99,6 @@ #import "CCDrawingPrimitives.h" #import "CCScene.h" #import "CCScheduler.h" -#import "CCBlockSupport.h" #import "CCCamera.h" #import "CCProtocols.h" #import "CCNode.h" @@ -113,27 +111,39 @@ #import "CCMotionStreak.h" #import "CCConfiguration.h" +// Shaders +#import "CCGLProgram.h" +#import "ccGLStateCache.h" +#import "CCShaderCache.h" +#import "ccShaders.h" + // // cocos2d macros // #import "ccTypes.h" #import "ccMacros.h" +// +// Deprecated methods/classes/functions since v1.0 +// +#import "ccDeprecated.h" // Platform common #import "Platforms/CCGL.h" #import "Platforms/CCNS.h" -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #import "Platforms/iOS/CCTouchDispatcher.h" #import "Platforms/iOS/CCTouchDelegateProtocol.h" #import "Platforms/iOS/CCTouchHandler.h" -#import "Platforms/iOS/EAGLView.h" +#import "Platforms/iOS/CCGLView.h" #import "Platforms/iOS/CCDirectorIOS.h" -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) -#import "Platforms/Mac/MacGLView.h" +#elif defined(__CC_PLATFORM_MAC) +#import "Platforms/Mac/CCGLView.h" #import "Platforms/Mac/CCDirectorMac.h" +#import "Platforms/Mac/CCWindow.h" +#import "Platforms/Mac/CCEventDispatcher.h" #endif // @@ -145,20 +155,21 @@ #import "Support/ccCArray.h" #import "Support/CCArray.h" #import "Support/ccUtils.h" - -#if CC_ENABLE_PROFILERS +#import "Support/TransformUtils.h" #import "Support/CCProfiling.h" -#endif // CC_ENABLE_PROFILERS +// +// external +// +#import "kazmath/kazmath.h" +#import "kazmath/GL/matrix.h" -// compatibility with v0.8 -#import "CCCompatibility.h" // free functions NSString * cocos2dVersion(void); -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED +#ifdef __CC_PLATFORM_IOS #ifndef __IPHONE_4_0 #error "If you are targeting iPad, you should set BASE SDK = 4.0 (or 4.1, or 4.2), and set the 'iOS deploy target' = 3.2" #endif diff --git a/Example/libs/cocos2d/cocos2d.m b/Example/libs/cocos2d/cocos2d.m index 619d367..197ec75 100644 --- a/Example/libs/cocos2d/cocos2d.m +++ b/Example/libs/cocos2d/cocos2d.m @@ -2,17 +2,18 @@ * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2008-2010 Ricardo Quesada - * + * Copyright (c) 2011 Zynga Inc. + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,10 +25,10 @@ #import - -static NSString *version = @"cocos2d v0.99.5"; +#import "cocos2d.h" +static NSString *version = @"cocos2d v2.0.0-rc0"; NSString *cocos2dVersion() -{ +{ return version; } diff --git a/TouchTrailLayer.h b/TouchTrailLayer.h index ee7c89c..570fde0 100644 --- a/TouchTrailLayer.h +++ b/TouchTrailLayer.h @@ -31,4 +31,5 @@ CFMutableDictionaryRef map; } ++ (CCScene *) scene; @end diff --git a/TouchTrailLayer.m b/TouchTrailLayer.m index 613e3b9..4ca654f 100644 --- a/TouchTrailLayer.m +++ b/TouchTrailLayer.m @@ -25,28 +25,26 @@ #import "TouchTrailLayer.h" -void releaseBlade(CFAllocatorRef allocator, const void *value) -{ - [(CCBlade*)value finish]; -} - -CFDictionaryValueCallBacks valueCallbacks = { - 0, - NULL, - releaseBlade, - NULL, - NULL -}; - @implementation TouchTrailLayer - (id) init{ self = [super init]; isTouchEnabled_ = 1; - map = CFDictionaryCreateMutable(NULL,0,NULL,&valueCallbacks); + map = CFDictionaryCreateMutable(NULL,0,NULL,NULL); + CCSprite *bg = [CCSprite spriteWithFile:@"Default.png"]; + bg.rotation = 90; + bg.position = ccp(240,160); + [self addChild:bg]; + return self; } ++ (CCScene *) scene{ + CCScene *scene = [CCScene node]; + [scene addChild:[self node]]; + return scene; +} + - (void) ccTouchesBegan:(NSSet *) touches withEvent:(UIEvent *) event{ for (UITouch *touch in touches) { CCBlade *w = [CCBlade bladeWithMaximumPoint:50]; @@ -75,7 +73,7 @@ - (void) ccTouchesMoved:(NSSet *) touches withEvent:(UIEvent *) event{ - (void) ccTouchesEnded:(NSSet *) touches withEvent:(UIEvent *) event{ for (UITouch *touch in touches) { CCBlade *w = (CCBlade *)CFDictionaryGetValue(map, touch); - [w dim:YES]; + [w finish]; CFDictionaryRemoveValue(map,touch); } } From 5cfe48825cca48890fed98c9edfa531490e992b7 Mon Sep 17 00:00:00 2001 From: Panajev Date: Mon, 10 Sep 2012 18:06:21 +0200 Subject: [PATCH 4/6] (+): converted the sample and the library to ARC. The example now uses Cocos2D as an external static library. Instructions on how to obtain the complete library package (CocosLib + CocosTools + Utilities), build it, and install it can be found here: https://github.com/Panajev/CocosLib#howto-install --- CCBlade.h | 2 +- CCBlade.m | 5 +- Example/Classes/ExampleAppDelegate.h | 6 +- Example/Classes/ExampleAppDelegate.m | 79 +- Example/Classes/HelloWorldLayer.m | 11 - Example/Example.xcodeproj/project.pbxproj | 1308 +------------- .../contents.xcworkspacedata | 7 + .../UserInterfaceState.xcuserstate | Bin 0 -> 32623 bytes .../WorkspaceSettings.xcsettings | 10 + .../xcdebugger/Breakpoints.xcbkptlist | 5 + .../xcschemes/Example.xcscheme | 86 + .../xcschemes/cocos2d libraries.xcscheme | 59 + .../xcschemes/xcschememanagement.plist | 32 + Example/LICENSE.cocos2d | 23 - Example/LICENSE.cocosdenshion | 21 - Example/libs/CocosDenshion/CDAudioManager.h | 241 --- Example/libs/CocosDenshion/CDAudioManager.m | 897 ---------- Example/libs/CocosDenshion/CDConfig.h | 60 - Example/libs/CocosDenshion/CDOpenALSupport.h | 77 - Example/libs/CocosDenshion/CDOpenALSupport.m | 246 --- Example/libs/CocosDenshion/CocosDenshion.h | 430 ----- Example/libs/CocosDenshion/CocosDenshion.m | 1570 ----------------- .../libs/CocosDenshion/SimpleAudioEngine.h | 90 - .../libs/CocosDenshion/SimpleAudioEngine.m | 222 --- Example/libs/FontLabel/FontLabel.h | 44 - Example/libs/FontLabel/FontLabel.m | 186 -- .../libs/FontLabel/FontLabelStringDrawing.h | 69 - .../libs/FontLabel/FontLabelStringDrawing.m | 890 ---------- Example/libs/FontLabel/FontManager.h | 85 - Example/libs/FontLabel/FontManager.m | 124 -- Example/libs/FontLabel/ZAttributedString.h | 77 - Example/libs/FontLabel/ZAttributedString.m | 595 ------- .../libs/FontLabel/ZAttributedStringPrivate.h | 24 - Example/libs/FontLabel/ZFont.h | 47 - Example/libs/FontLabel/ZFont.m | 171 -- Example/libs/TouchJSON/CDataScanner.h | 68 - Example/libs/TouchJSON/CDataScanner.m | 270 --- .../Extensions/CDataScanner_Extensions.h | 37 - .../Extensions/CDataScanner_Extensions.m | 80 - .../Extensions/NSCharacterSet_Extensions.h | 36 - .../Extensions/NSCharacterSet_Extensions.m | 48 - .../Extensions/NSDictionary_JSONExtensions.h | 36 - .../Extensions/NSDictionary_JSONExtensions.m | 41 - .../Extensions/NSScanner_Extensions.h | 44 - .../Extensions/NSScanner_Extensions.m | 118 -- .../libs/TouchJSON/JSON/CJSONDeserializer.h | 59 - .../libs/TouchJSON/JSON/CJSONDeserializer.m | 84 - Example/libs/TouchJSON/JSON/CJSONScanner.h | 43 - Example/libs/TouchJSON/JSON/CJSONScanner.m | 536 ------ Example/libs/TouchJSON/JSON/CJSONSerializer.h | 45 - Example/libs/TouchJSON/JSON/CJSONSerializer.m | 184 -- Example/libs/cocos2d/CCAction.h | 195 -- Example/libs/cocos2d/CCAction.m | 357 ---- Example/libs/cocos2d/CCActionCamera.h | 73 - Example/libs/cocos2d/CCActionCamera.m | 147 -- Example/libs/cocos2d/CCActionEase.h | 159 -- Example/libs/cocos2d/CCActionEase.m | 532 ------ Example/libs/cocos2d/CCActionGrid.h | 165 -- Example/libs/cocos2d/CCActionGrid.m | 386 ---- Example/libs/cocos2d/CCActionGrid3D.h | 205 --- Example/libs/cocos2d/CCActionGrid3D.m | 652 ------- Example/libs/cocos2d/CCActionInstant.h | 227 --- Example/libs/cocos2d/CCActionInstant.m | 510 ------ Example/libs/cocos2d/CCActionInterval.h | 431 ----- Example/libs/cocos2d/CCActionInterval.m | 1442 --------------- Example/libs/cocos2d/CCActionManager.h | 107 -- Example/libs/cocos2d/CCActionManager.m | 319 ---- Example/libs/cocos2d/CCActionPageTurn3D.h | 42 - Example/libs/cocos2d/CCActionPageTurn3D.m | 86 - Example/libs/cocos2d/CCActionProgressTimer.h | 59 - Example/libs/cocos2d/CCActionProgressTimer.m | 103 -- Example/libs/cocos2d/CCActionTiledGrid.h | 211 --- Example/libs/cocos2d/CCActionTiledGrid.m | 768 -------- Example/libs/cocos2d/CCActionTween.h | 62 - Example/libs/cocos2d/CCActionTween.m | 72 - Example/libs/cocos2d/CCAnimation.h | 150 -- Example/libs/cocos2d/CCAnimation.m | 200 --- Example/libs/cocos2d/CCAnimationCache.h | 74 - Example/libs/cocos2d/CCAnimationCache.m | 250 --- Example/libs/cocos2d/CCAtlasNode.h | 96 - Example/libs/cocos2d/CCAtlasNode.m | 209 --- Example/libs/cocos2d/CCCamera.h | 98 - Example/libs/cocos2d/CCCamera.m | 148 -- Example/libs/cocos2d/CCConfiguration.h | 118 -- Example/libs/cocos2d/CCConfiguration.m | 179 -- Example/libs/cocos2d/CCDirector.h | 332 ---- Example/libs/cocos2d/CCDirector.m | 606 ------- Example/libs/cocos2d/CCDrawingPrimitives.h | 114 -- Example/libs/cocos2d/CCDrawingPrimitives.m | 311 ---- Example/libs/cocos2d/CCGLProgram.h | 156 -- Example/libs/cocos2d/CCGLProgram.m | 395 ----- Example/libs/cocos2d/CCGrabber.h | 44 - Example/libs/cocos2d/CCGrabber.m | 99 -- Example/libs/cocos2d/CCGrid.h | 130 -- Example/libs/cocos2d/CCGrid.m | 572 ------ Example/libs/cocos2d/CCLabelAtlas.h | 57 - Example/libs/cocos2d/CCLabelAtlas.m | 181 -- Example/libs/cocos2d/CCLabelBMFont.h | 213 --- Example/libs/cocos2d/CCLabelBMFont.m | 930 ---------- Example/libs/cocos2d/CCLabelTTF.h | 87 - Example/libs/cocos2d/CCLabelTTF.m | 216 --- Example/libs/cocos2d/CCLayer.h | 280 --- Example/libs/cocos2d/CCLayer.m | 628 ------- Example/libs/cocos2d/CCMenu.h | 100 -- Example/libs/cocos2d/CCMenu.m | 554 ------ Example/libs/cocos2d/CCMenuItem.h | 423 ----- Example/libs/cocos2d/CCMenuItem.m | 854 --------- Example/libs/cocos2d/CCMotionStreak.h | 84 - Example/libs/cocos2d/CCMotionStreak.m | 272 --- Example/libs/cocos2d/CCNode.h | 571 ------ Example/libs/cocos2d/CCNode.m | 885 ---------- Example/libs/cocos2d/CCParallaxNode.h | 50 - Example/libs/cocos2d/CCParallaxNode.m | 161 -- Example/libs/cocos2d/CCParticleBatchNode.h | 99 -- Example/libs/cocos2d/CCParticleBatchNode.m | 473 ----- Example/libs/cocos2d/CCParticleExamples.h | 109 -- Example/libs/cocos2d/CCParticleExamples.m | 926 ---------- Example/libs/cocos2d/CCParticleSystem.h | 449 ----- Example/libs/cocos2d/CCParticleSystem.m | 872 --------- Example/libs/cocos2d/CCParticleSystemQuad.h | 75 - Example/libs/cocos2d/CCParticleSystemQuad.m | 502 ------ Example/libs/cocos2d/CCProgressTimer.h | 94 - Example/libs/cocos2d/CCProgressTimer.m | 540 ------ Example/libs/cocos2d/CCProtocols.h | 132 -- Example/libs/cocos2d/CCRenderTexture.h | 117 -- Example/libs/cocos2d/CCRenderTexture.m | 356 ---- Example/libs/cocos2d/CCScene.h | 43 - Example/libs/cocos2d/CCScene.m | 45 - Example/libs/cocos2d/CCScheduler.h | 200 --- Example/libs/cocos2d/CCScheduler.m | 688 -------- Example/libs/cocos2d/CCShaderCache.h | 60 - Example/libs/cocos2d/CCShaderCache.m | 214 --- Example/libs/cocos2d/CCSprite.h | 288 --- Example/libs/cocos2d/CCSprite.m | 951 ---------- Example/libs/cocos2d/CCSpriteBatchNode.h | 138 -- Example/libs/cocos2d/CCSpriteBatchNode.m | 663 ------- Example/libs/cocos2d/CCSpriteFrame.h | 126 -- Example/libs/cocos2d/CCSpriteFrame.m | 183 -- Example/libs/cocos2d/CCSpriteFrameCache.h | 133 -- Example/libs/cocos2d/CCSpriteFrameCache.m | 375 ---- Example/libs/cocos2d/CCTMXLayer.h | 164 -- Example/libs/cocos2d/CCTMXLayer.m | 658 ------- Example/libs/cocos2d/CCTMXObjectGroup.h | 67 - Example/libs/cocos2d/CCTMXObjectGroup.m | 86 - Example/libs/cocos2d/CCTMXTiledMap.h | 145 -- Example/libs/cocos2d/CCTMXTiledMap.m | 217 --- Example/libs/cocos2d/CCTMXXMLParser.h | 226 --- Example/libs/cocos2d/CCTMXXMLParser.m | 523 ------ Example/libs/cocos2d/CCTexture2D.h | 338 ---- Example/libs/cocos2d/CCTexture2D.m | 827 --------- Example/libs/cocos2d/CCTextureAtlas.h | 188 -- Example/libs/cocos2d/CCTextureAtlas.m | 545 ------ Example/libs/cocos2d/CCTextureCache.h | 146 -- Example/libs/cocos2d/CCTextureCache.m | 505 ------ Example/libs/cocos2d/CCTexturePVR.h | 127 -- Example/libs/cocos2d/CCTexturePVR.m | 429 ----- Example/libs/cocos2d/CCTileMapAtlas.h | 83 - Example/libs/cocos2d/CCTileMapAtlas.m | 245 --- Example/libs/cocos2d/CCTransition.h | 296 ---- Example/libs/cocos2d/CCTransition.m | 1067 ----------- Example/libs/cocos2d/CCTransitionPageTurn.h | 60 - Example/libs/cocos2d/CCTransitionPageTurn.m | 117 -- Example/libs/cocos2d/CCTransitionProgress.h | 62 - Example/libs/cocos2d/CCTransitionProgress.m | 276 --- Example/libs/cocos2d/Platforms/CCGL.h | 59 - Example/libs/cocos2d/Platforms/CCNS.h | 78 - .../cocos2d/Platforms/Mac/CCDirectorMac.h | 110 -- .../cocos2d/Platforms/Mac/CCDirectorMac.m | 555 ------ .../cocos2d/Platforms/Mac/CCEventDispatcher.h | 283 --- .../cocos2d/Platforms/Mac/CCEventDispatcher.m | 694 -------- Example/libs/cocos2d/Platforms/Mac/CCGLView.h | 92 - Example/libs/cocos2d/Platforms/Mac/CCGLView.m | 287 --- Example/libs/cocos2d/Platforms/Mac/CCWindow.h | 41 - Example/libs/cocos2d/Platforms/Mac/CCWindow.m | 69 - .../cocos2d/Platforms/iOS/CCDirectorIOS.h | 104 -- .../cocos2d/Platforms/iOS/CCDirectorIOS.m | 552 ------ .../cocos2d/Platforms/iOS/CCES2Renderer.h | 83 - .../cocos2d/Platforms/iOS/CCES2Renderer.m | 248 --- .../libs/cocos2d/Platforms/iOS/CCESRenderer.h | 54 - Example/libs/cocos2d/Platforms/iOS/CCGLView.h | 160 -- Example/libs/cocos2d/Platforms/iOS/CCGLView.m | 360 ---- .../Platforms/iOS/CCTouchDelegateProtocol.h | 75 - .../cocos2d/Platforms/iOS/CCTouchDispatcher.h | 120 -- .../cocos2d/Platforms/iOS/CCTouchDispatcher.m | 341 ---- .../cocos2d/Platforms/iOS/CCTouchHandler.h | 93 - .../cocos2d/Platforms/iOS/CCTouchHandler.m | 135 -- Example/libs/cocos2d/Support/CCArray.h | 106 -- Example/libs/cocos2d/Support/CCArray.m | 304 ---- Example/libs/cocos2d/Support/CCFileUtils.h | 132 -- Example/libs/cocos2d/Support/CCFileUtils.m | 319 ---- Example/libs/cocos2d/Support/CCProfiling.h | 89 - Example/libs/cocos2d/Support/CCProfiling.m | 186 -- Example/libs/cocos2d/Support/CCVertex.h | 36 - Example/libs/cocos2d/Support/CCVertex.m | 138 -- .../libs/cocos2d/Support/CGPointExtension.h | 344 ---- .../libs/cocos2d/Support/CGPointExtension.m | 196 -- .../cocos2d/Support/NSThread+performBlock.h | 22 - .../cocos2d/Support/NSThread+performBlock.m | 76 - .../libs/cocos2d/Support/OpenGL_Internal.h | 86 - Example/libs/cocos2d/Support/TGAlib.h | 55 - Example/libs/cocos2d/Support/TGAlib.m | 274 --- Example/libs/cocos2d/Support/TransformUtils.h | 37 - Example/libs/cocos2d/Support/TransformUtils.m | 47 - Example/libs/cocos2d/Support/ZipUtils.h | 91 - Example/libs/cocos2d/Support/ZipUtils.m | 250 --- Example/libs/cocos2d/Support/base64.c | 93 - Example/libs/cocos2d/Support/base64.h | 33 - Example/libs/cocos2d/Support/ccCArray.h | 460 ----- Example/libs/cocos2d/Support/ccUtils.c | 20 - Example/libs/cocos2d/Support/ccUtils.h | 36 - Example/libs/cocos2d/Support/uthash.h | 972 ---------- Example/libs/cocos2d/Support/utlist.h | 490 ----- Example/libs/cocos2d/ccConfig.h | 245 --- Example/libs/cocos2d/ccDeprecated.h | 219 --- Example/libs/cocos2d/ccDeprecated.m | 328 ---- Example/libs/cocos2d/ccGLStateCache.h | 143 -- Example/libs/cocos2d/ccGLStateCache.m | 226 --- Example/libs/cocos2d/ccMacros.h | 342 ---- .../cocos2d/ccShader_PositionColor_frag.h | 12 - .../cocos2d/ccShader_PositionColor_vert.h | 17 - .../ccShader_PositionTextureA8Color_frag.h | 16 - .../ccShader_PositionTextureA8Color_vert.h | 21 - ...hader_PositionTextureColorAlphaTest_frag.h | 23 - .../ccShader_PositionTextureColor_frag.h | 14 - .../ccShader_PositionTextureColor_vert.h | 22 - .../cocos2d/ccShader_PositionTexture_frag.h | 13 - .../ccShader_PositionTexture_uColor_frag.h | 16 - .../ccShader_PositionTexture_uColor_vert.h | 18 - .../cocos2d/ccShader_PositionTexture_vert.h | 17 - .../cocos2d/ccShader_Position_uColor_frag.h | 12 - .../cocos2d/ccShader_Position_uColor_vert.h | 19 - Example/libs/cocos2d/ccShaders.h | 45 - Example/libs/cocos2d/ccShaders.m | 65 - Example/libs/cocos2d/ccTypes.h | 335 ---- Example/libs/cocos2d/cocos2d.h | 176 -- Example/libs/cocos2d/cocos2d.m | 34 - Example/libs/cocoslive/CLScoreServerPost.h | 141 -- Example/libs/cocoslive/CLScoreServerPost.m | 332 ---- Example/libs/cocoslive/CLScoreServerRequest.h | 121 -- Example/libs/cocoslive/CLScoreServerRequest.m | 256 --- Example/libs/cocoslive/cocoslive.h | 42 - Example/libs/cocoslive/cocoslive.m | 34 - .../kazmath/include/kazmath/GL/mat4stack.h | 51 - .../libs/kazmath/include/kazmath/GL/matrix.h | 58 - Example/libs/kazmath/include/kazmath/aabb.h | 53 - .../libs/kazmath/include/kazmath/kazmath.h | 39 - Example/libs/kazmath/include/kazmath/mat3.h | 75 - Example/libs/kazmath/include/kazmath/mat4.h | 93 - .../include/kazmath/neon_matrix_impl.h | 41 - Example/libs/kazmath/include/kazmath/plane.h | 70 - .../libs/kazmath/include/kazmath/quaternion.h | 113 -- Example/libs/kazmath/include/kazmath/ray2.h | 50 - .../libs/kazmath/include/kazmath/utility.h | 74 - Example/libs/kazmath/include/kazmath/vec2.h | 64 - Example/libs/kazmath/include/kazmath/vec3.h | 68 - Example/libs/kazmath/include/kazmath/vec4.h | 68 - Example/libs/kazmath/src/CMakeLists.txt | 14 - Example/libs/kazmath/src/ChangeLog | 738 -------- Example/libs/kazmath/src/GL/mat4stack.c | 74 - Example/libs/kazmath/src/GL/matrix.c | 191 -- Example/libs/kazmath/src/aabb.c | 63 - Example/libs/kazmath/src/mat3.c | 372 ---- Example/libs/kazmath/src/mat4.c | 789 --------- Example/libs/kazmath/src/neon_matrix_impl.c | 97 - Example/libs/kazmath/src/plane.c | 175 -- Example/libs/kazmath/src/quaternion.c | 582 ------ Example/libs/kazmath/src/ray2.c | 184 -- Example/libs/kazmath/src/utility.c | 59 - Example/libs/kazmath/src/vec2.c | 118 -- Example/libs/kazmath/src/vec3.c | 310 ---- Example/libs/kazmath/src/vec4.c | 154 -- Example/main.m | 8 +- TouchTrailLayer.m | 9 +- 273 files changed, 260 insertions(+), 61296 deletions(-) create mode 100644 Example/Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 Example/Example.xcodeproj/project.xcworkspace/xcuserdata/Panajev.xcuserdatad/UserInterfaceState.xcuserstate create mode 100644 Example/Example.xcodeproj/project.xcworkspace/xcuserdata/Panajev.xcuserdatad/WorkspaceSettings.xcsettings create mode 100644 Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist create mode 100644 Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/Example.xcscheme create mode 100644 Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/cocos2d libraries.xcscheme create mode 100644 Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/xcschememanagement.plist delete mode 100644 Example/LICENSE.cocos2d delete mode 100644 Example/LICENSE.cocosdenshion delete mode 100644 Example/libs/CocosDenshion/CDAudioManager.h delete mode 100644 Example/libs/CocosDenshion/CDAudioManager.m delete mode 100644 Example/libs/CocosDenshion/CDConfig.h delete mode 100644 Example/libs/CocosDenshion/CDOpenALSupport.h delete mode 100644 Example/libs/CocosDenshion/CDOpenALSupport.m delete mode 100644 Example/libs/CocosDenshion/CocosDenshion.h delete mode 100644 Example/libs/CocosDenshion/CocosDenshion.m delete mode 100644 Example/libs/CocosDenshion/SimpleAudioEngine.h delete mode 100644 Example/libs/CocosDenshion/SimpleAudioEngine.m delete mode 100644 Example/libs/FontLabel/FontLabel.h delete mode 100644 Example/libs/FontLabel/FontLabel.m delete mode 100644 Example/libs/FontLabel/FontLabelStringDrawing.h delete mode 100644 Example/libs/FontLabel/FontLabelStringDrawing.m delete mode 100644 Example/libs/FontLabel/FontManager.h delete mode 100644 Example/libs/FontLabel/FontManager.m delete mode 100644 Example/libs/FontLabel/ZAttributedString.h delete mode 100644 Example/libs/FontLabel/ZAttributedString.m delete mode 100644 Example/libs/FontLabel/ZAttributedStringPrivate.h delete mode 100644 Example/libs/FontLabel/ZFont.h delete mode 100644 Example/libs/FontLabel/ZFont.m delete mode 100644 Example/libs/TouchJSON/CDataScanner.h delete mode 100644 Example/libs/TouchJSON/CDataScanner.m delete mode 100644 Example/libs/TouchJSON/Extensions/CDataScanner_Extensions.h delete mode 100644 Example/libs/TouchJSON/Extensions/CDataScanner_Extensions.m delete mode 100644 Example/libs/TouchJSON/Extensions/NSCharacterSet_Extensions.h delete mode 100644 Example/libs/TouchJSON/Extensions/NSCharacterSet_Extensions.m delete mode 100644 Example/libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.h delete mode 100644 Example/libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.m delete mode 100644 Example/libs/TouchJSON/Extensions/NSScanner_Extensions.h delete mode 100644 Example/libs/TouchJSON/Extensions/NSScanner_Extensions.m delete mode 100644 Example/libs/TouchJSON/JSON/CJSONDeserializer.h delete mode 100644 Example/libs/TouchJSON/JSON/CJSONDeserializer.m delete mode 100644 Example/libs/TouchJSON/JSON/CJSONScanner.h delete mode 100644 Example/libs/TouchJSON/JSON/CJSONScanner.m delete mode 100644 Example/libs/TouchJSON/JSON/CJSONSerializer.h delete mode 100644 Example/libs/TouchJSON/JSON/CJSONSerializer.m delete mode 100644 Example/libs/cocos2d/CCAction.h delete mode 100644 Example/libs/cocos2d/CCAction.m delete mode 100644 Example/libs/cocos2d/CCActionCamera.h delete mode 100644 Example/libs/cocos2d/CCActionCamera.m delete mode 100644 Example/libs/cocos2d/CCActionEase.h delete mode 100644 Example/libs/cocos2d/CCActionEase.m delete mode 100644 Example/libs/cocos2d/CCActionGrid.h delete mode 100644 Example/libs/cocos2d/CCActionGrid.m delete mode 100644 Example/libs/cocos2d/CCActionGrid3D.h delete mode 100644 Example/libs/cocos2d/CCActionGrid3D.m delete mode 100644 Example/libs/cocos2d/CCActionInstant.h delete mode 100644 Example/libs/cocos2d/CCActionInstant.m delete mode 100644 Example/libs/cocos2d/CCActionInterval.h delete mode 100644 Example/libs/cocos2d/CCActionInterval.m delete mode 100644 Example/libs/cocos2d/CCActionManager.h delete mode 100644 Example/libs/cocos2d/CCActionManager.m delete mode 100644 Example/libs/cocos2d/CCActionPageTurn3D.h delete mode 100644 Example/libs/cocos2d/CCActionPageTurn3D.m delete mode 100644 Example/libs/cocos2d/CCActionProgressTimer.h delete mode 100644 Example/libs/cocos2d/CCActionProgressTimer.m delete mode 100644 Example/libs/cocos2d/CCActionTiledGrid.h delete mode 100644 Example/libs/cocos2d/CCActionTiledGrid.m delete mode 100644 Example/libs/cocos2d/CCActionTween.h delete mode 100644 Example/libs/cocos2d/CCActionTween.m delete mode 100644 Example/libs/cocos2d/CCAnimation.h delete mode 100644 Example/libs/cocos2d/CCAnimation.m delete mode 100644 Example/libs/cocos2d/CCAnimationCache.h delete mode 100644 Example/libs/cocos2d/CCAnimationCache.m delete mode 100644 Example/libs/cocos2d/CCAtlasNode.h delete mode 100644 Example/libs/cocos2d/CCAtlasNode.m delete mode 100644 Example/libs/cocos2d/CCCamera.h delete mode 100644 Example/libs/cocos2d/CCCamera.m delete mode 100644 Example/libs/cocos2d/CCConfiguration.h delete mode 100644 Example/libs/cocos2d/CCConfiguration.m delete mode 100644 Example/libs/cocos2d/CCDirector.h delete mode 100644 Example/libs/cocos2d/CCDirector.m delete mode 100644 Example/libs/cocos2d/CCDrawingPrimitives.h delete mode 100644 Example/libs/cocos2d/CCDrawingPrimitives.m delete mode 100644 Example/libs/cocos2d/CCGLProgram.h delete mode 100644 Example/libs/cocos2d/CCGLProgram.m delete mode 100644 Example/libs/cocos2d/CCGrabber.h delete mode 100644 Example/libs/cocos2d/CCGrabber.m delete mode 100644 Example/libs/cocos2d/CCGrid.h delete mode 100644 Example/libs/cocos2d/CCGrid.m delete mode 100644 Example/libs/cocos2d/CCLabelAtlas.h delete mode 100644 Example/libs/cocos2d/CCLabelAtlas.m delete mode 100644 Example/libs/cocos2d/CCLabelBMFont.h delete mode 100644 Example/libs/cocos2d/CCLabelBMFont.m delete mode 100644 Example/libs/cocos2d/CCLabelTTF.h delete mode 100644 Example/libs/cocos2d/CCLabelTTF.m delete mode 100644 Example/libs/cocos2d/CCLayer.h delete mode 100644 Example/libs/cocos2d/CCLayer.m delete mode 100644 Example/libs/cocos2d/CCMenu.h delete mode 100644 Example/libs/cocos2d/CCMenu.m delete mode 100644 Example/libs/cocos2d/CCMenuItem.h delete mode 100644 Example/libs/cocos2d/CCMenuItem.m delete mode 100644 Example/libs/cocos2d/CCMotionStreak.h delete mode 100644 Example/libs/cocos2d/CCMotionStreak.m delete mode 100644 Example/libs/cocos2d/CCNode.h delete mode 100644 Example/libs/cocos2d/CCNode.m delete mode 100644 Example/libs/cocos2d/CCParallaxNode.h delete mode 100644 Example/libs/cocos2d/CCParallaxNode.m delete mode 100644 Example/libs/cocos2d/CCParticleBatchNode.h delete mode 100644 Example/libs/cocos2d/CCParticleBatchNode.m delete mode 100644 Example/libs/cocos2d/CCParticleExamples.h delete mode 100644 Example/libs/cocos2d/CCParticleExamples.m delete mode 100644 Example/libs/cocos2d/CCParticleSystem.h delete mode 100644 Example/libs/cocos2d/CCParticleSystem.m delete mode 100644 Example/libs/cocos2d/CCParticleSystemQuad.h delete mode 100644 Example/libs/cocos2d/CCParticleSystemQuad.m delete mode 100644 Example/libs/cocos2d/CCProgressTimer.h delete mode 100644 Example/libs/cocos2d/CCProgressTimer.m delete mode 100644 Example/libs/cocos2d/CCProtocols.h delete mode 100644 Example/libs/cocos2d/CCRenderTexture.h delete mode 100644 Example/libs/cocos2d/CCRenderTexture.m delete mode 100644 Example/libs/cocos2d/CCScene.h delete mode 100644 Example/libs/cocos2d/CCScene.m delete mode 100644 Example/libs/cocos2d/CCScheduler.h delete mode 100644 Example/libs/cocos2d/CCScheduler.m delete mode 100644 Example/libs/cocos2d/CCShaderCache.h delete mode 100644 Example/libs/cocos2d/CCShaderCache.m delete mode 100644 Example/libs/cocos2d/CCSprite.h delete mode 100644 Example/libs/cocos2d/CCSprite.m delete mode 100644 Example/libs/cocos2d/CCSpriteBatchNode.h delete mode 100644 Example/libs/cocos2d/CCSpriteBatchNode.m delete mode 100644 Example/libs/cocos2d/CCSpriteFrame.h delete mode 100644 Example/libs/cocos2d/CCSpriteFrame.m delete mode 100644 Example/libs/cocos2d/CCSpriteFrameCache.h delete mode 100644 Example/libs/cocos2d/CCSpriteFrameCache.m delete mode 100644 Example/libs/cocos2d/CCTMXLayer.h delete mode 100644 Example/libs/cocos2d/CCTMXLayer.m delete mode 100644 Example/libs/cocos2d/CCTMXObjectGroup.h delete mode 100644 Example/libs/cocos2d/CCTMXObjectGroup.m delete mode 100644 Example/libs/cocos2d/CCTMXTiledMap.h delete mode 100644 Example/libs/cocos2d/CCTMXTiledMap.m delete mode 100644 Example/libs/cocos2d/CCTMXXMLParser.h delete mode 100644 Example/libs/cocos2d/CCTMXXMLParser.m delete mode 100644 Example/libs/cocos2d/CCTexture2D.h delete mode 100644 Example/libs/cocos2d/CCTexture2D.m delete mode 100644 Example/libs/cocos2d/CCTextureAtlas.h delete mode 100644 Example/libs/cocos2d/CCTextureAtlas.m delete mode 100644 Example/libs/cocos2d/CCTextureCache.h delete mode 100644 Example/libs/cocos2d/CCTextureCache.m delete mode 100644 Example/libs/cocos2d/CCTexturePVR.h delete mode 100644 Example/libs/cocos2d/CCTexturePVR.m delete mode 100644 Example/libs/cocos2d/CCTileMapAtlas.h delete mode 100644 Example/libs/cocos2d/CCTileMapAtlas.m delete mode 100644 Example/libs/cocos2d/CCTransition.h delete mode 100644 Example/libs/cocos2d/CCTransition.m delete mode 100644 Example/libs/cocos2d/CCTransitionPageTurn.h delete mode 100644 Example/libs/cocos2d/CCTransitionPageTurn.m delete mode 100644 Example/libs/cocos2d/CCTransitionProgress.h delete mode 100644 Example/libs/cocos2d/CCTransitionProgress.m delete mode 100644 Example/libs/cocos2d/Platforms/CCGL.h delete mode 100644 Example/libs/cocos2d/Platforms/CCNS.h delete mode 100644 Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.h delete mode 100644 Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.m delete mode 100644 Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.h delete mode 100644 Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.m delete mode 100644 Example/libs/cocos2d/Platforms/Mac/CCGLView.h delete mode 100644 Example/libs/cocos2d/Platforms/Mac/CCGLView.m delete mode 100644 Example/libs/cocos2d/Platforms/Mac/CCWindow.h delete mode 100644 Example/libs/cocos2d/Platforms/Mac/CCWindow.m delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.m delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCESRenderer.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCGLView.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCGLView.m delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.h delete mode 100644 Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.m delete mode 100644 Example/libs/cocos2d/Support/CCArray.h delete mode 100644 Example/libs/cocos2d/Support/CCArray.m delete mode 100644 Example/libs/cocos2d/Support/CCFileUtils.h delete mode 100644 Example/libs/cocos2d/Support/CCFileUtils.m delete mode 100644 Example/libs/cocos2d/Support/CCProfiling.h delete mode 100644 Example/libs/cocos2d/Support/CCProfiling.m delete mode 100644 Example/libs/cocos2d/Support/CCVertex.h delete mode 100644 Example/libs/cocos2d/Support/CCVertex.m delete mode 100644 Example/libs/cocos2d/Support/CGPointExtension.h delete mode 100644 Example/libs/cocos2d/Support/CGPointExtension.m delete mode 100644 Example/libs/cocos2d/Support/NSThread+performBlock.h delete mode 100644 Example/libs/cocos2d/Support/NSThread+performBlock.m delete mode 100644 Example/libs/cocos2d/Support/OpenGL_Internal.h delete mode 100644 Example/libs/cocos2d/Support/TGAlib.h delete mode 100644 Example/libs/cocos2d/Support/TGAlib.m delete mode 100644 Example/libs/cocos2d/Support/TransformUtils.h delete mode 100644 Example/libs/cocos2d/Support/TransformUtils.m delete mode 100644 Example/libs/cocos2d/Support/ZipUtils.h delete mode 100644 Example/libs/cocos2d/Support/ZipUtils.m delete mode 100644 Example/libs/cocos2d/Support/base64.c delete mode 100644 Example/libs/cocos2d/Support/base64.h delete mode 100644 Example/libs/cocos2d/Support/ccCArray.h delete mode 100644 Example/libs/cocos2d/Support/ccUtils.c delete mode 100644 Example/libs/cocos2d/Support/ccUtils.h delete mode 100644 Example/libs/cocos2d/Support/uthash.h delete mode 100644 Example/libs/cocos2d/Support/utlist.h delete mode 100644 Example/libs/cocos2d/ccConfig.h delete mode 100644 Example/libs/cocos2d/ccDeprecated.h delete mode 100644 Example/libs/cocos2d/ccDeprecated.m delete mode 100644 Example/libs/cocos2d/ccGLStateCache.h delete mode 100644 Example/libs/cocos2d/ccGLStateCache.m delete mode 100644 Example/libs/cocos2d/ccMacros.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionColor_frag.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionColor_vert.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionTextureA8Color_frag.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionTextureA8Color_vert.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionTextureColorAlphaTest_frag.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionTextureColor_frag.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionTextureColor_vert.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionTexture_frag.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionTexture_uColor_frag.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionTexture_uColor_vert.h delete mode 100644 Example/libs/cocos2d/ccShader_PositionTexture_vert.h delete mode 100644 Example/libs/cocos2d/ccShader_Position_uColor_frag.h delete mode 100644 Example/libs/cocos2d/ccShader_Position_uColor_vert.h delete mode 100644 Example/libs/cocos2d/ccShaders.h delete mode 100644 Example/libs/cocos2d/ccShaders.m delete mode 100644 Example/libs/cocos2d/ccTypes.h delete mode 100644 Example/libs/cocos2d/cocos2d.h delete mode 100644 Example/libs/cocos2d/cocos2d.m delete mode 100644 Example/libs/cocoslive/CLScoreServerPost.h delete mode 100644 Example/libs/cocoslive/CLScoreServerPost.m delete mode 100644 Example/libs/cocoslive/CLScoreServerRequest.h delete mode 100644 Example/libs/cocoslive/CLScoreServerRequest.m delete mode 100644 Example/libs/cocoslive/cocoslive.h delete mode 100644 Example/libs/cocoslive/cocoslive.m delete mode 100644 Example/libs/kazmath/include/kazmath/GL/mat4stack.h delete mode 100644 Example/libs/kazmath/include/kazmath/GL/matrix.h delete mode 100644 Example/libs/kazmath/include/kazmath/aabb.h delete mode 100644 Example/libs/kazmath/include/kazmath/kazmath.h delete mode 100644 Example/libs/kazmath/include/kazmath/mat3.h delete mode 100644 Example/libs/kazmath/include/kazmath/mat4.h delete mode 100644 Example/libs/kazmath/include/kazmath/neon_matrix_impl.h delete mode 100644 Example/libs/kazmath/include/kazmath/plane.h delete mode 100644 Example/libs/kazmath/include/kazmath/quaternion.h delete mode 100644 Example/libs/kazmath/include/kazmath/ray2.h delete mode 100644 Example/libs/kazmath/include/kazmath/utility.h delete mode 100644 Example/libs/kazmath/include/kazmath/vec2.h delete mode 100644 Example/libs/kazmath/include/kazmath/vec3.h delete mode 100644 Example/libs/kazmath/include/kazmath/vec4.h delete mode 100644 Example/libs/kazmath/src/CMakeLists.txt delete mode 100644 Example/libs/kazmath/src/ChangeLog delete mode 100644 Example/libs/kazmath/src/GL/mat4stack.c delete mode 100644 Example/libs/kazmath/src/GL/matrix.c delete mode 100644 Example/libs/kazmath/src/aabb.c delete mode 100644 Example/libs/kazmath/src/mat3.c delete mode 100644 Example/libs/kazmath/src/mat4.c delete mode 100644 Example/libs/kazmath/src/neon_matrix_impl.c delete mode 100644 Example/libs/kazmath/src/plane.c delete mode 100644 Example/libs/kazmath/src/quaternion.c delete mode 100644 Example/libs/kazmath/src/ray2.c delete mode 100644 Example/libs/kazmath/src/utility.c delete mode 100644 Example/libs/kazmath/src/vec2.c delete mode 100644 Example/libs/kazmath/src/vec3.c delete mode 100644 Example/libs/kazmath/src/vec4.c diff --git a/CCBlade.h b/CCBlade.h index a5de4eb..4b1a073 100644 --- a/CCBlade.h +++ b/CCBlade.h @@ -47,7 +47,7 @@ inline void f1(CGPoint p1, CGPoint p2, float d, CGPoint *o1, CGPoint *o2); BOOL willPop; } @property (readonly) unsigned int pointLimit; -@property(retain) CCTexture2D *texture; +@property(strong) CCTexture2D *texture; @property(nonatomic) float width; @property (nonatomic) BOOL autoDim; diff --git a/CCBlade.m b/CCBlade.m index c5c62dd..2fe3cd5 100644 --- a/CCBlade.m +++ b/CCBlade.m @@ -66,7 +66,7 @@ @implementation CCBlade @synthesize autoDim; + (id) bladeWithMaximumPoint:(int) limit{ - return [[[self alloc] initWithMaximumPoint:limit] autorelease]; + return [[self alloc] initWithMaximumPoint:limit]; } - (id) initWithMaximumPoint:(int) limit{ @@ -90,12 +90,9 @@ - (id) initWithMaximumPoint:(int) limit{ } - (void) dealloc{ - [_texture release]; free(vertices); free(coordinates); - [path release]; - [super dealloc]; } - (void) populateVertices{ diff --git a/Example/Classes/ExampleAppDelegate.h b/Example/Classes/ExampleAppDelegate.h index 5e91569..f0cf408 100644 --- a/Example/Classes/ExampleAppDelegate.h +++ b/Example/Classes/ExampleAppDelegate.h @@ -13,12 +13,12 @@ UIWindow *window_; UINavigationController *navController_; - CCDirectorIOS *director_; // weak ref + CCDirectorIOS *__unsafe_unretained director_; // weak ref } -@property (nonatomic, retain) UIWindow *window; +@property (nonatomic, strong) UIWindow *window; @property (readonly) UINavigationController *navController; -@property (readonly) CCDirectorIOS *director; +@property (unsafe_unretained, readonly) CCDirectorIOS *director; @end diff --git a/Example/Classes/ExampleAppDelegate.m b/Example/Classes/ExampleAppDelegate.m index 4cb64a5..fe0f677 100644 --- a/Example/Classes/ExampleAppDelegate.m +++ b/Example/Classes/ExampleAppDelegate.m @@ -20,8 +20,8 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( { // Create the main window window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; - - + + // Create an CCGLView with a RGB565 color buffer, and a depth buffer of 0-bits CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds] pixelFormat:kEAGLColorFormatRGB565 //kEAGLColorFormatRGBA8 @@ -31,58 +31,66 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( multiSampling:NO numberOfSamples:0]; - director_ = (CCDirectorIOS*) [CCDirector sharedDirector]; + // Enable multiple touches + [glView setMultipleTouchEnabled:YES]; + director_ = (CCDirectorIOS*) [CCDirector sharedDirector]; + director_.wantsFullScreenLayout = YES; - + // Display FSP and SPF - [director_ setDisplayStats:YES]; - + [director_ setDisplayStats:NO]; + // set FPS at 60 [director_ setAnimationInterval:1.0/60]; - + // attach the openglView to the director [director_ setView:glView]; - + // for rotation and other messages [director_ setDelegate:self]; - + // 2D projection [director_ setProjection:kCCDirectorProjection2D]; - // [director setProjection:kCCDirectorProjection3D]; - + // [director setProjection:kCCDirectorProjection3D]; + // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices if( ! [director_ enableRetinaDisplay:YES] ) CCLOG(@"Retina Display Not supported"); - - // Create a Navigation Controller with the Director - navController_ = [[UINavigationController alloc] initWithRootViewController:director_]; - navController_.navigationBarHidden = YES; - - // set the Navigation Controller as the root view controller - // [window_ setRootViewController:rootViewController_]; - [window_ addSubview:navController_.view]; - - // make main window visible - [window_ makeKeyAndVisible]; - + // Default texture format for PNG/BMP/TIFF/JPEG/GIF images // It can be RGBA8888, RGBA4444, RGB5_A1, RGB565 // You can change anytime. [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888]; - - // When in iPhone RetinaDisplay, iPad, iPad RetinaDisplay mode, CCFileUtils will append the "-hd", "-ipad", "-ipadhd" to all loaded files - // If the -hd, -ipad, -ipadhd files are not found, it will load the non-suffixed version - [CCFileUtils setiPhoneRetinaDisplaySuffix:@"-hd"]; // Default on iPhone RetinaDisplay is "-hd" - [CCFileUtils setiPadSuffix:@"-ipad"]; // Default on iPad is "" (empty string) - [CCFileUtils setiPadRetinaDisplaySuffix:@"-ipadhd"]; // Default on iPad RetinaDisplay is "-ipadhd" - + + // If the 1st suffix is not found and if fallback is enabled then fallback suffixes are going to searched. If none is found, it will try with the name without suffix. + // On iPad HD : "-ipadhd", "-ipad", "-hd" + // On iPad : "-ipad", "-hd" + // On iPhone HD: "-hd" + CCFileUtils *sharedFileUtils = [CCFileUtils sharedFileUtils]; + [sharedFileUtils setEnableFallbackSuffixes:NO]; // Default: NO. No fallback suffixes are going to be used + [sharedFileUtils setiPhoneRetinaDisplaySuffix:@"-hd"]; // Default on iPhone RetinaDisplay is "-hd" + [sharedFileUtils setiPadSuffix:@"-ipad"]; // Default on iPad is "ipad" + [sharedFileUtils setiPadRetinaDisplaySuffix:@"-ipadhd"]; // Default on iPad RetinaDisplay is "-ipadhd" + // Assume that PVR images have premultiplied alpha [CCTexture2D PVRImagesHavePremultipliedAlpha:YES]; - + // and add the scene to the stack. The director will run it when it automatically when the view is displayed. [director_ pushScene: [TouchTrailLayer scene]]; - + + + // Create a Navigation Controller with the Director + navController_ = [[UINavigationController alloc] initWithRootViewController:director_]; + navController_.navigationBarHidden = YES; + + // set the Navigation Controller as the root view controller + // [window_ addSubview:navController_.view]; // Generates flicker. + [window_ setRootViewController:navController_]; + + // make main window visible + [window_ makeKeyAndVisible]; + return YES; } @@ -137,12 +145,5 @@ -(void) applicationSignificantTimeChange:(UIApplication *)application [[CCDirector sharedDirector] setNextDeltaTimeZero:YES]; } -- (void) dealloc -{ - [window_ release]; - [navController_ release]; - - [super dealloc]; -} @end diff --git a/Example/Classes/HelloWorldLayer.m b/Example/Classes/HelloWorldLayer.m index 6e69819..f812a15 100644 --- a/Example/Classes/HelloWorldLayer.m +++ b/Example/Classes/HelloWorldLayer.m @@ -73,7 +73,6 @@ -(id) init [[app navController] presentModalViewController:achivementViewController animated:YES]; - [achivementViewController release]; } ]; @@ -88,7 +87,6 @@ -(id) init [[app navController] presentModalViewController:leaderboardViewController animated:YES]; - [leaderboardViewController release]; } ]; @@ -105,15 +103,6 @@ -(id) init } // on "dealloc" you need to release all your retained objects -- (void) dealloc -{ - // in case you have something to dealloc, do it in this method - // in this particular example nothing needs to be released. - // cocos2d will automatically release all the children (Label) - - // don't forget to call "super dealloc" - [super dealloc]; -} #pragma mark GameKit delegate diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index f48cde7..ffc4799 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -9,218 +9,6 @@ /* Begin PBXBuildFile section */ 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; 1F3B9A2D0EF2145700286867 /* ExampleAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1F3B9A2B0EF2145700286867 /* ExampleAppDelegate.m */; }; - 473FCB47156A52A3007DD659 /* CCAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA8A156A52A3007DD659 /* CCAction.h */; }; - 473FCB48156A52A3007DD659 /* CCAction.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA8B156A52A3007DD659 /* CCAction.m */; }; - 473FCB49156A52A3007DD659 /* CCActionCamera.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA8C156A52A3007DD659 /* CCActionCamera.h */; }; - 473FCB4A156A52A3007DD659 /* CCActionCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA8D156A52A3007DD659 /* CCActionCamera.m */; }; - 473FCB4B156A52A3007DD659 /* CCActionEase.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA8E156A52A3007DD659 /* CCActionEase.h */; }; - 473FCB4C156A52A3007DD659 /* CCActionEase.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA8F156A52A3007DD659 /* CCActionEase.m */; }; - 473FCB4D156A52A3007DD659 /* CCActionGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA90156A52A3007DD659 /* CCActionGrid.h */; }; - 473FCB4E156A52A3007DD659 /* CCActionGrid.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA91156A52A3007DD659 /* CCActionGrid.m */; }; - 473FCB4F156A52A3007DD659 /* CCActionGrid3D.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA92156A52A3007DD659 /* CCActionGrid3D.h */; }; - 473FCB50156A52A3007DD659 /* CCActionGrid3D.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA93156A52A3007DD659 /* CCActionGrid3D.m */; }; - 473FCB51156A52A3007DD659 /* CCActionInstant.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA94156A52A3007DD659 /* CCActionInstant.h */; }; - 473FCB52156A52A3007DD659 /* CCActionInstant.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA95156A52A3007DD659 /* CCActionInstant.m */; }; - 473FCB53156A52A3007DD659 /* CCActionInterval.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA96156A52A3007DD659 /* CCActionInterval.h */; }; - 473FCB54156A52A3007DD659 /* CCActionInterval.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA97156A52A3007DD659 /* CCActionInterval.m */; }; - 473FCB55156A52A3007DD659 /* CCActionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA98156A52A3007DD659 /* CCActionManager.h */; }; - 473FCB56156A52A3007DD659 /* CCActionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA99156A52A3007DD659 /* CCActionManager.m */; }; - 473FCB57156A52A3007DD659 /* CCActionPageTurn3D.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA9A156A52A3007DD659 /* CCActionPageTurn3D.h */; }; - 473FCB58156A52A3007DD659 /* CCActionPageTurn3D.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA9B156A52A3007DD659 /* CCActionPageTurn3D.m */; }; - 473FCB59156A52A3007DD659 /* CCActionProgressTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA9C156A52A3007DD659 /* CCActionProgressTimer.h */; }; - 473FCB5A156A52A3007DD659 /* CCActionProgressTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA9D156A52A3007DD659 /* CCActionProgressTimer.m */; }; - 473FCB5B156A52A3007DD659 /* CCActionTiledGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCA9E156A52A3007DD659 /* CCActionTiledGrid.h */; }; - 473FCB5C156A52A3007DD659 /* CCActionTiledGrid.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCA9F156A52A3007DD659 /* CCActionTiledGrid.m */; }; - 473FCB5D156A52A3007DD659 /* CCActionTween.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA0156A52A3007DD659 /* CCActionTween.h */; }; - 473FCB5E156A52A3007DD659 /* CCActionTween.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA1156A52A3007DD659 /* CCActionTween.m */; }; - 473FCB5F156A52A3007DD659 /* CCAnimation.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA2156A52A3007DD659 /* CCAnimation.h */; }; - 473FCB60156A52A3007DD659 /* CCAnimation.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA3156A52A3007DD659 /* CCAnimation.m */; }; - 473FCB61156A52A3007DD659 /* CCAnimationCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA4156A52A3007DD659 /* CCAnimationCache.h */; }; - 473FCB62156A52A3007DD659 /* CCAnimationCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA5156A52A3007DD659 /* CCAnimationCache.m */; }; - 473FCB63156A52A3007DD659 /* CCAtlasNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA6156A52A3007DD659 /* CCAtlasNode.h */; }; - 473FCB64156A52A3007DD659 /* CCAtlasNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA7156A52A3007DD659 /* CCAtlasNode.m */; }; - 473FCB65156A52A3007DD659 /* CCCamera.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAA8156A52A3007DD659 /* CCCamera.h */; }; - 473FCB66156A52A3007DD659 /* CCCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAA9156A52A3007DD659 /* CCCamera.m */; }; - 473FCB67156A52A3007DD659 /* ccConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAAA156A52A3007DD659 /* ccConfig.h */; }; - 473FCB68156A52A3007DD659 /* CCConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAAB156A52A3007DD659 /* CCConfiguration.h */; }; - 473FCB69156A52A3007DD659 /* CCConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAAC156A52A3007DD659 /* CCConfiguration.m */; }; - 473FCB6A156A52A3007DD659 /* ccDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAAD156A52A3007DD659 /* ccDeprecated.h */; }; - 473FCB6B156A52A3007DD659 /* ccDeprecated.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAAE156A52A3007DD659 /* ccDeprecated.m */; }; - 473FCB6C156A52A3007DD659 /* CCDirector.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAAF156A52A3007DD659 /* CCDirector.h */; }; - 473FCB6D156A52A3007DD659 /* CCDirector.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB0156A52A3007DD659 /* CCDirector.m */; }; - 473FCB6E156A52A3007DD659 /* CCDrawingPrimitives.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB1156A52A3007DD659 /* CCDrawingPrimitives.h */; }; - 473FCB6F156A52A3007DD659 /* CCDrawingPrimitives.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB2156A52A3007DD659 /* CCDrawingPrimitives.m */; }; - 473FCB70156A52A3007DD659 /* CCGLProgram.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB3156A52A3007DD659 /* CCGLProgram.h */; }; - 473FCB71156A52A3007DD659 /* CCGLProgram.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB4156A52A3007DD659 /* CCGLProgram.m */; }; - 473FCB72156A52A3007DD659 /* ccGLStateCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB5156A52A3007DD659 /* ccGLStateCache.h */; }; - 473FCB73156A52A3007DD659 /* ccGLStateCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB6156A52A3007DD659 /* ccGLStateCache.m */; }; - 473FCB74156A52A3007DD659 /* CCGrabber.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB7156A52A3007DD659 /* CCGrabber.h */; }; - 473FCB75156A52A3007DD659 /* CCGrabber.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAB8156A52A3007DD659 /* CCGrabber.m */; }; - 473FCB76156A52A3007DD659 /* CCGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAB9156A52A3007DD659 /* CCGrid.h */; }; - 473FCB77156A52A3007DD659 /* CCGrid.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCABA156A52A3007DD659 /* CCGrid.m */; }; - 473FCB78156A52A3007DD659 /* CCLabelAtlas.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCABB156A52A3007DD659 /* CCLabelAtlas.h */; }; - 473FCB79156A52A3007DD659 /* CCLabelAtlas.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCABC156A52A3007DD659 /* CCLabelAtlas.m */; }; - 473FCB7A156A52A3007DD659 /* CCLabelBMFont.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCABD156A52A3007DD659 /* CCLabelBMFont.h */; }; - 473FCB7B156A52A3007DD659 /* CCLabelBMFont.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCABE156A52A3007DD659 /* CCLabelBMFont.m */; }; - 473FCB7C156A52A3007DD659 /* CCLabelTTF.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCABF156A52A3007DD659 /* CCLabelTTF.h */; }; - 473FCB7D156A52A3007DD659 /* CCLabelTTF.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC0156A52A3007DD659 /* CCLabelTTF.m */; }; - 473FCB7E156A52A3007DD659 /* CCLayer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC1156A52A3007DD659 /* CCLayer.h */; }; - 473FCB7F156A52A3007DD659 /* CCLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC2156A52A3007DD659 /* CCLayer.m */; }; - 473FCB80156A52A3007DD659 /* ccMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC3156A52A3007DD659 /* ccMacros.h */; }; - 473FCB81156A52A3007DD659 /* CCMenu.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC4156A52A3007DD659 /* CCMenu.h */; }; - 473FCB82156A52A3007DD659 /* CCMenu.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC5156A52A3007DD659 /* CCMenu.m */; }; - 473FCB83156A52A3007DD659 /* CCMenuItem.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC6156A52A3007DD659 /* CCMenuItem.h */; }; - 473FCB84156A52A3007DD659 /* CCMenuItem.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC7156A52A3007DD659 /* CCMenuItem.m */; }; - 473FCB85156A52A3007DD659 /* CCMotionStreak.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAC8156A52A3007DD659 /* CCMotionStreak.h */; }; - 473FCB86156A52A3007DD659 /* CCMotionStreak.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAC9156A52A3007DD659 /* CCMotionStreak.m */; }; - 473FCB87156A52A3007DD659 /* CCNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCACA156A52A3007DD659 /* CCNode.h */; }; - 473FCB88156A52A3007DD659 /* CCNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCACB156A52A3007DD659 /* CCNode.m */; }; - 473FCB89156A52A3007DD659 /* CCParallaxNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCACC156A52A3007DD659 /* CCParallaxNode.h */; }; - 473FCB8A156A52A3007DD659 /* CCParallaxNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCACD156A52A3007DD659 /* CCParallaxNode.m */; }; - 473FCB8B156A52A3007DD659 /* CCParticleBatchNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCACE156A52A3007DD659 /* CCParticleBatchNode.h */; }; - 473FCB8C156A52A3007DD659 /* CCParticleBatchNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCACF156A52A3007DD659 /* CCParticleBatchNode.m */; }; - 473FCB8D156A52A3007DD659 /* CCParticleExamples.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD0156A52A3007DD659 /* CCParticleExamples.h */; }; - 473FCB8E156A52A3007DD659 /* CCParticleExamples.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAD1156A52A3007DD659 /* CCParticleExamples.m */; }; - 473FCB8F156A52A3007DD659 /* CCParticleSystem.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD2156A52A3007DD659 /* CCParticleSystem.h */; }; - 473FCB90156A52A3007DD659 /* CCParticleSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAD3156A52A3007DD659 /* CCParticleSystem.m */; }; - 473FCB91156A52A3007DD659 /* CCParticleSystemQuad.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD4156A52A3007DD659 /* CCParticleSystemQuad.h */; }; - 473FCB92156A52A3007DD659 /* CCParticleSystemQuad.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAD5156A52A3007DD659 /* CCParticleSystemQuad.m */; }; - 473FCB93156A52A3007DD659 /* CCProgressTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD6156A52A3007DD659 /* CCProgressTimer.h */; }; - 473FCB94156A52A3007DD659 /* CCProgressTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAD7156A52A3007DD659 /* CCProgressTimer.m */; }; - 473FCB95156A52A3007DD659 /* CCProtocols.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD8156A52A3007DD659 /* CCProtocols.h */; }; - 473FCB96156A52A3007DD659 /* CCRenderTexture.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAD9156A52A3007DD659 /* CCRenderTexture.h */; }; - 473FCB97156A52A3007DD659 /* CCRenderTexture.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCADA156A52A3007DD659 /* CCRenderTexture.m */; }; - 473FCB98156A52A3007DD659 /* CCScene.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCADB156A52A3007DD659 /* CCScene.h */; }; - 473FCB99156A52A3007DD659 /* CCScene.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCADC156A52A3007DD659 /* CCScene.m */; }; - 473FCB9A156A52A3007DD659 /* CCScheduler.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCADD156A52A3007DD659 /* CCScheduler.h */; }; - 473FCB9B156A52A3007DD659 /* CCScheduler.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCADE156A52A3007DD659 /* CCScheduler.m */; }; - 473FCB9C156A52A3007DD659 /* ccShader_Position_uColor_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCADF156A52A3007DD659 /* ccShader_Position_uColor_frag.h */; }; - 473FCB9D156A52A3007DD659 /* ccShader_Position_uColor_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE0156A52A3007DD659 /* ccShader_Position_uColor_vert.h */; }; - 473FCB9E156A52A3007DD659 /* ccShader_PositionColor_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE1156A52A3007DD659 /* ccShader_PositionColor_frag.h */; }; - 473FCB9F156A52A3007DD659 /* ccShader_PositionColor_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE2156A52A3007DD659 /* ccShader_PositionColor_vert.h */; }; - 473FCBA0156A52A3007DD659 /* ccShader_PositionTexture_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE3156A52A3007DD659 /* ccShader_PositionTexture_frag.h */; }; - 473FCBA1156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE4156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h */; }; - 473FCBA2156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE5156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h */; }; - 473FCBA3156A52A3007DD659 /* ccShader_PositionTexture_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE6156A52A3007DD659 /* ccShader_PositionTexture_vert.h */; }; - 473FCBA4156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE7156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h */; }; - 473FCBA5156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE8156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h */; }; - 473FCBA6156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAE9156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h */; }; - 473FCBA7156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAEA156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h */; }; - 473FCBA8156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAEB156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h */; }; - 473FCBA9156A52A3007DD659 /* CCShaderCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAEC156A52A3007DD659 /* CCShaderCache.h */; }; - 473FCBAA156A52A3007DD659 /* CCShaderCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAED156A52A3007DD659 /* CCShaderCache.m */; }; - 473FCBAB156A52A3007DD659 /* ccShaders.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAEE156A52A3007DD659 /* ccShaders.h */; }; - 473FCBAC156A52A3007DD659 /* ccShaders.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAEF156A52A3007DD659 /* ccShaders.m */; }; - 473FCBAD156A52A3007DD659 /* CCSprite.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF0156A52A3007DD659 /* CCSprite.h */; }; - 473FCBAE156A52A3007DD659 /* CCSprite.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF1156A52A3007DD659 /* CCSprite.m */; }; - 473FCBAF156A52A3007DD659 /* CCSpriteBatchNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF2156A52A3007DD659 /* CCSpriteBatchNode.h */; }; - 473FCBB0156A52A3007DD659 /* CCSpriteBatchNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF3156A52A3007DD659 /* CCSpriteBatchNode.m */; }; - 473FCBB1156A52A3007DD659 /* CCSpriteFrame.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF4156A52A3007DD659 /* CCSpriteFrame.h */; }; - 473FCBB2156A52A3007DD659 /* CCSpriteFrame.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF5156A52A3007DD659 /* CCSpriteFrame.m */; }; - 473FCBB3156A52A3007DD659 /* CCSpriteFrameCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF6156A52A3007DD659 /* CCSpriteFrameCache.h */; }; - 473FCBB4156A52A3007DD659 /* CCSpriteFrameCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF7156A52A3007DD659 /* CCSpriteFrameCache.m */; }; - 473FCBB5156A52A3007DD659 /* CCTexture2D.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAF8156A52A3007DD659 /* CCTexture2D.h */; }; - 473FCBB6156A52A3007DD659 /* CCTexture2D.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAF9156A52A3007DD659 /* CCTexture2D.m */; }; - 473FCBB7156A52A3007DD659 /* CCTextureAtlas.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAFA156A52A3007DD659 /* CCTextureAtlas.h */; }; - 473FCBB8156A52A3007DD659 /* CCTextureAtlas.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAFB156A52A3007DD659 /* CCTextureAtlas.m */; }; - 473FCBB9156A52A3007DD659 /* CCTextureCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAFC156A52A3007DD659 /* CCTextureCache.h */; }; - 473FCBBA156A52A3007DD659 /* CCTextureCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAFD156A52A3007DD659 /* CCTextureCache.m */; }; - 473FCBBB156A52A3007DD659 /* CCTexturePVR.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCAFE156A52A3007DD659 /* CCTexturePVR.h */; }; - 473FCBBC156A52A3007DD659 /* CCTexturePVR.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCAFF156A52A3007DD659 /* CCTexturePVR.m */; }; - 473FCBBD156A52A3007DD659 /* CCTileMapAtlas.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB00156A52A3007DD659 /* CCTileMapAtlas.h */; }; - 473FCBBE156A52A3007DD659 /* CCTileMapAtlas.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB01156A52A3007DD659 /* CCTileMapAtlas.m */; }; - 473FCBBF156A52A3007DD659 /* CCTMXLayer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB02156A52A3007DD659 /* CCTMXLayer.h */; }; - 473FCBC0156A52A3007DD659 /* CCTMXLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB03156A52A3007DD659 /* CCTMXLayer.m */; }; - 473FCBC1156A52A3007DD659 /* CCTMXObjectGroup.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB04156A52A3007DD659 /* CCTMXObjectGroup.h */; }; - 473FCBC2156A52A3007DD659 /* CCTMXObjectGroup.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB05156A52A3007DD659 /* CCTMXObjectGroup.m */; }; - 473FCBC3156A52A3007DD659 /* CCTMXTiledMap.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB06156A52A3007DD659 /* CCTMXTiledMap.h */; }; - 473FCBC4156A52A3007DD659 /* CCTMXTiledMap.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB07156A52A3007DD659 /* CCTMXTiledMap.m */; }; - 473FCBC5156A52A3007DD659 /* CCTMXXMLParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB08156A52A3007DD659 /* CCTMXXMLParser.h */; }; - 473FCBC6156A52A3007DD659 /* CCTMXXMLParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB09156A52A3007DD659 /* CCTMXXMLParser.m */; }; - 473FCBC7156A52A3007DD659 /* CCTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB0A156A52A3007DD659 /* CCTransition.h */; }; - 473FCBC8156A52A3007DD659 /* CCTransition.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB0B156A52A3007DD659 /* CCTransition.m */; }; - 473FCBC9156A52A3007DD659 /* CCTransitionPageTurn.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB0C156A52A3007DD659 /* CCTransitionPageTurn.h */; }; - 473FCBCA156A52A3007DD659 /* CCTransitionPageTurn.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB0D156A52A3007DD659 /* CCTransitionPageTurn.m */; }; - 473FCBCB156A52A3007DD659 /* CCTransitionProgress.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB0E156A52A3007DD659 /* CCTransitionProgress.h */; }; - 473FCBCC156A52A3007DD659 /* CCTransitionProgress.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB0F156A52A3007DD659 /* CCTransitionProgress.m */; }; - 473FCBCD156A52A3007DD659 /* ccTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB10156A52A3007DD659 /* ccTypes.h */; }; - 473FCBCE156A52A3007DD659 /* cocos2d.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB11156A52A3007DD659 /* cocos2d.h */; }; - 473FCBCF156A52A3007DD659 /* cocos2d.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB12156A52A3007DD659 /* cocos2d.m */; }; - 473FCBD0156A52A3007DD659 /* CCGL.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB14156A52A3007DD659 /* CCGL.h */; }; - 473FCBD1156A52A3007DD659 /* CCNS.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB15156A52A3007DD659 /* CCNS.h */; }; - 473FCBD2156A52A3007DD659 /* CCDirectorIOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB17156A52A3007DD659 /* CCDirectorIOS.h */; }; - 473FCBD3156A52A3007DD659 /* CCDirectorIOS.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB18156A52A3007DD659 /* CCDirectorIOS.m */; }; - 473FCBD4156A52A3007DD659 /* CCES2Renderer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB19156A52A3007DD659 /* CCES2Renderer.h */; }; - 473FCBD5156A52A3007DD659 /* CCES2Renderer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB1A156A52A3007DD659 /* CCES2Renderer.m */; }; - 473FCBD6156A52A3007DD659 /* CCESRenderer.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB1B156A52A3007DD659 /* CCESRenderer.h */; }; - 473FCBD7156A52A3007DD659 /* CCGLView.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB1C156A52A3007DD659 /* CCGLView.h */; }; - 473FCBD8156A52A3007DD659 /* CCGLView.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB1D156A52A3007DD659 /* CCGLView.m */; }; - 473FCBD9156A52A3007DD659 /* CCTouchDelegateProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB1E156A52A3007DD659 /* CCTouchDelegateProtocol.h */; }; - 473FCBDA156A52A3007DD659 /* CCTouchDispatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB1F156A52A3007DD659 /* CCTouchDispatcher.h */; }; - 473FCBDB156A52A3007DD659 /* CCTouchDispatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB20156A52A3007DD659 /* CCTouchDispatcher.m */; }; - 473FCBDC156A52A3007DD659 /* CCTouchHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB21156A52A3007DD659 /* CCTouchHandler.h */; }; - 473FCBDD156A52A3007DD659 /* CCTouchHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB22156A52A3007DD659 /* CCTouchHandler.m */; }; - 473FCBDE156A52A3007DD659 /* CCDirectorMac.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB24156A52A3007DD659 /* CCDirectorMac.h */; }; - 473FCBDF156A52A3007DD659 /* CCDirectorMac.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB25156A52A3007DD659 /* CCDirectorMac.m */; }; - 473FCBE0156A52A3007DD659 /* CCEventDispatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB26156A52A3007DD659 /* CCEventDispatcher.h */; }; - 473FCBE1156A52A3007DD659 /* CCEventDispatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB27156A52A3007DD659 /* CCEventDispatcher.m */; }; - 473FCBE2156A52A3007DD659 /* CCGLView.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB28156A52A3007DD659 /* CCGLView.h */; }; - 473FCBE3156A52A3007DD659 /* CCGLView.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB29156A52A3007DD659 /* CCGLView.m */; }; - 473FCBE4156A52A3007DD659 /* CCWindow.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB2A156A52A3007DD659 /* CCWindow.h */; }; - 473FCBE5156A52A3007DD659 /* CCWindow.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB2B156A52A3007DD659 /* CCWindow.m */; }; - 473FCBE6156A52A3007DD659 /* base64.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB2D156A52A3007DD659 /* base64.c */; }; - 473FCBE7156A52A3007DD659 /* base64.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB2E156A52A3007DD659 /* base64.h */; }; - 473FCBE8156A52A3007DD659 /* CCArray.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB2F156A52A3007DD659 /* CCArray.h */; }; - 473FCBE9156A52A3007DD659 /* CCArray.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB30156A52A3007DD659 /* CCArray.m */; }; - 473FCBEA156A52A3007DD659 /* ccCArray.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB31156A52A3007DD659 /* ccCArray.h */; }; - 473FCBEB156A52A3007DD659 /* CCFileUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB32156A52A3007DD659 /* CCFileUtils.h */; }; - 473FCBEC156A52A3007DD659 /* CCFileUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB33156A52A3007DD659 /* CCFileUtils.m */; }; - 473FCBED156A52A3007DD659 /* CCProfiling.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB34156A52A3007DD659 /* CCProfiling.h */; }; - 473FCBEE156A52A3007DD659 /* CCProfiling.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB35156A52A3007DD659 /* CCProfiling.m */; }; - 473FCBEF156A52A3007DD659 /* ccUtils.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB36156A52A3007DD659 /* ccUtils.c */; }; - 473FCBF0156A52A3007DD659 /* ccUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB37156A52A3007DD659 /* ccUtils.h */; }; - 473FCBF1156A52A3007DD659 /* CCVertex.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB38156A52A3007DD659 /* CCVertex.h */; }; - 473FCBF2156A52A3007DD659 /* CCVertex.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB39156A52A3007DD659 /* CCVertex.m */; }; - 473FCBF3156A52A3007DD659 /* CGPointExtension.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB3A156A52A3007DD659 /* CGPointExtension.h */; }; - 473FCBF4156A52A3007DD659 /* CGPointExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB3B156A52A3007DD659 /* CGPointExtension.m */; }; - 473FCBF5156A52A3007DD659 /* NSThread+performBlock.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB3C156A52A3007DD659 /* NSThread+performBlock.h */; }; - 473FCBF6156A52A3007DD659 /* NSThread+performBlock.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB3D156A52A3007DD659 /* NSThread+performBlock.m */; }; - 473FCBF7156A52A3007DD659 /* OpenGL_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB3E156A52A3007DD659 /* OpenGL_Internal.h */; }; - 473FCBF8156A52A3007DD659 /* TGAlib.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB3F156A52A3007DD659 /* TGAlib.h */; }; - 473FCBF9156A52A3007DD659 /* TGAlib.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB40156A52A3007DD659 /* TGAlib.m */; }; - 473FCBFA156A52A3007DD659 /* TransformUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB41156A52A3007DD659 /* TransformUtils.h */; }; - 473FCBFB156A52A3007DD659 /* TransformUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB42156A52A3007DD659 /* TransformUtils.m */; }; - 473FCBFC156A52A3007DD659 /* uthash.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB43156A52A3007DD659 /* uthash.h */; }; - 473FCBFD156A52A3007DD659 /* utlist.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB44156A52A3007DD659 /* utlist.h */; }; - 473FCBFE156A52A3007DD659 /* ZipUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCB45156A52A3007DD659 /* ZipUtils.h */; }; - 473FCBFF156A52A3007DD659 /* ZipUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCB46156A52A3007DD659 /* ZipUtils.m */; }; - 473FCC23156A52FF007DD659 /* aabb.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC03156A52FF007DD659 /* aabb.h */; }; - 473FCC24156A52FF007DD659 /* mat4stack.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC05156A52FF007DD659 /* mat4stack.h */; }; - 473FCC25156A52FF007DD659 /* matrix.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC06156A52FF007DD659 /* matrix.h */; }; - 473FCC26156A52FF007DD659 /* kazmath.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC07156A52FF007DD659 /* kazmath.h */; }; - 473FCC27156A52FF007DD659 /* mat3.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC08156A52FF007DD659 /* mat3.h */; }; - 473FCC28156A52FF007DD659 /* mat4.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC09156A52FF007DD659 /* mat4.h */; }; - 473FCC29156A52FF007DD659 /* neon_matrix_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0A156A52FF007DD659 /* neon_matrix_impl.h */; }; - 473FCC2A156A52FF007DD659 /* plane.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0B156A52FF007DD659 /* plane.h */; }; - 473FCC2B156A52FF007DD659 /* quaternion.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0C156A52FF007DD659 /* quaternion.h */; }; - 473FCC2C156A52FF007DD659 /* ray2.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0D156A52FF007DD659 /* ray2.h */; }; - 473FCC2D156A52FF007DD659 /* utility.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0E156A52FF007DD659 /* utility.h */; }; - 473FCC2E156A52FF007DD659 /* vec2.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC0F156A52FF007DD659 /* vec2.h */; }; - 473FCC2F156A52FF007DD659 /* vec3.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC10156A52FF007DD659 /* vec3.h */; }; - 473FCC30156A52FF007DD659 /* vec4.h in Headers */ = {isa = PBXBuildFile; fileRef = 473FCC11156A52FF007DD659 /* vec4.h */; }; - 473FCC31156A52FF007DD659 /* aabb.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC13156A52FF007DD659 /* aabb.c */; }; - 473FCC32156A52FF007DD659 /* mat4stack.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC17156A52FF007DD659 /* mat4stack.c */; }; - 473FCC33156A52FF007DD659 /* matrix.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC18156A52FF007DD659 /* matrix.c */; }; - 473FCC34156A52FF007DD659 /* mat3.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC19156A52FF007DD659 /* mat3.c */; }; - 473FCC35156A52FF007DD659 /* mat4.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1A156A52FF007DD659 /* mat4.c */; }; - 473FCC36156A52FF007DD659 /* neon_matrix_impl.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1B156A52FF007DD659 /* neon_matrix_impl.c */; }; - 473FCC37156A52FF007DD659 /* plane.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1C156A52FF007DD659 /* plane.c */; }; - 473FCC38156A52FF007DD659 /* quaternion.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1D156A52FF007DD659 /* quaternion.c */; }; - 473FCC39156A52FF007DD659 /* ray2.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1E156A52FF007DD659 /* ray2.c */; }; - 473FCC3A156A52FF007DD659 /* utility.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC1F156A52FF007DD659 /* utility.c */; }; - 473FCC3B156A52FF007DD659 /* vec2.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC20156A52FF007DD659 /* vec2.c */; }; - 473FCC3C156A52FF007DD659 /* vec3.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC21156A52FF007DD659 /* vec3.c */; }; - 473FCC3D156A52FF007DD659 /* vec4.c in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC22156A52FF007DD659 /* vec4.c */; }; 473FCC44156A6B03007DD659 /* HelloWorldLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 473FCC43156A6B03007DD659 /* HelloWorldLayer.m */; }; 473FCC46156A6BCE007DD659 /* GameKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 473FCC45156A6BCE007DD659 /* GameKit.framework */; }; 473FCC4C156A6DC4007DD659 /* fps_images.png in Resources */ = {isa = PBXBuildFile; fileRef = 473FCC49156A6DC4007DD659 /* fps_images.png */; }; @@ -235,58 +23,8 @@ 47B802CD13F269D9006B0B98 /* streak2-hd.png in Resources */ = {isa = PBXBuildFile; fileRef = 47B802CA13F269D9006B0B98 /* streak2-hd.png */; }; 47B802CE13F269D9006B0B98 /* streak3-hd.png in Resources */ = {isa = PBXBuildFile; fileRef = 47B802CB13F269D9006B0B98 /* streak3-hd.png */; }; 47B802D013F26A4C006B0B98 /* Default-hd.png in Resources */ = {isa = PBXBuildFile; fileRef = 47B802CF13F26A4C006B0B98 /* Default-hd.png */; }; - 504DFBCE10AF12E9006D82FE /* CLScoreServerPost.h in Headers */ = {isa = PBXBuildFile; fileRef = 504DFBC810AF12E9006D82FE /* CLScoreServerPost.h */; }; - 504DFBCF10AF12E9006D82FE /* CLScoreServerPost.m in Sources */ = {isa = PBXBuildFile; fileRef = 504DFBC910AF12E9006D82FE /* CLScoreServerPost.m */; }; - 504DFBD010AF12E9006D82FE /* CLScoreServerRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 504DFBCA10AF12E9006D82FE /* CLScoreServerRequest.h */; }; - 504DFBD110AF12E9006D82FE /* CLScoreServerRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 504DFBCB10AF12E9006D82FE /* CLScoreServerRequest.m */; }; - 504DFBD210AF12E9006D82FE /* cocoslive.h in Headers */ = {isa = PBXBuildFile; fileRef = 504DFBCC10AF12E9006D82FE /* cocoslive.h */; }; - 504DFBD310AF12E9006D82FE /* cocoslive.m in Sources */ = {isa = PBXBuildFile; fileRef = 504DFBCD10AF12E9006D82FE /* cocoslive.m */; }; - 505574581045D68500A31725 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */; }; - 505574591045D68500A31725 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */; }; - 5055745A1045D68500A31725 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1B60F6022AE0040855A /* CoreGraphics.framework */; }; - 5055745B1045D68500A31725 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC6640040F83B3EA000B3E49 /* OpenAL.framework */; }; - 5055745C1045D68500A31725 /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1BA0F6022AE0040855A /* OpenGLES.framework */; }; - 5055745D1045D68500A31725 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1BC0F6022AE0040855A /* QuartzCore.framework */; }; - 5055745E1045D69D00A31725 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EDB87102F4C4000A389B3 /* libz.dylib */; }; - 50674853107A3AF30090963A /* ZAttributedString.h in Headers */ = {isa = PBXBuildFile; fileRef = 50674850107A3AF30090963A /* ZAttributedString.h */; }; - 50674854107A3AF30090963A /* ZAttributedString.m in Sources */ = {isa = PBXBuildFile; fileRef = 50674851107A3AF30090963A /* ZAttributedString.m */; }; - 50674855107A3AF30090963A /* ZAttributedStringPrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 50674852107A3AF30090963A /* ZAttributedStringPrivate.h */; }; 506EDB88102F4C4000A389B3 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EDB87102F4C4000A389B3 /* libz.dylib */; }; 506EDBA5102F4C9F00A389B3 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */; }; - 506EE1A91030508200A389B3 /* libcocos2d libraries.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EE05E10304ED200A389B3 /* libcocos2d libraries.a */; }; - 507ED63C11C638C6002ED3FC /* CDAudioManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 507ED63311C638C6002ED3FC /* CDAudioManager.h */; }; - 507ED63D11C638C6002ED3FC /* CDAudioManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 507ED63411C638C6002ED3FC /* CDAudioManager.m */; }; - 507ED63E11C638C6002ED3FC /* CDConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 507ED63511C638C6002ED3FC /* CDConfig.h */; }; - 507ED63F11C638C6002ED3FC /* CDOpenALSupport.h in Headers */ = {isa = PBXBuildFile; fileRef = 507ED63611C638C6002ED3FC /* CDOpenALSupport.h */; }; - 507ED64011C638C6002ED3FC /* CDOpenALSupport.m in Sources */ = {isa = PBXBuildFile; fileRef = 507ED63711C638C6002ED3FC /* CDOpenALSupport.m */; }; - 507ED64111C638C6002ED3FC /* CocosDenshion.h in Headers */ = {isa = PBXBuildFile; fileRef = 507ED63811C638C6002ED3FC /* CocosDenshion.h */; }; - 507ED64211C638C6002ED3FC /* CocosDenshion.m in Sources */ = {isa = PBXBuildFile; fileRef = 507ED63911C638C6002ED3FC /* CocosDenshion.m */; }; - 507ED64311C638C6002ED3FC /* SimpleAudioEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 507ED63A11C638C6002ED3FC /* SimpleAudioEngine.h */; }; - 507ED64411C638C6002ED3FC /* SimpleAudioEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 507ED63B11C638C6002ED3FC /* SimpleAudioEngine.m */; }; - 50F4132A106926B2002A0D5E /* FontLabel.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F41307106926B2002A0D5E /* FontLabel.h */; }; - 50F4132B106926B2002A0D5E /* FontLabel.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F41308106926B2002A0D5E /* FontLabel.m */; }; - 50F4132C106926B2002A0D5E /* FontLabelStringDrawing.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F41309106926B2002A0D5E /* FontLabelStringDrawing.h */; }; - 50F4132D106926B2002A0D5E /* FontLabelStringDrawing.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F4130A106926B2002A0D5E /* FontLabelStringDrawing.m */; }; - 50F4132E106926B2002A0D5E /* FontManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F4130B106926B2002A0D5E /* FontManager.h */; }; - 50F4132F106926B2002A0D5E /* FontManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F4130C106926B2002A0D5E /* FontManager.m */; }; - 50F41332106926B2002A0D5E /* ZFont.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F4130F106926B2002A0D5E /* ZFont.h */; }; - 50F41333106926B2002A0D5E /* ZFont.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F41310106926B2002A0D5E /* ZFont.m */; }; - 50F41334106926B2002A0D5E /* CDataScanner.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F41312106926B2002A0D5E /* CDataScanner.h */; }; - 50F41335106926B2002A0D5E /* CDataScanner.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F41313106926B2002A0D5E /* CDataScanner.m */; }; - 50F41336106926B2002A0D5E /* CDataScanner_Extensions.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F41315106926B2002A0D5E /* CDataScanner_Extensions.h */; }; - 50F41337106926B2002A0D5E /* CDataScanner_Extensions.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F41316106926B2002A0D5E /* CDataScanner_Extensions.m */; }; - 50F41338106926B2002A0D5E /* NSCharacterSet_Extensions.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F41317106926B2002A0D5E /* NSCharacterSet_Extensions.h */; }; - 50F41339106926B2002A0D5E /* NSCharacterSet_Extensions.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F41318106926B2002A0D5E /* NSCharacterSet_Extensions.m */; }; - 50F4133A106926B2002A0D5E /* NSDictionary_JSONExtensions.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F41319106926B2002A0D5E /* NSDictionary_JSONExtensions.h */; }; - 50F4133B106926B2002A0D5E /* NSDictionary_JSONExtensions.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F4131A106926B2002A0D5E /* NSDictionary_JSONExtensions.m */; }; - 50F4133C106926B2002A0D5E /* NSScanner_Extensions.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F4131B106926B2002A0D5E /* NSScanner_Extensions.h */; }; - 50F4133D106926B2002A0D5E /* NSScanner_Extensions.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F4131C106926B2002A0D5E /* NSScanner_Extensions.m */; }; - 50F4133E106926B2002A0D5E /* CJSONDeserializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F4131E106926B2002A0D5E /* CJSONDeserializer.h */; }; - 50F4133F106926B2002A0D5E /* CJSONDeserializer.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F4131F106926B2002A0D5E /* CJSONDeserializer.m */; }; - 50F41340106926B2002A0D5E /* CJSONScanner.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F41320106926B2002A0D5E /* CJSONScanner.h */; }; - 50F41341106926B2002A0D5E /* CJSONScanner.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F41321106926B2002A0D5E /* CJSONScanner.m */; }; - 50F41342106926B2002A0D5E /* CJSONSerializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 50F41322106926B2002A0D5E /* CJSONSerializer.h */; }; - 50F41343106926B2002A0D5E /* CJSONSerializer.m in Sources */ = {isa = PBXBuildFile; fileRef = 50F41323106926B2002A0D5E /* CJSONSerializer.m */; }; 50F414F01069373D002A0D5E /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 50F414EC1069373D002A0D5E /* Default.png */; }; 50F414F21069373D002A0D5E /* Icon.png in Resources */ = {isa = PBXBuildFile; fileRef = 50F414EE1069373D002A0D5E /* Icon.png */; }; DC6640030F83B3EA000B3E49 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */; }; @@ -304,236 +42,12 @@ E02BB763126CC1E0006E46A2 /* iTunesArtwork in Resources */ = {isa = PBXBuildFile; fileRef = E02BB762126CC1E0006E46A2 /* iTunesArtwork */; }; /* End PBXBuildFile section */ -/* Begin PBXContainerItemProxy section */ - 506EE1A71030507B00A389B3 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 29B97313FDCFA39411CA2CEA /* Project object */; - proxyType = 1; - remoteGlobalIDString = 506EE05D10304ED200A389B3; - remoteInfo = "cocos2d libraries"; - }; -/* End PBXContainerItemProxy section */ - /* Begin PBXFileReference section */ 1D6058910D05DD3D006BFB54 /* CCBlade.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CCBlade.app; sourceTree = BUILT_PRODUCTS_DIR; }; 1F3B9A2B0EF2145700286867 /* ExampleAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ExampleAppDelegate.m; path = Classes/ExampleAppDelegate.m; sourceTree = SOURCE_ROOT; }; 1F3B9A2C0EF2145700286867 /* ExampleAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ExampleAppDelegate.h; path = Classes/ExampleAppDelegate.h; sourceTree = SOURCE_ROOT; }; 1F3B9A820EF2151B00286867 /* Example_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Example_Prefix.pch; sourceTree = SOURCE_ROOT; }; 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - 473FCA8A156A52A3007DD659 /* CCAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAction.h; sourceTree = ""; }; - 473FCA8B156A52A3007DD659 /* CCAction.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAction.m; sourceTree = ""; }; - 473FCA8C156A52A3007DD659 /* CCActionCamera.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionCamera.h; sourceTree = ""; }; - 473FCA8D156A52A3007DD659 /* CCActionCamera.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionCamera.m; sourceTree = ""; }; - 473FCA8E156A52A3007DD659 /* CCActionEase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionEase.h; sourceTree = ""; }; - 473FCA8F156A52A3007DD659 /* CCActionEase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionEase.m; sourceTree = ""; }; - 473FCA90156A52A3007DD659 /* CCActionGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionGrid.h; sourceTree = ""; }; - 473FCA91156A52A3007DD659 /* CCActionGrid.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionGrid.m; sourceTree = ""; }; - 473FCA92156A52A3007DD659 /* CCActionGrid3D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionGrid3D.h; sourceTree = ""; }; - 473FCA93156A52A3007DD659 /* CCActionGrid3D.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionGrid3D.m; sourceTree = ""; }; - 473FCA94156A52A3007DD659 /* CCActionInstant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionInstant.h; sourceTree = ""; }; - 473FCA95156A52A3007DD659 /* CCActionInstant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionInstant.m; sourceTree = ""; }; - 473FCA96156A52A3007DD659 /* CCActionInterval.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionInterval.h; sourceTree = ""; }; - 473FCA97156A52A3007DD659 /* CCActionInterval.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionInterval.m; sourceTree = ""; }; - 473FCA98156A52A3007DD659 /* CCActionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionManager.h; sourceTree = ""; }; - 473FCA99156A52A3007DD659 /* CCActionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionManager.m; sourceTree = ""; }; - 473FCA9A156A52A3007DD659 /* CCActionPageTurn3D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionPageTurn3D.h; sourceTree = ""; }; - 473FCA9B156A52A3007DD659 /* CCActionPageTurn3D.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionPageTurn3D.m; sourceTree = ""; }; - 473FCA9C156A52A3007DD659 /* CCActionProgressTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionProgressTimer.h; sourceTree = ""; }; - 473FCA9D156A52A3007DD659 /* CCActionProgressTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionProgressTimer.m; sourceTree = ""; }; - 473FCA9E156A52A3007DD659 /* CCActionTiledGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionTiledGrid.h; sourceTree = ""; }; - 473FCA9F156A52A3007DD659 /* CCActionTiledGrid.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionTiledGrid.m; sourceTree = ""; }; - 473FCAA0156A52A3007DD659 /* CCActionTween.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionTween.h; sourceTree = ""; }; - 473FCAA1156A52A3007DD659 /* CCActionTween.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCActionTween.m; sourceTree = ""; }; - 473FCAA2156A52A3007DD659 /* CCAnimation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAnimation.h; sourceTree = ""; }; - 473FCAA3156A52A3007DD659 /* CCAnimation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAnimation.m; sourceTree = ""; }; - 473FCAA4156A52A3007DD659 /* CCAnimationCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAnimationCache.h; sourceTree = ""; }; - 473FCAA5156A52A3007DD659 /* CCAnimationCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAnimationCache.m; sourceTree = ""; }; - 473FCAA6156A52A3007DD659 /* CCAtlasNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAtlasNode.h; sourceTree = ""; }; - 473FCAA7156A52A3007DD659 /* CCAtlasNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCAtlasNode.m; sourceTree = ""; }; - 473FCAA8156A52A3007DD659 /* CCCamera.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCCamera.h; sourceTree = ""; }; - 473FCAA9156A52A3007DD659 /* CCCamera.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCCamera.m; sourceTree = ""; }; - 473FCAAA156A52A3007DD659 /* ccConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccConfig.h; sourceTree = ""; }; - 473FCAAB156A52A3007DD659 /* CCConfiguration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCConfiguration.h; sourceTree = ""; }; - 473FCAAC156A52A3007DD659 /* CCConfiguration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCConfiguration.m; sourceTree = ""; }; - 473FCAAD156A52A3007DD659 /* ccDeprecated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccDeprecated.h; sourceTree = ""; }; - 473FCAAE156A52A3007DD659 /* ccDeprecated.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ccDeprecated.m; sourceTree = ""; }; - 473FCAAF156A52A3007DD659 /* CCDirector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDirector.h; sourceTree = ""; }; - 473FCAB0156A52A3007DD659 /* CCDirector.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDirector.m; sourceTree = ""; }; - 473FCAB1156A52A3007DD659 /* CCDrawingPrimitives.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDrawingPrimitives.h; sourceTree = ""; }; - 473FCAB2156A52A3007DD659 /* CCDrawingPrimitives.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDrawingPrimitives.m; sourceTree = ""; }; - 473FCAB3156A52A3007DD659 /* CCGLProgram.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGLProgram.h; sourceTree = ""; }; - 473FCAB4156A52A3007DD659 /* CCGLProgram.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGLProgram.m; sourceTree = ""; }; - 473FCAB5156A52A3007DD659 /* ccGLStateCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccGLStateCache.h; sourceTree = ""; }; - 473FCAB6156A52A3007DD659 /* ccGLStateCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ccGLStateCache.m; sourceTree = ""; }; - 473FCAB7156A52A3007DD659 /* CCGrabber.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGrabber.h; sourceTree = ""; }; - 473FCAB8156A52A3007DD659 /* CCGrabber.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGrabber.m; sourceTree = ""; }; - 473FCAB9156A52A3007DD659 /* CCGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGrid.h; sourceTree = ""; }; - 473FCABA156A52A3007DD659 /* CCGrid.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGrid.m; sourceTree = ""; }; - 473FCABB156A52A3007DD659 /* CCLabelAtlas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLabelAtlas.h; sourceTree = ""; }; - 473FCABC156A52A3007DD659 /* CCLabelAtlas.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLabelAtlas.m; sourceTree = ""; }; - 473FCABD156A52A3007DD659 /* CCLabelBMFont.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLabelBMFont.h; sourceTree = ""; }; - 473FCABE156A52A3007DD659 /* CCLabelBMFont.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLabelBMFont.m; sourceTree = ""; }; - 473FCABF156A52A3007DD659 /* CCLabelTTF.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLabelTTF.h; sourceTree = ""; }; - 473FCAC0156A52A3007DD659 /* CCLabelTTF.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLabelTTF.m; sourceTree = ""; }; - 473FCAC1156A52A3007DD659 /* CCLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLayer.h; sourceTree = ""; }; - 473FCAC2156A52A3007DD659 /* CCLayer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCLayer.m; sourceTree = ""; }; - 473FCAC3156A52A3007DD659 /* ccMacros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccMacros.h; sourceTree = ""; }; - 473FCAC4156A52A3007DD659 /* CCMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCMenu.h; sourceTree = ""; }; - 473FCAC5156A52A3007DD659 /* CCMenu.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCMenu.m; sourceTree = ""; }; - 473FCAC6156A52A3007DD659 /* CCMenuItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCMenuItem.h; sourceTree = ""; }; - 473FCAC7156A52A3007DD659 /* CCMenuItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCMenuItem.m; sourceTree = ""; }; - 473FCAC8156A52A3007DD659 /* CCMotionStreak.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCMotionStreak.h; sourceTree = ""; }; - 473FCAC9156A52A3007DD659 /* CCMotionStreak.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCMotionStreak.m; sourceTree = ""; }; - 473FCACA156A52A3007DD659 /* CCNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCNode.h; sourceTree = ""; }; - 473FCACB156A52A3007DD659 /* CCNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCNode.m; sourceTree = ""; }; - 473FCACC156A52A3007DD659 /* CCParallaxNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParallaxNode.h; sourceTree = ""; }; - 473FCACD156A52A3007DD659 /* CCParallaxNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParallaxNode.m; sourceTree = ""; }; - 473FCACE156A52A3007DD659 /* CCParticleBatchNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleBatchNode.h; sourceTree = ""; }; - 473FCACF156A52A3007DD659 /* CCParticleBatchNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleBatchNode.m; sourceTree = ""; }; - 473FCAD0156A52A3007DD659 /* CCParticleExamples.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleExamples.h; sourceTree = ""; }; - 473FCAD1156A52A3007DD659 /* CCParticleExamples.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleExamples.m; sourceTree = ""; }; - 473FCAD2156A52A3007DD659 /* CCParticleSystem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleSystem.h; sourceTree = ""; }; - 473FCAD3156A52A3007DD659 /* CCParticleSystem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleSystem.m; sourceTree = ""; }; - 473FCAD4156A52A3007DD659 /* CCParticleSystemQuad.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCParticleSystemQuad.h; sourceTree = ""; }; - 473FCAD5156A52A3007DD659 /* CCParticleSystemQuad.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCParticleSystemQuad.m; sourceTree = ""; }; - 473FCAD6156A52A3007DD659 /* CCProgressTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCProgressTimer.h; sourceTree = ""; }; - 473FCAD7156A52A3007DD659 /* CCProgressTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCProgressTimer.m; sourceTree = ""; }; - 473FCAD8156A52A3007DD659 /* CCProtocols.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCProtocols.h; sourceTree = ""; }; - 473FCAD9156A52A3007DD659 /* CCRenderTexture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCRenderTexture.h; sourceTree = ""; }; - 473FCADA156A52A3007DD659 /* CCRenderTexture.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCRenderTexture.m; sourceTree = ""; }; - 473FCADB156A52A3007DD659 /* CCScene.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCScene.h; sourceTree = ""; }; - 473FCADC156A52A3007DD659 /* CCScene.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCScene.m; sourceTree = ""; }; - 473FCADD156A52A3007DD659 /* CCScheduler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCScheduler.h; sourceTree = ""; }; - 473FCADE156A52A3007DD659 /* CCScheduler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCScheduler.m; sourceTree = ""; }; - 473FCADF156A52A3007DD659 /* ccShader_Position_uColor_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_Position_uColor_frag.h; sourceTree = ""; }; - 473FCAE0156A52A3007DD659 /* ccShader_Position_uColor_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_Position_uColor_vert.h; sourceTree = ""; }; - 473FCAE1156A52A3007DD659 /* ccShader_PositionColor_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionColor_frag.h; sourceTree = ""; }; - 473FCAE2156A52A3007DD659 /* ccShader_PositionColor_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionColor_vert.h; sourceTree = ""; }; - 473FCAE3156A52A3007DD659 /* ccShader_PositionTexture_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTexture_frag.h; sourceTree = ""; }; - 473FCAE4156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTexture_uColor_frag.h; sourceTree = ""; }; - 473FCAE5156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTexture_uColor_vert.h; sourceTree = ""; }; - 473FCAE6156A52A3007DD659 /* ccShader_PositionTexture_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTexture_vert.h; sourceTree = ""; }; - 473FCAE7156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureA8Color_frag.h; sourceTree = ""; }; - 473FCAE8156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureA8Color_vert.h; sourceTree = ""; }; - 473FCAE9156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureColor_frag.h; sourceTree = ""; }; - 473FCAEA156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureColor_vert.h; sourceTree = ""; }; - 473FCAEB156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShader_PositionTextureColorAlphaTest_frag.h; sourceTree = ""; }; - 473FCAEC156A52A3007DD659 /* CCShaderCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCShaderCache.h; sourceTree = ""; }; - 473FCAED156A52A3007DD659 /* CCShaderCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCShaderCache.m; sourceTree = ""; }; - 473FCAEE156A52A3007DD659 /* ccShaders.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccShaders.h; sourceTree = ""; }; - 473FCAEF156A52A3007DD659 /* ccShaders.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ccShaders.m; sourceTree = ""; }; - 473FCAF0156A52A3007DD659 /* CCSprite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSprite.h; sourceTree = ""; }; - 473FCAF1156A52A3007DD659 /* CCSprite.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSprite.m; sourceTree = ""; }; - 473FCAF2156A52A3007DD659 /* CCSpriteBatchNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteBatchNode.h; sourceTree = ""; }; - 473FCAF3156A52A3007DD659 /* CCSpriteBatchNode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteBatchNode.m; sourceTree = ""; }; - 473FCAF4156A52A3007DD659 /* CCSpriteFrame.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteFrame.h; sourceTree = ""; }; - 473FCAF5156A52A3007DD659 /* CCSpriteFrame.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteFrame.m; sourceTree = ""; }; - 473FCAF6156A52A3007DD659 /* CCSpriteFrameCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSpriteFrameCache.h; sourceTree = ""; }; - 473FCAF7156A52A3007DD659 /* CCSpriteFrameCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSpriteFrameCache.m; sourceTree = ""; }; - 473FCAF8156A52A3007DD659 /* CCTexture2D.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTexture2D.h; sourceTree = ""; }; - 473FCAF9156A52A3007DD659 /* CCTexture2D.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTexture2D.m; sourceTree = ""; }; - 473FCAFA156A52A3007DD659 /* CCTextureAtlas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTextureAtlas.h; sourceTree = ""; }; - 473FCAFB156A52A3007DD659 /* CCTextureAtlas.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTextureAtlas.m; sourceTree = ""; }; - 473FCAFC156A52A3007DD659 /* CCTextureCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTextureCache.h; sourceTree = ""; }; - 473FCAFD156A52A3007DD659 /* CCTextureCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTextureCache.m; sourceTree = ""; }; - 473FCAFE156A52A3007DD659 /* CCTexturePVR.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTexturePVR.h; sourceTree = ""; }; - 473FCAFF156A52A3007DD659 /* CCTexturePVR.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTexturePVR.m; sourceTree = ""; }; - 473FCB00156A52A3007DD659 /* CCTileMapAtlas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTileMapAtlas.h; sourceTree = ""; }; - 473FCB01156A52A3007DD659 /* CCTileMapAtlas.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTileMapAtlas.m; sourceTree = ""; }; - 473FCB02156A52A3007DD659 /* CCTMXLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXLayer.h; sourceTree = ""; }; - 473FCB03156A52A3007DD659 /* CCTMXLayer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXLayer.m; sourceTree = ""; }; - 473FCB04156A52A3007DD659 /* CCTMXObjectGroup.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXObjectGroup.h; sourceTree = ""; }; - 473FCB05156A52A3007DD659 /* CCTMXObjectGroup.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXObjectGroup.m; sourceTree = ""; }; - 473FCB06156A52A3007DD659 /* CCTMXTiledMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXTiledMap.h; sourceTree = ""; }; - 473FCB07156A52A3007DD659 /* CCTMXTiledMap.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXTiledMap.m; sourceTree = ""; }; - 473FCB08156A52A3007DD659 /* CCTMXXMLParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXXMLParser.h; sourceTree = ""; }; - 473FCB09156A52A3007DD659 /* CCTMXXMLParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTMXXMLParser.m; sourceTree = ""; }; - 473FCB0A156A52A3007DD659 /* CCTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTransition.h; sourceTree = ""; }; - 473FCB0B156A52A3007DD659 /* CCTransition.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTransition.m; sourceTree = ""; }; - 473FCB0C156A52A3007DD659 /* CCTransitionPageTurn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTransitionPageTurn.h; sourceTree = ""; }; - 473FCB0D156A52A3007DD659 /* CCTransitionPageTurn.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTransitionPageTurn.m; sourceTree = ""; }; - 473FCB0E156A52A3007DD659 /* CCTransitionProgress.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTransitionProgress.h; sourceTree = ""; }; - 473FCB0F156A52A3007DD659 /* CCTransitionProgress.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTransitionProgress.m; sourceTree = ""; }; - 473FCB10156A52A3007DD659 /* ccTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccTypes.h; sourceTree = ""; }; - 473FCB11156A52A3007DD659 /* cocos2d.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = cocos2d.h; sourceTree = ""; }; - 473FCB12156A52A3007DD659 /* cocos2d.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = cocos2d.m; sourceTree = ""; }; - 473FCB14156A52A3007DD659 /* CCGL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGL.h; sourceTree = ""; }; - 473FCB15156A52A3007DD659 /* CCNS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCNS.h; sourceTree = ""; }; - 473FCB17156A52A3007DD659 /* CCDirectorIOS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDirectorIOS.h; sourceTree = ""; }; - 473FCB18156A52A3007DD659 /* CCDirectorIOS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDirectorIOS.m; sourceTree = ""; }; - 473FCB19156A52A3007DD659 /* CCES2Renderer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCES2Renderer.h; sourceTree = ""; }; - 473FCB1A156A52A3007DD659 /* CCES2Renderer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCES2Renderer.m; sourceTree = ""; }; - 473FCB1B156A52A3007DD659 /* CCESRenderer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCESRenderer.h; sourceTree = ""; }; - 473FCB1C156A52A3007DD659 /* CCGLView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGLView.h; sourceTree = ""; }; - 473FCB1D156A52A3007DD659 /* CCGLView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGLView.m; sourceTree = ""; }; - 473FCB1E156A52A3007DD659 /* CCTouchDelegateProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTouchDelegateProtocol.h; sourceTree = ""; }; - 473FCB1F156A52A3007DD659 /* CCTouchDispatcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTouchDispatcher.h; sourceTree = ""; }; - 473FCB20156A52A3007DD659 /* CCTouchDispatcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTouchDispatcher.m; sourceTree = ""; }; - 473FCB21156A52A3007DD659 /* CCTouchHandler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTouchHandler.h; sourceTree = ""; }; - 473FCB22156A52A3007DD659 /* CCTouchHandler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCTouchHandler.m; sourceTree = ""; }; - 473FCB24156A52A3007DD659 /* CCDirectorMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCDirectorMac.h; sourceTree = ""; }; - 473FCB25156A52A3007DD659 /* CCDirectorMac.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCDirectorMac.m; sourceTree = ""; }; - 473FCB26156A52A3007DD659 /* CCEventDispatcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCEventDispatcher.h; sourceTree = ""; }; - 473FCB27156A52A3007DD659 /* CCEventDispatcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCEventDispatcher.m; sourceTree = ""; }; - 473FCB28156A52A3007DD659 /* CCGLView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCGLView.h; sourceTree = ""; }; - 473FCB29156A52A3007DD659 /* CCGLView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCGLView.m; sourceTree = ""; }; - 473FCB2A156A52A3007DD659 /* CCWindow.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCWindow.h; sourceTree = ""; }; - 473FCB2B156A52A3007DD659 /* CCWindow.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCWindow.m; sourceTree = ""; }; - 473FCB2D156A52A3007DD659 /* base64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = base64.c; sourceTree = ""; }; - 473FCB2E156A52A3007DD659 /* base64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = base64.h; sourceTree = ""; }; - 473FCB2F156A52A3007DD659 /* CCArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCArray.h; sourceTree = ""; }; - 473FCB30156A52A3007DD659 /* CCArray.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCArray.m; sourceTree = ""; }; - 473FCB31156A52A3007DD659 /* ccCArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccCArray.h; sourceTree = ""; }; - 473FCB32156A52A3007DD659 /* CCFileUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCFileUtils.h; sourceTree = ""; }; - 473FCB33156A52A3007DD659 /* CCFileUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCFileUtils.m; sourceTree = ""; }; - 473FCB34156A52A3007DD659 /* CCProfiling.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCProfiling.h; sourceTree = ""; }; - 473FCB35156A52A3007DD659 /* CCProfiling.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCProfiling.m; sourceTree = ""; }; - 473FCB36156A52A3007DD659 /* ccUtils.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ccUtils.c; sourceTree = ""; }; - 473FCB37156A52A3007DD659 /* ccUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccUtils.h; sourceTree = ""; }; - 473FCB38156A52A3007DD659 /* CCVertex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCVertex.h; sourceTree = ""; }; - 473FCB39156A52A3007DD659 /* CCVertex.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCVertex.m; sourceTree = ""; }; - 473FCB3A156A52A3007DD659 /* CGPointExtension.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CGPointExtension.h; sourceTree = ""; }; - 473FCB3B156A52A3007DD659 /* CGPointExtension.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CGPointExtension.m; sourceTree = ""; }; - 473FCB3C156A52A3007DD659 /* NSThread+performBlock.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSThread+performBlock.h"; sourceTree = ""; }; - 473FCB3D156A52A3007DD659 /* NSThread+performBlock.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSThread+performBlock.m"; sourceTree = ""; }; - 473FCB3E156A52A3007DD659 /* OpenGL_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OpenGL_Internal.h; sourceTree = ""; }; - 473FCB3F156A52A3007DD659 /* TGAlib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TGAlib.h; sourceTree = ""; }; - 473FCB40156A52A3007DD659 /* TGAlib.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TGAlib.m; sourceTree = ""; }; - 473FCB41156A52A3007DD659 /* TransformUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TransformUtils.h; sourceTree = ""; }; - 473FCB42156A52A3007DD659 /* TransformUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TransformUtils.m; sourceTree = ""; }; - 473FCB43156A52A3007DD659 /* uthash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = uthash.h; sourceTree = ""; }; - 473FCB44156A52A3007DD659 /* utlist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utlist.h; sourceTree = ""; }; - 473FCB45156A52A3007DD659 /* ZipUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZipUtils.h; sourceTree = ""; }; - 473FCB46156A52A3007DD659 /* ZipUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZipUtils.m; sourceTree = ""; }; - 473FCC03156A52FF007DD659 /* aabb.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = aabb.h; sourceTree = ""; }; - 473FCC05156A52FF007DD659 /* mat4stack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mat4stack.h; sourceTree = ""; }; - 473FCC06156A52FF007DD659 /* matrix.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = matrix.h; sourceTree = ""; }; - 473FCC07156A52FF007DD659 /* kazmath.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = kazmath.h; sourceTree = ""; }; - 473FCC08156A52FF007DD659 /* mat3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mat3.h; sourceTree = ""; }; - 473FCC09156A52FF007DD659 /* mat4.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mat4.h; sourceTree = ""; }; - 473FCC0A156A52FF007DD659 /* neon_matrix_impl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = neon_matrix_impl.h; sourceTree = ""; }; - 473FCC0B156A52FF007DD659 /* plane.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = plane.h; sourceTree = ""; }; - 473FCC0C156A52FF007DD659 /* quaternion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = quaternion.h; sourceTree = ""; }; - 473FCC0D156A52FF007DD659 /* ray2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ray2.h; sourceTree = ""; }; - 473FCC0E156A52FF007DD659 /* utility.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utility.h; sourceTree = ""; }; - 473FCC0F156A52FF007DD659 /* vec2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vec2.h; sourceTree = ""; }; - 473FCC10156A52FF007DD659 /* vec3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vec3.h; sourceTree = ""; }; - 473FCC11156A52FF007DD659 /* vec4.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vec4.h; sourceTree = ""; }; - 473FCC13156A52FF007DD659 /* aabb.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = aabb.c; sourceTree = ""; }; - 473FCC14156A52FF007DD659 /* ChangeLog */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ChangeLog; sourceTree = ""; }; - 473FCC15156A52FF007DD659 /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; - 473FCC17156A52FF007DD659 /* mat4stack.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mat4stack.c; sourceTree = ""; }; - 473FCC18156A52FF007DD659 /* matrix.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = matrix.c; sourceTree = ""; }; - 473FCC19156A52FF007DD659 /* mat3.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mat3.c; sourceTree = ""; }; - 473FCC1A156A52FF007DD659 /* mat4.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mat4.c; sourceTree = ""; }; - 473FCC1B156A52FF007DD659 /* neon_matrix_impl.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = neon_matrix_impl.c; sourceTree = ""; }; - 473FCC1C156A52FF007DD659 /* plane.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = plane.c; sourceTree = ""; }; - 473FCC1D156A52FF007DD659 /* quaternion.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = quaternion.c; sourceTree = ""; }; - 473FCC1E156A52FF007DD659 /* ray2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ray2.c; sourceTree = ""; }; - 473FCC1F156A52FF007DD659 /* utility.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = utility.c; sourceTree = ""; }; - 473FCC20156A52FF007DD659 /* vec2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vec2.c; sourceTree = ""; }; - 473FCC21156A52FF007DD659 /* vec3.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vec3.c; sourceTree = ""; }; - 473FCC22156A52FF007DD659 /* vec4.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vec4.c; sourceTree = ""; }; 473FCC42156A6B03007DD659 /* HelloWorldLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HelloWorldLayer.h; sourceTree = ""; }; 473FCC43156A6B03007DD659 /* HelloWorldLayer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HelloWorldLayer.m; sourceTree = ""; }; 473FCC45156A6BCE007DD659 /* GameKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GameKit.framework; path = System/Library/Frameworks/GameKit.framework; sourceTree = SDKROOT; }; @@ -551,53 +65,8 @@ 47B802CA13F269D9006B0B98 /* streak2-hd.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "streak2-hd.png"; sourceTree = ""; }; 47B802CB13F269D9006B0B98 /* streak3-hd.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "streak3-hd.png"; sourceTree = ""; }; 47B802CF13F26A4C006B0B98 /* Default-hd.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-hd.png"; sourceTree = ""; }; - 504DFBC810AF12E9006D82FE /* CLScoreServerPost.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CLScoreServerPost.h; sourceTree = ""; }; - 504DFBC910AF12E9006D82FE /* CLScoreServerPost.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CLScoreServerPost.m; sourceTree = ""; }; - 504DFBCA10AF12E9006D82FE /* CLScoreServerRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CLScoreServerRequest.h; sourceTree = ""; }; - 504DFBCB10AF12E9006D82FE /* CLScoreServerRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CLScoreServerRequest.m; sourceTree = ""; }; - 504DFBCC10AF12E9006D82FE /* cocoslive.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = cocoslive.h; sourceTree = ""; }; - 504DFBCD10AF12E9006D82FE /* cocoslive.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = cocoslive.m; sourceTree = ""; }; - 504DFC6810AF1739006D82FE /* LICENSE.cocos2d */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE.cocos2d; sourceTree = ""; }; - 504DFC6910AF1739006D82FE /* LICENSE.cocosdenshion */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE.cocosdenshion; sourceTree = ""; }; - 50674850107A3AF30090963A /* ZAttributedString.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZAttributedString.h; sourceTree = ""; }; - 50674851107A3AF30090963A /* ZAttributedString.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZAttributedString.m; sourceTree = ""; }; - 50674852107A3AF30090963A /* ZAttributedStringPrivate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZAttributedStringPrivate.h; sourceTree = ""; }; 506EDB87102F4C4000A389B3 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; 506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; - 506EE05E10304ED200A389B3 /* libcocos2d libraries.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libcocos2d libraries.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 507ED63311C638C6002ED3FC /* CDAudioManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDAudioManager.h; sourceTree = ""; }; - 507ED63411C638C6002ED3FC /* CDAudioManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDAudioManager.m; sourceTree = ""; }; - 507ED63511C638C6002ED3FC /* CDConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDConfig.h; sourceTree = ""; }; - 507ED63611C638C6002ED3FC /* CDOpenALSupport.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDOpenALSupport.h; sourceTree = ""; }; - 507ED63711C638C6002ED3FC /* CDOpenALSupport.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDOpenALSupport.m; sourceTree = ""; }; - 507ED63811C638C6002ED3FC /* CocosDenshion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CocosDenshion.h; sourceTree = ""; }; - 507ED63911C638C6002ED3FC /* CocosDenshion.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CocosDenshion.m; sourceTree = ""; }; - 507ED63A11C638C6002ED3FC /* SimpleAudioEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleAudioEngine.h; sourceTree = ""; }; - 507ED63B11C638C6002ED3FC /* SimpleAudioEngine.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SimpleAudioEngine.m; sourceTree = ""; }; - 50F41307106926B2002A0D5E /* FontLabel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FontLabel.h; sourceTree = ""; }; - 50F41308106926B2002A0D5E /* FontLabel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FontLabel.m; sourceTree = ""; }; - 50F41309106926B2002A0D5E /* FontLabelStringDrawing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FontLabelStringDrawing.h; sourceTree = ""; }; - 50F4130A106926B2002A0D5E /* FontLabelStringDrawing.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FontLabelStringDrawing.m; sourceTree = ""; }; - 50F4130B106926B2002A0D5E /* FontManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FontManager.h; sourceTree = ""; }; - 50F4130C106926B2002A0D5E /* FontManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FontManager.m; sourceTree = ""; }; - 50F4130F106926B2002A0D5E /* ZFont.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZFont.h; sourceTree = ""; }; - 50F41310106926B2002A0D5E /* ZFont.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZFont.m; sourceTree = ""; }; - 50F41312106926B2002A0D5E /* CDataScanner.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDataScanner.h; sourceTree = ""; }; - 50F41313106926B2002A0D5E /* CDataScanner.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDataScanner.m; sourceTree = ""; }; - 50F41315106926B2002A0D5E /* CDataScanner_Extensions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDataScanner_Extensions.h; sourceTree = ""; }; - 50F41316106926B2002A0D5E /* CDataScanner_Extensions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDataScanner_Extensions.m; sourceTree = ""; }; - 50F41317106926B2002A0D5E /* NSCharacterSet_Extensions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NSCharacterSet_Extensions.h; sourceTree = ""; }; - 50F41318106926B2002A0D5E /* NSCharacterSet_Extensions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NSCharacterSet_Extensions.m; sourceTree = ""; }; - 50F41319106926B2002A0D5E /* NSDictionary_JSONExtensions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NSDictionary_JSONExtensions.h; sourceTree = ""; }; - 50F4131A106926B2002A0D5E /* NSDictionary_JSONExtensions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NSDictionary_JSONExtensions.m; sourceTree = ""; }; - 50F4131B106926B2002A0D5E /* NSScanner_Extensions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NSScanner_Extensions.h; sourceTree = ""; }; - 50F4131C106926B2002A0D5E /* NSScanner_Extensions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NSScanner_Extensions.m; sourceTree = ""; }; - 50F4131E106926B2002A0D5E /* CJSONDeserializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CJSONDeserializer.h; sourceTree = ""; }; - 50F4131F106926B2002A0D5E /* CJSONDeserializer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CJSONDeserializer.m; sourceTree = ""; }; - 50F41320106926B2002A0D5E /* CJSONScanner.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CJSONScanner.h; sourceTree = ""; }; - 50F41321106926B2002A0D5E /* CJSONScanner.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CJSONScanner.m; sourceTree = ""; }; - 50F41322106926B2002A0D5E /* CJSONSerializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CJSONSerializer.h; sourceTree = ""; }; - 50F41323106926B2002A0D5E /* CJSONSerializer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CJSONSerializer.m; sourceTree = ""; }; 50F414EC1069373D002A0D5E /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = ""; }; 50F414EE1069373D002A0D5E /* Icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Icon.png; sourceTree = ""; }; 50F414EF1069373D002A0D5E /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -631,21 +100,6 @@ DC6640050F83B3EA000B3E49 /* OpenAL.framework in Frameworks */, 506EDB88102F4C4000A389B3 /* libz.dylib in Frameworks */, 506EDBA5102F4C9F00A389B3 /* AVFoundation.framework in Frameworks */, - 506EE1A91030508200A389B3 /* libcocos2d libraries.a in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 506EE05C10304ED200A389B3 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 505574581045D68500A31725 /* AVFoundation.framework in Frameworks */, - 505574591045D68500A31725 /* AudioToolbox.framework in Frameworks */, - 5055745A1045D68500A31725 /* CoreGraphics.framework in Frameworks */, - 5055745B1045D68500A31725 /* OpenAL.framework in Frameworks */, - 5055745C1045D68500A31725 /* OpenGLES.framework in Frameworks */, - 5055745D1045D68500A31725 /* QuartzCore.framework in Frameworks */, - 5055745E1045D69D00A31725 /* libz.dylib in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -656,7 +110,6 @@ isa = PBXGroup; children = ( 1D6058910D05DD3D006BFB54 /* CCBlade.app */, - 506EE05E10304ED200A389B3 /* libcocos2d libraries.a */, ); name = Products; sourceTree = ""; @@ -665,9 +118,6 @@ isa = PBXGroup; children = ( 473FCC45156A6BCE007DD659 /* GameKit.framework */, - 504DFC6810AF1739006D82FE /* LICENSE.cocos2d */, - 504DFC6910AF1739006D82FE /* LICENSE.cocosdenshion */, - 506EDAA3102F461B00A389B3 /* cocos2d Sources */, 2D500B1D0D5A766B00DBA0E3 /* Classes */, 29B97315FDCFA39411CA2CEA /* Other Sources */, 50F414EB1069373D002A0D5E /* Resources */, @@ -717,411 +167,6 @@ path = Classes; sourceTree = ""; }; - 473FCA89156A52A3007DD659 /* cocos2d */ = { - isa = PBXGroup; - children = ( - 473FCA8A156A52A3007DD659 /* CCAction.h */, - 473FCA8B156A52A3007DD659 /* CCAction.m */, - 473FCA8C156A52A3007DD659 /* CCActionCamera.h */, - 473FCA8D156A52A3007DD659 /* CCActionCamera.m */, - 473FCA8E156A52A3007DD659 /* CCActionEase.h */, - 473FCA8F156A52A3007DD659 /* CCActionEase.m */, - 473FCA90156A52A3007DD659 /* CCActionGrid.h */, - 473FCA91156A52A3007DD659 /* CCActionGrid.m */, - 473FCA92156A52A3007DD659 /* CCActionGrid3D.h */, - 473FCA93156A52A3007DD659 /* CCActionGrid3D.m */, - 473FCA94156A52A3007DD659 /* CCActionInstant.h */, - 473FCA95156A52A3007DD659 /* CCActionInstant.m */, - 473FCA96156A52A3007DD659 /* CCActionInterval.h */, - 473FCA97156A52A3007DD659 /* CCActionInterval.m */, - 473FCA98156A52A3007DD659 /* CCActionManager.h */, - 473FCA99156A52A3007DD659 /* CCActionManager.m */, - 473FCA9A156A52A3007DD659 /* CCActionPageTurn3D.h */, - 473FCA9B156A52A3007DD659 /* CCActionPageTurn3D.m */, - 473FCA9C156A52A3007DD659 /* CCActionProgressTimer.h */, - 473FCA9D156A52A3007DD659 /* CCActionProgressTimer.m */, - 473FCA9E156A52A3007DD659 /* CCActionTiledGrid.h */, - 473FCA9F156A52A3007DD659 /* CCActionTiledGrid.m */, - 473FCAA0156A52A3007DD659 /* CCActionTween.h */, - 473FCAA1156A52A3007DD659 /* CCActionTween.m */, - 473FCAA2156A52A3007DD659 /* CCAnimation.h */, - 473FCAA3156A52A3007DD659 /* CCAnimation.m */, - 473FCAA4156A52A3007DD659 /* CCAnimationCache.h */, - 473FCAA5156A52A3007DD659 /* CCAnimationCache.m */, - 473FCAA6156A52A3007DD659 /* CCAtlasNode.h */, - 473FCAA7156A52A3007DD659 /* CCAtlasNode.m */, - 473FCAA8156A52A3007DD659 /* CCCamera.h */, - 473FCAA9156A52A3007DD659 /* CCCamera.m */, - 473FCAAA156A52A3007DD659 /* ccConfig.h */, - 473FCAAB156A52A3007DD659 /* CCConfiguration.h */, - 473FCAAC156A52A3007DD659 /* CCConfiguration.m */, - 473FCAAD156A52A3007DD659 /* ccDeprecated.h */, - 473FCAAE156A52A3007DD659 /* ccDeprecated.m */, - 473FCAAF156A52A3007DD659 /* CCDirector.h */, - 473FCAB0156A52A3007DD659 /* CCDirector.m */, - 473FCAB1156A52A3007DD659 /* CCDrawingPrimitives.h */, - 473FCAB2156A52A3007DD659 /* CCDrawingPrimitives.m */, - 473FCAB3156A52A3007DD659 /* CCGLProgram.h */, - 473FCAB4156A52A3007DD659 /* CCGLProgram.m */, - 473FCAB5156A52A3007DD659 /* ccGLStateCache.h */, - 473FCAB6156A52A3007DD659 /* ccGLStateCache.m */, - 473FCAB7156A52A3007DD659 /* CCGrabber.h */, - 473FCAB8156A52A3007DD659 /* CCGrabber.m */, - 473FCAB9156A52A3007DD659 /* CCGrid.h */, - 473FCABA156A52A3007DD659 /* CCGrid.m */, - 473FCABB156A52A3007DD659 /* CCLabelAtlas.h */, - 473FCABC156A52A3007DD659 /* CCLabelAtlas.m */, - 473FCABD156A52A3007DD659 /* CCLabelBMFont.h */, - 473FCABE156A52A3007DD659 /* CCLabelBMFont.m */, - 473FCABF156A52A3007DD659 /* CCLabelTTF.h */, - 473FCAC0156A52A3007DD659 /* CCLabelTTF.m */, - 473FCAC1156A52A3007DD659 /* CCLayer.h */, - 473FCAC2156A52A3007DD659 /* CCLayer.m */, - 473FCAC3156A52A3007DD659 /* ccMacros.h */, - 473FCAC4156A52A3007DD659 /* CCMenu.h */, - 473FCAC5156A52A3007DD659 /* CCMenu.m */, - 473FCAC6156A52A3007DD659 /* CCMenuItem.h */, - 473FCAC7156A52A3007DD659 /* CCMenuItem.m */, - 473FCAC8156A52A3007DD659 /* CCMotionStreak.h */, - 473FCAC9156A52A3007DD659 /* CCMotionStreak.m */, - 473FCACA156A52A3007DD659 /* CCNode.h */, - 473FCACB156A52A3007DD659 /* CCNode.m */, - 473FCACC156A52A3007DD659 /* CCParallaxNode.h */, - 473FCACD156A52A3007DD659 /* CCParallaxNode.m */, - 473FCACE156A52A3007DD659 /* CCParticleBatchNode.h */, - 473FCACF156A52A3007DD659 /* CCParticleBatchNode.m */, - 473FCAD0156A52A3007DD659 /* CCParticleExamples.h */, - 473FCAD1156A52A3007DD659 /* CCParticleExamples.m */, - 473FCAD2156A52A3007DD659 /* CCParticleSystem.h */, - 473FCAD3156A52A3007DD659 /* CCParticleSystem.m */, - 473FCAD4156A52A3007DD659 /* CCParticleSystemQuad.h */, - 473FCAD5156A52A3007DD659 /* CCParticleSystemQuad.m */, - 473FCAD6156A52A3007DD659 /* CCProgressTimer.h */, - 473FCAD7156A52A3007DD659 /* CCProgressTimer.m */, - 473FCAD8156A52A3007DD659 /* CCProtocols.h */, - 473FCAD9156A52A3007DD659 /* CCRenderTexture.h */, - 473FCADA156A52A3007DD659 /* CCRenderTexture.m */, - 473FCADB156A52A3007DD659 /* CCScene.h */, - 473FCADC156A52A3007DD659 /* CCScene.m */, - 473FCADD156A52A3007DD659 /* CCScheduler.h */, - 473FCADE156A52A3007DD659 /* CCScheduler.m */, - 473FCADF156A52A3007DD659 /* ccShader_Position_uColor_frag.h */, - 473FCAE0156A52A3007DD659 /* ccShader_Position_uColor_vert.h */, - 473FCAE1156A52A3007DD659 /* ccShader_PositionColor_frag.h */, - 473FCAE2156A52A3007DD659 /* ccShader_PositionColor_vert.h */, - 473FCAE3156A52A3007DD659 /* ccShader_PositionTexture_frag.h */, - 473FCAE4156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h */, - 473FCAE5156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h */, - 473FCAE6156A52A3007DD659 /* ccShader_PositionTexture_vert.h */, - 473FCAE7156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h */, - 473FCAE8156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h */, - 473FCAE9156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h */, - 473FCAEA156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h */, - 473FCAEB156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h */, - 473FCAEC156A52A3007DD659 /* CCShaderCache.h */, - 473FCAED156A52A3007DD659 /* CCShaderCache.m */, - 473FCAEE156A52A3007DD659 /* ccShaders.h */, - 473FCAEF156A52A3007DD659 /* ccShaders.m */, - 473FCAF0156A52A3007DD659 /* CCSprite.h */, - 473FCAF1156A52A3007DD659 /* CCSprite.m */, - 473FCAF2156A52A3007DD659 /* CCSpriteBatchNode.h */, - 473FCAF3156A52A3007DD659 /* CCSpriteBatchNode.m */, - 473FCAF4156A52A3007DD659 /* CCSpriteFrame.h */, - 473FCAF5156A52A3007DD659 /* CCSpriteFrame.m */, - 473FCAF6156A52A3007DD659 /* CCSpriteFrameCache.h */, - 473FCAF7156A52A3007DD659 /* CCSpriteFrameCache.m */, - 473FCAF8156A52A3007DD659 /* CCTexture2D.h */, - 473FCAF9156A52A3007DD659 /* CCTexture2D.m */, - 473FCAFA156A52A3007DD659 /* CCTextureAtlas.h */, - 473FCAFB156A52A3007DD659 /* CCTextureAtlas.m */, - 473FCAFC156A52A3007DD659 /* CCTextureCache.h */, - 473FCAFD156A52A3007DD659 /* CCTextureCache.m */, - 473FCAFE156A52A3007DD659 /* CCTexturePVR.h */, - 473FCAFF156A52A3007DD659 /* CCTexturePVR.m */, - 473FCB00156A52A3007DD659 /* CCTileMapAtlas.h */, - 473FCB01156A52A3007DD659 /* CCTileMapAtlas.m */, - 473FCB02156A52A3007DD659 /* CCTMXLayer.h */, - 473FCB03156A52A3007DD659 /* CCTMXLayer.m */, - 473FCB04156A52A3007DD659 /* CCTMXObjectGroup.h */, - 473FCB05156A52A3007DD659 /* CCTMXObjectGroup.m */, - 473FCB06156A52A3007DD659 /* CCTMXTiledMap.h */, - 473FCB07156A52A3007DD659 /* CCTMXTiledMap.m */, - 473FCB08156A52A3007DD659 /* CCTMXXMLParser.h */, - 473FCB09156A52A3007DD659 /* CCTMXXMLParser.m */, - 473FCB0A156A52A3007DD659 /* CCTransition.h */, - 473FCB0B156A52A3007DD659 /* CCTransition.m */, - 473FCB0C156A52A3007DD659 /* CCTransitionPageTurn.h */, - 473FCB0D156A52A3007DD659 /* CCTransitionPageTurn.m */, - 473FCB0E156A52A3007DD659 /* CCTransitionProgress.h */, - 473FCB0F156A52A3007DD659 /* CCTransitionProgress.m */, - 473FCB10156A52A3007DD659 /* ccTypes.h */, - 473FCB11156A52A3007DD659 /* cocos2d.h */, - 473FCB12156A52A3007DD659 /* cocos2d.m */, - 473FCB13156A52A3007DD659 /* Platforms */, - 473FCB2C156A52A3007DD659 /* Support */, - ); - name = cocos2d; - path = libs/cocos2d; - sourceTree = ""; - }; - 473FCB13156A52A3007DD659 /* Platforms */ = { - isa = PBXGroup; - children = ( - 473FCB14156A52A3007DD659 /* CCGL.h */, - 473FCB15156A52A3007DD659 /* CCNS.h */, - 473FCB16156A52A3007DD659 /* iOS */, - 473FCB23156A52A3007DD659 /* Mac */, - ); - path = Platforms; - sourceTree = ""; - }; - 473FCB16156A52A3007DD659 /* iOS */ = { - isa = PBXGroup; - children = ( - 473FCB17156A52A3007DD659 /* CCDirectorIOS.h */, - 473FCB18156A52A3007DD659 /* CCDirectorIOS.m */, - 473FCB19156A52A3007DD659 /* CCES2Renderer.h */, - 473FCB1A156A52A3007DD659 /* CCES2Renderer.m */, - 473FCB1B156A52A3007DD659 /* CCESRenderer.h */, - 473FCB1C156A52A3007DD659 /* CCGLView.h */, - 473FCB1D156A52A3007DD659 /* CCGLView.m */, - 473FCB1E156A52A3007DD659 /* CCTouchDelegateProtocol.h */, - 473FCB1F156A52A3007DD659 /* CCTouchDispatcher.h */, - 473FCB20156A52A3007DD659 /* CCTouchDispatcher.m */, - 473FCB21156A52A3007DD659 /* CCTouchHandler.h */, - 473FCB22156A52A3007DD659 /* CCTouchHandler.m */, - ); - path = iOS; - sourceTree = ""; - }; - 473FCB23156A52A3007DD659 /* Mac */ = { - isa = PBXGroup; - children = ( - 473FCB24156A52A3007DD659 /* CCDirectorMac.h */, - 473FCB25156A52A3007DD659 /* CCDirectorMac.m */, - 473FCB26156A52A3007DD659 /* CCEventDispatcher.h */, - 473FCB27156A52A3007DD659 /* CCEventDispatcher.m */, - 473FCB28156A52A3007DD659 /* CCGLView.h */, - 473FCB29156A52A3007DD659 /* CCGLView.m */, - 473FCB2A156A52A3007DD659 /* CCWindow.h */, - 473FCB2B156A52A3007DD659 /* CCWindow.m */, - ); - path = Mac; - sourceTree = ""; - }; - 473FCB2C156A52A3007DD659 /* Support */ = { - isa = PBXGroup; - children = ( - 473FCB2D156A52A3007DD659 /* base64.c */, - 473FCB2E156A52A3007DD659 /* base64.h */, - 473FCB2F156A52A3007DD659 /* CCArray.h */, - 473FCB30156A52A3007DD659 /* CCArray.m */, - 473FCB31156A52A3007DD659 /* ccCArray.h */, - 473FCB32156A52A3007DD659 /* CCFileUtils.h */, - 473FCB33156A52A3007DD659 /* CCFileUtils.m */, - 473FCB34156A52A3007DD659 /* CCProfiling.h */, - 473FCB35156A52A3007DD659 /* CCProfiling.m */, - 473FCB36156A52A3007DD659 /* ccUtils.c */, - 473FCB37156A52A3007DD659 /* ccUtils.h */, - 473FCB38156A52A3007DD659 /* CCVertex.h */, - 473FCB39156A52A3007DD659 /* CCVertex.m */, - 473FCB3A156A52A3007DD659 /* CGPointExtension.h */, - 473FCB3B156A52A3007DD659 /* CGPointExtension.m */, - 473FCB3C156A52A3007DD659 /* NSThread+performBlock.h */, - 473FCB3D156A52A3007DD659 /* NSThread+performBlock.m */, - 473FCB3E156A52A3007DD659 /* OpenGL_Internal.h */, - 473FCB3F156A52A3007DD659 /* TGAlib.h */, - 473FCB40156A52A3007DD659 /* TGAlib.m */, - 473FCB41156A52A3007DD659 /* TransformUtils.h */, - 473FCB42156A52A3007DD659 /* TransformUtils.m */, - 473FCB43156A52A3007DD659 /* uthash.h */, - 473FCB44156A52A3007DD659 /* utlist.h */, - 473FCB45156A52A3007DD659 /* ZipUtils.h */, - 473FCB46156A52A3007DD659 /* ZipUtils.m */, - ); - path = Support; - sourceTree = ""; - }; - 473FCC00156A52FF007DD659 /* kazmath */ = { - isa = PBXGroup; - children = ( - 473FCC01156A52FF007DD659 /* include */, - 473FCC12156A52FF007DD659 /* src */, - ); - name = kazmath; - path = libs/kazmath; - sourceTree = ""; - }; - 473FCC01156A52FF007DD659 /* include */ = { - isa = PBXGroup; - children = ( - 473FCC02156A52FF007DD659 /* kazmath */, - ); - path = include; - sourceTree = ""; - }; - 473FCC02156A52FF007DD659 /* kazmath */ = { - isa = PBXGroup; - children = ( - 473FCC03156A52FF007DD659 /* aabb.h */, - 473FCC04156A52FF007DD659 /* GL */, - 473FCC07156A52FF007DD659 /* kazmath.h */, - 473FCC08156A52FF007DD659 /* mat3.h */, - 473FCC09156A52FF007DD659 /* mat4.h */, - 473FCC0A156A52FF007DD659 /* neon_matrix_impl.h */, - 473FCC0B156A52FF007DD659 /* plane.h */, - 473FCC0C156A52FF007DD659 /* quaternion.h */, - 473FCC0D156A52FF007DD659 /* ray2.h */, - 473FCC0E156A52FF007DD659 /* utility.h */, - 473FCC0F156A52FF007DD659 /* vec2.h */, - 473FCC10156A52FF007DD659 /* vec3.h */, - 473FCC11156A52FF007DD659 /* vec4.h */, - ); - path = kazmath; - sourceTree = ""; - }; - 473FCC04156A52FF007DD659 /* GL */ = { - isa = PBXGroup; - children = ( - 473FCC05156A52FF007DD659 /* mat4stack.h */, - 473FCC06156A52FF007DD659 /* matrix.h */, - ); - path = GL; - sourceTree = ""; - }; - 473FCC12156A52FF007DD659 /* src */ = { - isa = PBXGroup; - children = ( - 473FCC13156A52FF007DD659 /* aabb.c */, - 473FCC14156A52FF007DD659 /* ChangeLog */, - 473FCC15156A52FF007DD659 /* CMakeLists.txt */, - 473FCC16156A52FF007DD659 /* GL */, - 473FCC19156A52FF007DD659 /* mat3.c */, - 473FCC1A156A52FF007DD659 /* mat4.c */, - 473FCC1B156A52FF007DD659 /* neon_matrix_impl.c */, - 473FCC1C156A52FF007DD659 /* plane.c */, - 473FCC1D156A52FF007DD659 /* quaternion.c */, - 473FCC1E156A52FF007DD659 /* ray2.c */, - 473FCC1F156A52FF007DD659 /* utility.c */, - 473FCC20156A52FF007DD659 /* vec2.c */, - 473FCC21156A52FF007DD659 /* vec3.c */, - 473FCC22156A52FF007DD659 /* vec4.c */, - ); - path = src; - sourceTree = ""; - }; - 473FCC16156A52FF007DD659 /* GL */ = { - isa = PBXGroup; - children = ( - 473FCC17156A52FF007DD659 /* mat4stack.c */, - 473FCC18156A52FF007DD659 /* matrix.c */, - ); - path = GL; - sourceTree = ""; - }; - 504DFBC710AF12E9006D82FE /* cocoslive */ = { - isa = PBXGroup; - children = ( - 504DFBC810AF12E9006D82FE /* CLScoreServerPost.h */, - 504DFBC910AF12E9006D82FE /* CLScoreServerPost.m */, - 504DFBCA10AF12E9006D82FE /* CLScoreServerRequest.h */, - 504DFBCB10AF12E9006D82FE /* CLScoreServerRequest.m */, - 504DFBCC10AF12E9006D82FE /* cocoslive.h */, - 504DFBCD10AF12E9006D82FE /* cocoslive.m */, - ); - name = cocoslive; - path = libs/cocoslive; - sourceTree = ""; - }; - 506EDAA3102F461B00A389B3 /* cocos2d Sources */ = { - isa = PBXGroup; - children = ( - 473FCC00156A52FF007DD659 /* kazmath */, - 473FCA89156A52A3007DD659 /* cocos2d */, - 507ED63211C638C6002ED3FC /* CocosDenshion */, - 504DFBC710AF12E9006D82FE /* cocoslive */, - 50F41306106926B2002A0D5E /* FontLabel */, - 50F41311106926B2002A0D5E /* TouchJSON */, - ); - name = "cocos2d Sources"; - sourceTree = ""; - }; - 507ED63211C638C6002ED3FC /* CocosDenshion */ = { - isa = PBXGroup; - children = ( - 507ED63311C638C6002ED3FC /* CDAudioManager.h */, - 507ED63411C638C6002ED3FC /* CDAudioManager.m */, - 507ED63511C638C6002ED3FC /* CDConfig.h */, - 507ED63611C638C6002ED3FC /* CDOpenALSupport.h */, - 507ED63711C638C6002ED3FC /* CDOpenALSupport.m */, - 507ED63811C638C6002ED3FC /* CocosDenshion.h */, - 507ED63911C638C6002ED3FC /* CocosDenshion.m */, - 507ED63A11C638C6002ED3FC /* SimpleAudioEngine.h */, - 507ED63B11C638C6002ED3FC /* SimpleAudioEngine.m */, - ); - name = CocosDenshion; - path = libs/CocosDenshion; - sourceTree = ""; - }; - 50F41306106926B2002A0D5E /* FontLabel */ = { - isa = PBXGroup; - children = ( - 50674850107A3AF30090963A /* ZAttributedString.h */, - 50674851107A3AF30090963A /* ZAttributedString.m */, - 50674852107A3AF30090963A /* ZAttributedStringPrivate.h */, - 50F41307106926B2002A0D5E /* FontLabel.h */, - 50F41308106926B2002A0D5E /* FontLabel.m */, - 50F41309106926B2002A0D5E /* FontLabelStringDrawing.h */, - 50F4130A106926B2002A0D5E /* FontLabelStringDrawing.m */, - 50F4130B106926B2002A0D5E /* FontManager.h */, - 50F4130C106926B2002A0D5E /* FontManager.m */, - 50F4130F106926B2002A0D5E /* ZFont.h */, - 50F41310106926B2002A0D5E /* ZFont.m */, - ); - name = FontLabel; - path = libs/FontLabel; - sourceTree = ""; - }; - 50F41311106926B2002A0D5E /* TouchJSON */ = { - isa = PBXGroup; - children = ( - 50F41312106926B2002A0D5E /* CDataScanner.h */, - 50F41313106926B2002A0D5E /* CDataScanner.m */, - 50F41314106926B2002A0D5E /* Extensions */, - 50F4131D106926B2002A0D5E /* JSON */, - ); - name = TouchJSON; - path = libs/TouchJSON; - sourceTree = ""; - }; - 50F41314106926B2002A0D5E /* Extensions */ = { - isa = PBXGroup; - children = ( - 50F41315106926B2002A0D5E /* CDataScanner_Extensions.h */, - 50F41316106926B2002A0D5E /* CDataScanner_Extensions.m */, - 50F41317106926B2002A0D5E /* NSCharacterSet_Extensions.h */, - 50F41318106926B2002A0D5E /* NSCharacterSet_Extensions.m */, - 50F41319106926B2002A0D5E /* NSDictionary_JSONExtensions.h */, - 50F4131A106926B2002A0D5E /* NSDictionary_JSONExtensions.m */, - 50F4131B106926B2002A0D5E /* NSScanner_Extensions.h */, - 50F4131C106926B2002A0D5E /* NSScanner_Extensions.m */, - ); - path = Extensions; - sourceTree = ""; - }; - 50F4131D106926B2002A0D5E /* JSON */ = { - isa = PBXGroup; - children = ( - 50F4131E106926B2002A0D5E /* CJSONDeserializer.h */, - 50F4131F106926B2002A0D5E /* CJSONDeserializer.m */, - 50F41320106926B2002A0D5E /* CJSONScanner.h */, - 50F41321106926B2002A0D5E /* CJSONScanner.m */, - 50F41322106926B2002A0D5E /* CJSONSerializer.h */, - 50F41323106926B2002A0D5E /* CJSONSerializer.m */, - ); - path = JSON; - sourceTree = ""; - }; 50F414EB1069373D002A0D5E /* Resources */ = { isa = PBXGroup; children = ( @@ -1150,157 +195,6 @@ }; /* End PBXGroup section */ -/* Begin PBXHeadersBuildPhase section */ - 506EE05A10304ED200A389B3 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 50F4132A106926B2002A0D5E /* FontLabel.h in Headers */, - 50F4132C106926B2002A0D5E /* FontLabelStringDrawing.h in Headers */, - 50F4132E106926B2002A0D5E /* FontManager.h in Headers */, - 50F41332106926B2002A0D5E /* ZFont.h in Headers */, - 50F41334106926B2002A0D5E /* CDataScanner.h in Headers */, - 50F41336106926B2002A0D5E /* CDataScanner_Extensions.h in Headers */, - 50F41338106926B2002A0D5E /* NSCharacterSet_Extensions.h in Headers */, - 50F4133A106926B2002A0D5E /* NSDictionary_JSONExtensions.h in Headers */, - 50F4133C106926B2002A0D5E /* NSScanner_Extensions.h in Headers */, - 50F4133E106926B2002A0D5E /* CJSONDeserializer.h in Headers */, - 50F41340106926B2002A0D5E /* CJSONScanner.h in Headers */, - 50F41342106926B2002A0D5E /* CJSONSerializer.h in Headers */, - 50674853107A3AF30090963A /* ZAttributedString.h in Headers */, - 50674855107A3AF30090963A /* ZAttributedStringPrivate.h in Headers */, - 504DFBCE10AF12E9006D82FE /* CLScoreServerPost.h in Headers */, - 504DFBD010AF12E9006D82FE /* CLScoreServerRequest.h in Headers */, - 504DFBD210AF12E9006D82FE /* cocoslive.h in Headers */, - 507ED63C11C638C6002ED3FC /* CDAudioManager.h in Headers */, - 507ED63E11C638C6002ED3FC /* CDConfig.h in Headers */, - 507ED63F11C638C6002ED3FC /* CDOpenALSupport.h in Headers */, - 507ED64111C638C6002ED3FC /* CocosDenshion.h in Headers */, - 507ED64311C638C6002ED3FC /* SimpleAudioEngine.h in Headers */, - 473FCB47156A52A3007DD659 /* CCAction.h in Headers */, - 473FCB49156A52A3007DD659 /* CCActionCamera.h in Headers */, - 473FCB4B156A52A3007DD659 /* CCActionEase.h in Headers */, - 473FCB4D156A52A3007DD659 /* CCActionGrid.h in Headers */, - 473FCB4F156A52A3007DD659 /* CCActionGrid3D.h in Headers */, - 473FCB51156A52A3007DD659 /* CCActionInstant.h in Headers */, - 473FCB53156A52A3007DD659 /* CCActionInterval.h in Headers */, - 473FCB55156A52A3007DD659 /* CCActionManager.h in Headers */, - 473FCB57156A52A3007DD659 /* CCActionPageTurn3D.h in Headers */, - 473FCB59156A52A3007DD659 /* CCActionProgressTimer.h in Headers */, - 473FCB5B156A52A3007DD659 /* CCActionTiledGrid.h in Headers */, - 473FCB5D156A52A3007DD659 /* CCActionTween.h in Headers */, - 473FCB5F156A52A3007DD659 /* CCAnimation.h in Headers */, - 473FCB61156A52A3007DD659 /* CCAnimationCache.h in Headers */, - 473FCB63156A52A3007DD659 /* CCAtlasNode.h in Headers */, - 473FCB65156A52A3007DD659 /* CCCamera.h in Headers */, - 473FCB67156A52A3007DD659 /* ccConfig.h in Headers */, - 473FCB68156A52A3007DD659 /* CCConfiguration.h in Headers */, - 473FCB6A156A52A3007DD659 /* ccDeprecated.h in Headers */, - 473FCB6C156A52A3007DD659 /* CCDirector.h in Headers */, - 473FCB6E156A52A3007DD659 /* CCDrawingPrimitives.h in Headers */, - 473FCB70156A52A3007DD659 /* CCGLProgram.h in Headers */, - 473FCB72156A52A3007DD659 /* ccGLStateCache.h in Headers */, - 473FCB74156A52A3007DD659 /* CCGrabber.h in Headers */, - 473FCB76156A52A3007DD659 /* CCGrid.h in Headers */, - 473FCB78156A52A3007DD659 /* CCLabelAtlas.h in Headers */, - 473FCB7A156A52A3007DD659 /* CCLabelBMFont.h in Headers */, - 473FCB7C156A52A3007DD659 /* CCLabelTTF.h in Headers */, - 473FCB7E156A52A3007DD659 /* CCLayer.h in Headers */, - 473FCB80156A52A3007DD659 /* ccMacros.h in Headers */, - 473FCB81156A52A3007DD659 /* CCMenu.h in Headers */, - 473FCB83156A52A3007DD659 /* CCMenuItem.h in Headers */, - 473FCB85156A52A3007DD659 /* CCMotionStreak.h in Headers */, - 473FCB87156A52A3007DD659 /* CCNode.h in Headers */, - 473FCB89156A52A3007DD659 /* CCParallaxNode.h in Headers */, - 473FCB8B156A52A3007DD659 /* CCParticleBatchNode.h in Headers */, - 473FCB8D156A52A3007DD659 /* CCParticleExamples.h in Headers */, - 473FCB8F156A52A3007DD659 /* CCParticleSystem.h in Headers */, - 473FCB91156A52A3007DD659 /* CCParticleSystemQuad.h in Headers */, - 473FCB93156A52A3007DD659 /* CCProgressTimer.h in Headers */, - 473FCB95156A52A3007DD659 /* CCProtocols.h in Headers */, - 473FCB96156A52A3007DD659 /* CCRenderTexture.h in Headers */, - 473FCB98156A52A3007DD659 /* CCScene.h in Headers */, - 473FCB9A156A52A3007DD659 /* CCScheduler.h in Headers */, - 473FCB9C156A52A3007DD659 /* ccShader_Position_uColor_frag.h in Headers */, - 473FCB9D156A52A3007DD659 /* ccShader_Position_uColor_vert.h in Headers */, - 473FCB9E156A52A3007DD659 /* ccShader_PositionColor_frag.h in Headers */, - 473FCB9F156A52A3007DD659 /* ccShader_PositionColor_vert.h in Headers */, - 473FCBA0156A52A3007DD659 /* ccShader_PositionTexture_frag.h in Headers */, - 473FCBA1156A52A3007DD659 /* ccShader_PositionTexture_uColor_frag.h in Headers */, - 473FCBA2156A52A3007DD659 /* ccShader_PositionTexture_uColor_vert.h in Headers */, - 473FCBA3156A52A3007DD659 /* ccShader_PositionTexture_vert.h in Headers */, - 473FCBA4156A52A3007DD659 /* ccShader_PositionTextureA8Color_frag.h in Headers */, - 473FCBA5156A52A3007DD659 /* ccShader_PositionTextureA8Color_vert.h in Headers */, - 473FCBA6156A52A3007DD659 /* ccShader_PositionTextureColor_frag.h in Headers */, - 473FCBA7156A52A3007DD659 /* ccShader_PositionTextureColor_vert.h in Headers */, - 473FCBA8156A52A3007DD659 /* ccShader_PositionTextureColorAlphaTest_frag.h in Headers */, - 473FCBA9156A52A3007DD659 /* CCShaderCache.h in Headers */, - 473FCBAB156A52A3007DD659 /* ccShaders.h in Headers */, - 473FCBAD156A52A3007DD659 /* CCSprite.h in Headers */, - 473FCBAF156A52A3007DD659 /* CCSpriteBatchNode.h in Headers */, - 473FCBB1156A52A3007DD659 /* CCSpriteFrame.h in Headers */, - 473FCBB3156A52A3007DD659 /* CCSpriteFrameCache.h in Headers */, - 473FCBB5156A52A3007DD659 /* CCTexture2D.h in Headers */, - 473FCBB7156A52A3007DD659 /* CCTextureAtlas.h in Headers */, - 473FCBB9156A52A3007DD659 /* CCTextureCache.h in Headers */, - 473FCBBB156A52A3007DD659 /* CCTexturePVR.h in Headers */, - 473FCBBD156A52A3007DD659 /* CCTileMapAtlas.h in Headers */, - 473FCBBF156A52A3007DD659 /* CCTMXLayer.h in Headers */, - 473FCBC1156A52A3007DD659 /* CCTMXObjectGroup.h in Headers */, - 473FCBC3156A52A3007DD659 /* CCTMXTiledMap.h in Headers */, - 473FCBC5156A52A3007DD659 /* CCTMXXMLParser.h in Headers */, - 473FCBC7156A52A3007DD659 /* CCTransition.h in Headers */, - 473FCBC9156A52A3007DD659 /* CCTransitionPageTurn.h in Headers */, - 473FCBCB156A52A3007DD659 /* CCTransitionProgress.h in Headers */, - 473FCBCD156A52A3007DD659 /* ccTypes.h in Headers */, - 473FCBCE156A52A3007DD659 /* cocos2d.h in Headers */, - 473FCBD0156A52A3007DD659 /* CCGL.h in Headers */, - 473FCBD1156A52A3007DD659 /* CCNS.h in Headers */, - 473FCBD2156A52A3007DD659 /* CCDirectorIOS.h in Headers */, - 473FCBD4156A52A3007DD659 /* CCES2Renderer.h in Headers */, - 473FCBD6156A52A3007DD659 /* CCESRenderer.h in Headers */, - 473FCBD7156A52A3007DD659 /* CCGLView.h in Headers */, - 473FCBD9156A52A3007DD659 /* CCTouchDelegateProtocol.h in Headers */, - 473FCBDA156A52A3007DD659 /* CCTouchDispatcher.h in Headers */, - 473FCBDC156A52A3007DD659 /* CCTouchHandler.h in Headers */, - 473FCBDE156A52A3007DD659 /* CCDirectorMac.h in Headers */, - 473FCBE0156A52A3007DD659 /* CCEventDispatcher.h in Headers */, - 473FCBE2156A52A3007DD659 /* CCGLView.h in Headers */, - 473FCBE4156A52A3007DD659 /* CCWindow.h in Headers */, - 473FCBE7156A52A3007DD659 /* base64.h in Headers */, - 473FCBE8156A52A3007DD659 /* CCArray.h in Headers */, - 473FCBEA156A52A3007DD659 /* ccCArray.h in Headers */, - 473FCBEB156A52A3007DD659 /* CCFileUtils.h in Headers */, - 473FCBED156A52A3007DD659 /* CCProfiling.h in Headers */, - 473FCBF0156A52A3007DD659 /* ccUtils.h in Headers */, - 473FCBF1156A52A3007DD659 /* CCVertex.h in Headers */, - 473FCBF3156A52A3007DD659 /* CGPointExtension.h in Headers */, - 473FCBF5156A52A3007DD659 /* NSThread+performBlock.h in Headers */, - 473FCBF7156A52A3007DD659 /* OpenGL_Internal.h in Headers */, - 473FCBF8156A52A3007DD659 /* TGAlib.h in Headers */, - 473FCBFA156A52A3007DD659 /* TransformUtils.h in Headers */, - 473FCBFC156A52A3007DD659 /* uthash.h in Headers */, - 473FCBFD156A52A3007DD659 /* utlist.h in Headers */, - 473FCBFE156A52A3007DD659 /* ZipUtils.h in Headers */, - 473FCC23156A52FF007DD659 /* aabb.h in Headers */, - 473FCC24156A52FF007DD659 /* mat4stack.h in Headers */, - 473FCC25156A52FF007DD659 /* matrix.h in Headers */, - 473FCC26156A52FF007DD659 /* kazmath.h in Headers */, - 473FCC27156A52FF007DD659 /* mat3.h in Headers */, - 473FCC28156A52FF007DD659 /* mat4.h in Headers */, - 473FCC29156A52FF007DD659 /* neon_matrix_impl.h in Headers */, - 473FCC2A156A52FF007DD659 /* plane.h in Headers */, - 473FCC2B156A52FF007DD659 /* quaternion.h in Headers */, - 473FCC2C156A52FF007DD659 /* ray2.h in Headers */, - 473FCC2D156A52FF007DD659 /* utility.h in Headers */, - 473FCC2E156A52FF007DD659 /* vec2.h in Headers */, - 473FCC2F156A52FF007DD659 /* vec3.h in Headers */, - 473FCC30156A52FF007DD659 /* vec4.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - /* Begin PBXNativeTarget section */ 1D6058900D05DD3D006BFB54 /* Example */ = { isa = PBXNativeTarget; @@ -1313,30 +207,12 @@ buildRules = ( ); dependencies = ( - 506EE1A81030507B00A389B3 /* PBXTargetDependency */, ); name = Example; productName = Example; productReference = 1D6058910D05DD3D006BFB54 /* CCBlade.app */; productType = "com.apple.product-type.application"; }; - 506EE05D10304ED200A389B3 /* cocos2d libraries */ = { - isa = PBXNativeTarget; - buildConfigurationList = 506EE06410304F0100A389B3 /* Build configuration list for PBXNativeTarget "cocos2d libraries" */; - buildPhases = ( - 506EE05A10304ED200A389B3 /* Headers */, - 506EE05B10304ED200A389B3 /* Sources */, - 506EE05C10304ED200A389B3 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = "cocos2d libraries"; - productName = "cocos2d libraries"; - productReference = 506EE05E10304ED200A389B3 /* libcocos2d libraries.a */; - productType = "com.apple.product-type.library.static"; - }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -1357,7 +233,6 @@ projectRoot = ""; targets = ( 1D6058900D05DD3D006BFB54 /* Example */, - 506EE05D10304ED200A389B3 /* cocos2d libraries */, ); }; /* End PBXProject section */ @@ -1403,141 +278,14 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 506EE05B10304ED200A389B3 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 50F4132B106926B2002A0D5E /* FontLabel.m in Sources */, - 50F4132D106926B2002A0D5E /* FontLabelStringDrawing.m in Sources */, - 50F4132F106926B2002A0D5E /* FontManager.m in Sources */, - 50F41333106926B2002A0D5E /* ZFont.m in Sources */, - 50F41335106926B2002A0D5E /* CDataScanner.m in Sources */, - 50F41337106926B2002A0D5E /* CDataScanner_Extensions.m in Sources */, - 50F41339106926B2002A0D5E /* NSCharacterSet_Extensions.m in Sources */, - 50F4133B106926B2002A0D5E /* NSDictionary_JSONExtensions.m in Sources */, - 50F4133D106926B2002A0D5E /* NSScanner_Extensions.m in Sources */, - 50F4133F106926B2002A0D5E /* CJSONDeserializer.m in Sources */, - 50F41341106926B2002A0D5E /* CJSONScanner.m in Sources */, - 50F41343106926B2002A0D5E /* CJSONSerializer.m in Sources */, - 50674854107A3AF30090963A /* ZAttributedString.m in Sources */, - 504DFBCF10AF12E9006D82FE /* CLScoreServerPost.m in Sources */, - 504DFBD110AF12E9006D82FE /* CLScoreServerRequest.m in Sources */, - 504DFBD310AF12E9006D82FE /* cocoslive.m in Sources */, - 507ED63D11C638C6002ED3FC /* CDAudioManager.m in Sources */, - 507ED64011C638C6002ED3FC /* CDOpenALSupport.m in Sources */, - 507ED64211C638C6002ED3FC /* CocosDenshion.m in Sources */, - 507ED64411C638C6002ED3FC /* SimpleAudioEngine.m in Sources */, - 473FCB48156A52A3007DD659 /* CCAction.m in Sources */, - 473FCB4A156A52A3007DD659 /* CCActionCamera.m in Sources */, - 473FCB4C156A52A3007DD659 /* CCActionEase.m in Sources */, - 473FCB4E156A52A3007DD659 /* CCActionGrid.m in Sources */, - 473FCB50156A52A3007DD659 /* CCActionGrid3D.m in Sources */, - 473FCB52156A52A3007DD659 /* CCActionInstant.m in Sources */, - 473FCB54156A52A3007DD659 /* CCActionInterval.m in Sources */, - 473FCB56156A52A3007DD659 /* CCActionManager.m in Sources */, - 473FCB58156A52A3007DD659 /* CCActionPageTurn3D.m in Sources */, - 473FCB5A156A52A3007DD659 /* CCActionProgressTimer.m in Sources */, - 473FCB5C156A52A3007DD659 /* CCActionTiledGrid.m in Sources */, - 473FCB5E156A52A3007DD659 /* CCActionTween.m in Sources */, - 473FCB60156A52A3007DD659 /* CCAnimation.m in Sources */, - 473FCB62156A52A3007DD659 /* CCAnimationCache.m in Sources */, - 473FCB64156A52A3007DD659 /* CCAtlasNode.m in Sources */, - 473FCB66156A52A3007DD659 /* CCCamera.m in Sources */, - 473FCB69156A52A3007DD659 /* CCConfiguration.m in Sources */, - 473FCB6B156A52A3007DD659 /* ccDeprecated.m in Sources */, - 473FCB6D156A52A3007DD659 /* CCDirector.m in Sources */, - 473FCB6F156A52A3007DD659 /* CCDrawingPrimitives.m in Sources */, - 473FCB71156A52A3007DD659 /* CCGLProgram.m in Sources */, - 473FCB73156A52A3007DD659 /* ccGLStateCache.m in Sources */, - 473FCB75156A52A3007DD659 /* CCGrabber.m in Sources */, - 473FCB77156A52A3007DD659 /* CCGrid.m in Sources */, - 473FCB79156A52A3007DD659 /* CCLabelAtlas.m in Sources */, - 473FCB7B156A52A3007DD659 /* CCLabelBMFont.m in Sources */, - 473FCB7D156A52A3007DD659 /* CCLabelTTF.m in Sources */, - 473FCB7F156A52A3007DD659 /* CCLayer.m in Sources */, - 473FCB82156A52A3007DD659 /* CCMenu.m in Sources */, - 473FCB84156A52A3007DD659 /* CCMenuItem.m in Sources */, - 473FCB86156A52A3007DD659 /* CCMotionStreak.m in Sources */, - 473FCB88156A52A3007DD659 /* CCNode.m in Sources */, - 473FCB8A156A52A3007DD659 /* CCParallaxNode.m in Sources */, - 473FCB8C156A52A3007DD659 /* CCParticleBatchNode.m in Sources */, - 473FCB8E156A52A3007DD659 /* CCParticleExamples.m in Sources */, - 473FCB90156A52A3007DD659 /* CCParticleSystem.m in Sources */, - 473FCB92156A52A3007DD659 /* CCParticleSystemQuad.m in Sources */, - 473FCB94156A52A3007DD659 /* CCProgressTimer.m in Sources */, - 473FCB97156A52A3007DD659 /* CCRenderTexture.m in Sources */, - 473FCB99156A52A3007DD659 /* CCScene.m in Sources */, - 473FCB9B156A52A3007DD659 /* CCScheduler.m in Sources */, - 473FCBAA156A52A3007DD659 /* CCShaderCache.m in Sources */, - 473FCBAC156A52A3007DD659 /* ccShaders.m in Sources */, - 473FCBAE156A52A3007DD659 /* CCSprite.m in Sources */, - 473FCBB0156A52A3007DD659 /* CCSpriteBatchNode.m in Sources */, - 473FCBB2156A52A3007DD659 /* CCSpriteFrame.m in Sources */, - 473FCBB4156A52A3007DD659 /* CCSpriteFrameCache.m in Sources */, - 473FCBB6156A52A3007DD659 /* CCTexture2D.m in Sources */, - 473FCBB8156A52A3007DD659 /* CCTextureAtlas.m in Sources */, - 473FCBBA156A52A3007DD659 /* CCTextureCache.m in Sources */, - 473FCBBC156A52A3007DD659 /* CCTexturePVR.m in Sources */, - 473FCBBE156A52A3007DD659 /* CCTileMapAtlas.m in Sources */, - 473FCBC0156A52A3007DD659 /* CCTMXLayer.m in Sources */, - 473FCBC2156A52A3007DD659 /* CCTMXObjectGroup.m in Sources */, - 473FCBC4156A52A3007DD659 /* CCTMXTiledMap.m in Sources */, - 473FCBC6156A52A3007DD659 /* CCTMXXMLParser.m in Sources */, - 473FCBC8156A52A3007DD659 /* CCTransition.m in Sources */, - 473FCBCA156A52A3007DD659 /* CCTransitionPageTurn.m in Sources */, - 473FCBCC156A52A3007DD659 /* CCTransitionProgress.m in Sources */, - 473FCBCF156A52A3007DD659 /* cocos2d.m in Sources */, - 473FCBD3156A52A3007DD659 /* CCDirectorIOS.m in Sources */, - 473FCBD5156A52A3007DD659 /* CCES2Renderer.m in Sources */, - 473FCBD8156A52A3007DD659 /* CCGLView.m in Sources */, - 473FCBDB156A52A3007DD659 /* CCTouchDispatcher.m in Sources */, - 473FCBDD156A52A3007DD659 /* CCTouchHandler.m in Sources */, - 473FCBDF156A52A3007DD659 /* CCDirectorMac.m in Sources */, - 473FCBE1156A52A3007DD659 /* CCEventDispatcher.m in Sources */, - 473FCBE3156A52A3007DD659 /* CCGLView.m in Sources */, - 473FCBE5156A52A3007DD659 /* CCWindow.m in Sources */, - 473FCBE6156A52A3007DD659 /* base64.c in Sources */, - 473FCBE9156A52A3007DD659 /* CCArray.m in Sources */, - 473FCBEC156A52A3007DD659 /* CCFileUtils.m in Sources */, - 473FCBEE156A52A3007DD659 /* CCProfiling.m in Sources */, - 473FCBEF156A52A3007DD659 /* ccUtils.c in Sources */, - 473FCBF2156A52A3007DD659 /* CCVertex.m in Sources */, - 473FCBF4156A52A3007DD659 /* CGPointExtension.m in Sources */, - 473FCBF6156A52A3007DD659 /* NSThread+performBlock.m in Sources */, - 473FCBF9156A52A3007DD659 /* TGAlib.m in Sources */, - 473FCBFB156A52A3007DD659 /* TransformUtils.m in Sources */, - 473FCBFF156A52A3007DD659 /* ZipUtils.m in Sources */, - 473FCC31156A52FF007DD659 /* aabb.c in Sources */, - 473FCC32156A52FF007DD659 /* mat4stack.c in Sources */, - 473FCC33156A52FF007DD659 /* matrix.c in Sources */, - 473FCC34156A52FF007DD659 /* mat3.c in Sources */, - 473FCC35156A52FF007DD659 /* mat4.c in Sources */, - 473FCC36156A52FF007DD659 /* neon_matrix_impl.c in Sources */, - 473FCC37156A52FF007DD659 /* plane.c in Sources */, - 473FCC38156A52FF007DD659 /* quaternion.c in Sources */, - 473FCC39156A52FF007DD659 /* ray2.c in Sources */, - 473FCC3A156A52FF007DD659 /* utility.c in Sources */, - 473FCC3B156A52FF007DD659 /* vec2.c in Sources */, - 473FCC3C156A52FF007DD659 /* vec3.c in Sources */, - 473FCC3D156A52FF007DD659 /* vec4.c in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXSourcesBuildPhase section */ -/* Begin PBXTargetDependency section */ - 506EE1A81030507B00A389B3 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 506EE05D10304ED200A389B3 /* cocos2d libraries */; - targetProxy = 506EE1A71030507B00A389B3 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - /* Begin XCBuildConfiguration section */ 1D6058940D05DD3E006BFB54 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_OBJC_ARC = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer: Duc Hiep Ngo (36Q6CZ7F37)"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; @@ -1548,11 +296,12 @@ GCC_PREFIX_HEADER = Example_Prefix.pch; GCC_TREAT_WARNINGS_AS_ERRORS = NO; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - HEADER_SEARCH_PATHS = "\"libs/kazmath/include\""; + HEADER_SEARCH_PATHS = "~/Programming/SharedLibs/Cocos/include/**"; INFOPLIST_FILE = Resources/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 3.1; + LIBRARY_SEARCH_PATHS = "~/Programming/SharedLibs/Cocos/lib/**"; ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = ""; + OTHER_LDFLAGS = "-lCocos"; PREBINDING = NO; PRODUCT_NAME = CCBlade; "PROVISIONING_PROFILE[sdk=iphoneos*]" = "9FC23DC7-CB28-4671-9494-EB7B1F3ABCBE"; @@ -1565,6 +314,7 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_OBJC_ARC = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer: Duc Hiep Ngo (36Q6CZ7F37)"; COPY_PHASE_STRIP = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; @@ -1573,14 +323,12 @@ GCC_PREFIX_HEADER = Example_Prefix.pch; GCC_TREAT_WARNINGS_AS_ERRORS = NO; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - HEADER_SEARCH_PATHS = "\"libs/kazmath/include\""; + HEADER_SEARCH_PATHS = "~/Programming/SharedLibs/Cocos/include/**"; INFOPLIST_FILE = Resources/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 3.1; + LIBRARY_SEARCH_PATHS = "~/Programming/SharedLibs/Cocos/lib/**"; ONLY_ACTIVE_ARCH = NO; - OTHER_LDFLAGS = ( - "-all_load", - "-ObjC", - ); + OTHER_LDFLAGS = "-lCocos"; PREBINDING = NO; PRODUCT_NAME = CCBlade; "PROVISIONING_PROFILE[sdk=iphoneos*]" = "9FC23DC7-CB28-4671-9494-EB7B1F3ABCBE"; @@ -1589,37 +337,6 @@ }; name = Release; }; - 506EE05F10304ED500A389B3 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_TREAT_WARNINGS_AS_ERRORS = NO; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - HEADER_SEARCH_PATHS = "\"libs/kazmath/include\""; - PREBINDING = NO; - PRODUCT_NAME = "cocos2d libraries"; - }; - name = Debug; - }; - 506EE06010304ED500A389B3 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_ENABLE_FIX_AND_CONTINUE = NO; - GCC_TREAT_WARNINGS_AS_ERRORS = NO; - GCC_VERSION = com.apple.compilers.llvm.clang.1_0; - HEADER_SEARCH_PATHS = "\"libs/kazmath/include\""; - PREBINDING = NO; - PRODUCT_NAME = "cocos2d libraries"; - ZERO_LINK = NO; - }; - name = Release; - }; C01FCF4F08A954540054247B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -1677,15 +394,6 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 506EE06410304F0100A389B3 /* Build configuration list for PBXNativeTarget "cocos2d libraries" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 506EE05F10304ED500A389B3 /* Debug */, - 506EE06010304ED500A389B3 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; C01FCF4E08A954540054247B /* Build configuration list for PBXProject "Example" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/Example/Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Example/Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..6d2a51b --- /dev/null +++ b/Example/Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Example/Example.xcodeproj/project.xcworkspace/xcuserdata/Panajev.xcuserdatad/UserInterfaceState.xcuserstate b/Example/Example.xcodeproj/project.xcworkspace/xcuserdata/Panajev.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000000000000000000000000000000000000..1d4702233bdbddf7efe8d6702be5090a8b25b07d GIT binary patch literal 32623 zcmd752Ygdy_c(r^dv9{P(x!Vt(*aGo_o9q6N!!pi2}!zGAx+aZkPbQ+GQ1a5R9q-3 zA|M-4a3CV$0#Q-GfuOj>JrNfoD*8Y7-rO`Pg%@7@f8QT`piOetbDr~@bDs0uoTs_l z>FDjt&OU}A495tJ#6*~w`kVTvF?p7~r`OTd*_hnbJl$^V>upN5_So7T@U}U*ud6!* zL)Wc+I2g~yD9i^7#lo;~Oo63hX;?azfn{P@ST>e}ojtH&C!Myv^& zh)u#KV^grHm<6+At=J5#7wg0Nv02z`>?&*#wivq(y8*icTaMj{-Gyz#wqp-r4`YvD zk77Hp$FQB)%G7(0P|f_;j8hJAy5i~WfGg#C&A zg`LCxMkMk>QWS<_kPOL@0_C7wREkESGBg@ZKt^OjW>kmjQ3Gm3O~`_#p;pv}W}+U{ zi~7(UbR$}dZbCPsThOiOHna@gj@F?2&|0((tw$TsMzje%j2=O|&>r*@dJa90UPLdU z!{}9X1igjcM#s^I=o9n>`V#$&enG#Y)95$!7dnR%IEjmJe_V=3;n8>uo`@&m$+#TP z#Pje`co{w#*WeX+C9cPta0_n7+wmEAC*Fnk;&br%IE`O}ufkX3Yw-K&h?T^>#42JnIg7lCTu3tHHRKZVM)GFzHu4VgF7h67 z6?q@Ip4>#7FCMIi)uv%kx5i9Y7$KrSwzhuyQp0>L)0mnDe4o=7F{J;AfiQ!Mc0XL5ZxrY zRdl=PPSFa{y`nXub)t=;EusfR+eMFv9uw^nJt=xx^qlB<(Tk#&MTbPMiH?YliH?ij z6MZN;A^J@8rRW>c_o7pxpGBudzl;79{VhgfQcQ{c#1gSo94d|wM~mac@!~}B2(et8 zCe9S+i1Woo;!^Qw@i?(cTp`wqYs7l7QCuf(6i*UQ6= zp!iks8{(tlx5e*@KM;Q`{#5*h_-pZZ;vd96iGLNJ5&t1RMY zx}Lg~x`$dx-Ak>aR#R)J`>3td1Jr}mHfk631ht!bn%YafK^>vqq>fU@sJEzhsSl_R zsgI~nsZ-Q1)UVX<)LH6WU2J&UVZ*TDw1^hd z6zxO%(tfl*9dJJ;!xFGWkRlEnfsMpQ(h@q5mV!inbTAzUe^aNjTpXP(U9&5CtQ~fX zGy&ew_q5o1>@9BYW^1#mtFy1C%jpC+Y>`I0k+hu^ppIT!kKNu`+tmX2>7HWqlm~F@ zIvq3n?b;R?iKEqF@3BbZ0bFV814lkIH;Z(PCqXYsESidPO-?}ts86XW$;elhs545` z6$KeZImLO(3Qa*pc2SO}wC1iZXS20O+gtDGbu>Fc+9>x(fO5I_NAu?878j(;it`tw z%jV_eXJ@C&N{aFqEO?Wf`aG;)9To?Q40;nQ!iupHtaKtj>z$y-M*dfOFBpfir^h;X zJphbq)S2{L`0^3vaST?4$+u!-v2mCZE5}rr8q;7ESS1}ohtgqmI2}Pp(ou9Y9kUhF z!VFepHCQdCgWn9;1UeRGa2P$DPNVDKx2d#+PPIrQl)b$WMXjBEnifZ2S5I$^b#7OG zpG7K#v6|YuX6vl89Bo$kWD>jq!>+M5+np9^#s&3U*XM9L`sONo>{b&*=)QV~eKt?d zO^W?&(A;}XmD=9xXzLt;0xJ+t-(l}%jSUh-pL5v7=~MH+1G>bJF< zd#ny849nh=*&%3h8rF=-*I`yVejR3`WvnKG)%9k#z}h~0M=w8hZP@hnSUcvR6X+CL zArNq4U0BF^tOM($6X~S&ST{D4PNqlDBc}ivPm`6xYgPrd*0xSZUw@0;kTh=b3XJ{3 zo5CDy?qr=w?Etgx>a_O2+|R*A32f$J3kR{GfsLFVnKZ6T=0W5d?Aob1Q*D2r6%3U# zp$*tItP$}%mSERgq@iwr0cIPpC7$eV#BRal8?dF=P1wzJI-NmhZoqEEZpN0;S#%~n zj#bmJMjNc$Oi*^Uqc77vrJ35^-hMl*_F$9U2`QJo#r=^*D!TxVsjsKs*4N)-7lwN` zwvILM71%x4O6*>26}B2%gWZR%rL*ZAI+xC)^XUS*kS?N&w}PYEfNjJ!!Otz&{qX+- z;HpaKQo0O&j;6=J|6^Hs*)^-_>FMeLJL$9cI6B)jove~tSo3kMY$FH^lEWJ+a9Y;x zUV95`RqSY3>^a@m&K7$MKSCCbHN)QWx#qdu;1t5yH@wCS)Lp1Pwg-C} z8&#(>!3*AupLKz=foLB#eJ!ov-+#g5{R7J5Fy$bYvTLSzEH?bO?bM5ExxKZk$L?m& zgP%7WdASP~2{10+I}n=?x+RrtUkN!%ELw0Qs{7=>W+wQC0;!%?K*I#Co| zPp5KrgkrJj8&Dh?hKAD(bQ3+v?J7|MO7`+$Dl`%TRU_-ey2o)oOb{X!Wq3hWqAWUw zp2$KjrM)2YP@yLzDniBdWO@p#bT)9gV+0!t+-xjTXI5P=hMT znGWy@S+j-gDa&DK@9MOh?Y({QtF^@fP~0vuOEU*NNT=25(sq_gRqnL5*fYRXW@KF` z)}S${60$Ee7L7wnRE|_gjWno&o<>{gX4*!#(000&ZUYyF*qE(FHK-QpkRDc1JH+W& z`c8TaeLwvO>&&FA=TY06``g;=J$w|6fZ_6CkISfF*>tv8ds^6N$O7{pP4s|}hQdc` zd#knI*~gLM>BwAf8Q86JZy&fQqrJPw-V482*~r9tG=Z}_Oipxi*#f&dggKmuCWCpP zNwi}fnnF)!r5?d^cV!kAVjvK(A{$GfnVzu@wa`vF)m&?JbPAugBPSNJ0XfigG=uJ- zJL#?sr~{PNMR$X$?qCf-;l+;iBX$!cF`aGPukP3f83Z_QZ&;Ue82o;vy{p6C*E5&5 z^nS?Y&@6f;9V7@f7ct-|(N$<3nvWKsh3INT(>-)A-ADJ+v*_9MoGoY(T8yqi*P`pt z5_CO1m%fT#MBhqZN8d&-qf;k?qp_>4eO5M3OyXtYq=opU?sXuF$hU;>E2jL%E$k%jI8?o?4)^xh56~S z+?>L~1x@pEvvc7^_JX(2X0!$KNB5(x=mGQ~+J?4cT3BF$kTqR4&g`cSsEAE6IfxFh z$AP!mEd!(nbM&nO?!agCQu-SD7J4xqYmsKTlOV6DQFpQAGTr+bcTU6`+oM>)2DAe` zhIZ1|($~{Bzy<<60dil5o}B2x=Q?@`*u!})h|B)a)94wClntu`rUYDIL2z;#td5@b z=vi#ke}LimV!xs%Asj8?h1d@-ZlssEqZc{=lD&*xK?l*HNiD8TC>T^zpD^Y0P4vw) zW|7Ws1%ofm%5s95o$X!VY5xx$Gq07`(Cd&BLv}7qn=s|;(HpEXhWd!dd=nkDNadhU zuZbK`uJ<}!kB+hAE*ah;jmfatxT&=FmfPE`ou#uKeeIfA;E78u(vfa6V)Jj_RR|-< z{-Ia9v4UO9`3#TcEk!OSxES{VaBg#m z`_hp5aJs+)U?Yf2@IZPUz0sZB;K6v9XC{J&;}P_FdIM|(z2r(7H_t1B!DI2^UU>1i zjNU|VrbkY4Nyeux^SV9r9()8o(kmOo6?mFk)^vKSAZr#YYc`%kKR|CEkToAK^5R*H zm(UN=+vt%^pmpAqlEyivd2t+rE4^^aaTWa#{jiYU3Mm0E?c}{2?lHUy*W%+bf4mwU z!fSCI>~4Cxy88HuX0rtySN(}>vv)fBdwI@m-N!zskN+g9n~xdieMCPAhWjY}^xL=r zp8yPuxCu7{lWM#H3et_(*lGYMs>8;}B9F z;PfQ@6urYER^SuyNqnrJchisYuAR4zY2c`FE8dLT=$-WA^ezua4N;zVm|or!cY^nP z;sV~2_mf_O#QR{F4cKIK2%Ajr0ok6SVS@(SIeacGQoI(l!WWnD1^7aXGzF&A9aOxk zE8erP9>1D(PnQbLISib^7g?l9m%w2?zL=$cDWJmYyB5C3#I`^nUsU`bGLB`oII&Nc?t8i!aCT#P7oI##gW#Qb?O$rehf# zF*wQKz6>sBa0R3zQr2IDmBXH3Mt7H^v#*z{B|?7K0&c{W|MC{cC11T2T|M9lAx(_r z%^X4|U!yFyw?jtR)iaqdMw)ExcD5QC#=kW7cR~fL&(XrBq@E5rt_o_wO_kWmfxHg4QYxI!hASVeV z95?+RO5!RiWVuQOSygtYvkQEJvjtoLR}J-$@O4hYBmWy+wR`I77$*s&ShxNUb>-3> ztSmKb3ZVdQ_ny#qIU(P&Nay|!gyeP%UiS47C(iNz=XBOCtmjYgFTmNLyJ5e$oL&gK z#d#a>FY&MNujzN`_vrWO)Ox|f1i&|U<3m66Z9u^>ZExEIZ$QI$uBP8 zu^-fCPj_JxV#03->;OUn*q_m#v&{4IiePt{13!55&(|4N2xx7Co19mK zec2H3nS8CI2I^p$z3ds*Eba^|eF#v2wAtFzW_O*TxhM|>E^JSP050q~A;1qMxP|9f z-VZ4)RPrIEXme%D!bVVtt**Gs!+Qz?<%tUt5folS=!8uKp{LKdHW7poHW7r0Fw?)& zf4DahL<2F=b3=f26O-Xc>MUENwU6`MIuO$c+aO3gK>o=>UYE^5UQ9SHwZAMRXInL{C#MSFVFH7K1SQANnMNzGj!a+A@0SaA9cu#9UZ9#4KVq zF^55jK{$hm4a8N%JYqhBNCt@*BnI!p>#v^IoJE>=L7jQb*o74 ziXm}5aVu-$HxM@xONpC^n~7T(s)?Ip5y^0 z@Ze50yrB4V!Mq_%m8asVQGp6uvh*OrYikWQ{bA|b#C^nCVjZy_=4vCciP%hRA?_!( z5)Tj$65ELF#6!fx#3RI`#17&yVkhx9v5R>-{ao+h3lo+X|m_7eMu=ZXEq z3&e}WOT+=y;ydDd;w13{af16lL4fJ3?zd{DH%+LkfCH48BRu! zkz^DZO~#P1WE?q+98SiQGBSZoB$LQwas)Y&Od;i@f=ngT$aFG;%p|kOY%+(;CG*I9 zvVbfki^yWKge)aTk!9p)att|^97ih2a#BUANex*+R+3eumK;x3lQm>5sU!8Ift)}Z zNfT)%>&SYtfovq3$cf}6axyuEoJv~AX{42GCT(O3X(wCBHnN>`kkiQ-q?7C*JIOAx zo197ZkiBFdgMt_o%%Bhkg)%6NLE#LFU{EB3q8Jp-pcn?lGANEg!x%K2LGcWdF(`pS zi400&P%?u?FlZ!$QWzv>kb*&}3`%2AI)gG8l*ynh24yoShe5dv%41MIg9;c_$eZw3b2Z7_^>2 z8yK{aL7Nz~nL%3^bU%Z(GUx#YJ;wD<)YT@goI??G(X3Hh3^ht~h2B`}rVFzV7_oyf>XkKGwMFSE0hk9s zMk78pxTDtm`KG2?PZ_{^hKAFZkN1QF;{v!5L(r>I8d*_|8kN4*V6v#SMqzwlhk!HO zg`@B0&JpL&FR#MAWNy;>t+!8!q~af7kk!`13k zHFau@rAnhzgP4{IqrTR{j?l~!RM)A@UMhjr2ILfj$r^1yUL;j18th9 zajOy*C*b7{#xtpuI*YOfY*}AtRB0?Q01e2XH-a8Gx!mf7MGXXGg9&h!;~G6HtT1d? z`T#xxv1bV~6FiLtsptIptYR!CZKckl(V4a88ci+ybh7|20XXRw#4&1IQX1=6DGf?< zmB0@C3ZNzrLe-nAG)8VVc%~IK%1Spk@IZhPiPZLPXV+ZzaYwLivr%jCf&%vhP;p*R z${MrAsAC6RY1G#l1R21AT?AC$0A?b9f{O#t*b7jt^)MgsfdDDL0Hi@#-QZf7blbe z`8@}j;ze6)sM6~+dT>VrhUBf2Q!e_|@RW<)DTBnl-)WyeAEpi#tVO4+b<6%U2N{Qk zh6Du~-HJYaQKBZZ-n{^S=OBk)fastg@FxcxiE133GdSN=UZ+!olr?(R4-0zun}ZrL z0HtoK(UyZtsRjGdmV>)DHw_9eBE;dupNCUtG_q^YTMiM)K@anQhCtx*S*$lQ46Ha2 z#lfZwz(TaC1`ns!njq3QnJl#s0cv3OSycBY2OTjW7Au1VT&`KGbITsh0gW60Vs&C^(3-2*P^eQYjcN-_nGv#u0hPpYNZ|uW zu-dCEdW*Tq;3gc;!GsOK=#5|)oSPK{Oyod3Y={pyHEPcgA{xO#dDxIUW2jY{K$#ZE zlr$={7iBqz<1uuY5pG~G6!*lYaX`ZdB&^nG43ITw>)F_(X=J068#t2#P8a}&iGr+w zb%Pd@hE4srfa-?N8BBb@QE*db(Lf$7C?cN&_E3Z%u9qT;IH>3W5lk>_msUL@v#4~i zsCBxF+R5m_bQ_dL9h-*@nuu{6oQJ+Z1s-!@@R|XY3)o<_&9Jt)vX@$RVL;{qv^~SE zsDc9?fjoef2188~Xqe4Zw2++X4NcxSS`J6%iKA)MsOrqha&SZJ?CCs`R#6QHKI{VE zAXkO9QJ4-r2b<;z%cix48m-9;lnv}E=96fX#te(eofL_T9A<(irdvaX>PnW1mzL_z zm#V@D&Zj|dtRC#?8adb)Puc@gvFa4WpTq%X4h_gJF&M8aA%RrY%gCm3$VnGKt}`3z zV5M;xzQE3UF?L>z)SzT=L2SAuAh%qM9X~6s)Ly`7<1oDDeLxKZ>;&-X9Qa7j@vyeU znl}J*UfN`-s(`4hG%E$94h|{B6G?Cj?tO;7hIMBiX^^O!!;138;xZG@*e&Yiz>>Yd zILl(^&;s81d=<|+e-MVc@*3EuTtu9?9Fp9V51XTawQ?pXaMI{tR{`$|W1r8Vc`cL% zBdkUk?0JjoY7RC9ne0}0N>au?p~r6VYZ};K>hg+ppkr^>xQN3VF$inG?uT-x*K#-t3uq_h6)^cExLxCB!Zrj|zK_#Pl{`hTTo{;-qmb6A-~m0Z)Fj%*;m9tG!+S9S z{NeuuZmO&B2t_+CEI#YPOihph)e5v9=YSI~EDAR>?(AH&n}b)vA-mHqtEs84mD%7y z5_mGSN0y(NBg>F+)rU%Zr@e=JlxF^Xwi;9cSr?mgskppZX;ukU1kqC*y{gNg$JbmM ziwhyxvAGPlsWU8SziZPAynp+9=mSQK8~37GKsl^I9KF?IL@k` z%eV#IzrfKQeVKICO_1J$8|U^DDuEVMYGDIgeVMe}GIEPcr3WilR=P@30%a)u0_Dpc zy;cXgGvr}PBU`2OOpgV+P)YtTBxbib#yYN|0;{(Y5+Cq1`UbX;>h|MMng+_3V^i$p zYjj)|2%9^driR_jYijfcmXRPZ6uN^|Zb{P~{!HgPk#++?> zWQ|Z`2U24%lN8tt?4xU;&RP!jD7KW&J0vL71GVDIq{gjksN1?1GnDy(%;h=WLB6gQ2z|#98g;3JR2H`GT*od|VZ$v@`hlZ# z5xW==iFc%`#>NX%`-!7ga4B+mP~*1#LIq6p>!s7+6b@?{6l7}BnU(I{)ftXP;ibsI z($MO-d>C?L&+5V-9Fa?&dDm>I3~SQlwzl zz<_$#Um=h7E*^-JIdYfe16}0Kr;&1bBDvJd9Z5nVOE4_A-KTQoF4vP8lqOg`gAxgG z21n~6S&jGVG*!VdH~5V@cRgC1%~7bhRDJWwjH^s69L4fGUJsMZznk|46kL_H^(~PMOn{7I`W_Ri#l?TTD>-hf+3VBCxOYI9wK&b1WLJh=sBo zs$1;w7dSDXuRebl*}DS^Y1lzcAlo)?4y&EvylO%-&@TvF^WDKkwyvBd>)Twh9<<&k&r?Wdg@#@)fC{ ztMJ0E8y=qE)@nsv4HWX>07+G?fjJj+X69Jwu80+HPezTo4i>OSb|`M(h#RhmIQL)x zo3g;JR|gM5nB2!-;)xvjDOW_Emt9~|q1C`)iihglOM42(>&jMyH!pCjW<9GdH;-u? z597Z$9-XFvEg1-tZQ~e}|2GVTvnZ8UTG0BhX@$#3!BqJjAyhfsT5)hZE>bJG6hFZ} ztHYgk8{Nuqa&-SI>+x91CPeheB?5!a8NBJ?P98 zf-TSCm|U4}se|KHI0xgrBs@1*XV$x|ZXQRz=8DEpr>oY%gFzs;vJ%e71<4owE2O#H zOPCOWG{cd;vb9pD<4D&i%QZrAU3?8kxAqFP!O>+O)2W3BBoutaOa48X;VHg4_xir^ z-%~U9j3yjs3u?ZZBYlzGw}(qorKQ0GgWNNXoMA)Z0|Gz02ZdF{)?L|pyW2Kyy9{M; zl--H54hoRMJVX6klHf5C5o)LUmVs4@dnX)yj)#8me&FjRS|JZi!cMG%qbn=Q|HVp9q=CdluDo zYzoIdpaRBRrB{R411B)z`#2VtmcU(z1y`9u zSis>dlnWu>(z+G5>AzK++n8Wi2j>cWAcI08_pq^9uhP36&HWq;>m^x}m*U(kYU^su zS_4GLfz2wHlk$%Pn>01t0hh2Y9_094+Di7~=dq&MiGqSA)NCxua(5l_p?_gsJho_V zYv8tneB>1d@hHdY(w5-G2Em?|Yv8QhXlc+Ws|D&iIqH`dXuYVrr^IyxDCpjMsXW1v zzqAd=(B$EPM>q$D?SUE&`Msxi4@dk8mpVJK!Sl3cZ)Z&$}qT8xy=4`)CzBo}zO<4lCZzQ7B`3H8^ZC zB{XK6dleiV!?AI@-8KVi3%sogkJ7`!P^!5n*x6s;!BcqrMwsiDI8y1COsZ1l-blW} zp=Mn&YAx#v-1V5l9CrDIuwgLnxzBKWV)ux+#i2BV!*UaRog=8Z5`sFDs)DQU2-)qE5nXst zfE8Z@Wa03Z+n#CEeBDP-%}I`p>0e_5UsW(Pz~ik0b;BPy4u*e?Lv1zt?2hpCz4#Z7 z{FTkEr=E;Zl^2xr8%O(M4&*=2ttV{=tSW7_mY2OYsF5hWIyD+}N0 zAKWBh14U6jY&#{_cdg-T)NEhU!C*tTu5*1Mp7Nvoy*h|dfmD$98zB@lc-=^aQejj$ z4oT4W41xy%exwg?q@t*3Du#lSxt|$ynn9rWb6y=KC>h&PfKdx1zX9Wa={YLYw}6uQTbRR{w0IJ zXZ#9Xwce#u*~Sa16GssDa~T{ znGU|gX)oWHG`}E2ZOG5Gc6VoSo%oo>47G?_%-|9R zPhs#dcJSFSc<)AOuBK|x0>sqc!SG8*HxIsYiz*v4eVy+R5NC3=UoR z;NFm=u|M)8Y?y2Wj>+Dnp2YmAJ=9ZdXVMnvd#n$}CpQcCIU$@NMdDFqmv)cScFHG6 z8WS6rJR&V8zsPmtim#u4fFuxZ&~WL2zhDD;%+onk`}FxjDibOd};rBov8wvN&+ObVCm{PHf(sjpDZCU3Enq3 zuCfEy)(WS!truRi3q5JvNPh6a5-EG%3asLqew(AkTG_+iE09s%w-e>TP6zF zH;YT4GpC1AT6lG>FNM`M#QR*2glhX-=vU~vPV30%F=n>2Cyn4DtzfuYCJD>Ha^Z>- z4O~8AgsZZe;hv0{ST9_Vbv0a!bqieVunMkpSPOSIY=V0mw!+0&yWu*5m$4&ofxssi z+e80r>@S2+01Ah0^6_xtRTeaNSEEX#Mb*dvS6od((@+QMM*VQH)y;5))lT#TdYV@- zj`*K&LyFfQ=t_YP<2pT1&rr`!arb#(J8o})x1PgBfu7k{!qV7By$t<%V0G`OUZC!v zUZM_gYdoI8Ww6W{Jb}RzH&d^mQ`8~qFf_P5#o$Tw8U{~h@R87-hilN2c<~j=HzfTJ zKp+$Jm1LW9dOJQZ7s3LW`sT7X)cglXw)Hj#nKaIa*U+2P+prRkQ}3{L&$el119`=< zvj?DY<_KP8?@{mb+Oe;v-ec2Gsky7gI#*`xlNFX`=gADU(rYUEp330q44w(@b)Y37 z^)r_Z;b|7B@w{YmmbE9V6&4QL&3{&IR_mPZwyRoax8%>cs>E45y=QjroH^O;`Lna( zPg`e}Ig4+Zmto5*Y%R&t&HoZ!|PcO~VSXQfw@_f!s>&BA{=r9xoK z5doWw7%Gm+qH-Y5ETD?u?ygbPXlg8_q*T;oxT$L%+`{!NbrR$c@)_n6?<4cc_fh(& zeJXskKGi<8K31RUK3zUDeR_TReHQsF@wvfgsn2abxBD#jxyxsx&l5hoefIer^f~VH zfzLNSKluFU^Rv$xpR+!H`keC>`v&8tjw_HFdF_*#8!zII=yZ>Mj!Z;x-E z?{eS!eGmD*t|(M1Q$|j(@IyzW-?dG5+KHwf^J% zYy9i{>-`)3?f!lKv;61yU*$jFf1y9^zsP@?{~i8!`rqw;kN>^?tNriuU+4db|6BgQ z2KWbL1tJJ|Fl(;7fro z2ObPO9Qaz`$AO;&eirye;8%g)1b!EIGVoO3PeEkRu%NV{!l0UmYgx>34WdcX7m={D(8(r2X4N%u+jOJ9^8kiH^4Bz;Hvx%8jl(BQ1# z+Tf<({@_KyOM`C?zBPDR@EyUcg4YDE4PGC-F?e(EzTmHee+wBNk`j^^GCITK`fz4GK*PO%JUOHH3DB&I!FL zbbjcyp-Vz<2wfJsCiH>OouRuzcZco?D+wzPYYdwb)*CiIY)ja-u;XFBh7Su*4bKf9 z6Fx4yJX{@K8*U1344)d_7Ct@P8QvLwZTRis_lBHICURV)CbBY88(AG$7dbU@ zMr3znPh?-@+{k&63nH(MTo$=9^1;Zxk?%#Gjyw~2HuBHNb5Rjd@lhkAa--^^tWmZo zdsJJLBWht39knRxnyBldu8&$4wIXU|)T*d8QEQ{NMm-p{J!)6f?x;Oc`=efrIuP}G z)CW-?MV*NHH0sZ&b5Z|9qi7;JAUY^II65>sF1jMRI=Vl4Vf4o6tk#MHz%Viw2T7PBSh zy_oM~sn~?r;#f^=O{^}~5NnKWik%cYC3aeDbL_pbZ^eEZdn)#)*k58#$DWBj8~bOR zPn=&|KwMy)G%h4AEG{B0DQ-kuN}M8YZQS;_hvOcNdu&+wF#WIz!%V~Kh8-UE?y&cV zeK_pn;WLLX98M2kH2j))EM5{H6dxQP8ow!iNBooVPsKkI|6Ke_@h`_8j6WRzTKrq_ zpT>U||9kvDG9)8pB3XbeP$rdy$iid^vQ$}-Y>aH2tX!s+Rm*B+df5b-NoJ9?%lc*W zWea7rY?15+*;3ifvRh@#WNTzwWIJU~$)1rtC)+1`S$0r%SoWIi4cWW0Pi3cMzsY`= z{UQ4+fk+S~Pzk;X{t00T!xB;xG7_>9auf0s3KLWbnuN*(ZNia+j}pF1IGJ!N;irUO z5>6+aNhA}+i9U&bi2;d0i6Mz$iR#3z#5IYpCZ0AR$p zNvD#rWWQuda!_(`a#-@P20 zyq9uA%1tS^rre%#XUd9{dsEh=tV`LLvL)q#l$B4Dc_`gpK>bY=akbazo-0}^0yqxNjW9=lS|}Md8j-> z9xacP$IBDtBjj>TZkd4*gnuaWEJMtPmQQ9emNRc@8H$lK)8 z%S@}Ns3-SZz=@M*fHVoB~r2 z3bDdh5ugZCgebxlQHof_a7BV5S&^bhRb(i#6?uw6MTw$JF;-Eo&?u@D)e41b;X;Cw-oOv-dB92_(bu!;w#0sij#^T z6~8EcQ=C=&rT8ZmPZg#5r23~yQX^7jsY$7tR9)({)V9>_)VZniQ0hM(kp5G~$c(Iv+>E-6sTtOc8!~RsxHIF0j8`+>$T*XUWfGag zGDl`AGOIEtWSTR3Gv{Ysow+)5bLQ5}W0@ajp2#Ay0MU#4^sJ7o8?)}n zx-096ti4(Lv);@4EbGf`Jlj7zFuO2&Y<79})aDkM&S7xuy-krTK`-SXpvwz9{ zEhj8zSdJ`be2yunKBq5dK@OdBU(WqG59Yj*^JdOlIltxnlZ)rZ<&Mae=NfXGawq35 z%w3XuW9|dFkLB*lJ(2rO?)Q0ko_}6o-srrFJZ;{LyuQ5IdH3Y4&)byuY~F#qgL%K? z{gwAmeq_EZKPkU7UzJ~xKP}&p@62DGzdC-i;tLWBR0TB! z`T|EmPeFgdvVxTbs|)rO94vUX;G2S<3r-hC6vh`O7ODzs3iXAv3+ckeg_{c>F5FT0 zX5ssV9~A`@g%?E?l@)1G!^=|2Qp+@Dy0QsnGs^nPW|yrg+fw#G*`cyyWyj0@8SOLLe{|;PqS2+J zr;KhL?HGOI=sQN=HG0qJ{i9zR<2NRBOvD)LnCW9W#ym9Ui7|V|ipK_x4H;`3J8A6H zvD?NzK6dvwa-3wGbllW&ZR4hodwkrp}l z_o)x6U)4|=sU}p@q-oaJHJddLYj$W(YJSt4t*ERpRG2F6saRjJsp7keUn|a37F3R@ zR94stc=2sux$^RDEmpm({1Lf3B&isjF$M zd8Fpanx|{=TL0R>T6=A0?abOkwa03Y>k4&ab>+G{bgOjt>3-Jzsry?$Ro|wcu76&C zNdKB4$&hZyGV~c17-+*ghEEKiPspB7GNEk3stKDW+;0pw4mTzkZ#3RvyvumX_`C5> z6I4%36HQx9J4}z8NwdT(HBUC%&F$vh=6&WD>ZEnib#Zkw>iX(t*S%QxTHTTQVf7>H z74@_0>H5X>Z`FTP|4DvnSD$7EgL&(%wn?C!L*)PZmv9 zPp+M8n0)o*>nAUr{LJK+CciQza7yHqm?_OuW=!dvvUkcWQw~oJof8^we`K$k6S-&{i5~T z)|0J2w*K5EZX4eARNLORSKE%Y9dCQD?ZdXu+rDc1w(VrwsrJP7(e3r^miG4c8SS0z zGu!*xXSFYGzp?%1_S@R;XkXdBx_xc?hW1VEueJZ>kUMf5d5#iCg`?JCaF`tRjwz05 z4jWuo-0qm^=yS|>+~By)afjnB$32d_dCDt2N_kQ%^fp3 zdOBuz+}Lqb$DJK3I#zb9>e$q=r{kH9=Q{RvywLGd$IBfDJ6`R0qvL4DTOFTveBSY8 z$2Xm0I;%TtJN2E$&c{2S?|h;2rOsEn(!0iVsk*d$JqU-ZlGr~!uAlrX4C|`?{{W@I B-sJ!Q literal 0 HcmV?d00001 diff --git a/Example/Example.xcodeproj/project.xcworkspace/xcuserdata/Panajev.xcuserdatad/WorkspaceSettings.xcsettings b/Example/Example.xcodeproj/project.xcworkspace/xcuserdata/Panajev.xcuserdatad/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..659c876 --- /dev/null +++ b/Example/Example.xcodeproj/project.xcworkspace/xcuserdata/Panajev.xcuserdatad/WorkspaceSettings.xcsettings @@ -0,0 +1,10 @@ + + + + + HasAskedToTakeAutomaticSnapshotBeforeSignificantChanges + + SnapshotAutomaticallyBeforeSignificantChanges + + + diff --git a/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist b/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist new file mode 100644 index 0000000..05301bc --- /dev/null +++ b/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist @@ -0,0 +1,5 @@ + + + diff --git a/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/Example.xcscheme b/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/Example.xcscheme new file mode 100644 index 0000000..a679d7c --- /dev/null +++ b/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/Example.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/cocos2d libraries.xcscheme b/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/cocos2d libraries.xcscheme new file mode 100644 index 0000000..94eaaeb --- /dev/null +++ b/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/cocos2d libraries.xcscheme @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/xcschememanagement.plist b/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..23e994e --- /dev/null +++ b/Example/Example.xcodeproj/xcuserdata/Panajev.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,32 @@ + + + + + SchemeUserState + + Example.xcscheme + + orderHint + 0 + + cocos2d libraries.xcscheme + + orderHint + 1 + + + SuppressBuildableAutocreation + + 1D6058900D05DD3D006BFB54 + + primary + + + 506EE05D10304ED200A389B3 + + primary + + + + + diff --git a/Example/LICENSE.cocos2d b/Example/LICENSE.cocos2d deleted file mode 100644 index 9800e4a..0000000 --- a/Example/LICENSE.cocos2d +++ /dev/null @@ -1,23 +0,0 @@ -cocos2d for iPhone: http://www.cocos2d-iphone.org - -Copyright (c) 2008-2010 - Ricardo Quesada and contributors -(see each file to see the different copyright owners) - - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Example/LICENSE.cocosdenshion b/Example/LICENSE.cocosdenshion deleted file mode 100644 index 124035f..0000000 --- a/Example/LICENSE.cocosdenshion +++ /dev/null @@ -1,21 +0,0 @@ - CocosDenshion Sound Engine - - Copyright (c) 2010 Steve Oldmeadow - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. \ No newline at end of file diff --git a/Example/libs/CocosDenshion/CDAudioManager.h b/Example/libs/CocosDenshion/CDAudioManager.h deleted file mode 100644 index a245465..0000000 --- a/Example/libs/CocosDenshion/CDAudioManager.h +++ /dev/null @@ -1,241 +0,0 @@ -/* - Copyright (c) 2010 Steve Oldmeadow - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - $Id$ - */ - -#import "CocosDenshion.h" -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 30000 - #import -#else - #import "CDXMacOSXSupport.h" -#endif - -/** Different modes of the engine */ -typedef enum { - kAMM_FxOnly, //!Other apps will be able to play audio - kAMM_FxPlusMusic, //!Only this app will play audio - kAMM_FxPlusMusicIfNoOtherAudio, //!If another app is playing audio at start up then allow it to continue and don't play music - kAMM_MediaPlayback, //!This app takes over audio e.g music player app - kAMM_PlayAndRecord //!App takes over audio and has input and output -} tAudioManagerMode; - -/** Possible states of the engine */ -typedef enum { - kAMStateUninitialised, //!Audio manager has not been initialised - do not use - kAMStateInitialising, //!Audio manager is in the process of initialising - do not use - kAMStateInitialised //!Audio manager is initialised - safe to use -} tAudioManagerState; - -typedef enum { - kAMRBDoNothing, //Audio manager will not do anything on resign or becoming active - kAMRBStopPlay, //Background music is stopped on resign and resumed on become active - kAMRBStop //Background music is stopped on resign but not resumed - maybe because you want to do this from within your game -} tAudioManagerResignBehavior; - - -@interface CDAsynchInitialiser : NSOperation {} -@end - -/** CDAudioManager supports two long audio source channels called left and right*/ -typedef enum { - kASC_Left = 0, - kASC_Right = 1 -} tAudioSourceChannel; - -typedef enum { - kLAS_Init, - kLAS_Loaded, - kLAS_Playing, - kLAS_Paused, - kLAS_Stopped, -} tLongAudioSourceState; - -@class CDLongAudioSource; -@protocol CDLongAudioSourceDelegate -@optional -/** The audio source completed playing */ -- (void) cdAudioSourceDidFinishPlaying:(CDLongAudioSource *) audioSource; -/** The file used to load the audio source has changed */ -- (void) cdAudioSourceFileDidChange:(CDLongAudioSource *) audioSource; -@end - -/** - CDLongAudioSource represents an audio source that has a long duration which makes - it costly to load into memory for playback as an effect using CDSoundEngine. Examples - include background music and narration tracks. The audio file may or may not be compressed. - Bear in mind that current iDevices can only use hardware to decode a single compressed - audio file at a time and playing multiple compressed files will result in a performance drop - as software decompression will take place. - @since v0.99 - */ -@interface CDLongAudioSource : NSObject { - AVAudioPlayer *audioSourcePlayer; - NSString *audioSourceFilePath; - NSInteger numberOfLoops; - float volume; - id delegate; - BOOL mute; - BOOL enabled_; - BOOL backgroundMusic; -@public - BOOL systemPaused;//Used for auto resign handling - NSTimeInterval systemPauseLocation;//Used for auto resign handling -@protected - tLongAudioSourceState state; -} -@property (readonly) AVAudioPlayer *audioSourcePlayer; -@property (readonly) NSString *audioSourceFilePath; -@property (readwrite, nonatomic) NSInteger numberOfLoops; -@property (readwrite, nonatomic) float volume; -@property (assign) id delegate; -/* This long audio source functions as background music */ -@property (readwrite, nonatomic) BOOL backgroundMusic; - -/** Loads the file into the audio source */ --(void) load:(NSString*) filePath; -/** Plays the audio source */ --(void) play; -/** Stops playing the audio soruce */ --(void) stop; -/** Pauses the audio source */ --(void) pause; -/** Rewinds the audio source */ --(void) rewind; -/** Resumes playing the audio source if it was paused */ --(void) resume; -/** Returns whether or not the audio source is playing */ --(BOOL) isPlaying; - -@end - -/** - CDAudioManager manages audio requirements for a game. It provides access to a CDSoundEngine object - for playing sound effects. It provides access to two CDLongAudioSource object (left and right channel) - for playing long duration audio such as background music and narration tracks. Additionally it manages - the audio session to take care of things like audio session interruption and interacting with the audio - of other apps that are running on the device. - - Requirements: - - Firmware: OS 2.2 or greater - - Files: CDAudioManager.*, CocosDenshion.* - - Frameworks: OpenAL, AudioToolbox, AVFoundation - @since v0.8 - */ -@interface CDAudioManager : NSObject { - CDSoundEngine *soundEngine; - CDLongAudioSource *backgroundMusic; - NSMutableArray *audioSourceChannels; - NSString* _audioSessionCategory; - BOOL _audioWasPlayingAtStartup; - tAudioManagerMode _mode; - SEL backgroundMusicCompletionSelector; - id backgroundMusicCompletionListener; - BOOL willPlayBackgroundMusic; - BOOL _mute; - BOOL _resigned; - BOOL _interrupted; - BOOL _audioSessionActive; - BOOL enabled_; - - //For handling resign/become active - BOOL _isObservingAppEvents; - tAudioManagerResignBehavior _resignBehavior; -} - -@property (readonly) CDSoundEngine *soundEngine; -@property (readonly) CDLongAudioSource *backgroundMusic; -@property (readonly) BOOL willPlayBackgroundMusic; - -/** Returns the shared singleton */ -+ (CDAudioManager *) sharedManager; -+ (tAudioManagerState) sharedManagerState; -/** Configures the shared singleton with a mode*/ -+ (void) configure: (tAudioManagerMode) mode; -/** Initializes the engine asynchronously with a mode */ -+ (void) initAsynchronously: (tAudioManagerMode) mode; -/** Initializes the engine synchronously with a mode, channel definition and a total number of channels */ -- (id) init: (tAudioManagerMode) mode; --(void) audioSessionInterrupted; --(void) audioSessionResumed; --(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle; -/** Returns true is audio is muted at a hardware level e.g user has ringer switch set to off */ --(BOOL) isDeviceMuted; -/** Returns true if another app is playing audio such as the iPod music player */ --(BOOL) isOtherAudioPlaying; -/** Sets the way the audio manager interacts with the operating system such as whether it shares output with other apps or obeys the mute switch */ --(void) setMode:(tAudioManagerMode) mode; -/** Shuts down the shared audio manager instance so that it can be reinitialised */ -+(void) end; - -/** Call if you want to use built in resign behavior but need to do some additional audio processing on resign active. */ -- (void) applicationWillResignActive; -/** Call if you want to use built in resign behavior but need to do some additional audio processing on become active. */ -- (void) applicationDidBecomeActive; - -//New AVAudioPlayer API -/** Loads the data from the specified file path to the channel's audio source */ --(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel; -/** Retrieves the audio source for the specified channel */ --(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel; - -//Legacy AVAudioPlayer API -/** Plays music in background. The music can be looped or not - It is recommended to use .aac files as background music since they are decoded by the device (hardware). - */ --(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop; -/** Preloads a background music */ --(void) preloadBackgroundMusic:(NSString*) filePath; -/** Stops playing the background music */ --(void) stopBackgroundMusic; -/** Pauses the background music */ --(void) pauseBackgroundMusic; -/** Rewinds the background music */ --(void) rewindBackgroundMusic; -/** Resumes playing the background music */ --(void) resumeBackgroundMusic; -/** Returns whether or not the background music is playing */ --(BOOL) isBackgroundMusicPlaying; - --(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector; - -@end - -/** Fader for long audio source objects */ -@interface CDLongAudioSourceFader : CDPropertyModifier{} -@end - -static const int kCDNoBuffer = -1; - -/** Allows buffers to be associated with file names */ -@interface CDBufferManager:NSObject{ - NSMutableDictionary* loadedBuffers; - NSMutableArray *freedBuffers; - CDSoundEngine *soundEngine; - int nextBufferId; -} - --(id) initWithEngine:(CDSoundEngine *) theSoundEngine; --(int) bufferForFile:(NSString*) filePath create:(BOOL) create; --(void) releaseBufferForFile:(NSString *) filePath; - -@end - diff --git a/Example/libs/CocosDenshion/CDAudioManager.m b/Example/libs/CocosDenshion/CDAudioManager.m deleted file mode 100644 index 6f25a54..0000000 --- a/Example/libs/CocosDenshion/CDAudioManager.m +++ /dev/null @@ -1,897 +0,0 @@ -/* - Copyright (c) 2010 Steve Oldmeadow - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - $Id$ - */ - - -#import "CDAudioManager.h" - -//Audio session interruption callback - used if sound engine is -//handling audio session interruption automatically -/* -extern void managerInterruptionCallback (void *inUserData, UInt32 interruptionState ) { - CDAudioManager *controller = (CDAudioManager *) inUserData; - if (interruptionState == kAudioSessionBeginInterruption) { - [controller audioSessionInterrupted]; - } else if (interruptionState == kAudioSessionEndInterruption) { - [controller audioSessionResumed]; - } -} -*/ - -//NSOperation object used to asynchronously initialise -@implementation CDAsynchInitialiser - --(void) main { - [super main]; - [CDAudioManager sharedManager]; -} - -@end - -@implementation CDLongAudioSource - -@synthesize audioSourcePlayer, audioSourceFilePath, delegate, backgroundMusic; - --(id) init { - if ((self = [super init])) { - state = kLAS_Init; - volume = 1.0f; - mute = NO; - enabled_ = YES; - } - return self; -} - --(void) dealloc { - CDLOG(@"Denshion::CDLongAudioSource - deallocating %@", self); - [audioSourcePlayer release]; - [audioSourceFilePath release]; - [super dealloc]; -} - --(void) load:(NSString*) filePath { - //We have alread loaded a file previously, check if we are being asked to load the same file - if (state == kLAS_Init || ![filePath isEqualToString:audioSourceFilePath]) { - CDLOG(@"Denshion::CDLongAudioSource - Loading new audio source %@",filePath); - //New file - if (state != kLAS_Init) { - [audioSourceFilePath release];//Release old file path - [audioSourcePlayer release];//Release old AVAudioPlayer, they can't be reused - } - audioSourceFilePath = [filePath copy]; - NSError *error = nil; - NSString *path = [CDUtilities fullPathFromRelativePath:audioSourceFilePath]; - audioSourcePlayer = [(AVAudioPlayer*)[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; - if (error == nil) { - [audioSourcePlayer prepareToPlay]; - audioSourcePlayer.delegate = self; - if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceFileDidChange:)]) { - //Tell our delegate the file has changed - [delegate cdAudioSourceFileDidChange:self]; - } - } else { - CDLOG(@"Denshion::CDLongAudioSource - Error initialising audio player: %@",error); - } - } else { - //Same file - just return it to a consistent state - [self pause]; - [self rewind]; - } - audioSourcePlayer.volume = volume; - audioSourcePlayer.numberOfLoops = numberOfLoops; - state = kLAS_Loaded; -} - --(void) play { - if (enabled_) { - self->systemPaused = NO; - [audioSourcePlayer play]; - } else { - CDLOG(@"Denshion::CDLongAudioSource long audio source didn't play because it is disabled"); - } -} - --(void) stop { - [audioSourcePlayer stop]; -} - --(void) pause { - [audioSourcePlayer pause]; -} - --(void) rewind { - [audioSourcePlayer setCurrentTime:0]; -} - --(void) resume { - [audioSourcePlayer play]; -} - --(BOOL) isPlaying { - if (state != kLAS_Init) { - return [audioSourcePlayer isPlaying]; - } else { - return NO; - } -} - --(void) setVolume:(float) newVolume -{ - volume = newVolume; - if (state != kLAS_Init && !mute) { - audioSourcePlayer.volume = newVolume; - } -} - --(float) volume -{ - return volume; -} - -#pragma mark Audio Interrupt Protocol --(BOOL) mute -{ - return mute; -} - --(void) setMute:(BOOL) muteValue -{ - if (mute != muteValue) { - if (mute) { - //Turn sound back on - audioSourcePlayer.volume = volume; - } else { - audioSourcePlayer.volume = 0.0f; - } - mute = muteValue; - } -} - --(BOOL) enabled -{ - return enabled_; -} - --(void) setEnabled:(BOOL)enabledValue -{ - if (enabledValue != enabled_) { - enabled_ = enabledValue; - if (!enabled_) { - //"Stop" the sounds - [self pause]; - [self rewind]; - } - } -} - --(NSInteger) numberOfLoops { - return numberOfLoops; -} - --(void) setNumberOfLoops:(NSInteger) loopCount -{ - audioSourcePlayer.numberOfLoops = loopCount; - numberOfLoops = loopCount; -} - -- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { - CDLOG(@"Denshion::CDLongAudioSource - audio player finished"); -#if TARGET_IPHONE_SIMULATOR - CDLOG(@"Denshion::CDLongAudioSource - workaround for OpenAL clobbered audio issue"); - //This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is - //that OpenAL audio playback is clobbered when an AVAudioPlayer stops. Workaround - //is to keep the player playing on an endless loop with 0 volume and then when - //it is played again reset the volume and set loop count appropriately. - //NB: this workaround is not foolproof but it is good enough for most situations. - player.numberOfLoops = -1; - player.volume = 0; - [player play]; -#endif - if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceDidFinishPlaying:)]) { - [delegate cdAudioSourceDidFinishPlaying:self]; - } -} - --(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player { - CDLOG(@"Denshion::CDLongAudioSource - audio player interrupted"); -} - --(void)audioPlayerEndInterruption:(AVAudioPlayer *)player { - CDLOG(@"Denshion::CDLongAudioSource - audio player resumed"); - if (self.backgroundMusic) { - //Check if background music can play as rules may have changed during - //the interruption. This is to address a specific issue in 4.x when - //fast task switching - if([CDAudioManager sharedManager].willPlayBackgroundMusic) { - [player play]; - } - } else { - [player play]; - } -} - -@end - - -@interface CDAudioManager (PrivateMethods) --(BOOL) audioSessionSetActive:(BOOL) active; --(BOOL) audioSessionSetCategory:(NSString*) category; --(void) badAlContextHandler; -@end - - -@implementation CDAudioManager -#define BACKGROUND_MUSIC_CHANNEL kASC_Left - -@synthesize soundEngine, willPlayBackgroundMusic; -static CDAudioManager *sharedManager; -static tAudioManagerState _sharedManagerState = kAMStateUninitialised; -static tAudioManagerMode configuredMode; -static BOOL configured = FALSE; - --(BOOL) audioSessionSetActive:(BOOL) active { - NSError *activationError = nil; - if ([[AVAudioSession sharedInstance] setActive:active error:&activationError]) { - _audioSessionActive = active; - CDLOG(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active); - return YES; - } else { - //Failed - CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError); - return NO; - } -} - --(BOOL) audioSessionSetCategory:(NSString*) category { - NSError *categoryError = nil; - if ([[AVAudioSession sharedInstance] setCategory:category error:&categoryError]) { - CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category); - return YES; - } else { - //Failed - CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError); - return NO; - } -} - -// Init -+ (CDAudioManager *) sharedManager -{ - @synchronized(self) { - if (!sharedManager) { - if (!configured) { - //Set defaults here - configuredMode = kAMM_FxPlusMusicIfNoOtherAudio; - } - sharedManager = [[CDAudioManager alloc] init:configuredMode]; - _sharedManagerState = kAMStateInitialised;//This is only really relevant when using asynchronous initialisation - } - } - return sharedManager; -} - -+ (tAudioManagerState) sharedManagerState { - return _sharedManagerState; -} - -/** - * Call this to set up audio manager asynchronously. Initialisation is finished when sharedManagerState == kAMStateInitialised - */ -+ (void) initAsynchronously: (tAudioManagerMode) mode { - @synchronized(self) { - if (_sharedManagerState == kAMStateUninitialised) { - _sharedManagerState = kAMStateInitialising; - [CDAudioManager configure:mode]; - CDAsynchInitialiser *initOp = [[[CDAsynchInitialiser alloc] init] autorelease]; - NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease]; - [opQ addOperation:initOp]; - } - } -} - -+ (id) alloc -{ - @synchronized(self) { - NSAssert(sharedManager == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; - } - return nil; -} - -/* - * Call this method before accessing the shared manager in order to configure the shared audio manager - */ -+ (void) configure: (tAudioManagerMode) mode { - configuredMode = mode; - configured = TRUE; -} - --(BOOL) isOtherAudioPlaying { - UInt32 isPlaying = 0; - UInt32 varSize = sizeof(isPlaying); - AudioSessionGetProperty (kAudioSessionProperty_OtherAudioIsPlaying, &varSize, &isPlaying); - return (isPlaying != 0); -} - --(void) setMode:(tAudioManagerMode) mode { - - _mode = mode; - switch (_mode) { - - case kAMM_FxOnly: - //Share audio with other app - CDLOG(@"Denshion::CDAudioManager - Audio will be shared"); - //_audioSessionCategory = kAudioSessionCategory_AmbientSound; - _audioSessionCategory = AVAudioSessionCategoryAmbient; - willPlayBackgroundMusic = NO; - break; - - case kAMM_FxPlusMusic: - //Use audio exclusively - if other audio is playing it will be stopped - CDLOG(@"Denshion::CDAudioManager - Audio will be exclusive"); - //_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound; - _audioSessionCategory = AVAudioSessionCategorySoloAmbient; - willPlayBackgroundMusic = YES; - break; - - case kAMM_MediaPlayback: - //Use audio exclusively, ignore mute switch and sleep - CDLOG(@"Denshion::CDAudioManager - Media playback mode, audio will be exclusive"); - //_audioSessionCategory = kAudioSessionCategory_MediaPlayback; - _audioSessionCategory = AVAudioSessionCategoryPlayback; - willPlayBackgroundMusic = YES; - break; - - case kAMM_PlayAndRecord: - //Use audio exclusively, ignore mute switch and sleep, has inputs and outputs - CDLOG(@"Denshion::CDAudioManager - Play and record mode, audio will be exclusive"); - //_audioSessionCategory = kAudioSessionCategory_PlayAndRecord; - _audioSessionCategory = AVAudioSessionCategoryPlayAndRecord; - willPlayBackgroundMusic = YES; - break; - - default: - //kAudioManagerFxPlusMusicIfNoOtherAudio - if ([self isOtherAudioPlaying]) { - CDLOG(@"Denshion::CDAudioManager - Other audio is playing audio will be shared"); - //_audioSessionCategory = kAudioSessionCategory_AmbientSound; - _audioSessionCategory = AVAudioSessionCategoryAmbient; - willPlayBackgroundMusic = NO; - } else { - CDLOG(@"Denshion::CDAudioManager - Other audio is not playing audio will be exclusive"); - //_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound; - _audioSessionCategory = AVAudioSessionCategorySoloAmbient; - willPlayBackgroundMusic = YES; - } - - break; - } - - [self audioSessionSetCategory:_audioSessionCategory]; - -} - -/** - * This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the - * audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following - * standard practices. If we detect this situation then we will attempt to resume the audio session ourselves. - * Known triggers: lock the device then unlock it (iOS 4.2 gm), playback a song using MPMediaPlayer (iOS 4.0) - */ -- (void) badAlContextHandler { - if (_interrupted && alcGetCurrentContext() == NULL) { - CDLOG(@"Denshion::CDAudioManager - bad OpenAL context detected, attempting to resume audio session"); - [self audioSessionResumed]; - } -} - -- (id) init: (tAudioManagerMode) mode { - if ((self = [super init])) { - - //Initialise the audio session - AVAudioSession* session = [AVAudioSession sharedInstance]; - session.delegate = self; - - _mode = mode; - backgroundMusicCompletionSelector = nil; - _isObservingAppEvents = FALSE; - _mute = NO; - _resigned = NO; - _interrupted = NO; - enabled_ = YES; - _audioSessionActive = NO; - [self setMode:mode]; - soundEngine = [[CDSoundEngine alloc] init]; - - //Set up audioSource channels - audioSourceChannels = [[NSMutableArray alloc] init]; - CDLongAudioSource *leftChannel = [[CDLongAudioSource alloc] init]; - leftChannel.backgroundMusic = YES; - CDLongAudioSource *rightChannel = [[CDLongAudioSource alloc] init]; - rightChannel.backgroundMusic = NO; - [audioSourceChannels insertObject:leftChannel atIndex:kASC_Left]; - [audioSourceChannels insertObject:rightChannel atIndex:kASC_Right]; - [leftChannel release]; - [rightChannel release]; - //Used to support legacy APIs - backgroundMusic = [self audioSourceForChannel:BACKGROUND_MUSIC_CHANNEL]; - backgroundMusic.delegate = self; - - //Add handler for bad al context messages, these are posted by the sound engine. - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(badAlContextHandler) name:CD_MSG_BAD_AL_CONTEXT object:nil]; - - } - return self; -} - --(void) dealloc { - CDLOG(@"Denshion::CDAudioManager - deallocating"); - [self stopBackgroundMusic]; - [soundEngine release]; - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [self audioSessionSetActive:NO]; - [audioSourceChannels release]; - [super dealloc]; -} - -/** Retrieves the audio source for the specified channel */ --(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel -{ - return (CDLongAudioSource*)[audioSourceChannels objectAtIndex:channel]; -} - -/** Loads the data from the specified file path to the channel's audio source */ --(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel -{ - CDLongAudioSource *audioSource = [self audioSourceForChannel:channel]; - if (audioSource) { - [audioSource load:filePath]; - } - return audioSource; -} - --(BOOL) isBackgroundMusicPlaying { - return [self.backgroundMusic isPlaying]; -} - -//NB: originally I tried using a route change listener and intended to store the current route, -//however, on a 3gs running 3.1.2 no route change is generated when the user switches the -//ringer mute switch to off (i.e. enables sound) therefore polling is the only reliable way to -//determine ringer switch state --(BOOL) isDeviceMuted { - -#if TARGET_IPHONE_SIMULATOR - //Calling audio route stuff on the simulator causes problems - return NO; -#else - CFStringRef newAudioRoute; - UInt32 propertySize = sizeof (CFStringRef); - - AudioSessionGetProperty ( - kAudioSessionProperty_AudioRoute, - &propertySize, - &newAudioRoute - ); - - if (newAudioRoute == NULL) { - //Don't expect this to happen but playing safe otherwise a null in the CFStringCompare will cause a crash - return YES; - } else { - CFComparisonResult newDeviceIsMuted = CFStringCompare ( - newAudioRoute, - (CFStringRef) @"", - 0 - ); - - return (newDeviceIsMuted == kCFCompareEqualTo); - } -#endif -} - -#pragma mark Audio Interrupt Protocol - --(BOOL) mute { - return _mute; -} - --(void) setMute:(BOOL) muteValue { - if (muteValue != _mute) { - _mute = muteValue; - [soundEngine setMute:muteValue]; - for( CDLongAudioSource *audioSource in audioSourceChannels) { - audioSource.mute = muteValue; - } - } -} - --(BOOL) enabled { - return enabled_; -} - --(void) setEnabled:(BOOL) enabledValue { - if (enabledValue != enabled_) { - enabled_ = enabledValue; - [soundEngine setEnabled:enabled_]; - for( CDLongAudioSource *audioSource in audioSourceChannels) { - audioSource.enabled = enabled_; - } - } -} - --(CDLongAudioSource*) backgroundMusic -{ - return backgroundMusic; -} - -//Load background music ready for playing --(void) preloadBackgroundMusic:(NSString*) filePath -{ - [self.backgroundMusic load:filePath]; -} - --(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop -{ - [self.backgroundMusic load:filePath]; - - if (!willPlayBackgroundMusic || _mute) { - CDLOG(@"Denshion::CDAudioManager - play bgm aborted because audio is not exclusive or sound is muted"); - return; - } - - if (loop) { - [self.backgroundMusic setNumberOfLoops:-1]; - } else { - [self.backgroundMusic setNumberOfLoops:0]; - } - [self.backgroundMusic play]; -} - --(void) stopBackgroundMusic -{ - [self.backgroundMusic stop]; -} - --(void) pauseBackgroundMusic -{ - [self.backgroundMusic pause]; -} - --(void) resumeBackgroundMusic -{ - if (!willPlayBackgroundMusic || _mute) { - CDLOG(@"Denshion::CDAudioManager - resume bgm aborted because audio is not exclusive or sound is muted"); - return; - } - - [self.backgroundMusic resume]; -} - --(void) rewindBackgroundMusic -{ - [self.backgroundMusic rewind]; -} - --(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector { - backgroundMusicCompletionListener = listener; - backgroundMusicCompletionSelector = selector; -} - -/* - * Call this method to have the audio manager automatically handle application resign and - * become active. Pass a tAudioManagerResignBehavior to indicate the desired behavior - * for resigning and becoming active again. - * - * If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive - * methods are automatically called, otherwise you must call them yourself at the appropriate time. - * - * Based on idea of Dominique Bongard - */ --(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle { - - if (!_isObservingAppEvents && autoHandle) { - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:@"UIApplicationWillResignActiveNotification" object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:@"UIApplicationDidBecomeActiveNotification" object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:@"UIApplicationWillTerminateNotification" object:nil]; - _isObservingAppEvents = TRUE; - } - _resignBehavior = resignBehavior; -} - -- (void) applicationWillResignActive { - self->_resigned = YES; - - //Set the audio sesssion to one that allows sharing so that other audio won't be clobbered on resume - [self audioSessionSetCategory:AVAudioSessionCategoryAmbient]; - - switch (_resignBehavior) { - - case kAMRBStopPlay: - - for( CDLongAudioSource *audioSource in audioSourceChannels) { - if (audioSource.isPlaying) { - audioSource->systemPaused = YES; - audioSource->systemPauseLocation = audioSource.audioSourcePlayer.currentTime; - [audioSource stop]; - } else { - //Music is either paused or stopped, if it is paused it will be restarted - //by OS so we will stop it. - audioSource->systemPaused = NO; - [audioSource stop]; - } - } - break; - - case kAMRBStop: - //Stop music regardless of whether it is playing or not because if it was paused - //then the OS would resume it - for( CDLongAudioSource *audioSource in audioSourceChannels) { - [audioSource stop]; - } - - default: - break; - - } - CDLOG(@"Denshion::CDAudioManager - handled resign active"); -} - -//Called when application resigns active only if setResignBehavior has been called -- (void) applicationWillResignActive:(NSNotification *) notification -{ - [self applicationWillResignActive]; -} - -- (void) applicationDidBecomeActive { - - if (self->_resigned) { - _resigned = NO; - //Reset the mode incase something changed with audio while we were inactive - [self setMode:_mode]; - switch (_resignBehavior) { - - case kAMRBStopPlay: - - //Music had been stopped but stop maintains current time - //so playing again will continue from where music was before resign active. - //We check if music can be played because while we were inactive the user might have - //done something that should force music to not play such as starting a track in the iPod - if (self.willPlayBackgroundMusic) { - for( CDLongAudioSource *audioSource in audioSourceChannels) { - if (audioSource->systemPaused) { - [audioSource resume]; - audioSource->systemPaused = NO; - } - } - } - break; - - default: - break; - - } - CDLOG(@"Denshion::CDAudioManager - audio manager handled become active"); - } -} - -//Called when application becomes active only if setResignBehavior has been called -- (void) applicationDidBecomeActive:(NSNotification *) notification -{ - [self applicationDidBecomeActive]; -} - -//Called when application terminates only if setResignBehavior has been called -- (void) applicationWillTerminate:(NSNotification *) notification -{ - CDLOG(@"Denshion::CDAudioManager - audio manager handling terminate"); - [self stopBackgroundMusic]; -} - -/** The audio source completed playing */ -- (void) cdAudioSourceDidFinishPlaying:(CDLongAudioSource *) audioSource { - CDLOG(@"Denshion::CDAudioManager - audio manager got told background music finished"); - if (backgroundMusicCompletionSelector != nil) { - [backgroundMusicCompletionListener performSelector:backgroundMusicCompletionSelector]; - } -} - --(void) beginInterruption { - CDLOG(@"Denshion::CDAudioManager - begin interruption"); - [self audioSessionInterrupted]; -} - --(void) endInterruption { - CDLOG(@"Denshion::CDAudioManager - end interruption"); - [self audioSessionResumed]; -} - -#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 --(void) endInterruptionWithFlags:(NSUInteger)flags { - CDLOG(@"Denshion::CDAudioManager - interruption ended with flags %i",flags); - if (flags == AVAudioSessionInterruptionFlags_ShouldResume) { - [self audioSessionResumed]; - } -} -#endif - --(void)audioSessionInterrupted -{ - if (!_interrupted) { - CDLOG(@"Denshion::CDAudioManager - Audio session interrupted"); - _interrupted = YES; - - // Deactivate the current audio session - [self audioSessionSetActive:NO]; - - if (alcGetCurrentContext() != NULL) { - CDLOG(@"Denshion::CDAudioManager - Setting OpenAL context to NULL"); - - ALenum error = AL_NO_ERROR; - - // set the current context to NULL will 'shutdown' openAL - alcMakeContextCurrent(NULL); - - if((error = alGetError()) != AL_NO_ERROR) { - CDLOG(@"Denshion::CDAudioManager - Error making context current %x\n", error); - } - #pragma unused(error) - } - } -} - --(void)audioSessionResumed -{ - if (_interrupted) { - CDLOG(@"Denshion::CDAudioManager - Audio session resumed"); - _interrupted = NO; - - BOOL activationResult = NO; - // Reactivate the current audio session - activationResult = [self audioSessionSetActive:YES]; - - //This code is to handle a problem with iOS 4.0 and 4.01 where reactivating the session can fail if - //task switching is performed too rapidly. A test case that reliably reproduces the issue is to call the - //iPhone and then hang up after two rings (timing may vary ;)) - //Basically we keep waiting and trying to let the OS catch up with itself but the number of tries is - //limited. - if (!activationResult) { - CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle"); - int activateCount = 0; - while (!activationResult && activateCount < 10) { - [NSThread sleepForTimeInterval:0.5]; - activationResult = [self audioSessionSetActive:YES]; - activateCount++; - CDLOG(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult); - } - } - - if (alcGetCurrentContext() == NULL) { - CDLOG(@"Denshion::CDAudioManager - Restoring OpenAL context"); - ALenum error = AL_NO_ERROR; - // Restore open al context - alcMakeContextCurrent([soundEngine openALContext]); - if((error = alGetError()) != AL_NO_ERROR) { - CDLOG(@"Denshion::CDAudioManager - Error making context current%x\n", error); - } - #pragma unused(error) - } - } -} - -+(void) end { - [sharedManager release]; - sharedManager = nil; -} - -@end - -/////////////////////////////////////////////////////////////////////////////////////// -@implementation CDLongAudioSourceFader - --(void) _setTargetProperty:(float) newVal { - ((CDLongAudioSource*)target).volume = newVal; -} - --(float) _getTargetProperty { - return ((CDLongAudioSource*)target).volume; -} - --(void) _stopTarget { - //Pause instead of stop as stop releases resources and causes problems in the simulator - [((CDLongAudioSource*)target) pause]; -} - --(Class) _allowableType { - return [CDLongAudioSource class]; -} - -@end -/////////////////////////////////////////////////////////////////////////////////////// -@implementation CDBufferManager - --(id) initWithEngine:(CDSoundEngine *) theSoundEngine { - if ((self = [super init])) { - soundEngine = theSoundEngine; - loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START]; - freedBuffers = [[NSMutableArray alloc] init]; - nextBufferId = 0; - } - return self; -} - --(void) dealloc { - [loadedBuffers release]; - [freedBuffers release]; - [super dealloc]; -} - --(int) bufferForFile:(NSString*) filePath create:(BOOL) create { - - NSNumber* soundId = (NSNumber*)[loadedBuffers objectForKey:filePath]; - if(soundId == nil) - { - if (create) { - NSNumber* bufferId = nil; - //First try to get a buffer from the free buffers - if ([freedBuffers count] > 0) { - bufferId = [[[freedBuffers lastObject] retain] autorelease]; - [freedBuffers removeLastObject]; - CDLOG(@"Denshion::CDBufferManager reusing buffer id %i",[bufferId intValue]); - } else { - bufferId = [[NSNumber alloc] initWithInt:nextBufferId]; - [bufferId autorelease]; - CDLOG(@"Denshion::CDBufferManager generating new buffer id %i",[bufferId intValue]); - nextBufferId++; - } - - if ([soundEngine loadBuffer:[bufferId intValue] filePath:filePath]) { - //File successfully loaded - CDLOG(@"Denshion::CDBufferManager buffer loaded %@ %@",bufferId,filePath); - [loadedBuffers setObject:bufferId forKey:filePath]; - return [bufferId intValue]; - } else { - //File didn't load, put buffer id on free list - [freedBuffers addObject:bufferId]; - return kCDNoBuffer; - } - } else { - //No matching buffer was found - return kCDNoBuffer; - } - } else { - return [soundId intValue]; - } -} - --(void) releaseBufferForFile:(NSString *) filePath { - int bufferId = [self bufferForFile:filePath create:NO]; - if (bufferId != kCDNoBuffer) { - [soundEngine unloadBuffer:bufferId]; - [loadedBuffers removeObjectForKey:filePath]; - NSNumber *freedBufferId = [[NSNumber alloc] initWithInt:bufferId]; - [freedBufferId autorelease]; - [freedBuffers addObject:freedBufferId]; - } -} -@end - - - diff --git a/Example/libs/CocosDenshion/CDConfig.h b/Example/libs/CocosDenshion/CDConfig.h deleted file mode 100644 index 2bd8f76..0000000 --- a/Example/libs/CocosDenshion/CDConfig.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright (c) 2010 Steve Oldmeadow - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - $Id$ - */ -#define COCOSDENSHION_VERSION "Aphex.rc" - - -/** - If enabled code useful for debugging such as parameter check assertions will be performed. - If you experience any problems you should enable this and test your code with a debug build. - */ -//#define CD_DEBUG 1 - -/** - The total number of sounds/buffers that can be loaded assuming memory is sufficient - */ -//Number of buffers slots that will be initially created -#define CD_BUFFERS_START 64 -//Number of buffers that will be added -#define CD_BUFFERS_INCREMENT 16 - -/** - If enabled, OpenAL code will use static buffers. When static buffers are used the audio - data is managed outside of OpenAL, this eliminates a memcpy operation which leads to - higher performance when loading sounds. - - However, the downside is that when the audio data is freed you must - be certain that it is no longer being accessed otherwise your app will crash. Testing on OS 2.2.1 - and 3.1.2 has shown that this may occur if a buffer is being used by a source with state = AL_PLAYING - when the buffer is deleted. If the data is freed too quickly after the source is stopped then - a crash will occur. The implemented workaround is that when static buffers are used the unloadBuffer code will wait for - any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any - performance gains that are achieved during loading. - - Performance tests on a 1st gen iPod running OS 2.2.1 loading the CocosDenshionDemo sounds were ~0.14 seconds without - static buffers and ~0.12 seconds when using static buffers. - - */ -//#define CD_USE_STATIC_BUFFERS 1 - - diff --git a/Example/libs/CocosDenshion/CDOpenALSupport.h b/Example/libs/CocosDenshion/CDOpenALSupport.h deleted file mode 100644 index 661c69e..0000000 --- a/Example/libs/CocosDenshion/CDOpenALSupport.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - - Disclaimer: IMPORTANT: This Apple software is supplied to you by - Apple Inc. ("Apple") in consideration of your agreement to the - following terms, and your use, installation, modification or - redistribution of this Apple software constitutes acceptance of these - terms. If you do not agree with these terms, please do not use, - install, modify or redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. - may be used to endorse or promote products derived from the Apple - Software without specific prior written permission from Apple. Except - as expressly stated in this notice, no other rights or licenses, express - or implied, are granted by Apple herein, including but not limited to - any patent rights that may be infringed by your derivative works or by - other works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2009 Apple Inc. All Rights Reserved. - - $Id$ - */ - -/* - This file contains code from version 1.1 and 1.4 of MyOpenALSupport.h taken from Apple's oalTouch version. - The 1.4 version code is used for loading IMA4 files, however, this code causes very noticeable clicking - when used to load wave files that are looped so the 1.1 version code is used specifically for loading - wav files. - */ - -#ifndef __CD_OPENAL_H -#define __CD_OPENAL_H - -#ifdef __cplusplus -extern "C" { -#endif - - -#import -#import -#import - - -//Taken from oalTouch MyOpenALSupport 1.1 -void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); -void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); -void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); - -#ifdef __cplusplus -} -#endif - -#endif - - diff --git a/Example/libs/CocosDenshion/CDOpenALSupport.m b/Example/libs/CocosDenshion/CDOpenALSupport.m deleted file mode 100644 index ab0df8e..0000000 --- a/Example/libs/CocosDenshion/CDOpenALSupport.m +++ /dev/null @@ -1,246 +0,0 @@ -/* - - Disclaimer: IMPORTANT: This Apple software is supplied to you by - Apple Inc. ("Apple") in consideration of your agreement to the - following terms, and your use, installation, modification or - redistribution of this Apple software constitutes acceptance of these - terms. If you do not agree with these terms, please do not use, - install, modify or redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. - may be used to endorse or promote products derived from the Apple - Software without specific prior written permission from Apple. Except - as expressly stated in this notice, no other rights or licenses, express - or implied, are granted by Apple herein, including but not limited to - any patent rights that may be infringed by your derivative works or by - other works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2009 Apple Inc. All Rights Reserved. - - $Id: CDOpenALSupport.h 16 2010-03-11 06:22:10Z steveoldmeadow $ - */ - -#import "CDOpenALSupport.h" -#import "CocosDenshion.h" -#import -#import - -//Taken from oalTouch MyOpenALSupport 1.1 -void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate) -{ - OSStatus err = noErr; - UInt64 fileDataSize = 0; - AudioStreamBasicDescription theFileFormat; - UInt32 thePropertySize = sizeof(theFileFormat); - AudioFileID afid = 0; - void* theData = NULL; - - // Open a file with ExtAudioFileOpen() - err = AudioFileOpenURL(inFileURL, kAudioFileReadPermission, 0, &afid); - if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileOpenURL FAILED, Error = %ld\n", err); goto Exit; } - - // Get the audio data format - err = AudioFileGetProperty(afid, kAudioFilePropertyDataFormat, &thePropertySize, &theFileFormat); - if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFileProperty_DataFormat) FAILED, Error = %ld\n", err); goto Exit; } - - if (theFileFormat.mChannelsPerFrame > 2) { - CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n"); goto Exit; - } - - if ((theFileFormat.mFormatID != kAudioFormatLinearPCM) || (!TestAudioFormatNativeEndian(theFileFormat))) { - CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be little-endian PCM\n"); goto Exit; - } - - if ((theFileFormat.mBitsPerChannel != 8) && (theFileFormat.mBitsPerChannel != 16)) { - CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be 8 or 16 bit PCM\n"); goto Exit; - } - - - thePropertySize = sizeof(fileDataSize); - err = AudioFileGetProperty(afid, kAudioFilePropertyAudioDataByteCount, &thePropertySize, &fileDataSize); - if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFilePropertyAudioDataByteCount) FAILED, Error = %ld\n", err); goto Exit; } - - // Read all the data into memory - UInt32 dataSize = (UInt32)fileDataSize; - theData = malloc(dataSize); - if (theData) - { - AudioFileReadBytes(afid, false, 0, &dataSize, theData); - if(err == noErr) - { - // success - *outDataSize = (ALsizei)dataSize; - //This fix was added by me, however, 8 bit sounds have a clipping sound at the end so aren't really usable (SO) - if (theFileFormat.mBitsPerChannel == 16) { - *outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; - } else { - *outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8; - } - *outSampleRate = (ALsizei)theFileFormat.mSampleRate; - } - else - { - // failure - free (theData); - theData = NULL; // make sure to return NULL - CDLOG(@"MyGetOpenALAudioData: ExtAudioFileRead FAILED, Error = %ld\n", err); goto Exit; - } - } - -Exit: - // Dispose the ExtAudioFileRef, it is no longer needed - if (afid) AudioFileClose(afid); - return theData; -} - -//Taken from oalTouch MyOpenALSupport 1.4 -void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate) -{ - OSStatus status = noErr; - BOOL abort = NO; - SInt64 theFileLengthInFrames = 0; - AudioStreamBasicDescription theFileFormat; - UInt32 thePropertySize = sizeof(theFileFormat); - ExtAudioFileRef extRef = NULL; - void* theData = NULL; - AudioStreamBasicDescription theOutputFormat; - UInt32 dataSize = 0; - - // Open a file with ExtAudioFileOpen() - status = ExtAudioFileOpenURL(inFileURL, &extRef); - if (status != noErr) - { - CDLOG(@"MyGetOpenALAudioData: ExtAudioFileOpenURL FAILED, Error = %ld\n", status); - abort = YES; - } - if (abort) - goto Exit; - - // Get the audio data format - status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &theFileFormat); - if (status != noErr) - { - CDLOG(@"MyGetOpenALAudioData: ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = %ld\n", status); - abort = YES; - } - if (abort) - goto Exit; - - if (theFileFormat.mChannelsPerFrame > 2) - { - CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n"); - abort = YES; - } - if (abort) - goto Exit; - - // Set the client format to 16 bit signed integer (native-endian) data - // Maintain the channel count and sample rate of the original source format - theOutputFormat.mSampleRate = theFileFormat.mSampleRate; - theOutputFormat.mChannelsPerFrame = theFileFormat.mChannelsPerFrame; - - theOutputFormat.mFormatID = kAudioFormatLinearPCM; - theOutputFormat.mBytesPerPacket = 2 * theOutputFormat.mChannelsPerFrame; - theOutputFormat.mFramesPerPacket = 1; - theOutputFormat.mBytesPerFrame = 2 * theOutputFormat.mChannelsPerFrame; - theOutputFormat.mBitsPerChannel = 16; - theOutputFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger; - - // Set the desired client (output) data format - status = ExtAudioFileSetProperty(extRef, kExtAudioFileProperty_ClientDataFormat, sizeof(theOutputFormat), &theOutputFormat); - if (status != noErr) - { - CDLOG(@"MyGetOpenALAudioData: ExtAudioFileSetProperty(kExtAudioFileProperty_ClientDataFormat) FAILED, Error = %ld\n", status); - abort = YES; - } - if (abort) - goto Exit; - - // Get the total frame count - thePropertySize = sizeof(theFileLengthInFrames); - status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileLengthFrames, &thePropertySize, &theFileLengthInFrames); - if (status != noErr) - { - CDLOG(@"MyGetOpenALAudioData: ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = %ld\n", status); - abort = YES; - } - if (abort) - goto Exit; - - // Read all the data into memory - dataSize = (UInt32) theFileLengthInFrames * theOutputFormat.mBytesPerFrame; - theData = malloc(dataSize); - if (theData) - { - AudioBufferList theDataBuffer; - theDataBuffer.mNumberBuffers = 1; - theDataBuffer.mBuffers[0].mDataByteSize = dataSize; - theDataBuffer.mBuffers[0].mNumberChannels = theOutputFormat.mChannelsPerFrame; - theDataBuffer.mBuffers[0].mData = theData; - - // Read the data into an AudioBufferList - status = ExtAudioFileRead(extRef, (UInt32*)&theFileLengthInFrames, &theDataBuffer); - if(status == noErr) - { - // success - *outDataSize = (ALsizei)dataSize; - *outDataFormat = (theOutputFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; - *outSampleRate = (ALsizei)theOutputFormat.mSampleRate; - } - else - { - // failure - free (theData); - theData = NULL; // make sure to return NULL - CDLOG(@"MyGetOpenALAudioData: ExtAudioFileRead FAILED, Error = %ld\n", status); - abort = YES; - } - } - if (abort) - goto Exit; - -Exit: - // Dispose the ExtAudioFileRef, it is no longer needed - if (extRef) ExtAudioFileDispose(extRef); - return theData; -} - -void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate) { - - CFStringRef extension = CFURLCopyPathExtension(inFileURL); - CFComparisonResult isWavFile = 0; - if (extension != NULL) { - isWavFile = CFStringCompare (extension,(CFStringRef)@"wav", kCFCompareCaseInsensitive); - CFRelease(extension); - } - - if (isWavFile == kCFCompareEqualTo) { - return CDloadWaveAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); - } else { - return CDloadCafAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); - } -} - diff --git a/Example/libs/CocosDenshion/CocosDenshion.h b/Example/libs/CocosDenshion/CocosDenshion.h deleted file mode 100644 index bb5c720..0000000 --- a/Example/libs/CocosDenshion/CocosDenshion.h +++ /dev/null @@ -1,430 +0,0 @@ -/* - Copyright (c) 2010 Steve Oldmeadow - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - $Id$ - */ - - - -/** -@file -@b IMPORTANT -There are 3 different ways of using CocosDenshion. Depending on which you choose you -will need to include different files and frameworks. - -@par SimpleAudioEngine -This is recommended for basic audio requirements. If you just want to play some sound fx -and some background music and have no interest in learning the lower level workings then -this is the interface to use. - -Requirements: - - Firmware: OS 2.2 or greater - - Files: SimpleAudioEngine.*, CocosDenshion.* - - Frameworks: OpenAL, AudioToolbox, AVFoundation - -@par CDAudioManager -CDAudioManager is basically a thin wrapper around an AVAudioPlayer object used for playing -background music and a CDSoundEngine object used for playing sound effects. It manages the -audio session for you deals with audio session interruption. It is fairly low level and it -is expected you have some understanding of the underlying technologies. For example, for -many use cases regarding background music it is expected you will work directly with the -backgroundMusic AVAudioPlayer which is exposed as a property. - -Requirements: - - Firmware: OS 2.2 or greater - - Files: CDAudioManager.*, CocosDenshion.* - - Frameworks: OpenAL, AudioToolbox, AVFoundation - -@par CDSoundEngine -CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch -example. It can playback up to 32 sounds simultaneously with control over pitch, pan -and gain. It can be set up to handle audio session interruption automatically. You -may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine -because you require OS 2.0 compatibility. - -Requirements: - - Firmware: OS 2.0 or greater - - Files: CocosDenshion.* - - Frameworks: OpenAL, AudioToolbox - -*/ - -#import -#import -#import -#import -#import "CDConfig.h" - - -#if !defined(CD_DEBUG) || CD_DEBUG == 0 -#define CDLOG(...) do {} while (0) -#define CDLOGINFO(...) do {} while (0) - -#elif CD_DEBUG == 1 -#define CDLOG(...) NSLog(__VA_ARGS__) -#define CDLOGINFO(...) do {} while (0) - -#elif CD_DEBUG > 1 -#define CDLOG(...) NSLog(__VA_ARGS__) -#define CDLOGINFO(...) NSLog(__VA_ARGS__) -#endif // CD_DEBUG - - -#import "CDOpenALSupport.h" - -//Tested source limit on 2.2.1 and 3.1.2 with up to 128 sources and appears to work. Older OS versions e.g 2.2 may support only 32 -#define CD_SOURCE_LIMIT 32 //Total number of sources we will ever want, may actually get less -#define CD_NO_SOURCE 0xFEEDFAC //Return value indicating playback failed i.e. no source -#define CD_IGNORE_AUDIO_SESSION 0xBEEFBEE //Used internally to indicate audio session will not be handled -#define CD_MUTE 0xFEEDBAB //Return value indicating sound engine is muted or non functioning -#define CD_NO_SOUND = -1; - -#define CD_SAMPLE_RATE_HIGH 44100 -#define CD_SAMPLE_RATE_MID 22050 -#define CD_SAMPLE_RATE_LOW 16000 -#define CD_SAMPLE_RATE_BASIC 8000 -#define CD_SAMPLE_RATE_DEFAULT 44100 - -#define CD_MSG_BAD_AL_CONTEXT @"cdbadalcontext" - -enum bufferState { - CD_BS_EMPTY = 0, - CD_BS_LOADED = 1, - CD_BS_FAILED = 2 -}; - -typedef struct _sourceGroup { - int startIndex; - int currentIndex; - int totalSources; - bool enabled; - bool nonInterruptible; - int *sourceStatuses;//pointer into array of source status information -} sourceGroup; - -typedef struct _bufferInfo { - ALuint bufferId; - int bufferState; - void* bufferData; - ALenum format; - ALsizei sizeInBytes; - ALsizei frequencyInHertz; -} bufferInfo; - -typedef struct _sourceInfo { - bool usable; - ALuint sourceId; - ALuint attachedBufferId; -} sourceInfo; - -#pragma mark CDAudioTransportProtocol - -@protocol CDAudioTransportProtocol -/** Play the audio */ --(BOOL) play; -/** Pause the audio, retain resources */ --(BOOL) pause; -/** Stop the audio, release resources */ --(BOOL) stop; -/** Return playback to beginning */ --(BOOL) rewind; -@end - -#pragma mark CDAudioInterruptProtocol - -@protocol CDAudioInterruptProtocol -/** Is audio mute */ --(BOOL) mute; -/** If YES then audio is silenced but not stopped, calls to start new audio will proceed but silently */ --(void) setMute:(BOOL) muteValue; -/** Is audio enabled */ --(BOOL) enabled; -/** If NO then all audio is stopped and any calls to start new audio will be ignored */ --(void) setEnabled:(BOOL) enabledValue; -@end - -#pragma mark CDUtilities -/** - Collection of utilities required by CocosDenshion - */ -@interface CDUtilities : NSObject -{ -} - -/** Fundamentally the same as the corresponding method is CCFileUtils but added to break binding to cocos2d */ -+(NSString*) fullPathFromRelativePath:(NSString*) relPath; - -@end - - -#pragma mark CDSoundEngine - -/** CDSoundEngine is built upon OpenAL and works with SDK 2.0. - CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch - example. It can playback up to 32 sounds simultaneously with control over pitch, pan - and gain. It can be set up to handle audio session interruption automatically. You - may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine - because you require OS 2.0 compatibility. - - Requirements: - - Firmware: OS 2.0 or greater - - Files: CocosDenshion.* - - Frameworks: OpenAL, AudioToolbox - - @since v0.8 - */ -@class CDSoundSource; -@interface CDSoundEngine : NSObject { - - bufferInfo *_buffers; - sourceInfo *_sources; - sourceGroup *_sourceGroups; - ALCcontext *context; - int _sourceGroupTotal; - UInt32 _audioSessionCategory; - BOOL _handleAudioSession; - BOOL mute_; - BOOL enabled_; - ALfloat _preMuteGain; - - ALenum lastErrorCode_; - BOOL functioning_; - float asynchLoadProgress_; - BOOL getGainWorks_; - - //For managing dynamic allocation of sources and buffers - int sourceTotal_; - int bufferTotal; - -} - -@property (readwrite, nonatomic) ALfloat masterGain; -@property (readonly) ALenum lastErrorCode;//Last OpenAL error code that was generated -@property (readonly) BOOL functioning;//Is the sound engine functioning -@property (readwrite) float asynchLoadProgress; -@property (readonly) BOOL getGainWorks;//Does getting the gain for a source work -/** Total number of sources available */ -@property (readonly) int sourceTotal; -/** Total number of source groups that have been defined */ -@property (readonly) int sourceGroupTotal; - -/** Sets the sample rate for the audio mixer. For best performance this should match the sample rate of your audio content */ -+(void) setMixerSampleRate:(Float32) sampleRate; - -/** Initializes the engine with a group definition and a total number of groups */ --(id)init; - -/** Plays a sound in a channel group with a pitch, pan and gain. The sound could played looped or not */ --(ALuint) playSound:(int) soundId sourceGroupId:(int)sourceGroupId pitch:(float) pitch pan:(float) pan gain:(float) gain loop:(BOOL) loop; - -/** Creates and returns a sound source object for the specified sound within the specified source group. - */ --(CDSoundSource *) soundSourceForSound:(int) soundId sourceGroupId:(int) sourceGroupId; - -/** Stops playing a sound */ -- (void) stopSound:(ALuint) sourceId; -/** Stops playing a source group */ -- (void) stopSourceGroup:(int) sourceGroupId; -/** Stops all playing sounds */ --(void) stopAllSounds; --(void) defineSourceGroups:(NSArray*) sourceGroupDefinitions; --(void) defineSourceGroups:(int[]) sourceGroupDefinitions total:(int) total; --(void) setSourceGroupNonInterruptible:(int) sourceGroupId isNonInterruptible:(BOOL) isNonInterruptible; --(void) setSourceGroupEnabled:(int) sourceGroupId enabled:(BOOL) enabled; --(BOOL) sourceGroupEnabled:(int) sourceGroupId; --(BOOL) loadBufferFromData:(int) soundId soundData:(ALvoid*) soundData format:(ALenum) format size:(ALsizei) size freq:(ALsizei) freq; --(BOOL) loadBuffer:(int) soundId filePath:(NSString*) filePath; --(void) loadBuffersAsynchronously:(NSArray *) loadRequests; --(BOOL) unloadBuffer:(int) soundId; --(ALCcontext *) openALContext; - -/** Returns the duration of the buffer in seconds or a negative value if the buffer id is invalid */ --(float) bufferDurationInSeconds:(int) soundId; -/** Returns the size of the buffer in bytes or a negative value if the buffer id is invalid */ --(ALsizei) bufferSizeInBytes:(int) soundId; -/** Returns the sampling frequency of the buffer in hertz or a negative value if the buffer id is invalid */ --(ALsizei) bufferFrequencyInHertz:(int) soundId; - -/** Used internally, never call unless you know what you are doing */ --(void) _soundSourcePreRelease:(CDSoundSource *) soundSource; - -@end - -#pragma mark CDSoundSource -/** CDSoundSource is a wrapper around an OpenAL sound source. - It allows you to manipulate properties such as pitch, gain, pan and looping while the - sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much - added functionality. - - @since v1.0 - */ -@interface CDSoundSource : NSObject { - ALenum lastError; -@public - ALuint _sourceId; - ALuint _sourceIndex; - CDSoundEngine* _engine; - int _soundId; - float _preMuteGain; - BOOL enabled_; - BOOL mute_; -} -@property (readwrite, nonatomic) float pitch; -@property (readwrite, nonatomic) float gain; -@property (readwrite, nonatomic) float pan; -@property (readwrite, nonatomic) BOOL looping; -@property (readonly) BOOL isPlaying; -@property (readwrite, nonatomic) int soundId; -/** Returns the duration of the attached buffer in seconds or a negative value if the buffer is invalid */ -@property (readonly) float durationInSeconds; - -/** Stores the last error code that occurred. Check against AL_NO_ERROR */ -@property (readonly) ALenum lastError; -/** Do not init yourself, get an instance from the sourceForSound factory method on CDSoundEngine */ --(id)init:(ALuint) theSourceId sourceIndex:(int) index soundEngine:(CDSoundEngine*) engine; - -@end - -#pragma mark CDAudioInterruptTargetGroup - -/** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled. - Setting mute and enabled for the group propagates to all children. - Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings - if that is what you want to do.*/ -@interface CDAudioInterruptTargetGroup : NSObject { - BOOL mute_; - BOOL enabled_; - NSMutableArray *children_; -} --(void) addAudioInterruptTarget:(NSObject*) interruptibleTarget; -@end - -#pragma mark CDAsynchBufferLoader - -/** CDAsynchBufferLoader - TODO - */ -@interface CDAsynchBufferLoader : NSOperation { - NSArray *_loadRequests; - CDSoundEngine *_soundEngine; -} - --(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine; - -@end - -#pragma mark CDBufferLoadRequest - -/** CDBufferLoadRequest */ -@interface CDBufferLoadRequest: NSObject -{ - NSString *filePath; - int soundId; - //id loader; -} - -@property (readonly) NSString *filePath; -@property (readonly) int soundId; - -- (id)init:(int) theSoundId filePath:(NSString *) theFilePath; -@end - -/** Interpolation type */ -typedef enum { - kIT_Linear, //!Straight linear interpolation fade - kIT_SCurve, //!S curved interpolation - kIT_Exponential //!Exponential interpolation -} tCDInterpolationType; - -#pragma mark CDFloatInterpolator -@interface CDFloatInterpolator: NSObject -{ - float start; - float end; - float lastValue; - tCDInterpolationType interpolationType; -} -@property (readwrite, nonatomic) float start; -@property (readwrite, nonatomic) float end; -@property (readwrite, nonatomic) tCDInterpolationType interpolationType; - -/** Return a value between min and max based on t which represents fractional progress where 0 is the start - and 1 is the end */ --(float) interpolate:(float) t; --(id) init:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal; - -@end - -#pragma mark CDPropertyModifier - -/** Base class for classes that modify properties such as pitch, pan and gain */ -@interface CDPropertyModifier: NSObject -{ - CDFloatInterpolator *interpolator; - float startValue; - float endValue; - id target; - BOOL stopTargetWhenComplete; - -} -@property (readwrite, nonatomic) BOOL stopTargetWhenComplete; -@property (readwrite, nonatomic) float startValue; -@property (readwrite, nonatomic) float endValue; -@property (readwrite, nonatomic) tCDInterpolationType interpolationType; - --(id) init:(id) theTarget interpolationType:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal; -/** Set to a fractional value between 0 and 1 where 0 equals the start and 1 equals the end*/ --(void) modify:(float) t; - --(void) _setTargetProperty:(float) newVal; --(float) _getTargetProperty; --(void) _stopTarget; --(Class) _allowableType; - -@end - -#pragma mark CDSoundSourceFader - -/** Fader for CDSoundSource objects */ -@interface CDSoundSourceFader : CDPropertyModifier{} -@end - -#pragma mark CDSoundSourcePanner - -/** Panner for CDSoundSource objects */ -@interface CDSoundSourcePanner : CDPropertyModifier{} -@end - -#pragma mark CDSoundSourcePitchBender - -/** Pitch bender for CDSoundSource objects */ -@interface CDSoundSourcePitchBender : CDPropertyModifier{} -@end - -#pragma mark CDSoundEngineFader - -/** Fader for CDSoundEngine objects */ -@interface CDSoundEngineFader : CDPropertyModifier{} -@end - - - - diff --git a/Example/libs/CocosDenshion/CocosDenshion.m b/Example/libs/CocosDenshion/CocosDenshion.m deleted file mode 100644 index 3b252fe..0000000 --- a/Example/libs/CocosDenshion/CocosDenshion.m +++ /dev/null @@ -1,1570 +0,0 @@ -/* - Copyright (c) 2010 Steve Oldmeadow - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - $Id$ - */ - -#import "CocosDenshion.h" - -typedef ALvoid AL_APIENTRY (*alBufferDataStaticProcPtr) (const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq); -ALvoid alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq) -{ - static alBufferDataStaticProcPtr proc = NULL; - - if (proc == NULL) { - proc = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic"); - } - - if (proc) - proc(bid, format, data, size, freq); - - return; -} - -typedef ALvoid AL_APIENTRY (*alcMacOSXMixerOutputRateProcPtr) (const ALdouble value); -ALvoid alcMacOSXMixerOutputRateProc(const ALdouble value) -{ - static alcMacOSXMixerOutputRateProcPtr proc = NULL; - - if (proc == NULL) { - proc = (alcMacOSXMixerOutputRateProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alcMacOSXMixerOutputRate"); - } - - if (proc) - proc(value); - - return; -} - -@interface CDSoundEngine (PrivateMethods) --(BOOL) _initOpenAL; --(void) _testGetGain; --(void) _dumpSourceGroupsInfo; --(void) _getSourceIndexForSourceGroup; --(void) _freeSourceGroups; --(BOOL) _setUpSourceGroups:(int[]) definitions total:(int) total; -@end - -#pragma mark - -#pragma mark CDUtilities - -@implementation CDUtilities - -+(NSString*) fullPathFromRelativePath:(NSString*) relPath -{ - // do not convert an absolute path (starting with '/') - if(([relPath length] > 0) && ([relPath characterAtIndex:0] == '/')) - { - return relPath; - } - - NSMutableArray *imagePathComponents = [NSMutableArray arrayWithArray:[relPath pathComponents]]; - NSString *file = [imagePathComponents lastObject]; - - [imagePathComponents removeLastObject]; - NSString *imageDirectory = [NSString pathWithComponents:imagePathComponents]; - - NSString *fullpath = [[NSBundle mainBundle] pathForResource:file ofType:nil inDirectory:imageDirectory]; - if (fullpath == nil) - fullpath = relPath; - - return fullpath; -} - -@end - -#pragma mark - -#pragma mark CDSoundEngine - -@implementation CDSoundEngine - -static Float32 _mixerSampleRate; -static BOOL _mixerRateSet = NO; - -@synthesize lastErrorCode = lastErrorCode_; -@synthesize functioning = functioning_; -@synthesize asynchLoadProgress = asynchLoadProgress_; -@synthesize getGainWorks = getGainWorks_; -@synthesize sourceTotal = sourceTotal_; - -+ (void) setMixerSampleRate:(Float32) sampleRate { - _mixerRateSet = YES; - _mixerSampleRate = sampleRate; -} - -- (void) _testGetGain { - float testValue = 0.7f; - ALuint testSourceId = _sources[0].sourceId; - alSourcef(testSourceId, AL_GAIN, 0.0f);//Start from know value - alSourcef(testSourceId, AL_GAIN, testValue); - ALfloat gainVal; - alGetSourcef(testSourceId, AL_GAIN, &gainVal); - getGainWorks_ = (gainVal == testValue); - CDLOG(@"Denshion::CDSoundEngine - testing get gain for source %i",getGainWorks_); -} - -//Generate sources one at a time until we fail --(void) _generateSources { - - _sources = (sourceInfo*)malloc( sizeof(_sources[0]) * CD_SOURCE_LIMIT); - BOOL hasFailed = NO; - sourceTotal_ = 0; - alGetError();//Clear error - while (!hasFailed && sourceTotal_ < CD_SOURCE_LIMIT) { - CDLOG(@"Denshion::CDSoundEngine - try to generate source %i",sourceTotal_); - alGenSources(1, &(_sources[sourceTotal_].sourceId)); - if (alGetError() == AL_NO_ERROR) { - //Now try attaching source to null buffer - alSourcei(_sources[sourceTotal_].sourceId, AL_BUFFER, 0); - if (alGetError() == AL_NO_ERROR) { - _sources[sourceTotal_].usable = true; - sourceTotal_++; - } else { - hasFailed = YES; - } - } else { - _sources[sourceTotal_].usable = false; - hasFailed = YES; - } - } - //Mark the rest of the sources as not usable - for (int i=sourceTotal_; i < CD_SOURCE_LIMIT; i++) { - _sources[i].usable = false; - } - CDLOG(@"Denshion::CDSoundEngine - total sources %i",sourceTotal_); -} - --(void) _generateBuffers:(int) startIndex endIndex:(int) endIndex { - CDLOG(@"Denshion::CDSoundEngine - generate buffers %i to %i",startIndex,endIndex); - if (_buffers) { - alGetError(); - for (int i=startIndex; i <= endIndex; i++) { - alGenBuffers(1, &_buffers[i].bufferId); - _buffers[i].bufferData = NULL; - if (alGetError() == AL_NO_ERROR) { - _buffers[i].bufferState = CD_BS_EMPTY; - CDLOG(@"Denshion::CDSoundEngine - buffer created %i",_buffers[i].bufferId); - } else { - _buffers[i].bufferState = CD_BS_FAILED; - CDLOG(@"Denshion::CDSoundEngine - buffer creation failed %i",i); - } - } - } -} - -/** - * Internal method called during init - */ -- (BOOL) _initOpenAL -{ - //ALenum error; - context = NULL; - ALCdevice *newDevice = NULL; - - //Set the mixer rate for the audio mixer - if (!_mixerRateSet) { - _mixerSampleRate = CD_SAMPLE_RATE_DEFAULT; - } - alcMacOSXMixerOutputRateProc(_mixerSampleRate); - CDLOG(@"Denshion::CDSoundEngine - mixer output rate set to %0.2f",_mixerSampleRate); - - // Create a new OpenAL Device - // Pass NULL to specify the system's default output device - newDevice = alcOpenDevice(NULL); - if (newDevice != NULL) - { - // Create a new OpenAL Context - // The new context will render to the OpenAL Device just created - context = alcCreateContext(newDevice, 0); - if (context != NULL) - { - // Make the new context the Current OpenAL Context - alcMakeContextCurrent(context); - - // Create some OpenAL Buffer Objects - [self _generateBuffers:0 endIndex:bufferTotal-1]; - - // Create some OpenAL Source Objects - [self _generateSources]; - - } - } else { - return FALSE;//No device - } - alGetError();//Clear error - return TRUE; -} - -- (void) dealloc { - - ALCcontext *currentContext = NULL; - ALCdevice *device = NULL; - - [self stopAllSounds]; - - CDLOG(@"Denshion::CDSoundEngine - Deallocing sound engine."); - [self _freeSourceGroups]; - - // Delete the Sources - CDLOG(@"Denshion::CDSoundEngine - deleting sources."); - for (int i=0; i < sourceTotal_; i++) { - alSourcei(_sources[i].sourceId, AL_BUFFER, 0);//Detach from current buffer - alDeleteSources(1, &(_sources[i].sourceId)); - if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { - CDLOG(@"Denshion::CDSoundEngine - Error deleting source! %x\n", lastErrorCode_); - } - } - - // Delete the Buffers - CDLOG(@"Denshion::CDSoundEngine - deleting buffers."); - for (int i=0; i < bufferTotal; i++) { - alDeleteBuffers(1, &_buffers[i].bufferId); -#ifdef CD_USE_STATIC_BUFFERS - if (_buffers[i].bufferData) { - free(_buffers[i].bufferData); - } -#endif - } - CDLOG(@"Denshion::CDSoundEngine - free buffers."); - free(_buffers); - currentContext = alcGetCurrentContext(); - //Get device for active context - device = alcGetContextsDevice(currentContext); - //Release context - CDLOG(@"Denshion::CDSoundEngine - destroy context."); - alcDestroyContext(currentContext); - //Close device - CDLOG(@"Denshion::CDSoundEngine - close device."); - alcCloseDevice(device); - CDLOG(@"Denshion::CDSoundEngine - free sources."); - free(_sources); - - [super dealloc]; -} - --(int) sourceGroupTotal { - return _sourceGroupTotal; -} - --(void) _freeSourceGroups -{ - CDLOG(@"Denshion::CDSoundEngine freeing source groups"); - if(_sourceGroups) { - for (int i=0; i < _sourceGroupTotal; i++) { - if (_sourceGroups[i].sourceStatuses) { - free(_sourceGroups[i].sourceStatuses); - CDLOG(@"Denshion::CDSoundEngine freed source statuses %i",i); - } - } - free(_sourceGroups); - } -} - --(BOOL) _redefineSourceGroups:(int[]) definitions total:(int) total -{ - if (_sourceGroups) { - //Stop all sounds - [self stopAllSounds]; - //Need to free source groups - [self _freeSourceGroups]; - } - return [self _setUpSourceGroups:definitions total:total]; -} - --(BOOL) _setUpSourceGroups:(int[]) definitions total:(int) total -{ - _sourceGroups = (sourceGroup *)malloc( sizeof(_sourceGroups[0]) * total); - if(!_sourceGroups) { - CDLOG(@"Denshion::CDSoundEngine - source groups memory allocation failed"); - return NO; - } - - _sourceGroupTotal = total; - int sourceCount = 0; - for (int i=0; i < _sourceGroupTotal; i++) { - - _sourceGroups[i].startIndex = 0; - _sourceGroups[i].currentIndex = _sourceGroups[i].startIndex; - _sourceGroups[i].enabled = false; - _sourceGroups[i].nonInterruptible = false; - _sourceGroups[i].totalSources = definitions[i]; - _sourceGroups[i].sourceStatuses = malloc(sizeof(_sourceGroups[i].sourceStatuses[0]) * _sourceGroups[i].totalSources); - if (_sourceGroups[i].sourceStatuses) { - for (int j=0; j < _sourceGroups[i].totalSources; j++) { - //First bit is used to indicate whether source is locked, index is shifted back 1 bit - _sourceGroups[i].sourceStatuses[j] = (sourceCount + j) << 1; - } - } - sourceCount += definitions[i]; - CDLOG(@"Denshion::CDSoundEngine - source def %i %i %i",i,_sourceGroups[i].startIndex, _sourceGroups[i].currentIndex); - } - [self _dumpSourceGroupsInfo]; - return YES; -} - --(void) defineSourceGroups:(int[]) sourceGroupDefinitions total:(int) total { - [self _redefineSourceGroups:sourceGroupDefinitions total:total]; -} - --(void) defineSourceGroups:(NSArray*) sourceGroupDefinitions { - CDLOG(@"Denshion::CDSoundEngine - source groups defined by NSArray."); - int totalDefs = [sourceGroupDefinitions count]; - int* defs = (int *)malloc( sizeof(int) * totalDefs); - int currentIndex = 0; - for (id currentDef in sourceGroupDefinitions) { - if ([currentDef isKindOfClass:[NSNumber class]]) { - defs[currentIndex] = [(NSNumber*)currentDef integerValue]; - CDLOG(@"Denshion::CDSoundEngine - found definition %i.",defs[currentIndex]); - } else { - CDLOG(@"Denshion::CDSoundEngine - warning, did not understand source definition."); - defs[currentIndex] = 0; - } - currentIndex++; - } - [self _redefineSourceGroups:defs total:totalDefs]; - free(defs); -} - -- (id)init -{ - if ((self = [super init])) { - - asynchLoadProgress_ = 0.0f; - - bufferTotal = CD_BUFFERS_START; - _buffers = (bufferInfo *)malloc( sizeof(_buffers[0]) * bufferTotal); - - // Initialize our OpenAL environment - if ([self _initOpenAL]) { - //Set up the default source group - a single group that contains all the sources - int sourceDefs[1]; - sourceDefs[0] = self.sourceTotal; - [self _setUpSourceGroups:sourceDefs total:1]; - - functioning_ = YES; - //Synchronize premute gain - _preMuteGain = self.masterGain; - mute_ = NO; - enabled_ = YES; - //Test whether get gain works for sources - [self _testGetGain]; - } else { - //Something went wrong with OpenAL - functioning_ = NO; - } - } - - return self; -} - -/** - * Delete the buffer identified by soundId - * @return true if buffer deleted successfully, otherwise false - */ -- (BOOL) unloadBuffer:(int) soundId -{ - //Ensure soundId is within array bounds otherwise memory corruption will occur - if (soundId < 0 || soundId >= bufferTotal) { - CDLOG(@"Denshion::CDSoundEngine - soundId is outside array bounds, maybe you need to increase CD_MAX_BUFFERS"); - return FALSE; - } - - //Before a buffer can be deleted any sources that are attached to it must be stopped - for (int i=0; i < sourceTotal_; i++) { - //Note: tried getting the AL_BUFFER attribute of the source instead but doesn't - //appear to work on a device - just returned zero. - if (_buffers[soundId].bufferId == _sources[i].attachedBufferId) { - - CDLOG(@"Denshion::CDSoundEngine - Found attached source %i %i %i",i,_buffers[soundId].bufferId,_sources[i].sourceId); -#ifdef CD_USE_STATIC_BUFFERS - //When using static buffers a crash may occur if a source is playing with a buffer that is about - //to be deleted even though we stop the source and successfully delete the buffer. Crash is confirmed - //on 2.2.1 and 3.1.2, however, it will only occur if a source is used rapidly after having its prior - //data deleted. To avoid any possibility of the crash we wait for the source to finish playing. - ALint state; - - alGetSourcei(_sources[i].sourceId, AL_SOURCE_STATE, &state); - - if (state == AL_PLAYING) { - CDLOG(@"Denshion::CDSoundEngine - waiting for source to complete playing before removing buffer data"); - alSourcei(_sources[i].sourceId, AL_LOOPING, FALSE);//Turn off looping otherwise loops will never end - while (state == AL_PLAYING) { - alGetSourcei(_sources[i].sourceId, AL_SOURCE_STATE, &state); - usleep(10000); - } - } -#endif - //Stop source and detach - alSourceStop(_sources[i].sourceId); - if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { - CDLOG(@"Denshion::CDSoundEngine - error stopping source: %x\n", lastErrorCode_); - } - - alSourcei(_sources[i].sourceId, AL_BUFFER, 0);//Attach to "NULL" buffer to detach - if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { - CDLOG(@"Denshion::CDSoundEngine - error detaching buffer: %x\n", lastErrorCode_); - } else { - //Record that source is now attached to nothing - _sources[i].attachedBufferId = 0; - } - } - } - - alDeleteBuffers(1, &_buffers[soundId].bufferId); - if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { - CDLOG(@"Denshion::CDSoundEngine - error deleting buffer: %x\n", lastErrorCode_); - _buffers[soundId].bufferState = CD_BS_FAILED; - return FALSE; - } else { -#ifdef CD_USE_STATIC_BUFFERS - //Free previous data, if alDeleteBuffer has returned without error then no - if (_buffers[soundId].bufferData) { - CDLOG(@"Denshion::CDSoundEngine - freeing static data for soundId %i @ %i",soundId,_buffers[soundId].bufferData); - free(_buffers[soundId].bufferData);//Free the old data - _buffers[soundId].bufferData = NULL; - } -#endif - } - - alGenBuffers(1, &_buffers[soundId].bufferId); - if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { - CDLOG(@"Denshion::CDSoundEngine - error regenerating buffer: %x\n", lastErrorCode_); - _buffers[soundId].bufferState = CD_BS_FAILED; - return FALSE; - } else { - //We now have an empty buffer - _buffers[soundId].bufferState = CD_BS_EMPTY; - CDLOG(@"Denshion::CDSoundEngine - buffer %i successfully unloaded\n",soundId); - return TRUE; - } -} - -/** - * Load buffers asynchronously - * Check asynchLoadProgress for progress. asynchLoadProgress represents fraction of completion. When it equals 1.0 loading - * is complete. NB: asynchLoadProgress is simply based on the number of load requests, it does not take into account - * file sizes. - * @param An array of CDBufferLoadRequest objects - */ -- (void) loadBuffersAsynchronously:(NSArray *) loadRequests { - @synchronized(self) { - asynchLoadProgress_ = 0.0f; - CDAsynchBufferLoader *loaderOp = [[[CDAsynchBufferLoader alloc] init:loadRequests soundEngine:self] autorelease]; - NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease]; - [opQ addOperation:loaderOp]; - } -} - --(BOOL) _resizeBuffers:(int) increment { - - void * tmpBufferInfos = realloc( _buffers, sizeof(_buffers[0]) * (bufferTotal + increment) ); - - if(!tmpBufferInfos) { - free(tmpBufferInfos); - return NO; - } else { - _buffers = tmpBufferInfos; - int oldBufferTotal = bufferTotal; - bufferTotal = bufferTotal + increment; - [self _generateBuffers:oldBufferTotal endIndex:bufferTotal-1]; - return YES; - } -} - --(BOOL) loadBufferFromData:(int) soundId soundData:(ALvoid*) soundData format:(ALenum) format size:(ALsizei) size freq:(ALsizei) freq { - - CDLOG(@"Denshion::CDSoundEngine - Loading buffer %i ", soundId); - - if (!functioning_) { - //OpenAL initialisation has previously failed - CDLOG(@"Denshion::CDSoundEngine - Loading buffer failed because sound engine state != functioning"); - return FALSE; - } - - //Ensure soundId is within array bounds otherwise memory corruption will occur - if (soundId < 0) { - CDLOG(@"Denshion::CDSoundEngine - soundId is negative"); - return FALSE; - } - - if (soundId >= bufferTotal) { - //Need to resize the buffers - int requiredIncrement = CD_BUFFERS_INCREMENT; - while (bufferTotal + requiredIncrement < soundId) { - requiredIncrement += CD_BUFFERS_INCREMENT; - } - CDLOG(@"Denshion::CDSoundEngine - attempting to resize buffers by %i for sound %i",requiredIncrement,soundId); - if (![self _resizeBuffers:requiredIncrement]) { - CDLOG(@"Denshion::CDSoundEngine - buffer resize failed"); - return FALSE; - } - } - - if (soundData) - { - if (_buffers[soundId].bufferState != CD_BS_EMPTY) { - CDLOG(@"Denshion::CDSoundEngine - non empty buffer, regenerating"); - if (![self unloadBuffer:soundId]) { - //Deletion of buffer failed, delete buffer routine has set buffer state and lastErrorCode - return NO; - } - } - -#ifdef CD_DEBUG - //Check that sample rate matches mixer rate and warn if they do not - if (freq != (int)_mixerSampleRate) { - CDLOG(@"Denshion::CDSoundEngine - WARNING sample rate does not match mixer sample rate performance will not be optimal."); - } -#endif - -#ifdef CD_USE_STATIC_BUFFERS - alBufferDataStaticProc(_buffers[soundId].bufferId, format, soundData, size, freq); - _buffers[soundId].bufferData = data;//Save the pointer to the new data -#else - alBufferData(_buffers[soundId].bufferId, format, soundData, size, freq); -#endif - if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { - CDLOG(@"Denshion::CDSoundEngine - error attaching audio to buffer: %x", lastErrorCode_); - _buffers[soundId].bufferState = CD_BS_FAILED; - return FALSE; - } - } else { - CDLOG(@"Denshion::CDSoundEngine Buffer data is null!"); - _buffers[soundId].bufferState = CD_BS_FAILED; - return FALSE; - } - - _buffers[soundId].format = format; - _buffers[soundId].sizeInBytes = size; - _buffers[soundId].frequencyInHertz = freq; - _buffers[soundId].bufferState = CD_BS_LOADED; - CDLOG(@"Denshion::CDSoundEngine - =============== Buffer Loaded ==============="); - return TRUE; - -} - -/** - * Load sound data for later play back. - * @return TRUE if buffer loaded okay for play back otherwise false - */ -- (BOOL) loadBuffer:(int) soundId filePath:(NSString*) filePath -{ - - ALvoid* data; - ALenum format; - ALsizei size; - ALsizei freq; - - CDLOG(@"Denshion::CDSoundEngine - Loading openAL buffer %i %@", soundId, filePath); - - CFURLRef fileURL = nil; - NSString *path = [CDUtilities fullPathFromRelativePath:filePath]; - if (path) { - fileURL = (CFURLRef)[[NSURL fileURLWithPath:path] retain]; - } - - if (fileURL) - { - data = CDGetOpenALAudioData(fileURL, &size, &format, &freq); - CFRelease(fileURL); - BOOL result = [self loadBufferFromData:soundId soundData:data format:format size:size freq:freq]; -#ifndef CD_USE_STATIC_BUFFERS - free(data);//Data can be freed here because alBufferData performs a memcpy -#endif - return result; - } else { - CDLOG(@"Denshion::CDSoundEngine Could not find file!\n"); - //Don't change buffer state here as it will be the same as before method was called - return FALSE; - } -} - --(BOOL) validateBufferId:(int) soundId { - if (soundId < 0 || soundId >= bufferTotal) { - CDLOG(@"Denshion::CDSoundEngine - validateBufferId buffer outside range %i",soundId); - return NO; - } else if (_buffers[soundId].bufferState != CD_BS_LOADED) { - CDLOG(@"Denshion::CDSoundEngine - validateBufferId invalide buffer state %i",soundId); - return NO; - } else { - return YES; - } -} - --(float) bufferDurationInSeconds:(int) soundId { - if ([self validateBufferId:soundId]) { - float factor = 0.0f; - switch (_buffers[soundId].format) { - case AL_FORMAT_MONO8: - factor = 1.0f; - break; - case AL_FORMAT_MONO16: - factor = 0.5f; - break; - case AL_FORMAT_STEREO8: - factor = 0.5f; - break; - case AL_FORMAT_STEREO16: - factor = 0.25f; - break; - } - return (float)_buffers[soundId].sizeInBytes/(float)_buffers[soundId].frequencyInHertz * factor; - } else { - return -1.0f; - } -} - --(ALsizei) bufferSizeInBytes:(int) soundId { - if ([self validateBufferId:soundId]) { - return _buffers[soundId].sizeInBytes; - } else { - return -1.0f; - } -} - --(ALsizei) bufferFrequencyInHertz:(int) soundId { - if ([self validateBufferId:soundId]) { - return _buffers[soundId].frequencyInHertz; - } else { - return -1.0f; - } -} - -- (ALfloat) masterGain { - if (mute_) { - //When mute the real gain will always be 0 therefore return the preMuteGain value - return _preMuteGain; - } else { - ALfloat gain; - alGetListenerf(AL_GAIN, &gain); - return gain; - } -} - -/** - * Overall gain setting multiplier. e.g 0.5 is half the gain. - */ -- (void) setMasterGain:(ALfloat) newGainValue { - if (mute_) { - _preMuteGain = newGainValue; - } else { - alListenerf(AL_GAIN, newGainValue); - } -} - -#pragma mark CDSoundEngine AudioInterrupt protocol -- (BOOL) mute { - return mute_; -} - -/** - * Setting mute silences all sounds but playing sounds continue to advance playback - */ -- (void) setMute:(BOOL) newMuteValue { - - if (newMuteValue == mute_) { - return; - } - - mute_ = newMuteValue; - if (mute_) { - //Remember what the gain was - _preMuteGain = self.masterGain; - //Set gain to 0 - do not use the property as this will adjust preMuteGain when muted - alListenerf(AL_GAIN, 0.0f); - } else { - //Restore gain to what it was before being muted - self.masterGain = _preMuteGain; - } -} - -- (BOOL) enabled { - return enabled_; -} - -- (void) setEnabled:(BOOL)enabledValue -{ - if (enabled_ == enabledValue) { - return; - } - enabled_ = enabledValue; - if (enabled_ == NO) { - [self stopAllSounds]; - } -} - --(void) _lockSource:(int) sourceIndex lock:(BOOL) lock { - BOOL found = NO; - for (int i=0; i < _sourceGroupTotal && !found; i++) { - if (_sourceGroups[i].sourceStatuses) { - for (int j=0; j < _sourceGroups[i].totalSources && !found; j++) { - //First bit is used to indicate whether source is locked, index is shifted back 1 bit - if((_sourceGroups[i].sourceStatuses[j] >> 1)==sourceIndex) { - if (lock) { - //Set first bit to lock this source - _sourceGroups[i].sourceStatuses[j] |= 1; - } else { - //Unset first bit to unlock this source - _sourceGroups[i].sourceStatuses[j] &= ~1; - } - found = YES; - } - } - } - } -} - --(int) _getSourceIndexForSourceGroup:(int)sourceGroupId -{ - int sourceIndex = -1;//Using -1 to indicate no source found - BOOL complete = NO; - ALint sourceState = 0; - sourceGroup *thisSourceGroup = &_sourceGroups[sourceGroupId]; - thisSourceGroup->currentIndex = thisSourceGroup->startIndex; - while (!complete) { - //Iterate over sources looking for one that is not locked, first bit indicates if source is locked - if ((thisSourceGroup->sourceStatuses[thisSourceGroup->currentIndex] & 1) == 0) { - //This source is not locked - sourceIndex = thisSourceGroup->sourceStatuses[thisSourceGroup->currentIndex] >> 1;//shift back to get the index - if (thisSourceGroup->nonInterruptible) { - //Check if this source is playing, if so it can't be interrupted - alGetSourcei(_sources[sourceIndex].sourceId, AL_SOURCE_STATE, &sourceState); - if (sourceState != AL_PLAYING) { - //complete = YES; - //Set start index so next search starts at the next position - thisSourceGroup->startIndex = thisSourceGroup->currentIndex + 1; - break; - } else { - sourceIndex = -1;//The source index was no good because the source was playing - } - } else { - //complete = YES; - //Set start index so next search starts at the next position - thisSourceGroup->startIndex = thisSourceGroup->currentIndex + 1; - break; - } - } - thisSourceGroup->currentIndex++; - if (thisSourceGroup->currentIndex >= thisSourceGroup->totalSources) { - //Reset to the beginning - thisSourceGroup->currentIndex = 0; - } - if (thisSourceGroup->currentIndex == thisSourceGroup->startIndex) { - //We have looped around and got back to the start - complete = YES; - } - } - - //Reset start index to beginning if beyond bounds - if (thisSourceGroup->startIndex >= thisSourceGroup->totalSources) { - thisSourceGroup->startIndex = 0; - } - - if (sourceIndex >= 0) { - return sourceIndex; - } else { - return CD_NO_SOURCE; - } - -} - -/** - * Play a sound. - * @param soundId the id of the sound to play (buffer id). - * @param SourceGroupId the source group that will be used to play the sound. - * @param pitch pitch multiplier. e.g 1.0 is unaltered, 0.5 is 1 octave lower. - * @param pan stereo position. -1 is fully left, 0 is centre and 1 is fully right. - * @param gain gain multiplier. e.g. 1.0 is unaltered, 0.5 is half the gain - * @param loop should the sound be looped or one shot. - * @return the id of the source being used to play the sound or CD_MUTE if the sound engine is muted or non functioning - * or CD_NO_SOURCE if a problem occurs setting up the source - * - */ -- (ALuint)playSound:(int) soundId sourceGroupId:(int)sourceGroupId pitch:(float) pitch pan:(float) pan gain:(float) gain loop:(BOOL) loop { - -#ifdef CD_DEBUG - //Sanity check parameters - only in DEBUG - NSAssert(soundId >= 0, @"soundId can not be negative"); - NSAssert(soundId < bufferTotal, @"soundId exceeds limit"); - NSAssert(sourceGroupId >= 0, @"sourceGroupId can not be negative"); - NSAssert(sourceGroupId < _sourceGroupTotal, @"sourceGroupId exceeds limit"); - NSAssert(pitch > 0, @"pitch must be greater than zero"); - NSAssert(pan >= -1 && pan <= 1, @"pan must be between -1 and 1"); - NSAssert(gain >= 0, @"gain can not be negative"); -#endif - //If mute or initialisation has failed or buffer is not loaded then do nothing - if (!enabled_ || !functioning_ || _buffers[soundId].bufferState != CD_BS_LOADED || _sourceGroups[sourceGroupId].enabled) { -#ifdef CD_DEBUG - if (!functioning_) { - CDLOG(@"Denshion::CDSoundEngine - sound playback aborted because sound engine is not functioning"); - } else if (_buffers[soundId].bufferState != CD_BS_LOADED) { - CDLOG(@"Denshion::CDSoundEngine - sound playback aborted because buffer %i is not loaded", soundId); - } -#endif - return CD_MUTE; - } - - int sourceIndex = [self _getSourceIndexForSourceGroup:sourceGroupId]; - - if (sourceIndex != CD_NO_SOURCE) { - ALint state; - ALuint source = _sources[sourceIndex].sourceId; - ALuint buffer = _buffers[soundId].bufferId; - alGetError();//Clear the error code - alGetSourcei(source, AL_SOURCE_STATE, &state); - if (state == AL_PLAYING) { - alSourceStop(source); - } - alSourcei(source, AL_BUFFER, buffer);//Attach to sound - alSourcef(source, AL_PITCH, pitch);//Set pitch - alSourcei(source, AL_LOOPING, loop);//Set looping - alSourcef(source, AL_GAIN, gain);//Set gain/volume - float sourcePosAL[] = {pan, 0.0f, 0.0f};//Set position - just using left and right panning - alSourcefv(source, AL_POSITION, sourcePosAL); - alGetError();//Clear the error code - alSourcePlay(source); - if((lastErrorCode_ = alGetError()) == AL_NO_ERROR) { - //Everything was okay - _sources[sourceIndex].attachedBufferId = buffer; - return source; - } else { - if (alcGetCurrentContext() == NULL) { - CDLOG(@"Denshion::CDSoundEngine - posting bad OpenAL context message"); - [[NSNotificationCenter defaultCenter] postNotificationName:CD_MSG_BAD_AL_CONTEXT object:nil]; - } - return CD_NO_SOURCE; - } - } else { - return CD_NO_SOURCE; - } -} - --(BOOL) _soundSourceAttachToBuffer:(CDSoundSource*) soundSource soundId:(int) soundId { - //Attach the source to the buffer - ALint state; - ALuint source = soundSource->_sourceId; - ALuint buffer = _buffers[soundId].bufferId; - alGetSourcei(source, AL_SOURCE_STATE, &state); - if (state == AL_PLAYING) { - alSourceStop(source); - } - alGetError();//Clear the error code - alSourcei(source, AL_BUFFER, buffer);//Attach to sound data - if((lastErrorCode_ = alGetError()) == AL_NO_ERROR) { - _sources[soundSource->_sourceIndex].attachedBufferId = buffer; - //_sourceBufferAttachments[soundSource->_sourceIndex] = buffer;//Keep track of which - soundSource->_soundId = soundId; - return YES; - } else { - return NO; - } -} - -/** - * Get a sound source for the specified sound in the specified source group - */ --(CDSoundSource *) soundSourceForSound:(int) soundId sourceGroupId:(int) sourceGroupId -{ - if (!functioning_) { - return nil; - } - //Check if a source is available - int sourceIndex = [self _getSourceIndexForSourceGroup:sourceGroupId]; - if (sourceIndex != CD_NO_SOURCE) { - CDSoundSource *result = [[CDSoundSource alloc] init:_sources[sourceIndex].sourceId sourceIndex:sourceIndex soundEngine:self]; - [self _lockSource:sourceIndex lock:YES]; - //Try to attach to the buffer - if ([self _soundSourceAttachToBuffer:result soundId:soundId]) { - //Set to a known state - result.pitch = 1.0f; - result.pan = 0.0f; - result.gain = 1.0f; - result.looping = NO; - return [result autorelease]; - } else { - //Release the sound source we just created, this will also unlock the source - [result release]; - return nil; - } - } else { - //No available source within that source group - return nil; - } -} - --(void) _soundSourcePreRelease:(CDSoundSource *) soundSource { - CDLOG(@"Denshion::CDSoundEngine _soundSourcePreRelease %i",soundSource->_sourceIndex); - //Unlock the sound source's source - [self _lockSource:soundSource->_sourceIndex lock:NO]; -} - -/** - * Stop all sounds playing within a source group - */ -- (void) stopSourceGroup:(int) sourceGroupId { - - if (!functioning_ || sourceGroupId >= _sourceGroupTotal) { - return; - } - int sourceCount = _sourceGroups[sourceGroupId].totalSources; - for (int i=0; i < sourceCount; i++) { - int sourceIndex = _sourceGroups[sourceGroupId].sourceStatuses[i] >> 1; - alSourceStop(_sources[sourceIndex].sourceId); - } - alGetError();//Clear error in case we stopped any sounds that couldn't be stopped -} - -/** - * Stop a sound playing. - * @param sourceId an OpenAL source identifier i.e. the return value of playSound - */ -- (void)stopSound:(ALuint) sourceId { - if (!functioning_) { - return; - } - alSourceStop(sourceId); - alGetError();//Clear error in case we stopped any sounds that couldn't be stopped -} - -- (void) stopAllSounds { - for (int i=0; i < sourceTotal_; i++) { - alSourceStop(_sources[i].sourceId); - } - alGetError();//Clear error in case we stopped any sounds that couldn't be stopped -} - -/** - * Set a source group as non interruptible. Default is that source groups are interruptible. - * Non interruptible means that if a request to play a sound is made for a source group and there are - * no free sources available then the play request will be ignored and CD_NO_SOURCE will be returned. - */ -- (void) setSourceGroupNonInterruptible:(int) sourceGroupId isNonInterruptible:(BOOL) isNonInterruptible { - if (isNonInterruptible) { - _sourceGroups[sourceGroupId].nonInterruptible = true; - } else { - _sourceGroups[sourceGroupId].nonInterruptible = false; - } -} - -/** - * Set the mute property for a source group. If mute is turned on any sounds in that source group - * will be stopped and further sounds in that source group will play. However, turning mute off - * will not restart any sounds that were playing when mute was turned on. Also the mute setting - * for the sound engine must be taken into account. If the sound engine is mute no sounds will play - * no matter what the source group mute setting is. - */ -- (void) setSourceGroupEnabled:(int) sourceGroupId enabled:(BOOL) enabled { - if (enabled) { - _sourceGroups[sourceGroupId].enabled = true; - [self stopSourceGroup:sourceGroupId]; - } else { - _sourceGroups[sourceGroupId].enabled = false; - } -} - -/** - * Return the mute property for the source group identified by sourceGroupId - */ -- (BOOL) sourceGroupEnabled:(int) sourceGroupId { - return _sourceGroups[sourceGroupId].enabled; -} - --(ALCcontext *) openALContext { - return context; -} - -- (void) _dumpSourceGroupsInfo { -#ifdef CD_DEBUG - CDLOG(@"-------------- source Group Info --------------"); - for (int i=0; i < _sourceGroupTotal; i++) { - CDLOG(@"Group: %i start:%i total:%i",i,_sourceGroups[i].startIndex, _sourceGroups[i].totalSources); - CDLOG(@"----- mute:%i nonInterruptible:%i",_sourceGroups[i].enabled, _sourceGroups[i].nonInterruptible); - CDLOG(@"----- Source statuses ----"); - for (int j=0; j < _sourceGroups[i].totalSources; j++) { - CDLOG(@"Source status:%i index=%i locked=%i",j,_sourceGroups[i].sourceStatuses[j] >> 1, _sourceGroups[i].sourceStatuses[j] & 1); - } - } -#endif -} - -@end - -/////////////////////////////////////////////////////////////////////////////////////// -@implementation CDSoundSource - -@synthesize lastError; - -//Macro for handling the al error code -#define CDSOUNDSOURCE_UPDATE_LAST_ERROR (lastError = alGetError()) -#define CDSOUNDSOURCE_ERROR_HANDLER ( CDSOUNDSOURCE_UPDATE_LAST_ERROR == AL_NO_ERROR) - --(id)init:(ALuint) theSourceId sourceIndex:(int) index soundEngine:(CDSoundEngine*) engine { - if ((self = [super init])) { - _sourceId = theSourceId; - _engine = engine; - _sourceIndex = index; - enabled_ = YES; - mute_ = NO; - _preMuteGain = self.gain; - } - return self; -} - --(void) dealloc -{ - CDLOG(@"Denshion::CDSoundSource deallocated %i",self->_sourceIndex); - - //Notify sound engine we are about to release - [_engine _soundSourcePreRelease:self]; - [super dealloc]; -} - -- (void) setPitch:(float) newPitchValue { - alSourcef(_sourceId, AL_PITCH, newPitchValue); - CDSOUNDSOURCE_UPDATE_LAST_ERROR; -} - -- (void) setGain:(float) newGainValue { - if (!mute_) { - alSourcef(_sourceId, AL_GAIN, newGainValue); - } else { - _preMuteGain = newGainValue; - } - CDSOUNDSOURCE_UPDATE_LAST_ERROR; -} - -- (void) setPan:(float) newPanValue { - float sourcePosAL[] = {newPanValue, 0.0f, 0.0f};//Set position - just using left and right panning - alSourcefv(_sourceId, AL_POSITION, sourcePosAL); - CDSOUNDSOURCE_UPDATE_LAST_ERROR; - -} - -- (void) setLooping:(BOOL) newLoopingValue { - alSourcei(_sourceId, AL_LOOPING, newLoopingValue); - CDSOUNDSOURCE_UPDATE_LAST_ERROR; - -} - -- (BOOL) isPlaying { - ALint state; - alGetSourcei(_sourceId, AL_SOURCE_STATE, &state); - CDSOUNDSOURCE_UPDATE_LAST_ERROR; - return (state == AL_PLAYING); -} - -- (float) pitch { - ALfloat pitchVal; - alGetSourcef(_sourceId, AL_PITCH, &pitchVal); - CDSOUNDSOURCE_UPDATE_LAST_ERROR; - return pitchVal; -} - -- (float) pan { - ALfloat sourcePosAL[] = {0.0f,0.0f,0.0f}; - alGetSourcefv(_sourceId, AL_POSITION, sourcePosAL); - CDSOUNDSOURCE_UPDATE_LAST_ERROR; - return sourcePosAL[0]; -} - -- (float) gain { - if (!mute_) { - ALfloat val; - alGetSourcef(_sourceId, AL_GAIN, &val); - CDSOUNDSOURCE_UPDATE_LAST_ERROR; - return val; - } else { - return _preMuteGain; - } -} - -- (BOOL) looping { - ALfloat val; - alGetSourcef(_sourceId, AL_LOOPING, &val); - CDSOUNDSOURCE_UPDATE_LAST_ERROR; - return val; -} - --(BOOL) stop { - alSourceStop(_sourceId); - return CDSOUNDSOURCE_ERROR_HANDLER; -} - --(BOOL) play { - if (enabled_) { - alSourcePlay(_sourceId); - CDSOUNDSOURCE_UPDATE_LAST_ERROR; - if (lastError != AL_NO_ERROR) { - if (alcGetCurrentContext() == NULL) { - CDLOG(@"Denshion::CDSoundSource - posting bad OpenAL context message"); - [[NSNotificationCenter defaultCenter] postNotificationName:CD_MSG_BAD_AL_CONTEXT object:nil]; - } - return NO; - } else { - return YES; - } - } else { - return NO; - } -} - --(BOOL) pause { - alSourcePause(_sourceId); - return CDSOUNDSOURCE_ERROR_HANDLER; -} - --(BOOL) rewind { - alSourceRewind(_sourceId); - return CDSOUNDSOURCE_ERROR_HANDLER; -} - --(void) setSoundId:(int) soundId { - [_engine _soundSourceAttachToBuffer:self soundId:soundId]; -} - --(int) soundId { - return _soundId; -} - --(float) durationInSeconds { - return [_engine bufferDurationInSeconds:_soundId]; -} - -#pragma mark CDSoundSource AudioInterrupt protocol -- (BOOL) mute { - return mute_; -} - -/** - * Setting mute silences all sounds but playing sounds continue to advance playback - */ -- (void) setMute:(BOOL) newMuteValue { - - if (newMuteValue == mute_) { - return; - } - - if (newMuteValue) { - //Remember what the gain was - _preMuteGain = self.gain; - self.gain = 0.0f; - mute_ = newMuteValue;//Make sure this is done after setting the gain property as the setter behaves differently depending on mute value - } else { - //Restore gain to what it was before being muted - mute_ = newMuteValue; - self.gain = _preMuteGain; - } -} - -- (BOOL) enabled { - return enabled_; -} - -- (void) setEnabled:(BOOL)enabledValue -{ - if (enabled_ == enabledValue) { - return; - } - enabled_ = enabledValue; - if (enabled_ == NO) { - [self stop]; - } -} - -@end - -//////////////////////////////////////////////////////////////////////////// -#pragma mark - -#pragma mark CDAudioInterruptTargetGroup - -@implementation CDAudioInterruptTargetGroup - --(id) init { - if ((self = [super init])) { - children_ = [[NSMutableArray alloc] initWithCapacity:32]; - enabled_ = YES; - mute_ = NO; - } - return self; -} - --(void) addAudioInterruptTarget:(NSObject*) interruptibleTarget { - //Synchronize child with group settings; - [interruptibleTarget setMute:mute_]; - [interruptibleTarget setEnabled:enabled_]; - [children_ addObject:interruptibleTarget]; -} - --(void) removeAudioInterruptTarget:(NSObject*) interruptibleTarget { - [children_ removeObjectIdenticalTo:interruptibleTarget]; -} - -- (BOOL) mute { - return mute_; -} - -/** - * Setting mute silences all sounds but playing sounds continue to advance playback - */ -- (void) setMute:(BOOL) newMuteValue { - - if (newMuteValue == mute_) { - return; - } - - for (NSObject* target in children_) { - [target setMute:newMuteValue]; - } -} - -- (BOOL) enabled { - return enabled_; -} - -- (void) setEnabled:(BOOL)enabledValue -{ - if (enabledValue == enabled_) { - return; - } - - for (NSObject* target in children_) { - [target setEnabled:enabledValue]; - } -} - -@end - - - -//////////////////////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CDAsynchBufferLoader - -@implementation CDAsynchBufferLoader - --(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine { - if ((self = [super init])) { - _loadRequests = loadRequests; - [_loadRequests retain]; - _soundEngine = theSoundEngine; - [_soundEngine retain]; - } - return self; -} - --(void) main { - CDLOG(@"Denshion::CDAsynchBufferLoader - loading buffers"); - [super main]; - _soundEngine.asynchLoadProgress = 0.0f; - - if ([_loadRequests count] > 0) { - float increment = 1.0f / [_loadRequests count]; - //Iterate over load request and load - for (CDBufferLoadRequest *loadRequest in _loadRequests) { - [_soundEngine loadBuffer:loadRequest.soundId filePath:loadRequest.filePath]; - _soundEngine.asynchLoadProgress += increment; - } - } - - //Completed - _soundEngine.asynchLoadProgress = 1.0f; - -} - --(void) dealloc { - [_loadRequests release]; - [_soundEngine release]; - [super dealloc]; -} - -@end - - -/////////////////////////////////////////////////////////////////////////////////////// -#pragma mark - -#pragma mark CDBufferLoadRequest - -@implementation CDBufferLoadRequest - -@synthesize filePath, soundId; - --(id) init:(int) theSoundId filePath:(NSString *) theFilePath { - if ((self = [super init])) { - soundId = theSoundId; - filePath = theFilePath; - [filePath retain]; - } - return self; -} - --(void) dealloc { - [filePath release]; - [super dealloc]; -} - -@end - -/////////////////////////////////////////////////////////////////////////////////////// -#pragma mark - -#pragma mark CDFloatInterpolator - -@implementation CDFloatInterpolator -@synthesize start,end,interpolationType; - --(float) interpolate:(float) t { - - if (t < 1.0f) { - switch (interpolationType) { - case kIT_Linear: - //Linear interpolation - return ((end - start) * t) + start; - - case kIT_SCurve: - //Cubic s curve t^2 * (3 - 2t) - return ((float)(t * t * (3.0 - (2.0 * t))) * (end - start)) + start; - - case kIT_Exponential: - //Formulas taken from EaseAction - if (end > start) { - //Fade in - float logDelta = (t==0) ? 0 : powf(2, 10 * (t/1 - 1)) - 1 * 0.001f; - return ((end - start) * logDelta) + start; - } else { - //Fade Out - float logDelta = (-powf(2, -10 * t/1) + 1); - return ((end - start) * logDelta) + start; - } - default: - return 0.0f; - } - } else { - return end; - } -} - --(id) init:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal { - if ((self = [super init])) { - start = startVal; - end = endVal; - interpolationType = type; - } - return self; -} - -@end - -/////////////////////////////////////////////////////////////////////////////////////// -#pragma mark - -#pragma mark CDPropertyModifier - -@implementation CDPropertyModifier - -@synthesize stopTargetWhenComplete; - --(id) init:(id) theTarget interpolationType:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal { - if ((self = [super init])) { - if (target) { - //Release the previous target if there is one - [target release]; - } - target = theTarget; -#if CD_DEBUG - //Check target is of the required type - if (![theTarget isMemberOfClass:[self _allowableType]] ) { - CDLOG(@"Denshion::CDPropertyModifier target is not of type %@",[self _allowableType]); - NSAssert([theTarget isKindOfClass:[CDSoundEngine class]], @"CDPropertyModifier target not of required type"); - } -#endif - [target retain]; - startValue = startVal; - endValue = endVal; - if (interpolator) { - //Release previous interpolator if there is one - [interpolator release]; - } - interpolator = [[CDFloatInterpolator alloc] init:type startVal:startVal endVal:endVal]; - stopTargetWhenComplete = NO; - } - return self; -} - --(void) dealloc { - CDLOG(@"Denshion::CDPropertyModifier deallocated %@",self); - [target release]; - [interpolator release]; - [super dealloc]; -} - --(void) modify:(float) t { - if (t < 1.0) { - [self _setTargetProperty:[interpolator interpolate:t]]; - } else { - //At the end - [self _setTargetProperty:endValue]; - if (stopTargetWhenComplete) { - [self _stopTarget]; - } - } -} - --(float) startValue { - return startValue; -} - --(void) setStartValue:(float) startVal -{ - startValue = startVal; - interpolator.start = startVal; -} - --(float) endValue { - return startValue; -} - --(void) setEndValue:(float) endVal -{ - endValue = endVal; - interpolator.end = endVal; -} - --(tCDInterpolationType) interpolationType { - return interpolator.interpolationType; -} - --(void) setInterpolationType:(tCDInterpolationType) interpolationType { - interpolator.interpolationType = interpolationType; -} - --(void) _setTargetProperty:(float) newVal { - -} - --(float) _getTargetProperty { - return 0.0f; -} - --(void) _stopTarget { - -} - --(Class) _allowableType { - return [NSObject class]; -} -@end - -/////////////////////////////////////////////////////////////////////////////////////// -#pragma mark - -#pragma mark CDSoundSourceFader - -@implementation CDSoundSourceFader - --(void) _setTargetProperty:(float) newVal { - ((CDSoundSource*)target).gain = newVal; -} - --(float) _getTargetProperty { - return ((CDSoundSource*)target).gain; -} - --(void) _stopTarget { - [((CDSoundSource*)target) stop]; -} - --(Class) _allowableType { - return [CDSoundSource class]; -} - -@end - -/////////////////////////////////////////////////////////////////////////////////////// -#pragma mark - -#pragma mark CDSoundSourcePanner - -@implementation CDSoundSourcePanner - --(void) _setTargetProperty:(float) newVal { - ((CDSoundSource*)target).pan = newVal; -} - --(float) _getTargetProperty { - return ((CDSoundSource*)target).pan; -} - --(void) _stopTarget { - [((CDSoundSource*)target) stop]; -} - --(Class) _allowableType { - return [CDSoundSource class]; -} - -@end - -/////////////////////////////////////////////////////////////////////////////////////// -#pragma mark - -#pragma mark CDSoundSourcePitchBender - -@implementation CDSoundSourcePitchBender - --(void) _setTargetProperty:(float) newVal { - ((CDSoundSource*)target).pitch = newVal; -} - --(float) _getTargetProperty { - return ((CDSoundSource*)target).pitch; -} - --(void) _stopTarget { - [((CDSoundSource*)target) stop]; -} - --(Class) _allowableType { - return [CDSoundSource class]; -} - -@end - -/////////////////////////////////////////////////////////////////////////////////////// -#pragma mark - -#pragma mark CDSoundEngineFader - -@implementation CDSoundEngineFader - --(void) _setTargetProperty:(float) newVal { - ((CDSoundEngine*)target).masterGain = newVal; -} - --(float) _getTargetProperty { - return ((CDSoundEngine*)target).masterGain; -} - --(void) _stopTarget { - [((CDSoundEngine*)target) stopAllSounds]; -} - --(Class) _allowableType { - return [CDSoundEngine class]; -} - -@end - - diff --git a/Example/libs/CocosDenshion/SimpleAudioEngine.h b/Example/libs/CocosDenshion/SimpleAudioEngine.h deleted file mode 100644 index 35396c6..0000000 --- a/Example/libs/CocosDenshion/SimpleAudioEngine.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - Copyright (c) 2010 Steve Oldmeadow - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - $Id$ - */ - - -#import "CDAudioManager.h" - -/** - A wrapper to the CDAudioManager object. - This is recommended for basic audio requirements. If you just want to play some sound fx - and some background music and have no interest in learning the lower level workings then - this is the interface to use. - - Requirements: - - Firmware: OS 2.2 or greater - - Files: SimpleAudioEngine.*, CocosDenshion.* - - Frameworks: OpenAL, AudioToolbox, AVFoundation - @since v0.8 - */ -@interface SimpleAudioEngine : NSObject { - - BOOL mute_; - BOOL enabled_; -} - -/** Background music volume. Range is 0.0f to 1.0f. This will only have an effect if willPlayBackgroundMusic returns YES */ -@property (readwrite) float backgroundMusicVolume; -/** Effects volume. Range is 0.0f to 1.0f */ -@property (readwrite) float effectsVolume; -/** If NO it indicates background music will not be played either because no background music is loaded or the audio session does not permit it.*/ -@property (readonly) BOOL willPlayBackgroundMusic; - -/** returns the shared instance of the SimpleAudioEngine object */ -+ (SimpleAudioEngine*) sharedEngine; - -/** Preloads a music file so it will be ready to play as background music */ --(void) preloadBackgroundMusic:(NSString*) filePath; - -/** plays background music in a loop*/ --(void) playBackgroundMusic:(NSString*) filePath; -/** plays background music, if loop is true the music will repeat otherwise it will be played once */ --(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop; -/** stops playing background music */ --(void) stopBackgroundMusic; -/** pauses the background music */ --(void) pauseBackgroundMusic; -/** resume background music that has been paused */ --(void) resumeBackgroundMusic; -/** rewind the background music */ --(void) rewindBackgroundMusic; -/** returns whether or not the background music is playing */ --(BOOL) isBackgroundMusicPlaying; - -/** plays an audio effect with a file path*/ --(ALuint) playEffect:(NSString*) filePath; -/** stop a sound that is playing, note you must pass in the soundId that is returned when you started playing the sound with playEffect */ --(void) stopEffect:(ALuint) soundId; -/** plays an audio effect with a file path, pitch, pan and gain */ --(ALuint) playEffect:(NSString*) filePath pitch:(Float32) pitch pan:(Float32) pan gain:(Float32) gain; -/** preloads an audio effect */ --(void) preloadEffect:(NSString*) filePath; -/** unloads an audio effect from memory */ --(void) unloadEffect:(NSString*) filePath; -/** Gets a CDSoundSource object set up to play the specified file. */ --(CDSoundSource *) soundSourceForFile:(NSString*) filePath; - -/** Shuts down the shared audio engine instance so that it can be reinitialised */ -+(void) end; - -@end diff --git a/Example/libs/CocosDenshion/SimpleAudioEngine.m b/Example/libs/CocosDenshion/SimpleAudioEngine.m deleted file mode 100644 index a93f86a..0000000 --- a/Example/libs/CocosDenshion/SimpleAudioEngine.m +++ /dev/null @@ -1,222 +0,0 @@ -/* - Copyright (c) 2010 Steve Oldmeadow - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - $Id$ - */ - -#import "SimpleAudioEngine.h" - -@implementation SimpleAudioEngine - -static SimpleAudioEngine *sharedEngine = nil; -static CDSoundEngine* soundEngine = nil; -static CDAudioManager *am = nil; -static CDBufferManager *bufferManager = nil; - -// Init -+ (SimpleAudioEngine *) sharedEngine -{ - @synchronized(self) { - if (!sharedEngine) - sharedEngine = [[SimpleAudioEngine alloc] init]; - } - return sharedEngine; -} - -+ (id) alloc -{ - @synchronized(self) { - NSAssert(sharedEngine == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; - } - return nil; -} - --(id) init -{ - if((self=[super init])) { - am = [CDAudioManager sharedManager]; - soundEngine = am.soundEngine; - bufferManager = [[CDBufferManager alloc] initWithEngine:soundEngine]; - mute_ = NO; - enabled_ = YES; - } - return self; -} - -// Memory -- (void) dealloc -{ - am = nil; - soundEngine = nil; - bufferManager = nil; - [super dealloc]; -} - -+(void) end -{ - am = nil; - [CDAudioManager end]; - [bufferManager release]; - [sharedEngine release]; - sharedEngine = nil; -} - -#pragma mark SimpleAudioEngine - background music - --(void) preloadBackgroundMusic:(NSString*) filePath { - [am preloadBackgroundMusic:filePath]; -} - --(void) playBackgroundMusic:(NSString*) filePath -{ - [am playBackgroundMusic:filePath loop:TRUE]; -} - --(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop -{ - [am playBackgroundMusic:filePath loop:loop]; -} - --(void) stopBackgroundMusic -{ - [am stopBackgroundMusic]; -} - --(void) pauseBackgroundMusic { - [am pauseBackgroundMusic]; -} - --(void) resumeBackgroundMusic { - [am resumeBackgroundMusic]; -} - --(void) rewindBackgroundMusic { - [am rewindBackgroundMusic]; -} - --(BOOL) isBackgroundMusicPlaying { - return [am isBackgroundMusicPlaying]; -} - --(BOOL) willPlayBackgroundMusic { - return [am willPlayBackgroundMusic]; -} - -#pragma mark SimpleAudioEngine - sound effects - --(ALuint) playEffect:(NSString*) filePath -{ - return [self playEffect:filePath pitch:1.0f pan:0.0f gain:1.0f]; -} - --(ALuint) playEffect:(NSString*) filePath pitch:(Float32) pitch pan:(Float32) pan gain:(Float32) gain -{ - int soundId = [bufferManager bufferForFile:filePath create:YES]; - if (soundId != kCDNoBuffer) { - return [soundEngine playSound:soundId sourceGroupId:0 pitch:pitch pan:pan gain:gain loop:false]; - } else { - return CD_MUTE; - } -} - --(void) stopEffect:(ALuint) soundId { - [soundEngine stopSound:soundId]; -} - --(void) preloadEffect:(NSString*) filePath -{ - int soundId = [bufferManager bufferForFile:filePath create:YES]; - if (soundId == kCDNoBuffer) { - CDLOG(@"Denshion::SimpleAudioEngine sound failed to preload %@",filePath); - } else { - CDLOG(@"Denshion::SimpleAudioEngine preloaded %@",filePath); - } -} - --(void) unloadEffect:(NSString*) filePath -{ - CDLOG(@"Denshion::SimpleAudioEngine unloadedEffect %@",filePath); - [bufferManager releaseBufferForFile:filePath]; -} - -#pragma mark Audio Interrupt Protocol --(BOOL) mute -{ - return mute_; -} - --(void) setMute:(BOOL) muteValue -{ - if (mute_ != muteValue) { - mute_ = muteValue; - am.mute = mute_; - } -} - --(BOOL) enabled -{ - return enabled_; -} - --(void) setEnabled:(BOOL) enabledValue -{ - if (enabled_ != enabledValue) { - enabled_ = enabledValue; - am.enabled = enabled_; - } -} - - -#pragma mark SimpleAudioEngine - BackgroundMusicVolume --(float) backgroundMusicVolume -{ - return am.backgroundMusic.volume; -} - --(void) setBackgroundMusicVolume:(float) volume -{ - am.backgroundMusic.volume = volume; -} - -#pragma mark SimpleAudioEngine - EffectsVolume --(float) effectsVolume -{ - return am.soundEngine.masterGain; -} - --(void) setEffectsVolume:(float) volume -{ - am.soundEngine.masterGain = volume; -} - --(CDSoundSource *) soundSourceForFile:(NSString*) filePath { - int soundId = [bufferManager bufferForFile:filePath create:YES]; - if (soundId != kCDNoBuffer) { - CDSoundSource *result = [soundEngine soundSourceForSound:soundId sourceGroupId:0]; - CDLOG(@"Denshion::SimpleAudioEngine sound source created for %@",filePath); - return result; - } else { - return nil; - } -} - -@end diff --git a/Example/libs/FontLabel/FontLabel.h b/Example/libs/FontLabel/FontLabel.h deleted file mode 100644 index 6de9c2c..0000000 --- a/Example/libs/FontLabel/FontLabel.h +++ /dev/null @@ -1,44 +0,0 @@ -// -// FontLabel.h -// FontLabel -// -// Created by Kevin Ballard on 5/8/09. -// Copyright © 2009 Zynga Game Networks -// -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#import -#import - -@class ZFont; -@class ZAttributedString; - -@interface FontLabel : UILabel { - void *reserved; // works around a bug in UILabel - ZFont *zFont; - ZAttributedString *zAttributedText; -} -@property (nonatomic, setter=setCGFont:) CGFontRef cgFont __AVAILABILITY_INTERNAL_DEPRECATED; -@property (nonatomic, assign) CGFloat pointSize __AVAILABILITY_INTERNAL_DEPRECATED; -@property (nonatomic, retain, setter=setZFont:) ZFont *zFont; -// if attributedText is nil, fall back on using the inherited UILabel properties -// if attributedText is non-nil, the font/text/textColor -// in addition, adjustsFontSizeToFitWidth does not work with attributed text -@property (nonatomic, copy) ZAttributedString *zAttributedText; -// -initWithFrame:fontName:pointSize: uses FontManager to look up the font name -- (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName pointSize:(CGFloat)pointSize; -- (id)initWithFrame:(CGRect)frame zFont:(ZFont *)font; -- (id)initWithFrame:(CGRect)frame font:(CGFontRef)font pointSize:(CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED; -@end diff --git a/Example/libs/FontLabel/FontLabel.m b/Example/libs/FontLabel/FontLabel.m deleted file mode 100644 index 4fc82b0..0000000 --- a/Example/libs/FontLabel/FontLabel.m +++ /dev/null @@ -1,186 +0,0 @@ -// -// FontLabel.m -// FontLabel -// -// Created by Kevin Ballard on 5/8/09. -// Copyright © 2009 Zynga Game Networks -// -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#import "FontLabel.h" -#import "FontManager.h" -#import "FontLabelStringDrawing.h" -#import "ZFont.h" - -@interface ZFont (ZFontPrivate) -@property (nonatomic, readonly) CGFloat ratio; -@end - -@implementation FontLabel -@synthesize zFont; -@synthesize zAttributedText; - -- (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName pointSize:(CGFloat)pointSize { - return [self initWithFrame:frame zFont:[[FontManager sharedManager] zFontWithName:fontName pointSize:pointSize]]; -} - -- (id)initWithFrame:(CGRect)frame zFont:(ZFont *)font { - if ((self = [super initWithFrame:frame])) { - zFont = [font retain]; - } - return self; -} - -- (id)initWithFrame:(CGRect)frame font:(CGFontRef)font pointSize:(CGFloat)pointSize { - return [self initWithFrame:frame zFont:[ZFont fontWithCGFont:font size:pointSize]]; -} - -- (CGFontRef)cgFont { - return self.zFont.cgFont; -} - -- (void)setCGFont:(CGFontRef)font { - if (self.zFont.cgFont != font) { - self.zFont = [ZFont fontWithCGFont:font size:self.zFont.pointSize]; - } -} - -- (CGFloat)pointSize { - return self.zFont.pointSize; -} - -- (void)setPointSize:(CGFloat)pointSize { - if (self.zFont.pointSize != pointSize) { - self.zFont = [ZFont fontWithCGFont:self.zFont.cgFont size:pointSize]; - } -} - -- (void)setZAttributedText:(ZAttributedString *)attStr { - if (zAttributedText != attStr) { - [zAttributedText release]; - zAttributedText = [attStr copy]; - [self setNeedsDisplay]; - } -} - -- (void)drawTextInRect:(CGRect)rect { - if (self.zFont == NULL && self.zAttributedText == nil) { - [super drawTextInRect:rect]; - return; - } - - if (self.zAttributedText == nil) { - // this method is documented as setting the text color for us, but that doesn't appear to be the case - if (self.highlighted) { - [(self.highlightedTextColor ?: [UIColor whiteColor]) setFill]; - } else { - [(self.textColor ?: [UIColor blackColor]) setFill]; - } - - ZFont *actualFont = self.zFont; - CGSize origSize = rect.size; - if (self.numberOfLines == 1) { - origSize.height = actualFont.leading; - CGPoint point = CGPointMake(rect.origin.x, - rect.origin.y + roundf(((rect.size.height - actualFont.leading) / 2.0f))); - CGSize size = [self.text sizeWithZFont:actualFont]; - if (self.adjustsFontSizeToFitWidth && self.minimumFontSize < actualFont.pointSize) { - if (size.width > origSize.width) { - CGFloat desiredRatio = (origSize.width * actualFont.ratio) / size.width; - CGFloat desiredPointSize = desiredRatio * actualFont.pointSize / actualFont.ratio; - actualFont = [actualFont fontWithSize:MAX(MAX(desiredPointSize, self.minimumFontSize), 1.0f)]; - size = [self.text sizeWithZFont:actualFont]; - } - if (!CGSizeEqualToSize(origSize, size)) { - switch (self.baselineAdjustment) { - case UIBaselineAdjustmentAlignCenters: - point.y += roundf((origSize.height - size.height) / 2.0f); - break; - case UIBaselineAdjustmentAlignBaselines: - point.y += (self.zFont.ascender - actualFont.ascender); - break; - case UIBaselineAdjustmentNone: - break; - } - } - } - size.width = MIN(size.width, origSize.width); - // adjust the point for alignment - switch (self.textAlignment) { - case UITextAlignmentLeft: - break; - case UITextAlignmentCenter: - point.x += (origSize.width - size.width) / 2.0f; - break; - case UITextAlignmentRight: - point.x += origSize.width - size.width; - break; - } - [self.text drawAtPoint:point forWidth:size.width withZFont:actualFont lineBreakMode:self.lineBreakMode]; - } else { - CGSize size = [self.text sizeWithZFont:actualFont constrainedToSize:origSize lineBreakMode:self.lineBreakMode numberOfLines:self.numberOfLines]; - CGPoint point = rect.origin; - point.y += roundf((rect.size.height - size.height) / 2.0f); - rect = (CGRect){point, CGSizeMake(rect.size.width, size.height)}; - [self.text drawInRect:rect withZFont:actualFont lineBreakMode:self.lineBreakMode alignment:self.textAlignment numberOfLines:self.numberOfLines]; - } - } else { - ZAttributedString *attStr = self.zAttributedText; - if (self.highlighted) { - // modify the string to change the base color - ZMutableAttributedString *mutStr = [[attStr mutableCopy] autorelease]; - NSRange activeRange = NSMakeRange(0, attStr.length); - while (activeRange.length > 0) { - NSRange effective; - UIColor *color = [attStr attribute:ZForegroundColorAttributeName atIndex:activeRange.location - longestEffectiveRange:&effective inRange:activeRange]; - if (color == nil) { - [mutStr addAttribute:ZForegroundColorAttributeName value:[UIColor whiteColor] range:effective]; - } - activeRange.location += effective.length, activeRange.length -= effective.length; - } - attStr = mutStr; - } - CGSize size = [attStr sizeConstrainedToSize:rect.size lineBreakMode:self.lineBreakMode numberOfLines:self.numberOfLines]; - CGPoint point = rect.origin; - point.y += roundf((rect.size.height - size.height) / 2.0f); - rect = (CGRect){point, CGSizeMake(rect.size.width, size.height)}; - [attStr drawInRect:rect withLineBreakMode:self.lineBreakMode alignment:self.textAlignment numberOfLines:self.numberOfLines]; - } -} - -- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines { - if (self.zFont == NULL && self.zAttributedText == nil) { - return [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines]; - } - - if (numberOfLines == 1) { - // if numberOfLines == 1 we need to use the version that converts spaces - CGSize size = [self.text sizeWithZFont:self.zFont]; - bounds.size.width = MIN(bounds.size.width, size.width); - bounds.size.height = MIN(bounds.size.height, size.height); - } else { - if (numberOfLines > 0) bounds.size.height = MIN(bounds.size.height, self.zFont.leading * numberOfLines); - bounds.size = [self.text sizeWithZFont:self.zFont constrainedToSize:bounds.size lineBreakMode:self.lineBreakMode]; - } - return bounds; -} - -- (void)dealloc { - [zFont release]; - [zAttributedText release]; - [super dealloc]; -} -@end diff --git a/Example/libs/FontLabel/FontLabelStringDrawing.h b/Example/libs/FontLabel/FontLabelStringDrawing.h deleted file mode 100644 index 821da22..0000000 --- a/Example/libs/FontLabel/FontLabelStringDrawing.h +++ /dev/null @@ -1,69 +0,0 @@ -// -// FontLabelStringDrawing.h -// FontLabel -// -// Created by Kevin Ballard on 5/5/09. -// Copyright © 2009 Zynga Game Networks -// -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#import -#import "ZAttributedString.h" - -@class ZFont; - -@interface NSString (FontLabelStringDrawing) -// CGFontRef-based methods -- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED; -- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize constrainedToSize:(CGSize)size __AVAILABILITY_INTERNAL_DEPRECATED; -- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize constrainedToSize:(CGSize)size - lineBreakMode:(UILineBreakMode)lineBreakMode __AVAILABILITY_INTERNAL_DEPRECATED; -- (CGSize)drawAtPoint:(CGPoint)point withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED; -- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED; -- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize - lineBreakMode:(UILineBreakMode)lineBreakMode __AVAILABILITY_INTERNAL_DEPRECATED; -- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize - lineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment __AVAILABILITY_INTERNAL_DEPRECATED; - -// ZFont-based methods -- (CGSize)sizeWithZFont:(ZFont *)font; -- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size; -- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode; -- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode - numberOfLines:(NSUInteger)numberOfLines; -- (CGSize)drawAtPoint:(CGPoint)point withZFont:(ZFont *)font; -- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode; -- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font; -- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode; -- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode - alignment:(UITextAlignment)alignment; -- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode - alignment:(UITextAlignment)alignment numberOfLines:(NSUInteger)numberOfLines; -@end - -@interface ZAttributedString (ZAttributedStringDrawing) -- (CGSize)size; -- (CGSize)sizeConstrainedToSize:(CGSize)size; -- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode; -- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode - numberOfLines:(NSUInteger)numberOfLines; -- (CGSize)drawAtPoint:(CGPoint)point; -- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode; -- (CGSize)drawInRect:(CGRect)rect; -- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode; -- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment; -- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment - numberOfLines:(NSUInteger)numberOfLines; -@end diff --git a/Example/libs/FontLabel/FontLabelStringDrawing.m b/Example/libs/FontLabel/FontLabelStringDrawing.m deleted file mode 100644 index 4f30066..0000000 --- a/Example/libs/FontLabel/FontLabelStringDrawing.m +++ /dev/null @@ -1,890 +0,0 @@ -// -// FontLabelStringDrawing.m -// FontLabel -// -// Created by Kevin Ballard on 5/5/09. -// Copyright © 2009 Zynga Game Networks -// -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#import "FontLabelStringDrawing.h" -#import "ZFont.h" -#import "ZAttributedStringPrivate.h" - -@interface ZFont (ZFontPrivate) -@property (nonatomic, readonly) CGFloat ratio; -@end - -#define kUnicodeHighSurrogateStart 0xD800 -#define kUnicodeHighSurrogateEnd 0xDBFF -#define kUnicodeHighSurrogateMask kUnicodeHighSurrogateStart -#define kUnicodeLowSurrogateStart 0xDC00 -#define kUnicodeLowSurrogateEnd 0xDFFF -#define kUnicodeLowSurrogateMask kUnicodeLowSurrogateStart -#define kUnicodeSurrogateTypeMask 0xFC00 -#define UnicharIsHighSurrogate(c) ((c & kUnicodeSurrogateTypeMask) == kUnicodeHighSurrogateMask) -#define UnicharIsLowSurrogate(c) ((c & kUnicodeSurrogateTypeMask) == kUnicodeLowSurrogateMask) -#define ConvertSurrogatePairToUTF32(high, low) ((UInt32)((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)) - -typedef enum { - kFontTableFormat4 = 4, - kFontTableFormat12 = 12, -} FontTableFormat; - -typedef struct fontTable { - NSUInteger retainCount; - CFDataRef cmapTable; - FontTableFormat format; - union { - struct { - UInt16 segCountX2; - UInt16 *endCodes; - UInt16 *startCodes; - UInt16 *idDeltas; - UInt16 *idRangeOffsets; - } format4; - struct { - UInt32 nGroups; - struct { - UInt32 startCharCode; - UInt32 endCharCode; - UInt32 startGlyphCode; - } *groups; - } format12; - } cmap; -} fontTable; - -static FontTableFormat supportedFormats[] = { kFontTableFormat4, kFontTableFormat12 }; -static size_t supportedFormatsCount = sizeof(supportedFormats) / sizeof(FontTableFormat); - -static fontTable *newFontTable(CFDataRef cmapTable, FontTableFormat format) { - fontTable *table = (struct fontTable *)malloc(sizeof(struct fontTable)); - table->retainCount = 1; - table->cmapTable = CFRetain(cmapTable); - table->format = format; - return table; -} - -static fontTable *retainFontTable(fontTable *table) { - if (table != NULL) { - table->retainCount++; - } - return table; -} - -static void releaseFontTable(fontTable *table) { - if (table != NULL) { - if (table->retainCount <= 1) { - CFRelease(table->cmapTable); - free(table); - } else { - table->retainCount--; - } - } -} - -static const void *fontTableRetainCallback(CFAllocatorRef allocator, const void *value) { - return retainFontTable((fontTable *)value); -} - -static void fontTableReleaseCallback(CFAllocatorRef allocator, const void *value) { - releaseFontTable((fontTable *)value); -} - -static const CFDictionaryValueCallBacks kFontTableDictionaryValueCallBacks = { - .version = 0, - .retain = &fontTableRetainCallback, - .release = &fontTableReleaseCallback, - .copyDescription = NULL, - .equal = NULL -}; - -// read the cmap table from the font -// we only know how to understand some of the table formats at the moment -static fontTable *readFontTableFromCGFont(CGFontRef font) { - CFDataRef cmapTable = CGFontCopyTableForTag(font, 'cmap'); - NSCAssert1(cmapTable != NULL, @"CGFontCopyTableForTag returned NULL for 'cmap' tag in font %@", - (font ? [(id)CFCopyDescription(font) autorelease] : @"(null)")); - const UInt8 * const bytes = CFDataGetBytePtr(cmapTable); - NSCAssert1(OSReadBigInt16(bytes, 0) == 0, @"cmap table for font %@ has bad version number", - (font ? [(id)CFCopyDescription(font) autorelease] : @"(null)")); - UInt16 numberOfSubtables = OSReadBigInt16(bytes, 2); - const UInt8 *unicodeSubtable = NULL; - //UInt16 unicodeSubtablePlatformID; - UInt16 unicodeSubtablePlatformSpecificID; - FontTableFormat unicodeSubtableFormat; - const UInt8 * const encodingSubtables = &bytes[4]; - for (UInt16 i = 0; i < numberOfSubtables; i++) { - const UInt8 * const encodingSubtable = &encodingSubtables[8 * i]; - UInt16 platformID = OSReadBigInt16(encodingSubtable, 0); - UInt16 platformSpecificID = OSReadBigInt16(encodingSubtable, 2); - // find the best subtable - // best is defined by a combination of encoding and format - // At the moment we only support format 4, so ignore all other format tables - // We prefer platformID == 0, but we will also accept Microsoft's unicode format - if (platformID == 0 || (platformID == 3 && platformSpecificID == 1)) { - BOOL preferred = NO; - if (unicodeSubtable == NULL) { - preferred = YES; - } else if (platformID == 0 && platformSpecificID > unicodeSubtablePlatformSpecificID) { - preferred = YES; - } - if (preferred) { - UInt32 offset = OSReadBigInt32(encodingSubtable, 4); - const UInt8 *subtable = &bytes[offset]; - UInt16 format = OSReadBigInt16(subtable, 0); - for (size_t i = 0; i < supportedFormatsCount; i++) { - if (format == supportedFormats[i]) { - if (format >= 8) { - // the version is a fixed-point - UInt16 formatFrac = OSReadBigInt16(subtable, 2); - if (formatFrac != 0) { - // all the current formats with a Fixed version are always *.0 - continue; - } - } - unicodeSubtable = subtable; - //unicodeSubtablePlatformID = platformID; - unicodeSubtablePlatformSpecificID = platformSpecificID; - unicodeSubtableFormat = format; - break; - } - } - } - } - } - fontTable *table = NULL; - if (unicodeSubtable != NULL) { - table = newFontTable(cmapTable, unicodeSubtableFormat); - switch (unicodeSubtableFormat) { - case kFontTableFormat4: - // subtable format 4 - //UInt16 length = OSReadBigInt16(unicodeSubtable, 2); - //UInt16 language = OSReadBigInt16(unicodeSubtable, 4); - table->cmap.format4.segCountX2 = OSReadBigInt16(unicodeSubtable, 6); - //UInt16 searchRange = OSReadBigInt16(unicodeSubtable, 8); - //UInt16 entrySelector = OSReadBigInt16(unicodeSubtable, 10); - //UInt16 rangeShift = OSReadBigInt16(unicodeSubtable, 12); - table->cmap.format4.endCodes = (UInt16*)&unicodeSubtable[14]; - table->cmap.format4.startCodes = (UInt16*)&((UInt8*)table->cmap.format4.endCodes)[table->cmap.format4.segCountX2+2]; - table->cmap.format4.idDeltas = (UInt16*)&((UInt8*)table->cmap.format4.startCodes)[table->cmap.format4.segCountX2]; - table->cmap.format4.idRangeOffsets = (UInt16*)&((UInt8*)table->cmap.format4.idDeltas)[table->cmap.format4.segCountX2]; - //UInt16 *glyphIndexArray = &idRangeOffsets[segCountX2]; - break; - case kFontTableFormat12: - table->cmap.format12.nGroups = OSReadBigInt32(unicodeSubtable, 12); - table->cmap.format12.groups = (void *)&unicodeSubtable[16]; - break; - default: - releaseFontTable(table); - table = NULL; - } - } - CFRelease(cmapTable); - return table; -} - -// outGlyphs must be at least size n -static void mapCharactersToGlyphsInFont(const fontTable *table, unichar characters[], size_t charLen, CGGlyph outGlyphs[], size_t *outGlyphLen) { - if (table != NULL) { - NSUInteger j = 0; - switch (table->format) { - case kFontTableFormat4: { - for (NSUInteger i = 0; i < charLen; i++, j++) { - unichar c = characters[i]; - UInt16 segOffset; - BOOL foundSegment = NO; - for (segOffset = 0; segOffset < table->cmap.format4.segCountX2; segOffset += 2) { - UInt16 endCode = OSReadBigInt16(table->cmap.format4.endCodes, segOffset); - if (endCode >= c) { - foundSegment = YES; - break; - } - } - if (!foundSegment) { - // no segment - // this is an invalid font - outGlyphs[j] = 0; - } else { - UInt16 startCode = OSReadBigInt16(table->cmap.format4.startCodes, segOffset); - if (!(startCode <= c)) { - // the code falls in a hole between segments - outGlyphs[j] = 0; - } else { - UInt16 idRangeOffset = OSReadBigInt16(table->cmap.format4.idRangeOffsets, segOffset); - if (idRangeOffset == 0) { - UInt16 idDelta = OSReadBigInt16(table->cmap.format4.idDeltas, segOffset); - outGlyphs[j] = (c + idDelta) % 65536; - } else { - // use the glyphIndexArray - UInt16 glyphOffset = idRangeOffset + 2 * (c - startCode); - outGlyphs[j] = OSReadBigInt16(&((UInt8*)table->cmap.format4.idRangeOffsets)[segOffset], glyphOffset); - } - } - } - } - break; - } - case kFontTableFormat12: { - UInt32 lastSegment = UINT32_MAX; - for (NSUInteger i = 0; i < charLen; i++, j++) { - unichar c = characters[i]; - UInt32 c32 = c; - if (UnicharIsHighSurrogate(c)) { - if (i+1 < charLen) { // do we have another character after this one? - unichar cc = characters[i+1]; - if (UnicharIsLowSurrogate(cc)) { - c32 = ConvertSurrogatePairToUTF32(c, cc); - i++; - } - } - } - // Start the heuristic search - // If this is an ASCII char, just do a linear search - // Otherwise do a hinted, modified binary search - // Start the first pivot at the last range found - // And when moving the pivot, limit the movement by increasing - // powers of two. This should help with locality - __typeof__(table->cmap.format12.groups[0]) *foundGroup = NULL; - if (c32 <= 0x7F) { - // ASCII - for (UInt32 idx = 0; idx < table->cmap.format12.nGroups; idx++) { - __typeof__(table->cmap.format12.groups[idx]) *group = &table->cmap.format12.groups[idx]; - if (c32 < OSSwapBigToHostInt32(group->startCharCode)) { - // we've fallen into a hole - break; - } else if (c32 <= OSSwapBigToHostInt32(group->endCharCode)) { - // this is the range - foundGroup = group; - break; - } - } - } else { - // heuristic search - UInt32 maxJump = (lastSegment == UINT32_MAX ? UINT32_MAX / 2 : 8); - UInt32 lowIdx = 0, highIdx = table->cmap.format12.nGroups; // highIdx is the first invalid idx - UInt32 pivot = (lastSegment == UINT32_MAX ? lowIdx + (highIdx - lowIdx) / 2 : lastSegment); - while (highIdx > lowIdx) { - __typeof__(table->cmap.format12.groups[pivot]) *group = &table->cmap.format12.groups[pivot]; - if (c32 < OSSwapBigToHostInt32(group->startCharCode)) { - highIdx = pivot; - } else if (c32 > OSSwapBigToHostInt32(group->endCharCode)) { - lowIdx = pivot + 1; - } else { - // we've hit the range - foundGroup = group; - break; - } - if (highIdx - lowIdx > maxJump * 2) { - if (highIdx == pivot) { - pivot -= maxJump; - } else { - pivot += maxJump; - } - maxJump *= 2; - } else { - pivot = lowIdx + (highIdx - lowIdx) / 2; - } - } - if (foundGroup != NULL) lastSegment = pivot; - } - if (foundGroup == NULL) { - outGlyphs[j] = 0; - } else { - outGlyphs[j] = (CGGlyph)(OSSwapBigToHostInt32(foundGroup->startGlyphCode) + - (c32 - OSSwapBigToHostInt32(foundGroup->startCharCode))); - } - } - break; - } - } - if (outGlyphLen != NULL) *outGlyphLen = j; - } else { - // we have no table, so just null out the glyphs - bzero(outGlyphs, charLen*sizeof(CGGlyph)); - if (outGlyphLen != NULL) *outGlyphLen = 0; - } -} - -static BOOL mapGlyphsToAdvancesInFont(ZFont *font, size_t n, CGGlyph glyphs[], CGFloat outAdvances[]) { - int advances[n]; - if (CGFontGetGlyphAdvances(font.cgFont, glyphs, n, advances)) { - CGFloat ratio = font.ratio; - - for (size_t i = 0; i < n; i++) { - outAdvances[i] = advances[i]*ratio; - } - return YES; - } else { - bzero(outAdvances, n*sizeof(CGFloat)); - } - return NO; -} - -static id getValueOrDefaultForRun(ZAttributeRun *run, NSString *key) { - id value = [run.attributes objectForKey:key]; - if (value == nil) { - static NSDictionary *defaultValues = nil; - if (defaultValues == nil) { - defaultValues = [[NSDictionary alloc] initWithObjectsAndKeys: - [ZFont fontWithUIFont:[UIFont systemFontOfSize:12]], ZFontAttributeName, - [UIColor blackColor], ZForegroundColorAttributeName, - [UIColor clearColor], ZBackgroundColorAttributeName, - [NSNumber numberWithInt:ZUnderlineStyleNone], ZUnderlineStyleAttributeName, - nil]; - } - value = [defaultValues objectForKey:key]; - } - return value; -} - -static void readRunInformation(NSArray *attributes, NSUInteger len, CFMutableDictionaryRef fontTableMap, - NSUInteger index, ZAttributeRun **currentRun, NSUInteger *nextRunStart, - ZFont **currentFont, fontTable **currentTable) { - *currentRun = [attributes objectAtIndex:index]; - *nextRunStart = ([attributes count] > index+1 ? [[attributes objectAtIndex:index+1] index] : len); - *currentFont = getValueOrDefaultForRun(*currentRun, ZFontAttributeName); - if (!CFDictionaryGetValueIfPresent(fontTableMap, (*currentFont).cgFont, (const void **)currentTable)) { - *currentTable = readFontTableFromCGFont((*currentFont).cgFont); - CFDictionarySetValue(fontTableMap, (*currentFont).cgFont, *currentTable); - releaseFontTable(*currentTable); - } -} - -static CGSize drawOrSizeTextConstrainedToSize(BOOL performDraw, NSString *string, NSArray *attributes, CGSize constrainedSize, NSUInteger maxLines, - UILineBreakMode lineBreakMode, UITextAlignment alignment, BOOL ignoreColor) { - NSUInteger len = [string length]; - NSUInteger idx = 0; - CGPoint drawPoint = CGPointZero; - CGSize retValue = CGSizeZero; - CGContextRef ctx = (performDraw ? UIGraphicsGetCurrentContext() : NULL); - - BOOL convertNewlines = (maxLines == 1); - - // Extract the characters from the string - // Convert newlines to spaces if necessary - unichar *characters = (unichar *)malloc(sizeof(unichar) * len); - if (convertNewlines) { - NSCharacterSet *charset = [NSCharacterSet newlineCharacterSet]; - NSRange range = NSMakeRange(0, len); - size_t cIdx = 0; - while (range.length > 0) { - NSRange newlineRange = [string rangeOfCharacterFromSet:charset options:0 range:range]; - if (newlineRange.location == NSNotFound) { - [string getCharacters:&characters[cIdx] range:range]; - cIdx += range.length; - break; - } else { - NSUInteger delta = newlineRange.location - range.location; - if (newlineRange.location > range.location) { - [string getCharacters:&characters[cIdx] range:NSMakeRange(range.location, delta)]; - } - cIdx += delta; - characters[cIdx] = (unichar)' '; - cIdx++; - delta += newlineRange.length; - range.location += delta, range.length -= delta; - if (newlineRange.length == 1 && range.length >= 1 && - [string characterAtIndex:newlineRange.location] == (unichar)'\r' && - [string characterAtIndex:range.location] == (unichar)'\n') { - // CRLF sequence, skip the LF - range.location += 1, range.length -= 1; - } - } - } - len = cIdx; - } else { - [string getCharacters:characters range:NSMakeRange(0, len)]; - } - - // Create storage for glyphs and advances - CGGlyph *glyphs; - CGFloat *advances; - { - NSUInteger maxRunLength = 0; - ZAttributeRun *a = [attributes objectAtIndex:0]; - for (NSUInteger i = 1; i < [attributes count]; i++) { - ZAttributeRun *b = [attributes objectAtIndex:i]; - maxRunLength = MAX(maxRunLength, b.index - a.index); - a = b; - } - maxRunLength = MAX(maxRunLength, len - a.index); - maxRunLength++; // for a potential ellipsis - glyphs = (CGGlyph *)malloc(sizeof(CGGlyph) * maxRunLength); - advances = (CGFloat *)malloc(sizeof(CGFloat) * maxRunLength); - } - - // Use this table to cache all fontTable objects - CFMutableDictionaryRef fontTableMap = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, - &kFontTableDictionaryValueCallBacks); - - // Fetch initial style values - NSUInteger currentRunIdx = 0; - ZAttributeRun *currentRun; - NSUInteger nextRunStart; - ZFont *currentFont; - fontTable *currentTable; - -#define READ_RUN() readRunInformation(attributes, len, fontTableMap, \ - currentRunIdx, ¤tRun, &nextRunStart, \ - ¤tFont, ¤tTable) - - READ_RUN(); - - // fetch the glyphs for the first run - size_t glyphCount; - NSUInteger glyphIdx; - -#define READ_GLYPHS() do { \ - mapCharactersToGlyphsInFont(currentTable, &characters[currentRun.index], (nextRunStart - currentRun.index), glyphs, &glyphCount); \ - mapGlyphsToAdvancesInFont(currentFont, (nextRunStart - currentRun.index), glyphs, advances); \ - glyphIdx = 0; \ - } while (0) - - READ_GLYPHS(); - - NSCharacterSet *alphaCharset = [NSCharacterSet alphanumericCharacterSet]; - - // scan left-to-right looking for newlines or until we hit the width constraint - // When we hit a wrapping point, calculate truncation as follows: - // If we have room to draw at least one more character on the next line, no truncation - // Otherwise apply the truncation algorithm to the current line. - // After calculating any truncation, draw. - // Each time we hit the end of an attribute run, calculate the new font and make sure - // it fits (vertically) within the size constraint. If not, truncate this line. - // When we draw, iterate over the attribute runs for this line and draw each run separately - BOOL lastLine = NO; // used to indicate truncation and to stop the iterating - NSUInteger lineCount = 1; - while (idx < len && !lastLine) { - if (maxLines > 0 && lineCount == maxLines) { - lastLine = YES; - } - // scan left-to-right - struct { - NSUInteger index; - NSUInteger glyphIndex; - NSUInteger currentRunIdx; - } indexCache = { idx, glyphIdx, currentRunIdx }; - CGSize lineSize = CGSizeMake(0, currentFont.leading); - CGFloat lineAscender = currentFont.ascender; - struct { - NSUInteger index; - NSUInteger glyphIndex; - NSUInteger currentRunIdx; - CGSize lineSize; - } lastWrapCache = {0, 0, 0, CGSizeZero}; - BOOL inAlpha = NO; // used for calculating wrap points - - BOOL finishLine = NO; - for (;idx <= len && !finishLine;) { - NSUInteger skipCount = 0; - if (idx == len) { - finishLine = YES; - lastLine = YES; - } else { - if (idx >= nextRunStart) { - // cycle the font and table and grab the next set of glyphs - do { - currentRunIdx++; - READ_RUN(); - } while (idx >= nextRunStart); - READ_GLYPHS(); - // re-scan the characters to synchronize the glyph index - for (NSUInteger j = currentRun.index; j < idx; j++) { - if (UnicharIsHighSurrogate(characters[j]) && j+1 lineSize.height) { - lineSize.height = currentFont.leading; - if (retValue.height + currentFont.ascender > constrainedSize.height) { - lastLine = YES; - finishLine = YES; - } - } - lineAscender = MAX(lineAscender, currentFont.ascender); - } - unichar c = characters[idx]; - if (c == (unichar)'\n' || c == 0x0085) { // U+0085 is the NEXT_LINE unicode character - finishLine = YES; - skipCount = 1; - } else if (c == (unichar)'\r') { - finishLine = YES; - // check for CRLF - if (idx+1 < len && characters[idx+1] == (unichar)'\n') { - skipCount = 2; - } else { - skipCount = 1; - } - } else if (lineSize.width + advances[glyphIdx] > constrainedSize.width) { - finishLine = YES; - if (retValue.height + lineSize.height + currentFont.ascender > constrainedSize.height) { - lastLine = YES; - } - // walk backwards if wrapping is necessary - if (lastWrapCache.index > indexCache.index && lineBreakMode != UILineBreakModeCharacterWrap && - (!lastLine || lineBreakMode != UILineBreakModeClip)) { - // we're doing some sort of word wrapping - idx = lastWrapCache.index; - lineSize = lastWrapCache.lineSize; - if (!lastLine) { - // re-check if this is the last line - if (lastWrapCache.currentRunIdx != currentRunIdx) { - currentRunIdx = lastWrapCache.currentRunIdx; - READ_RUN(); - READ_GLYPHS(); - } - if (retValue.height + lineSize.height + currentFont.ascender > constrainedSize.height) { - lastLine = YES; - } - } - glyphIdx = lastWrapCache.glyphIndex; - // skip any spaces - for (NSUInteger j = idx; j < len && characters[j] == (unichar)' '; j++) { - skipCount++; - } - } - } - } - if (finishLine) { - // TODO: support head/middle truncation - if (lastLine && idx < len && lineBreakMode == UILineBreakModeTailTruncation) { - // truncate - unichar ellipsis = 0x2026; // ellipsis (…) - CGGlyph ellipsisGlyph; - mapCharactersToGlyphsInFont(currentTable, &ellipsis, 1, &ellipsisGlyph, NULL); - CGFloat ellipsisWidth; - mapGlyphsToAdvancesInFont(currentFont, 1, &ellipsisGlyph, &ellipsisWidth); - while ((idx - indexCache.index) > 1 && lineSize.width + ellipsisWidth > constrainedSize.width) { - // we have more than 1 character and we're too wide, so back up - idx--; - if (UnicharIsHighSurrogate(characters[idx]) && UnicharIsLowSurrogate(characters[idx+1])) { - idx--; - } - if (idx < currentRun.index) { - ZFont *oldFont = currentFont; - do { - currentRunIdx--; - READ_RUN(); - } while (idx < currentRun.index); - READ_GLYPHS(); - glyphIdx = glyphCount-1; - if (oldFont != currentFont) { - mapCharactersToGlyphsInFont(currentTable, &ellipsis, 1, &ellipsisGlyph, NULL); - mapGlyphsToAdvancesInFont(currentFont, 1, &ellipsisGlyph, &ellipsisWidth); - } - } else { - glyphIdx--; - } - lineSize.width -= advances[glyphIdx]; - } - // skip any spaces before truncating - while ((idx - indexCache.index) > 1 && characters[idx-1] == (unichar)' ') { - idx--; - if (idx < currentRun.index) { - currentRunIdx--; - READ_RUN(); - READ_GLYPHS(); - glyphIdx = glyphCount-1; - } else { - glyphIdx--; - } - lineSize.width -= advances[glyphIdx]; - } - lineSize.width += ellipsisWidth; - glyphs[glyphIdx] = ellipsisGlyph; - idx++; - glyphIdx++; - } - retValue.width = MAX(retValue.width, lineSize.width); - retValue.height += lineSize.height; - - // draw - if (performDraw) { - switch (alignment) { - case UITextAlignmentLeft: - drawPoint.x = 0; - break; - case UITextAlignmentCenter: - drawPoint.x = (constrainedSize.width - lineSize.width) / 2.0f; - break; - case UITextAlignmentRight: - drawPoint.x = constrainedSize.width - lineSize.width; - break; - } - NSUInteger stopGlyphIdx = glyphIdx; - NSUInteger lastRunIdx = currentRunIdx; - NSUInteger stopCharIdx = idx; - idx = indexCache.index; - if (currentRunIdx != indexCache.currentRunIdx) { - currentRunIdx = indexCache.currentRunIdx; - READ_RUN(); - READ_GLYPHS(); - } - glyphIdx = indexCache.glyphIndex; - for (NSUInteger drawIdx = currentRunIdx; drawIdx <= lastRunIdx; drawIdx++) { - if (drawIdx != currentRunIdx) { - currentRunIdx = drawIdx; - READ_RUN(); - READ_GLYPHS(); - } - NSUInteger numGlyphs; - if (drawIdx == lastRunIdx) { - numGlyphs = stopGlyphIdx - glyphIdx; - idx = stopCharIdx; - } else { - numGlyphs = glyphCount - glyphIdx; - idx = nextRunStart; - } - CGContextSetFont(ctx, currentFont.cgFont); - CGContextSetFontSize(ctx, currentFont.pointSize); - // calculate the fragment size - CGFloat fragmentWidth = 0; - for (NSUInteger g = 0; g < numGlyphs; g++) { - fragmentWidth += advances[glyphIdx + g]; - } - - if (!ignoreColor) { - UIColor *foregroundColor = getValueOrDefaultForRun(currentRun, ZForegroundColorAttributeName); - UIColor *backgroundColor = getValueOrDefaultForRun(currentRun, ZBackgroundColorAttributeName); - if (backgroundColor != nil && ![backgroundColor isEqual:[UIColor clearColor]]) { - [backgroundColor setFill]; - UIRectFillUsingBlendMode((CGRect){ drawPoint, { fragmentWidth, lineSize.height } }, kCGBlendModeNormal); - } - [foregroundColor setFill]; - } - - CGContextShowGlyphsAtPoint(ctx, drawPoint.x, drawPoint.y + lineAscender, &glyphs[glyphIdx], numGlyphs); - NSNumber *underlineStyle = getValueOrDefaultForRun(currentRun, ZUnderlineStyleAttributeName); - if ([underlineStyle integerValue] & ZUnderlineStyleMask) { - // we only support single for the time being - UIRectFill(CGRectMake(drawPoint.x, drawPoint.y + lineAscender, fragmentWidth, 1)); - } - drawPoint.x += fragmentWidth; - glyphIdx += numGlyphs; - } - drawPoint.y += lineSize.height; - } - idx += skipCount; - glyphIdx += skipCount; - lineCount++; - } else { - // Mark a wrap point before spaces and after any stretch of non-alpha characters - BOOL markWrap = NO; - if (characters[idx] == (unichar)' ') { - markWrap = YES; - } else if ([alphaCharset characterIsMember:characters[idx]]) { - if (!inAlpha) { - markWrap = YES; - inAlpha = YES; - } - } else { - inAlpha = NO; - } - if (markWrap) { - lastWrapCache = (__typeof__(lastWrapCache)){ - .index = idx, - .glyphIndex = glyphIdx, - .currentRunIdx = currentRunIdx, - .lineSize = lineSize - }; - } - lineSize.width += advances[glyphIdx]; - glyphIdx++; - idx++; - if (idx < len && UnicharIsHighSurrogate(characters[idx-1]) && UnicharIsLowSurrogate(characters[idx])) { - // skip the second half of the surrogate pair - idx++; - } - } - } - } - CFRelease(fontTableMap); - free(glyphs); - free(advances); - free(characters); - -#undef READ_GLYPHS -#undef READ_RUN - - return retValue; -} - -static NSArray *attributeRunForFont(ZFont *font) { - return [NSArray arrayWithObject:[ZAttributeRun attributeRunWithIndex:0 - attributes:[NSDictionary dictionaryWithObject:font - forKey:ZFontAttributeName]]]; -} - -static CGSize drawTextInRect(CGRect rect, NSString *text, NSArray *attributes, UILineBreakMode lineBreakMode, - UITextAlignment alignment, NSUInteger numberOfLines, BOOL ignoreColor) { - CGContextRef ctx = UIGraphicsGetCurrentContext(); - - CGContextSaveGState(ctx); - - // flip it upside-down because our 0,0 is upper-left, whereas ttfs are for screens where 0,0 is lower-left - CGAffineTransform textTransform = CGAffineTransformMake(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); - CGContextSetTextMatrix(ctx, textTransform); - - CGContextTranslateCTM(ctx, rect.origin.x, rect.origin.y); - - CGContextSetTextDrawingMode(ctx, kCGTextFill); - CGSize size = drawOrSizeTextConstrainedToSize(YES, text, attributes, rect.size, numberOfLines, lineBreakMode, alignment, ignoreColor); - - CGContextRestoreGState(ctx); - - return size; -} - -@implementation NSString (FontLabelStringDrawing) -// CGFontRef-based methods -- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize { - return [self sizeWithZFont:[ZFont fontWithCGFont:font size:pointSize]]; -} - -- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize constrainedToSize:(CGSize)size { - return [self sizeWithZFont:[ZFont fontWithCGFont:font size:pointSize] constrainedToSize:size]; -} - -- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize constrainedToSize:(CGSize)size - lineBreakMode:(UILineBreakMode)lineBreakMode { - return [self sizeWithZFont:[ZFont fontWithCGFont:font size:pointSize] constrainedToSize:size lineBreakMode:lineBreakMode]; -} - -- (CGSize)drawAtPoint:(CGPoint)point withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize { - return [self drawAtPoint:point withZFont:[ZFont fontWithCGFont:font size:pointSize]]; -} - -- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize { - return [self drawInRect:rect withZFont:[ZFont fontWithCGFont:font size:pointSize]]; -} - -- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize lineBreakMode:(UILineBreakMode)lineBreakMode { - return [self drawInRect:rect withZFont:[ZFont fontWithCGFont:font size:pointSize] lineBreakMode:lineBreakMode]; -} - -- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize - lineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment { - return [self drawInRect:rect withZFont:[ZFont fontWithCGFont:font size:pointSize] lineBreakMode:lineBreakMode alignment:alignment]; -} - -// ZFont-based methods -- (CGSize)sizeWithZFont:(ZFont *)font { - CGSize size = drawOrSizeTextConstrainedToSize(NO, self, attributeRunForFont(font), CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX), 1, - UILineBreakModeClip, UITextAlignmentLeft, YES); - return CGSizeMake(ceilf(size.width), ceilf(size.height)); -} - -- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size { - return [self sizeWithZFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap]; -} - -/* - According to experimentation with UIStringDrawing, this can actually return a CGSize whose height is greater - than the one passed in. The two cases are as follows: - 1. If the given size parameter's height is smaller than a single line, the returned value will - be the height of one line. - 2. If the given size parameter's height falls between multiples of a line height, and the wrapped string - actually extends past the size.height, and the difference between size.height and the previous multiple - of a line height is >= the font's ascender, then the returned size's height is extended to the next line. - To put it simply, if the baseline point of a given line falls in the given size, the entire line will - be present in the output size. - */ -- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode { - size = drawOrSizeTextConstrainedToSize(NO, self, attributeRunForFont(font), size, 0, lineBreakMode, UITextAlignmentLeft, YES); - return CGSizeMake(ceilf(size.width), ceilf(size.height)); -} - -- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode - numberOfLines:(NSUInteger)numberOfLines { - size = drawOrSizeTextConstrainedToSize(NO, self, attributeRunForFont(font), size, numberOfLines, lineBreakMode, UITextAlignmentLeft, YES); - return CGSizeMake(ceilf(size.width), ceilf(size.height)); -} - -- (CGSize)drawAtPoint:(CGPoint)point withZFont:(ZFont *)font { - return [self drawAtPoint:point forWidth:CGFLOAT_MAX withZFont:font lineBreakMode:UILineBreakModeClip]; -} - -- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode { - return drawTextInRect((CGRect){ point, { width, CGFLOAT_MAX } }, self, attributeRunForFont(font), lineBreakMode, UITextAlignmentLeft, 1, YES); -} - -- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font { - return [self drawInRect:rect withZFont:font lineBreakMode:UILineBreakModeWordWrap]; -} - -- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode { - return [self drawInRect:rect withZFont:font lineBreakMode:lineBreakMode alignment:UITextAlignmentLeft]; -} - -- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode - alignment:(UITextAlignment)alignment { - return drawTextInRect(rect, self, attributeRunForFont(font), lineBreakMode, alignment, 0, YES); -} - -- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode - alignment:(UITextAlignment)alignment numberOfLines:(NSUInteger)numberOfLines { - return drawTextInRect(rect, self, attributeRunForFont(font), lineBreakMode, alignment, numberOfLines, YES); -} -@end - -@implementation ZAttributedString (ZAttributedStringDrawing) -- (CGSize)size { - CGSize size = drawOrSizeTextConstrainedToSize(NO, self.string, self.attributes, CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX), 1, - UILineBreakModeClip, UITextAlignmentLeft, NO); - return CGSizeMake(ceilf(size.width), ceilf(size.height)); -} - -- (CGSize)sizeConstrainedToSize:(CGSize)size { - return [self sizeConstrainedToSize:size lineBreakMode:UILineBreakModeWordWrap]; -} - -- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode { - size = drawOrSizeTextConstrainedToSize(NO, self.string, self.attributes, size, 0, lineBreakMode, UITextAlignmentLeft, NO); - return CGSizeMake(ceilf(size.width), ceilf(size.height)); -} - -- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode - numberOfLines:(NSUInteger)numberOfLines { - size = drawOrSizeTextConstrainedToSize(NO, self.string, self.attributes, size, numberOfLines, lineBreakMode, UITextAlignmentLeft, NO); - return CGSizeMake(ceilf(size.width), ceilf(size.height)); -} - -- (CGSize)drawAtPoint:(CGPoint)point { - return [self drawAtPoint:point forWidth:CGFLOAT_MAX lineBreakMode:UILineBreakModeClip]; -} - -- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode { - return drawTextInRect((CGRect){ point, { width, CGFLOAT_MAX } }, self.string, self.attributes, lineBreakMode, UITextAlignmentLeft, 1, NO); -} - -- (CGSize)drawInRect:(CGRect)rect { - return [self drawInRect:rect withLineBreakMode:UILineBreakModeWordWrap]; -} - -- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode { - return [self drawInRect:rect withLineBreakMode:lineBreakMode alignment:UITextAlignmentLeft]; -} - -- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment { - return drawTextInRect(rect, self.string, self.attributes, lineBreakMode, alignment, 0, NO); -} - -- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment - numberOfLines:(NSUInteger)numberOfLines { - return drawTextInRect(rect, self.string, self.attributes, lineBreakMode, alignment, numberOfLines, NO); -} -@end diff --git a/Example/libs/FontLabel/FontManager.h b/Example/libs/FontLabel/FontManager.h deleted file mode 100644 index 1592b8a..0000000 --- a/Example/libs/FontLabel/FontManager.h +++ /dev/null @@ -1,85 +0,0 @@ -// -// FontManager.h -// FontLabel -// -// Created by Kevin Ballard on 5/5/09. -// Copyright © 2009 Zynga Game Networks -// -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#import -#import - -@class ZFont; - -@interface FontManager : NSObject { - CFMutableDictionaryRef fonts; - NSMutableDictionary *urls; -} -+ (FontManager *)sharedManager; -/*! - @method - @abstract Loads a TTF font from the main bundle - @param filename The name of the font file to load (with or without extension). - @return YES if the font was loaded, NO if an error occurred - @discussion If the font has already been loaded, this method does nothing and returns YES. - This method first attempts to load the font by appending .ttf to the filename. - If that file does not exist, it tries the filename exactly as given. -*/ -- (BOOL)loadFont:(NSString *)filename; -/*! - @method - @abstract Loads a font from the given file URL - @param url A file URL that points to a font file - @return YES if the font was loaded, NO if an error occurred - @discussion If the font has already been loaded, this method does nothing and returns YES. -*/ -- (BOOL)loadFontURL:(NSURL *)url; -/*! - @method - @abstract Returns the loaded font with the given filename - @param filename The name of the font file that was given to -loadFont: - @return A CGFontRef, or NULL if the specified font cannot be found - @discussion If the font has not been loaded yet, -loadFont: will be - called with the given name first. -*/ -- (CGFontRef)fontWithName:(NSString *)filename __AVAILABILITY_INTERNAL_DEPRECATED; -/*! - @method - @abstract Returns a ZFont object corresponding to the loaded font with the given filename and point size - @param filename The name of the font file that was given to -loadFont: - @param pointSize The point size of the font - @return A ZFont, or NULL if the specified font cannot be found - @discussion If the font has not been loaded yet, -loadFont: will be - called with the given name first. -*/ -- (ZFont *)zFontWithName:(NSString *)filename pointSize:(CGFloat)pointSize; -/*! - @method - @abstract Returns a ZFont object corresponding to the loaded font with the given file URL and point size - @param url A file URL that points to a font file - @param pointSize The point size of the font - @return A ZFont, or NULL if the specified font cannot be loaded - @discussion If the font has not been loaded yet, -loadFontURL: will be called with the given URL first. -*/ -- (ZFont *)zFontWithURL:(NSURL *)url pointSize:(CGFloat)pointSize; -/*! - @method - @abstract Returns a CFArrayRef of all loaded CGFont objects - @return A CFArrayRef of all loaded CGFont objects - @description You are responsible for releasing the CFArrayRef -*/ -- (CFArrayRef)copyAllFonts; -@end diff --git a/Example/libs/FontLabel/FontManager.m b/Example/libs/FontLabel/FontManager.m deleted file mode 100644 index c961de1..0000000 --- a/Example/libs/FontLabel/FontManager.m +++ /dev/null @@ -1,124 +0,0 @@ -// -// FontManager.m -// FontLabel -// -// Created by Kevin Ballard on 5/5/09. -// Copyright © 2009 Zynga Game Networks -// -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#import "FontManager.h" -#import "ZFont.h" -#import "CCConfiguration.h" - -static FontManager *sharedFontManager = nil; - -@implementation FontManager -+ (FontManager *)sharedManager { - @synchronized(self) { - if (sharedFontManager == nil) { - sharedFontManager = [[self alloc] init]; - } - } - return sharedFontManager; -} - -- (id)init { - if ((self = [super init])) { - fonts = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - urls = [[NSMutableDictionary alloc] init]; - } - return self; -} - -- (BOOL)loadFont:(NSString *)filename { - NSString *fontPath = [[NSBundle mainBundle] pathForResource:filename ofType:@"ttf"]; - if (fontPath == nil) { - fontPath = [[NSBundle mainBundle] pathForResource:filename ofType:nil]; - } - if (fontPath == nil) return NO; - - NSURL *url = [NSURL fileURLWithPath:fontPath]; - if ([self loadFontURL:url]) { - [urls setObject:url forKey:filename]; - return YES; - } - return NO; -} - -- (BOOL)loadFontURL:(NSURL *)url { - CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((CFURLRef)url); - if (fontDataProvider == NULL) return NO; - CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider); - CGDataProviderRelease(fontDataProvider); - if (newFont == NULL) return NO; - - CFDictionarySetValue(fonts, url, newFont); - CGFontRelease(newFont); - return YES; -} - -- (CGFontRef)fontWithName:(NSString *)filename { - CGFontRef font = NULL; - NSURL *url = [urls objectForKey:filename]; - if (url == nil && [self loadFont:filename]) { - url = [urls objectForKey:filename]; - } - if (url != nil) { - font = (CGFontRef)CFDictionaryGetValue(fonts, url); - } - return font; -} - -- (ZFont *)zFontWithName:(NSString *)filename pointSize:(CGFloat)pointSize { - NSURL *url = [urls objectForKey:filename]; - if (url == nil && [self loadFont:filename]) { - url = [urls objectForKey:filename]; - } - if (url != nil) { - CGFontRef cgFont = (CGFontRef)CFDictionaryGetValue(fonts, url); - if (cgFont != NULL) { - return [ZFont fontWithCGFont:cgFont size:pointSize]; - } - } - return nil; -} - -- (ZFont *)zFontWithURL:(NSURL *)url pointSize:(CGFloat)pointSize { - CGFontRef cgFont = (CGFontRef)CFDictionaryGetValue(fonts, url); - if (cgFont == NULL && [self loadFontURL:url]) { - cgFont = (CGFontRef)CFDictionaryGetValue(fonts, url); - } - if (cgFont != NULL) { - return [ZFont fontWithCGFont:cgFont size:pointSize]; - } - return nil; -} - -- (CFArrayRef)copyAllFonts { - CFIndex count = CFDictionaryGetCount(fonts); - CGFontRef *values = (CGFontRef *)malloc(sizeof(CGFontRef) * count); - CFDictionaryGetKeysAndValues(fonts, NULL, (const void **)values); - CFArrayRef array = CFArrayCreate(NULL, (const void **)values, count, &kCFTypeArrayCallBacks); - free(values); - return array; -} - -- (void)dealloc { - CFRelease(fonts); - [urls release]; - [super dealloc]; -} -@end diff --git a/Example/libs/FontLabel/ZAttributedString.h b/Example/libs/FontLabel/ZAttributedString.h deleted file mode 100644 index e194c81..0000000 --- a/Example/libs/FontLabel/ZAttributedString.h +++ /dev/null @@ -1,77 +0,0 @@ -// -// ZAttributedString.h -// FontLabel -// -// Created by Kevin Ballard on 9/22/09. -// Copyright 2009 Zynga Game Networks. All rights reserved. -// - -#import - -#if NS_BLOCKS_AVAILABLE -#define Z_BLOCKS 1 -#else -// set this to 1 if you are using PLBlocks -#define Z_BLOCKS 0 -#endif - -#if Z_BLOCKS -enum { - ZAttributedStringEnumerationReverse = (1UL << 1), - ZAttributedStringEnumerationLongestEffectiveRangeNotRequired = (1UL << 20) -}; -typedef NSUInteger ZAttributedStringEnumerationOptions; -#endif - -@interface ZAttributedString : NSObject { - NSMutableString *_buffer; - NSMutableArray *_attributes; -} -@property (nonatomic, readonly) NSUInteger length; -@property (nonatomic, readonly) NSString *string; -- (id)initWithAttributedString:(ZAttributedString *)attr; -- (id)initWithString:(NSString *)str; -- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attributes; -- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange; -- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit; -- (ZAttributedString *)attributedSubstringFromRange:(NSRange)aRange; -- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange; -- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit; -#if Z_BLOCKS -- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts - usingBlock:(void (^)(id value, NSRange range, BOOL *stop))block; -- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts - usingBlock:(void (^)(NSDictionary *attrs, NSRange range, BOOL *stop))block; -#endif -- (BOOL)isEqualToAttributedString:(ZAttributedString *)otherString; -@end - -@interface ZMutableAttributedString : ZAttributedString { -} -- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range; -- (void)addAttributes:(NSDictionary *)attributes range:(NSRange)range; -- (void)appendAttributedString:(ZAttributedString *)str; -- (void)deleteCharactersInRange:(NSRange)range; -- (void)insertAttributedString:(ZAttributedString *)str atIndex:(NSUInteger)idx; -- (void)removeAttribute:(NSString *)name range:(NSRange)range; -- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(ZAttributedString *)str; -- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str; -- (void)setAttributedString:(ZAttributedString *)str; -- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range; -@end - -extern NSString * const ZFontAttributeName; -extern NSString * const ZForegroundColorAttributeName; -extern NSString * const ZBackgroundColorAttributeName; -extern NSString * const ZUnderlineStyleAttributeName; - -enum { - ZUnderlineStyleNone = 0x00, - ZUnderlineStyleSingle = 0x01 -}; -#define ZUnderlineStyleMask 0x00FF - -enum { - ZUnderlinePatternSolid = 0x0000 -}; -#define ZUnderlinePatternMask 0xFF00 diff --git a/Example/libs/FontLabel/ZAttributedString.m b/Example/libs/FontLabel/ZAttributedString.m deleted file mode 100644 index e1557c0..0000000 --- a/Example/libs/FontLabel/ZAttributedString.m +++ /dev/null @@ -1,595 +0,0 @@ -// -// ZAttributedString.m -// FontLabel -// -// Created by Kevin Ballard on 9/22/09. -// Copyright 2009 Zynga Game Networks. All rights reserved. -// - -#import "ZAttributedString.h" -#import "ZAttributedStringPrivate.h" - -@interface ZAttributedString () -- (NSUInteger)indexOfEffectiveAttributeRunForIndex:(NSUInteger)index; -- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange uniquingOnName:(NSString *)attributeName; -- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange - inRange:(NSRange)rangeLimit uniquingOnName:(NSString *)attributeName; -@end - -@interface ZAttributedString () -@property (nonatomic, readonly) NSArray *attributes; -@end - -@implementation ZAttributedString -@synthesize string = _buffer; -@synthesize attributes = _attributes; - -- (id)initWithAttributedString:(ZAttributedString *)attr { - NSParameterAssert(attr != nil); - if ((self = [super init])) { - _buffer = [attr->_buffer mutableCopy]; - _attributes = [[NSMutableArray alloc] initWithArray:attr->_attributes copyItems:YES]; - } - return self; -} - -- (id)initWithString:(NSString *)str { - return [self initWithString:str attributes:nil]; -} - -- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attributes { - if ((self = [super init])) { - _buffer = [str mutableCopy]; - _attributes = [[NSMutableArray alloc] initWithObjects:[ZAttributeRun attributeRunWithIndex:0 attributes:attributes], nil]; - } - return self; -} - -- (id)init { - return [self initWithString:@"" attributes:nil]; -} - -- (id)initWithCoder:(NSCoder *)decoder { - if ((self = [super init])) { - _buffer = [[decoder decodeObjectForKey:@"buffer"] mutableCopy]; - _attributes = [[decoder decodeObjectForKey:@"attributes"] mutableCopy]; - } - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder { - [aCoder encodeObject:_buffer forKey:@"buffer"]; - [aCoder encodeObject:_attributes forKey:@"attributes"]; -} - -- (id)copyWithZone:(NSZone *)zone { - return [self retain]; -} - -- (id)mutableCopyWithZone:(NSZone *)zone { - return [(ZMutableAttributedString*)[ZMutableAttributedString allocWithZone:zone] initWithAttributedString:self]; -} - -- (NSUInteger)length { - return [_buffer length]; -} - -- (NSString *)description { - NSMutableArray *components = [NSMutableArray arrayWithCapacity:[_attributes count]*2]; - NSRange range = NSMakeRange(0, 0); - for (NSUInteger i = 0; i <= [_attributes count]; i++) { - range.location = NSMaxRange(range); - ZAttributeRun *run; - if (i < [_attributes count]) { - run = [_attributes objectAtIndex:i]; - range.length = run.index - range.location; - } else { - run = nil; - range.length = [_buffer length] - range.location; - } - if (range.length > 0) { - [components addObject:[NSString stringWithFormat:@"\"%@\"", [_buffer substringWithRange:range]]]; - } - if (run != nil) { - NSMutableArray *attrDesc = [NSMutableArray arrayWithCapacity:[run.attributes count]]; - for (id key in run.attributes) { - [attrDesc addObject:[NSString stringWithFormat:@"%@: %@", key, [run.attributes objectForKey:key]]]; - } - [components addObject:[NSString stringWithFormat:@"{%@}", [attrDesc componentsJoinedByString:@", "]]]; - } - } - return [NSString stringWithFormat:@"%@", [components componentsJoinedByString:@" "]]; -} - -- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange { - NSParameterAssert(attributeName != nil); - return [[self attributesAtIndex:index effectiveRange:aRange uniquingOnName:attributeName] objectForKey:attributeName]; -} - -- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit { - NSParameterAssert(attributeName != nil); - return [[self attributesAtIndex:index longestEffectiveRange:aRange inRange:rangeLimit uniquingOnName:attributeName] objectForKey:attributeName]; -} - -- (ZAttributedString *)attributedSubstringFromRange:(NSRange)aRange { - if (NSMaxRange(aRange) > [_buffer length]) { - @throw [NSException exceptionWithName:NSRangeException reason:@"range was outisde of the attributed string" userInfo:nil]; - } - ZMutableAttributedString *newStr = [self mutableCopy]; - if (aRange.location > 0) { - [newStr deleteCharactersInRange:NSMakeRange(0, aRange.location)]; - } - if (NSMaxRange(aRange) < [_buffer length]) { - [newStr deleteCharactersInRange:NSMakeRange(aRange.length, [_buffer length] - NSMaxRange(aRange))]; - } - return [newStr autorelease]; -} - -- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange { - return [NSDictionary dictionaryWithDictionary:[self attributesAtIndex:index effectiveRange:aRange uniquingOnName:nil]]; -} - -- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit { - return [NSDictionary dictionaryWithDictionary:[self attributesAtIndex:index longestEffectiveRange:aRange inRange:rangeLimit uniquingOnName:nil]]; -} - -#if Z_BLOCKS -// Warning: this code has not been tested. The only guarantee is that it compiles. -- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts - usingBlock:(void (^)(id, NSRange, BOOL*))block { - if (opts & ZAttributedStringEnumerationLongestEffectiveRangeNotRequired) { - [self enumerateAttributesInRange:enumerationRange options:opts usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) { - id value = [attrs objectForKey:attrName]; - if (value != nil) { - block(value, range, stop); - } - }]; - } else { - __block id oldValue = nil; - __block NSRange effectiveRange = NSMakeRange(0, 0); - [self enumerateAttributesInRange:enumerationRange options:opts usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) { - id value = [attrs objectForKey:attrName]; - if (oldValue == nil) { - oldValue = value; - effectiveRange = range; - } else if (value != nil && [oldValue isEqual:value]) { - // combine the attributes - effectiveRange = NSUnionRange(effectiveRange, range); - } else { - BOOL innerStop = NO; - block(oldValue, effectiveRange, &innerStop); - if (innerStop) { - *stop = YES; - oldValue = nil; - } else { - oldValue = value; - } - } - }]; - if (oldValue != nil) { - BOOL innerStop = NO; // necessary for the block, but unused - block(oldValue, effectiveRange, &innerStop); - } - } -} - -- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts - usingBlock:(void (^)(NSDictionary*, NSRange, BOOL*))block { - // copy the attributes so we can mutate the string if necessary during enumeration - // also clip the array during copy to only the subarray of attributes that cover the requested range - NSArray *attrs; - if (NSEqualRanges(enumerationRange, NSMakeRange(0, 0))) { - attrs = [NSArray arrayWithArray:_attributes]; - } else { - // in this binary search, last is the first run after the range - NSUInteger first = 0, last = [_attributes count]; - while (last > first+1) { - NSUInteger pivot = (last + first) / 2; - ZAttributeRun *run = [_attributes objectAtIndex:pivot]; - if (run.index < enumerationRange.location) { - first = pivot; - } else if (run.index >= NSMaxRange(enumerationRange)) { - last = pivot; - } - } - attrs = [_attributes subarrayWithRange:NSMakeRange(first, last-first)]; - } - if (opts & ZAttributedStringEnumerationReverse) { - NSUInteger end = [_buffer length]; - for (ZAttributeRun *run in [attrs reverseObjectEnumerator]) { - BOOL stop = NO; - NSUInteger start = run.index; - // clip to enumerationRange - start = MAX(start, enumerationRange.location); - end = MIN(end, NSMaxRange(enumerationRange)); - block(run.attributes, NSMakeRange(start, end - start), &stop); - if (stop) break; - end = run.index; - } - } else { - NSUInteger start = 0; - ZAttributeRun *run = [attrs objectAtIndex:0]; - NSInteger offset = 0; - NSInteger oldLength = [_buffer length]; - for (NSUInteger i = 1;;i++) { - NSUInteger end; - if (i >= [attrs count]) { - end = oldLength; - } else { - end = [[attrs objectAtIndex:i] index]; - } - BOOL stop = NO; - NSUInteger clippedStart = MAX(start, enumerationRange.location); - NSUInteger clippedEnd = MIN(end, NSMaxRange(enumerationRange)); - block(run.attributes, NSMakeRange(clippedStart + offset, clippedEnd - start), &stop); - if (stop || i >= [attrs count]) break; - start = end; - NSUInteger newLength = [_buffer length]; - offset += (newLength - oldLength); - oldLength = newLength; - } - } -} -#endif - -- (BOOL)isEqualToAttributedString:(ZAttributedString *)otherString { - return ([_buffer isEqualToString:otherString->_buffer] && [_attributes isEqualToArray:otherString->_attributes]); -} - -- (BOOL)isEqual:(id)object { - return [object isKindOfClass:[ZAttributedString class]] && [self isEqualToAttributedString:(ZAttributedString *)object]; -} - -#pragma mark - - -- (NSUInteger)indexOfEffectiveAttributeRunForIndex:(NSUInteger)index { - NSUInteger first = 0, last = [_attributes count]; - while (last > first + 1) { - NSUInteger pivot = (last + first) / 2; - ZAttributeRun *run = [_attributes objectAtIndex:pivot]; - if (run.index > index) { - last = pivot; - } else if (run.index < index) { - first = pivot; - } else { - first = pivot; - break; - } - } - return first; -} - -- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange uniquingOnName:(NSString *)attributeName { - if (index >= [_buffer length]) { - @throw [NSException exceptionWithName:NSRangeException reason:@"index beyond range of attributed string" userInfo:nil]; - } - NSUInteger runIndex = [self indexOfEffectiveAttributeRunForIndex:index]; - ZAttributeRun *run = [_attributes objectAtIndex:runIndex]; - if (aRange != NULL) { - aRange->location = run.index; - runIndex++; - if (runIndex < [_attributes count]) { - aRange->length = [[_attributes objectAtIndex:runIndex] index] - aRange->location; - } else { - aRange->length = [_buffer length] - aRange->location; - } - } - return run.attributes; -} -- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange - inRange:(NSRange)rangeLimit uniquingOnName:(NSString *)attributeName { - if (index >= [_buffer length]) { - @throw [NSException exceptionWithName:NSRangeException reason:@"index beyond range of attributed string" userInfo:nil]; - } else if (NSMaxRange(rangeLimit) > [_buffer length]) { - @throw [NSException exceptionWithName:NSRangeException reason:@"rangeLimit beyond range of attributed string" userInfo:nil]; - } - NSUInteger runIndex = [self indexOfEffectiveAttributeRunForIndex:index]; - ZAttributeRun *run = [_attributes objectAtIndex:runIndex]; - if (aRange != NULL) { - if (attributeName != nil) { - id value = [run.attributes objectForKey:attributeName]; - NSUInteger endRunIndex = runIndex+1; - runIndex--; - // search backwards - while (true) { - if (run.index <= rangeLimit.location) { - break; - } - ZAttributeRun *prevRun = [_attributes objectAtIndex:runIndex]; - id prevValue = [prevRun.attributes objectForKey:attributeName]; - if (prevValue == value || (value != nil && [prevValue isEqual:value])) { - runIndex--; - run = prevRun; - } else { - break; - } - } - // search forwards - ZAttributeRun *endRun = nil; - while (endRunIndex < [_attributes count]) { - ZAttributeRun *nextRun = [_attributes objectAtIndex:endRunIndex]; - if (nextRun.index >= NSMaxRange(rangeLimit)) { - endRun = nextRun; - break; - } - id nextValue = [nextRun.attributes objectForKey:attributeName]; - if (nextValue == value || (value != nil && [nextValue isEqual:value])) { - endRunIndex++; - } else { - endRun = nextRun; - break; - } - } - aRange->location = MAX(run.index, rangeLimit.location); - aRange->length = MIN((endRun ? endRun.index : [_buffer length]), NSMaxRange(rangeLimit)) - aRange->location; - } else { - // with no attribute name, we don't need to do any real searching, - // as we already guarantee each run has unique attributes. - // just make sure to clip the range to the rangeLimit - aRange->location = MAX(run.index, rangeLimit.location); - ZAttributeRun *endRun = (runIndex+1 < [_attributes count] ? [_attributes objectAtIndex:runIndex+1] : nil); - aRange->length = MIN((endRun ? endRun.index : [_buffer length]), NSMaxRange(rangeLimit)) - aRange->location; - } - } - return run.attributes; -} - -- (void)dealloc { - [_buffer release]; - [_attributes release]; - [super dealloc]; -} -@end - -@interface ZMutableAttributedString () -- (void)cleanupAttributesInRange:(NSRange)range; -- (NSRange)rangeOfAttributeRunsForRange:(NSRange)range; -- (void)offsetRunsInRange:(NSRange )range byOffset:(NSInteger)offset; -@end - -@implementation ZMutableAttributedString -- (id)copyWithZone:(NSZone *)zone { - return [(ZMutableAttributedString*)[ZAttributedString allocWithZone:zone] initWithAttributedString:self]; -} - -- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range { - range = [self rangeOfAttributeRunsForRange:range]; - for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) { - [run.attributes setObject:value forKey:name]; - } - [self cleanupAttributesInRange:range]; -} - -- (void)addAttributes:(NSDictionary *)attributes range:(NSRange)range { - range = [self rangeOfAttributeRunsForRange:range]; - for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) { - [run.attributes addEntriesFromDictionary:attributes]; - } - [self cleanupAttributesInRange:range]; -} - -- (void)appendAttributedString:(ZAttributedString *)str { - [self insertAttributedString:str atIndex:[_buffer length]]; -} - -- (void)deleteCharactersInRange:(NSRange)range { - NSRange runRange = [self rangeOfAttributeRunsForRange:range]; - [_buffer replaceCharactersInRange:range withString:@""]; - [_attributes removeObjectsInRange:runRange]; - for (NSUInteger i = runRange.location; i < [_attributes count]; i++) { - ZAttributeRun *run = [_attributes objectAtIndex:i]; - ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:(run.index - range.length) attributes:run.attributes]; - [_attributes replaceObjectAtIndex:i withObject:newRun]; - [newRun release]; - } - [self cleanupAttributesInRange:NSMakeRange(runRange.location, 0)]; -} - -- (void)insertAttributedString:(ZAttributedString *)str atIndex:(NSUInteger)idx { - [self replaceCharactersInRange:NSMakeRange(idx, 0) withAttributedString:str]; -} - -- (void)removeAttribute:(NSString *)name range:(NSRange)range { - range = [self rangeOfAttributeRunsForRange:range]; - for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) { - [run.attributes removeObjectForKey:name]; - } - [self cleanupAttributesInRange:range]; -} - -- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(ZAttributedString *)str { - NSRange replaceRange = [self rangeOfAttributeRunsForRange:range]; - NSInteger offset = [str->_buffer length] - range.length; - [_buffer replaceCharactersInRange:range withString:str->_buffer]; - [_attributes replaceObjectsInRange:replaceRange withObjectsFromArray:str->_attributes]; - NSRange newRange = NSMakeRange(replaceRange.location, [str->_attributes count]); - [self offsetRunsInRange:newRange byOffset:range.location]; - [self offsetRunsInRange:NSMakeRange(NSMaxRange(newRange), [_attributes count] - NSMaxRange(newRange)) byOffset:offset]; - [self cleanupAttributesInRange:NSMakeRange(newRange.location, 0)]; - [self cleanupAttributesInRange:NSMakeRange(NSMaxRange(newRange), 0)]; -} - -- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str { - [self replaceCharactersInRange:range withAttributedString:[[[ZAttributedString alloc] initWithString:str] autorelease]]; -} - -- (void)setAttributedString:(ZAttributedString *)str { - [_buffer release], _buffer = [str->_buffer mutableCopy]; - [_attributes release], _attributes = [str->_attributes mutableCopy]; -} - -- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range { - range = [self rangeOfAttributeRunsForRange:range]; - for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) { - [run.attributes setDictionary:attributes]; - } - [self cleanupAttributesInRange:range]; -} - -#pragma mark - - -// splits the existing runs to provide one or more new runs for the given range -- (NSRange)rangeOfAttributeRunsForRange:(NSRange)range { - NSParameterAssert(NSMaxRange(range) <= [_buffer length]); - - // find (or create) the first run - NSUInteger first = 0; - ZAttributeRun *lastRun = nil; - for (;;first++) { - if (first >= [_attributes count]) { - // we didn't find a run - first = [_attributes count]; - ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:range.location attributes:lastRun.attributes]; - [_attributes addObject:newRun]; - [newRun release]; - break; - } - ZAttributeRun *run = [_attributes objectAtIndex:first]; - if (run.index == range.location) { - break; - } else if (run.index > range.location) { - ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:range.location attributes:lastRun.attributes]; - [_attributes insertObject:newRun atIndex:first]; - [newRun release]; - break; - } - lastRun = run; - } - - if (((ZAttributeRun *)[_attributes lastObject]).index < NSMaxRange(range)) { - NSRange subrange = NSMakeRange(first, [_attributes count] - first); - if (NSMaxRange(range) < [_buffer length]) { - ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:NSMaxRange(range) attributes:(NSDictionary*)[[_attributes lastObject] attributes]]; - [_attributes addObject:newRun]; - [newRun release]; - } - return subrange; - } else { - // find the last run within and the first run after the range - NSUInteger lastIn = first, firstAfter = [_attributes count]-1; - while (firstAfter > lastIn + 1) { - NSUInteger idx = (firstAfter + lastIn) / 2; - ZAttributeRun *run = [_attributes objectAtIndex:idx]; - if (run.index < range.location) { - lastIn = idx; - } else if (run.index > range.location) { - firstAfter = idx; - } else { - // this is definitively the first run after the range - firstAfter = idx; - break; - } - } - if ([[_attributes objectAtIndex:firstAfter] index] > NSMaxRange(range)) { - // the first after is too far after, insert another run! - ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:NSMaxRange(range) - attributes:(NSDictionary*)[[_attributes objectAtIndex:firstAfter-1] attributes]]; - [_attributes insertObject:newRun atIndex:firstAfter]; - [newRun release]; - } - return NSMakeRange(lastIn, firstAfter - lastIn); - } -} - -- (void)cleanupAttributesInRange:(NSRange)range { - // expand the range to include one surrounding attribute on each side - if (range.location > 0) { - range.location -= 1; - range.length += 1; - } - if (NSMaxRange(range) < [_attributes count]) { - range.length += 1; - } else { - // make sure the range is capped to the attributes count - range.length = [_attributes count] - range.location; - } - if (range.length == 0) return; - ZAttributeRun *lastRun = [_attributes objectAtIndex:range.location]; - for (NSUInteger i = range.location+1; i < NSMaxRange(range);) { - ZAttributeRun *run = [_attributes objectAtIndex:i]; - if ([lastRun.attributes isEqualToDictionary:run.attributes]) { - [_attributes removeObjectAtIndex:i]; - range.length -= 1; - } else { - lastRun = run; - i++; - } - } -} - -- (void)offsetRunsInRange:(NSRange)range byOffset:(NSInteger)offset { - for (NSUInteger i = range.location; i < NSMaxRange(range); i++) { - ZAttributeRun *run = [_attributes objectAtIndex:i]; - ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:run.index + offset attributes:run.attributes]; - [_attributes replaceObjectAtIndex:i withObject:newRun]; - [newRun release]; - } -} -@end - -@implementation ZAttributeRun -@synthesize index = _index; -@synthesize attributes = _attributes; - -+ (id)attributeRunWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs { - return [[[self alloc] initWithIndex:idx attributes:attrs] autorelease]; -} - -- (id)initWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs { - if ((self = [super init])) { - _index = idx; - if (attrs == nil) { - _attributes = [[NSMutableDictionary alloc] init]; - } else { - _attributes = [attrs mutableCopy]; - } - } - return self; -} - -- (id)initWithCoder:(NSCoder *)decoder { - if ((self = [super init])) { - _index = [[decoder decodeObjectForKey:@"index"] unsignedIntegerValue]; - _attributes = [[decoder decodeObjectForKey:@"attributes"] mutableCopy]; - } - return self; -} - -- (id)init { - return [self initWithIndex:0 attributes:[NSDictionary dictionary]]; -} - -- (id)copyWithZone:(NSZone *)zone { - return [[ZAttributeRun allocWithZone:zone] initWithIndex:_index attributes:_attributes]; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder { - [aCoder encodeObject:[NSNumber numberWithUnsignedInteger:_index] forKey:@"index"]; - [aCoder encodeObject:_attributes forKey:@"attributes"]; -} - -- (NSString *)description { - NSMutableArray *components = [NSMutableArray arrayWithCapacity:[_attributes count]]; - for (id key in _attributes) { - [components addObject:[NSString stringWithFormat:@"%@=%@", key, [_attributes objectForKey:key]]]; - } - return [NSString stringWithFormat:@"<%@: %p index=%lu attributes={%@}>", - NSStringFromClass([self class]), self, (unsigned long)_index, [components componentsJoinedByString:@" "]]; -} - -- (BOOL)isEqual:(id)object { - if (![object isKindOfClass:[ZAttributeRun class]]) return NO; - ZAttributeRun *other = (ZAttributeRun *)object; - return _index == other->_index && [_attributes isEqualToDictionary:other->_attributes]; -} - -- (void)dealloc { - [_attributes release]; - [super dealloc]; -} -@end - -NSString * const ZFontAttributeName = @"ZFontAttributeName"; -NSString * const ZForegroundColorAttributeName = @"ZForegroundColorAttributeName"; -NSString * const ZBackgroundColorAttributeName = @"ZBackgroundColorAttributeName"; -NSString * const ZUnderlineStyleAttributeName = @"ZUnderlineStyleAttributeName"; diff --git a/Example/libs/FontLabel/ZAttributedStringPrivate.h b/Example/libs/FontLabel/ZAttributedStringPrivate.h deleted file mode 100644 index 1021d7b..0000000 --- a/Example/libs/FontLabel/ZAttributedStringPrivate.h +++ /dev/null @@ -1,24 +0,0 @@ -// -// ZAttributedStringPrivate.h -// FontLabel -// -// Created by Kevin Ballard on 9/23/09. -// Copyright 2009 Zynga Game Networks. All rights reserved. -// - -#import -#import "ZAttributedString.h" - -@interface ZAttributeRun : NSObject { - NSUInteger _index; - NSMutableDictionary *_attributes; -} -@property (nonatomic, readonly) NSUInteger index; -@property (nonatomic, readonly) NSMutableDictionary *attributes; -+ (id)attributeRunWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs; -- (id)initWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs; -@end - -@interface ZAttributedString (ZAttributedStringPrivate) -@property (nonatomic, readonly) NSArray *attributes; -@end diff --git a/Example/libs/FontLabel/ZFont.h b/Example/libs/FontLabel/ZFont.h deleted file mode 100644 index 05ae823..0000000 --- a/Example/libs/FontLabel/ZFont.h +++ /dev/null @@ -1,47 +0,0 @@ -// -// ZFont.h -// FontLabel -// -// Created by Kevin Ballard on 7/2/09. -// Copyright © 2009 Zynga Game Networks -// -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#import -#import - -@interface ZFont : NSObject { - CGFontRef _cgFont; - CGFloat _pointSize; - CGFloat _ratio; - NSString *_familyName; - NSString *_fontName; - NSString *_postScriptName; -} -@property (nonatomic, readonly) CGFontRef cgFont; -@property (nonatomic, readonly) CGFloat pointSize; -@property (nonatomic, readonly) CGFloat ascender; -@property (nonatomic, readonly) CGFloat descender; -@property (nonatomic, readonly) CGFloat leading; -@property (nonatomic, readonly) CGFloat xHeight; -@property (nonatomic, readonly) CGFloat capHeight; -@property (nonatomic, readonly) NSString *familyName; -@property (nonatomic, readonly) NSString *fontName; -@property (nonatomic, readonly) NSString *postScriptName; -+ (ZFont *)fontWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize; -+ (ZFont *)fontWithUIFont:(UIFont *)uiFont; -- (id)initWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize; -- (ZFont *)fontWithSize:(CGFloat)fontSize; -@end diff --git a/Example/libs/FontLabel/ZFont.m b/Example/libs/FontLabel/ZFont.m deleted file mode 100644 index a81f53b..0000000 --- a/Example/libs/FontLabel/ZFont.m +++ /dev/null @@ -1,171 +0,0 @@ -// -// ZFont.m -// FontLabel -// -// Created by Kevin Ballard on 7/2/09. -// Copyright © 2009 Zynga Game Networks -// -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#import "ZFont.h" - -@interface ZFont () -@property (nonatomic, readonly) CGFloat ratio; -- (NSString *)copyNameTableEntryForID:(UInt16)nameID; -@end - -@implementation ZFont -@synthesize cgFont=_cgFont, pointSize=_pointSize, ratio=_ratio; - -+ (ZFont *)fontWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize { - return [[[self alloc] initWithCGFont:cgFont size:fontSize] autorelease]; -} - -+ (ZFont *)fontWithUIFont:(UIFont *)uiFont { - NSParameterAssert(uiFont != nil); - CGFontRef cgFont = CGFontCreateWithFontName((CFStringRef)uiFont.fontName); - ZFont *zFont = [[self alloc] initWithCGFont:cgFont size:uiFont.pointSize]; - CGFontRelease(cgFont); - return [zFont autorelease]; -} - -- (id)initWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize { - if ((self = [super init])) { - _cgFont = CGFontRetain(cgFont); - _pointSize = fontSize; - _ratio = fontSize/CGFontGetUnitsPerEm(cgFont); - } - return self; -} - -- (id)init { - NSAssert(NO, @"-init is not valid for ZFont"); - [self release]; - return nil; -} - -- (CGFloat)ascender { - return ceilf(self.ratio * CGFontGetAscent(self.cgFont)); -} - -- (CGFloat)descender { - return floorf(self.ratio * CGFontGetDescent(self.cgFont)); -} - -- (CGFloat)leading { - return (self.ascender - self.descender); -} - -- (CGFloat)capHeight { - return ceilf(self.ratio * CGFontGetCapHeight(self.cgFont)); -} - -- (CGFloat)xHeight { - return ceilf(self.ratio * CGFontGetXHeight(self.cgFont)); -} - -- (NSString *)familyName { - if (_familyName == nil) { - _familyName = [self copyNameTableEntryForID:1]; - } - return _familyName; -} - -- (NSString *)fontName { - if (_fontName == nil) { - _fontName = [self copyNameTableEntryForID:4]; - } - return _fontName; -} - -- (NSString *)postScriptName { - if (_postScriptName == nil) { - _postScriptName = [self copyNameTableEntryForID:6]; - } - return _postScriptName; -} - -- (ZFont *)fontWithSize:(CGFloat)fontSize { - if (fontSize == self.pointSize) return self; - NSParameterAssert(fontSize > 0.0); - return [[[ZFont alloc] initWithCGFont:self.cgFont size:fontSize] autorelease]; -} - -- (BOOL)isEqual:(id)object { - if (![object isKindOfClass:[ZFont class]]) return NO; - ZFont *font = (ZFont *)object; - return (font.cgFont == self.cgFont && font.pointSize == self.pointSize); -} - -- (NSString *)copyNameTableEntryForID:(UInt16)aNameID { - CFDataRef nameTable = CGFontCopyTableForTag(self.cgFont, 'name'); - NSAssert1(nameTable != NULL, @"CGFontCopyTableForTag returned NULL for 'name' tag in font %@", - [(id)CFCopyDescription(self.cgFont) autorelease]); - const UInt8 * const bytes = CFDataGetBytePtr(nameTable); - NSAssert1(OSReadBigInt16(bytes, 0) == 0, @"name table for font %@ has bad version number", - [(id)CFCopyDescription(self.cgFont) autorelease]); - const UInt16 count = OSReadBigInt16(bytes, 2); - const UInt16 stringOffset = OSReadBigInt16(bytes, 4); - const UInt8 * const nameRecords = &bytes[6]; - UInt16 nameLength = 0; - UInt16 nameOffset = 0; - NSStringEncoding encoding = 0; - for (UInt16 idx = 0; idx < count; idx++) { - const uintptr_t recordOffset = 12 * idx; - const UInt16 nameID = OSReadBigInt16(nameRecords, recordOffset + 6); - if (nameID != aNameID) continue; - const UInt16 platformID = OSReadBigInt16(nameRecords, recordOffset + 0); - const UInt16 platformSpecificID = OSReadBigInt16(nameRecords, recordOffset + 2); - encoding = 0; - // for now, we only support a subset of encodings - switch (platformID) { - case 0: // Unicode - encoding = NSUTF16StringEncoding; - break; - case 1: // Macintosh - switch (platformSpecificID) { - case 0: - encoding = NSMacOSRomanStringEncoding; - break; - } - case 3: // Microsoft - switch (platformSpecificID) { - case 1: - encoding = NSUTF16StringEncoding; - break; - } - } - if (encoding == 0) continue; - nameLength = OSReadBigInt16(nameRecords, recordOffset + 8); - nameOffset = OSReadBigInt16(nameRecords, recordOffset + 10); - break; - } - NSString *result = nil; - if (nameOffset > 0) { - const UInt8 *nameBytes = &bytes[stringOffset + nameOffset]; - result = [[NSString alloc] initWithBytes:nameBytes length:nameLength encoding:encoding]; - } - CFRelease(nameTable); - return result; -} - -- (void)dealloc { - CGFontRelease(_cgFont); - [_familyName release]; - [_fontName release]; - [_postScriptName release]; - [super dealloc]; -} -@end diff --git a/Example/libs/TouchJSON/CDataScanner.h b/Example/libs/TouchJSON/CDataScanner.h deleted file mode 100644 index a768892..0000000 --- a/Example/libs/TouchJSON/CDataScanner.h +++ /dev/null @@ -1,68 +0,0 @@ -// -// CDataScanner.h -// TouchJSON -// -// Created by Jonathan Wight on 04/16/08. -// Copyright (c) 2008 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import - -// NSScanner - -@interface CDataScanner : NSObject { - NSData *data; - - u_int8_t *start; - u_int8_t *end; - u_int8_t *current; - NSUInteger length; - - NSCharacterSet *doubleCharacters; -} - -@property (readwrite, nonatomic, retain) NSData *data; -@property (readwrite, nonatomic, assign) NSUInteger scanLocation; -@property (readonly, nonatomic, assign) BOOL isAtEnd; - -+ (id)scannerWithData:(NSData *)inData; - -- (unichar)currentCharacter; -- (unichar)scanCharacter; -- (BOOL)scanCharacter:(unichar)inCharacter; - -- (BOOL)scanUTF8String:(const char *)inString intoString:(NSString **)outValue; -- (BOOL)scanString:(NSString *)inString intoString:(NSString **)outValue; -- (BOOL)scanCharactersFromSet:(NSCharacterSet *)inSet intoString:(NSString **)outValue; // inSet must only contain 7-bit ASCII characters - -- (BOOL)scanUpToString:(NSString *)string intoString:(NSString **)outValue; -- (BOOL)scanUpToCharactersFromSet:(NSCharacterSet *)set intoString:(NSString **)outValue; // inSet must only contain 7-bit ASCII characters - -- (BOOL)scanNumber:(NSNumber **)outValue; - -- (void)skipWhitespace; - -- (NSString *)remainingString; - -@end diff --git a/Example/libs/TouchJSON/CDataScanner.m b/Example/libs/TouchJSON/CDataScanner.m deleted file mode 100644 index 44df309..0000000 --- a/Example/libs/TouchJSON/CDataScanner.m +++ /dev/null @@ -1,270 +0,0 @@ -// -// CDataScanner.m -// TouchJSON -// -// Created by Jonathan Wight on 04/16/08. -// Copyright (c) 2008 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "CDataScanner.h" - -#import "CDataScanner_Extensions.h" - -@interface CDataScanner () -@property (readwrite, nonatomic, retain) NSCharacterSet *doubleCharacters; -@end - -#pragma mark - - -inline static unichar CharacterAtPointer(void *start, void *end) -{ -#pragma unused(end) - -const u_int8_t theByte = *(u_int8_t *)start; -if (theByte & 0x80) - { - // TODO -- UNICODE!!!! (well in theory nothing todo here) - } -const unichar theCharacter = theByte; -return(theCharacter); -} - -@implementation CDataScanner - -@dynamic data; -@dynamic scanLocation; -@dynamic isAtEnd; -@synthesize doubleCharacters; - -+ (id)scannerWithData:(NSData *)inData -{ -CDataScanner *theScanner = [[[self alloc] init] autorelease]; -theScanner.data = inData; -return(theScanner); -} - -- (id)init -{ -if ((self = [super init]) != nil) - { - self.doubleCharacters = [NSCharacterSet characterSetWithCharactersInString:@"0123456789eE-."]; - } -return(self); -} - -- (void)dealloc -{ -self.data = NULL; -self.doubleCharacters = NULL; -// -[super dealloc]; -} - -- (NSUInteger)scanLocation -{ -return(current - start); -} - -- (NSData *)data -{ -return(data); -} - -- (void)setData:(NSData *)inData -{ -if (data != inData) - { - if (data) - { - [data release]; - data = NULL; - } - - if (inData) - { - data = [inData retain]; - // - start = (u_int8_t *)data.bytes; - end = start + data.length; - current = start; - length = data.length; - } - } -} - -- (void)setScanLocation:(NSUInteger)inScanLocation -{ -current = start + inScanLocation; -} - -- (BOOL)isAtEnd -{ -return(self.scanLocation >= length); -} - -- (unichar)currentCharacter -{ -return(CharacterAtPointer(current, end)); -} - -#pragma mark - - -- (unichar)scanCharacter -{ -const unichar theCharacter = CharacterAtPointer(current++, end); -return(theCharacter); -} - -- (BOOL)scanCharacter:(unichar)inCharacter -{ -unichar theCharacter = CharacterAtPointer(current, end); -if (theCharacter == inCharacter) - { - ++current; - return(YES); - } -else - return(NO); -} - -- (BOOL)scanUTF8String:(const char *)inString intoString:(NSString **)outValue; -{ -const size_t theLength = strlen(inString); -if ((size_t)(end - current) < theLength) - return(NO); -if (strncmp((char *)current, inString, theLength) == 0) - { - current += theLength; - if (outValue) - *outValue = [NSString stringWithUTF8String:inString]; - return(YES); - } -return(NO); -} - -- (BOOL)scanString:(NSString *)inString intoString:(NSString **)outValue -{ -if ((size_t)(end - current) < inString.length) - return(NO); -if (strncmp((char *)current, [inString UTF8String], inString.length) == 0) - { - current += inString.length; - if (outValue) - *outValue = inString; - return(YES); - } -return(NO); -} - -- (BOOL)scanCharactersFromSet:(NSCharacterSet *)inSet intoString:(NSString **)outValue -{ -u_int8_t *P; -for (P = current; P < end && [inSet characterIsMember:*P] == YES; ++P) - ; - -if (P == current) - { - return(NO); - } - -if (outValue) - { - *outValue = [[[NSString alloc] initWithBytes:current length:P - current encoding:NSUTF8StringEncoding] autorelease]; - } - -current = P; - -return(YES); -} - -- (BOOL)scanUpToString:(NSString *)inString intoString:(NSString **)outValue -{ -const char *theToken = [inString UTF8String]; -const char *theResult = strnstr((char *)current, theToken, end - current); -if (theResult == NULL) - { - return(NO); - } - -if (outValue) - { - *outValue = [[[NSString alloc] initWithBytes:current length:theResult - (char *)current encoding:NSUTF8StringEncoding] autorelease]; - } - -current = (u_int8_t *)theResult; - -return(YES); -} - -- (BOOL)scanUpToCharactersFromSet:(NSCharacterSet *)inSet intoString:(NSString **)outValue -{ -u_int8_t *P; -for (P = current; P < end && [inSet characterIsMember:*P] == NO; ++P) - ; - -if (P == current) - { - return(NO); - } - -if (outValue) - { - *outValue = [[[NSString alloc] initWithBytes:current length:P - current encoding:NSUTF8StringEncoding] autorelease]; - } - -current = P; - -return(YES); -} - -- (BOOL)scanNumber:(NSNumber **)outValue -{ -// Replace all of this with a strtod call -NSString *theString = NULL; -if ([self scanCharactersFromSet:doubleCharacters intoString:&theString]) - { - if (outValue) - *outValue = [NSNumber numberWithDouble:[theString doubleValue]]; // TODO dont use doubleValue - return(YES); - } -return(NO); -} - -- (void)skipWhitespace -{ -u_int8_t *P; -for (P = current; P < end && (isspace(*P)); ++P) - ; - -current = P; -} - -- (NSString *)remainingString -{ -NSData *theRemainingData = [NSData dataWithBytes:current length:end - current]; -NSString *theString = [[[NSString alloc] initWithData:theRemainingData encoding:NSUTF8StringEncoding] autorelease]; -return(theString); -} - -@end diff --git a/Example/libs/TouchJSON/Extensions/CDataScanner_Extensions.h b/Example/libs/TouchJSON/Extensions/CDataScanner_Extensions.h deleted file mode 100644 index 8c3c8dd..0000000 --- a/Example/libs/TouchJSON/Extensions/CDataScanner_Extensions.h +++ /dev/null @@ -1,37 +0,0 @@ -// -// CDataScanner_Extensions.h -// TouchJSON -// -// Created by Jonathan Wight on 12/08/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "CDataScanner.h" - -@interface CDataScanner (CDataScanner_Extensions) - -- (BOOL)scanCStyleComment:(NSString **)outComment; -- (BOOL)scanCPlusPlusStyleComment:(NSString **)outComment; - -@end diff --git a/Example/libs/TouchJSON/Extensions/CDataScanner_Extensions.m b/Example/libs/TouchJSON/Extensions/CDataScanner_Extensions.m deleted file mode 100644 index c1a16d9..0000000 --- a/Example/libs/TouchJSON/Extensions/CDataScanner_Extensions.m +++ /dev/null @@ -1,80 +0,0 @@ -// -// NSScanner_Extensions.m -// TouchJSON -// -// Created by Jonathan Wight on 12/08/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "CDataScanner_Extensions.h" - -#import "NSCharacterSet_Extensions.h" - -@implementation CDataScanner (CDataScanner_Extensions) - -- (BOOL)scanCStyleComment:(NSString **)outComment -{ -if ([self scanString:@"/*" intoString:NULL] == YES) - { - NSString *theComment = NULL; - if ([self scanUpToString:@"*/" intoString:&theComment] == NO) - [NSException raise:NSGenericException format:@"Started to scan a C style comment but it wasn't terminated."]; - - if ([theComment rangeOfString:@"/*"].location != NSNotFound) - [NSException raise:NSGenericException format:@"C style comments should not be nested."]; - - if ([self scanString:@"*/" intoString:NULL] == NO) - [NSException raise:NSGenericException format:@"C style comment did not end correctly."]; - - if (outComment != NULL) - *outComment = theComment; - - return(YES); - } -else - { - return(NO); - } -} - -- (BOOL)scanCPlusPlusStyleComment:(NSString **)outComment -{ -if ([self scanString:@"//" intoString:NULL] == YES) - { - NSString *theComment = NULL; - [self scanUpToCharactersFromSet:[NSCharacterSet linebreaksCharacterSet] intoString:&theComment]; - [self scanCharactersFromSet:[NSCharacterSet linebreaksCharacterSet] intoString:NULL]; - - if (outComment != NULL) - *outComment = theComment; - - return(YES); - } -else - { - return(NO); - } -} - -@end diff --git a/Example/libs/TouchJSON/Extensions/NSCharacterSet_Extensions.h b/Example/libs/TouchJSON/Extensions/NSCharacterSet_Extensions.h deleted file mode 100644 index c934a7d..0000000 --- a/Example/libs/TouchJSON/Extensions/NSCharacterSet_Extensions.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// NSCharacterSet_Extensions.h -// TouchJSON -// -// Created by Jonathan Wight on 12/08/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import - -@interface NSCharacterSet (NSCharacterSet_Extensions) - -+ (NSCharacterSet *)linebreaksCharacterSet; - -@end diff --git a/Example/libs/TouchJSON/Extensions/NSCharacterSet_Extensions.m b/Example/libs/TouchJSON/Extensions/NSCharacterSet_Extensions.m deleted file mode 100644 index f0306a5..0000000 --- a/Example/libs/TouchJSON/Extensions/NSCharacterSet_Extensions.m +++ /dev/null @@ -1,48 +0,0 @@ -// -// NSCharacterSet_Extensions.m -// TouchJSON -// -// Created by Jonathan Wight on 12/08/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "NSCharacterSet_Extensions.h" - -@implementation NSCharacterSet (NSCharacterSet_Extensions) - -#define LF 0x000a // Line Feed -#define FF 0x000c // Form Feed -#define CR 0x000d // Carriage Return -#define NEL 0x0085 // Next Line -#define LS 0x2028 // Line Separator -#define PS 0x2029 // Paragraph Separator - -+ (NSCharacterSet *)linebreaksCharacterSet -{ -unichar theCharacters[] = { LF, FF, CR, NEL, LS, PS, }; - -return([NSCharacterSet characterSetWithCharactersInString:[NSString stringWithCharacters:theCharacters length:sizeof(theCharacters) / sizeof(*theCharacters)]]); -} - -@end diff --git a/Example/libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.h b/Example/libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.h deleted file mode 100644 index 4d88124..0000000 --- a/Example/libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// NSDictionary_JSONExtensions.h -// TouchJSON -// -// Created by Jonathan Wight on 04/17/08. -// Copyright (c) 2008 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import - -@interface NSDictionary (NSDictionary_JSONExtensions) - -+ (id)dictionaryWithJSONData:(NSData *)inData error:(NSError **)outError; - -@end diff --git a/Example/libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.m b/Example/libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.m deleted file mode 100644 index 005efc6..0000000 --- a/Example/libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.m +++ /dev/null @@ -1,41 +0,0 @@ -// -// NSDictionary_JSONExtensions.m -// TouchJSON -// -// Created by Jonathan Wight on 04/17/08. -// Copyright (c) 2008 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "NSDictionary_JSONExtensions.h" - -#import "CJSONDeserializer.h" - -@implementation NSDictionary (NSDictionary_JSONExtensions) - -+ (id)dictionaryWithJSONData:(NSData *)inData error:(NSError **)outError -{ -return([[CJSONDeserializer deserializer] deserialize:inData error:outError]); -} - -@end diff --git a/Example/libs/TouchJSON/Extensions/NSScanner_Extensions.h b/Example/libs/TouchJSON/Extensions/NSScanner_Extensions.h deleted file mode 100644 index fc8c774..0000000 --- a/Example/libs/TouchJSON/Extensions/NSScanner_Extensions.h +++ /dev/null @@ -1,44 +0,0 @@ -// -// NSScanner_Extensions.h -// CocoaJSON -// -// Created by Jonathan Wight on 12/08/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import - -@interface NSScanner (NSScanner_Extensions) - -- (NSString *)remainingString; - -- (unichar)currentCharacter; -- (unichar)scanCharacter; -- (BOOL)scanCharacter:(unichar)inCharacter; -- (void)backtrack:(unsigned)inCount; - -- (BOOL)scanCStyleComment:(NSString **)outComment; -- (BOOL)scanCPlusPlusStyleComment:(NSString **)outComment; - -@end diff --git a/Example/libs/TouchJSON/Extensions/NSScanner_Extensions.m b/Example/libs/TouchJSON/Extensions/NSScanner_Extensions.m deleted file mode 100644 index 981366f..0000000 --- a/Example/libs/TouchJSON/Extensions/NSScanner_Extensions.m +++ /dev/null @@ -1,118 +0,0 @@ -// -// NSScanner_Extensions.m -// CocoaJSON -// -// Created by Jonathan Wight on 12/08/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "NSScanner_Extensions.h" - -#import "NSCharacterSet_Extensions.h" - -@implementation NSScanner (NSScanner_Extensions) - -- (NSString *)remainingString -{ -return([[self string] substringFromIndex:[self scanLocation]]); -} - -- (unichar)currentCharacter -{ -return([[self string] characterAtIndex:[self scanLocation]]); -} - -- (unichar)scanCharacter -{ -unsigned theScanLocation = [self scanLocation]; -unichar theCharacter = [[self string] characterAtIndex:theScanLocation]; -[self setScanLocation:theScanLocation + 1]; -return(theCharacter); -} - -- (BOOL)scanCharacter:(unichar)inCharacter -{ -unsigned theScanLocation = [self scanLocation]; -if ([[self string] characterAtIndex:theScanLocation] == inCharacter) - { - [self setScanLocation:theScanLocation + 1]; - return(YES); - } -else - return(NO); -} - -- (void)backtrack:(unsigned)inCount -{ -unsigned theScanLocation = [self scanLocation]; -if (inCount > theScanLocation) - [NSException raise:NSGenericException format:@"Backtracked too far."]; -[self setScanLocation:theScanLocation - inCount]; -} - -- (BOOL)scanCStyleComment:(NSString **)outComment -{ -if ([self scanString:@"/*" intoString:NULL] == YES) - { - NSString *theComment = NULL; - if ([self scanUpToString:@"*/" intoString:&theComment] == NO) - [NSException raise:NSGenericException format:@"Started to scan a C style comment but it wasn't terminated."]; - - if ([theComment rangeOfString:@"/*"].location != NSNotFound) - [NSException raise:NSGenericException format:@"C style comments should not be nested."]; - - if ([self scanString:@"*/" intoString:NULL] == NO) - [NSException raise:NSGenericException format:@"C style comment did not end correctly."]; - - if (outComment != NULL) - *outComment = theComment; - - return(YES); - } -else - { - return(NO); - } -} - -- (BOOL)scanCPlusPlusStyleComment:(NSString **)outComment -{ -if ([self scanString:@"//" intoString:NULL] == YES) - { - NSString *theComment = NULL; - [self scanUpToCharactersFromSet:[NSCharacterSet linebreaksCharacterSet] intoString:&theComment]; - [self scanCharactersFromSet:[NSCharacterSet linebreaksCharacterSet] intoString:NULL]; - - if (outComment != NULL) - *outComment = theComment; - - return(YES); - } -else - { - return(NO); - } -} - -@end diff --git a/Example/libs/TouchJSON/JSON/CJSONDeserializer.h b/Example/libs/TouchJSON/JSON/CJSONDeserializer.h deleted file mode 100644 index 7a805f9..0000000 --- a/Example/libs/TouchJSON/JSON/CJSONDeserializer.h +++ /dev/null @@ -1,59 +0,0 @@ -// -// CJSONDeserializer.h -// TouchJSON -// -// Created by Jonathan Wight on 12/15/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import - -extern NSString *const kJSONDeserializerErrorDomain /* = @"CJSONDeserializerErrorDomain" */; - -@protocol CDeserializerProtocol - -- (id)deserializeAsDictionary:(NSData *)inData error:(NSError **)outError; - -@end - -#pragma mark - - -@interface CJSONDeserializer : NSObject { - -} - -+ (id)deserializer; - -- (id)deserializeAsDictionary:(NSData *)inData error:(NSError **)outError; - -@end - -#pragma mark - - -@interface CJSONDeserializer (CJSONDeserializer_Deprecated) - -/// You should switch to using deserializeAsDictionary:error: instead. -- (id)deserialize:(NSData *)inData error:(NSError **)outError; - -@end diff --git a/Example/libs/TouchJSON/JSON/CJSONDeserializer.m b/Example/libs/TouchJSON/JSON/CJSONDeserializer.m deleted file mode 100644 index 1dbb317..0000000 --- a/Example/libs/TouchJSON/JSON/CJSONDeserializer.m +++ /dev/null @@ -1,84 +0,0 @@ -// -// CJSONDeserializer.m -// TouchJSON -// -// Created by Jonathan Wight on 12/15/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "CJSONDeserializer.h" - -#import "CJSONScanner.h" -#import "CDataScanner.h" - -NSString *const kJSONDeserializerErrorDomain = @"CJSONDeserializerErrorDomain"; - -@implementation CJSONDeserializer - -+ (id)deserializer -{ -return([[[self alloc] init] autorelease]); -} - -- (id)deserializeAsDictionary:(NSData *)inData error:(NSError **)outError; -{ -if (inData == NULL || [inData length] == 0) - { - if (outError) - *outError = [NSError errorWithDomain:kJSONDeserializerErrorDomain code:-1 userInfo:NULL]; - - return(NULL); - } -CJSONScanner *theScanner = [CJSONScanner scannerWithData:inData]; -NSDictionary *theDictionary = NULL; -if ([theScanner scanJSONDictionary:&theDictionary error:outError] == YES) - return(theDictionary); -else - return(NULL); -} - -@end - -#pragma mark - - -@implementation CJSONDeserializer (CJSONDeserializer_Deprecated) - -- (id)deserialize:(NSData *)inData error:(NSError **)outError -{ -if (inData == NULL || [inData length] == 0) - { - if (outError) - *outError = [NSError errorWithDomain:kJSONDeserializerErrorDomain code:-1 userInfo:NULL]; - - return(NULL); - } -CJSONScanner *theScanner = [CJSONScanner scannerWithData:inData]; -id theObject = NULL; -if ([theScanner scanJSONObject:&theObject error:outError] == YES) - return(theObject); -else - return(NULL); -} - -@end diff --git a/Example/libs/TouchJSON/JSON/CJSONScanner.h b/Example/libs/TouchJSON/JSON/CJSONScanner.h deleted file mode 100644 index 70d6074..0000000 --- a/Example/libs/TouchJSON/JSON/CJSONScanner.h +++ /dev/null @@ -1,43 +0,0 @@ -// -// CJSONScanner.h -// TouchJSON -// -// Created by Jonathan Wight on 12/07/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "CDataScanner.h" - -@interface CJSONScanner : CDataScanner { -} - -- (BOOL)scanJSONObject:(id *)outObject error:(NSError **)outError; -- (BOOL)scanJSONDictionary:(NSDictionary **)outDictionary error:(NSError **)outError; -- (BOOL)scanJSONArray:(NSArray **)outArray error:(NSError **)outError; -- (BOOL)scanJSONStringConstant:(NSString **)outStringConstant error:(NSError **)outError; -- (BOOL)scanJSONNumberConstant:(NSNumber **)outNumberConstant error:(NSError **)outError; - -@end - -extern NSString *const kJSONScannerErrorDomain /* = @"CJSONScannerErrorDomain" */; diff --git a/Example/libs/TouchJSON/JSON/CJSONScanner.m b/Example/libs/TouchJSON/JSON/CJSONScanner.m deleted file mode 100644 index c9b1d58..0000000 --- a/Example/libs/TouchJSON/JSON/CJSONScanner.m +++ /dev/null @@ -1,536 +0,0 @@ -// -// CJSONScanner.m -// TouchJSON -// -// Created by Jonathan Wight on 12/07/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "CJSONScanner.h" - -#import "NSCharacterSet_Extensions.h" -#import "CDataScanner_Extensions.h" - -#if !defined(TREAT_COMMENTS_AS_WHITESPACE) -#define TREAT_COMMENTS_AS_WHITESPACE 0 -#endif // !defined(TREAT_COMMENTS_AS_WHITESPACE) - -NSString *const kJSONScannerErrorDomain = @"CJSONScannerErrorDomain"; - -inline static int HexToInt(char inCharacter) -{ -int theValues[] = { 0x0 /* 48 '0' */, 0x1 /* 49 '1' */, 0x2 /* 50 '2' */, 0x3 /* 51 '3' */, 0x4 /* 52 '4' */, 0x5 /* 53 '5' */, 0x6 /* 54 '6' */, 0x7 /* 55 '7' */, 0x8 /* 56 '8' */, 0x9 /* 57 '9' */, -1 /* 58 ':' */, -1 /* 59 ';' */, -1 /* 60 '<' */, -1 /* 61 '=' */, -1 /* 62 '>' */, -1 /* 63 '?' */, -1 /* 64 '@' */, 0xa /* 65 'A' */, 0xb /* 66 'B' */, 0xc /* 67 'C' */, 0xd /* 68 'D' */, 0xe /* 69 'E' */, 0xf /* 70 'F' */, -1 /* 71 'G' */, -1 /* 72 'H' */, -1 /* 73 'I' */, -1 /* 74 'J' */, -1 /* 75 'K' */, -1 /* 76 'L' */, -1 /* 77 'M' */, -1 /* 78 'N' */, -1 /* 79 'O' */, -1 /* 80 'P' */, -1 /* 81 'Q' */, -1 /* 82 'R' */, -1 /* 83 'S' */, -1 /* 84 'T' */, -1 /* 85 'U' */, -1 /* 86 'V' */, -1 /* 87 'W' */, -1 /* 88 'X' */, -1 /* 89 'Y' */, -1 /* 90 'Z' */, -1 /* 91 '[' */, -1 /* 92 '\' */, -1 /* 93 ']' */, -1 /* 94 '^' */, -1 /* 95 '_' */, -1 /* 96 '`' */, 0xa /* 97 'a' */, 0xb /* 98 'b' */, 0xc /* 99 'c' */, 0xd /* 100 'd' */, 0xe /* 101 'e' */, 0xf /* 102 'f' */, }; -if (inCharacter >= '0' && inCharacter <= 'f') - return(theValues[inCharacter - '0']); -else - return(-1); -} - -@interface CJSONScanner () -- (BOOL)scanNotQuoteCharactersIntoString:(NSString **)outValue; -@end - -#pragma mark - - -@implementation CJSONScanner - -- (id)init -{ -if ((self = [super init]) != nil) - { - } -return(self); -} - -- (void)dealloc -{ -// -[super dealloc]; -} - -#pragma mark - - -- (void)setData:(NSData *)inData -{ -NSData *theData = inData; -if (theData && theData.length >= 4) - { - // This code is lame, but it works. Because the first character of any JSON string will always be a (ascii) control character we can work out the Unicode encoding by the bit pattern. See section 3 of http://www.ietf.org/rfc/rfc4627.txt - const char *theChars = theData.bytes; - NSStringEncoding theEncoding = NSUTF8StringEncoding; - if (theChars[0] != 0 && theChars[1] == 0) - { - if (theChars[2] != 0 && theChars[3] == 0) - theEncoding = NSUTF16LittleEndianStringEncoding; - else if (theChars[2] == 0 && theChars[3] == 0) - theEncoding = NSUTF32LittleEndianStringEncoding; - } - else if (theChars[0] == 0 && theChars[2] == 0 && theChars[3] != 0) - { - if (theChars[1] == 0) - theEncoding = NSUTF32BigEndianStringEncoding; - else if (theChars[1] != 0) - theEncoding = NSUTF16BigEndianStringEncoding; - } - - if (theEncoding != NSUTF8StringEncoding) - { - NSString *theString = [[NSString alloc] initWithData:theData encoding:theEncoding]; - theData = [theString dataUsingEncoding:NSUTF8StringEncoding]; - [theString release]; - } - } -[super setData:theData]; -} - -#pragma mark - - -- (BOOL)scanJSONObject:(id *)outObject error:(NSError **)outError -{ -[self skipWhitespace]; - -id theObject = NULL; - -const unichar C = [self currentCharacter]; -switch (C) - { - case 't': - if ([self scanUTF8String:"true" intoString:NULL]) - { - theObject = [NSNumber numberWithBool:YES]; - } - break; - case 'f': - if ([self scanUTF8String:"false" intoString:NULL]) - { - theObject = [NSNumber numberWithBool:NO]; - } - break; - case 'n': - if ([self scanUTF8String:"null" intoString:NULL]) - { - theObject = [NSNull null]; - } - break; - case '\"': - case '\'': - [self scanJSONStringConstant:&theObject error:outError]; - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - [self scanJSONNumberConstant:&theObject error:outError]; - break; - case '{': - [self scanJSONDictionary:&theObject error:outError]; - break; - case '[': - [self scanJSONArray:&theObject error:outError]; - break; - default: - - break; - } - -if (outObject != NULL) - *outObject = theObject; -return(YES); -} - -- (BOOL)scanJSONDictionary:(NSDictionary **)outDictionary error:(NSError **)outError -{ -NSUInteger theScanLocation = [self scanLocation]; - -if ([self scanCharacter:'{'] == NO) - { - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan dictionary. Dictionary that does not start with '{' character.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-1 userInfo:theUserInfo]; - } - return(NO); - } - -NSMutableDictionary *theDictionary = [[NSMutableDictionary alloc] init]; - -while ([self currentCharacter] != '}') - { - [self skipWhitespace]; - - if ([self currentCharacter] == '}') - break; - - NSString *theKey = NULL; - if ([self scanJSONStringConstant:&theKey error:outError] == NO) - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan dictionary. Failed to scan a key.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-2 userInfo:theUserInfo]; - } - [theDictionary release]; - return(NO); - } - - [self skipWhitespace]; - - if ([self scanCharacter:':'] == NO) - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan dictionary. Key was not terminated with a ':' character.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-3 userInfo:theUserInfo]; - } - [theDictionary release]; - return(NO); - } - - id theValue = NULL; - if ([self scanJSONObject:&theValue error:outError] == NO) - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan dictionary. Failed to scan a value.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-4 userInfo:theUserInfo]; - } - [theDictionary release]; - return(NO); - } - - [theDictionary setValue:theValue forKey:theKey]; - - [self skipWhitespace]; - if ([self scanCharacter:','] == NO) - { - if ([self currentCharacter] != '}') - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan dictionary. Key value pairs not delimited with a ',' character.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-5 userInfo:theUserInfo]; - } - [theDictionary release]; - return(NO); - } - break; - } - else - { - [self skipWhitespace]; - if ([self currentCharacter] == '}') - break; - } - } - -if ([self scanCharacter:'}'] == NO) - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan dictionary. Dictionary not terminated by a '}' character.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-6 userInfo:theUserInfo]; - } - [theDictionary release]; - return(NO); - } - -if (outDictionary != NULL) - *outDictionary = [[theDictionary copy] autorelease]; - -[theDictionary release]; - -return(YES); -} - -- (BOOL)scanJSONArray:(NSArray **)outArray error:(NSError **)outError -{ -NSUInteger theScanLocation = [self scanLocation]; - -if ([self scanCharacter:'['] == NO) - { - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan array. Array not started by a '{' character.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-7 userInfo:theUserInfo]; - } - return(NO); - } - -NSMutableArray *theArray = [[NSMutableArray alloc] init]; - -[self skipWhitespace]; -while ([self currentCharacter] != ']') - { - NSString *theValue = NULL; - if ([self scanJSONObject:&theValue error:outError] == NO) - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan array. Could not scan a value.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-8 userInfo:theUserInfo]; - } - [theArray release]; - return(NO); - } - - [theArray addObject:theValue]; - - [self skipWhitespace]; - if ([self scanCharacter:','] == NO) - { - [self skipWhitespace]; - if ([self currentCharacter] != ']') - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan array. Array not terminated by a ']' character.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-9 userInfo:theUserInfo]; - } - [theArray release]; - return(NO); - } - - break; - } - [self skipWhitespace]; - } - -[self skipWhitespace]; - -if ([self scanCharacter:']'] == NO) - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan array. Array not terminated by a ']' character.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-10 userInfo:theUserInfo]; - } - [theArray release]; - return(NO); - } - -if (outArray != NULL) - *outArray = [[theArray copy] autorelease]; - -[theArray release]; - -return(YES); -} - -- (BOOL)scanJSONStringConstant:(NSString **)outStringConstant error:(NSError **)outError -{ -NSUInteger theScanLocation = [self scanLocation]; - -[self skipWhitespace]; // TODO - i want to remove this method. But breaks unit tests. - -NSMutableString *theString = [[NSMutableString alloc] init]; - -if ([self scanCharacter:'"'] == NO) - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan string constant. String not started by a '\"' character.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-11 userInfo:theUserInfo]; - } - [theString release]; - return(NO); - } - -while ([self scanCharacter:'"'] == NO) - { - NSString *theStringChunk = NULL; - if ([self scanNotQuoteCharactersIntoString:&theStringChunk]) - { - [theString appendString:theStringChunk]; - } - - if ([self scanCharacter:'\\'] == YES) - { - unichar theCharacter = [self scanCharacter]; - switch (theCharacter) - { - case '"': - case '\\': - case '/': - break; - case 'b': - theCharacter = '\b'; - break; - case 'f': - theCharacter = '\f'; - break; - case 'n': - theCharacter = '\n'; - break; - case 'r': - theCharacter = '\r'; - break; - case 't': - theCharacter = '\t'; - break; - case 'u': - { - theCharacter = 0; - - int theShift; - for (theShift = 12; theShift >= 0; theShift -= 4) - { - const int theDigit = HexToInt([self scanCharacter]); - if (theDigit == -1) - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan string constant. Unicode character could not be decoded.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-12 userInfo:theUserInfo]; - } - [theString release]; - return(NO); - } - theCharacter |= (theDigit << theShift); - } - } - break; - default: - { - [self setScanLocation:theScanLocation]; - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan string constant. Unknown escape code.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-13 userInfo:theUserInfo]; - } - [theString release]; - return(NO); - } - break; - } - CFStringAppendCharacters((CFMutableStringRef)theString, &theCharacter, 1); - } - } - -if (outStringConstant != NULL) - *outStringConstant = [[theString copy] autorelease]; - -[theString release]; - -return(YES); -} - -- (BOOL)scanJSONNumberConstant:(NSNumber **)outNumberConstant error:(NSError **)outError -{ -NSNumber *theNumber = NULL; -if ([self scanNumber:&theNumber] == YES) - { - if (outNumberConstant != NULL) - *outNumberConstant = theNumber; - return(YES); - } -else - { - if (outError) - { - NSDictionary *theUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"Could not scan number constant.", NSLocalizedDescriptionKey, - NULL]; - *outError = [NSError errorWithDomain:kJSONScannerErrorDomain code:-14 userInfo:theUserInfo]; - } - return(NO); - } -} - -#if TREAT_COMMENTS_AS_WHITESPACE -- (void)skipWhitespace -{ -[super skipWhitespace]; -[self scanCStyleComment:NULL]; -[self scanCPlusPlusStyleComment:NULL]; -[super skipWhitespace]; -} -#endif // TREAT_COMMENTS_AS_WHITESPACE - -#pragma mark - - -- (BOOL)scanNotQuoteCharactersIntoString:(NSString **)outValue -{ -u_int8_t *P; -for (P = current; P < end && *P != '\"' && *P != '\\'; ++P) - ; - -if (P == current) - { - return(NO); - } - -if (outValue) - { - *outValue = [[[NSString alloc] initWithBytes:current length:P - current encoding:NSUTF8StringEncoding] autorelease]; - } - -current = P; - -return(YES); -} - -@end diff --git a/Example/libs/TouchJSON/JSON/CJSONSerializer.h b/Example/libs/TouchJSON/JSON/CJSONSerializer.h deleted file mode 100644 index b858bf1..0000000 --- a/Example/libs/TouchJSON/JSON/CJSONSerializer.h +++ /dev/null @@ -1,45 +0,0 @@ -// -// CJSONSerializer.h -// TouchJSON -// -// Created by Jonathan Wight on 12/07/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import - -@interface CJSONSerializer : NSObject { -} - -+ (id)serializer; - -- (NSString *)serializeObject:(id)inObject; - -- (NSString *)serializeNull:(NSNull *)inNull; -- (NSString *)serializeNumber:(NSNumber *)inNumber; -- (NSString *)serializeString:(NSString *)inString; -- (NSString *)serializeArray:(NSArray *)inArray; -- (NSString *)serializeDictionary:(NSDictionary *)inDictionary; - -@end diff --git a/Example/libs/TouchJSON/JSON/CJSONSerializer.m b/Example/libs/TouchJSON/JSON/CJSONSerializer.m deleted file mode 100644 index 7511e11..0000000 --- a/Example/libs/TouchJSON/JSON/CJSONSerializer.m +++ /dev/null @@ -1,184 +0,0 @@ -// -// CJSONSerializer.m -// TouchJSON -// -// Created by Jonathan Wight on 12/07/2005. -// Copyright (c) 2005 Jonathan Wight -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// - -#import "CJSONSerializer.h" - -@implementation CJSONSerializer - -+ (id)serializer -{ -return([[[self alloc] init] autorelease]); -} - -- (NSString *)serializeObject:(id)inObject; -{ -NSString *theResult = @""; - -if ([inObject isKindOfClass:[NSNull class]]) - { - theResult = [self serializeNull:inObject]; - } -else if ([inObject isKindOfClass:[NSNumber class]]) - { - theResult = [self serializeNumber:inObject]; - } -else if ([inObject isKindOfClass:[NSString class]]) - { - theResult = [self serializeString:inObject]; - } -else if ([inObject isKindOfClass:[NSArray class]]) - { - theResult = [self serializeArray:inObject]; - } -else if ([inObject isKindOfClass:[NSDictionary class]]) - { - theResult = [self serializeDictionary:inObject]; - } -else if ([inObject isKindOfClass:[NSData class]]) - { - NSString *theString = [[[NSString alloc] initWithData:inObject encoding:NSUTF8StringEncoding] autorelease]; - theResult = [self serializeString:theString]; - } -else - { - [NSException raise:NSGenericException format:@"Cannot serialize data of type '%@'", NSStringFromClass([inObject class])]; - } -if (theResult == NULL) - [NSException raise:NSGenericException format:@"Could not serialize object '%@'", inObject]; -return(theResult); -} - -- (NSString *)serializeNull:(NSNull *)inNull -{ -#pragma unused (inNull) -return(@"null"); -} - -- (NSString *)serializeNumber:(NSNumber *)inNumber -{ -NSString *theResult = NULL; -switch (CFNumberGetType((CFNumberRef)inNumber)) - { - case kCFNumberCharType: - { - int theValue = [inNumber intValue]; - if (theValue == 0) - theResult = @"false"; - else if (theValue == 1) - theResult = @"true"; - else - theResult = [inNumber stringValue]; - } - break; - case kCFNumberSInt8Type: - case kCFNumberSInt16Type: - case kCFNumberSInt32Type: - case kCFNumberSInt64Type: - case kCFNumberFloat32Type: - case kCFNumberFloat64Type: - case kCFNumberShortType: - case kCFNumberIntType: - case kCFNumberLongType: - case kCFNumberLongLongType: - case kCFNumberFloatType: - case kCFNumberDoubleType: - case kCFNumberCFIndexType: - default: - theResult = [inNumber stringValue]; - break; - } -return(theResult); -} - -- (NSString *)serializeString:(NSString *)inString -{ -NSMutableString *theMutableCopy = [[inString mutableCopy] autorelease]; -[theMutableCopy replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:0 range:NSMakeRange(0, [theMutableCopy length])]; -[theMutableCopy replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:0 range:NSMakeRange(0, [theMutableCopy length])]; -[theMutableCopy replaceOccurrencesOfString:@"/" withString:@"\\/" options:0 range:NSMakeRange(0, [theMutableCopy length])]; -[theMutableCopy replaceOccurrencesOfString:@"\b" withString:@"\\b" options:0 range:NSMakeRange(0, [theMutableCopy length])]; -[theMutableCopy replaceOccurrencesOfString:@"\f" withString:@"\\f" options:0 range:NSMakeRange(0, [theMutableCopy length])]; -[theMutableCopy replaceOccurrencesOfString:@"\n" withString:@"\\n" options:0 range:NSMakeRange(0, [theMutableCopy length])]; -[theMutableCopy replaceOccurrencesOfString:@"\n" withString:@"\\n" options:0 range:NSMakeRange(0, [theMutableCopy length])]; -[theMutableCopy replaceOccurrencesOfString:@"\t" withString:@"\\t" options:0 range:NSMakeRange(0, [theMutableCopy length])]; -/* - case 'u': - { - theCharacter = 0; - - int theShift; - for (theShift = 12; theShift >= 0; theShift -= 4) - { - int theDigit = HexToInt([self scanCharacter]); - if (theDigit == -1) - { - [self setScanLocation:theScanLocation]; - return(NO); - } - theCharacter |= (theDigit << theShift); - } - } -*/ -return([NSString stringWithFormat:@"\"%@\"", theMutableCopy]); -} - -- (NSString *)serializeArray:(NSArray *)inArray -{ -NSMutableString *theString = [NSMutableString string]; - -NSEnumerator *theEnumerator = [inArray objectEnumerator]; -id theValue = NULL; -while ((theValue = [theEnumerator nextObject]) != NULL) - { - [theString appendString:[self serializeObject:theValue]]; - if (theValue != [inArray lastObject]) - [theString appendString:@","]; - } -return([NSString stringWithFormat:@"[%@]", theString]); -} - -- (NSString *)serializeDictionary:(NSDictionary *)inDictionary -{ -NSMutableString *theString = [NSMutableString string]; - -NSArray *theKeys = [inDictionary allKeys]; -NSEnumerator *theEnumerator = [theKeys objectEnumerator]; -NSString *theKey = NULL; -while ((theKey = [theEnumerator nextObject]) != NULL) - { - id theValue = [inDictionary objectForKey:theKey]; - - [theString appendFormat:@"%@:%@", [self serializeString:theKey], [self serializeObject:theValue]]; - if (theKey != [theKeys lastObject]) - [theString appendString:@","]; - } -return([NSString stringWithFormat:@"{%@}", theString]); -} - -@end diff --git a/Example/libs/cocos2d/CCAction.h b/Example/libs/cocos2d/CCAction.h deleted file mode 100644 index f1da6b8..0000000 --- a/Example/libs/cocos2d/CCAction.h +++ /dev/null @@ -1,195 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#include -#import - -#import "ccTypes.h" - -enum { - //! Default tag - kCCActionTagInvalid = -1, -}; - -/** Base class for CCAction objects. - */ -@interface CCAction : NSObject -{ - id originalTarget_; - id target_; - NSInteger tag_; -} - -/** The "target". The action will modify the target properties. - The target will be set with the 'startWithTarget' method. - When the 'stop' method is called, target will be set to nil. - The target is 'assigned', it is not 'retained'. - */ -@property (nonatomic,readonly,assign) id target; - -/** The original target, since target can be nil. - Is the target that were used to run the action. Unless you are doing something complex, like CCActionManager, you should NOT call this method. - @since v0.8.2 -*/ -@property (nonatomic,readonly,assign) id originalTarget; - - -/** The action tag. An identifier of the action */ -@property (nonatomic,readwrite,assign) NSInteger tag; - -/** Allocates and initializes the action */ -+(id) action; - -/** Initializes the action */ --(id) init; - --(id) copyWithZone: (NSZone*) zone; - -//! return YES if the action has finished --(BOOL) isDone; -//! called before the action start. It will also set the target. --(void) startWithTarget:(id)target; -//! called after the action has finished. It will set the 'target' to nil. -//! IMPORTANT: You should never call "[action stop]" manually. Instead, use: "[target stopAction:action];" --(void) stop; -//! called every frame with its delta time. DON'T override unless you know what you are doing. --(void) step: (ccTime) dt; -//! called once per frame. time a value between 0 and 1 -//! For example: -//! * 0 means that the action just started -//! * 0.5 means that the action is in the middle -//! * 1 means that the action is over --(void) update: (ccTime) time; - -@end - -/** Base class actions that do have a finite time duration. - Possible actions: - - An action with a duration of 0 seconds - - An action with a duration of 35.5 seconds - Infitite time actions are valid - */ -@interface CCFiniteTimeAction : CCAction -{ - //! duration in seconds - ccTime duration_; -} -//! duration in seconds of the action -@property (nonatomic,readwrite) ccTime duration; - -/** returns a reversed action */ -- (CCFiniteTimeAction*) reverse; -@end - - -@class CCActionInterval; -/** Repeats an action for ever. - To repeat the an action for a limited number of times use the Repeat action. - @warning This action can't be Sequenceable because it is not an IntervalAction - */ -@interface CCRepeatForever : CCAction -{ - CCActionInterval *innerAction_; -} -/** Inner action */ -@property (nonatomic, readwrite, retain) CCActionInterval *innerAction; - -/** creates the action */ -+(id) actionWithAction: (CCActionInterval*) action; -/** initializes the action */ --(id) initWithAction: (CCActionInterval*) action; -@end - -/** Changes the speed of an action, making it take longer (speed<1) - or less (speed>1) time. - Useful to simulate 'slow motion' or 'fast forward' effect. - @warning This action can't be Sequenceable because it is not an CCIntervalAction - */ -@interface CCSpeed : CCAction -{ - CCActionInterval *innerAction_; - float speed_; -} -/** alter the speed of the inner function in runtime */ -@property (nonatomic,readwrite) float speed; -/** Inner action of CCSpeed */ -@property (nonatomic, readwrite, retain) CCActionInterval *innerAction; - -/** creates the action */ -+(id) actionWithAction: (CCActionInterval*) action speed:(float)value; -/** initializes the action */ --(id) initWithAction: (CCActionInterval*) action speed:(float)value; -@end - -@class CCNode; -/** CCFollow is an action that "follows" a node. - - Eg: - [layer runAction: [CCFollow actionWithTarget:hero]]; - - Instead of using CCCamera as a "follower", use this action instead. - @since v0.99.2 - */ -@interface CCFollow : CCAction -{ - /* node to follow */ - CCNode *followedNode_; - - /* whether camera should be limited to certain area */ - BOOL boundarySet; - - /* if screensize is bigger than the boundary - update not needed */ - BOOL boundaryFullyCovered; - - /* fast access to the screen dimensions */ - CGPoint halfScreenSize; - CGPoint fullScreenSize; - - /* world boundaries */ - float leftBoundary; - float rightBoundary; - float topBoundary; - float bottomBoundary; -} - -/** alter behavior - turn on/off boundary */ -@property (nonatomic,readwrite) BOOL boundarySet; - -/** creates the action with no boundary set */ -+(id) actionWithTarget:(CCNode *)followedNode; - -/** creates the action with a set boundary */ -+(id) actionWithTarget:(CCNode *)followedNode worldBoundary:(CGRect)rect; - -/** initializes the action */ --(id) initWithTarget:(CCNode *)followedNode; - -/** initializes the action with a set boundary */ --(id) initWithTarget:(CCNode *)followedNode worldBoundary:(CGRect)rect; - -@end - diff --git a/Example/libs/cocos2d/CCAction.m b/Example/libs/cocos2d/CCAction.m deleted file mode 100644 index a1765da..0000000 --- a/Example/libs/cocos2d/CCAction.m +++ /dev/null @@ -1,357 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCDirector.h" -#import "ccMacros.h" -#import "CCAction.h" -#import "CCActionInterval.h" -#import "Support/CGPointExtension.h" - -// -// Action Base Class -// -#pragma mark - -#pragma mark Action -@implementation CCAction - -@synthesize tag = tag_, target = target_, originalTarget = originalTarget_; - -+(id) action -{ - return [[[self alloc] init] autorelease]; -} - --(id) init -{ - if( (self=[super init]) ) { - originalTarget_ = target_ = nil; - tag_ = kCCActionTagInvalid; - } - return self; -} - --(void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - [super dealloc]; -} - --(NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Tag = %i>", [self class], self, tag_]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] init]; - copy.tag = tag_; - return copy; -} - --(void) startWithTarget:(id)aTarget -{ - originalTarget_ = target_ = aTarget; -} - --(void) stop -{ - target_ = nil; -} - --(BOOL) isDone -{ - return YES; -} - --(void) step: (ccTime) dt -{ - CCLOG(@"[Action step]. override me"); -} - --(void) update: (ccTime) time -{ - CCLOG(@"[Action update]. override me"); -} -@end - -// -// FiniteTimeAction -// -#pragma mark - -#pragma mark FiniteTimeAction -@implementation CCFiniteTimeAction -@synthesize duration = duration_; - -- (CCFiniteTimeAction*) reverse -{ - CCLOG(@"cocos2d: FiniteTimeAction#reverse: Implement me"); - return nil; -} -@end - - -// -// RepeatForever -// -#pragma mark - -#pragma mark RepeatForever -@implementation CCRepeatForever -@synthesize innerAction=innerAction_; -+(id) actionWithAction: (CCActionInterval*) action -{ - return [[[self alloc] initWithAction: action] autorelease]; -} - --(id) initWithAction: (CCActionInterval*) action -{ - if( (self=[super init]) ) - self.innerAction = action; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithAction:[[innerAction_ copy] autorelease] ]; - return copy; -} - --(void) dealloc -{ - [innerAction_ release]; - [super dealloc]; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - [innerAction_ startWithTarget:target_]; -} - --(void) step:(ccTime) dt -{ - [innerAction_ step: dt]; - if( [innerAction_ isDone] ) { - ccTime diff = innerAction_.elapsed - innerAction_.duration; - [innerAction_ startWithTarget:target_]; - - // to prevent jerk. issue #390, 1247 - [innerAction_ step: 0.0f]; - [innerAction_ step: diff]; - } -} - - --(BOOL) isDone -{ - return NO; -} - -- (CCActionInterval *) reverse -{ - return [CCRepeatForever actionWithAction:[innerAction_ reverse]]; -} -@end - -// -// Speed -// -#pragma mark - -#pragma mark Speed -@implementation CCSpeed -@synthesize speed=speed_; -@synthesize innerAction=innerAction_; - -+(id) actionWithAction: (CCActionInterval*) action speed:(float)value -{ - return [[[self alloc] initWithAction: action speed:value] autorelease]; -} - --(id) initWithAction: (CCActionInterval*) action speed:(float)value -{ - if( (self=[super init]) ) { - self.innerAction = action; - speed_ = value; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithAction:[[innerAction_ copy] autorelease] speed:speed_]; - return copy; -} - --(void) dealloc -{ - [innerAction_ release]; - [super dealloc]; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - [innerAction_ startWithTarget:target_]; -} - --(void) stop -{ - [innerAction_ stop]; - [super stop]; -} - --(void) step:(ccTime) dt -{ - [innerAction_ step: dt * speed_]; -} - --(BOOL) isDone -{ - return [innerAction_ isDone]; -} - -- (CCActionInterval *) reverse -{ - return [CCSpeed actionWithAction:[innerAction_ reverse] speed:speed_]; -} -@end - -// -// Follow -// -#pragma mark - -#pragma mark Follow -@implementation CCFollow - -@synthesize boundarySet; - -+(id) actionWithTarget:(CCNode *) fNode -{ - return [[[self alloc] initWithTarget:fNode] autorelease]; -} - -+(id) actionWithTarget:(CCNode *) fNode worldBoundary:(CGRect)rect -{ - return [[[self alloc] initWithTarget:fNode worldBoundary:rect] autorelease]; -} - --(id) initWithTarget:(CCNode *)fNode -{ - if( (self=[super init]) ) { - - followedNode_ = [fNode retain]; - boundarySet = FALSE; - boundaryFullyCovered = FALSE; - - CGSize s = [[CCDirector sharedDirector] winSize]; - fullScreenSize = CGPointMake(s.width, s.height); - halfScreenSize = ccpMult(fullScreenSize, .5f); - } - - return self; -} - --(id) initWithTarget:(CCNode *)fNode worldBoundary:(CGRect)rect -{ - if( (self=[super init]) ) { - - followedNode_ = [fNode retain]; - boundarySet = TRUE; - boundaryFullyCovered = FALSE; - - CGSize winSize = [[CCDirector sharedDirector] winSize]; - fullScreenSize = CGPointMake(winSize.width, winSize.height); - halfScreenSize = ccpMult(fullScreenSize, .5f); - - leftBoundary = -((rect.origin.x+rect.size.width) - fullScreenSize.x); - rightBoundary = -rect.origin.x ; - topBoundary = -rect.origin.y; - bottomBoundary = -((rect.origin.y+rect.size.height) - fullScreenSize.y); - - if(rightBoundary < leftBoundary) - { - // screen width is larger than world's boundary width - //set both in the middle of the world - rightBoundary = leftBoundary = (leftBoundary + rightBoundary) / 2; - } - if(topBoundary < bottomBoundary) - { - // screen width is larger than world's boundary width - //set both in the middle of the world - topBoundary = bottomBoundary = (topBoundary + bottomBoundary) / 2; - } - - if( (topBoundary == bottomBoundary) && (leftBoundary == rightBoundary) ) - boundaryFullyCovered = TRUE; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] init]; - copy.tag = tag_; - return copy; -} - --(void) step:(ccTime) dt -{ - if(boundarySet) - { - // whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased - if(boundaryFullyCovered) - return; - - CGPoint tempPos = ccpSub( halfScreenSize, followedNode_.position); - [target_ setPosition:ccp(clampf(tempPos.x,leftBoundary,rightBoundary), clampf(tempPos.y,bottomBoundary,topBoundary))]; - } - else - [target_ setPosition:ccpSub( halfScreenSize, followedNode_.position )]; -} - - --(BOOL) isDone -{ - return !followedNode_.isRunning; -} - --(void) stop -{ - target_ = nil; - [super stop]; -} - --(void) dealloc -{ - [followedNode_ release]; - [super dealloc]; -} - -@end - - diff --git a/Example/libs/cocos2d/CCActionCamera.h b/Example/libs/cocos2d/CCActionCamera.h deleted file mode 100644 index 3c3934c..0000000 --- a/Example/libs/cocos2d/CCActionCamera.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCActionInterval.h" - -@class CCCamera; - -/** Base class for CCCamera actions - */ -@interface CCActionCamera : CCActionInterval -{ - float centerXOrig_; - float centerYOrig_; - float centerZOrig_; - - float eyeXOrig_; - float eyeYOrig_; - float eyeZOrig_; - - float upXOrig_; - float upYOrig_; - float upZOrig_; -} -@end - -/** CCOrbitCamera action - Orbits the camera around the center of the screen using spherical coordinates - */ -@interface CCOrbitCamera : CCActionCamera -{ - float radius_; - float deltaRadius_; - float angleZ_; - float deltaAngleZ_; - float angleX_; - float deltaAngleX_; - - float radZ_; - float radDeltaZ_; - float radX_; - float radDeltaX_; - -} -/** creates a CCOrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX */ -+(id) actionWithDuration:(float) t radius:(float)r deltaRadius:(float) dr angleZ:(float)z deltaAngleZ:(float)dz angleX:(float)x deltaAngleX:(float)dx; -/** initializes a CCOrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX */ --(id) initWithDuration:(float) t radius:(float)r deltaRadius:(float) dr angleZ:(float)z deltaAngleZ:(float)dz angleX:(float)x deltaAngleX:(float)dx; -/** positions the camera according to spherical coordinates */ --(void) sphericalRadius:(float*) r zenith:(float*) zenith azimuth:(float*) azimuth; -@end diff --git a/Example/libs/cocos2d/CCActionCamera.m b/Example/libs/cocos2d/CCActionCamera.m deleted file mode 100644 index c46f239..0000000 --- a/Example/libs/cocos2d/CCActionCamera.m +++ /dev/null @@ -1,147 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - - -#import "CCActionCamera.h" -#import "CCNode.h" -#import "CCCamera.h" -#import "ccMacros.h" - -// -// CameraAction -// -@implementation CCActionCamera --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - CCCamera *camera = [target_ camera]; - [camera centerX:¢erXOrig_ centerY:¢erYOrig_ centerZ:¢erZOrig_]; - [camera eyeX:&eyeXOrig_ eyeY:&eyeYOrig_ eyeZ:&eyeZOrig_]; - [camera upX:&upXOrig_ upY:&upYOrig_ upZ: &upZOrig_]; -} - --(id) reverse -{ - return [CCReverseTime actionWithAction:self]; -} -@end - -@implementation CCOrbitCamera -+(id) actionWithDuration:(float)t radius:(float)r deltaRadius:(float) dr angleZ:(float)z deltaAngleZ:(float)dz angleX:(float)x deltaAngleX:(float)dx -{ - return [[[self alloc] initWithDuration:t radius:r deltaRadius:dr angleZ:z deltaAngleZ:dz angleX:x deltaAngleX:dx] autorelease]; -} - --(id) copyWithZone: (NSZone*) zone -{ - return [[[self class] allocWithZone: zone] initWithDuration:duration_ radius:radius_ deltaRadius:deltaRadius_ angleZ:angleZ_ deltaAngleZ:deltaAngleZ_ angleX:angleX_ deltaAngleX:deltaAngleX_]; -} - - --(id) initWithDuration:(float)t radius:(float)r deltaRadius:(float) dr angleZ:(float)z deltaAngleZ:(float)dz angleX:(float)x deltaAngleX:(float)dx -{ - if((self=[super initWithDuration:t]) ) { - - radius_ = r; - deltaRadius_ = dr; - angleZ_ = z; - deltaAngleZ_ = dz; - angleX_ = x; - deltaAngleX_ = dx; - - radDeltaZ_ = (CGFloat)CC_DEGREES_TO_RADIANS(dz); - radDeltaX_ = (CGFloat)CC_DEGREES_TO_RADIANS(dx); - } - - return self; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - float r, zenith, azimuth; - - [self sphericalRadius: &r zenith:&zenith azimuth:&azimuth]; - -#if 0 // isnan() is not supported on the simulator, and isnan() always returns false. - if( isnan(radius_) ) - radius_ = r; - - if( isnan( angleZ_) ) - angleZ_ = (CGFloat)CC_RADIANS_TO_DEGREES(zenith); - - if( isnan( angleX_ ) ) - angleX_ = (CGFloat)CC_RADIANS_TO_DEGREES(azimuth); -#endif - - radZ_ = (CGFloat)CC_DEGREES_TO_RADIANS(angleZ_); - radX_ = (CGFloat)CC_DEGREES_TO_RADIANS(angleX_); -} - --(void) update: (ccTime) dt -{ - float r = (radius_ + deltaRadius_ * dt) *[CCCamera getZEye]; - float za = radZ_ + radDeltaZ_ * dt; - float xa = radX_ + radDeltaX_ * dt; - - float i = sinf(za) * cosf(xa) * r + centerXOrig_; - float j = sinf(za) * sinf(xa) * r + centerYOrig_; - float k = cosf(za) * r + centerZOrig_; - - [[target_ camera] setEyeX:i eyeY:j eyeZ:k]; -} - --(void) sphericalRadius:(float*) newRadius zenith:(float*) zenith azimuth:(float*) azimuth -{ - float ex, ey, ez, cx, cy, cz, x, y, z; - float r; // radius - float s; - - CCCamera *camera = [target_ camera]; - [camera eyeX:&ex eyeY:&ey eyeZ:&ez]; - [camera centerX:&cx centerY:&cy centerZ:&cz]; - - x = ex-cx; - y = ey-cy; - z = ez-cz; - - r = sqrtf( x*x + y*y + z*z); - s = sqrtf( x*x + y*y); - if(s==0.0f) - s = FLT_EPSILON; - if(r==0.0f) - r = FLT_EPSILON; - - *zenith = acosf( z/r); - if( x < 0 ) - *azimuth = (float)M_PI - asinf(y/s); - else - *azimuth = asinf(y/s); - - *newRadius = r / [CCCamera getZEye]; -} -@end diff --git a/Example/libs/cocos2d/CCActionEase.h b/Example/libs/cocos2d/CCActionEase.h deleted file mode 100644 index 4c91e56..0000000 --- a/Example/libs/cocos2d/CCActionEase.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2009 Jason Booth - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionInterval.h" - -/** Base class for Easing actions - */ -@interface CCActionEase : CCActionInterval -{ - CCActionInterval * other; -} -/** creates the action */ -+(id) actionWithAction: (CCActionInterval*) action; -/** initializes the action */ --(id) initWithAction: (CCActionInterval*) action; -@end - -/** Base class for Easing actions with rate parameters - */ -@interface CCEaseRateAction : CCActionEase -{ - float rate; -} -/** rate value for the actions */ -@property (nonatomic,readwrite,assign) float rate; -/** Creates the action with the inner action and the rate parameter */ -+(id) actionWithAction: (CCActionInterval*) action rate:(float)rate; -/** Initializes the action with the inner action and the rate parameter */ --(id) initWithAction: (CCActionInterval*) action rate:(float)rate; -@end - -/** CCEaseIn action with a rate - */ -@interface CCEaseIn : CCEaseRateAction {} @end - -/** CCEaseOut action with a rate - */ -@interface CCEaseOut : CCEaseRateAction {} @end - -/** CCEaseInOut action with a rate - */ -@interface CCEaseInOut : CCEaseRateAction {} @end - -/** CCEase Exponential In - */ -@interface CCEaseExponentialIn : CCActionEase {} @end -/** Ease Exponential Out - */ -@interface CCEaseExponentialOut : CCActionEase {} @end -/** Ease Exponential InOut - */ -@interface CCEaseExponentialInOut : CCActionEase {} @end -/** Ease Sine In - */ -@interface CCEaseSineIn : CCActionEase {} @end -/** Ease Sine Out - */ -@interface CCEaseSineOut : CCActionEase {} @end -/** Ease Sine InOut - */ -@interface CCEaseSineInOut : CCActionEase {} @end - -/** Ease Elastic abstract class - @since v0.8.2 - */ -@interface CCEaseElastic : CCActionEase -{ - float period_; -} - -/** period of the wave in radians. default is 0.3 */ -@property (nonatomic,readwrite) float period; - -/** Creates the action with the inner action and the period in radians (default is 0.3) */ -+(id) actionWithAction: (CCActionInterval*) action period:(float)period; -/** Initializes the action with the inner action and the period in radians (default is 0.3) */ --(id) initWithAction: (CCActionInterval*) action period:(float)period; -@end - -/** Ease Elastic In action. - @warning This action doesn't use a bijective fucntion. Actions like Sequence might have an unexpected result when used with this action. - @since v0.8.2 - */ -@interface CCEaseElasticIn : CCEaseElastic {} @end -/** Ease Elastic Out action. - @warning This action doesn't use a bijective fucntion. Actions like Sequence might have an unexpected result when used with this action. - @since v0.8.2 - */ -@interface CCEaseElasticOut : CCEaseElastic {} @end -/** Ease Elastic InOut action. - @warning This action doesn't use a bijective fucntion. Actions like Sequence might have an unexpected result when used with this action. - @since v0.8.2 - */ -@interface CCEaseElasticInOut : CCEaseElastic {} @end - -/** CCEaseBounce abstract class. - @since v0.8.2 -*/ -@interface CCEaseBounce : CCActionEase {} @end - -/** CCEaseBounceIn action. - @warning This action doesn't use a bijective fucntion. Actions like Sequence might have an unexpected result when used with this action. - @since v0.8.2 -*/ -@interface CCEaseBounceIn : CCEaseBounce {} @end - -/** EaseBounceOut action. - @warning This action doesn't use a bijective fucntion. Actions like Sequence might have an unexpected result when used with this action. - @since v0.8.2 - */ -@interface CCEaseBounceOut : CCEaseBounce {} @end - -/** CCEaseBounceInOut action. - @warning This action doesn't use a bijective fucntion. Actions like Sequence might have an unexpected result when used with this action. - @since v0.8.2 - */ -@interface CCEaseBounceInOut : CCEaseBounce {} @end - -/** CCEaseBackIn action. - @warning This action doesn't use a bijective fucntion. Actions like Sequence might have an unexpected result when used with this action. - @since v0.8.2 - */ -@interface CCEaseBackIn : CCActionEase {} @end - -/** CCEaseBackOut action. - @warning This action doesn't use a bijective fucntion. Actions like Sequence might have an unexpected result when used with this action. - @since v0.8.2 - */ -@interface CCEaseBackOut : CCActionEase {} @end - -/** CCEaseBackInOut action. - @warning This action doesn't use a bijective fucntion. Actions like Sequence might have an unexpected result when used with this action. - @since v0.8.2 - */ -@interface CCEaseBackInOut : CCActionEase {} @end - diff --git a/Example/libs/cocos2d/CCActionEase.m b/Example/libs/cocos2d/CCActionEase.m deleted file mode 100644 index 25b1cf0..0000000 --- a/Example/libs/cocos2d/CCActionEase.m +++ /dev/null @@ -1,532 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2009 Jason Booth - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -/* - * Elastic, Back and Bounce actions based on code from: - * http://github.com/NikhilK/silverlightfx/ - * - * by http://github.com/NikhilK - */ - -#import "CCActionEase.h" - -#ifndef M_PI_X_2 -#define M_PI_X_2 (float)M_PI * 2.0f -#endif - -#pragma mark EaseAction - -// -// EaseAction -// -@implementation CCActionEase - -+(id) actionWithAction: (CCActionInterval*) action -{ - return [[[self alloc] initWithAction: action] autorelease ]; -} - --(id) initWithAction: (CCActionInterval*) action -{ - NSAssert( action!=nil, @"Ease: arguments must be non-nil"); - - if( (self=[super initWithDuration: action.duration]) ) - other = [action retain]; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone:zone] initWithAction:[[other copy] autorelease]]; - return copy; -} - --(void) dealloc -{ - [other release]; - [super dealloc]; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - [other startWithTarget:target_]; -} - --(void) stop -{ - [other stop]; - [super stop]; -} - --(void) update: (ccTime) t -{ - [other update: t]; -} - --(CCActionInterval*) reverse -{ - return [[self class] actionWithAction: [other reverse]]; -} -@end - - -#pragma mark - -#pragma mark EaseRate - -// -// EaseRateAction -// -@implementation CCEaseRateAction -@synthesize rate; -+(id) actionWithAction: (CCActionInterval*) action rate:(float)aRate -{ - return [[[self alloc] initWithAction: action rate:aRate] autorelease ]; -} - --(id) initWithAction: (CCActionInterval*) action rate:(float)aRate -{ - if( (self=[super initWithAction:action ]) ) - self.rate = aRate; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone:zone] initWithAction:[[other copy] autorelease] rate:rate]; - return copy; -} - --(void) dealloc -{ - [super dealloc]; -} - --(CCActionInterval*) reverse -{ - return [[self class] actionWithAction: [other reverse] rate:1/rate]; -} -@end - -// -// EeseIn -// -@implementation CCEaseIn --(void) update: (ccTime) t -{ - [other update: powf(t,rate)]; -} -@end - -// -// EaseOut -// -@implementation CCEaseOut --(void) update: (ccTime) t -{ - [other update: powf(t,1/rate)]; -} -@end - -// -// EaseInOut -// -@implementation CCEaseInOut --(void) update: (ccTime) t -{ - t *= 2; - if (t < 1) { - [other update: 0.5f * powf (t, rate)]; - } - else { - [other update: 1.0f - 0.5f * powf(2-t, rate)]; - } -} - -// InOut and OutIn are symmetrical --(CCActionInterval*) reverse -{ - return [[self class] actionWithAction: [other reverse] rate:rate]; -} - -@end - -#pragma mark - -#pragma mark EaseExponential - -// -// EaseExponentialIn -// -@implementation CCEaseExponentialIn --(void) update: (ccTime) t -{ - [other update: (t==0) ? 0 : powf(2, 10 * (t/1 - 1)) - 1 * 0.001f]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseExponentialOut actionWithAction: [other reverse]]; -} -@end - -// -// EaseExponentialOut -// -@implementation CCEaseExponentialOut --(void) update: (ccTime) t -{ - [other update: (t==1) ? 1 : (-powf(2, -10 * t/1) + 1)]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseExponentialIn actionWithAction: [other reverse]]; -} -@end - -// -// EaseExponentialInOut -// -@implementation CCEaseExponentialInOut --(void) update: (ccTime) t -{ - t /= 0.5f; - if (t < 1) - t = 0.5f * powf(2, 10 * (t - 1)); - else - t = 0.5f * (-powf(2, -10 * (t -1) ) + 2); - - [other update:t]; -} -@end - - -#pragma mark - -#pragma mark EaseSin actions - -// -// EaseSineIn -// -@implementation CCEaseSineIn --(void) update: (ccTime) t -{ - [other update:-1*cosf(t * (float)M_PI_2) +1]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseSineOut actionWithAction: [other reverse]]; -} -@end - -// -// EaseSineOut -// -@implementation CCEaseSineOut --(void) update: (ccTime) t -{ - [other update:sinf(t * (float)M_PI_2)]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseSineIn actionWithAction: [other reverse]]; -} -@end - -// -// EaseSineInOut -// -@implementation CCEaseSineInOut --(void) update: (ccTime) t -{ - [other update:-0.5f*(cosf( (float)M_PI*t) - 1)]; -} -@end - -#pragma mark - -#pragma mark EaseElastic actions - -// -// EaseElastic -// -@implementation CCEaseElastic - -@synthesize period = period_; - -+(id) actionWithAction: (CCActionInterval*) action -{ - return [[[self alloc] initWithAction:action period:0.3f] autorelease]; -} - -+(id) actionWithAction: (CCActionInterval*) action period:(float)period -{ - return [[[self alloc] initWithAction:action period:period] autorelease]; -} - --(id) initWithAction: (CCActionInterval*) action -{ - return [self initWithAction:action period:0.3f]; -} - --(id) initWithAction: (CCActionInterval*) action period:(float)period -{ - if( (self=[super initWithAction:action]) ) - period_ = period; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone:zone] initWithAction:[[other copy] autorelease] period:period_]; - return copy; -} - --(CCActionInterval*) reverse -{ - NSAssert(NO,@"Override me"); - return nil; -} - -@end - -// -// EaseElasticIn -// - -@implementation CCEaseElasticIn --(void) update: (ccTime) t -{ - ccTime newT = 0; - if (t == 0 || t == 1) - newT = t; - - else { - float s = period_ / 4; - t = t - 1; - newT = -powf(2, 10 * t) * sinf( (t-s) *M_PI_X_2 / period_); - } - [other update:newT]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseElasticOut actionWithAction: [other reverse] period:period_]; -} - -@end - -// -// EaseElasticOut -// -@implementation CCEaseElasticOut - --(void) update: (ccTime) t -{ - ccTime newT = 0; - if (t == 0 || t == 1) { - newT = t; - - } else { - float s = period_ / 4; - newT = powf(2, -10 * t) * sinf( (t-s) *M_PI_X_2 / period_) + 1; - } - [other update:newT]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseElasticIn actionWithAction: [other reverse] period:period_]; -} - -@end - -// -// EaseElasticInOut -// -@implementation CCEaseElasticInOut --(void) update: (ccTime) t -{ - ccTime newT = 0; - - if( t == 0 || t == 1 ) - newT = t; - else { - t = t * 2; - if(! period_ ) - period_ = 0.3f * 1.5f; - ccTime s = period_ / 4; - - t = t -1; - if( t < 0 ) - newT = -0.5f * powf(2, 10 * t) * sinf((t - s) * M_PI_X_2 / period_); - else - newT = powf(2, -10 * t) * sinf((t - s) * M_PI_X_2 / period_) * 0.5f + 1; - } - [other update:newT]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseElasticInOut actionWithAction: [other reverse] period:period_]; -} - -@end - -#pragma mark - -#pragma mark EaseBounce actions - -// -// EaseBounce -// -@implementation CCEaseBounce --(ccTime) bounceTime:(ccTime) t -{ - if (t < 1 / 2.75) { - return 7.5625f * t * t; - } - else if (t < 2 / 2.75) { - t -= 1.5f / 2.75f; - return 7.5625f * t * t + 0.75f; - } - else if (t < 2.5 / 2.75) { - t -= 2.25f / 2.75f; - return 7.5625f * t * t + 0.9375f; - } - - t -= 2.625f / 2.75f; - return 7.5625f * t * t + 0.984375f; -} -@end - -// -// EaseBounceIn -// - -@implementation CCEaseBounceIn - --(void) update: (ccTime) t -{ - ccTime newT = 1 - [self bounceTime:1-t]; - [other update:newT]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseBounceOut actionWithAction: [other reverse]]; -} - -@end - -@implementation CCEaseBounceOut - --(void) update: (ccTime) t -{ - ccTime newT = [self bounceTime:t]; - [other update:newT]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseBounceIn actionWithAction: [other reverse]]; -} - -@end - -@implementation CCEaseBounceInOut - --(void) update: (ccTime) t -{ - ccTime newT = 0; - if (t < 0.5) { - t = t * 2; - newT = (1 - [self bounceTime:1-t] ) * 0.5f; - } else - newT = [self bounceTime:t * 2 - 1] * 0.5f + 0.5f; - - [other update:newT]; -} -@end - -#pragma mark - -#pragma mark Ease Back actions - -// -// EaseBackIn -// -@implementation CCEaseBackIn - --(void) update: (ccTime) t -{ - ccTime overshoot = 1.70158f; - [other update: t * t * ((overshoot + 1) * t - overshoot)]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseBackOut actionWithAction: [other reverse]]; -} -@end - -// -// EaseBackOut -// -@implementation CCEaseBackOut --(void) update: (ccTime) t -{ - ccTime overshoot = 1.70158f; - - t = t - 1; - [other update: t * t * ((overshoot + 1) * t + overshoot) + 1]; -} - -- (CCActionInterval*) reverse -{ - return [CCEaseBackIn actionWithAction: [other reverse]]; -} -@end - -// -// EaseBackInOut -// -@implementation CCEaseBackInOut - --(void) update: (ccTime) t -{ - ccTime overshoot = 1.70158f * 1.525f; - - t = t * 2; - if (t < 1) - [other update: (t * t * ((overshoot + 1) * t - overshoot)) / 2]; - else { - t = t - 2; - [other update: (t * t * ((overshoot + 1) * t + overshoot)) / 2 + 1]; - } -} -@end diff --git a/Example/libs/cocos2d/CCActionGrid.h b/Example/libs/cocos2d/CCActionGrid.h deleted file mode 100644 index 244ee79..0000000 --- a/Example/libs/cocos2d/CCActionGrid.h +++ /dev/null @@ -1,165 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionInterval.h" -#import "CCActionInstant.h" -#import "CCGrid.h" - -@class CCGridBase; - -/** Base class for Grid actions */ -@interface CCGridAction : CCActionInterval -{ - ccGridSize gridSize_; -} - -/** size of the grid */ -@property (nonatomic,readwrite) ccGridSize gridSize; - -/** creates the action with size and duration */ -+(id) actionWithSize:(ccGridSize)size duration:(ccTime)d; -/** initializes the action with size and duration */ --(id) initWithSize:(ccGridSize)gridSize duration:(ccTime)d; -/** returns the grid */ --(CCGridBase *)grid; - -@end - -//////////////////////////////////////////////////////////// - -/** Base class for CCGrid3D actions. - Grid3D actions can modify a non-tiled grid. - */ -@interface CCGrid3DAction : CCGridAction -{ -} - -/** returns the vertex than belongs to certain position in the grid */ --(ccVertex3F)vertex:(ccGridSize)pos; -/** returns the non-transformed vertex than belongs to certain position in the grid */ --(ccVertex3F)originalVertex:(ccGridSize)pos; -/** sets a new vertex to a certain position of the grid */ --(void)setVertex:(ccGridSize)pos vertex:(ccVertex3F)vertex; - -@end - -//////////////////////////////////////////////////////////// - -/** Base class for CCTiledGrid3D actions */ -@interface CCTiledGrid3DAction : CCGridAction -{ -} - -/** returns the tile that belongs to a certain position of the grid */ --(ccQuad3)tile:(ccGridSize)pos; -/** returns the non-transformed tile that belongs to a certain position of the grid */ --(ccQuad3)originalTile:(ccGridSize)pos; -/** sets a new tile to a certain position of the grid */ --(void)setTile:(ccGridSize)pos coords:(ccQuad3)coords; - -@end - -//////////////////////////////////////////////////////////// - -/** CCAccelDeccelAmplitude action */ -@interface CCAccelDeccelAmplitude : CCActionInterval -{ - float rate_; - CCActionInterval *other_; -} - -/** amplitude rate */ -@property (nonatomic,readwrite) float rate; - -/** creates the action with an inner action that has the amplitude property, and a duration time */ -+(id)actionWithAction:(CCAction*)action duration:(ccTime)d; -/** initializes the action with an inner action that has the amplitude property, and a duration time */ --(id)initWithAction:(CCAction*)action duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCAccelAmplitude action */ -@interface CCAccelAmplitude : CCActionInterval -{ - float rate_; - CCActionInterval *other_; -} - -/** amplitude rate */ -@property (nonatomic,readwrite) float rate; - -/** creates the action with an inner action that has the amplitude property, and a duration time */ -+(id)actionWithAction:(CCAction*)action duration:(ccTime)d; -/** initializes the action with an inner action that has the amplitude property, and a duration time */ --(id)initWithAction:(CCAction*)action duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCDeccelAmplitude action */ -@interface CCDeccelAmplitude : CCActionInterval -{ - float rate_; - CCActionInterval *other_; -} - -/** amplitude rate */ -@property (nonatomic,readwrite) float rate; - -/** creates the action with an inner action that has the amplitude property, and a duration time */ -+(id)actionWithAction:(CCAction*)action duration:(ccTime)d; -/** initializes the action with an inner action that has the amplitude property, and a duration time */ --(id)initWithAction:(CCAction*)action duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCStopGrid action. - Don't call this action if another grid action is active. - Call if you want to remove the the grid effect. Example: - [Sequence actions:[Lens ...], [StopGrid action], nil]; - */ -@interface CCStopGrid : CCActionInstant -{ -} -@end - -//////////////////////////////////////////////////////////// - -/** CCReuseGrid action */ -@interface CCReuseGrid : CCActionInstant -{ - int t_; -} -/** creates an action with the number of times that the current grid will be reused */ -+(id) actionWithTimes: (int) times; -/** initializes an action with the number of times that the current grid will be reused */ --(id) initWithTimes: (int) times; -@end diff --git a/Example/libs/cocos2d/CCActionGrid.m b/Example/libs/cocos2d/CCActionGrid.m deleted file mode 100644 index fd87ac8..0000000 --- a/Example/libs/cocos2d/CCActionGrid.m +++ /dev/null @@ -1,386 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionGrid.h" -#import "CCDirector.h" - -#pragma mark - -#pragma mark GridAction - -@implementation CCGridAction - -@synthesize gridSize = gridSize_; - -+(id) actionWithSize:(ccGridSize)size duration:(ccTime)d -{ - return [[[self alloc] initWithSize:size duration:d ] autorelease]; -} - --(id) initWithSize:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithDuration:d]) ) - { - gridSize_ = gSize; - } - - return self; -} - --(void)startWithTarget:(id)target -{ - [super startWithTarget:target]; - - CCGridBase *newgrid = [self grid]; - - CCNode *t = (CCNode*) target; - CCGridBase *targetGrid = [t grid]; - - if ( targetGrid && targetGrid.reuseGrid > 0 ) - { - if ( targetGrid.active && targetGrid.gridSize.x == gridSize_.x && targetGrid.gridSize.y == gridSize_.y && [targetGrid isKindOfClass:[newgrid class]] ) - [targetGrid reuse]; - else - [NSException raise:@"GridBase" format:@"Cannot reuse grid"]; - } - else - { - if ( targetGrid && targetGrid.active ) - targetGrid.active = NO; - - [t setGrid: newgrid]; - t.grid.active = YES; - } -} - --(CCGridBase *)grid -{ - [NSException raise:@"GridBase" format:@"Abstract class needs implementation"]; - return nil; -} - -- (CCActionInterval*) reverse -{ - return [CCReverseTime actionWithAction:self]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithSize:gridSize_ duration:duration_]; - return copy; -} -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark Grid3DAction - -@implementation CCGrid3DAction - --(CCGridBase *)grid -{ - return [CCGrid3D gridWithSize:gridSize_]; -} - --(ccVertex3F)vertex:(ccGridSize)pos -{ - CCGrid3D *g = (CCGrid3D *)[target_ grid]; - return [g vertex:pos]; -} - --(ccVertex3F)originalVertex:(ccGridSize)pos -{ - CCGrid3D *g = (CCGrid3D *)[target_ grid]; - return [g originalVertex:pos]; -} - --(void)setVertex:(ccGridSize)pos vertex:(ccVertex3F)vertex -{ - CCGrid3D *g = (CCGrid3D *)[target_ grid]; - [g setVertex:pos vertex:vertex]; -} -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark TiledGrid3DAction - -@implementation CCTiledGrid3DAction - --(CCGridBase *)grid -{ - return [CCTiledGrid3D gridWithSize:gridSize_]; -} - --(ccQuad3)tile:(ccGridSize)pos -{ - CCTiledGrid3D *g = (CCTiledGrid3D *)[target_ grid]; - return [g tile:pos]; -} - --(ccQuad3)originalTile:(ccGridSize)pos -{ - CCTiledGrid3D *g = (CCTiledGrid3D *)[target_ grid]; - return [g originalTile:pos]; -} - --(void)setTile:(ccGridSize)pos coords:(ccQuad3)coords -{ - CCTiledGrid3D *g = (CCTiledGrid3D *)[target_ grid]; - [g setTile:pos coords:coords]; -} - -@end - -//////////////////////////////////////////////////////////// - -@interface CCActionInterval (Amplitude) --(void)setAmplitudeRate:(CGFloat)amp; --(CGFloat)getAmplitudeRate; -@end - -@implementation CCActionInterval (Amplitude) --(void)setAmplitudeRate:(CGFloat)amp -{ - [NSException raise:@"IntervalAction (Amplitude)" format:@"Abstract class needs implementation"]; -} - --(CGFloat)getAmplitudeRate -{ - [NSException raise:@"IntervalAction (Amplitude)" format:@"Abstract class needs implementation"]; - return 0; -} -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark AccelDeccelAmplitude - -@implementation CCAccelDeccelAmplitude - -@synthesize rate=rate_; - -+(id)actionWithAction:(CCAction*)action duration:(ccTime)d -{ - return [[[self alloc] initWithAction:action duration:d ] autorelease]; -} - --(id)initWithAction:(CCAction *)action duration:(ccTime)d -{ - if ( (self = [super initWithDuration:d]) ) - { - rate_ = 1.0f; - other_ = (CCActionInterval*)[action retain]; - } - - return self; -} - --(void)dealloc -{ - [other_ release]; - [super dealloc]; -} - --(void)startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - [other_ startWithTarget:target_]; -} - --(void) update: (ccTime) time -{ - float f = time*2; - - if (f > 1) - { - f -= 1; - f = 1 - f; - } - - [other_ setAmplitudeRate:powf(f, rate_)]; - [other_ update:time]; -} - -- (CCActionInterval*) reverse -{ - return [CCAccelDeccelAmplitude actionWithAction:[other_ reverse] duration:duration_]; -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark AccelAmplitude - -@implementation CCAccelAmplitude - -@synthesize rate=rate_; - -+(id)actionWithAction:(CCAction*)action duration:(ccTime)d -{ - return [[[self alloc] initWithAction:action duration:d ] autorelease]; -} - --(id)initWithAction:(CCAction *)action duration:(ccTime)d -{ - if ( (self = [super initWithDuration:d]) ) - { - rate_ = 1.0f; - other_ = (CCActionInterval*)[action retain]; - } - - return self; -} - --(void)dealloc -{ - [other_ release]; - [super dealloc]; -} - --(void)startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - [other_ startWithTarget:target_]; -} - --(void) update: (ccTime) time -{ - [other_ setAmplitudeRate:powf(time, rate_)]; - [other_ update:time]; -} - -- (CCActionInterval*) reverse -{ - return [CCAccelAmplitude actionWithAction:[other_ reverse] duration:self.duration]; -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark DeccelAmplitude - -@implementation CCDeccelAmplitude - -@synthesize rate=rate_; - -+(id)actionWithAction:(CCAction*)action duration:(ccTime)d -{ - return [[[self alloc] initWithAction:action duration:d ] autorelease]; -} - --(id)initWithAction:(CCAction *)action duration:(ccTime)d -{ - if ( (self = [super initWithDuration:d]) ) - { - rate_ = 1.0f; - other_ = (CCActionInterval*)[action retain]; - } - - return self; -} - --(void)dealloc -{ - [other_ release]; - [super dealloc]; -} - --(void)startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - [other_ startWithTarget:target_]; -} - --(void) update: (ccTime) time -{ - [other_ setAmplitudeRate:powf((1-time), rate_)]; - [other_ update:time]; -} - -- (CCActionInterval*) reverse -{ - return [CCDeccelAmplitude actionWithAction:[other_ reverse] duration:self.duration]; -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark StopGrid - -@implementation CCStopGrid - --(void)startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - - if ( [[self target] grid] && [[[self target] grid] active] ) { - [[[self target] grid] setActive: NO]; - -// [[self target] setGrid: nil]; - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark ReuseGrid - -@implementation CCReuseGrid - -+(id)actionWithTimes:(int)times -{ - return [[[self alloc] initWithTimes:times ] autorelease]; -} - --(id)initWithTimes:(int)times -{ - if ( (self = [super init]) ) - t_ = times; - - return self; -} - --(void)startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - - CCNode *myTarget = (CCNode*) [self target]; - if ( myTarget.grid && myTarget.grid.active ) - myTarget.grid.reuseGrid += t_; -} - -@end diff --git a/Example/libs/cocos2d/CCActionGrid3D.h b/Example/libs/cocos2d/CCActionGrid3D.h deleted file mode 100644 index 7e1c40e..0000000 --- a/Example/libs/cocos2d/CCActionGrid3D.h +++ /dev/null @@ -1,205 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionGrid.h" - -/** CCWaves3D action */ -@interface CCWaves3D : CCGrid3DAction -{ - int waves; - float amplitude; - float amplitudeRate; -} - -/** amplitude of the wave */ -@property (nonatomic,readwrite) float amplitude; -/** amplitude rate of the wave */ -@property (nonatomic,readwrite) float amplitudeRate; - -+(id)actionWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; --(id)initWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCFlipX3D action */ -@interface CCFlipX3D : CCGrid3DAction -{ -} - -/** creates the action with duration */ -+(id) actionWithDuration:(ccTime)d; -/** initizlies the action with duration */ --(id) initWithDuration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCFlipY3D action */ -@interface CCFlipY3D : CCFlipX3D -{ -} - -@end - -//////////////////////////////////////////////////////////// - -/** CCLens3D action */ -@interface CCLens3D : CCGrid3DAction -{ - CGPoint position_; - float radius_; - float lensEffect_; - BOOL dirty_; -} - -/** lens effect. Defaults to 0.7 - 0 means no effect, 1 is very strong effect */ -@property (nonatomic,readwrite) float lensEffect; -/** lens center position in Points */ -@property (nonatomic,readwrite) CGPoint position; - -/** creates the action with center position in Points, radius, a grid size and duration */ -+(id)actionWithPosition:(CGPoint)pos radius:(float)r grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with center position in Points, radius, a grid size and duration */ --(id)initWithPosition:(CGPoint)pos radius:(float)r grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCRipple3D action */ -@interface CCRipple3D : CCGrid3DAction -{ - CGPoint position_; - float radius_; - int waves_; - float amplitude_; - float amplitudeRate_; -} - -/** center position in Points */ -@property (nonatomic,readwrite) CGPoint position; -/** amplitude */ -@property (nonatomic,readwrite) float amplitude; -/** amplitude rate */ -@property (nonatomic,readwrite) float amplitudeRate; - -/** creates the action with a position in points, radius, number of waves, amplitude, a grid size and duration */ -+(id)actionWithPosition:(CGPoint)pos radius:(float)r waves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with a position in points, radius, number of waves, amplitude, a grid size and duration */ --(id)initWithPosition:(CGPoint)pos radius:(float)r waves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCShaky3D action */ -@interface CCShaky3D : CCGrid3DAction -{ - int randrange; - BOOL shakeZ; -} - -/** creates the action with a range, shake Z vertices, a grid and duration */ -+(id)actionWithRange:(int)range shakeZ:(BOOL)shakeZ grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with a range, shake Z vertices, a grid and duration */ --(id)initWithRange:(int)range shakeZ:(BOOL)shakeZ grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCLiquid action */ -@interface CCLiquid : CCGrid3DAction -{ - int waves; - float amplitude; - float amplitudeRate; - -} - -/** amplitude */ -@property (nonatomic,readwrite) float amplitude; -/** amplitude rate */ -@property (nonatomic,readwrite) float amplitudeRate; - -/** creates the action with amplitude, a grid and duration */ -+(id)actionWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with amplitude, a grid and duration */ --(id)initWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCWaves action */ -@interface CCWaves : CCGrid3DAction -{ - int waves; - float amplitude; - float amplitudeRate; - BOOL vertical; - BOOL horizontal; -} - -/** amplitude */ -@property (nonatomic,readwrite) float amplitude; -/** amplitude rate */ -@property (nonatomic,readwrite) float amplitudeRate; - -/** initializes the action with amplitude, horizontal sin, vertical sin, a grid and duration */ -+(id)actionWithWaves:(int)wav amplitude:(float)amp horizontal:(BOOL)h vertical:(BOOL)v grid:(ccGridSize)gridSize duration:(ccTime)d; -/** creates the action with amplitude, horizontal sin, vertical sin, a grid and duration */ --(id)initWithWaves:(int)wav amplitude:(float)amp horizontal:(BOOL)h vertical:(BOOL)v grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCTwirl action */ -@interface CCTwirl : CCGrid3DAction -{ - CGPoint position_; - int twirls_; - float amplitude_; - float amplitudeRate_; -} - -/** twirl center */ -@property (nonatomic,readwrite) CGPoint position; -/** amplitude */ -@property (nonatomic,readwrite) float amplitude; -/** amplitude rate */ -@property (nonatomic,readwrite) float amplitudeRate; - -/** creates the action with center position, number of twirls, amplitude, a grid size and duration */ -+(id)actionWithPosition:(CGPoint)pos twirls:(int)t amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with center position, number of twirls, amplitude, a grid size and duration */ --(id)initWithPosition:(CGPoint)pos twirls:(int)t amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end diff --git a/Example/libs/cocos2d/CCActionGrid3D.m b/Example/libs/cocos2d/CCActionGrid3D.m deleted file mode 100644 index e9fb707..0000000 --- a/Example/libs/cocos2d/CCActionGrid3D.m +++ /dev/null @@ -1,652 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionGrid3D.h" -#import "ccMacros.h" -#import "Support/CGPointExtension.h" - -#pragma mark - -#pragma mark Waves3D - -@implementation CCWaves3D - -@synthesize amplitude; -@synthesize amplitudeRate; - -+(id)actionWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithWaves:wav amplitude:amp grid:gridSize duration:d] autorelease]; -} - --(id)initWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - waves = wav; - amplitude = amp; - amplitudeRate = 1.0f; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithWaves:waves amplitude:amplitude grid:gridSize_ duration:duration_]; - return copy; -} - - --(void)update:(ccTime)time -{ - int i, j; - - for( i = 0; i < (gridSize_.x+1); i++ ) - { - for( j = 0; j < (gridSize_.y+1); j++ ) - { - ccVertex3F v = [self originalVertex:ccg(i,j)]; - v.z += (sinf((CGFloat)M_PI*time*waves*2 + (v.y+v.x) * .01f) * amplitude * amplitudeRate); - [self setVertex:ccg(i,j) vertex:v]; - } - } -} -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark FlipX3D - -@implementation CCFlipX3D - -+(id) actionWithDuration:(ccTime)d -{ - return [[[self alloc] initWithSize:ccg(1,1) duration:d] autorelease]; -} - --(id) initWithDuration:(ccTime)d -{ - return [super initWithSize:ccg(1,1) duration:d]; -} - --(id)initWithSize:(ccGridSize)gSize duration:(ccTime)d -{ - if ( gSize.x != 1 || gSize.y != 1 ) - { - [NSException raise:@"FlipX3D" format:@"Grid size must be (1,1)"]; - } - - return [super initWithSize:gSize duration:d]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithSize:gridSize_ duration:duration_]; - return copy; -} - - --(void)update:(ccTime)time -{ - CGFloat angle = (CGFloat)M_PI * time; // 180 degrees - CGFloat mz = sinf( angle ); - angle = angle / 2.0f; // x calculates degrees from 0 to 90 - CGFloat mx = cosf( angle ); - - ccVertex3F v0, v1, v, diff; - - v0 = [self originalVertex:ccg(1,1)]; - v1 = [self originalVertex:ccg(0,0)]; - - CGFloat x0 = v0.x; - CGFloat x1 = v1.x; - CGFloat x; - ccGridSize a, b, c, d; - - if ( x0 > x1 ) - { - // Normal Grid - a = ccg(0,0); - b = ccg(0,1); - c = ccg(1,0); - d = ccg(1,1); - x = x0; - } - else - { - // Reversed Grid - c = ccg(0,0); - d = ccg(0,1); - a = ccg(1,0); - b = ccg(1,1); - x = x1; - } - - diff.x = ( x - x * mx ); - diff.z = fabsf( floorf( (x * mz) / 4.0f ) ); - -// bottom-left - v = [self originalVertex:a]; - v.x = diff.x; - v.z += diff.z; - [self setVertex:a vertex:v]; - -// upper-left - v = [self originalVertex:b]; - v.x = diff.x; - v.z += diff.z; - [self setVertex:b vertex:v]; - -// bottom-right - v = [self originalVertex:c]; - v.x -= diff.x; - v.z -= diff.z; - [self setVertex:c vertex:v]; - -// upper-right - v = [self originalVertex:d]; - v.x -= diff.x; - v.z -= diff.z; - [self setVertex:d vertex:v]; -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark FlipY3D - -@implementation CCFlipY3D - --(void)update:(ccTime)time -{ - CGFloat angle = (CGFloat)M_PI * time; // 180 degrees - CGFloat mz = sinf( angle ); - angle = angle / 2.0f; // x calculates degrees from 0 to 90 - CGFloat my = cosf( angle ); - - ccVertex3F v0, v1, v, diff; - - v0 = [self originalVertex:ccg(1,1)]; - v1 = [self originalVertex:ccg(0,0)]; - - CGFloat y0 = v0.y; - CGFloat y1 = v1.y; - CGFloat y; - ccGridSize a, b, c, d; - - if ( y0 > y1 ) - { - // Normal Grid - a = ccg(0,0); - b = ccg(0,1); - c = ccg(1,0); - d = ccg(1,1); - y = y0; - } - else - { - // Reversed Grid - b = ccg(0,0); - a = ccg(0,1); - d = ccg(1,0); - c = ccg(1,1); - y = y1; - } - - diff.y = y - y * my; - diff.z = fabsf( floorf( (y * mz) / 4.0f ) ); - - // bottom-left - v = [self originalVertex:a]; - v.y = diff.y; - v.z += diff.z; - [self setVertex:a vertex:v]; - - // upper-left - v = [self originalVertex:b]; - v.y -= diff.y; - v.z -= diff.z; - [self setVertex:b vertex:v]; - - // bottom-right - v = [self originalVertex:c]; - v.y = diff.y; - v.z += diff.z; - [self setVertex:c vertex:v]; - - // upper-right - v = [self originalVertex:d]; - v.y -= diff.y; - v.z -= diff.z; - [self setVertex:d vertex:v]; -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark Lens3D - -@implementation CCLens3D - -@synthesize lensEffect=lensEffect_; - -+(id)actionWithPosition:(CGPoint)pos radius:(float)r grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithPosition:pos radius:r grid:gridSize duration:d] autorelease]; -} - --(id)initWithPosition:(CGPoint)pos radius:(float)r grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - position_ = ccp(-1,-1); - self.position = pos; - radius_ = r; - lensEffect_ = 0.7f; - dirty_ = YES; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithPosition:position_ radius:radius_ grid:gridSize_ duration:duration_]; - return copy; -} - --(void) setPosition:(CGPoint)pos -{ - if( ! CGPointEqualToPoint(pos, position_) ) { - position_ = pos; - dirty_ = YES; - } -} - --(CGPoint) position -{ - return position_; -} - --(void)update:(ccTime)time -{ - if ( dirty_ ) - { - int i, j; - - for( i = 0; i < gridSize_.x+1; i++ ) - { - for( j = 0; j < gridSize_.y+1; j++ ) - { - ccVertex3F v = [self originalVertex:ccg(i,j)]; - CGPoint vect = ccpSub(position_, ccp(v.x,v.y)); - CGFloat r = ccpLength(vect); - - if ( r < radius_ ) - { - r = radius_ - r; - CGFloat pre_log = r / radius_; - if ( pre_log == 0 ) pre_log = 0.001f; - float l = logf(pre_log) * lensEffect_; - float new_r = expf( l ) * radius_; - - if ( ccpLength(vect) > 0 ) - { - vect = ccpNormalize(vect); - CGPoint new_vect = ccpMult(vect, new_r); - v.z += ccpLength(new_vect) * lensEffect_; - } - } - - [self setVertex:ccg(i,j) vertex:v]; - } - } - - dirty_ = NO; - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark Ripple3D - -@implementation CCRipple3D - -@synthesize amplitude = amplitude_; -@synthesize amplitudeRate = amplitudeRate_; - -+(id)actionWithPosition:(CGPoint)pos radius:(float)r waves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithPosition:pos radius:r waves:wav amplitude:amp grid:gridSize duration:d] autorelease]; -} - --(id)initWithPosition:(CGPoint)pos radius:(float)r waves:(int)wav amplitude:(float)amp grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - self.position = pos; - radius_ = r; - waves_ = wav; - amplitude_ = amp; - amplitudeRate_ = 1.0f; - } - - return self; -} - --(CGPoint) position -{ - return position_; -} - --(void) setPosition:(CGPoint)pos -{ - position_ = pos; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithPosition:position_ radius:radius_ waves:waves_ amplitude:amplitude_ grid:gridSize_ duration:duration_]; - return copy; -} - - --(void)update:(ccTime)time -{ - int i, j; - - for( i = 0; i < (gridSize_.x+1); i++ ) - { - for( j = 0; j < (gridSize_.y+1); j++ ) - { - ccVertex3F v = [self originalVertex:ccg(i,j)]; - CGPoint vect = ccpSub(position_, ccp(v.x,v.y)); - CGFloat r = ccpLength(vect); - - if ( r < radius_ ) - { - r = radius_ - r; - CGFloat rate = powf( r / radius_, 2); - v.z += (sinf( time*(CGFloat)M_PI*waves_*2 + r * 0.1f) * amplitude_ * amplitudeRate_ * rate ); - } - - [self setVertex:ccg(i,j) vertex:v]; - } - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark Shaky3D - -@implementation CCShaky3D - -+(id)actionWithRange:(int)range shakeZ:(BOOL)sz grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithRange:range shakeZ:sz grid:gridSize duration:d] autorelease]; -} - --(id)initWithRange:(int)range shakeZ:(BOOL)sz grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - randrange = range; - shakeZ = sz; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithRange:randrange shakeZ:shakeZ grid:gridSize_ duration:duration_]; - return copy; -} - --(void)update:(ccTime)time -{ - int i, j; - - for( i = 0; i < (gridSize_.x+1); i++ ) - { - for( j = 0; j < (gridSize_.y+1); j++ ) - { - ccVertex3F v = [self originalVertex:ccg(i,j)]; - v.x += ( rand() % (randrange*2) ) - randrange; - v.y += ( rand() % (randrange*2) ) - randrange; - if( shakeZ ) - v.z += ( rand() % (randrange*2) ) - randrange; - - [self setVertex:ccg(i,j) vertex:v]; - } - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark Liquid - -@implementation CCLiquid - -@synthesize amplitude; -@synthesize amplitudeRate; - -+(id)actionWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithWaves:wav amplitude:amp grid:gridSize duration:d] autorelease]; -} - --(id)initWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - waves = wav; - amplitude = amp; - amplitudeRate = 1.0f; - } - - return self; -} - --(void)update:(ccTime)time -{ - int i, j; - - for( i = 1; i < gridSize_.x; i++ ) - { - for( j = 1; j < gridSize_.y; j++ ) - { - ccVertex3F v = [self originalVertex:ccg(i,j)]; - v.x = (v.x + (sinf(time*(CGFloat)M_PI*waves*2 + v.x * .01f) * amplitude * amplitudeRate)); - v.y = (v.y + (sinf(time*(CGFloat)M_PI*waves*2 + v.y * .01f) * amplitude * amplitudeRate)); - [self setVertex:ccg(i,j) vertex:v]; - } - } -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithWaves:waves amplitude:amplitude grid:gridSize_ duration:duration_]; - return copy; -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark Waves - -@implementation CCWaves - -@synthesize amplitude; -@synthesize amplitudeRate; - -+(id)actionWithWaves:(int)wav amplitude:(float)amp horizontal:(BOOL)h vertical:(BOOL)v grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithWaves:wav amplitude:amp horizontal:h vertical:v grid:gridSize duration:d] autorelease]; -} - --(id)initWithWaves:(int)wav amplitude:(float)amp horizontal:(BOOL)h vertical:(BOOL)v grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - waves = wav; - amplitude = amp; - amplitudeRate = 1.0f; - horizontal = h; - vertical = v; - } - - return self; -} - --(void)update:(ccTime)time -{ - int i, j; - - for( i = 0; i < (gridSize_.x+1); i++ ) - { - for( j = 0; j < (gridSize_.y+1); j++ ) - { - ccVertex3F v = [self originalVertex:ccg(i,j)]; - - if ( vertical ) - v.x = (v.x + (sinf(time*(CGFloat)M_PI*waves*2 + v.y * .01f) * amplitude * amplitudeRate)); - - if ( horizontal ) - v.y = (v.y + (sinf(time*(CGFloat)M_PI*waves*2 + v.x * .01f) * amplitude * amplitudeRate)); - - [self setVertex:ccg(i,j) vertex:v]; - } - } -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithWaves:waves amplitude:amplitude horizontal:horizontal vertical:vertical grid:gridSize_ duration:duration_]; - return copy; -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark Twirl - -@implementation CCTwirl - -@synthesize amplitude = amplitude_; -@synthesize amplitudeRate = amplitudeRate_; - -+(id)actionWithPosition:(CGPoint)pos twirls:(int)t amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithPosition:pos twirls:t amplitude:amp grid:gridSize duration:d] autorelease]; -} - --(id)initWithPosition:(CGPoint)pos twirls:(int)t amplitude:(float)amp grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - self.position = pos; - twirls_ = t; - amplitude_ = amp; - amplitudeRate_ = 1.0f; - } - - return self; -} - --(void) setPosition:(CGPoint)pos -{ - position_ = pos; -} - --(CGPoint) position -{ - return position_; -} - --(void)update:(ccTime)time -{ - int i, j; - CGPoint c = position_; - - for( i = 0; i < (gridSize_.x+1); i++ ) - { - for( j = 0; j < (gridSize_.y+1); j++ ) - { - ccVertex3F v = [self originalVertex:ccg(i,j)]; - - CGPoint avg = ccp(i-(gridSize_.x/2.0f), j-(gridSize_.y/2.0f)); - CGFloat r = ccpLength( avg ); - - CGFloat amp = 0.1f * amplitude_ * amplitudeRate_; - CGFloat a = r * cosf( (CGFloat)M_PI/2.0f + time * (CGFloat)M_PI * twirls_ * 2 ) * amp; - - float cosA = cosf(a); - float sinA = sinf(a); - - CGPoint d = { - sinA * (v.y-c.y) + cosA * (v.x-c.x), - cosA * (v.y-c.y) - sinA * (v.x-c.x) - }; - - v.x = c.x + d.x; - v.y = c.y + d.y; - - [self setVertex:ccg(i,j) vertex:v]; - } - } -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithPosition:position_ - twirls:twirls_ - amplitude:amplitude_ - grid:gridSize_ - duration:duration_]; - return copy; -} - - -@end diff --git a/Example/libs/cocos2d/CCActionInstant.h b/Example/libs/cocos2d/CCActionInstant.h deleted file mode 100644 index 928732b..0000000 --- a/Example/libs/cocos2d/CCActionInstant.h +++ /dev/null @@ -1,227 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCAction.h" - -/** Instant actions are immediate actions. They don't have a duration like - the CCIntervalAction actions. -*/ -@interface CCActionInstant : CCFiniteTimeAction -{ -} -@end - -/** Show the node - */ - @interface CCShow : CCActionInstant -{ -} -@end - -/** Hide the node - */ -@interface CCHide : CCActionInstant -{ -} -@end - -/** Toggles the visibility of a node - */ -@interface CCToggleVisibility : CCActionInstant -{ -} -@end - -/** Flips the sprite horizontally - @since v0.99.0 - */ -@interface CCFlipX : CCActionInstant -{ - BOOL flipX; -} -+(id) actionWithFlipX:(BOOL)x; --(id) initWithFlipX:(BOOL)x; -@end - -/** Flips the sprite vertically - @since v0.99.0 - */ -@interface CCFlipY : CCActionInstant -{ - BOOL flipY; -} -+(id) actionWithFlipY:(BOOL)y; --(id) initWithFlipY:(BOOL)y; -@end - -/** Places the node in a certain position - */ -@interface CCPlace : CCActionInstant -{ - CGPoint position; -} -/** creates a Place action with a position */ -+(id) actionWithPosition: (CGPoint) pos; -/** Initializes a Place action with a position */ --(id) initWithPosition: (CGPoint) pos; -@end - -/** Calls a 'callback' - */ -@interface CCCallFunc : CCActionInstant -{ - id targetCallback_; - SEL selector_; -} - -/** Target that will be called */ -@property (nonatomic, readwrite, retain) id targetCallback; - -/** creates the action with the callback */ -+(id) actionWithTarget: (id) t selector:(SEL) s; -/** initializes the action with the callback */ --(id) initWithTarget: (id) t selector:(SEL) s; -/** exeuctes the callback */ --(void) execute; -@end - -/** Calls a 'callback' with the node as the first argument. - N means Node - */ -@interface CCCallFuncN : CCCallFunc -{ -} -@end - -typedef void (*CC_CALLBACK_ND)(id, SEL, id, void *); -/** Calls a 'callback' with the node as the first argument and the 2nd argument is data. - * ND means: Node and Data. Data is void *, so it could be anything. - */ -@interface CCCallFuncND : CCCallFuncN -{ - void *data_; - CC_CALLBACK_ND callbackMethod_; -} - -/** Invocation object that has the target#selector and the parameters */ -@property (nonatomic,readwrite) CC_CALLBACK_ND callbackMethod; - -/** creates the action with the callback and the data to pass as an argument */ -+(id) actionWithTarget: (id) t selector:(SEL) s data:(void*)d; -/** initializes the action with the callback and the data to pass as an argument */ --(id) initWithTarget:(id) t selector:(SEL) s data:(void*) d; -@end - -/** Calls a 'callback' with an object as the first argument. - O means Object. - @since v0.99.5 - */ -@interface CCCallFuncO : CCCallFunc -{ - id object_; -} -/** object to be passed as argument */ -@property (nonatomic, readwrite, retain) id object; - -/** creates the action with the callback and the object to pass as an argument */ -+(id) actionWithTarget: (id) t selector:(SEL) s object:(id)object; -/** initializes the action with the callback and the object to pass as an argument */ --(id) initWithTarget:(id) t selector:(SEL) s object:(id)object; - -@end - -#pragma mark Blocks Support - -/** Executes a callback using a block. - */ -@interface CCCallBlock : CCActionInstant -{ - void (^block_)(); -} - -/** creates the action with the specified block, to be used as a callback. - The block will be "copied". - */ -+(id) actionWithBlock:(void(^)())block; - -/** initialized the action with the specified block, to be used as a callback. - The block will be "copied". - */ --(id) initWithBlock:(void(^)())block; - -/** executes the callback */ --(void) execute; -@end - -@class CCNode; - -/** Executes a callback using a block with a single CCNode parameter. - */ -@interface CCCallBlockN : CCActionInstant -{ - void (^block_)(CCNode *); -} - -/** creates the action with the specified block, to be used as a callback. - The block will be "copied". - */ -+(id) actionWithBlock:(void(^)(CCNode *node))block; - -/** initialized the action with the specified block, to be used as a callback. - The block will be "copied". - */ --(id) initWithBlock:(void(^)(CCNode *node))block; - -/** executes the callback */ --(void) execute; -@end - -/** Executes a callback using a block with a single NSObject parameter. - @since v2.0 - */ -@interface CCCallBlockO : CCActionInstant -{ - void (^block_)(id object); - id object_; -} - -/** object to be passed to the block */ -@property (nonatomic,retain) id object; - -/** creates the action with the specified block, to be used as a callback. - The block will be "copied". - */ -+(id) actionWithBlock:(void(^)(id object))block object:(id)object; - -/** initialized the action with the specified block, to be used as a callback. - The block will be "copied". - */ --(id) initWithBlock:(void(^)(id object))block object:(id)object; - -/** executes the callback */ --(void) execute; -@end diff --git a/Example/libs/cocos2d/CCActionInstant.m b/Example/libs/cocos2d/CCActionInstant.m deleted file mode 100644 index 90a82c9..0000000 --- a/Example/libs/cocos2d/CCActionInstant.m +++ /dev/null @@ -1,510 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionInstant.h" -#import "CCNode.h" -#import "CCSprite.h" - - -// -// InstantAction -// -#pragma mark CCActionInstant - -@implementation CCActionInstant - --(id) init -{ - if( (self=[super init]) ) - duration_ = 0; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] init]; - return copy; -} - -- (BOOL) isDone -{ - return YES; -} - --(void) step: (ccTime) dt -{ - [self update: 1]; -} - --(void) update: (ccTime) t -{ - // nothing -} - --(CCFiniteTimeAction*) reverse -{ - return [[self copy] autorelease]; -} -@end - -// -// Show -// -#pragma mark CCShow - -@implementation CCShow --(void) update:(ccTime)time -{ - ((CCNode *)target_).visible = YES; -} - --(CCFiniteTimeAction*) reverse -{ - return [CCHide action]; -} -@end - -// -// Hide -// -#pragma mark CCHide - -@implementation CCHide --(void) update:(ccTime)time -{ - ((CCNode *)target_).visible = NO; -} - --(CCFiniteTimeAction*) reverse -{ - return [CCShow action]; -} -@end - -// -// ToggleVisibility -// -#pragma mark CCToggleVisibility - -@implementation CCToggleVisibility --(void) update:(ccTime)time -{ - ((CCNode *)target_).visible = !((CCNode *)target_).visible; -} -@end - -// -// FlipX -// -#pragma mark CCFlipX - -@implementation CCFlipX -+(id) actionWithFlipX:(BOOL)x -{ - return [[[self alloc] initWithFlipX:x] autorelease]; -} - --(id) initWithFlipX:(BOOL)x -{ - if(( self=[super init])) - flipX = x; - - return self; -} - --(void) update:(ccTime)time -{ - [(CCSprite*)target_ setFlipX:flipX]; -} - --(CCFiniteTimeAction*) reverse -{ - return [CCFlipX actionWithFlipX:!flipX]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithFlipX:flipX]; - return copy; -} -@end - -// -// FlipY -// -#pragma mark CCFlipY - -@implementation CCFlipY -+(id) actionWithFlipY:(BOOL)y -{ - return [[[self alloc] initWithFlipY:y] autorelease]; -} - --(id) initWithFlipY:(BOOL)y -{ - if(( self=[super init])) - flipY = y; - - return self; -} - --(void) update:(ccTime)time -{ - [(CCSprite*)target_ setFlipY:flipY]; -} - --(CCFiniteTimeAction*) reverse -{ - return [CCFlipY actionWithFlipY:!flipY]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithFlipY:flipY]; - return copy; -} -@end - - -// -// Place -// -#pragma mark CCPlace - -@implementation CCPlace -+(id) actionWithPosition: (CGPoint) pos -{ - return [[[self alloc]initWithPosition:pos]autorelease]; -} - --(id) initWithPosition: (CGPoint) pos -{ - if( (self=[super init]) ) - position = pos; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithPosition: position]; - return copy; -} - --(void) update:(ccTime)time -{ - ((CCNode *)target_).position = position; -} - -@end - -// -// CallFunc -// -#pragma mark CCCallFunc - -@implementation CCCallFunc - -@synthesize targetCallback = targetCallback_; - -+(id) actionWithTarget: (id) t selector:(SEL) s -{ - return [[[self alloc] initWithTarget: t selector: s] autorelease]; -} - --(id) initWithTarget: (id) t selector:(SEL) s -{ - if( (self=[super init]) ) { - self.targetCallback = t; - selector_ = s; - } - return self; -} - --(NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Tag = %i | target = %@ | selector = %@>", - [self class], - self, - tag_, - [targetCallback_ class], - NSStringFromSelector(selector_) - ]; -} - --(void) dealloc -{ - [targetCallback_ release]; - [super dealloc]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithTarget:targetCallback_ selector:selector_]; - return copy; -} - --(void) update:(ccTime)time -{ - [self execute]; -} - --(void) execute -{ - [targetCallback_ performSelector:selector_]; -} -@end - -// -// CallFuncN -// -#pragma mark CCCallFuncN - -@implementation CCCallFuncN - --(void) execute -{ - [targetCallback_ performSelector:selector_ withObject:target_]; -} -@end - -// -// CallFuncND -// -#pragma mark CCCallFuncND - -@implementation CCCallFuncND - -@synthesize callbackMethod = callbackMethod_; - -+(id) actionWithTarget:(id)t selector:(SEL)s data:(void*)d -{ - return [[[self alloc] initWithTarget:t selector:s data:d] autorelease]; -} - --(id) initWithTarget:(id)t selector:(SEL)s data:(void*)d -{ - if( (self=[super initWithTarget:t selector:s]) ) { - data_ = d; - -#if COCOS2D_DEBUG - NSMethodSignature * sig = [t methodSignatureForSelector:s]; // added - NSAssert(sig !=0 , @"Signature not found for selector - does it have the following form? -(void)name:(id)sender data:(void*)data"); -#endif - callbackMethod_ = (CC_CALLBACK_ND) [t methodForSelector:s]; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithTarget:targetCallback_ selector:selector_ data:data_]; - return copy; -} - --(void) dealloc -{ - // nothing to dealloc really. Everything is dealloc on super (CCCallFuncN) - [super dealloc]; -} - --(void) execute -{ - callbackMethod_(targetCallback_,selector_,target_, data_); -} -@end - -@implementation CCCallFuncO -@synthesize object = object_; - -+(id) actionWithTarget: (id) t selector:(SEL) s object:(id)object -{ - return [[[self alloc] initWithTarget:t selector:s object:object] autorelease]; -} - --(id) initWithTarget:(id) t selector:(SEL) s object:(id)object -{ - if( (self=[super initWithTarget:t selector:s] ) ) - self.object = object; - - return self; -} - -- (void) dealloc -{ - [object_ release]; - [super dealloc]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithTarget:targetCallback_ selector:selector_ object:object_]; - return copy; -} - - --(void) execute -{ - [targetCallback_ performSelector:selector_ withObject:object_]; -} - -@end - - -#pragma mark - -#pragma mark Blocks - -#pragma mark CCCallBlock - -@implementation CCCallBlock - -+(id) actionWithBlock:(void(^)())block -{ - return [[[self alloc] initWithBlock:block] autorelease]; -} - --(id) initWithBlock:(void(^)())block -{ - if ((self = [super init])) - block_ = [block copy]; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithBlock:block_]; - return copy; -} - --(void) update:(ccTime)time -{ - [self execute]; -} - --(void) execute -{ - block_(); -} - --(void) dealloc -{ - [block_ release]; - [super dealloc]; -} - -@end - -#pragma mark CCCallBlockN - -@implementation CCCallBlockN - -+(id) actionWithBlock:(void(^)(CCNode *node))block -{ - return [[[self alloc] initWithBlock:block] autorelease]; -} - --(id) initWithBlock:(void(^)(CCNode *node))block -{ - if ((self = [super init])) - block_ = [block copy]; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithBlock:block_]; - return copy; -} - --(void) update:(ccTime)time -{ - [self execute]; -} - --(void) execute -{ - block_(target_); -} - --(void) dealloc -{ - [block_ release]; - [super dealloc]; -} - -@end - -#pragma mark CCCallBlockO - -@implementation CCCallBlockO - -@synthesize object=object_; - -+(id) actionWithBlock:(void(^)(id object))block object:(id)object -{ - return [[[self alloc] initWithBlock:block object:object] autorelease]; -} - --(id) initWithBlock:(void(^)(id object))block object:(id)object -{ - if ((self = [super init])) { - block_ = [block copy]; - object_ = [object retain]; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCActionInstant *copy = [[[self class] allocWithZone: zone] initWithBlock:block_]; - return copy; -} - --(void) update:(ccTime)time -{ - [self execute]; -} - --(void) execute -{ - block_(object_); -} - --(void) dealloc -{ - [object_ release]; - [block_ release]; - - [super dealloc]; -} - -@end - diff --git a/Example/libs/cocos2d/CCActionInterval.h b/Example/libs/cocos2d/CCActionInterval.h deleted file mode 100644 index 6356768..0000000 --- a/Example/libs/cocos2d/CCActionInterval.h +++ /dev/null @@ -1,431 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCNode.h" -#import "CCAction.h" -#import "CCProtocols.h" - -#include - -/** An interval action is an action that takes place within a certain period of time. -It has an start time, and a finish time. The finish time is the parameter -duration plus the start time. - -These CCActionInterval actions have some interesting properties, like: - - They can run normally (default) - - They can run reversed with the reverse method - - They can run with the time altered with the Accelerate, AccelDeccel and Speed actions. - -For example, you can simulate a Ping Pong effect running the action normally and -then running it again in Reverse mode. - -Example: - - CCAction * pingPongAction = [CCSequence actions: action, [action reverse], nil]; -*/ -@interface CCActionInterval: CCFiniteTimeAction -{ - ccTime elapsed_; - BOOL firstTick_; -} - -/** how many seconds had elapsed since the actions started to run. */ -@property (nonatomic,readonly) ccTime elapsed; - -/** creates the action */ -+(id) actionWithDuration: (ccTime) d; -/** initializes the action */ --(id) initWithDuration: (ccTime) d; -/** returns YES if the action has finished */ --(BOOL) isDone; -/** returns a reversed action */ -- (CCActionInterval*) reverse; -@end - -/** Runs actions sequentially, one after another - */ -@interface CCSequence : CCActionInterval -{ - CCFiniteTimeAction *actions_[2]; - ccTime split_; - int last_; -} -/** helper contructor to create an array of sequenceable actions */ -+(id) actions: (CCFiniteTimeAction*) action1, ... NS_REQUIRES_NIL_TERMINATION; -/** helper contructor to create an array of sequenceable actions given an array */ -+(id) actionsWithArray: (NSArray*) actions; -/** creates the action */ -+(id) actionOne:(CCFiniteTimeAction*)actionOne two:(CCFiniteTimeAction*)actionTwo; -/** initializes the action */ --(id) initOne:(CCFiniteTimeAction*)actionOne two:(CCFiniteTimeAction*)actionTwo; -@end - - -/** Repeats an action a number of times. - * To repeat an action forever use the CCRepeatForever action. - */ -@interface CCRepeat : CCActionInterval -{ - NSUInteger times_; - NSUInteger total_; - ccTime nextDt_; - BOOL isActionInstant_; - CCFiniteTimeAction *innerAction_; -} - -/** Inner action */ -@property (nonatomic,readwrite,retain) CCFiniteTimeAction *innerAction; - -/** creates a CCRepeat action. Times is an unsigned integer between 1 and MAX_UINT. - */ -+(id) actionWithAction:(CCFiniteTimeAction*)action times: (NSUInteger)times; -/** initializes a CCRepeat action. Times is an unsigned integer between 1 and MAX_UINT */ --(id) initWithAction:(CCFiniteTimeAction*)action times: (NSUInteger)times; -@end - -/** Spawn a new action immediately - */ -@interface CCSpawn : CCActionInterval -{ - CCFiniteTimeAction *one_; - CCFiniteTimeAction *two_; -} -/** helper constructor to create an array of spawned actions */ -+(id) actions: (CCFiniteTimeAction*) action1, ... NS_REQUIRES_NIL_TERMINATION; -/** helper contructor to create an array of spawned actions given an array */ -+(id) actionsWithArray: (NSArray*) actions; -/** creates the Spawn action */ -+(id) actionOne: (CCFiniteTimeAction*) one two:(CCFiniteTimeAction*) two; -/** initializes the Spawn action with the 2 actions to spawn */ --(id) initOne: (CCFiniteTimeAction*) one two:(CCFiniteTimeAction*) two; -@end - -/** Rotates a CCNode object to a certain angle by modifying it's - rotation attribute. - The direction will be decided by the shortest angle. -*/ -@interface CCRotateTo : CCActionInterval -{ - float dstAngle_; - float startAngle_; - float diffAngle_; -} -/** creates the action */ -+(id) actionWithDuration:(ccTime)duration angle:(float)angle; -/** initializes the action */ --(id) initWithDuration:(ccTime)duration angle:(float)angle; -@end - -/** Rotates a CCNode object clockwise a number of degrees by modiying its rotation attribute. -*/ -@interface CCRotateBy : CCActionInterval -{ - float angle_; - float startAngle_; -} -/** creates the action */ -+(id) actionWithDuration:(ccTime)duration angle:(float)deltaAngle; -/** initializes the action */ --(id) initWithDuration:(ccTime)duration angle:(float)deltaAngle; -@end - -/** Moves a CCNode object to the position x,y. x and y are absolute coordinates by modifying its position attribute. -*/ -@interface CCMoveTo : CCActionInterval -{ - CGPoint endPosition_; - CGPoint startPosition_; - CGPoint delta_; -} -/** creates the action */ -+(id) actionWithDuration:(ccTime)duration position:(CGPoint)position; -/** initializes the action */ --(id) initWithDuration:(ccTime)duration position:(CGPoint)position; -@end - -/** Moves a CCNode object x,y pixels by modifying its position attribute. - x and y are relative to the position of the object. - Duration is is seconds. -*/ -@interface CCMoveBy : CCMoveTo -{ -} -/** creates the action */ -+(id) actionWithDuration: (ccTime)duration position:(CGPoint)deltaPosition; -/** initializes the action */ --(id) initWithDuration: (ccTime)duration position:(CGPoint)deltaPosition; -@end - -/** Skews a CCNode object to given angles by modifying its skewX and skewY attributes - @since v1.0 - */ -@interface CCSkewTo : CCActionInterval -{ - float skewX_; - float skewY_; - float startSkewX_; - float startSkewY_; - float endSkewX_; - float endSkewY_; - float deltaX_; - float deltaY_; -} -/** creates the action */ -+(id) actionWithDuration:(ccTime)t skewX:(float)sx skewY:(float)sy; -/** initializes the action */ --(id) initWithDuration:(ccTime)t skewX:(float)sx skewY:(float)sy; -@end - -/** Skews a CCNode object by skewX and skewY degrees - @since v1.0 - */ -@interface CCSkewBy : CCSkewTo -{ -} -@end - -/** Moves a CCNode object simulating a parabolic jump movement by modifying its position attribute. -*/ - @interface CCJumpBy : CCActionInterval -{ - CGPoint startPosition_; - CGPoint delta_; - ccTime height_; - NSUInteger jumps_; -} -/** creates the action */ -+(id) actionWithDuration: (ccTime)duration position:(CGPoint)position height:(ccTime)height jumps:(NSUInteger)jumps; -/** initializes the action */ --(id) initWithDuration: (ccTime)duration position:(CGPoint)position height:(ccTime)height jumps:(NSUInteger)jumps; -@end - -/** Moves a CCNode object to a parabolic position simulating a jump movement by modifying its position attribute. -*/ - @interface CCJumpTo : CCJumpBy -{ -} -@end - -/** bezier configuration structure - */ -typedef struct _ccBezierConfig { - //! end position of the bezier - CGPoint endPosition; - //! Bezier control point 1 - CGPoint controlPoint_1; - //! Bezier control point 2 - CGPoint controlPoint_2; -} ccBezierConfig; - -/** An action that moves the target with a cubic Bezier curve by a certain distance. - */ -@interface CCBezierBy : CCActionInterval -{ - ccBezierConfig config_; - CGPoint startPosition_; -} - -/** creates the action with a duration and a bezier configuration */ -+(id) actionWithDuration: (ccTime) t bezier:(ccBezierConfig) c; - -/** initializes the action with a duration and a bezier configuration */ --(id) initWithDuration: (ccTime) t bezier:(ccBezierConfig) c; -@end - -/** An action that moves the target with a cubic Bezier curve to a destination point. - @since v0.8.2 - */ -@interface CCBezierTo : CCBezierBy -{ -} -@end - -/** Scales a CCNode object to a zoom factor by modifying its scale attribute. - @warning This action doesn't support "reverse" - */ -@interface CCScaleTo : CCActionInterval -{ - float scaleX_; - float scaleY_; - float startScaleX_; - float startScaleY_; - float endScaleX_; - float endScaleY_; - float deltaX_; - float deltaY_; -} -/** creates the action with the same scale factor for X and Y */ -+(id) actionWithDuration: (ccTime)duration scale:(float) s; -/** initializes the action with the same scale factor for X and Y */ --(id) initWithDuration: (ccTime)duration scale:(float) s; -/** creates the action with and X factor and a Y factor */ -+(id) actionWithDuration: (ccTime)duration scaleX:(float) sx scaleY:(float)sy; -/** initializes the action with and X factor and a Y factor */ --(id) initWithDuration: (ccTime)duration scaleX:(float) sx scaleY:(float)sy; -@end - -/** Scales a CCNode object a zoom factor by modifying its scale attribute. -*/ -@interface CCScaleBy : CCScaleTo -{ -} -@end - -/** Blinks a CCNode object by modifying its visible attribute -*/ -@interface CCBlink : CCActionInterval -{ - NSUInteger times_; -} -/** creates the action */ -+(id) actionWithDuration: (ccTime)duration blinks:(NSUInteger)blinks; -/** initilizes the action */ --(id) initWithDuration: (ccTime)duration blinks:(NSUInteger)blinks; -@end - -/** Fades In an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 0 to 255. - The "reverse" of this action is FadeOut - */ -@interface CCFadeIn : CCActionInterval -{ -} -@end - -/** Fades Out an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 255 to 0. - The "reverse" of this action is FadeIn -*/ -@interface CCFadeOut : CCActionInterval -{ -} -@end - -/** Fades an object that implements the CCRGBAProtocol protocol. It modifies the opacity from the current value to a custom one. - @warning This action doesn't support "reverse" - */ -@interface CCFadeTo : CCActionInterval -{ - GLubyte toOpacity_; - GLubyte fromOpacity_; -} -/** creates an action with duration and opactiy */ -+(id) actionWithDuration:(ccTime)duration opacity:(GLubyte)opactiy; -/** initializes the action with duration and opacity */ --(id) initWithDuration:(ccTime)duration opacity:(GLubyte)opacity; -@end - -/** Tints a CCNode that implements the CCNodeRGB protocol from current tint to a custom one. - @warning This action doesn't support "reverse" - @since v0.7.2 -*/ -@interface CCTintTo : CCActionInterval -{ - ccColor3B to_; - ccColor3B from_; -} -/** creates an action with duration and color */ -+(id) actionWithDuration:(ccTime)duration red:(GLubyte)red green:(GLubyte)green blue:(GLubyte)blue; -/** initializes the action with duration and color */ --(id) initWithDuration:(ccTime)duration red:(GLubyte)red green:(GLubyte)green blue:(GLubyte)blue; -@end - -/** Tints a CCNode that implements the CCNodeRGB protocol from current tint to a custom one. - @since v0.7.2 - */ -@interface CCTintBy : CCActionInterval -{ - GLshort deltaR_, deltaG_, deltaB_; - GLshort fromR_, fromG_, fromB_; -} -/** creates an action with duration and color */ -+(id) actionWithDuration:(ccTime)duration red:(GLshort)deltaRed green:(GLshort)deltaGreen blue:(GLshort)deltaBlue; -/** initializes the action with duration and color */ --(id) initWithDuration:(ccTime)duration red:(GLshort)deltaRed green:(GLshort)deltaGreen blue:(GLshort)deltaBlue; -@end - -/** Delays the action a certain amount of seconds -*/ -@interface CCDelayTime : CCActionInterval -{ -} -@end - -/** Executes an action in reverse order, from time=duration to time=0 - - @warning Use this action carefully. This action is not - sequenceable. Use it as the default "reversed" method - of your own actions, but using it outside the "reversed" - scope is not recommended. -*/ -@interface CCReverseTime : CCActionInterval -{ - CCFiniteTimeAction * other_; -} -/** creates the action */ -+(id) actionWithAction: (CCFiniteTimeAction*) action; -/** initializes the action */ --(id) initWithAction: (CCFiniteTimeAction*) action; -@end - - -@class CCAnimation; -@class CCTexture2D; -/** Animates a sprite given the name of an Animation */ -@interface CCAnimate : CCActionInterval -{ - NSMutableArray *splitTimes_; - NSInteger nextFrame_; - CCAnimation *animation_; - id origFrame_; - NSUInteger executedLoops_; -} -/** animation used for the animage */ -@property (readwrite,nonatomic,retain) CCAnimation * animation; - -/** creates the action with an Animation and will restore the original frame when the animation is over */ -+(id) actionWithAnimation:(CCAnimation*)animation; -/** initializes the action with an Animation and will restore the original frame when the animtion is over */ --(id) initWithAnimation:(CCAnimation*)animation; -@end - -/** Overrides the target of an action so that it always runs on the target - * specified at action creation rather than the one specified by runAction. - */ -@interface CCTargetedAction : CCActionInterval -{ - id forcedTarget_; - CCFiniteTimeAction* action_; -} -/** This is the target that the action will be forced to run with */ -@property(readwrite,nonatomic,retain) id forcedTarget; - -/** Create an action with the specified action and forced target */ -+ (id) actionWithTarget:(id) target action:(CCFiniteTimeAction*) action; - -/** Init an action with the specified action and forced target */ -- (id) initWithTarget:(id) target action:(CCFiniteTimeAction*) action; - -@end diff --git a/Example/libs/cocos2d/CCActionInterval.m b/Example/libs/cocos2d/CCActionInterval.m deleted file mode 100644 index 60c886d..0000000 --- a/Example/libs/cocos2d/CCActionInterval.m +++ /dev/null @@ -1,1442 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - - -#import "CCActionInterval.h" -#import "CCActionInstant.h" -#import "CCSprite.h" -#import "CCSpriteFrame.h" -#import "CCAnimation.h" -#import "CCNode.h" -#import "Support/CGPointExtension.h" - -// -// IntervalAction -// -#pragma mark - CCIntervalAction -@implementation CCActionInterval - -@synthesize elapsed = elapsed_; - --(id) init -{ - NSAssert(NO, @"IntervalActionInit: Init not supported. Use InitWithDuration"); - [self release]; - return nil; -} - -+(id) actionWithDuration: (ccTime) d -{ - return [[[self alloc] initWithDuration:d ] autorelease]; -} - --(id) initWithDuration: (ccTime) d -{ - if( (self=[super init]) ) { - duration_ = d; - - // prevent division by 0 - // This comparison could be in step:, but it might decrease the performance - // by 3% in heavy based action games. - if( duration_ == 0 ) - duration_ = FLT_EPSILON; - elapsed_ = 0; - firstTick_ = YES; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] ]; - return copy; -} - -- (BOOL) isDone -{ - return (elapsed_ >= duration_); -} - --(void) step: (ccTime) dt -{ - if( firstTick_ ) { - firstTick_ = NO; - elapsed_ = 0; - } else - elapsed_ += dt; - - - [self update: MAX(0, // needed for rewind. elapsed could be negative - MIN(1, elapsed_/ - MAX(duration_,FLT_EPSILON) // division by 0 - ) - ) - ]; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - elapsed_ = 0.0f; - firstTick_ = YES; -} - -- (CCActionInterval*) reverse -{ - NSAssert(NO, @"CCIntervalAction: reverse not implemented."); - return nil; -} -@end - -// -// Sequence -// -#pragma mark - CCSequence -@implementation CCSequence -+(id) actions: (CCFiniteTimeAction*) action1, ... -{ - va_list params; - va_start(params,action1); - - CCFiniteTimeAction *now; - CCFiniteTimeAction *prev = action1; - - while( action1 ) { - now = va_arg(params,CCFiniteTimeAction*); - if ( now ) - prev = [self actionOne: prev two: now]; - else - break; - } - va_end(params); - return prev; -} - -+(id) actionsWithArray: (NSArray*) actions -{ - CCFiniteTimeAction *prev = [actions objectAtIndex:0]; - - for (NSUInteger i = 1; i < [actions count]; i++) - prev = [self actionOne:prev two:[actions objectAtIndex:i]]; - - return prev; -} - -+(id) actionOne: (CCFiniteTimeAction*) one two: (CCFiniteTimeAction*) two -{ - return [[[self alloc] initOne:one two:two ] autorelease]; -} - --(id) initOne: (CCFiniteTimeAction*) one two: (CCFiniteTimeAction*) two -{ - NSAssert( one!=nil && two!=nil, @"Sequence: arguments must be non-nil"); - NSAssert( one!=actions_[0] && one!=actions_[1], @"Sequence: re-init using the same parameters is not supported"); - NSAssert( two!=actions_[1] && two!=actions_[0], @"Sequence: re-init using the same parameters is not supported"); - - ccTime d = [one duration] + [two duration]; - - if( (self=[super initWithDuration: d]) ) { - - // XXX: Supports re-init without leaking. Fails if one==one_ || two==two_ - [actions_[0] release]; - [actions_[1] release]; - - actions_[0] = [one retain]; - actions_[1] = [two retain]; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone:zone] initOne:[[actions_[0] copy] autorelease] two:[[actions_[1] copy] autorelease] ]; - return copy; -} - --(void) dealloc -{ - [actions_[0] release]; - [actions_[1] release]; - [super dealloc]; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - split_ = [actions_[0] duration] / MAX(duration_, FLT_EPSILON); - last_ = -1; -} - --(void) stop -{ - // Issue #1305 - if( last_ != - 1) - [actions_[last_] stop]; - - [super stop]; -} - --(void) update: (ccTime) t -{ - int found = 0; - ccTime new_t = 0.0f; - - if( t < split_ ) { - // action[0] - found = 0; - if( split_ != 0 ) - new_t = t / split_; - else - new_t = 1; - - } else { - // action[1] - found = 1; - if ( split_ == 1 ) - new_t = 1; - else - new_t = (t-split_) / (1 - split_ ); - } - - if ( found==1 ) { - - if( last_ == -1 ) { - // action[0] was skipped, execute it. - [actions_[0] startWithTarget:target_]; - [actions_[0] update:1.0f]; - [actions_[0] stop]; - } - else if( last_ == 0 ) - { - // switching to action 1. stop action 0. - [actions_[0] update: 1.0f]; - [actions_[0] stop]; - } - } - - // New action. Start it. - if( found != last_ ) - [actions_[found] startWithTarget:target_]; - - [actions_[found] update: new_t]; - last_ = found; -} - -- (CCActionInterval *) reverse -{ - return [[self class] actionOne: [actions_[1] reverse] two: [actions_[0] reverse ] ]; -} -@end - -// -// Repeat -// -#pragma mark - CCRepeat -@implementation CCRepeat -@synthesize innerAction=innerAction_; - -+(id) actionWithAction:(CCFiniteTimeAction*)action times:(NSUInteger)times -{ - return [[[self alloc] initWithAction:action times:times] autorelease]; -} - --(id) initWithAction:(CCFiniteTimeAction*)action times:(NSUInteger)times -{ - ccTime d = [action duration] * times; - - if( (self=[super initWithDuration: d ]) ) { - times_ = times; - self.innerAction = action; - isActionInstant_ = ([action isKindOfClass:[CCActionInstant class]]) ? YES : NO; - - //a instant action needs to be executed one time less in the update method since it uses startWithTarget to execute the action - if (isActionInstant_) times_ -=1; - total_ = 0; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone:zone] initWithAction:[[innerAction_ copy] autorelease] times:times_]; - return copy; -} - --(void) dealloc -{ - [innerAction_ release]; - [super dealloc]; -} - --(void) startWithTarget:(id)aTarget -{ - total_ = 0; - nextDt_ = [innerAction_ duration]/duration_; - [super startWithTarget:aTarget]; - [innerAction_ startWithTarget:aTarget]; -} - --(void) stop -{ - [innerAction_ stop]; - [super stop]; -} - - -// issue #80. Instead of hooking step:, hook update: since it can be called by any -// container action like CCRepeat, CCSequence, CCEase, etc.. --(void) update:(ccTime) dt -{ - if (dt >= nextDt_) - { - while (dt > nextDt_ && total_ < times_) - { - - [innerAction_ update:1.0f]; - total_++; - - [innerAction_ stop]; - [innerAction_ startWithTarget:target_]; - nextDt_ += [innerAction_ duration]/duration_; - } - - // fix for issue #1288, incorrect end value of repeat - if(dt >= 1.0f && total_ < times_) - { - total_++; - } - - // don't set a instantaction back or update it, it has no use because it has no duration - if (!isActionInstant_) - { - if (total_ == times_) - { - [innerAction_ update:1]; - [innerAction_ stop]; - } - else - { - // issue #390 prevent jerk, use right update - [innerAction_ update:dt - (nextDt_ - innerAction_.duration/duration_)]; - } - } - } - else - { - [innerAction_ update:fmodf(dt * times_,1.0f)]; - } -} - --(BOOL) isDone -{ - return ( total_ == times_ ); -} - -- (CCActionInterval *) reverse -{ - return [[self class] actionWithAction:[innerAction_ reverse] times:times_]; -} -@end - -// -// Spawn -// -#pragma mark - CCSpawn - -@implementation CCSpawn -+(id) actions: (CCFiniteTimeAction*) action1, ... -{ - va_list params; - va_start(params,action1); - - CCFiniteTimeAction *now; - CCFiniteTimeAction *prev = action1; - - while( action1 ) { - now = va_arg(params,CCFiniteTimeAction*); - if ( now ) - prev = [self actionOne: prev two: now]; - else - break; - } - va_end(params); - return prev; -} - -+(id) actionsWithArray: (NSArray*) actions -{ - CCFiniteTimeAction *prev = [actions objectAtIndex:0]; - - for (NSUInteger i = 1; i < [actions count]; i++) - prev = [self actionOne:prev two:[actions objectAtIndex:i]]; - - return prev; -} - -+(id) actionOne: (CCFiniteTimeAction*) one two: (CCFiniteTimeAction*) two -{ - return [[[self alloc] initOne:one two:two ] autorelease]; -} - --(id) initOne: (CCFiniteTimeAction*) one two: (CCFiniteTimeAction*) two -{ - NSAssert( one!=nil && two!=nil, @"Spawn: arguments must be non-nil"); - NSAssert( one!=one_ && one!=two_, @"Spawn: reinit using same parameters is not supported"); - NSAssert( two!=two_ && two!=one_, @"Spawn: reinit using same parameters is not supported"); - - ccTime d1 = [one duration]; - ccTime d2 = [two duration]; - - if( (self=[super initWithDuration: MAX(d1,d2)] ) ) { - - // XXX: Supports re-init without leaking. Fails if one==one_ || two==two_ - [one_ release]; - [two_ release]; - - one_ = one; - two_ = two; - - if( d1 > d2 ) - two_ = [CCSequence actionOne:two two:[CCDelayTime actionWithDuration: (d1-d2)] ]; - else if( d1 < d2) - one_ = [CCSequence actionOne:one two: [CCDelayTime actionWithDuration: (d2-d1)] ]; - - [one_ retain]; - [two_ retain]; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initOne: [[one_ copy] autorelease] two: [[two_ copy] autorelease] ]; - return copy; -} - --(void) dealloc -{ - [one_ release]; - [two_ release]; - [super dealloc]; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - [one_ startWithTarget:target_]; - [two_ startWithTarget:target_]; -} - --(void) stop -{ - [one_ stop]; - [two_ stop]; - [super stop]; -} - --(void) update: (ccTime) t -{ - [one_ update:t]; - [two_ update:t]; -} - -- (CCActionInterval *) reverse -{ - return [[self class] actionOne: [one_ reverse] two: [two_ reverse ] ]; -} -@end - -// -// RotateTo -// -#pragma mark - CCRotateTo - -@implementation CCRotateTo -+(id) actionWithDuration: (ccTime) t angle:(float) a -{ - return [[[self alloc] initWithDuration:t angle:a ] autorelease]; -} - --(id) initWithDuration: (ccTime) t angle:(float) a -{ - if( (self=[super initWithDuration: t]) ) - dstAngle_ = a; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] angle:dstAngle_]; - return copy; -} - --(void) startWithTarget:(CCNode *)aTarget -{ - [super startWithTarget:aTarget]; - - startAngle_ = [target_ rotation]; - if (startAngle_ > 0) - startAngle_ = fmodf(startAngle_, 360.0f); - else - startAngle_ = fmodf(startAngle_, -360.0f); - - diffAngle_ =dstAngle_ - startAngle_; - if (diffAngle_ > 180) - diffAngle_ -= 360; - if (diffAngle_ < -180) - diffAngle_ += 360; -} --(void) update: (ccTime) t -{ - [target_ setRotation: startAngle_ + diffAngle_ * t]; -} -@end - - -// -// RotateBy -// -#pragma mark - CCRotateBy - -@implementation CCRotateBy -+(id) actionWithDuration: (ccTime) t angle:(float) a -{ - return [[[self alloc] initWithDuration:t angle:a ] autorelease]; -} - --(id) initWithDuration: (ccTime) t angle:(float) a -{ - if( (self=[super initWithDuration: t]) ) - angle_ = a; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] angle: angle_]; - return copy; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - startAngle_ = [target_ rotation]; -} - --(void) update: (ccTime) t -{ - // XXX: shall I add % 360 - [target_ setRotation: (startAngle_ +angle_ * t )]; -} - --(CCActionInterval*) reverse -{ - return [[self class] actionWithDuration:duration_ angle:-angle_]; -} - -@end - -// -// MoveTo -// -#pragma mark - CCMoveTo - -@implementation CCMoveTo -+(id) actionWithDuration: (ccTime) t position: (CGPoint) p -{ - return [[[self alloc] initWithDuration:t position:p ] autorelease]; -} - --(id) initWithDuration: (ccTime) t position: (CGPoint) p -{ - if( (self=[super initWithDuration: t]) ) - endPosition_ = p; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] position: endPosition_]; - return copy; -} - --(void) startWithTarget:(CCNode *)aTarget -{ - [super startWithTarget:aTarget]; - startPosition_ = [(CCNode*)target_ position]; - delta_ = ccpSub( endPosition_, startPosition_ ); -} - --(void) update: (ccTime) t -{ - [target_ setPosition: ccp( (startPosition_.x + delta_.x * t ), (startPosition_.y + delta_.y * t ) )]; -} -@end - -// -// MoveBy -// -#pragma mark - CCMoveBy - -@implementation CCMoveBy -+(id) actionWithDuration: (ccTime) t position: (CGPoint) p -{ - return [[[self alloc] initWithDuration:t position:p ] autorelease]; -} - --(id) initWithDuration: (ccTime) t position: (CGPoint) p -{ - if( (self=[super initWithDuration: t]) ) - delta_ = p; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] position: delta_]; - return copy; -} - --(void) startWithTarget:(CCNode *)aTarget -{ - CGPoint dTmp = delta_; - [super startWithTarget:aTarget]; - delta_ = dTmp; -} - --(CCActionInterval*) reverse -{ - return [[self class] actionWithDuration:duration_ position:ccp( -delta_.x, -delta_.y)]; -} -@end - - -// -// SkewTo -// -#pragma mark - CCSkewTo - -@implementation CCSkewTo -+(id) actionWithDuration:(ccTime)t skewX:(float)sx skewY:(float)sy -{ - return [[[self alloc] initWithDuration: t skewX:sx skewY:sy] autorelease]; -} - --(id) initWithDuration:(ccTime)t skewX:(float)sx skewY:(float)sy -{ - if( (self=[super initWithDuration:t]) ) { - endSkewX_ = sx; - endSkewY_ = sy; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] skewX:endSkewX_ skewY:endSkewY_]; - return copy; -} - --(void) startWithTarget:(CCNode *)aTarget -{ - [super startWithTarget:aTarget]; - - startSkewX_ = [target_ skewX]; - - if (startSkewX_ > 0) - startSkewX_ = fmodf(startSkewX_, 180.0f); - else - startSkewX_ = fmodf(startSkewX_, -180.0f); - - deltaX_ = endSkewX_ - startSkewX_; - - if ( deltaX_ > 180 ) { - deltaX_ -= 360; - } - if ( deltaX_ < -180 ) { - deltaX_ += 360; - } - - startSkewY_ = [target_ skewY]; - - if (startSkewY_ > 0) - startSkewY_ = fmodf(startSkewY_, 360.0f); - else - startSkewY_ = fmodf(startSkewY_, -360.0f); - - deltaY_ = endSkewY_ - startSkewY_; - - if ( deltaY_ > 180 ) { - deltaY_ -= 360; - } - if ( deltaY_ < -180 ) { - deltaY_ += 360; - } -} - --(void) update: (ccTime) t -{ - [target_ setSkewX: (startSkewX_ + deltaX_ * t ) ]; - [target_ setSkewY: (startSkewY_ + deltaY_ * t ) ]; -} - -@end - -// -// CCSkewBy -// -#pragma mark - CCSkewBy - -@implementation CCSkewBy - --(id) initWithDuration:(ccTime)t skewX:(float)deltaSkewX skewY:(float)deltaSkewY -{ - if( (self=[super initWithDuration:t skewX:deltaSkewX skewY:deltaSkewY]) ) { - skewX_ = deltaSkewX; - skewY_ = deltaSkewY; - } - return self; -} - --(void) startWithTarget:(CCNode *)aTarget -{ - [super startWithTarget:aTarget]; - deltaX_ = skewX_; - deltaY_ = skewY_; - endSkewX_ = startSkewX_ + deltaX_; - endSkewY_ = startSkewY_ + deltaY_; -} - --(CCActionInterval*) reverse -{ - return [[self class] actionWithDuration:duration_ skewX:-skewX_ skewY:-skewY_]; -} -@end - - -// -// JumpBy -// -#pragma mark - CCJumpBy - -@implementation CCJumpBy -+(id) actionWithDuration: (ccTime) t position: (CGPoint) pos height: (ccTime) h jumps:(NSUInteger)j -{ - return [[[self alloc] initWithDuration: t position: pos height: h jumps:j] autorelease]; -} - --(id) initWithDuration: (ccTime) t position: (CGPoint) pos height: (ccTime) h jumps:(NSUInteger)j -{ - if( (self=[super initWithDuration:t]) ) { - delta_ = pos; - height_ = h; - jumps_ = j; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] position:delta_ height:height_ jumps:jumps_]; - return copy; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - startPosition_ = [(CCNode*)target_ position]; -} - --(void) update: (ccTime) t -{ - // Sin jump. Less realistic -// ccTime y = height * fabsf( sinf(t * (CGFloat)M_PI * jumps ) ); -// y += delta.y * t; -// ccTime x = delta.x * t; -// [target setPosition: ccp( startPosition.x + x, startPosition.y + y )]; - - // parabolic jump (since v0.8.2) - ccTime frac = fmodf( t * jumps_, 1.0f ); - ccTime y = height_ * 4 * frac * (1 - frac); - y += delta_.y * t; - ccTime x = delta_.x * t; - [target_ setPosition: ccp( startPosition_.x + x, startPosition_.y + y )]; - -} - --(CCActionInterval*) reverse -{ - return [[self class] actionWithDuration:duration_ position: ccp(-delta_.x,-delta_.y) height:height_ jumps:jumps_]; -} -@end - -// -// JumpTo -// -#pragma mark - CCJumpTo - -@implementation CCJumpTo --(void) startWithTarget:(CCNode *)aTarget -{ - [super startWithTarget:aTarget]; - delta_ = ccp( delta_.x - startPosition_.x, delta_.y - startPosition_.y ); -} -@end - - -#pragma mark - CCBezierBy - -// Bezier cubic formula: -// ((1 - t) + t)3 = 1 -// Expands to… -// (1 - t)3 + 3t(1-t)2 + 3t2(1 - t) + t3 = 1 -static inline float bezierat( float a, float b, float c, float d, ccTime t ) -{ - return (powf(1-t,3) * a + - 3*t*(powf(1-t,2))*b + - 3*powf(t,2)*(1-t)*c + - powf(t,3)*d ); -} - -// -// BezierBy -// -@implementation CCBezierBy -+(id) actionWithDuration: (ccTime) t bezier:(ccBezierConfig) c -{ - return [[[self alloc] initWithDuration:t bezier:c ] autorelease]; -} - --(id) initWithDuration: (ccTime) t bezier:(ccBezierConfig) c -{ - if( (self=[super initWithDuration: t]) ) { - config_ = c; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] bezier:config_]; - return copy; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - startPosition_ = [(CCNode*)target_ position]; -} - --(void) update: (ccTime) t -{ - float xa = 0; - float xb = config_.controlPoint_1.x; - float xc = config_.controlPoint_2.x; - float xd = config_.endPosition.x; - - float ya = 0; - float yb = config_.controlPoint_1.y; - float yc = config_.controlPoint_2.y; - float yd = config_.endPosition.y; - - float x = bezierat(xa, xb, xc, xd, t); - float y = bezierat(ya, yb, yc, yd, t); - [target_ setPosition: ccpAdd( startPosition_, ccp(x,y))]; -} - -- (CCActionInterval*) reverse -{ - ccBezierConfig r; - - r.endPosition = ccpNeg(config_.endPosition); - r.controlPoint_1 = ccpAdd(config_.controlPoint_2, ccpNeg(config_.endPosition)); - r.controlPoint_2 = ccpAdd(config_.controlPoint_1, ccpNeg(config_.endPosition)); - - CCBezierBy *action = [[self class] actionWithDuration:[self duration] bezier:r]; - return action; -} -@end - -// -// BezierTo -// -#pragma mark - CCBezierTo -@implementation CCBezierTo --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - config_.controlPoint_1 = ccpSub(config_.controlPoint_1, startPosition_); - config_.controlPoint_2 = ccpSub(config_.controlPoint_2, startPosition_); - config_.endPosition = ccpSub(config_.endPosition, startPosition_); -} -@end - - -// -// ScaleTo -// -#pragma mark - CCScaleTo -@implementation CCScaleTo -+(id) actionWithDuration: (ccTime) t scale:(float) s -{ - return [[[self alloc] initWithDuration: t scale:s] autorelease]; -} - --(id) initWithDuration: (ccTime) t scale:(float) s -{ - if( (self=[super initWithDuration: t]) ) { - endScaleX_ = s; - endScaleY_ = s; - } - return self; -} - -+(id) actionWithDuration: (ccTime) t scaleX:(float)sx scaleY:(float)sy -{ - return [[[self alloc] initWithDuration: t scaleX:sx scaleY:sy] autorelease]; -} - --(id) initWithDuration: (ccTime) t scaleX:(float)sx scaleY:(float)sy -{ - if( (self=[super initWithDuration: t]) ) { - endScaleX_ = sx; - endScaleY_ = sy; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] scaleX:endScaleX_ scaleY:endScaleY_]; - return copy; -} - --(void) startWithTarget:(CCNode *)aTarget -{ - [super startWithTarget:aTarget]; - startScaleX_ = [target_ scaleX]; - startScaleY_ = [target_ scaleY]; - deltaX_ = endScaleX_ - startScaleX_; - deltaY_ = endScaleY_ - startScaleY_; -} - --(void) update: (ccTime) t -{ - [target_ setScaleX: (startScaleX_ + deltaX_ * t ) ]; - [target_ setScaleY: (startScaleY_ + deltaY_ * t ) ]; -} -@end - -// -// ScaleBy -// -#pragma mark - CCScaleBy -@implementation CCScaleBy --(void) startWithTarget:(CCNode *)aTarget -{ - [super startWithTarget:aTarget]; - deltaX_ = startScaleX_ * endScaleX_ - startScaleX_; - deltaY_ = startScaleY_ * endScaleY_ - startScaleY_; -} - --(CCActionInterval*) reverse -{ - return [[self class] actionWithDuration:duration_ scaleX:1/endScaleX_ scaleY:1/endScaleY_]; -} -@end - -// -// Blink -// -#pragma mark - CCBlink -@implementation CCBlink -+(id) actionWithDuration: (ccTime) t blinks: (NSUInteger) b -{ - return [[[ self alloc] initWithDuration: t blinks: b] autorelease]; -} - --(id) initWithDuration: (ccTime) t blinks: (NSUInteger) b -{ - if( (self=[super initWithDuration: t] ) ) - times_ = b; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] blinks: times_]; - return copy; -} - --(void) update: (ccTime) t -{ - if( ! [self isDone] ) { - ccTime slice = 1.0f / times_; - ccTime m = fmodf(t, slice); - [target_ setVisible: (m > slice/2) ? YES : NO]; - } -} - --(CCActionInterval*) reverse -{ - // return 'self' - return [[self class] actionWithDuration:duration_ blinks: times_]; -} -@end - -// -// FadeIn -// -#pragma mark - CCFadeIn -@implementation CCFadeIn --(void) update: (ccTime) t -{ - [(id) target_ setOpacity: 255 *t]; -} - --(CCActionInterval*) reverse -{ - return [CCFadeOut actionWithDuration:duration_]; -} -@end - -// -// FadeOut -// -#pragma mark - CCFadeOut -@implementation CCFadeOut --(void) update: (ccTime) t -{ - [(id) target_ setOpacity: 255 *(1-t)]; -} - --(CCActionInterval*) reverse -{ - return [CCFadeIn actionWithDuration:duration_]; -} -@end - -// -// FadeTo -// -#pragma mark - CCFadeTo -@implementation CCFadeTo -+(id) actionWithDuration: (ccTime) t opacity: (GLubyte) o -{ - return [[[ self alloc] initWithDuration: t opacity: o] autorelease]; -} - --(id) initWithDuration: (ccTime) t opacity: (GLubyte) o -{ - if( (self=[super initWithDuration: t] ) ) - toOpacity_ = o; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:[self duration] opacity:toOpacity_]; - return copy; -} - --(void) startWithTarget:(CCNode *)aTarget -{ - [super startWithTarget:aTarget]; - fromOpacity_ = [(id)target_ opacity]; -} - --(void) update: (ccTime) t -{ - [(id)target_ setOpacity:fromOpacity_ + ( toOpacity_ - fromOpacity_ ) * t]; -} -@end - -// -// TintTo -// -#pragma mark - CCTintTo -@implementation CCTintTo -+(id) actionWithDuration:(ccTime)t red:(GLubyte)r green:(GLubyte)g blue:(GLubyte)b -{ - return [[(CCTintTo*)[ self alloc] initWithDuration:t red:r green:g blue:b] autorelease]; -} - --(id) initWithDuration: (ccTime) t red:(GLubyte)r green:(GLubyte)g blue:(GLubyte)b -{ - if( (self=[super initWithDuration:t] ) ) - to_ = ccc3(r,g,b); - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [(CCTintTo*)[[self class] allocWithZone: zone] initWithDuration:[self duration] red:to_.r green:to_.g blue:to_.b]; - return copy; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - - id tn = (id) target_; - from_ = [tn color]; -} - --(void) update: (ccTime) t -{ - id tn = (id) target_; - [tn setColor:ccc3(from_.r + (to_.r - from_.r) * t, from_.g + (to_.g - from_.g) * t, from_.b + (to_.b - from_.b) * t)]; -} -@end - -// -// TintBy -// -#pragma mark - CCTintBy -@implementation CCTintBy -+(id) actionWithDuration:(ccTime)t red:(GLshort)r green:(GLshort)g blue:(GLshort)b -{ - return [[(CCTintBy*)[ self alloc] initWithDuration:t red:r green:g blue:b] autorelease]; -} - --(id) initWithDuration:(ccTime)t red:(GLshort)r green:(GLshort)g blue:(GLshort)b -{ - if( (self=[super initWithDuration: t] ) ) { - deltaR_ = r; - deltaG_ = g; - deltaB_ = b; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - return[(CCTintBy*)[[self class] allocWithZone: zone] initWithDuration: [self duration] red:deltaR_ green:deltaG_ blue:deltaB_]; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - - id tn = (id) target_; - ccColor3B color = [tn color]; - fromR_ = color.r; - fromG_ = color.g; - fromB_ = color.b; -} - --(void) update: (ccTime) t -{ - id tn = (id) target_; - [tn setColor:ccc3( fromR_ + deltaR_ * t, fromG_ + deltaG_ * t, fromB_ + deltaB_ * t)]; -} - -- (CCActionInterval*) reverse -{ - return [CCTintBy actionWithDuration:duration_ red:-deltaR_ green:-deltaG_ blue:-deltaB_]; -} -@end - -// -// DelayTime -// -#pragma mark - CCDelayTime -@implementation CCDelayTime --(void) update: (ccTime) t -{ - return; -} - --(id)reverse -{ - return [[self class] actionWithDuration:duration_]; -} -@end - -// -// ReverseTime -// -#pragma mark - CCReverseTime -@implementation CCReverseTime -+(id) actionWithAction: (CCFiniteTimeAction*) action -{ - // casting to prevent warnings - CCReverseTime *a = [self alloc]; - return [[a initWithAction:action] autorelease]; -} - --(id) initWithAction: (CCFiniteTimeAction*) action -{ - NSAssert(action != nil, @"CCReverseTime: action should not be nil"); - NSAssert(action != other_, @"CCReverseTime: re-init doesn't support using the same arguments"); - - if( (self=[super initWithDuration: [action duration]]) ) { - // Don't leak if action is reused - [other_ release]; - other_ = [action retain]; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - return [[[self class] allocWithZone: zone] initWithAction:[[other_ copy] autorelease] ]; -} - --(void) dealloc -{ - [other_ release]; - [super dealloc]; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - [other_ startWithTarget:target_]; -} - --(void) stop -{ - [other_ stop]; - [super stop]; -} - --(void) update:(ccTime)t -{ - [other_ update:1-t]; -} - --(CCActionInterval*) reverse -{ - return [[other_ copy] autorelease]; -} -@end - -// -// Animate -// - -#pragma mark - CCAnimate -@implementation CCAnimate - -@synthesize animation = animation_; - -+(id) actionWithAnimation: (CCAnimation*)anim -{ - return [[[self alloc] initWithAnimation:anim] autorelease]; -} - -// delegate initializer --(id) initWithAnimation:(CCAnimation*)anim -{ - NSAssert( anim!=nil, @"Animate: argument Animation must be non-nil"); - - float singleDuration = anim.duration; - - if( (self=[super initWithDuration:singleDuration * anim.loops] ) ) { - - nextFrame_ = 0; - self.animation = anim; - origFrame_ = nil; - executedLoops_ = 0; - - splitTimes_ = [[NSMutableArray alloc] initWithCapacity:anim.frames.count]; - - float accumUnitsOfTime = 0; - float newUnitOfTimeValue = singleDuration / anim.totalDelayUnits; - - for( CCAnimationFrame *frame in anim.frames ) { - - NSNumber *value = [NSNumber numberWithFloat: (accumUnitsOfTime * newUnitOfTimeValue) / singleDuration]; - accumUnitsOfTime += frame.delayUnits; - - [splitTimes_ addObject:value]; - } - } - return self; -} - - --(id) copyWithZone: (NSZone*) zone -{ - return [[[self class] allocWithZone: zone] initWithAnimation:[[animation_ copy]autorelease] ]; -} - --(void) dealloc -{ - [splitTimes_ release]; - [animation_ release]; - [origFrame_ release]; - [super dealloc]; -} - --(void) startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - CCSprite *sprite = target_; - - [origFrame_ release]; - - if( animation_.restoreOriginalFrame ) - origFrame_ = [[sprite displayFrame] retain]; - - nextFrame_ = 0; - executedLoops_ = 0; -} - --(void) stop -{ - if( animation_.restoreOriginalFrame ) { - CCSprite *sprite = target_; - [sprite setDisplayFrame:origFrame_]; - } - - [super stop]; -} - --(void) update: (ccTime) t -{ - - // if t==1, ignore. Animation should finish with t==1 - if( t < 1.0f ) { - t *= animation_.loops; - - // new loop? If so, reset frame counter - NSUInteger loopNumber = (NSUInteger)t; - if( loopNumber > executedLoops_ ) { - nextFrame_ = 0; - executedLoops_++; - } - - // new t for animations - t = fmodf(t, 1.0f); - } - - NSArray *frames = [animation_ frames]; - NSUInteger numberOfFrames = [frames count]; - CCSpriteFrame *frameToDisplay = nil; - - for( NSUInteger i=nextFrame_; i < numberOfFrames; i++ ) { - NSNumber *splitTime = [splitTimes_ objectAtIndex:i]; - - if( [splitTime floatValue] <= t ) { - CCAnimationFrame *frame = [frames objectAtIndex:i]; - frameToDisplay = [frame spriteFrame]; - [(CCSprite*)target_ setDisplayFrame: frameToDisplay]; - - NSDictionary *dict = [frame userInfo]; - if( dict ) - [[NSNotificationCenter defaultCenter] postNotificationName:CCAnimationFrameDisplayedNotification object:target_ userInfo:dict]; - - nextFrame_ = i+1; - - break; - } - } -} - -- (CCActionInterval *) reverse -{ - NSArray *oldArray = [animation_ frames]; - NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:[oldArray count]]; - NSEnumerator *enumerator = [oldArray reverseObjectEnumerator]; - for (id element in enumerator) - [newArray addObject:[[element copy] autorelease]]; - - CCAnimation *newAnim = [CCAnimation animationWithAnimationFrames:newArray delayPerUnit:animation_.delayPerUnit loops:animation_.loops]; - newAnim.restoreOriginalFrame = animation_.restoreOriginalFrame; - return [[self class] actionWithAnimation:newAnim]; -} -@end - - -#pragma mark - CCTargetedAction - -@implementation CCTargetedAction - -@synthesize forcedTarget = forcedTarget_; - -+ (id) actionWithTarget:(id) target action:(CCFiniteTimeAction*) action -{ - return [[ (CCTargetedAction*)[self alloc] initWithTarget:target action:action] autorelease]; -} - -- (id) initWithTarget:(id) targetIn action:(CCFiniteTimeAction*) actionIn -{ - if((self = [super initWithDuration:actionIn.duration])) - { - forcedTarget_ = [targetIn retain]; - action_ = [actionIn retain]; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [ (CCTargetedAction*) [[self class] allocWithZone: zone] initWithTarget:target_ action:[[action_ copy] autorelease]]; - return copy; -} - -- (void) dealloc -{ - [forcedTarget_ release]; - [action_ release]; - [super dealloc]; -} - -//- (void) updateDuration:(id)aTarget -//{ -// [action updateDuration:forcedTarget]; -// duration_ = action.duration; -//} - -- (void) startWithTarget:(id)aTarget -{ - [super startWithTarget:forcedTarget_]; - [action_ startWithTarget:forcedTarget_]; -} - -- (void) stop -{ - [action_ stop]; -} - -- (void) update:(ccTime) time -{ - [action_ update:time]; -} - -@end diff --git a/Example/libs/cocos2d/CCActionManager.h b/Example/libs/cocos2d/CCActionManager.h deleted file mode 100644 index 33a32eb..0000000 --- a/Example/libs/cocos2d/CCActionManager.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCAction.h" -#import "ccMacros.h" -#import "Support/ccCArray.h" -#import "Support/uthash.h" - -#define kCCActionManagerPriority 0 - -typedef struct _hashElement -{ - struct ccArray *actions; - NSUInteger actionIndex; - BOOL currentActionSalvaged; - BOOL paused; - UT_hash_handle hh; - - CC_ARC_UNSAFE_RETAINED id target; - CC_ARC_UNSAFE_RETAINED CCAction *currentAction; -} tHashElement; - - -/** CCActionManager the object that manages all the actions. - Normally you won't need to use this API directly. 99% of the cases you will use the CCNode interface, which uses this object. - But there are some cases where you might need to use this API dirctly: - Examples: - - When you want to run an action where the target is different from a CCNode. - - When you want to pause / resume the actions - - @since v0.8 - */ -@interface CCActionManager : NSObject -{ - tHashElement *targets; - tHashElement *currentTarget; - BOOL currentTargetSalvaged; -} - - -// actions - -/** Adds an action with a target. - If the target is already present, then the action will be added to the existing target. - If the target is not present, a new instance of this target will be created either paused or paused, and the action will be added to the newly created target. - When the target is paused, the queued actions won't be 'ticked'. - */ --(void) addAction: (CCAction*) action target:(id)target paused:(BOOL)paused; -/** Removes all actions from all the targers. - */ --(void) removeAllActions; - -/** Removes all actions from a certain target. - All the actions that belongs to the target will be removed. - */ --(void) removeAllActionsFromTarget:(id)target; -/** Removes an action given an action reference. - */ --(void) removeAction: (CCAction*) action; -/** Removes an action given its tag and the target */ --(void) removeActionByTag:(NSInteger)tag target:(id)target; -/** Gets an action given its tag an a target - @return the Action the with the given tag - */ --(CCAction*) getActionByTag:(NSInteger) tag target:(id)target; -/** Returns the numbers of actions that are running in a certain target - * Composable actions are counted as 1 action. Example: - * If you are running 1 Sequence of 7 actions, it will return 1. - * If you are running 7 Sequences of 2 actions, it will return 7. - */ --(NSUInteger) numberOfRunningActionsInTarget:(id)target; - -/** Pauses the target: all running actions and newly added actions will be paused. - */ --(void) pauseTarget:(id)target; -/** Resumes the target. All queued actions will be resumed. - */ --(void) resumeTarget:(id)target; - -@end - diff --git a/Example/libs/cocos2d/CCActionManager.m b/Example/libs/cocos2d/CCActionManager.m deleted file mode 100644 index 79e2203..0000000 --- a/Example/libs/cocos2d/CCActionManager.m +++ /dev/null @@ -1,319 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionManager.h" -#import "CCScheduler.h" -#import "ccMacros.h" - -@interface CCActionManager (Private) --(void) removeActionAtIndex:(NSUInteger)index hashElement:(tHashElement*)element; --(void) deleteHashElement:(tHashElement*)element; --(void) actionAllocWithHashElement:(tHashElement*)element; -@end - - -@implementation CCActionManager - --(id) init -{ - if ((self=[super init]) ) { - targets = NULL; - } - - return self; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X>", [self class], self]; -} - -- (void) dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@", self); - - [self removeAllActions]; - - [super dealloc]; -} - -#pragma mark ActionManager - Private - --(void) deleteHashElement:(tHashElement*)element -{ - ccArrayFree(element->actions); - HASH_DEL(targets, element); -// CCLOG(@"cocos2d: ---- buckets: %d/%d - %@", targets->entries, targets->size, element->target); - [element->target release]; - free(element); -} - --(void) actionAllocWithHashElement:(tHashElement*)element -{ - // 4 actions per Node by default - if( element->actions == nil ) - element->actions = ccArrayNew(4); - else if( element->actions->num == element->actions->max ) - ccArrayDoubleCapacity(element->actions); -} - --(void) removeActionAtIndex:(NSUInteger)index hashElement:(tHashElement*)element -{ - id action = element->actions->arr[index]; - - if( action == element->currentAction && !element->currentActionSalvaged ) { - [element->currentAction retain]; - element->currentActionSalvaged = YES; - } - - ccArrayRemoveObjectAtIndex(element->actions, index); - - // update actionIndex in case we are in tick:, looping over the actions - if( element->actionIndex >= index ) - element->actionIndex--; - - if( element->actions->num == 0 ) { - if( currentTarget == element ) - currentTargetSalvaged = YES; - else - [self deleteHashElement: element]; - } -} - -#pragma mark ActionManager - Pause / Resume - --(void) pauseTarget:(id)target -{ - tHashElement *element = NULL; - HASH_FIND_INT(targets, &target, element); - if( element ) - element->paused = YES; -// else -// CCLOG(@"cocos2d: pauseAllActions: Target not found"); -} - --(void) resumeTarget:(id)target -{ - tHashElement *element = NULL; - HASH_FIND_INT(targets, &target, element); - if( element ) - element->paused = NO; -// else -// CCLOG(@"cocos2d: resumeAllActions: Target not found"); -} - -#pragma mark ActionManager - run - --(void) addAction:(CCAction*)action target:(id)target paused:(BOOL)paused -{ - NSAssert( action != nil, @"Argument action must be non-nil"); - NSAssert( target != nil, @"Argument target must be non-nil"); - - tHashElement *element = NULL; - HASH_FIND_INT(targets, &target, element); - if( ! element ) { - element = calloc( sizeof( *element ), 1 ); - element->paused = paused; - element->target = [target retain]; - HASH_ADD_INT(targets, target, element); -// CCLOG(@"cocos2d: ---- buckets: %d/%d - %@", targets->entries, targets->size, element->target); - - } - - [self actionAllocWithHashElement:element]; - - NSAssert( !ccArrayContainsObject(element->actions, action), @"runAction: Action already running"); - ccArrayAppendObject(element->actions, action); - - [action startWithTarget:target]; -} - -#pragma mark ActionManager - remove - --(void) removeAllActions -{ - for(tHashElement *element=targets; element != NULL; ) { - id target = element->target; - element = element->hh.next; - [self removeAllActionsFromTarget:target]; - } -} --(void) removeAllActionsFromTarget:(id)target -{ - // explicit nil handling - if( target == nil ) - return; - - tHashElement *element = NULL; - HASH_FIND_INT(targets, &target, element); - if( element ) { - if( ccArrayContainsObject(element->actions, element->currentAction) && !element->currentActionSalvaged ) { - [element->currentAction retain]; - element->currentActionSalvaged = YES; - } - ccArrayRemoveAllObjects(element->actions); - if( currentTarget == element ) - currentTargetSalvaged = YES; - else - [self deleteHashElement:element]; - } -// else { -// CCLOG(@"cocos2d: removeAllActionsFromTarget: Target not found"); -// } -} - --(void) removeAction: (CCAction*) action -{ - // explicit nil handling - if (action == nil) - return; - - tHashElement *element = NULL; - id target = [action originalTarget]; - HASH_FIND_INT(targets, &target, element ); - if( element ) { - NSUInteger i = ccArrayGetIndexOfObject(element->actions, action); - if( i != NSNotFound ) - [self removeActionAtIndex:i hashElement:element]; - } -// else { -// CCLOG(@"cocos2d: removeAction: Target not found"); -// } -} - --(void) removeActionByTag:(NSInteger)aTag target:(id)target -{ - NSAssert( aTag != kCCActionTagInvalid, @"Invalid tag"); - NSAssert( target != nil, @"Target should be ! nil"); - - tHashElement *element = NULL; - HASH_FIND_INT(targets, &target, element); - - if( element ) { - NSUInteger limit = element->actions->num; - for( NSUInteger i = 0; i < limit; i++) { - CCAction *a = element->actions->arr[i]; - - if( a.tag == aTag && [a originalTarget]==target) { - [self removeActionAtIndex:i hashElement:element]; - break; - } - } - - } -} - -#pragma mark ActionManager - get - --(CCAction*) getActionByTag:(NSInteger)aTag target:(id)target -{ - NSAssert( aTag != kCCActionTagInvalid, @"Invalid tag"); - - tHashElement *element = NULL; - HASH_FIND_INT(targets, &target, element); - - if( element ) { - if( element->actions != nil ) { - NSUInteger limit = element->actions->num; - for( NSUInteger i = 0; i < limit; i++) { - CCAction *a = element->actions->arr[i]; - - if( a.tag == aTag ) - return a; - } - } -// CCLOG(@"cocos2d: getActionByTag: Action not found"); - } -// else { -// CCLOG(@"cocos2d: getActionByTag: Target not found"); -// } - return nil; -} - --(NSUInteger) numberOfRunningActionsInTarget:(id) target -{ - tHashElement *element = NULL; - HASH_FIND_INT(targets, &target, element); - if( element ) - return element->actions ? element->actions->num : 0; - -// CCLOG(@"cocos2d: numberOfRunningActionsInTarget: Target not found"); - return 0; -} - -#pragma mark ActionManager - main loop - --(void) update: (ccTime) dt -{ - for(tHashElement *elt = targets; elt != NULL; ) { - - currentTarget = elt; - currentTargetSalvaged = NO; - - if( ! currentTarget->paused ) { - - // The 'actions' ccArray may change while inside this loop. - for( currentTarget->actionIndex = 0; currentTarget->actionIndex < currentTarget->actions->num; currentTarget->actionIndex++) { - currentTarget->currentAction = currentTarget->actions->arr[currentTarget->actionIndex]; - currentTarget->currentActionSalvaged = NO; - - [currentTarget->currentAction step: dt]; - - if( currentTarget->currentActionSalvaged ) { - // The currentAction told the node to remove it. To prevent the action from - // accidentally deallocating itself before finishing its step, we retained - // it. Now that step is done, it's safe to release it. - [currentTarget->currentAction release]; - - } else if( [currentTarget->currentAction isDone] ) { - [currentTarget->currentAction stop]; - - CCAction *a = currentTarget->currentAction; - // Make currentAction nil to prevent removeAction from salvaging it. - currentTarget->currentAction = nil; - [self removeAction:a]; - } - - currentTarget->currentAction = nil; - } - } - - // elt, at this moment, is still valid - // so it is safe to ask this here (issue #490) - elt = elt->hh.next; - - // only delete currentTarget if no actions were scheduled during the cycle (issue #481) - if( currentTargetSalvaged && currentTarget->actions->num == 0 ) - [self deleteHashElement:currentTarget]; - } - - // issue #635 - currentTarget = nil; -} -@end diff --git a/Example/libs/cocos2d/CCActionPageTurn3D.h b/Example/libs/cocos2d/CCActionPageTurn3D.h deleted file mode 100644 index 6199aff..0000000 --- a/Example/libs/cocos2d/CCActionPageTurn3D.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Sindesso Pty Ltd http://www.sindesso.com/ - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionGrid3D.h" - -/** - * This action simulates a page turn from the bottom right hand corner of the screen - * It's not much use by itself but is used by the PageTurnTransition. - * - * Based on an original paper by L Hong et al. - * http://www.parc.com/publication/1638/turning-pages-of-3d-electronic-books.html - * - * @since v0.8.2 - */ -@interface CCPageTurn3D : CCGrid3DAction -{ -} - -@end diff --git a/Example/libs/cocos2d/CCActionPageTurn3D.m b/Example/libs/cocos2d/CCActionPageTurn3D.m deleted file mode 100644 index cff9bc2..0000000 --- a/Example/libs/cocos2d/CCActionPageTurn3D.m +++ /dev/null @@ -1,86 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Sindesso Pty Ltd http://www.sindesso.com/ - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCActionPageTurn3D.h" - -@implementation CCPageTurn3D - -/* - * Update each tick - * Time is the percentage of the way through the duration - */ --(void)update:(ccTime)time -{ - float tt = MAX( 0, time - 0.25f ); - float deltaAy = ( tt * tt * 500); - float ay = -100 - deltaAy; - - float deltaTheta = - (float) M_PI_2 * sqrtf( time) ; - float theta = /*0.01f*/ + (float) M_PI_2 +deltaTheta; - - float sinTheta = sinf(theta); - float cosTheta = cosf(theta); - - for( int i = 0; i <=gridSize_.x; i++ ) - { - for( int j = 0; j <= gridSize_.y; j++ ) - { - // Get original vertex - ccVertex3F p = [self originalVertex:ccg(i,j)]; - - float R = sqrtf(p.x*p.x + (p.y - ay) * (p.y - ay)); - float r = R * sinTheta; - float alpha = asinf( p.x / R ); - float beta = alpha / sinTheta; - float cosBeta = cosf( beta ); - - // If beta > PI then we've wrapped around the cone - // Reduce the radius to stop these points interfering with others - if( beta <= M_PI) - p.x = ( r * sinf(beta)); - else - { - // Force X = 0 to stop wrapped - // points - p.x = 0; - } - - p.y = ( R + ay - ( r*(1 - cosBeta)*sinTheta)); - - // We scale z here to avoid the animation being - // too much bigger than the screen due to perspectve transform - p.z = (r * ( 1 - cosBeta ) * cosTheta) / 7; // "100" didn't work for - - // Stop z coord from dropping beneath underlying page in a transition - // issue #751 - if( p.z<0.5f ) - p.z = 0.5f; - - // Set new coords - [self setVertex:ccg(i,j) vertex:p]; - } - } -} -@end diff --git a/Example/libs/cocos2d/CCActionProgressTimer.h b/Example/libs/cocos2d/CCActionProgressTimer.h deleted file mode 100644 index 2b9e771..0000000 --- a/Example/libs/cocos2d/CCActionProgressTimer.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (C) 2010 Lam Pham - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import -#import "CCProgressTimer.h" -#import "CCActionInterval.h" - -/** - Progress to percentage -@since v0.99.1 -*/ -@interface CCProgressTo : CCActionInterval -{ - float to_; - float from_; -} -/** Creates and initializes with a duration and a percent */ -+(id) actionWithDuration:(ccTime)duration percent:(float)percent; -/** Initializes with a duration and a percent */ --(id) initWithDuration:(ccTime)duration percent:(float)percent; -@end - -/** - Progress from a percentage to another percentage - @since v0.99.1 - */ -@interface CCProgressFromTo : CCActionInterval -{ - float to_; - float from_; -} -/** Creates and initializes the action with a duration, a "from" percentage and a "to" percentage */ -+(id) actionWithDuration:(ccTime)duration from:(float)fromPercentage to:(float) toPercentage; -/** Initializes the action with a duration, a "from" percentage and a "to" percentage */ --(id) initWithDuration:(ccTime)duration from:(float)fromPercentage to:(float) toPercentage; -@end diff --git a/Example/libs/cocos2d/CCActionProgressTimer.m b/Example/libs/cocos2d/CCActionProgressTimer.m deleted file mode 100644 index d5e2993..0000000 --- a/Example/libs/cocos2d/CCActionProgressTimer.m +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (C) 2010 Lam Pham - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionProgressTimer.h" - -#define kProgressTimerCast CCProgressTimer* - -@implementation CCProgressTo -+(id) actionWithDuration: (ccTime) t percent: (float) v -{ - return [[[ self alloc] initWithDuration: t percent: v] autorelease]; -} - --(id) initWithDuration: (ccTime) t percent: (float) v -{ - if( (self=[super initWithDuration: t] ) ) - to_ = v; - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:duration_ percent:to_]; - return copy; -} - --(void) startWithTarget:(id) aTarget; -{ - [super startWithTarget:aTarget]; - from_ = [(kProgressTimerCast)target_ percentage]; - - // XXX: Is this correct ? - // Adding it to support CCRepeat - if( from_ == 100) - from_ = 0; -} - --(void) update: (ccTime) t -{ - [(kProgressTimerCast)target_ setPercentage: from_ + ( to_ - from_ ) * t]; -} -@end - -@implementation CCProgressFromTo -+(id) actionWithDuration: (ccTime) t from:(float)fromPercentage to:(float) toPercentage -{ - return [[[self alloc] initWithDuration: t from: fromPercentage to: toPercentage] autorelease]; -} - --(id) initWithDuration: (ccTime) t from:(float)fromPercentage to:(float) toPercentage -{ - if( (self=[super initWithDuration: t] ) ){ - to_ = toPercentage; - from_ = fromPercentage; - } - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration:duration_ from:from_ to:to_]; - return copy; -} - -- (CCActionInterval *) reverse -{ - return [[self class] actionWithDuration:duration_ from:to_ to:from_]; -} - --(void) startWithTarget:(id) aTarget; -{ - [super startWithTarget:aTarget]; -} - --(void) update: (ccTime) t -{ - [(kProgressTimerCast)target_ setPercentage: from_ + ( to_ - from_ ) * t]; -} -@end diff --git a/Example/libs/cocos2d/CCActionTiledGrid.h b/Example/libs/cocos2d/CCActionTiledGrid.h deleted file mode 100644 index 42b23a6..0000000 --- a/Example/libs/cocos2d/CCActionTiledGrid.h +++ /dev/null @@ -1,211 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCActionGrid.h" - -/** CCShakyTiles3D action */ -@interface CCShakyTiles3D : CCTiledGrid3DAction -{ - int randrange; - BOOL shakeZ; -} - -/** creates the action with a range, whether or not to shake Z vertices, a grid size, and duration */ -+(id)actionWithRange:(int)range shakeZ:(BOOL)shakeZ grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with a range, whether or not to shake Z vertices, a grid size, and duration */ --(id)initWithRange:(int)range shakeZ:(BOOL)shakeZ grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCShatteredTiles3D action */ -@interface CCShatteredTiles3D : CCTiledGrid3DAction -{ - int randrange; - BOOL once; - BOOL shatterZ; -} - -/** creates the action with a range, whether of not to shatter Z vertices, a grid size and duration */ -+(id)actionWithRange:(int)range shatterZ:(BOOL)shatterZ grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with a range, whether or not to shatter Z vertices, a grid size and duration */ --(id)initWithRange:(int)range shatterZ:(BOOL)shatterZ grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCShuffleTiles action - Shuffle the tiles in random order - */ -@interface CCShuffleTiles : CCTiledGrid3DAction -{ - int seed; - NSUInteger tilesCount; - int *tilesOrder; - void *tiles; -} - -/** creates the action with a random seed, the grid size and the duration */ -+(id)actionWithSeed:(int)s grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with a random seed, the grid size and the duration */ --(id)initWithSeed:(int)s grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCFadeOutTRTiles action - Fades out the tiles in a Top-Right direction - */ -@interface CCFadeOutTRTiles : CCTiledGrid3DAction -{ -} -@end - -//////////////////////////////////////////////////////////// - -/** CCFadeOutBLTiles action. - Fades out the tiles in a Bottom-Left direction - */ -@interface CCFadeOutBLTiles : CCFadeOutTRTiles -{ -} -@end - -//////////////////////////////////////////////////////////// - -/** CCFadeOutUpTiles action. - Fades out the tiles in upwards direction - */ -@interface CCFadeOutUpTiles : CCFadeOutTRTiles -{ -} -@end - -//////////////////////////////////////////////////////////// - -/** CCFadeOutDownTiles action. - Fades out the tiles in downwards direction - */ -@interface CCFadeOutDownTiles : CCFadeOutUpTiles -{ -} -@end - -//////////////////////////////////////////////////////////// - -/** CCTurnOffTiles action. - Turn off the files in random order - */ -@interface CCTurnOffTiles : CCTiledGrid3DAction -{ - int seed; - NSUInteger tilesCount; - int *tilesOrder; -} - -/** creates the action with a random seed, the grid size and the duration */ -+(id)actionWithSeed:(int)s grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with a random seed, the grid size and the duration */ --(id)initWithSeed:(int)s grid:(ccGridSize)gridSize duration:(ccTime)d; -@end - -//////////////////////////////////////////////////////////// - -/** CCWavesTiles3D action. */ -@interface CCWavesTiles3D : CCTiledGrid3DAction -{ - int waves; - float amplitude; - float amplitudeRate; -} - -/** waves amplitude */ -@property (nonatomic,readwrite) float amplitude; -/** waves amplitude rate */ -@property (nonatomic,readwrite) float amplitudeRate; - -/** creates the action with a number of waves, the waves amplitude, the grid size and the duration */ -+(id)actionWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with a number of waves, the waves amplitude, the grid size and the duration */ --(id)initWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCJumpTiles3D action. - A sin function is executed to move the tiles across the Z axis - */ -@interface CCJumpTiles3D : CCTiledGrid3DAction -{ - int jumps; - float amplitude; - float amplitudeRate; -} - -/** amplitude of the sin*/ -@property (nonatomic,readwrite) float amplitude; -/** amplitude rate */ -@property (nonatomic,readwrite) float amplitudeRate; - -/** creates the action with the number of jumps, the sin amplitude, the grid size and the duration */ -+(id)actionWithJumps:(int)j amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; -/** initializes the action with the number of jumps, the sin amplitude, the grid size and the duration */ --(id)initWithJumps:(int)j amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d; - -@end - -//////////////////////////////////////////////////////////// - -/** CCSplitRows action */ -@interface CCSplitRows : CCTiledGrid3DAction -{ - int rows; - CGSize winSize; -} -/** creates the action with the number of rows to split and the duration */ -+(id)actionWithRows:(int)rows duration:(ccTime)duration; -/** initializes the action with the number of rows to split and the duration */ --(id)initWithRows:(int)rows duration:(ccTime)duration; - -@end - -//////////////////////////////////////////////////////////// - -/** CCSplitCols action */ -@interface CCSplitCols : CCTiledGrid3DAction -{ - int cols; - CGSize winSize; -} -/** creates the action with the number of columns to split and the duration */ -+(id)actionWithCols:(int)cols duration:(ccTime)duration; -/** initializes the action with the number of columns to split and the duration */ --(id)initWithCols:(int)cols duration:(ccTime)duration; - -@end diff --git a/Example/libs/cocos2d/CCActionTiledGrid.m b/Example/libs/cocos2d/CCActionTiledGrid.m deleted file mode 100644 index f8d6a2d..0000000 --- a/Example/libs/cocos2d/CCActionTiledGrid.m +++ /dev/null @@ -1,768 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCActionTiledGrid.h" -#import "CCDirector.h" -#import "ccMacros.h" -#import "Support/CGPointExtension.h" - -typedef struct -{ - CGPoint position; - CGPoint startPosition; - ccGridSize delta; -} Tile; - -#pragma mark - -#pragma mark ShakyTiles3D - -@implementation CCShakyTiles3D - -+(id)actionWithRange:(int)range shakeZ:(BOOL)shakeZ grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithRange:range shakeZ:shakeZ grid:gridSize duration:d] autorelease]; -} - --(id)initWithRange:(int)range shakeZ:(BOOL)sz grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - randrange = range; - shakeZ = sz; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithRange:randrange shakeZ:shakeZ grid:gridSize_ duration:duration_]; - return copy; -} - - --(void)update:(ccTime)time -{ - int i, j; - - for( i = 0; i < gridSize_.x; i++ ) - { - for( j = 0; j < gridSize_.y; j++ ) - { - ccQuad3 coords = [self originalTile:ccg(i,j)]; - - // X - coords.bl.x += ( rand() % (randrange*2) ) - randrange; - coords.br.x += ( rand() % (randrange*2) ) - randrange; - coords.tl.x += ( rand() % (randrange*2) ) - randrange; - coords.tr.x += ( rand() % (randrange*2) ) - randrange; - - // Y - coords.bl.y += ( rand() % (randrange*2) ) - randrange; - coords.br.y += ( rand() % (randrange*2) ) - randrange; - coords.tl.y += ( rand() % (randrange*2) ) - randrange; - coords.tr.y += ( rand() % (randrange*2) ) - randrange; - - if( shakeZ ) { - coords.bl.z += ( rand() % (randrange*2) ) - randrange; - coords.br.z += ( rand() % (randrange*2) ) - randrange; - coords.tl.z += ( rand() % (randrange*2) ) - randrange; - coords.tr.z += ( rand() % (randrange*2) ) - randrange; - } - - [self setTile:ccg(i,j) coords:coords]; - } - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCShatteredTiles3D - -@implementation CCShatteredTiles3D - -+(id)actionWithRange:(int)range shatterZ:(BOOL)sz grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithRange:range shatterZ:sz grid:gridSize duration:d] autorelease]; -} - --(id)initWithRange:(int)range shatterZ:(BOOL)sz grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - once = NO; - randrange = range; - shatterZ = sz; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithRange:randrange shatterZ:shatterZ grid:gridSize_ duration:duration_]; - return copy; -} - - --(void)update:(ccTime)time -{ - int i, j; - - if ( once == NO ) - { - for( i = 0; i < gridSize_.x; i++ ) - { - for( j = 0; j < gridSize_.y; j++ ) - { - ccQuad3 coords = [self originalTile:ccg(i,j)]; - - // X - coords.bl.x += ( rand() % (randrange*2) ) - randrange; - coords.br.x += ( rand() % (randrange*2) ) - randrange; - coords.tl.x += ( rand() % (randrange*2) ) - randrange; - coords.tr.x += ( rand() % (randrange*2) ) - randrange; - - // Y - coords.bl.y += ( rand() % (randrange*2) ) - randrange; - coords.br.y += ( rand() % (randrange*2) ) - randrange; - coords.tl.y += ( rand() % (randrange*2) ) - randrange; - coords.tr.y += ( rand() % (randrange*2) ) - randrange; - - if( shatterZ ) { - coords.bl.z += ( rand() % (randrange*2) ) - randrange; - coords.br.z += ( rand() % (randrange*2) ) - randrange; - coords.tl.z += ( rand() % (randrange*2) ) - randrange; - coords.tr.z += ( rand() % (randrange*2) ) - randrange; - } - - [self setTile:ccg(i,j) coords:coords]; - } - } - - once = YES; - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCShuffleTiles - -@implementation CCShuffleTiles - -+(id)actionWithSeed:(int)s grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithSeed:s grid:gridSize duration:d] autorelease]; -} - --(id)initWithSeed:(int)s grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - seed = s; - tilesOrder = nil; - tiles = nil; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithSeed:seed grid:gridSize_ duration:duration_]; - return copy; -} - - --(void)dealloc -{ - if ( tilesOrder ) free(tilesOrder); - if ( tiles ) free(tiles); - [super dealloc]; -} - --(void)shuffle:(int*)array count:(NSUInteger)len -{ - NSInteger i; - for( i = len - 1; i >= 0; i-- ) - { - NSInteger j = rand() % (i+1); - int v = array[i]; - array[i] = array[j]; - array[j] = v; - } -} - --(ccGridSize)getDelta:(ccGridSize)pos -{ - CGPoint pos2; - - NSInteger idx = pos.x * gridSize_.y + pos.y; - - pos2.x = tilesOrder[idx] / (int)gridSize_.y; - pos2.y = tilesOrder[idx] % (int)gridSize_.y; - - return ccg(pos2.x - pos.x, pos2.y - pos.y); -} - --(void)placeTile:(ccGridSize)pos tile:(Tile)t -{ - ccQuad3 coords = [self originalTile:pos]; - - CGPoint step = [[target_ grid] step]; - coords.bl.x += (int)(t.position.x * step.x); - coords.bl.y += (int)(t.position.y * step.y); - - coords.br.x += (int)(t.position.x * step.x); - coords.br.y += (int)(t.position.y * step.y); - - coords.tl.x += (int)(t.position.x * step.x); - coords.tl.y += (int)(t.position.y * step.y); - - coords.tr.x += (int)(t.position.x * step.x); - coords.tr.y += (int)(t.position.y * step.y); - - [self setTile:pos coords:coords]; -} - --(void)startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - - if ( seed != -1 ) - srand(seed); - - tilesCount = gridSize_.x * gridSize_.y; - tilesOrder = (int*)malloc(tilesCount*sizeof(int)); - int i, j; - - for( i = 0; i < tilesCount; i++ ) - tilesOrder[i] = i; - - [self shuffle:tilesOrder count:tilesCount]; - - tiles = malloc(tilesCount*sizeof(Tile)); - Tile *tileArray = (Tile*)tiles; - - for( i = 0; i < gridSize_.x; i++ ) - { - for( j = 0; j < gridSize_.y; j++ ) - { - tileArray->position = ccp(i,j); - tileArray->startPosition = ccp(i,j); - tileArray->delta = [self getDelta:ccg(i,j)]; - tileArray++; - } - } -} - --(void)update:(ccTime)time -{ - int i, j; - - Tile *tileArray = (Tile*)tiles; - - for( i = 0; i < gridSize_.x; i++ ) - { - for( j = 0; j < gridSize_.y; j++ ) - { - tileArray->position = ccpMult( ccp(tileArray->delta.x, tileArray->delta.y), time); - [self placeTile:ccg(i,j) tile:*tileArray]; - tileArray++; - } - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCFadeOutTRTiles - -@implementation CCFadeOutTRTiles - --(float)testFunc:(ccGridSize)pos time:(ccTime)time -{ - CGPoint n = ccpMult( ccp(gridSize_.x,gridSize_.y), time); - if ( (n.x+n.y) == 0.0f ) - return 1.0f; - - return powf( (pos.x+pos.y) / (n.x+n.y), 6 ); -} - --(void)turnOnTile:(ccGridSize)pos -{ - [self setTile:pos coords:[self originalTile:pos]]; -} - --(void)turnOffTile:(ccGridSize)pos -{ - ccQuad3 coords; - bzero(&coords, sizeof(ccQuad3)); - [self setTile:pos coords:coords]; -} - --(void)transformTile:(ccGridSize)pos distance:(float)distance -{ - ccQuad3 coords = [self originalTile:pos]; - CGPoint step = [[target_ grid] step]; - - coords.bl.x += (step.x / 2) * (1.0f - distance); - coords.bl.y += (step.y / 2) * (1.0f - distance); - - coords.br.x -= (step.x / 2) * (1.0f - distance); - coords.br.y += (step.y / 2) * (1.0f - distance); - - coords.tl.x += (step.x / 2) * (1.0f - distance); - coords.tl.y -= (step.y / 2) * (1.0f - distance); - - coords.tr.x -= (step.x / 2) * (1.0f - distance); - coords.tr.y -= (step.y / 2) * (1.0f - distance); - - [self setTile:pos coords:coords]; -} - --(void)update:(ccTime)time -{ - int i, j; - - for( i = 0; i < gridSize_.x; i++ ) - { - for( j = 0; j < gridSize_.y; j++ ) - { - float distance = [self testFunc:ccg(i,j) time:time]; - if ( distance == 0 ) - [self turnOffTile:ccg(i,j)]; - else if ( distance < 1 ) - [self transformTile:ccg(i,j) distance:distance]; - else - [self turnOnTile:ccg(i,j)]; - } - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCFadeOutBLTiles - -@implementation CCFadeOutBLTiles - --(float)testFunc:(ccGridSize)pos time:(ccTime)time -{ - CGPoint n = ccpMult(ccp(gridSize_.x, gridSize_.y), (1.0f-time)); - if ( (pos.x+pos.y) == 0 ) - return 1.0f; - - return powf( (n.x+n.y) / (pos.x+pos.y), 6 ); -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCFadeOutUpTiles - -@implementation CCFadeOutUpTiles - --(float)testFunc:(ccGridSize)pos time:(ccTime)time -{ - CGPoint n = ccpMult(ccp(gridSize_.x, gridSize_.y), time); - if ( n.y == 0 ) - return 1.0f; - - return powf( pos.y / n.y, 6 ); -} - --(void)transformTile:(ccGridSize)pos distance:(float)distance -{ - ccQuad3 coords = [self originalTile:pos]; - CGPoint step = [[target_ grid] step]; - - coords.bl.y += (step.y / 2) * (1.0f - distance); - coords.br.y += (step.y / 2) * (1.0f - distance); - coords.tl.y -= (step.y / 2) * (1.0f - distance); - coords.tr.y -= (step.y / 2) * (1.0f - distance); - - [self setTile:pos coords:coords]; -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCFadeOutDownTiles - -@implementation CCFadeOutDownTiles - --(float)testFunc:(ccGridSize)pos time:(ccTime)time -{ - CGPoint n = ccpMult(ccp(gridSize_.x,gridSize_.y), (1.0f - time)); - if ( pos.y == 0 ) - return 1.0f; - - return powf( n.y / pos.y, 6 ); -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark TurnOffTiles - -@implementation CCTurnOffTiles - -+(id)actionWithSeed:(int)s grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithSeed:s grid:gridSize duration:d] autorelease]; -} - --(id)initWithSeed:(int)s grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - seed = s; - tilesOrder = nil; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithSeed:seed grid:gridSize_ duration:duration_]; - return copy; -} - --(void)dealloc -{ - if ( tilesOrder ) free(tilesOrder); - [super dealloc]; -} - --(void)shuffle:(int*)array count:(NSUInteger)len -{ - NSInteger i; - for( i = len - 1; i >= 0; i-- ) - { - NSInteger j = rand() % (i+1); - int v = array[i]; - array[i] = array[j]; - array[j] = v; - } -} - --(void)turnOnTile:(ccGridSize)pos -{ - [self setTile:pos coords:[self originalTile:pos]]; -} - --(void)turnOffTile:(ccGridSize)pos -{ - ccQuad3 coords; - - bzero(&coords, sizeof(ccQuad3)); - [self setTile:pos coords:coords]; -} - --(void)startWithTarget:(id)aTarget -{ - int i; - - [super startWithTarget:aTarget]; - - if ( seed != -1 ) - srand(seed); - - tilesCount = gridSize_.x * gridSize_.y; - tilesOrder = (int*)malloc(tilesCount*sizeof(int)); - - for( i = 0; i < tilesCount; i++ ) - tilesOrder[i] = i; - - [self shuffle:tilesOrder count:tilesCount]; -} - --(void)update:(ccTime)time -{ - int i, l, t; - - l = (int)(time * (float)tilesCount); - - for( i = 0; i < tilesCount; i++ ) - { - t = tilesOrder[i]; - ccGridSize tilePos = ccg( t / gridSize_.y, t % gridSize_.y ); - - if ( i < l ) - [self turnOffTile:tilePos]; - else - [self turnOnTile:tilePos]; - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCWavesTiles3D - -@implementation CCWavesTiles3D - -@synthesize amplitude; -@synthesize amplitudeRate; - -+(id)actionWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithWaves:wav amplitude:amp grid:gridSize duration:d] autorelease]; -} - --(id)initWithWaves:(int)wav amplitude:(float)amp grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - waves = wav; - amplitude = amp; - amplitudeRate = 1.0f; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithWaves:waves amplitude:amplitude grid:gridSize_ duration:duration_]; - return copy; -} - - --(void)update:(ccTime)time -{ - int i, j; - - for( i = 0; i < gridSize_.x; i++ ) - { - for( j = 0; j < gridSize_.y; j++ ) - { - ccQuad3 coords = [self originalTile:ccg(i,j)]; - - coords.bl.z = (sinf(time*(CGFloat)M_PI*waves*2 + (coords.bl.y+coords.bl.x) * .01f) * amplitude * amplitudeRate ); - coords.br.z = coords.bl.z; - coords.tl.z = coords.bl.z; - coords.tr.z = coords.bl.z; - - [self setTile:ccg(i,j) coords:coords]; - } - } -} -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCJumpTiles3D - -@implementation CCJumpTiles3D - -@synthesize amplitude; -@synthesize amplitudeRate; - -+(id)actionWithJumps:(int)j amplitude:(float)amp grid:(ccGridSize)gridSize duration:(ccTime)d -{ - return [[[self alloc] initWithJumps:j amplitude:amp grid:gridSize duration:d] autorelease]; -} - --(id)initWithJumps:(int)j amplitude:(float)amp grid:(ccGridSize)gSize duration:(ccTime)d -{ - if ( (self = [super initWithSize:gSize duration:d]) ) - { - jumps = j; - amplitude = amp; - amplitudeRate = 1.0f; - } - - return self; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithJumps:jumps amplitude:amplitude grid:gridSize_ duration:duration_]; - return copy; -} - - --(void)update:(ccTime)time -{ - int i, j; - - float sinz = (sinf((CGFloat)M_PI*time*jumps*2) * amplitude * amplitudeRate ); - float sinz2 = (sinf((CGFloat)M_PI*(time*jumps*2 + 1)) * amplitude * amplitudeRate ); - - for( i = 0; i < gridSize_.x; i++ ) - { - for( j = 0; j < gridSize_.y; j++ ) - { - ccQuad3 coords = [self originalTile:ccg(i,j)]; - - if ( ((i+j) % 2) == 0 ) - { - coords.bl.z += sinz; - coords.br.z += sinz; - coords.tl.z += sinz; - coords.tr.z += sinz; - } - else - { - coords.bl.z += sinz2; - coords.br.z += sinz2; - coords.tl.z += sinz2; - coords.tr.z += sinz2; - } - - [self setTile:ccg(i,j) coords:coords]; - } - } -} -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark SplitRows - -@implementation CCSplitRows - -+(id)actionWithRows:(int)r duration:(ccTime)d -{ - return [[[self alloc] initWithRows:r duration:d] autorelease]; -} - --(id)initWithRows:(int)r duration:(ccTime)d -{ - rows = r; - return [super initWithSize:ccg(1,r) duration:d]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithRows:rows duration:duration_]; - return copy; -} - --(void)startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - winSize = [[CCDirector sharedDirector] winSizeInPixels]; -} - --(void)update:(ccTime)time -{ - int j; - - for( j = 0; j < gridSize_.y; j++ ) - { - ccQuad3 coords = [self originalTile:ccg(0,j)]; - float direction = 1; - - if ( (j % 2 ) == 0 ) - direction = -1; - - coords.bl.x += direction * winSize.width * time; - coords.br.x += direction * winSize.width * time; - coords.tl.x += direction * winSize.width * time; - coords.tr.x += direction * winSize.width * time; - - [self setTile:ccg(0,j) coords:coords]; - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCSplitCols - -@implementation CCSplitCols - -+(id)actionWithCols:(int)c duration:(ccTime)d -{ - return [[[self alloc] initWithCols:c duration:d] autorelease]; -} - --(id)initWithCols:(int)c duration:(ccTime)d -{ - cols = c; - return [super initWithSize:ccg(c,1) duration:d]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCGridAction *copy = [[[self class] allocWithZone:zone] initWithCols:cols duration:duration_]; - return copy; -} - --(void)startWithTarget:(id)aTarget -{ - [super startWithTarget:aTarget]; - winSize = [[CCDirector sharedDirector] winSizeInPixels]; -} - --(void)update:(ccTime)time -{ - int i; - - for( i = 0; i < gridSize_.x; i++ ) - { - ccQuad3 coords = [self originalTile:ccg(i,0)]; - float direction = 1; - - if ( (i % 2 ) == 0 ) - direction = -1; - - coords.bl.y += direction * winSize.height * time; - coords.br.y += direction * winSize.height * time; - coords.tl.y += direction * winSize.height * time; - coords.tr.y += direction * winSize.height * time; - - [self setTile:ccg(i,0) coords:coords]; - } -} - -@end diff --git a/Example/libs/cocos2d/CCActionTween.h b/Example/libs/cocos2d/CCActionTween.h deleted file mode 100644 index 378a828..0000000 --- a/Example/libs/cocos2d/CCActionTween.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright 2009 lhunath (Maarten Billemont) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import -#import "CCActionInterval.h" - -/** CCActionTween - - CCActionTween is an action that lets you update any property of an object. - For example, if you want to modify the "width" property of a target from 200 to 300 in 2 seconds, then: - - id modifyWidth = [CCActionTween actionWithDuration:2 key:@"width" from:200 to:300]; - [target runAction:modifyWidth]; - - - Another example: CCScaleTo action could be rewriten using CCPropertyAction: - - // scaleA and scaleB are equivalents - id scaleA = [CCScaleTo actionWithDuration:2 scale:3]; - id scaleB = [CCActionTween actionWithDuration:2 key:@"scale" from:1 to:3]; - - - @since v0.99.2 - */ -@interface CCActionTween : CCActionInterval -{ - NSString *key_; - - float from_, to_; - float delta_; -} - -/** creates an initializes the action with the property name (key), and the from and to parameters. */ -+ (id)actionWithDuration:(ccTime)aDuration key:(NSString *)key from:(float)from to:(float)to; - -/** initializes the action with the property name (key), and the from and to parameters. */ -- (id)initWithDuration:(ccTime)aDuration key:(NSString *)key from:(float)from to:(float)to; - -@end diff --git a/Example/libs/cocos2d/CCActionTween.m b/Example/libs/cocos2d/CCActionTween.m deleted file mode 100644 index a119d72..0000000 --- a/Example/libs/cocos2d/CCActionTween.m +++ /dev/null @@ -1,72 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright 2009 lhunath (Maarten Billemont) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCActionTween.h" - - -@implementation CCActionTween - -+ (id)actionWithDuration:(ccTime)aDuration key:(NSString *)aKey from:(float)aFrom to:(float)aTo { - - return [[[[self class] alloc] initWithDuration:aDuration key:aKey from:aFrom to:aTo] autorelease]; -} - -- (id)initWithDuration:(ccTime)aDuration key:(NSString *)key from:(float)from to:(float)to { - - if ((self = [super initWithDuration:aDuration])) { - - key_ = [key copy]; - to_ = to; - from_ = from; - - } - - return self; -} - -- (void) dealloc -{ - [key_ release]; - [super dealloc]; -} - -- (void)startWithTarget:aTarget -{ - [super startWithTarget:aTarget]; - delta_ = to_ - from_; -} - -- (void) update:(ccTime) dt -{ - [target_ setValue:[NSNumber numberWithFloat:to_ - delta_ * (1 - dt)] forKey:key_]; -} - -- (CCActionInterval *) reverse -{ - return [[self class] actionWithDuration:duration_ key:key_ from:to_ to:from_]; -} - - -@end diff --git a/Example/libs/cocos2d/CCAnimation.h b/Example/libs/cocos2d/CCAnimation.h deleted file mode 100644 index a20def3..0000000 --- a/Example/libs/cocos2d/CCAnimation.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import -#ifdef __CC_PLATFORM_IOS -#import -#endif // IPHONE - -@class CCSpriteFrame; -@class CCTexture2D; -@class CCSpriteFrame; - -/** CCAnimationFrame - A frame of the animation. It contains information like: - - sprite frame name - - # of delay units. - - offset - - @since v2.0 - */ -@interface CCAnimationFrame : NSObject -{ - CCSpriteFrame* spriteFrame_; - float delayUnits_; - NSDictionary *userInfo_; -} -/** CCSpriteFrameName to be used */ -@property (nonatomic, readwrite, retain) CCSpriteFrame* spriteFrame; - -/** how many units of time the frame takes */ -@property (nonatomic, readwrite) float delayUnits; - -/** A CCAnimationFrameDisplayedNotification notification will be broadcasted when the frame is displayed with this dictionary as UserInfo. If UserInfo is nil, then no notification will be broadcasted. */ -@property (nonatomic, readwrite, retain) NSDictionary *userInfo; - -/** initializes the animation frame with a spriteframe, number of delay units and a notification user info */ --(id) initWithSpriteFrame:(CCSpriteFrame*)spriteFrame delayUnits:(float)delayUnits userInfo:(NSDictionary*)userInfo; -@end - -/** A CCAnimation object is used to perform animations on the CCSprite objects. - - The CCAnimation object contains CCAnimationFrame objects, and a possible delay between the frames. - You can animate a CCAnimation object by using the CCAnimate action. Example: - - [sprite runAction:[CCAnimate actionWithAnimation:animation]]; - - */ -@interface CCAnimation : NSObject -{ - NSMutableArray *frames_; - float totalDelayUnits_; - float delayPerUnit_; - BOOL restoreOriginalFrame_; - NSUInteger loops_; -} - -/** total Delay units of the CCAnimation. */ -@property (nonatomic, readonly) float totalDelayUnits; -/** Delay in seconds of the "delay unit" */ -@property (nonatomic, readwrite) float delayPerUnit; -/** duration in seconds of the whole animation. It is the result of totalDelayUnits * delayPerUnit */ -@property (nonatomic,readonly) float duration; -/** array of CCAnimationFrames */ -@property (nonatomic,readwrite,retain) NSMutableArray *frames; -/** whether or not it shall restore the original frame when the animation finishes */ -@property (nonatomic,readwrite) BOOL restoreOriginalFrame; -/** how many times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ... */ -@property (nonatomic, readwrite) NSUInteger loops; - -/** Creates an animation - @since v0.99.5 - */ -+(id) animation; - -/** Creates an animation with an array of CCSpriteFrame. - The frames will be created with one "delay unit". - @since v0.99.5 - */ -+(id) animationWithSpriteFrames:(NSArray*)arrayOfSpriteFrameNames; - -/* Creates an animation with an array of CCSpriteFrame and a delay between frames in seconds. - The frames will be added with one "delay unit". - @since v0.99.5 - */ -+(id) animationWithSpriteFrames:(NSArray*)arrayOfSpriteFrameNames delay:(float)delay; - -/* Creates an animation with an array of CCAnimationFrame, the delay per units in seconds and and how many times it should be executed. - @since v2.0 - */ -+(id) animationWithAnimationFrames:(NSArray*)arrayOfAnimationFrames delayPerUnit:(float)delayPerUnit loops:(NSUInteger)loops; - - -/** Initializes a CCAnimation with an array of CCSpriteFrame. - The frames will be added with one "delay unit". - @since v0.99.5 -*/ --(id) initWithSpriteFrames:(NSArray*)arrayOfSpriteFrameNames; - -/** Initializes a CCAnimation with an array of CCSpriteFrames and a delay between frames in seconds. - The frames will be added with one "delay unit". - @since v0.99.5 - */ --(id) initWithSpriteFrames:(NSArray *)arrayOfSpriteFrameNames delay:(float)delay; - -/* Initializes an animation with an array of CCAnimationFrame and the delay per units in seconds. - @since v2.0 - */ --(id) initWithAnimationFrames:(NSArray*)arrayOfAnimationFrames delayPerUnit:(float)delayPerUnit loops:(NSUInteger)loops; - -/** Adds a CCSpriteFrame to a CCAnimation. - The frame will be added with one "delay unit". -*/ --(void) addSpriteFrame:(CCSpriteFrame*)frame; - -/** Adds a frame with an image filename. Internally it will create a CCSpriteFrame and it will add it. - The frame will be added with one "delay unit". - Added to facilitate the migration from v0.8 to v0.9. - */ --(void) addSpriteFrameWithFilename:(NSString*)filename; - -/** Adds a frame with a texture and a rect. Internally it will create a CCSpriteFrame and it will add it. - The frame will be added with one "delay unit". - Added to facilitate the migration from v0.8 to v0.9. - */ --(void) addSpriteFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; - -@end diff --git a/Example/libs/cocos2d/CCAnimation.m b/Example/libs/cocos2d/CCAnimation.m deleted file mode 100644 index 7426349..0000000 --- a/Example/libs/cocos2d/CCAnimation.m +++ /dev/null @@ -1,200 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "ccMacros.h" -#import "CCAnimation.h" -#import "CCSpriteFrame.h" -#import "CCTexture2D.h" -#import "CCTextureCache.h" - -#pragma mark - CCAnimationFrame -@implementation CCAnimationFrame - -@synthesize spriteFrame = spriteFrame_, delayUnits = delayUnits_, userInfo=userInfo_; - --(id) initWithSpriteFrame:(CCSpriteFrame *)spriteFrame delayUnits:(float)delayUnits userInfo:(NSDictionary*)userInfo -{ - if( (self=[super init]) ) { - self.spriteFrame = spriteFrame; - self.delayUnits = delayUnits; - self.userInfo = userInfo; - } - - return self; -} - --(void) dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@", self); - - [spriteFrame_ release]; - [userInfo_ release]; - - [super dealloc]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCAnimationFrame *copy = [[[self class] allocWithZone: zone] initWithSpriteFrame:[[spriteFrame_ copy] autorelease] delayUnits:delayUnits_ userInfo:[[userInfo_ copy] autorelease] ]; - return copy; -} - --(NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | SpriteFrame = %08X, delayUnits = %0.2f >", [self class], self, spriteFrame_, delayUnits_ ]; -} -@end - - -#pragma mark - CCAnimation - -@implementation CCAnimation -@synthesize frames = frames_, totalDelayUnits=totalDelayUnits_, delayPerUnit=delayPerUnit_, restoreOriginalFrame=restoreOriginalFrame_, loops=loops_; - -+(id) animation -{ - return [[[self alloc] init] autorelease]; -} - -+(id) animationWithSpriteFrames:(NSArray*)frames -{ - return [[[self alloc] initWithSpriteFrames:frames] autorelease]; -} - -+(id) animationWithSpriteFrames:(NSArray*)frames delay:(float)delay -{ - return [[[self alloc] initWithSpriteFrames:frames delay:delay] autorelease]; -} - -+(id) animationWithAnimationFrames:(NSArray*)arrayOfAnimationFrames delayPerUnit:(float)delayPerUnit loops:(NSUInteger)loops -{ - return [[[self alloc] initWithAnimationFrames:arrayOfAnimationFrames delayPerUnit:delayPerUnit loops:loops] autorelease]; -} - --(id) init -{ - return [self initWithSpriteFrames:nil delay:0]; -} - --(id) initWithSpriteFrames:(NSArray*)frames -{ - return [self initWithSpriteFrames:frames delay:0]; -} - --(id) initWithSpriteFrames:(NSArray*)array delay:(float)delay -{ - if( (self=[super init]) ) - { - loops_ = 1; - delayPerUnit_ = delay; - - self.frames = [NSMutableArray arrayWithCapacity:[array count]]; - - for( CCSpriteFrame *frame in array ) { - CCAnimationFrame *animFrame = [[CCAnimationFrame alloc] initWithSpriteFrame:frame delayUnits:1 userInfo:nil]; - - [self.frames addObject:animFrame]; - [animFrame release]; - totalDelayUnits_++; - } - - } - return self; -} - --(id) initWithAnimationFrames:(NSArray*)arrayOfAnimationFrames delayPerUnit:(float)delayPerUnit loops:(NSUInteger)loops -{ - if( ( self=[super init]) ) - { - delayPerUnit_ = delayPerUnit; - loops_ = loops; - - self.frames = [NSMutableArray arrayWithArray:arrayOfAnimationFrames]; - - for( CCAnimationFrame *animFrame in frames_ ) - totalDelayUnits_ += animFrame.delayUnits; - } - return self; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | frames=%d, totalDelayUnits=%d, delayPerUnit=%f, loops=%d>", [self class], self, - [frames_ count], - totalDelayUnits_, - delayPerUnit_, - loops_ - ]; -} - --(float) duration -{ - return totalDelayUnits_ * delayPerUnit_; -} - -- (id)copyWithZone:(NSZone *)zone -{ - CCAnimation *animation = [[[self class] allocWithZone: zone] initWithAnimationFrames:frames_ delayPerUnit:delayPerUnit_ loops:loops_]; - animation.restoreOriginalFrame = restoreOriginalFrame_; - - return animation; -} - --(void) dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@",self); - - [frames_ release]; - [super dealloc]; -} - --(void) addSpriteFrame:(CCSpriteFrame*)frame -{ - CCAnimationFrame *animFrame = [[CCAnimationFrame alloc] initWithSpriteFrame:frame delayUnits:1 userInfo:nil]; - [frames_ addObject:animFrame]; - [animFrame release]; - - // update duration - totalDelayUnits_++; -} - --(void) addSpriteFrameWithFilename:(NSString*)filename -{ - CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:filename]; - CGRect rect = CGRectZero; - rect.size = texture.contentSize; - CCSpriteFrame *spriteFrame = [CCSpriteFrame frameWithTexture:texture rect:rect]; - - [self addSpriteFrame:spriteFrame]; -} - --(void) addSpriteFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect -{ - CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:texture rect:rect]; - [self addSpriteFrame:frame]; -} - -@end diff --git a/Example/libs/cocos2d/CCAnimationCache.h b/Example/libs/cocos2d/CCAnimationCache.h deleted file mode 100644 index 5488e8a..0000000 --- a/Example/libs/cocos2d/CCAnimationCache.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import - -@class CCAnimation; - -/** Singleton that manages the CCAnimation objects. - It saves in a cache the animations. You should use this class if you want to save your animations in a cache. - - @since v0.99.5 - */ -@interface CCAnimationCache : NSObject -{ - NSMutableDictionary *animations_; -} - -/** Retruns ths shared instance of the Animation cache */ -+ (CCAnimationCache *) sharedAnimationCache; - -/** Purges the cache. It releases all the CCAnimation objects and the shared instance. - */ -+(void)purgeSharedAnimationCache; - -/** Adds a CCAnimation with a name. - */ --(void) addAnimation:(CCAnimation*)animation name:(NSString*)name; - -/** Deletes a CCAnimation from the cache. - */ --(void) removeAnimationByName:(NSString*)name; - -/** Returns a CCAnimation that was previously added. - If the name is not found it will return nil. - You should retain the returned copy if you are going to use it. - */ --(CCAnimation*) animationByName:(NSString*)name; - -/** Adds an animation from an NSDictionary - Make sure that the frames were previously loaded in the CCSpriteFrameCache. - @since v1.1 - */ --(void)addAnimationsWithDictionary:(NSDictionary *)dictionary; - -/** Adds an animation from a plist file. - Make sure that the frames were previously loaded in the CCSpriteFrameCache. - @since v1.1 - */ --(void)addAnimationsWithFile:(NSString *)plist; - -@end diff --git a/Example/libs/cocos2d/CCAnimationCache.m b/Example/libs/cocos2d/CCAnimationCache.m deleted file mode 100644 index f57cd33..0000000 --- a/Example/libs/cocos2d/CCAnimationCache.m +++ /dev/null @@ -1,250 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Copyright (c) 2011 John Wordsworth - * - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCAnimationCache.h" -#import "ccMacros.h" -#import "CCSpriteFrameCache.h" -#import "CCAnimation.h" -#import "CCSprite.h" -#import "Support/CCFileUtils.h" - - -@implementation CCAnimationCache - -#pragma mark CCAnimationCache - Alloc, Init & Dealloc - -static CCAnimationCache *sharedAnimationCache_=nil; - -+ (CCAnimationCache *)sharedAnimationCache -{ - if (!sharedAnimationCache_) - sharedAnimationCache_ = [[CCAnimationCache alloc] init]; - - return sharedAnimationCache_; -} - -+(id)alloc -{ - NSAssert(sharedAnimationCache_ == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; -} - -+(void)purgeSharedAnimationCache -{ - [sharedAnimationCache_ release]; - sharedAnimationCache_ = nil; -} - --(id) init -{ - if( (self=[super init]) ) { - animations_ = [[NSMutableDictionary alloc] initWithCapacity: 20]; - } - - return self; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | num of animations = %i>", [self class], self, [animations_ count]]; -} - --(void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - [animations_ release]; - [super dealloc]; -} - -#pragma mark CCAnimationCache - load/get/del - --(void) addAnimation:(CCAnimation*)animation name:(NSString*)name -{ - [animations_ setObject:animation forKey:name]; -} - --(void) removeAnimationByName:(NSString*)name -{ - if( ! name ) - return; - - [animations_ removeObjectForKey:name]; -} - --(CCAnimation*) animationByName:(NSString*)name -{ - return [animations_ objectForKey:name]; -} - -#pragma mark CCAnimationCache - from file - --(void) parseVersion1:(NSDictionary*)animations -{ - NSArray* animationNames = [animations allKeys]; - CCSpriteFrameCache *frameCache = [CCSpriteFrameCache sharedSpriteFrameCache]; - - for( NSString *name in animationNames ) { - NSDictionary* animationDict = [animations objectForKey:name]; - NSArray *frameNames = [animationDict objectForKey:@"frames"]; - NSNumber *delay = [animationDict objectForKey:@"delay"]; - CCAnimation* animation = nil; - - if ( frameNames == nil ) { - CCLOG(@"cocos2d: CCAnimationCache: Animation '%@' found in dictionary without any frames - cannot add to animation cache.", name); - continue; - } - - NSMutableArray *frames = [NSMutableArray arrayWithCapacity:[frameNames count]]; - - for( NSString *frameName in frameNames ) { - CCSpriteFrame *spriteFrame = [frameCache spriteFrameByName:frameName]; - - if ( ! spriteFrame ) { - CCLOG(@"cocos2d: CCAnimationCache: Animation '%@' refers to frame '%@' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.", name, frameName); - - continue; - } - - CCAnimationFrame *animFrame = [[CCAnimationFrame alloc] initWithSpriteFrame:spriteFrame delayUnits:1 userInfo:nil]; - [frames addObject:animFrame]; - [animFrame release]; - } - - if ( [frames count] == 0 ) { - CCLOG(@"cocos2d: CCAnimationCache: None of the frames for animation '%@' were found in the CCSpriteFrameCache. Animation is not being added to the Animation Cache.", name); - continue; - } else if ( [frames count] != [frameNames count] ) { - CCLOG(@"cocos2d: CCAnimationCache: An animation in your dictionary refers to a frame which is not in the CCSpriteFrameCache. Some or all of the frames for the animation '%@' may be missing.", name); - } - - animation = [CCAnimation animationWithAnimationFrames:frames delayPerUnit:[delay floatValue] loops:1 ]; - - [[CCAnimationCache sharedAnimationCache] addAnimation:animation name:name]; - } -} - --(void) parseVersion2:(NSDictionary*)animations -{ - NSArray* animationNames = [animations allKeys]; - CCSpriteFrameCache *frameCache = [CCSpriteFrameCache sharedSpriteFrameCache]; - - for( NSString *name in animationNames ) - { - NSDictionary* animationDict = [animations objectForKey:name]; - - NSNumber *loops = [animationDict objectForKey:@"loops"]; - BOOL restoreOriginalFrame = [[animationDict objectForKey:@"restoreOriginalFrame"] boolValue]; - NSArray *frameArray = [animationDict objectForKey:@"frames"]; - - - if ( frameArray == nil ) { - CCLOG(@"cocos2d: CCAnimationCache: Animation '%@' found in dictionary without any frames - cannot add to animation cache.", name); - continue; - } - - // Array of AnimationFrames - NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[frameArray count]]; - - for( NSDictionary *entry in frameArray ) { - NSString *spriteFrameName = [entry objectForKey:@"spriteframe"]; - CCSpriteFrame *spriteFrame = [frameCache spriteFrameByName:spriteFrameName]; - - if( ! spriteFrame ) { - CCLOG(@"cocos2d: CCAnimationCache: Animation '%@' refers to frame '%@' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.", name, spriteFrameName); - - continue; - } - - float delayUnits = [[entry objectForKey:@"delayUnits"] floatValue]; - NSDictionary *userInfo = [entry objectForKey:@"notification"]; - - CCAnimationFrame *animFrame = [[CCAnimationFrame alloc] initWithSpriteFrame:spriteFrame delayUnits:delayUnits userInfo:userInfo]; - - [array addObject:animFrame]; - [animFrame release]; - } - - float delayPerUnit = [[animationDict objectForKey:@"delayPerUnit"] floatValue]; - CCAnimation *animation = [[CCAnimation alloc] initWithAnimationFrames:array delayPerUnit:delayPerUnit loops:(loops?[loops intValue]:1)]; - [array release]; - - [animation setRestoreOriginalFrame:restoreOriginalFrame]; - - [[CCAnimationCache sharedAnimationCache] addAnimation:animation name:name]; - [animation release]; - } -} - --(void)addAnimationsWithDictionary:(NSDictionary *)dictionary -{ - NSDictionary *animations = [dictionary objectForKey:@"animations"]; - - if ( animations == nil ) { - CCLOG(@"cocos2d: CCAnimationCache: No animations were found in provided dictionary."); - return; - } - - NSUInteger version = 1; - NSDictionary *properties = [dictionary objectForKey:@"properties"]; - if( properties ) - version = [[properties objectForKey:@"format"] intValue]; - - NSArray *spritesheets = [properties objectForKey:@"spritesheets"]; - for( NSString *name in spritesheets ) - [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:name]; - - switch (version) { - case 1: - [self parseVersion1:animations]; - break; - case 2: - [self parseVersion2:animations]; - break; - default: - NSAssert(NO, @"Invalid animation format"); - } -} - - -/** Read an NSDictionary from a plist file and parse it automatically for animations */ --(void)addAnimationsWithFile:(NSString *)plist -{ - NSAssert( plist, @"Invalid texture file name"); - - NSString *path = [CCFileUtils fullPathFromRelativePath:plist]; - NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - - NSAssert1( dict, @"CCAnimationCache: File could not be found: %@", plist); - - - [self addAnimationsWithDictionary:dict]; -} - -@end diff --git a/Example/libs/cocos2d/CCAtlasNode.h b/Example/libs/cocos2d/CCAtlasNode.h deleted file mode 100644 index 5360e54..0000000 --- a/Example/libs/cocos2d/CCAtlasNode.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -#import "CCTextureAtlas.h" -#import "CCNode.h" -#import "CCProtocols.h" - -/** CCAtlasNode is a subclass of CCNode that implements the CCRGBAProtocol and - CCTextureProtocol protocol - - It knows how to render a TextureAtlas object. - If you are going to render a TextureAtlas consider subclassing CCAtlasNode (or a subclass of CCAtlasNode) - - All features from CCNode are valid, plus the following features: - - opacity and RGB colors - */ -@interface CCAtlasNode : CCNode -{ - // texture atlas - CCTextureAtlas *textureAtlas_; - - // chars per row - NSUInteger itemsPerRow_; - // chars per column - NSUInteger itemsPerColumn_; - - // width of each char - NSUInteger itemWidth_; - // height of each char - NSUInteger itemHeight_; - - // quads to draw - NSUInteger quadsToDraw_; - - // blend function - ccBlendFunc blendFunc_; - - // texture RGBA. - GLubyte opacity_; - ccColor3B color_; - ccColor3B colorUnmodified_; - BOOL opacityModifyRGB_; - - // color uniform - GLint uniformColor_; -} - -/** conforms to CCTextureProtocol protocol */ -@property (nonatomic,readwrite,retain) CCTextureAtlas *textureAtlas; - -/** conforms to CCTextureProtocol protocol */ -@property (nonatomic,readwrite) ccBlendFunc blendFunc; - -/** conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readwrite) GLubyte opacity; -/** conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readwrite) ccColor3B color; - -/** how many quads to draw */ -@property (nonatomic,readwrite) NSUInteger quadsToDraw; - -/** creates a CCAtlasNode with an Atlas file the width and height of each item measured in points and the quantity of items to render*/ -+(id) atlasWithTileFile:(NSString*)tile tileWidth:(NSUInteger)w tileHeight:(NSUInteger)h itemsToRender: (NSUInteger) c; - -/** initializes an CCAtlasNode with an Atlas file the width and height of each item measured in points and the quantity of items to render*/ --(id) initWithTileFile:(NSString*)tile tileWidth:(NSUInteger)w tileHeight:(NSUInteger)h itemsToRender: (NSUInteger) c; - -/** updates the Atlas (indexed vertex array). - * Shall be overriden in subclasses - */ --(void) updateAtlasValues; -@end diff --git a/Example/libs/cocos2d/CCAtlasNode.m b/Example/libs/cocos2d/CCAtlasNode.m deleted file mode 100644 index bb083c1..0000000 --- a/Example/libs/cocos2d/CCAtlasNode.m +++ /dev/null @@ -1,209 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -#import "CCAtlasNode.h" -#import "ccMacros.h" -#import "CCGLProgram.h" -#import "CCShaderCache.h" -#import "ccGLStateCache.h" -#import "CCDirector.h" -#import "Support/TransformUtils.h" - -// external -#import "kazmath/GL/matrix.h" - - -@interface CCAtlasNode () --(void) calculateMaxItems; --(void) updateBlendFunc; --(void) updateOpacityModifyRGB; -@end - -@implementation CCAtlasNode - -@synthesize textureAtlas = textureAtlas_; -@synthesize blendFunc = blendFunc_; -@synthesize quadsToDraw = quadsToDraw_; - -#pragma mark CCAtlasNode - Creation & Init -- (id) init -{ - NSAssert( NO, @"Not supported - Use initWtihTileFile instead"); - return self; -} - -+(id) atlasWithTileFile:(NSString*)tile tileWidth:(NSUInteger)w tileHeight:(NSUInteger)h itemsToRender: (NSUInteger) c -{ - return [[[self alloc] initWithTileFile:tile tileWidth:w tileHeight:h itemsToRender:c] autorelease]; -} - --(id) initWithTileFile:(NSString*)tile tileWidth:(NSUInteger)w tileHeight:(NSUInteger)h itemsToRender: (NSUInteger) c -{ - if( (self=[super init]) ) { - - itemWidth_ = w; - itemHeight_ = h; - - opacity_ = 255; - color_ = colorUnmodified_ = ccWHITE; - opacityModifyRGB_ = YES; - - blendFunc_.src = CC_BLEND_SRC; - blendFunc_.dst = CC_BLEND_DST; - - CCTextureAtlas * newAtlas = [[CCTextureAtlas alloc] initWithFile:tile capacity:c]; - self.textureAtlas = newAtlas; - [newAtlas release]; - - if( ! textureAtlas_ ) { - CCLOG(@"cocos2d: Could not initialize CCAtlasNode. Invalid Texture"); - [self release]; - return nil; - } - - [self updateBlendFunc]; - [self updateOpacityModifyRGB]; - - [self calculateMaxItems]; - - self.quadsToDraw = c; - - // shader stuff - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTexture_uColor]; - uniformColor_ = glGetUniformLocation( shaderProgram_->program_, "u_color"); - } - return self; -} - --(void) dealloc -{ - [textureAtlas_ release]; - - [super dealloc]; -} - -#pragma mark CCAtlasNode - Atlas generation - --(void) calculateMaxItems -{ - CGSize s = [[textureAtlas_ texture] contentSize]; - itemsPerColumn_ = s.height / itemHeight_; - itemsPerRow_ = s.width / itemWidth_; -} - --(void) updateAtlasValues -{ - [NSException raise:@"CCAtlasNode:Abstract" format:@"updateAtlasValue not overriden"]; -} - -#pragma mark CCAtlasNode - draw -- (void) draw -{ - CC_NODE_DRAW_SETUP(); - - ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); - - GLfloat colors[4] = {color_.r / 255.0f, color_.g / 255.0f, color_.b / 255.0f, opacity_ / 255.0f}; - [shaderProgram_ setUniformLocation:uniformColor_ with4fv:colors count:1]; - - [textureAtlas_ drawNumberOfQuads:quadsToDraw_ fromIndex:0]; -} - -#pragma mark CCAtlasNode - RGBA protocol - -- (ccColor3B) color -{ - if(opacityModifyRGB_) - return colorUnmodified_; - - return color_; -} - --(void) setColor:(ccColor3B)color3 -{ - color_ = colorUnmodified_ = color3; - - if( opacityModifyRGB_ ){ - color_.r = color3.r * opacity_/255; - color_.g = color3.g * opacity_/255; - color_.b = color3.b * opacity_/255; - } -} - --(GLubyte) opacity -{ - return opacity_; -} - --(void) setOpacity:(GLubyte) anOpacity -{ - opacity_ = anOpacity; - - // special opacity for premultiplied textures - if( opacityModifyRGB_ ) - [self setColor: colorUnmodified_]; -} - --(void) setOpacityModifyRGB:(BOOL)modify -{ - ccColor3B oldColor = self.color; - opacityModifyRGB_ = modify; - self.color = oldColor; -} - --(BOOL) doesOpacityModifyRGB -{ - return opacityModifyRGB_; -} - --(void) updateOpacityModifyRGB -{ - opacityModifyRGB_ = [textureAtlas_.texture hasPremultipliedAlpha]; -} - -#pragma mark CCAtlasNode - CCNodeTexture protocol - --(void) updateBlendFunc -{ - if( ! [textureAtlas_.texture hasPremultipliedAlpha] ) { - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; - } -} - --(void) setTexture:(CCTexture2D*)texture -{ - textureAtlas_.texture = texture; - [self updateBlendFunc]; - [self updateOpacityModifyRGB]; -} - --(CCTexture2D*) texture -{ - return textureAtlas_.texture; -} - -@end diff --git a/Example/libs/cocos2d/CCCamera.h b/Example/libs/cocos2d/CCCamera.h deleted file mode 100644 index 415caf7..0000000 --- a/Example/libs/cocos2d/CCCamera.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - - -#import "CCNode.h" -#import "kazmath/mat4.h" - -/** - A CCCamera is used in every CCNode. - Useful to look at the object from different views. - The OpenGL gluLookAt() function is used to locate the - camera. - - If the object is transformed by any of the scale, rotation or - position attributes, then they will override the camera. - - IMPORTANT: Either your use the camera or the rotation/scale/position properties. You can't use both. - World coordinates won't work if you use the camera. - - Limitations: - - - Some nodes, like CCParallaxNode, CCParticle uses world node coordinates, and they won't work properly if you move them (or any of their ancestors) - using the camera. - - - It doesn't work on batched nodes like CCSprite objects when they are parented to a CCSpriteBatchNode object. - - - It is recommended to use it ONLY if you are going to create 3D effects. For 2D effecs, use the action CCFollow or position/scale/rotate. - -*/ - -@interface CCCamera : NSObject -{ - float eyeX_; - float eyeY_; - float eyeZ_; - - float centerX_; - float centerY_; - float centerZ_; - - float upX_; - float upY_; - float upZ_; - - BOOL dirty_; - - kmMat4 lookupMatrix_; -} - -/** whether of not the camera is dirty */ -@property (nonatomic,readwrite) BOOL dirty; - -/** returns the Z eye */ -+(float) getZEye; - -/** sets the camera in the defaul position */ --(void) restore; -/** Sets the camera using gluLookAt using its eye, center and up_vector */ --(void) locate; -/** sets the eye values in points */ --(void) setEyeX: (float)x eyeY:(float)y eyeZ:(float)z; -/** sets the center values in points */ --(void) setCenterX: (float)x centerY:(float)y centerZ:(float)z; -/** sets the up values */ --(void) setUpX: (float)x upY:(float)y upZ:(float)z; - -/** get the eye vector values in points */ --(void) eyeX:(float*)x eyeY:(float*)y eyeZ:(float*)z; -/** get the center vector values in points */ --(void) centerX:(float*)x centerY:(float*)y centerZ:(float*)z; -/** get the up vector values */ --(void) upX:(float*)x upY:(float*)y upZ:(float*)z; - - -@end diff --git a/Example/libs/cocos2d/CCCamera.m b/Example/libs/cocos2d/CCCamera.m deleted file mode 100644 index ff90496..0000000 --- a/Example/libs/cocos2d/CCCamera.m +++ /dev/null @@ -1,148 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -#import "Platforms/CCGL.h" -#import "CCCamera.h" -#import "ccMacros.h" -#import "CCDrawingPrimitives.h" -#import "kazmath/GL/matrix.h" - -@implementation CCCamera - -@synthesize dirty = dirty_; - --(id) init -{ - if( (self=[super init]) ) - [self restore]; - - return self; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | center = (%.2f,%.2f,%.2f)>", [self class], self, centerX_, centerY_, centerZ_]; -} - - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - [super dealloc]; -} - --(void) restore -{ - eyeX_ = eyeY_ = 0; - eyeZ_ = [CCCamera getZEye]; - - centerX_ = centerY_ = centerZ_ = 0; - - upX_ = 0.0f; - upY_ = 1.0f; - upZ_ = 0.0f; - - kmMat4Identity( &lookupMatrix_ ); - - dirty_ = NO; -} - --(void) locate -{ - if( dirty_ ) { - - kmVec3 eye, center, up; - - kmVec3Fill( &eye, eyeX_, eyeY_ , eyeZ_ ); - kmVec3Fill( ¢er, centerX_, centerY_, centerZ_ ); - - kmVec3Fill( &up, upX_, upY_, upZ_); - kmMat4LookAt( &lookupMatrix_, &eye, ¢er, &up); - - dirty_ = NO; - - } - - kmGLMultMatrix( &lookupMatrix_ ); - -} - -+(float) getZEye -{ - return FLT_EPSILON; - // CGSize s = [[CCDirector sharedDirector] displaySize]; - // return ( s.height / 1.1566f ); -} - --(void) setEyeX: (float)x eyeY:(float)y eyeZ:(float)z -{ - eyeX_ = x; - eyeY_ = y; - eyeZ_ = z; - - dirty_ = YES; -} - --(void) setCenterX: (float)x centerY:(float)y centerZ:(float)z -{ - centerX_ = x; - centerY_ = y; - centerZ_ = z; - - dirty_ = YES; -} - --(void) setUpX: (float)x upY:(float)y upZ:(float)z -{ - upX_ = x; - upY_ = y; - upZ_ = z; - - dirty_ = YES; -} - --(void) eyeX: (float*)x eyeY:(float*)y eyeZ:(float*)z -{ - *x = eyeX_; - *y = eyeY_; - *z = eyeZ_; -} - --(void) centerX: (float*)x centerY:(float*)y centerZ:(float*)z -{ - *x = centerX_; - *y = centerY_; - *z = centerZ_; -} - --(void) upX: (float*)x upY:(float*)y upZ:(float*)z -{ - *x = upX_; - *y = upY_; - *z = upZ_; -} - -@end diff --git a/Example/libs/cocos2d/CCConfiguration.h b/Example/libs/cocos2d/CCConfiguration.h deleted file mode 100644 index 9bae614..0000000 --- a/Example/libs/cocos2d/CCConfiguration.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import - -#import "Platforms/CCGL.h" - -/** OS version definitions. Includes both iOS and Mac OS versions - */ -enum { - kCCiOSVersion_4_0 = 0x04000000, - kCCiOSVersion_4_0_1 = 0x04000100, - kCCiOSVersion_4_1 = 0x04010000, - kCCiOSVersion_4_2 = 0x04020000, - kCCiOSVersion_4_2_1 = 0x04020100, - kCCiOSVersion_4_3 = 0x04030000, - kCCiOSVersion_4_3_1 = 0x04030100, - kCCiOSVersion_4_3_2 = 0x04030200, - kCCiOSVersion_4_3_3 = 0x04030300, - kCCiOSVersion_4_3_4 = 0x04030400, - kCCiOSVersion_4_3_5 = 0x04030500, - kCCiOSVersion_5_0 = 0x05000000, - kCCiOSVersion_5_0_1 = 0x05000100, - - kCCMacVersion_10_6 = 0x0a060000, - kCCMacVersion_10_7 = 0x0a070000, - kCCMacVersion_10_8 = 0x0a080000, -}; - -/** - CCConfiguration contains some openGL variables - @since v0.99.0 - */ -@interface CCConfiguration : NSObject { - - GLint maxTextureSize_; - GLint maxModelviewStackDepth_; - BOOL supportsPVRTC_; - BOOL supportsNPOT_; - BOOL supportsBGRA8888_; - BOOL supportsDiscardFramebuffer_; - unsigned int OSVersion_; - GLint maxSamplesAllowed_; - GLint maxTextureUnits_; -} - -/** OpenGL Max texture size. */ -@property (nonatomic, readonly) GLint maxTextureSize; - -/** OpenGL Max Modelview Stack Depth. */ -@property (nonatomic, readonly) GLint maxModelviewStackDepth; - -/** returns the maximum texture units - @since v2.0.0 - */ -@property (nonatomic, readonly) GLint maxTextureUnits; - -/** Whether or not the GPU supports NPOT (Non Power Of Two) textures. - OpenGL ES 2.0 already supports NPOT (iOS). - - @since v0.99.2 - */ -@property (nonatomic, readonly) BOOL supportsNPOT; - -/** Whether or not PVR Texture Compressed is supported */ -@property (nonatomic, readonly) BOOL supportsPVRTC; - -/** Whether or not BGRA8888 textures are supported. - - @since v0.99.2 - */ -@property (nonatomic, readonly) BOOL supportsBGRA8888; - -/** Whether or not glDiscardFramebufferEXT is supported - - @since v0.99.2 - */ -@property (nonatomic, readonly) BOOL supportsDiscardFramebuffer; - -/** returns the OS version. - - On iOS devices it returns the firmware version. - - On Mac returns the OS version - - @since v0.99.5 - */ -@property (nonatomic, readonly) unsigned int OSVersion; - -/** returns a shared instance of the CCConfiguration */ -+(CCConfiguration *) sharedConfiguration; - -/** returns whether or not an OpenGL is supported */ -- (BOOL) checkForGLExtension:(NSString *)searchName; - - - -@end diff --git a/Example/libs/cocos2d/CCConfiguration.m b/Example/libs/cocos2d/CCConfiguration.m deleted file mode 100644 index 24b2cae..0000000 --- a/Example/libs/cocos2d/CCConfiguration.m +++ /dev/null @@ -1,179 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "ccMacros.h" - -#ifdef __CC_PLATFORM_IOS -#import // Needed for UIDevice -#endif - -#import "Platforms/CCGL.h" -#import "CCConfiguration.h" -#import "ccMacros.h" -#import "ccConfig.h" -#import "Support/OpenGL_Internal.h" - -@implementation CCConfiguration - -@synthesize maxTextureSize = maxTextureSize_, maxTextureUnits=maxTextureUnits_; -@synthesize supportsPVRTC = supportsPVRTC_; -@synthesize maxModelviewStackDepth = maxModelviewStackDepth_; -@synthesize supportsNPOT = supportsNPOT_; -@synthesize supportsBGRA8888 = supportsBGRA8888_; -@synthesize supportsDiscardFramebuffer = supportsDiscardFramebuffer_; -@synthesize OSVersion = OSVersion_; - -// -// singleton stuff -// -static CCConfiguration *_sharedConfiguration = nil; - -static char * glExtensions; - -+ (CCConfiguration *)sharedConfiguration -{ - if (!_sharedConfiguration) - _sharedConfiguration = [[self alloc] init]; - - return _sharedConfiguration; -} - -+(id)alloc -{ - NSAssert(_sharedConfiguration == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; -} - - -#ifdef __CC_PLATFORM_IOS -#elif defined(__CC_PLATFORM_MAC) -- (NSString*)getMacVersion -{ - SInt32 versionMajor, versionMinor, versionBugFix; - Gestalt(gestaltSystemVersionMajor, &versionMajor); - Gestalt(gestaltSystemVersionMinor, &versionMinor); - Gestalt(gestaltSystemVersionBugFix, &versionBugFix); - - return [NSString stringWithFormat:@"%d.%d.%d", versionMajor, versionMinor, versionBugFix]; -} -#endif // __CC_PLATFORM_MAC - --(id) init -{ - if( (self=[super init])) { - - // Obtain iOS version - OSVersion_ = 0; -#ifdef __CC_PLATFORM_IOS - NSString *OSVer = [[UIDevice currentDevice] systemVersion]; -#elif defined(__CC_PLATFORM_MAC) - NSString *OSVer = [self getMacVersion]; -#endif - NSArray *arr = [OSVer componentsSeparatedByString:@"."]; - int idx = 0x01000000; - for( NSString *str in arr ) { - int value = [str intValue]; - OSVersion_ += value * idx; - idx = idx >> 8; - } - CCLOG(@"cocos2d: OS version: %@ (0x%08x)", OSVer, OSVersion_); - - CCLOG(@"cocos2d: GL_VENDOR: %s", glGetString(GL_VENDOR) ); - CCLOG(@"cocos2d: GL_RENDERER: %s", glGetString ( GL_RENDERER ) ); - CCLOG(@"cocos2d: GL_VERSION: %s", glGetString ( GL_VERSION ) ); - - glExtensions = (char*) glGetString(GL_EXTENSIONS); - - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize_); - glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits_ ); - -#ifdef __CC_PLATFORM_IOS - if( OSVersion_ >= kCCiOSVersion_4_0 ) - glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamplesAllowed_); - else - maxSamplesAllowed_ = 0; -#elif defined(__CC_PLATFORM_MAC) - glGetIntegerv(GL_MAX_SAMPLES, &maxSamplesAllowed_); -#endif - - supportsPVRTC_ = [self checkForGLExtension:@"GL_IMG_texture_compression_pvrtc"]; -#ifdef __CC_PLATFORM_IOS - supportsNPOT_ = YES; -#elif defined(__CC_PLATFORM_MAC) - supportsNPOT_ = [self checkForGLExtension:@"GL_ARB_texture_non_power_of_two"]; -#endif - // It seems that somewhere between firmware iOS 3.0 and 4.2 Apple renamed - // GL_IMG_... to GL_APPLE.... So we should check both names - -#ifdef __CC_PLATFORM_IOS - BOOL bgra8a = [self checkForGLExtension:@"GL_IMG_texture_format_BGRA8888"]; - BOOL bgra8b = [self checkForGLExtension:@"GL_APPLE_texture_format_BGRA8888"]; - supportsBGRA8888_ = bgra8a | bgra8b; -#elif defined(__CC_PLATFORM_MAC) - supportsBGRA8888_ = [self checkForGLExtension:@"GL_EXT_bgra"]; -#endif - - supportsDiscardFramebuffer_ = [self checkForGLExtension:@"GL_EXT_discard_framebuffer"]; - - CCLOG(@"cocos2d: GL_MAX_TEXTURE_SIZE: %d", maxTextureSize_); - CCLOG(@"cocos2d: GL_MAX_TEXTURE_UNITS: %d", maxTextureUnits_); - CCLOG(@"cocos2d: GL_MAX_SAMPLES: %d", maxSamplesAllowed_); - CCLOG(@"cocos2d: GL supports PVRTC: %s", (supportsPVRTC_ ? "YES" : "NO") ); - CCLOG(@"cocos2d: GL supports BGRA8888 textures: %s", (supportsBGRA8888_ ? "YES" : "NO") ); - CCLOG(@"cocos2d: GL supports NPOT textures: %s", (supportsNPOT_ ? "YES" : "NO") ); - CCLOG(@"cocos2d: GL supports discard_framebuffer: %s", (supportsDiscardFramebuffer_ ? "YES" : "NO") ); - - - CCLOG(@"cocos2d: compiled with Profiling Support: %s", -#if CC_ENABLE_PROFILERS - - "YES - *** Disable it when you finish profiling ***" -#else - "NO" -#endif - ); - - } - -#if CC_ENABLE_GL_STATE_CACHE == 0 - printf("\n"); - NSLog(@"cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it by editing ccConfig.h"); - printf("\n"); -#endif - - CHECK_GL_ERROR_DEBUG(); - - return self; -} - -- (BOOL) checkForGLExtension:(NSString *)searchName -{ - // For best results, extensionsNames should be stored in your renderer so that it does not - // need to be recreated on each invocation. - NSString *extensionsString = [NSString stringWithCString:glExtensions encoding: NSASCIIStringEncoding]; - NSArray *extensionsNames = [extensionsString componentsSeparatedByString:@" "]; - return [extensionsNames containsObject: searchName]; -} -@end diff --git a/Example/libs/cocos2d/CCDirector.h b/Example/libs/cocos2d/CCDirector.h deleted file mode 100644 index 1fda4c0..0000000 --- a/Example/libs/cocos2d/CCDirector.h +++ /dev/null @@ -1,332 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -#import "ccConfig.h" -#import "ccTypes.h" -#import "ccMacros.h" - -#import "CCProtocols.h" -#import "Platforms/CCGL.h" -#import "kazmath/mat4.h" - -/** @typedef ccDirectorProjection - Possible OpenGL projections used by director - */ -typedef enum { - /// sets a 2D projection (orthogonal projection). - kCCDirectorProjection2D, - - /// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500. - kCCDirectorProjection3D, - - /// it calls "updateProjection" on the projection delegate. - kCCDirectorProjectionCustom, - - /// Detault projection is 3D projection - kCCDirectorProjectionDefault = kCCDirectorProjection3D, - -} ccDirectorProjection; - - -@class CCLabelAtlas; -@class CCScene; -@class CCScheduler; -@class CCActionManager; - - -#ifdef __CC_PLATFORM_IOS -#define CC_VIEWCONTROLLER UIViewController -#elif defined(__CC_PLATFORM_MAC) -#define CC_VIEWCONTROLLER NSObject -#endif - -/**Class that creates and handle the main Window and manages how -and when to execute the Scenes. - - The CCDirector is also resposible for: - - initializing the OpenGL ES context - - setting the OpenGL pixel format (default on is RGB565) - - setting the OpenGL buffer depth (default one is 0-bit) - - setting the projection (default one is 3D) - - Since the CCDirector is a singleton, the standard way to use it is by calling: - - [[CCDirector sharedDirector] methodName]; - - The CCDirector also sets the default OpenGL context: - - GL_TEXTURE_2D is enabled - - GL_VERTEX_ARRAY is enabled - - GL_COLOR_ARRAY is enabled - - GL_TEXTURE_COORD_ARRAY is enabled -*/ -@interface CCDirector : CC_VIEWCONTROLLER -{ - // internal timer - NSTimeInterval animationInterval_; - NSTimeInterval oldAnimationInterval_; - - /* stats */ - BOOL displayStats_; - - NSUInteger frames_; - NSUInteger totalFrames_; - ccTime secondsPerFrame_; - - ccTime accumDt_; - ccTime frameRate_; - CCLabelAtlas *FPSLabel_; - CCLabelAtlas *SPFLabel_; - CCLabelAtlas *drawsLabel_; - - /* is the running scene paused */ - BOOL isPaused_; - - /* The running scene */ - CCScene *runningScene_; - - /* This object will be visited after the scene. Useful to hook a notification node */ - id notificationNode_; - - /* will be the next 'runningScene' in the next frame - nextScene is a weak reference. */ - CCScene *nextScene_; - - /* If YES, then "old" scene will receive the cleanup message */ - BOOL sendCleanupToScene_; - - /* scheduled scenes */ - NSMutableArray *scenesStack_; - - /* last time the main loop was updated */ - struct timeval lastUpdate_; - /* delta time since last tick to main loop */ - ccTime dt; - /* whether or not the next delta time will be zero */ - BOOL nextDeltaTimeZero_; - - /* projection used */ - ccDirectorProjection projection_; - - /* CCDirector delegate */ - id delegate_; - - /* window size in points */ - CGSize winSizeInPoints_; - - /* window size in pixels */ - CGSize winSizeInPixels_; - - /* the cocos2d running thread */ - NSThread *runningThread_; - - /* scheduler associated with this director */ - CCScheduler *scheduler_; - - /* action manager associated with this director */ - CCActionManager *actionManager_; - - /* OpenGLView. On iOS it is a copy of self.view */ - CCGLView *view_; -} - -/** returns the cocos2d thread. - If you want to run any cocos2d task, run it in this thread. - On iOS usually it is the main thread. - @since v0.99.5 - */ -@property (readonly, nonatomic ) NSThread *runningThread; -/** The current running Scene. Director can only run one Scene at the time */ -@property (nonatomic,readonly) CCScene* runningScene; -/** The FPS value */ -@property (nonatomic,readwrite, assign) NSTimeInterval animationInterval; -/** Whether or not to display director statistics */ -@property (nonatomic, readwrite, assign) BOOL displayStats; -/** whether or not the next delta time will be zero */ -@property (nonatomic,readwrite,assign) BOOL nextDeltaTimeZero; -/** Whether or not the Director is paused */ -@property (nonatomic,readonly) BOOL isPaused; -/** Sets an OpenGL projection */ -@property (nonatomic,readwrite) ccDirectorProjection projection; -/** How many frames were called since the director started */ -@property (nonatomic,readonly) NSUInteger totalFrames; -/** seconds per frame */ -@property (nonatomic, readonly) ccTime secondsPerFrame; - -/** Whether or not the replaced scene will receive the cleanup message. - If the new scene is pushed, then the old scene won't receive the "cleanup" message. - If the new scene replaces the old one, the it will receive the "cleanup" message. - @since v0.99.0 - */ -@property (nonatomic, readonly) BOOL sendCleanupToScene; - -/** This object will be visited after the main scene is visited. - This object MUST implement the "visit" selector. - Useful to hook a notification object, like CCNotifications (http://github.com/manucorporat/CCNotifications) - @since v0.99.5 - */ -@property (nonatomic, readwrite, retain) id notificationNode; - -/** CCDirector delegate. It shall implemente the CCDirectorDelegate protocol - @since v0.99.5 - */ -@property (nonatomic, readwrite, retain) id delegate; - -/** CCScheduler associated with this director - @since v2.0 - */ -@property (nonatomic,readwrite,retain) CCScheduler *scheduler; - -/** CCActionManager associated with this director - @since v2.0 - */ -@property (nonatomic,readwrite,retain) CCActionManager *actionManager; - -/** returns a shared instance of the director */ -+(CCDirector*)sharedDirector; - - -#pragma mark Director - Stats - -#pragma mark Director - Win Size -/** returns the size of the OpenGL view in points */ -- (CGSize) winSize; - -/** returns the size of the OpenGL view in pixels. - On Mac winSize and winSizeInPixels return the same value. - */ -- (CGSize) winSizeInPixels; - -/** changes the projection size */ --(void) reshapeProjection:(CGSize)newWindowSize; - -/** converts a UIKit coordinate to an OpenGL coordinate - Useful to convert (multi) touchs coordinates to the current layout (portrait or landscape) - */ --(CGPoint) convertToGL: (CGPoint) p; -/** converts an OpenGL coordinate to a UIKit coordinate - Useful to convert node points to window points for calls such as glScissor - */ --(CGPoint) convertToUI:(CGPoint)p; - -/// XXX: missing description --(float) getZEye; - -#pragma mark Director - Scene Management - -/**Enters the Director's main loop with the given Scene. - * Call it to run only your FIRST scene. - * Don't call it if there is already a running scene. - * - * It will call pushScene: and then it will call startAnimation - */ -- (void) runWithScene:(CCScene*) scene; - -/**Suspends the execution of the running scene, pushing it on the stack of suspended scenes. - * The new scene will be executed. - * Try to avoid big stacks of pushed scenes to reduce memory allocation. - * ONLY call it if there is a running scene. - */ -- (void) pushScene:(CCScene*) scene; - -/**Pops out a scene from the queue. - * This scene will replace the running one. - * The running scene will be deleted. If there are no more scenes in the stack the execution is terminated. - * ONLY call it if there is a running scene. - */ -- (void) popScene; - -/** Replaces the running scene with a new one. The running scene is terminated. - * ONLY call it if there is a running scene. - */ --(void) replaceScene: (CCScene*) scene; - -/** Ends the execution, releases the running scene. - It doesn't remove the OpenGL view from its parent. You have to do it manually. - */ --(void) end; - -/** Pauses the running scene. - The running scene will be _drawed_ but all scheduled timers will be paused - While paused, the draw rate will be 4 FPS to reduce CPU consuption - */ --(void) pause; - -/** Resumes the paused scene - The scheduled timers will be activated again. - The "delta time" will be 0 (as if the game wasn't paused) - */ --(void) resume; - -/** Stops the animation. Nothing will be drawn. The main loop won't be triggered anymore. - If you wan't to pause your animation call [pause] instead. - */ --(void) stopAnimation; - -/** The main loop is triggered again. - Call this function only if [stopAnimation] was called earlier - @warning Dont' call this function to start the main loop. To run the main loop call runWithScene - */ --(void) startAnimation; - -/** Draw the scene. - This method is called every frame. Don't call it manually. - */ --(void) drawScene; - - -// XXX: Hack. Should be placed on CCDirectorMac.h. Refactoring needed -#if defined(__CC_PLATFORM_MAC) -/** sets the openGL view */ --(void) setView:(CCGLView*)view; - -/** returns the OpenGL view */ --(CCGLView*) view; -#endif - -#pragma mark Director - Memory Helper - -/** Removes all the cocos2d data that was cached automatically. - It will purge the CCTextureCache, CCLabelBMFont cache. - IMPORTANT: The CCSpriteFrameCache won't be purged. If you want to purge it, you have to purge it manually. - @since v0.99.3 - */ --(void) purgeCachedData; - -// OpenGL Helper - -/** sets the OpenGL default values */ --(void) setGLDefaultValues; -/** enables/disables OpenGL alpha blending */ -- (void) setAlphaBlending: (BOOL) on; -/** enables/disables OpenGL depth test */ -- (void) setDepthTest: (BOOL) on; - -// helper -/** creates the Stats labels */ --(void) createStatsLabel; -@end - -// optimization. Should only be used to read it. Never to write it. -extern NSUInteger __ccNumberOfDraws; diff --git a/Example/libs/cocos2d/CCDirector.m b/Example/libs/cocos2d/CCDirector.m deleted file mode 100644 index 7134942..0000000 --- a/Example/libs/cocos2d/CCDirector.m +++ /dev/null @@ -1,606 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -/* Idea of decoupling Window from Director taken from OC3D project: http://code.google.com/p/oc3d/ - */ - -#import - -// cocos2d imports -#import "CCDirector.h" -#import "CCScheduler.h" -#import "CCActionManager.h" -#import "CCTextureCache.h" -#import "CCAnimationCache.h" -#import "CCLabelAtlas.h" -#import "ccMacros.h" -#import "CCTransition.h" -#import "CCScene.h" -#import "CCSpriteFrameCache.h" -#import "CCTexture2D.h" -#import "CCLabelBMFont.h" -#import "CCLayer.h" -#import "ccGLStateCache.h" -#import "CCShaderCache.h" - -// support imports -#import "Platforms/CCGL.h" -#import "Platforms/CCNS.h" - -#import "Support/OpenGL_Internal.h" -#import "Support/CGPointExtension.h" -#import "Support/CCProfiling.h" - -#ifdef __CC_PLATFORM_IOS -#import "Platforms/iOS/CCDirectorIOS.h" -#define CC_DIRECTOR_DEFAULT CCDirectorDisplayLink -#elif defined(__CC_PLATFORM_MAC) -#import "Platforms/Mac/CCDirectorMac.h" -#define CC_DIRECTOR_DEFAULT CCDirectorDisplayLink -#endif - - -#pragma mark - -#pragma mark Director - global variables (optimization) - -// XXX it shoul be a Director ivar. Move it there once support for multiple directors is added -NSUInteger __ccNumberOfDraws = 0; - -#define kDefaultFPS 60.0 // 60 frames per second - -extern NSString * cocos2dVersion(void); - -@interface CCDirector (Private) --(void) setNextScene; -// shows the statistics --(void) showStats; -// calculates delta time since last time it was called --(void) calculateDeltaTime; -// calculates the milliseconds per frame from the start of the frame --(void) calculateMPF; -@end - -@implementation CCDirector - -@synthesize animationInterval = animationInterval_; -@synthesize runningScene = runningScene_; -@synthesize displayStats = displayStats_; -@synthesize nextDeltaTimeZero = nextDeltaTimeZero_; -@synthesize isPaused = isPaused_; -@synthesize sendCleanupToScene = sendCleanupToScene_; -@synthesize runningThread = runningThread_; -@synthesize notificationNode = notificationNode_; -@synthesize delegate = delegate_; -@synthesize totalFrames = totalFrames_; -@synthesize secondsPerFrame = secondsPerFrame_; -@synthesize scheduler = scheduler_; -@synthesize actionManager = actionManager_; - -// -// singleton stuff -// -static CCDirector *_sharedDirector = nil; - -+ (CCDirector *)sharedDirector -{ - if (!_sharedDirector) { - - // - // Default Director is DisplayLink - // - if( [ [CCDirector class] isEqual:[self class]] ) - _sharedDirector = [[CC_DIRECTOR_DEFAULT alloc] init]; - else - _sharedDirector = [[self alloc] init]; - } - - return _sharedDirector; -} - -+(id)alloc -{ - NSAssert(_sharedDirector == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; -} - -- (id) init -{ - CCLOG(@"cocos2d: %@", cocos2dVersion() ); - - if( (self=[super init] ) ) { - - CCLOG(@"cocos2d: Using Director Type:%@", [self class]); - - // scenes - runningScene_ = nil; - nextScene_ = nil; - - notificationNode_ = nil; - - oldAnimationInterval_ = animationInterval_ = 1.0 / kDefaultFPS; - scenesStack_ = [[NSMutableArray alloc] initWithCapacity:10]; - - // Set default projection (3D) - projection_ = kCCDirectorProjectionDefault; - - // projection delegate if "Custom" projection is used - delegate_ = nil; - - // FPS - displayStats_ = NO; - totalFrames_ = frames_ = 0; - - // paused ? - isPaused_ = NO; - - // running thread - runningThread_ = nil; - - // scheduler - scheduler_ = [[CCScheduler alloc] init]; - - // action manager - actionManager_ = [[CCActionManager alloc] init]; - [scheduler_ scheduleUpdateForTarget:actionManager_ priority:kCCActionManagerPriority paused:NO]; - - winSizeInPixels_ = winSizeInPoints_ = CGSizeZero; - } - - return self; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Size: %0.f x %0.f, view = %@>", [self class], self, winSizeInPoints_.width, winSizeInPoints_.height, view_]; -} - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - [FPSLabel_ release]; - [SPFLabel_ release]; - [drawsLabel_ release]; - [runningScene_ release]; - [notificationNode_ release]; - [scenesStack_ release]; - [scheduler_ release]; - [actionManager_ release]; - [delegate_ release]; - - _sharedDirector = nil; - - [super dealloc]; -} - --(void) setGLDefaultValues -{ - // This method SHOULD be called only after view_ was initialized - NSAssert( view_, @"view_ must be initialized"); - - [self setAlphaBlending: YES]; - [self setDepthTest: YES]; - [self setProjection: projection_]; - - // set other opengl default values - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); -} - -// -// Draw the Scene -// -- (void) drawScene -{ - // Override me -} - --(void) calculateDeltaTime -{ - struct timeval now; - - if( gettimeofday( &now, NULL) != 0 ) { - CCLOG(@"cocos2d: error in gettimeofday"); - dt = 0; - return; - } - - // new delta time - if( nextDeltaTimeZero_ ) { - dt = 0; - nextDeltaTimeZero_ = NO; - } else { - dt = (now.tv_sec - lastUpdate_.tv_sec) + (now.tv_usec - lastUpdate_.tv_usec) / 1000000.0f; - dt = MAX(0,dt); - } - -#ifdef DEBUG - // If we are debugging our code, prevent big delta time - if( dt > 0.2f ) - dt = 1/60.0f; -#endif - - lastUpdate_ = now; -} - -#pragma mark Director - Memory Helper - --(void) purgeCachedData -{ - [CCLabelBMFont purgeCachedData]; - [[CCTextureCache sharedTextureCache] removeUnusedTextures]; -} - -#pragma mark Director - Scene OpenGL Helper - --(ccDirectorProjection) projection -{ - return projection_; -} - --(float) getZEye -{ - return ( winSizeInPixels_.height / 1.1566f ); -} - --(void) setProjection:(ccDirectorProjection)projection -{ - CCLOG(@"cocos2d: override me"); -} - -- (void) setAlphaBlending: (BOOL) on -{ - if (on) { - ccGLEnable(CC_GL_BLEND); - ccGLBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); - - } else - glDisable(GL_BLEND); - - CHECK_GL_ERROR_DEBUG(); -} - -- (void) setDepthTest: (BOOL) on -{ - if (on) { - glClearDepth(1.0f); - - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LEQUAL); -// glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); - } else - glDisable( GL_DEPTH_TEST ); - - CHECK_GL_ERROR_DEBUG(); -} - -#pragma mark Director Integration with a UIKit view - --(void) setView:(CCGLView*)view -{ -// NSAssert( view, @"OpenGLView must be non-nil"); - - if( view != view_ ) { - -#ifdef __CC_PLATFORM_IOS - [super setView:view]; -#endif - [view_ release]; - view_ = [view retain]; - - // set size - winSizeInPixels_ = winSizeInPoints_ = CCNSSizeToCGSize( [view_ bounds].size ); - - [self createStatsLabel]; - - // it could be nil - if( view ) - [self setGLDefaultValues]; - - CHECK_GL_ERROR_DEBUG(); - } -} - --(CCGLView*) view -{ - return view_; -} - - -#pragma mark Director Scene Landscape - --(CGPoint)convertToGL:(CGPoint)uiPoint -{ - CCLOG(@"CCDirector#convertToGL: OVERRIDE ME."); - return CGPointZero; -} - --(CGPoint)convertToUI:(CGPoint)glPoint -{ - CCLOG(@"CCDirector#convertToUI: OVERRIDE ME."); - return CGPointZero; -} - --(CGSize)winSize -{ - return winSizeInPoints_; -} - --(CGSize)winSizeInPixels -{ - return winSizeInPixels_; -} - --(void) reshapeProjection:(CGSize)newWindowSize -{ - winSizeInPixels_ = winSizeInPoints_ = newWindowSize; - [self setProjection:projection_]; -} - -#pragma mark Director Scene Management - -- (void)runWithScene:(CCScene*) scene -{ - NSAssert( scene != nil, @"Argument must be non-nil"); - - [self pushScene:scene]; - [self startAnimation]; -} - --(void) replaceScene: (CCScene*) scene -{ - NSAssert( scene != nil, @"Argument must be non-nil"); - - NSUInteger index = [scenesStack_ count]; - - sendCleanupToScene_ = YES; - [scenesStack_ replaceObjectAtIndex:index-1 withObject:scene]; - nextScene_ = scene; // nextScene_ is a weak ref -} - -- (void) pushScene: (CCScene*) scene -{ - NSAssert( scene != nil, @"Argument must be non-nil"); - - sendCleanupToScene_ = NO; - - [scenesStack_ addObject: scene]; - nextScene_ = scene; // nextScene_ is a weak ref -} - --(void) popScene -{ - NSAssert( runningScene_ != nil, @"A running Scene is needed"); - - [scenesStack_ removeLastObject]; - NSUInteger c = [scenesStack_ count]; - - if( c == 0 ) - [self end]; - else { - sendCleanupToScene_ = YES; - nextScene_ = [scenesStack_ objectAtIndex:c-1]; - } -} - --(void) end -{ - [runningScene_ onExit]; - [runningScene_ cleanup]; - [runningScene_ release]; - - runningScene_ = nil; - nextScene_ = nil; - - // remove all objects, but don't release it. - // runWithScene might be executed after 'end'. - [scenesStack_ removeAllObjects]; - - [self stopAnimation]; - - [FPSLabel_ release]; - [SPFLabel_ release]; - [drawsLabel_ release]; - FPSLabel_ = nil, SPFLabel_=nil, drawsLabel_=nil; - - [delegate_ release]; - delegate_ = nil; - - [self setView:nil]; - - // Purge bitmap cache - [CCLabelBMFont purgeCachedData]; - - // Purge all managers / caches - [CCAnimationCache purgeSharedAnimationCache]; - [CCSpriteFrameCache purgeSharedSpriteFrameCache]; - [CCTextureCache purgeSharedTextureCache]; - [CCShaderCache purgeSharedShaderCache]; - - // OpenGL view - - // Since the director doesn't attach the openglview to the window - // it shouldn't remove it from the window too. -// [openGLView_ removeFromSuperview]; - - - // Invalidate GL state cache - ccGLInvalidateStateCache(); - - CHECK_GL_ERROR(); -} - --(void) setNextScene -{ - Class transClass = [CCTransitionScene class]; - BOOL runningIsTransition = [runningScene_ isKindOfClass:transClass]; - BOOL newIsTransition = [nextScene_ isKindOfClass:transClass]; - - // If it is not a transition, call onExit/cleanup - if( ! newIsTransition ) { - [runningScene_ onExit]; - - // issue #709. the root node (scene) should receive the cleanup message too - // otherwise it might be leaked. - if( sendCleanupToScene_) - [runningScene_ cleanup]; - } - - [runningScene_ release]; - - runningScene_ = [nextScene_ retain]; - nextScene_ = nil; - - if( ! runningIsTransition ) { - [runningScene_ onEnter]; - [runningScene_ onEnterTransitionDidFinish]; - } -} - --(void) pause -{ - if( isPaused_ ) - return; - - oldAnimationInterval_ = animationInterval_; - - // when paused, don't consume CPU - [self setAnimationInterval:1/4.0]; - - [self willChangeValueForKey:@"isPaused"]; - isPaused_ = YES; - [self didChangeValueForKey:@"isPaused"]; -} - --(void) resume -{ - if( ! isPaused_ ) - return; - - [self setAnimationInterval: oldAnimationInterval_]; - - if( gettimeofday( &lastUpdate_, NULL) != 0 ) { - CCLOG(@"cocos2d: Director: Error in gettimeofday"); - } - - [self willChangeValueForKey:@"isPaused"]; - isPaused_ = NO; - [self didChangeValueForKey:@"isPaused"]; - - dt = 0; -} - -- (void)startAnimation -{ - CCLOG(@"cocos2d: Director#startAnimation. Override me"); -} - -- (void)stopAnimation -{ - CCLOG(@"cocos2d: Director#stopAnimation. Override me"); -} - -- (void)setAnimationInterval:(NSTimeInterval)interval -{ - CCLOG(@"cocos2d: Director#setAnimationInterval. Override me"); -} - - -// display statistics --(void) showStats -{ - frames_++; - accumDt_ += dt; - - if( displayStats_ ) { - // Ms per Frame - - if( accumDt_ > CC_DIRECTOR_STATS_INTERVAL) - { - NSString *spfstr = [[NSString alloc] initWithFormat:@"%.3f", secondsPerFrame_]; - [SPFLabel_ setString:spfstr]; - [spfstr release]; - - frameRate_ = frames_/accumDt_; - frames_ = 0; - accumDt_ = 0; - -// sprintf(format,"%.1f",frameRate); -// [FPSLabel setCString:format]; - - NSString *fpsstr = [[NSString alloc] initWithFormat:@"%.1f", frameRate_]; - [FPSLabel_ setString:fpsstr]; - [fpsstr release]; - - NSString *draws = [[NSString alloc] initWithFormat:@"%4d", __ccNumberOfDraws]; - [drawsLabel_ setString:draws]; - [draws release]; - } - - [drawsLabel_ visit]; - [FPSLabel_ visit]; - [SPFLabel_ visit]; - } - - __ccNumberOfDraws = 0; -} - --(void) calculateMPF -{ - struct timeval now; - gettimeofday( &now, NULL); - - secondsPerFrame_ = (now.tv_sec - lastUpdate_.tv_sec) + (now.tv_usec - lastUpdate_.tv_usec) / 1000000.0f; -} - -#pragma mark Director - Helper - --(void) createStatsLabel -{ - if( FPSLabel_ && SPFLabel_ ) { - CCTexture2D *texture = [FPSLabel_ texture]; - - [FPSLabel_ release]; - [SPFLabel_ release]; - [[CCTextureCache sharedTextureCache ] removeTexture:texture]; - FPSLabel_ = nil; - SPFLabel_ = nil; - } - - CCTexture2DPixelFormat currentFormat = [CCTexture2D defaultAlphaPixelFormat]; - [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA4444]; - FPSLabel_ = [[CCLabelAtlas alloc] initWithString:@"00.0" charMapFile:@"fps_images.png" itemWidth:12 itemHeight:32 startCharMap:'.']; - SPFLabel_ = [[CCLabelAtlas alloc] initWithString:@"0.000" charMapFile:@"fps_images.png" itemWidth:12 itemHeight:32 startCharMap:'.']; - drawsLabel_ = [[CCLabelAtlas alloc] initWithString:@"000" charMapFile:@"fps_images.png" itemWidth:12 itemHeight:32 startCharMap:'.']; - - [CCTexture2D setDefaultAlphaPixelFormat:currentFormat]; - - [drawsLabel_ setPosition: ccpAdd( ccp(0,34), CC_DIRECTOR_STATS_POSITION ) ]; - [SPFLabel_ setPosition: ccpAdd( ccp(0,17), CC_DIRECTOR_STATS_POSITION ) ]; - [FPSLabel_ setPosition: CC_DIRECTOR_STATS_POSITION ]; -} - -@end - diff --git a/Example/libs/cocos2d/CCDrawingPrimitives.h b/Example/libs/cocos2d/CCDrawingPrimitives.h deleted file mode 100644 index 2be4042..0000000 --- a/Example/libs/cocos2d/CCDrawingPrimitives.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -#ifndef __CC_DRAWING_PRIMITIVES_H -#define __CC_DRAWING_PRIMITIVES_H - -#import - -#import "ccTypes.h" -#import "ccMacros.h" - -#ifdef __CC_PLATFORM_IOS -#import // for CGPoint -#endif - - -#ifdef __cplusplus -extern "C" { -#endif - -/** - @file - Drawing OpenGL ES primitives. - - ccDrawPoint - - ccDrawLine - - ccDrawPoly - - ccDrawCircle - - ccDrawQuadBezier - - ccDrawCubicBezier - - You can change the color, width and other property by calling the - glColor4ub(), glLineWidth(), glPointSize(). - - @warning These functions draws the Line, Point, Polygon, immediately. They aren't batched. If you are going to make a game that depends on these primitives, I suggest creating a batch. - */ - - -/** draws a point given x and y coordinate measured in points. */ -void ccDrawPoint( CGPoint point ); - -/** draws an array of points. - @since v0.7.2 - */ -void ccDrawPoints( const CGPoint *points, NSUInteger numberOfPoints ); - -/** draws a line given the origin and destination point measured in points. */ -void ccDrawLine( CGPoint origin, CGPoint destination ); - -/** draws a poligon given a pointer to CGPoint coordiantes and the number of vertices measured in points. - The polygon can be closed or open - */ -void ccDrawPoly( const CGPoint *vertices, NSUInteger numOfVertices, BOOL closePolygon ); - -/** draws a filled polygon given a pointer to CGPoint coordiantes, the number of vertices measured in points, and a color. - */ -void ccDrawFilledPoly( const CGPoint *poli, NSUInteger numberOfPoints, ccColor4F color ); - -/** draws a circle given the center, radius and number of segments measured in points */ -void ccDrawCircle( CGPoint center, float radius, float angle, NSUInteger segments, BOOL drawLineToCenter); - -/** draws a quad bezier path measured in points. - @since v0.8 - */ -void ccDrawQuadBezier(CGPoint origin, CGPoint control, CGPoint destination, NSUInteger segments); - -/** draws a cubic bezier path measured in points. - @since v0.8 - */ -void ccDrawCubicBezier(CGPoint origin, CGPoint control1, CGPoint control2, CGPoint destination, NSUInteger segments); - -/** set the drawing color with 4 unsigned bytes - @since v2.0 - */ -void ccDrawColor4B( GLubyte r, GLubyte g, GLubyte b, GLubyte a ); - -/** set the drawing color with 4 floats - @since v2.0 - */ -void ccDrawColor4F( GLfloat r, GLfloat g, GLfloat b, GLfloat a ); - -/** set the point size in points. Default 1. - @since v2.0 - */ -void ccPointSize( GLfloat pointSize ); - - -#ifdef __cplusplus -} -#endif - -#endif // __CC_DRAWING_PRIMITIVES_H diff --git a/Example/libs/cocos2d/CCDrawingPrimitives.m b/Example/libs/cocos2d/CCDrawingPrimitives.m deleted file mode 100644 index 5f70223..0000000 --- a/Example/libs/cocos2d/CCDrawingPrimitives.m +++ /dev/null @@ -1,311 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import -#import -#import - -#import "CCDrawingPrimitives.h" -#import "ccMacros.h" -#import "Platforms/CCGL.h" -#import "ccGLStateCache.h" -#import "CCShaderCache.h" -#import "CCGLProgram.h" -#import "Support/OpenGL_Internal.h" - - -static BOOL initialized = NO; -static CCGLProgram *shader_ = nil; -static int colorLocation_ = -1; -static ccColor4F color_ = {1,1,1,1}; -static int pointSizeLocation_ = -1; -static GLfloat pointSize_ = 1; - -static void lazy_init( void ) -{ - if( ! initialized ) { - - // - // Position and 1 color passed as a uniform (to similate glColor4ub ) - // - shader_ = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_Position_uColor]; - - colorLocation_ = glGetUniformLocation( shader_->program_, "u_color"); - pointSizeLocation_ = glGetUniformLocation( shader_->program_, "u_pointSize"); - - initialized = YES; - } - -} - -void ccDrawPoint( CGPoint point ) -{ - lazy_init(); - - ccVertex2F p = (ccVertex2F) {point.x, point.y}; - - ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position ); - - [shader_ use]; - [shader_ setUniformForModelViewProjectionMatrix]; - - [shader_ setUniformLocation:colorLocation_ with4fv:(GLfloat*) &color_.r count:1]; - [shader_ setUniformLocation:pointSizeLocation_ withF1:pointSize_]; - - glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, &p); - - glDrawArrays(GL_POINTS, 0, 1); - - CC_INCREMENT_GL_DRAWS(1); -} - -void ccDrawPoints( const CGPoint *points, NSUInteger numberOfPoints ) -{ - lazy_init(); - - ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position ); - - [shader_ use]; - [shader_ setUniformForModelViewProjectionMatrix]; - [shader_ setUniformLocation:colorLocation_ with4fv:(GLfloat*) &color_.r count:1]; - [shader_ setUniformLocation:pointSizeLocation_ withF1:pointSize_]; - - // XXX: Mac OpenGL error. arrays can't go out of scope before draw is executed - ccVertex2F newPoints[numberOfPoints]; - - // iPhone and 32-bit machines optimization - if( sizeof(CGPoint) == sizeof(ccVertex2F) ) - glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, points); - - else - { - // Mac on 64-bit - for( NSUInteger i=0; i -#import "ccMacros.h" - -#ifdef __CC_PLATFORM_IOS -#import -#import -#elif defined(__CC_PLATFORM_MAC) -#import -#endif // __CC_PLATFORM_MAC - -enum { - kCCVertexAttrib_Position, - kCCVertexAttrib_Color, - kCCVertexAttrib_TexCoords, - - kCCVertexAttrib_MAX, -}; - -enum { - kCCUniformMVPMatrix, - kCCUniformSampler, - - kCCUniform_MAX, -}; - -#define kCCShader_PositionTextureColor @"ShaderPositionTextureColor" -#define kCCShader_PositionTextureColorAlphaTest @"ShaderPositionTextureColorAlphaTest" -#define kCCShader_PositionColor @"ShaderPositionColor" -#define kCCShader_PositionTexture @"ShaderPositionTexture" -#define kCCShader_PositionTexture_uColor @"ShaderPositionTexture_uColor" -#define kCCShader_PositionTextureA8Color @"ShaderPositionTextureA8Color" -#define kCCShader_Position_uColor @"ShaderPosition_uColor" - -// uniform names -#define kCCUniformMVPMatrix_s "u_MVPMatrix" -#define kCCUniformSampler_s "u_texture" -#define kCCUniformAlphaTestValue "u_alpha_value" - -// Attribute names -#define kCCAttributeNameColor @"a_color" -#define kCCAttributeNamePosition @"a_position" -#define kCCAttributeNameTexCoord @"a_texCoord" - - -struct _hashUniformEntry; - -/** CCGLProgram - Class that implements a glProgram - - - @since v2.0.0 - */ -@interface CCGLProgram : NSObject -{ - struct _hashUniformEntry *hashForUniforms_; - -@public - GLuint program_, - vertShader_, - fragShader_; - - GLint uniforms_[kCCUniform_MAX]; -} - -/** Initializes the CCGLProgram with a vertex and fragment with bytes array */ -- (id)initWithVertexShaderByteArray:(const GLchar*)vShaderByteArray fragmentShaderByteArray:(const GLchar*)fShaderByteArray; - -/** Initializes the CCGLProgram with a vertex and fragment with contents of filenames */ -- (id)initWithVertexShaderFilename:(NSString *)vShaderFilename fragmentShaderFilename:(NSString *)fShaderFilename; - -/** It will add a new attribute to the shader */ -- (void)addAttribute:(NSString *)attributeName index:(GLuint)index; - -/** links the glProgram */ -- (BOOL)link; - -/** it will call glUseProgram() */ -- (void)use; - -/** It will create 3 uniforms: - - kCCUniformPMatrix - - kCCUniformMVMatrix - - kCCUniformSampler - - And it will bind "kCCUniformSampler" to 0 - */ -- (void) updateUniforms; - -/** calls glUniform1i only if the values are different than the previous call for this same shader program. */ --(void) setUniformLocation:(NSUInteger)location withI1:(GLint)i1; - -/** calls glUniform1f only if the values are different than the previous call for this same shader program. */ --(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1; - -/** calls glUniform2f only if the values are different than the previous call for this same shader program. */ --(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2; - -/** calls glUniform3f only if the values are different than the previous call for this same shader program. */ --(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 f3:(GLfloat)f3; - -/** calls glUniform4f only if the values are different than the previous call for this same shader program. */ --(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 f3:(GLfloat)f3 f4:(GLfloat)f4; - -/** calls glUniform2fv only if the values are different than the previous call for this same shader program. */ --(void) setUniformLocation:(NSUInteger)location with2fv:(GLfloat*)floats count:(NSUInteger)numberOfArrays; - -/** calls glUniform3fv only if the values are different than the previous call for this same shader program. */ --(void) setUniformLocation:(NSUInteger)location with3fv:(GLfloat*)floats count:(NSUInteger)numberOfArrays; - -/** calls glUniform4fv only if the values are different than the previous call for this same shader program. */ --(void) setUniformLocation:(NSUInteger)location with4fv:(GLvoid*)floats count:(NSUInteger)numberOfArrays; - -/** calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. */ --(void) setUniformLocation:(NSUInteger)location withMatrix4fv:(GLvoid*)matrix_array count:(NSUInteger)numberOfMatrix; - -/** will update the MVP matrix on the MVP uniform if it is different than the previous call for this same shader program. */ --(void) setUniformForModelViewProjectionMatrix; - -/** returns the vertexShader error log */ -- (NSString *)vertexShaderLog; - -/** returns the fragmentShader error log */ -- (NSString *)fragmentShaderLog; - -/** returns the program error log */ -- (NSString *)programLog; -@end diff --git a/Example/libs/cocos2d/CCGLProgram.m b/Example/libs/cocos2d/CCGLProgram.m deleted file mode 100644 index 6602945..0000000 --- a/Example/libs/cocos2d/CCGLProgram.m +++ /dev/null @@ -1,395 +0,0 @@ -// -// Copyright 2011 Jeff Lamarche -// -// Copyright 2012 Goffredo Marocchi -// -// Copyright 2012 Ricardo Quesada -// -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided -// that the following conditions are met: -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and -// the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions -// and the following disclaimer in the documentation and/or other materials provided with the -// distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT -// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -#import "CCGLProgram.h" -#import "ccGLStateCache.h" -#import "ccMacros.h" -#import "Support/CCFileUtils.h" -#import "Support/uthash.h" -#import "Support/OpenGL_Internal.h" - -// extern -#import "kazmath/GL/matrix.h" -#import "kazmath/kazmath.h" - - -typedef struct _hashUniformEntry -{ - GLvoid *value; // value - NSUInteger location; // Key - UT_hash_handle hh; // hash entry -} tHashUniformEntry; - - -#pragma mark Function Pointer Definitions -typedef void (*GLInfoFunction)(GLuint program, - GLenum pname, - GLint* params); -typedef void (*GLLogFunction) (GLuint program, - GLsizei bufsize, - GLsizei* length, - GLchar* infolog); -#pragma mark - -#pragma mark Private Extension Method Declaration - -@interface CCGLProgram() -- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type byteArray:(const GLchar*)byteArray; - -- (NSString *)logForOpenGLObject:(GLuint)object infoCallback:(GLInfoFunction)infoFunc logFunc:(GLLogFunction)logFunc; -@end - -#pragma mark - - -@implementation CCGLProgram -- (id)initWithVertexShaderByteArray:(const GLchar *)vShaderByteArray fragmentShaderByteArray:(const GLchar *)fShaderByteArray -{ - if ((self = [super init]) ) - { - program_ = glCreateProgram(); - - vertShader_ = fragShader_ = 0; - - if( vShaderByteArray ) { - - if (![self compileShader:&vertShader_ - type:GL_VERTEX_SHADER - byteArray:vShaderByteArray] ) - CCLOG(@"cocos2d: ERROR: Failed to compile vertex shader"); - } - - // Create and compile fragment shader - if( fShaderByteArray ) { - if (![self compileShader:&fragShader_ - type:GL_FRAGMENT_SHADER - byteArray:fShaderByteArray] ) - - CCLOG(@"cocos2d: ERROR: Failed to compile fragment shader"); - } - - if( vertShader_ ) - glAttachShader(program_, vertShader_); - - if( fragShader_ ) - glAttachShader(program_, fragShader_); - - hashForUniforms_ = NULL; - } - - return self; -} - -- (id)initWithVertexShaderFilename:(NSString *)vShaderFilename fragmentShaderFilename:(NSString *)fShaderFilename -{ - - const GLchar * vertexSource = (GLchar*) [[NSString stringWithContentsOfFile:[CCFileUtils fullPathFromRelativePath:vShaderFilename] encoding:NSUTF8StringEncoding error:nil] UTF8String]; - const GLchar * fragmentSource = (GLchar*) [[NSString stringWithContentsOfFile:[CCFileUtils fullPathFromRelativePath:fShaderFilename] encoding:NSUTF8StringEncoding error:nil] UTF8String]; - - return [self initWithVertexShaderByteArray:vertexSource fragmentShaderByteArray:fragmentSource]; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Program = %i, VertexShader = %i, FragmentShader = %i>", [self class], self, program_, vertShader_, fragShader_]; -} - - -- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type byteArray:(const GLchar *)source -{ - GLint status; - - if (!source) - return NO; - - *shader = glCreateShader(type); - glShaderSource(*shader, 1, &source, NULL); - glCompileShader(*shader); - - glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); - - if( ! status ) { - if( type == GL_VERTEX_SHADER ) - CCLOG(@"cocos2d: %@", [self vertexShaderLog] ); - else - CCLOG(@"cocos2d: %@", [self fragmentShaderLog] ); - - } - return ( status == GL_TRUE ); -} - -#pragma mark - - -- (void)addAttribute:(NSString *)attributeName index:(GLuint)index -{ - glBindAttribLocation(program_, - index, - [attributeName UTF8String]); -} - --(void) updateUniforms -{ - // Since sample most probably won't change, set it to 0 now. - - uniforms_[kCCUniformMVPMatrix] = glGetUniformLocation(program_, kCCUniformMVPMatrix_s); - - uniforms_[kCCUniformSampler] = glGetUniformLocation(program_, kCCUniformSampler_s); - - [self use]; - - [self setUniformLocation:uniforms_[kCCUniformSampler] withI1:0]; -} - -#pragma mark - - -- (BOOL)link -{ - glLinkProgram(program_); - -#if DEBUG - GLint status; - glValidateProgram(program_); - - glGetProgramiv(program_, GL_LINK_STATUS, &status); - if (status == GL_FALSE) { - CCLOG(@"cocos2d: ERROR: Failed to link program: %i", program_); - if( vertShader_ ) - glDeleteShader( vertShader_ ); - if( fragShader_ ) - glDeleteShader( fragShader_ ); - ccGLDeleteProgram( program_ ); - vertShader_ = fragShader_ = program_ = 0; - return NO; - } -#endif - - if (vertShader_) - glDeleteShader(vertShader_); - if (fragShader_) - glDeleteShader(fragShader_); - - vertShader_ = fragShader_ = 0; - - return YES; -} - -- (void)use -{ - ccGLUseProgram(program_); -} - -#pragma mark - - -- (NSString *)logForOpenGLObject:(GLuint)object - infoCallback:(GLInfoFunction)infoFunc - logFunc:(GLLogFunction)logFunc -{ - GLint logLength = 0, charsWritten = 0; - - infoFunc(object, GL_INFO_LOG_LENGTH, &logLength); - if (logLength < 1) - return nil; - - char *logBytes = malloc(logLength); - logFunc(object, logLength, &charsWritten, logBytes); - NSString *log = [[[NSString alloc] initWithBytes:logBytes - length:logLength - encoding:NSUTF8StringEncoding] - autorelease]; - free(logBytes); - return log; -} - -- (NSString *)vertexShaderLog -{ - return [self logForOpenGLObject:vertShader_ - infoCallback:(GLInfoFunction)&glGetShaderiv - logFunc:(GLLogFunction)&glGetShaderInfoLog]; - -} - -- (NSString *)fragmentShaderLog -{ - return [self logForOpenGLObject:fragShader_ - infoCallback:(GLInfoFunction)&glGetShaderiv - logFunc:(GLLogFunction)&glGetShaderInfoLog]; -} - -- (NSString *)programLog -{ - return [self logForOpenGLObject:program_ - infoCallback:(GLInfoFunction)&glGetProgramiv - logFunc:(GLLogFunction)&glGetProgramInfoLog]; -} - -#pragma mark - Uniform cache - --(BOOL) updateUniformLocation:(NSUInteger)location withData:(GLvoid*)data sizeOfData:(NSUInteger)bytes -{ - BOOL updated = YES; - tHashUniformEntry *element = NULL; - HASH_FIND_INT(hashForUniforms_, &location, element); - - if( ! element ) { - - element = malloc( sizeof(*element) ); - - // key - element->location = location; - - // value - element->value = malloc( bytes ); - memcpy(element->value, data, bytes ); - - HASH_ADD_INT(hashForUniforms_, location, element); - } - else - { - if( memcmp( element->value, data, bytes) == 0 ) - updated = NO; - else - memcpy( element->value, data, bytes ); - } - - return updated; -} - --(void) setUniformLocation:(NSUInteger)location withI1:(GLint)i1 -{ - BOOL updated = [self updateUniformLocation:location withData:&i1 sizeOfData:sizeof(i1)*1]; - - if( updated ) - glUniform1i( (GLint)location, i1); -} - --(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 -{ - BOOL updated = [self updateUniformLocation:location withData:&f1 sizeOfData:sizeof(f1)*1]; - - if( updated ) - glUniform1f( (GLint)location, f1); -} - --(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 -{ - GLfloat floats[2] = {f1,f2}; - BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(floats)]; - - if( updated ) - glUniform2f( (GLint)location, f1, f2); -} - --(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 f3:(GLfloat)f3 -{ - GLfloat floats[3] = {f1,f2,f3}; - BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(floats)]; - - if( updated ) - glUniform3f( (GLint)location, f1, f2, f3); -} - --(void) setUniformLocation:(NSUInteger)location withF1:(GLfloat)f1 f2:(GLfloat)f2 f3:(GLfloat)f3 f4:(GLfloat)f4 -{ - GLfloat floats[4] = {f1,f2,f3,f4}; - BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(floats)]; - - if( updated ) - glUniform4f( (GLint)location, f1, f2, f3,f4); -} - --(void) setUniformLocation:(NSUInteger)location with2fv:(GLfloat*)floats count:(NSUInteger)numberOfArrays -{ - BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(float)*2*numberOfArrays]; - - if( updated ) - glUniform2fv( (GLint)location, (GLsizei)numberOfArrays, floats ); -} - --(void) setUniformLocation:(NSUInteger)location with3fv:(GLfloat*)floats count:(NSUInteger)numberOfArrays -{ - BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(float)*3*numberOfArrays]; - - if( updated ) - glUniform3fv( (GLint)location, (GLsizei)numberOfArrays, floats ); -} - --(void) setUniformLocation:(NSUInteger)location with4fv:(GLvoid*)floats count:(NSUInteger)numberOfArrays -{ - BOOL updated = [self updateUniformLocation:location withData:floats sizeOfData:sizeof(float)*4*numberOfArrays]; - - if( updated ) - glUniform4fv( (GLint)location, (GLsizei)numberOfArrays, floats ); -} - - --(void) setUniformLocation:(NSUInteger)location withMatrix4fv:(GLvoid*)matrixArray count:(NSUInteger)numberOfMatrices -{ - BOOL updated = [self updateUniformLocation:location withData:matrixArray sizeOfData:sizeof(float)*16*numberOfMatrices]; - - if( updated ) - glUniformMatrix4fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray); -} - --(void) setUniformForModelViewProjectionMatrix -{ - kmMat4 matrixP; - kmMat4 matrixMV; - kmMat4 matrixMVP; - - kmGLGetMatrix(KM_GL_PROJECTION, &matrixP ); - kmGLGetMatrix(KM_GL_MODELVIEW, &matrixMV ); - - kmMat4Multiply(&matrixMVP, &matrixP, &matrixMV); - - [self setUniformLocation:uniforms_[kCCUniformMVPMatrix] withMatrix4fv:matrixMVP.mat count:1]; -} - - -#pragma mark - - -- (void)dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@", self); - - // there is no need to delete the shaders. They should have been already deleted. - NSAssert( vertShader_ == 0, @"Vertex Shaders should have been already deleted"); - NSAssert( fragShader_ == 0, @"Vertex Shaders should have been already deleted"); - - if (program_) - ccGLDeleteProgram(program_); - - tHashUniformEntry *current_element, *tmp; - - // Purge uniform hash - HASH_ITER(hh, hashForUniforms_, current_element, tmp) { - HASH_DEL(hashForUniforms_, current_element); - free(current_element->value); - free(current_element); - } - - [super dealloc]; -} -@end diff --git a/Example/libs/cocos2d/CCGrabber.h b/Example/libs/cocos2d/CCGrabber.h deleted file mode 100644 index 5b086c6..0000000 --- a/Example/libs/cocos2d/CCGrabber.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "Platforms/CCGL.h" -#import - -@class CCTexture2D; - -/** FBO class that grabs the the contents of the screen */ -@interface CCGrabber : NSObject -{ - GLuint fbo_; - GLint oldFBO_; - GLfloat oldClearColor_[4]; -} - --(void)grab:(CCTexture2D*)texture; --(void)beforeRender:(CCTexture2D*)texture; --(void)afterRender:(CCTexture2D*)texture; - -@end diff --git a/Example/libs/cocos2d/CCGrabber.m b/Example/libs/cocos2d/CCGrabber.m deleted file mode 100644 index 5b12542..0000000 --- a/Example/libs/cocos2d/CCGrabber.m +++ /dev/null @@ -1,99 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "Platforms/CCGL.h" -#import "CCGrabber.h" -#import "ccMacros.h" -#import "CCTexture2D.h" -#import "Support/OpenGL_Internal.h" - -@implementation CCGrabber - --(id) init -{ - if(( self = [super init] )) { - // generate FBO - glGenFramebuffers(1, &fbo_); - } - return self; -} - --(void)grab:(CCTexture2D*)texture -{ - glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFBO_); - - // bind - glBindFramebuffer(GL_FRAMEBUFFER, fbo_); - - // associate texture with FBO - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture.name, 0); - - // check if it worked (probably worth doing :) ) - GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - if (status != GL_FRAMEBUFFER_COMPLETE) - [NSException raise:@"Frame Grabber" format:@"Could not attach texture to framebuffer"]; - - glBindFramebuffer(GL_FRAMEBUFFER, oldFBO_); -} - --(void)beforeRender:(CCTexture2D*)texture -{ - glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFBO_); - glBindFramebuffer(GL_FRAMEBUFFER, fbo_); - - // save clear color - glGetFloatv(GL_COLOR_CLEAR_VALUE,oldClearColor_); - - // BUG XXX: doesn't work with RGB565. - glClearColor(0,0,0,0); - - // BUG #631: To fix #631, uncomment the lines with #631 - // Warning: But it CCGrabber won't work with 2 effects at the same time -// glClearColor(0.0f,0.0f,0.0f,1.0f); // #631 - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - -// glColorMask(TRUE, TRUE, TRUE, FALSE); // #631 - -} - --(void)afterRender:(CCTexture2D*)texture -{ - glBindFramebuffer(GL_FRAMEBUFFER, oldFBO_); -// glColorMask(TRUE, TRUE, TRUE, TRUE); // #631 - - // Restore clear color - glClearColor( oldClearColor_[0], oldClearColor_[1], oldClearColor_[2], oldClearColor_[3] ); -} - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - glDeleteFramebuffers(1, &fbo_); - [super dealloc]; -} - -@end diff --git a/Example/libs/cocos2d/CCGrid.h b/Example/libs/cocos2d/CCGrid.h deleted file mode 100644 index df8fa34..0000000 --- a/Example/libs/cocos2d/CCGrid.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import - -#import "CCNode.h" -#import "CCCamera.h" -#import "ccTypes.h" -#import "CCDirector.h" -#import "kazmath/mat4.h" - -@class CCTexture2D; -@class CCGrabber; -@class CCGLProgram; - -/** Base class for other - */ -@interface CCGridBase : NSObject -{ - BOOL active_; - int reuseGrid_; - ccGridSize gridSize_; - CCTexture2D *texture_; - CGPoint step_; - CCGrabber *grabber_; - BOOL isTextureFlipped_; - - CCGLProgram *shaderProgram_; - - ccDirectorProjection directorProjection_; -} - -/** wheter or not the grid is active */ -@property (nonatomic,readwrite) BOOL active; -/** number of times that the grid will be reused */ -@property (nonatomic,readwrite) int reuseGrid; -/** size of the grid */ -@property (nonatomic,readonly) ccGridSize gridSize; -/** pixels between the grids */ -@property (nonatomic,readwrite) CGPoint step; -/** texture used */ -@property (nonatomic, retain) CCTexture2D *texture; -/** grabber used */ -@property (nonatomic, retain) CCGrabber *grabber; -/** is texture flipped */ -@property (nonatomic, readwrite) BOOL isTextureFlipped; -/** shader program */ -@property (nonatomic, readwrite, assign) CCGLProgram *shaderProgram; - -+(id) gridWithSize:(ccGridSize)gridSize texture:(CCTexture2D*)texture flippedTexture:(BOOL)flipped; -+(id) gridWithSize:(ccGridSize)gridSize; - --(id) initWithSize:(ccGridSize)gridSize texture:(CCTexture2D*)texture flippedTexture:(BOOL)flipped; --(id)initWithSize:(ccGridSize)gridSize; --(void)beforeDraw; --(void)afterDraw:(CCNode*)target; --(void)blit; --(void)reuse; - --(void)calculateVertexPoints; - -@end - -//////////////////////////////////////////////////////////// - -/** - CCGrid3D is a 3D grid implementation. Each vertex has 3 dimensions: x,y,z - */ -@interface CCGrid3D : CCGridBase -{ - GLvoid *texCoordinates; - GLvoid *vertices; - GLvoid *originalVertices; - GLushort *indices; -} - -/** returns the vertex at a given position */ --(ccVertex3F)vertex:(ccGridSize)pos; -/** returns the original (non-transformed) vertex at a given position */ --(ccVertex3F)originalVertex:(ccGridSize)pos; -/** sets a new vertex at a given position */ --(void)setVertex:(ccGridSize)pos vertex:(ccVertex3F)vertex; - -@end - -//////////////////////////////////////////////////////////// - -/** - CCTiledGrid3D is a 3D grid implementation. It differs from Grid3D in that - the tiles can be separated from the grid. -*/ -@interface CCTiledGrid3D : CCGridBase -{ - GLvoid *texCoordinates; - GLvoid *vertices; - GLvoid *originalVertices; - GLushort *indices; -} - -/** returns the tile at the given position */ --(ccQuad3)tile:(ccGridSize)pos; -/** returns the original tile (untransformed) at the given position */ --(ccQuad3)originalTile:(ccGridSize)pos; -/** sets a new tile */ --(void)setTile:(ccGridSize)pos coords:(ccQuad3)coords; - -@end diff --git a/Example/libs/cocos2d/CCGrid.m b/Example/libs/cocos2d/CCGrid.m deleted file mode 100644 index d3abb88..0000000 --- a/Example/libs/cocos2d/CCGrid.m +++ /dev/null @@ -1,572 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 On-Core - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "ccMacros.h" -#import "CCGrid.h" -#import "CCTexture2D.h" -#import "CCDirector.h" -#import "CCGrabber.h" -#import "CCGLProgram.h" -#import "CCShaderCache.h" -#import "ccGLStateCache.h" - -#import "Platforms/CCGL.h" -#import "Support/CGPointExtension.h" -#import "Support/ccUtils.h" -#import "Support/TransformUtils.h" -#import "Support/OpenGL_Internal.h" - -#import "kazmath/kazmath.h" -#import "kazmath/GL/matrix.h" - -#ifdef __CC_PLATFORM_IOS -#import "Platforms/iOS/CCDirectorIOS.h" -#endif // __CC_PLATFORM_IOS - -#pragma mark - -#pragma mark CCGridBase - -@implementation CCGridBase - -@synthesize reuseGrid = reuseGrid_; -@synthesize texture = texture_; -@synthesize grabber = grabber_; -@synthesize gridSize = gridSize_; -@synthesize step = step_; -@synthesize shaderProgram = shaderProgram_; - -+(id) gridWithSize:(ccGridSize)gridSize texture:(CCTexture2D*)texture flippedTexture:(BOOL)flipped -{ - return [[[self alloc] initWithSize:gridSize texture:texture flippedTexture:flipped] autorelease]; -} - -+(id) gridWithSize:(ccGridSize)gridSize -{ - return [[(CCGridBase*)[self alloc] initWithSize:gridSize] autorelease]; -} - --(id) initWithSize:(ccGridSize)gridSize texture:(CCTexture2D*)texture flippedTexture:(BOOL)flipped -{ - if( (self=[super init]) ) { - - active_ = NO; - reuseGrid_ = 0; - gridSize_ = gridSize; - - self.texture = texture; - isTextureFlipped_ = flipped; - - CGSize texSize = [texture_ contentSize]; - step_.x = texSize.width / gridSize_.x; - step_.y = texSize.height / gridSize_.y; - - grabber_ = [[CCGrabber alloc] init]; - [grabber_ grab:texture_]; - - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTexture]; - - [self calculateVertexPoints]; - } - return self; -} - --(id)initWithSize:(ccGridSize)gSize -{ - CCDirector *director = [CCDirector sharedDirector]; - CGSize s = [director winSizeInPixels]; - - - unsigned long POTWide = ccNextPOT(s.width); - unsigned long POTHigh = ccNextPOT(s.height); - -#ifdef __CC_PLATFORM_IOS - CCGLView *glview = (CCGLView*)[[CCDirector sharedDirector] view]; - NSString *pixelFormat = [glview pixelFormat]; - - CCTexture2DPixelFormat format = [pixelFormat isEqualToString: kEAGLColorFormatRGB565] ? kCCTexture2DPixelFormat_RGB565 : kCCTexture2DPixelFormat_RGBA8888; -#elif defined(__CC_PLATFORM_MAC) - CCTexture2DPixelFormat format = kCCTexture2DPixelFormat_RGBA8888; -#endif - - int bpp = ( format == kCCTexture2DPixelFormat_RGB565 ? 2 : 4 ); - - void *data = calloc((size_t)(POTWide * POTHigh * bpp), 1); - if( ! data ) { - CCLOG(@"cocos2d: CCGrid: not enough memory"); - [self release]; - return nil; - } - - CCTexture2D *texture = [[CCTexture2D alloc] initWithData:data pixelFormat:format pixelsWide:POTWide pixelsHigh:POTHigh contentSize:s]; - free( data ); - - if( ! texture ) { - CCLOG(@"cocos2d: CCGrid: error creating texture"); - [self release]; - return nil; - } - - self = [self initWithSize:gSize texture:texture flippedTexture:NO]; - - [texture release]; - - return self; -} -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Dimensions = %ix%i>", [self class], self, gridSize_.x, gridSize_.y]; -} - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - -// [self setActive: NO]; - - [texture_ release]; - [grabber_ release]; - [super dealloc]; -} - -// properties --(BOOL) active -{ - return active_; -} - --(void) setActive:(BOOL)active -{ - active_ = active; - if( ! active ) { - CCDirector *director = [CCDirector sharedDirector]; - ccDirectorProjection proj = [director projection]; - [director setProjection:proj]; - } -} - --(BOOL) isTextureFlipped -{ - return isTextureFlipped_; -} - --(void) setIsTextureFlipped:(BOOL)flipped -{ - if( isTextureFlipped_ != flipped ) { - isTextureFlipped_ = flipped; - [self calculateVertexPoints]; - } -} - --(void)set2DProjection -{ - CCDirector *director = [CCDirector sharedDirector]; - - CGSize size = [director winSizeInPixels]; - - glViewport(0, 0, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); - kmGLMatrixMode(KM_GL_PROJECTION); - kmGLLoadIdentity(); - - kmMat4 orthoMatrix; - kmMat4OrthographicProjection(&orthoMatrix, 0, size.width * CC_CONTENT_SCALE_FACTOR(), 0, size.height * CC_CONTENT_SCALE_FACTOR(), -1, 1); - kmGLMultMatrix( &orthoMatrix ); - - kmGLMatrixMode(KM_GL_MODELVIEW); - kmGLLoadIdentity(); - - - ccSetProjectionMatrixDirty(); -} - --(void)beforeDraw -{ - // save projection - CCDirector *director = [CCDirector sharedDirector]; - directorProjection_ = [director projection]; - - // 2d projection -// [director setProjection:kCCDirectorProjection2D]; - [self set2DProjection]; - - - [grabber_ beforeRender:texture_]; -} - - --(void)afterDraw:(CCNode *)target -{ - [grabber_ afterRender:texture_]; - - // restore projection - CCDirector *director = [CCDirector sharedDirector]; - [director setProjection: directorProjection_]; - - if( target.camera.dirty ) { - - CGPoint offset = [target anchorPointInPoints]; - - // - // XXX: Camera should be applied in the AnchorPoint - // - kmGLTranslatef(offset.x, offset.y, 0); - [target.camera locate]; - kmGLTranslatef(-offset.x, -offset.y, 0); - } - - ccGLBindTexture2D( texture_.name ); - - [self blit]; -} - - --(void)blit -{ - [NSException raise:@"GridBase" format:@"Abstract class needs implementation"]; -} - --(void)reuse -{ - [NSException raise:@"GridBase" format:@"Abstract class needs implementation"]; -} - --(void)calculateVertexPoints -{ - [NSException raise:@"GridBase" format:@"Abstract class needs implementation"]; -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCGrid3D -@implementation CCGrid3D - --(void)dealloc -{ - free(texCoordinates); - free(vertices); - free(indices); - free(originalVertices); - [super dealloc]; -} - --(void)blit -{ - NSInteger n = gridSize_.x * gridSize_.y; - - ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords ); - [shaderProgram_ use]; - [shaderProgram_ setUniformForModelViewProjectionMatrix]; - - // - // Attributes - // - - // position - glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, vertices); - - // texCoods - glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, texCoordinates); - - glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, indices); - - CC_INCREMENT_GL_DRAWS(1); -} - --(void)calculateVertexPoints -{ - float width = (float)texture_.pixelsWide; - float height = (float)texture_.pixelsHigh; - float imageH = texture_.contentSizeInPixels.height; - - int x, y, i; - - if (vertices) free(vertices); - if (originalVertices) free(originalVertices); - if (texCoordinates) free(texCoordinates); - if (indices) free(indices); - - NSUInteger numOfPoints = (gridSize_.x+1) * (gridSize_.y+1); - - vertices = malloc(numOfPoints * sizeof(ccVertex3F)); - originalVertices = malloc(numOfPoints * sizeof(ccVertex3F)); - texCoordinates = malloc(numOfPoints * sizeof(ccVertex2F)); - indices = malloc( (gridSize_.x * gridSize_.y) * sizeof(GLushort)*6); - - GLfloat *vertArray = (GLfloat*)vertices; - GLfloat *texArray = (GLfloat*)texCoordinates; - GLushort *idxArray = (GLushort *)indices; - - for( x = 0; x < gridSize_.x; x++ ) - { - for( y = 0; y < gridSize_.y; y++ ) - { - NSInteger idx = (y * gridSize_.x) + x; - - GLfloat x1 = x * step_.x; - GLfloat x2 = x1 + step_.x; - GLfloat y1 = y * step_.y; - GLfloat y2 = y1 + step_.y; - - GLushort a = x * (gridSize_.y+1) + y; - GLushort b = (x+1) * (gridSize_.y+1) + y; - GLushort c = (x+1) * (gridSize_.y+1) + (y+1); - GLushort d = x * (gridSize_.y+1) + (y+1); - - GLushort tempidx[6] = { a, b, d, b, c, d }; - - memcpy(&idxArray[6*idx], tempidx, 6*sizeof(GLushort)); - - int l1[4] = { a*3, b*3, c*3, d*3 }; - ccVertex3F e = {x1,y1,0}; - ccVertex3F f = {x2,y1,0}; - ccVertex3F g = {x2,y2,0}; - ccVertex3F h = {x1,y2,0}; - - ccVertex3F l2[4] = { e, f, g, h }; - - int tex1[4] = { a*2, b*2, c*2, d*2 }; - CGPoint tex2[4] = { ccp(x1, y1), ccp(x2, y1), ccp(x2, y2), ccp(x1, y2) }; - - for( i = 0; i < 4; i++ ) - { - vertArray[ l1[i] ] = l2[i].x; - vertArray[ l1[i] + 1 ] = l2[i].y; - vertArray[ l1[i] + 2 ] = l2[i].z; - - texArray[ tex1[i] ] = tex2[i].x / width; - if( isTextureFlipped_ ) - texArray[ tex1[i] + 1 ] = (imageH - tex2[i].y) / height; - else - texArray[ tex1[i] + 1 ] = tex2[i].y / height; - } - } - } - - memcpy(originalVertices, vertices, (gridSize_.x+1)*(gridSize_.y+1)*sizeof(ccVertex3F)); -} - --(ccVertex3F)vertex:(ccGridSize)pos -{ - NSInteger index = (pos.x * (gridSize_.y+1) + pos.y) * 3; - float *vertArray = (float *)vertices; - - ccVertex3F vert = { vertArray[index], vertArray[index+1], vertArray[index+2] }; - - return vert; -} - --(ccVertex3F)originalVertex:(ccGridSize)pos -{ - NSInteger index = (pos.x * (gridSize_.y+1) + pos.y) * 3; - float *vertArray = (float *)originalVertices; - - ccVertex3F vert = { vertArray[index], vertArray[index+1], vertArray[index+2] }; - - return vert; -} - --(void)setVertex:(ccGridSize)pos vertex:(ccVertex3F)vertex -{ - NSInteger index = (pos.x * (gridSize_.y+1) + pos.y) * 3; - float *vertArray = (float *)vertices; - vertArray[index] = vertex.x; - vertArray[index+1] = vertex.y; - vertArray[index+2] = vertex.z; -} - --(void)reuse -{ - if ( reuseGrid_ > 0 ) - { - memcpy(originalVertices, vertices, (gridSize_.x+1)*(gridSize_.y+1)*sizeof(ccVertex3F)); - reuseGrid_--; - } -} - -@end - -//////////////////////////////////////////////////////////// - -#pragma mark - -#pragma mark CCTiledGrid3D - -@implementation CCTiledGrid3D - --(void)dealloc -{ - free(texCoordinates); - free(vertices); - free(indices); - free(originalVertices); - [super dealloc]; -} - --(void)blit -{ - NSInteger n = gridSize_.x * gridSize_.y; - - [shaderProgram_ use]; - [shaderProgram_ setUniformForModelViewProjectionMatrix]; - - - // - // Attributes - // - ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords ); - - // position - glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, vertices); - - // texCoods - glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, texCoordinates); - - glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, indices); - - CC_INCREMENT_GL_DRAWS(1); -} - --(void)calculateVertexPoints -{ - float width = (float)texture_.pixelsWide; - float height = (float)texture_.pixelsHigh; - float imageH = texture_.contentSizeInPixels.height; - - NSInteger numQuads = gridSize_.x * gridSize_.y; - - if (vertices) free(vertices); - if (originalVertices) free(originalVertices); - if (texCoordinates) free(texCoordinates); - if (indices) free(indices); - - vertices = malloc(numQuads*4*sizeof(ccVertex3F)); - originalVertices = malloc(numQuads*4*sizeof(ccVertex3F)); - texCoordinates = malloc(numQuads*4*sizeof(ccVertex2F)); - indices = malloc(numQuads*6*sizeof(GLushort)); - - GLfloat *vertArray = (GLfloat*)vertices; - GLfloat *texArray = (GLfloat*)texCoordinates; - GLushort *idxArray = (GLushort *)indices; - - int x, y; - - for( x = 0; x < gridSize_.x; x++ ) - { - for( y = 0; y < gridSize_.y; y++ ) - { - float x1 = x * step_.x; - float x2 = x1 + step_.x; - float y1 = y * step_.y; - float y2 = y1 + step_.y; - - *vertArray++ = x1; - *vertArray++ = y1; - *vertArray++ = 0; - *vertArray++ = x2; - *vertArray++ = y1; - *vertArray++ = 0; - *vertArray++ = x1; - *vertArray++ = y2; - *vertArray++ = 0; - *vertArray++ = x2; - *vertArray++ = y2; - *vertArray++ = 0; - - float newY1 = y1; - float newY2 = y2; - - if( isTextureFlipped_ ) { - newY1 = imageH - y1; - newY2 = imageH - y2; - } - - *texArray++ = x1 / width; - *texArray++ = newY1 / height; - *texArray++ = x2 / width; - *texArray++ = newY1 / height; - *texArray++ = x1 / width; - *texArray++ = newY2 / height; - *texArray++ = x2 / width; - *texArray++ = newY2 / height; - } - } - - for( x = 0; x < numQuads; x++) - { - idxArray[x*6+0] = x*4+0; - idxArray[x*6+1] = x*4+1; - idxArray[x*6+2] = x*4+2; - - idxArray[x*6+3] = x*4+1; - idxArray[x*6+4] = x*4+2; - idxArray[x*6+5] = x*4+3; - } - - memcpy(originalVertices, vertices, numQuads*12*sizeof(GLfloat)); -} - --(void)setTile:(ccGridSize)pos coords:(ccQuad3)coords -{ - NSInteger idx = (gridSize_.y * pos.x + pos.y) * 4 * 3; - float *vertArray = (float*)vertices; - memcpy(&vertArray[idx], &coords, sizeof(ccQuad3)); -} - --(ccQuad3)originalTile:(ccGridSize)pos -{ - NSInteger idx = (gridSize_.y * pos.x + pos.y) * 4 * 3; - float *vertArray = (float*)originalVertices; - - ccQuad3 ret; - memcpy(&ret, &vertArray[idx], sizeof(ccQuad3)); - - return ret; -} - --(ccQuad3)tile:(ccGridSize)pos -{ - NSInteger idx = (gridSize_.y * pos.x + pos.y) * 4 * 3; - float *vertArray = (float*)vertices; - - ccQuad3 ret; - memcpy(&ret, &vertArray[idx], sizeof(ccQuad3)); - - return ret; -} - --(void)reuse -{ - if ( reuseGrid_ > 0 ) - { - NSInteger numQuads = gridSize_.x * gridSize_.y; - - memcpy(originalVertices, vertices, numQuads*12*sizeof(GLfloat)); - reuseGrid_--; - } -} - -@end diff --git a/Example/libs/cocos2d/CCLabelAtlas.h b/Example/libs/cocos2d/CCLabelAtlas.h deleted file mode 100644 index 63f1c15..0000000 --- a/Example/libs/cocos2d/CCLabelAtlas.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCAtlasNode.h" -#import "CCTextureAtlas.h" - -/** CCLabelAtlas is a subclass of CCAtlasNode. - - It can be as a replacement of CCLabel since it is MUCH faster. - - CCLabelAtlas versus CCLabel: - - CCLabelAtlas is MUCH faster than CCLabel - - CCLabelAtlas "characters" have a fixed height and width - - CCLabelAtlas "characters" can be anything you want since they are taken from an image file - - A more flexible class is CCLabelBMFont. It supports variable width characters and it also has a nice editor. - */ -@interface CCLabelAtlas : CCAtlasNode -{ - // string to render - NSString *string_; - - // the first char in the charmap - unsigned char mapStartChar_; -} - - -/** creates the CCLabelAtlas with a string, a char map file(the atlas), the width and height of each element in points and the starting char of the atlas */ -+(id) labelWithString:(NSString*) string charMapFile: (NSString*) charmapfile itemWidth:(NSUInteger)w itemHeight:(NSUInteger)h startCharMap:(unsigned char)c; - -/** initializes the CCLabelAtlas with a string, a char map file(the atlas), the width and height in points of each element and the starting char of the atlas */ --(id) initWithString:(NSString*) string charMapFile: (NSString*) charmapfile itemWidth:(NSUInteger)w itemHeight:(NSUInteger)h startCharMap:(unsigned char)c; -@end diff --git a/Example/libs/cocos2d/CCLabelAtlas.m b/Example/libs/cocos2d/CCLabelAtlas.m deleted file mode 100644 index e16ebde..0000000 --- a/Example/libs/cocos2d/CCLabelAtlas.m +++ /dev/null @@ -1,181 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "ccConfig.h" -#import "ccMacros.h" -#import "CCDrawingPrimitives.h" -#import "CCLabelAtlas.h" -#import "CCShaderCache.h" -#import "CCGLProgram.h" -#import "ccGLStateCache.h" -#import "CCDirector.h" -#import "Support/CGPointExtension.h" -#import "Support/TransformUtils.h" - -// external -#import "kazmath/GL/matrix.h" - -@implementation CCLabelAtlas - -#pragma mark CCLabelAtlas - Creation & Init -+(id) labelWithString:(NSString*)string charMapFile:(NSString*)charmapfile itemWidth:(NSUInteger)w itemHeight:(NSUInteger)h startCharMap:(unsigned char)c -{ - return [[[self alloc] initWithString:string charMapFile:charmapfile itemWidth:w itemHeight:h startCharMap:c] autorelease]; -} - --(id) initWithString:(NSString*) theString charMapFile: (NSString*) charmapfile itemWidth:(NSUInteger)w itemHeight:(NSUInteger)h startCharMap:(unsigned char)c -{ - - if ((self=[super initWithTileFile:charmapfile tileWidth:w tileHeight:h itemsToRender:[theString length] ]) ) { - - mapStartChar_ = c; - [self setString: theString]; - } - - return self; -} - --(void) dealloc -{ - [string_ release]; - - [super dealloc]; -} - -#pragma mark CCLabelAtlas - Atlas generation - --(void) updateAtlasValues -{ - NSUInteger n = [string_ length]; - - ccV3F_C4B_T2F_Quad quad; - - const unsigned char *s = (unsigned char*) [string_ UTF8String]; - - CCTexture2D *texture = [textureAtlas_ texture]; - float textureWide = [texture pixelsWide]; - float textureHigh = [texture pixelsHigh]; - float itemWidthInPixels = itemWidth_ * CC_CONTENT_SCALE_FACTOR(); - float itemHeightInPixels = itemHeight_ * CC_CONTENT_SCALE_FACTOR(); - - - for( NSUInteger i=0; i textureAtlas_.capacity ) - [textureAtlas_ resizeCapacity:len]; - - [string_ release]; - string_ = [newString copy]; - [self updateAtlasValues]; - - CGSize s = CGSizeMake(len * itemWidth_, itemHeight_); - [self setContentSize:s]; - - self.quadsToDraw = len; - } -} - --(NSString*) string -{ - return string_; -} - -#pragma mark CCLabelAtlas - DebugDraw - -#if CC_LABELATLAS_DEBUG_DRAW -- (void) draw -{ - [super draw]; - - CGSize s = [self contentSize]; - CGPoint vertices[4]={ - ccp(0,0),ccp(s.width,0), - ccp(s.width,s.height),ccp(0,s.height), - }; - ccDrawPoly(vertices, 4, YES); -} -#endif // CC_LABELATLAS_DEBUG_DRAW - -@end diff --git a/Example/libs/cocos2d/CCLabelBMFont.h b/Example/libs/cocos2d/CCLabelBMFont.h deleted file mode 100644 index 0aaea60..0000000 --- a/Example/libs/cocos2d/CCLabelBMFont.h +++ /dev/null @@ -1,213 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * Portions of this code are based and inspired on: - * http://www.71squared.co.uk/2009/04/iphone-game-programming-tutorial-4-bitmap-font-class - * by Michael Daley - * - * Use any of these editors to generate BMFonts: - * http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) - * http://www.n4te.com/hiero/hiero.jnlp (Free, Java) - * http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) - * http://www.angelcode.com/products/bmfont/ (Free, Windows only) - */ - -#import "CCSpriteBatchNode.h" -#import "Support/uthash.h" - -enum { - kCCLabelAutomaticWidth = -1, -}; - -struct _KerningHashElement; - -/** @struct ccBMFontDef - BMFont definition - */ -typedef struct _BMFontDef { - //! ID of the character - unichar charID; - //! origin and size of the font - CGRect rect; - //! The X amount the image should be offset when drawing the image (in pixels) - short xOffset; - //! The Y amount the image should be offset when drawing the image (in pixels) - short yOffset; - //! The amount to move the current position after drawing the character (in pixels) - short xAdvance; -} ccBMFontDef; - -/** @struct ccBMFontPadding - BMFont padding - @since v0.8.2 - */ -typedef struct _BMFontPadding { - /// padding left - int left; - /// padding top - int top; - /// padding right - int right; - /// padding bottom - int bottom; -} ccBMFontPadding; - - -/** CCBMFontConfiguration has parsed configuration of the the .fnt file - @since v0.8 - */ -@interface CCBMFontConfiguration : NSObject -{ - // XXX: Creating a public interface so that the bitmapFontArray[] is accesible -@public - - // BMFont definitions - struct _FontDefHashElement *fontDefDictionary_; - - // FNTConfig: Common Height - NSUInteger commonHeight_; - - // Padding - ccBMFontPadding padding_; - - // atlas name - NSString *atlasName_; - - // values for kerning - struct _KerningHashElement *kerningDictionary_; -} - -/** allocates a CCBMFontConfiguration with a FNT file */ -+(id) configurationWithFNTFile:(NSString*)FNTfile; -/** initializes a CCBMFontConfiguration with a FNT file */ --(id) initWithFNTfile:(NSString*)FNTfile; -@end - - -/** CCLabelBMFont is a subclass of CCSpriteBatchNode - - Features: - - Treats each character like a CCSprite. This means that each individual character can be: - - rotated - - scaled - - translated - - tinted - - chage the opacity - - It can be used as part of a menu item. - - anchorPoint can be used to align the "label" - - Supports AngelCode text format - - Limitations: - - All inner characters are using an anchorPoint of (0.5f, 0.5f) and it is not recommend to change it - because it might affect the rendering - - CCLabelBMFont implements the protocol CCLabelProtocol, like CCLabel and CCLabelAtlas. - CCLabelBMFont has the flexibility of CCLabel, the speed of CCLabelAtlas and all the features of CCSprite. - If in doubt, use CCLabelBMFont instead of CCLabelAtlas / CCLabel. - - Supported editors: - - http://glyphdesigner.71squared.com/ - - http://www.bmglyph.com/ - - http://www.n4te.com/hiero/hiero.jnlp - - http://slick.cokeandcode.com/demos/hiero.jnlp - - http://www.angelcode.com/products/bmfont/ - - @since v0.8 - */ - -@interface CCLabelBMFont : CCSpriteBatchNode -{ - // string to render - NSString *string_; - - // name of fntFile - NSString *fntFile_; - - // initial string without line breaks - NSString *initialString_; - // max width until a line break is added - float width_; - // alignment of all lines - CCTextAlignment alignment_; - - CCBMFontConfiguration *configuration_; - - // texture RGBA - GLubyte opacity_; - ccColor3B color_; - BOOL opacityModifyRGB_; - - // offset of the texture atlas - CGPoint imageOffset_; -} - -/** Purges the cached data. - Removes from memory the cached configurations and the atlas name dictionary. - @since v0.99.3 - */ -+(void) purgeCachedData; - -/** alignment used for the label */ -@property (nonatomic,assign,readonly) CCTextAlignment alignment; -/** fntFile used for the font */ -@property (nonatomic,retain) NSString* fntFile; -/** conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readwrite) GLubyte opacity; -/** conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readwrite) ccColor3B color; - - -/** creates a BMFont label with an initial string and the FNT file. */ -+(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile; -/** creates a BMFont label with an initial string, the FNT file, width, and alignment option */ -+(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment; -/** creates a BMFont label with an initial string, the FNT file, width, alignment option and the offset of where the glpyhs start on the .PNG image */ -+(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment imageOffset:(CGPoint)offset; - -/** init a BMFont label with an initial string and the FNT file */ --(id) initWithString:(NSString*)string fntFile:(NSString*)fntFile; -/** init a BMFont label with an initial string and the FNT file, width, and alignment option*/ --(id) initWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment; -/** init a BMFont label with an initial string and the FNT file, width, alignment option and the offset of where the glyphs start on the .PNG image */ --(id) initWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment imageOffset:(CGPoint)offset; - -/** updates the font chars based on the string to render */ --(void) createFontChars; - -/** set label width */ -- (void)setWidth:(float)width; - -/** set label alignment */ -- (void)setAlignment:(CCTextAlignment)alignment; - -@end - -/** Free function that parses a FNT file a place it on the cache - */ -CCBMFontConfiguration * FNTConfigLoadFile( NSString *file ); -/** Purges the FNT config cache - */ -void FNTConfigRemoveCache( void ); - - diff --git a/Example/libs/cocos2d/CCLabelBMFont.m b/Example/libs/cocos2d/CCLabelBMFont.m deleted file mode 100644 index a91e4e3..0000000 --- a/Example/libs/cocos2d/CCLabelBMFont.m +++ /dev/null @@ -1,930 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * Portions of this code are based and inspired on: - * http://www.71squared.co.uk/2009/04/iphone-game-programming-tutorial-4-bitmap-font-class - * by Michael Daley - * - * - * Use any of these editors to generate BMFonts: - * http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) - * http://www.n4te.com/hiero/hiero.jnlp (Free, Java) - * http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) - * http://www.angelcode.com/products/bmfont/ (Free, Windows only) - */ - -#import "ccConfig.h" -#import "ccMacros.h" -#import "CCLabelBMFont.h" -#import "CCSprite.h" -#import "CCDrawingPrimitives.h" -#import "CCConfiguration.h" -#import "CCTextureCache.h" -#import "Support/CCFileUtils.h" -#import "Support/CGPointExtension.h" -#import "Support/uthash.h" - -#pragma mark - -#pragma mark FNTConfig Cache - free functions - -NSMutableDictionary *configurations = nil; -CCBMFontConfiguration* FNTConfigLoadFile( NSString *fntFile) -{ - CCBMFontConfiguration *ret = nil; - - if( configurations == nil ) - configurations = [[NSMutableDictionary dictionaryWithCapacity:3] retain]; - - ret = [configurations objectForKey:fntFile]; - if( ret == nil ) { - ret = [CCBMFontConfiguration configurationWithFNTFile:fntFile]; - [configurations setObject:ret forKey:fntFile]; - } - - return ret; -} - -void FNTConfigRemoveCache( void ) -{ - [configurations removeAllObjects]; -} - -#pragma mark - Hash Element - -// Equal function for targetSet. -typedef struct _KerningHashElement -{ - int key; // key for the hash. 16-bit for 1st element, 16-bit for 2nd element - int amount; - UT_hash_handle hh; -} tKerningHashElement; - - -#pragma mark - -#pragma mark BitmapFontConfiguration - -typedef struct _FontDefHashElement -{ - NSUInteger key; // key. Font Unicode value - ccBMFontDef fontDef; // font definition - UT_hash_handle hh; -} tFontDefHashElement; - - -@interface CCBMFontConfiguration () --(void) parseConfigFile:(NSString*)controlFile; --(void) parseCharacterDefinition:(NSString*)line charDef:(ccBMFontDef*)characterDefinition; --(void) parseInfoArguments:(NSString*)line; --(void) parseCommonArguments:(NSString*)line; --(void) parseImageFileName:(NSString*)line fntFile:(NSString*)fntFile; --(void) parseKerningCapacity:(NSString*)line; --(void) parseKerningEntry:(NSString*)line; --(void) purgeKerningDictionary; --(void) purgeFontDefDictionary; -@end - -#pragma mark - -#pragma mark CCBMFontConfiguration - -@implementation CCBMFontConfiguration - -+(id) configurationWithFNTFile:(NSString*)FNTfile -{ - return [[[self alloc] initWithFNTfile:FNTfile] autorelease]; -} - --(id) initWithFNTfile:(NSString*)fntFile -{ - if((self=[super init])) { - - kerningDictionary_ = NULL; - fontDefDictionary_ = NULL; - - [self parseConfigFile:fntFile]; - } - return self; -} - -- (void) dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@", self); - [self purgeFontDefDictionary]; - [self purgeKerningDictionary]; - [atlasName_ release]; - [super dealloc]; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Glphys:%d Kernings:%d | Image = %@>", [self class], self, - HASH_COUNT(fontDefDictionary_), - HASH_COUNT(kerningDictionary_), - atlasName_]; -} - - --(void) purgeFontDefDictionary -{ - tFontDefHashElement *current, *tmp; - - HASH_ITER(hh, fontDefDictionary_, current, tmp) { - HASH_DEL(fontDefDictionary_, current); - free(current); - } -} - --(void) purgeKerningDictionary -{ - tKerningHashElement *current; - - while(kerningDictionary_) { - current = kerningDictionary_; - HASH_DEL(kerningDictionary_,current); - free(current); - } -} - -- (void)parseConfigFile:(NSString*)fntFile -{ - NSString *fullpath = [CCFileUtils fullPathFromRelativePath:fntFile]; - NSError *error; - NSString *contents = [NSString stringWithContentsOfFile:fullpath encoding:NSUTF8StringEncoding error:&error]; - - NSAssert1( contents, @"cocos2d: Error parsing FNTfile: %@", error); - - - // Move all lines in the string, which are denoted by \n, into an array - NSArray *lines = [[NSArray alloc] initWithArray:[contents componentsSeparatedByString:@"\n"]]; - - // Create an enumerator which we can use to move through the lines read from the control file - NSEnumerator *nse = [lines objectEnumerator]; - - // Create a holder for each line we are going to work with - NSString *line; - - // Loop through all the lines in the lines array processing each one - while( (line = [nse nextObject]) ) { - // parse spacing / padding - if([line hasPrefix:@"info face"]) { - // XXX: info parsing is incomplete - // Not needed for the Hiero editors, but needed for the AngelCode editor - // [self parseInfoArguments:line]; - } - // Check to see if the start of the line is something we are interested in - else if([line hasPrefix:@"common lineHeight"]) { - [self parseCommonArguments:line]; - } - else if([line hasPrefix:@"page id"]) { - [self parseImageFileName:line fntFile:fntFile]; - } - else if([line hasPrefix:@"chars c"]) { - // Ignore this line - } - else if([line hasPrefix:@"char"]) { - // Parse the current line and create a new CharDef - tFontDefHashElement *element = malloc( sizeof(*element) ); - - [self parseCharacterDefinition:line charDef:&element->fontDef]; - - element->key = element->fontDef.charID; - HASH_ADD_INT(fontDefDictionary_, key, element); - } - else if([line hasPrefix:@"kernings count"]) { - [self parseKerningCapacity:line]; - } - else if([line hasPrefix:@"kerning first"]) { - [self parseKerningEntry:line]; - } - } - // Finished with lines so release it - [lines release]; -} - --(void) parseImageFileName:(NSString*)line fntFile:(NSString*)fntFile -{ - NSString *propertyValue = nil; - - // Break the values for this line up using = - NSArray *values = [line componentsSeparatedByString:@"="]; - - // Get the enumerator for the array of components which has been created - NSEnumerator *nse = [values objectEnumerator]; - - // We need to move past the first entry in the array before we start assigning values - [nse nextObject]; - - // page ID. Sanity check - propertyValue = [nse nextObject]; - NSAssert( [propertyValue intValue] == 0, @"XXX: LabelBMFont only supports 1 page"); - - // file - propertyValue = [nse nextObject]; - NSArray *array = [propertyValue componentsSeparatedByString:@"\""]; - propertyValue = [array objectAtIndex:1]; - NSAssert(propertyValue,@"LabelBMFont file could not be found"); - - // Supports subdirectories - NSString *dir = [fntFile stringByDeletingLastPathComponent]; - atlasName_ = [dir stringByAppendingPathComponent:propertyValue]; - - [atlasName_ retain]; -} - --(void) parseInfoArguments:(NSString*)line -{ - // - // possible lines to parse: - // info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0 - // info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 - // - NSArray *values = [line componentsSeparatedByString:@"="]; - NSEnumerator *nse = [values objectEnumerator]; - NSString *propertyValue = nil; - - // We need to move past the first entry in the array before we start assigning values - [nse nextObject]; - - // face (ignore) - [nse nextObject]; - - // size (ignore) - [nse nextObject]; - - // bold (ignore) - [nse nextObject]; - - // italic (ignore) - [nse nextObject]; - - // charset (ignore) - [nse nextObject]; - - // unicode (ignore) - [nse nextObject]; - - // strechH (ignore) - [nse nextObject]; - - // smooth (ignore) - [nse nextObject]; - - // aa (ignore) - [nse nextObject]; - - // padding (ignore) - propertyValue = [nse nextObject]; - { - - NSArray *paddingValues = [propertyValue componentsSeparatedByString:@","]; - NSEnumerator *paddingEnum = [paddingValues objectEnumerator]; - // padding top - propertyValue = [paddingEnum nextObject]; - padding_.top = [propertyValue intValue]; - - // padding right - propertyValue = [paddingEnum nextObject]; - padding_.right = [propertyValue intValue]; - - // padding bottom - propertyValue = [paddingEnum nextObject]; - padding_.bottom = [propertyValue intValue]; - - // padding left - propertyValue = [paddingEnum nextObject]; - padding_.left = [propertyValue intValue]; - - CCLOG(@"cocos2d: padding: %d,%d,%d,%d", padding_.left, padding_.top, padding_.right, padding_.bottom); - } - - // spacing (ignore) - [nse nextObject]; -} - --(void) parseCommonArguments:(NSString*)line -{ - // - // line to parse: - // common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0 - // - NSArray *values = [line componentsSeparatedByString:@"="]; - NSEnumerator *nse = [values objectEnumerator]; - NSString *propertyValue = nil; - - // We need to move past the first entry in the array before we start assigning values - [nse nextObject]; - - // Character ID - propertyValue = [nse nextObject]; - commonHeight_ = [propertyValue intValue]; - - // base (ignore) - [nse nextObject]; - - - // scaleW. sanity check - propertyValue = [nse nextObject]; - NSAssert( [propertyValue intValue] <= [[CCConfiguration sharedConfiguration] maxTextureSize], @"CCLabelBMFont: page can't be larger than supported"); - - // scaleH. sanity check - propertyValue = [nse nextObject]; - NSAssert( [propertyValue intValue] <= [[CCConfiguration sharedConfiguration] maxTextureSize], @"CCLabelBMFont: page can't be larger than supported"); - - // pages. sanity check - propertyValue = [nse nextObject]; - NSAssert( [propertyValue intValue] == 1, @"CCBitfontAtlas: only supports 1 page"); - - // packed (ignore) What does this mean ?? -} -- (void)parseCharacterDefinition:(NSString*)line charDef:(ccBMFontDef*)characterDefinition -{ - // Break the values for this line up using = - NSArray *values = [line componentsSeparatedByString:@"="]; - NSEnumerator *nse = [values objectEnumerator]; - NSString *propertyValue; - - // We need to move past the first entry in the array before we start assigning values - [nse nextObject]; - - // Character ID - propertyValue = [nse nextObject]; - propertyValue = [propertyValue substringToIndex: [propertyValue rangeOfString: @" "].location]; - characterDefinition->charID = [propertyValue intValue]; - - // Character x - propertyValue = [nse nextObject]; - characterDefinition->rect.origin.x = [propertyValue intValue]; - // Character y - propertyValue = [nse nextObject]; - characterDefinition->rect.origin.y = [propertyValue intValue]; - // Character width - propertyValue = [nse nextObject]; - characterDefinition->rect.size.width = [propertyValue intValue]; - // Character height - propertyValue = [nse nextObject]; - characterDefinition->rect.size.height = [propertyValue intValue]; - // Character xoffset - propertyValue = [nse nextObject]; - characterDefinition->xOffset = [propertyValue intValue]; - // Character yoffset - propertyValue = [nse nextObject]; - characterDefinition->yOffset = [propertyValue intValue]; - // Character xadvance - propertyValue = [nse nextObject]; - characterDefinition->xAdvance = [propertyValue intValue]; -} - --(void) parseKerningCapacity:(NSString*) line -{ - // When using uthash there is not need to parse the capacity. - - // NSAssert(!kerningDictionary, @"dictionary already initialized"); - // - // // Break the values for this line up using = - // NSArray *values = [line componentsSeparatedByString:@"="]; - // NSEnumerator *nse = [values objectEnumerator]; - // NSString *propertyValue; - // - // // We need to move past the first entry in the array before we start assigning values - // [nse nextObject]; - // - // // count - // propertyValue = [nse nextObject]; - // int capacity = [propertyValue intValue]; - // - // if( capacity != -1 ) - // kerningDictionary = ccHashSetNew(capacity, targetSetEql); -} - --(void) parseKerningEntry:(NSString*) line -{ - NSArray *values = [line componentsSeparatedByString:@"="]; - NSEnumerator *nse = [values objectEnumerator]; - NSString *propertyValue; - - // We need to move past the first entry in the array before we start assigning values - [nse nextObject]; - - // first - propertyValue = [nse nextObject]; - int first = [propertyValue intValue]; - - // second - propertyValue = [nse nextObject]; - int second = [propertyValue intValue]; - - // second - propertyValue = [nse nextObject]; - int amount = [propertyValue intValue]; - - tKerningHashElement *element = calloc( sizeof( *element ), 1 ); - element->amount = amount; - element->key = (first<<16) | (second&0xffff); - HASH_ADD_INT(kerningDictionary_,key, element); -} - -@end - -#pragma mark - -#pragma mark CCLabelBMFont - -@interface CCLabelBMFont () - --(int) kerningAmountForFirst:(unichar)first second:(unichar)second; --(void) updateLabel; --(void) setString:(NSString*) newString updateLabel:(BOOL)update; - -@end - -#pragma mark - -#pragma mark CCLabelBMFont - -@implementation CCLabelBMFont - -@synthesize alignment = alignment_; -@synthesize opacity = opacity_, color = color_; - - -#pragma mark LabelBMFont - Purge Cache -+(void) purgeCachedData -{ - FNTConfigRemoveCache(); -} - -#pragma mark LabelBMFont - Creation & Init - -+(id) labelWithString:(NSString *)string fntFile:(NSString *)fntFile -{ - return [[[self alloc] initWithString:string fntFile:fntFile width:kCCLabelAutomaticWidth alignment:CCTextAlignmentLeft imageOffset:CGPointZero] autorelease]; -} - -+(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment -{ - return [[[self alloc] initWithString:string fntFile:fntFile width:width alignment:alignment imageOffset:CGPointZero] autorelease]; -} - -+(id) labelWithString:(NSString*)string fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment imageOffset:(CGPoint)offset -{ - return [[[self alloc] initWithString:string fntFile:fntFile width:width alignment:alignment imageOffset:offset] autorelease]; -} - --(id) initWithString:(NSString*)theString fntFile:(NSString*)fntFile -{ - return [self initWithString:theString fntFile:fntFile width:kCCLabelAutomaticWidth alignment:CCTextAlignmentLeft]; -} - --(id) initWithString:(NSString*)theString fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment -{ - return [self initWithString:theString fntFile:fntFile width:width alignment:alignment imageOffset:CGPointZero]; -} - --(id) initWithString:(NSString*)theString fntFile:(NSString*)fntFile width:(float)width alignment:(CCTextAlignment)alignment imageOffset:(CGPoint)offset -{ - NSAssert(!configuration_, @"re-init is no longer supported"); - - configuration_ = FNTConfigLoadFile(fntFile); - [configuration_ retain]; - - fntFile_ = [fntFile retain]; - - NSAssert( configuration_, @"Error creating config for LabelBMFont"); - - if ((self=[super initWithFile:configuration_->atlasName_ capacity:[theString length]])) { - - width_ = width; - alignment_ = alignment; - - opacity_ = 255; - color_ = ccWHITE; - - contentSize_ = CGSizeZero; - - opacityModifyRGB_ = [[textureAtlas_ texture] hasPremultipliedAlpha]; - - anchorPoint_ = ccp(0.5f, 0.5f); - - imageOffset_ = offset; - - [self setString:theString updateLabel:YES]; - } - - return self; -} - --(void) dealloc -{ - [string_ release]; - [initialString_ release]; - [configuration_ release]; - [fntFile_ release]; - - [super dealloc]; -} - -#pragma mark LabelBMFont - Alignment - -- (void)updateLabel -{ - [self setString:initialString_ updateLabel:NO]; - - if (width_ > 0){ - //Step 1: Make multiline - - NSString *multilineString = @"", *lastWord = @""; - int line = 1, i = 0; - NSUInteger stringLength = [self.string length]; - float startOfLine = -1, startOfWord = -1; - int skip = 0; - //Go through each character and insert line breaks as necessary - for (int j = 0; j < [children_ count]; j++) { - CCSprite *characterSprite; - - while(!(characterSprite = (CCSprite *)[self getChildByTag:j+skip])) - skip++; - - if (!characterSprite.visible) continue; - - if (i >= stringLength || i < 0) - break; - - unichar character = [self.string characterAtIndex:i]; - - if (startOfWord == -1) - startOfWord = characterSprite.position.x - characterSprite.contentSize.width/2; - if (startOfLine == -1) - startOfLine = startOfWord; - - //Character is a line break - //Put lastWord on the current line and start a new line - //Reset lastWord - if ([[NSCharacterSet newlineCharacterSet] characterIsMember:character]) { - lastWord = [[lastWord stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] stringByAppendingFormat:@"%C", character]; - multilineString = [multilineString stringByAppendingString:lastWord]; - lastWord = @""; - startOfWord = -1; - line++; - startOfLine = -1; - i++; - - //CCLabelBMFont do not have a character for new lines, so do NOT "continue;" in the for loop. Process the next character - if (i >= stringLength || i < 0) - break; - character = [self.string characterAtIndex:i]; - - if (startOfWord == -1) - startOfWord = characterSprite.position.x - characterSprite.contentSize.width/2; - if (startOfLine == -1) - startOfLine = startOfWord; - } - - //Character is a whitespace - //Put lastWord on current line and continue on current line - //Reset lastWord - if ([[NSCharacterSet whitespaceCharacterSet] characterIsMember:character]) { - lastWord = [lastWord stringByAppendingFormat:@"%C", character]; - multilineString = [multilineString stringByAppendingString:lastWord]; - lastWord = @""; - startOfWord = -1; - i++; - continue; - } - - //Character is out of bounds - //Do not put lastWord on current line. Add "\n" to current line to start a new line - //Append to lastWord - if (characterSprite.position.x + characterSprite.contentSize.width/2 - startOfLine > width_) { - lastWord = [lastWord stringByAppendingFormat:@"%C", character]; - NSString *trimmedString = [multilineString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; - multilineString = [trimmedString stringByAppendingString:@"\n"]; - line++; - startOfLine = -1; - i++; - continue; - } else { - //Character is normal - //Append to lastWord - lastWord = [lastWord stringByAppendingFormat:@"%C", character]; - i++; - continue; - } - } - - multilineString = [multilineString stringByAppendingFormat:@"%@", lastWord]; - - [self setString:multilineString updateLabel:NO]; - } - - //Step 2: Make alignment - - if (self.alignment != CCTextAlignmentLeft) { - - int i = 0; - //Number of spaces skipped - int lineNumber = 0; - //Go through line by line - for (NSString *lineString in [string_ componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) { - int lineWidth = 0; - - //Find index of last character in this line - NSInteger index = i + [lineString length] - 1 + lineNumber; - if (index < 0) - continue; - - //Find position of last character on the line - CCSprite *lastChar = (CCSprite *)[self getChildByTag:index]; - - lineWidth = lastChar.position.x + lastChar.contentSize.width/2; - - //Figure out how much to shift each character in this line horizontally - float shift = 0; - switch (self.alignment) { - case CCTextAlignmentCenter: - shift = self.contentSize.width/2 - lineWidth/2; - break; - case CCTextAlignmentRight: - shift = self.contentSize.width - lineWidth; - default: - break; - } - - if (shift != 0) { - int j = 0; - //For each character, shift it so that the line is center aligned - for (j = 0; j < [lineString length]; j++) { - index = i + j + lineNumber; - if (index < 0) - continue; - CCSprite *characterSprite = (CCSprite *)[self getChildByTag:index]; - characterSprite.position = ccpAdd(characterSprite.position, ccp(shift, 0)); - } - } - i += [lineString length]; - lineNumber++; - } - } -} - -#pragma mark LabelBMFont - Atlas generation - --(int) kerningAmountForFirst:(unichar)first second:(unichar)second -{ - int ret = 0; - unsigned int key = (first<<16) | (second & 0xffff); - - if( configuration_->kerningDictionary_ ) { - tKerningHashElement *element = NULL; - HASH_FIND_INT(configuration_->kerningDictionary_, &key, element); - if(element) - ret = element->amount; - } - - return ret; -} - --(void) createFontChars -{ - NSInteger nextFontPositionX = 0; - NSInteger nextFontPositionY = 0; - unichar prev = -1; - NSInteger kerningAmount = 0; - - CGSize tmpSize = CGSizeZero; - - NSInteger longestLine = 0; - NSUInteger totalHeight = 0; - - NSUInteger quantityOfLines = 1; - - NSUInteger stringLen = [string_ length]; - if( ! stringLen ) - return; - - // quantity of lines NEEDS to be calculated before parsing the lines, - // since the Y position needs to be calcualted before hand - for(NSUInteger i=0; i < stringLen-1;i++) { - unichar c = [string_ characterAtIndex:i]; - if( c=='\n') - quantityOfLines++; - } - - totalHeight = configuration_->commonHeight_ * quantityOfLines; - nextFontPositionY = -(configuration_->commonHeight_ - configuration_->commonHeight_*quantityOfLines); - - for(NSUInteger i = 0; icommonHeight_; - continue; - } - - kerningAmount = [self kerningAmountForFirst:prev second:c]; - - - tFontDefHashElement *element = NULL; - - // unichar is a short, and an int is needed on HASH_FIND_INT - NSUInteger key = (NSUInteger)c; - HASH_FIND_INT(configuration_->fontDefDictionary_ , &key, element); - NSAssert(element, @"FontDefinition could not be found!"); - - ccBMFontDef fontDef = element->fontDef; - - CGRect rect = fontDef.rect; - rect = CC_RECT_PIXELS_TO_POINTS(rect); - - rect.origin.x += imageOffset_.x; - rect.origin.y += imageOffset_.y; - - CCSprite *fontChar; - - fontChar = (CCSprite*) [self getChildByTag:i]; - if( ! fontChar ) { - fontChar = [[CCSprite alloc] initWithTexture:textureAtlas_.texture rect:rect]; - [self addChild:fontChar z:0 tag:i]; - [fontChar release]; - } - else { - // reusing fonts - [fontChar setTextureRect:rect rotated:NO untrimmedSize:rect.size]; - - // restore to default in case they were modified - fontChar.visible = YES; - fontChar.opacity = 255; - } - - float yOffset = configuration_->commonHeight_ - fontDef.yOffset; - CGPoint fontPos = ccp( (float)nextFontPositionX + fontDef.xOffset + fontDef.rect.size.width*0.5f + kerningAmount, - (float)nextFontPositionY + yOffset - rect.size.height*0.5f * CC_CONTENT_SCALE_FACTOR() ); - fontChar.position = CC_POINT_PIXELS_TO_POINTS(fontPos); - - // update kerning - nextFontPositionX += fontDef.xAdvance + kerningAmount; - prev = c; - - // Apply label properties - [fontChar setOpacityModifyRGB:opacityModifyRGB_]; - // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on - [fontChar setColor:color_]; - - // only apply opacity if it is different than 255 ) - // to prevent modifying the color too (issue #610) - if( opacity_ != 255 ) - [fontChar setOpacity: opacity_]; - - if (longestLine < nextFontPositionX) - longestLine = nextFontPositionX; - } - - tmpSize.width = longestLine; - tmpSize.height = totalHeight; - - [self setContentSize:CC_SIZE_PIXELS_TO_POINTS(tmpSize)]; -} - -#pragma mark LabelBMFont - CCLabelProtocol protocol --(NSString*) string -{ - return string_; -} - --(void) setCString:(char*)label -{ - [self setString:[NSString stringWithUTF8String:label] ]; -} - -- (void) setString:(NSString*)newString -{ - [self setString:newString updateLabel:YES]; -} - -- (void) setString:(NSString*) newString updateLabel:(BOOL)update -{ - if( !update ) { - [string_ release]; - string_ = [newString copy]; - } else { - [initialString_ release]; - initialString_ = [newString copy]; - } - - CCSprite *child; - CCARRAY_FOREACH(children_, child) - child.visible = NO; - - [self createFontChars]; - - if (update) - [self updateLabel]; -} - -#pragma mark LabelBMFont - CCRGBAProtocol protocol - --(void) setColor:(ccColor3B)color -{ - color_ = color; - - CCSprite *child; - CCARRAY_FOREACH(children_, child) - [child setColor:color_]; -} - --(void) setOpacity:(GLubyte)opacity -{ - opacity_ = opacity; - - id child; - CCARRAY_FOREACH(children_, child) - [child setOpacity:opacity_]; -} --(void) setOpacityModifyRGB:(BOOL)modify -{ - opacityModifyRGB_ = modify; - - id child; - CCARRAY_FOREACH(children_, child) - [child setOpacityModifyRGB:modify]; -} - --(BOOL) doesOpacityModifyRGB -{ - return opacityModifyRGB_; -} - -#pragma mark LabelBMFont - AnchorPoint --(void) setAnchorPoint:(CGPoint)point -{ - if( ! CGPointEqualToPoint(point, anchorPoint_) ) { - [super setAnchorPoint:point]; - [self createFontChars]; - } -} - -#pragma mark LabelBMFont - Alignment -- (void)setWidth:(float)width { - width_ = width; - [self updateLabel]; -} - -- (void)setAlignment:(CCTextAlignment)alignment { - alignment_ = alignment; - [self updateLabel]; -} - -#pragma mark LabelBMFont - FntFile -- (void) setFntFile:(NSString*) fntFile -{ - if( fntFile != fntFile_ ) { - [fntFile_ release]; - fntFile_ = [fntFile retain]; - - [configuration_ release]; - configuration_ = FNTConfigLoadFile(fntFile); - [configuration_ retain]; - - [self setTexture:[[CCTextureCache sharedTextureCache] addImage:configuration_->atlasName_]]; - [self createFontChars]; - } -} - -- (NSString*) fntFile -{ - return fntFile_; -} - -#pragma mark LabelBMFont - Debug draw -#if CC_LABELBMFONT_DEBUG_DRAW --(void) draw -{ - [super draw]; - - CGSize s = [self contentSize]; - CGPoint vertices[4]={ - ccp(0,0),ccp(s.width,0), - ccp(s.width,s.height),ccp(0,s.height), - }; - ccDrawPoly(vertices, 4, YES); -} -#endif // CC_LABELBMFONT_DEBUG_DRAW -@end diff --git a/Example/libs/cocos2d/CCLabelTTF.h b/Example/libs/cocos2d/CCLabelTTF.h deleted file mode 100644 index fcbd1dc..0000000 --- a/Example/libs/cocos2d/CCLabelTTF.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCTexture2D.h" -#import "CCSprite.h" -#import "Platforms/CCNS.h" - - -/** CCLabel is a subclass of CCTextureNode that knows how to render text labels - * - * All features from CCTextureNode are valid in CCLabel - * - * CCLabel objects are slow. Consider using CCLabelAtlas or CCLabelBMFont instead. - */ - -@interface CCLabelTTF : CCSprite -{ - CGSize dimensions_; - CCTextAlignment alignment_; - NSString * fontName_; - CGFloat fontSize_; - CCLineBreakMode lineBreakMode_; - NSString *string_; -} - -/** Font name used in the label */ -@property (nonatomic,retain) NSString* fontName; -/** Font size of the label */ -@property (nonatomic,assign) float fontSize; -/** Dimensions of the label in Points */ -@property (nonatomic,assign) CGSize dimensions; - -/** creates a CCLabel from a fontname, alignment, dimension in points, line break mode, and font size in points. - Supported lineBreakModes: - - iOS: all UILineBreakMode supported modes - - Mac: Only NSLineBreakByWordWrapping is supported. - @since v1.0 - */ -+ (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size; -/** creates a CCLabel from a fontname, alignment, dimension in points and font size in points*/ -+ (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size; -/** creates a CCLabel from a fontname and font size in points*/ -+ (id) labelWithString:(NSString*)string fontName:(NSString*)name fontSize:(CGFloat)size; -/** initializes the CCLabel with a font name, alignment, dimension in points, line brea mode and font size in points. - Supported lineBreakModes: - - iOS: all UILineBreakMode supported modes - - Mac: Only NSLineBreakByWordWrapping is supported. - @since v1.0 - */ -- (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size; -/** initializes the CCLabel with a font name, alignment, dimension in points and font size in points */ -- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size; -/** initializes the CCLabel with a font name and font size in points */ -- (id) initWithString:(NSString*)string fontName:(NSString*)name fontSize:(CGFloat)size; - -/** changes the string to render - * @warning Changing the string is as expensive as creating a new CCLabel. To obtain better performance use CCLabelAtlas - */ -- (void) setString:(NSString*)str; - - - -@end diff --git a/Example/libs/cocos2d/CCLabelTTF.m b/Example/libs/cocos2d/CCLabelTTF.m deleted file mode 100644 index 75dcedc..0000000 --- a/Example/libs/cocos2d/CCLabelTTF.m +++ /dev/null @@ -1,216 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCLabelTTF.h" -#import "Support/CGPointExtension.h" -#import "ccMacros.h" -#import "CCShaderCache.h" -#import "CCGLProgram.h" - -#ifdef __CC_PLATFORM_IOS -#import "Platforms/iOS/CCDirectorIOS.h" -#endif - -#if CC_USE_LA88_LABELS -#define SHADER_PROGRAM kCCShader_PositionTextureColor -#else -#define SHADER_PROGRAM kCCShader_PositionTextureA8Color -#endif - -@implementation CCLabelTTF - -- (id) init -{ - return [self initWithString:@"" fontName:@"Helvetica" fontSize:12]; -} - -+ (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size; -{ - return [[[self alloc] initWithString: string dimensions:dimensions alignment:alignment lineBreakMode:lineBreakMode fontName:name fontSize:size]autorelease]; -} - -+ (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size -{ - return [[[self alloc] initWithString: string dimensions:dimensions alignment:alignment fontName:name fontSize:size]autorelease]; -} - -+ (id) labelWithString:(NSString*)string fontName:(NSString*)name fontSize:(CGFloat)size -{ - return [[[self alloc] initWithString: string fontName:name fontSize:size]autorelease]; -} - - -- (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size -{ - if( (self=[super init]) ) { - - // shader program - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:SHADER_PROGRAM]; - - dimensions_ = CGSizeMake( dimensions.width, dimensions.height ); - alignment_ = alignment; - fontName_ = [name retain]; - fontSize_ = size; - lineBreakMode_ = lineBreakMode; - - [self setString:str]; - } - return self; -} - -- (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size -{ - return [self initWithString:str dimensions:dimensions alignment:alignment lineBreakMode:CCLineBreakModeWordWrap fontName:name fontSize:size]; -} - -- (id) initWithString:(NSString*)str fontName:(NSString*)name fontSize:(CGFloat)size -{ - if( (self=[super init]) ) { - - // shader program - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:SHADER_PROGRAM]; - - dimensions_ = CGSizeZero; - fontName_ = [name retain]; - fontSize_ = size; - - [self setString:str]; - } - return self; -} - -- (void) setString:(NSString*)str -{ - [string_ release]; - string_ = [str copy]; - - CCTexture2D *tex; - if( CGSizeEqualToSize( dimensions_, CGSizeZero ) ) - tex = [[CCTexture2D alloc] initWithString:str - fontName:fontName_ - fontSize:fontSize_ * CC_CONTENT_SCALE_FACTOR()]; - else - tex = [[CCTexture2D alloc] initWithString:str - dimensions:CC_SIZE_POINTS_TO_PIXELS(dimensions_) - alignment:alignment_ - lineBreakMode:lineBreakMode_ - fontName:fontName_ - fontSize:fontSize_ * CC_CONTENT_SCALE_FACTOR()]; - -#ifdef __CC_PLATFORM_IOS - // iPad ? - if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) { - if( CC_CONTENT_SCALE_FACTOR() == 2 ) - [tex setResolutionType:kCCResolutioniPadRetinaDisplay]; - else - [tex setResolutionType:kCCResolutioniPad]; - } - // iPhone ? - else - { - if( CC_CONTENT_SCALE_FACTOR() == 2 ) - [tex setResolutionType:kCCResolutioniPhoneRetinaDisplay]; - else - [tex setResolutionType:kCCResolutioniPhone]; - } -#endif - - [self setTexture:tex]; - [tex release]; - - CGRect rect = CGRectZero; - rect.size = [texture_ contentSize]; - [self setTextureRect: rect]; -} - --(NSString*) string -{ - return string_; -} - -- (void)setFontName:(NSString*)fontName -{ - if( fontName != fontName_ ) { - [fontName_ release]; - fontName_ = [fontName retain]; - - // Force update - [self setString:[self string]]; - } -} - -- (NSString*)fontName -{ - return fontName_; -} - -- (void) setFontSize:(float)fontSize -{ - if( fontSize != fontSize_ ) { - fontSize_ = fontSize; - - // Force update - [self setString:[self string]]; - } -} - -- (float) fontSize -{ - return fontSize_; -} - --(void) setDimensions:(CGSize) dim -{ - if( dim.width != dimensions_.width || dim.height != dimensions_.height) - { - dimensions_ = dim; - - // Force update - [self setString:[self string]]; - } -} - --(CGSize) dimensions -{ - return dimensions_; -} - -- (void) dealloc -{ - [string_ release]; - [fontName_ release]; - - [super dealloc]; -} - -- (NSString*) description -{ - // XXX: string_, fontName_ can't be displayed here, since they might be already released - - return [NSString stringWithFormat:@"<%@ = %08X | FontSize = %.1f>", [self class], self, fontSize_]; -} -@end diff --git a/Example/libs/cocos2d/CCLayer.h b/Example/libs/cocos2d/CCLayer.h deleted file mode 100644 index a2b08f5..0000000 --- a/Example/libs/cocos2d/CCLayer.h +++ /dev/null @@ -1,280 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - - -#import "ccMacros.h" - -#ifdef __CC_PLATFORM_IOS -#import // Needed for UIAccelerometerDelegate -#import "Platforms/iOS/CCTouchDelegateProtocol.h" // Touches only supported on iOS -#elif defined(__CC_PLATFORM_MAC) -#import "Platforms/Mac/CCEventDispatcher.h" -#endif - -#import "CCProtocols.h" -#import "CCNode.h" - -#pragma mark - -#pragma mark CCLayer - -/** CCLayer is a subclass of CCNode that implements the CCTouchEventsDelegate protocol. - - All features from CCNode are valid, plus the following new features: - - It can receive iPhone Touches - - It can receive Accelerometer input -*/ -#ifdef __CC_PLATFORM_IOS -@interface CCLayer : CCNode -{ - BOOL isTouchEnabled_; - BOOL isAccelerometerEnabled_; -} -/** If isTouchEnabled, this method is called onEnter. Override it to change the - way CCLayer receives touch events. - ( Default: [touchDispatcher addStandardDelegate:self priority:0] ) - Example: - -(void) registerWithTouchDispatcher - { - [touchDispatcher addTargetedDelegate:self priority:INT_MIN+1 swallowsTouches:YES]; - } - - Valid only on iOS. Not valid on Mac. - - @since v0.8.0 - */ --(void) registerWithTouchDispatcher; - -/** whether or not it will receive Touch events. - You can enable / disable touch events with this property. - Only the touches of this node will be affected. This "method" is not propagated to its children. - - Valid on iOS and Mac OS X v10.6 and later. - - @since v0.8.1 - */ -@property(nonatomic,assign) BOOL isTouchEnabled; -/** whether or not it will receive Accelerometer events - You can enable / disable accelerometer events with this property. - - Valid only on iOS. Not valid on Mac. - - @since v0.8.1 - */ -@property(nonatomic,assign) BOOL isAccelerometerEnabled; - -#elif defined(__CC_PLATFORM_MAC) - - -@interface CCLayer : CCNode -{ - BOOL isMouseEnabled_; - BOOL isKeyboardEnabled_; - BOOL isTouchEnabled_; -} - -/** whether or not it will receive mouse events. - - Valind only Mac. Not valid on iOS - */ -@property (nonatomic, readwrite) BOOL isMouseEnabled; - -/** whether or not it will receive keyboard events. - - Valind only Mac. Not valid on iOS - */ -@property (nonatomic, readwrite) BOOL isKeyboardEnabled; - -/** whether or not it will receive touch events. - - Valid on iOS and Mac OS X v10.6 and later. - */ -@property (nonatomic, readwrite) BOOL isTouchEnabled; - -/** priority of the mouse event delegate. - Default 0. - Override this method to set another priority. - - Valind only Mac. Not valid on iOS - */ --(NSInteger) mouseDelegatePriority; - -/** priority of the keyboard event delegate. - Default 0. - Override this method to set another priority. - - Valind only Mac. Not valid on iOS - */ --(NSInteger) keyboardDelegatePriority; - -/** priority of the touch event delegate. - Default 0. - Override this method to set another priority. - - Valind only Mac. Not valid on iOS - */ --(NSInteger) touchDelegatePriority; - -#endif // mac - - -@end - -#pragma mark - -#pragma mark CCLayerColor - -/** CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol. - - All features from CCLayer are valid, plus the following new features: - - opacity - - RGB colors - */ -@interface CCLayerColor : CCLayer -{ - GLubyte opacity_; - ccColor3B color_; - ccVertex2F squareVertices_[4]; - ccColor4F squareColors_[4]; - - ccBlendFunc blendFunc_; -} - -/** creates a CCLayer with color, width and height in Points*/ -+ (id) layerWithColor: (ccColor4B)color width:(GLfloat)w height:(GLfloat)h; -/** creates a CCLayer with color. Width and height are the window size. */ -+ (id) layerWithColor: (ccColor4B)color; - -/** initializes a CCLayer with color, width and height in Points. - This is the designated initializer. - */ -- (id) initWithColor:(ccColor4B)color width:(GLfloat)w height:(GLfloat)h; -/** initializes a CCLayer with color. Width and height are the window size. */ -- (id) initWithColor:(ccColor4B)color; - -/** change width in Points */ --(void) changeWidth: (GLfloat)w; -/** change height in Points */ --(void) changeHeight: (GLfloat)h; -/** change width and height in Points - @since v0.8 - */ --(void) changeWidth:(GLfloat)w height:(GLfloat)h; - -/** Opacity: conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readonly) GLubyte opacity; -/** Opacity: conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readonly) ccColor3B color; -/** BlendFunction. Conforms to CCBlendProtocol protocol */ -@property (nonatomic,readwrite) ccBlendFunc blendFunc; -@end - -#pragma mark - -#pragma mark CCLayerGradient - -/** CCLayerGradient is a subclass of CCLayerColor that draws gradients across -the background. - - All features from CCLayerColor are valid, plus the following new features: - - direction - - final color - - interpolation mode - - Color is interpolated between the startColor and endColor along the given - vector (starting at the origin, ending at the terminus). If no vector is - supplied, it defaults to (0, -1) -- a fade from top to bottom. - - If 'compressedInterpolation' is disabled, you will not see either the start or end color for - non-cardinal vectors; a smooth gradient implying both end points will be still - be drawn, however. - - If ' compressedInterpolation' is enabled (default mode) you will see both the start and end colors of the gradient. - - @since v0.99.5 - */ -@interface CCLayerGradient : CCLayerColor -{ - ccColor3B endColor_; - GLubyte startOpacity_; - GLubyte endOpacity_; - CGPoint vector_; - BOOL compressedInterpolation_; -} - -/** Creates a full-screen CCLayer with a gradient between start and end. */ -+ (id) layerWithColor: (ccColor4B) start fadingTo: (ccColor4B) end; -/** Creates a full-screen CCLayer with a gradient between start and end in the direction of v. */ -+ (id) layerWithColor: (ccColor4B) start fadingTo: (ccColor4B) end alongVector: (CGPoint) v; - -/** Initializes the CCLayer with a gradient between start and end. */ -- (id) initWithColor: (ccColor4B) start fadingTo: (ccColor4B) end; -/** Initializes the CCLayer with a gradient between start and end in the direction of v. */ -- (id) initWithColor: (ccColor4B) start fadingTo: (ccColor4B) end alongVector: (CGPoint) v; - -/** The starting color. */ -@property (nonatomic, readwrite) ccColor3B startColor; -/** The ending color. */ -@property (nonatomic, readwrite) ccColor3B endColor; -/** The starting opacity. */ -@property (nonatomic, readwrite) GLubyte startOpacity; -/** The ending color. */ -@property (nonatomic, readwrite) GLubyte endOpacity; -/** The vector along which to fade color. */ -@property (nonatomic, readwrite) CGPoint vector; -/** Whether or not the interpolation will be compressed in order to display all the colors of the gradient both in canonical and non canonical vectors - Default: YES - */ -@property (nonatomic, readwrite) BOOL compressedInterpolation; - -@end - -#pragma mark - -#pragma mark CCLayerMultiplex - -/** CCLayerMultiplex is a CCLayer with the ability to multiplex its children. - Features: - - It supports one or more children - - Only one children will be active a time - */ -@interface CCLayerMultiplex : CCLayer -{ - unsigned int enabledLayer_; - NSMutableArray *layers_; -} - -/** creates a CCMultiplexLayer with one or more layers using a variable argument list. */ -+(id) layerWithLayers: (CCLayer*) layer, ... NS_REQUIRES_NIL_TERMINATION; -/** initializes a MultiplexLayer with one or more layers using a variable argument list. */ --(id) initWithLayers: (CCLayer*) layer vaList:(va_list) params; -/** switches to a certain layer indexed by n. - The current (old) layer will be removed from its parent with 'cleanup:YES'. - */ --(void) switchTo: (unsigned int) n; -/** release the current layer and switches to another layer indexed by n. - The current (old) layer will be removed from its parent with 'cleanup:YES'. - */ --(void) switchToAndReleaseMe: (unsigned int) n; -@end - diff --git a/Example/libs/cocos2d/CCLayer.m b/Example/libs/cocos2d/CCLayer.m deleted file mode 100644 index 277f99d..0000000 --- a/Example/libs/cocos2d/CCLayer.m +++ /dev/null @@ -1,628 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import - -#import "Platforms/CCGL.h" - -#import "CCLayer.h" -#import "CCDirector.h" -#import "ccMacros.h" -#import "CCShaderCache.h" -#import "CCGLProgram.h" -#import "ccGLStateCache.h" -#import "Support/TransformUtils.h" -#import "Support/CGPointExtension.h" - -#ifdef __CC_PLATFORM_IOS -#import "Platforms/iOS/CCTouchDispatcher.h" -#import "Platforms/iOS/CCDirectorIOS.h" -#elif defined(__CC_PLATFORM_MAC) -#import "Platforms/Mac/CCEventDispatcher.h" -#import "Platforms/Mac/CCDirectorMac.h" -#endif - -// extern -#import "kazmath/GL/matrix.h" - -#pragma mark - -#pragma mark Layer - -@implementation CCLayer - -#pragma mark Layer - Init --(id) init -{ - if( (self=[super init]) ) { - - CGSize s = [[CCDirector sharedDirector] winSize]; - anchorPoint_ = ccp(0.5f, 0.5f); - [self setContentSize:s]; - self.isRelativeAnchorPoint = NO; - - isTouchEnabled_ = NO; - -#ifdef __CC_PLATFORM_IOS - isAccelerometerEnabled_ = NO; -#elif defined(__CC_PLATFORM_MAC) - isMouseEnabled_ = NO; - isKeyboardEnabled_ = NO; -#endif - } - - return self; -} - -#pragma mark Layer - Touch and Accelerometer related - -#ifdef __CC_PLATFORM_IOS --(void) registerWithTouchDispatcher -{ - CCDirector *director = [CCDirector sharedDirector]; - [[director touchDispatcher] addStandardDelegate:self priority:0]; -} - --(BOOL) isAccelerometerEnabled -{ - return isAccelerometerEnabled_; -} - --(void) setIsAccelerometerEnabled:(BOOL)enabled -{ - if( enabled != isAccelerometerEnabled_ ) { - isAccelerometerEnabled_ = enabled; - if( isRunning_ ) { - if( enabled ) - [[UIAccelerometer sharedAccelerometer] setDelegate:self]; - else - [[UIAccelerometer sharedAccelerometer] setDelegate:nil]; - } - } -} - --(BOOL) isTouchEnabled -{ - return isTouchEnabled_; -} - --(void) setIsTouchEnabled:(BOOL)enabled -{ - if( isTouchEnabled_ != enabled ) { - isTouchEnabled_ = enabled; - if( isRunning_ ) { - if( enabled ) - [self registerWithTouchDispatcher]; - else { - CCDirector *director = [CCDirector sharedDirector]; - [[director touchDispatcher] removeDelegate:self]; - } - } - } -} - -#elif defined(__CC_PLATFORM_MAC) - -#pragma mark CCLayer - Mouse, Keyboard & Touch events - --(NSInteger) mouseDelegatePriority -{ - return 0; -} - --(BOOL) isMouseEnabled -{ - return isMouseEnabled_; -} - --(void) setIsMouseEnabled:(BOOL)enabled -{ - if( isMouseEnabled_ != enabled ) { - isMouseEnabled_ = enabled; - - if( isRunning_ ) { - CCDirector *director = [CCDirector sharedDirector]; - if( enabled ) - [[director eventDispatcher] addMouseDelegate:self priority:[self mouseDelegatePriority]]; - else - [[director eventDispatcher] removeMouseDelegate:self]; - } - } -} - --(NSInteger) keyboardDelegatePriority -{ - return 0; -} - --(BOOL) isKeyboardEnabled -{ - return isKeyboardEnabled_; -} - --(void) setIsKeyboardEnabled:(BOOL)enabled -{ - if( isKeyboardEnabled_ != enabled ) { - isKeyboardEnabled_ = enabled; - - if( isRunning_ ) { - CCDirector *director = [CCDirector sharedDirector]; - if( enabled ) - [[director eventDispatcher] addKeyboardDelegate:self priority:[self keyboardDelegatePriority] ]; - else - [[director eventDispatcher] removeKeyboardDelegate:self]; - } - } -} - --(NSInteger) touchDelegatePriority -{ - return 0; -} - --(BOOL) isTouchEnabled -{ - return isTouchEnabled_; -} - --(void) setIsTouchEnabled:(BOOL)enabled -{ - if( isTouchEnabled_ != enabled ) { - isTouchEnabled_ = enabled; - if( isRunning_ ) { - CCDirector *director = [CCDirector sharedDirector]; - if( enabled ) - [[director eventDispatcher] addTouchDelegate:self priority:[self touchDelegatePriority]]; - else - [[director eventDispatcher] removeTouchDelegate:self]; - } - } -} - - -#endif // Mac - - -#pragma mark Layer - Callbacks --(void) onEnter -{ -#ifdef __CC_PLATFORM_IOS - // register 'parent' nodes first - // since events are propagated in reverse order - if (isTouchEnabled_) - [self registerWithTouchDispatcher]; - -#elif defined(__CC_PLATFORM_MAC) - CCDirector *director = [CCDirector sharedDirector]; - CCEventDispatcher *eventDispatcher = [director eventDispatcher]; - - if( isMouseEnabled_ ) - [eventDispatcher addMouseDelegate:self priority:[self mouseDelegatePriority]]; - - if( isKeyboardEnabled_) - [eventDispatcher addKeyboardDelegate:self priority:[self keyboardDelegatePriority]]; - - if( isTouchEnabled_) - [eventDispatcher addTouchDelegate:self priority:[self touchDelegatePriority]]; - -#endif - - // then iterate over all the children - [super onEnter]; -} - -// issue #624. -// Can't register mouse, touches here because of #issue #1018, and #1021 --(void) onEnterTransitionDidFinish -{ -#ifdef __CC_PLATFORM_IOS - if( isAccelerometerEnabled_ ) - [[UIAccelerometer sharedAccelerometer] setDelegate:self]; -#endif - - [super onEnterTransitionDidFinish]; -} - - --(void) onExit -{ - CCDirector *director = [CCDirector sharedDirector]; - -#ifdef __CC_PLATFORM_IOS - if( isTouchEnabled_ ) - [[director touchDispatcher] removeDelegate:self]; - - if( isAccelerometerEnabled_ ) - [[UIAccelerometer sharedAccelerometer] setDelegate:nil]; - -#elif defined(__CC_PLATFORM_MAC) - CCEventDispatcher *eventDispatcher = [director eventDispatcher]; - if( isMouseEnabled_ ) - [eventDispatcher removeMouseDelegate:self]; - - if( isKeyboardEnabled_ ) - [eventDispatcher removeKeyboardDelegate:self]; - - if( isTouchEnabled_ ) - [eventDispatcher removeTouchDelegate:self]; - -#endif - - [super onExit]; -} - -#ifdef __CC_PLATFORM_IOS --(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event -{ - NSAssert(NO, @"Layer#ccTouchBegan override me"); - return YES; -} -#endif -@end - -#pragma mark - -#pragma mark LayerColor - -@interface CCLayerColor (Private) --(void) updateColor; -@end - -@implementation CCLayerColor - -// Opacity and RGB color protocol -@synthesize opacity = opacity_, color = color_; -@synthesize blendFunc = blendFunc_; - - -+ (id) layerWithColor:(ccColor4B)color width:(GLfloat)w height:(GLfloat) h -{ - return [[[self alloc] initWithColor:color width:w height:h] autorelease]; -} - -+ (id) layerWithColor:(ccColor4B)color -{ - return [[(CCLayerColor*)[self alloc] initWithColor:color] autorelease]; -} - --(id) init -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - return [self initWithColor:ccc4(0,0,0,0) width:s.width height:s.height]; -} - -// Designated initializer -- (id) initWithColor:(ccColor4B)color width:(GLfloat)w height:(GLfloat) h -{ - if( (self=[super init]) ) { - - // default blend function - blendFunc_ = (ccBlendFunc) { GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA }; - - color_.r = color.r; - color_.g = color.g; - color_.b = color.b; - opacity_ = color.a; - - for (NSUInteger i = 0; i -{ - tCCMenuState state_; - CCMenuItem *selectedItem_; - GLubyte opacity_; - ccColor3B color_; - BOOL enabled_; -} - -/** conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readonly) GLubyte opacity; -/** conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readonly) ccColor3B color; -/** whether or not the menu will receive events */ -@property (nonatomic, readwrite) BOOL enabled; - -/** creates a CCMenu with its items */ -+ (id) menuWithItems: (CCMenuItem*) item, ... NS_REQUIRES_NIL_TERMINATION; - -/** creates a CCMenu with a NSArray of CCMenuItem objects */ -+ (id) menuWithArray:(NSArray*)arrayOfItems; - -/** initializes a CCMenu with its items */ -- (id) initWithItems: (CCMenuItem*) item vaList: (va_list) args; - -/** initializes a CCMenu with a NSArray of CCMenuItem objects */ -- (id) initWithArray:(NSArray*)arrayOfItems; - -/** align items vertically */ --(void) alignItemsVertically; -/** align items vertically with padding - @since v0.7.2 - */ --(void) alignItemsVerticallyWithPadding:(float) padding; - -/** align items horizontally */ --(void) alignItemsHorizontally; -/** align items horizontally with padding - @since v0.7.2 - */ --(void) alignItemsHorizontallyWithPadding: (float) padding; - -/** align items in rows of columns */ --(void) alignItemsInColumns: (NSNumber *) columns, ... NS_REQUIRES_NIL_TERMINATION; --(void) alignItemsInColumns: (NSNumber *) columns vaList: (va_list) args; - -/** align items in columns of rows */ --(void) alignItemsInRows: (NSNumber *) rows, ... NS_REQUIRES_NIL_TERMINATION; --(void) alignItemsInRows: (NSNumber *) rows vaList: (va_list) args; - -/** set event handler priority. By default it is: kCCMenuTouchPriority */ --(void) setHandlerPriority:(NSInteger)newPriority; - -@end diff --git a/Example/libs/cocos2d/CCMenu.m b/Example/libs/cocos2d/CCMenu.m deleted file mode 100644 index b7efda2..0000000 --- a/Example/libs/cocos2d/CCMenu.m +++ /dev/null @@ -1,554 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - - -#import "CCMenu.h" -#import "CCDirector.h" -#import "Support/CGPointExtension.h" -#import "ccMacros.h" - -#ifdef __CC_PLATFORM_IOS -#import "Platforms/iOS/CCDirectorIOS.h" -#import "Platforms/iOS/CCTouchDispatcher.h" -#elif defined(__CC_PLATFORM_MAC) -#import "Platforms/Mac/CCGLView.h" -#import "Platforms/Mac/CCDirectorMac.h" -#endif - -enum { - kDefaultPadding = 5, -}; - -#pragma mark - CCMenu - -@implementation CCMenu - -@synthesize opacity = opacity_, color = color_, enabled=enabled_; - -+(id) menuWithArray:(NSArray *)arrayOfItems -{ - return [[[self alloc] initWithArray:arrayOfItems] autorelease]; -} - -+(id) menuWithItems: (CCMenuItem*) item, ... -{ - va_list args; - va_start(args,item); - - id s = [[[self alloc] initWithItems: item vaList:args] autorelease]; - - va_end(args); - return s; -} - --(id) init -{ - return [self initWithArray:nil]; -} - --(id) initWithItems: (CCMenuItem*) item vaList: (va_list) args -{ - NSMutableArray *array = nil; - if( item ) { - array = [NSMutableArray arrayWithObject:item]; - CCMenuItem *i = va_arg(args, CCMenuItem*); - while(i) { - [array addObject:i]; - i = va_arg(args, CCMenuItem*); - } - } - - return [self initWithArray:array]; -} - --(id) initWithArray:(NSArray *)arrayOfItems -{ - if( (self=[super init]) ) { -#ifdef __CC_PLATFORM_IOS - self.isTouchEnabled = YES; -#elif defined(__CC_PLATFORM_MAC) - self.isMouseEnabled = YES; -#endif - enabled_ = YES; - - // by default, menu in the center of the screen - CGSize s = [[CCDirector sharedDirector] winSize]; - - self.isRelativeAnchorPoint = NO; - anchorPoint_ = ccp(0.5f, 0.5f); - [self setContentSize:s]; - - // XXX: in v0.7, winSize should return the visible size - // XXX: so the bar calculation should be done there -#ifdef __CC_PLATFORM_IOS - CGRect r = [[UIApplication sharedApplication] statusBarFrame]; - s.height -= r.size.height; -#endif - self.position = ccp(s.width/2, s.height/2); - - int z=0; - - for( CCMenuItem *item in arrayOfItems) { - [self addChild: item z:z]; - z++; - } - -// [self alignItemsVertically]; - - selectedItem_ = nil; - state_ = kCCMenuStateWaiting; - } - - return self; -} - --(void) dealloc -{ - [super dealloc]; -} - -/* - * override add: - */ --(void) addChild:(CCMenuItem*)child z:(NSInteger)z tag:(NSInteger) aTag -{ - NSAssert( [child isKindOfClass:[CCMenuItem class]], @"Menu only supports MenuItem objects as children"); - [super addChild:child z:z tag:aTag]; -} - -- (void) onExit -{ - if(state_ == kCCMenuStateTrackingTouch) - { - [selectedItem_ unselected]; - state_ = kCCMenuStateWaiting; - selectedItem_ = nil; - } - [super onExit]; -} - -#pragma mark Menu - Events - --(void) setHandlerPriority:(NSInteger)newPriority -{ -#ifdef __CC_PLATFORM_IOS - CCTouchDispatcher *dispatcher = [[CCDirector sharedDirector] touchDispatcher]; - [dispatcher setPriority:newPriority forDelegate:self]; - -#elif defined(__CC_PLATFORM_MAC) - CCEventDispatcher *dispatcher = [[CCDirector sharedDirector] eventDispatcher]; - [dispatcher removeMouseDelegate:self]; - [dispatcher addMouseDelegate:self priority:newPriority]; -#endif -} - -#pragma mark Menu - Events Touches - -#ifdef __CC_PLATFORM_IOS --(void) registerWithTouchDispatcher -{ - CCDirector *director = [CCDirector sharedDirector]; - [[director touchDispatcher] addTargetedDelegate:self priority:kCCMenuHandlerPriority swallowsTouches:YES]; -} - --(CCMenuItem *) itemForTouch: (UITouch *) touch -{ - CGPoint touchLocation = [touch locationInView: [touch view]]; - touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation]; - - CCMenuItem* item; - CCARRAY_FOREACH(children_, item){ - // ignore invisible and disabled items: issue #779, #866 - if ( [item visible] && [item isEnabled] ) { - - CGPoint local = [item convertToNodeSpace:touchLocation]; - CGRect r = [item rect]; - r.origin = CGPointZero; - - if( CGRectContainsPoint( r, local ) ) - return item; - } - } - return nil; -} - --(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event -{ - if( state_ != kCCMenuStateWaiting || !visible_ || ! enabled_) - return NO; - - for( CCNode *c = self.parent; c != nil; c = c.parent ) - if( c.visible == NO ) - return NO; - - selectedItem_ = [self itemForTouch:touch]; - [selectedItem_ selected]; - - if( selectedItem_ ) { - state_ = kCCMenuStateTrackingTouch; - return YES; - } - return NO; -} - --(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event -{ - NSAssert(state_ == kCCMenuStateTrackingTouch, @"[Menu ccTouchEnded] -- invalid state"); - - [selectedItem_ unselected]; - [selectedItem_ activate]; - - state_ = kCCMenuStateWaiting; -} - --(void) ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event -{ - NSAssert(state_ == kCCMenuStateTrackingTouch, @"[Menu ccTouchCancelled] -- invalid state"); - - [selectedItem_ unselected]; - - state_ = kCCMenuStateWaiting; -} - --(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event -{ - NSAssert(state_ == kCCMenuStateTrackingTouch, @"[Menu ccTouchMoved] -- invalid state"); - - CCMenuItem *currentItem = [self itemForTouch:touch]; - - if (currentItem != selectedItem_) { - [selectedItem_ unselected]; - selectedItem_ = currentItem; - [selectedItem_ selected]; - } -} - -#pragma mark Menu - Events Mouse - -#elif defined(__CC_PLATFORM_MAC) - --(NSInteger) mouseDelegatePriority -{ - return kCCMenuHandlerPriority+1; -} - --(CCMenuItem *) itemForMouseEvent: (NSEvent *) event -{ - CGPoint location = [[CCDirector sharedDirector] convertEventToGL:event]; - - CCMenuItem* item; - CCARRAY_FOREACH(children_, item){ - // ignore invisible and disabled items: issue #779, #866 - if ( [item visible] && [item isEnabled] ) { - - CGPoint local = [item convertToNodeSpace:location]; - - CGRect r = [item rect]; - r.origin = CGPointZero; - - if( CGRectContainsPoint( r, local ) ) - return item; - } - } - return nil; -} - --(BOOL) ccMouseUp:(NSEvent *)event -{ - if( ! visible_ || ! enabled_) - return NO; - - if(state_ == kCCMenuStateTrackingTouch) { - if( selectedItem_ ) { - [selectedItem_ unselected]; - [selectedItem_ activate]; - } - state_ = kCCMenuStateWaiting; - - return YES; - } - return NO; -} - --(BOOL) ccMouseDown:(NSEvent *)event -{ - if( ! visible_ || ! enabled_) - return NO; - - selectedItem_ = [self itemForMouseEvent:event]; - [selectedItem_ selected]; - - if( selectedItem_ ) { - state_ = kCCMenuStateTrackingTouch; - return YES; - } - - return NO; -} - --(BOOL) ccMouseDragged:(NSEvent *)event -{ - if( ! visible_ || ! enabled_) - return NO; - - if(state_ == kCCMenuStateTrackingTouch) { - CCMenuItem *currentItem = [self itemForMouseEvent:event]; - - if (currentItem != selectedItem_) { - [selectedItem_ unselected]; - selectedItem_ = currentItem; - [selectedItem_ selected]; - } - - return YES; - } - return NO; -} - -#endif // Mac Mouse support - -#pragma mark Menu - Alignment --(void) alignItemsVertically -{ - [self alignItemsVerticallyWithPadding:kDefaultPadding]; -} --(void) alignItemsVerticallyWithPadding:(float)padding -{ - float height = -padding; - - CCMenuItem *item; - CCARRAY_FOREACH(children_, item) - height += item.contentSize.height * item.scaleY + padding; - - float y = height / 2.0f; - - CCARRAY_FOREACH(children_, item) { - CGSize itemSize = item.contentSize; - [item setPosition:ccp(0, y - itemSize.height * item.scaleY / 2.0f)]; - y -= itemSize.height * item.scaleY + padding; - } -} - --(void) alignItemsHorizontally -{ - [self alignItemsHorizontallyWithPadding:kDefaultPadding]; -} - --(void) alignItemsHorizontallyWithPadding:(float)padding -{ - - float width = -padding; - CCMenuItem *item; - CCARRAY_FOREACH(children_, item) - width += item.contentSize.width * item.scaleX + padding; - - float x = -width / 2.0f; - - CCARRAY_FOREACH(children_, item){ - CGSize itemSize = item.contentSize; - [item setPosition:ccp(x + itemSize.width * item.scaleX / 2.0f, 0)]; - x += itemSize.width * item.scaleX + padding; - } -} - --(void) alignItemsInColumns: (NSNumber *) columns, ... -{ - va_list args; - va_start(args, columns); - - [self alignItemsInColumns:columns vaList:args]; - - va_end(args); -} - --(void) alignItemsInColumns: (NSNumber *) columns vaList: (va_list) args -{ - NSMutableArray *rows = [[NSMutableArray alloc] initWithObjects:columns, nil]; - columns = va_arg(args, NSNumber*); - while(columns) { - [rows addObject:columns]; - columns = va_arg(args, NSNumber*); - } - - int height = -5; - NSUInteger row = 0, rowHeight = 0, columnsOccupied = 0, rowColumns; - CCMenuItem *item; - CCARRAY_FOREACH(children_, item){ - NSAssert( row < [rows count], @"Too many menu items for the amount of rows/columns."); - - rowColumns = [(NSNumber *) [rows objectAtIndex:row] unsignedIntegerValue]; - NSAssert( rowColumns, @"Can't have zero columns on a row"); - - rowHeight = fmaxf(rowHeight, item.contentSize.height); - ++columnsOccupied; - - if(columnsOccupied >= rowColumns) { - height += rowHeight + 5; - - columnsOccupied = 0; - rowHeight = 0; - ++row; - } - } - NSAssert( !columnsOccupied, @"Too many rows/columns for available menu items." ); - - CGSize winSize = [[CCDirector sharedDirector] winSize]; - - row = 0; rowHeight = 0; rowColumns = 0; - float w, x, y = height / 2; - CCARRAY_FOREACH(children_, item) { - if(rowColumns == 0) { - rowColumns = [(NSNumber *) [rows objectAtIndex:row] unsignedIntegerValue]; - w = winSize.width / (1 + rowColumns); - x = w; - } - - CGSize itemSize = item.contentSize; - rowHeight = fmaxf(rowHeight, itemSize.height); - [item setPosition:ccp(x - winSize.width / 2, - y - itemSize.height / 2)]; - - x += w; - ++columnsOccupied; - - if(columnsOccupied >= rowColumns) { - y -= rowHeight + 5; - - columnsOccupied = 0; - rowColumns = 0; - rowHeight = 0; - ++row; - } - } - - [rows release]; -} - --(void) alignItemsInRows: (NSNumber *) rows, ... -{ - va_list args; - va_start(args, rows); - - [self alignItemsInRows:rows vaList:args]; - - va_end(args); -} - --(void) alignItemsInRows: (NSNumber *) rows vaList: (va_list) args -{ - NSMutableArray *columns = [[NSMutableArray alloc] initWithObjects:rows, nil]; - rows = va_arg(args, NSNumber*); - while(rows) { - [columns addObject:rows]; - rows = va_arg(args, NSNumber*); - } - - NSMutableArray *columnWidths = [[NSMutableArray alloc] init]; - NSMutableArray *columnHeights = [[NSMutableArray alloc] init]; - - int width = -10, columnHeight = -5; - NSUInteger column = 0, columnWidth = 0, rowsOccupied = 0, columnRows; - CCMenuItem *item; - CCARRAY_FOREACH(children_, item){ - NSAssert( column < [columns count], @"Too many menu items for the amount of rows/columns."); - - columnRows = [(NSNumber *) [columns objectAtIndex:column] unsignedIntegerValue]; - NSAssert( columnRows, @"Can't have zero rows on a column"); - - CGSize itemSize = item.contentSize; - columnWidth = fmaxf(columnWidth, itemSize.width); - columnHeight += itemSize.height + 5; - ++rowsOccupied; - - if(rowsOccupied >= columnRows) { - [columnWidths addObject:[NSNumber numberWithUnsignedInteger:columnWidth]]; - [columnHeights addObject:[NSNumber numberWithUnsignedInteger:columnHeight]]; - width += columnWidth + 10; - - rowsOccupied = 0; - columnWidth = 0; - columnHeight = -5; - ++column; - } - } - NSAssert( !rowsOccupied, @"Too many rows/columns for available menu items."); - - CGSize winSize = [[CCDirector sharedDirector] winSize]; - - column = 0; columnWidth = 0; columnRows = 0; - float x = -width / 2, y; - - CCARRAY_FOREACH(children_, item){ - if(columnRows == 0) { - columnRows = [(NSNumber *) [columns objectAtIndex:column] unsignedIntegerValue]; - y = ([(NSNumber *) [columnHeights objectAtIndex:column] intValue] + winSize.height) / 2; - } - - CGSize itemSize = item.contentSize; - columnWidth = fmaxf(columnWidth, itemSize.width); - [item setPosition:ccp(x + [(NSNumber *) [columnWidths objectAtIndex:column] unsignedIntegerValue] / 2, - y - winSize.height / 2)]; - - y -= itemSize.height + 10; - ++rowsOccupied; - - if(rowsOccupied >= columnRows) { - x += columnWidth + 5; - - rowsOccupied = 0; - columnRows = 0; - columnWidth = 0; - ++column; - } - } - - [columns release]; - [columnWidths release]; - [columnHeights release]; -} - -#pragma mark Menu - Opacity Protocol - -/** Override synthesized setOpacity to recurse items */ -- (void) setOpacity:(GLubyte)newOpacity -{ - opacity_ = newOpacity; - - id item; - CCARRAY_FOREACH(children_, item) - [item setOpacity:opacity_]; -} - --(void) setColor:(ccColor3B)color -{ - color_ = color; - - id item; - CCARRAY_FOREACH(children_, item) - [item setColor:color_]; -} -@end diff --git a/Example/libs/cocos2d/CCMenuItem.h b/Example/libs/cocos2d/CCMenuItem.h deleted file mode 100644 index 6336534..0000000 --- a/Example/libs/cocos2d/CCMenuItem.h +++ /dev/null @@ -1,423 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCNode.h" -#import "CCProtocols.h" - -@class CCSprite; -@class CCSpriteFrame; - -#define kCCItemSize 32 - -#pragma mark - -#pragma mark CCMenuItem -/** CCMenuItem base class - * - * Subclass CCMenuItem (or any subclass) to create your custom CCMenuItem objects. - */ -@interface CCMenuItem : CCNode -{ - // used for menu items using a block - void (^block_)(id sender); - - BOOL isEnabled_; - BOOL isSelected_; -} - -/** returns whether or not the item is selected -@since v0.8.2 -*/ -@property (nonatomic,readonly) BOOL isSelected; - -/** Creates a CCMenuItem with a target/selector. - target/selector will be implemented using blocks. - "target" won't be retained. - */ -+(id) itemWithTarget:(id)target selector:(SEL)selector; - -/** Creates a CCMenuItem with the specified block. - The block will be "copied". - */ -+(id) itemWithBlock:(void(^)(id sender))block; - -/** Initializes a CCMenuItem with a target/selector */ --(id) initWithTarget:(id)target selector:(SEL)selector; - -/** Initializes a CCMenuItem with the specified block. - The block will be "copied". -*/ --(id) initWithBlock:(void(^)(id sender))block; - -/** Returns the outside box in points */ --(CGRect) rect; - -/** Activate the item */ --(void) activate; - -/** The item was selected (not activated), similar to "mouse-over" */ --(void) selected; - -/** The item was unselected */ --(void) unselected; - -/** Enable or disabled the CCMenuItem */ --(void) setIsEnabled:(BOOL)enabled; - -/** Returns whether or not the CCMenuItem is enabled */ --(BOOL) isEnabled; - -/** Sets the block that is called when the item is tapped. - The block will be "copied". - */ --(void) setBlock:(void(^)(id sender))block; - -/** Sets the target and selector that is called when the item is tapped. - target/selector will be implemented using blocks. - "target" won't be retained. - */ --(void) setTarget:(id)target selector:(SEL)selector; - -/** cleanup event. It will release the block and call [super cleanup] */ --(void) cleanup; - -@end - -#pragma mark - -#pragma mark CCMenuItemLabel - -/** An abstract class for "label" CCMenuItemLabel items - Any CCNode that supports the CCLabelProtocol protocol can be added. - Supported nodes: - - CCLabelBMFont - - CCLabelAtlas - - CCLabelTTF - */ -@interface CCMenuItemLabel : CCMenuItem -{ - CCNode *label_; - ccColor3B colorBackup; - ccColor3B disabledColor_; - float originalScale_; -} - -/** the color that will be used to disable the item */ -@property (nonatomic,readwrite) ccColor3B disabledColor; - -/** Label that is rendered. It can be any CCNode that implements the CCLabelProtocol */ -@property (nonatomic,readwrite,assign) CCNode* label; - -/** creates a CCMenuItemLabel with a Label. Block will benil */ -+(id) itemWithLabel:(CCNode*)label; - -/** creates a CCMenuItemLabel with a Label, target and selector. - The "target" won't be retained. - */ -+(id) itemWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector; - -/** creates a CCMenuItemLabel with a Label and a block to execute. - The block will be "copied". - */ -+(id) itemWithLabel:(CCNode*)label block:(void(^)(id sender))block; - -/** initializes a CCMenuItemLabel with a Label, target and selector. - Internally it will create a block that executes the target/selector. - The "target" won't be retained. - */ --(id) initWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector; - -/** initializes a CCMenuItemLabel with a Label and a block to execute. - The block will be "copied". - This is the designated initializer. - */ --(id) initWithLabel:(CCNode*)label block:(void(^)(id sender))block; - -/** sets a new string to the inner label */ --(void) setString:(NSString*)label; - -/** Enable or disabled the CCMenuItemFont - @warning setIsEnabled changes the RGB color of the font - */ --(void) setIsEnabled: (BOOL)enabled; -@end - -#pragma mark - -#pragma mark CCMenuItemAtlasFont - -/** A CCMenuItemAtlasFont - Helper class that creates a CCMenuItemLabel class with a CCLabelAtlas - */ -@interface CCMenuItemAtlasFont : CCMenuItemLabel -{ -} - -/** creates a menu item from a string and atlas with a target/selector */ -+(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap; - -/** creates a menu item from a string and atlas. Use it with CCMenuItemToggle. - The "target" won't be retained. - */ -+(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id)target selector:(SEL)selector; - -/** initializes a menu item from a string and atlas with a target/selector. - The "target" won't be retained. - */ --(id) initWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id)target selector:(SEL)selector; - -/** creates a menu item from a string and atlas. Use it with CCMenuItemToggle. - The block will be "copied". - */ -+(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block; - -/** initializes a menu item from a string and atlas with a block. - The block will be "copied". - */ --(id) initWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block; - -@end - -#pragma mark - -#pragma mark CCMenuItemFont - -/** A CCMenuItemFont - Helper class that creates a CCMenuItemLabel class with a Label - */ -@interface CCMenuItemFont : CCMenuItemLabel -{ - NSUInteger fontSize_; - NSString *fontName_; -} -/** set default font size */ -+(void) setFontSize: (NSUInteger) s; - -/** get default font size */ -+(NSUInteger) fontSize; - -/** set default font name */ -+(void) setFontName: (NSString*) n; - -/** get default font name */ -+(NSString*) fontName; - -/** creates a menu item from a string without target/selector. To be used with CCMenuItemToggle */ -+(id) itemWithString: (NSString*) value; - -/** creates a menu item from a string with a target/selector. - The "target" won't be retained. - */ -+(id) itemWithString: (NSString*) value target:(id) r selector:(SEL) s; - -/** creates a menu item from a string with the specified block. - The block will be "copied". - */ -+(id) itemWithString: (NSString*) value block:(void(^)(id sender))block; - -/** initializes a menu item from a string with a target/selector - The "target" won't be retained. - */ --(id) initWithString: (NSString*) value target:(id) r selector:(SEL) s; - -/** set font size */ --(void) setFontSize: (NSUInteger) s; - -/** get font size */ --(NSUInteger) fontSize; - -/** set the font name */ --(void) setFontName: (NSString*) n; - -/** get the font name */ --(NSString*) fontName; - -/** initializes a menu item from a string with the specified block. - The block will be "copied". - */ --(id) initWithString: (NSString*) value block:(void(^)(id sender))block; - -@end - -#pragma mark - -#pragma mark CCMenuItemSprite - -/** CCMenuItemSprite accepts CCNode objects as items. - The images has 3 different states: - - unselected image - - selected image - - disabled image - - @since v0.8.0 - */ -@interface CCMenuItemSprite : CCMenuItem -{ - CCNode *normalImage_, *selectedImage_, *disabledImage_; -} - -// weak references - -/** the image used when the item is not selected */ -@property (nonatomic,readwrite,assign) CCNode *normalImage; -/** the image used when the item is selected */ -@property (nonatomic,readwrite,assign) CCNode *selectedImage; -/** the image used when the item is disabled */ -@property (nonatomic,readwrite,assign) CCNode *disabledImage; - -/** creates a menu item with a normal and selected image*/ -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite; -/** creates a menu item with a normal and selected image with target/selector. - The "target" won't be retained. - */ -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector; - -/** creates a menu item with a normal,selected and disabled image with target/selector. - The "target" won't be retained. - */ -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector; - -/** creates a menu item with a normal and selected image with a block. - The block will be "copied". - */ -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block; - -/** creates a menu item with a normal,selected and disabled image with a block. - The block will be "copied". - */ -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block; - -/** initializes a menu item with a normal, selected and disabled image with target/selector. - The "target" won't be retained. - */ --(id) initWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector; - -/** initializes a menu item with a normal, selected and disabled image with a block. - The block will be "copied". - */ --(id) initWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block; - -@end - -#pragma mark - -#pragma mark CCMenuItemImage - -/** CCMenuItemImage accepts images as items. - The images has 3 different states: - - unselected image - - selected image - - disabled image - - For best results try that all images are of the same size - */ -@interface CCMenuItemImage : CCMenuItemSprite -{ -} - -/** creates a menu item with a normal and selected image*/ -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2; - -/** creates a menu item with a normal and selected image with target/selector */ -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) r selector:(SEL) s; - -/** creates a menu item with a normal,selected and disabled image with target/selector. - The "target" won't be retained. - */ -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s; - -/** creates a menu item with a normal and selected image with a block. - The block will be "copied". - */ -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block; - -/** creates a menu item with a normal,selected and disabled image with a block. - The block will be "copied". -*/ -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block; - -/** initializes a menu item with a normal, selected and disabled image with target/selector. - The "target" won't be retained. - */ --(id) initWithNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s; - -/** initializes a menu item with a normal, selected and disabled image with a block. - The block will be "copied". -*/ --(id) initWithNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block; - -/** sets the sprite frame for the normal image */ -- (void) setNormalSpriteFrame:(CCSpriteFrame*)frame; - -/** sets the sprite frame for the selected image */ -- (void) setSelectedSpriteFrame:(CCSpriteFrame*)frame; - -/** sets the sprite frame for the disabled image */ -- (void) setDisabledSpriteFrame:(CCSpriteFrame*)frame; - -@end - -#pragma mark - -#pragma mark CCMenuItemToggle - -/** A CCMenuItemToggle - A simple container class that "toggles" its inner items - The inner itmes can be any MenuItem - */ -@interface CCMenuItemToggle : CCMenuItem -{ - NSUInteger selectedIndex_; - NSMutableArray* subItems_; - GLubyte opacity_; - ccColor3B color_; -} - -/** conforms with CCRGBAProtocol protocol */ -@property (nonatomic,readonly) GLubyte opacity; -/** conforms with CCRGBAProtocol protocol */ -@property (nonatomic,readonly) ccColor3B color; - -/** returns the selected item */ -@property (nonatomic,readwrite) NSUInteger selectedIndex; -/** NSMutableArray that contains the subitems. You can add/remove items in runtime, and you can replace the array with a new one. - @since v0.7.2 - */ -@property (nonatomic,readwrite,retain) NSMutableArray *subItems; - -/** creates a menu item from a list of items with a target/selector */ -+(id) itemWithTarget:(id)target selector:(SEL)selector items:(CCMenuItem*) item, ... NS_REQUIRES_NIL_TERMINATION; - -/** creates a menu item from a list of items and executes the given block when the item is selected. - The block will be "copied". - */ -+(id) itemWithItems:(NSArray*)arrayOfItems block:(void(^)(id sender))block; - -/** initializes a menu item from a list of items with a target selector */ --(id) initWithTarget:(id)target selector:(SEL)selector items:(CCMenuItem*) item vaList:(va_list) args; - -/** initializes a menu item from a list of items with a block. - The block will be "copied". - */ --(id) initWithItems:(NSArray*)arrayOfItems block:(void (^)(id))block; - -/** return the selected item */ --(CCMenuItem*) selectedItem; -@end - diff --git a/Example/libs/cocos2d/CCMenuItem.m b/Example/libs/cocos2d/CCMenuItem.m deleted file mode 100644 index de7fe40..0000000 --- a/Example/libs/cocos2d/CCMenuItem.m +++ /dev/null @@ -1,854 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCMenuItem.h" -#import "CCLabelTTF.h" -#import "CCLabelAtlas.h" -#import "CCActionInterval.h" -#import "CCSprite.h" -#import "Support/CGPointExtension.h" - -static NSUInteger _fontSize = kCCItemSize; -static NSString *_fontName = @"Marker Felt"; -static BOOL _fontNameRelease = NO; - - -const NSInteger kCCCurrentItemTag = 0xc0c05001; -const NSInteger kCCZoomActionTag = 0xc0c05002; - - -#pragma mark - -#pragma mark CCMenuItem - -@implementation CCMenuItem - -@synthesize isSelected=isSelected_; -+(id) itemWithTarget:(id) r selector:(SEL) s -{ - return [[[self alloc] initWithTarget:r selector:s] autorelease]; -} - -+(id) itemWithBlock:(void(^)(id sender))block { - return [[[self alloc] initWithBlock:block] autorelease]; -} - --(id) init -{ - return [self initWithBlock:nil]; -} - --(id) initWithTarget:(id)target selector:(SEL)selector -{ - // avoid retain cycle - __block id t = target; - return [self initWithBlock:^(id sender) { - - [t performSelector:selector withObject:sender]; - }]; - -} - - -// Designated initializer --(id) initWithBlock:(void (^)(id))block -{ - if((self=[super init]) ) { - - if( block ) - block_ = [block copy]; - - anchorPoint_ = ccp(0.5f, 0.5f); - isEnabled_ = YES; - isSelected_ = NO; - - } - return self; -} - --(void) dealloc -{ - [block_ release]; - - [super dealloc]; -} - --(void) cleanup -{ - [block_ release]; - block_ = nil; - - [super cleanup]; -} - --(void) selected -{ - isSelected_ = YES; -} - --(void) unselected -{ - isSelected_ = NO; -} - --(void) activate -{ - if(isEnabled_&& block_ ) - block_(self); -} - --(void) setIsEnabled: (BOOL)enabled -{ - isEnabled_ = enabled; -} - --(BOOL) isEnabled -{ - return isEnabled_; -} - --(CGRect) rect -{ - return CGRectMake( position_.x - contentSize_.width*anchorPoint_.x, - position_.y - contentSize_.height*anchorPoint_.y, - contentSize_.width, contentSize_.height); -} - --(void) setBlock:(void(^)(id sender))block -{ - [block_ release]; - block_ = [block copy]; -} - --(void) setTarget:(id)target selector:(SEL)selector -{ - [self setBlock:^(id sender) { - - [target performSelector:selector withObject:sender]; - }]; -} - -@end - - -#pragma mark - -#pragma mark CCMenuItemLabel - -@implementation CCMenuItemLabel - -@synthesize disabledColor = disabledColor_; - -+(id) itemWithLabel:(CCNode*)label -{ - return [[[self alloc] initWithLabel:label block:nil] autorelease]; -} - -+(id) itemWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector -{ - return [[[self alloc] initWithLabel:label target:target selector:selector] autorelease]; -} - -+(id) itemWithLabel:(CCNode*)label block:(void(^)(id sender))block { - return [[[self alloc] initWithLabel:label block:block] autorelease]; -} - - --(id) initWithLabel:(CCNode*)label target:(id)target selector:(SEL)selector -{ - // avoid retain cycle - __block id t = target; - - self = [self initWithLabel:label block: ^(id sender) { - [t performSelector:selector withObject:sender]; - } - ]; - return self; -} - -// -// Designated initializer -// --(id) initWithLabel:(CCNode *)label block:(void (^)(id))block -{ - if( (self=[self initWithBlock:block]) ) { - originalScale_ = 1; - colorBackup = ccWHITE; - disabledColor_ = ccc3( 126,126,126); - self.label = label; - } - - return self; -} - --(CCNode*) label -{ - return label_; -} --(void) setLabel:(CCNode*) label -{ - if( label != label_ ) { - [self removeChild:label_ cleanup:YES]; - [self addChild:label]; - - label_ = label; - label_.anchorPoint = ccp(0,0); - - [self setContentSize:[label_ contentSize]]; - } -} - --(void) setString:(NSString *)string -{ - [label_ setString:string]; - [self setContentSize: [label_ contentSize]]; -} - --(void) activate { - if(isEnabled_) { - [self stopAllActions]; - - self.scale = originalScale_; - - [super activate]; - } -} - --(void) selected -{ - // subclass to change the default action - if(isEnabled_) { - [super selected]; - - CCAction *action = [self getActionByTag:kCCZoomActionTag]; - if( action ) - [self stopAction:action]; - else - originalScale_ = self.scale; - - CCAction *zoomAction = [CCScaleTo actionWithDuration:0.1f scale:originalScale_ * 1.2f]; - zoomAction.tag = kCCZoomActionTag; - [self runAction:zoomAction]; - } -} - --(void) unselected -{ - // subclass to change the default action - if(isEnabled_) { - [super unselected]; - [self stopActionByTag:kCCZoomActionTag]; - CCAction *zoomAction = [CCScaleTo actionWithDuration:0.1f scale:originalScale_]; - zoomAction.tag = kCCZoomActionTag; - [self runAction:zoomAction]; - } -} - --(void) setIsEnabled: (BOOL)enabled -{ - if( isEnabled_ != enabled ) { - if(enabled == NO) { - colorBackup = [label_ color]; - [label_ setColor: disabledColor_]; - } - else - [label_ setColor:colorBackup]; - } - - [super setIsEnabled:enabled]; -} - -- (void) setOpacity: (GLubyte)opacity -{ - [label_ setOpacity:opacity]; -} --(GLubyte) opacity -{ - return [label_ opacity]; -} --(void) setColor:(ccColor3B)color -{ - [label_ setColor:color]; -} --(ccColor3B) color -{ - return [label_ color]; -} -@end - -#pragma mark - CCMenuItemAtlasFont - -@implementation CCMenuItemAtlasFont - -+(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap -{ - return [CCMenuItemAtlasFont itemWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:nil selector:nil]; -} - -+(id) itemWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id)target selector:(SEL)selector -{ - return [[[self alloc] initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:target selector:selector] autorelease]; -} - -+(id) itemWithString:(NSString*)value charMapFile:(NSString*)charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block -{ - return [[[self alloc] initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap block:block] autorelease]; -} - --(id) initWithString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id)target selector:(SEL)selector -{ - // avoid retain cycle - __block id t = target; - - return [self initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap block:^(id sender) { - [t performSelector:selector withObject:sender]; - } ]; -} - -// -// Designated initializer -// --(id) initWithString:(NSString*)value charMapFile:(NSString*)charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block -{ - NSAssert( [value length] > 0, @"value length must be greater than 0"); - - CCLabelAtlas *label = [[CCLabelAtlas alloc] initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap]; - - id ret = [self initWithLabel:label block:block]; - - [label release]; - - return ret; - -} - --(void) dealloc -{ - [super dealloc]; -} -@end - - -#pragma mark - CCMenuItemFont - -@implementation CCMenuItemFont - -+(void) setFontSize: (NSUInteger) s -{ - _fontSize = s; -} - -+(NSUInteger) fontSize -{ - return _fontSize; -} - -+(void) setFontName: (NSString*) n -{ - if( _fontNameRelease ) - [_fontName release]; - - _fontName = [n retain]; - _fontNameRelease = YES; -} - -+(NSString*) fontName -{ - return _fontName; -} - -+(id) itemWithString: (NSString*) value target:(id) r selector:(SEL) s -{ - return [[[self alloc] initWithString: value target:r selector:s] autorelease]; -} - -+(id) itemWithString: (NSString*) value -{ - return [[[self alloc] initWithString: value target:nil selector:nil] autorelease]; -} - -+(id) itemWithString: (NSString*) value block:(void(^)(id sender))block -{ - return [[[self alloc] initWithString:value block:block] autorelease]; -} - --(id) initWithString: (NSString*) value target:(id)target selector:(SEL)selector -{ - // avoid retain cycle - __block id t = target; - - return [self initWithString:value block:^(id sender) { - [t performSelector:selector withObject:sender]; - }]; -} - -// -// Designated initializer -// --(id) initWithString: (NSString*)string block:(void(^)(id sender))block -{ - NSAssert( [string length] > 0, @"Value length must be greater than 0"); - - fontName_ = [_fontName copy]; - fontSize_ = _fontSize; - - CCLabelTTF *label = [CCLabelTTF labelWithString:string fontName:fontName_ fontSize:fontSize_]; - - if((self=[super initWithLabel:label block:block]) ) { - // do something ? - } - - return self; -} - --(void) recreateLabel -{ - CCLabelTTF *label = [[CCLabelTTF alloc] initWithString:[label_ string] fontName:fontName_ fontSize:fontSize_]; - self.label = label; - [label release]; -} - --(void) setFontSize: (NSUInteger) size -{ - fontSize_ = size; - [self recreateLabel]; -} - --(NSUInteger) fontSize -{ - return fontSize_; -} - --(void) setFontName: (NSString*) fontName -{ - if (fontName_) - [fontName_ release]; - - fontName_ = [fontName copy]; - [self recreateLabel]; -} - --(NSString*) fontName -{ - return fontName_; -} -@end - -#pragma mark - CCMenuItemSprite - -@implementation CCMenuItemSprite - -@synthesize normalImage=normalImage_, selectedImage=selectedImage_, disabledImage=disabledImage_; - -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite -{ - return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:nil target:nil selector:nil]; -} - -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector -{ - return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:nil target:target selector:selector]; -} - -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector -{ - return [[[self alloc] initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite target:target selector:selector] autorelease]; -} - -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block -{ - return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:nil block:block]; -} - -+(id) itemWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block -{ - return [[[self alloc] initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:block] autorelease]; -} - --(id) initWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector -{ - // avoid retain cycle - __block id t = target; - - return [self initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:^(id sender) { - [t performSelector:selector withObject:sender]; - } ]; -} - -// -// Designated initializer -// --(id) initWithNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block -{ - if ( (self = [super initWithBlock:block] ) ) { - - self.normalImage = normalSprite; - self.selectedImage = selectedSprite; - self.disabledImage = disabledSprite; - - [self setContentSize: [normalImage_ contentSize]]; - } - return self; -} - --(void) setNormalImage:(CCNode *)image -{ - if( image != normalImage_ ) { - image.anchorPoint = ccp(0,0); - image.visible = YES; - - [self removeChild:normalImage_ cleanup:YES]; - [self addChild:image]; - - normalImage_ = image; - - [self setContentSize: [normalImage_ contentSize]]; - } -} - --(void) setSelectedImage:(CCNode *)image -{ - if( image != selectedImage_ ) { - image.anchorPoint = ccp(0,0); - image.visible = NO; - - [self removeChild:selectedImage_ cleanup:YES]; - [self addChild:image]; - - selectedImage_ = image; - } -} - --(void) setDisabledImage:(CCNode *)image -{ - if( image != disabledImage_ ) { - image.anchorPoint = ccp(0,0); - image.visible = NO; - - [self removeChild:disabledImage_ cleanup:YES]; - [self addChild:image]; - - disabledImage_ = image; - } -} - -#pragma mark CCMenuItemSprite - CCRGBAProtocol protocol - -- (void) setOpacity: (GLubyte)opacity -{ - [normalImage_ setOpacity:opacity]; - [selectedImage_ setOpacity:opacity]; - [disabledImage_ setOpacity:opacity]; -} - --(void) setColor:(ccColor3B)color -{ - [normalImage_ setColor:color]; - [selectedImage_ setColor:color]; - [disabledImage_ setColor:color]; -} - --(GLubyte) opacity -{ - return [normalImage_ opacity]; -} - --(ccColor3B) color -{ - return [normalImage_ color]; -} - --(void) selected -{ - [super selected]; - - if( selectedImage_ ) { - [normalImage_ setVisible:NO]; - [selectedImage_ setVisible:YES]; - [disabledImage_ setVisible:NO]; - - } else { // there is not selected image - - [normalImage_ setVisible:YES]; - [selectedImage_ setVisible:NO]; - [disabledImage_ setVisible:NO]; - } -} - --(void) unselected -{ - [super unselected]; - [normalImage_ setVisible:YES]; - [selectedImage_ setVisible:NO]; - [disabledImage_ setVisible:NO]; -} - --(void) setIsEnabled:(BOOL)enabled -{ - [super setIsEnabled:enabled]; - - if( enabled ) { - [normalImage_ setVisible:YES]; - [selectedImage_ setVisible:NO]; - [disabledImage_ setVisible:NO]; - - } else { - if( disabledImage_ ) { - [normalImage_ setVisible:NO]; - [selectedImage_ setVisible:NO]; - [disabledImage_ setVisible:YES]; - } else { - [normalImage_ setVisible:YES]; - [selectedImage_ setVisible:NO]; - [disabledImage_ setVisible:NO]; - } - } -} - -@end - -#pragma mark - CCMenuItemImage - -@implementation CCMenuItemImage - -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 -{ - return [self itemWithNormalImage:value selectedImage:value2 disabledImage: nil target:nil selector:nil]; -} - -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) t selector:(SEL) s -{ - return [self itemWithNormalImage:value selectedImage:value2 disabledImage: nil target:t selector:s]; -} - -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage: (NSString*) value3 -{ - return [[[self alloc] initWithNormalImage:value selectedImage:value2 disabledImage:value3 target:nil selector:nil] autorelease]; -} - -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage: (NSString*) value3 target:(id) t selector:(SEL) s -{ - return [[[self alloc] initWithNormalImage:value selectedImage:value2 disabledImage:value3 target:t selector:s] autorelease]; -} - -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block -{ - return [self itemWithNormalImage:value selectedImage:value2 disabledImage:nil block:block]; -} - -+(id) itemWithNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block -{ - return [[[self alloc] initWithNormalImage:value selectedImage:value2 disabledImage:value3 block:block] autorelease]; -} - --(id) initWithNormalImage: (NSString*) normalI selectedImage:(NSString*)selectedI disabledImage: (NSString*) disabledI target:(id)target selector:(SEL)selector -{ - // avoid retain cycle - __block id t = target; - - return [self initWithNormalImage:normalI selectedImage:selectedI disabledImage:disabledI block:^(id sender) { - [t performSelector:selector withObject:sender]; - }]; -} - - -// -// Designated initializer -// --(id) initWithNormalImage:(NSString*)normalI selectedImage:(NSString*)selectedI disabledImage:(NSString*)disabledI block:(void(^)(id sender))block -{ - CCNode *normalImage = [CCSprite spriteWithFile:normalI]; - CCNode *selectedImage = nil; - CCNode *disabledImage = nil; - - if( selectedI ) - selectedImage = [CCSprite spriteWithFile:selectedI]; - if(disabledI) - disabledImage = [CCSprite spriteWithFile:disabledI]; - - return [super initWithNormalSprite:normalImage selectedSprite:selectedImage disabledSprite:disabledImage block:block]; -} - -// -// Setter of sprite frames -// --(void) setNormalSpriteFrame:(CCSpriteFrame *)frame -{ - [self setNormalImage:[CCSprite spriteWithSpriteFrame:frame]]; -} - --(void) setSelectedSpriteFrame:(CCSpriteFrame *)frame -{ - [self setSelectedImage:[CCSprite spriteWithSpriteFrame:frame]]; -} - --(void) setDisabledSpriteFrame:(CCSpriteFrame *)frame -{ - [self setDisabledImage:[CCSprite spriteWithSpriteFrame:frame]]; -} - -@end - -#pragma mark - CCMenuItemToggle - -// -// MenuItemToggle -// -@implementation CCMenuItemToggle - -@synthesize subItems = subItems_; -@synthesize opacity = opacity_, color = color_; - -+(id) itemWithTarget: (id)t selector: (SEL)sel items: (CCMenuItem*) item, ... -{ - va_list args; - va_start(args, item); - - id s = [[[self alloc] initWithTarget: t selector:sel items: item vaList:args] autorelease]; - - va_end(args); - return s; -} - -+(id) itemWithItems:(NSArray*)arrayOfItems block:(void(^)(id))block -{ - return [[[self alloc] initWithItems:arrayOfItems block:block] autorelease]; -} - --(id) initWithTarget:(id)target selector:(SEL)selector items:(CCMenuItem*) item vaList: (va_list) args -{ - NSMutableArray *array = [NSMutableArray arrayWithCapacity:2]; - - int z = 0; - CCMenuItem *i = item; - while(i) { - z++; - [array addObject:i]; - i = va_arg(args, CCMenuItem*); - } - - // avoid retain cycle - __block id t = target; - - return [self initWithItems:array block:^(id sender) { - [t performSelector:selector withObject:sender]; - } - ]; -} - --(id) initWithItems:(NSArray*)arrayOfItems block:(void(^)(id sender))block -{ - if( (self=[super initWithBlock:block] ) ) { - - self.subItems = [NSMutableArray arrayWithArray:arrayOfItems]; - - selectedIndex_ = NSUIntegerMax; - [self setSelectedIndex:0]; - } - - return self; -} - --(void) dealloc -{ - [subItems_ release]; - [super dealloc]; -} - --(void)setSelectedIndex:(NSUInteger)index -{ - if( index != selectedIndex_ ) { - selectedIndex_=index; - CCMenuItem *currentItem = (CCMenuItem*)[self getChildByTag:kCCCurrentItemTag]; - if( currentItem ) - [currentItem removeFromParentAndCleanup:NO]; - - CCMenuItem *item = [subItems_ objectAtIndex:selectedIndex_]; - [self addChild:item z:0 tag:kCCCurrentItemTag]; - - CGSize s = [item contentSize]; - [self setContentSize: s]; - item.position = ccp( s.width/2, s.height/2 ); - } -} - --(NSUInteger) selectedIndex -{ - return selectedIndex_; -} - - --(void) selected -{ - [super selected]; - [[subItems_ objectAtIndex:selectedIndex_] selected]; -} - --(void) unselected -{ - [super unselected]; - [[subItems_ objectAtIndex:selectedIndex_] unselected]; -} - --(void) activate -{ - // update index - if( isEnabled_ ) { - NSUInteger newIndex = (selectedIndex_ + 1) % [subItems_ count]; - [self setSelectedIndex:newIndex]; - - } - - [super activate]; -} - --(void) setIsEnabled: (BOOL)enabled -{ - [super setIsEnabled:enabled]; - for(CCMenuItem* item in subItems_) - [item setIsEnabled:enabled]; -} - --(CCMenuItem*) selectedItem -{ - return [subItems_ objectAtIndex:selectedIndex_]; -} - -#pragma mark CCMenuItemToggle - CCRGBAProtocol protocol - -- (void) setOpacity: (GLubyte)opacity -{ - opacity_ = opacity; - for(CCMenuItem* item in subItems_) - [item setOpacity:opacity]; -} - -- (void) setColor:(ccColor3B)color -{ - color_ = color; - for(CCMenuItem* item in subItems_) - [item setColor:color]; -} - -@end diff --git a/Example/libs/cocos2d/CCMotionStreak.h b/Example/libs/cocos2d/CCMotionStreak.h deleted file mode 100644 index cf8a627..0000000 --- a/Example/libs/cocos2d/CCMotionStreak.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2011 ForzeField Studios S.L. http://forzefield.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import -#import "CCTexture2D.h" -#import "ccTypes.h" -#import "CCNode.h" - -/** MotionStreak. - Creates a trailing path. - */ -@interface CCMotionStreak : CCNode -{ - CCTexture2D *texture_; - CGPoint positionR_; - ccColor3B color_; - ccBlendFunc blendFunc_; - float stroke_; - float fadeDelta_; - float minSeg_; - - NSUInteger maxPoints_; - NSUInteger nuPoints_; - - /** Pointers */ - CGPoint *pointVertexes_; - float *pointState_; - - // Opengl - ccVertex2F *vertices_; - unsigned char *colorPointer_; - ccTex2F *texCoords_; - - BOOL fastMode_; -} -/** blending function */ -@property (nonatomic, readwrite, assign) ccBlendFunc blendFunc; - -/** When fast mode is enbled, new points are added faster but with lower precision */ -@property (nonatomic, readwrite, assign, getter = isFastMode) BOOL fastMode; - -/** texture used for the motion streak */ -@property (nonatomic, retain) CCTexture2D *texture; - -/** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename */ -+ (id) streakWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color textureFilename:(NSString*)path; -/** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture */ -+ (id) streakWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color texture:(CCTexture2D*)texture; - -/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ -- (id) initWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color textureFilename:(NSString*)path; -/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ -- (id) initWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color texture:(CCTexture2D*)texture; - -/** color used for the tint */ -- (void) tintWithColor:(ccColor3B)colors; - -/** Remove all living segments of the ribbon */ -- (void) reset; - -@end diff --git a/Example/libs/cocos2d/CCMotionStreak.m b/Example/libs/cocos2d/CCMotionStreak.m deleted file mode 100644 index 1350005..0000000 --- a/Example/libs/cocos2d/CCMotionStreak.m +++ /dev/null @@ -1,272 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2011 ForzeField Studios S.L. http://forzefield.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCMotionStreak.h" -#import "CCTextureCache.h" -#import "ccGLStateCache.h" -#import "CCGLProgram.h" -#import "CCShaderCache.h" -#import "ccMacros.h" - -#import "Support/CCVertex.h" -#import "Support/CGPointExtension.h" - - -@implementation CCMotionStreak -@synthesize texture = texture_; -@synthesize blendFunc = blendFunc_; -@synthesize fastMode = fastMode_; - -+ (id) streakWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color textureFilename:(NSString*)path -{ - return [[[self alloc] initWithFade:fade minSeg:minSeg width:stroke color:color textureFilename:path] autorelease]; -} - -+ (id) streakWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color texture:(CCTexture2D*)texture -{ - return [[[self alloc] initWithFade:fade minSeg:minSeg width:stroke color:color texture:texture] autorelease]; -} - -- (id) initWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color textureFilename:(NSString*)path -{ - NSAssert(path != nil, @"Invalid filename"); - - CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:path]; - return [self initWithFade:fade minSeg:minSeg width:stroke color:color texture:texture]; -} - -- (id) initWithFade:(float)fade minSeg:(float)minSeg width:(float)stroke color:(ccColor3B)color texture:(CCTexture2D*)texture -{ - self = [super init]; - if (self) - { - [super setPosition:CGPointZero]; - [self setAnchorPoint:CGPointZero]; - [self setIsRelativeAnchorPoint:NO]; - - positionR_ = CGPointZero; - fastMode_ = YES; - minSeg_ = (minSeg == -1.0f) ? stroke/5.0f : minSeg; - minSeg_ *= minSeg_; - - stroke_ = stroke; - fadeDelta_ = 1.0f/fade; - - maxPoints_ = (int)(fade*60.0f)+2; - nuPoints_ = 0; - pointState_ = malloc(sizeof(float) * maxPoints_); - pointVertexes_ = malloc(sizeof(CGPoint) * maxPoints_); - - vertices_ = malloc(sizeof(ccVertex2F) * maxPoints_ * 2); - texCoords_ = malloc(sizeof(ccTex2F) * maxPoints_ * 2); - colorPointer_ = malloc(sizeof(GLubyte) * maxPoints_ * 2 * 4); - - // Set blend mode - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; - - // shader program - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; - - [self setTexture:texture]; - [self setColor:color]; - [self scheduleUpdate]; - } - return self; -} - -#pragma mark - - -- (void) setPosition:(CGPoint)position -{ - positionR_ = position; -} - -- (void) tintWithColor:(ccColor3B)colors -{ - [self setColor:colors]; - - // Fast assignation - for(int i = 0; i0) - { - // Move data - pointState_[newIdx] = pointState_[i]; - - // Move point - pointVertexes_[newIdx] = pointVertexes_[i]; - - // Move vertices - i2 = i*2; - newIdx2 = newIdx*2; - vertices_[newIdx2] = vertices_[i2]; - vertices_[newIdx2+1] = vertices_[i2+1]; - - // Move color - i2 *= 4; - newIdx2 *= 4; - colorPointer_[newIdx2+0] = colorPointer_[i2+0]; - colorPointer_[newIdx2+1] = colorPointer_[i2+1]; - colorPointer_[newIdx2+2] = colorPointer_[i2+2]; - colorPointer_[newIdx2+4] = colorPointer_[i2+4]; - colorPointer_[newIdx2+5] = colorPointer_[i2+5]; - colorPointer_[newIdx2+6] = colorPointer_[i2+6]; - }else - newIdx2 = newIdx*8; - - const GLubyte op = pointState_[newIdx] * 255.0f; - colorPointer_[newIdx2+3] = op; - colorPointer_[newIdx2+7] = op; - } - } - nuPoints_-=mov; - - // Append new point - BOOL appendNewPoint = YES; - if(nuPoints_ >= maxPoints_) - appendNewPoint = NO; - - else if(nuPoints_>0) - { - BOOL a1 = ccpDistanceSQ(pointVertexes_[nuPoints_-1], positionR_) < minSeg_; - BOOL a2 = (nuPoints_ == 1) ? NO : (ccpDistanceSQ(pointVertexes_[nuPoints_-2], positionR_) < (minSeg_ * 2.0f)); - if(a1 || a2) - appendNewPoint = NO; - } - - if(appendNewPoint) - { - pointVertexes_[nuPoints_] = positionR_; - pointState_[nuPoints_] = 1.0f; - - // Color asignation - const NSUInteger offset = nuPoints_*8; - *((ccColor3B*)(colorPointer_ + offset)) = color_; - *((ccColor3B*)(colorPointer_ + offset+4)) = color_; - - // Opacity - colorPointer_[offset+3] = 255; - colorPointer_[offset+7] = 255; - - // Generate polygon - if(nuPoints_ > 0 && fastMode_ ) - { - if(nuPoints_ > 1) - ccVertexLineToPolygon(pointVertexes_, stroke_, vertices_, texCoords_, nuPoints_, 1); - else - ccVertexLineToPolygon(pointVertexes_, stroke_, vertices_, texCoords_, 0, 2); - } - - nuPoints_ ++; - } - - if( ! fastMode_ ) - ccVertexLineToPolygon(pointVertexes_, stroke_, vertices_, texCoords_, 0, nuPoints_); -} - -- (void) reset -{ - nuPoints_ = 0; -} - -- (void) draw -{ - if(nuPoints_ <= 1) - return; - - CC_NODE_DRAW_SETUP(); - - ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex ); - ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); - - ccGLBindTexture2D( [texture_ name] ); - - glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices_); - glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, texCoords_); - glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colorPointer_); - - glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)nuPoints_*2); - - CC_INCREMENT_GL_DRAWS(1); -} - -- (void)dealloc -{ - [texture_ release]; - - free(pointState_); - free(pointVertexes_); - free(vertices_); - free(colorPointer_); - free(texCoords_); - - [super dealloc]; -} - -@end diff --git a/Example/libs/cocos2d/CCNode.h b/Example/libs/cocos2d/CCNode.h deleted file mode 100644 index 028c285..0000000 --- a/Example/libs/cocos2d/CCNode.h +++ /dev/null @@ -1,571 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "Platforms/CCGL.h" -#import "ccTypes.h" -#import "CCProtocols.h" -#import "ccConfig.h" -#import "ccGLStateCache.h" -#import "Support/CCArray.h" -#import "kazmath/kazmath.h" - -enum { - kCCNodeTagInvalid = -1, -}; - -@class CCCamera; -@class CCGridBase; -@class CCGLProgram; -@class CCScheduler; -@class CCActionManager; -@class CCAction; - -/** CCNode is the main element. Anything thats gets drawn or contains things that get drawn is a CCNode. - The most popular CCNodes are: CCScene, CCLayer, CCSprite, CCMenu. - - The main features of a CCNode are: - - They can contain other CCNode nodes (addChild, getChildByTag, removeChild, etc) - - They can schedule periodic callback (schedule, unschedule, etc) - - They can execute actions (runAction, stopAction, etc) - - Some CCNode nodes provide extra functionality for them or their children. - - Subclassing a CCNode usually means (one/all) of: - - overriding init to initialize resources and schedule callbacks - - create callbacks to handle the advancement of time - - overriding draw to render the node - - Features of CCNode: - - position - - scale (x, y) - - rotation (in degrees, clockwise) - - CCCamera (an interface to gluLookAt ) - - CCGridBase (to do mesh transformations) - - anchor point - - size - - visible - - z-order - - openGL z position - - Default values: - - rotation: 0 - - position: (x=0,y=0) - - scale: (x=1,y=1) - - contentSize: (x=0,y=0) - - anchorPoint: (x=0,y=0) - - Limitations: - - A CCNode is a "void" object. It doesn't have a texture - - Order in transformations with grid disabled - -# The node will be translated (position) - -# The node will be rotated (rotation) - -# The node will be skewed (skewX, skewY) - -# The node will be scaled (scale, scaleX, scaleY) - -# The node will be moved according to the camera values (camera) - - Order in transformations with grid enabled - -# The node will be translated (position) - -# The node will be rotated (rotation) - -# The node will be skewed (skewX, skewY) - -# The node will be scaled (scale, scaleX, scaleY) - -# The grid will capture the screen - -# The node will be moved according to the camera values (camera) - -# The grid will render the captured screen - - Camera: - - Each node has a camera. By default it points to the center of the CCNode. - */ -@interface CCNode : NSObject -{ - // rotation angle - float rotation_; - - // scaling factors - float scaleX_, scaleY_; - - // openGL real Z vertex - float vertexZ_; - - // position of the node - CGPoint position_; - - // skew angles - float skewX_, skewY_; - - // anchor point in points - CGPoint anchorPointInPoints_; - // anchor point normalized (NOT in points) - CGPoint anchorPoint_; - - // untransformed size of the node - CGSize contentSize_; - - // transform - CGAffineTransform transform_, inverse_; - - // a Camera - CCCamera *camera_; - - // a Grid - CCGridBase *grid_; - - // z-order value - NSInteger zOrder_; - - // array of children - CCArray *children_; - - // weakref to parent - CCNode *parent_; - - // a tag. any number you want to assign to the node - NSInteger tag_; - - // user data field - void *userData_; - id userObject_; - - // Shader - CCGLProgram *shaderProgram_; - - // Server side state - ccGLServerState glServerState_; - - // used to preserve sequence while sorting children with the same zOrder - NSUInteger orderOfArrival_; - - // scheduler used to schedule timers and updates - CCScheduler *scheduler_; - - // ActionManager used to handle all the actions - CCActionManager *actionManager_; - - // Is running - BOOL isRunning_; - - BOOL isTransformDirty_; - BOOL isInverseDirty_; - - // is visible - BOOL visible_; - // If YES the transformtions will be relative to (-transform.x, -transform.y). - // Sprites, Labels and any other "small" object uses it. - // Scenes, Layers and other "whole screen" object don't use it. - BOOL isRelativeAnchorPoint_; - - BOOL isReorderChildDirty_; -} - -/** The z order of the node relative to its "siblings": children of the same parent */ -@property(nonatomic,assign) NSInteger zOrder; -/** The real openGL Z vertex. - Differences between openGL Z vertex and cocos2d Z order: - - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children - - OpenGL Z might require to set 2D projection - - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: vertexZ = 0 - @warning: Use it at your own risk since it might break the cocos2d parent-children z order - @since v0.8 - */ -@property (nonatomic,readwrite) float vertexZ; - -/** The X skew angle of the node in degrees. - This angle describes the shear distortion in the X direction. - Thus, it is the angle between the Y axis and the left edge of the shape - The default skewX angle is 0. Positive values distort the node in a CW direction. - */ -@property(nonatomic,readwrite,assign) float skewX; - -/** The Y skew angle of the node in degrees. - This angle describes the shear distortion in the Y direction. - Thus, it is the angle between the X axis and the bottom edge of the shape - The default skewY angle is 0. Positive values distort the node in a CCW direction. - */ -@property(nonatomic,readwrite,assign) float skewY; -/** The rotation (angle) of the node in degrees. 0 is the default rotation angle. Positive values rotate node CW. */ -@property(nonatomic,readwrite,assign) float rotation; -/** The scale factor of the node. 1.0 is the default scale factor. It modifies the X and Y scale at the same time. */ -@property(nonatomic,readwrite,assign) float scale; -/** The scale factor of the node. 1.0 is the default scale factor. It only modifies the X scale factor. */ -@property(nonatomic,readwrite,assign) float scaleX; -/** The scale factor of the node. 1.0 is the default scale factor. It only modifies the Y scale factor. */ -@property(nonatomic,readwrite,assign) float scaleY; -/** Position (x,y) of the node in points. (0,0) is the left-bottom corner. */ -@property(nonatomic,readwrite,assign) CGPoint position; -/** A CCCamera object that lets you move the node using a gluLookAt */ -@property(nonatomic,readonly) CCCamera* camera; -/** Array of children */ -@property(nonatomic,readonly) CCArray *children; -/** A CCGrid object that is used when applying effects */ -@property(nonatomic,readwrite,retain) CCGridBase* grid; -/** Whether of not the node is visible. Default is YES */ -@property(nonatomic,readwrite,assign) BOOL visible; -/** anchorPoint is the point around which all transformations and positioning manipulations take place. - It's like a pin in the node where it is "attached" to its parent. - The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner. - But you can use values higher than (1,1) and lower than (0,0) too. - The default anchorPoint is (0,0). It starts in the bottom-left corner. CCSprite and other subclasses have a different default anchorPoint. - @since v0.8 - */ -@property(nonatomic,readwrite) CGPoint anchorPoint; -/** The anchorPoint in absolute pixels. - Since v0.8 you can only read it. If you wish to modify it, use anchorPoint instead - */ -@property(nonatomic,readonly) CGPoint anchorPointInPoints; - -/** The untransformed size of the node in Points - The contentSize remains the same no matter the node is scaled or rotated. - All nodes has a size. Layer and Scene has the same size of the screen. - @since v0.8 - */ -@property (nonatomic,readwrite) CGSize contentSize; - -/** whether or not the node is running */ -@property(nonatomic,readonly) BOOL isRunning; -/** A weak reference to the parent */ -@property(nonatomic,readwrite,assign) CCNode* parent; -/** If YES the transformtions will be relative to its anchor point. - * Sprites, Labels and any other sizeble object use it have it enabled by default. - * Scenes, Layers and other "whole screen" object don't use it, have it disabled by default. - */ -@property(nonatomic,readwrite,assign) BOOL isRelativeAnchorPoint; -/** A tag used to identify the node easily */ -@property(nonatomic,readwrite,assign) NSInteger tag; -/** A custom user data pointer */ -@property(nonatomic,readwrite,assign) void* userData; -/** Similar to userData, but instead of holding a void* it holds an id */ -@property(nonatomic,readwrite,retain) id userObject; - -/** Shader Program - @since v2.0 - */ -@property(nonatomic,readwrite,retain) CCGLProgram *shaderProgram; - -/** used internally for zOrder sorting, don't change this manually */ -@property(nonatomic,readwrite) NSUInteger orderOfArrival; - -/** GL server side state - @since v2.0 -*/ -@property (nonatomic, readwrite) ccGLServerState glServerState; - -/** CCActionManager used by all the actions. - IMPORTANT: If you set a new CCActionManager, then previously created actions are going to be removed. - @since v2.0 - */ -@property (nonatomic, readwrite, retain) CCActionManager *actionManager; - -/** CCScheduler used to schedule all "updates" and timers. - IMPORTANT: If you set a new CCScheduler, then previously created timers/update are going to be removed. - @since v2.0 - */ -@property (nonatomic, readwrite, retain) CCScheduler *scheduler; - -// initializators -/** allocates and initializes a node. - The node will be created as "autorelease". - */ -+(id) node; -/** initializes the node */ --(id) init; - - -// scene managment - -/** Event that is called every time the CCNode enters the 'stage'. - If the CCNode enters the 'stage' with a transition, this event is called when the transition starts. - During onEnter you can't access a sibling node. - If you override onEnter, you shall call [super onEnter]. - */ --(void) onEnter; - -/** Event that is called when the CCNode enters in the 'stage'. - If the CCNode enters the 'stage' with a transition, this event is called when the transition finishes. - If you override onEnterTransitionDidFinish, you shall call [super onEnterTransitionDidFinish]. - @since v0.8 - */ --(void) onEnterTransitionDidFinish; - -/** Event that is called every time the CCNode leaves the 'stage'. - If the CCNode leaves the 'stage' with a transition, this event is called when the transition finishes. - During onExit you can't access a sibling node. - If you override onExit, you shall call [super onExit]. - */ --(void) onExit; - -/** callback that is called every time the CCNode leaves the 'stage'. - If the CCNode leaves the 'stage' with a transition, this callback is called when the transition starts. - */ --(void) onExitTransitionDidStart; - -// composition: ADD - -/** Adds a child to the container with z-order as 0. - If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - @since v0.7.1 - */ --(void) addChild: (CCNode*)node; - -/** Adds a child to the container with a z-order. - If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - @since v0.7.1 - */ --(void) addChild: (CCNode*)node z:(NSInteger)z; - -/** Adds a child to the container with z order and tag. - If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - @since v0.7.1 - */ --(void) addChild: (CCNode*)node z:(NSInteger)z tag:(NSInteger)tag; - -// composition: REMOVE - -/** Remove itself from its parent node. If cleanup is YES, then also remove all actions and callbacks. - If the node orphan, then nothing happens. - @since v0.99.3 - */ --(void) removeFromParentAndCleanup:(BOOL)cleanup; - -/** Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter. - @since v0.7.1 - */ --(void) removeChild: (CCNode*)node cleanup:(BOOL)cleanup; - -/** Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter - @since v0.7.1 - */ --(void) removeChildByTag:(NSInteger) tag cleanup:(BOOL)cleanup; - -/** Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter. - @since v0.7.1 - */ --(void) removeAllChildrenWithCleanup:(BOOL)cleanup; - -// composition: GET -/** Gets a child from the container given its tag - @return returns a CCNode object - @since v0.7.1 - */ --(CCNode*) getChildByTag:(NSInteger) tag; - -/** Reorders a child according to a new z value. - * The child MUST be already added. - */ --(void) reorderChild:(CCNode*)child z:(NSInteger)zOrder; - -/** performance improvement, Sort the children array once before drawing, instead of every time when a child is added or reordered - don't call this manually unless a child added needs to be removed in the same frame */ -- (void) sortAllChildren; - -/** Event that is called when the running node is no longer running (eg: its CCScene is being removed from the "stage" ). - On cleanup you should break any possible circular references. - CCNode's cleanup removes any possible scheduled timer and/or any possible action. - If you override cleanup, you shall call [super cleanup] - @since v0.8 - */ --(void) cleanup; - -// draw - -/** Override this method to draw your own node. - You should use cocos2d's GL API to enable/disable the GL state / shaders. - For further info, please see ccGLstate.h. - You shall NOT call [super draw]; - */ --(void) draw; - -/** recursive method that visit its children and draw them */ --(void) visit; - -// transformations - -/** performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes. */ --(void) transform; - -/** performs OpenGL view-matrix transformation of its ancestors. - Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO) it is necessary to transform the ancestors again. - @since v0.7.2 - */ --(void) transformAncestors; - -/** returns a "local" axis aligned bounding box of the node in points. - The returned box is relative only to its parent. - The returned box is in Points. - - @since v0.8.2 - */ -- (CGRect) boundingBox; - -// actions - -/** Executes an action, and returns the action that is executed. - The node becomes the action's target. - @warning Starting from v0.8 actions don't retain their target anymore. - @since v0.7.1 - @return An Action pointer - */ --(CCAction*) runAction: (CCAction*) action; -/** Removes all actions from the running action list */ --(void) stopAllActions; -/** Removes an action from the running action list */ --(void) stopAction: (CCAction*) action; -/** Removes an action from the running action list given its tag - @since v0.7.1 -*/ --(void) stopActionByTag:(NSInteger) tag; -/** Gets an action from the running action list given its tag - @since v0.7.1 - @return the Action the with the given tag - */ --(CCAction*) getActionByTag:(NSInteger) tag; -/** Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays). - * Composable actions are counted as 1 action. Example: - * If you are running 1 Sequence of 7 actions, it will return 1. - * If you are running 7 Sequences of 2 actions, it will return 7. - */ --(NSUInteger) numberOfRunningActions; - -// timers - -/** check whether a selector is scheduled. */ -//-(BOOL) isScheduled: (SEL) selector; - -/** schedules the "update" method. It will use the order number 0. This method will be called every frame. - Scheduled methods with a lower order value will be called before the ones that have a higher order value. - Only one "udpate" method could be scheduled per node. - - @since v0.99.3 - */ --(void) scheduleUpdate; - -/** schedules the "update" selector with a custom priority. This selector will be called every frame. - Scheduled selectors with a lower priority will be called before the ones that have a higher value. - Only one "udpate" selector could be scheduled per node (You can't have 2 'update' selectors). - - @since v0.99.3 - */ --(void) scheduleUpdateWithPriority:(NSInteger)priority; - -/* unschedules the "update" method. - - @since v0.99.3 - */ --(void) unscheduleUpdate; - - -/** schedules a selector. - The scheduled selector will be ticked every frame - */ --(void) schedule: (SEL) s; -/** schedules a custom selector with an interval time in seconds. - If time is 0 it will be ticked every frame. - If time is 0, it is recommended to use 'scheduleUpdate' instead. - - If the selector is already scheduled, then the interval parameter will be updated without scheduling it again. - */ --(void) schedule: (SEL) s interval:(ccTime)seconds; -/** - repeat will execute the action repeat + 1 times, for a continues action use kCCRepeatForever - delay is the amount of time the action will wait before execution - */ --(void) schedule:(SEL)selector interval:(ccTime)interval repeat: (uint) repeat delay:(ccTime) delay; - -/** - Schedules a selector that runs only once, with a delay of 0 or larger -*/ -- (void) scheduleOnce:(SEL) selector delay:(ccTime) delay; - -/** unschedules a custom selector.*/ --(void) unschedule: (SEL) s; - -/** unschedule all scheduled selectors: custom selectors, and the 'update' selector. - Actions are not affected by this method. -@since v0.99.3 - */ --(void) unscheduleAllSelectors; - -/** resumes all scheduled selectors and actions. - Called internally by onEnter - */ --(void) resumeSchedulerAndActions; -/** pauses all scheduled selectors and actions. - Called internally by onExit - */ --(void) pauseSchedulerAndActions; - - -// transformation methods - -/** Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates. - The matrix is in Pixels. - @since v0.7.1 - */ -- (CGAffineTransform)nodeToParentTransform; -/** Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates. - The matrix is in Pixels. - @since v0.7.1 - */ -- (CGAffineTransform)parentToNodeTransform; -/** Retrusn the world affine transform matrix. The matrix is in Pixels. - @since v0.7.1 - */ -- (CGAffineTransform)nodeToWorldTransform; -/** Returns the inverse world affine transform matrix. The matrix is in Pixels. - @since v0.7.1 - */ -- (CGAffineTransform)worldToNodeTransform; -/** Converts a Point to node (local) space coordinates. The result is in Points. - @since v0.7.1 - */ -- (CGPoint)convertToNodeSpace:(CGPoint)worldPoint; -/** Converts a Point to world space coordinates. The result is in Points. - @since v0.7.1 - */ -- (CGPoint)convertToWorldSpace:(CGPoint)nodePoint; -/** Converts a Point to node (local) space coordinates. The result is in Points. - treating the returned/received node point as anchor relative. - @since v0.7.1 - */ -- (CGPoint)convertToNodeSpaceAR:(CGPoint)worldPoint; -/** Converts a local Point to world space coordinates.The result is in Points. - treating the returned/received node point as anchor relative. - @since v0.7.1 - */ -- (CGPoint)convertToWorldSpaceAR:(CGPoint)nodePoint; - -#ifdef __CC_PLATFORM_IOS -/** Converts a UITouch to node (local) space coordinates. The result is in Points. - @since v0.7.1 - */ -- (CGPoint)convertTouchToNodeSpace:(UITouch *)touch; -/** Converts a UITouch to node (local) space coordinates. The result is in Points. - This method is AR (Anchor Relative).. - @since v0.7.1 - */ -- (CGPoint)convertTouchToNodeSpaceAR:(UITouch *)touch; -#endif // __CC_PLATFORM_IOS -@end diff --git a/Example/libs/cocos2d/CCNode.m b/Example/libs/cocos2d/CCNode.m deleted file mode 100644 index 9a70409..0000000 --- a/Example/libs/cocos2d/CCNode.m +++ /dev/null @@ -1,885 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "CCNode.h" -#import "CCGrid.h" -#import "CCDirector.h" -#import "CCActionManager.h" -#import "CCCamera.h" -#import "CCScheduler.h" -#import "ccConfig.h" -#import "ccMacros.h" -#import "Support/CGPointExtension.h" -#import "Support/ccCArray.h" -#import "Support/TransformUtils.h" -#import "ccMacros.h" -#import "CCGLProgram.h" - -// externals -#import "kazmath/GL/matrix.h" - -#ifdef __CC_PLATFORM_IOS -#import "Platforms/iOS/CCDirectorIOS.h" -#endif - - -#if CC_NODE_RENDER_SUBPIXEL -#define RENDER_IN_SUBPIXEL -#else -#define RENDER_IN_SUBPIXEL (NSInteger) -#endif - - -@interface CCNode () -// lazy allocs --(void) childrenAlloc; -// helper that reorder a child --(void) insertChild:(CCNode*)child z:(NSInteger)z; -// used internally to alter the zOrder variable. DON'T call this method manually --(void) _setZOrder:(NSInteger) z; --(void) detachChild:(CCNode *)child cleanup:(BOOL)doCleanup; -@end - -@implementation CCNode - -// XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. -static NSUInteger globalOrderOfArrival = 1; - -@synthesize children = children_; -@synthesize visible = visible_; -@synthesize parent = parent_; -@synthesize grid = grid_; -@synthesize zOrder = zOrder_; -@synthesize tag = tag_; -@synthesize vertexZ = vertexZ_; -@synthesize isRunning = isRunning_; -@synthesize userData = userData_, userObject = userObject_; -@synthesize shaderProgram = shaderProgram_; -@synthesize orderOfArrival = orderOfArrival_; -@synthesize glServerState = glServerState_; - -#pragma mark CCNode - Transform related properties - -@synthesize rotation = rotation_, scaleX = scaleX_, scaleY = scaleY_; -@synthesize position = position_; -@synthesize anchorPoint = anchorPoint_, anchorPointInPoints = anchorPointInPoints_; -@synthesize contentSize = contentSize_; -@synthesize isRelativeAnchorPoint = isRelativeAnchorPoint_; -@synthesize skewX = skewX_, skewY = skewY_; - -#pragma mark CCNode - Init & cleanup - -+(id) node -{ - return [[[self alloc] init] autorelease]; -} - --(id) init -{ - if ((self=[super init]) ) { - - isRunning_ = NO; - - skewX_ = skewY_ = 0.0f; - rotation_ = 0.0f; - scaleX_ = scaleY_ = 1.0f; - position_ = CGPointZero; - contentSize_ = CGSizeZero; - anchorPointInPoints_ = anchorPoint_ = CGPointZero; - - - // "whole screen" objects. like Scenes and Layers, should set isRelativeAnchorPoint to NO - isRelativeAnchorPoint_ = YES; - - isTransformDirty_ = isInverseDirty_ = YES; - - vertexZ_ = 0; - - grid_ = nil; - - visible_ = YES; - - tag_ = kCCNodeTagInvalid; - - zOrder_ = 0; - - // lazy alloc - camera_ = nil; - - // children (lazy allocs) - children_ = nil; - - // userData is always inited as nil - userData_ = NULL; - userObject_ = nil; - - //initialize parent to nil - parent_ = nil; - - shaderProgram_ = nil; - - orderOfArrival_ = 0; - - glServerState_ = CC_GL_BLEND; - - // set default scheduler and actionManager - CCDirector *director = [CCDirector sharedDirector]; - self.actionManager = [director actionManager]; - self.scheduler = [director scheduler]; - } - - return self; -} - -- (void)cleanup -{ - // actions - [self stopAllActions]; - [self unscheduleAllSelectors]; - - // timers - [children_ makeObjectsPerformSelector:@selector(cleanup)]; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Tag = %i>", [self class], self, tag_]; -} - -- (void) dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@", self); - - [actionManager_ release]; - [scheduler_ release]; - [camera_ release]; - [grid_ release]; - [shaderProgram_ release]; - [userObject_ release]; - - // children - CCNode *child; - CCARRAY_FOREACH(children_, child) - child.parent = nil; - - [children_ release]; - - [super dealloc]; -} - -#pragma mark Setters - -// getters synthesized, setters explicit --(void) setRotation: (float)newRotation -{ - rotation_ = newRotation; - isTransformDirty_ = isInverseDirty_ = YES; -} - --(void) setScaleX: (float)newScaleX -{ - scaleX_ = newScaleX; - isTransformDirty_ = isInverseDirty_ = YES; -} - --(void) setScaleY: (float)newScaleY -{ - scaleY_ = newScaleY; - isTransformDirty_ = isInverseDirty_ = YES; -} - --(void) setSkewX:(float)newSkewX -{ - skewX_ = newSkewX; - isTransformDirty_ = isInverseDirty_ = YES; -} - --(void) setSkewY:(float)newSkewY -{ - skewY_ = newSkewY; - isTransformDirty_ = isInverseDirty_ = YES; -} - --(void) setPosition: (CGPoint)newPosition -{ - position_ = newPosition; - isTransformDirty_ = isInverseDirty_ = YES; -} - --(void) setIsRelativeAnchorPoint: (BOOL)newValue -{ - isRelativeAnchorPoint_ = newValue; - isTransformDirty_ = isInverseDirty_ = YES; -} - --(void) setAnchorPoint:(CGPoint)point -{ - if( ! CGPointEqualToPoint(point, anchorPoint_) ) { - anchorPoint_ = point; - anchorPointInPoints_ = ccp( contentSize_.width * anchorPoint_.x, contentSize_.height * anchorPoint_.y ); - isTransformDirty_ = isInverseDirty_ = YES; - } -} - --(void) setContentSize:(CGSize)size -{ - if( ! CGSizeEqualToSize(size, contentSize_) ) { - contentSize_ = size; - - anchorPointInPoints_ = ccp( contentSize_.width * anchorPoint_.x, contentSize_.height * anchorPoint_.y ); - isTransformDirty_ = isInverseDirty_ = YES; - } -} - -- (CGRect) boundingBox -{ - CGRect rect = CGRectMake(0, 0, contentSize_.width, contentSize_.height); - return CGRectApplyAffineTransform(rect, [self nodeToParentTransform]); -} - --(void) setVertexZ:(float)vertexZ -{ - vertexZ_ = vertexZ; -} - --(float) scale -{ - NSAssert( scaleX_ == scaleY_, @"CCNode#scale. ScaleX != ScaleY. Don't know which one to return"); - return scaleX_; -} - --(void) setScale:(float) s -{ - scaleX_ = scaleY_ = s; - isTransformDirty_ = isInverseDirty_ = YES; -} - -- (void) setZOrder:(NSInteger)zOrder -{ - [self _setZOrder:zOrder]; - - if (parent_) - [parent_ reorderChild:self z:zOrder]; -} - -#pragma mark CCNode Composition - --(void) childrenAlloc -{ - children_ = [[CCArray alloc] initWithCapacity:4]; -} - -// camera: lazy alloc --(CCCamera*) camera -{ - if( ! camera_ ) { - camera_ = [[CCCamera alloc] init]; - - // by default, center camera at the Sprite's anchor point -// [camera_ setCenterX:anchorPointInPoints_.x centerY:anchorPointInPoints_.y centerZ:0]; -// [camera_ setEyeX:anchorPointInPoints_.x eyeY:anchorPointInPoints_.y eyeZ:1]; - -// [camera_ setCenterX:0 centerY:0 centerZ:0]; -// [camera_ setEyeX:0 eyeY:0 eyeZ:1]; - } - - return camera_; -} - --(CCNode*) getChildByTag:(NSInteger) aTag -{ - NSAssert( aTag != kCCNodeTagInvalid, @"Invalid tag"); - - CCNode *node; - CCARRAY_FOREACH(children_, node){ - if( node.tag == aTag ) - return node; - } - // not found - return nil; -} - -/* "add" logic MUST only be on this method - * If a class want's to extend the 'addChild' behaviour it only needs - * to override this method - */ --(void) addChild: (CCNode*) child z:(NSInteger)z tag:(NSInteger) aTag -{ - NSAssert( child != nil, @"Argument must be non-nil"); - NSAssert( child.parent == nil, @"child already added. It can't be added again"); - - if( ! children_ ) - [self childrenAlloc]; - - [self insertChild:child z:z]; - - child.tag = aTag; - - [child setParent: self]; - - [child setOrderOfArrival: globalOrderOfArrival++]; - - if( isRunning_ ) { - [child onEnter]; - [child onEnterTransitionDidFinish]; - } -} - --(void) addChild: (CCNode*) child z:(NSInteger)z -{ - NSAssert( child != nil, @"Argument must be non-nil"); - [self addChild:child z:z tag:child.tag]; -} - --(void) addChild: (CCNode*) child -{ - NSAssert( child != nil, @"Argument must be non-nil"); - [self addChild:child z:child.zOrder tag:child.tag]; -} - --(void) removeFromParentAndCleanup:(BOOL)cleanup -{ - [parent_ removeChild:self cleanup:cleanup]; -} - -/* "remove" logic MUST only be on this method - * If a class want's to extend the 'removeChild' behavior it only needs - * to override this method - */ --(void) removeChild: (CCNode*)child cleanup:(BOOL)cleanup -{ - // explicit nil handling - if (child == nil) - return; - - if ( [children_ containsObject:child] ) - [self detachChild:child cleanup:cleanup]; -} - --(void) removeChildByTag:(NSInteger)aTag cleanup:(BOOL)cleanup -{ - NSAssert( aTag != kCCNodeTagInvalid, @"Invalid tag"); - - CCNode *child = [self getChildByTag:aTag]; - - if (child == nil) - CCLOG(@"cocos2d: removeChildByTag: child not found!"); - else - [self removeChild:child cleanup:cleanup]; -} - --(void) removeAllChildrenWithCleanup:(BOOL)cleanup -{ - // not using detachChild improves speed here - CCNode *c; - CCARRAY_FOREACH(children_, c) - { - // IMPORTANT: - // -1st do onExit - // -2nd cleanup - if (isRunning_) - { - [c onExitTransitionDidStart]; - [c onExit]; - } - - if (cleanup) - [c cleanup]; - - // set parent nil at the end (issue #476) - [c setParent:nil]; - } - - [children_ removeAllObjects]; -} - --(void) detachChild:(CCNode *)child cleanup:(BOOL)doCleanup -{ - // IMPORTANT: - // -1st do onExit - // -2nd cleanup - if (isRunning_) - { - [child onExitTransitionDidStart]; - [child onExit]; - } - - // If you don't do cleanup, the child's actions will not get removed and the - // its scheduledSelectors_ dict will not get released! - if (doCleanup) - [child cleanup]; - - // set parent nil at the end (issue #476) - [child setParent:nil]; - - [children_ removeObject:child]; -} - -// used internally to alter the zOrder variable. DON'T call this method manually --(void) _setZOrder:(NSInteger) z -{ - zOrder_ = z; -} - -// helper used by reorderChild & add --(void) insertChild:(CCNode*)child z:(NSInteger)z -{ - isReorderChildDirty_=YES; - - ccArrayAppendObjectWithResize(children_->data, child); - [child _setZOrder:z]; -} - --(void) reorderChild:(CCNode*) child z:(NSInteger)z -{ - NSAssert( child != nil, @"Child must be non-nil"); - - isReorderChildDirty_ = YES; - - [child setOrderOfArrival: globalOrderOfArrival++]; - [child _setZOrder:z]; -} - -- (void) sortAllChildren -{ - if (isReorderChildDirty_) - { - NSInteger i,j,length = children_->data->num; - CCNode ** x = children_->data->arr; - CCNode *tempItem; - - // insertion sort - for(i=1; i=0 && ( tempItem.zOrder < x[j].zOrder || ( tempItem.zOrder== x[j].zOrder && tempItem.orderOfArrival < x[j].orderOfArrival ) ) ) - { - x[j+1] = x[j]; - j = j-1; - } - x[j+1] = tempItem; - } - - //don't need to check children recursively, that's done in visit of each child - - isReorderChildDirty_ = NO; - } -} - -#pragma mark CCNode Draw - --(void) draw -{ -} - --(void) visit -{ - // quick return if not visible. children won't be drawn. - if (!visible_) - return; - - kmGLPushMatrix(); - - if ( grid_ && grid_.active) - [grid_ beforeDraw]; - - [self transform]; - - if(children_) { - - [self sortAllChildren]; - - ccArray *arrayData = children_->data; - NSUInteger i = 0; - - // draw children zOrder < 0 - for( ; i < arrayData->num; i++ ) { - CCNode *child = arrayData->arr[i]; - if ( [child zOrder] < 0 ) - [child visit]; - else - break; - } - - // self draw - [self draw]; - - // draw children zOrder >= 0 - for( ; i < arrayData->num; i++ ) { - CCNode *child = arrayData->arr[i]; - [child visit]; - } - - } else - [self draw]; - - // reset for next frame - orderOfArrival_ = 0; - - if ( grid_ && grid_.active) - [grid_ afterDraw:self]; - - kmGLPopMatrix(); -} - -#pragma mark CCNode - Transformations - --(void) transformAncestors -{ - if( parent_ ) { - [parent_ transformAncestors]; - [parent_ transform]; - } -} - --(void) transform -{ - kmMat4 transfrom4x4; - - // Convert 3x3 into 4x4 matrix - CGAffineTransform tmpAffine = [self nodeToParentTransform]; - CGAffineToGL(&tmpAffine, transfrom4x4.mat); - - // Update Z vertex manually - transfrom4x4.mat[14] = vertexZ_; - - kmGLMultMatrix( &transfrom4x4 ); - - - // XXX: Expensive calls. Camera should be integrated into the cached affine matrix - if ( camera_ && !(grid_ && grid_.active) ) - { - BOOL translate = (anchorPointInPoints_.x != 0.0f || anchorPointInPoints_.y != 0.0f); - - if( translate ) - kmGLTranslatef(RENDER_IN_SUBPIXEL(anchorPointInPoints_.x), RENDER_IN_SUBPIXEL(anchorPointInPoints_.y), 0 ); - - [camera_ locate]; - - if( translate ) - kmGLTranslatef(RENDER_IN_SUBPIXEL(-anchorPointInPoints_.x), RENDER_IN_SUBPIXEL(-anchorPointInPoints_.y), 0 ); - } -} - -#pragma mark CCNode SceneManagement - --(void) onEnter -{ - [children_ makeObjectsPerformSelector:@selector(onEnter)]; - [self resumeSchedulerAndActions]; - - isRunning_ = YES; -} - --(void) onEnterTransitionDidFinish -{ - [children_ makeObjectsPerformSelector:@selector(onEnterTransitionDidFinish)]; -} - --(void) onExitTransitionDidStart -{ - [children_ makeObjectsPerformSelector:@selector(onExitTransitionDidStart)]; -} - --(void) onExit -{ - [self pauseSchedulerAndActions]; - isRunning_ = NO; - - [children_ makeObjectsPerformSelector:@selector(onExit)]; -} - -#pragma mark CCNode Actions - --(void) setActionManager:(CCActionManager *)actionManager -{ - if( actionManager != actionManager_ ) { - [self stopAllActions]; - [actionManager_ release]; - - actionManager_ = [actionManager retain]; - } -} - --(CCActionManager*) actionManager -{ - return actionManager_; -} - --(CCAction*) runAction:(CCAction*) action -{ - NSAssert( action != nil, @"Argument must be non-nil"); - - [actionManager_ addAction:action target:self paused:!isRunning_]; - return action; -} - --(void) stopAllActions -{ - [actionManager_ removeAllActionsFromTarget:self]; -} - --(void) stopAction: (CCAction*) action -{ - [actionManager_ removeAction:action]; -} - --(void) stopActionByTag:(NSInteger)aTag -{ - NSAssert( aTag != kCCActionTagInvalid, @"Invalid tag"); - [actionManager_ removeActionByTag:aTag target:self]; -} - --(CCAction*) getActionByTag:(NSInteger) aTag -{ - NSAssert( aTag != kCCActionTagInvalid, @"Invalid tag"); - return [actionManager_ getActionByTag:aTag target:self]; -} - --(NSUInteger) numberOfRunningActions -{ - return [actionManager_ numberOfRunningActionsInTarget:self]; -} - -#pragma mark CCNode - Scheduler - --(void) setScheduler:(CCScheduler *)scheduler -{ - if( scheduler != scheduler_ ) { - [self unscheduleAllSelectors]; - [scheduler_ release]; - - scheduler_ = [scheduler retain]; - } -} - --(CCScheduler*) scheduler -{ - return scheduler_; -} - --(void) scheduleUpdate -{ - [self scheduleUpdateWithPriority:0]; -} - --(void) scheduleUpdateWithPriority:(NSInteger)priority -{ - [scheduler_ scheduleUpdateForTarget:self priority:priority paused:!isRunning_]; -} - --(void) unscheduleUpdate -{ - [scheduler_ unscheduleUpdateForTarget:self]; -} - --(void) schedule:(SEL)selector -{ - [self schedule:selector interval:0 repeat:kCCRepeatForever delay:0]; -} - --(void) schedule:(SEL)selector interval:(ccTime)interval -{ - [self schedule:selector interval:interval repeat:kCCRepeatForever delay:0]; -} - --(void) schedule:(SEL)selector interval:(ccTime)interval repeat: (uint) repeat delay:(ccTime) delay -{ - NSAssert( selector != nil, @"Argument must be non-nil"); - NSAssert( interval >=0, @"Arguemnt must be positive"); - - [scheduler_ scheduleSelector:selector forTarget:self interval:interval paused:!isRunning_ repeat:repeat delay:delay]; -} - -- (void) scheduleOnce:(SEL) selector delay:(ccTime) delay -{ - [self schedule:selector interval:0.f repeat:0 delay:delay]; -} - --(void) unschedule:(SEL)selector -{ - // explicit nil handling - if (selector == nil) - return; - - [scheduler_ unscheduleSelector:selector forTarget:self]; -} - --(void) unscheduleAllSelectors -{ - [scheduler_ unscheduleAllSelectorsForTarget:self]; -} -- (void) resumeSchedulerAndActions -{ - [scheduler_ resumeTarget:self]; - [actionManager_ resumeTarget:self]; -} - -- (void) pauseSchedulerAndActions -{ - [scheduler_ pauseTarget:self]; - [actionManager_ pauseTarget:self]; -} - -#pragma mark CCNode Transform - -- (CGAffineTransform)nodeToParentTransform -{ - if ( isTransformDirty_ ) { - - // Translate values - float x = position_.x; - float y = position_.y; - - if ( !isRelativeAnchorPoint_ ) { - x += anchorPointInPoints_.x; - y += anchorPointInPoints_.y; - } - - // Rotation values - float c = 1, s = 0; - if( rotation_ ) { - float radians = -CC_DEGREES_TO_RADIANS(rotation_); - c = cosf(radians); - s = sinf(radians); - } - - BOOL needsSkewMatrix = ( skewX_ || skewY_ ); - - - // optimization: - // inline anchor point calculation if skew is not needed - if( !needsSkewMatrix && !CGPointEqualToPoint(anchorPointInPoints_, CGPointZero) ) { - x += c * -anchorPointInPoints_.x * scaleX_ + -s * -anchorPointInPoints_.y * scaleY_; - y += s * -anchorPointInPoints_.x * scaleX_ + c * -anchorPointInPoints_.y * scaleY_; - } - - - // Build Transform Matrix - transform_ = CGAffineTransformMake( c * scaleX_, s * scaleX_, - -s * scaleY_, c * scaleY_, - x, y ); - - // XXX: Try to inline skew - // If skew is needed, apply skew and then anchor point - if( needsSkewMatrix ) { - CGAffineTransform skewMatrix = CGAffineTransformMake(1.0f, tanf(CC_DEGREES_TO_RADIANS(skewY_)), - tanf(CC_DEGREES_TO_RADIANS(skewX_)), 1.0f, - 0.0f, 0.0f ); - transform_ = CGAffineTransformConcat(skewMatrix, transform_); - - // adjust anchor point - if( ! CGPointEqualToPoint(anchorPointInPoints_, CGPointZero) ) - transform_ = CGAffineTransformTranslate(transform_, -anchorPointInPoints_.x, -anchorPointInPoints_.y); - } - - isTransformDirty_ = NO; - } - - return transform_; -} - -- (CGAffineTransform)parentToNodeTransform -{ - if ( isInverseDirty_ ) { - inverse_ = CGAffineTransformInvert([self nodeToParentTransform]); - isInverseDirty_ = NO; - } - - return inverse_; -} - -- (CGAffineTransform)nodeToWorldTransform -{ - CGAffineTransform t = [self nodeToParentTransform]; - - for (CCNode *p = parent_; p != nil; p = p.parent) - t = CGAffineTransformConcat(t, [p nodeToParentTransform]); - - return t; -} - -- (CGAffineTransform)worldToNodeTransform -{ - return CGAffineTransformInvert([self nodeToWorldTransform]); -} - -- (CGPoint)convertToNodeSpace:(CGPoint)worldPoint -{ - CGPoint ret = CGPointApplyAffineTransform(worldPoint, [self worldToNodeTransform]); - return ret; -} - -- (CGPoint)convertToWorldSpace:(CGPoint)nodePoint -{ - CGPoint ret = CGPointApplyAffineTransform(nodePoint, [self nodeToWorldTransform]); - return ret; -} - -- (CGPoint)convertToNodeSpaceAR:(CGPoint)worldPoint -{ - CGPoint nodePoint = [self convertToNodeSpace:worldPoint]; - return ccpSub(nodePoint, anchorPointInPoints_); -} - -- (CGPoint)convertToWorldSpaceAR:(CGPoint)nodePoint -{ - nodePoint = ccpAdd(nodePoint, anchorPointInPoints_); - return [self convertToWorldSpace:nodePoint]; -} - -- (CGPoint)convertToWindowSpace:(CGPoint)nodePoint -{ - CGPoint worldPoint = [self convertToWorldSpace:nodePoint]; - return [[CCDirector sharedDirector] convertToUI:worldPoint]; -} - -// convenience methods which take a UITouch instead of CGPoint - -#ifdef __CC_PLATFORM_IOS - -- (CGPoint)convertTouchToNodeSpace:(UITouch *)touch -{ - CGPoint point = [touch locationInView: [touch view]]; - point = [[CCDirector sharedDirector] convertToGL: point]; - return [self convertToNodeSpace:point]; -} - -- (CGPoint)convertTouchToNodeSpaceAR:(UITouch *)touch -{ - CGPoint point = [touch locationInView: [touch view]]; - point = [[CCDirector sharedDirector] convertToGL: point]; - return [self convertToNodeSpaceAR:point]; -} - -#endif // __CC_PLATFORM_IOS - - -@end diff --git a/Example/libs/cocos2d/CCParallaxNode.h b/Example/libs/cocos2d/CCParallaxNode.h deleted file mode 100644 index 9f3eac3..0000000 --- a/Example/libs/cocos2d/CCParallaxNode.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCNode.h" -#import "Support/ccCArray.h" - -/** CCParallaxNode: A node that simulates a parallax scroller - - The children will be moved faster / slower than the parent according the the parallax ratio. - - */ -@interface CCParallaxNode : CCNode -{ - ccArray *parallaxArray_; - CGPoint lastPosition; -} - -/** array that holds the offset / ratio of the children */ -@property (nonatomic,readwrite) ccArray * parallaxArray; - -/** Adds a child to the container with a z-order, a parallax ratio and a position offset - It returns self, so you can chain several addChilds. - @since v0.8 - */ --(void) addChild: (CCNode*)node z:(NSInteger)z parallaxRatio:(CGPoint)c positionOffset:(CGPoint)positionOffset; - -@end diff --git a/Example/libs/cocos2d/CCParallaxNode.m b/Example/libs/cocos2d/CCParallaxNode.m deleted file mode 100644 index d30486c..0000000 --- a/Example/libs/cocos2d/CCParallaxNode.m +++ /dev/null @@ -1,161 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCParallaxNode.h" -#import "Support/CGPointExtension.h" -#import "Support/ccCArray.h" - -@interface CGPointObject : NSObject -{ - CGPoint ratio_; - CGPoint offset_; - CCNode *child_; // weak ref -} -@property (nonatomic,readwrite) CGPoint ratio; -@property (nonatomic,readwrite) CGPoint offset; -@property (nonatomic,readwrite,assign) CCNode *child; -+(id) pointWithCGPoint:(CGPoint)point offset:(CGPoint)offset; --(id) initWithCGPoint:(CGPoint)point offset:(CGPoint)offset; -@end -@implementation CGPointObject -@synthesize ratio = ratio_; -@synthesize offset = offset_; -@synthesize child=child_; - -+(id) pointWithCGPoint:(CGPoint)ratio offset:(CGPoint)offset -{ - return [[[self alloc] initWithCGPoint:ratio offset:offset] autorelease]; -} --(id) initWithCGPoint:(CGPoint)ratio offset:(CGPoint)offset -{ - if( (self=[super init])) { - ratio_ = ratio; - offset_ = offset; - } - return self; -} -@end - -@implementation CCParallaxNode - -@synthesize parallaxArray = parallaxArray_; - --(id) init -{ - if( (self=[super init]) ) { - parallaxArray_ = ccArrayNew(5); - lastPosition = CGPointMake(-100,-100); - } - return self; -} - -- (void) dealloc -{ - if( parallaxArray_ ) { - ccArrayFree(parallaxArray_); - parallaxArray_ = nil; - } - [super dealloc]; -} - --(void) addChild:(CCNode*)child z:(NSInteger)z tag:(NSInteger)tag -{ - NSAssert(NO,@"ParallaxNode: use addChild:z:parallaxRatio:positionOffset instead"); -} - --(void) addChild: (CCNode*) child z:(NSInteger)z parallaxRatio:(CGPoint)ratio positionOffset:(CGPoint)offset -{ - NSAssert( child != nil, @"Argument must be non-nil"); - CGPointObject *obj = [CGPointObject pointWithCGPoint:ratio offset:offset]; - obj.child = child; - ccArrayAppendObjectWithResize(parallaxArray_, obj); - - CGPoint pos = self.position; - pos.x = pos.x * ratio.x + offset.x; - pos.y = pos.y * ratio.y + offset.y; - child.position = pos; - - [super addChild: child z:z tag:child.tag]; -} - --(void) removeChild:(CCNode*)node cleanup:(BOOL)cleanup -{ - for( unsigned int i=0;i < parallaxArray_->num;i++) { - CGPointObject *point = parallaxArray_->arr[i]; - if( [point.child isEqual:node] ) { - ccArrayRemoveObjectAtIndex(parallaxArray_, i); - break; - } - } - [super removeChild:node cleanup:cleanup]; -} - --(void) removeAllChildrenWithCleanup:(BOOL)cleanup -{ - ccArrayRemoveAllObjects(parallaxArray_); - [super removeAllChildrenWithCleanup:cleanup]; -} - --(CGPoint) absolutePosition_ -{ - CGPoint ret = position_; - - CCNode *cn = self; - - while (cn.parent != nil) { - cn = cn.parent; - ret = ccpAdd( ret, cn.position ); - } - - return ret; -} - -/* - The positions are updated at visit because: - - using a timer is not guaranteed that it will called after all the positions were updated - - overriding "draw" will only be precise if the children have a z > 0 -*/ --(void) visit -{ -// CGPoint pos = position_; -// CGPoint pos = [self convertToWorldSpace:CGPointZero]; - CGPoint pos = [self absolutePosition_]; - if( ! CGPointEqualToPoint(pos, lastPosition) ) { - - for(unsigned int i=0; i < parallaxArray_->num; i++ ) { - - CGPointObject *point = parallaxArray_->arr[i]; - float x = -pos.x + pos.x * point.ratio.x + point.offset.x; - float y = -pos.y + pos.y * point.ratio.y + point.offset.y; - point.child.position = ccp(x,y); - } - - lastPosition = pos; - } - - [super visit]; -} -@end diff --git a/Example/libs/cocos2d/CCParticleBatchNode.h b/Example/libs/cocos2d/CCParticleBatchNode.h deleted file mode 100644 index ec5e9bf..0000000 --- a/Example/libs/cocos2d/CCParticleBatchNode.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (C) 2009 Matt Oswald - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Copyright (c) 2011 Marco Tillemans - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCNode.h" -@class CCTextureAtlas; -@class CCParticleSystem; - -//don't use lazy sorting for particle systems -@interface CCNode (extension) --(void) setZOrder:(NSUInteger) z; -@end - -/** CCParticleBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call - * (often known as "batch draw"). - * - * A CCParticleBatchNode can reference one and only one texture (one image file, one texture atlas). - * Only the CCParticleSystems that are contained in that texture can be added to the CCSpriteBatchNode. - * All CCParticleSystems added to a CCSpriteBatchNode are drawn in one OpenGL ES draw call. - * If the CCParticleSystems are not added to a CCParticleBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient. - * - * - * Limitations: - * - At the moment only CCParticleSystemQuad is supported - * - All systems need to be drawn with the same parameters, blend function, aliasing, texture - * - * Most efficient usage - * - Initialize the ParticleBatchNode with the texture and enough capacity for all the particle systems - * - Initialize all particle systems and add them as child to the batch node - * @since v1.1 - */ - -@interface CCParticleBatchNode : CCNode { - - CCTextureAtlas *textureAtlas_; - ccBlendFunc blendFunc_; -} - -/** the texture atlas used for drawing the quads */ -@property (nonatomic, retain) CCTextureAtlas* textureAtlas; -/** the blend function used for drawing the quads */ -@property (nonatomic, readwrite) ccBlendFunc blendFunc; - -/** initializes the particle system with CCTexture2D, a default capacity of 500 */ -+(id)batchNodeWithTexture:(CCTexture2D *)tex; - -/** initializes the particle system with the name of a file on disk (for a list of supported formats look at the CCTexture2D class), a default capacity of 500 particles */ -+(id)batchNodeWithFile:(NSString*) imageFile; - -/** initializes the particle system with CCTexture2D, a capacity of particles, which particle system to use */ -+(id)batchNodeWithTexture:(CCTexture2D *)tex capacity:(NSUInteger) capacity; - -/** initializes the particle system with the name of a file on disk (for a list of supported formats look at the CCTexture2D class), a capacity of particles */ -+(id)batchNodeWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity; - -/** initializes the particle system with CCTexture2D, a capacity of particles */ --(id)initWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity; - -/** initializes the particle system with the name of a file on disk (for a list of supported formats look at the CCTexture2D class), a capacity of particles */ --(id)initWithFile:(NSString *)fileImage capacity:(NSUInteger)capacity; - -/** Add a child into the CCParticleBatchNode */ --(void) addChild:(CCParticleSystem*)child z:(NSInteger)z tag:(NSInteger) aTag; - -/** Inserts a child into the CCParticleBatchNode */ --(void) insertChild:(CCParticleSystem*) pSystem inAtlasAtIndex:(NSUInteger)index; - -/** remove child from the CCParticleBatchNode */ --(void) removeChild:(CCParticleSystem*) pSystem cleanup:(BOOL)doCleanUp; - -/** disables a particle by inserting a 0'd quad into the texture atlas */ --(void) disableParticle:(NSUInteger) particleIndex; -@end diff --git a/Example/libs/cocos2d/CCParticleBatchNode.m b/Example/libs/cocos2d/CCParticleBatchNode.m deleted file mode 100644 index f786a5c..0000000 --- a/Example/libs/cocos2d/CCParticleBatchNode.m +++ /dev/null @@ -1,473 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (C) 2009 Matt Oswald - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Copyright (c) 2011 Marco Tillemans - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCParticleBatchNode.h" -#import "CCTextureCache.h" -#import "CCTextureAtlas.h" -#import "ccConfig.h" -#import "ccMacros.h" -#import "CCGrid.h" -#import "Support/CGPointExtension.h" -#import "CCParticleSystem.h" -#import "CCParticleSystem.h" -#import "CCShaderCache.h" -#import "CCGLProgram.h" -#import "ccGLStateCache.h" - -#import "Support/base64.h" -#import "Support/ZipUtils.h" -#import "Support/CCFileUtils.h" - -#import "kazmath/GL/matrix.h" - -#define kCCParticleDefaultCapacity 500 - -@interface CCNode() --(void) _setZOrder:(NSInteger)z; -@end - -@interface CCParticleBatchNode (private) --(void) updateAllAtlasIndexes; --(void) increaseAtlasCapacityTo:(NSUInteger) quantity; --(NSUInteger) searchNewPositionInChildrenForZ:(NSInteger)z; --(void) getCurrentIndex:(NSUInteger*)oldIndex newIndex:(NSUInteger*)newIndex forChild:(CCNode*)child z:(NSInteger)z; --(NSUInteger) addChildHelper: (CCNode*) child z:(NSInteger)z tag:(NSInteger) aTag; -@end - -@implementation CCParticleBatchNode - -@synthesize textureAtlas = textureAtlas_; -@synthesize blendFunc = blendFunc_; - -/* - * creation with CCTexture2D - */ -+(id)batchNodeWithTexture:(CCTexture2D *)tex -{ - return [[[self alloc] initWithTexture:tex capacity:kCCParticleDefaultCapacity] autorelease]; -} - -+(id)batchNodeWithTexture:(CCTexture2D *)tex capacity:(NSUInteger) capacity -{ - return [[[self alloc] initWithTexture:tex capacity:capacity] autorelease]; -} - -/* - * creation with File Image - */ -+(id)batchNodeWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity -{ - return [[[self alloc] initWithFile:fileImage capacity:capacity] autorelease]; -} - -+(id)batchNodeWithFile:(NSString*) imageFile -{ - return [[[self alloc] initWithFile:imageFile capacity:kCCParticleDefaultCapacity] autorelease]; -} - -/* - * init with CCTexture2D - */ --(id)initWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity -{ - if (self = [super init]) - { - textureAtlas_ = [[CCTextureAtlas alloc] initWithTexture:tex capacity:capacity]; - - // no lazy alloc in this node - children_ = [[CCArray alloc] initWithCapacity:capacity]; - - blendFunc_.src = CC_BLEND_SRC; - blendFunc_.dst = CC_BLEND_DST; - - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; - } - - return self; -} - -/* - * init with FileImage - */ --(id)initWithFile:(NSString *)fileImage capacity:(NSUInteger)capacity -{ - CCTexture2D *tex = [[CCTextureCache sharedTextureCache] addImage:fileImage]; - return [self initWithTexture:tex capacity:capacity]; -} - --(NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Tag = %i>", [self class], self, tag_ ]; -} - --(void)dealloc -{ - [textureAtlas_ release]; - [super dealloc]; -} - -#pragma mark CCParticleBatchNode - composition - -// override visit. -// Don't call visit on it's children --(void) visit -{ - // CAREFUL: - // This visit is almost identical to CCNode#visit - // with the exception that it doesn't call visit on it's children - // - // The alternative is to have a void CCSprite#visit, but - // although this is less mantainable, is faster - // - if (!visible_) - return; - - kmGLPushMatrix(); - - if ( grid_ && grid_.active) { - [grid_ beforeDraw]; - [self transformAncestors]; - } - - [self transform]; - - [self draw]; - - if ( grid_ && grid_.active) - [grid_ afterDraw:self]; - - kmGLPopMatrix(); -} - -// override addChild: --(void) addChild:(CCParticleSystem*)child z:(NSInteger)z tag:(NSInteger) aTag -{ - NSAssert( child != nil, @"Argument must be non-nil"); - NSAssert( [child isKindOfClass:[CCParticleSystem class]], @"CCParticleBatchNode only supports CCQuadParticleSystems as children"); - NSAssert( child.texture.name == textureAtlas_.texture.name, @"CCParticleSystem is not using the same texture id"); - - // If this is the 1st children, then copy blending function - if( [children_ count] == 0 ) - blendFunc_ = [child blendFunc]; - - NSAssert( blendFunc_.src == child.blendFunc.src && blendFunc_.dst == child.blendFunc.dst, @"Can't add a PaticleSystem that uses a differnt blending function"); - - //no lazy sorting, so don't call super addChild, call helper instead - NSUInteger pos = [self addChildHelper:child z:z tag:aTag]; - - //get new atlasIndex - NSUInteger atlasIndex; - - if (pos != 0) - atlasIndex = [[children_ objectAtIndex:pos-1] atlasIndex] + [[children_ objectAtIndex:pos-1] totalParticles]; - else - atlasIndex = 0; - - [self insertChild:child inAtlasAtIndex:atlasIndex]; - - // update quad info - [child setBatchNode:self]; -} - -// don't use lazy sorting, reordering the particle systems quads afterwards would be too complex -// XXX research whether lazy sorting + freeing current quads and calloc a new block with size of capacity would be faster -// XXX or possibly using vertexZ for reordering, that would be fastest -// this helper is almost equivalent to CCNode's addChild, but doesn't make use of the lazy sorting --(NSUInteger) addChildHelper: (CCNode*) child z:(NSInteger)z tag:(NSInteger) aTag -{ - NSAssert( child != nil, @"Argument must be non-nil"); - NSAssert( child.parent == nil, @"child already added. It can't be added again"); - - if( ! children_ ) - children_ = [[CCArray alloc] initWithCapacity:4]; - - //don't use a lazy insert - NSUInteger pos = [self searchNewPositionInChildrenForZ:z]; - - [children_ insertObject:child atIndex:pos]; - - child.tag = aTag; - [child _setZOrder:z]; - - [child setParent: self]; - - if( isRunning_ ) { - [child onEnter]; - [child onEnterTransitionDidFinish]; - } - return pos; -} - -// Reorder will be done in this function, no "lazy" reorder to particles --(void) reorderChild:(CCParticleSystem*)child z:(NSInteger)z -{ - NSAssert( child != nil, @"Child must be non-nil"); - NSAssert( [children_ containsObject:child], @"Child doesn't belong to batch" ); - - if( z == child.zOrder ) - return; - - // no reordering if only 1 child - if( [children_ count] > 1) - { - NSUInteger newIndex, oldIndex; - - [self getCurrentIndex:&oldIndex newIndex:&newIndex forChild:child z:z]; - - if( oldIndex != newIndex ) { - - // reorder children_ array - [child retain]; - [children_ removeObjectAtIndex:oldIndex]; - [children_ insertObject:child atIndex:newIndex]; - [child release]; - - // save old altasIndex - NSUInteger oldAtlasIndex = child.atlasIndex; - - // update atlas index - [self updateAllAtlasIndexes]; - - // Find new AtlasIndex - NSUInteger newAtlasIndex = 0; - for( NSUInteger i=0;i < [children_ count];i++) { - CCParticleSystem *node = [children_ objectAtIndex:i]; - if( node == child ) { - newAtlasIndex = [child atlasIndex]; - break; - } - } - - // reorder textureAtlas quads - [textureAtlas_ moveQuadsFromIndex:oldAtlasIndex amount:child.totalParticles atIndex:newAtlasIndex]; - - [child updateWithNoTime]; - } - } - - [child _setZOrder:z]; -} - --(void) getCurrentIndex:(NSUInteger*)oldIndex newIndex:(NSUInteger*)newIndex forChild:(CCNode*)child z:(NSInteger)z -{ - BOOL foundCurrentIdx = NO; - BOOL foundNewIdx = NO; - - NSInteger minusOne = 0; - NSUInteger count = [children_ count]; - - for( NSUInteger i=0; i < count; i++ ) { - - CCNode *node = [children_ objectAtIndex:i]; - - // new index - if( node.zOrder > z && ! foundNewIdx ) { - *newIndex = i; - foundNewIdx = YES; - - if( foundCurrentIdx && foundNewIdx ) - break; - } - - // current index - if( child == node ) { - *oldIndex = i; - foundCurrentIdx = YES; - - if( ! foundNewIdx ) - minusOne = -1; - - if( foundCurrentIdx && foundNewIdx ) - break; - - } - - } - - if( ! foundNewIdx ) - *newIndex = count; - - *newIndex += minusOne; -} - --(NSUInteger) searchNewPositionInChildrenForZ: (NSInteger) z -{ - NSUInteger count = [children_ count]; - - for( NSUInteger i=0; i < count; i++ ) { - CCNode *child = [children_ objectAtIndex:i]; - if (child.zOrder > z) - return i; - } - return count; -} - -// override removeChild: --(void)removeChild: (CCParticleSystem*) child cleanup:(BOOL)doCleanup -{ - // explicit nil handling - if (child == nil) - return; - - NSAssert([children_ containsObject:child], @"CCParticleBatchNode doesn't contain the sprite. Can't remove it"); - - [super removeChild:child cleanup:doCleanup]; - - // remove child helper - [textureAtlas_ removeQuadsAtIndex:child.atlasIndex amount:child.totalParticles]; - - // after memmove of data, empty the quads at the end of array - [textureAtlas_ fillWithEmptyQuadsFromIndex:textureAtlas_.totalQuads amount:child.totalParticles]; - - // paticle could be reused for self rendering - [child setBatchNode:nil]; - - [self updateAllAtlasIndexes]; -} - --(void)removeChildAtIndex:(NSUInteger)index cleanup:(BOOL) doCleanup -{ - [self removeChild:(CCParticleSystem *)[children_ objectAtIndex:index] cleanup:doCleanup]; -} - --(void)removeAllChildrenWithCleanup:(BOOL)doCleanup -{ - [children_ makeObjectsPerformSelector:@selector(useSelfRender)]; - - [super removeAllChildrenWithCleanup:doCleanup]; - - [textureAtlas_ removeAllQuads]; -} - -#pragma mark CCParticleBatchNode - Node overrides --(void) draw -{ - CC_PROFILER_STOP(@"CCParticleBatchNode - draw"); - - if( textureAtlas_.totalQuads == 0 ) - return; - - CC_NODE_DRAW_SETUP(); - - ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); - - [textureAtlas_ drawQuads]; - - CC_PROFILER_STOP(@"CCParticleBatchNode - draw"); -} - -#pragma mark CCParticleBatchNode - private - --(void) increaseAtlasCapacityTo:(NSUInteger) quantity -{ - CCLOG(@"cocos2d: CCParticleBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", - (long)textureAtlas_.capacity, - (long)quantity); - - if( ! [textureAtlas_ resizeCapacity:quantity] ) { - // serious problems - CCLOG(@"cocos2d: WARNING: Not enough memory to resize the atlas"); - NSAssert(NO,@"XXX: CCParticleBatchNode #increaseAtlasCapacity SHALL handle this assert"); - } -} - -//sets a 0'd quad into the quads array --(void) disableParticle:(NSUInteger)particleIndex -{ - ccV3F_C4B_T2F_Quad* quad = &((textureAtlas_.quads)[particleIndex]); - quad->br.vertices.x = quad->br.vertices.y = quad->tr.vertices.x = quad->tr.vertices.y = quad->tl.vertices.x = quad->tl.vertices.y = quad->bl.vertices.x = quad->bl.vertices.y = 0.0f; -} - -#pragma mark CCParticleBatchNode - add / remove / reorder helper methods - -// add child helper --(void) insertChild:(CCParticleSystem*) pSystem inAtlasAtIndex:(NSUInteger)index -{ - pSystem.atlasIndex = index; - - if(textureAtlas_.totalQuads + pSystem.totalParticles > textureAtlas_.capacity) - { - [self increaseAtlasCapacityTo:textureAtlas_.totalQuads + pSystem.totalParticles]; - - // after a realloc empty quads of textureAtlas can be filled with gibberish (realloc doesn't perform calloc), insert empty quads to prevent it - [textureAtlas_ fillWithEmptyQuadsFromIndex:textureAtlas_.capacity - pSystem.totalParticles amount:pSystem.totalParticles]; - } - - // make room for quads, not necessary for last child - if (pSystem.atlasIndex + pSystem.totalParticles != textureAtlas_.totalQuads) - [textureAtlas_ moveQuadsFromIndex:index to:index+pSystem.totalParticles]; - - // increase totalParticles here for new particles, update method of particlesystem will fill the quads - [textureAtlas_ increaseTotalQuadsWith:pSystem.totalParticles]; - - [self updateAllAtlasIndexes]; -} - -//rebuild atlas indexes --(void) updateAllAtlasIndexes -{ - CCParticleSystem *child; - NSUInteger index = 0; - - CCARRAY_FOREACH(children_,child) - { - child.atlasIndex = index; - index += child.totalParticles; - } -} - -#pragma mark CCParticleBatchNode - CocosNodeTexture protocol - --(void) updateBlendFunc -{ - if( ! [textureAtlas_.texture hasPremultipliedAlpha] ) { - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; - } -} - --(void) setTexture:(CCTexture2D*)texture -{ - textureAtlas_.texture = texture; - - // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it - if( texture && ! [texture hasPremultipliedAlpha] && ( blendFunc_.src == CC_BLEND_SRC && blendFunc_.dst == CC_BLEND_DST ) ) - { - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; - } -} - --(CCTexture2D*) texture -{ - return textureAtlas_.texture; -} - -@end diff --git a/Example/libs/cocos2d/CCParticleExamples.h b/Example/libs/cocos2d/CCParticleExamples.h deleted file mode 100644 index 9952726..0000000 --- a/Example/libs/cocos2d/CCParticleExamples.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "ccMacros.h" -#import "CCParticleSystemQuad.h" - -// build each architecture with the optimal particle system - -// ARMv7, Mac or Simulator use "Quad" particle -#if defined(__ARM_NEON__) || defined(__CC_PLATFORM_MAC) || TARGET_IPHONE_SIMULATOR - #define ARCH_OPTIMAL_PARTICLE_SYSTEM CCParticleSystemQuad - -// ARMv6 use "Point" particle -#elif __arm__ - #define ARCH_OPTIMAL_PARTICLE_SYSTEM CCParticleSystemPoint -#else - #error(unknown architecture) -#endif - - -//! A fire particle system -@interface CCParticleFire: ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! A fireworks particle system -@interface CCParticleFireworks : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! A sun particle system -@interface CCParticleSun : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! A galaxy particle system -@interface CCParticleGalaxy : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! A flower particle system -@interface CCParticleFlower : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! A meteor particle system -@interface CCParticleMeteor : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! An spiral particle system -@interface CCParticleSpiral : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! An explosion particle system -@interface CCParticleExplosion : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! An smoke particle system -@interface CCParticleSmoke : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! An snow particle system -@interface CCParticleSnow : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end - -//! A rain particle system -@interface CCParticleRain : ARCH_OPTIMAL_PARTICLE_SYSTEM -{ -} -@end diff --git a/Example/libs/cocos2d/CCParticleExamples.m b/Example/libs/cocos2d/CCParticleExamples.m deleted file mode 100644 index c21cf83..0000000 --- a/Example/libs/cocos2d/CCParticleExamples.m +++ /dev/null @@ -1,926 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -// cocos2d -#import "CCParticleExamples.h" -#import "CCTextureCache.h" -#import "CCDirector.h" -#import "Support/CGPointExtension.h" - -// -// ParticleFireworks -// -@implementation CCParticleFireworks --(id) init -{ - return [self initWithTotalParticles:1500]; -} - --(id) initWithTotalParticles:(NSUInteger)p -{ - if( (self=[super initWithTotalParticles:p]) ) { - // duration - duration = kCCParticleDurationInfinity; - - // Gravity Mode - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(0,-90); - - // Gravity Mode: radial - self.radialAccel = 0; - self.radialAccelVar = 0; - - // Gravity Mode: speed of particles - self.speed = 180; - self.speedVar = 50; - - // emitter position - CGSize winSize = [[CCDirector sharedDirector] winSize]; - self.position = ccp(winSize.width/2, winSize.height/2); - - // angle - angle = 90; - angleVar = 20; - - // life of particles - life = 3.5f; - lifeVar = 1; - - // emits per frame - emissionRate = totalParticles/life; - - // color of particles - startColor.r = 0.5f; - startColor.g = 0.5f; - startColor.b = 0.5f; - startColor.a = 1.0f; - startColorVar.r = 0.5f; - startColorVar.g = 0.5f; - startColorVar.b = 0.5f; - startColorVar.a = 0.1f; - endColor.r = 0.1f; - endColor.g = 0.1f; - endColor.b = 0.1f; - endColor.a = 0.2f; - endColorVar.r = 0.1f; - endColorVar.g = 0.1f; - endColorVar.b = 0.1f; - endColorVar.a = 0.2f; - - // size, in pixels - startSize = 8.0f; - startSizeVar = 2.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = NO; - } - - return self; -} -@end - -// -// ParticleFire -// -@implementation CCParticleFire --(id) init -{ - return [self initWithTotalParticles:250]; -} - --(id) initWithTotalParticles:(NSUInteger) p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // duration - duration = kCCParticleDurationInfinity; - - // Gravity Mode - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(0,0); - - // Gravity Mode: radial acceleration - self.radialAccel = 0; - self.radialAccelVar = 0; - - // Gravity Mode: speed of particles - self.speed = 60; - self.speedVar = 20; - - // starting angle - angle = 90; - angleVar = 10; - - // emitter position - CGSize winSize = [[CCDirector sharedDirector] winSize]; - self.position = ccp(winSize.width/2, 60); - posVar = ccp(40, 20); - - // life of particles - life = 3; - lifeVar = 0.25f; - - - // size, in pixels - startSize = 54.0f; - startSizeVar = 10.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per frame - emissionRate = totalParticles/life; - - // color of particles - startColor.r = 0.76f; - startColor.g = 0.25f; - startColor.b = 0.12f; - startColor.a = 1.0f; - startColorVar.r = 0.0f; - startColorVar.g = 0.0f; - startColorVar.b = 0.0f; - startColorVar.a = 0.0f; - endColor.r = 0.0f; - endColor.g = 0.0f; - endColor.b = 0.0f; - endColor.a = 1.0f; - endColorVar.r = 0.0f; - endColorVar.g = 0.0f; - endColorVar.b = 0.0f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = YES; - } - - return self; -} -@end - -// -// ParticleSun -// -@implementation CCParticleSun --(id) init -{ - return [self initWithTotalParticles:350]; -} - --(id) initWithTotalParticles:(NSUInteger) p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // additive - self.blendAdditive = YES; - - // duration - duration = kCCParticleDurationInfinity; - - // Gravity Mode - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(0,0); - - // Gravity mode: radial acceleration - self.radialAccel = 0; - self.radialAccelVar = 0; - - // Gravity mode: speed of particles - self.speed = 20; - self.speedVar = 5; - - - // angle - angle = 90; - angleVar = 360; - - // emitter position - CGSize winSize = [[CCDirector sharedDirector] winSize]; - self.position = ccp(winSize.width/2, winSize.height/2); - posVar = CGPointZero; - - // life of particles - life = 1; - lifeVar = 0.5f; - - // size, in pixels - startSize = 30.0f; - startSizeVar = 10.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per seconds - emissionRate = totalParticles/life; - - // color of particles - startColor.r = 0.76f; - startColor.g = 0.25f; - startColor.b = 0.12f; - startColor.a = 1.0f; - startColorVar.r = 0.0f; - startColorVar.g = 0.0f; - startColorVar.b = 0.0f; - startColorVar.a = 0.0f; - endColor.r = 0.0f; - endColor.g = 0.0f; - endColor.b = 0.0f; - endColor.a = 1.0f; - endColorVar.r = 0.0f; - endColorVar.g = 0.0f; - endColorVar.b = 0.0f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - } - - return self; -} -@end - -// -// ParticleGalaxy -// -@implementation CCParticleGalaxy --(id) init -{ - return [self initWithTotalParticles:200]; -} - --(id) initWithTotalParticles:(NSUInteger)p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // duration - duration = kCCParticleDurationInfinity; - - // Gravity Mode - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(0,0); - - // Gravity Mode: speed of particles - self.speed = 60; - self.speedVar = 10; - - // Gravity Mode: radial - self.radialAccel = -80; - self.radialAccelVar = 0; - - // Gravity Mode: tagential - self.tangentialAccel = 80; - self.tangentialAccelVar = 0; - - // angle - angle = 90; - angleVar = 360; - - // emitter position - CGSize winSize = [[CCDirector sharedDirector] winSize]; - self.position = ccp(winSize.width/2, winSize.height/2); - posVar = CGPointZero; - - // life of particles - life = 4; - lifeVar = 1; - - // size, in pixels - startSize = 37.0f; - startSizeVar = 10.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per second - emissionRate = totalParticles/life; - - // color of particles - startColor.r = 0.12f; - startColor.g = 0.25f; - startColor.b = 0.76f; - startColor.a = 1.0f; - startColorVar.r = 0.0f; - startColorVar.g = 0.0f; - startColorVar.b = 0.0f; - startColorVar.a = 0.0f; - endColor.r = 0.0f; - endColor.g = 0.0f; - endColor.b = 0.0f; - endColor.a = 1.0f; - endColorVar.r = 0.0f; - endColorVar.g = 0.0f; - endColorVar.b = 0.0f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = YES; - } - - return self; -} -@end - -// -// ParticleFlower -// -@implementation CCParticleFlower --(id) init -{ - return [self initWithTotalParticles:250]; -} - --(id) initWithTotalParticles:(NSUInteger) p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // duration - duration = kCCParticleDurationInfinity; - - // Gravity Mode - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(0,0); - - // Gravity Mode: speed of particles - self.speed = 80; - self.speedVar = 10; - - // Gravity Mode: radial - self.radialAccel = -60; - self.radialAccelVar = 0; - - // Gravity Mode: tagential - self.tangentialAccel = 15; - self.tangentialAccelVar = 0; - - // angle - angle = 90; - angleVar = 360; - - // emitter position - CGSize winSize = [[CCDirector sharedDirector] winSize]; - self.position = ccp(winSize.width/2, winSize.height/2); - posVar = CGPointZero; - - // life of particles - life = 4; - lifeVar = 1; - - // size, in pixels - startSize = 30.0f; - startSizeVar = 10.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per second - emissionRate = totalParticles/life; - - // color of particles - startColor.r = 0.50f; - startColor.g = 0.50f; - startColor.b = 0.50f; - startColor.a = 1.0f; - startColorVar.r = 0.5f; - startColorVar.g = 0.5f; - startColorVar.b = 0.5f; - startColorVar.a = 0.5f; - endColor.r = 0.0f; - endColor.g = 0.0f; - endColor.b = 0.0f; - endColor.a = 1.0f; - endColorVar.r = 0.0f; - endColorVar.g = 0.0f; - endColorVar.b = 0.0f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = YES; - } - - return self; -} -@end - -// -// ParticleMeteor -// -@implementation CCParticleMeteor --(id) init -{ - return [self initWithTotalParticles:150]; -} - --(id) initWithTotalParticles:(NSUInteger) p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // duration - duration = kCCParticleDurationInfinity; - - // Gravity Mode - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(-200,200); - - // Gravity Mode: speed of particles - self.speed = 15; - self.speedVar = 5; - - // Gravity Mode: radial - self.radialAccel = 0; - self.radialAccelVar = 0; - - // Gravity Mode: tagential - self.tangentialAccel = 0; - self.tangentialAccelVar = 0; - - // angle - angle = 90; - angleVar = 360; - - // emitter position - CGSize winSize = [[CCDirector sharedDirector] winSize]; - self.position = ccp(winSize.width/2, winSize.height/2); - posVar = CGPointZero; - - // life of particles - life = 2; - lifeVar = 1; - - // size, in pixels - startSize = 60.0f; - startSizeVar = 10.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per second - emissionRate = totalParticles/life; - - // color of particles - startColor.r = 0.2f; - startColor.g = 0.4f; - startColor.b = 0.7f; - startColor.a = 1.0f; - startColorVar.r = 0.0f; - startColorVar.g = 0.0f; - startColorVar.b = 0.2f; - startColorVar.a = 0.1f; - endColor.r = 0.0f; - endColor.g = 0.0f; - endColor.b = 0.0f; - endColor.a = 1.0f; - endColorVar.r = 0.0f; - endColorVar.g = 0.0f; - endColorVar.b = 0.0f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = YES; - } - - return self; -} -@end - -// -// ParticleSpiral -// -@implementation CCParticleSpiral --(id) init -{ - return [self initWithTotalParticles:500]; -} - --(id) initWithTotalParticles:(NSUInteger) p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // duration - duration = kCCParticleDurationInfinity; - - // Gravity Mode - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(0,0); - - // Gravity Mode: speed of particles - self.speed = 150; - self.speedVar = 0; - - // Gravity Mode: radial - self.radialAccel = -380; - self.radialAccelVar = 0; - - // Gravity Mode: tagential - self.tangentialAccel = 45; - self.tangentialAccelVar = 0; - - // angle - angle = 90; - angleVar = 0; - - // emitter position - CGSize winSize = [[CCDirector sharedDirector] winSize]; - self.position = ccp(winSize.width/2, winSize.height/2); - posVar = CGPointZero; - - // life of particles - life = 12; - lifeVar = 0; - - // size, in pixels - startSize = 20.0f; - startSizeVar = 0.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per second - emissionRate = totalParticles/life; - - // color of particles - startColor.r = 0.5f; - startColor.g = 0.5f; - startColor.b = 0.5f; - startColor.a = 1.0f; - startColorVar.r = 0.5f; - startColorVar.g = 0.5f; - startColorVar.b = 0.5f; - startColorVar.a = 0.0f; - endColor.r = 0.5f; - endColor.g = 0.5f; - endColor.b = 0.5f; - endColor.a = 1.0f; - endColorVar.r = 0.5f; - endColorVar.g = 0.5f; - endColorVar.b = 0.5f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = NO; - } - - return self; -} -@end - -// -// ParticleExplosion -// -@implementation CCParticleExplosion --(id) init -{ - return [self initWithTotalParticles:700]; -} - --(id) initWithTotalParticles:(NSUInteger)p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // duration - duration = 0.1f; - - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(0,0); - - // Gravity Mode: speed of particles - self.speed = 70; - self.speedVar = 40; - - // Gravity Mode: radial - self.radialAccel = 0; - self.radialAccelVar = 0; - - // Gravity Mode: tagential - self.tangentialAccel = 0; - self.tangentialAccelVar = 0; - - // angle - angle = 90; - angleVar = 360; - - // emitter position - CGSize winSize = [[CCDirector sharedDirector] winSize]; - self.position = ccp(winSize.width/2, winSize.height/2); - posVar = CGPointZero; - - // life of particles - life = 5.0f; - lifeVar = 2; - - // size, in pixels - startSize = 15.0f; - startSizeVar = 10.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per second - emissionRate = totalParticles/duration; - - // color of particles - startColor.r = 0.7f; - startColor.g = 0.1f; - startColor.b = 0.2f; - startColor.a = 1.0f; - startColorVar.r = 0.5f; - startColorVar.g = 0.5f; - startColorVar.b = 0.5f; - startColorVar.a = 0.0f; - endColor.r = 0.5f; - endColor.g = 0.5f; - endColor.b = 0.5f; - endColor.a = 0.0f; - endColorVar.r = 0.5f; - endColorVar.g = 0.5f; - endColorVar.b = 0.5f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = NO; - } - - return self; -} -@end - -// -// ParticleSmoke -// -@implementation CCParticleSmoke --(id) init -{ - return [self initWithTotalParticles:200]; -} - --(id) initWithTotalParticles:(NSUInteger) p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // duration - duration = kCCParticleDurationInfinity; - - // Emitter mode: Gravity Mode - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(0,0); - - // Gravity Mode: radial acceleration - self.radialAccel = 0; - self.radialAccelVar = 0; - - // Gravity Mode: speed of particles - self.speed = 25; - self.speedVar = 10; - - // angle - angle = 90; - angleVar = 5; - - // emitter position - CGSize winSize = [[CCDirector sharedDirector] winSize]; - self.position = ccp(winSize.width/2, 0); - posVar = ccp(20, 0); - - // life of particles - life = 4; - lifeVar = 1; - - // size, in pixels - startSize = 60.0f; - startSizeVar = 10.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per frame - emissionRate = totalParticles/life; - - // color of particles - startColor.r = 0.8f; - startColor.g = 0.8f; - startColor.b = 0.8f; - startColor.a = 1.0f; - startColorVar.r = 0.02f; - startColorVar.g = 0.02f; - startColorVar.b = 0.02f; - startColorVar.a = 0.0f; - endColor.r = 0.0f; - endColor.g = 0.0f; - endColor.b = 0.0f; - endColor.a = 1.0f; - endColorVar.r = 0.0f; - endColorVar.g = 0.0f; - endColorVar.b = 0.0f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = NO; - } - - return self; -} -@end - -@implementation CCParticleSnow --(id) init -{ - return [self initWithTotalParticles:700]; -} - --(id) initWithTotalParticles:(NSUInteger)p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // duration - duration = kCCParticleDurationInfinity; - - // set gravity mode. - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(0,-1); - - // Gravity Mode: speed of particles - self.speed = 5; - self.speedVar = 1; - - // Gravity Mode: radial - self.radialAccel = 0; - self.radialAccelVar = 1; - - // Gravity mode: tagential - self.tangentialAccel = 0; - self.tangentialAccelVar = 1; - - // emitter position - self.position = (CGPoint) { - [[CCDirector sharedDirector] winSize].width / 2, - [[CCDirector sharedDirector] winSize].height + 10 - }; - posVar = ccp( [[CCDirector sharedDirector] winSize].width / 2, 0 ); - - // angle - angle = -90; - angleVar = 5; - - // life of particles - life = 45; - lifeVar = 15; - - // size, in pixels - startSize = 10.0f; - startSizeVar = 5.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per second - emissionRate = 10; - - // color of particles - startColor.r = 1.0f; - startColor.g = 1.0f; - startColor.b = 1.0f; - startColor.a = 1.0f; - startColorVar.r = 0.0f; - startColorVar.g = 0.0f; - startColorVar.b = 0.0f; - startColorVar.a = 0.0f; - endColor.r = 1.0f; - endColor.g = 1.0f; - endColor.b = 1.0f; - endColor.a = 0.0f; - endColorVar.r = 0.0f; - endColorVar.g = 0.0f; - endColorVar.b = 0.0f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = NO; - } - - return self; -} -@end - -@implementation CCParticleRain --(id) init -{ - return [self initWithTotalParticles:1000]; -} - --(id) initWithTotalParticles:(NSUInteger)p -{ - if( (self=[super initWithTotalParticles:p]) ) { - - // duration - duration = kCCParticleDurationInfinity; - - self.emitterMode = kCCParticleModeGravity; - - // Gravity Mode: gravity - self.gravity = ccp(10,-10); - - // Gravity Mode: radial - self.radialAccel = 0; - self.radialAccelVar = 1; - - // Gravity Mode: tagential - self.tangentialAccel = 0; - self.tangentialAccelVar = 1; - - // Gravity Mode: speed of particles - self.speed = 130; - self.speedVar = 30; - - // angle - angle = -90; - angleVar = 5; - - - // emitter position - self.position = (CGPoint) { - [[CCDirector sharedDirector] winSize].width / 2, - [[CCDirector sharedDirector] winSize].height - }; - posVar = ccp( [[CCDirector sharedDirector] winSize].width / 2, 0 ); - - // life of particles - life = 4.5f; - lifeVar = 0; - - // size, in pixels - startSize = 4.0f; - startSizeVar = 2.0f; - endSize = kCCParticleStartSizeEqualToEndSize; - - // emits per second - emissionRate = 20; - - // color of particles - startColor.r = 0.7f; - startColor.g = 0.8f; - startColor.b = 1.0f; - startColor.a = 1.0f; - startColorVar.r = 0.0f; - startColorVar.g = 0.0f; - startColorVar.b = 0.0f; - startColorVar.a = 0.0f; - endColor.r = 0.7f; - endColor.g = 0.8f; - endColor.b = 1.0f; - endColor.a = 0.5f; - endColorVar.r = 0.0f; - endColorVar.g = 0.0f; - endColorVar.b = 0.0f; - endColorVar.a = 0.0f; - - self.texture = [[CCTextureCache sharedTextureCache] addImage: @"fire.png"]; - - // additive - self.blendAdditive = NO; - } - - return self; -} -@end diff --git a/Example/libs/cocos2d/CCParticleSystem.h b/Example/libs/cocos2d/CCParticleSystem.h deleted file mode 100644 index 82c70d0..0000000 --- a/Example/libs/cocos2d/CCParticleSystem.h +++ /dev/null @@ -1,449 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCProtocols.h" -#import "CCNode.h" -#import "ccTypes.h" -#import "ccConfig.h" - -@class CCParticleBatchNode; - -//* @enum -enum { - /** The Particle emitter lives forever */ - kCCParticleDurationInfinity = -1, - - /** The starting size of the particle is equal to the ending size */ - kCCParticleStartSizeEqualToEndSize = -1, - - /** The starting radius of the particle is equal to the ending radius */ - kCCParticleStartRadiusEqualToEndRadius = -1, - - // backward compatible - kParticleStartSizeEqualToEndSize = kCCParticleStartSizeEqualToEndSize, - kParticleDurationInfinity = kCCParticleDurationInfinity, -}; - -//* @enum -enum { - /** Gravity mode (A mode) */ - kCCParticleModeGravity, - - /** Radius mode (B mode) */ - kCCParticleModeRadius, -}; - - -/** @typedef tCCPositionType - possible types of particle positions - */ -typedef enum { - /** Living particles are attached to the world and are unaffected by emitter repositioning. */ - kCCPositionTypeFree, - - /** Living particles are attached to the world but will follow the emitter repositioning. - Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite. - */ - kCCPositionTypeRelative, - - /** Living particles are attached to the emitter and are translated along with it. */ - kCCPositionTypeGrouped, -}tCCPositionType; - -// backward compatible -enum { - kPositionTypeFree = kCCPositionTypeFree, - kPositionTypeGrouped = kCCPositionTypeGrouped, -}; - -/** @struct tCCParticle - Structure that contains the values of each particle - */ -typedef struct sCCParticle { - CGPoint pos; - CGPoint startPos; - - ccColor4F color; - ccColor4F deltaColor; - - float size; - float deltaSize; - - float rotation; - float deltaRotation; - - ccTime timeToLive; - - NSUInteger atlasIndex; - - union { - // Mode A: gravity, direction, radial accel, tangential accel - struct { - CGPoint dir; - float radialAccel; - float tangentialAccel; - } A; - - // Mode B: radius mode - struct { - float angle; - float degreesPerSecond; - float radius; - float deltaRadius; - } B; - } mode; - -}tCCParticle; - -typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CGPoint); - -@class CCTexture2D; - -/** Particle System base class - Attributes of a Particle System: - - emmision rate of the particles - - Gravity Mode (Mode A): - - gravity - - direction - - speed +- variance - - tangential acceleration +- variance - - radial acceleration +- variance - - Radius Mode (Mode B): - - startRadius +- variance - - endRadius +- variance - - rotate +- variance - - Properties common to all modes: - - life +- life variance - - start spin +- variance - - end spin +- variance - - start size +- variance - - end size +- variance - - start color +- variance - - end color +- variance - - life +- variance - - blending function - - texture - - cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/). - 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, - cocos2d uses a another approach, but the results are almost identical. - - cocos2d supports all the variables used by Particle Designer plus a bit more: - - spinning particles (supported when using CCParticleSystemQuad) - - tangential acceleration (Gravity mode) - - radial acceleration (Gravity mode) - - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only) - - It is possible to customize any of the above mentioned properties in runtime. Example: - - @code - emitter.radialAccel = 15; - emitter.startSpin = 0; - @endcode - - */ -@interface CCParticleSystem : CCNode -{ - // is the particle system active ? - BOOL active; - // duration in seconds of the system. -1 is infinity - float duration; - // time elapsed since the start of the system (in seconds) - float elapsed; - - // position is from "superclass" CocosNode - CGPoint sourcePosition; - // Position variance - CGPoint posVar; - - // The angle (direction) of the particles measured in degrees - float angle; - // Angle variance measured in degrees; - float angleVar; - - // Different modes - - NSInteger emitterMode_; - union { - // Mode A:Gravity + Tangential Accel + Radial Accel - struct { - // gravity of the particles - CGPoint gravity; - - // The speed the particles will have. - float speed; - // The speed variance - float speedVar; - - // Tangential acceleration - float tangentialAccel; - // Tangential acceleration variance - float tangentialAccelVar; - - // Radial acceleration - float radialAccel; - // Radial acceleration variance - float radialAccelVar; - } A; - - // Mode B: circular movement (gravity, radial accel and tangential accel don't are not used in this mode) - struct { - - // The starting radius of the particles - float startRadius; - // The starting radius variance of the particles - float startRadiusVar; - // The ending radius of the particles - float endRadius; - // The ending radius variance of the particles - float endRadiusVar; - // Number of degress to rotate a particle around the source pos per second - float rotatePerSecond; - // Variance in degrees for rotatePerSecond - float rotatePerSecondVar; - } B; - } mode; - - // start ize of the particles - float startSize; - // start Size variance - float startSizeVar; - // End size of the particle - float endSize; - // end size of variance - float endSizeVar; - - // How many seconds will the particle live - float life; - // Life variance - float lifeVar; - - // Start color of the particles - ccColor4F startColor; - // Start color variance - ccColor4F startColorVar; - // End color of the particles - ccColor4F endColor; - // End color variance - ccColor4F endColorVar; - - // start angle of the particles - float startSpin; - // start angle variance - float startSpinVar; - // End angle of the particle - float endSpin; - // end angle ariance - float endSpinVar; - - // Array of particles - tCCParticle *particles; - // Maximum particles - NSUInteger totalParticles; - // Count of active particles - NSUInteger particleCount; - // Number of allocated particles - NSUInteger allocatedParticles; - - // How many particles can be emitted per second - float emissionRate; - float emitCounter; - - // Texture of the particles - CCTexture2D *texture_; - // blend function - ccBlendFunc blendFunc_; - - // movment type: free or grouped - tCCPositionType positionType_; - - // Whether or not the node will be auto-removed when there are not particles - BOOL autoRemoveOnFinish_; - - // particle idx - NSUInteger particleIdx; - - // Optimization - CC_UPDATE_PARTICLE_IMP updateParticleImp; - SEL updateParticleSel; - - // for batching. If nil, then it won't be batched - CCParticleBatchNode *batchNode_; - - // index of system in batch node array - NSUInteger atlasIndex_; - - //YES if scaled or rotated - BOOL transformSystemDirty_; -} - -/** Is the emitter active */ -@property (nonatomic,readonly) BOOL active; -/** Quantity of particles that are being simulated at the moment */ -@property (nonatomic,readonly) NSUInteger particleCount; -/** How many seconds the emitter wil run. -1 means 'forever' */ -@property (nonatomic,readwrite,assign) float duration; -/** sourcePosition of the emitter */ -@property (nonatomic,readwrite,assign) CGPoint sourcePosition; -/** Position variance of the emitter */ -@property (nonatomic,readwrite,assign) CGPoint posVar; -/** life, and life variation of each particle */ -@property (nonatomic,readwrite,assign) float life; -/** life variance of each particle */ -@property (nonatomic,readwrite,assign) float lifeVar; -/** angle and angle variation of each particle */ -@property (nonatomic,readwrite,assign) float angle; -/** angle variance of each particle */ -@property (nonatomic,readwrite,assign) float angleVar; - -/** Gravity value. Only available in 'Gravity' mode. */ -@property (nonatomic,readwrite,assign) CGPoint gravity; -/** speed of each particle. Only available in 'Gravity' mode. */ -@property (nonatomic,readwrite,assign) float speed; -/** speed variance of each particle. Only available in 'Gravity' mode. */ -@property (nonatomic,readwrite,assign) float speedVar; -/** tangential acceleration of each particle. Only available in 'Gravity' mode. */ -@property (nonatomic,readwrite,assign) float tangentialAccel; -/** tangential acceleration variance of each particle. Only available in 'Gravity' mode. */ -@property (nonatomic,readwrite,assign) float tangentialAccelVar; -/** radial acceleration of each particle. Only available in 'Gravity' mode. */ -@property (nonatomic,readwrite,assign) float radialAccel; -/** radial acceleration variance of each particle. Only available in 'Gravity' mode. */ -@property (nonatomic,readwrite,assign) float radialAccelVar; - -/** The starting radius of the particles. Only available in 'Radius' mode. */ -@property (nonatomic,readwrite,assign) float startRadius; -/** The starting radius variance of the particles. Only available in 'Radius' mode. */ -@property (nonatomic,readwrite,assign) float startRadiusVar; -/** The ending radius of the particles. Only available in 'Radius' mode. */ -@property (nonatomic,readwrite,assign) float endRadius; -/** The ending radius variance of the particles. Only available in 'Radius' mode. */ -@property (nonatomic,readwrite,assign) float endRadiusVar; -/** Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. */ -@property (nonatomic,readwrite,assign) float rotatePerSecond; -/** Variance in degrees for rotatePerSecond. Only available in 'Radius' mode. */ -@property (nonatomic,readwrite,assign) float rotatePerSecondVar; - -/** start size in pixels of each particle */ -@property (nonatomic,readwrite,assign) float startSize; -/** size variance in pixels of each particle */ -@property (nonatomic,readwrite,assign) float startSizeVar; -/** end size in pixels of each particle */ -@property (nonatomic,readwrite,assign) float endSize; -/** end size variance in pixels of each particle */ -@property (nonatomic,readwrite,assign) float endSizeVar; -/** start color of each particle */ -@property (nonatomic,readwrite,assign) ccColor4F startColor; -/** start color variance of each particle */ -@property (nonatomic,readwrite,assign) ccColor4F startColorVar; -/** end color and end color variation of each particle */ -@property (nonatomic,readwrite,assign) ccColor4F endColor; -/** end color variance of each particle */ -@property (nonatomic,readwrite,assign) ccColor4F endColorVar; -//* initial angle of each particle -@property (nonatomic,readwrite,assign) float startSpin; -//* initial angle of each particle -@property (nonatomic,readwrite,assign) float startSpinVar; -//* initial angle of each particle -@property (nonatomic,readwrite,assign) float endSpin; -//* initial angle of each particle -@property (nonatomic,readwrite,assign) float endSpinVar; -/** emission rate of the particles */ -@property (nonatomic,readwrite,assign) float emissionRate; -/** maximum particles of the system */ -@property (nonatomic,readwrite,assign) NSUInteger totalParticles; -/** conforms to CocosNodeTexture protocol */ -@property (nonatomic,readwrite, retain) CCTexture2D * texture; -/** conforms to CocosNodeTexture protocol */ -@property (nonatomic,readwrite) ccBlendFunc blendFunc; -/** whether or not the particles are using blend additive. - If enabled, the following blending function will be used. - @code - source blend function = GL_SRC_ALPHA; - dest blend function = GL_ONE; - @endcode - */ -@property (nonatomic,readwrite) BOOL blendAdditive; -/** particles movement type: Free or Grouped - @since v0.8 - */ -@property (nonatomic,readwrite) tCCPositionType positionType; -/** whether or not the node will be auto-removed when it has no particles left. - By default it is NO. - @since v0.8 - */ -@property (nonatomic,readwrite) BOOL autoRemoveOnFinish; -/** Switch between different kind of emitter modes: - - kCCParticleModeGravity: uses gravity, speed, radial and tangential acceleration - - kCCParticleModeRadius: uses radius movement + rotation - */ -@property (nonatomic,readwrite) NSInteger emitterMode; - -/** weak reference to the CCSpriteBatchNode that renders the CCSprite */ -@property (nonatomic,readwrite,assign) CCParticleBatchNode *batchNode; - -@property (nonatomic,readwrite) NSUInteger atlasIndex; - -/** creates an initializes a CCParticleSystem from a plist file. - This plist files can be creted manually or with Particle Designer: - http://particledesigner.71squared.com/ - @since v0.99.3 - */ -+(id) particleWithFile:(NSString*)plistFile; - -/** initializes a CCParticleSystem from a plist file. - This plist files can be creted manually or with Particle Designer: - http://particledesigner.71squared.com/ - @since v0.99.3 - */ --(id) initWithFile:(NSString*) plistFile; - -/** initializes a particle system from a NSDictionary. - @since v0.99.3 - */ --(id) initWithDictionary:(NSDictionary*)dictionary; - -//! Initializes a system with a fixed number of particles --(id) initWithTotalParticles:(NSUInteger) numberOfParticles; -//! stop emitting particles. Running particles will continue to run until they die --(void) stopSystem; -//! Kill all living particles. --(void) resetSystem; -//! whether or not the system is full --(BOOL) isFull; - -//! should be overriden by subclasses --(void) updateQuadWithParticle:(tCCParticle*)particle newPosition:(CGPoint)pos; -//! should be overriden by subclasses --(void) postStep; - -//! called in every loop. --(void) update: (ccTime) dt; - --(void) updateWithNoTime; - -@end diff --git a/Example/libs/cocos2d/CCParticleSystem.m b/Example/libs/cocos2d/CCParticleSystem.m deleted file mode 100644 index 6146ffd..0000000 --- a/Example/libs/cocos2d/CCParticleSystem.m +++ /dev/null @@ -1,872 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -// ideas taken from: -// . The ocean spray in your face [Jeff Lander] -// http://www.double.co.nz/dust/col0798.pdf -// . Building an Advanced Particle System [John van der Burg] -// http://www.gamasutra.com/features/20000623/vanderburg_01.htm -// . LOVE game engine -// http://love2d.org/ -// -// -// Radius mode support, from 71 squared -// http://particledesigner.71squared.com/ -// -// IMPORTANT: Particle Designer is supported by cocos2d, but -// 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, -// cocos2d uses a another approach, but the results are almost identical. -// - -// opengl -#import "Platforms/CCGL.h" - -// cocos2d -#import "ccConfig.h" -#import "CCParticleSystem.h" -#import "CCParticleBatchNode.h" -#import "CCTextureCache.h" -#import "CCTextureAtlas.h" -#import "ccMacros.h" -#import "Support/CCProfiling.h" - -// support -#import "Support/OpenGL_Internal.h" -#import "Support/CGPointExtension.h" -#import "Support/base64.h" -#import "Support/ZipUtils.h" -#import "Support/CCFileUtils.h" - -@implementation CCParticleSystem -@synthesize active, duration; -@synthesize sourcePosition, posVar; -@synthesize particleCount; -@synthesize life, lifeVar; -@synthesize angle, angleVar; -@synthesize startColor, startColorVar, endColor, endColorVar; -@synthesize startSpin, startSpinVar, endSpin, endSpinVar; -@synthesize emissionRate; -@synthesize startSize, startSizeVar; -@synthesize endSize, endSizeVar; -@synthesize blendFunc = blendFunc_; -@synthesize positionType = positionType_; -@synthesize autoRemoveOnFinish = autoRemoveOnFinish_; -@synthesize emitterMode = emitterMode_; -@synthesize atlasIndex = atlasIndex_; - -+(id) particleWithFile:(NSString*) plistFile -{ - return [[[self alloc] initWithFile:plistFile] autorelease]; -} - --(id) init { - return [self initWithTotalParticles:150]; -} - --(id) initWithFile:(NSString *)plistFile -{ - NSString *path = [CCFileUtils fullPathFromRelativePath:plistFile]; - NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - - NSAssert( dict != nil, @"Particles: file not found"); - return [self initWithDictionary:dict]; -} - --(id) initWithDictionary:(NSDictionary *)dictionary -{ - NSUInteger maxParticles = [[dictionary valueForKey:@"maxParticles"] integerValue]; - // self, not super - - if ((self=[self initWithTotalParticles:maxParticles] ) ) - { - // angle - angle = [[dictionary valueForKey:@"angle"] floatValue]; - angleVar = [[dictionary valueForKey:@"angleVariance"] floatValue]; - - // duration - duration = [[dictionary valueForKey:@"duration"] floatValue]; - - // blend function - blendFunc_.src = [[dictionary valueForKey:@"blendFuncSource"] intValue]; - blendFunc_.dst = [[dictionary valueForKey:@"blendFuncDestination"] intValue]; - - // color - float r,g,b,a; - - r = [[dictionary valueForKey:@"startColorRed"] floatValue]; - g = [[dictionary valueForKey:@"startColorGreen"] floatValue]; - b = [[dictionary valueForKey:@"startColorBlue"] floatValue]; - a = [[dictionary valueForKey:@"startColorAlpha"] floatValue]; - startColor = (ccColor4F) {r,g,b,a}; - - r = [[dictionary valueForKey:@"startColorVarianceRed"] floatValue]; - g = [[dictionary valueForKey:@"startColorVarianceGreen"] floatValue]; - b = [[dictionary valueForKey:@"startColorVarianceBlue"] floatValue]; - a = [[dictionary valueForKey:@"startColorVarianceAlpha"] floatValue]; - startColorVar = (ccColor4F) {r,g,b,a}; - - r = [[dictionary valueForKey:@"finishColorRed"] floatValue]; - g = [[dictionary valueForKey:@"finishColorGreen"] floatValue]; - b = [[dictionary valueForKey:@"finishColorBlue"] floatValue]; - a = [[dictionary valueForKey:@"finishColorAlpha"] floatValue]; - endColor = (ccColor4F) {r,g,b,a}; - - r = [[dictionary valueForKey:@"finishColorVarianceRed"] floatValue]; - g = [[dictionary valueForKey:@"finishColorVarianceGreen"] floatValue]; - b = [[dictionary valueForKey:@"finishColorVarianceBlue"] floatValue]; - a = [[dictionary valueForKey:@"finishColorVarianceAlpha"] floatValue]; - endColorVar = (ccColor4F) {r,g,b,a}; - - // particle size - startSize = [[dictionary valueForKey:@"startParticleSize"] floatValue]; - startSizeVar = [[dictionary valueForKey:@"startParticleSizeVariance"] floatValue]; - endSize = [[dictionary valueForKey:@"finishParticleSize"] floatValue]; - endSizeVar = [[dictionary valueForKey:@"finishParticleSizeVariance"] floatValue]; - - // position - float x = [[dictionary valueForKey:@"sourcePositionx"] floatValue]; - float y = [[dictionary valueForKey:@"sourcePositiony"] floatValue]; - self.position = ccp(x,y); - posVar.x = [[dictionary valueForKey:@"sourcePositionVariancex"] floatValue]; - posVar.y = [[dictionary valueForKey:@"sourcePositionVariancey"] floatValue]; - - // Spinning - startSpin = [[dictionary valueForKey:@"rotationStart"] floatValue]; - startSpinVar = [[dictionary valueForKey:@"rotationStartVariance"] floatValue]; - endSpin = [[dictionary valueForKey:@"rotationEnd"] floatValue]; - endSpinVar = [[dictionary valueForKey:@"rotationEndVariance"] floatValue]; - - emitterMode_ = [[dictionary valueForKey:@"emitterType"] intValue]; - - // Mode A: Gravity + tangential accel + radial accel - if( emitterMode_ == kCCParticleModeGravity ) { - // gravity - mode.A.gravity.x = [[dictionary valueForKey:@"gravityx"] floatValue]; - mode.A.gravity.y = [[dictionary valueForKey:@"gravityy"] floatValue]; - - // - // speed - mode.A.speed = [[dictionary valueForKey:@"speed"] floatValue]; - mode.A.speedVar = [[dictionary valueForKey:@"speedVariance"] floatValue]; - - // radial acceleration - NSString *tmp = [dictionary valueForKey:@"radialAcceleration"]; - mode.A.radialAccel = tmp ? [tmp floatValue] : 0; - - tmp = [dictionary valueForKey:@"radialAccelVariance"]; - mode.A.radialAccelVar = tmp ? [tmp floatValue] : 0; - - // tangential acceleration - tmp = [dictionary valueForKey:@"tangentialAcceleration"]; - mode.A.tangentialAccel = tmp ? [tmp floatValue] : 0; - - tmp = [dictionary valueForKey:@"tangentialAccelVariance"]; - mode.A.tangentialAccelVar = tmp ? [tmp floatValue] : 0; - } - - // or Mode B: radius movement - else if( emitterMode_ == kCCParticleModeRadius ) { - float maxRadius = [[dictionary valueForKey:@"maxRadius"] floatValue]; - float maxRadiusVar = [[dictionary valueForKey:@"maxRadiusVariance"] floatValue]; - float minRadius = [[dictionary valueForKey:@"minRadius"] floatValue]; - - mode.B.startRadius = maxRadius; - mode.B.startRadiusVar = maxRadiusVar; - mode.B.endRadius = minRadius; - mode.B.endRadiusVar = 0; - mode.B.rotatePerSecond = [[dictionary valueForKey:@"rotatePerSecond"] floatValue]; - mode.B.rotatePerSecondVar = [[dictionary valueForKey:@"rotatePerSecondVariance"] floatValue]; - - } else { - NSAssert( NO, @"Invalid emitterType in config file"); - } - - // life span - life = [[dictionary valueForKey:@"particleLifespan"] floatValue]; - lifeVar = [[dictionary valueForKey:@"particleLifespanVariance"] floatValue]; - - // emission Rate - emissionRate = totalParticles/life; - - //don't get the internal texture if a batchNode is used - if (!batchNode_) - { - // texture - // Try to get the texture from the cache - NSString *textureName = [dictionary valueForKey:@"textureFileName"]; - - CCTexture2D *tex = [[CCTextureCache sharedTextureCache] addImage:textureName]; - - if( tex ) - [self setTexture:tex]; - else { - - NSString *textureData = [dictionary valueForKey:@"textureImageData"]; - NSAssert( textureData, @"CCParticleSystem: Couldn't load texture"); - - // if it fails, try to get it from the base64-gzipped data - unsigned char *buffer = NULL; - int len = base64Decode((unsigned char*)[textureData UTF8String], (unsigned int)[textureData length], &buffer); - NSAssert( buffer != NULL, @"CCParticleSystem: error decoding textureImageData"); - - unsigned char *deflated = NULL; - NSUInteger deflatedLen = ccInflateMemory(buffer, len, &deflated); - free( buffer ); - - NSAssert( deflated != NULL, @"CCParticleSystem: error ungzipping textureImageData"); - NSData *data = [[NSData alloc] initWithBytes:deflated length:deflatedLen]; - -#ifdef __CC_PLATFORM_IOS - UIImage *image = [[UIImage alloc] initWithData:data]; -#elif defined(__CC_PLATFORM_MAC) - NSBitmapImageRep *image = [[NSBitmapImageRep alloc] initWithData:data]; -#endif - - free(deflated); deflated = NULL; - - [self setTexture: [ [CCTextureCache sharedTextureCache] addCGImage:[image CGImage] forKey:textureName]]; - [data release]; - [image release]; - } - - NSAssert( [self texture] != NULL, @"CCParticleSystem: error loading the texture"); - } - } - - return self; -} - --(id) initWithTotalParticles:(NSUInteger) numberOfParticles -{ - if( (self=[super init]) ) { - - totalParticles = numberOfParticles; - - particles = calloc( totalParticles, sizeof(tCCParticle) ); - - if( ! particles ) { - CCLOG(@"Particle system: not enough memory"); - [self release]; - return nil; - } - allocatedParticles = numberOfParticles; - - if (batchNode_) - { - for (int i = 0; i < totalParticles; i++) - { - particles[i].atlasIndex=i; - } - } - - // default, active - active = YES; - - // default blend function - blendFunc_ = (ccBlendFunc) { CC_BLEND_SRC, CC_BLEND_DST }; - - // default movement type; - positionType_ = kCCPositionTypeFree; - - // by default be in mode A: - emitterMode_ = kCCParticleModeGravity; - - autoRemoveOnFinish_ = NO; - - // Optimization: compile udpateParticle method - updateParticleSel = @selector(updateQuadWithParticle:newPosition:); - updateParticleImp = (CC_UPDATE_PARTICLE_IMP) [self methodForSelector:updateParticleSel]; - - //for batchNode - transformSystemDirty_ = NO; - - // udpate after action in run! - [self scheduleUpdateWithPriority:1]; - } - return self; -} - --(void) dealloc -{ - free( particles ); - - [texture_ release]; - - [super dealloc]; -} - --(void) initParticle: (tCCParticle*) particle -{ - //CGPoint currentPosition = position_; - // timeToLive - // no negative life. prevent division by 0 - particle->timeToLive = life + lifeVar * CCRANDOM_MINUS1_1(); - particle->timeToLive = MAX(0, particle->timeToLive); - - // position - particle->pos.x = sourcePosition.x + posVar.x * CCRANDOM_MINUS1_1(); - particle->pos.y = sourcePosition.y + posVar.y * CCRANDOM_MINUS1_1(); - - // Color - ccColor4F start; - start.r = clampf( startColor.r + startColorVar.r * CCRANDOM_MINUS1_1(), 0, 1); - start.g = clampf( startColor.g + startColorVar.g * CCRANDOM_MINUS1_1(), 0, 1); - start.b = clampf( startColor.b + startColorVar.b * CCRANDOM_MINUS1_1(), 0, 1); - start.a = clampf( startColor.a + startColorVar.a * CCRANDOM_MINUS1_1(), 0, 1); - - ccColor4F end; - end.r = clampf( endColor.r + endColorVar.r * CCRANDOM_MINUS1_1(), 0, 1); - end.g = clampf( endColor.g + endColorVar.g * CCRANDOM_MINUS1_1(), 0, 1); - end.b = clampf( endColor.b + endColorVar.b * CCRANDOM_MINUS1_1(), 0, 1); - end.a = clampf( endColor.a + endColorVar.a * CCRANDOM_MINUS1_1(), 0, 1); - - particle->color = start; - particle->deltaColor.r = (end.r - start.r) / particle->timeToLive; - particle->deltaColor.g = (end.g - start.g) / particle->timeToLive; - particle->deltaColor.b = (end.b - start.b) / particle->timeToLive; - particle->deltaColor.a = (end.a - start.a) / particle->timeToLive; - - // size - float startS = startSize + startSizeVar * CCRANDOM_MINUS1_1(); - startS = MAX(0, startS); // No negative value - - particle->size = startS; - if( endSize == kCCParticleStartSizeEqualToEndSize ) - particle->deltaSize = 0; - else { - float endS = endSize + endSizeVar * CCRANDOM_MINUS1_1(); - endS = MAX(0, endS); // No negative values - particle->deltaSize = (endS - startS) / particle->timeToLive; - } - - // rotation - float startA = startSpin + startSpinVar * CCRANDOM_MINUS1_1(); - float endA = endSpin + endSpinVar * CCRANDOM_MINUS1_1(); - particle->rotation = startA; - particle->deltaRotation = (endA - startA) / particle->timeToLive; - - // position - if( positionType_ == kCCPositionTypeFree ) - particle->startPos = [self convertToWorldSpace:CGPointZero]; - - else if( positionType_ == kCCPositionTypeRelative ) - particle->startPos = position_; - - - // direction - float a = CC_DEGREES_TO_RADIANS( angle + angleVar * CCRANDOM_MINUS1_1() ); - - // Mode Gravity: A - if( emitterMode_ == kCCParticleModeGravity ) { - - CGPoint v = {cosf( a ), sinf( a )}; - float s = mode.A.speed + mode.A.speedVar * CCRANDOM_MINUS1_1(); - - // direction - particle->mode.A.dir = ccpMult( v, s ); - - // radial accel - particle->mode.A.radialAccel = mode.A.radialAccel + mode.A.radialAccelVar * CCRANDOM_MINUS1_1(); - - // tangential accel - particle->mode.A.tangentialAccel = mode.A.tangentialAccel + mode.A.tangentialAccelVar * CCRANDOM_MINUS1_1(); - } - - // Mode Radius: B - else { - // Set the default diameter of the particle from the source position - float startRadius = mode.B.startRadius + mode.B.startRadiusVar * CCRANDOM_MINUS1_1(); - float endRadius = mode.B.endRadius + mode.B.endRadiusVar * CCRANDOM_MINUS1_1(); - - particle->mode.B.radius = startRadius; - - if( mode.B.endRadius == kCCParticleStartRadiusEqualToEndRadius ) - particle->mode.B.deltaRadius = 0; - else - particle->mode.B.deltaRadius = (endRadius - startRadius) / particle->timeToLive; - - particle->mode.B.angle = a; - particle->mode.B.degreesPerSecond = CC_DEGREES_TO_RADIANS(mode.B.rotatePerSecond + mode.B.rotatePerSecondVar * CCRANDOM_MINUS1_1()); - } -} - --(BOOL) addParticle -{ - if( [self isFull] ) - return NO; - - tCCParticle * particle = &particles[ particleCount ]; - - [self initParticle: particle]; - particleCount++; - - return YES; -} - --(void) stopSystem -{ - active = NO; - elapsed = duration; - emitCounter = 0; -} - --(void) resetSystem -{ - active = YES; - elapsed = 0; - for(particleIdx = 0; particleIdx < particleCount; ++particleIdx) { - tCCParticle *p = &particles[particleIdx]; - p->timeToLive = 0; - } - -} - --(BOOL) isFull -{ - return (particleCount == totalParticles); -} - -#pragma mark ParticleSystem - MainLoop --(void) update: (ccTime) dt -{ - CC_PROFILER_START_CATEGORY(kCCProfilerCategoryParticles , @"CCParticleSystem - update"); - - if( active && emissionRate ) { - float rate = 1.0f / emissionRate; - - //issue #1201, prevent bursts of particles, due to too high emitCounter - if (particleCount < totalParticles) - emitCounter += dt; - - while( particleCount < totalParticles && emitCounter > rate ) { - [self addParticle]; - emitCounter -= rate; - } - - elapsed += dt; - - if(duration != -1 && duration < elapsed) - [self stopSystem]; - } - - particleIdx = 0; - - CGPoint currentPosition = CGPointZero; - if( positionType_ == kCCPositionTypeFree ) - currentPosition = [self convertToWorldSpace:CGPointZero]; - - else if( positionType_ == kCCPositionTypeRelative ) - currentPosition = position_; - - if (visible_) - { - while( particleIdx < particleCount ) - { - tCCParticle *p = &particles[particleIdx]; - - // life - p->timeToLive -= dt; - - if( p->timeToLive > 0 ) { - - // Mode A: gravity, direction, tangential accel & radial accel - if( emitterMode_ == kCCParticleModeGravity ) { - CGPoint tmp, radial, tangential; - - radial = CGPointZero; - // radial acceleration - if(p->pos.x || p->pos.y) - radial = ccpNormalize(p->pos); - - tangential = radial; - radial = ccpMult(radial, p->mode.A.radialAccel); - - // tangential acceleration - float newy = tangential.x; - tangential.x = -tangential.y; - tangential.y = newy; - tangential = ccpMult(tangential, p->mode.A.tangentialAccel); - - // (gravity + radial + tangential) * dt - tmp = ccpAdd( ccpAdd( radial, tangential), mode.A.gravity); - tmp = ccpMult( tmp, dt); - p->mode.A.dir = ccpAdd( p->mode.A.dir, tmp); - tmp = ccpMult(p->mode.A.dir, dt); - p->pos = ccpAdd( p->pos, tmp ); - } - - // Mode B: radius movement - else { - // Update the angle and radius of the particle. - p->mode.B.angle += p->mode.B.degreesPerSecond * dt; - p->mode.B.radius += p->mode.B.deltaRadius * dt; - - p->pos.x = - cosf(p->mode.B.angle) * p->mode.B.radius; - p->pos.y = - sinf(p->mode.B.angle) * p->mode.B.radius; - } - - // color - p->color.r += (p->deltaColor.r * dt); - p->color.g += (p->deltaColor.g * dt); - p->color.b += (p->deltaColor.b * dt); - p->color.a += (p->deltaColor.a * dt); - - // size - p->size += (p->deltaSize * dt); - p->size = MAX( 0, p->size ); - - // angle - p->rotation += (p->deltaRotation * dt); - - // - // update values in quad - // - - CGPoint newPos; - - if( positionType_ == kCCPositionTypeFree || positionType_ == kCCPositionTypeRelative ) - { - CGPoint diff = ccpSub( currentPosition, p->startPos ); - newPos = ccpSub(p->pos, diff); - } else - newPos = p->pos; - - // translate newPos to correct position, since matrix transform isn't performed in batchnode - // don't update the particle with the new position information, it will interfere with the radius and tangential calculations - if (batchNode_) - { - newPos.x+=position_.x; - newPos.y+=position_.y; - } - - updateParticleImp(self, updateParticleSel, p, newPos); - - // update particle counter - particleIdx++; - - } else { - // life < 0 - NSInteger currentIndex = p->atlasIndex; - - if( particleIdx != particleCount-1 ) - particles[particleIdx] = particles[particleCount-1]; - - if (batchNode_) - { - //disable the switched particle - [batchNode_ disableParticle:(atlasIndex_+currentIndex)]; - - //switch indexes - particles[particleCount-1].atlasIndex = currentIndex; - } - - particleCount--; - - if( particleCount == 0 && autoRemoveOnFinish_ ) { - [self unscheduleUpdate]; - [parent_ removeChild:self cleanup:YES]; - return; - } - } - }//while - transformSystemDirty_ = NO; - } - - if (!batchNode_) - [self postStep]; - - CC_PROFILER_STOP_CATEGORY(kCCProfilerCategoryParticles , @"CCParticleSystem - update"); -} - --(void) updateWithNoTime -{ - [self update:0.0f]; -} - --(void) updateQuadWithParticle:(tCCParticle*)particle newPosition:(CGPoint)pos; -{ - // should be overriden -} - --(void) postStep -{ - // should be overriden -} - -#pragma mark ParticleSystem - CCTexture protocol - --(void) setTexture:(CCTexture2D*) texture -{ - texture_ = [texture retain]; - - // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it - if( texture_ && ! [texture hasPremultipliedAlpha] && - ( blendFunc_.src == CC_BLEND_SRC && blendFunc_.dst == CC_BLEND_DST ) ) { - - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; - } -} - --(CCTexture2D*) texture -{ - return texture_; -} - -#pragma mark ParticleSystem - Additive Blending --(void) setBlendAdditive:(BOOL)additive -{ - if( additive ) { - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE; - - } else { - - if( texture_ && ! [texture_ hasPremultipliedAlpha] ) { - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; - } else { - blendFunc_.src = CC_BLEND_SRC; - blendFunc_.dst = CC_BLEND_DST; - } - } -} - --(BOOL) blendAdditive -{ - return( blendFunc_.src == GL_SRC_ALPHA && blendFunc_.dst == GL_ONE); -} - -#pragma mark ParticleSystem - Total Particles Property - -- (void) setTotalParticles:(NSUInteger)tp -{ - NSAssert( tp <= allocatedParticles, @"Particle: resizing particle array only supported for quads"); - totalParticles = tp; -} - -- (NSUInteger) totalParticles -{ - return totalParticles; -} - -#pragma mark ParticleSystem - Properties of Gravity Mode --(void) setTangentialAccel:(float)t -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - mode.A.tangentialAccel = t; -} --(float) tangentialAccel -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - return mode.A.tangentialAccel; -} - --(void) setTangentialAccelVar:(float)t -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - mode.A.tangentialAccelVar = t; -} --(float) tangentialAccelVar -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - return mode.A.tangentialAccelVar; -} - --(void) setRadialAccel:(float)t -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - mode.A.radialAccel = t; -} --(float) radialAccel -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - return mode.A.radialAccel; -} - --(void) setRadialAccelVar:(float)t -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - mode.A.radialAccelVar = t; -} --(float) radialAccelVar -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - return mode.A.radialAccelVar; -} - --(void) setGravity:(CGPoint)g -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - mode.A.gravity = g; -} --(CGPoint) gravity -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - return mode.A.gravity; -} - --(void) setSpeed:(float)speed -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - mode.A.speed = speed; -} --(float) speed -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - return mode.A.speed; -} - --(void) setSpeedVar:(float)speedVar -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - mode.A.speedVar = speedVar; -} --(float) speedVar -{ - NSAssert( emitterMode_ == kCCParticleModeGravity, @"Particle Mode should be Gravity"); - return mode.A.speedVar; -} - -#pragma mark ParticleSystem - Properties of Radius Mode - --(void) setStartRadius:(float)startRadius -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - mode.B.startRadius = startRadius; -} --(float) startRadius -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - return mode.B.startRadius; -} - --(void) setStartRadiusVar:(float)startRadiusVar -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - mode.B.startRadiusVar = startRadiusVar; -} --(float) startRadiusVar -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - return mode.B.startRadiusVar; -} - --(void) setEndRadius:(float)endRadius -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - mode.B.endRadius = endRadius; -} --(float) endRadius -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - return mode.B.endRadius; -} - --(void) setEndRadiusVar:(float)endRadiusVar -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - mode.B.endRadiusVar = endRadiusVar; -} --(float) endRadiusVar -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - return mode.B.endRadiusVar; -} - --(void) setRotatePerSecond:(float)degrees -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - mode.B.rotatePerSecond = degrees; -} --(float) rotatePerSecond -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - return mode.B.rotatePerSecond; -} - --(void) setRotatePerSecondVar:(float)degrees -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - mode.B.rotatePerSecondVar = degrees; -} --(float) rotatePerSecondVar -{ - NSAssert( emitterMode_ == kCCParticleModeRadius, @"Particle Mode should be Radius"); - return mode.B.rotatePerSecondVar; -} - -#pragma mark ParticleSystem - methods for batchNode rendering - --(CCParticleBatchNode*) batchNode -{ - return batchNode_; -} - --(void) setBatchNode:(CCParticleBatchNode*) batchNode -{ - if( batchNode_ != batchNode ) { - - batchNode_ = batchNode; // weak reference - - if( batchNode ) { - //each particle needs a unique index - for (int i = 0; i < totalParticles; i++) - { - particles[i].atlasIndex=i; - } - } - } -} - -//don't use a transform matrix, this is faster --(void) setScale:(float) s -{ - transformSystemDirty_ = YES; - [super setScale:s]; -} - --(void) setRotation: (float)newRotation -{ - transformSystemDirty_ = YES; - [super setRotation:newRotation]; -} - --(void) setScaleX: (float)newScaleX -{ - transformSystemDirty_ = YES; - [super setScaleX:newScaleX]; -} - --(void) setScaleY: (float)newScaleY -{ - transformSystemDirty_ = YES; - [super setScaleY:newScaleY]; -} - - -@end diff --git a/Example/libs/cocos2d/CCParticleSystemQuad.h b/Example/libs/cocos2d/CCParticleSystemQuad.h deleted file mode 100644 index c515ca8..0000000 --- a/Example/libs/cocos2d/CCParticleSystemQuad.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Leonardo Kasperavičius - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCParticleSystem.h" -#import "ccConfig.h" - -@class CCSpriteFrame; - -/** CCParticleSystemQuad is a subclass of CCParticleSystem - - It includes all the features of ParticleSystem. - - Special features and Limitations: - - Particle size can be any float number. - - The system can be scaled - - The particles can be rotated - - On 1st and 2nd gen iPhones: It is only a bit slower that CCParticleSystemPoint - - On 3rd gen iPhone and iPads: It is MUCH faster than CCParticleSystemPoint - - It consumes more RAM and more GPU memory than CCParticleSystemPoint - - It supports subrects - @since v0.8 - */ -@interface CCParticleSystemQuad : CCParticleSystem -{ - ccV3F_C4B_T2F_Quad *quads_; // quads to be rendered - GLushort *indices_; // indices - GLuint VAOname_; - GLuint buffersVBO_[2]; //0: vertex 1: indices -} - -/** initialices the indices for the vertices */ --(void) initIndices; - -/** initilizes the texture with a rectangle measured Points */ --(void) initTexCoordsWithRect:(CGRect)rect; - -/** Sets a new CCSpriteFrame as particle. - WARNING: this method is experimental. Use setTexture:withRect instead. - @since v0.99.4 - */ --(void)setDisplayFrame:(CCSpriteFrame*)spriteFrame; - -/** Sets a new texture with a rect. The rect is in Points. - @since v0.99.4 - */ --(void) setTexture:(CCTexture2D *)texture withRect:(CGRect)rect; - -@end - diff --git a/Example/libs/cocos2d/CCParticleSystemQuad.m b/Example/libs/cocos2d/CCParticleSystemQuad.m deleted file mode 100644 index 3a67a7b..0000000 --- a/Example/libs/cocos2d/CCParticleSystemQuad.m +++ /dev/null @@ -1,502 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Leonardo Kasperavičius - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -// opengl -#import "Platforms/CCGL.h" - -// cocos2d -#import "ccConfig.h" -#import "CCParticleSystemQuad.h" -#import "CCParticleBatchNode.h" -#import "CCTextureAtlas.h" -#import "CCTextureCache.h" -#import "ccMacros.h" -#import "CCSpriteFrame.h" -#import "CCDirector.h" -#import "CCShaderCache.h" -#import "ccGLStateCache.h" -#import "CCGLProgram.h" - -// support -#import "Support/OpenGL_Internal.h" -#import "Support/CGPointExtension.h" -#import "Support/TransformUtils.h" - -// extern -#import "kazmath/GL/matrix.h" - -@interface CCParticleSystemQuad () --(void) initVAO; --(BOOL) allocMemory; -@end - -@implementation CCParticleSystemQuad - -// overriding the init method --(id) initWithTotalParticles:(NSUInteger) numberOfParticles -{ - // base initialization - if( (self=[super initWithTotalParticles:numberOfParticles]) ) { - - // allocating data space - if( ! [self allocMemory] ) { - [self release]; - return nil; - } - - // Don't initialize the texCoords yet since there are not textures -// [self initTexCoordsWithRect:CGRectMake(0, 0, [texture_ pixelsWide], [texture_ pixelsHigh])]; - - [self initIndices]; - [self initVAO]; - - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; - } - - return self; -} - --(BOOL) allocMemory -{ - NSAssert( ( !quads_ && !indices_), @"Memory already alloced"); - NSAssert( !batchNode_, @"Memory should not be alloced when not using batchNode"); - - quads_ = calloc( sizeof(quads_[0]) * totalParticles, 1 ); - indices_ = calloc( sizeof(indices_[0]) * totalParticles * 6, 1 ); - - if( !quads_ || !indices_) { - CCLOG(@"cocos2d: Particle system: not enough memory"); - if( quads_ ) - free( quads_ ); - if(indices_) - free(indices_); - - return NO; - } - - return YES; -} - -- (void) setTotalParticles:(NSUInteger)tp -{ - // If we are setting the total numer of particles to a number higher - // than what is allocated, we need to allocate new arrays - if( tp > allocatedParticles ) - { - // Allocate new memory - size_t particlesSize = tp * sizeof(tCCParticle); - size_t quadsSize = sizeof(quads_[0]) * tp * 1; - size_t indicesSize = sizeof(indices_[0]) * tp * 6 * 1; - - tCCParticle* particlesNew = realloc(particles, particlesSize); - ccV3F_C4B_T2F_Quad *quadsNew = realloc(quads_, quadsSize); - GLushort* indicesNew = realloc(indices_, indicesSize); - - if (particlesNew && quadsNew && indicesNew) - { - // Assign pointers - particles = particlesNew; - quads_ = quadsNew; - indices_ = indicesNew; - - // Clear the memory - memset(particles, 0, particlesSize); - memset(quads_, 0, quadsSize); - memset(indices_, 0, indicesSize); - - allocatedParticles = tp; - } - else - { - // Out of memory, failed to resize some array - if (particlesNew) particles = particlesNew; - if (quadsNew) quads_ = quadsNew; - if (indicesNew) indices_ = indicesNew; - - CCLOG(@"Particle system: out of memory"); - return; - } - - totalParticles = tp; - - // Init particles - if (batchNode_) - { - for (int i = 0; i < totalParticles; i++) - { - particles[i].atlasIndex=i; - } - } - - [self initIndices]; - [self initVAO]; - } - else - { - totalParticles = tp; - } -} - --(void) initVAO -{ - glGenVertexArrays(1, &VAOname_); - glBindVertexArray(VAOname_); - -#define kQuadSize sizeof(quads_[0].bl) - - glGenBuffers(2, &buffersVBO_[0]); - - glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * totalParticles, quads_, GL_DYNAMIC_DRAW); - - // vertices - glEnableVertexAttribArray(kCCVertexAttrib_Position); - glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, vertices)); - - // colors - glEnableVertexAttribArray(kCCVertexAttrib_Color); - glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, colors)); - - // tex coords - glEnableVertexAttribArray(kCCVertexAttrib_TexCoords); - glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, texCoords)); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffersVBO_[1]); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices_[0]) * totalParticles * 6, indices_, GL_STATIC_DRAW); - - glBindVertexArray(0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - glBindBuffer(GL_ARRAY_BUFFER, 0); - - CHECK_GL_ERROR_DEBUG(); -} - --(void) dealloc -{ - if( ! batchNode_ ) { - free(quads_); - free(indices_); - - glDeleteBuffers(2, &buffersVBO_[0]); - glDeleteVertexArrays(1, &VAOname_); - } - - [super dealloc]; -} - -// pointRect is in Points coordinates. --(void) initTexCoordsWithRect:(CGRect)pointRect -{ - // convert to Tex coords - - CGRect rect = CGRectMake( - pointRect.origin.x * CC_CONTENT_SCALE_FACTOR(), - pointRect.origin.y * CC_CONTENT_SCALE_FACTOR(), - pointRect.size.width * CC_CONTENT_SCALE_FACTOR(), - pointRect.size.height * CC_CONTENT_SCALE_FACTOR() ); - - GLfloat wide = [texture_ pixelsWide]; - GLfloat high = [texture_ pixelsHigh]; - -#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - GLfloat left = (rect.origin.x*2+1) / (wide*2); - GLfloat bottom = (rect.origin.y*2+1) / (high*2); - GLfloat right = left + (rect.size.width*2-2) / (wide*2); - GLfloat top = bottom + (rect.size.height*2-2) / (high*2); -#else - GLfloat left = rect.origin.x / wide; - GLfloat bottom = rect.origin.y / high; - GLfloat right = left + rect.size.width / wide; - GLfloat top = bottom + rect.size.height / high; -#endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - - // Important. Texture in cocos2d are inverted, so the Y component should be inverted -//<<<<<<< HEAD - CC_SWAP( top, bottom); - - ccV3F_C4B_T2F_Quad *quads; - NSUInteger start, end; - if (batchNode_) - { - quads = [[batchNode_ textureAtlas] quads]; - start = atlasIndex_; - end = atlasIndex_ + totalParticles; - } - else - { - quads = quads_; - start = 0; - end = totalParticles; - } - - for(NSUInteger i=start; i>>>>>> develop - } -} - --(void) setTexture:(CCTexture2D *)texture withRect:(CGRect)rect -{ - // Only update the texture if is different from the current one - if( [texture name] != [texture_ name] ) - [super setTexture:texture]; - - [self initTexCoordsWithRect:rect]; -} - --(void) setTexture:(CCTexture2D *)texture -{ - CGSize s = [texture contentSize]; - [self setTexture:texture withRect:CGRectMake(0,0, s.width, s.height)]; -} - --(void) setDisplayFrame:(CCSpriteFrame *)spriteFrame -{ - - NSAssert( CGPointEqualToPoint( spriteFrame.offsetInPixels , CGPointZero ), @"QuadParticle only supports SpriteFrames with no offsets"); - - // update texture before updating texture rect - if ( spriteFrame.texture.name != texture_.name ) - [self setTexture: spriteFrame.texture]; -} - --(void) initIndices -{ - for( NSUInteger i = 0; i < totalParticles; i++) { - const NSUInteger i6 = i*6; - const NSUInteger i4 = i*4; - indices_[i6+0] = (GLushort) i4+0; - indices_[i6+1] = (GLushort) i4+1; - indices_[i6+2] = (GLushort) i4+2; - - indices_[i6+5] = (GLushort) i4+1; - indices_[i6+4] = (GLushort) i4+2; - indices_[i6+3] = (GLushort) i4+3; - } -} - --(void) updateQuadWithParticle:(tCCParticle*)p newPosition:(CGPoint)newPos -{ - ccV3F_C4B_T2F_Quad *quad; - - if (batchNode_) - { - ccV3F_C4B_T2F_Quad *batchQuads = [[batchNode_ textureAtlas] quads]; - quad = &(batchQuads[atlasIndex_+p->atlasIndex]); - } - else - quad = &(quads_[particleIdx]); - - ccColor4B color = { p->color.r*255, p->color.g*255, p->color.b*255, p->color.a*255}; - quad->bl.colors = color; - quad->br.colors = color; - quad->tl.colors = color; - quad->tr.colors = color; - - // vertices - GLfloat size_2 = p->size/2; - if( p->rotation ) { - GLfloat x1 = -size_2; - GLfloat y1 = -size_2; - - GLfloat x2 = size_2; - GLfloat y2 = size_2; - GLfloat x = newPos.x; - GLfloat y = newPos.y; - - GLfloat r = (GLfloat)-CC_DEGREES_TO_RADIANS(p->rotation); - GLfloat cr = cosf(r); - GLfloat sr = sinf(r); - GLfloat ax = x1 * cr - y1 * sr + x; - GLfloat ay = x1 * sr + y1 * cr + y; - GLfloat bx = x2 * cr - y1 * sr + x; - GLfloat by = x2 * sr + y1 * cr + y; - GLfloat cx = x2 * cr - y2 * sr + x; - GLfloat cy = x2 * sr + y2 * cr + y; - GLfloat dx = x1 * cr - y2 * sr + x; - GLfloat dy = x1 * sr + y2 * cr + y; - - // bottom-left - quad->bl.vertices.x = ax; - quad->bl.vertices.y = ay; - - // bottom-right vertex: - quad->br.vertices.x = bx; - quad->br.vertices.y = by; - - // top-left vertex: - quad->tl.vertices.x = dx; - quad->tl.vertices.y = dy; - - // top-right vertex: - quad->tr.vertices.x = cx; - quad->tr.vertices.y = cy; - } else { - // bottom-left vertex: - quad->bl.vertices.x = newPos.x - size_2; - quad->bl.vertices.y = newPos.y - size_2; - - // bottom-right vertex: - quad->br.vertices.x = newPos.x + size_2; - quad->br.vertices.y = newPos.y - size_2; - - // top-left vertex: - quad->tl.vertices.x = newPos.x - size_2; - quad->tl.vertices.y = newPos.y + size_2; - - // top-right vertex: - quad->tr.vertices.x = newPos.x + size_2; - quad->tr.vertices.y = newPos.y + size_2; - } -} - --(void) postStep -{ - glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0] ); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(quads_[0])*particleCount, quads_); - glBindBuffer(GL_ARRAY_BUFFER, 0); - - CHECK_GL_ERROR_DEBUG(); -} - -// overriding draw method --(void) draw -{ - NSAssert(!batchNode_,@"draw should not be called when added to a particleBatchNode"); - - CC_NODE_DRAW_SETUP(); - - ccGLBindTexture2D( [texture_ name] ); - ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); - - NSAssert( particleIdx == particleCount, @"Abnormal error in particle quad"); - - glBindVertexArray( VAOname_ ); - - glDrawElements(GL_TRIANGLES, (GLsizei) particleIdx*6, GL_UNSIGNED_SHORT, 0); - - glBindVertexArray( 0 ); - - CC_INCREMENT_GL_DRAWS(1); - - CHECK_GL_ERROR_DEBUG(); -} - --(void) setBatchNode:(CCParticleBatchNode *)batchNode -{ - if( batchNode_ != batchNode ) { - - CCParticleBatchNode *oldBatch = batchNode_; - - [super setBatchNode:batchNode]; - - // NEW: is self render ? - if( ! batchNode ) { - [self allocMemory]; - [self initIndices]; - [self setTexture:[oldBatch texture]]; - [self initVAO]; - } - - // OLD: was it self render ? cleanup - else if( ! oldBatch ) - { - // copy current state to batch - ccV3F_C4B_T2F_Quad *batchQuads = [[batchNode_ textureAtlas] quads]; - ccV3F_C4B_T2F_Quad *quad = &(batchQuads[atlasIndex_] ); - memcpy( quad, quads_, totalParticles * sizeof(quads_[0]) ); - - if (quads_) - free(quads_); - quads_ = NULL; - - if (indices_) - free(indices_); - indices_ = NULL; - - glDeleteBuffers(2, &buffersVBO_[0]); - glDeleteVertexArrays(1, &VAOname_); - } - } -} - -@end diff --git a/Example/libs/cocos2d/CCProgressTimer.h b/Example/libs/cocos2d/CCProgressTimer.h deleted file mode 100644 index ce058d9..0000000 --- a/Example/libs/cocos2d/CCProgressTimer.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Lam Pham - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import -#import "CCSprite.h" - -/** Types of progress - @since v0.99.1 - */ -typedef enum { - /// Radial Counter-Clockwise - kCCProgressTimerTypeRadial, - /// Bar - kCCProgressTimerTypeBar, -} CCProgressTimerType; - -/** - CCProgresstimer is a subclass of CCNode. - It renders the inner sprite according to the percentage. - The progress can be Radial, Horizontal or vertical. - @since v0.99.1 - */ -@interface CCProgressTimer : CCNode { - CCProgressTimerType type_; - float percentage_; - CCSprite *sprite_; - - int vertexDataCount_; - ccV2F_C4B_T2F *vertexData_; - CGPoint midpoint_; - CGPoint barChangeRate_; - BOOL reverseDirection_; -} -@property (nonatomic) ccColor3B color; -@property (nonatomic) GLubyte opacity; -/** Change the percentage to change progress. */ -@property (nonatomic, readwrite) CCProgressTimerType type; -@property (nonatomic, readwrite) BOOL reverseDirection; -@property (nonatomic, readonly) ccV2F_C4B_T2F *vertexData; -@property (nonatomic, readonly) int vertexDataCount; - -/** - * Midpoint is used to modify the progress start position. - * If you're using radials type then the midpoint changes the center point - * If you're using bar type the the midpoint changes the bar growth - * it expands from the center but clamps to the sprites edge so: - * you want a left to right then set the midpoint all the way to ccp(0,y) - * you want a right to left then set the midpoint all the way to ccp(1,y) - * you want a bottom to top then set the midpoint all the way to ccp(x,0) - * you want a top to bottom then set the midpoint all the way to ccp(x,1) - */ -@property (nonatomic, readwrite) CGPoint midpoint; - -/** - * This allows the bar type to move the component at a specific rate - * Set the component to 0 to make sure it stays at 100%. - * For example you want a left to right bar but not have the height stay 100% - * Set the rate to be ccp(0,1); and set the midpoint to = ccp(0,.5f); - */ -@property (nonatomic, readwrite) CGPoint barChangeRate; - -/** Percentages are from 0 to 100 */ -@property (nonatomic, readwrite) float percentage; - -/** The image to show the progress percentage */ -@property (nonatomic, readwrite, retain) CCSprite *sprite; - -/** Creates a progress timer with the sprite as the shape the timer goes through */ -+ (id) progressWithSprite:(CCSprite*) sprite; -/** Initializes a progress timer with the sprite as the shape the timer goes through */ -- (id) initWithSprite:(CCSprite*) sprite; -@end diff --git a/Example/libs/cocos2d/CCProgressTimer.m b/Example/libs/cocos2d/CCProgressTimer.m deleted file mode 100644 index 084b0c6..0000000 --- a/Example/libs/cocos2d/CCProgressTimer.m +++ /dev/null @@ -1,540 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Lam Pham - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCProgressTimer.h" - -#import "ccMacros.h" -#import "CCTextureCache.h" -#import "CCGLProgram.h" -#import "CCShaderCache.h" -#import "ccGLStateCache.h" -#import "CCDirector.h" -#import "Support/CGPointExtension.h" -#import "Support/TransformUtils.h" -#import "CCDrawingPrimitives.h" - -// extern -#import "kazmath/GL/matrix.h" - -#define kProgressTextureCoordsCount 4 -// kProgressTextureCoords holds points {0,1} {0,0} {1,0} {1,1} we can represent it as bits -const char kCCProgressTextureCoords = 0x4b; - -@interface CCProgressTimer () - --(void)updateProgress; --(void)updateBar; --(void)updateRadial; --(void)updateColor; --(CGPoint)boundaryTexCoord:(char)index; -@end - - -@implementation CCProgressTimer -@synthesize percentage = percentage_; -@synthesize sprite = sprite_; -@synthesize type = type_; -@synthesize reverseDirection = reverseDirection_; -@synthesize midpoint = midpoint_; -@synthesize barChangeRate = barChangeRate_; -@synthesize vertexData = vertexData_; -@synthesize vertexDataCount = vertexDataCount_; - -+(id)progressWithSprite:(CCSprite*) sprite -{ - return [[[self alloc]initWithSprite:sprite] autorelease]; -} - --(id) init -{ - return [self initWithSprite:nil]; -} - -// designated initializer --(id)initWithSprite:(CCSprite*) sprite -{ - if(( self = [super init] )){ - percentage_ = 0.f; - vertexData_ = NULL; - vertexDataCount_ = 0; - self.anchorPoint = ccp(0.5f,0.5f); - self.type = kCCProgressTimerTypeRadial; - self.reverseDirection = NO; - self.midpoint = ccp(.5f, .5f); - self.barChangeRate = ccp(1,1); - self.sprite = sprite; - - // shader program - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; - } - return self; -} - --(void)dealloc -{ - if(vertexData_){ - free(vertexData_); - } - [sprite_ release]; - [super dealloc]; -} - --(void)setPercentage:(float) percentage -{ - if(percentage_ != percentage) { - percentage_ = clampf( percentage, 0, 100); - [self updateProgress]; - } -} - --(void)setSprite:(CCSprite *)newSprite -{ - if(sprite_ != newSprite){ - [sprite_ release]; - sprite_ = [newSprite retain]; - self.contentSize = sprite_.contentSize; - - // Everytime we set a new sprite, we free the current vertex data - if(vertexData_){ - free(vertexData_); - vertexData_ = NULL; - vertexDataCount_ = 0; - } - } -} - --(void)setType:(CCProgressTimerType)newType -{ - if (newType != type_) { - - // release all previous information - if(vertexData_){ - free(vertexData_); - vertexData_ = NULL; - vertexDataCount_ = 0; - } - type_ = newType; - } -} - --(void)setReverseProgress:(BOOL)reverse -{ - if( reverseDirection_ != reverse ) { - reverseDirection_ = reverse; - - // release all previous information - if(vertexData_){ - free(vertexData_); - vertexData_ = NULL; - vertexDataCount_ = 0; - } - } -} - --(void)setColor:(ccColor3B)c -{ - sprite_.color = c; - [self updateColor]; -} - --(ccColor3B)color -{ - return sprite_.color; -} - --(void)setOpacity:(GLubyte)o -{ - sprite_.opacity = o; - [self updateColor]; -} - --(GLubyte)opacity -{ - return sprite_.opacity; -} - -#pragma mark ProgressTimer Internal - -/// -// @returns the vertex position from the texture coordinate -/// --(ccTex2F)textureCoordFromAlphaPoint:(CGPoint) alpha -{ - if (!sprite_) { - return (ccTex2F){0,0}; - } - ccV3F_C4B_T2F_Quad quad = sprite_.quad; - CGPoint min = (CGPoint){quad.bl.texCoords.u,quad.bl.texCoords.v}; - CGPoint max = (CGPoint){quad.tr.texCoords.u,quad.tr.texCoords.v}; - // Fix bug #1303 so that progress timer handles sprite frame texture rotation - if (sprite_.textureRectRotated) { - CC_SWAP(alpha.x, alpha.y); - } - return (ccTex2F){min.x * (1.f - alpha.x) + max.x * alpha.x, min.y * (1.f - alpha.y) + max.y * alpha.y}; -} - --(ccVertex2F)vertexFromAlphaPoint:(CGPoint) alpha -{ - if (!sprite_) { - return (ccVertex2F){0.f, 0.f}; - } - ccV3F_C4B_T2F_Quad quad = sprite_.quad; - CGPoint min = (CGPoint){quad.bl.vertices.x,quad.bl.vertices.y}; - CGPoint max = (CGPoint){quad.tr.vertices.x,quad.tr.vertices.y}; - return (ccVertex2F){min.x * (1.f - alpha.x) + max.x * alpha.x, min.y * (1.f - alpha.y) + max.y * alpha.y}; -} - --(void)updateColor -{ - if (!sprite_) { - return; - } - if(vertexData_){ - ccColor4B sc = sprite_.quad.tl.colors; - for (int i=0; i < vertexDataCount_; ++i) { - vertexData_[i].colors = sc; - } - } -} - --(void)updateProgress -{ - switch (type_) { - case kCCProgressTimerTypeRadial: - [self updateRadial]; - break; - case kCCProgressTimerTypeBar: - [self updateBar]; - break; - default: - break; - } -} - --(void)setAnchorPoint:(CGPoint)anchorPoint -{ - [super setAnchorPoint:anchorPoint]; -} - --(CGPoint) midpoint -{ - return midpoint_; -} - --(void)setMidpoint:(CGPoint)midPoint -{ - midpoint_ = ccpClamp(midPoint, CGPointZero, ccp(1,1)); -} - -/// -// Update does the work of mapping the texture onto the triangles -// It now doesn't occur the cost of free/alloc data every update cycle. -// It also only changes the percentage point but no other points if they have not -// been modified. -// -// It now deals with flipped texture. If you run into this problem, just use the -// sprite property and enable the methods flipX, flipY. -/// --(void)updateRadial -{ - if (!sprite_) { - return; - } - - float alpha = percentage_ / 100.f; - - float angle = 2.f*((float)M_PI) * ( reverseDirection_ == YES ? alpha : 1.f - alpha); - - // We find the vector to do a hit detection based on the percentage - // We know the first vector is the one @ 12 o'clock (top,mid) so we rotate - // from that by the progress angle around the midpoint_ pivot - CGPoint topMid = ccp(midpoint_.x, 1.f); - CGPoint percentagePt = ccpRotateByAngle(topMid, midpoint_, angle); - - - int index = 0; - CGPoint hit = CGPointZero; - - if (alpha == 0.f) { - // More efficient since we don't always need to check intersection - // If the alpha is zero then the hit point is top mid and the index is 0. - hit = topMid; - index = 0; - } else if (alpha == 1.f) { - // More efficient since we don't always need to check intersection - // If the alpha is one then the hit point is top mid and the index is 4. - hit = topMid; - index = 4; - } else { - // We run a for loop checking the edges of the texture to find the - // intersection point - // We loop through five points since the top is split in half - - float min_t = FLT_MAX; - - for (int i = 0; i <= kProgressTextureCoordsCount; ++i) { - int pIndex = (i + (kProgressTextureCoordsCount - 1))%kProgressTextureCoordsCount; - - CGPoint edgePtA = [self boundaryTexCoord:i % kProgressTextureCoordsCount]; - CGPoint edgePtB = [self boundaryTexCoord:pIndex]; - - // Remember that the top edge is split in half for the 12 o'clock position - // Let's deal with that here by finding the correct endpoints - if(i == 0){ - edgePtB = ccpLerp(edgePtA, edgePtB, 1 - midpoint_.x); - } else if(i == 4){ - edgePtA = ccpLerp(edgePtA, edgePtB, 1 - midpoint_.x); - } - - // s and t are returned by ccpLineIntersect - float s = 0, t = 0; - if(ccpLineIntersect(edgePtA, edgePtB, midpoint_, percentagePt, &s, &t)) - { - - // Since our hit test is on rays we have to deal with the top edge - // being in split in half so we have to test as a segment - if ((i == 0 || i == 4)) { - // s represents the point between edgePtA--edgePtB - if (!(0.f <= s && s <= 1.f)) { - continue; - } - } - // As long as our t isn't negative we are at least finding a - // correct hitpoint from midpoint_ to percentagePt. - if (t >= 0.f) { - // Because the percentage line and all the texture edges are - // rays we should only account for the shortest intersection - if (t < min_t) { - min_t = t; - index = i; - } - } - } - } - - // Now that we have the minimum magnitude we can use that to find our intersection - hit = ccpAdd(midpoint_, ccpMult(ccpSub(percentagePt, midpoint_),min_t)); - - } - - - // The size of the vertex data is the index from the hitpoint - // the 3 is for the midpoint_, 12 o'clock point and hitpoint position. - - BOOL sameIndexCount = YES; - if(vertexDataCount_ != index + 3){ - sameIndexCount = NO; - if(vertexData_){ - free(vertexData_); - vertexData_ = NULL; - vertexDataCount_ = 0; - } - } - - - if(!vertexData_) { - vertexDataCount_ = index + 3; - vertexData_ = malloc(vertexDataCount_ * sizeof(ccV2F_C4B_T2F)); - NSAssert( vertexData_, @"CCProgressTimer. Not enough memory"); - } - [self updateColor]; - - if (!sameIndexCount) { - - // First we populate the array with the midpoint_, then all - // vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint - vertexData_[0].texCoords = [self textureCoordFromAlphaPoint:midpoint_]; - vertexData_[0].vertices = [self vertexFromAlphaPoint:midpoint_]; - - vertexData_[1].texCoords = [self textureCoordFromAlphaPoint:topMid]; - vertexData_[1].vertices = [self vertexFromAlphaPoint:topMid]; - - for(int i = 0; i < index; ++i){ - CGPoint alphaPoint = [self boundaryTexCoord:i]; - vertexData_[i+2].texCoords = [self textureCoordFromAlphaPoint:alphaPoint]; - vertexData_[i+2].vertices = [self vertexFromAlphaPoint:alphaPoint]; - } - } - - // hitpoint will go last - vertexData_[vertexDataCount_ - 1].texCoords = [self textureCoordFromAlphaPoint:hit]; - vertexData_[vertexDataCount_ - 1].vertices = [self vertexFromAlphaPoint:hit]; -} - -/// -// Update does the work of mapping the texture onto the triangles for the bar -// It now doesn't occur the cost of free/alloc data every update cycle. -// It also only changes the percentage point but no other points if they have not -// been modified. -// -// It now deals with flipped texture. If you run into this problem, just use the -// sprite property and enable the methods flipX, flipY. -/// --(void)updateBar -{ - if (!sprite_) { - return; - } - float alpha = percentage_ / 100.f; - CGPoint alphaOffset = ccpMult(ccp(1.f * (1.f - barChangeRate_.x) + alpha * barChangeRate_.x, 1.f * (1.f - barChangeRate_.y) + alpha * barChangeRate_.y), .5f); - CGPoint min = ccpSub(midpoint_, alphaOffset); - CGPoint max = ccpAdd(midpoint_, alphaOffset); - - if (min.x < 0.f) { - max.x += -min.x; - min.x = 0.f; - } - - if (max.x > 1.f) { - min.x -= max.x - 1.f; - max.x = 1.f; - } - - if (min.y < 0.f) { - max.y += -min.y; - min.y = 0.f; - } - - if (max.y > 1.f) { - min.y -= max.y - 1.f; - max.y = 1.f; - } - - - if (!reverseDirection_) { - if(!vertexData_) { - vertexDataCount_ = 4; - vertexData_ = malloc(vertexDataCount_ * sizeof(ccV2F_C4B_T2F)); - NSAssert( vertexData_, @"CCProgressTimer. Not enough memory"); - } - // TOPLEFT - vertexData_[0].texCoords = [self textureCoordFromAlphaPoint:ccp(min.x,max.y)]; - vertexData_[0].vertices = [self vertexFromAlphaPoint:ccp(min.x,max.y)]; - - // BOTLEFT - vertexData_[1].texCoords = [self textureCoordFromAlphaPoint:ccp(min.x,min.y)]; - vertexData_[1].vertices = [self vertexFromAlphaPoint:ccp(min.x,min.y)]; - - // TOPRIGHT - vertexData_[2].texCoords = [self textureCoordFromAlphaPoint:ccp(max.x,max.y)]; - vertexData_[2].vertices = [self vertexFromAlphaPoint:ccp(max.x,max.y)]; - - // BOTRIGHT - vertexData_[3].texCoords = [self textureCoordFromAlphaPoint:ccp(max.x,min.y)]; - vertexData_[3].vertices = [self vertexFromAlphaPoint:ccp(max.x,min.y)]; - } else { - if(!vertexData_) { - vertexDataCount_ = 8; - vertexData_ = malloc(vertexDataCount_ * sizeof(ccV2F_C4B_T2F)); - NSAssert( vertexData_, @"CCProgressTimer. Not enough memory"); - // TOPLEFT 1 - vertexData_[0].texCoords = [self textureCoordFromAlphaPoint:ccp(0,1)]; - vertexData_[0].vertices = [self vertexFromAlphaPoint:ccp(0,1)]; - - // BOTLEFT 1 - vertexData_[1].texCoords = [self textureCoordFromAlphaPoint:ccp(0,0)]; - vertexData_[1].vertices = [self vertexFromAlphaPoint:ccp(0,0)]; - - // TOPRIGHT 2 - vertexData_[6].texCoords = [self textureCoordFromAlphaPoint:ccp(1,1)]; - vertexData_[6].vertices = [self vertexFromAlphaPoint:ccp(1,1)]; - - // BOTRIGHT 2 - vertexData_[7].texCoords = [self textureCoordFromAlphaPoint:ccp(1,0)]; - vertexData_[7].vertices = [self vertexFromAlphaPoint:ccp(1,0)]; - } - - // TOPRIGHT 1 - vertexData_[2].texCoords = [self textureCoordFromAlphaPoint:ccp(min.x,max.y)]; - vertexData_[2].vertices = [self vertexFromAlphaPoint:ccp(min.x,max.y)]; - - // BOTRIGHT 1 - vertexData_[3].texCoords = [self textureCoordFromAlphaPoint:ccp(min.x,min.y)]; - vertexData_[3].vertices = [self vertexFromAlphaPoint:ccp(min.x,min.y)]; - - // TOPLEFT 2 - vertexData_[4].texCoords = [self textureCoordFromAlphaPoint:ccp(max.x,max.y)]; - vertexData_[4].vertices = [self vertexFromAlphaPoint:ccp(max.x,max.y)]; - - // BOTLEFT 2 - vertexData_[5].texCoords = [self textureCoordFromAlphaPoint:ccp(max.x,min.y)]; - vertexData_[5].vertices = [self vertexFromAlphaPoint:ccp(max.x,min.y)]; - } - [self updateColor]; -} - --(CGPoint)boundaryTexCoord:(char)index -{ - if (index < kProgressTextureCoordsCount) { - if (reverseDirection_) { - return ccp((kCCProgressTextureCoords>>(7-(index<<1)))&1,(kCCProgressTextureCoords>>(7-((index<<1)+1)))&1); - } else { - return ccp((kCCProgressTextureCoords>>((index<<1)+1))&1,(kCCProgressTextureCoords>>(index<<1))&1); - } - } - return CGPointZero; -} - --(void) draw -{ - if( ! vertexData_ || ! sprite_) - return; - - CC_NODE_DRAW_SETUP(); - - ccGLBlendFunc( sprite_.blendFunc.src, sprite_.blendFunc.dst ); - - ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex ); - - ccGLBindTexture2D( sprite_.texture.name ); - - glVertexAttribPointer( kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(vertexData_[0]) , &vertexData_[0].vertices); - glVertexAttribPointer( kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(vertexData_[0]), &vertexData_[0].texCoords); - glVertexAttribPointer( kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(vertexData_[0]), &vertexData_[0].colors); - - if(type_ == kCCProgressTimerTypeRadial) - { - glDrawArrays(GL_TRIANGLE_FAN, 0, vertexDataCount_); - } - else if (type_ == kCCProgressTimerTypeBar) - { - if (!reverseDirection_) - { - glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexDataCount_); - } - else - { - glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexDataCount_/2); - glDrawArrays(GL_TRIANGLE_STRIP, 4, vertexDataCount_/2); - - // 2 draw calls - CC_INCREMENT_GL_DRAWS(1); - } - } - CC_INCREMENT_GL_DRAWS(1); - -} - -@end diff --git a/Example/libs/cocos2d/CCProtocols.h b/Example/libs/cocos2d/CCProtocols.h deleted file mode 100644 index e55ec92..0000000 --- a/Example/libs/cocos2d/CCProtocols.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "ccMacros.h" -#import "ccTypes.h" -#import "CCTexture2D.h" - -#pragma mark - -#pragma mark CCRGBAProtocol - -/// CC RGBA protocol -@protocol CCRGBAProtocol -/** sets Color - @since v0.8 - */ --(void) setColor:(ccColor3B)color; -/** returns the color - @since v0.8 - */ --(ccColor3B) color; - -/// returns the opacity --(GLubyte) opacity; -/** sets the opacity. - @warning If the the texture has premultiplied alpha then, the R, G and B channels will be modifed. - Values goes from 0 to 255, where 255 means fully opaque. - */ --(void) setOpacity: (GLubyte) opacity; -@optional -/** sets the premultipliedAlphaOpacity property. - If set to NO then opacity will be applied as: glColor(R,G,B,opacity); - If set to YES then oapcity will be applied as: glColor(opacity, opacity, opacity, opacity ); - Textures with premultiplied alpha will have this property by default on YES. Otherwise the default value is NO - @since v0.8 - */ --(void) setOpacityModifyRGB:(BOOL)boolean; -/** returns whether or not the opacity will be applied using glColor(R,G,B,opacity) or glColor(opacity, opacity, opacity, opacity); - @since v0.8 - */ - -(BOOL) doesOpacityModifyRGB; -@end - -#pragma mark - -#pragma mark CCBlendProtocol -/** - You can specify the blending fuction. - @since v0.99.0 - */ -@protocol CCBlendProtocol -/** set the source blending function for the texture */ --(void) setBlendFunc:(ccBlendFunc)blendFunc; -/** returns the blending function used for the texture */ --(ccBlendFunc) blendFunc; -@end - - -#pragma mark - -#pragma mark CCTextureProtocol - -/** CCNode objects that uses a Texture2D to render the images. - The texture can have a blending function. - If the texture has alpha premultiplied the default blending function is: - src=GL_ONE dst= GL_ONE_MINUS_SRC_ALPHA - else - src=GL_SRC_ALPHA dst= GL_ONE_MINUS_SRC_ALPHA - But you can change the blending funtion at any time. - @since v0.8.0 - */ -@protocol CCTextureProtocol -/** returns the used texture */ --(CCTexture2D*) texture; -/** sets a new texture. it will be retained */ --(void) setTexture:(CCTexture2D*)texture; -@end - -#pragma mark - -#pragma mark CCLabelProtocol -/** Common interface for Labels */ -@protocol CCLabelProtocol -/** sets a new label using an NSString. - The string will be copied. - */ --(void) setString:(NSString*)label; -/** returns the string that is rendered */ --(NSString*) string; -@optional -/** sets a new label using a CString. - It is faster than setString since it doesn't require to alloc/retain/release an NString object. - @since v0.99.0 - */ --(void) setCString:(char*)label; -@end - - -#pragma mark - -#pragma mark CCDirectorDelegate -/** CCDirector delegate */ -@protocol CCDirectorDelegate - -@optional -/** Called by CCDirector when the porjection is updated, and "custom" projection is used */ --(void) updateProjection; - -#ifdef __CC_PLATFORM_IOS -/** Returns a Boolean value indicating whether the CCDirector supports the specified orientation. Default value is YES (supports all possible orientations) */ -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; - -#endif // __CC_PLATFORM_IOS - -@end diff --git a/Example/libs/cocos2d/CCRenderTexture.h b/Example/libs/cocos2d/CCRenderTexture.h deleted file mode 100644 index d71d19c..0000000 --- a/Example/libs/cocos2d/CCRenderTexture.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Jason Booth - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import - -#import "ccMacros.h" -#import "CCNode.h" -#import "CCSprite.h" -#import "Support/OpenGL_Internal.h" -#import "kazmath/mat4.h" - -#ifdef __CC_PLATFORM_IOS -#import -#endif // iPHone - -typedef enum -{ - kCCImageFormatJPEG = 0, - kCCImageFormatPNG = 1, -} tCCImageFormat; - - -/** - CCRenderTexture is a generic rendering target. To render things into it, - simply construct a render target, call begin on it, call visit on any cocos2d - scenes or objects to render them, and call end. For convienience, render texture - adds a sprite as its display child with the results, so you can simply add - the render texture to your scene and treat it like any other CCNode. - There are also functions for saving the render texture to disk in PNG or JPG format. - - @since v0.8.1 - */ -@interface CCRenderTexture : CCNode -{ - GLuint fbo_; - GLint oldFBO_; - CCTexture2D* texture_; - CCSprite* sprite_; - - GLenum pixelFormat_; -} - -/** The CCSprite being used. - The sprite, by default, will use the following blending function: GL_ONE, GL_ONE_MINUS_SRC_ALPHA. - The blending function can be changed in runtime by calling: - - [[renderTexture sprite] setBlendFunc:(ccBlendFunc){GL_ONE, GL_ONE_MINUS_SRC_ALPHA}]; -*/ -@property (nonatomic,readwrite, assign) CCSprite* sprite; - -/** creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */ -+(id)renderTextureWithWidth:(int)w height:(int)h pixelFormat:(CCTexture2DPixelFormat) format; - -/** creates a RenderTexture object with width and height in Points, pixel format is RGBA8888 */ -+(id)renderTextureWithWidth:(int)w height:(int)h; - -/** initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */ --(id)initWithWidth:(int)w height:(int)h pixelFormat:(CCTexture2DPixelFormat) format; - -/** starts grabbing */ --(void)begin; - -/** starts rendering to the texture while clearing the texture first. - This is more efficient then calling -clear first and then -begin */ --(void)beginWithClear:(float)r g:(float)g b:(float)b a:(float)a; - -/** ends grabbing */ --(void)end; - -/** clears the texture with a color */ --(void)clear:(float)r g:(float)g b:(float)b a:(float)a; - -/* creates a new CGImage from with the texture's data. - Caller is responsible for releasing it by calling CGImageRelease(). - */ --(CGImageRef) newCGImage; - -/** saves the texture into a file using JPEG format. The file will be saved in the Documents folder. - Returns YES if the operation is successful. - */ --(BOOL)saveToFile:(NSString*)name; - -/** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder. - Returns YES if the operation is successful. - */ --(BOOL)saveToFile:(NSString*)name format:(tCCImageFormat)format; - -#ifdef __CC_PLATFORM_IOS - -/* returns an autoreleased UIImage from the texture */ --(UIImage *) getUIImage; - -#endif // __CC_PLATFORM_IOS - -@end - diff --git a/Example/libs/cocos2d/CCRenderTexture.m b/Example/libs/cocos2d/CCRenderTexture.m deleted file mode 100644 index 9af0374..0000000 --- a/Example/libs/cocos2d/CCRenderTexture.m +++ /dev/null @@ -1,356 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Jason Booth - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCRenderTexture.h" -#import "CCDirector.h" -#import "ccMacros.h" -#import "CCGLProgram.h" -#import "ccGLStateCache.h" -#import "CCConfiguration.h" -#import "Support/ccUtils.h" -#import "Support/CCFileUtils.h" - -#if __CC_PLATFORM_MAC -#import -#endif - -// extern -#import "kazmath/GL/matrix.h" - -@implementation CCRenderTexture - -@synthesize sprite=sprite_; - -// issue #994 -+(id)renderTextureWithWidth:(int)w height:(int)h pixelFormat:(CCTexture2DPixelFormat) format -{ - return [[[self alloc] initWithWidth:w height:h pixelFormat:format] autorelease]; -} - -+(id)renderTextureWithWidth:(int)w height:(int)h -{ - return [[[self alloc] initWithWidth:w height:h pixelFormat:kCCTexture2DPixelFormat_RGBA8888] autorelease]; -} - --(id)initWithWidth:(int)w height:(int)h -{ - return [self initWithWidth:w height:h pixelFormat:kCCTexture2DPixelFormat_RGBA8888]; -} - --(id)initWithWidth:(int)w height:(int)h pixelFormat:(CCTexture2DPixelFormat) format -{ - if ((self = [super init])) - { - NSAssert(format != kCCTexture2DPixelFormat_A8,@"only RGB and RGBA formats are valid for a render texture"); - - CCDirector *director = [CCDirector sharedDirector]; - - // XXX multithread - if( [director runningThread] != [NSThread currentThread] ) - CCLOG(@"cocos2d: WARNING. CCRenderTexture is running on its own thread. Make sure that an OpenGL context is being used on this thread!"); - - - w *= CC_CONTENT_SCALE_FACTOR(); - h *= CC_CONTENT_SCALE_FACTOR(); - - glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFBO_); - - // textures must be power of two - NSUInteger powW; - NSUInteger powH; - - if( [[CCConfiguration sharedConfiguration] supportsNPOT] ) { - powW = w; - powH = h; - } else { - powW = ccNextPOT(w); - powH = ccNextPOT(h); - } - - void *data = malloc((int)(powW * powH * 4)); - memset(data, 0, (int)(powW * powH * 4)); - pixelFormat_=format; - - texture_ = [[CCTexture2D alloc] initWithData:data pixelFormat:pixelFormat_ pixelsWide:powW pixelsHigh:powH contentSize:CGSizeMake(w, h)]; - free( data ); - - // generate FBO - glGenFramebuffers(1, &fbo_); - glBindFramebuffer(GL_FRAMEBUFFER, fbo_); - - // associate texture with FBO - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_.name, 0); - - // check if it worked (probably worth doing :) ) - NSAssert( glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, @"Could not attach texture to framebuffer"); - - [texture_ setAliasTexParameters]; - - sprite_ = [CCSprite spriteWithTexture:texture_]; - - [texture_ release]; - [sprite_ setScaleY:-1]; - [self addChild:sprite_]; - - // issue #937 - [sprite_ setBlendFunc:(ccBlendFunc){GL_ONE, GL_ONE_MINUS_SRC_ALPHA}]; - - glBindFramebuffer(GL_FRAMEBUFFER, oldFBO_); - } - return self; -} - --(void)dealloc -{ - glDeleteFramebuffers(1, &fbo_); - - [super dealloc]; -} - --(void)begin -{ - CCDirector *director = [CCDirector sharedDirector]; - - // Save the current matrix - kmGLPushMatrix(); - - CGSize texSize = [texture_ contentSizeInPixels]; - - - // Calculate the adjustment ratios based on the old and new projections - CGSize size = [director winSizeInPixels]; - float widthRatio = size.width / texSize.width; - float heightRatio = size.height / texSize.height; - - - // Adjust the orthographic projection and viewport - glViewport(0, 0, texSize.width * CC_CONTENT_SCALE_FACTOR(), texSize.height * CC_CONTENT_SCALE_FACTOR() ); - - // special viewport for 3d projection + retina display - if ( director.projection == kCCDirectorProjection3D && CC_CONTENT_SCALE_FACTOR() != 1 ) - glViewport(-texSize.width/2, -texSize.height/2, texSize.width * CC_CONTENT_SCALE_FACTOR(), texSize.height * CC_CONTENT_SCALE_FACTOR() ); - - kmMat4 orthoMatrix; - kmMat4OrthographicProjection(&orthoMatrix, (float)-1.0 / widthRatio, (float)1.0 / widthRatio, - (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 ); - kmGLMultMatrix(&orthoMatrix); - - glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFBO_); - glBindFramebuffer(GL_FRAMEBUFFER, fbo_); -} - --(void)beginWithClear:(float)r g:(float)g b:(float)b a:(float)a -{ - [self begin]; - - // save clear color - GLfloat clearColor[4]; - glGetFloatv(GL_COLOR_CLEAR_VALUE,clearColor); - - glClearColor(r, g, b, a); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - // restore clear color - glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); -} - --(void)end -{ - CCDirector *director = [CCDirector sharedDirector]; - - glBindFramebuffer(GL_FRAMEBUFFER, oldFBO_); - - kmGLPopMatrix(); - - CGSize size = [director winSizeInPixels]; - - // restore viewport - glViewport(0, 0, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); - - // special viewport for 3d projection + retina display - if ( director.projection == kCCDirectorProjection3D && CC_CONTENT_SCALE_FACTOR() != 1 ) - glViewport(-size.width/2, -size.height/2, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); - - [director setProjection:director.projection]; -} - --(void)clear:(float)r g:(float)g b:(float)b a:(float)a -{ - [self beginWithClear:r g:g b:b a:a]; - [self end]; -} - -#pragma mark RenderTexture - Save Image - --(CGImageRef) newCGImage -{ - NSAssert(pixelFormat_ == kCCTexture2DPixelFormat_RGBA8888,@"only RGBA8888 can be saved as image"); - - - CGSize s = [texture_ contentSizeInPixels]; - int tx = s.width; - int ty = s.height; - - int bitsPerComponent = 8; - int bitsPerPixel = 32; - int bytesPerPixel = (bitsPerComponent * 4)/8; - int bytesPerRow = bytesPerPixel * tx; - NSInteger myDataLength = bytesPerRow * ty; - - GLubyte *buffer = calloc(myDataLength,1); - GLubyte *pixels = calloc(myDataLength,1); - - - if( ! (buffer && pixels) ) { - CCLOG(@"cocos2d: CCRenderTexture#getCGImageFromBuffer: not enough memory"); - free(buffer); - free(pixels); - return nil; - } - - [self begin]; - - - glReadPixels(0,0,tx,ty,GL_RGBA,GL_UNSIGNED_BYTE, buffer); - - [self end]; - - // make data provider with data. - - CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault; - CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer, myDataLength, NULL); - CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); - CGImageRef iref = CGImageCreate(tx, ty, - bitsPerComponent, bitsPerPixel, bytesPerRow, - colorSpaceRef, bitmapInfo, provider, - NULL, false, - kCGRenderingIntentDefault); - - CGContextRef context = CGBitmapContextCreate(pixels, tx, - ty, CGImageGetBitsPerComponent(iref), - CGImageGetBytesPerRow(iref), CGImageGetColorSpace(iref), - bitmapInfo); - - // vertically flipped - if( YES ) { - CGContextTranslateCTM(context, 0.0f, ty); - CGContextScaleCTM(context, 1.0f, -1.0f); - } - CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, tx, ty), iref); - CGImageRef image = CGBitmapContextCreateImage(context); - - CGImageRelease(iref); - CGContextRelease(context); - CGColorSpaceRelease(colorSpaceRef); - CGDataProviderRelease(provider); - - free(pixels); - free(buffer); - - return image; -} - --(BOOL) saveToFile:(NSString*)name -{ - return [self saveToFile:name format:kCCImageFormatJPEG]; -} - --(BOOL)saveToFile:(NSString*)fileName format:(tCCImageFormat)format -{ - BOOL success; - - NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName]; - - CGImageRef imageRef = [self newCGImage]; - - if( ! imageRef ) { - CCLOG(@"cocos2d: Error: Cannot create CGImage ref from texture"); - return NO; - } - -#if __CC_PLATFORM_IOS - - UIImage* image = [[UIImage alloc] initWithCGImage:imageRef scale:CC_CONTENT_SCALE_FACTOR() orientation:UIImageOrientationUp]; - NSData *imageData; - - if( format == kCCImageFormatPNG ) - imageData = UIImagePNGRepresentation( image ); - - else if( format == kCCImageFormatJPEG ) - imageData = UIImageJPEGRepresentation(image, 0.9f); - - else - NSAssert(NO, @"Unsupported format"); - - [image release]; - - success = [imageData writeToFile:fullPath atomically:YES]; - - -#elif __CC_PLATFORM_MAC - - CFURLRef url = (CFURLRef)[NSURL fileURLWithPath:fullPath]; - - CGImageDestinationRef dest; - - if( format == kCCImageFormatPNG ) - dest = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL); - - else if( format == kCCImageFormatJPEG ) - dest = CGImageDestinationCreateWithURL(url, kUTTypeJPEG, 1, NULL); - - else - NSAssert(NO, @"Unsupported format"); - - CGImageDestinationAddImage(dest, imageRef, nil); - - success = CGImageDestinationFinalize(dest); - - CFRelease(dest); -#endif - - CGImageRelease(imageRef); - - if( ! success ) - CCLOG(@"cocos2d: ERROR: Failed to save file:%@ to disk",fullPath); - - return success; -} - - -#if __CC_PLATFORM_IOS - --(UIImage *) getUIImage -{ - CGImageRef imageRef = [self newCGImage]; - - UIImage* image = [[UIImage alloc] initWithCGImage:imageRef scale:CC_CONTENT_SCALE_FACTOR() orientation:UIImageOrientationUp]; - - CGImageRelease( imageRef ); - - return [image autorelease]; -} -#endif // __CC_PLATFORM_IOS -@end diff --git a/Example/libs/cocos2d/CCScene.h b/Example/libs/cocos2d/CCScene.h deleted file mode 100644 index 36b9085..0000000 --- a/Example/libs/cocos2d/CCScene.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCNode.h" - -/** CCScene is a subclass of CCNode that is used only as an abstract concept. - - CCScene an CCNode are almost identical with the difference that CCScene has its - anchor point (by default) at the center of the screen. - - For the moment CCScene has no other logic than that, but in future releases it might have - additional logic. - - It is a good practice to use and CCScene as the parent of all your nodes. -*/ -@interface CCScene : CCNode -{ -} -@end diff --git a/Example/libs/cocos2d/CCScene.m b/Example/libs/cocos2d/CCScene.m deleted file mode 100644 index 8c0f4a5..0000000 --- a/Example/libs/cocos2d/CCScene.m +++ /dev/null @@ -1,45 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCScene.h" -#import "Support/CGPointExtension.h" -#import "CCDirector.h" - - -@implementation CCScene --(id) init -{ - if( (self=[super init]) ) { - CGSize s = [[CCDirector sharedDirector] winSize]; - self.isRelativeAnchorPoint = NO; - anchorPoint_ = ccp(0.5f, 0.5f); - [self setContentSize:s]; - } - - return self; -} -@end diff --git a/Example/libs/cocos2d/CCScheduler.h b/Example/libs/cocos2d/CCScheduler.h deleted file mode 100644 index 32ca9ca..0000000 --- a/Example/libs/cocos2d/CCScheduler.h +++ /dev/null @@ -1,200 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - - -#import "Support/uthash.h" -#import "ccTypes.h" - -typedef void (*TICK_IMP)(id, SEL, ccTime); - -// -// CCTimer -// -/** Light weight timer */ -@interface CCTimer : NSObject -{ - id target; - TICK_IMP impMethod; - - ccTime elapsed; - BOOL runForever; - BOOL useDelay; - uint nTimesExecuted; - uint repeat; //0 = once, 1 is 2 x executed - ccTime delay; - -@public // optimization - ccTime interval; - SEL selector; -} -/** interval in seconds */ -@property (nonatomic,readwrite,assign) ccTime interval; - -/** Allocates a timer with a target and a selector. -*/ -+(id) timerWithTarget:(id) t selector:(SEL)s; - -/** Allocates a timer with a target, a selector and an interval in seconds. -*/ -+(id) timerWithTarget:(id) t selector:(SEL)s interval:(ccTime)seconds; - -/** Initializes a timer with a target and a selector. -*/ - -(id) initWithTarget:(id) t selector:(SEL)s; - -/** Initializes a timer with a target, a selector, an interval in seconds, repeat in number of times to repeat, delay in seconds -*/ --(id) initWithTarget:(id)t selector:(SEL)s interval:(ccTime) seconds repeat:(uint) r delay:(ccTime) d; - - -/** triggers the timer */ --(void) update: (ccTime) dt; -@end - - - -// -// CCScheduler -// -/** CCScheduler is responsible of triggering the scheduled callbacks. - You should not use NSTimer. Instead use this class. - - There are 2 different types of callbacks (selectors): - - - update selector: the 'update' selector will be called every frame. You can customize the priority. - - custom selector: A custom selector will be called every frame, or with a custom interval of time - - The 'custom selectors' should be avoided when possible. It is faster, and consumes less memory to use the 'update selector'. - -*/ - -struct _listEntry; -struct _hashSelectorEntry; -struct _hashUpdateEntry; - -@interface CCScheduler : NSObject -{ - ccTime timeScale_; - - // - // "updates with priority" stuff - // - struct _listEntry *updatesNeg; // list of priority < 0 - struct _listEntry *updates0; // list priority == 0 - struct _listEntry *updatesPos; // list priority > 0 - struct _hashUpdateEntry *hashForUpdates; // hash used to fetch quickly the list entries for pause,delete,etc. - - // Used for "selectors with interval" - struct _hashSelectorEntry *hashForSelectors; - struct _hashSelectorEntry *currentTarget; - BOOL currentTargetSalvaged; - - // Optimization - TICK_IMP impMethod; - SEL updateSelector; - - BOOL updateHashLocked; // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. -} - -/** Modifies the time of all scheduled callbacks. - You can use this property to create a 'slow motion' or 'fast fordward' effect. - Default is 1.0. To create a 'slow motion' effect, use values below 1.0. - To create a 'fast fordward' effect, use values higher than 1.0. - @since v0.8 - @warning It will affect EVERY scheduled selector / action. - */ -@property (nonatomic,readwrite) ccTime timeScale; - -/** 'update' the scheduler. - You should NEVER call this method, unless you know what you are doing. - */ --(void) update:(ccTime)dt; - -/** The scheduled method will be called every 'interval' seconds. - If paused is YES, then it won't be called until it is resumed. - If 'interval' is 0, it will be called every frame, but if so, it recommened to use 'scheduleUpdateForTarget:' instead. - If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again. - repeat let the action be repeated repeat + 1 times, use kCCRepeatForever to let the action run continiously - delay is the amount of time the action will wait before it'll start - - @since v0.99.3, repeat and delay added in v1.1 - */ --(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused repeat: (uint) repeat delay: (ccTime) delay; - -/** calls scheduleSelector with kCCRepeatForever and a 0 delay */ --(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused; - -/** Schedules the 'update' selector for a given target with a given priority. - The 'update' selector will be called every frame. - The lower the priority, the earlier it is called. - @since v0.99.3 - */ --(void) scheduleUpdateForTarget:(id)target priority:(NSInteger)priority paused:(BOOL)paused; - -/** Unshedules a selector for a given target. - If you want to unschedule the "update", use unscheudleUpdateForTarget. - @since v0.99.3 - */ --(void) unscheduleSelector:(SEL)selector forTarget:(id)target; - -/** Unschedules the update selector for a given target - @since v0.99.3 - */ --(void) unscheduleUpdateForTarget:(id)target; - -/** Unschedules all selectors for a given target. - This also includes the "update" selector. - @since v0.99.3 - */ --(void) unscheduleAllSelectorsForTarget:(id)target; - -/** Unschedules all selectors from all targets. - You should NEVER call this method, unless you know what you are doing. - - @since v0.99.3 - */ --(void) unscheduleAllSelectors; - -/** Pauses the target. - All scheduled selectors/update for a given target won't be 'ticked' until the target is resumed. - If the target is not present, nothing happens. - @since v0.99.3 - */ --(void) pauseTarget:(id)target; - -/** Resumes the target. - The 'target' will be unpaused, so all schedule selectors/update will be 'ticked' again. - If the target is not present, nothing happens. - @since v0.99.3 - */ --(void) resumeTarget:(id)target; - -/** Returns whether or not the target is paused - @since v1.0.0 - */ --(BOOL) isTargetPaused:(id)target; - -@end diff --git a/Example/libs/cocos2d/CCScheduler.m b/Example/libs/cocos2d/CCScheduler.m deleted file mode 100644 index 73c8eac..0000000 --- a/Example/libs/cocos2d/CCScheduler.m +++ /dev/null @@ -1,688 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -// cocos2d imports -#import "CCScheduler.h" -#import "ccMacros.h" -#import "CCDirector.h" -#import "Support/uthash.h" -#import "Support/utlist.h" -#import "Support/ccCArray.h" - -// -// Data structures -// -#pragma mark - -#pragma mark Data Structures - -// A list double-linked list used for "updates with priority" -typedef struct _listEntry -{ - struct _listEntry *prev, *next; - TICK_IMP impMethod; - id target; // not retained (retained by hashUpdateEntry) - NSInteger priority; - BOOL paused; - BOOL markedForDeletion; // selector will no longer be called and entry will be removed at end of the next tick -} tListEntry; - -typedef struct _hashUpdateEntry -{ - tListEntry **list; // Which list does it belong to ? - tListEntry *entry; // entry in the list - id target; // hash key (retained) - UT_hash_handle hh; -} tHashUpdateEntry; - -// Hash Element used for "selectors with interval" -typedef struct _hashSelectorEntry -{ - struct ccArray *timers; - id target; // hash key (retained) - unsigned int timerIndex; - CCTimer *currentTimer; - BOOL currentTimerSalvaged; - BOOL paused; - UT_hash_handle hh; -} tHashSelectorEntry; - - - -// -// CCTimer -// -#pragma mark - -#pragma mark - CCTimer - -@implementation CCTimer - -@synthesize interval; - --(id) init -{ - NSAssert(NO, @"CCTimer: Init not supported."); - [self release]; - return nil; -} - -+(id) timerWithTarget:(id)t selector:(SEL)s -{ - return [[[self alloc] initWithTarget:t selector:s interval:0 repeat:kCCRepeatForever delay:0] autorelease]; -} - -+(id) timerWithTarget:(id)t selector:(SEL)s interval:(ccTime) i -{ - return [[[self alloc] initWithTarget:t selector:s interval:i repeat:kCCRepeatForever delay:0] autorelease]; -} - --(id) initWithTarget:(id)t selector:(SEL)s -{ - return [self initWithTarget:t selector:s interval:0 repeat:kCCRepeatForever delay: 0]; -} - --(id) initWithTarget:(id)t selector:(SEL)s interval:(ccTime) seconds repeat:(uint) r delay:(ccTime) d -{ - if( (self=[super init]) ) { -#if COCOS2D_DEBUG - NSMethodSignature *sig = [t methodSignatureForSelector:s]; - NSAssert(sig !=0 , @"Signature not found for selector - does it have the following form? -(void) name: (ccTime) dt"); -#endif - - // target is not retained. It is retained in the hash structure - target = t; - selector = s; - impMethod = (TICK_IMP) [t methodForSelector:s]; - elapsed = -1; - interval = seconds; - repeat = r; - delay = d; - useDelay = (delay > 0) ? YES : NO; - repeat = r; - runForever = (repeat == kCCRepeatForever) ? YES : NO; - } - return self; -} - - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | target:%@ selector:(%@)>", [self class], self, [target class], NSStringFromSelector(selector)]; -} - --(void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - [super dealloc]; -} - --(void) update: (ccTime) dt -{ - if( elapsed == - 1) - { - elapsed = 0; - nTimesExecuted = 0; - } - else - { - if (runForever && !useDelay) - {//standard timer usage - elapsed += dt; - if( elapsed >= interval ) { - impMethod(target, selector, elapsed); - elapsed = 0; - - } - } - else - {//advanced usage - elapsed += dt; - if (useDelay) - { - if( elapsed >= delay ) - { - impMethod(target, selector, elapsed); - elapsed = elapsed - delay; - nTimesExecuted+=1; - useDelay = NO; - } - } - else - { - if (elapsed >= interval) - { - impMethod(target, selector, elapsed); - elapsed = 0; - nTimesExecuted += 1; - - } - } - - if (nTimesExecuted > repeat) - { //unschedule timer - [[[CCDirector sharedDirector] scheduler] unscheduleSelector:selector forTarget:target]; - } - } - } -} -@end - -// -// CCScheduler -// -#pragma mark - -#pragma mark - CCScheduler - -@interface CCScheduler (Private) --(void) removeHashElement:(tHashSelectorEntry*)element; -@end - -@implementation CCScheduler - -@synthesize timeScale = timeScale_; - -- (id) init -{ - if( (self=[super init]) ) { - timeScale_ = 1.0f; - - // used to trigger CCTimer#update - updateSelector = @selector(update:); - impMethod = (TICK_IMP) [CCTimer instanceMethodForSelector:updateSelector]; - - // updates with priority - updates0 = NULL; - updatesNeg = NULL; - updatesPos = NULL; - hashForUpdates = NULL; - - // selectors with interval - currentTarget = nil; - currentTargetSalvaged = NO; - hashForSelectors = nil; - updateHashLocked = NO; - } - - return self; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | timeScale = %0.2f >", [self class], self, timeScale_]; -} - -- (void) dealloc -{ - CCLOG(@"cocos2d: deallocing %@", self); - - [self unscheduleAllSelectors]; - - [super dealloc]; -} - - -#pragma mark CCScheduler - Custom Selectors - --(void) removeHashElement:(tHashSelectorEntry*)element -{ - ccArrayFree(element->timers); - [element->target release]; - HASH_DEL(hashForSelectors, element); - free(element); -} - --(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused -{ - [self scheduleSelector:selector forTarget:target interval:interval paused:paused repeat:kCCRepeatForever delay:0.0f]; -} - --(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused repeat:(uint) repeat delay:(ccTime) delay -{ - NSAssert( selector != nil, @"Argument selector must be non-nil"); - NSAssert( target != nil, @"Argument target must be non-nil"); - - tHashSelectorEntry *element = NULL; - HASH_FIND_INT(hashForSelectors, &target, element); - - if( ! element ) { - element = calloc( sizeof( *element ), 1 ); - element->target = [target retain]; - HASH_ADD_INT( hashForSelectors, target, element ); - - // Is this the 1st element ? Then set the pause level to all the selectors of this target - element->paused = paused; - - } else - NSAssert( element->paused == paused, @"CCScheduler. Trying to schedule a selector with a pause value different than the target"); - - - if( element->timers == nil ) - element->timers = ccArrayNew(10); - else - { - for( unsigned int i=0; i< element->timers->num; i++ ) { - CCTimer *timer = element->timers->arr[i]; - if( selector == timer->selector ) { - CCLOG(@"CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.2f to %.2f", timer->interval, interval); - timer->interval = interval; - return; - } - } - ccArrayEnsureExtraCapacity(element->timers, 1); - } - - CCTimer *timer = [[CCTimer alloc] initWithTarget:target selector:selector interval:interval repeat:repeat delay:delay]; - ccArrayAppendObject(element->timers, timer); - [timer release]; -} - --(void) unscheduleSelector:(SEL)selector forTarget:(id)target -{ - // explicity handle nil arguments when removing an object - if( target==nil && selector==NULL) - return; - - NSAssert( target != nil, @"Target MUST not be nil"); - NSAssert( selector != NULL, @"Selector MUST not be NULL"); - - tHashSelectorEntry *element = NULL; - HASH_FIND_INT(hashForSelectors, &target, element); - - if( element ) { - - for( unsigned int i=0; i< element->timers->num; i++ ) { - CCTimer *timer = element->timers->arr[i]; - - - if( selector == timer->selector ) { - - if( timer == element->currentTimer && !element->currentTimerSalvaged ) { - [element->currentTimer retain]; - element->currentTimerSalvaged = YES; - } - - ccArrayRemoveObjectAtIndex(element->timers, i ); - - // update timerIndex in case we are in tick:, looping over the actions - if( element->timerIndex >= i ) - element->timerIndex--; - - if( element->timers->num == 0 ) { - if( currentTarget == element ) - currentTargetSalvaged = YES; - else - [self removeHashElement: element]; - } - return; - } - } - } - - // Not Found -// NSLog(@"CCScheduler#unscheduleSelector:forTarget: selector not found: %@", selString); - -} - -#pragma mark CCScheduler - Update Specific - --(void) priorityIn:(tListEntry**)list target:(id)target priority:(NSInteger)priority paused:(BOOL)paused -{ - tListEntry *listElement = malloc( sizeof(*listElement) ); - - listElement->target = target; - listElement->priority = priority; - listElement->paused = paused; - listElement->impMethod = (TICK_IMP) [target methodForSelector:updateSelector]; - listElement->next = listElement->prev = NULL; - listElement->markedForDeletion = NO; - - // empty list ? - if( ! *list ) { - DL_APPEND( *list, listElement ); - - } else { - BOOL added = NO; - - for( tListEntry *elem = *list; elem ; elem = elem->next ) { - if( priority < elem->priority ) { - - if( elem == *list ) - DL_PREPEND(*list, listElement); - else { - listElement->next = elem; - listElement->prev = elem->prev; - - elem->prev->next = listElement; - elem->prev = listElement; - } - - added = YES; - break; - } - } - - // Not added? priority has the higher value. Append it. - if( !added ) - DL_APPEND(*list, listElement); - } - - // update hash entry for quicker access - tHashUpdateEntry *hashElement = calloc( sizeof(*hashElement), 1 ); - hashElement->target = [target retain]; - hashElement->list = list; - hashElement->entry = listElement; - HASH_ADD_INT(hashForUpdates, target, hashElement ); -} - --(void) appendIn:(tListEntry**)list target:(id)target paused:(BOOL)paused -{ - tListEntry *listElement = malloc( sizeof( * listElement ) ); - - listElement->target = target; - listElement->paused = paused; - listElement->markedForDeletion = NO; - listElement->impMethod = (TICK_IMP) [target methodForSelector:updateSelector]; - - DL_APPEND(*list, listElement); - - - // update hash entry for quicker access - tHashUpdateEntry *hashElement = calloc( sizeof(*hashElement), 1 ); - hashElement->target = [target retain]; - hashElement->list = list; - hashElement->entry = listElement; - HASH_ADD_INT(hashForUpdates, target, hashElement ); -} - --(void) scheduleUpdateForTarget:(id)target priority:(NSInteger)priority paused:(BOOL)paused -{ - tHashUpdateEntry * hashElement = NULL; - HASH_FIND_INT(hashForUpdates, &target, hashElement); - if(hashElement) - { -#if COCOS2D_DEBUG >= 1 - NSAssert( hashElement->entry->markedForDeletion, @"CCScheduler: You can't re-schedule an 'update' selector'. Unschedule it first"); -#endif - // TODO : check if priority has changed! - - hashElement->entry->markedForDeletion = NO; - return; - } - - // most of the updates are going to be 0, that's way there - // is an special list for updates with priority 0 - if( priority == 0 ) - [self appendIn:&updates0 target:target paused:paused]; - - else if( priority < 0 ) - [self priorityIn:&updatesNeg target:target priority:priority paused:paused]; - - else // priority > 0 - [self priorityIn:&updatesPos target:target priority:priority paused:paused]; -} - -- (void) removeUpdateFromHash:(tListEntry*)entry -{ - tHashUpdateEntry * element = NULL; - - HASH_FIND_INT(hashForUpdates, &entry->target, element); - if( element ) { - // list entry - DL_DELETE( *element->list, element->entry ); - free( element->entry ); - - // hash entry - [element->target release]; - HASH_DEL( hashForUpdates, element); - free(element); - } -} - --(void) unscheduleUpdateForTarget:(id)target -{ - if( target == nil ) - return; - - tHashUpdateEntry * element = NULL; - HASH_FIND_INT(hashForUpdates, &target, element); - if( element ) { - if(updateHashLocked) - element->entry->markedForDeletion = YES; - else - [self removeUpdateFromHash:element->entry]; - -// // list entry -// DL_DELETE( *element->list, element->entry ); -// free( element->entry ); -// -// // hash entry -// [element->target release]; -// HASH_DEL( hashForUpdates, element); -// free(element); - } -} - -#pragma mark CCScheduler - Common for Update selector & Custom Selectors - --(void) unscheduleAllSelectors -{ - // Custom Selectors - for(tHashSelectorEntry *element=hashForSelectors; element != NULL; ) { - id target = element->target; - element=element->hh.next; - [self unscheduleAllSelectorsForTarget:target]; - } - - // Updates selectors - tListEntry *entry, *tmp; - DL_FOREACH_SAFE( updates0, entry, tmp ) { - [self unscheduleUpdateForTarget:entry->target]; - } - DL_FOREACH_SAFE( updatesNeg, entry, tmp ) { - [self unscheduleUpdateForTarget:entry->target]; - } - DL_FOREACH_SAFE( updatesPos, entry, tmp ) { - [self unscheduleUpdateForTarget:entry->target]; - } - -} - --(void) unscheduleAllSelectorsForTarget:(id)target -{ - // explicit nil handling - if( target == nil ) - return; - - // Custom Selectors - tHashSelectorEntry *element = NULL; - HASH_FIND_INT(hashForSelectors, &target, element); - - if( element ) { - if( ccArrayContainsObject(element->timers, element->currentTimer) && !element->currentTimerSalvaged ) { - [element->currentTimer retain]; - element->currentTimerSalvaged = YES; - } - ccArrayRemoveAllObjects(element->timers); - if( currentTarget == element ) - currentTargetSalvaged = YES; - else - [self removeHashElement:element]; - } - - // Update Selector - [self unscheduleUpdateForTarget:target]; -} - --(void) resumeTarget:(id)target -{ - NSAssert( target != nil, @"target must be non nil" ); - - // Custom Selectors - tHashSelectorEntry *element = NULL; - HASH_FIND_INT(hashForSelectors, &target, element); - if( element ) - element->paused = NO; - - // Update selector - tHashUpdateEntry * elementUpdate = NULL; - HASH_FIND_INT(hashForUpdates, &target, elementUpdate); - if( elementUpdate ) { - NSAssert( elementUpdate->entry != NULL, @"resumeTarget: unknown error"); - elementUpdate->entry->paused = NO; - } -} - --(void) pauseTarget:(id)target -{ - NSAssert( target != nil, @"target must be non nil" ); - - // Custom selectors - tHashSelectorEntry *element = NULL; - HASH_FIND_INT(hashForSelectors, &target, element); - if( element ) - element->paused = YES; - - // Update selector - tHashUpdateEntry * elementUpdate = NULL; - HASH_FIND_INT(hashForUpdates, &target, elementUpdate); - if( elementUpdate ) { - NSAssert( elementUpdate->entry != NULL, @"pauseTarget: unknown error"); - elementUpdate->entry->paused = YES; - } - -} - --(BOOL) isTargetPaused:(id)target -{ - NSAssert( target != nil, @"target must be non nil" ); - - // Custom selectors - tHashSelectorEntry *element = NULL; - HASH_FIND_INT(hashForSelectors, &target, element); - if( element ) - { - return element->paused; - } - return NO; // should never get here - -} - -#pragma mark CCScheduler - Main Loop - --(void) update: (ccTime) dt -{ - updateHashLocked = YES; - - if( timeScale_ != 1.0f ) - dt *= timeScale_; - - // Iterate all over the Updates selectors - tListEntry *entry, *tmp; - - // updates with priority < 0 - DL_FOREACH_SAFE( updatesNeg, entry, tmp ) { - if( ! entry->paused && !entry->markedForDeletion ) - entry->impMethod( entry->target, updateSelector, dt ); - } - - // updates with priority == 0 - DL_FOREACH_SAFE( updates0, entry, tmp ) { - if( ! entry->paused && !entry->markedForDeletion ) - { - entry->impMethod( entry->target, updateSelector, dt ); - } - } - - // updates with priority > 0 - DL_FOREACH_SAFE( updatesPos, entry, tmp ) { - if( ! entry->paused && !entry->markedForDeletion ) - entry->impMethod( entry->target, updateSelector, dt ); - } - - // Iterate all over the custome selectors - for(tHashSelectorEntry *elt=hashForSelectors; elt != NULL; ) { - - currentTarget = elt; - currentTargetSalvaged = NO; - - if( ! currentTarget->paused ) { - - // The 'timers' ccArray may change while inside this loop. - for( elt->timerIndex = 0; elt->timerIndex < elt->timers->num; elt->timerIndex++) { - elt->currentTimer = elt->timers->arr[elt->timerIndex]; - elt->currentTimerSalvaged = NO; - - impMethod( elt->currentTimer, updateSelector, dt); - - if( elt->currentTimerSalvaged ) { - // The currentTimer told the remove itself. To prevent the timer from - // accidentally deallocating itself before finishing its step, we retained - // it. Now that step is done, it is safe to release it. - [elt->currentTimer release]; - } - - elt->currentTimer = nil; - } - } - - // elt, at this moment, is still valid - // so it is safe to ask this here (issue #490) - elt = elt->hh.next; - - // only delete currentTarget if no actions were scheduled during the cycle (issue #481) - if( currentTargetSalvaged && currentTarget->timers->num == 0 ) - [self removeHashElement:currentTarget]; - } - - // delete all updates that are morked for deletion - // updates with priority < 0 - DL_FOREACH_SAFE( updatesNeg, entry, tmp ) { - if(entry->markedForDeletion ) - { - [self removeUpdateFromHash:entry]; - } - } - - // updates with priority == 0 - DL_FOREACH_SAFE( updates0, entry, tmp ) { - if(entry->markedForDeletion ) - { - [self removeUpdateFromHash:entry]; - } - } - - // updates with priority > 0 - DL_FOREACH_SAFE( updatesPos, entry, tmp ) { - if(entry->markedForDeletion ) - { - [self removeUpdateFromHash:entry]; - } - } - - updateHashLocked = NO; - currentTarget = nil; -} -@end - diff --git a/Example/libs/cocos2d/CCShaderCache.h b/Example/libs/cocos2d/CCShaderCache.h deleted file mode 100644 index 5c93a99..0000000 --- a/Example/libs/cocos2d/CCShaderCache.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import -#import "ccMacros.h" -#ifdef __CC_PLATFORM_IOS -#import -#endif // __CC_PLATFORM_IOS - -@class CCGLProgram; - -/** CCShaderCache - Singleton that stores manages GL shaders - @since v2.0 - */ -@interface CCShaderCache : NSObject { - - NSMutableDictionary *programs_; - -} - -/** returns the shared instance */ -+ (CCShaderCache *)sharedShaderCache; - -/** purges the cache. It releases the retained instance. */ -+(void)purgeSharedShaderCache; - -/** loads the default shaders */ --(void) loadDefaultShaders; - -/** returns a GL program for a given key */ --(CCGLProgram *) programForKey:(NSString*)key; - -/** adds a CCGLProgram to the cache for a given name */ -- (void) addProgram:(CCGLProgram*)program forKey:(NSString*)key; - -@end - diff --git a/Example/libs/cocos2d/CCShaderCache.m b/Example/libs/cocos2d/CCShaderCache.m deleted file mode 100644 index db701cf..0000000 --- a/Example/libs/cocos2d/CCShaderCache.m +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "CCShaderCache.h" -#import "ccShaders.h" -#import "CCGLProgram.h" -#import "ccMacros.h" -#import "Support/OpenGL_Internal.h" - -static CCShaderCache *_sharedShaderCache; - -@implementation CCShaderCache - -#pragma mark CCShaderCache - Alloc, Init & Dealloc - -+ (CCShaderCache *)sharedShaderCache -{ - if (!_sharedShaderCache) - _sharedShaderCache = [[CCShaderCache alloc] init]; - - return _sharedShaderCache; -} - -+(void)purgeSharedShaderCache -{ - [_sharedShaderCache release]; - _sharedShaderCache = nil; -} - - -+(id)alloc -{ - NSAssert(_sharedShaderCache == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; -} - -- (void)dealloc -{ - CCLOGINFO(@"cocos2d deallocing %@", self); - - [programs_ release]; - [super dealloc]; -} - -+(void)purgeSharedTextureCache -{ - [_sharedShaderCache release]; - _sharedShaderCache = nil; -} - --(id) init -{ - if( (self=[super init]) ) { - programs_ = [[NSMutableDictionary alloc ] initWithCapacity: 10]; - - [self loadDefaultShaders]; - } - - return self; -} - --(void) loadDefaultShaders -{ - // Position Texture Color shader - CCGLProgram *p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTextureColor_vert - fragmentShaderByteArray:ccPositionTextureColor_frag]; - - [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; - [p addAttribute:kCCAttributeNameColor index:kCCVertexAttrib_Color]; - [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; - - [p link]; - [p updateUniforms]; - - [programs_ setObject:p forKey:kCCShader_PositionTextureColor]; - [p release]; - - CHECK_GL_ERROR_DEBUG(); - - // Position Texture Color alpha test - p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTextureColor_vert - fragmentShaderByteArray:ccPositionTextureColorAlphaTest_frag]; - - [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; - [p addAttribute:kCCAttributeNameColor index:kCCVertexAttrib_Color]; - [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; - - [p link]; - [p updateUniforms]; - - [programs_ setObject:p forKey:kCCShader_PositionTextureColorAlphaTest]; - [p release]; - - CHECK_GL_ERROR_DEBUG(); - - // - // Position, Color shader - // - p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionColor_vert - fragmentShaderByteArray:ccPositionColor_frag]; - - [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; - [p addAttribute:kCCAttributeNameColor index:kCCVertexAttrib_Color]; - - [p link]; - [p updateUniforms]; - - [programs_ setObject:p forKey:kCCShader_PositionColor]; - [p release]; - - CHECK_GL_ERROR_DEBUG(); - - // - // Position Texture shader - // - p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTexture_vert - fragmentShaderByteArray:ccPositionTexture_frag]; - - [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; - [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; - - [p link]; - [p updateUniforms]; - - [programs_ setObject:p forKey:kCCShader_PositionTexture]; - [p release]; - - CHECK_GL_ERROR_DEBUG(); - - // - // Position, Texture attribs, 1 Color as uniform shader - // - p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTexture_uColor_vert - fragmentShaderByteArray:ccPositionTexture_uColor_frag]; - - [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; - [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; - - [p link]; - [p updateUniforms]; - - [programs_ setObject:p forKey:kCCShader_PositionTexture_uColor]; - [p release]; - - CHECK_GL_ERROR_DEBUG(); - - // - // Position Texture A8 Color shader - // - p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTextureA8Color_vert - fragmentShaderByteArray:ccPositionTextureA8Color_frag]; - - [p addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position]; - [p addAttribute:kCCAttributeNameColor index:kCCVertexAttrib_Color]; - [p addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords]; - - [p link]; - [p updateUniforms]; - - [programs_ setObject:p forKey:kCCShader_PositionTextureA8Color]; - [p release]; - - CHECK_GL_ERROR_DEBUG(); - - // - // Position and 1 color passed as a uniform (to similate glColor4ub ) - // - p = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPosition_uColor_vert - fragmentShaderByteArray:ccPosition_uColor_frag]; - - [p addAttribute:@"aVertex" index:kCCVertexAttrib_Position]; - - [p link]; - [p updateUniforms]; - - [programs_ setObject:p forKey:kCCShader_Position_uColor]; - [p release]; - - CHECK_GL_ERROR_DEBUG(); -} - --(CCGLProgram *) programForKey:(NSString*)key -{ - return [programs_ objectForKey:key]; -} - -- (void) addProgram:(CCGLProgram*)program forKey:(NSString*)key -{ - [programs_ setObject:program forKey:key]; -} - -@end diff --git a/Example/libs/cocos2d/CCSprite.h b/Example/libs/cocos2d/CCSprite.h deleted file mode 100644 index 497ce22..0000000 --- a/Example/libs/cocos2d/CCSprite.h +++ /dev/null @@ -1,288 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCNode.h" -#import "CCProtocols.h" -#import "CCTextureAtlas.h" - -@class CCSpriteBatchNode; -@class CCSpriteFrame; -@class CCAnimation; - -#pragma mark CCSprite - -#define CCSpriteIndexNotInitialized 0xffffffff /// CCSprite invalid index on the CCSpriteBatchode - - -/** CCSprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) - * - * CCSprite can be created with an image, or with a sub-rectangle of an image. - * - * If the parent or any of its ancestors is a CCSpriteBatchNode then the following features/limitations are valid - * - Features when the parent is a CCBatchNode: - * - MUCH faster rendering, specially if the CCSpriteBatchNode has many children. All the children will be drawn in a single batch. - * - * - Limitations - * - Camera is not supported yet (eg: CCOrbitCamera action doesn't work) - * - GridBase actions are not supported (eg: CCLens, CCRipple, CCTwirl) - * - The Alias/Antialias property belongs to CCSpriteBatchNode, so you can't individually set the aliased property. - * - The Blending function property belongs to CCSpriteBatchNode, so you can't individually set the blending function property. - * - Parallax scroller is not supported, but can be simulated with a "proxy" sprite. - * - * If the parent is an standard CCNode, then CCSprite behaves like any other CCNode: - * - It supports blending functions - * - It supports aliasing / antialiasing - * - But the rendering will be slower: 1 draw per children. - * - * The default anchorPoint in CCSprite is (0.5, 0.5). - */ -@interface CCSprite : CCNode -{ - - // - // Data used when the sprite is rendered using a CCSpriteBatchNode - // - CCTextureAtlas *textureAtlas_; // Sprite Sheet texture atlas (weak reference) - NSUInteger atlasIndex_; // Absolute (real) Index on the batch node - CCSpriteBatchNode *batchNode_; // Used batch node (weak reference) - CGAffineTransform transformToBatch_; // - BOOL dirty_; // Sprite needs to be updated - BOOL recursiveDirty_; // Subchildren needs to be updated - BOOL hasChildren_; // optimization to check if it contain children - BOOL shouldBeHidden_; // should not be drawn because one of the ancestors is not visible - - // - // Data used when the sprite is self-rendered - // - ccBlendFunc blendFunc_; // Needed for the texture protocol - CCTexture2D *texture_; // Texture used to render the sprite - - // - // Shared data - // - - // sprite rectangle - CGRect rect_; - - // texture - BOOL rectRotated_; - - // Offset Position (used by Zwoptex) - CGPoint offsetPosition_; - CGPoint unflippedOffsetPositionFromCenter_; - - // vertex coords, texture coords and color info - ccV3F_C4B_T2F_Quad quad_; - - // opacity and RGB protocol - GLubyte opacity_; - ccColor3B color_; - ccColor3B colorUnmodified_; - BOOL opacityModifyRGB_; - - // image is flipped - BOOL flipX_; - BOOL flipY_; -} - -/** whether or not the Sprite needs to be updated in the Atlas */ -@property (nonatomic,readwrite) BOOL dirty; -/** the quad (tex coords, vertex coords and color) information */ -@property (nonatomic,readonly) ccV3F_C4B_T2F_Quad quad; -/** The index used on the TextureAtlas. Don't modify this value unless you know what you are doing */ -@property (nonatomic,readwrite) NSUInteger atlasIndex; -/** returns the texture rect of the CCSprite in points */ -@property (nonatomic,readonly) CGRect textureRect; -/** returns whether or not the texture rectangle is rotated */ -@property (nonatomic,readonly) BOOL textureRectRotated; -/** whether or not the sprite is flipped horizontally. - It only flips the texture of the sprite, and not the texture of the sprite's children. - Also, flipping the texture doesn't alter the anchorPoint. - If you want to flip the anchorPoint too, and/or to flip the children too use: - - sprite.scaleX *= -1; - */ -@property (nonatomic,readwrite) BOOL flipX; -/** whether or not the sprite is flipped vertically. - It only flips the texture of the sprite, and not the texture of the sprite's children. - Also, flipping the texture doesn't alter the anchorPoint. - If you want to flip the anchorPoint too, and/or to flip the children too use: - - sprite.scaleY *= -1; - */ -@property (nonatomic,readwrite) BOOL flipY; -/** opacity: conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readwrite) GLubyte opacity; -/** RGB colors: conforms to CCRGBAProtocol protocol */ -@property (nonatomic,readwrite) ccColor3B color; -/** weak reference of the CCTextureAtlas used when the sprite is rendered using a CCSpriteBatchNode */ -@property (nonatomic,readwrite,assign) CCTextureAtlas *textureAtlas; -/** weak reference to the CCSpriteBatchNode that renders the CCSprite */ -@property (nonatomic,readwrite,assign) CCSpriteBatchNode *batchNode; -/** offset position in points of the sprite in points. Calculated automatically by editors like Zwoptex. - @since v0.99.0 - */ -@property (nonatomic,readonly) CGPoint offsetPosition; -/** conforms to CCTextureProtocol protocol */ -@property (nonatomic,readwrite) ccBlendFunc blendFunc; - -#pragma mark CCSprite - Initializers - -/** Creates an sprite with a texture. - The rect used will be the size of the texture. - The offset will be (0,0). - */ -+(id) spriteWithTexture:(CCTexture2D*)texture; - -/** Creates an sprite with a texture and a rect. - The offset will be (0,0). - */ -+(id) spriteWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; - -/** Creates an sprite with an sprite frame. - */ -+(id) spriteWithSpriteFrame:(CCSpriteFrame*)spriteFrame; - -/** Creates an sprite with an sprite frame name. - An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name. - If the CCSpriteFrame doesn't exist it will raise an exception. - @since v0.9 - */ -+(id) spriteWithSpriteFrameName:(NSString*)spriteFrameName; - -/** Creates an sprite with an image filename. - The rect used will be the size of the image. - The offset will be (0,0). - */ -+(id) spriteWithFile:(NSString*)filename; - -/** Creates an sprite with an image filename and a rect. - The offset will be (0,0). - */ -+(id) spriteWithFile:(NSString*)filename rect:(CGRect)rect; - -/** Creates an sprite with a CGImageRef and a key. - The key is used by the CCTextureCache to know if a texture was already created with this CGImage. - For example, a valid key is: @"sprite_frame_01". - If key is nil, then a new texture will be created each time by the CCTextureCache. - @since v0.99.0 - */ -+(id) spriteWithCGImage: (CGImageRef)image key:(NSString*)key; - -/** Initializes an sprite with a texture. - The rect used will be the size of the texture. - The offset will be (0,0). - */ --(id) initWithTexture:(CCTexture2D*)texture; - -/** Initializes an sprite with a texture and a rect in points (unrotated) - The offset will be (0,0). - */ --(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; - -/** Initializes an sprite with a texture and a rect in points, optionally rotated. - The offset will be (0,0). - IMPORTANT: This is the designated initializer. - */ -- (id)initWithTexture:(CCTexture2D *)texture rect:(CGRect)rect rotated:(BOOL)rotated; - - -/** Initializes an sprite with an sprite frame. - */ --(id) initWithSpriteFrame:(CCSpriteFrame*)spriteFrame; - -/** Initializes an sprite with an sprite frame name. - An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name. - If the CCSpriteFrame doesn't exist it will raise an exception. - @since v0.9 - */ --(id) initWithSpriteFrameName:(NSString*)spriteFrameName; - -/** Initializes an sprite with an image filename. - The rect used will be the size of the image. - The offset will be (0,0). - */ --(id) initWithFile:(NSString*)filename; - -/** Initializes an sprite with an image filename, and a rect. - The offset will be (0,0). - */ --(id) initWithFile:(NSString*)filename rect:(CGRect)rect; - -/** Initializes an sprite with a CGImageRef and a key - The key is used by the CCTextureCache to know if a texture was already created with this CGImage. - For example, a valid key is: @"sprite_frame_01". - If key is nil, then a new texture will be created each time by the CCTextureCache. - @since v0.99.0 - */ --(id) initWithCGImage:(CGImageRef)image key:(NSString*)key; - -#pragma mark CCSprite - BatchNode methods - -/** updates the quad according the the rotation, position, scale values. - */ --(void)updateTransform; - -#pragma mark CCSprite - Texture methods - -/** set the texture rect of the CCSprite in points. - It will call setTextureRect:rotated:untrimmedSize with rotated = NO, and utrimmedSize = rect.size. - */ --(void) setTextureRect:(CGRect) rect; - -/** set the texture rect, rectRotated and untrimmed size of the CCSprite in points. - It will update the texture coordinates and the vertex rectangle. - */ --(void) setTextureRect:(CGRect)rect rotated:(BOOL)rotated untrimmedSize:(CGSize)size; - -/** set the vertex rect. - It will be called internally by setTextureRect. Useful if you want to create 2x images from SD images in Retina Display. - Do not call it manually. Use setTextureRect instead. - */ --(void)setVertexRect:(CGRect)rect; - - -#pragma mark CCSprite - Frames - -/** sets a new display frame to the CCSprite. */ --(void) setDisplayFrame:(CCSpriteFrame*)newFrame; - -/** returns whether or not a CCSpriteFrame is being displayed */ --(BOOL) isFrameDisplayed:(CCSpriteFrame*)frame; - -/** returns the current displayed frame. */ --(CCSpriteFrame*) displayFrame; - -#pragma mark CCSprite - Animation - -/** changes the display frame with animation name and index. - The animation name will be get from the CCAnimationCache - @since v0.99.5 - */ --(void) setDisplayFrameWithAnimationName:(NSString*)animationName index:(int) frameIndex; - -@end diff --git a/Example/libs/cocos2d/CCSprite.m b/Example/libs/cocos2d/CCSprite.m deleted file mode 100644 index a19ed22..0000000 --- a/Example/libs/cocos2d/CCSprite.m +++ /dev/null @@ -1,951 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "ccConfig.h" -#import "CCSpriteBatchNode.h" -#import "CCSprite.h" -#import "CCSpriteFrame.h" -#import "CCSpriteFrameCache.h" -#import "CCAnimation.h" -#import "CCAnimationCache.h" -#import "CCTextureCache.h" -#import "CCDrawingPrimitives.h" -#import "CCShaderCache.h" -#import "ccGLStateCache.h" -#import "CCGLProgram.h" -#import "CCDirector.h" -#import "Support/CGPointExtension.h" -#import "Support/TransformUtils.h" -#import "Support/CCProfiling.h" -#import "Support/OpenGL_Internal.h" - -// external -#import "kazmath/GL/matrix.h" - -#pragma mark - -#pragma mark CCSprite - -#if CC_SPRITEBATCHNODE_RENDER_SUBPIXEL -#define RENDER_IN_SUBPIXEL -#else -#define RENDER_IN_SUBPIXEL(__A__) ( (int)(__A__)) -#endif - - -@interface CCSprite () --(void) setTextureCoords:(CGRect)rect; --(void) updateBlendFunc; --(void) setReorderChildDirtyRecursively; -@end - -@implementation CCSprite - -@synthesize dirty = dirty_; -@synthesize quad = quad_; -@synthesize atlasIndex = atlasIndex_; -@synthesize textureRect = rect_; -@synthesize textureRectRotated = rectRotated_; -@synthesize blendFunc = blendFunc_; -@synthesize textureAtlas = textureAtlas_; -@synthesize offsetPosition = offsetPosition_; - - -+(id)spriteWithTexture:(CCTexture2D*)texture -{ - return [[[self alloc] initWithTexture:texture] autorelease]; -} - -+(id)spriteWithTexture:(CCTexture2D*)texture rect:(CGRect)rect -{ - return [[[self alloc] initWithTexture:texture rect:rect] autorelease]; -} - -+(id)spriteWithFile:(NSString*)filename -{ - return [[[self alloc] initWithFile:filename] autorelease]; -} - -+(id)spriteWithFile:(NSString*)filename rect:(CGRect)rect -{ - return [[[self alloc] initWithFile:filename rect:rect] autorelease]; -} - -+(id)spriteWithSpriteFrame:(CCSpriteFrame*)spriteFrame -{ - return [[[self alloc] initWithSpriteFrame:spriteFrame] autorelease]; -} - -+(id)spriteWithSpriteFrameName:(NSString*)spriteFrameName -{ - CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:spriteFrameName]; - - NSAssert1(frame!=nil, @"Invalid spriteFrameName: %@", spriteFrameName); - return [self spriteWithSpriteFrame:frame]; -} - -+(id)spriteWithCGImage:(CGImageRef)image key:(NSString*)key -{ - return [[[self alloc] initWithCGImage:image key:key] autorelease]; -} - --(id) init -{ - return [self initWithTexture:nil rect:CGRectZero]; -} - -// designated initializer --(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect rotated:(BOOL)rotated -{ - if( (self = [super init]) ) - { - // shader program - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; - - dirty_ = recursiveDirty_ = NO; - - opacityModifyRGB_ = YES; - opacity_ = 255; - color_ = colorUnmodified_ = ccWHITE; - - blendFunc_.src = CC_BLEND_SRC; - blendFunc_.dst = CC_BLEND_DST; - - flipY_ = flipX_ = NO; - - // default transform anchor: center - anchorPoint_ = ccp(0.5f, 0.5f); - - // zwoptex default values - offsetPosition_ = CGPointZero; - - hasChildren_ = NO; - batchNode_ = nil; - - // clean the Quad - bzero(&quad_, sizeof(quad_)); - - // Atlas: Color - ccColor4B tmpColor = {255,255,255,255}; - quad_.bl.colors = tmpColor; - quad_.br.colors = tmpColor; - quad_.tl.colors = tmpColor; - quad_.tr.colors = tmpColor; - - [self setTexture:texture]; - [self setTextureRect:rect rotated:rotated untrimmedSize:rect.size]; - - - // by default use "Self Render". - // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" - [self setBatchNode:nil]; - - } - return self; -} - --(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect -{ - return [self initWithTexture:texture rect:rect rotated:NO]; -} - --(id) initWithTexture:(CCTexture2D*)texture -{ - NSAssert(texture!=nil, @"Invalid texture for sprite"); - - CGRect rect = CGRectZero; - rect.size = texture.contentSize; - return [self initWithTexture:texture rect:rect]; -} - --(id) initWithFile:(NSString*)filename -{ - NSAssert(filename != nil, @"Invalid filename for sprite"); - - CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage: filename]; - if( texture ) { - CGRect rect = CGRectZero; - rect.size = texture.contentSize; - return [self initWithTexture:texture rect:rect]; - } - - [self release]; - return nil; -} - --(id) initWithFile:(NSString*)filename rect:(CGRect)rect -{ - NSAssert(filename!=nil, @"Invalid filename for sprite"); - - CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage: filename]; - if( texture ) - return [self initWithTexture:texture rect:rect]; - - [self release]; - return nil; -} - -- (id) initWithSpriteFrame:(CCSpriteFrame*)spriteFrame -{ - NSAssert(spriteFrame!=nil, @"Invalid spriteFrame for sprite"); - - id ret = [self initWithTexture:spriteFrame.texture rect:spriteFrame.rect]; - [self setDisplayFrame:spriteFrame]; - return ret; -} - --(id)initWithSpriteFrameName:(NSString*)spriteFrameName -{ - NSAssert(spriteFrameName!=nil, @"Invalid spriteFrameName for sprite"); - - CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:spriteFrameName]; - return [self initWithSpriteFrame:frame]; -} - -- (id) initWithCGImage:(CGImageRef)image key:(NSString*)key -{ - NSAssert(image!=nil, @"Invalid CGImageRef for sprite"); - - // XXX: possible bug. See issue #349. New API should be added - CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addCGImage:image forKey:key]; - - CGRect rect = CGRectZero; - rect.size = texture.contentSize; - - return [self initWithTexture:texture rect:rect]; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Rect = (%.2f,%.2f,%.2f,%.2f) | tag = %i | atlasIndex = %i>", [self class], self, - rect_.origin.x, rect_.origin.y, rect_.size.width, rect_.size.height, - tag_, - atlasIndex_ - ]; -} - -- (void) dealloc -{ - [texture_ release]; - [super dealloc]; -} - --(CCSpriteBatchNode*) batchNode -{ - return batchNode_; -} - --(void) setBatchNode:(CCSpriteBatchNode *)batchNode -{ - batchNode_ = batchNode; // weak reference - - // self render - if( ! batchNode ) { - atlasIndex_ = CCSpriteIndexNotInitialized; - textureAtlas_ = nil; - dirty_ = recursiveDirty_ = NO; - - float x1 = offsetPosition_.x; - float y1 = offsetPosition_.y; - float x2 = x1 + rect_.size.width; - float y2 = y1 + rect_.size.height; - quad_.bl.vertices = (ccVertex3F) { x1, y1, 0 }; - quad_.br.vertices = (ccVertex3F) { x2, y1, 0 }; - quad_.tl.vertices = (ccVertex3F) { x1, y2, 0 }; - quad_.tr.vertices = (ccVertex3F) { x2, y2, 0 }; - - } else { - - // using batch - transformToBatch_ = CGAffineTransformIdentity; - textureAtlas_ = [batchNode textureAtlas]; // weak ref - } -} - --(void) setTextureRect:(CGRect)rect -{ - [self setTextureRect:rect rotated:NO untrimmedSize:rect.size]; -} - --(void) setTextureRect:(CGRect)rect rotated:(BOOL)rotated untrimmedSize:(CGSize)untrimmedSize -{ - rectRotated_ = rotated; - - [self setContentSize:untrimmedSize]; - [self setVertexRect:rect]; - [self setTextureCoords:rect]; - - CGPoint relativeOffset = unflippedOffsetPositionFromCenter_; - - // issue #732 - if( flipX_ ) - relativeOffset.x = -relativeOffset.x; - if( flipY_ ) - relativeOffset.y = -relativeOffset.y; - - - offsetPosition_.x = relativeOffset.x + (contentSize_.width - rect_.size.width) / 2; - offsetPosition_.y = relativeOffset.y + (contentSize_.height - rect_.size.height) / 2; - - - // rendering using batch node - if( batchNode_ ) { - // update dirty_, don't update recursiveDirty_ - dirty_ = YES; - } - - // self rendering - else - { - // Atlas: Vertex - float x1 = offsetPosition_.x; - float y1 = offsetPosition_.y; - float x2 = x1 + rect_.size.width; - float y2 = y1 + rect_.size.height; - - // Don't update Z. - quad_.bl.vertices = (ccVertex3F) { x1, y1, 0 }; - quad_.br.vertices = (ccVertex3F) { x2, y1, 0 }; - quad_.tl.vertices = (ccVertex3F) { x1, y2, 0 }; - quad_.tr.vertices = (ccVertex3F) { x2, y2, 0 }; - } -} - -// override this method to generate "double scale" sprites --(void) setVertexRect:(CGRect)rect -{ - rect_ = rect; -} - --(void) setTextureCoords:(CGRect)rect -{ - rect = CC_RECT_POINTS_TO_PIXELS(rect); - - CCTexture2D *tex = (batchNode_) ? [textureAtlas_ texture] : texture_; - if(!tex) - return; - - float atlasWidth = (float)tex.pixelsWide; - float atlasHeight = (float)tex.pixelsHigh; - - float left, right ,top , bottom; - - if(rectRotated_) - { -#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - left = (2*rect.origin.x+1)/(2*atlasWidth); - right = left+(rect.size.height*2-2)/(2*atlasWidth); - top = (2*rect.origin.y+1)/(2*atlasHeight); - bottom = top+(rect.size.width*2-2)/(2*atlasHeight); -#else - left = rect.origin.x/atlasWidth; - right = left+(rect.size.height/atlasWidth); - top = rect.origin.y/atlasHeight; - bottom = top+(rect.size.width/atlasHeight); -#endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - - if( flipX_) - CC_SWAP(top,bottom); - if( flipY_) - CC_SWAP(left,right); - - quad_.bl.texCoords.u = left; - quad_.bl.texCoords.v = top; - quad_.br.texCoords.u = left; - quad_.br.texCoords.v = bottom; - quad_.tl.texCoords.u = right; - quad_.tl.texCoords.v = top; - quad_.tr.texCoords.u = right; - quad_.tr.texCoords.v = bottom; - } else { -#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - left = (2*rect.origin.x+1)/(2*atlasWidth); - right = left + (rect.size.width*2-2)/(2*atlasWidth); - top = (2*rect.origin.y+1)/(2*atlasHeight); - bottom = top + (rect.size.height*2-2)/(2*atlasHeight); -#else - left = rect.origin.x/atlasWidth; - right = left + rect.size.width/atlasWidth; - top = rect.origin.y/atlasHeight; - bottom = top + rect.size.height/atlasHeight; -#endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - - if( flipX_) - CC_SWAP(left,right); - if( flipY_) - CC_SWAP(top,bottom); - - quad_.bl.texCoords.u = left; - quad_.bl.texCoords.v = bottom; - quad_.br.texCoords.u = right; - quad_.br.texCoords.v = bottom; - quad_.tl.texCoords.u = left; - quad_.tl.texCoords.v = top; - quad_.tr.texCoords.u = right; - quad_.tr.texCoords.v = top; - } -} - --(void)updateTransform -{ - NSAssert( batchNode_, @"updateTransform is only valid when CCSprite is being rendered using an CCSpriteBatchNode"); - - // recaculate matrix only if it is dirty - if( self.dirty ) { - - // If it is not visible, or one of its ancestors is not visible, then do nothing: - if( !visible_ || ( parent_ && parent_ != batchNode_ && ((CCSprite*)parent_)->shouldBeHidden_) ) { - quad_.br.vertices = quad_.tl.vertices = quad_.tr.vertices = quad_.bl.vertices = (ccVertex3F){0,0,0}; - shouldBeHidden_ = YES; - } - - else { - - shouldBeHidden_ = NO; - - if( ! parent_ || parent_ == batchNode_ ) - transformToBatch_ = [self nodeToParentTransform]; - - else { - NSAssert( [parent_ isKindOfClass:[CCSprite class]], @"Logic error in CCSprite. Parent must be a CCSprite"); - - transformToBatch_ = CGAffineTransformConcat( [self nodeToParentTransform] , ((CCSprite*)parent_)->transformToBatch_ ); - } - - // - // calculate the Quad based on the Affine Matrix - // - - CGSize size = rect_.size; - - float x1 = offsetPosition_.x; - float y1 = offsetPosition_.y; - - float x2 = x1 + size.width; - float y2 = y1 + size.height; - float x = transformToBatch_.tx; - float y = transformToBatch_.ty; - - float cr = transformToBatch_.a; - float sr = transformToBatch_.b; - float cr2 = transformToBatch_.d; - float sr2 = -transformToBatch_.c; - float ax = x1 * cr - y1 * sr2 + x; - float ay = x1 * sr + y1 * cr2 + y; - - float bx = x2 * cr - y1 * sr2 + x; - float by = x2 * sr + y1 * cr2 + y; - - float cx = x2 * cr - y2 * sr2 + x; - float cy = x2 * sr + y2 * cr2 + y; - - float dx = x1 * cr - y2 * sr2 + x; - float dy = x1 * sr + y2 * cr2 + y; - - quad_.bl.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), vertexZ_ }; - quad_.br.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), vertexZ_ }; - quad_.tl.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), vertexZ_ }; - quad_.tr.vertices = (ccVertex3F) { RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), vertexZ_ }; - } - - [textureAtlas_ updateQuad:&quad_ atIndex:atlasIndex_]; - dirty_ = recursiveDirty_ = NO; - } - - // recursively iterate over children - if( hasChildren_ ) - [children_ makeObjectsPerformSelector:@selector(updateTransform)]; - -#if CC_SPRITE_DEBUG_DRAW - // draw bounding box - CGPoint vertices[4] = { - ccp( quad_.bl.vertices.x, quad_.bl.vertices.y ), - ccp( quad_.br.vertices.x, quad_.br.vertices.y ), - ccp( quad_.tr.vertices.x, quad_.tr.vertices.y ), - ccp( quad_.tl.vertices.x, quad_.tl.vertices.y ), - }; - ccDrawPoly(vertices, 4, YES); -#endif // CC_SPRITE_DEBUG_DRAW - -} - -#pragma mark CCSprite - draw - --(void) draw -{ - CC_PROFILER_START_CATEGORY(kCCProfilerCategorySprite, @"CCSprite - draw"); - - NSAssert(!batchNode_, @"If CCSprite is being rendered by CCSpriteBatchNode, CCSprite#draw SHOULD NOT be called"); - - CC_NODE_DRAW_SETUP(); - - ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); - - ccGLBindTexture2D( [texture_ name] ); - - // - // Attributes - // - - ccGLEnableVertexAttribs( kCCVertexAttribFlag_PosColorTex ); - -#define kQuadSize sizeof(quad_.bl) - long offset = (long)&quad_; - - // vertex - NSInteger diff = offsetof( ccV3F_C4B_T2F, vertices); - glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff)); - - // texCoods - diff = offsetof( ccV3F_C4B_T2F, texCoords); - glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff)); - - // color - diff = offsetof( ccV3F_C4B_T2F, colors); - glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff)); - - - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - - CHECK_GL_ERROR_DEBUG(); - - -#if CC_SPRITE_DEBUG_DRAW == 1 - // draw bounding box - CGPoint vertices[4]={ - ccp(quad_.tl.vertices.x,quad_.tl.vertices.y), - ccp(quad_.bl.vertices.x,quad_.bl.vertices.y), - ccp(quad_.br.vertices.x,quad_.br.vertices.y), - ccp(quad_.tr.vertices.x,quad_.tr.vertices.y), - }; - ccDrawPoly(vertices, 4, YES); -#elif CC_SPRITE_DEBUG_DRAW == 2 - // draw texture box - CGSize s = self.textureRect.size; - CGPoint offsetPix = self.offsetPosition; - CGPoint vertices[4] = { - ccp(offsetPix.x,offsetPix.y), ccp(offsetPix.x+s.width,offsetPix.y), - ccp(offsetPix.x+s.width,offsetPix.y+s.height), ccp(offsetPix.x,offsetPix.y+s.height) - }; - ccDrawPoly(vertices, 4, YES); -#endif // CC_SPRITE_DEBUG_DRAW - - CC_INCREMENT_GL_DRAWS(1); - - CC_PROFILER_STOP_CATEGORY(kCCProfilerCategorySprite, @"CCSprite - draw"); -} - -#pragma mark CCSprite - CCNode overrides - --(void) addChild:(CCSprite*)child z:(NSInteger)z tag:(NSInteger) aTag -{ - NSAssert( child != nil, @"Argument must be non-nil"); - - if( batchNode_ ) { - NSAssert( [child isKindOfClass:[CCSprite class]], @"CCSprite only supports CCSprites as children when using CCSpriteBatchNode"); - NSAssert( child.texture.name == textureAtlas_.texture.name, @"CCSprite is not using the same texture id"); - - //put it in descendants array of batch node - [batchNode_ appendChild:child]; - - if (!isReorderChildDirty_) - [self setReorderChildDirtyRecursively]; - } - - //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check - [super addChild:child z:z tag:aTag]; - - hasChildren_ = YES; -} - --(void) reorderChild:(CCSprite*)child z:(NSInteger)z -{ - NSAssert( child != nil, @"Child must be non-nil"); - NSAssert( [children_ containsObject:child], @"Child doesn't belong to Sprite" ); - - if( z == child.zOrder ) - return; - - if( batchNode_ && ! isReorderChildDirty_) - { - [self setReorderChildDirtyRecursively]; - [batchNode_ reorderBatch:YES]; - } - - [super reorderChild:child z:z]; -} - --(void)removeChild: (CCSprite *)sprite cleanup:(BOOL)doCleanup -{ - if( batchNode_ ) - [batchNode_ removeSpriteFromAtlas:sprite]; - - [super removeChild:sprite cleanup:doCleanup]; - - hasChildren_ = ( [children_ count] > 0 ); -} - --(void)removeAllChildrenWithCleanup:(BOOL)doCleanup -{ - if( batchNode_ ) { - CCSprite *child; - CCARRAY_FOREACH(children_, child) - [batchNode_ removeSpriteFromAtlas:child]; - } - - [super removeAllChildrenWithCleanup:doCleanup]; - - hasChildren_ = NO; -} - -- (void) sortAllChildren -{ - if (isReorderChildDirty_) - { - NSInteger i,j,length = children_->data->num; - CCNode** x = children_->data->arr; - CCNode *tempItem; - - // insertion sort - for(i=1; i=0 && ( tempItem.zOrder < x[j].zOrder || ( tempItem.zOrder == x[j].zOrder && tempItem.orderOfArrival < x[j].orderOfArrival ) ) ) - { - x[j+1] = x[j]; - j = j-1; - } - x[j+1] = tempItem; - } - - if ( batchNode_) - [children_ makeObjectsPerformSelector:@selector(sortAllChildren)]; - - isReorderChildDirty_=NO; - } -} - -// -// CCNode property overloads -// used only when parent is CCSpriteBatchNode -// -#pragma mark CCSprite - property overloads - --(void) setReorderChildDirtyRecursively -{ - //only set parents flag the first time - - if ( ! isReorderChildDirty_ ) - { - isReorderChildDirty_ = YES; - CCNode* node = (CCNode*) parent_; - while (node && node != batchNode_) - { - [(CCSprite*)node setReorderChildDirtyRecursively]; - node=node.parent; - } - } -} - --(void) setDirtyRecursively:(BOOL)b -{ - dirty_ = recursiveDirty_ = b; - // recursively set dirty - if( hasChildren_ ) { - CCSprite *child; - CCARRAY_FOREACH(children_, child) - [child setDirtyRecursively:YES]; - } -} - -// XXX HACK: optimization -#define SET_DIRTY_RECURSIVELY() { \ - if( batchNode_ && ! recursiveDirty_ ) { \ - dirty_ = recursiveDirty_ = YES; \ - if( hasChildren_) \ - [self setDirtyRecursively:YES]; \ - } \ - } - --(void)setPosition:(CGPoint)pos -{ - [super setPosition:pos]; - SET_DIRTY_RECURSIVELY(); -} - --(void)setRotation:(float)rot -{ - [super setRotation:rot]; - SET_DIRTY_RECURSIVELY(); -} - --(void)setSkewX:(float)sx -{ - [super setSkewX:sx]; - SET_DIRTY_RECURSIVELY(); -} - --(void)setSkewY:(float)sy -{ - [super setSkewY:sy]; - SET_DIRTY_RECURSIVELY(); -} - --(void)setScaleX:(float) sx -{ - [super setScaleX:sx]; - SET_DIRTY_RECURSIVELY(); -} - --(void)setScaleY:(float) sy -{ - [super setScaleY:sy]; - SET_DIRTY_RECURSIVELY(); -} - --(void)setScale:(float) s -{ - [super setScale:s]; - SET_DIRTY_RECURSIVELY(); -} - --(void) setVertexZ:(float)z -{ - [super setVertexZ:z]; - SET_DIRTY_RECURSIVELY(); -} - --(void)setAnchorPoint:(CGPoint)anchor -{ - [super setAnchorPoint:anchor]; - SET_DIRTY_RECURSIVELY(); -} - --(void)setIsRelativeAnchorPoint:(BOOL)relative -{ - NSAssert( ! batchNode_, @"relativeTransformAnchor is invalid in CCSprite"); - [super setIsRelativeAnchorPoint:relative]; -} - --(void)setVisible:(BOOL)v -{ - [super setVisible:v]; - SET_DIRTY_RECURSIVELY(); -} - --(void)setFlipX:(BOOL)b -{ - if( flipX_ != b ) { - flipX_ = b; - [self setTextureRect:rect_ rotated:rectRotated_ untrimmedSize:contentSize_]; - } -} --(BOOL) flipX -{ - return flipX_; -} - --(void) setFlipY:(BOOL)b -{ - if( flipY_ != b ) { - flipY_ = b; - [self setTextureRect:rect_ rotated:rectRotated_ untrimmedSize:contentSize_]; - } -} --(BOOL) flipY -{ - return flipY_; -} - -// -// RGBA protocol -// -#pragma mark CCSprite - RGBA protocol --(void) updateColor -{ - ccColor4B color4 = {color_.r, color_.g, color_.b, opacity_}; - - quad_.bl.colors = color4; - quad_.br.colors = color4; - quad_.tl.colors = color4; - quad_.tr.colors = color4; - - // renders using batch node - if( batchNode_ ) { - if( atlasIndex_ != CCSpriteIndexNotInitialized) - [textureAtlas_ updateQuad:&quad_ atIndex:atlasIndex_]; - else - // no need to set it recursively - // update dirty_, don't update recursiveDirty_ - dirty_ = YES; - } - // self render - // do nothing -} - --(GLubyte) opacity -{ - return opacity_; -} - --(void) setOpacity:(GLubyte) anOpacity -{ - opacity_ = anOpacity; - - // special opacity for premultiplied textures - if( opacityModifyRGB_ ) - [self setColor: colorUnmodified_]; - - [self updateColor]; -} - -- (ccColor3B) color -{ - if(opacityModifyRGB_) - return colorUnmodified_; - - return color_; -} - --(void) setColor:(ccColor3B)color3 -{ - color_ = colorUnmodified_ = color3; - - if( opacityModifyRGB_ ){ - color_.r = color3.r * opacity_/255.0f; - color_.g = color3.g * opacity_/255.0f; - color_.b = color3.b * opacity_/255.0f; - } - - [self updateColor]; -} - --(void) setOpacityModifyRGB:(BOOL)modify -{ - ccColor3B oldColor = self.color; - opacityModifyRGB_ = modify; - self.color = oldColor; -} - --(BOOL) doesOpacityModifyRGB -{ - return opacityModifyRGB_; -} - -// -// Frames -// -#pragma mark CCSprite - Frames - --(void) setDisplayFrame:(CCSpriteFrame*)frame -{ - unflippedOffsetPositionFromCenter_ = frame.offset; - - CCTexture2D *newTexture = [frame texture]; - // update texture before updating texture rect - if ( newTexture.name != texture_.name ) - [self setTexture: newTexture]; - - // update rect - rectRotated_ = frame.rotated; - - [self setTextureRect:frame.rect rotated:rectRotated_ untrimmedSize:frame.originalSize]; -} - --(void) setDisplayFrameWithAnimationName: (NSString*) animationName index:(int) frameIndex -{ - NSAssert( animationName, @"CCSprite#setDisplayFrameWithAnimationName. animationName must not be nil"); - - CCAnimation *a = [[CCAnimationCache sharedAnimationCache] animationByName:animationName]; - - NSAssert( a, @"CCSprite#setDisplayFrameWithAnimationName: Frame not found"); - - CCAnimationFrame *frame = [[a frames] objectAtIndex:frameIndex]; - - NSAssert( frame, @"CCSprite#setDisplayFrame. Invalid frame"); - - [self setDisplayFrame:frame.spriteFrame]; -} - - --(BOOL) isFrameDisplayed:(CCSpriteFrame*)frame -{ - CGRect r = [frame rect]; - return ( CGRectEqualToRect(r, rect_) && - frame.texture.name == self.texture.name && - CGPointEqualToPoint( frame.offset, unflippedOffsetPositionFromCenter_ ) ); -} - --(CCSpriteFrame*) displayFrame -{ - return [CCSpriteFrame frameWithTexture:texture_ - rectInPixels:CC_RECT_POINTS_TO_PIXELS(rect_) - rotated:rectRotated_ - offset:unflippedOffsetPositionFromCenter_ - originalSize:CC_SIZE_POINTS_TO_PIXELS(contentSize_)]; -} - -#pragma mark CCSprite - CocosNodeTexture protocol - --(void) updateBlendFunc -{ - NSAssert( ! batchNode_, @"CCSprite: updateBlendFunc doesn't work when the sprite is rendered using a CCSpriteBatchNode"); - - // it is possible to have an untextured sprite - if( !texture_ || ! [texture_ hasPremultipliedAlpha] ) { - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; - [self setOpacityModifyRGB:NO]; - } else { - blendFunc_.src = CC_BLEND_SRC; - blendFunc_.dst = CC_BLEND_DST; - [self setOpacityModifyRGB:YES]; - } -} - --(void) setTexture:(CCTexture2D*)texture -{ - NSAssert( ! batchNode_, @"CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteBatchNode"); - - // accept texture==nil as argument - NSAssert( !texture || [texture isKindOfClass:[CCTexture2D class]], @"setTexture expects a CCTexture2D. Invalid argument"); - - if( texture_ != texture ) { - [texture_ release]; - texture_ = [texture retain]; - - [self updateBlendFunc]; - } -} - --(CCTexture2D*) texture -{ - return texture_; -} - -@end diff --git a/Example/libs/cocos2d/CCSpriteBatchNode.h b/Example/libs/cocos2d/CCSpriteBatchNode.h deleted file mode 100644 index ca13ef0..0000000 --- a/Example/libs/cocos2d/CCSpriteBatchNode.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (C) 2009 Matt Oswald - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCNode.h" -#import "CCProtocols.h" -#import "CCTextureAtlas.h" -#import "ccMacros.h" - -#pragma mark CCSpriteBatchNode - -@class CCSprite; - -/** CCSpriteBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call - * (often known as "batch draw"). - * - * A CCSpriteBatchNode can reference one and only one texture (one image file, one texture atlas). - * Only the CCSprites that are contained in that texture can be added to the CCSpriteBatchNode. - * All CCSprites added to a CCSpriteBatchNode are drawn in one OpenGL ES draw call. - * If the CCSprites are not added to a CCSpriteBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient. - * - * - * Limitations: - * - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is CCSprite or any subclass of CCSprite. eg: particles, labels and layer can't be added to a CCSpriteBatchNode. - * - Either all its children are Aliased or Antialiased. It can't be a mix. This is because "alias" is a property of the texture, and all the sprites share the same texture. - * - * @since v0.7.1 - */ -@interface CCSpriteBatchNode : CCNode -{ - CCTextureAtlas *textureAtlas_; - ccBlendFunc blendFunc_; - - // all descendants: chlidren, gran children, etc... - CCArray *descendants_; -} - -/** returns the TextureAtlas that is used */ -@property (nonatomic,readwrite,retain) CCTextureAtlas * textureAtlas; - -/** conforms to CCTextureProtocol protocol */ -@property (nonatomic,readwrite) ccBlendFunc blendFunc; - -/** descendants (children, gran children, etc) */ -@property (nonatomic,readonly) CCArray *descendants; - -/** creates a CCSpriteBatchNode with a texture2d and a default capacity of 29 children. - The capacity will be increased in 33% in runtime if it run out of space. - */ -+(id)batchNodeWithTexture:(CCTexture2D *)tex; - -/** creates a CCSpriteBatchNode with a texture2d and capacity of children. - The capacity will be increased in 33% in runtime if it run out of space. - */ -+(id)batchNodeWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity; - -/** creates a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) with a default capacity of 29 children. - The capacity will be increased in 33% in runtime if it run out of space. - The file will be loaded using the TextureMgr. - */ -+(id)batchNodeWithFile:(NSString*) fileImage; - -/** creates a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and capacity of children. - The capacity will be increased in 33% in runtime if it run out of space. - The file will be loaded using the TextureMgr. -*/ -+(id)batchNodeWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity; - -/** initializes a CCSpriteBatchNode with a texture2d and capacity of children. - The capacity will be increased in 33% in runtime if it run out of space. - */ --(id)initWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity; -/** initializes a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children. - The capacity will be increased in 33% in runtime if it run out of space. - The file will be loaded using the TextureMgr. - */ --(id)initWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity; - --(void) increaseAtlasCapacity; - -/** removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter. - @warning Removing a child from a CCSpriteBatchNode is very slow - */ --(void)removeChildAtIndex:(NSUInteger)index cleanup:(BOOL)doCleanup; - -/** removes a child given a reference. It will also cleanup the running actions depending on the cleanup parameter. - @warning Removing a child from a CCSpriteBatchNode is very slow - */ --(void)removeChild: (CCSprite *)sprite cleanup:(BOOL)doCleanup; - --(void) insertChild:(CCSprite*)child inAtlasAtIndex:(NSUInteger)index; --(void) appendChild:(CCSprite*)sprite; --(void) removeSpriteFromAtlas:(CCSprite*)sprite; - --(NSUInteger) rebuildIndexInOrder:(CCSprite*)parent atlasIndex:(NSUInteger)index; --(NSUInteger) atlasIndexForChild:(CCSprite*)sprite atZ:(NSInteger)z; -/* Sprites use this to start sortChildren, don't call this manually */ -- (void) reorderBatch:(BOOL) reorder; - -@end - -@interface CCSpriteBatchNode (QuadExtensions) -/** Adds a quad into the texture atlas but it won't be added into the children array. - This method should be called only when you are dealing with very big AtlasSrite and when most of the CCSprite won't be updated. - For example: a tile map (CCTMXMap) or a label with lots of characgers (CCLabelBMFont) - */ --(id) addSpriteWithoutQuad:(CCSprite*)child z:(NSUInteger)z tag:(NSInteger)aTag; - -/* This is the opposite of "addQuadFromSprite". - It adds the sprite to the children and descendants array, but it doesn't add it to the texture atlas. - */ --(void) addQuadFromSprite:(CCSprite*)sprite quadIndex:(NSUInteger)index; -@end diff --git a/Example/libs/cocos2d/CCSpriteBatchNode.m b/Example/libs/cocos2d/CCSpriteBatchNode.m deleted file mode 100644 index fe17956..0000000 --- a/Example/libs/cocos2d/CCSpriteBatchNode.m +++ /dev/null @@ -1,663 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (C) 2009 Matt Oswald - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "ccConfig.h" -#import "CCSprite.h" -#import "CCSpriteBatchNode.h" -#import "CCGrid.h" -#import "CCDrawingPrimitives.h" -#import "CCTextureCache.h" -#import "CCShaderCache.h" -#import "CCGLProgram.h" -#import "ccGLStateCache.h" -#import "CCDirector.h" -#import "Support/CGPointExtension.h" -#import "Support/TransformUtils.h" -#import "Support/CCProfiling.h" - -// external -#import "kazmath/GL/matrix.h" - -const NSUInteger defaultCapacity = 29; - -#pragma mark - -#pragma mark CCSpriteBatchNode - -@interface CCSpriteBatchNode (private) --(void) updateAtlasIndex:(CCSprite*) sprite currentIndex:(NSInteger*) curIndex; --(void) swap:(NSInteger) oldIndex withNewIndex:(NSInteger) newIndex; --(void) updateBlendFunc; -@end - -@implementation CCSpriteBatchNode - -@synthesize textureAtlas = textureAtlas_; -@synthesize blendFunc = blendFunc_; -@synthesize descendants = descendants_; - - -/* - * creation with CCTexture2D - */ -+(id)batchNodeWithTexture:(CCTexture2D *)tex -{ - return [[[self alloc] initWithTexture:tex capacity:defaultCapacity] autorelease]; -} - -+(id)batchNodeWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity -{ - return [[[self alloc] initWithTexture:tex capacity:capacity] autorelease]; -} - -/* - * creation with File Image - */ -+(id)batchNodeWithFile:(NSString*)fileImage capacity:(NSUInteger)capacity -{ - return [[[self alloc] initWithFile:fileImage capacity:capacity] autorelease]; -} - -+(id)batchNodeWithFile:(NSString*) imageFile -{ - return [[[self alloc] initWithFile:imageFile capacity:defaultCapacity] autorelease]; -} - -/* - * init with CCTexture2D - */ --(id)initWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity -{ - if( (self=[super init])) { - - blendFunc_.src = CC_BLEND_SRC; - blendFunc_.dst = CC_BLEND_DST; - textureAtlas_ = [[CCTextureAtlas alloc] initWithTexture:tex capacity:capacity]; - - [self updateBlendFunc]; - - // no lazy alloc in this node - children_ = [[CCArray alloc] initWithCapacity:capacity]; - descendants_ = [[CCArray alloc] initWithCapacity:capacity]; - - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor]; - } - - return self; -} - -/* - * init with FileImage - */ --(id)initWithFile:(NSString *)fileImage capacity:(NSUInteger)capacity -{ - CCTexture2D *tex = [[CCTextureCache sharedTextureCache] addImage:fileImage]; - return [self initWithTexture:tex capacity:capacity]; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Tag = %i>", [self class], self, tag_ ]; -} - --(void)dealloc -{ - [textureAtlas_ release]; - [descendants_ release]; - - [super dealloc]; -} - -#pragma mark CCSpriteBatchNode - composition - -// override visit. -// Don't call visit on its children --(void) visit -{ - CC_PROFILER_START_CATEGORY(kCCProfilerCategoryBatchSprite, @"CCSpriteBatchNode - visit"); - - NSAssert(parent_ != nil, @"CCSpriteBatchNode should NOT be root node"); - - // CAREFUL: - // This visit is almost identical to CCNode#visit - // with the exception that it doesn't call visit on its children - // - // The alternative is to have a void CCSprite#visit, but - // although this is less mantainable, is faster - // - if (!visible_) - return; - - kmGLPushMatrix(); - - if ( grid_ && grid_.active) { - [grid_ beforeDraw]; - [self transformAncestors]; - } - - [self sortAllChildren]; - [self transform]; - [self draw]; - - if ( grid_ && grid_.active) - [grid_ afterDraw:self]; - - kmGLPopMatrix(); - - orderOfArrival_ = 0; - - CC_PROFILER_STOP_CATEGORY(kCCProfilerCategoryBatchSprite, @"CCSpriteBatchNode - visit"); -} - -// override addChild: --(void) addChild:(CCSprite*)child z:(NSInteger)z tag:(NSInteger) aTag -{ - NSAssert( child != nil, @"Argument must be non-nil"); - NSAssert( [child isKindOfClass:[CCSprite class]], @"CCSpriteBatchNode only supports CCSprites as children"); - NSAssert( child.texture.name == textureAtlas_.texture.name, @"CCSprite is not using the same texture id"); - - [super addChild:child z:z tag:aTag]; - - [self appendChild:child]; -} - -// override reorderChild --(void) reorderChild:(CCSprite*)child z:(NSInteger)z -{ - NSAssert( child != nil, @"Child must be non-nil"); - NSAssert( [children_ containsObject:child], @"Child doesn't belong to Sprite" ); - - if( z == child.zOrder ) - return; - - //set the z-order and sort later - [super reorderChild:child z:z]; -} - -// override removeChild: --(void)removeChild: (CCSprite *)sprite cleanup:(BOOL)doCleanup -{ - // explicit nil handling - if (sprite == nil) - return; - - NSAssert([children_ containsObject:sprite], @"CCSpriteBatchNode doesn't contain the sprite. Can't remove it"); - - // cleanup before removing - [self removeSpriteFromAtlas:sprite]; - - [super removeChild:sprite cleanup:doCleanup]; -} - --(void)removeChildAtIndex:(NSUInteger)index cleanup:(BOOL)doCleanup -{ - [self removeChild:(CCSprite *)[children_ objectAtIndex:index] cleanup:doCleanup]; -} - --(void)removeAllChildrenWithCleanup:(BOOL)doCleanup -{ - // Invalidate atlas index. issue #569 - // useSelfRender should be performed on all descendants. issue #1216 - [descendants_ makeObjectsPerformSelector:@selector(setBatchNode:) withObject:nil]; - - [super removeAllChildrenWithCleanup:doCleanup]; - - [descendants_ removeAllObjects]; - [textureAtlas_ removeAllQuads]; -} - -//override sortAllChildren -- (void) sortAllChildren -{ - if (isReorderChildDirty_) - { - NSInteger i,j,length = children_->data->num; - CCNode ** x = children_->data->arr; - CCNode *tempItem; - CCSprite *child; - - //insertion sort - for(i=1; i=0 && ( tempItem.zOrder < x[j].zOrder || ( tempItem.zOrder == x[j].zOrder && tempItem.orderOfArrival < x[j].orderOfArrival ) ) ) - { - x[j+1] = x[j]; - j--; - } - - x[j+1] = tempItem; - } - - //sorted now check all children - if ([children_ count] > 0) - { - //first sort all children recursively based on zOrder - [children_ makeObjectsPerformSelector:@selector(sortAllChildren)]; - - NSInteger index=0; - - //fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact) - // and at the same time reorder descedants and the quads to the right index - CCARRAY_FOREACH(children_, child) - [self updateAtlasIndex:child currentIndex:&index]; - } - - isReorderChildDirty_=NO; - } -} - --(void) updateAtlasIndex:(CCSprite*) sprite currentIndex:(NSInteger*) curIndex -{ - CCArray *array = [sprite children]; - NSUInteger count = [array count]; - NSInteger oldIndex; - - if( count == 0 ) - { - oldIndex = sprite.atlasIndex; - sprite.atlasIndex = *curIndex; - sprite.orderOfArrival = 0; - if (oldIndex != *curIndex) - [self swap:oldIndex withNewIndex:*curIndex]; - (*curIndex)++; - } - else - { - BOOL needNewIndex=YES; - - if (((CCSprite*) (array->data->arr[0])).zOrder >= 0) - { - //all children are in front of the parent - oldIndex = sprite.atlasIndex; - sprite.atlasIndex = *curIndex; - sprite.orderOfArrival = 0; - if (oldIndex != *curIndex) - [self swap:oldIndex withNewIndex:*curIndex]; - (*curIndex)++; - - needNewIndex = NO; - } - - CCSprite* child; - CCARRAY_FOREACH(array,child) - { - if (needNewIndex && child.zOrder >= 0) - { - oldIndex = sprite.atlasIndex; - sprite.atlasIndex = *curIndex; - sprite.orderOfArrival = 0; - if (oldIndex != *curIndex) - [self swap:oldIndex withNewIndex:*curIndex]; - (*curIndex)++; - needNewIndex = NO; - - } - - [self updateAtlasIndex:child currentIndex:curIndex]; - } - - if (needNewIndex) - {//all children have a zOrder < 0) - oldIndex=sprite.atlasIndex; - sprite.atlasIndex=*curIndex; - sprite.orderOfArrival=0; - if (oldIndex!=*curIndex) - [self swap:oldIndex withNewIndex:*curIndex]; - (*curIndex)++; - } - } -} - -- (void) swap:(NSInteger) oldIndex withNewIndex:(NSInteger) newIndex -{ - id* x = descendants_->data->arr; - ccV3F_C4B_T2F_Quad* quads = textureAtlas_.quads; - - id tempItem = x[oldIndex]; - ccV3F_C4B_T2F_Quad tempItemQuad=quads[oldIndex]; - - //update the index of other swapped item - ((CCSprite*) x[newIndex]).atlasIndex=oldIndex; - - x[oldIndex]=x[newIndex]; - quads[oldIndex]=quads[newIndex]; - x[newIndex]=tempItem; - quads[newIndex]=tempItemQuad; -} - -- (void) reorderBatch:(BOOL) reorder -{ - isReorderChildDirty_=reorder; -} - -#pragma mark CCSpriteBatchNode - draw --(void) draw -{ - CC_PROFILER_START(@"CCSpriteBatchNode - draw"); - - // Optimization: Fast Dispatch - if( textureAtlas_.totalQuads == 0 ) - return; - - CC_NODE_DRAW_SETUP(); - - [children_ makeObjectsPerformSelector:@selector(updateTransform)]; - - ccGLBlendFunc( blendFunc_.src, blendFunc_.dst ); - - [textureAtlas_ drawQuads]; - - CC_PROFILER_STOP(@"CCSpriteBatchNode - draw"); -} - -#pragma mark CCSpriteBatchNode - private --(void) increaseAtlasCapacity -{ - // if we're going beyond the current CCTextureAtlas's capacity, - // all the previously initialized sprites will need to redo their texture coords - // this is likely computationally expensive - NSUInteger quantity = (textureAtlas_.capacity + 1) * 4 / 3; - - CCLOG(@"cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from [%lu] to [%lu].", - (long)textureAtlas_.capacity, - (long)quantity); - - - if( ! [textureAtlas_ resizeCapacity:quantity] ) { - // serious problems - CCLOG(@"cocos2d: WARNING: Not enough memory to resize the atlas"); - NSAssert(NO,@"XXX: CCSpriteBatchNode#increaseAtlasCapacity SHALL handle this assert"); - } -} - - -#pragma mark CCSpriteBatchNode - Atlas Index Stuff - --(NSUInteger) rebuildIndexInOrder:(CCSprite*)node atlasIndex:(NSUInteger)index -{ - CCSprite *sprite; - CCARRAY_FOREACH(node.children, sprite){ - if( sprite.zOrder < 0 ) - index = [self rebuildIndexInOrder:sprite atlasIndex:index]; - } - - // ignore self (batch node) - if( ! [node isEqual:self]) { - node.atlasIndex = index; - index++; - } - - CCARRAY_FOREACH(node.children, sprite){ - if( sprite.zOrder >= 0 ) - index = [self rebuildIndexInOrder:sprite atlasIndex:index]; - } - - return index; -} - --(NSUInteger) highestAtlasIndexInChild:(CCSprite*)sprite -{ - CCArray *array = [sprite children]; - NSUInteger count = [array count]; - if( count == 0 ) - return sprite.atlasIndex; - else - return [self highestAtlasIndexInChild:[array lastObject]]; -} - --(NSUInteger) lowestAtlasIndexInChild:(CCSprite*)sprite -{ - CCArray *array = [sprite children]; - NSUInteger count = [array count]; - if( count == 0 ) - return sprite.atlasIndex; - else - return [self lowestAtlasIndexInChild:[array objectAtIndex:0] ]; -} - - --(NSUInteger)atlasIndexForChild:(CCSprite*)sprite atZ:(NSInteger)z -{ - CCArray *brothers = [[sprite parent] children]; - NSUInteger childIndex = [brothers indexOfObject:sprite]; - - // ignore parent Z if parent is batchnode - BOOL ignoreParent = ( sprite.parent == self ); - CCSprite *previous = nil; - if( childIndex > 0 ) - previous = [brothers objectAtIndex:childIndex-1]; - - // first child of the sprite sheet - if( ignoreParent ) { - if( childIndex == 0 ) - return 0; - // else - return [self highestAtlasIndexInChild: previous] + 1; - } - - // parent is a CCSprite, so, it must be taken into account - - // first child of an CCSprite ? - if( childIndex == 0 ) - { - CCSprite *p = (CCSprite*) sprite.parent; - - // less than parent and brothers - if( z < 0 ) - return p.atlasIndex; - else - return p.atlasIndex+1; - - } else { - // previous & sprite belong to the same branch - if( ( previous.zOrder < 0 && z < 0 )|| (previous.zOrder >= 0 && z >= 0) ) - return [self highestAtlasIndexInChild:previous] + 1; - - // else (previous < 0 and sprite >= 0 ) - CCSprite *p = (CCSprite*) sprite.parent; - return p.atlasIndex + 1; - } - - NSAssert( NO, @"Should not happen. Error calculating Z on Batch Node"); - return 0; -} - -#pragma mark CCSpriteBatchNode - add / remove / reorder helper methods -// add child helper --(void) insertChild:(CCSprite*)sprite inAtlasAtIndex:(NSUInteger)index -{ - [sprite setBatchNode:self]; - [sprite setAtlasIndex:index]; - [sprite setDirty: YES]; - - if(textureAtlas_.totalQuads == textureAtlas_.capacity) - [self increaseAtlasCapacity]; - - ccV3F_C4B_T2F_Quad quad = [sprite quad]; - [textureAtlas_ insertQuad:&quad atIndex:index]; - - ccArray *descendantsData = descendants_->data; - - ccArrayInsertObjectAtIndex(descendantsData, sprite, index); - - // update indices - NSUInteger i = index+1; - CCSprite *child; - for(; inum; i++){ - child = descendantsData->arr[i]; - child.atlasIndex = child.atlasIndex + 1; - } - - // add children recursively - CCARRAY_FOREACH(sprite.children, child){ - NSUInteger idx = [self atlasIndexForChild:child atZ: child.zOrder]; - [self insertChild:child inAtlasAtIndex:idx]; - } -} - -// addChild helper, faster than insertChild --(void) appendChild:(CCSprite*)sprite -{ - isReorderChildDirty_=YES; - [sprite setBatchNode:self]; - [sprite setDirty: YES]; - - if(textureAtlas_.totalQuads == textureAtlas_.capacity) - [self increaseAtlasCapacity]; - - ccArray *descendantsData = descendants_->data; - - ccArrayAppendObjectWithResize(descendantsData, sprite); - - NSUInteger index=descendantsData->num-1; - - sprite.atlasIndex=index; - - ccV3F_C4B_T2F_Quad quad = [sprite quad]; - [textureAtlas_ insertQuad:&quad atIndex:index]; - - // add children recursively - CCSprite* child; - CCARRAY_FOREACH(sprite.children, child) - [self appendChild:child]; -} - - -// remove child helper --(void) removeSpriteFromAtlas:(CCSprite*)sprite -{ - // remove from TextureAtlas - [textureAtlas_ removeQuadAtIndex:sprite.atlasIndex]; - - // Cleanup sprite. It might be reused (issue #569) - [sprite setBatchNode:nil]; - - ccArray *descendantsData = descendants_->data; - NSUInteger index = ccArrayGetIndexOfObject(descendantsData, sprite); - if( index != NSNotFound ) { - ccArrayRemoveObjectAtIndex(descendantsData, index); - - // update all sprites beyond this one - NSUInteger count = descendantsData->num; - - for(; index < count; index++) - { - CCSprite *s = descendantsData->arr[index]; - s.atlasIndex = s.atlasIndex - 1; - } - } - - // remove children recursively - CCSprite *child; - CCARRAY_FOREACH(sprite.children, child) - [self removeSpriteFromAtlas:child]; -} - -#pragma mark CCSpriteBatchNode - CocosNodeTexture protocol - --(void) updateBlendFunc -{ - if( ! [textureAtlas_.texture hasPremultipliedAlpha] ) { - blendFunc_.src = GL_SRC_ALPHA; - blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; - } -} - --(void) setTexture:(CCTexture2D*)texture -{ - textureAtlas_.texture = texture; - [self updateBlendFunc]; -} - --(CCTexture2D*) texture -{ - return textureAtlas_.texture; -} -@end - -#pragma mark - CCSpriteBatchNode Extension - - -@implementation CCSpriteBatchNode (QuadExtension) - --(void) addQuadFromSprite:(CCSprite*)sprite quadIndex:(NSUInteger)index -{ - NSAssert( sprite != nil, @"Argument must be non-nil"); - NSAssert( [sprite isKindOfClass:[CCSprite class]], @"CCSpriteBatchNode only supports CCSprites as children"); - - - while(index >= textureAtlas_.capacity || textureAtlas_.capacity == textureAtlas_.totalQuads ) - [self increaseAtlasCapacity]; - - // - // update the quad directly. Don't add the sprite to the scene graph - // - - [sprite setBatchNode:self]; - [sprite setAtlasIndex:index]; - - ccV3F_C4B_T2F_Quad quad = [sprite quad]; - [textureAtlas_ insertQuad:&quad atIndex:index]; - - // XXX: updateTransform will update the textureAtlas too using updateQuad. - // XXX: so, it should be AFTER the insertQuad - [sprite setDirty:YES]; - [sprite updateTransform]; -} - --(id) addSpriteWithoutQuad:(CCSprite*)child z:(NSUInteger)z tag:(NSInteger)aTag -{ - NSAssert( child != nil, @"Argument must be non-nil"); - NSAssert( [child isKindOfClass:[CCSprite class]], @"CCSpriteBatchNode only supports CCSprites as children"); - - // quad index is Z - [child setAtlasIndex:z]; - - // XXX: optimize with a binary search - int i=0; - for( CCSprite *c in descendants_ ) { - if( c.atlasIndex >= z ) - break; - i++; - } - [descendants_ insertObject:child atIndex:i]; - - - // IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array - [super addChild:child z:z tag:aTag]; - - //#issue 1262 don't use lazy sorting, tiles are added as quads not as sprites, so sprites need to be added in order - [self reorderBatch:NO]; - return self; -} -@end - diff --git a/Example/libs/cocos2d/CCSpriteFrame.h b/Example/libs/cocos2d/CCSpriteFrame.h deleted file mode 100644 index fcc8084..0000000 --- a/Example/libs/cocos2d/CCSpriteFrame.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import -#import "CCNode.h" -#import "CCProtocols.h" - -/** A CCSpriteFrame has: - - texture: A CCTexture2D that will be used by the CCSprite - - rectangle: A rectangle of the texture - - - You can modify the frame of a CCSprite by doing: - - CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:texture rect:rect offset:offset]; - [sprite setDisplayFrame:frame]; - */ -@interface CCSpriteFrame : NSObject -{ - CGRect rect_; - CGRect rectInPixels_; - BOOL rotated_; - CGPoint offset_; - CGPoint offsetInPixels_; - CGSize originalSize_; - CGSize originalSizeInPixels_; - CCTexture2D *texture_; - NSString *textureFilename_; -} -/** rect of the frame in points. If it is updated, then rectInPixels will be updated too. */ -@property (nonatomic,readwrite) CGRect rect; - -/** rect of the frame in pixels. If it is updated, then rect (points) will be udpated too. */ -@property (nonatomic,readwrite) CGRect rectInPixels; - -/** whether or not the rect of the frame is rotated ( x = x+width, y = y+height, width = height, height = width ) */ -@property (nonatomic,readwrite) BOOL rotated; - -/** offset of the frame in points */ -@property (nonatomic,readwrite) CGPoint offset; - -/** offset of the frame in pixels */ -@property (nonatomic,readwrite) CGPoint offsetInPixels; - -/** original size of the trimmed image in points */ -@property (nonatomic,readwrite) CGSize originalSize; - -/** original size of the trimmed image in pixels */ -@property (nonatomic,readwrite) CGSize originalSizeInPixels; - -/** texture of the frame */ -@property (nonatomic, retain, readwrite) CCTexture2D *texture; - -/** texture file name of the frame */ -@property (nonatomic, retain, readonly) NSString *textureFilename; - -/** Create a CCSpriteFrame with a texture, rect in points. - It is assumed that the frame was not trimmed. - */ -+(id) frameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; - -/** Create a CCSpriteFrame with a texture filename, rect in points. - It is assumed that the frame was not trimmed. - */ -+(id) frameWithTextureFilename:(NSString*)filename rect:(CGRect)rect; - -/** Create a CCSpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. - The originalSize is the size in pixels of the frame before being trimmed. - */ -+(id) frameWithTexture:(CCTexture2D*)texture rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize; - - -/** Create a CCSpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels. - The originalSize is the size in pixels of the frame before being trimmed. - */ -+(id) frameWithTextureFilename:(NSString*)filename rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize; - - -/** Initializes a CCSpriteFrame with a texture, rect in points; - It is assumed that the frame was not trimmed. - */ --(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect; - -/** Initializes a CCSpriteFrame with a texture filename, rect in points; - It is assumed that the frame was not trimmed. - */ --(id) initWithTextureFilename:(NSString*)filename rect:(CGRect)rect; - - -/** Initializes a CCSpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. - The originalSize is the size in pixels of the frame before being trimmed. - */ --(id) initWithTexture:(CCTexture2D*)texture rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize; - -/** Initializes a CCSpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. - The originalSize is the size in pixels of the frame before being trimmed. - - @since v1.1 - */ --(id) initWithTextureFilename:(NSString*)filename rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize; - -@end - diff --git a/Example/libs/cocos2d/CCSpriteFrame.m b/Example/libs/cocos2d/CCSpriteFrame.m deleted file mode 100644 index d9174dc..0000000 --- a/Example/libs/cocos2d/CCSpriteFrame.m +++ /dev/null @@ -1,183 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCTextureCache.h" -#import "CCSpriteFrame.h" -#import "ccMacros.h" - -@implementation CCSpriteFrame -@synthesize offsetInPixels = offsetInPixels_, offset = offset_; -@synthesize originalSize = originalSize_, originalSizeInPixels = originalSizeInPixels_; -@synthesize textureFilename = textureFilename_; -@synthesize rotated = rotated_; - -+(id) frameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect -{ - return [[[self alloc] initWithTexture:texture rect:rect] autorelease]; -} - -+(id) frameWithTextureFilename:(NSString*)filename rect:(CGRect)rect -{ - return [[[self alloc] initWithTextureFilename:filename rect:rect] autorelease]; -} - -+(id) frameWithTexture:(CCTexture2D*)texture rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize -{ - return [[[self alloc] initWithTexture:texture rectInPixels:rect rotated:rotated offset:offset originalSize:originalSize] autorelease]; -} - -+(id) frameWithTextureFilename:(NSString*)filename rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize -{ - return [[[self alloc] initWithTextureFilename:filename rectInPixels:rect rotated:rotated offset:offset originalSize:originalSize] autorelease]; -} - --(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect -{ - CGRect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect ); - return [self initWithTexture:texture rectInPixels:rectInPixels rotated:NO offset:CGPointZero originalSize:rectInPixels.size]; -} - --(id) initWithTextureFilename:(NSString*)filename rect:(CGRect)rect -{ - CGRect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect ); - return [self initWithTextureFilename:filename rectInPixels:rectInPixels rotated:NO offset:CGPointZero originalSize:rectInPixels.size]; -} - --(id) initWithTexture:(CCTexture2D*)texture rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize -{ - if( (self=[super init]) ) - { - self.texture = texture; - rectInPixels_ = rect; - rect_ = CC_RECT_PIXELS_TO_POINTS( rect ); - offsetInPixels_ = offset; - offset_ = CC_POINT_PIXELS_TO_POINTS( offsetInPixels_ ); - originalSizeInPixels_ = originalSize; - originalSize_ = CC_SIZE_PIXELS_TO_POINTS( originalSizeInPixels_ ); - rotated_ = rotated; - } - return self; -} - --(id) initWithTextureFilename:(NSString *)filename rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize -{ - if( (self=[super init]) ) - { - texture_ = nil; - textureFilename_ = [filename copy]; - rectInPixels_ = rect; - rect_ = CC_RECT_PIXELS_TO_POINTS( rect ); - offsetInPixels_ = offset; - offset_ = CC_POINT_PIXELS_TO_POINTS( offsetInPixels_ ); - originalSizeInPixels_ = originalSize; - originalSize_ = CC_SIZE_PIXELS_TO_POINTS( originalSizeInPixels_ ); - rotated_ = rotated; - } - return self; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Texture=%@, Rect = (%.2f,%.2f,%.2f,%.2f)> rotated:%d", [self class], self, - textureFilename_, - rect_.origin.x, - rect_.origin.y, - rect_.size.width, - rect_.size.height, - rotated_ - ]; -} - -- (void) dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@",self); - [texture_ release]; - [textureFilename_ release]; - [super dealloc]; -} - --(id) copyWithZone: (NSZone*) zone -{ - CCSpriteFrame *copy = [[[self class] allocWithZone: zone] initWithTextureFilename:textureFilename_ rectInPixels:rectInPixels_ rotated:rotated_ offset:offsetInPixels_ originalSize:originalSizeInPixels_]; - copy.texture = texture_; - return copy; -} - --(CGRect) rect -{ - return rect_; -} - --(CGRect) rectInPixels -{ - return rectInPixels_; -} - --(void) setRect:(CGRect)rect -{ - rect_ = rect; - rectInPixels_ = CC_RECT_POINTS_TO_PIXELS( rect_ ); -} - --(void) setRectInPixels:(CGRect)rectInPixels -{ - rectInPixels_ = rectInPixels; - rect_ = CC_RECT_PIXELS_TO_POINTS( rectInPixels_ ); -} - --(void) setOffset:(CGPoint)offsets -{ - offset_ = offsets; - offsetInPixels_ = CC_POINT_POINTS_TO_PIXELS( offset_ ); -} - --(void) setOffsetInPixels:(CGPoint)offsetInPixels -{ - offsetInPixels_ = offsetInPixels; - offset_ = CC_POINT_PIXELS_TO_POINTS( offsetInPixels_ ); -} - --(void) setTexture:(CCTexture2D *)texture -{ - if( texture_ != texture ) { - [texture_ release]; - texture_ = [texture retain]; - } -} - --(CCTexture2D*) texture -{ - if( texture_ ) - return texture_; - - if( textureFilename_ ) - return [[CCTextureCache sharedTextureCache] addImage:textureFilename_]; - - // no texture or texture filename - return nil; -} -@end diff --git a/Example/libs/cocos2d/CCSpriteFrameCache.h b/Example/libs/cocos2d/CCSpriteFrameCache.h deleted file mode 100644 index 23507e4..0000000 --- a/Example/libs/cocos2d/CCSpriteFrameCache.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Jason Booth - * - * Copyright (c) 2009 Robert J Payne - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -/* - * To create sprite frames and texture atlas, use this tool: - * http://zwoptex.zwopple.com/ - */ - -#import - -#import "CCSpriteFrame.h" - -@class CCSprite; -@class CCTexture2D; - -/** Singleton that handles the loading of the sprite frames. - It saves in a cache the sprite frames. - @since v0.9 - */ -@interface CCSpriteFrameCache : NSObject -{ - NSMutableDictionary *spriteFrames_; - NSMutableDictionary *spriteFramesAliases_; -} - -/** Retruns ths shared instance of the Sprite Frame cache */ -+ (CCSpriteFrameCache *) sharedSpriteFrameCache; - -/** Purges the cache. It releases all the Sprite Frames and the retained instance. - */ -+(void)purgeSharedSpriteFrameCache; - - -/** Adds multiple Sprite Frames with a dictionary. The texture filename will be associated with the created sprite frames. - */ --(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary textureFilename:(NSString*)filename; - -/** Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. - */ --(void) addSpriteFramesWithDictionary:(NSDictionary *)dictionary texture:(CCTexture2D *)texture; - -/** Adds multiple Sprite Frames from a plist file. - * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png . - * If you want to use another texture, you should use the addSpriteFramesWithFile:texture method. - */ --(void) addSpriteFramesWithFile:(NSString*)plist; - -/** Adds multiple Sprite Frames from a plist file. The texture filename will be associated with the created sprite frames. - */ --(void) addSpriteFramesWithFile:(NSString*)plist textureFilename:(NSString*)filename; - -/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. - */ --(void) addSpriteFramesWithFile:(NSString*)plist texture:(CCTexture2D*)texture; - -/** Adds an sprite frame with a given name. - If the name already exists, then the contents of the old name will be replaced with the new one. - */ --(void) addSpriteFrame:(CCSpriteFrame*)frame name:(NSString*)frameName; - - -/** Purges the dictionary of loaded sprite frames. - * Call this method if you receive the "Memory Warning". - * In the short term: it will free some resources preventing your app from being killed. - * In the medium term: it will allocate more resources. - * In the long term: it will be the same. - */ --(void) removeSpriteFrames; - -/** Removes unused sprite frames. - * Sprite Frames that have a retain count of 1 will be deleted. - * It is convinient to call this method after when starting a new Scene. - */ --(void) removeUnusedSpriteFrames; - -/** Deletes an sprite frame from the sprite frame cache. - */ --(void) removeSpriteFrameByName:(NSString*)name; - -/** Removes multiple Sprite Frames from a plist file. -* Sprite Frames stored in this file will be removed. -* It is convinient to call this method when a specific texture needs to be removed. -* @since v0.99.5 -*/ -- (void) removeSpriteFramesFromFile:(NSString*) plist; - -/** Removes multiple Sprite Frames from NSDictionary. - * @since v0.99.5 - */ -- (void) removeSpriteFramesFromDictionary:(NSDictionary*) dictionary; - -/** Removes all Sprite Frames associated with the specified textures. - * It is convinient to call this method when a specific texture needs to be removed. - * @since v0.995. - */ -- (void) removeSpriteFramesFromTexture:(CCTexture2D*) texture; - -/** Returns an Sprite Frame that was previously added. - If the name is not found it will return nil. - You should retain the returned copy if you are going to use it. - */ --(CCSpriteFrame*) spriteFrameByName:(NSString*)name; - -@end diff --git a/Example/libs/cocos2d/CCSpriteFrameCache.m b/Example/libs/cocos2d/CCSpriteFrameCache.m deleted file mode 100644 index e0ab1a8..0000000 --- a/Example/libs/cocos2d/CCSpriteFrameCache.m +++ /dev/null @@ -1,375 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Jason Booth - * - * Copyright (c) 2009 Robert J Payne - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -/* - * To create sprite frames and texture atlas, use any of these tools: - * http://zwoptexapp.com/ - * http://www.texturepacker.com/ - * - */ - -#import "Platforms/CCNS.h" -#import "ccMacros.h" -#import "CCTextureCache.h" -#import "CCSpriteFrameCache.h" -#import "CCSpriteFrame.h" -#import "CCSprite.h" -#import "Support/CCFileUtils.h" - - -@implementation CCSpriteFrameCache - -#pragma mark CCSpriteFrameCache - Alloc, Init & Dealloc - -static CCSpriteFrameCache *sharedSpriteFrameCache_=nil; - -+ (CCSpriteFrameCache *)sharedSpriteFrameCache -{ - if (!sharedSpriteFrameCache_) - sharedSpriteFrameCache_ = [[CCSpriteFrameCache alloc] init]; - - return sharedSpriteFrameCache_; -} - -+(id)alloc -{ - NSAssert(sharedSpriteFrameCache_ == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; -} - -+(void)purgeSharedSpriteFrameCache -{ - [sharedSpriteFrameCache_ release]; - sharedSpriteFrameCache_ = nil; -} - --(id) init -{ - if( (self=[super init]) ) { - spriteFrames_ = [[NSMutableDictionary alloc] initWithCapacity: 100]; - spriteFramesAliases_ = [[NSMutableDictionary alloc] initWithCapacity:10]; - } - - return self; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | num of sprite frames = %i>", [self class], self, [spriteFrames_ count]]; -} - --(void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - [spriteFrames_ release]; - [spriteFramesAliases_ release]; - [super dealloc]; -} - -#pragma mark CCSpriteFrameCache - loading sprite frames - --(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary textureReference:(id)textureReference -{ - /* - Supported Zwoptex Formats: - ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version - ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b - ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1 - ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+ - */ - NSDictionary *metadataDict = [dictionary objectForKey:@"metadata"]; - NSDictionary *framesDict = [dictionary objectForKey:@"frames"]; - - int format = 0; - - // get the format - if(metadataDict != nil) - format = [[metadataDict objectForKey:@"format"] intValue]; - - // check the format - NSAssert( format >= 0 && format <= 3, @"cocos2d: WARNING: format is not supported for CCSpriteFrameCache addSpriteFramesWithDictionary:textureFilename:"); - - // SpriteFrame info - CGRect rectInPixels; - BOOL isRotated; - CGPoint frameOffset; - CGSize originalSize; - - // add real frames - for(NSString *frameDictKey in framesDict) { - NSDictionary *frameDict = [framesDict objectForKey:frameDictKey]; - CCSpriteFrame *spriteFrame=nil; - if(format == 0) { - float x = [[frameDict objectForKey:@"x"] floatValue]; - float y = [[frameDict objectForKey:@"y"] floatValue]; - float w = [[frameDict objectForKey:@"width"] floatValue]; - float h = [[frameDict objectForKey:@"height"] floatValue]; - float ox = [[frameDict objectForKey:@"offsetX"] floatValue]; - float oy = [[frameDict objectForKey:@"offsetY"] floatValue]; - int ow = [[frameDict objectForKey:@"originalWidth"] intValue]; - int oh = [[frameDict objectForKey:@"originalHeight"] intValue]; - // check ow/oh - if(!ow || !oh) - CCLOG(@"cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist"); - - // abs ow/oh - ow = abs(ow); - oh = abs(oh); - - // set frame info - rectInPixels = CGRectMake(x, y, w, h); - isRotated = NO; - frameOffset = CGPointMake(ox, oy); - originalSize = CGSizeMake(ow, oh); - } else if(format == 1 || format == 2) { - CGRect frame = CCRectFromString([frameDict objectForKey:@"frame"]); - BOOL rotated = NO; - - // rotation - if(format == 2) - rotated = [[frameDict objectForKey:@"rotated"] boolValue]; - - CGPoint offset = CCPointFromString([frameDict objectForKey:@"offset"]); - CGSize sourceSize = CCSizeFromString([frameDict objectForKey:@"sourceSize"]); - - // set frame info - rectInPixels = frame; - isRotated = rotated; - frameOffset = offset; - originalSize = sourceSize; - } else if(format == 3) { - // get values - CGSize spriteSize = CCSizeFromString([frameDict objectForKey:@"spriteSize"]); - CGPoint spriteOffset = CCPointFromString([frameDict objectForKey:@"spriteOffset"]); - CGSize spriteSourceSize = CCSizeFromString([frameDict objectForKey:@"spriteSourceSize"]); - CGRect textureRect = CCRectFromString([frameDict objectForKey:@"textureRect"]); - BOOL textureRotated = [[frameDict objectForKey:@"textureRotated"] boolValue]; - - // get aliases - NSArray *aliases = [frameDict objectForKey:@"aliases"]; - for(NSString *alias in aliases) { - if( [spriteFramesAliases_ objectForKey:alias] ) - CCLOG(@"cocos2d: WARNING: an alias with name %@ already exists",alias); - - [spriteFramesAliases_ setObject:frameDictKey forKey:alias]; - } - - // set frame info - rectInPixels = CGRectMake(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height); - isRotated = textureRotated; - frameOffset = spriteOffset; - originalSize = spriteSourceSize; - } - - NSString *textureFileName = nil; - CCTexture2D * texture = nil; - - if ( [textureReference isKindOfClass:[NSString class]] ) - { - textureFileName = textureReference; - } - else if ( [textureReference isKindOfClass:[CCTexture2D class]] ) - { - texture = textureReference; - } - - if ( textureFileName ) - { - spriteFrame = [[CCSpriteFrame alloc] initWithTextureFilename:textureFileName rectInPixels:rectInPixels rotated:isRotated offset:frameOffset originalSize:originalSize]; - } - else - { - spriteFrame = [[CCSpriteFrame alloc] initWithTexture:texture rectInPixels:rectInPixels rotated:isRotated offset:frameOffset originalSize:originalSize]; - } - - // add sprite frame - [spriteFrames_ setObject:spriteFrame forKey:frameDictKey]; - [spriteFrame release]; - } -} - --(void) addSpriteFramesWithDictionary:(NSDictionary*)dictionary textureFilename:(NSString*)textureFilename -{ - return [self addSpriteFramesWithDictionary:dictionary textureReference:textureFilename]; -} - --(void) addSpriteFramesWithDictionary:(NSDictionary *)dictionary texture:(CCTexture2D *)texture -{ - return [self addSpriteFramesWithDictionary:dictionary textureReference:texture]; -} - --(void) addSpriteFramesWithFile:(NSString*)plist textureReference:(id)textureReference -{ - NSAssert(textureReference, @"textureReference should not be nil"); - NSAssert(plist, @"plist filename should not be nil"); - - NSString *path = [CCFileUtils fullPathFromRelativePath:plist]; - NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - - [self addSpriteFramesWithDictionary:dict textureReference:textureReference]; -} - --(void) addSpriteFramesWithFile:(NSString*)plist textureFilename:(NSString*)textureFilename -{ - return [self addSpriteFramesWithFile:plist textureReference:textureFilename]; -} - --(void) addSpriteFramesWithFile:(NSString*)plist texture:(CCTexture2D*)texture -{ - return [self addSpriteFramesWithFile:plist textureReference:texture]; -} - - --(void) addSpriteFramesWithFile:(NSString*)plist -{ - NSAssert(plist, @"plist filename should not be nil"); - - NSString *path = [CCFileUtils fullPathFromRelativePath:plist]; - NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - - NSString *texturePath = nil; - NSDictionary *metadataDict = [dict objectForKey:@"metadata"]; - if( metadataDict ) - // try to read texture file name from meta data - texturePath = [metadataDict objectForKey:@"textureFileName"]; - - - if( texturePath ) - { - // build texture path relative to plist file - NSString *textureBase = [plist stringByDeletingLastPathComponent]; - texturePath = [textureBase stringByAppendingPathComponent:texturePath]; - } else { - // build texture path by replacing file extension - texturePath = [plist stringByDeletingPathExtension]; - texturePath = [texturePath stringByAppendingPathExtension:@"png"]; - - CCLOG(@"cocos2d: CCSpriteFrameCache: Trying to use file '%@' as texture", texturePath); - } - - - [self addSpriteFramesWithDictionary:dict textureFilename:texturePath]; -} - --(void) addSpriteFrame:(CCSpriteFrame*)frame name:(NSString*)frameName -{ - [spriteFrames_ setObject:frame forKey:frameName]; -} - -#pragma mark CCSpriteFrameCache - removing - --(void) removeSpriteFrames -{ - [spriteFrames_ removeAllObjects]; - [spriteFramesAliases_ removeAllObjects]; -} - --(void) removeUnusedSpriteFrames -{ - NSArray *keys = [spriteFrames_ allKeys]; - for( id key in keys ) { - id value = [spriteFrames_ objectForKey:key]; - if( [value retainCount] == 1 ) { - CCLOG(@"cocos2d: CCSpriteFrameCache: removing unused frame: %@", key); - [spriteFrames_ removeObjectForKey:key]; - } - } -} - --(void) removeSpriteFrameByName:(NSString*)name -{ - // explicit nil handling - if( ! name ) - return; - - // Is this an alias ? - NSString *key = [spriteFramesAliases_ objectForKey:name]; - - if( key ) { - [spriteFrames_ removeObjectForKey:key]; - [spriteFramesAliases_ removeObjectForKey:name]; - - } else - [spriteFrames_ removeObjectForKey:name]; -} - -- (void) removeSpriteFramesFromFile:(NSString*) plist -{ - NSString *path = [CCFileUtils fullPathFromRelativePath:plist]; - NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - - [self removeSpriteFramesFromDictionary:dict]; -} - -- (void) removeSpriteFramesFromDictionary:(NSDictionary*) dictionary -{ - NSDictionary *framesDict = [dictionary objectForKey:@"frames"]; - NSMutableArray *keysToRemove=[NSMutableArray array]; - - for(NSString *frameDictKey in framesDict) - { - if ([spriteFrames_ objectForKey:frameDictKey]!=nil) - [keysToRemove addObject:frameDictKey]; - } - [spriteFrames_ removeObjectsForKeys:keysToRemove]; -} - -- (void) removeSpriteFramesFromTexture:(CCTexture2D*) texture -{ - NSMutableArray *keysToRemove=[NSMutableArray array]; - - for (NSString *spriteFrameKey in spriteFrames_) - { - if ([[spriteFrames_ valueForKey:spriteFrameKey] texture] == texture) - [keysToRemove addObject:spriteFrameKey]; - - } - [spriteFrames_ removeObjectsForKeys:keysToRemove]; -} - -#pragma mark CCSpriteFrameCache - getting - --(CCSpriteFrame*) spriteFrameByName:(NSString*)name -{ - CCSpriteFrame *frame = [spriteFrames_ objectForKey:name]; - if( ! frame ) { - // try alias dictionary - NSString *key = [spriteFramesAliases_ objectForKey:name]; - frame = [spriteFrames_ objectForKey:key]; - - if( ! frame ) - CCLOG(@"cocos2d: CCSpriteFrameCache: Frame '%@' not found", name); - } - - return frame; -} - -@end diff --git a/Example/libs/cocos2d/CCTMXLayer.h b/Example/libs/cocos2d/CCTMXLayer.h deleted file mode 100644 index ed1f4f1..0000000 --- a/Example/libs/cocos2d/CCTMXLayer.h +++ /dev/null @@ -1,164 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * TMX Tiled Map support: - * http://www.mapeditor.org - * - */ - - -#import "CCAtlasNode.h" -#import "CCSpriteBatchNode.h" -#import "CCTMXXMLParser.h" - -@class CCTMXMapInfo; -@class CCTMXLayerInfo; -@class CCTMXTilesetInfo; - - -/** CCTMXLayer represents the TMX layer. - - It is a subclass of CCSpriteBatchNode. By default the tiles are rendered using a CCTextureAtlas. - If you mofify a tile on runtime, then, that tile will become a CCSprite, otherwise no CCSprite objects are created. - The benefits of using CCSprite objects as tiles are: - - tiles (CCSprite) can be rotated/scaled/moved with a nice API - - cocos2d v2.0 doesn't support the cc_vertexz value. Whenever a the cc_vertexz property is found, it will raise an exception. - - "value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer. - The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a differnt - value, like 0.5. - - For further information, please see the programming guide: - - http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps - - @since v0.8.1 - - Tiles can have tile flags for additional properties. At the moment only flip horizontal and flip vertical are used. These bit flags are defined in CCTMXXMLParser.h. - - @since 1.1 - */ -@interface CCTMXLayer : CCSpriteBatchNode -{ - CCTMXTilesetInfo *tileset_; - NSString *layerName_; - CGSize layerSize_; - CGSize mapTileSize_; - uint32_t *tiles_; // GID are 32 bit - NSUInteger layerOrientation_; - NSMutableArray *properties_; - - unsigned char opacity_; // TMX Layer supports opacity - - NSUInteger minGID_; - NSUInteger maxGID_; - - // Only used when vertexZ is used - NSInteger vertexZvalue_; - BOOL useAutomaticVertexZ_; - - // used for optimization - CCSprite *reusedTile_; - ccCArray *atlasIndexArray_; -} -/** name of the layer */ -@property (nonatomic,readwrite,retain) NSString *layerName; -/** size of the layer in tiles */ -@property (nonatomic,readwrite) CGSize layerSize; -/** size of the map's tile (could be differnt from the tile's size) */ -@property (nonatomic,readwrite) CGSize mapTileSize; -/** pointer to the map of tiles */ -@property (nonatomic,readwrite) uint32_t *tiles; -/** Tilset information for the layer */ -@property (nonatomic,readwrite,retain) CCTMXTilesetInfo *tileset; -/** Layer orientation, which is the same as the map orientation */ -@property (nonatomic,readwrite) NSUInteger layerOrientation; -/** properties from the layer. They can be added using Tiled */ -@property (nonatomic,readwrite,retain) NSMutableArray *properties; - -/** creates a CCTMXLayer with an tileset info, a layer info and a map info */ -+(id) layerWithTilesetInfo:(CCTMXTilesetInfo*)tilesetInfo layerInfo:(CCTMXLayerInfo*)layerInfo mapInfo:(CCTMXMapInfo*)mapInfo; -/** initializes a CCTMXLayer with a tileset info, a layer info and a map info */ --(id) initWithTilesetInfo:(CCTMXTilesetInfo*)tilesetInfo layerInfo:(CCTMXLayerInfo*)layerInfo mapInfo:(CCTMXMapInfo*)mapInfo; - -/** dealloc the map that contains the tile position from memory. - Unless you want to know at runtime the tiles positions, you can safely call this method. - If you are going to call [layer tileGIDAt:] then, don't release the map - */ --(void) releaseMap; - -/** returns the tile (CCSprite) at a given a tile coordinate. - The returned CCSprite will be already added to the CCTMXLayer. Don't add it again. - The CCSprite can be treated like any other CCSprite: rotated, scaled, translated, opacity, color, etc. - You can remove either by calling: - - [layer removeChild:sprite cleanup:cleanup]; - - or [layer removeTileAt:ccp(x,y)]; - */ --(CCSprite*) tileAt:(CGPoint)tileCoordinate; - -/** returns the tile gid at a given tile coordinate. - if it returns 0, it means that the tile is empty. - This method requires the the tile map has not been previously released (eg. don't call [layer releaseMap]) - */ --(uint32_t) tileGIDAt:(CGPoint)tileCoordinate; - -/** returns the tile gid at a given tile coordinate. It also returns the tile flags. - This method requires the the tile map has not been previously released (eg. don't call [layer releaseMap]) - */ --(uint32_t) tileGIDAt:(CGPoint)pos withFlags:(ccTMXTileFlags*)flags; - -/** sets the tile gid (gid = tile global id) at a given tile coordinate. - The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1. - If a tile is already placed at that position, then it will be removed. - */ --(void) setTileGID:(uint32_t)gid at:(CGPoint)tileCoordinate; - -/** sets the tile gid (gid = tile global id) at a given tile coordinate. - The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1. - If a tile is already placed at that position, then it will be removed. - - Use withFlags if the tile flags need to be changed as well - */ - --(void) setTileGID:(uint32_t)gid at:(CGPoint)pos withFlags:(ccTMXTileFlags)flags; - -/** removes a tile at given tile coordinate */ --(void) removeTileAt:(CGPoint)tileCoordinate; - -/** returns the position in points of a given tile coordinate */ --(CGPoint) positionAt:(CGPoint)tileCoordinate; - -/** return the value for the specific property name */ --(id) propertyNamed:(NSString *)propertyName; - -/** Creates the tiles */ --(void) setupTiles; - -/** CCTMXLayer doesn't support adding a CCSprite manually. - @warning addchild:z:tag: is not supported on CCTMXLayer. Instead of setTileGID:at:/tileAt: - */ --(void) addChild: (CCNode*)node z:(NSInteger)z tag:(NSInteger)tag; -@end diff --git a/Example/libs/cocos2d/CCTMXLayer.m b/Example/libs/cocos2d/CCTMXLayer.m deleted file mode 100644 index 6738e19..0000000 --- a/Example/libs/cocos2d/CCTMXLayer.m +++ /dev/null @@ -1,658 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * TMX Tiled Map support: - * http://www.mapeditor.org - * - */ - -#import "CCTMXLayer.h" -#import "CCTMXTiledMap.h" -#import "CCTMXXMLParser.h" -#import "CCSprite.h" -#import "CCSpriteBatchNode.h" -#import "CCTextureCache.h" -#import "CCShaderCache.h" -#import "CCGLProgram.h" -#import "Support/CGPointExtension.h" - - -#pragma mark - -#pragma mark CCTMXLayer - -int compareInts (const void * a, const void * b); - - -@interface CCTMXLayer () --(CGPoint) positionForIsoAt:(CGPoint)pos; --(CGPoint) positionForOrthoAt:(CGPoint)pos; --(CGPoint) positionForHexAt:(CGPoint)pos; - --(CGPoint) calculateLayerOffset:(CGPoint)offset; - -/* optimization methos */ --(CCSprite*) appendTileForGID:(uint32_t)gid at:(CGPoint)pos; --(CCSprite*) insertTileForGID:(uint32_t)gid at:(CGPoint)pos; --(CCSprite*) updateTileForGID:(uint32_t)gid at:(CGPoint)pos; - -/* The layer recognizes some special properties, like cc_vertez */ --(void) parseInternalProperties; -- (void) setupTileSprite:(CCSprite*) sprite position:(CGPoint)pos withGID:(uint32_t)gid; - --(NSInteger) vertexZForPos:(CGPoint)pos; - -// index --(NSUInteger) atlasIndexForExistantZ:(NSUInteger)z; --(NSUInteger) atlasIndexForNewZ:(NSUInteger)z; -@end - -@implementation CCTMXLayer -@synthesize layerSize = layerSize_, layerName = layerName_, tiles = tiles_; -@synthesize tileset = tileset_; -@synthesize layerOrientation = layerOrientation_; -@synthesize mapTileSize = mapTileSize_; -@synthesize properties = properties_; - -#pragma mark CCTMXLayer - init & alloc & dealloc - -+(id) layerWithTilesetInfo:(CCTMXTilesetInfo*)tilesetInfo layerInfo:(CCTMXLayerInfo*)layerInfo mapInfo:(CCTMXMapInfo*)mapInfo -{ - return [[[self alloc] initWithTilesetInfo:tilesetInfo layerInfo:layerInfo mapInfo:mapInfo] autorelease]; -} - --(id) initWithTilesetInfo:(CCTMXTilesetInfo*)tilesetInfo layerInfo:(CCTMXLayerInfo*)layerInfo mapInfo:(CCTMXMapInfo*)mapInfo -{ - // XXX: is 35% a good estimate ? - CGSize size = layerInfo.layerSize; - float totalNumberOfTiles = size.width * size.height; - float capacity = totalNumberOfTiles * 0.35f + 1; // 35 percent is occupied ? - - CCTexture2D *tex = nil; - if( tilesetInfo ) - tex = [[CCTextureCache sharedTextureCache] addImage:tilesetInfo.sourceImage]; - - if((self = [super initWithTexture:tex capacity:capacity])) { - - // layerInfo - self.layerName = layerInfo.name; - layerSize_ = size; - tiles_ = layerInfo.tiles; - minGID_ = layerInfo.minGID; - maxGID_ = layerInfo.maxGID; - opacity_ = layerInfo.opacity; - self.properties = [NSMutableDictionary dictionaryWithDictionary:layerInfo.properties]; - - // tilesetInfo - self.tileset = tilesetInfo; - - // mapInfo - mapTileSize_ = mapInfo.tileSize; - layerOrientation_ = mapInfo.orientation; - - // offset (after layer orientation is set); - CGPoint offset = [self calculateLayerOffset:layerInfo.offset]; - [self setPosition:CC_POINT_PIXELS_TO_POINTS(offset)]; - - atlasIndexArray_ = ccCArrayNew(totalNumberOfTiles); - - [self setContentSize:CC_SIZE_PIXELS_TO_POINTS(CGSizeMake( layerSize_.width * mapTileSize_.width, layerSize_.height * mapTileSize_.height ))]; - - useAutomaticVertexZ_= NO; - vertexZvalue_ = 0; - } - - return self; -} - -- (void) dealloc -{ - [layerName_ release]; - [tileset_ release]; - [reusedTile_ release]; - [properties_ release]; - - if( atlasIndexArray_ ) { - ccCArrayFree(atlasIndexArray_); - atlasIndexArray_ = NULL; - } - - if( tiles_ ) { - free(tiles_); - tiles_ = NULL; - } - - [super dealloc]; -} - --(void) releaseMap -{ - if( tiles_) { - free( tiles_); - tiles_ = NULL; - } - - if( atlasIndexArray_ ) { - ccCArrayFree(atlasIndexArray_); - atlasIndexArray_ = NULL; - } -} - -#pragma mark CCTMXLayer - setup Tiles - --(CCSprite*) reusedTileWithRect:(CGRect)rect -{ - if( ! reusedTile_ ) { - reusedTile_ = [[CCSprite alloc] initWithTexture:textureAtlas_.texture rect:rect rotated:NO]; - [reusedTile_ setBatchNode:self]; - } - else - { - // XXX: should not be re-init. Potential memeory leak. Not following best practices - // XXX: it shall call directory [setRect:rect] - [reusedTile_ initWithTexture:textureAtlas_.texture rect:rect rotated:NO]; - - // Since initWithTexture resets the batchNode, we need to re add it. - // but should be removed once initWithTexture is not called again - [reusedTile_ setBatchNode:self]; - } - - return reusedTile_; -} - --(void) setupTiles -{ - // Optimization: quick hack that sets the image size on the tileset - tileset_.imageSize = [textureAtlas_.texture contentSizeInPixels]; - - // By default all the tiles are aliased - // pros: - // - easier to render - // cons: - // - difficult to scale / rotate / etc. - [textureAtlas_.texture setAliasTexParameters]; - - // Parse cocos2d properties - [self parseInternalProperties]; - - for( NSUInteger y = 0; y < layerSize_.height; y++ ) { - for( NSUInteger x = 0; x < layerSize_.width; x++ ) { - - NSUInteger pos = x + layerSize_.width * y; - uint32_t gid = tiles_[ pos ]; - - // gid are stored in little endian. - // if host is big endian, then swap - gid = CFSwapInt32LittleToHost( gid ); - - // XXX: gid == 0 --> empty tile - if( gid != 0 ) { - [self appendTileForGID:gid at:ccp(x,y)]; - - // Optimization: update min and max GID rendered by the layer - minGID_ = MIN(gid, minGID_); - maxGID_ = MAX(gid, maxGID_); -// minGID_ = MIN((gid & kFlippedMask), minGID_); -// maxGID_ = MAX((gid & kFlippedMask), maxGID_); - } - } - } - - NSAssert( maxGID_ >= tileset_.firstGid && - minGID_ >= tileset_.firstGid, @"TMX: Only 1 tilset per layer is supported"); -} - -#pragma mark CCTMXLayer - Properties - --(id) propertyNamed:(NSString *)propertyName -{ - return [properties_ valueForKey:propertyName]; -} - --(void) parseInternalProperties -{ - // if cc_vertex=automatic, then tiles will be rendered using vertexz - - NSString *vertexz = [self propertyNamed:@"cc_vertexz"]; - if( vertexz ) { - - // If "automatic" is on, then parse the "cc_alpha_func" too - if( [vertexz isEqualToString:@"automatic"] ) { - useAutomaticVertexZ_ = YES; - - NSString *alphaFuncVal = [self propertyNamed:@"cc_alpha_func"]; - float alphaFuncValue = [alphaFuncVal floatValue]; - - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColorAlphaTest]; - - GLint alphaValueLocation = glGetUniformLocation(self.shaderProgram->program_, kCCUniformAlphaTestValue); - - // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison - [self.shaderProgram setUniformLocation:alphaValueLocation withF1:alphaFuncValue]; - } - else - vertexZvalue_ = [vertexz intValue]; - } -} - -#pragma mark CCTMXLayer - obtaining tiles/gids - --(CCSprite*) tileAt:(CGPoint)pos -{ - NSAssert( pos.x < layerSize_.width && pos.y < layerSize_.height && pos.x >=0 && pos.y >=0, @"TMXLayer: invalid position"); - NSAssert( tiles_ && atlasIndexArray_, @"TMXLayer: the tiles map has been released"); - - CCSprite *tile = nil; - uint32_t gid = [self tileGIDAt:pos]; - - // if GID == 0, then no tile is present - if( gid ) { - int z = pos.x + pos.y * layerSize_.width; - tile = (CCSprite*) [self getChildByTag:z]; - - // tile not created yet. create it - if( ! tile ) { - CGRect rect = [tileset_ rectForGID:gid]; - rect = CC_RECT_PIXELS_TO_POINTS(rect); - tile = [[CCSprite alloc] initWithTexture:self.texture rect:rect]; - [tile setBatchNode:self]; - - CGPoint p = [self positionAt:pos]; - [tile setPosition:p]; - [tile setVertexZ: [self vertexZForPos:pos]]; - tile.anchorPoint = CGPointZero; - [tile setOpacity:opacity_]; - - NSUInteger indexForZ = [self atlasIndexForExistantZ:z]; - [self addSpriteWithoutQuad:tile z:indexForZ tag:z]; - [tile release]; - } - } - return tile; -} - --(uint32_t) tileGIDAt:(CGPoint)pos -{ - return [self tileGIDAt:pos withFlags:NULL]; -} - --(uint32_t) tileGIDAt:(CGPoint)pos withFlags:(ccTMXTileFlags*)flags -{ - NSAssert( pos.x < layerSize_.width && pos.y < layerSize_.height && pos.x >=0 && pos.y >=0, @"TMXLayer: invalid position"); - NSAssert( tiles_ && atlasIndexArray_, @"TMXLayer: the tiles map has been released"); - - NSInteger idx = pos.x + pos.y * layerSize_.width; - - // Bits on the far end of the 32-bit global tile ID are used for tile flags - - uint32_t tile = tiles_[idx]; - - // issue1264, flipped tiles can be changed dynamically - if (flags) - *flags = tile & kCCFlipedAll; - - return ( tile & kCCFlippedMask); -} - -#pragma mark CCTMXLayer - adding helper methods - -- (void) setupTileSprite:(CCSprite*) sprite position:(CGPoint)pos withGID:(uint32_t)gid -{ - [sprite setPosition: [self positionAt:pos]]; - [sprite setVertexZ: [self vertexZForPos:pos]]; - sprite.anchorPoint = CGPointZero; - [sprite setOpacity:opacity_]; - - //issue 1264, flip can be undone as well - if (gid & kCCTMXTileHorizontalFlag) - sprite.flipX = YES; - else - sprite.flipX = NO; - - if (gid & kCCTMXTileVerticalFlag) - sprite.flipY = YES; - else - sprite.flipY = NO; - - if( gid & kCCTMXTileDiagonalFlag) - NSAssert(NO, @"Tiled Anti-Diagonally Flip not supported yet"); -} - --(CCSprite*) insertTileForGID:(uint32_t)gid at:(CGPoint)pos -{ - CGRect rect = [tileset_ rectForGID:gid]; - rect = CC_RECT_PIXELS_TO_POINTS(rect); - - NSInteger z = pos.x + pos.y * layerSize_.width; - - CCSprite *tile = [self reusedTileWithRect:rect]; - - [self setupTileSprite:tile position:pos withGID:gid]; - - // get atlas index - NSUInteger indexForZ = [self atlasIndexForNewZ:z]; - - // Optimization: add the quad without adding a child - [self addQuadFromSprite:tile quadIndex:indexForZ]; - - // insert it into the local atlasindex array - ccCArrayInsertValueAtIndex(atlasIndexArray_, (void*)z, indexForZ); - - // update possible children - CCSprite *sprite; - CCARRAY_FOREACH(children_, sprite) { - NSUInteger ai = [sprite atlasIndex]; - if( ai >= indexForZ) - [sprite setAtlasIndex: ai+1]; - } - - tiles_[z] = gid; - - return tile; -} - --(CCSprite*) updateTileForGID:(uint32_t)gid at:(CGPoint)pos -{ - CGRect rect = [tileset_ rectForGID:gid]; - rect = CC_RECT_PIXELS_TO_POINTS(rect); - - int z = pos.x + pos.y * layerSize_.width; - - CCSprite *tile = [self reusedTileWithRect:rect]; - - [self setupTileSprite:tile position:pos withGID:gid]; - - // get atlas index - NSUInteger indexForZ = [self atlasIndexForExistantZ:z]; - - [tile setAtlasIndex:indexForZ]; - [tile setDirty:YES]; - [tile updateTransform]; - tiles_[z] = gid; - - return tile; -} - - -// used only when parsing the map. useless after the map was parsed -// since lot's of assumptions are no longer true --(CCSprite*) appendTileForGID:(uint32_t)gid at:(CGPoint)pos -{ - CGRect rect = [tileset_ rectForGID:gid]; - rect = CC_RECT_PIXELS_TO_POINTS(rect); - - NSInteger z = pos.x + pos.y * layerSize_.width; - - CCSprite *tile = [self reusedTileWithRect:rect]; - - [self setupTileSprite:tile position:pos withGID:gid]; - - // optimization: - // The difference between appendTileForGID and insertTileforGID is that append is faster, since - // it appends the tile at the end of the texture atlas - NSUInteger indexForZ = atlasIndexArray_->num; - - - // don't add it using the "standard" way. - [self addQuadFromSprite:tile quadIndex:indexForZ]; - - - // append should be after addQuadFromSprite since it modifies the quantity values - ccCArrayInsertValueAtIndex(atlasIndexArray_, (void*)z, indexForZ); - - return tile; -} - -#pragma mark CCTMXLayer - atlasIndex and Z - -int compareInts (const void * a, const void * b) -{ - return ( *(int*)a - *(int*)b ); -} - --(NSUInteger) atlasIndexForExistantZ:(NSUInteger)z -{ - NSInteger key = z; - NSInteger *item = bsearch((void*)&key, (void*)&atlasIndexArray_->arr[0], atlasIndexArray_->num, sizeof(void*), compareInts); - - NSAssert( item, @"TMX atlas index not found. Shall not happen"); - - NSUInteger index = ((NSInteger)item - (NSInteger)atlasIndexArray_->arr) / sizeof(void*); - return index; -} - --(NSUInteger)atlasIndexForNewZ:(NSUInteger)z -{ - // XXX: This can be improved with a sort of binary search - NSUInteger i = 0; - for(i = 0; i< atlasIndexArray_->num; i++) { - NSUInteger val = (NSUInteger) atlasIndexArray_->arr[i]; - if( z < val ) - break; - } - return i; -} - -#pragma mark CCTMXLayer - adding / remove tiles --(void) setTileGID:(uint32_t)gid at:(CGPoint)pos -{ - [self setTileGID:gid at:pos withFlags:NO]; -} - --(void) setTileGID:(uint32_t)gid at:(CGPoint)pos withFlags:(ccTMXTileFlags)flags -{ - NSAssert( pos.x < layerSize_.width && pos.y < layerSize_.height && pos.x >=0 && pos.y >=0, @"TMXLayer: invalid position"); - NSAssert( tiles_ && atlasIndexArray_, @"TMXLayer: the tiles map has been released"); - NSAssert( gid == 0 || gid >= tileset_.firstGid, @"TMXLayer: invalid gid" ); - - ccTMXTileFlags currentFlags; - uint32_t currentGID = [self tileGIDAt:pos withFlags:¤tFlags]; - - if (currentGID != gid || currentFlags != flags ) - { - uint32_t gidAndFlags = gid | flags; - - // setting gid=0 is equal to remove the tile - if( gid == 0 ) - [self removeTileAt:pos]; - - // empty tile. create a new one - else if( currentGID == 0 ) - [self insertTileForGID:gidAndFlags at:pos]; - - // modifying an existing tile with a non-empty tile - else { - - NSUInteger z = pos.x + pos.y * layerSize_.width; - CCSprite *sprite = (CCSprite*)[self getChildByTag:z]; - if( sprite ) { - CGRect rect = [tileset_ rectForGID:gid]; - rect = CC_RECT_PIXELS_TO_POINTS(rect); - - [sprite setTextureRect:rect rotated:NO untrimmedSize:rect.size]; - - if (flags) - [self setupTileSprite:sprite position:[sprite position] withGID:gidAndFlags]; - - tiles_[z] = gidAndFlags; - } else - [self updateTileForGID:gidAndFlags at:pos]; - } - } -} - --(void) addChild: (CCNode*)node z:(NSInteger)z tag:(NSInteger)tag -{ - NSAssert(NO, @"addChild: is not supported on CCTMXLayer. Instead use setTileGID:at:/tileAt:"); -} - --(void) removeChild:(CCSprite*)sprite cleanup:(BOOL)cleanup -{ - // allows removing nil objects - if( ! sprite ) - return; - - NSAssert( [children_ containsObject:sprite], @"Tile does not belong to TMXLayer"); - - NSUInteger atlasIndex = [sprite atlasIndex]; - NSUInteger zz = (NSUInteger) atlasIndexArray_->arr[atlasIndex]; - tiles_[zz] = 0; - ccCArrayRemoveValueAtIndex(atlasIndexArray_, atlasIndex); - [super removeChild:sprite cleanup:cleanup]; -} - --(void) removeTileAt:(CGPoint)pos -{ - NSAssert( pos.x < layerSize_.width && pos.y < layerSize_.height && pos.x >=0 && pos.y >=0, @"TMXLayer: invalid position"); - NSAssert( tiles_ && atlasIndexArray_, @"TMXLayer: the tiles map has been released"); - - uint32_t gid = [self tileGIDAt:pos]; - - if( gid ) { - - NSUInteger z = pos.x + pos.y * layerSize_.width; - NSUInteger atlasIndex = [self atlasIndexForExistantZ:z]; - - // remove tile from GID map - tiles_[z] = 0; - - // remove tile from atlas position array - ccCArrayRemoveValueAtIndex(atlasIndexArray_, atlasIndex); - - // remove it from sprites and/or texture atlas - id sprite = [self getChildByTag:z]; - if( sprite ) - [super removeChild:sprite cleanup:YES]; - else { - [textureAtlas_ removeQuadAtIndex:atlasIndex]; - - // update possible children - CCARRAY_FOREACH(children_, sprite) { - NSUInteger ai = [sprite atlasIndex]; - if( ai >= atlasIndex) { - [sprite setAtlasIndex: ai-1]; - } - } - } - } -} - -#pragma mark CCTMXLayer - obtaining positions, offset - --(CGPoint) calculateLayerOffset:(CGPoint)pos -{ - CGPoint ret = CGPointZero; - switch( layerOrientation_ ) { - case CCTMXOrientationOrtho: - ret = ccp( pos.x * mapTileSize_.width, -pos.y *mapTileSize_.height); - break; - case CCTMXOrientationIso: - ret = ccp( (mapTileSize_.width /2) * (pos.x - pos.y), - (mapTileSize_.height /2 ) * (-pos.x - pos.y) ); - break; - case CCTMXOrientationHex: - NSAssert(CGPointEqualToPoint(pos, CGPointZero), @"offset for hexagonal map not implemented yet"); - break; - } - return ret; -} - --(CGPoint) positionAt:(CGPoint)pos -{ - CGPoint ret = CGPointZero; - switch( layerOrientation_ ) { - case CCTMXOrientationOrtho: - ret = [self positionForOrthoAt:pos]; - break; - case CCTMXOrientationIso: - ret = [self positionForIsoAt:pos]; - break; - case CCTMXOrientationHex: - ret = [self positionForHexAt:pos]; - break; - } - - ret = CC_POINT_PIXELS_TO_POINTS( ret ); - return ret; -} - --(CGPoint) positionForOrthoAt:(CGPoint)pos -{ - CGPoint xy = { - pos.x * mapTileSize_.width, - (layerSize_.height - pos.y - 1) * mapTileSize_.height, - }; - return xy; -} - --(CGPoint) positionForIsoAt:(CGPoint)pos -{ - CGPoint xy = { - mapTileSize_.width /2 * ( layerSize_.width + pos.x - pos.y - 1), - mapTileSize_.height /2 * (( layerSize_.height * 2 - pos.x - pos.y) - 2), - }; - return xy; -} - --(CGPoint) positionForHexAt:(CGPoint)pos -{ - float diffY = 0; - if( (int)pos.x % 2 == 1 ) - diffY = -mapTileSize_.height/2 ; - - CGPoint xy = { - pos.x * mapTileSize_.width*3/4, - (layerSize_.height - pos.y - 1) * mapTileSize_.height + diffY - }; - return xy; -} - --(NSInteger) vertexZForPos:(CGPoint)pos -{ - NSInteger ret = 0; - NSUInteger maxVal = 0; - if( useAutomaticVertexZ_ ) { - switch( layerOrientation_ ) { - case CCTMXOrientationIso: - maxVal = layerSize_.width + layerSize_.height; - ret = -(maxVal - (pos.x + pos.y)); - break; - case CCTMXOrientationOrtho: - ret = -(layerSize_.height-pos.y); - break; - case CCTMXOrientationHex: - NSAssert(NO,@"TMX Hexa zOrder not supported"); - break; - default: - NSAssert(NO,@"TMX invalid value"); - break; - } - } else - ret = vertexZvalue_; - - return ret; -} - -@end - diff --git a/Example/libs/cocos2d/CCTMXObjectGroup.h b/Example/libs/cocos2d/CCTMXObjectGroup.h deleted file mode 100644 index 17fa09c..0000000 --- a/Example/libs/cocos2d/CCTMXObjectGroup.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Neophit - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * TMX Tiled Map support: - * http://www.mapeditor.org - * - */ - -#import "CCNode.h" - - -@class CCTMXObjectGroup; - - -/** CCTMXObjectGroup represents the TMX object group. -@since v0.99.0 -*/ -@interface CCTMXObjectGroup : NSObject -{ - NSString *groupName_; - CGPoint positionOffset_; - NSMutableArray *objects_; - NSMutableDictionary *properties_; -} - -/** name of the group */ -@property (nonatomic,readwrite,retain) NSString *groupName; -/** offset position of child objects */ -@property (nonatomic,readwrite,assign) CGPoint positionOffset; -/** array of the objects */ -@property (nonatomic,readwrite,retain) NSMutableArray *objects; -/** list of properties stored in a dictionary */ -@property (nonatomic,readwrite,retain) NSMutableDictionary *properties; - -/** return the value for the specific property name */ --(id) propertyNamed:(NSString *)propertyName; - -/** return the dictionary for the specific object name. - It will return the 1st object found on the array for the given name. - */ --(NSMutableDictionary*) objectNamed:(NSString *)objectName; - -@end diff --git a/Example/libs/cocos2d/CCTMXObjectGroup.m b/Example/libs/cocos2d/CCTMXObjectGroup.m deleted file mode 100644 index 970effa..0000000 --- a/Example/libs/cocos2d/CCTMXObjectGroup.m +++ /dev/null @@ -1,86 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Neophit - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * TMX Tiled Map support: - * http://www.mapeditor.org - * - */ - -#import "CCTMXObjectGroup.h" -#import "CCTMXXMLParser.h" -#import "ccMacros.h" -#import "Support/CGPointExtension.h" - - -#pragma mark - -#pragma mark TMXObjectGroup - -@implementation CCTMXObjectGroup - -@synthesize groupName = groupName_; -@synthesize objects = objects_; -@synthesize positionOffset = positionOffset_; -@synthesize properties = properties_; - --(id) init -{ - if (( self=[super init] )) { - self.groupName = nil; - self.positionOffset = CGPointZero; - self.objects = [NSMutableArray arrayWithCapacity:10]; - self.properties = [NSMutableDictionary dictionaryWithCapacity:5]; - } - return self; -} - --(void) dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@", self ); - - [groupName_ release]; - [objects_ release]; - [properties_ release]; - [super dealloc]; -} - --(NSMutableDictionary*) objectNamed:(NSString *)objectName -{ - for( id object in objects_ ) { - if( [[object valueForKey:@"name"] isEqual:objectName] ) - return object; - } - - // object not found - return nil; -} - --(id) propertyNamed:(NSString *)propertyName -{ - return [properties_ valueForKey:propertyName]; -} - -@end diff --git a/Example/libs/cocos2d/CCTMXTiledMap.h b/Example/libs/cocos2d/CCTMXTiledMap.h deleted file mode 100644 index 084187c..0000000 --- a/Example/libs/cocos2d/CCTMXTiledMap.h +++ /dev/null @@ -1,145 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * TMX Tiled Map support: - * http://www.mapeditor.org - * - */ - -#import "CCNode.h" - -@class CCTMXLayer; -@class CCTMXObjectGroup; - -/** Possible oritentations of the TMX map */ -enum -{ - /** Orthogonal orientation */ - CCTMXOrientationOrtho, - - /** Hexagonal orientation */ - CCTMXOrientationHex, - - /** Isometric orientation */ - CCTMXOrientationIso, -}; - -/** CCTMXTiledMap knows how to parse and render a TMX map. - - It adds support for the TMX tiled map format used by http://www.mapeditor.org - It supports isometric, hexagonal and orthogonal tiles. - It also supports object groups, objects, and properties. - - Features: - - Each tile will be treated as an CCSprite - - The sprites are created on demand. They will be created only when you call "[layer tileAt:]" - - Each tile can be rotated / moved / scaled / tinted / "opacitied", since each tile is a CCSprite - - Tiles can be added/removed in runtime - - The z-order of the tiles can be modified in runtime - - Each tile has an anchorPoint of (0,0) - - The anchorPoint of the TMXTileMap is (0,0) - - The TMX layers will be added as a child - - The TMX layers will be aliased by default - - The tileset image will be loaded using the CCTextureCache - - Each tile will have a unique tag - - Each tile will have a unique z value. top-left: z=1, bottom-right: z=max z - - Each object group will be treated as an NSMutableArray - - Object class which will contain all the properties in a dictionary - - Properties can be assigned to the Map, Layer, Object Group, and Object - - Limitations: - - It only supports one tileset per layer. - - Embeded images are not supported - - It only supports the XML format (the JSON format is not supported) - - Technical description: - Each layer is created using an CCTMXLayer (subclass of CCSpriteBatchNode). If you have 5 layers, then 5 CCTMXLayer will be created, - unless the layer visibility is off. In that case, the layer won't be created at all. - You can obtain the layers (CCTMXLayer objects) at runtime by: - - [map getChildByTag: tag_number]; // 0=1st layer, 1=2nd layer, 2=3rd layer, etc... - - [map layerNamed: name_of_the_layer]; - - Each object group is created using a CCTMXObjectGroup which is a subclass of NSMutableArray. - You can obtain the object groups at runtime by: - - [map objectGroupNamed: name_of_the_object_group]; - - Each object is a CCTMXObject. - - Each property is stored as a key-value pair in an NSMutableDictionary. - You can obtain the properties at runtime by: - - [map propertyNamed: name_of_the_property]; - [layer propertyNamed: name_of_the_property]; - [objectGroup propertyNamed: name_of_the_property]; - [object propertyNamed: name_of_the_property]; - - @since v0.8.1 - */ -@interface CCTMXTiledMap : CCNode -{ - CGSize mapSize_; - CGSize tileSize_; - int mapOrientation_; - NSMutableArray *objectGroups_; - NSMutableDictionary *properties_; - NSMutableDictionary *tileProperties_; -} - -/** the map's size property measured in tiles */ -@property (nonatomic,readonly) CGSize mapSize; -/** the tiles's size property measured in pixels */ -@property (nonatomic,readonly) CGSize tileSize; -/** map orientation */ -@property (nonatomic,readonly) int mapOrientation; -/** object groups */ -@property (nonatomic,readwrite,retain) NSMutableArray *objectGroups; -/** properties */ -@property (nonatomic,readwrite,retain) NSMutableDictionary *properties; - -/** creates a TMX Tiled Map with a TMX file.*/ -+(id) tiledMapWithTMXFile:(NSString*)tmxFile; - -/** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ -+(id) tiledMapWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath; - -/** initializes a TMX Tiled Map with a TMX file */ --(id) initWithTMXFile:(NSString*)tmxFile; - -/** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ --(id) initWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath; - -/** return the TMXLayer for the specific layer */ --(CCTMXLayer*) layerNamed:(NSString *)layerName; - -/** return the TMXObjectGroup for the secific group */ --(CCTMXObjectGroup*) objectGroupNamed:(NSString *)groupName; - -/** return the value for the specific property name */ --(id) propertyNamed:(NSString *)propertyName; - -/** return properties dictionary for tile GID */ --(NSDictionary*)propertiesForGID:(unsigned int)GID; -@end - diff --git a/Example/libs/cocos2d/CCTMXTiledMap.m b/Example/libs/cocos2d/CCTMXTiledMap.m deleted file mode 100644 index 0117b2e..0000000 --- a/Example/libs/cocos2d/CCTMXTiledMap.m +++ /dev/null @@ -1,217 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * TMX Tiled Map support: - * http://www.mapeditor.org - * - */ - -#import "CCTMXTiledMap.h" -#import "CCTMXXMLParser.h" -#import "CCTMXLayer.h" -#import "CCTMXObjectGroup.h" -#import "CCSprite.h" -#import "CCTextureCache.h" -#import "Support/CGPointExtension.h" - - -#pragma mark - -#pragma mark CCTMXTiledMap - -@interface CCTMXTiledMap (Private) --(id) parseLayer:(CCTMXLayerInfo*)layer map:(CCTMXMapInfo*)mapInfo; --(CCTMXTilesetInfo*) tilesetForLayer:(CCTMXLayerInfo*)layerInfo map:(CCTMXMapInfo*)mapInfo; --(void) buildWithMapInfo:(CCTMXMapInfo*)mapInfo; -@end - -@implementation CCTMXTiledMap -@synthesize mapSize = mapSize_; -@synthesize tileSize = tileSize_; -@synthesize mapOrientation = mapOrientation_; -@synthesize objectGroups = objectGroups_; -@synthesize properties = properties_; - -+(id) tiledMapWithTMXFile:(NSString*)tmxFile -{ - return [[[self alloc] initWithTMXFile:tmxFile] autorelease]; -} - -+(id) tiledMapWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath -{ - return [[[self alloc] initWithXML:tmxString resourcePath:resourcePath] autorelease]; -} - --(void) buildWithMapInfo:(CCTMXMapInfo*)mapInfo -{ - mapSize_ = mapInfo.mapSize; - tileSize_ = mapInfo.tileSize; - mapOrientation_ = mapInfo.orientation; - objectGroups_ = [mapInfo.objectGroups retain]; - properties_ = [mapInfo.properties retain]; - tileProperties_ = [mapInfo.tileProperties retain]; - - int idx=0; - - for( CCTMXLayerInfo *layerInfo in mapInfo.layers ) { - - if( layerInfo.visible ) { - CCNode *child = [self parseLayer:layerInfo map:mapInfo]; - [self addChild:child z:idx tag:idx]; - - // update content size with the max size - CGSize childSize = [child contentSize]; - CGSize currentSize = [self contentSize]; - currentSize.width = MAX( currentSize.width, childSize.width ); - currentSize.height = MAX( currentSize.height, childSize.height ); - [self setContentSize:currentSize]; - - idx++; - } - } -} - --(id) initWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath -{ - if ((self=[super init])) { - - [self setContentSize:CGSizeZero]; - - CCTMXMapInfo *mapInfo = [CCTMXMapInfo formatWithXML:tmxString resourcePath:resourcePath]; - - NSAssert( [mapInfo.tilesets count] != 0, @"TMXTiledMap: Map not found. Please check the filename."); - [self buildWithMapInfo:mapInfo]; - } - - return self; -} - --(id) initWithTMXFile:(NSString*)tmxFile -{ - NSAssert(tmxFile != nil, @"TMXTiledMap: tmx file should not bi nil"); - - if ((self=[super init])) { - - [self setContentSize:CGSizeZero]; - - CCTMXMapInfo *mapInfo = [CCTMXMapInfo formatWithTMXFile:tmxFile]; - - NSAssert( [mapInfo.tilesets count] != 0, @"TMXTiledMap: Map not found. Please check the filename."); - [self buildWithMapInfo:mapInfo]; - } - - return self; -} - --(void) dealloc -{ - [objectGroups_ release]; - [properties_ release]; - [tileProperties_ release]; - [super dealloc]; -} - -// private --(id) parseLayer:(CCTMXLayerInfo*)layerInfo map:(CCTMXMapInfo*)mapInfo -{ - CCTMXTilesetInfo *tileset = [self tilesetForLayer:layerInfo map:mapInfo]; - CCTMXLayer *layer = [CCTMXLayer layerWithTilesetInfo:tileset layerInfo:layerInfo mapInfo:mapInfo]; - - // tell the layerinfo to release the ownership of the tiles map. - layerInfo.ownTiles = NO; - - [layer setupTiles]; - - return layer; -} - --(CCTMXTilesetInfo*) tilesetForLayer:(CCTMXLayerInfo*)layerInfo map:(CCTMXMapInfo*)mapInfo -{ - CGSize size = layerInfo.layerSize; - - id iter = [mapInfo.tilesets reverseObjectEnumerator]; - for( CCTMXTilesetInfo* tileset in iter) { - for( unsigned int y = 0; y < size.height; y++ ) { - for( unsigned int x = 0; x < size.width; x++ ) { - - unsigned int pos = x + size.width * y; - unsigned int gid = layerInfo.tiles[ pos ]; - - // gid are stored in little endian. - // if host is big endian, then swap - gid = CFSwapInt32LittleToHost( gid ); - - // XXX: gid == 0 --> empty tile - if( gid != 0 ) { - - // Optimization: quick return - // if the layer is invalid (more than 1 tileset per layer) an assert will be thrown later - if( (gid & kCCFlippedMask) >= tileset.firstGid ) - return tileset; - } - } - } - } - - // If all the tiles are 0, return empty tileset - CCLOG(@"cocos2d: Warning: TMX Layer '%@' has no tiles", layerInfo.name); - return nil; -} - - -// public - --(CCTMXLayer*) layerNamed:(NSString *)layerName -{ - CCTMXLayer *layer; - CCARRAY_FOREACH(children_, layer) { - if([layer isKindOfClass:[CCTMXLayer class]]) - if([layer.layerName isEqual:layerName]) - return layer; - } - - // layer not found - return nil; -} - --(CCTMXObjectGroup*) objectGroupNamed:(NSString *)groupName -{ - for( CCTMXObjectGroup *objectGroup in objectGroups_ ) { - if( [objectGroup.groupName isEqual:groupName] ) - return objectGroup; - } - - // objectGroup not found - return nil; -} - --(id) propertyNamed:(NSString *)propertyName -{ - return [properties_ valueForKey:propertyName]; -} --(NSDictionary*)propertiesForGID:(unsigned int)GID{ - return [tileProperties_ objectForKey:[NSNumber numberWithInt:GID]]; -} -@end - diff --git a/Example/libs/cocos2d/CCTMXXMLParser.h b/Example/libs/cocos2d/CCTMXXMLParser.h deleted file mode 100644 index 91628c5..0000000 --- a/Example/libs/cocos2d/CCTMXXMLParser.h +++ /dev/null @@ -1,226 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * TMX Tiled Map support: - * http://www.mapeditor.org - * - */ - -/* - * Internal TMX parser - * - * IMPORTANT: These classed should not be documented using doxygen strings - * since the user should not use them. - * - */ - - -#import - -#import "ccMacros.h" - -enum { - TMXLayerAttribNone = 1 << 0, - TMXLayerAttribBase64 = 1 << 1, - TMXLayerAttribGzip = 1 << 2, - TMXLayerAttribZlib = 1 << 3, -}; - -enum { - TMXPropertyNone, - TMXPropertyMap, - TMXPropertyLayer, - TMXPropertyObjectGroup, - TMXPropertyObject, - TMXPropertyTile -}; - -typedef enum ccTMXTileFlags_ { - kCCTMXTileHorizontalFlag = 0x80000000, - kCCTMXTileVerticalFlag = 0x40000000, - kCCTMXTileDiagonalFlag = 0x20000000, - - kCCFlipedAll = (kCCTMXTileHorizontalFlag|kCCTMXTileVerticalFlag|kCCTMXTileDiagonalFlag), - kCCFlippedMask = ~(kCCFlipedAll), -} ccTMXTileFlags; - -// Bits on the far end of the 32-bit global tile ID (GID's) are used for tile flags - -/* CCTMXLayerInfo contains the information about the layers like: - - Layer name - - Layer size - - Layer opacity at creation time (it can be modified at runtime) - - Whether the layer is visible (if it is not visible, then the CCNode won't be created) - - This information is obtained from the TMX file. - */ -@interface CCTMXLayerInfo : NSObject -{ - NSString *name_; - CGSize layerSize_; - unsigned int *tiles_; - BOOL visible_; - unsigned char opacity_; - BOOL ownTiles_; - unsigned int minGID_; - unsigned int maxGID_; - NSMutableDictionary *properties_; - CGPoint offset_; -} - -@property (nonatomic,readwrite,retain) NSString *name; -@property (nonatomic,readwrite) CGSize layerSize; -@property (nonatomic,readwrite) unsigned int *tiles; -@property (nonatomic,readwrite) BOOL visible; -@property (nonatomic,readwrite) unsigned char opacity; -@property (nonatomic,readwrite) BOOL ownTiles; -@property (nonatomic,readwrite) unsigned int minGID; -@property (nonatomic,readwrite) unsigned int maxGID; -@property (nonatomic,readwrite,retain) NSMutableDictionary *properties; -@property (nonatomic,readwrite) CGPoint offset; -@end - -/* CCTMXTilesetInfo contains the information about the tilesets like: - - Tileset name - - Tilset spacing - - Tileset margin - - size of the tiles - - Image used for the tiles - - Image size - - This information is obtained from the TMX file. - */ -@interface CCTMXTilesetInfo : NSObject -{ - NSString *name_; - unsigned int firstGid_; - CGSize tileSize_; - unsigned int spacing_; - unsigned int margin_; - - // filename containing the tiles (should be spritesheet / texture atlas) - NSString *sourceImage_; - - // size in pixels of the image - CGSize imageSize_; -} -@property (nonatomic,readwrite,retain) NSString *name; -@property (nonatomic,readwrite,assign) unsigned int firstGid; -@property (nonatomic,readwrite,assign) CGSize tileSize; -@property (nonatomic,readwrite,assign) unsigned int spacing; -@property (nonatomic,readwrite,assign) unsigned int margin; -@property (nonatomic,readwrite,retain) NSString *sourceImage; -@property (nonatomic,readwrite,assign) CGSize imageSize; - --(CGRect) rectForGID:(unsigned int)gid; -@end - -/* CCTMXMapInfo contains the information about the map like: - - Map orientation (hexagonal, isometric or orthogonal) - - Tile size - - Map size - - And it also contains: - - Layers (an array of TMXLayerInfo objects) - - Tilesets (an array of TMXTilesetInfo objects) - - ObjectGroups (an array of TMXObjectGroupInfo objects) - - This information is obtained from the TMX file. - - */ -#ifdef __CC_PLATFORM_IOS -#if defined(__IPHONE_4_0) -@interface CCTMXMapInfo : NSObject -#else -@interface CCTMXMapInfo : NSObject -#endif - -#elif defined(__CC_PLATFORM_MAC) -@interface CCTMXMapInfo : NSObject -#endif -{ - NSMutableString *currentString; - BOOL storingCharacters; - int layerAttribs; - int parentElement; - unsigned int parentGID_; - - - // tmx filename - NSString *filename_; - - // tmx resource path - NSString *resources_; - - // map orientation - int orientation_; - - // map width & height - CGSize mapSize_; - - // tiles width & height - CGSize tileSize_; - - // Layers - NSMutableArray *layers_; - - // tilesets - NSMutableArray *tilesets_; - - // ObjectGroups - NSMutableArray *objectGroups_; - - // properties - NSMutableDictionary *properties_; - - // tile properties - NSMutableDictionary *tileProperties_; -} - -@property (nonatomic,readwrite,assign) int orientation; -@property (nonatomic,readwrite,assign) CGSize mapSize; -@property (nonatomic,readwrite,assign) CGSize tileSize; -@property (nonatomic,readwrite,retain) NSMutableArray *layers; -@property (nonatomic,readwrite,retain) NSMutableArray *tilesets; -@property (nonatomic,readwrite,retain) NSString *filename; -@property (nonatomic,readwrite,retain) NSString *resources; -@property (nonatomic,readwrite,retain) NSMutableArray *objectGroups; -@property (nonatomic,readwrite,retain) NSMutableDictionary *properties; -@property (nonatomic,readwrite,retain) NSMutableDictionary *tileProperties; - -/** creates a TMX Format with a tmx file */ -+(id) formatWithTMXFile:(NSString*)tmxFile; - -/** creates a TMX Format with an XML string and a TMX resource path */ -+(id) formatWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath; - -/** initializes a TMX format with a tmx file */ --(id) initWithTMXFile:(NSString*)tmxFile; - -/** initializes a TMX format with an XML string and a TMX resource path */ --(id) initWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath; - -@end - diff --git a/Example/libs/cocos2d/CCTMXXMLParser.m b/Example/libs/cocos2d/CCTMXXMLParser.m deleted file mode 100644 index daf3d1b..0000000 --- a/Example/libs/cocos2d/CCTMXXMLParser.m +++ /dev/null @@ -1,523 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * TMX Tiled Map support: - * http://www.mapeditor.org - * - */ - - -#import -#include - -#import "ccMacros.h" -#import "Support/CGPointExtension.h" -#import "CCTMXXMLParser.h" -#import "CCTMXTiledMap.h" -#import "CCTMXObjectGroup.h" -#import "Support/base64.h" -#import "Support/ZipUtils.h" -#import "Support/CCFileUtils.h" - -#pragma mark - -#pragma mark TMXLayerInfo - - -@implementation CCTMXLayerInfo - -@synthesize name = name_, layerSize = layerSize_, tiles = tiles_, visible = visible_, opacity = opacity_, ownTiles = ownTiles_, minGID = minGID_, maxGID = maxGID_, properties = properties_; -@synthesize offset = offset_; --(id) init -{ - if( (self=[super init])) { - ownTiles_ = YES; - minGID_ = 100000; - maxGID_ = 0; - self.name = nil; - tiles_ = NULL; - offset_ = CGPointZero; - self.properties = [NSMutableDictionary dictionaryWithCapacity:5]; - } - return self; -} -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@",self); - - [name_ release]; - [properties_ release]; - - if( ownTiles_ && tiles_ ) { - free( tiles_ ); - tiles_ = NULL; - } - [super dealloc]; -} - -@end - -#pragma mark - -#pragma mark TMXTilesetInfo -@implementation CCTMXTilesetInfo - -@synthesize name = name_, firstGid = firstGid_, tileSize = tileSize_, spacing = spacing_, margin = margin_, sourceImage = sourceImage_, imageSize = imageSize_; - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - [sourceImage_ release]; - [name_ release]; - [super dealloc]; -} - --(CGRect) rectForGID:(unsigned int)gid -{ - CGRect rect; - rect.size = tileSize_; - - gid &= kCCFlippedMask; - gid = gid - firstGid_; - - int max_x = (imageSize_.width - margin_*2 + spacing_) / (tileSize_.width + spacing_); - // int max_y = (imageSize.height - margin*2 + spacing) / (tileSize.height + spacing); - - rect.origin.x = (gid % max_x) * (tileSize_.width + spacing_) + margin_; - rect.origin.y = (gid / max_x) * (tileSize_.height + spacing_) + margin_; - - return rect; -} -@end - -#pragma mark - -#pragma mark CCTMXMapInfo - -@interface CCTMXMapInfo (Private) -/* initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ --(void) parseXMLFile:(NSString *)xmlFilename; -/* initalises parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ -- (void) parseXMLString:(NSString *)xmlString; -/* handles the work of parsing for parseXMLFile: and parseXMLString: */ -- (NSError*) parseXMLData:(NSData*)data; -@end - -@implementation CCTMXMapInfo - -@synthesize orientation = orientation_, mapSize = mapSize_, layers = layers_, tilesets = tilesets_, tileSize = tileSize_, filename = filename_, resources = resources_, objectGroups = objectGroups_, properties = properties_; -@synthesize tileProperties = tileProperties_; - -+(id) formatWithTMXFile:(NSString*)tmxFile -{ - return [[[self alloc] initWithTMXFile:tmxFile] autorelease]; -} - -+(id) formatWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath -{ - return [[[self alloc] initWithXML:tmxString resourcePath:resourcePath] autorelease]; -} - -- (void) internalInit:(NSString*)tmxFileName resourcePath:(NSString*)resourcePath -{ - self.tilesets = [NSMutableArray arrayWithCapacity:4]; - self.layers = [NSMutableArray arrayWithCapacity:4]; - self.filename = tmxFileName; - self.resources = resourcePath; - self.objectGroups = [NSMutableArray arrayWithCapacity:4]; - self.properties = [NSMutableDictionary dictionaryWithCapacity:5]; - self.tileProperties = [NSMutableDictionary dictionaryWithCapacity:5]; - - // tmp vars - currentString = [[NSMutableString alloc] initWithCapacity:1024]; - storingCharacters = NO; - layerAttribs = TMXLayerAttribNone; - parentElement = TMXPropertyNone; -} - --(id) initWithXML:(NSString *)tmxString resourcePath:(NSString*)resourcePath -{ - if( (self=[super init])) { - [self internalInit:nil resourcePath:resourcePath]; - [self parseXMLString:tmxString]; - } - return self; -} - --(id) initWithTMXFile:(NSString*)tmxFile -{ - if( (self=[super init])) { - [self internalInit:tmxFile resourcePath:nil]; - [self parseXMLFile:filename_]; - } - return self; -} - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - [tilesets_ release]; - [layers_ release]; - [filename_ release]; - [resources_ release]; - [currentString release]; - [objectGroups_ release]; - [properties_ release]; - [tileProperties_ release]; - [super dealloc]; -} - -- (NSError*) parseXMLData:(NSData*)data -{ - NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:data] autorelease]; - - // we'll do the parsing - [parser setDelegate:self]; - [parser setShouldProcessNamespaces:NO]; - [parser setShouldReportNamespacePrefixes:NO]; - [parser setShouldResolveExternalEntities:NO]; - [parser parse]; - - return [parser parserError]; -} - -- (void) parseXMLString:(NSString *)xmlString -{ - NSData* data = [xmlString dataUsingEncoding:NSUTF8StringEncoding]; - NSError* err = [self parseXMLData:data]; - (void)err; - NSAssert1( !err, @"Error parsing TMX data: %@.", [NSString stringWithCharacters:[data bytes] length:[data length]] ); -} - -- (void) parseXMLFile:(NSString *)xmlFilename -{ - NSURL *url = [NSURL fileURLWithPath:[CCFileUtils fullPathFromRelativePath:xmlFilename] ]; - NSData *data = [NSData dataWithContentsOfURL:url]; - NSError* err = [self parseXMLData:data]; - (void)err; - NSAssert3(!err, @"Error parsing TMX file: %@, %@ (%d).", xmlFilename, [err localizedDescription], [err code]); -} - -// the XML parser calls here with all the elements --(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict -{ - if([elementName isEqualToString:@"map"]) { - NSString *version = [attributeDict objectForKey:@"version"]; - if( ! [version isEqualToString:@"1.0"] ) - CCLOG(@"cocos2d: TMXFormat: Unsupported TMX version: %@", version); - NSString *orientationStr = [attributeDict objectForKey:@"orientation"]; - if( [orientationStr isEqualToString:@"orthogonal"]) - orientation_ = CCTMXOrientationOrtho; - else if ( [orientationStr isEqualToString:@"isometric"]) - orientation_ = CCTMXOrientationIso; - else if( [orientationStr isEqualToString:@"hexagonal"]) - orientation_ = CCTMXOrientationHex; - else - CCLOG(@"cocos2d: TMXFomat: Unsupported orientation: %@", orientation_); - - mapSize_.width = [[attributeDict objectForKey:@"width"] intValue]; - mapSize_.height = [[attributeDict objectForKey:@"height"] intValue]; - tileSize_.width = [[attributeDict objectForKey:@"tilewidth"] intValue]; - tileSize_.height = [[attributeDict objectForKey:@"tileheight"] intValue]; - - // The parent element is now "map" - parentElement = TMXPropertyMap; - } else if([elementName isEqualToString:@"tileset"]) { - - // If this is an external tileset then start parsing that - NSString *externalTilesetFilename = [attributeDict objectForKey:@"source"]; - if (externalTilesetFilename) { - // Tileset file will be relative to the map file. So we need to convert it to an absolute path - NSString *dir = [filename_ stringByDeletingLastPathComponent]; // Directory of map file - if (!dir) - dir = resources_; - externalTilesetFilename = [dir stringByAppendingPathComponent:externalTilesetFilename]; // Append path to tileset file - - [self parseXMLFile:externalTilesetFilename]; - } else { - - CCTMXTilesetInfo *tileset = [CCTMXTilesetInfo new]; - tileset.name = [attributeDict objectForKey:@"name"]; - tileset.firstGid = [[attributeDict objectForKey:@"firstgid"] intValue]; - tileset.spacing = [[attributeDict objectForKey:@"spacing"] intValue]; - tileset.margin = [[attributeDict objectForKey:@"margin"] intValue]; - CGSize s; - s.width = [[attributeDict objectForKey:@"tilewidth"] intValue]; - s.height = [[attributeDict objectForKey:@"tileheight"] intValue]; - tileset.tileSize = s; - - [tilesets_ addObject:tileset]; - [tileset release]; - } - - }else if([elementName isEqualToString:@"tile"]){ - CCTMXTilesetInfo* info = [tilesets_ lastObject]; - NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:3]; - parentGID_ = [info firstGid] + [[attributeDict objectForKey:@"id"] intValue]; - [tileProperties_ setObject:dict forKey:[NSNumber numberWithInt:parentGID_]]; - - parentElement = TMXPropertyTile; - - }else if([elementName isEqualToString:@"layer"]) { - CCTMXLayerInfo *layer = [CCTMXLayerInfo new]; - layer.name = [attributeDict objectForKey:@"name"]; - - CGSize s; - s.width = [[attributeDict objectForKey:@"width"] intValue]; - s.height = [[attributeDict objectForKey:@"height"] intValue]; - layer.layerSize = s; - - layer.visible = ![[attributeDict objectForKey:@"visible"] isEqualToString:@"0"]; - - if( [attributeDict objectForKey:@"opacity"] ) - layer.opacity = 255 * [[attributeDict objectForKey:@"opacity"] floatValue]; - else - layer.opacity = 255; - - int x = [[attributeDict objectForKey:@"x"] intValue]; - int y = [[attributeDict objectForKey:@"y"] intValue]; - layer.offset = ccp(x,y); - - [layers_ addObject:layer]; - [layer release]; - - // The parent element is now "layer" - parentElement = TMXPropertyLayer; - - } else if([elementName isEqualToString:@"objectgroup"]) { - - CCTMXObjectGroup *objectGroup = [[CCTMXObjectGroup alloc] init]; - objectGroup.groupName = [attributeDict objectForKey:@"name"]; - CGPoint positionOffset; - positionOffset.x = [[attributeDict objectForKey:@"x"] intValue] * tileSize_.width; - positionOffset.y = [[attributeDict objectForKey:@"y"] intValue] * tileSize_.height; - objectGroup.positionOffset = positionOffset; - - [objectGroups_ addObject:objectGroup]; - [objectGroup release]; - - // The parent element is now "objectgroup" - parentElement = TMXPropertyObjectGroup; - - } else if([elementName isEqualToString:@"image"]) { - - CCTMXTilesetInfo *tileset = [tilesets_ lastObject]; - - // build full path - NSString *imagename = [attributeDict objectForKey:@"source"]; - NSString *path = [filename_ stringByDeletingLastPathComponent]; - if (!path) - path = resources_; - tileset.sourceImage = [path stringByAppendingPathComponent:imagename]; - - } else if([elementName isEqualToString:@"data"]) { - NSString *encoding = [attributeDict objectForKey:@"encoding"]; - NSString *compression = [attributeDict objectForKey:@"compression"]; - - if( [encoding isEqualToString:@"base64"] ) { - layerAttribs |= TMXLayerAttribBase64; - storingCharacters = YES; - - if( [compression isEqualToString:@"gzip"] ) - layerAttribs |= TMXLayerAttribGzip; - - else if( [compression isEqualToString:@"zlib"] ) - layerAttribs |= TMXLayerAttribZlib; - - NSAssert( !compression || [compression isEqualToString:@"gzip"] || [compression isEqualToString:@"zlib"], @"TMX: unsupported compression method" ); - } - - NSAssert( layerAttribs != TMXLayerAttribNone, @"TMX tile map: Only base64 and/or gzip/zlib maps are supported" ); - - } else if([elementName isEqualToString:@"object"]) { - - CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; - - // The value for "type" was blank or not a valid class name - // Create an instance of TMXObjectInfo to store the object and its properties - NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:10]; - - // Parse everything automatically - NSArray *array = [NSArray arrayWithObjects:@"name", @"type", @"width", @"height", @"gid", nil]; - for( NSObject *key in array ) { - NSObject *obj = [attributeDict objectForKey:key]; - if( obj ) - [dict setObject:obj forKey:key]; - } - - // But X and Y since they need special treatment - // X - NSString *value = [attributeDict objectForKey:@"x"]; - if( value ) { - int x = [value intValue] + objectGroup.positionOffset.x; - [dict setObject:[NSNumber numberWithInt:x] forKey:@"x"]; - } - - // Y - value = [attributeDict objectForKey:@"y"]; - if( value ) { - int y = [value intValue] + objectGroup.positionOffset.y; - - // Correct y position. (Tiled uses Flipped, cocos2d uses Standard) - y = (mapSize_.height * tileSize_.height) - y - [[attributeDict objectForKey:@"height"] intValue]; - [dict setObject:[NSNumber numberWithInt:y] forKey:@"y"]; - } - - // Add the object to the objectGroup - [[objectGroup objects] addObject:dict]; - [dict release]; - - // The parent element is now "object" - parentElement = TMXPropertyObject; - - } else if([elementName isEqualToString:@"property"]) { - - if ( parentElement == TMXPropertyNone ) { - - CCLOG( @"TMX tile map: Parent element is unsupported. Cannot add property named '%@' with value '%@'", - [attributeDict objectForKey:@"name"], [attributeDict objectForKey:@"value"] ); - - } else if ( parentElement == TMXPropertyMap ) { - - // The parent element is the map - [properties_ setObject:[attributeDict objectForKey:@"value"] forKey:[attributeDict objectForKey:@"name"]]; - - } else if ( parentElement == TMXPropertyLayer ) { - - // The parent element is the last layer - CCTMXLayerInfo *layer = [layers_ lastObject]; - // Add the property to the layer - [[layer properties] setObject:[attributeDict objectForKey:@"value"] forKey:[attributeDict objectForKey:@"name"]]; - - } else if ( parentElement == TMXPropertyObjectGroup ) { - - // The parent element is the last object group - CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; - [[objectGroup properties] setObject:[attributeDict objectForKey:@"value"] forKey:[attributeDict objectForKey:@"name"]]; - - } else if ( parentElement == TMXPropertyObject ) { - - // The parent element is the last object - CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; - NSMutableDictionary *dict = [[objectGroup objects] lastObject]; - - NSString *propertyName = [attributeDict objectForKey:@"name"]; - NSString *propertyValue = [attributeDict objectForKey:@"value"]; - - [dict setObject:propertyValue forKey:propertyName]; - - } else if ( parentElement == TMXPropertyTile ) { - - NSMutableDictionary* dict = [tileProperties_ objectForKey:[NSNumber numberWithInt:parentGID_]]; - NSString *propertyName = [attributeDict objectForKey:@"name"]; - NSString *propertyValue = [attributeDict objectForKey:@"value"]; - [dict setObject:propertyValue forKey:propertyName]; - } - - } else if ([elementName isEqualToString:@"polygon"]) { - - // find parent object's dict and add polygon-points to it - CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; - NSMutableDictionary *dict = [[objectGroup objects] lastObject]; - [dict setObject:[attributeDict objectForKey:@"points"] forKey:@"polygonPoints"]; - - } else if ([elementName isEqualToString:@"polyline"]) { - - // find parent object's dict and add polyline-points to it - CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject]; - NSMutableDictionary *dict = [[objectGroup objects] lastObject]; - [dict setObject:[attributeDict objectForKey:@"points"] forKey:@"polylinePoints"]; - } -} - -- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName -{ - int len = 0; - - if([elementName isEqualToString:@"data"] && layerAttribs&TMXLayerAttribBase64) { - storingCharacters = NO; - - CCTMXLayerInfo *layer = [layers_ lastObject]; - - unsigned char *buffer; - len = base64Decode((unsigned char*)[currentString UTF8String], (unsigned int) [currentString length], &buffer); - if( ! buffer ) { - CCLOG(@"cocos2d: TiledMap: decode data error"); - return; - } - - if( layerAttribs & (TMXLayerAttribGzip | TMXLayerAttribZlib) ) { - unsigned char *deflated; - CGSize s = [layer layerSize]; - int sizeHint = s.width * s.height * sizeof(uint32_t); - - int inflatedLen = ccInflateMemoryWithHint(buffer, len, &deflated, sizeHint); - NSAssert( inflatedLen == sizeHint, @"CCTMXXMLParser: Hint failed!"); - - inflatedLen = (int)&inflatedLen; // XXX: to avoid warings in compiler - - free( buffer ); - - if( ! deflated ) { - CCLOG(@"cocos2d: TiledMap: inflate data error"); - return; - } - - layer.tiles = (unsigned int*) deflated; - } else - layer.tiles = (unsigned int*) buffer; - - [currentString setString:@""]; - - } else if ([elementName isEqualToString:@"map"]) { - // The map element has ended - parentElement = TMXPropertyNone; - - } else if ([elementName isEqualToString:@"layer"]) { - // The layer element has ended - parentElement = TMXPropertyNone; - - } else if ([elementName isEqualToString:@"objectgroup"]) { - // The objectgroup element has ended - parentElement = TMXPropertyNone; - - } else if ([elementName isEqualToString:@"object"]) { - // The object element has ended - parentElement = TMXPropertyNone; - } -} - -- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string -{ - if (storingCharacters) - [currentString appendString:string]; -} - - -// -// the level did not load, file not found, etc. -// --(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{ - CCLOG(@"cocos2d: Error on XML Parse: %@", [parseError localizedDescription] ); -} - -@end diff --git a/Example/libs/cocos2d/CCTexture2D.h b/Example/libs/cocos2d/CCTexture2D.h deleted file mode 100644 index e8101fd..0000000 --- a/Example/libs/cocos2d/CCTexture2D.h +++ /dev/null @@ -1,338 +0,0 @@ -/* - -===== IMPORTANT ===== - -This is sample code demonstrating API, technology or techniques in development. -Although this sample code has been reviewed for technical accuracy, it is not -final. Apple is supplying this information to help you plan for the adoption of -the technologies and programming interfaces described herein. This information -is subject to change, and software implemented based on this sample code should -be tested with final operating system software and final documentation. Newer -versions of this sample code may be provided with future seeds of the API or -technology. For information about updates to this and other developer -documentation, view the New & Updated sidebars in subsequent documentation -seeds. - -===================== - -File: Texture2D.h -Abstract: Creates OpenGL 2D textures from images or text. - -Version: 1.6 - -Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. -("Apple") in consideration of your agreement to the following terms, and your -use, installation, modification or redistribution of this Apple software -constitutes acceptance of these terms. If you do not agree with these terms, -please do not use, install, modify or redistribute this Apple software. - -In consideration of your agreement to abide by the following terms, and subject -to these terms, Apple grants you a personal, non-exclusive license, under -Apple's copyrights in this original Apple software (the "Apple Software"), to -use, reproduce, modify and redistribute the Apple Software, with or without -modifications, in source and/or binary forms; provided that if you redistribute -the Apple Software in its entirety and without modifications, you must retain -this notice and the following text and disclaimers in all such redistributions -of the Apple Software. -Neither the name, trademarks, service marks or logos of Apple Inc. may be used -to endorse or promote products derived from the Apple Software without specific -prior written permission from Apple. Except as expressly stated in this notice, -no other rights or licenses, express or implied, are granted by Apple herein, -including but not limited to any patent rights that may be infringed by your -derivative works or by other works in which the Apple Software may be -incorporated. - -The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN -COMBINATION WITH YOUR PRODUCTS. - -IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR -DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF -CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF -APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright (C) 2008 Apple Inc. All Rights Reserved. - -*/ - -#import // for NSObject - -#import "ccTypes.h" -#import "ccMacros.h" - -#import "Platforms/CCGL.h" // OpenGL stuff -#import "Platforms/CCNS.h" // Next-Step stuff - -//CONSTANTS: - -/** @typedef CCTexture2DPixelFormat - Possible texture pixel formats - */ -typedef enum { - kCCTexture2DPixelFormat_Automatic = 0, - //! 32-bit texture: RGBA8888 - kCCTexture2DPixelFormat_RGBA8888, - //! 16-bit texture without Alpha channel - kCCTexture2DPixelFormat_RGB565, - //! 24-bit texture without Alpha channel - kCCTexture2DPixelFormat_RGB888, - //! 8-bit textures used as masks - kCCTexture2DPixelFormat_A8, - //! 8-bit intensity texture - kCCTexture2DPixelFormat_I8, - //! 16-bit textures used as masks - kCCTexture2DPixelFormat_AI88, - //! 16-bit textures: RGBA4444 - kCCTexture2DPixelFormat_RGBA4444, - //! 16-bit textures: RGB5A1 - kCCTexture2DPixelFormat_RGB5A1, - //! 4-bit PVRTC-compressed texture: PVRTC4 - kCCTexture2DPixelFormat_PVRTC4, - //! 2-bit PVRTC-compressed texture: PVRTC2 - kCCTexture2DPixelFormat_PVRTC2, - - //! Default texture format: RGBA8888 - kCCTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_RGBA8888, - -} CCTexture2DPixelFormat; - - -@class CCGLProgram; - -/** CCTexture2D class. - * This class allows to easily create OpenGL 2D textures from images, text or raw data. - * The created CCTexture2D object will always have power-of-two dimensions. - * Depending on how you create the CCTexture2D object, the actual image area of the texture might be smaller than the texture dimensions i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0). - * Be aware that the content of the generated textures will be upside-down! - */ -@interface CCTexture2D : NSObject -{ - GLuint name_; - CGSize size_; - NSUInteger width_, - height_; - CCTexture2DPixelFormat format_; - GLfloat maxS_, - maxT_; - BOOL hasPremultipliedAlpha_; - -#ifdef __CC_PLATFORM_IOS - ccResolutionType resolutionType_; -#endif - - // needed for drawAtRect, drawInPoint - CCGLProgram *shaderProgram_; - -} -/** Intializes with a texture2d with data */ -- (id) initWithData:(const void*)data pixelFormat:(CCTexture2DPixelFormat)pixelFormat pixelsWide:(NSUInteger)width pixelsHigh:(NSUInteger)height contentSize:(CGSize)size; - -/** These functions are needed to create mutable textures */ -- (void) releaseData:(void*)data; -- (void*) keepData:(void*)data length:(NSUInteger)length; - -/** pixel format of the texture */ -@property(nonatomic,readonly) CCTexture2DPixelFormat pixelFormat; -/** width in pixels */ -@property(nonatomic,readonly) NSUInteger pixelsWide; -/** hight in pixels */ -@property(nonatomic,readonly) NSUInteger pixelsHigh; - -/** texture name */ -@property(nonatomic,readonly) GLuint name; - -/** returns content size of the texture in pixels */ -@property(nonatomic,readonly, nonatomic) CGSize contentSizeInPixels; - -/** texture max S */ -@property(nonatomic,readwrite) GLfloat maxS; -/** texture max T */ -@property(nonatomic,readwrite) GLfloat maxT; -/** whether or not the texture has their Alpha premultiplied */ -@property(nonatomic,readonly) BOOL hasPremultipliedAlpha; - -/** shader program used by drawAtPoint and drawInRect */ -@property(nonatomic,readwrite,retain) CCGLProgram *shaderProgram; - -#ifdef __CC_PLATFORM_IOS -/** Returns the resolution type of the texture. - Is it a RetinaDisplay texture, an iPad texture or an standard texture ? - Only valid on iOS. Not valid on OS X. - - Should be a readonly property. It is readwrite as a hack. - - @since v1.1 - */ -@property (nonatomic, readwrite) ccResolutionType resolutionType; -#endif - -/** returns the content size of the texture in points */ --(CGSize) contentSize; - - -@end - -/** -Drawing extensions to make it easy to draw basic quads using a CCTexture2D object. -These functions require GL_TEXTURE_2D and both GL_VERTEX_ARRAY and GL_TEXTURE_COORD_ARRAY client states to be enabled. -*/ -@interface CCTexture2D (Drawing) -/** draws a texture at a given point */ -- (void) drawAtPoint:(CGPoint)point; -/** draws a texture inside a rect */ -- (void) drawInRect:(CGRect)rect; -@end - -/** -Extensions to make it easy to create a CCTexture2D object from an image file. -Note that RGBA type textures will have their alpha premultiplied - use the blending mode (GL_ONE, GL_ONE_MINUS_SRC_ALPHA). -*/ -@interface CCTexture2D (Image) -/** Initializes a texture from a CGImage object */ -#ifdef __CC_PLATFORM_IOS -- (id) initWithCGImage:(CGImageRef)cgImage resolutionType:(ccResolutionType)resolution; -#elif defined(__CC_PLATFORM_MAC) -- (id) initWithCGImage:(CGImageRef)cgImage; -#endif -@end - -/** -Extensions to make it easy to create a CCTexture2D object from a string of text. -Note that the generated textures are of type A8 - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). -*/ -@interface CCTexture2D (Text) -/** Initializes a texture from a string with dimensions, alignment, line break mode, font name and font size - Supported lineBreakModes: - - iOS: all UILineBreakMode supported modes - - Mac: Only NSLineBreakByWordWrapping is supported. - @since v1.0 - */ -- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode fontName:(NSString*)name fontSize:(CGFloat)size; -/** Initializes a texture from a string with dimensions, alignment, font name and font size */ -- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size; -/** Initializes a texture from a string with font name and font size */ -- (id) initWithString:(NSString*)string fontName:(NSString*)name fontSize:(CGFloat)size; -@end - - -/** - Extensions to make it easy to create a CCTexture2D object from a PVRTC file - Note that the generated textures don't have their alpha premultiplied - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). - */ -@interface CCTexture2D (PVRSupport) -/** Initializes a texture from a PVR file. - - Supported PVR formats: - - BGRA 8888 - - RGBA 8888 - - RGBA 4444 - - RGBA 5551 - - RBG 565 - - A 8 - - I 8 - - AI 8 - - PVRTC 2BPP - - PVRTC 4BPP - - By default PVR images are treated as if they alpha channel is NOT premultiplied. You can override this behavior with this class method: - - PVRImagesHavePremultipliedAlpha:(BOOL)haveAlphaPremultiplied; - - IMPORTANT: This method is only defined on iOS. It is not supported on the Mac version. - - */ --(id) initWithPVRFile: (NSString*) file; - -/** treats (or not) PVR files as if they have alpha premultiplied. - Since it is impossible to know at runtime if the PVR images have the alpha channel premultiplied, it is - possible load them as if they have (or not) the alpha channel premultiplied. - - By default it is disabled. - - @since v0.99.5 - */ -+(void) PVRImagesHavePremultipliedAlpha:(BOOL)haveAlphaPremultiplied; -@end - -/** - Extension to set the Min / Mag filter - */ -typedef struct _ccTexParams { - GLuint minFilter; - GLuint magFilter; - GLuint wrapS; - GLuint wrapT; -} ccTexParams; - -@interface CCTexture2D (GLFilter) -/** sets the min filter, mag filter, wrap s and wrap t texture parameters. - If the texture size is NPOT (non power of 2), then in can only use GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}. - @since v0.8 - */ --(void) setTexParameters: (ccTexParams*) texParams; - -/** sets antialias texture parameters: - - GL_TEXTURE_MIN_FILTER = GL_LINEAR - - GL_TEXTURE_MAG_FILTER = GL_LINEAR - - @since v0.8 - */ -- (void) setAntiAliasTexParameters; - -/** sets alias texture parameters: - - GL_TEXTURE_MIN_FILTER = GL_NEAREST - - GL_TEXTURE_MAG_FILTER = GL_NEAREST - - @since v0.8 - */ -- (void) setAliasTexParameters; - - -/** Generates mipmap images for the texture. - It only works if the texture size is POT (power of 2). - @since v0.99.0 - */ --(void) generateMipmap; - - -@end - -@interface CCTexture2D (PixelFormat) -/** sets the default pixel format for CGImages that contains alpha channel. - If the CGImage contains alpha channel, then the options are: - - generate 32-bit textures: kCCTexture2DPixelFormat_RGBA8888 (default one) - - generate 16-bit textures: kCCTexture2DPixelFormat_RGBA4444 - - generate 16-bit textures: kCCTexture2DPixelFormat_RGB5A1 - - generate 24-bit textures: kCCTexture2DPixelFormat_RGB888 (no alpha) - - generate 16-bit textures: kCCTexture2DPixelFormat_RGB565 (no alpha) - - generate 8-bit textures: kCCTexture2DPixelFormat_A8 (only use it if you use just 1 color) - - How does it work ? - - If the image is an RGBA (with Alpha) then the default pixel format will be used (it can be a 8-bit, 16-bit or 32-bit texture) - - If the image is an RGB (without Alpha) then RGB888 (24-bit) or RGB565 texture will be used (16-bit texture) depending on the bpp of the orignal image - - This parameter is not valid for PVR images. - - @since v0.8 - */ -+(void) setDefaultAlphaPixelFormat:(CCTexture2DPixelFormat)format; - -/** returns the alpha pixel format - @since v0.8 - */ -+(CCTexture2DPixelFormat) defaultAlphaPixelFormat; - -/** returns the bits-per-pixel of the in-memory OpenGL texture - @since v1.0 - */ --(NSUInteger) bitsPerPixelForFormat; -@end - - - - - diff --git a/Example/libs/cocos2d/CCTexture2D.m b/Example/libs/cocos2d/CCTexture2D.m deleted file mode 100644 index 8b63f1d..0000000 --- a/Example/libs/cocos2d/CCTexture2D.m +++ /dev/null @@ -1,827 +0,0 @@ -/* - - ===== IMPORTANT ===== - - This is sample code demonstrating API, technology or techniques in development. - Although this sample code has been reviewed for technical accuracy, it is not - final. Apple is supplying this information to help you plan for the adoption of - the technologies and programming interfaces described herein. This information - is subject to change, and software implemented based on this sample code should - be tested with final operating system software and final documentation. Newer - versions of this sample code may be provided with future seeds of the API or - technology. For information about updates to this and other developer - documentation, view the New & Updated sidebars in subsequent documentationd - seeds. - - ===================== - - File: Texture2D.m - Abstract: Creates OpenGL 2D textures from images or text. - - Version: 1.6 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. - ("Apple") in consideration of your agreement to the following terms, and your - use, installation, modification or redistribution of this Apple software - constitutes acceptance of these terms. If you do not agree with these terms, - please do not use, install, modify or redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and subject - to these terms, Apple grants you a personal, non-exclusive license, under - Apple's copyrights in this original Apple software (the "Apple Software"), to - use, reproduce, modify and redistribute the Apple Software, with or without - modifications, in source and/or binary forms; provided that if you redistribute - the Apple Software in its entirety and without modifications, you must retain - this notice and the following text and disclaimers in all such redistributions - of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may be used - to endorse or promote products derived from the Apple Software without specific - prior written permission from Apple. Except as expressly stated in this notice, - no other rights or licenses, express or implied, are granted by Apple herein, - including but not limited to any patent rights that may be infringed by your - derivative works or by other works in which the Apple Software may be - incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO - WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED - WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN - COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR - DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF - CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF - APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2008 Apple Inc. All Rights Reserved. - - */ - -/* - * Support for RGBA_4_4_4_4 and RGBA_5_5_5_1 was copied from: - * https://devforums.apple.com/message/37855#37855 by a1studmuffin - */ - -/* - * Added many additions for cocos2d - */ - -#import "Platforms/CCGL.h" -#import "Platforms/CCNS.h" - -#import "CCTexture2D.h" -#import "ccConfig.h" -#import "ccMacros.h" -#import "CCConfiguration.h" -#import "CCTexturePVR.h" -#import "CCGLProgram.h" -#import "ccGLStateCache.h" -#import "CCShaderCache.h" -#import "CCDirector.h" - -#import "Support/ccUtils.h" -#import "Support/CCFileUtils.h" - - -#if CC_USE_LA88_LABELS -#define LABEL_PIXEL_FORMAT kCCTexture2DPixelFormat_AI88 -#else -#define LABEL_PIXEL_FORMAT kCCTexture2DPixelFormat_A8 -#endif - -//CLASS IMPLEMENTATIONS: - - -// If the image has alpha, you can create RGBA8 (32-bit) or RGBA4 (16-bit) or RGB5A1 (16-bit) -// Default is: RGBA8888 (32-bit textures) -static CCTexture2DPixelFormat defaultAlphaPixelFormat_ = kCCTexture2DPixelFormat_Default; - -#pragma mark - -#pragma mark CCTexture2D - Main - -@implementation CCTexture2D - -@synthesize contentSizeInPixels = size_, pixelFormat = format_, pixelsWide = width_, pixelsHigh = height_, name = name_, maxS = maxS_, maxT = maxT_; -@synthesize hasPremultipliedAlpha = hasPremultipliedAlpha_; -@synthesize shaderProgram = shaderProgram_; - -#ifdef __CC_PLATFORM_IOS -@synthesize resolutionType = resolutionType_; -#endif - - -- (id) initWithData:(const void*)data pixelFormat:(CCTexture2DPixelFormat)pixelFormat pixelsWide:(NSUInteger)width pixelsHigh:(NSUInteger)height contentSize:(CGSize)size -{ - if((self = [super init])) { - glPixelStorei(GL_UNPACK_ALIGNMENT,1); - glGenTextures(1, &name_); - ccGLBindTexture2D( name_ ); - - [self setAntiAliasTexParameters]; - - // Specify OpenGL texture image - - switch(pixelFormat) - { - case kCCTexture2DPixelFormat_RGBA8888: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) width, (GLsizei) height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - break; - case kCCTexture2DPixelFormat_RGBA4444: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) width, (GLsizei) height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data); - break; - case kCCTexture2DPixelFormat_RGB5A1: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) width, (GLsizei) height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, data); - break; - case kCCTexture2DPixelFormat_RGB565: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, (GLsizei) width, (GLsizei) height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data); - break; - case kCCTexture2DPixelFormat_RGB888: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, (GLsizei) width, (GLsizei) height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); - break; - case kCCTexture2DPixelFormat_AI88: - glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, (GLsizei) width, (GLsizei) height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, data); - break; - case kCCTexture2DPixelFormat_A8: - glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, (GLsizei) width, (GLsizei) height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data); - break; - default: - [NSException raise:NSInternalInconsistencyException format:@""]; - - } - - size_ = size; - width_ = width; - height_ = height; - format_ = pixelFormat; - maxS_ = size.width / (float)width; - maxT_ = size.height / (float)height; - - hasPremultipliedAlpha_ = NO; - -#ifdef __CC_PLATFORM_IOS - resolutionType_ = kCCResolutionUnknown; -#endif - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTexture]; - } - return self; -} - -- (void) releaseData:(void*)data -{ - //Free data - free(data); -} - -- (void*) keepData:(void*)data length:(NSUInteger)length -{ - //The texture data mustn't be saved becuase it isn't a mutable texture. - return data; -} - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - [shaderProgram_ release]; - - if( name_ ) - ccGLDeleteTexture( name_ ); - - [super dealloc]; -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | Name = %i | Dimensions = %ix%i | Coordinates = (%.2f, %.2f)>", [self class], self, name_, width_, height_, maxS_, maxT_]; -} - --(CGSize) contentSize -{ - CGSize ret; - ret.width = size_.width / CC_CONTENT_SCALE_FACTOR(); - ret.height = size_.height / CC_CONTENT_SCALE_FACTOR(); - - return ret; -} - -@end - -#pragma mark - -#pragma mark CCTexture2D - Image - -@implementation CCTexture2D (Image) - -#ifdef __CC_PLATFORM_IOS -- (id) initWithCGImage:(CGImageRef)cgImage resolutionType:(ccResolutionType)resolution -#elif defined(__CC_PLATFORM_MAC) -- (id) initWithCGImage:(CGImageRef)cgImage -#endif -{ - NSUInteger POTWide, POTHigh; - CGContextRef context = nil; - void* data = nil; - CGColorSpaceRef colorSpace; - void* tempData; - unsigned int* inPixel32; - unsigned short* outPixel16; - BOOL hasAlpha; - CGImageAlphaInfo info; - CGSize imageSize; - CCTexture2DPixelFormat pixelFormat; - - if(cgImage == NULL) { - CCLOG(@"cocos2d: CCTexture2D. Can't create Texture. cgImage is nil"); - [self release]; - return nil; - } - - CCConfiguration *conf = [CCConfiguration sharedConfiguration]; - - if( [conf supportsNPOT] ) { - POTWide = CGImageGetWidth(cgImage); - POTHigh = CGImageGetHeight(cgImage); - - } - else - { - POTWide = ccNextPOT(CGImageGetWidth(cgImage)); - POTHigh = ccNextPOT(CGImageGetHeight(cgImage)); - } - - NSUInteger maxTextureSize = [conf maxTextureSize]; - if( POTHigh > maxTextureSize || POTWide > maxTextureSize ) { - CCLOG(@"cocos2d: WARNING: Image (%lu x %lu) is bigger than the supported %ld x %ld", - (long)POTWide, (long)POTHigh, - (long)maxTextureSize, (long)maxTextureSize); - [self release]; - return nil; - } - - info = CGImageGetAlphaInfo(cgImage); - hasAlpha = ((info == kCGImageAlphaPremultipliedLast) || (info == kCGImageAlphaPremultipliedFirst) || (info == kCGImageAlphaLast) || (info == kCGImageAlphaFirst) ? YES : NO); - - size_t bpp = CGImageGetBitsPerComponent(cgImage); - colorSpace = CGImageGetColorSpace(cgImage); - - if(colorSpace) { - if( hasAlpha ) { - pixelFormat = defaultAlphaPixelFormat_; - info = kCGImageAlphaPremultipliedLast; - } - else - { - info = kCGImageAlphaNoneSkipLast; - - if( bpp >= 8 ) - pixelFormat = kCCTexture2DPixelFormat_RGB888; - else - pixelFormat = kCCTexture2DPixelFormat_RGB565; - - CCLOG(@"cocos2d: CCTexture2D: Using %@ texture since image has no alpha", (bpp>=8) ? @"RGBA888" : @"RGB565" ); - - } - } else { - // NOTE: No colorspace means a mask image - CCLOG(@"cocos2d: CCTexture2D: Using A8 texture since image is a mask"); - pixelFormat = kCCTexture2DPixelFormat_A8; - } - - imageSize = CGSizeMake(CGImageGetWidth(cgImage), CGImageGetHeight(cgImage)); - - // Create the bitmap graphics context - - switch(pixelFormat) { - case kCCTexture2DPixelFormat_RGBA8888: - case kCCTexture2DPixelFormat_RGBA4444: - case kCCTexture2DPixelFormat_RGB5A1: - case kCCTexture2DPixelFormat_RGB565: - case kCCTexture2DPixelFormat_RGB888: - colorSpace = CGColorSpaceCreateDeviceRGB(); - data = malloc(POTHigh * POTWide * 4); -// info = hasAlpha ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNoneSkipLast; -// info = kCGImageAlphaPremultipliedLast; // issue #886. This patch breaks BMP images. - context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, info | kCGBitmapByteOrder32Big); - CGColorSpaceRelease(colorSpace); - break; - case kCCTexture2DPixelFormat_A8: - data = malloc(POTHigh * POTWide); - info = kCGImageAlphaOnly; - context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, NULL, info); - break; - default: - [NSException raise:NSInternalInconsistencyException format:@"Invalid pixel format"]; - } - - - CGContextClearRect(context, CGRectMake(0, 0, POTWide, POTHigh)); - CGContextTranslateCTM(context, 0, POTHigh - imageSize.height); - CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(cgImage), CGImageGetHeight(cgImage)), cgImage); - - // Repack the pixel data into the right format - - if(pixelFormat == kCCTexture2DPixelFormat_RGB565) { - //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB" - tempData = malloc(POTHigh * POTWide * 2); - inPixel32 = (unsigned int*)data; - outPixel16 = (unsigned short*)tempData; - for(unsigned int i = 0; i < POTWide * POTHigh; ++i, ++inPixel32) - *outPixel16++ = ((((*inPixel32 >> 0) & 0xFF) >> 3) << 11) | ((((*inPixel32 >> 8) & 0xFF) >> 2) << 5) | ((((*inPixel32 >> 16) & 0xFF) >> 3) << 0); - free(data); - data = tempData; - - } - - else if(pixelFormat == kCCTexture2DPixelFormat_RGB888) { - //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRRRRGGGGGGGGBBBBBBB" - tempData = malloc(POTHigh * POTWide * 3); - char *inData = (char*)data; - char *outData = (char*)tempData; - int j=0; - for(unsigned int i = 0; i < POTWide * POTHigh *4; i++) { - outData[j++] = inData[i++]; - outData[j++] = inData[i++]; - outData[j++] = inData[i++]; - } - free(data); - data = tempData; - - } - - else if (pixelFormat == kCCTexture2DPixelFormat_RGBA4444) { - //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA" - tempData = malloc(POTHigh * POTWide * 2); - inPixel32 = (unsigned int*)data; - outPixel16 = (unsigned short*)tempData; - for(unsigned int i = 0; i < POTWide * POTHigh; ++i, ++inPixel32) - *outPixel16++ = - ((((*inPixel32 >> 0) & 0xFF) >> 4) << 12) | // R - ((((*inPixel32 >> 8) & 0xFF) >> 4) << 8) | // G - ((((*inPixel32 >> 16) & 0xFF) >> 4) << 4) | // B - ((((*inPixel32 >> 24) & 0xFF) >> 4) << 0); // A - - - free(data); - data = tempData; - - } - else if (pixelFormat == kCCTexture2DPixelFormat_RGB5A1) { - //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA" - tempData = malloc(POTHigh * POTWide * 2); - inPixel32 = (unsigned int*)data; - outPixel16 = (unsigned short*)tempData; - for(unsigned int i = 0; i < POTWide * POTHigh; ++i, ++inPixel32) - *outPixel16++ = - ((((*inPixel32 >> 0) & 0xFF) >> 3) << 11) | // R - ((((*inPixel32 >> 8) & 0xFF) >> 3) << 6) | // G - ((((*inPixel32 >> 16) & 0xFF) >> 3) << 1) | // B - ((((*inPixel32 >> 24) & 0xFF) >> 7) << 0); // A - - - free(data); - data = tempData; - } - self = [self initWithData:data pixelFormat:pixelFormat pixelsWide:POTWide pixelsHigh:POTHigh contentSize:imageSize]; - - // should be after calling super init - hasPremultipliedAlpha_ = (info == kCGImageAlphaPremultipliedLast || info == kCGImageAlphaPremultipliedFirst); - - CGContextRelease(context); - [self releaseData:data]; - -#ifdef __CC_PLATFORM_IOS - resolutionType_ = resolution; -#endif - - return self; -} -@end - -#pragma mark - -#pragma mark CCTexture2D - Text - -@implementation CCTexture2D (Text) - -#ifdef __CC_PLATFORM_IOS - -- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment lineBreakMode:(CCLineBreakMode)lineBreakMode font:(id)uifont -{ - NSAssert( uifont, @"Invalid font"); - - NSUInteger POTWide = ccNextPOT(dimensions.width); - NSUInteger POTHigh = ccNextPOT(dimensions.height); - unsigned char* data; - - CGContextRef context; - CGColorSpaceRef colorSpace; - -#if CC_USE_LA88_LABELS - data = calloc(POTHigh, POTWide * 2); -#else - data = calloc(POTHigh, POTWide); -#endif - - colorSpace = CGColorSpaceCreateDeviceGray(); - context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, colorSpace, kCGImageAlphaNone); - CGColorSpaceRelease(colorSpace); - - if( ! context ) { - free(data); - [self release]; - return nil; - } - - CGContextSetGrayFillColor(context, 1.0f, 1.0f); - CGContextTranslateCTM(context, 0.0f, POTHigh); - CGContextScaleCTM(context, 1.0f, -1.0f); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential - - UIGraphicsPushContext(context); - - // normal fonts - if( [uifont isKindOfClass:[UIFont class] ] ) - [string drawInRect:CGRectMake(0, 0, dimensions.width, dimensions.height) withFont:uifont lineBreakMode:lineBreakMode alignment:alignment]; - - UIGraphicsPopContext(); - -#if CC_USE_LA88_LABELS - NSUInteger textureSize = POTWide*POTHigh; - unsigned short *la88_data = (unsigned short*)data; - for(int i = textureSize-1; i>=0; i--) //Convert A8 to AI88 - la88_data[i] = (data[i] << 8) | 0xff; - -#endif - - self = [self initWithData:data pixelFormat:LABEL_PIXEL_FORMAT pixelsWide:POTWide pixelsHigh:POTHigh contentSize:dimensions]; - - CGContextRelease(context); - [self releaseData:data]; - - return self; -} - - - -#elif defined(__CC_PLATFORM_MAC) - -- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment attributedString:(NSAttributedString*)stringWithAttributes -{ - NSAssert(stringWithAttributes, @"Invalid stringWithAttributes"); - - // get nearest power of two - NSSize POTSize = NSMakeSize(ccNextPOT(dimensions.width), ccNextPOT(dimensions.height)); - - // get string dimensions - NSSize realDimensions = [stringWithAttributes size]; - - // Mac crashes if the width or height is 0 - if (realDimensions.width > 0 && realDimensions.height > 0) - { - // Disable antialias - [[NSGraphicsContext currentContext] setShouldAntialias:NO]; - - NSImage *image = [[NSImage alloc] initWithSize:POTSize]; - [image lockFocus]; - - [stringWithAttributes drawInRect:NSMakeRect(0, POTSize.height - dimensions.height, dimensions.width, dimensions.height)]; //POTSize.width, POTSize.height)]; - - NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0.0f, 0.0f, POTSize.width, POTSize.height)]; - [image unlockFocus]; - - unsigned char *data = (unsigned char*) [bitmap bitmapData]; //Use the same buffer to improve the performance. - - NSUInteger textureSize = POTSize.width * POTSize.height; -#if CC_USE_LA88_LABELS - unsigned short *dst = (unsigned short*)data; - for(int i = 0; iwrapS == GL_CLAMP_TO_EDGE && texParams->wrapT == GL_CLAMP_TO_EDGE), - @"GL_CLAMP_TO_EDGE should be used in NPOT textures"); - - ccGLBindTexture2D( name_ ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texParams->minFilter ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texParams->magFilter ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texParams->wrapS ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams->wrapT ); -} - --(void) setAliasTexParameters -{ - ccTexParams texParams = { GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE }; - [self setTexParameters: &texParams]; -} - --(void) setAntiAliasTexParameters -{ - ccTexParams texParams = { GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE }; - [self setTexParameters: &texParams]; -} -@end - - -#pragma mark - -#pragma mark CCTexture2D - Pixel Format - -// -// Texture options for images that contains alpha -// -@implementation CCTexture2D (PixelFormat) -+(void) setDefaultAlphaPixelFormat:(CCTexture2DPixelFormat)format -{ - defaultAlphaPixelFormat_ = format; -} - -+(CCTexture2DPixelFormat) defaultAlphaPixelFormat -{ - return defaultAlphaPixelFormat_; -} - --(NSUInteger) bitsPerPixelForFormat -{ - NSUInteger ret=0; - - switch (format_) { - case kCCTexture2DPixelFormat_RGBA8888: - ret = 32; - break; - case kCCTexture2DPixelFormat_RGB565: - ret = 16; - break; - case kCCTexture2DPixelFormat_RGB888: - ret = 24; - break; - case kCCTexture2DPixelFormat_A8: - ret = 8; - break; - case kCCTexture2DPixelFormat_RGBA4444: - ret = 16; - break; - case kCCTexture2DPixelFormat_RGB5A1: - ret = 16; - break; - case kCCTexture2DPixelFormat_PVRTC4: - ret = 4; - break; - case kCCTexture2DPixelFormat_PVRTC2: - ret = 2; - break; - case kCCTexture2DPixelFormat_I8: - ret = 8; - break; - case kCCTexture2DPixelFormat_AI88: - ret = 16; - break; - default: - ret = -1; - NSAssert1(NO , @"bitsPerPixelForFormat: %ld, unrecognised pixel format", (long)format_); - CCLOG(@"bitsPerPixelForFormat: %ld, cannot give useful result", (long)format_); - break; - } - return ret; -} -@end - diff --git a/Example/libs/cocos2d/CCTextureAtlas.h b/Example/libs/cocos2d/CCTextureAtlas.h deleted file mode 100644 index 4a61485..0000000 --- a/Example/libs/cocos2d/CCTextureAtlas.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCTexture2D.h" -#import "ccTypes.h" -#import "ccConfig.h" - -/** A class that implements a Texture Atlas. - Supported features: - * The atlas file can be a PVRTC, PNG or any other fomrat supported by Texture2D - * Quads can be udpated in runtime - * Quads can be added in runtime - * Quads can be removed in runtime - * Quads can be re-ordered in runtime - * The TextureAtlas capacity can be increased or decreased in runtime - * OpenGL component: V3F, C4B, T2F. - The quads are rendered using an OpenGL ES VBO. - To render the quads using an interleaved vertex array list, you should modify the ccConfig.h file - */ -@interface CCTextureAtlas : NSObject -{ - NSUInteger totalQuads_; - NSUInteger capacity_; - ccV3F_C4B_T2F_Quad *quads_; // quads to be rendered - GLushort *indices_; - CCTexture2D *texture_; - - GLuint buffersVBO_[2]; //0: vertex 1: indices - BOOL dirty_; //indicates whether or not the array buffer of the VBO needs to be updated - -#if CC_TEXTURE_ATLAS_USE_VAO - GLuint VAOname_; -#endif -} - -/** quantity of quads that are going to be drawn */ -@property (nonatomic,readonly) NSUInteger totalQuads; -/** quantity of quads that can be stored with the current texture atlas size */ -@property (nonatomic,readonly) NSUInteger capacity; -/** Texture of the texture atlas */ -@property (nonatomic,retain) CCTexture2D *texture; -/** Quads that are going to be rendered */ -@property (nonatomic,readwrite) ccV3F_C4B_T2F_Quad *quads; - -/** creates a TextureAtlas with an filename and with an initial capacity for Quads. - * The TextureAtlas capacity can be increased in runtime. - */ -+(id) textureAtlasWithFile:(NSString*)file capacity:(NSUInteger)capacity; - -/** initializes a TextureAtlas with a filename and with a certain capacity for Quads. - * The TextureAtlas capacity can be increased in runtime. - * - * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) - */ --(id) initWithFile: (NSString*) file capacity:(NSUInteger)capacity; - -/** creates a TextureAtlas with a previously initialized Texture2D object, and - * with an initial capacity for n Quads. - * The TextureAtlas capacity can be increased in runtime. - */ -+(id) textureAtlasWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity; - -/** initializes a TextureAtlas with a previously initialized Texture2D object, and - * with an initial capacity for Quads. - * The TextureAtlas capacity can be increased in runtime. - * - * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) - */ --(id) initWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)capacity; - -/** updates a Quad (texture, vertex and color) at a certain index - * index must be between 0 and the atlas capacity - 1 - @since v0.8 - */ --(void) updateQuad:(ccV3F_C4B_T2F_Quad*)quad atIndex:(NSUInteger)index; - -/** Inserts a Quad (texture, vertex and color) at a certain index - index must be between 0 and the atlas capacity - 1 - @since v0.8 - */ --(void) insertQuad:(ccV3F_C4B_T2F_Quad*)quad atIndex:(NSUInteger)index; - -/** Inserts a c array of quads at a given index - index must be between 0 and the atlas capacity - 1 - this method doesn't enlarge the array when amount + index > totalQuads - @since v1.1 -*/ --(void) insertQuads:(ccV3F_C4B_T2F_Quad*)quads atIndex:(NSUInteger)index amount:(NSUInteger)amount; - -/** Removes the quad that is located at a certain index and inserts it at a new index - This operation is faster than removing and inserting in a quad in 2 different steps - @since v0.7.2 -*/ --(void) insertQuadFromIndex:(NSUInteger)fromIndex atIndex:(NSUInteger)newIndex; - -/** removes a quad at a given index number. - The capacity remains the same, but the total number of quads to be drawn is reduced in 1 - @since v0.7.2 - */ --(void) removeQuadAtIndex:(NSUInteger) index; - -/** removes a amount of quads starting from index - @since 1.1 - */ -- (void) removeQuadsAtIndex:(NSUInteger) index amount:(NSUInteger) amount; - -/** removes all Quads. - The TextureAtlas capacity remains untouched. No memory is freed. - The total number of quads to be drawn will be 0 - @since v0.7.2 - */ --(void) removeAllQuads; - -/** resize the capacity of the CCTextureAtlas. - * The new capacity can be lower or higher than the current one - * It returns YES if the resize was successful. - * If it fails to resize the capacity it will return NO with a new capacity of 0. - */ --(BOOL) resizeCapacity: (NSUInteger) n; - -/** - Used internally by CCParticleBatchNode - don't use this unless you know what you're doing - @since 1.1 -*/ -- (void) increaseTotalQuadsWith:(NSUInteger) amount; - -/** Moves an amount of quads from oldIndex at newIndex - @since v1.1 - */ --(void) moveQuadsFromIndex:(NSUInteger)oldIndex amount:(NSUInteger) amount atIndex:(NSUInteger)newIndex; - -/** - Moves quads from index till totalQuads to the newIndex - Used internally by CCParticleBatchNode - This method doesn't enlarge the array if newIndex + quads to be moved > capacity - @since 1.1 -*/ -- (void) moveQuadsFromIndex:(NSUInteger) index to:(NSUInteger) newIndex; - -/** - Ensures that after a realloc quads are still empty - Used internally by CCParticleBatchNode - @since 1.1 -*/ -- (void) fillWithEmptyQuadsFromIndex:(NSUInteger) index amount:(NSUInteger) amount; - -/** draws n quads - * n can't be greater than the capacity of the Atlas - */ - --(void) drawNumberOfQuads: (NSUInteger) n; - -/** draws n quads from an index (offset). - n + start can't be greater than the capacity of the atlas - - @since v1.0 - */ --(void) drawNumberOfQuads: (NSUInteger) n fromIndex: (NSUInteger) start; - -/** draws all the Atlas's Quads - */ --(void) drawQuads; - -@end diff --git a/Example/libs/cocos2d/CCTextureAtlas.m b/Example/libs/cocos2d/CCTextureAtlas.m deleted file mode 100644 index a2b2932..0000000 --- a/Example/libs/cocos2d/CCTextureAtlas.m +++ /dev/null @@ -1,545 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -// cocos2d -#import "CCTextureAtlas.h" -#import "ccMacros.h" -#import "CCTexture2D.h" -#import "CCTextureCache.h" -#import "CCGLProgram.h" -#import "ccGLStateCache.h" -#import "Support/OpenGL_Internal.h" - -@interface CCTextureAtlas () --(void) setupIndices; --(void) mapBuffers; - - - -#if CC_TEXTURE_ATLAS_USE_VAO --(void) setupVBOandVAO; -#else --(void) setupVBO; -#endif -@end - -//According to some tests GL_TRIANGLE_STRIP is slower, MUCH slower. Probably I'm doing something very wrong - -@implementation CCTextureAtlas - -@synthesize totalQuads = totalQuads_, capacity = capacity_; -@synthesize texture = texture_; -@synthesize quads = quads_; - -#pragma mark TextureAtlas - alloc & init - -+(id) textureAtlasWithFile:(NSString*) file capacity: (NSUInteger) n -{ - return [[[self alloc] initWithFile:file capacity:n] autorelease]; -} - -+(id) textureAtlasWithTexture:(CCTexture2D *)tex capacity:(NSUInteger)n -{ - return [[[self alloc] initWithTexture:tex capacity:n] autorelease]; -} - --(id) initWithFile:(NSString*)file capacity:(NSUInteger)n -{ - // retained in property - CCTexture2D *tex = [[CCTextureCache sharedTextureCache] addImage:file]; - if( tex ) - return [self initWithTexture:tex capacity:n]; - - // else - { - CCLOG(@"cocos2d: Could not open file: %@", file); - [self release]; - return nil; - } -} - --(id) initWithTexture:(CCTexture2D*)tex capacity:(NSUInteger)n -{ - if( (self=[super init]) ) { - - capacity_ = n; - totalQuads_ = 0; - - // retained in property - self.texture = tex; - - // Re-initialization is not allowed - NSAssert(quads_==nil && indices_==nil, @"CCTextureAtlas re-initialization is not allowed"); - - quads_ = calloc( sizeof(quads_[0]) * capacity_, 1 ); - indices_ = calloc( sizeof(indices_[0]) * capacity_ * 6, 1 ); - - if( ! ( quads_ && indices_) ) { - CCLOG(@"cocos2d: CCTextureAtlas: not enough memory"); - if( quads_ ) - free(quads_); - if( indices_ ) - free(indices_); - - [self release]; - return nil; - } - - [self setupIndices]; - -#if CC_TEXTURE_ATLAS_USE_VAO - [self setupVBOandVAO]; -#else - [self setupVBO]; -#endif - - dirty_ = YES; - } - - return self; -} - --(NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | totalQuads = %i>", [self class], self, totalQuads_]; -} - --(void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@",self); - - free(quads_); - free(indices_); - - glDeleteBuffers(2, buffersVBO_); - -#if CC_TEXTURE_ATLAS_USE_VAO - glDeleteVertexArrays(1, &VAOname_); -#endif - - [texture_ release]; - - [super dealloc]; -} - --(void) setupIndices -{ - for( NSUInteger i = 0; i < capacity_;i++) - { -#if CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP - indices_[i*6+0] = i*4+0; - indices_[i*6+1] = i*4+0; - indices_[i*6+2] = i*4+2; - indices_[i*6+3] = i*4+1; - indices_[i*6+4] = i*4+3; - indices_[i*6+5] = i*4+3; -#else - indices_[i*6+0] = i*4+0; - indices_[i*6+1] = i*4+1; - indices_[i*6+2] = i*4+2; - - // inverted index. issue #179 - indices_[i*6+3] = i*4+3; - indices_[i*6+4] = i*4+2; - indices_[i*6+5] = i*4+1; -#endif - } -} - -#pragma mark TextureAtlas - VAO / VBO specific - -#if CC_TEXTURE_ATLAS_USE_VAO --(void) setupVBOandVAO -{ - glGenVertexArrays(1, &VAOname_); - glBindVertexArray(VAOname_); - -#define kQuadSize sizeof(quads_[0].bl) - - glGenBuffers(2, &buffersVBO_[0]); - - glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * capacity_, quads_, GL_DYNAMIC_DRAW); - - // vertices - glEnableVertexAttribArray(kCCVertexAttrib_Position); - glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, vertices)); - - // colors - glEnableVertexAttribArray(kCCVertexAttrib_Color); - glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, colors)); - - // tex coords - glEnableVertexAttribArray(kCCVertexAttrib_TexCoords); - glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, texCoords)); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffersVBO_[1]); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices_[0]) * capacity_ * 6, indices_, GL_STATIC_DRAW); - - glBindVertexArray(0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - glBindBuffer(GL_ARRAY_BUFFER, 0); - - CHECK_GL_ERROR_DEBUG(); -} -#else // CC_TEXTURE_ATLAS_USE_VAO --(void) setupVBO -{ - glGenBuffers(2, &buffersVBO_[0]); - - [self mapBuffers]; -} -#endif // ! // CC_TEXTURE_ATLAS_USE_VAO - - --(void) mapBuffers -{ - glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * capacity_, quads_, GL_DYNAMIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffersVBO_[1]); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices_[0]) * capacity_ * 6, indices_, GL_STATIC_DRAW); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - CHECK_GL_ERROR_DEBUG(); -} - -#pragma mark TextureAtlas - Update, Insert, Move & Remove - --(ccV3F_C4B_T2F_Quad *) quads -{ - //if someone accesses the quads directly, presume that changes will be made - dirty_ = YES; - return quads_; -} - --(void) updateQuad:(ccV3F_C4B_T2F_Quad*)quad atIndex:(NSUInteger) n -{ - NSAssert(n < capacity_, @"updateQuadWithTexture: Invalid index"); - - totalQuads_ = MAX( n+1, totalQuads_); - - quads_[n] = *quad; - - dirty_ = YES; -} - --(void) insertQuad:(ccV3F_C4B_T2F_Quad*)quad atIndex:(NSUInteger)index -{ - NSAssert(index < capacity_, @"insertQuadWithTexture: Invalid index"); - - totalQuads_++; - NSAssert( totalQuads_ <= capacity_, @"invalid totalQuads"); - - // issue #575. index can be > totalQuads - NSInteger remaining = (totalQuads_-1) - index; - - // last object doesn't need to be moved - if( remaining > 0) - // tex coordinates - memmove( &quads_[index+1],&quads_[index], sizeof(quads_[0]) * remaining ); - - quads_[index] = *quad; - - dirty_ = YES; -} - --(void) insertQuads:(ccV3F_C4B_T2F_Quad*)quads atIndex:(NSUInteger)index amount:(NSUInteger) amount -{ - NSAssert(index + amount <= capacity_, @"insertQuadWithTexture: Invalid index + amount"); - - totalQuads_+= amount; - - NSAssert( totalQuads_ <= capacity_, @"invalid totalQuads"); - - // issue #575. index can be > totalQuads - NSInteger remaining = (totalQuads_-1) - index - amount; - - // last object doesn't need to be moved - if( remaining > 0) - // tex coordinates - memmove( &quads_[index+amount],&quads_[index], sizeof(quads_[0]) * remaining ); - - - - NSUInteger max = index + amount; - NSUInteger j = 0; - for (NSUInteger i = index; i < max ; i++) - { - quads_[index] = quads[j]; - index++; - j++; - } - - dirty_ = YES; -} - --(void) insertQuadFromIndex:(NSUInteger)oldIndex atIndex:(NSUInteger)newIndex -{ - NSAssert(newIndex < totalQuads_, @"insertQuadFromIndex:atIndex: Invalid index"); - NSAssert(oldIndex < totalQuads_, @"insertQuadFromIndex:atIndex: Invalid index"); - - if( oldIndex == newIndex ) - return; - - NSUInteger howMany = labs( oldIndex - newIndex); - NSUInteger dst = oldIndex; - NSUInteger src = oldIndex + 1; - if( oldIndex > newIndex) { - dst = newIndex+1; - src = newIndex; - } - - // tex coordinates - ccV3F_C4B_T2F_Quad quadsBackup = quads_[oldIndex]; - memmove( &quads_[dst],&quads_[src], sizeof(quads_[0]) * howMany ); - quads_[newIndex] = quadsBackup; - - dirty_ = YES; -} - --(void) moveQuadsFromIndex:(NSUInteger)oldIndex amount:(NSUInteger) amount atIndex:(NSUInteger)newIndex -{ - NSAssert(newIndex + amount <= totalQuads_, @"insertQuadFromIndex:atIndex: Invalid index"); - NSAssert(oldIndex < totalQuads_, @"insertQuadFromIndex:atIndex: Invalid index"); - - if( oldIndex == newIndex ) - return; - - //create buffer - size_t quadSize = sizeof(ccV3F_C4B_T2F_Quad); - ccV3F_C4B_T2F_Quad *tempQuads = malloc( quadSize * amount); - memcpy( tempQuads, &quads_[oldIndex], quadSize * amount ); - - if (newIndex < oldIndex) - { - // move quads from newIndex to newIndex + amount to make room for buffer - memmove( &quads_[newIndex], &quads_[newIndex+amount], (oldIndex-newIndex)*quadSize); - } - else - { - // move quads above back - memmove( &quads_[oldIndex], &quads_[oldIndex+amount], (newIndex-oldIndex)*quadSize); - } - memcpy( &quads_[newIndex], tempQuads, amount*quadSize); - - free(tempQuads); - - dirty_ = YES; -} - --(void) removeQuadAtIndex:(NSUInteger) index -{ - NSAssert(index < totalQuads_, @"removeQuadAtIndex: Invalid index"); - - NSUInteger remaining = (totalQuads_-1) - index; - - // last object doesn't need to be moved - if( remaining ) - memmove( &quads_[index],&quads_[index+1], sizeof(quads_[0]) * remaining ); - - totalQuads_--; - - dirty_ = YES; -} - --(void) removeQuadsAtIndex:(NSUInteger) index amount:(NSUInteger) amount -{ - NSAssert(index + amount <= totalQuads_, @"removeQuadAtIndex: index + amount out of bounds"); - - NSUInteger remaining = (totalQuads_) - (index + amount); - - totalQuads_ -= amount; - - if ( remaining ) - memmove( &quads_[index], &quads_[index+amount], sizeof(quads_[0]) * remaining ); - - dirty_ = YES; -} - --(void) removeAllQuads -{ - totalQuads_ = 0; -} - -#pragma mark TextureAtlas - Resize - --(BOOL) resizeCapacity: (NSUInteger) newCapacity -{ - if( newCapacity == capacity_ ) - return YES; - - // update capacity and totolQuads - totalQuads_ = MIN(totalQuads_,newCapacity); - capacity_ = newCapacity; - - void * tmpQuads = realloc( quads_, sizeof(quads_[0]) * capacity_ ); - void * tmpIndices = realloc( indices_, sizeof(indices_[0]) * capacity_ * 6 ); - - if( ! ( tmpQuads && tmpIndices) ) { - CCLOG(@"cocos2d: CCTextureAtlas: not enough memory"); - if( tmpQuads ) - free(tmpQuads); - else - free(quads_); - - if( tmpIndices ) - free(tmpIndices); - else - free(indices_); - - indices_ = nil; - quads_ = nil; - capacity_ = totalQuads_ = 0; - return NO; - } - - quads_ = tmpQuads; - indices_ = tmpIndices; - - // Update Indices - [self setupIndices]; - [self mapBuffers]; - - dirty_ = YES; - - return YES; -} - -#pragma mark TextureAtlas - CCParticleBatchNode Specific - --(void) fillWithEmptyQuadsFromIndex:(NSUInteger) index amount:(NSUInteger) amount -{ - ccV3F_C4B_T2F_Quad quad; - bzero( &quad, sizeof(quad) ); - - NSUInteger to = index + amount; - for (NSInteger i = index ; i < to ; i++) - { - quads_[i] = quad; - } - -} --(void) increaseTotalQuadsWith:(NSUInteger) amount -{ - totalQuads_ += amount; -} - --(void) moveQuadsFromIndex:(NSUInteger) index to:(NSUInteger) newIndex -{ - NSAssert(newIndex + (totalQuads_ - index) <= capacity_, @"moveQuadsFromIndex move is out of bounds"); - - memmove(quads_ + newIndex,quads_ + index, (totalQuads_ - index) * sizeof(quads_[0])); -} - -#pragma mark TextureAtlas - Drawing - --(void) drawQuads -{ - [self drawNumberOfQuads: totalQuads_ fromIndex:0]; -} - --(void) drawNumberOfQuads: (NSUInteger) n -{ - [self drawNumberOfQuads:n fromIndex:0]; -} - --(void) drawNumberOfQuads: (NSUInteger) n fromIndex: (NSUInteger) start -{ - ccGLBindTexture2D( [texture_ name] ); - -#if CC_TEXTURE_ATLAS_USE_VAO - - // - // Using VBO and VAO - // - - // XXX: update is done in draw... perhaps it should be done in a timer - if (dirty_) { - glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); - glBufferSubData(GL_ARRAY_BUFFER, sizeof(quads_[0])*start, sizeof(quads_[0]) * n , &quads_[start] ); - glBindBuffer(GL_ARRAY_BUFFER, 0); - - dirty_ = NO; - } - - glBindVertexArray( VAOname_ ); - -#if CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP - glDrawElements(GL_TRIANGLE_STRIP, (GLsizei) n*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(indices_[0])) ); -#else - glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(indices_[0])) ); -#endif // CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP - - glBindVertexArray(0); - - -#else // ! CC_TEXTURE_ATLAS_USE_VAO - - // - // Using VBO without VAO - // - -#define kQuadSize sizeof(quads_[0].bl) - glBindBuffer(GL_ARRAY_BUFFER, buffersVBO_[0]); - - // XXX: update is done in draw... perhaps it should be done in a timer - if (dirty_) { - glBufferSubData(GL_ARRAY_BUFFER, sizeof(quads_[0])*start, sizeof(quads_[0]) * n , &quads_[start] ); - dirty_ = NO; - } - - ccGLEnableVertexAttribs( kCCVertexAttribFlag_PosColorTex ); - - // vertices - glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, vertices)); - - // colors - glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, colors)); - - // tex coords - glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( ccV3F_C4B_T2F, texCoords)); - - glBindBuffer(GL_ARRAY_BUFFER, 0); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffersVBO_[1]); - -#if CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP - glDrawElements(GL_TRIANGLE_STRIP, (GLsizei) n*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(indices_[0])) ); -#else - glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(indices_[0])) ); -#endif // CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - -#endif // CC_TEXTURE_ATLAS_USE_VAO - - CC_INCREMENT_GL_DRAWS(1); - - CHECK_GL_ERROR_DEBUG(); -} -@end diff --git a/Example/libs/cocos2d/CCTextureCache.h b/Example/libs/cocos2d/CCTextureCache.h deleted file mode 100644 index 18d24f0..0000000 --- a/Example/libs/cocos2d/CCTextureCache.h +++ /dev/null @@ -1,146 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "ccMacros.h" - -#ifdef __CC_PLATFORM_IOS -#import -#endif - -#import - -@class CCTexture2D; - -/** Singleton that handles the loading of textures - * Once the texture is loaded, the next time it will return - * a reference of the previously loaded texture reducing GPU & CPU memory - */ -@interface CCTextureCache : NSObject -{ - NSMutableDictionary *textures_; - - dispatch_queue_t _loadingQueue; - dispatch_queue_t _dictQueue; -} - -/** Retruns ths shared instance of the cache */ -+ (CCTextureCache *) sharedTextureCache; - -/** purges the cache. It releases the retained instance. - @since v0.99.0 - */ -+(void)purgeSharedTextureCache; - - -/** Returns a Texture2D object given an file image - * If the file image was not previously loaded, it will create a new CCTexture2D - * object and it will return it. It will use the filename as a key. - * Otherwise it will return a reference of a previosly loaded image. - * Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr, .gif - */ --(CCTexture2D*) addImage: (NSString*) fileimage; - -/** Asynchronously, load a texture2d from a file. - * If the file image was previously loaded, it will use it. - * Otherwise it will load a texture in a new thread, and when the image is loaded, the callback will be called with the Texture2D as a parameter. - * The callback will be called in the cocos2d thread, so it is safe to create any cocos2d object from the callback. - * Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr, .gif - * @since v0.8 - */ --(void) addImageAsync:(NSString*) filename target:(id)target selector:(SEL)selector; - -/** Asynchronously, load a texture2d from a file. - * If the file image was previously loaded, it will use it. - * Otherwise it will load a texture in a new thread, and when the image is loaded, the block will be called. - * The callback will be called in the cocos2d thread, so it is safe to create any cocos2d object from the callback. - * Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr, .gif - * @since v2.0 - */ --(void) addImageAsync:(NSString*) filename withBlock:(void(^)(CCTexture2D *tex))block; - - -/** Returns a Texture2D object given an CGImageRef image - * If the image was not previously loaded, it will create a new CCTexture2D object and it will return it. - * Otherwise it will return a reference of a previously loaded image - * The "key" parameter will be used as the "key" for the cache. - * If "key" is nil, then a new texture will be created each time. - * @since v0.8 - */ --(CCTexture2D*) addCGImage: (CGImageRef) image forKey: (NSString *)key; - -/** Returns an already created texture. Returns nil if the texture doesn't exist. - @since v0.99.5 - */ --(CCTexture2D *) textureForKey:(NSString *)key; - -/** Purges the dictionary of loaded textures. - * Call this method if you receive the "Memory Warning" - * In the short term: it will free some resources preventing your app from being killed - * In the medium term: it will allocate more resources - * In the long term: it will be the same - */ --(void) removeAllTextures; - -/** Removes unused textures - * Textures that have a retain count of 1 will be deleted - * It is convinient to call this method after when starting a new Scene - * @since v0.8 - */ --(void) removeUnusedTextures; - -/** Deletes a texture from the cache given a texture - */ --(void) removeTexture: (CCTexture2D*) tex; - -/** Deletes a texture from the cache given a its key name - @since v0.99.4 - */ --(void) removeTextureForKey: (NSString*) textureKeyName; - -@end - - -@interface CCTextureCache (PVRSupport) - -/** Returns a Texture2D object given an PVR filename. - * If the file image was not previously loaded, it will create a new CCTexture2D - * object and it will return it. Otherwise it will return a reference of a previosly loaded image - * - */ --(CCTexture2D*) addPVRImage:(NSString*) filename; - -@end - - -@interface CCTextureCache (Debug) -/** Output to CCLOG the current contents of this CCTextureCache - * This will attempt to calculate the size of each texture, and the total texture memory in use - * - * @since v1.0 - */ --(void) dumpCachedTextureInfo; - -@end diff --git a/Example/libs/cocos2d/CCTextureCache.m b/Example/libs/cocos2d/CCTextureCache.m deleted file mode 100644 index ff1545c..0000000 --- a/Example/libs/cocos2d/CCTextureCache.m +++ /dev/null @@ -1,505 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "ccMacros.h" -#import "Platforms/CCGL.h" -#import "CCTextureCache.h" -#import "CCTexture2D.h" -#import "CCTexturePVR.h" -#import "CCConfiguration.h" -#import "CCDirector.h" -#import "ccConfig.h" -#import "ccTypes.h" - -#import "Support/CCFileUtils.h" -#import "Support/NSThread+performBlock.h" - - -#ifdef __CC_PLATFORM_MAC -#import "Platforms/Mac/CCDirectorMac.h" -#endif - -// needed for CCCallFuncO in Mac-display_link version -//#import "CCActionManager.h" -//#import "CCActionInstant.h" - -#ifdef __CC_PLATFORM_IOS -static EAGLContext *_auxGLcontext = nil; -#elif defined(__CC_PLATFORM_MAC) -static NSOpenGLContext *_auxGLcontext = nil; -#endif - -@implementation CCTextureCache - -#pragma mark TextureCache - Alloc, Init & Dealloc -static CCTextureCache *sharedTextureCache; - -+ (CCTextureCache *)sharedTextureCache -{ - if (!sharedTextureCache) - sharedTextureCache = [[self alloc] init]; - - return sharedTextureCache; -} - -+(id)alloc -{ - NSAssert(sharedTextureCache == nil, @"Attempted to allocate a second instance of a singleton."); - return [super alloc]; -} - -+(void)purgeSharedTextureCache -{ - [sharedTextureCache release]; - sharedTextureCache = nil; -} - --(id) init -{ - if( (self=[super init]) ) { - textures_ = [[NSMutableDictionary dictionaryWithCapacity: 10] retain]; - - // init "global" stuff - _loadingQueue = dispatch_queue_create("org.cocos2d.texturecacheloading", NULL); - _dictQueue = dispatch_queue_create("org.cocos2d.texturecachedict", NULL); - - CCGLView *view = (CCGLView*)[[CCDirector sharedDirector] view]; - NSAssert(view, @"Do not initialize the TextureCache before the Director"); - -#ifdef __CC_PLATFORM_IOS - _auxGLcontext = [[EAGLContext alloc] - initWithAPI:kEAGLRenderingAPIOpenGLES2 - sharegroup:[[view context] sharegroup]]; - -#elif defined(__CC_PLATFORM_MAC) - NSOpenGLPixelFormat *pf = [view pixelFormat]; - NSOpenGLContext *share = [view openGLContext]; - - _auxGLcontext = [[NSOpenGLContext alloc] initWithFormat:pf shareContext:share]; - -#endif // __CC_PLATFORM_MAC - - NSAssert( _auxGLcontext, @"TextureCache: Could not create EAGL context"); - - } - - return self; -} - -- (NSString*) description -{ - __block NSString *desc = nil; - dispatch_sync(_dictQueue, ^{ - desc = [NSString stringWithFormat:@"<%@ = %08X | num of textures = %i | keys: %@>", - [self class], - self, - [textures_ count], - [textures_ allKeys] - ]; - }); - return desc; -} - --(void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - dispatch_sync(_dictQueue, ^{ - [textures_ release]; - }); - [_auxGLcontext release]; - _auxGLcontext = nil; - sharedTextureCache = nil; - dispatch_release(_loadingQueue); - dispatch_release(_dictQueue); - - [super dealloc]; -} - -#pragma mark TextureCache - Add Images - --(void) addImageAsync: (NSString*)path target:(id)target selector:(SEL)selector -{ - NSAssert(path != nil, @"TextureCache: fileimage MUST not be nill"); - NSAssert(target != nil, @"TextureCache: target can't be nil"); - NSAssert(selector != NULL, @"TextureCache: selector can't be NULL"); - - // optimization - - __block CCTexture2D * tex; - -#ifdef __CC_PLATFORM_IOS - path = [CCFileUtils removeSuffixFromFile:path]; -#endif - - dispatch_sync(_dictQueue, ^{ - tex = [textures_ objectForKey:path]; - }); - - if(tex) { - [target performSelector:selector withObject:tex]; - return; - } - - // dispatch it serially - dispatch_async(_loadingQueue, ^{ - - CCTexture2D *texture; - -#ifdef __CC_PLATFORM_IOS - if( [EAGLContext setCurrentContext:_auxGLcontext] ) { - - // load / create the texture - texture = [self addImage:path]; - - glFlush(); - - // callback should be executed in cocos2d thread - [target performSelector:selector onThread:[[CCDirector sharedDirector] runningThread] withObject:texture waitUntilDone:NO]; - - [EAGLContext setCurrentContext:nil]; - } else { - CCLOG(@"cocos2d: ERROR: TetureCache: Could not set EAGLContext"); - } - -#elif defined(__CC_PLATFORM_MAC) - - [_auxGLcontext makeCurrentContext]; - - // load / create the texture - texture = [self addImage:path]; - - glFlush(); - - // callback should be executed in cocos2d thread - [target performSelector:selector onThread:[[CCDirector sharedDirector] runningThread] withObject:texture waitUntilDone:NO]; - - [NSOpenGLContext clearCurrentContext]; - -#endif // __CC_PLATFORM_MAC - - }); -} - --(void) addImageAsync:(NSString*)path withBlock:(void(^)(CCTexture2D *tex))block -{ - NSAssert(path != nil, @"TextureCache: fileimage MUST not be nil"); - - // optimization - - __block CCTexture2D * tex; - -#ifdef __CC_PLATFORM_IOS - path = [CCFileUtils removeSuffixFromFile:path]; -#endif - - dispatch_sync(_dictQueue, ^{ - tex = [textures_ objectForKey:path]; - }); - - if(tex) { - block(tex); - return; - } - - // dispatch it serially - dispatch_async( _loadingQueue, ^{ - - CCTexture2D *texture; - -#ifdef __CC_PLATFORM_IOS - if( [EAGLContext setCurrentContext:_auxGLcontext] ) { - - // load / create the texture - texture = [self addImage:path]; - - glFlush(); - - // callback should be executed in cocos2d thread - NSThread *thread = [[CCDirector sharedDirector] runningThread]; - [thread performBlock:block withObject:texture waitUntilDone:NO]; - - [EAGLContext setCurrentContext:nil]; - } else { - CCLOG(@"cocos2d: ERROR: TetureCache: Could not set EAGLContext"); - } - -#elif defined(__CC_PLATFORM_MAC) - - [_auxGLcontext makeCurrentContext]; - - // load / create the texture - texture = [self addImage:path]; - - glFlush(); - - // callback should be executed in cocos2d thread - NSThread *thread = [[CCDirector sharedDirector] runningThread]; - [thread performBlock:block withObject:texture waitUntilDone:NO]; - - [NSOpenGLContext clearCurrentContext]; - -#endif // __CC_PLATFORM_MAC - - }); -} - --(CCTexture2D*) addImage: (NSString*) path -{ - NSAssert(path != nil, @"TextureCache: fileimage MUST not be nill"); - - __block CCTexture2D * tex = nil; - - // remove possible -HD suffix to prevent caching the same image twice (issue #1040) -#ifdef __CC_PLATFORM_IOS - path = [CCFileUtils removeSuffixFromFile: path]; -#endif - - dispatch_sync(_dictQueue, ^{ - tex = [textures_ objectForKey: path]; - }); - - if( ! tex ) { - - NSString *lowerCase = [path lowercaseString]; - - // all images are handled by UIKit/AppKit except PVR extension that is handled by cocos2d's handler - - if ( [lowerCase hasSuffix:@".pvr"] || [lowerCase hasSuffix:@".pvr.gz"] || [lowerCase hasSuffix:@".pvr.ccz"] ) - tex = [self addPVRImage:path]; - -#ifdef __CC_PLATFORM_IOS - - else { - - ccResolutionType resolution; - NSString *fullpath = [CCFileUtils fullPathFromRelativePath:path resolutionType:&resolution]; - - UIImage *image = [[UIImage alloc] initWithContentsOfFile:fullpath]; - tex = [[CCTexture2D alloc] initWithCGImage:image.CGImage resolutionType:resolution]; - [image release]; - - if( tex ){ - dispatch_sync(_dictQueue, ^{ - [textures_ setObject: tex forKey:path]; - }); - }else{ - CCLOG(@"cocos2d: Couldn't add image:%@ in CCTextureCache", path); - } - - // autorelease prevents possible crash in multithreaded environments - [tex autorelease]; - } - - -#elif defined(__CC_PLATFORM_MAC) - else { - NSString *fullpath = [CCFileUtils fullPathFromRelativePath: path ]; - - NSData *data = [[NSData alloc] initWithContentsOfFile:fullpath]; - NSBitmapImageRep *image = [[NSBitmapImageRep alloc] initWithData:data]; - tex = [ [CCTexture2D alloc] initWithCGImage:[image CGImage]]; - - [data release]; - [image release]; - - if( tex ){ - dispatch_sync(_dictQueue, ^{ - [textures_ setObject: tex forKey:path]; - }); - }else{ - CCLOG(@"cocos2d: Couldn't add image:%@ in CCTextureCache", path); - } - - // autorelease prevents possible crash in multithreaded environments - [tex autorelease]; - } -#endif // __CC_PLATFORM_MAC - - } - - return tex; -} - - --(CCTexture2D*) addCGImage: (CGImageRef) imageref forKey: (NSString *)key -{ - NSAssert(imageref != nil, @"TextureCache: image MUST not be nill"); - - __block CCTexture2D * tex = nil; - - // If key is nil, then create a new texture each time - if( key ) { - dispatch_sync(_dictQueue, ^{ - tex = [textures_ objectForKey:key]; - }); - if(tex) - return tex; - } - -#ifdef __CC_PLATFORM_IOS - tex = [[CCTexture2D alloc] initWithCGImage:imageref resolutionType:kCCResolutionUnknown]; -#elif __CC_PLATFORM_MAC - tex = [[CCTexture2D alloc] initWithCGImage:imageref]; -#endif - - if(tex && key){ - dispatch_sync(_dictQueue, ^{ - [textures_ setObject: tex forKey:key]; - }); - }else{ - CCLOG(@"cocos2d: Couldn't add CGImage in CCTextureCache"); - } - - return [tex autorelease]; -} - -#pragma mark TextureCache - Remove - --(void) removeAllTextures -{ - dispatch_sync(_dictQueue, ^{ - [textures_ removeAllObjects]; - }); -} - --(void) removeUnusedTextures -{ - dispatch_sync(_dictQueue, ^{ - NSArray *keys = [textures_ allKeys]; - for( id key in keys ) { - id value = [textures_ objectForKey:key]; - if( [value retainCount] == 1 ) { - CCLOG(@"cocos2d: CCTextureCache: removing unused texture: %@", key); - [textures_ removeObjectForKey:key]; - } - } - }); -} - --(void) removeTexture: (CCTexture2D*) tex -{ - if( ! tex ) - return; - - dispatch_sync(_dictQueue, ^{ - NSArray *keys = [textures_ allKeysForObject:tex]; - - for( NSUInteger i = 0; i < [keys count]; i++ ) - [textures_ removeObjectForKey:[keys objectAtIndex:i]]; - }); -} - --(void) removeTextureForKey:(NSString*)name -{ - if( ! name ) - return; - - dispatch_sync(_dictQueue, ^{ - [textures_ removeObjectForKey:name]; - }); -} - -#pragma mark TextureCache - Get -- (CCTexture2D *)textureForKey:(NSString *)key -{ - __block CCTexture2D *tex = nil; - - dispatch_sync(_dictQueue, ^{ - tex = [textures_ objectForKey:key]; - }); - - return tex; -} - -@end - - -@implementation CCTextureCache (PVRSupport) - --(CCTexture2D*) addPVRImage:(NSString*)path -{ - NSAssert(path != nil, @"TextureCache: fileimage MUST not be nill"); - - __block CCTexture2D * tex; - - // remove possible -HD suffix to prevent caching the same image twice (issue #1040) -#ifdef __CC_PLATFORM_IOS - path = [CCFileUtils removeSuffixFromFile: path]; -#endif - - dispatch_sync(_dictQueue, ^{ - tex = [textures_ objectForKey:path]; - }); - - if(tex) { - return tex; - } - - tex = [[CCTexture2D alloc] initWithPVRFile: path]; - if( tex ){ - dispatch_sync(_dictQueue, ^{ - [textures_ setObject: tex forKey:path]; - }); - }else{ - CCLOG(@"cocos2d: Couldn't add PVRImage:%@ in CCTextureCache",path); - } - - return [tex autorelease]; -} - -@end - - -@implementation CCTextureCache (Debug) - --(void) dumpCachedTextureInfo -{ - __block NSUInteger count = 0; - __block NSUInteger totalBytes = 0; - - dispatch_sync(_dictQueue, ^{ - for (NSString* texKey in textures_) { - CCTexture2D* tex = [textures_ objectForKey:texKey]; - NSUInteger bpp = [tex bitsPerPixelForFormat]; - // Each texture takes up width * height * bytesPerPixel bytes. - NSUInteger bytes = tex.pixelsWide * tex.pixelsHigh * bpp / 8; - totalBytes += bytes; - count++; - NSLog( @"cocos2d: \"%@\"\trc=%lu\tid=%lu\t%lu x %lu\t@ %ld bpp =>\t%lu KB", - texKey, - (long)[tex retainCount], - (long)tex.name, - (long)tex.pixelsWide, - (long)tex.pixelsHigh, - (long)bpp, - (long)bytes / 1024 ); - } - }); - NSLog( @"cocos2d: CCTextureCache dumpDebugInfo:\t%ld textures,\tfor %lu KB (%.2f MB)", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f)); -} - -@end diff --git a/Example/libs/cocos2d/CCTexturePVR.h b/Example/libs/cocos2d/CCTexturePVR.h deleted file mode 100644 index 6093941..0000000 --- a/Example/libs/cocos2d/CCTexturePVR.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - -File: PVRTexture.h -Abstract: The PVRTexture class is responsible for loading .pvr files. - -Version: 1.0 - -Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. -("Apple") in consideration of your agreement to the following terms, and your -use, installation, modification or redistribution of this Apple software -constitutes acceptance of these terms. If you do not agree with these terms, -please do not use, install, modify or redistribute this Apple software. - -In consideration of your agreement to abide by the following terms, and subject -to these terms, Apple grants you a personal, non-exclusive license, under -Apple's copyrights in this original Apple software (the "Apple Software"), to -use, reproduce, modify and redistribute the Apple Software, with or without -modifications, in source and/or binary forms; provided that if you redistribute -the Apple Software in its entirety and without modifications, you must retain -this notice and the following text and disclaimers in all such redistributions -of the Apple Software. -Neither the name, trademarks, service marks or logos of Apple Inc. may be used -to endorse or promote products derived from the Apple Software without specific -prior written permission from Apple. Except as expressly stated in this notice, -no other rights or licenses, express or implied, are granted by Apple herein, -including but not limited to any patent rights that may be infringed by your -derivative works or by other works in which the Apple Software may be -incorporated. - -The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN -COMBINATION WITH YOUR PRODUCTS. - -IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR -DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF -CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF -APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright (C) 2008 Apple Inc. All Rights Reserved. - -*/ - -#import - -#import "Platforms/CCGL.h" -#import "CCTexture2D.h" - - -#pragma mark - -#pragma mark CCTexturePVR - -struct CCPVRMipmap { - unsigned char *address; - unsigned int len; -}; - -enum { - CC_PVRMIPMAP_MAX = 16, -}; - -/** CCTexturePVR - - Object that loads PVR images. - - Supported PVR formats: - - RGBA8888 - - BGRA8888 - - RGBA4444 - - RGBA5551 - - RGB565 - - A8 - - I8 - - AI88 - - PVRTC 4BPP - - PVRTC 2BPP - - Limitations: - Pre-generated mipmaps, such as PVR textures with mipmap levels embedded in file, - are only supported if all individual sprites are of _square_ size. - To use mipmaps with non-square textures, instead call CCTexture2D#generateMipmap on the sheet texture itself - (and to save space, save the PVR sprite sheet without mip maps included). - */ -@interface CCTexturePVR : NSObject -{ - struct CCPVRMipmap mipmaps_[CC_PVRMIPMAP_MAX]; // pointer to mipmap images - int numberOfMipmaps_; // number of mipmap used - - unsigned int tableFormatIndex_; - uint32_t width_, height_; - GLuint name_; - BOOL hasAlpha_; - - // cocos2d integration - BOOL retainName_; - CCTexture2DPixelFormat format_; -} - -/** initializes a CCTexturePVR with a path */ -- (id)initWithContentsOfFile:(NSString *)path; -/** initializes a CCTexturePVR with an URL */ -- (id)initWithContentsOfURL:(NSURL *)url; -/** creates and initializes a CCTexturePVR with a path */ -+ (id)pvrTextureWithContentsOfFile:(NSString *)path; -/** creates and initializes a CCTexturePVR with an URL */ -+ (id)pvrTextureWithContentsOfURL:(NSURL *)url; - -/** texture id name */ -@property (nonatomic,readonly) GLuint name; -/** texture width */ -@property (nonatomic,readonly) uint32_t width; -/** texture height */ -@property (nonatomic,readonly) uint32_t height; -/** whether or not the texture has alpha */ -@property (nonatomic,readonly) BOOL hasAlpha; - -// cocos2d integration -@property (nonatomic,readwrite) BOOL retainName; -@property (nonatomic,readonly) CCTexture2DPixelFormat format; - -@end - - diff --git a/Example/libs/cocos2d/CCTexturePVR.m b/Example/libs/cocos2d/CCTexturePVR.m deleted file mode 100644 index bf0ad07..0000000 --- a/Example/libs/cocos2d/CCTexturePVR.m +++ /dev/null @@ -1,429 +0,0 @@ -/* - -File: PVRTexture.m -Abstract: The PVRTexture class is responsible for loading .pvr files. - -Version: 1.0 - -Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. -("Apple") in consideration of your agreement to the following terms, and your -use, installation, modification or redistribution of this Apple software -constitutes acceptance of these terms. If you do not agree with these terms, -please do not use, install, modify or redistribute this Apple software. - -In consideration of your agreement to abide by the following terms, and subject -to these terms, Apple grants you a personal, non-exclusive license, under -Apple's copyrights in this original Apple software (the "Apple Software"), to -use, reproduce, modify and redistribute the Apple Software, with or without -modifications, in source and/or binary forms; provided that if you redistribute -the Apple Software in its entirety and without modifications, you must retain -this notice and the following text and disclaimers in all such redistributions -of the Apple Software. -Neither the name, trademarks, service marks or logos of Apple Inc. may be used -to endorse or promote products derived from the Apple Software without specific -prior written permission from Apple. Except as expressly stated in this notice, -no other rights or licenses, express or implied, are granted by Apple herein, -including but not limited to any patent rights that may be infringed by your -derivative works or by other works in which the Apple Software may be -incorporated. - -The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN -COMBINATION WITH YOUR PRODUCTS. - -IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR -DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF -CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF -APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright (C) 2008 Apple Inc. All Rights Reserved. - -*/ - -/* - * Extended PVR formats for cocos2d project ( http://www.cocos2d-iphone.org ) - * - RGBA8888 - * - BGRA8888 - * - RGBA4444 - * - RGBA5551 - * - RGB565 - * - A8 - * - I8 - * - AI88 - */ - -#import - -#import "CCTexturePVR.h" -#import "ccMacros.h" -#import "CCConfiguration.h" -#import "ccGLStateCache.h" -#import "Support/ccUtils.h" -#import "Support/CCFileUtils.h" -#import "Support/ZipUtils.h" -#import "Support/OpenGL_Internal.h" - -#pragma mark - -#pragma mark CCTexturePVR - -#define PVR_TEXTURE_FLAG_TYPE_MASK 0xff - -// Values taken from PVRTexture.h from http://www.imgtec.com -enum { - kPVRTextureFlagMipmap = (1<<8), // has mip map levels - kPVRTextureFlagTwiddle = (1<<9), // is twiddled - kPVRTextureFlagBumpmap = (1<<10), // has normals encoded for a bump map - kPVRTextureFlagTiling = (1<<11), // is bordered for tiled pvr - kPVRTextureFlagCubemap = (1<<12), // is a cubemap/skybox - kPVRTextureFlagFalseMipCol = (1<<13), // are there false coloured MIP levels - kPVRTextureFlagVolume = (1<<14), // is this a volume texture - kPVRTextureFlagAlpha = (1<<15), // v2.1 is there transparency info in the texture - kPVRTextureFlagVerticalFlip = (1<<16), // v2.1 is the texture vertically flipped -}; - - -static char gPVRTexIdentifier[4] = "PVR!"; - -enum -{ - kPVRTexturePixelTypeRGBA_4444= 0x10, - kPVRTexturePixelTypeRGBA_5551, - kPVRTexturePixelTypeRGBA_8888, - kPVRTexturePixelTypeRGB_565, - kPVRTexturePixelTypeRGB_555, // unsupported - kPVRTexturePixelTypeRGB_888, - kPVRTexturePixelTypeI_8, - kPVRTexturePixelTypeAI_88, - kPVRTexturePixelTypePVRTC_2, - kPVRTexturePixelTypePVRTC_4, - kPVRTexturePixelTypeBGRA_8888, - kPVRTexturePixelTypeA_8, -}; - -static const uint32_t tableFormats[][7] = { - - // - PVR texture format - // - OpenGL internal format - // - OpenGL format - // - OpenGL type - // - bpp - // - compressed - // - Cocos2d texture format constant - { kPVRTexturePixelTypeRGBA_4444, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 16, NO, kCCTexture2DPixelFormat_RGBA4444 }, - { kPVRTexturePixelTypeRGBA_5551, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 16, NO, kCCTexture2DPixelFormat_RGB5A1 }, - { kPVRTexturePixelTypeRGBA_8888, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, NO, kCCTexture2DPixelFormat_RGBA8888 }, - { kPVRTexturePixelTypeRGB_565, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 16, NO, kCCTexture2DPixelFormat_RGB565 }, - { kPVRTexturePixelTypeRGB_888, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, 24, NO, kCCTexture2DPixelFormat_RGB888 }, - { kPVRTexturePixelTypeA_8, GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, 8, NO, kCCTexture2DPixelFormat_A8 }, - { kPVRTexturePixelTypeI_8, GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 8, NO, kCCTexture2DPixelFormat_I8 }, - { kPVRTexturePixelTypeAI_88, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 16, NO, kCCTexture2DPixelFormat_AI88 }, -#ifdef __CC_PLATFORM_IOS - { kPVRTexturePixelTypePVRTC_2, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, -1, -1, 2, YES, kCCTexture2DPixelFormat_PVRTC2 }, - { kPVRTexturePixelTypePVRTC_4, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, -1, -1, 4, YES, kCCTexture2DPixelFormat_PVRTC4 }, -#endif // iphone only - { kPVRTexturePixelTypeBGRA_8888, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE, 32, NO, kCCTexture2DPixelFormat_RGBA8888 }, -}; -#define MAX_TABLE_ELEMENTS (sizeof(tableFormats) / sizeof(tableFormats[0])) - -enum { - kCCInternalPVRTextureFormat, - kCCInternalOpenGLInternalFormat, - kCCInternalOpenGLFormat, - kCCInternalOpenGLType, - kCCInternalBPP, - kCCInternalCompressedImage, - kCCInternalCCTexture2DPixelFormat, -}; - -typedef struct _PVRTexHeader -{ - uint32_t headerLength; - uint32_t height; - uint32_t width; - uint32_t numMipmaps; - uint32_t flags; - uint32_t dataLength; - uint32_t bpp; - uint32_t bitmaskRed; - uint32_t bitmaskGreen; - uint32_t bitmaskBlue; - uint32_t bitmaskAlpha; - uint32_t pvrTag; - uint32_t numSurfs; -} PVRTexHeader; - - -@implementation CCTexturePVR - -@synthesize name = name_; -@synthesize width = width_; -@synthesize height = height_; -@synthesize hasAlpha = hasAlpha_; - -// cocos2d integration -@synthesize retainName = retainName_; -@synthesize format = format_; - - -- (BOOL)unpackPVRData:(unsigned char*)data PVRLen:(NSUInteger)len -{ - BOOL success = FALSE; - PVRTexHeader *header = NULL; - uint32_t flags, pvrTag; - uint32_t dataLength = 0, dataOffset = 0, dataSize = 0; - uint32_t blockSize = 0, widthBlocks = 0, heightBlocks = 0; - uint32_t width = 0, height = 0, bpp = 4; - uint8_t *bytes = NULL; - uint32_t formatFlags; - - header = (PVRTexHeader *)data; - - pvrTag = CFSwapInt32LittleToHost(header->pvrTag); - - if ((uint32_t)gPVRTexIdentifier[0] != ((pvrTag >> 0) & 0xff) || - (uint32_t)gPVRTexIdentifier[1] != ((pvrTag >> 8) & 0xff) || - (uint32_t)gPVRTexIdentifier[2] != ((pvrTag >> 16) & 0xff) || - (uint32_t)gPVRTexIdentifier[3] != ((pvrTag >> 24) & 0xff)) - { - return FALSE; - } - - CCConfiguration *configuration = [CCConfiguration sharedConfiguration]; - - flags = CFSwapInt32LittleToHost(header->flags); - formatFlags = flags & PVR_TEXTURE_FLAG_TYPE_MASK; - BOOL flipped = flags & kPVRTextureFlagVerticalFlip; - if( flipped ) - CCLOG(@"cocos2d: WARNING: Image is flipped. Regenerate it using PVRTexTool"); - - if( ! [configuration supportsNPOT] && - ( header->width != ccNextPOT(header->width) || header->height != ccNextPOT(header->height ) ) ) { - CCLOG(@"cocos2d: ERROR: Loding an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height); - return FALSE; - } - - for( tableFormatIndex_=0; tableFormatIndex_ < (unsigned int)MAX_TABLE_ELEMENTS ; tableFormatIndex_++) { - if( tableFormats[tableFormatIndex_][kCCInternalPVRTextureFormat] == formatFlags ) { - - numberOfMipmaps_ = 0; - - width_ = width = CFSwapInt32LittleToHost(header->width); - height_ = height = CFSwapInt32LittleToHost(header->height); - - if (CFSwapInt32LittleToHost(header->bitmaskAlpha)) - hasAlpha_ = TRUE; - else - hasAlpha_ = FALSE; - - dataLength = CFSwapInt32LittleToHost(header->dataLength); - bytes = ((uint8_t *)data) + sizeof(PVRTexHeader); - format_ = tableFormats[tableFormatIndex_][kCCInternalCCTexture2DPixelFormat]; - bpp = tableFormats[tableFormatIndex_][kCCInternalBPP]; - - // Calculate the data size for each texture level and respect the minimum number of blocks - while (dataOffset < dataLength) - { - switch (formatFlags) { - case kPVRTexturePixelTypePVRTC_2: - blockSize = 8 * 4; // Pixel by pixel block size for 2bpp - widthBlocks = width / 8; - heightBlocks = height / 4; - break; - case kPVRTexturePixelTypePVRTC_4: - blockSize = 4 * 4; // Pixel by pixel block size for 4bpp - widthBlocks = width / 4; - heightBlocks = height / 4; - break; - case kPVRTexturePixelTypeBGRA_8888: - if( ! [[CCConfiguration sharedConfiguration] supportsBGRA8888] ) { - CCLOG(@"cocos2d: TexturePVR. BGRA8888 not supported on this device"); - return FALSE; - } - default: - blockSize = 1; - widthBlocks = width; - heightBlocks = height; - break; - } - - // Clamp to minimum number of blocks - if (widthBlocks < 2) - widthBlocks = 2; - if (heightBlocks < 2) - heightBlocks = 2; - - dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8); - float packetLength = (dataLength-dataOffset); - packetLength = packetLength > dataSize ? dataSize : packetLength; - - mipmaps_[numberOfMipmaps_].address = bytes+dataOffset; - mipmaps_[numberOfMipmaps_].len = packetLength; - numberOfMipmaps_++; - - NSAssert( numberOfMipmaps_ < CC_PVRMIPMAP_MAX, @"TexturePVR: Maximum number of mimpaps reached. Increate the CC_PVRMIPMAP_MAX value"); - - dataOffset += packetLength; - - width = MAX(width >> 1, 1); - height = MAX(height >> 1, 1); - } - - success = TRUE; - break; - } - } - - if( ! success ) - CCLOG(@"cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%2x. Re-encode it with a OpenGL pixel format variant", formatFlags); - - return success; -} - - -- (BOOL)createGLTexture -{ - GLsizei width = width_; - GLsizei height = height_; - GLenum err; - - if (numberOfMipmaps_ > 0) - { - if (name_ != 0) - ccGLDeleteTexture( name_ ); - - glPixelStorei(GL_UNPACK_ALIGNMENT,1); - glGenTextures(1, &name_); - ccGLBindTexture2D( name_ ); - - } - - CHECK_GL_ERROR(); // clean possible GL error - - // Generate textures with mipmaps - for (GLint i=0; i < numberOfMipmaps_; i++) - { - GLenum internalFormat = tableFormats[tableFormatIndex_][kCCInternalOpenGLInternalFormat]; - GLenum format = tableFormats[tableFormatIndex_][kCCInternalOpenGLFormat]; - GLenum type = tableFormats[tableFormatIndex_][kCCInternalOpenGLType]; - BOOL compressed = tableFormats[tableFormatIndex_][kCCInternalCompressedImage]; - - if( compressed && ! [[CCConfiguration sharedConfiguration] supportsPVRTC] ) { - CCLOG(@"cocos2d: WARNING: PVRTC images are not supported"); - return FALSE; - } - - unsigned char *data = mipmaps_[i].address; - unsigned int datalen = mipmaps_[i].len; - - if( compressed) - glCompressedTexImage2D(GL_TEXTURE_2D, i, internalFormat, width, height, 0, datalen, data); - else - glTexImage2D(GL_TEXTURE_2D, i, internalFormat, width, height, 0, format, type, data); - - if( i > 0 && (width != height || ccNextPOT(width) != width ) ) - CCLOG(@"cocos2d: TexturePVR. WARNING. Mipmap level %u is not squared. Texture won't render correctly. width=%u != height=%u", i, width, height); - - err = glGetError(); - if (err != GL_NO_ERROR) - { - CCLOG(@"cocos2d: TexturePVR: Error uploading compressed texture level: %u . glError: 0x%04X", i, err); - return FALSE; - } - - width = MAX(width >> 1, 1); - height = MAX(height >> 1, 1); - } - - return TRUE; -} - - -- (id)initWithContentsOfFile:(NSString *)path -{ - if((self = [super init])) - { - unsigned char *pvrdata = NULL; - NSInteger pvrlen = 0; - NSString *lowerCase = [path lowercaseString]; - - if ( [lowerCase hasSuffix:@".ccz"]) - pvrlen = ccInflateCCZFile( [path UTF8String], &pvrdata ); - - else if( [lowerCase hasSuffix:@".gz"] ) - pvrlen = ccInflateGZipFile( [path UTF8String], &pvrdata ); - - else - pvrlen = ccLoadFileIntoMemory( [path UTF8String], &pvrdata ); - - if( pvrlen < 0 ) { - [self release]; - return nil; - } - - - numberOfMipmaps_ = 0; - - name_ = 0; - width_ = height_ = 0; - tableFormatIndex_ = -1; - hasAlpha_ = FALSE; - - retainName_ = NO; // cocos2d integration - - if( ! [self unpackPVRData:pvrdata PVRLen:pvrlen] || ![self createGLTexture] ) { - free(pvrdata); - [self release]; - return nil; - } - - free(pvrdata); - } - - return self; -} - -- (id)initWithContentsOfURL:(NSURL *)url -{ - if (![url isFileURL]) - { - CCLOG(@"cocos2d: CCPVRTexture: Only files are supported"); - [self release]; - return nil; - } - - return [self initWithContentsOfFile:[url path]]; -} - - -+ (id)pvrTextureWithContentsOfFile:(NSString *)path -{ - return [[[self alloc] initWithContentsOfFile:path] autorelease]; -} - - -+ (id)pvrTextureWithContentsOfURL:(NSURL *)url -{ - if (![url isFileURL]) - return nil; - - return [CCTexturePVR pvrTextureWithContentsOfFile:[url path]]; -} - - -- (void)dealloc -{ - CCLOGINFO( @"cocos2d: deallocing %@", self); - - if (name_ != 0 && ! retainName_ ) - ccGLDeleteTexture( name_ ); - - [super dealloc]; -} - -@end - diff --git a/Example/libs/cocos2d/CCTileMapAtlas.h b/Example/libs/cocos2d/CCTileMapAtlas.h deleted file mode 100644 index e8365e4..0000000 --- a/Example/libs/cocos2d/CCTileMapAtlas.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCTextureAtlas.h" -#import "CCAtlasNode.h" -#import "Support/TGAlib.h" - -/** CCTileMapAtlas is a subclass of CCAtlasNode. - - It knows how to render a map based of tiles. - The tiles must be in a .PNG format while the map must be a .TGA file. - - For more information regarding the format, please see this post: - http://www.cocos2d-iphone.org/archives/27 - - All features from CCAtlasNode are valid in CCTileMapAtlas - - IMPORTANT: - This class is deprecated. It is maintained for compatibility reasons only. - You SHOULD not use this class. - Instead, use the newer TMX file format: CCTMXTiledMap - */ -@interface CCTileMapAtlas : CCAtlasNode -{ - - /// info about the map file - tImageTGA *tgaInfo; - - /// x,y to altas dicctionary - NSMutableDictionary *posToAtlasIndex; - - /// numbers of tiles to render - int itemsToRender; -} - -/** TileMap info */ -@property (nonatomic,readonly) tImageTGA *tgaInfo; - -/** creates a CCTileMap with a tile file (atlas) with a map file and the width and height of each tile in points. - The tile file will be loaded using the TextureMgr. - */ -+(id) tileMapAtlasWithTileFile:(NSString*)tile mapFile:(NSString*)map tileWidth:(int)w tileHeight:(int)h; - -/** initializes a CCTileMap with a tile file (atlas) with a map file and the width and height of each tile in points. - The file will be loaded using the TextureMgr. - */ --(id) initWithTileFile:(NSString*)tile mapFile:(NSString*)map tileWidth:(int)w tileHeight:(int)h; - -/** returns a tile from position x,y. - For the moment only channel R is used - */ --(ccColor3B) tileAt: (ccGridSize) position; - -/** sets a tile at position x,y. - For the moment only channel R is used - */ --(void) setTile:(ccColor3B)tile at:(ccGridSize)position; -/** dealloc the map from memory */ --(void) releaseMap; -@end diff --git a/Example/libs/cocos2d/CCTileMapAtlas.m b/Example/libs/cocos2d/CCTileMapAtlas.m deleted file mode 100644 index 084a11d..0000000 --- a/Example/libs/cocos2d/CCTileMapAtlas.m +++ /dev/null @@ -1,245 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "ccConfig.h" -#import "CCTileMapAtlas.h" -#import "ccMacros.h" -#import "Support/CCFileUtils.h" - -@interface CCTileMapAtlas (Private) --(void) loadTGAfile:(NSString*)file; --(void) calculateItemsToRender; --(void) updateAtlasValueAt:(ccGridSize)pos withValue:(ccColor3B)value withIndex:(NSUInteger)idx; -@end - - -@implementation CCTileMapAtlas - -@synthesize tgaInfo; - -#pragma mark CCTileMapAtlas - Creation & Init -+(id) tileMapAtlasWithTileFile:(NSString*)tile mapFile:(NSString*)map tileWidth:(int)w tileHeight:(int)h -{ - return [[[self alloc] initWithTileFile:tile mapFile:map tileWidth:w tileHeight:h] autorelease]; -} - - --(id) initWithTileFile:(NSString*)tile mapFile:(NSString*)map tileWidth:(int)w tileHeight:(int)h -{ - [self loadTGAfile: map]; - [self calculateItemsToRender]; - - if( (self=[super initWithTileFile:tile tileWidth:w tileHeight:h itemsToRender: itemsToRender]) ) { - - color_ = ccWHITE; - - posToAtlasIndex = [[NSMutableDictionary dictionaryWithCapacity:itemsToRender] retain]; - - [self updateAtlasValues]; - - [self setContentSize: CGSizeMake(tgaInfo->width*itemWidth_, tgaInfo->height*itemHeight_)]; - } - - return self; -} - --(void) dealloc -{ - if( tgaInfo ) - tgaDestroy(tgaInfo); - - [posToAtlasIndex release]; - - [super dealloc]; -} - --(void) releaseMap -{ - if( tgaInfo ) - tgaDestroy(tgaInfo); - - tgaInfo = nil; - - [posToAtlasIndex release]; - posToAtlasIndex = nil; -} - --(void) calculateItemsToRender -{ - NSAssert( tgaInfo != nil, @"tgaInfo must be non-nil"); - - itemsToRender = 0; - for(int x = 0;x < tgaInfo->width; x++ ) { - for(int y = 0; y < tgaInfo->height; y++ ) { - ccColor3B *ptr = (ccColor3B*) tgaInfo->imageData; - ccColor3B value = ptr[x + y * tgaInfo->width]; - if( value.r ) - itemsToRender++; - } - } -} - --(void) loadTGAfile:(NSString*)file -{ - NSAssert( file != nil, @"file must be non-nil"); - - NSString *path = [CCFileUtils fullPathFromRelativePath:file ]; - -// //Find the path of the file -// NSBundle *mainBndl = [CCDirector sharedDirector].loadingBundle; -// NSString *resourcePath = [mainBndl resourcePath]; -// NSString * path = [resourcePath stringByAppendingPathComponent:file]; - - tgaInfo = tgaLoad( [path UTF8String] ); -#if 1 - if( tgaInfo->status != TGA_OK ) - [NSException raise:@"TileMapAtlasLoadTGA" format:@"TileMapAtas cannot load TGA file"]; - -#endif -} - -#pragma mark CCTileMapAtlas - Atlas generation / updates - --(void) setTile:(ccColor3B) tile at:(ccGridSize) pos -{ - NSAssert( tgaInfo != nil, @"tgaInfo must not be nil"); - NSAssert( posToAtlasIndex != nil, @"posToAtlasIndex must not be nil"); - NSAssert( pos.x < tgaInfo->width, @"Invalid position.x"); - NSAssert( pos.y < tgaInfo->height, @"Invalid position.x"); - NSAssert( tile.r != 0, @"R component must be non 0"); - - ccColor3B *ptr = (ccColor3B*) tgaInfo->imageData; - ccColor3B value = ptr[pos.x + pos.y * tgaInfo->width]; - if( value.r == 0 ) - CCLOG(@"cocos2d: Value.r must be non 0."); - else { - ptr[pos.x + pos.y * tgaInfo->width] = tile; - - // XXX: this method consumes a lot of memory - // XXX: a tree of something like that shall be impolemented - NSNumber *num = [posToAtlasIndex objectForKey: [NSString stringWithFormat:@"%d,%d", pos.x, pos.y]]; - [self updateAtlasValueAt:pos withValue:tile withIndex: [num integerValue]]; - } -} - --(ccColor3B) tileAt:(ccGridSize) pos -{ - NSAssert( tgaInfo != nil, @"tgaInfo must not be nil"); - NSAssert( pos.x < tgaInfo->width, @"Invalid position.x"); - NSAssert( pos.y < tgaInfo->height, @"Invalid position.y"); - - ccColor3B *ptr = (ccColor3B*) tgaInfo->imageData; - ccColor3B value = ptr[pos.x + pos.y * tgaInfo->width]; - - return value; -} - --(void) updateAtlasValueAt:(ccGridSize)pos withValue:(ccColor3B)value withIndex:(NSUInteger)idx -{ - ccV3F_C4B_T2F_Quad quad; - - NSInteger x = pos.x; - NSInteger y = pos.y; - float row = (value.r % itemsPerRow_); - float col = (value.r / itemsPerRow_); - - float textureWide = [[textureAtlas_ texture] pixelsWide]; - float textureHigh = [[textureAtlas_ texture] pixelsHigh]; - - float itemWidthInPixels = itemWidth_ * CC_CONTENT_SCALE_FACTOR(); - float itemHeightInPixels = itemHeight_ * CC_CONTENT_SCALE_FACTOR(); - - -#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - float left = (2*row*itemWidthInPixels+1)/(2*textureWide); - float right = left+(itemWidthInPixels*2-2)/(2*textureWide); - float top = (2*col*itemHeightInPixels+1)/(2*textureHigh); - float bottom = top+(itemHeightInPixels*2-2)/(2*textureHigh); -#else - float left = (row*itemWidthInPixels)/textureWide; - float right = left+itemWidthInPixels/textureWide; - float top = (col*itemHeightInPixels)/textureHigh; - float bottom = top+itemHeightInPixels/textureHigh; -#endif - - - quad.tl.texCoords.u = left; - quad.tl.texCoords.v = top; - quad.tr.texCoords.u = right; - quad.tr.texCoords.v = top; - quad.bl.texCoords.u = left; - quad.bl.texCoords.v = bottom; - quad.br.texCoords.u = right; - quad.br.texCoords.v = bottom; - - quad.bl.vertices.x = (int) (x * itemWidth_); - quad.bl.vertices.y = (int) (y * itemHeight_); - quad.bl.vertices.z = 0.0f; - quad.br.vertices.x = (int)(x * itemWidth_ + itemWidth_); - quad.br.vertices.y = (int)(y * itemHeight_); - quad.br.vertices.z = 0.0f; - quad.tl.vertices.x = (int)(x * itemWidth_); - quad.tl.vertices.y = (int)(y * itemHeight_ + itemHeight_); - quad.tl.vertices.z = 0.0f; - quad.tr.vertices.x = (int)(x * itemWidth_ + itemWidth_); - quad.tr.vertices.y = (int)(y * itemHeight_ + itemHeight_); - quad.tr.vertices.z = 0.0f; - - ccColor4B color = { color_.r, color_.g, color_.b, opacity_ }; - quad.tr.colors = color; - quad.tl.colors = color; - quad.br.colors = color; - quad.bl.colors = color; - [textureAtlas_ updateQuad:&quad atIndex:idx]; -} - --(void) updateAtlasValues -{ - NSAssert( tgaInfo != nil, @"tgaInfo must be non-nil"); - - - int total = 0; - - for(int x = 0;x < tgaInfo->width; x++ ) { - for(int y = 0; y < tgaInfo->height; y++ ) { - if( total < itemsToRender ) { - ccColor3B *ptr = (ccColor3B*) tgaInfo->imageData; - ccColor3B value = ptr[x + y * tgaInfo->width]; - - if( value.r != 0 ) { - [self updateAtlasValueAt:ccg(x,y) withValue:value withIndex:total]; - - NSString *key = [NSString stringWithFormat:@"%d,%d", x,y]; - NSNumber *num = [NSNumber numberWithInt:total]; - [posToAtlasIndex setObject:num forKey:key]; - - total++; - } - } - } - } -} -@end diff --git a/Example/libs/cocos2d/CCTransition.h b/Example/libs/cocos2d/CCTransition.h deleted file mode 100644 index f57a949..0000000 --- a/Example/libs/cocos2d/CCTransition.h +++ /dev/null @@ -1,296 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCScene.h" -@class CCActionInterval; -@class CCNode; - -/** CCTransitionEaseScene can ease the actions of the scene protocol. - @since v0.8.2 - */ -@protocol CCTransitionEaseScene -/** returns the Ease action that will be performed on a linear action. - @since v0.8.2 - */ --(CCActionInterval*) easeActionWithAction:(CCActionInterval*)action; -@end - -/** Orientation Type used by some transitions - */ -typedef enum { - /// An horizontal orientation where the Left is nearer - kOrientationLeftOver = 0, - /// An horizontal orientation where the Right is nearer - kOrientationRightOver = 1, - /// A vertical orientation where the Up is nearer - kOrientationUpOver = 0, - /// A vertical orientation where the Bottom is nearer - kOrientationDownOver = 1, -} tOrientation; - -/** Base class for CCTransition scenes - */ -@interface CCTransitionScene : CCScene -{ - CCScene *inScene_; - CCScene *outScene_; - ccTime duration_; - BOOL inSceneOnTop_; - BOOL sendCleanupToScene_; -} -/** creates a base transition with duration and incoming scene */ -+(id) transitionWithDuration:(ccTime) t scene:(CCScene*)s; -/** initializes a transition with duration and incoming scene */ --(id) initWithDuration:(ccTime) t scene:(CCScene*)s; -/** called after the transition finishes */ --(void) finish; -/** used by some transitions to hide the outter scene */ --(void) hideOutShowIn; -@end - -/** A CCTransition that supports orientation like. - * Possible orientation: LeftOver, RightOver, UpOver, DownOver - */ -@interface CCTransitionSceneOriented : CCTransitionScene -{ - tOrientation orientation; -} -/** creates a base transition with duration and incoming scene */ -+(id) transitionWithDuration:(ccTime) t scene:(CCScene*)s orientation:(tOrientation)o; -/** initializes a transition with duration and incoming scene */ --(id) initWithDuration:(ccTime) t scene:(CCScene*)s orientation:(tOrientation)o; -@end - - -/** CCTransitionRotoZoom: - Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming - */ -@interface CCTransitionRotoZoom : CCTransitionScene -{} -@end - -/** CCTransitionJumpZoom: - Zoom out and jump the outgoing scene, and then jump and zoom in the incoming -*/ -@interface CCTransitionJumpZoom : CCTransitionScene -{} -@end - -/** CCTransitionMoveInL: - Move in from to the left the incoming scene. -*/ -@interface CCTransitionMoveInL : CCTransitionScene -{} -/** initializes the scenes */ --(void) initScenes; -/** returns the action that will be performed */ --(CCActionInterval*) action; -@end - -/** CCTransitionMoveInR: - Move in from to the right the incoming scene. - */ -@interface CCTransitionMoveInR : CCTransitionMoveInL -{} -@end - -/** CCTransitionMoveInT: - Move in from to the top the incoming scene. - */ -@interface CCTransitionMoveInT : CCTransitionMoveInL -{} -@end - -/** CCTransitionMoveInB: - Move in from to the bottom the incoming scene. - */ -@interface CCTransitionMoveInB : CCTransitionMoveInL -{} -@end - -/** CCTransitionSlideInL: - Slide in the incoming scene from the left border. - */ -@interface CCTransitionSlideInL : CCTransitionScene -{} -/** initializes the scenes */ --(void) initScenes; -/** returns the action that will be performed by the incomming and outgoing scene */ --(CCActionInterval*) action; -@end - -/** CCTransitionSlideInR: - Slide in the incoming scene from the right border. - */ -@interface CCTransitionSlideInR : CCTransitionSlideInL -{} -@end - -/** CCTransitionSlideInB: - Slide in the incoming scene from the bottom border. - */ -@interface CCTransitionSlideInB : CCTransitionSlideInL -{} -@end - -/** CCTransitionSlideInT: - Slide in the incoming scene from the top border. - */ -@interface CCTransitionSlideInT : CCTransitionSlideInL -{} -@end - -/** - Shrink the outgoing scene while grow the incoming scene - */ -@interface CCTransitionShrinkGrow : CCTransitionScene -{} -@end - -/** CCTransitionFlipX: - Flips the screen horizontally. - The front face is the outgoing scene and the back face is the incoming scene. - */ -@interface CCTransitionFlipX : CCTransitionSceneOriented -{} -@end - -/** CCTransitionFlipY: - Flips the screen vertically. - The front face is the outgoing scene and the back face is the incoming scene. - */ -@interface CCTransitionFlipY : CCTransitionSceneOriented -{} -@end - -/** CCTransitionFlipAngular: - Flips the screen half horizontally and half vertically. - The front face is the outgoing scene and the back face is the incoming scene. - */ -@interface CCTransitionFlipAngular : CCTransitionSceneOriented -{} -@end - -/** CCTransitionZoomFlipX: - Flips the screen horizontally doing a zoom out/in - The front face is the outgoing scene and the back face is the incoming scene. - */ -@interface CCTransitionZoomFlipX : CCTransitionSceneOriented -{} -@end - -/** CCTransitionZoomFlipY: - Flips the screen vertically doing a little zooming out/in - The front face is the outgoing scene and the back face is the incoming scene. - */ -@interface CCTransitionZoomFlipY : CCTransitionSceneOriented -{} -@end - -/** CCTransitionZoomFlipAngular: - Flips the screen half horizontally and half vertically doing a little zooming out/in. - The front face is the outgoing scene and the back face is the incoming scene. - */ -@interface CCTransitionZoomFlipAngular : CCTransitionSceneOriented -{} -@end - -/** CCTransitionFade: - Fade out the outgoing scene and then fade in the incoming scene.''' - */ -@interface CCTransitionFade : CCTransitionScene -{ - ccColor4B color; -} -/** creates the transition with a duration and with an RGB color - * Example: [FadeTransition transitionWithDuration:2 scene:s withColor:ccc3(255,0,0)]; // red color - */ -+(id) transitionWithDuration:(ccTime)duration scene:(CCScene*)scene withColor:(ccColor3B)color; -/** initializes the transition with a duration and with an RGB color */ --(id) initWithDuration:(ccTime)duration scene:(CCScene*)scene withColor:(ccColor3B)color; -@end - - -/** - CCTransitionCrossFade: - Cross fades two scenes using the CCRenderTexture object. - */ -@class CCRenderTexture; -@interface CCTransitionCrossFade : CCTransitionScene -{} -@end - -/** CCTransitionTurnOffTiles: - Turn off the tiles of the outgoing scene in random order - */ -@interface CCTransitionTurnOffTiles : CCTransitionScene -{} -@end - -/** CCTransitionSplitCols: - The odd columns goes upwards while the even columns goes downwards. - */ -@interface CCTransitionSplitCols : CCTransitionScene -{} --(CCActionInterval*) action; -@end - -/** CCTransitionSplitRows: - The odd rows goes to the left while the even rows goes to the right. - */ -@interface CCTransitionSplitRows : CCTransitionSplitCols -{} -@end - -/** CCTransitionFadeTR: - Fade the tiles of the outgoing scene from the left-bottom corner the to top-right corner. - */ -@interface CCTransitionFadeTR : CCTransitionScene -{} --(CCActionInterval*) actionWithSize:(ccGridSize) vector; -@end - -/** CCTransitionFadeBL: - Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner. - */ -@interface CCTransitionFadeBL : CCTransitionFadeTR -{} -@end - -/** CCTransitionFadeUp: - * Fade the tiles of the outgoing scene from the bottom to the top. - */ -@interface CCTransitionFadeUp : CCTransitionFadeTR -{} -@end - -/** CCTransitionFadeDown: - * Fade the tiles of the outgoing scene from the top to the bottom. - */ -@interface CCTransitionFadeDown : CCTransitionFadeTR -{} -@end diff --git a/Example/libs/cocos2d/CCTransition.m b/Example/libs/cocos2d/CCTransition.m deleted file mode 100644 index f360a29..0000000 --- a/Example/libs/cocos2d/CCTransition.m +++ /dev/null @@ -1,1067 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - - -#import "CCTransition.h" -#import "CCNode.h" -#import "CCSprite.h" -#import "CCDirector.h" -#import "CCActionInterval.h" -#import "CCActionInstant.h" -#import "CCActionCamera.h" -#import "CCLayer.h" -#import "CCCamera.h" -#import "CCActionTiledGrid.h" -#import "CCActionEase.h" -#import "CCRenderTexture.h" -#import "ccMacros.h" -#import "Support/CGPointExtension.h" - -#ifdef __CC_PLATFORM_IOS -#import "Platforms/iOS/CCTouchDispatcher.h" -#import "Platforms/iOS/CCDirectorIOS.h" -#elif defined(__CC_PLATFORM_MAC) -#import "Platforms/Mac/CCDirectorMac.h" -#import "Platforms/Mac/CCEventDispatcher.h" -#endif - -const NSInteger kSceneFade = 0xFADEFADE; - - -@interface CCTransitionScene (Private) --(void) sceneOrder; -- (void)setNewScene:(ccTime)dt; -@end - -@implementation CCTransitionScene -+(id) transitionWithDuration:(ccTime) t scene:(CCScene*)s -{ - return [[[self alloc] initWithDuration:t scene:s] autorelease]; -} - --(id) initWithDuration:(ccTime) t scene:(CCScene*)s -{ - NSAssert( s != nil, @"Argument scene must be non-nil"); - - if( (self=[super init]) ) { - - duration_ = t; - - // retain - inScene_ = [s retain]; - outScene_ = [[CCDirector sharedDirector] runningScene]; - [outScene_ retain]; - - NSAssert( inScene_ != outScene_, @"Incoming scene must be different from the outgoing scene" ); - - // disable events while transitions - CCDirector *director = [CCDirector sharedDirector]; -#ifdef __CC_PLATFORM_IOS - [[director touchDispatcher] setDispatchEvents: NO]; -#elif defined(__CC_PLATFORM_MAC) - [[director eventDispatcher] setDispatchEvents: NO]; -#endif - - [self sceneOrder]; - } - return self; -} --(void) sceneOrder -{ - inSceneOnTop_ = YES; -} - --(void) draw -{ - [super draw]; - - if( inSceneOnTop_ ) { - [outScene_ visit]; - [inScene_ visit]; - } else { - [inScene_ visit]; - [outScene_ visit]; - } -} - --(void) finish -{ - /* clean up */ - [inScene_ setVisible:YES]; - [inScene_ setPosition:ccp(0,0)]; - [inScene_ setScale:1.0f]; - [inScene_ setRotation:0.0f]; - [inScene_.camera restore]; - - [outScene_ setVisible:NO]; - [outScene_ setPosition:ccp(0,0)]; - [outScene_ setScale:1.0f]; - [outScene_ setRotation:0.0f]; - [outScene_.camera restore]; - - [self schedule:@selector(setNewScene:) interval:0]; -} - --(void) setNewScene: (ccTime) dt -{ - [self unschedule:_cmd]; - - CCDirector *director = [CCDirector sharedDirector]; - - // Before replacing, save the "send cleanup to scene" - sendCleanupToScene_ = [director sendCleanupToScene]; - - [director replaceScene: inScene_]; - - // enable events while transitions -#ifdef __CC_PLATFORM_IOS - [[director touchDispatcher] setDispatchEvents: YES]; -#elif defined(__CC_PLATFORM_MAC) - [[director eventDispatcher] setDispatchEvents: YES]; -#endif - - // issue #267 - [outScene_ setVisible:YES]; -} - --(void) hideOutShowIn -{ - [inScene_ setVisible:YES]; - [outScene_ setVisible:NO]; -} - -// custom onEnter --(void) onEnter -{ - [super onEnter]; - - // outScene_ should not receive the onExit callback - // only the onExitTransitionDidStart - [outScene_ onExitTransitionDidStart]; - - [inScene_ onEnter]; -} - -// custom onExit --(void) onExit -{ - [super onExit]; - [outScene_ onExit]; - - // inScene_ should not receive the onEnter callback - // only the onEnterTransitionDidFinish - [inScene_ onEnterTransitionDidFinish]; -} - -// custom cleanup --(void) cleanup -{ - [super cleanup]; - - if( sendCleanupToScene_ ) - [outScene_ cleanup]; -} - --(void) dealloc -{ - [inScene_ release]; - [outScene_ release]; - [super dealloc]; -} -@end - -// -// Oriented Transition -// -@implementation CCTransitionSceneOriented -+(id) transitionWithDuration:(ccTime) t scene:(CCScene*)s orientation:(tOrientation)o -{ - return [[[self alloc] initWithDuration:t scene:s orientation:o] autorelease]; -} - --(id) initWithDuration:(ccTime) t scene:(CCScene*)s orientation:(tOrientation)o -{ - if( (self=[super initWithDuration:t scene:s]) ) - orientation = o; - return self; -} -@end - - -// -// RotoZoom -// -@implementation CCTransitionRotoZoom --(void) onEnter -{ - [super onEnter]; - - [inScene_ setScale:0.001f]; - [outScene_ setScale:1.0f]; - - [inScene_ setAnchorPoint:ccp(0.5f, 0.5f)]; - [outScene_ setAnchorPoint:ccp(0.5f, 0.5f)]; - - CCActionInterval *rotozoom = [CCSequence actions: [CCSpawn actions: - [CCScaleBy actionWithDuration:duration_/2 scale:0.001f], - [CCRotateBy actionWithDuration:duration_/2 angle:360 *2], - nil], - [CCDelayTime actionWithDuration:duration_/2], - nil]; - - - [outScene_ runAction: rotozoom]; - [inScene_ runAction: [CCSequence actions: - [rotozoom reverse], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil]]; -} -@end - -// -// JumpZoom -// -@implementation CCTransitionJumpZoom --(void) onEnter -{ - [super onEnter]; - CGSize s = [[CCDirector sharedDirector] winSize]; - - [inScene_ setScale:0.5f]; - [inScene_ setPosition:ccp( s.width,0 )]; - - [inScene_ setAnchorPoint:ccp(0.5f, 0.5f)]; - [outScene_ setAnchorPoint:ccp(0.5f, 0.5f)]; - - CCActionInterval *jump = [CCJumpBy actionWithDuration:duration_/4 position:ccp(-s.width,0) height:s.width/4 jumps:2]; - CCActionInterval *scaleIn = [CCScaleTo actionWithDuration:duration_/4 scale:1.0f]; - CCActionInterval *scaleOut = [CCScaleTo actionWithDuration:duration_/4 scale:0.5f]; - - CCActionInterval *jumpZoomOut = [CCSequence actions: scaleOut, jump, nil]; - CCActionInterval *jumpZoomIn = [CCSequence actions: jump, scaleIn, nil]; - - CCActionInterval *delay = [CCDelayTime actionWithDuration:duration_/2]; - - [outScene_ runAction: jumpZoomOut]; - [inScene_ runAction: [CCSequence actions: delay, - jumpZoomIn, - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil] ]; -} -@end - -// -// MoveInL -// -@implementation CCTransitionMoveInL --(void) onEnter -{ - [super onEnter]; - - [self initScenes]; - - CCActionInterval *a = [self action]; - - [inScene_ runAction: [CCSequence actions: - [self easeActionWithAction:a], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil] - ]; - -} --(CCActionInterval*) action -{ - return [CCMoveTo actionWithDuration:duration_ position:ccp(0,0)]; -} - --(CCActionInterval*) easeActionWithAction:(CCActionInterval*)action -{ - return [CCEaseOut actionWithAction:action rate:2.0f]; -// return [EaseElasticOut actionWithAction:action period:0.4f]; -} - --(void) initScenes -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - [inScene_ setPosition: ccp( -s.width,0) ]; -} -@end - -// -// MoveInR -// -@implementation CCTransitionMoveInR --(void) initScenes -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - [inScene_ setPosition: ccp( s.width,0) ]; -} -@end - -// -// MoveInT -// -@implementation CCTransitionMoveInT --(void) initScenes -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - [inScene_ setPosition: ccp( 0, s.height) ]; -} -@end - -// -// MoveInB -// -@implementation CCTransitionMoveInB --(void) initScenes -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - [inScene_ setPosition: ccp( 0, -s.height) ]; -} -@end - -// -// SlideInL -// - -// The adjust factor is needed to prevent issue #442 -// One solution is to use DONT_RENDER_IN_SUBPIXELS images, but NO -// The other issue is that in some transitions (and I don't know why) -// the order should be reversed (In in top of Out or vice-versa). -#define ADJUST_FACTOR 0.5f -@implementation CCTransitionSlideInL --(void) onEnter -{ - [super onEnter]; - - [self initScenes]; - - CCActionInterval *in = [self action]; - CCActionInterval *out = [self action]; - - id inAction = [self easeActionWithAction:in]; - id outAction = [CCSequence actions: - [self easeActionWithAction:out], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil]; - - [inScene_ runAction: inAction]; - [outScene_ runAction: outAction]; -} --(void) sceneOrder -{ - inSceneOnTop_ = NO; -} --(void) initScenes -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - [inScene_ setPosition: ccp( -(s.width-ADJUST_FACTOR),0) ]; -} --(CCActionInterval*) action -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - return [CCMoveBy actionWithDuration:duration_ position:ccp(s.width-ADJUST_FACTOR,0)]; -} - --(CCActionInterval*) easeActionWithAction:(CCActionInterval*)action -{ - return [CCEaseOut actionWithAction:action rate:2.0f]; -// return [EaseElasticOut actionWithAction:action period:0.4f]; -} - -@end - -// -// SlideInR -// -@implementation CCTransitionSlideInR --(void) sceneOrder -{ - inSceneOnTop_ = YES; -} --(void) initScenes -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - [inScene_ setPosition: ccp( s.width-ADJUST_FACTOR,0) ]; -} - --(CCActionInterval*) action -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - return [CCMoveBy actionWithDuration:duration_ position:ccp(-(s.width-ADJUST_FACTOR),0)]; -} - -@end - -// -// SlideInT -// -@implementation CCTransitionSlideInT --(void) sceneOrder -{ - inSceneOnTop_ = NO; -} --(void) initScenes -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - [inScene_ setPosition: ccp(0,s.height-ADJUST_FACTOR) ]; -} - --(CCActionInterval*) action -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - return [CCMoveBy actionWithDuration:duration_ position:ccp(0,-(s.height-ADJUST_FACTOR))]; -} - -@end - -// -// SlideInB -// -@implementation CCTransitionSlideInB --(void) sceneOrder -{ - inSceneOnTop_ = YES; -} - --(void) initScenes -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - [inScene_ setPosition: ccp(0,-(s.height-ADJUST_FACTOR)) ]; -} - --(CCActionInterval*) action -{ - CGSize s = [[CCDirector sharedDirector] winSize]; - return [CCMoveBy actionWithDuration:duration_ position:ccp(0,s.height-ADJUST_FACTOR)]; -} -@end - -// -// ShrinkGrow Transition -// -@implementation CCTransitionShrinkGrow --(void) onEnter -{ - [super onEnter]; - - [inScene_ setScale:0.001f]; - [outScene_ setScale:1.0f]; - - [inScene_ setAnchorPoint:ccp(2/3.0f,0.5f)]; - [outScene_ setAnchorPoint:ccp(1/3.0f,0.5f)]; - - CCActionInterval *scaleOut = [CCScaleTo actionWithDuration:duration_ scale:0.01f]; - CCActionInterval *scaleIn = [CCScaleTo actionWithDuration:duration_ scale:1.0f]; - - [inScene_ runAction: [self easeActionWithAction:scaleIn]]; - [outScene_ runAction: [CCSequence actions: - [self easeActionWithAction:scaleOut], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil] ]; -} --(CCActionInterval*) easeActionWithAction:(CCActionInterval*)action -{ - return [CCEaseOut actionWithAction:action rate:2.0f]; -// return [EaseElasticOut actionWithAction:action period:0.3f]; -} -@end - -// -// FlipX Transition -// -@implementation CCTransitionFlipX --(void) onEnter -{ - [super onEnter]; - - CCActionInterval *inA, *outA; - [inScene_ setVisible: NO]; - - float inDeltaZ, inAngleZ; - float outDeltaZ, outAngleZ; - - if( orientation == kOrientationRightOver ) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - - inA = [CCSequence actions: - [CCDelayTime actionWithDuration:duration_/2], - [CCShow action], - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:inAngleZ deltaAngleZ:inDeltaZ angleX:0 deltaAngleX:0], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - outA = [CCSequence actions: - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:0 deltaAngleX:0], - [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], - nil ]; - - [inScene_ runAction: inA]; - [outScene_ runAction: outA]; - -} -@end - -// -// FlipY Transition -// -@implementation CCTransitionFlipY --(void) onEnter -{ - [super onEnter]; - - CCActionInterval *inA, *outA; - [inScene_ setVisible: NO]; - - float inDeltaZ, inAngleZ; - float outDeltaZ, outAngleZ; - - if( orientation == kOrientationUpOver ) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - inA = [CCSequence actions: - [CCDelayTime actionWithDuration:duration_/2], - [CCShow action], - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:inAngleZ deltaAngleZ:inDeltaZ angleX:90 deltaAngleX:0], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - outA = [CCSequence actions: - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:90 deltaAngleX:0], - [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], - nil ]; - - [inScene_ runAction: inA]; - [outScene_ runAction: outA]; - -} -@end - -// -// FlipAngular Transition -// -@implementation CCTransitionFlipAngular --(void) onEnter -{ - [super onEnter]; - - CCActionInterval *inA, *outA; - [inScene_ setVisible: NO]; - - float inDeltaZ, inAngleZ; - float outDeltaZ, outAngleZ; - - if( orientation == kOrientationRightOver ) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - inA = [CCSequence actions: - [CCDelayTime actionWithDuration:duration_/2], - [CCShow action], - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:inAngleZ deltaAngleZ:inDeltaZ angleX:-45 deltaAngleX:0], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - outA = [CCSequence actions: - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:45 deltaAngleX:0], - [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], - nil ]; - - [inScene_ runAction: inA]; - [outScene_ runAction: outA]; -} -@end - -// -// ZoomFlipX Transition -// -@implementation CCTransitionZoomFlipX --(void) onEnter -{ - [super onEnter]; - - CCActionInterval *inA, *outA; - [inScene_ setVisible: NO]; - - float inDeltaZ, inAngleZ; - float outDeltaZ, outAngleZ; - - if( orientation == kOrientationRightOver ) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - inA = [CCSequence actions: - [CCDelayTime actionWithDuration:duration_/2], - [CCSpawn actions: - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:inAngleZ deltaAngleZ:inDeltaZ angleX:0 deltaAngleX:0], - [CCScaleTo actionWithDuration:duration_/2 scale:1], - [CCShow action], - nil], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - outA = [CCSequence actions: - [CCSpawn actions: - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:0 deltaAngleX:0], - [CCScaleTo actionWithDuration:duration_/2 scale:0.5f], - nil], - [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], - nil ]; - - inScene_.scale = 0.5f; - [inScene_ runAction: inA]; - [outScene_ runAction: outA]; -} -@end - -// -// ZoomFlipY Transition -// -@implementation CCTransitionZoomFlipY --(void) onEnter -{ - [super onEnter]; - - CCActionInterval *inA, *outA; - [inScene_ setVisible: NO]; - - float inDeltaZ, inAngleZ; - float outDeltaZ, outAngleZ; - - if( orientation == kOrientationUpOver ) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - - inA = [CCSequence actions: - [CCDelayTime actionWithDuration:duration_/2], - [CCSpawn actions: - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:inAngleZ deltaAngleZ:inDeltaZ angleX:90 deltaAngleX:0], - [CCScaleTo actionWithDuration:duration_/2 scale:1], - [CCShow action], - nil], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - outA = [CCSequence actions: - [CCSpawn actions: - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:90 deltaAngleX:0], - [CCScaleTo actionWithDuration:duration_/2 scale:0.5f], - nil], - [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], - nil ]; - - inScene_.scale = 0.5f; - [inScene_ runAction: inA]; - [outScene_ runAction: outA]; -} -@end - -// -// ZoomFlipAngular Transition -// -@implementation CCTransitionZoomFlipAngular --(void) onEnter -{ - [super onEnter]; - - CCActionInterval *inA, *outA; - [inScene_ setVisible: NO]; - - float inDeltaZ, inAngleZ; - float outDeltaZ, outAngleZ; - - if( orientation == kOrientationRightOver ) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - - inA = [CCSequence actions: - [CCDelayTime actionWithDuration:duration_/2], - [CCSpawn actions: - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:inAngleZ deltaAngleZ:inDeltaZ angleX:-45 deltaAngleX:0], - [CCScaleTo actionWithDuration:duration_/2 scale:1], - [CCShow action], - nil], - [CCShow action], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - outA = [CCSequence actions: - [CCSpawn actions: - [CCOrbitCamera actionWithDuration: duration_/2 radius: 1 deltaRadius:0 angleZ:outAngleZ deltaAngleZ:outDeltaZ angleX:45 deltaAngleX:0], - [CCScaleTo actionWithDuration:duration_/2 scale:0.5f], - nil], - [CCHide action], - [CCDelayTime actionWithDuration:duration_/2], - nil ]; - - inScene_.scale = 0.5f; - [inScene_ runAction: inA]; - [outScene_ runAction: outA]; -} -@end - - -// -// Fade Transition -// -@implementation CCTransitionFade -+(id) transitionWithDuration:(ccTime)d scene:(CCScene*)s withColor:(ccColor3B)color -{ - return [[[self alloc] initWithDuration:d scene:s withColor:color] autorelease]; -} - --(id) initWithDuration:(ccTime)d scene:(CCScene*)s withColor:(ccColor3B)aColor -{ - if( (self=[super initWithDuration:d scene:s]) ) { - color.r = aColor.r; - color.g = aColor.g; - color.b = aColor.b; - } - - return self; -} - --(id) initWithDuration:(ccTime)d scene:(CCScene*)s -{ - return [self initWithDuration:d scene:s withColor:ccBLACK]; -} - --(void) onEnter -{ - [super onEnter]; - - CCLayerColor *l = [CCLayerColor layerWithColor:color]; - [inScene_ setVisible: NO]; - - [self addChild: l z:2 tag:kSceneFade]; - - - CCNode *f = [self getChildByTag:kSceneFade]; - - CCActionInterval *a = [CCSequence actions: - [CCFadeIn actionWithDuration:duration_/2], - [CCCallFunc actionWithTarget:self selector:@selector(hideOutShowIn)], - [CCFadeOut actionWithDuration:duration_/2], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - [f runAction: a]; -} - --(void) onExit -{ - [super onExit]; - [self removeChildByTag:kSceneFade cleanup:NO]; -} -@end - - -// -// Cross Fade Transition -// -@implementation CCTransitionCrossFade - --(void) draw -{ - // override draw since both scenes (textures) are rendered in 1 scene -} - --(void) onEnter -{ - [super onEnter]; - - // create a transparent color layer - // in which we are going to add our rendertextures - ccColor4B color = {0,0,0,0}; - CGSize size = [[CCDirector sharedDirector] winSize]; - CCLayerColor * layer = [CCLayerColor layerWithColor:color]; - - // create the first render texture for inScene_ - CCRenderTexture *inTexture = [CCRenderTexture renderTextureWithWidth:size.width height:size.height]; - inTexture.sprite.anchorPoint= ccp(0.5f,0.5f); - inTexture.position = ccp(size.width/2, size.height/2); - inTexture.anchorPoint = ccp(0.5f,0.5f); - - // render inScene_ to its texturebuffer - [inTexture begin]; - [inScene_ visit]; - [inTexture end]; - - // create the second render texture for outScene_ - CCRenderTexture *outTexture = [CCRenderTexture renderTextureWithWidth:size.width height:size.height]; - outTexture.sprite.anchorPoint= ccp(0.5f,0.5f); - outTexture.position = ccp(size.width/2, size.height/2); - outTexture.anchorPoint = ccp(0.5f,0.5f); - - // render outScene_ to its texturebuffer - [outTexture begin]; - [outScene_ visit]; - [outTexture end]; - - // create blend functions - - ccBlendFunc blend1 = {GL_ONE, GL_ONE}; // inScene_ will lay on background and will not be used with alpha - ccBlendFunc blend2 = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA}; // we are going to blend outScene_ via alpha - - // set blendfunctions - [inTexture.sprite setBlendFunc:blend1]; - [outTexture.sprite setBlendFunc:blend2]; - - // add render textures to the layer - [layer addChild:inTexture]; - [layer addChild:outTexture]; - - // initial opacity: - [inTexture.sprite setOpacity:255]; - [outTexture.sprite setOpacity:255]; - - // create the blend action - CCActionInterval * layerAction = [CCSequence actions: - [CCFadeTo actionWithDuration:duration_ opacity:0], - [CCCallFunc actionWithTarget:self selector:@selector(hideOutShowIn)], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - - - // run the blend action - [outTexture.sprite runAction: layerAction]; - - // add the layer (which contains our two rendertextures) to the scene - [self addChild: layer z:2 tag:kSceneFade]; -} - -// clean up on exit --(void) onExit -{ - // remove our layer and release all containing objects - [self removeChildByTag:kSceneFade cleanup:NO]; - - [super onExit]; -} -@end - -// -// TurnOffTilesTransition -// -@implementation CCTransitionTurnOffTiles - -// override addScenes, and change the order --(void) sceneOrder -{ - inSceneOnTop_ = NO; -} - --(void) onEnter -{ - [super onEnter]; - CGSize s = [[CCDirector sharedDirector] winSize]; - float aspect = s.width / s.height; - int x = 12 * aspect; - int y = 12; - - id toff = [CCTurnOffTiles actionWithSize: ccg(x,y) duration:duration_]; - id action = [self easeActionWithAction:toff]; - [outScene_ runAction: [CCSequence actions: action, - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - [CCStopGrid action], - nil] - ]; - -} --(CCActionInterval*) easeActionWithAction:(CCActionInterval*)action -{ - return action; -// return [EaseIn actionWithAction:action rate:2.0f]; -} -@end - -#pragma mark Split Transitions - -// -// SplitCols Transition -// -@implementation CCTransitionSplitCols - --(void) onEnter -{ - [super onEnter]; - - inScene_.visible = NO; - - id split = [self action]; - id seq = [CCSequence actions: - split, - [CCCallFunc actionWithTarget:self selector:@selector(hideOutShowIn)], - [split reverse], - nil - ]; - [self runAction: [CCSequence actions: - [self easeActionWithAction:seq], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - [CCStopGrid action], - nil] - ]; -} - --(CCActionInterval*) action -{ - return [CCSplitCols actionWithCols:3 duration:duration_/2.0f]; -} - --(CCActionInterval*) easeActionWithAction:(CCActionInterval*)action -{ - return [CCEaseInOut actionWithAction:action rate:3.0f]; -} -@end - -// -// SplitRows Transition -// -@implementation CCTransitionSplitRows --(CCActionInterval*) action -{ - return [CCSplitRows actionWithRows:3 duration:duration_/2.0f]; -} -@end - - -#pragma mark Fade Grid Transitions - -// -// FadeTR Transition -// -@implementation CCTransitionFadeTR --(void) sceneOrder -{ - inSceneOnTop_ = NO; -} - --(void) onEnter -{ - [super onEnter]; - - CGSize s = [[CCDirector sharedDirector] winSize]; - float aspect = s.width / s.height; - int x = 12 * aspect; - int y = 12; - - id action = [self actionWithSize:ccg(x,y)]; - - [outScene_ runAction: [CCSequence actions: - [self easeActionWithAction:action], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - [CCStopGrid action], - nil] - ]; -} - --(CCActionInterval*) actionWithSize: (ccGridSize) v -{ - return [CCFadeOutTRTiles actionWithSize:v duration:duration_]; -} - --(CCActionInterval*) easeActionWithAction:(CCActionInterval*)action -{ - return action; -// return [CCEaseOut actionWithAction:action rate:3.0f]; -} -@end - -// -// FadeBL Transition -// -@implementation CCTransitionFadeBL --(CCActionInterval*) actionWithSize: (ccGridSize) v -{ - return [CCFadeOutBLTiles actionWithSize:v duration:duration_]; -} -@end - -// -// FadeUp Transition -// -@implementation CCTransitionFadeUp --(CCActionInterval*) actionWithSize: (ccGridSize) v -{ - return [CCFadeOutUpTiles actionWithSize:v duration:duration_]; -} -@end - -// -// FadeDown Transition -// -@implementation CCTransitionFadeDown --(CCActionInterval*) actionWithSize: (ccGridSize) v -{ - return [CCFadeOutDownTiles actionWithSize:v duration:duration_]; -} -@end diff --git a/Example/libs/cocos2d/CCTransitionPageTurn.h b/Example/libs/cocos2d/CCTransitionPageTurn.h deleted file mode 100644 index 1e83c08..0000000 --- a/Example/libs/cocos2d/CCTransitionPageTurn.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Sindesso Pty Ltd http://www.sindesso.com/ - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCTransition.h" - -/** CCTransitionPageTurn transition. - * A transition which peels back the bottom right hand corner of a scene - * to transition to the scene beneath it simulating a page turn - * - * This uses a 3DAction so it is strongly recommended that depth buffering - * is turned on in CCDirector using: - * - * [[CCDirector sharedDirector] setDepthBufferFormat:kCCDepthBuffer16]; - * - * @since v0.8.2 - */ -@interface CCTransitionPageTurn : CCTransitionScene -{ - BOOL back_; -} -/** - * creates a base transition with duration and incoming scene - * if back is TRUE then the effect is reversed to appear as if the incoming - * scene is being turned from left over the outgoing scene - */ -+(id) transitionWithDuration:(ccTime) t scene:(CCScene*)s backwards:(BOOL) back; - -/** - * creates a base transition with duration and incoming scene - * if back is TRUE then the effect is reversed to appear as if the incoming - * scene is being turned from left over the outgoing scene - */ --(id) initWithDuration:(ccTime) t scene:(CCScene*)s backwards:(BOOL) back; - --(CCActionInterval*) actionWithSize:(ccGridSize) vector; - -@end diff --git a/Example/libs/cocos2d/CCTransitionPageTurn.m b/Example/libs/cocos2d/CCTransitionPageTurn.m deleted file mode 100644 index 810284f..0000000 --- a/Example/libs/cocos2d/CCTransitionPageTurn.m +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Sindesso Pty Ltd http://www.sindesso.com/ - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCTransitionPageTurn.h" -#import "CCActionPageTurn3D.h" -#import "CCDirector.h" - -@implementation CCTransitionPageTurn - -/** creates a base transition with duration and incoming scene */ -+(id) transitionWithDuration:(ccTime) t scene:(CCScene*)s backwards:(BOOL) back -{ - return [[[self alloc] initWithDuration:t scene:s backwards:back] autorelease]; -} - -/** initializes a transition with duration and incoming scene */ --(id) initWithDuration:(ccTime) t scene:(CCScene*)s backwards:(BOOL) back -{ - // XXX: needed before [super init] - back_ = back; - - if( ( self = [super initWithDuration:t scene:s] ) ) - { - // do something - } - return self; -} - --(void) sceneOrder -{ - inSceneOnTop_ = back_; -} - -// --(void) onEnter -{ - [super onEnter]; - - CGSize s = [[CCDirector sharedDirector] winSize]; - int x, y; - if( s.width > s.height) - { - x = 16; - y = 12; - } - else - { - x = 12; - y = 16; - } - - id action = [self actionWithSize:ccg(x,y)]; - - if(! back_ ) - { - [outScene_ runAction: [CCSequence actions: - action, - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - [CCStopGrid action], - nil] - ]; - } - else - { - // to prevent initial flicker - inScene_.visible = NO; - [inScene_ runAction: [CCSequence actions: - [CCShow action], - action, - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - [CCStopGrid action], - nil] - ]; - } - -} - --(CCActionInterval*) actionWithSize: (ccGridSize) v -{ - if( back_ ) - { - // Get hold of the PageTurn3DAction - return [CCReverseTime actionWithAction: - [CCPageTurn3D actionWithSize:v duration:duration_]]; - } - else - { - // Get hold of the PageTurn3DAction - return [CCPageTurn3D actionWithSize:v duration:duration_]; - } -} - -@end - diff --git a/Example/libs/cocos2d/CCTransitionProgress.h b/Example/libs/cocos2d/CCTransitionProgress.h deleted file mode 100644 index 241ff63..0000000 --- a/Example/libs/cocos2d/CCTransitionProgress.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Lam Pham - * - * Copyright (c) 2012 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "CCTransition.h" - -@interface CCTransitionProgress : CCTransitionScene -{ - float to_, from_; - CCScene *sceneToBeModified_; -} -@end - -/** CCTransitionRadialCCW transition. - A counter colock-wise radial transition to the next scene - */ -@interface CCTransitionProgressRadialCCW : CCTransitionProgress -@end - -/** CCTransitionRadialCW transition. - A counter colock-wise radial transition to the next scene -*/ -@interface CCTransitionProgressRadialCW : CCTransitionProgress -@end - -/** CCTransitionProgressHorizontal transition. - A colock-wise radial transition to the next scene - */ -@interface CCTransitionProgressHorizontal : CCTransitionProgress -@end - -@interface CCTransitionProgressVertical : CCTransitionProgress -@end - -@interface CCTransitionProgressInOut : CCTransitionProgress -@end - -@interface CCTransitionProgressOutIn : CCTransitionProgress -@end diff --git a/Example/libs/cocos2d/CCTransitionProgress.m b/Example/libs/cocos2d/CCTransitionProgress.m deleted file mode 100644 index afe4de6..0000000 --- a/Example/libs/cocos2d/CCTransitionProgress.m +++ /dev/null @@ -1,276 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Lam Pham - * - * Copyright (c) 2012 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCTransitionProgress.h" -#import "CCDirector.h" -#import "CCRenderTexture.h" -#import "CCLayer.h" -#import "CCActionInstant.h" -#import "CCProgressTimer.h" -#import "CCActionProgressTimer.h" -#import "Support/CGPointExtension.h" - -enum { - kCCSceneRadial = 0xc001, -}; - -#pragma mark - CCTransitionProgress - -@interface CCTransitionProgress() --(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture; --(void) setupTransition; -@end - -@implementation CCTransitionProgress --(void) onEnter -{ - [super onEnter]; - - [self setupTransition]; - - // create a transparent color layer - // in which we are going to add our rendertextures - CGSize size = [[CCDirector sharedDirector] winSize]; - - // create the second render texture for outScene - CCRenderTexture *texture = [CCRenderTexture renderTextureWithWidth:size.width height:size.height]; - texture.sprite.anchorPoint= ccp(0.5f,0.5f); - texture.position = ccp(size.width/2, size.height/2); - texture.anchorPoint = ccp(0.5f,0.5f); - - // render outScene to its texturebuffer - [texture clear:0 g:0 b:0 a:1]; - [texture begin]; - [sceneToBeModified_ visit]; - [texture end]; - - - // Since we've passed the outScene to the texture we don't need it. - if( sceneToBeModified_ == outScene_ ) - [self hideOutShowIn]; - - // We need the texture in RenderTexture. - CCProgressTimer *node = [self progressTimerNodeWithRenderTexture:texture]; - - // create the blend action - CCActionInterval * layerAction = [CCSequence actions: - [CCProgressFromTo actionWithDuration:duration_ from:from_ to:to_], - [CCCallFunc actionWithTarget:self selector:@selector(finish)], - nil ]; - // run the blend action - [node runAction: layerAction]; - - // add the layer (which contains our two rendertextures) to the scene - [self addChild: node z:2 tag:kCCSceneRadial]; -} - -// clean up on exit --(void) onExit -{ - // remove our layer and release all containing objects - [self removeChildByTag:kCCSceneRadial cleanup:NO]; - [super onExit]; -} - --(void) sceneOrder -{ - inSceneOnTop_ = NO; -} - --(void) setupTransition -{ - sceneToBeModified_ = outScene_; - from_ = 100; - to_ = 0; -} - --(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture -{ - NSAssert(NO, @"override me - abstract class"); - - return nil; -} -@end - -#pragma mark - CCTransitionProgressRadialCCW - -@implementation CCTransitionProgressRadialCCW --(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture -{ - CGSize size = [[CCDirector sharedDirector] winSize]; - - CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; - - // but it is flipped upside down so we flip the sprite - node.sprite.flipY = YES; - node.type = kCCProgressTimerTypeRadial; - - // Return the radial type that we want to use - node.reverseDirection = NO; - node.percentage = 100; - node.position = ccp(size.width/2, size.height/2); - node.anchorPoint = ccp(0.5f,0.5f); - - return node; -} -@end - -#pragma mark - CCTransitionProgressRadialCW - -@implementation CCTransitionProgressRadialCW --(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture -{ - CGSize size = [[CCDirector sharedDirector] winSize]; - - CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; - - // but it is flipped upside down so we flip the sprite - node.sprite.flipY = YES; - node.type = kCCProgressTimerTypeRadial; - - // Return the radial type that we want to use - node.reverseDirection = YES; - node.percentage = 100; - node.position = ccp(size.width/2, size.height/2); - node.anchorPoint = ccp(0.5f,0.5f); - - return node; -} -@end - -#pragma mark - CCTransitionProgressHorizontal - -@implementation CCTransitionProgressHorizontal --(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture -{ - CGSize size = [[CCDirector sharedDirector] winSize]; - - CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; - - // but it is flipped upside down so we flip the sprite - node.sprite.flipY = YES; - node.type = kCCProgressTimerTypeBar; - - node.midpoint = ccp(1, 0); - node.barChangeRate = ccp(1,0); - - node.percentage = 100; - node.position = ccp(size.width/2, size.height/2); - node.anchorPoint = ccp(0.5f,0.5f); - - return node; -} -@end - -#pragma mark - CCTransitionProgressVertical - -@implementation CCTransitionProgressVertical --(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture -{ - CGSize size = [[CCDirector sharedDirector] winSize]; - - CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; - - // but it is flipped upside down so we flip the sprite - node.sprite.flipY = YES; - node.type = kCCProgressTimerTypeBar; - - node.midpoint = ccp(0, 0); - node.barChangeRate = ccp(0,1); - - node.percentage = 100; - node.position = ccp(size.width/2, size.height/2); - node.anchorPoint = ccp(0.5f,0.5f); - - return node; -} -@end - -#pragma mark - CCTransitionProgressInOut - -@implementation CCTransitionProgressInOut - --(void) sceneOrder -{ - inSceneOnTop_ = NO; -} - --(void) setupTransition -{ - sceneToBeModified_ = inScene_; - from_ = 0; - to_ = 100; -} - --(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture -{ - CGSize size = [[CCDirector sharedDirector] winSize]; - - CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; - - // but it is flipped upside down so we flip the sprite - node.sprite.flipY = YES; - node.type = kCCProgressTimerTypeBar; - - node.midpoint = ccp(.5f, .5f); - node.barChangeRate = ccp(1, 1); - - node.percentage = 0; - node.position = ccp(size.width/2, size.height/2); - node.anchorPoint = ccp(0.5f,0.5f); - - return node; -} -@end - -#pragma mark - CCTransitionProgressOutIn - -@implementation CCTransitionProgressOutIn --(CCProgressTimer*) progressTimerNodeWithRenderTexture:(CCRenderTexture*)texture -{ - CGSize size = [[CCDirector sharedDirector] winSize]; - - CCProgressTimer *node = [CCProgressTimer progressWithSprite:texture.sprite]; - - // but it is flipped upside down so we flip the sprite - node.sprite.flipY = YES; - node.type = kCCProgressTimerTypeBar; - - node.midpoint = ccp(.5f, .5f); - node.barChangeRate = ccp(1, 1); - - node.percentage = 100; - node.position = ccp(size.width/2, size.height/2); - node.anchorPoint = ccp(0.5f,0.5f); - - return node; -} -@end - - - diff --git a/Example/libs/cocos2d/Platforms/CCGL.h b/Example/libs/cocos2d/Platforms/CCGL.h deleted file mode 100644 index 26d6dd0..0000000 --- a/Example/libs/cocos2d/Platforms/CCGL.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// -// Common layer for OpenGL stuff -// - -#import "../ccMacros.h" - -#if __CC_PLATFORM_IOS -#import -#import -#import -#import "iOS/CCGLView.h" - -#elif __CC_PLATFORM_MAC -#import -#import -#import // needed for NSOpenGLView -#import "Mac/CCGLView.h" -#endif - - -// iOS -#if __CC_PLATFORM_IOS -#define glClearDepth glClearDepthf -#define glDeleteVertexArrays glDeleteVertexArraysOES -#define glGenVertexArrays glGenVertexArraysOES -#define glBindVertexArray glBindVertexArrayOES - -// Mac -#elif __CC_PLATFORM_MAC -#define glDeleteVertexArrays glDeleteVertexArraysAPPLE -#define glGenVertexArrays glGenVertexArraysAPPLE -#define glBindVertexArray glBindVertexArrayAPPLE - -#endif diff --git a/Example/libs/cocos2d/Platforms/CCNS.h b/Example/libs/cocos2d/Platforms/CCNS.h deleted file mode 100644 index 4fe5535..0000000 --- a/Example/libs/cocos2d/Platforms/CCNS.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// -// Common layer for NS (Next-Step) stuff -// - -#import "../ccMacros.h" - -#import // for NSObject - -#ifdef __CC_PLATFORM_IOS - -#define CCRectFromString(__r__) CGRectFromString(__r__) -#define CCPointFromString(__p__) CGPointFromString(__p__) -#define CCSizeFromString(__s__) CGSizeFromString(__s__) -#define CCNSSizeToCGSize -#define CCNSRectToCGRect -#define CCNSPointToCGPoint -#define CCTextAlignment UITextAlignment -#define CCTextAlignmentCenter UITextAlignmentCenter -#define CCTextAlignmentLeft UITextAlignmentLeft -#define CCTextAlignmentRight UITextAlignmentRight -#define CCLineBreakMode UILineBreakMode -#define CCLineBreakModeWordWrap UILineBreakModeWordWrap -#define CCLineBreakModeCharacterWrap UILineBreakModeCharacterWrap -#define CCLineBreakModeClip UILineBreakModeClip -#define CCLineBreakModeHeadTruncation UILineBreakModeHeadTruncation -#define CCLineBreakModeTailTruncation UILineBreakModeTailTruncation -#define CCLineBreakModeMiddleTruncation UILineBreakModeMiddleTruncation - - - -#elif defined(__CC_PLATFORM_MAC) - -#define CCRectFromString(__r__) NSRectToCGRect( NSRectFromString(__r__) ) -#define CCPointFromString(__p__) NSPointToCGPoint( NSPointFromString(__p__) ) -#define CCSizeFromString(__s__) NSSizeToCGSize( NSSizeFromString(__s__) ) -#define CCNSSizeToCGSize NSSizeToCGSize -#define CCNSRectToCGRect NSRectToCGRect -#define CCNSPointToCGPoint NSPointToCGPoint -#define CCTextAlignment NSTextAlignment -#define CCTextAlignmentCenter NSCenterTextAlignment -#define CCTextAlignmentLeft NSLeftTextAlignment -#define CCTextAlignmentRight NSRightTextAlignment -#define CCLineBreakMode NSLineBreakMode -#define CCLineBreakModeWordWrap NSLineBreakByWordWrapping -#define CCLineBreakModeClip -1 -#define CCLineBreakModeHeadTruncation -1 -#define CCLineBreakModeTailTruncation -1 -#define CCLineBreakModeMiddleTruncation -1 - - -#endif - - diff --git a/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.h b/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.h deleted file mode 100644 index 63ff82f..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_MAC - -#import -#import "../../CCDirector.h" - -@class CCEventDispatcher; - -enum { - /// If the window is resized, it won't be autoscaled - kCCDirectorResize_NoScale, - /// If the window is resized, it will be autoscaled (default behavior) - kCCDirectorResize_AutoScale, -}; - -@interface CCDirector (MacExtension) -/** sets the CCEventDispatcher (Mac only) */ -@property (nonatomic, readwrite, retain) CCEventDispatcher* eventDispatcher; - -/** converts an NSEvent to GL coordinates (Mac only) */ --(CGPoint) convertEventToGL:(NSEvent*)event; -@end - -/** Base class of Mac directors - @since v0.99.5 - */ -@interface CCDirectorMac : CCDirector -{ - BOOL isFullScreen_; - int resizeMode_; - CGPoint winOffset_; - CGSize originalWinSize_; - - NSWindow *fullScreenWindow_; - - // Event Dispatcher - CCEventDispatcher *eventDispatcher_; - - // cache - NSWindow *windowGLView_; - NSView *superViewGLView_; - NSRect originalWinRect_; // Original size and position -} - -// whether or not the view is in fullscreen mode -@property (nonatomic, readonly) BOOL isFullScreen; - -// resize mode: with or without scaling -@property (nonatomic, readwrite) int resizeMode; - -@property (nonatomic, readwrite) CGSize originalWinSize; - -/** Sets the view in fullscreen or window mode */ -- (void) setFullScreen:(BOOL)fullscreen; - -/** Converts window size coordiantes to logical coordinates. - Useful only if resizeMode is kCCDirectorResize_Scale. - If resizeMode is kCCDirectorResize_NoScale, then no conversion will be done. -*/ -- (CGPoint) convertToLogicalCoordinates:(CGPoint)coordinates; -@end - - -/** DisplayLinkDirector is a Director that synchronizes timers with the refresh rate of the display. - * - * Features and Limitations: - * - Only available on 3.1+ - * - Scheduled timers & drawing are synchronizes with the refresh rate of the display - * - Only supports animation intervals of 1/60 1/30 & 1/15 - * - * It is the recommended Director if the SDK is 3.1 or newer - * - * @since v0.8.2 - */ -@interface CCDirectorDisplayLink : CCDirectorMac -{ - CVDisplayLinkRef displayLink; -} -@end - -#endif // __CC_PLATFORM_MAC - diff --git a/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.m b/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.m deleted file mode 100644 index 0f14edc..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/CCDirectorMac.m +++ /dev/null @@ -1,555 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_MAC - -#import - -#import "CCDirectorMac.h" -#import "CCEventDispatcher.h" -#import "CCGLView.h" -#import "CCWindow.h" - -#import "../../CCNode.h" -#import "../../CCScheduler.h" -#import "../../ccMacros.h" -#import "../../CCGLProgram.h" -#import "../../ccGLStateCache.h" - -// external -#import "kazmath/kazmath.h" -#import "kazmath/GL/matrix.h" - -#pragma mark - -#pragma mark Director Mac extensions - - -@interface CCDirector () --(void) setNextScene; --(void) showStats; --(void) calculateDeltaTime; --(void) calculateMPF; -@end - -@implementation CCDirector (MacExtension) --(CGPoint) convertEventToGL:(NSEvent*)event -{ - NSPoint point = [[self view] convertPoint:[event locationInWindow] fromView:nil]; - CGPoint p = NSPointToCGPoint(point); - - return [(CCDirectorMac*)self convertToLogicalCoordinates:p]; -} - --(void) setEventDispatcher:(CCEventDispatcher *)dispatcher -{ - NSAssert(NO, @"override me"); -} - --(CCEventDispatcher *) eventDispatcher -{ - NSAssert(NO, @"override me"); - return nil; -} -@end - -#pragma mark - -#pragma mark Director Mac - -@implementation CCDirectorMac - -@synthesize isFullScreen = isFullScreen_; -@synthesize originalWinSize = originalWinSize_; - --(id) init -{ - if( (self = [super init]) ) { - isFullScreen_ = NO; - resizeMode_ = kCCDirectorResize_AutoScale; - - originalWinSize_ = CGSizeZero; - fullScreenWindow_ = nil; - windowGLView_ = nil; - winOffset_ = CGPointZero; - - eventDispatcher_ = [[CCEventDispatcher alloc] init]; - } - - return self; -} - -- (void) dealloc -{ - [eventDispatcher_ release]; - [view_ release]; - [superViewGLView_ release]; - [fullScreenWindow_ release]; - [windowGLView_ release]; - - [super dealloc]; -} - -// -// setFullScreen code taken from GLFullScreen example by Apple -// -- (void) setFullScreen:(BOOL)fullscreen -{ - // Mac OS X 10.6 and later offer a simplified mechanism to create full-screen contexts -#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 - - if (isFullScreen_ == fullscreen) - return; - - CCGLView *openGLview = (CCGLView*) self.view; - - if( fullscreen ) { - originalWinRect_ = [openGLview frame]; - - // Cache normal window and superview of openGLView - if(!windowGLView_) - windowGLView_ = [[openGLview window] retain]; - - [superViewGLView_ release]; - superViewGLView_ = [[openGLview superview] retain]; - - - // Get screen size - NSRect displayRect = [[NSScreen mainScreen] frame]; - - // Create a screen-sized window on the display you want to take over - fullScreenWindow_ = [[CCWindow alloc] initWithFrame:displayRect fullscreen:YES]; - - // Remove glView from window - [openGLview removeFromSuperview]; - - // Set new frame - [openGLview setFrame:displayRect]; - - // Attach glView to fullscreen window - [fullScreenWindow_ setContentView:openGLview]; - - // Show the fullscreen window - [fullScreenWindow_ makeKeyAndOrderFront:self]; - [fullScreenWindow_ makeMainWindow]; - - } else { - - // Remove glView from fullscreen window - [openGLview removeFromSuperview]; - - // Release fullscreen window - [fullScreenWindow_ release]; - fullScreenWindow_ = nil; - - // Attach glView to superview - [superViewGLView_ addSubview:openGLview]; - - // Set new frame - [openGLview setFrame:originalWinRect_]; - - // Show the window - [windowGLView_ makeKeyAndOrderFront:self]; - [windowGLView_ makeMainWindow]; - } - - // issue #1189 - [windowGLView_ makeFirstResponder:openGLview]; - - isFullScreen_ = fullscreen; - - [openGLview retain]; // Retain +1 - - // re-configure glView - [self setView:openGLview]; - - [openGLview release]; // Retain -1 - - [openGLview setNeedsDisplay:YES]; -#else -#error Full screen is not supported for Mac OS 10.5 or older yet -#error If you don't want FullScreen support, you can safely remove these 2 lines -#endif -} - --(void) setView:(CCGLView *)view -{ - if( view != view_) { - - [super setView:view]; - - // cache the NSWindow and NSOpenGLView created from the NIB - if( !isFullScreen_ && CGSizeEqualToSize(originalWinSize_, CGSizeZero)) - { - originalWinSize_ = winSizeInPixels_; - } - } -} - --(int) resizeMode -{ - return resizeMode_; -} - --(void) setResizeMode:(int)mode -{ - if( mode != resizeMode_ ) { - - resizeMode_ = mode; - - [self setProjection:projection_]; - [self.view setNeedsDisplay: YES]; - } -} - --(void) setProjection:(ccDirectorProjection)projection -{ - CGSize size = winSizeInPixels_; - - CGPoint offset = CGPointZero; - float widthAspect = size.width; - float heightAspect = size.height; - - - if( resizeMode_ == kCCDirectorResize_AutoScale && ! CGSizeEqualToSize(originalWinSize_, CGSizeZero ) ) { - - size = originalWinSize_; - - float aspect = originalWinSize_.width / originalWinSize_.height; - widthAspect = winSizeInPixels_.width; - heightAspect = winSizeInPixels_.width / aspect; - - if( heightAspect > winSizeInPixels_.height ) { - widthAspect = winSizeInPixels_.height * aspect; - heightAspect = winSizeInPixels_.height; - } - - winOffset_.x = (winSizeInPixels_.width - widthAspect) / 2; - winOffset_.y = (winSizeInPixels_.height - heightAspect) / 2; - - offset = winOffset_; - - } - - switch (projection) { - case kCCDirectorProjection2D: - - glViewport(offset.x, offset.y, widthAspect, heightAspect); - kmGLMatrixMode(KM_GL_PROJECTION); - kmGLLoadIdentity(); - - kmMat4 orthoMatrix; - kmMat4OrthographicProjection(&orthoMatrix, 0, size.width, 0, size.height, -1024, 1024); - kmGLMultMatrix( &orthoMatrix ); - - kmGLMatrixMode(KM_GL_MODELVIEW); - kmGLLoadIdentity(); - break; - - - case kCCDirectorProjection3D: - { - - float zeye = [self getZEye]; - - glViewport(offset.x, offset.y, widthAspect, heightAspect); - kmGLMatrixMode(KM_GL_PROJECTION); - kmGLLoadIdentity(); - - kmMat4 matrixPerspective, matrixLookup; - - // issue #1334 - kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, MAX(zeye*2,1500) ); -// kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, 1500); - - - kmGLMultMatrix(&matrixPerspective); - - - kmGLMatrixMode(KM_GL_MODELVIEW); - kmGLLoadIdentity(); - kmVec3 eye, center, up; - - float eyeZ = size.height * zeye / winSizeInPixels_.height; - - kmVec3Fill( &eye, size.width/2, size.height/2, eyeZ ); - kmVec3Fill( ¢er, size.width/2, size.height/2, 0 ); - kmVec3Fill( &up, 0, 1, 0); - kmMat4LookAt(&matrixLookup, &eye, ¢er, &up); - kmGLMultMatrix(&matrixLookup); - break; - } - - case kCCDirectorProjectionCustom: - if( [delegate_ respondsToSelector:@selector(updateProjection)] ) - [delegate_ updateProjection]; - break; - - default: - CCLOG(@"cocos2d: Director: unrecognized projection"); - break; - } - - projection_ = projection; - - ccSetProjectionMatrixDirty(); -} - - -// If scaling is supported, then it should always return the original size -// otherwise it should return the "real" size. --(CGSize) winSize -{ - if( resizeMode_ == kCCDirectorResize_AutoScale ) - return originalWinSize_; - - return winSizeInPixels_; -} - --(CGSize) winSizeInPixels -{ - return [self winSize]; -} - -- (CGPoint) convertToLogicalCoordinates:(CGPoint)coords -{ - CGPoint ret; - - if( resizeMode_ == kCCDirectorResize_NoScale ) - ret = coords; - - else { - - float x_diff = originalWinSize_.width / (winSizeInPixels_.width - winOffset_.x * 2); - float y_diff = originalWinSize_.height / (winSizeInPixels_.height - winOffset_.y * 2); - - float adjust_x = (winSizeInPixels_.width * x_diff - originalWinSize_.width ) / 2; - float adjust_y = (winSizeInPixels_.height * y_diff - originalWinSize_.height ) / 2; - - ret = CGPointMake( (x_diff * coords.x) - adjust_x, ( y_diff * coords.y ) - adjust_y ); - } - - return ret; -} - --(void) setEventDispatcher:(CCEventDispatcher *)dispatcher -{ - if( dispatcher != eventDispatcher_ ) { - [eventDispatcher_ release]; - eventDispatcher_ = [dispatcher retain]; - } -} - --(CCEventDispatcher *) eventDispatcher -{ - return eventDispatcher_; -} -@end - - -#pragma mark - -#pragma mark DirectorDisplayLink - - -@implementation CCDirectorDisplayLink - -- (CVReturn) getFrameForTime:(const CVTimeStamp*)outputTime -{ -#if (CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_DISPLAY_LINK_THREAD) - if( ! runningThread_ ) - runningThread_ = [NSThread currentThread]; - - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - [self drawScene]; - - // Process timers and other events - [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:nil]; - - [pool release]; - -#else - [self performSelector:@selector(drawScene) onThread:runningThread_ withObject:nil waitUntilDone:YES]; -#endif - - return kCVReturnSuccess; -} - -// This is the renderer output callback function -static CVReturn MyDisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* now, const CVTimeStamp* outputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext) -{ - CVReturn result = [(CCDirectorDisplayLink*)displayLinkContext getFrameForTime:outputTime]; - return result; -} - -- (void) startAnimation -{ - CCLOG(@"cocos2d: startAnimation"); -#if (CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_OWN_THREAD) - runningThread_ = [[NSThread alloc] initWithTarget:self selector:@selector(mainLoop) object:nil]; - [runningThread_ start]; -#elif (CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_MAIN_THREAD) - runningThread_ = [NSThread mainThread]; -#endif - - gettimeofday( &lastUpdate_, NULL); - - // Create a display link capable of being used with all active displays - CVDisplayLinkCreateWithActiveCGDisplays(&displayLink); - - // Set the renderer output callback function - CVDisplayLinkSetOutputCallback(displayLink, &MyDisplayLinkCallback, self); - - // Set the display link for the current renderer - CCGLView *openGLview = (CCGLView*) self.view; - CGLContextObj cglContext = [[openGLview openGLContext] CGLContextObj]; - CGLPixelFormatObj cglPixelFormat = [[openGLview pixelFormat] CGLPixelFormatObj]; - CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, cglContext, cglPixelFormat); - - // Activate the display link - CVDisplayLinkStart(displayLink); -} - -- (void) stopAnimation -{ - CCLOG(@"cocos2d: stopAnimation"); - - if( displayLink ) { - CVDisplayLinkStop(displayLink); - CVDisplayLinkRelease(displayLink); - displayLink = NULL; - -#if CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_OWN_THREAD - [runningThread_ cancel]; - [runningThread_ release]; - runningThread_ = nil; -#elif (CC_DIRECTOR_MAC_THREAD == CC_MAC_USE_MAIN_THREAD) - runningThread_ = nil; -#endif - } -} - --(void) dealloc -{ - if( displayLink ) { - CVDisplayLinkStop(displayLink); - CVDisplayLinkRelease(displayLink); - } - [super dealloc]; -} - -// -// Mac Director has its own thread -// --(void) mainLoop -{ - while( ![[NSThread currentThread] isCancelled] ) { - // There is no autorelease pool when this method is called because it will be called from a background thread - // It's important to create one or you will leak objects - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - [[NSRunLoop currentRunLoop] run]; - - [pool release]; - } -} - -// -// Draw the Scene -// -- (void) drawScene -{ - /* calculate "global" dt */ - [self calculateDeltaTime]; - - // We draw on a secondary thread through the display link - // When resizing the view, -reshape is called automatically on the main thread - // Add a mutex around to avoid the threads accessing the context simultaneously when resizing - - [self.view lockOpenGLContext]; - - /* tick before glClear: issue #533 */ - if( ! isPaused_ ) - [scheduler_ update: dt]; - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - /* to avoid flickr, nextScene MUST be here: after tick and before draw. - XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */ - if( nextScene_ ) - [self setNextScene]; - - kmGLPushMatrix(); - - - /* draw the scene */ - [runningScene_ visit]; - - /* draw the notification node */ - [notificationNode_ visit]; - - if( displayStats_ ) - [self showStats]; - - kmGLPopMatrix(); - - totalFrames_++; - - - // flush buffer - [self.view.openGLContext flushBuffer]; - - [self.view unlockOpenGLContext]; - - if( displayStats_ ) - [self calculateMPF]; -} - -// set the event dispatcher --(void) setView:(CCGLView *)view -{ - [super setView:view]; - - [view setEventDelegate:eventDispatcher_]; - [eventDispatcher_ setDispatchEvents: YES]; - - // Enable Touches. Default no. - // Only available on OS X 10.6+ -#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 - [view setAcceptsTouchEvents:NO]; -// [view setAcceptsTouchEvents:YES]; -#endif - - - // Synchronize buffer swaps with vertical refresh rate - [[view openGLContext] makeCurrentContext]; - GLint swapInt = 1; - [[view openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; -} - -@end - -#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.h b/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.h deleted file mode 100644 index fb114bc..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.h +++ /dev/null @@ -1,283 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_MAC - -#import - -#import "CCGLView.h" -#import "../../Support/uthash.h" // hack: uthash needs to be imported before utlist to prevent warning -#import "../../Support/utlist.h" -#import "../../ccConfig.h" - -#pragma mark - -#pragma mark CCMouseEventDelegate - -/** CCMouseEventDelegate protocol. - Implement it in your node to receive any of mouse events - */ -@protocol CCMouseEventDelegate -@optional - -// -// left -// -/** called when the "mouseDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccMouseDown:(NSEvent*)event; - -/** called when the "mouseDragged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccMouseDragged:(NSEvent*)event; - -/** called when the "mouseMoved" event is received. - Return YES to avoid propagating the event to other delegates. - By default, "mouseMoved" is disabled. To enable it, send the "setAcceptsMouseMovedEvents:YES" message to the main window. - */ --(BOOL) ccMouseMoved:(NSEvent*)event; - -/** called when the "mouseUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccMouseUp:(NSEvent*)event; - - -// -// right -// - -/** called when the "rightMouseDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccRightMouseDown:(NSEvent*)event; - -/** called when the "rightMouseDragged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccRightMouseDragged:(NSEvent*)event; - -/** called when the "rightMouseUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccRightMouseUp:(NSEvent*)event; - -// -// other -// - -/** called when the "otherMouseDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccOtherMouseDown:(NSEvent*)event; - -/** called when the "otherMouseDragged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccOtherMouseDragged:(NSEvent*)event; - -/** called when the "otherMouseUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccOtherMouseUp:(NSEvent*)event; - -// -// scroll wheel -// - -/** called when the "scrollWheel" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccScrollWheel:(NSEvent *)theEvent; - - -// -// enter / exit -// - -/** called when the "mouseEntered" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (void)ccMouseEntered:(NSEvent *)theEvent; - -/** called when the "mouseExited" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (void)ccMouseExited:(NSEvent *)theEvent; - -@end - -#pragma mark - -#pragma mark CCKeyboardEventDelegate - -/** CCKeyboardEventDelegate protocol. - Implement it in your node to receive any of keyboard events - */ -@protocol CCKeyboardEventDelegate -@optional -/** called when the "keyUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccKeyUp:(NSEvent*)event; - -/** called when the "keyDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccKeyDown:(NSEvent*)event; -/** called when the "flagsChanged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccFlagsChanged:(NSEvent*)event; -@end - -#pragma mark - -#pragma mark CCTouchEventDelegate - -/** CCTouchEventDelegate protocol. - Implement it in your node to receive any of touch events - */ -@protocol CCTouchEventDelegate -@optional -/** called when the "touchesBegan" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesBeganWithEvent:(NSEvent *)event; - -/** called when the "touchesMoved" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesMovedWithEvent:(NSEvent *)event; - -/** called when the "touchesEnded" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesEndedWithEvent:(NSEvent *)event; - -/** called when the "touchesCancelled" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesCancelledWithEvent:(NSEvent *)event; - -@end - -#pragma mark - CCEventObject - -@interface CCEventObject : NSObject -{ -@public - NSEvent *event; - SEL selector; -} -@end - -#pragma mark - CCEventDispatcher - -struct _listEntry; -struct _listDeletedEntry; -struct _listAddedEntry; - -/** CCEventDispatcher - - This is object is responsible for dispatching the events: - - Mouse events - - Keyboard events - - Touch events - - Only available on Mac - */ -@interface CCEventDispatcher : NSObject { - - BOOL dispatchEvents_; - BOOL dispatchingInProgress_; - - struct _listEntry *keyboardDelegates_; - struct _listEntry *mouseDelegates_; - struct _listEntry *touchDelegates_; - - struct _listDeletedEntry *delegatesToBeRemoved_; - struct _listAddedEntry *delegatesToBeAdded_; - -} - -@property (nonatomic, readwrite) BOOL dispatchEvents; - -#pragma mark CCEventDispatcher - Mouse - -/** Adds a mouse delegate to the dispatcher's list. - Delegates with a lower priority value will be called before higher priority values. - All the events will be propgated to all the delegates, unless the one delegate returns YES. - - IMPORTANT: The delegate will be retained. - */ --(void) addMouseDelegate:(id) delegate priority:(NSInteger)priority; - -/** removes a mouse delegate */ --(void) removeMouseDelegate:(id) delegate; - -/** Removes all mouse delegates, releasing all the delegates */ --(void) removeAllMouseDelegates; - -#pragma mark CCEventDispatcher - Keyboard - -/** Adds a Keyboard delegate to the dispatcher's list. - Delegates with a lower priority value will be called before higher priority values. - All the events will be propgated to all the delegates, unless the one delegate returns YES. - - IMPORTANT: The delegate will be retained. - */ --(void) addKeyboardDelegate:(id) delegate priority:(NSInteger)priority; - -/** removes a mouse delegate */ --(void) removeKeyboardDelegate:(id) delegate; - -/** Removes all mouse delegates, releasing all the delegates */ --(void) removeAllKeyboardDelegates; - -#pragma mark CCEventDispatcher - Touches - -/** Adds a Touch delegate to the dispatcher's list. - Delegates with a lower priority value will be called before higher priority values. - All the events will be propgated to all the delegates, unless the one delegate returns YES. - - IMPORTANT: The delegate will be retained. - */ -- (void)addTouchDelegate:(id)delegate priority:(NSInteger)priority; - -/** Removes a touch delegate */ -- (void)removeTouchDelegate:(id) delegate; - -/** Removes all touch delegates, releasing all the delegates */ -- (void)removeAllTouchDelegates; - --(void) dispatchEvent:(CCEventObject*)event; - -@end - - -#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.m b/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.m deleted file mode 100644 index b279174..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/CCEventDispatcher.m +++ /dev/null @@ -1,694 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_MAC - -#import "CCEventDispatcher.h" -#import "../../CCDirector.h" -#import "../../ccConfig.h" - -enum { - // mouse - kCCImplementsMouseDown = 1 << 0, - kCCImplementsMouseMoved = 1 << 1, - kCCImplementsMouseDragged = 1 << 2, - kCCImplementsMouseUp = 1 << 3, - kCCImplementsRightMouseDown = 1 << 4, - kCCImplementsRightMouseDragged = 1 << 5, - kCCImplementsRightMouseUp = 1 << 6, - kCCImplementsOtherMouseDown = 1 << 7, - kCCImplementsOtherMouseDragged = 1 << 8, - kCCImplementsOtherMouseUp = 1 << 9, - kCCImplementsScrollWheel = 1 << 10, - kCCImplementsMouseEntered = 1 << 11, - kCCImplementsMouseExited = 1 << 12, - - kCCImplementsTouchesBegan = 1 << 13, - kCCImplementsTouchesMoved = 1 << 14, - kCCImplementsTouchesEnded = 1 << 15, - kCCImplementsTouchesCancelled = 1 << 16, - - // keyboard - kCCImplementsKeyUp = 1 << 0, - kCCImplementsKeyDown = 1 << 1, - kCCImplementsFlagsChanged = 1 << 2, -}; - - -typedef struct _listEntry -{ - struct _listEntry *prev, *next; - id delegate; - NSInteger priority; - NSUInteger flags; -} tListEntry; - -typedef struct _listDeletedEntry -{ - struct _listDeletedEntry *prev, *next; - id delegate; - struct _listEntry **listToBeDeleted; - -} tListDeletedEntry; - -typedef struct _listAddedEntry -{ - struct _listAddedEntry *prev, *next; - id delegate; - NSInteger priority; - NSUInteger flags; - struct _listEntry **listToBeAdded; -} tListAddedEntry; - - - -#pragma mark - CCEventObject - -@implementation CCEventObject -@end - -#pragma mark - CCEventDispatcher - -@implementation CCEventDispatcher - -@synthesize dispatchEvents=dispatchEvents_; - --(id) init -{ - if( (self = [super init]) ) - { - // events enabled by default - dispatchEvents_ = YES; - - // delegates - keyboardDelegates_ = NULL; - mouseDelegates_ = NULL; - touchDelegates_ = NULL; - - delegatesToBeAdded_ = NULL; - delegatesToBeRemoved_ = NULL; - - dispatchingInProgress_ = NO; - } - - return self; -} - -- (void) dealloc -{ - [super dealloc]; -} - -#pragma mark CCEventDispatcher - add / remove delegates --(void) addLaterDelegate:(id)delegate priority:(NSInteger)priority flags:(NSUInteger)flags list:(tListEntry**)list -{ - tListAddedEntry *listElement = malloc( sizeof(*listElement) ); - - listElement->delegate = [delegate retain]; - listElement->priority = priority; - listElement->flags = flags; - listElement->listToBeAdded = list; - listElement->next = listElement->prev = NULL; - - DL_APPEND( delegatesToBeAdded_, listElement ); -} - --(void) addDelegate:(id)delegate priority:(NSInteger)priority flags:(NSUInteger)flags list:(tListEntry**)list -{ - tListEntry *listElement = malloc( sizeof(*listElement) ); - - listElement->delegate = [delegate retain]; - listElement->priority = priority; - listElement->flags = flags; - listElement->next = listElement->prev = NULL; - - // empty list ? - if( ! *list ) { - DL_APPEND( *list, listElement ); - - } else { - BOOL added = NO; - - for( tListEntry *elem = *list; elem ; elem = elem->next ) { - if( priority < elem->priority ) { - - if( elem == *list ) - DL_PREPEND(*list, listElement); - else { - listElement->next = elem; - listElement->prev = elem->prev; - - elem->prev->next = listElement; - elem->prev = listElement; - } - - added = YES; - break; - } - } - - // Not added? priority has the higher value. Append it. - if( !added ) - DL_APPEND(*list, listElement); - } -} - --(void) removeLaterDelegate:(id)delegate fromList:(tListEntry**)list -{ - tListDeletedEntry *listElement = malloc( sizeof(*listElement) ); - - listElement->delegate = [delegate retain]; - listElement->listToBeDeleted = list; - listElement->next = listElement->prev = NULL; - - DL_APPEND( delegatesToBeRemoved_, listElement ); -} - --(void) removeDelegate:(id)delegate fromList:(tListEntry**)list -{ - tListEntry *entry, *tmp; - - // updates with priority < 0 - DL_FOREACH_SAFE( *list, entry, tmp ) { - if( entry->delegate == delegate ) { - DL_DELETE( *list, entry ); - [delegate release]; - free(entry); - break; - } - } -} - --(void) removeAllDelegatesFromList:(tListEntry**)list -{ - NSAssert( ! dispatchingInProgress_, @"BUG. Open a ticket. Can't call this function when processing events."); - - @synchronized(self) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( *list, entry, tmp ) { - DL_DELETE( *list, entry ); - [entry->delegate release]; - free(entry); - } - } -} - - --(void) addMouseDelegate:(id) delegate priority:(NSInteger)priority -{ - NSUInteger flags = 0; - - flags |= ( [delegate respondsToSelector:@selector(ccMouseDown:)] ? kCCImplementsMouseDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseDragged:)] ? kCCImplementsMouseDragged : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseMoved:)] ? kCCImplementsMouseMoved : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseUp:)] ? kCCImplementsMouseUp : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccRightMouseDown:)] ? kCCImplementsRightMouseDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccRightMouseDragged:)] ? kCCImplementsRightMouseDragged : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccRightMouseUp:)] ? kCCImplementsRightMouseUp : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseDown:)] ? kCCImplementsOtherMouseDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseDragged:)] ? kCCImplementsOtherMouseDragged : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseUp:)] ? kCCImplementsOtherMouseUp : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccMouseEntered:)] ? kCCImplementsMouseEntered : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseExited:)] ? kCCImplementsMouseExited : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccScrollWheel:)] ? kCCImplementsScrollWheel : 0 ); - - if( dispatchingInProgress_ ) - [self addLaterDelegate:delegate priority:priority flags:flags list:&mouseDelegates_]; - else - [self addDelegate:delegate priority:priority flags:flags list:&mouseDelegates_]; - -} - --(void) removeMouseDelegate:(id) delegate -{ - if( dispatchingInProgress_ ) - [self removeLaterDelegate:delegate fromList:&mouseDelegates_]; - else - [self removeDelegate:delegate fromList:&mouseDelegates_]; -} - --(void) removeAllMouseDelegates -{ - [self removeAllDelegatesFromList:&mouseDelegates_]; -} - --(void) addKeyboardDelegate:(id) delegate priority:(NSInteger)priority -{ - NSUInteger flags = 0; - - flags |= ( [delegate respondsToSelector:@selector(ccKeyUp:)] ? kCCImplementsKeyUp : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccKeyDown:)] ? kCCImplementsKeyDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccFlagsChanged:)] ? kCCImplementsFlagsChanged : 0 ); - - if( dispatchingInProgress_ ) - [self addLaterDelegate:delegate priority:priority flags:flags list:&keyboardDelegates_]; - else - [self addDelegate:delegate priority:priority flags:flags list:&keyboardDelegates_]; -} - --(void) removeKeyboardDelegate:(id) delegate -{ - if( dispatchingInProgress_ ) - [self removeLaterDelegate:delegate fromList:&keyboardDelegates_]; - else - [self removeDelegate:delegate fromList:&keyboardDelegates_]; -} - --(void) removeAllKeyboardDelegates -{ - [self removeAllDelegatesFromList:&keyboardDelegates_]; -} - --(void) addTouchDelegate:(id) delegate priority:(NSInteger)priority -{ - NSUInteger flags = 0; - - flags |= ( [delegate respondsToSelector:@selector(ccTouchesBeganWithEvent:)] ? kCCImplementsTouchesBegan : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccTouchesMovedWithEvent:)] ? kCCImplementsTouchesMoved : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccTouchesEndedWithEvent:)] ? kCCImplementsTouchesEnded : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccTouchesCancelledWithEvent:)] ? kCCImplementsTouchesCancelled : 0 ); - - if( dispatchingInProgress_ ) - [self addLaterDelegate:delegate priority:priority flags:flags list:&touchDelegates_]; - else - [self addDelegate:delegate priority:priority flags:flags list:&touchDelegates_]; -} - --(void) removeTouchDelegate:(id) delegate -{ - if( dispatchingInProgress_ ) - [self removeLaterDelegate:delegate fromList:&touchDelegates_]; - else - [self removeDelegate:delegate fromList:&touchDelegates_]; -} - --(void) removeAllTouchDelegates -{ - [self removeAllDelegatesFromList:&touchDelegates_]; -} - - -#pragma mark CCEventDispatcher - Mouse events -// -// Mouse events -// - -// -// Left -// -- (void)mouseDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsMouseDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseMoved:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsMouseMoved ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseMoved:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseDragged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsMouseDragged ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseDragged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseUp:(NSEvent *)event -{ - @synchronized(self) { - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseUp:) withObject:event]; - if( swallows ) - break; - } - } - } - } -} - -// -// Mouse Right -// -- (void)rightMouseDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsRightMouseDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)rightMouseDragged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsRightMouseDragged ) { - void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDragged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)rightMouseUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsRightMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccRightMouseUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Mouse Other -// -- (void)otherMouseDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsOtherMouseDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)otherMouseDragged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsOtherMouseDragged ) { - void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDragged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)otherMouseUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsOtherMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Scroll Wheel -// -- (void)scrollWheel:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsScrollWheel ) { - void *swallows = [entry->delegate performSelector:@selector(ccScrollWheel:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Mouse enter / exit -- (void)mouseExited:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsMouseEntered ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseEntered:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseEntered:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsMouseExited) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseExited:) withObject:event]; - if( swallows ) - break; - } - } - } -} - - -#pragma mark CCEventDispatcher - Keyboard events - -// Keyboard events -- (void)keyDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsKeyDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccKeyDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)keyUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsKeyUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccKeyUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)flagsChanged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsFlagsChanged ) { - void *swallows = [entry->delegate performSelector:@selector(ccFlagsChanged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - - -#pragma mark CCEventDispatcher - Touch events - -- (void)touchesBeganWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsTouchesBegan) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesBeganWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)touchesMovedWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsTouchesMoved) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesMovedWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)touchesEndedWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsTouchesEnded) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesEndedWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)touchesCancelledWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kCCImplementsTouchesCancelled) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesCancelledWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)dispatchEvent:(CCEventObject*)e -{ - @synchronized(self) - { - NSEvent *event = e->event; - SEL selector = e->selector; - - // Dispatch events - if( dispatchEvents_ ) { - dispatchingInProgress_ = YES; - [self performSelector:selector onThread:[[CCDirector sharedDirector] runningThread] withObject:event waitUntilDone:YES]; - dispatchingInProgress_ = NO; - } - - - [event release]; - - // Remove possible delegates - tListDeletedEntry *dEntry, *tTmp; - DL_FOREACH_SAFE( delegatesToBeRemoved_ , dEntry, tTmp ) { - - [self removeDelegate:dEntry->delegate fromList:dEntry->listToBeDeleted]; - - DL_DELETE( delegatesToBeRemoved_, dEntry ); - [dEntry->delegate release]; - free(dEntry); - } - - // Add possible delegates - tListAddedEntry *entry, *tmp; - - DL_FOREACH_SAFE( delegatesToBeAdded_, entry, tmp ) { - - [self addDelegate:entry->delegate priority:entry->priority flags:entry->flags list:entry->listToBeAdded]; - - DL_DELETE( delegatesToBeAdded_, entry ); - [entry->delegate release]; - free(entry); - } - - } -} - -@end - -#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCGLView.h b/Example/libs/cocos2d/Platforms/Mac/CCGLView.h deleted file mode 100644 index c178ac8..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/CCGLView.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_MAC - -#import - -#import "../../ccConfig.h" - -//PROTOCOLS: - -@protocol CCEventDelegate -// Mouse -- (void)mouseDown:(NSEvent *)theEvent; -- (void)mouseUp:(NSEvent *)theEvent; -- (void)mouseMoved:(NSEvent *)theEvent; -- (void)mouseDragged:(NSEvent *)theEvent; -- (void)rightMouseDown:(NSEvent*)event; -- (void)rightMouseDragged:(NSEvent*)event; -- (void)rightMouseUp:(NSEvent*)event; -- (void)otherMouseDown:(NSEvent*)event; -- (void)otherMouseDragged:(NSEvent*)event; -- (void)otherMouseUp:(NSEvent*)event; -- (void)scrollWheel:(NSEvent *)theEvent; -- (void)mouseEntered:(NSEvent *)theEvent; -- (void)mouseExited:(NSEvent *)theEvent; - - -// Keyboard -- (void)keyDown:(NSEvent *)theEvent; -- (void)keyUp:(NSEvent *)theEvent; -- (void)flagsChanged:(NSEvent *)theEvent; - -// Touches -- (void)touchesBeganWithEvent:(NSEvent *)event; -- (void)touchesMovedWithEvent:(NSEvent *)event; -- (void)touchesEndedWithEvent:(NSEvent *)event; -- (void)touchesCancelledWithEvent:(NSEvent *)event; - -@end - -/** CCGLView - - Only available for Mac OS X - */ -@interface CCGLView : NSOpenGLView { - id eventDelegate_; -} - -/** Event delegate */ -@property (nonatomic, readwrite, assign) id eventDelegate; - -/** initializes the CCGLView with a frame rect and an OpenGL context */ -- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context; - -/** uses and locks the OpenGL context */ --(void) lockOpenGLContext; - -/** unlocks the openGL context */ --(void) unlockOpenGLContext; - -// private -+(void) load_; -@end - -#endif // __CC_PLATFORM_MAC - diff --git a/Example/libs/cocos2d/Platforms/Mac/CCGLView.m b/Example/libs/cocos2d/Platforms/Mac/CCGLView.m deleted file mode 100644 index 44d56e3..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/CCGLView.m +++ /dev/null @@ -1,287 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* - * Idea of subclassing NSOpenGLView was taken from "TextureUpload" Apple's sample - */ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_MAC - -#import - -#import "CCGLView.h" -#import "CCDirectorMac.h" -#import "CCEventDispatcher.h" -#import "../../ccConfig.h" -#import "../../ccMacros.h" - - -@implementation CCGLView - -@synthesize eventDelegate = eventDelegate_; - -+(void) load_ -{ - CCLOG(@"%@ loaded", self); -} - -- (id) initWithFrame:(NSRect)frameRect -{ - self = [self initWithFrame:frameRect shareContext:nil]; - return self; -} - -- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context -{ - NSOpenGLPixelFormatAttribute attribs[] = - { -// NSOpenGLPFAAccelerated, -// NSOpenGLPFANoRecovery, - NSOpenGLPFADoubleBuffer, - NSOpenGLPFADepthSize, 24, - - // Must specify the 3.2 Core Profile to use OpenGL 3.2 -#if 0 - NSOpenGLPFAOpenGLProfile, - NSOpenGLProfileVersion3_2Core, -#endif - - 0 - }; - - NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; - - if (!pixelFormat) - CCLOG(@"No OpenGL pixel format"); - - if( (self = [super initWithFrame:frameRect pixelFormat:[pixelFormat autorelease]]) ) { - - if( context ) - [self setOpenGLContext:context]; - - // event delegate - eventDelegate_ = nil; - } - - return self; -} - -- (void) update -{ - // XXX: Should I do something here ? - [super update]; -} - -- (void) prepareOpenGL -{ - // XXX: Initialize OpenGL context - - [super prepareOpenGL]; - - // Make this openGL context current to the thread - // (i.e. all openGL on this thread calls will go to this context) - [[self openGLContext] makeCurrentContext]; - - // Synchronize buffer swaps with vertical refresh rate - GLint swapInt = 1; - [[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; - -// GLint order = -1; -// [[self openGLContext] setValues:&order forParameter:NSOpenGLCPSurfaceOrder]; -} - -- (void) reshape -{ - // We draw on a secondary thread through the display link - // When resizing the view, -reshape is called automatically on the main thread - // Add a mutex around to avoid the threads accessing the context simultaneously when resizing - - [self lockOpenGLContext]; - - NSRect rect = [self bounds]; - - CCDirector *director = [CCDirector sharedDirector]; - [director reshapeProjection: NSSizeToCGSize(rect.size) ]; - - // avoid flicker - [director drawScene]; -// [self setNeedsDisplay:YES]; - - [self unlockOpenGLContext]; -} - - --(void) lockOpenGLContext -{ - NSOpenGLContext *glContext = [self openGLContext]; - NSAssert( glContext, @"FATAL: could not get openGL context"); - - [glContext makeCurrentContext]; - CGLLockContext([glContext CGLContextObj]); -} - --(void) unlockOpenGLContext -{ - NSOpenGLContext *glContext = [self openGLContext]; - NSAssert( glContext, @"FATAL: could not get openGL context"); - - CGLUnlockContext([glContext CGLContextObj]); -} - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - [super dealloc]; -} - -#define DISPATCH_EVENT(__event__, __selector__) \ - id obj = eventDelegate_; \ - CCEventObject *event = [[CCEventObject alloc] init]; \ - event->event = [__event__ retain]; \ - event->selector = __selector__; \ - [obj performSelector:@selector(dispatchEvent:) \ - onThread:[[CCDirector sharedDirector] runningThread] \ - withObject:event \ - waitUntilDone:NO]; \ - [event release]; - -#pragma mark CCGLView - Mouse events - -- (void)mouseDown:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseMoved:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseDragged:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseUp:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)rightMouseDown:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)rightMouseDragged:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)rightMouseUp:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)otherMouseDown:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)otherMouseDragged:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)otherMouseUp:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseEntered:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseExited:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - --(void) scrollWheel:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); -} - -#pragma mark CCGLView - Key events - --(BOOL) becomeFirstResponder -{ - return YES; -} - --(BOOL) acceptsFirstResponder -{ - return YES; -} - --(BOOL) resignFirstResponder -{ - return YES; -} - -- (void)keyDown:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)keyUp:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)flagsChanged:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -#pragma mark CCGLView - Touch events -- (void)touchesBeganWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesMovedWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesEndedWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesCancelledWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -@end - -#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCWindow.h b/Example/libs/cocos2d/Platforms/Mac/CCWindow.h deleted file mode 100644 index 7f37d4d..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/CCWindow.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_MAC - -#import - - -@interface CCWindow : NSWindow -{ -} -- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen; - -@end - - -#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/Mac/CCWindow.m b/Example/libs/cocos2d/Platforms/Mac/CCWindow.m deleted file mode 100644 index 8852a20..0000000 --- a/Example/libs/cocos2d/Platforms/Mac/CCWindow.m +++ /dev/null @@ -1,69 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_MAC - -#import "CCWindow.h" - - -@implementation CCWindow - -- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen -{ - int styleMask = fullscreen ? NSBackingStoreBuffered : ( NSTitledWindowMask | NSClosableWindowMask ); - self = [self initWithContentRect:frame - styleMask:styleMask - backing:NSBackingStoreBuffered - defer:YES]; - - if (self != nil) - { - if(fullscreen) - { - [self setLevel:NSMainMenuWindowLevel+1]; - [self setHidesOnDeactivate:YES]; - [self setHasShadow:NO]; - } - - [self setAcceptsMouseMovedEvents:NO]; - [self setOpaque:YES]; - } - return self; -} - -- (BOOL) canBecomeKeyWindow -{ - return YES; -} - -- (BOOL) canBecomeMainWindow -{ - return YES; -} -@end - -#endif // __CC_PLATFORM_MAC diff --git a/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h b/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h deleted file mode 100644 index 871b251..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -#import "../../CCDirector.h" -#import "kazmath/mat4.h" - -@class CCTouchDispatcher; - -/** CCDirector extensions for iPhone - */ -@interface CCDirector (iOSExtension) - -/** sets the CCTouchDispatcher (iOS only) */ -@property (nonatomic,readwrite,retain) CCTouchDispatcher * touchDispatcher; - -/** The size in pixels of the surface. It could be different than the screen size. - High-res devices might have a higher surface size than the screen size. - In non High-res device the contentScale will be emulated. - - The recommend way to enable Retina Display is by using the "enableRetinaDisplay:(BOOL)enabled" method. - - @since v0.99.4 - */ --(void) setContentScaleFactor:(CGFloat)scaleFactor; - -/** Will enable Retina Display on devices that supports it. - It will enable Retina Display on iPhone4 and iPod Touch 4. - It will return YES, if it could enabled it, otherwise it will return NO. - - This is the recommened way to enable Retina Display. - @since v0.99.5 - */ --(BOOL) enableRetinaDisplay:(BOOL)enableRetina; - -/** returns the content scale factor */ --(CGFloat) contentScaleFactor; -@end - -#pragma mark - -#pragma mark CCDirectorIOS - -/** CCDirectorIOS: Base class of iOS directors - @since v0.99.5 - */ -@interface CCDirectorIOS : CCDirector -{ - /* contentScaleFactor could be simulated */ - BOOL isContentScaleSupported_; - - CCTouchDispatcher *touchDispatcher_; -} -@end - -/** DisplayLinkDirector is a Director that synchronizes timers with the refresh rate of the display. - * - * Features and Limitations: - * - Only available on 3.1+ - * - Scheduled timers & drawing are synchronizes with the refresh rate of the display - * - Only supports animation intervals of 1/60 1/30 & 1/15 - * - * It is the recommended Director if the SDK is 3.1 or newer - * - * @since v0.8.2 - */ -@interface CCDirectorDisplayLink : CCDirectorIOS -{ - CADisplayLink *displayLink_; - CFTimeInterval lastDisplayTime_; -} --(void) mainLoop:(id)sender; -@end - -// optimization. Should only be used to read it. Never to write it. -extern CGFloat __ccContentScaleFactor; - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m b/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m deleted file mode 100644 index b39adb4..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m +++ /dev/null @@ -1,552 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -#import - -// cocos2d imports -#import "CCDirectorIOS.h" -#import "CCTouchDelegateProtocol.h" -#import "CCTouchDispatcher.h" -#import "../../CCScheduler.h" -#import "../../CCActionManager.h" -#import "../../CCTextureCache.h" -#import "../../ccMacros.h" -#import "../../CCScene.h" -#import "../../CCGLProgram.h" -#import "../../ccGLStateCache.h" -#import "../../CCLayer.h" - -// support imports -#import "../../Support/OpenGL_Internal.h" -#import "../../Support/CGPointExtension.h" -#import "../../Support/TransformUtils.h" - -#import "kazmath/kazmath.h" -#import "kazmath/GL/matrix.h" - -#if CC_ENABLE_PROFILERS -#import "../../Support/CCProfiling.h" -#endif - - -#pragma mark - -#pragma mark Director - global variables (optimization) - -CGFloat __ccContentScaleFactor = 1; - -#pragma mark - -#pragma mark Director - -@interface CCDirector () --(void) setNextScene; --(void) showStats; --(void) calculateDeltaTime; --(void) calculateMPF; -@end - -@implementation CCDirector (iOSExtensionClassMethods) - -+(Class) defaultDirector -{ - return [CCDirectorDisplayLink class]; -} - --(void) setInterfaceOrientationDelegate:(id)delegate -{ - // override me -} - --(CCTouchDispatcher*) touchDispatcher -{ - return nil; -} - --(void) setTouchDispatcher:(CCTouchDispatcher*)touchDispatcher -{ - // -} -@end - - - -#pragma mark - -#pragma mark CCDirectorIOS - -@interface CCDirectorIOS () --(void) updateContentScaleFactor; -@end - -@implementation CCDirectorIOS - -- (id) init -{ - if( (self=[super init]) ) { - - __ccContentScaleFactor = 1; - isContentScaleSupported_ = NO; - - touchDispatcher_ = [[CCTouchDispatcher alloc] init]; - - // running thread is main thread on iOS - runningThread_ = [NSThread currentThread]; - - // Apparently it comes with a default view, and we don't want it -// [self setView:nil]; - } - - return self; -} - -- (void) dealloc -{ - [touchDispatcher_ release]; - - [super dealloc]; -} - -// -// Draw the Scene -// -- (void) drawScene -{ - /* calculate "global" dt */ - [self calculateDeltaTime]; - - CCGLView *openGLview = (CCGLView*)[self view]; - - [EAGLContext setCurrentContext: [openGLview context]]; - - /* tick before glClear: issue #533 */ - if( ! isPaused_ ) - [scheduler_ update: dt]; - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - /* to avoid flickr, nextScene MUST be here: after tick and before draw. - XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */ - if( nextScene_ ) - [self setNextScene]; - - kmGLPushMatrix(); - - [runningScene_ visit]; - - [notificationNode_ visit]; - - if( displayStats_ ) - [self showStats]; - - kmGLPopMatrix(); - - totalFrames_++; - - [openGLview swapBuffers]; - - if( displayStats_ ) - [self calculateMPF]; -} - --(void) setProjection:(ccDirectorProjection)projection -{ - CGSize size = winSizeInPixels_; - CGSize sizePoint = winSizeInPoints_; - - glViewport(0, 0, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); - - switch (projection) { - case kCCDirectorProjection2D: - - kmGLMatrixMode(KM_GL_PROJECTION); - kmGLLoadIdentity(); - - kmMat4 orthoMatrix; - kmMat4OrthographicProjection(&orthoMatrix, 0, size.width, 0, size.height, -1024, 1024 ); - kmGLMultMatrix( &orthoMatrix ); - - kmGLMatrixMode(KM_GL_MODELVIEW); - kmGLLoadIdentity(); - break; - - case kCCDirectorProjection3D: - { - // reset the viewport if 3d proj & retina display - if( CC_CONTENT_SCALE_FACTOR() != 1 ) - glViewport(-size.width/2, -size.height/2, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); - - float zeye = [self getZEye]; - - kmMat4 matrixPerspective, matrixLookup; - - kmGLMatrixMode(KM_GL_PROJECTION); - kmGLLoadIdentity(); - - // issue #1334 - kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, zeye*2); -// kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, 1500); - - kmGLMultMatrix(&matrixPerspective); - - kmGLMatrixMode(KM_GL_MODELVIEW); - kmGLLoadIdentity(); - kmVec3 eye, center, up; - kmVec3Fill( &eye, sizePoint.width/2, sizePoint.height/2, zeye ); - kmVec3Fill( ¢er, sizePoint.width/2, sizePoint.height/2, 0 ); - kmVec3Fill( &up, 0, 1, 0); - kmMat4LookAt(&matrixLookup, &eye, ¢er, &up); - kmGLMultMatrix(&matrixLookup); - break; - } - - case kCCDirectorProjectionCustom: - if( [delegate_ respondsToSelector:@selector(updateProjection)] ) - [delegate_ updateProjection]; - break; - - default: - CCLOG(@"cocos2d: Director: unrecognized projection"); - break; - } - - projection_ = projection; - - ccSetProjectionMatrixDirty(); -} - -#pragma mark Director - TouchDispatcher - --(CCTouchDispatcher*) touchDispatcher -{ - return touchDispatcher_; -} - --(void) setTouchDispatcher:(CCTouchDispatcher*)touchDispatcher -{ - if( touchDispatcher != touchDispatcher_ ) { - [touchDispatcher_ release]; - touchDispatcher_ = [touchDispatcher retain]; - } -} - -#pragma mark Director - Retina Display - --(CGFloat) contentScaleFactor -{ - return __ccContentScaleFactor; -} - --(void) setContentScaleFactor:(CGFloat)scaleFactor -{ - if( scaleFactor != __ccContentScaleFactor ) { - - __ccContentScaleFactor = scaleFactor; - winSizeInPixels_ = CGSizeMake( winSizeInPoints_.width * scaleFactor, winSizeInPoints_.height * scaleFactor ); - - if( view_ ) - [self updateContentScaleFactor]; - - // update projection - [self setProjection:projection_]; - } -} - --(void) updateContentScaleFactor -{ - NSAssert( [view_ respondsToSelector:@selector(setContentScaleFactor:)], @"cocos2d v2.0+ runs on iOS 4 or later"); - - [view_ setContentScaleFactor: __ccContentScaleFactor]; - isContentScaleSupported_ = YES; -} - --(BOOL) enableRetinaDisplay:(BOOL)enabled -{ - // Already enabled ? - if( enabled && __ccContentScaleFactor == 2 ) - return YES; - - // Already disabled - if( ! enabled && __ccContentScaleFactor == 1 ) - return YES; - - // setContentScaleFactor is not supported - if (! [view_ respondsToSelector:@selector(setContentScaleFactor:)]) - return NO; - - // SD device - if ([[UIScreen mainScreen] scale] == 1.0) - return NO; - - float newScale = enabled ? 2 : 1; - [self setContentScaleFactor:newScale]; - - // Load Hi-Res FPS label - [self createStatsLabel]; - - return YES; -} - -// overriden, don't call super --(void) reshapeProjection:(CGSize)size -{ - winSizeInPoints_ = [view_ bounds].size; - winSizeInPixels_ = CGSizeMake(winSizeInPoints_.width * __ccContentScaleFactor, winSizeInPoints_.height *__ccContentScaleFactor); - - [self setProjection:projection_]; -} - -#pragma mark Director Point Convertion - --(CGPoint)convertToGL:(CGPoint)uiPoint -{ - CGSize s = winSizeInPoints_; - float newY = s.height - uiPoint.y; - - return ccp( uiPoint.x, newY ); -} - --(CGPoint)convertToUI:(CGPoint)glPoint -{ - CGSize winSize = winSizeInPoints_; - int oppositeY = winSize.height - glPoint.y; - - return ccp(glPoint.x, oppositeY); -} - --(void) end -{ - // don't release the event handlers - // They are needed in case the director is run again - [touchDispatcher_ removeAllDelegates]; - - [super end]; -} - -#pragma mark Director - UIViewController delegate - - --(void) setView:(CCGLView *)view -{ - if( view != view_) { - [super setView:view]; - - // set size - winSizeInPixels_ = CGSizeMake(winSizeInPoints_.width * __ccContentScaleFactor, winSizeInPoints_.height *__ccContentScaleFactor); - - if( __ccContentScaleFactor != 1 ) - [self updateContentScaleFactor]; - - [view setTouchDelegate: touchDispatcher_]; - [touchDispatcher_ setDispatchEvents: YES]; - } -} - -// Override to allow orientations other than the default portrait orientation. -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation -{ - BOOL ret =YES; - if( [delegate_ respondsToSelector:_cmd] ) - ret = (BOOL) [delegate_ shouldAutorotateToInterfaceOrientation:interfaceOrientation]; - - return ret; -} - --(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration -{ - // do something ? -} - - --(void) viewWillAppear:(BOOL)animated -{ - [super viewWillAppear:animated]; - [self startAnimation]; -} - --(void) viewDidAppear:(BOOL)animated -{ - [super viewDidAppear:animated]; -// [self startAnimation]; -} - --(void) viewWillDisappear:(BOOL)animated -{ -// [self stopAnimation]; - - [super viewWillDisappear:animated]; -} - --(void) viewDidDisappear:(BOOL)animated -{ - [self stopAnimation]; - - [super viewDidDisappear:animated]; -} - -- (void)didReceiveMemoryWarning -{ - // Release any cached data, images, etc that aren't in use. - [super purgeCachedData]; - - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; -} - --(void) viewDidLoad -{ - CCLOG(@"cocos2d: viewDidLoad"); - - [super viewDidLoad]; -} - - -- (void)viewDidUnload -{ - CCLOG(@"cocos2d: viewDidUnload"); - - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} -@end - - -#pragma mark - -#pragma mark DirectorDisplayLink - -@implementation CCDirectorDisplayLink - - --(void) mainLoop:(id)sender -{ - [self drawScene]; -} - -- (void)setAnimationInterval:(NSTimeInterval)interval -{ - animationInterval_ = interval; - if(displayLink_){ - [self stopAnimation]; - [self startAnimation]; - } -} - -- (void) startAnimation -{ - NSAssert( displayLink_ == nil, @"displayLink must be nil. Calling startAnimation twice?"); - - gettimeofday( &lastUpdate_, NULL); - - // approximate frame rate - // assumes device refreshes at 60 fps - int frameInterval = (int) floor(animationInterval_ * 60.0f); - - CCLOG(@"cocos2d: animation started with frame interval: %.2f", 60.0f/frameInterval); - - displayLink_ = [CADisplayLink displayLinkWithTarget:self selector:@selector(mainLoop:)]; - [displayLink_ setFrameInterval:frameInterval]; - -#if CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD - // - runningThread_ = [[NSThread alloc] initWithTarget:self selector:@selector(threadMainLoop) object:nil]; - [runningThread_ start]; - -#else - // setup DisplayLink in main thread - [displayLink_ addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; -#endif - - -} - -- (void) stopAnimation -{ - CCLOG(@"cocos2d: animation stopped"); - -#if CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD - [runningThread_ cancel]; - [runningThread_ release]; - runningThread_ = nil; -#endif - - [displayLink_ invalidate]; - displayLink_ = nil; -} - -// Overriden in order to use a more stable delta time --(void) calculateDeltaTime -{ - // New delta time - if( nextDeltaTimeZero_ ) { - dt = 0; - nextDeltaTimeZero_ = NO; - } else { - dt = displayLink_.timestamp - lastDisplayTime_; - dt = MAX(0,dt); - } - // Store this timestamp for next time - lastDisplayTime_ = displayLink_.timestamp; - - // needed for SPF - if( displayStats_ ) - gettimeofday( &lastUpdate_, NULL); - -#ifdef DEBUG - // If we are debugging our code, prevent big delta time - if( dt > 0.2f ) - dt = 1/60.0f; -#endif -} - - -#pragma mark Director Thread - -// -// Director has its own thread -// --(void) threadMainLoop -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - [displayLink_ addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; - - // start the run loop - [[NSRunLoop currentRunLoop] run]; - - [pool release]; -} - --(void) dealloc -{ - [displayLink_ release]; - [super dealloc]; -} -@end - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.h b/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.h deleted file mode 100644 index 9f6163b..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * File autogenerated with Xcode. Adapted for cocos2d needs. - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -#import "CCESRenderer.h" - -#import -#import - -@interface CCES2Renderer : NSObject -{ - // The pixel dimensions of the CAEAGLLayer - GLint backingWidth_; - GLint backingHeight_; - - unsigned int samplesToUse_; - BOOL multiSampling_; - - unsigned int depthFormat_; - unsigned int pixelFormat_; - - // The OpenGL ES names for the framebuffer and renderbuffer used to render to this view - GLuint defaultFramebuffer_; - GLuint colorRenderbuffer_; - GLuint depthBuffer_; - - - //buffers for MSAA - GLuint msaaFramebuffer_; - GLuint msaaColorbuffer_; - - EAGLContext *context_; -} - -/** Color Renderbuffer */ -@property (nonatomic,readonly) GLuint colorRenderbuffer; - -/** Default Renderbuffer */ -@property (nonatomic,readonly) GLuint defaultFramebuffer; - -/** MSAA Framebuffer */ -@property (nonatomic,readonly) GLuint msaaFramebuffer; - -/** MSAA Color Buffer */ -@property (nonatomic,readonly) GLuint msaaColorbuffer; - -/** EAGLContext */ -@property (nonatomic,readonly) EAGLContext* context; - -- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer; -@end - -#endif // __CC_PLATFORM_IOS - diff --git a/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.m b/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.m deleted file mode 100644 index 5416e5f..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCES2Renderer.m +++ /dev/null @@ -1,248 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * File autogenerated with Xcode. Adapted for cocos2d needs. - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -#import "CCES2Renderer.h" - -#import "../../Support/OpenGL_Internal.h" -#import "../../ccMacros.h" - -@implementation CCES2Renderer - -@synthesize context=context_; -@synthesize defaultFramebuffer=defaultFramebuffer_; -@synthesize colorRenderbuffer=colorRenderbuffer_; -@synthesize msaaColorbuffer=msaaColorbuffer_; -@synthesize msaaFramebuffer=msaaFramebuffer_; - -// Create an OpenGL ES 2.0 context -- (id) initWithDepthFormat:(unsigned int)depthFormat withPixelFormat:(unsigned int)pixelFormat withSharegroup:(EAGLSharegroup*)sharegroup withMultiSampling:(BOOL) multiSampling withNumberOfSamples:(unsigned int) requestedSamples -{ - self = [super init]; - if (self) - { - if( ! sharegroup ) - context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; - else - context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2 sharegroup:sharegroup]; - - if (!context_ || ![EAGLContext setCurrentContext:context_] ) - { - [self release]; - return nil; - } - - depthFormat_ = depthFormat; - pixelFormat_ = pixelFormat; - multiSampling_ = multiSampling; - - // Create default framebuffer object. The backing will be allocated for the current layer in -resizeFromLayer - glGenFramebuffers(1, &defaultFramebuffer_); - NSAssert( defaultFramebuffer_, @"Can't create default frame buffer"); - - glGenRenderbuffers(1, &colorRenderbuffer_); - NSAssert( colorRenderbuffer_, @"Can't create default render buffer"); - - glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer_); - glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer_); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderbuffer_); - - if (multiSampling_) - { - GLint maxSamplesAllowed; - glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamplesAllowed); - samplesToUse_ = MIN(maxSamplesAllowed,requestedSamples); - - /* Create the MSAA framebuffer (offscreen) */ - glGenFramebuffers(1, &msaaFramebuffer_); - NSAssert( msaaFramebuffer_, @"Can't create default MSAA frame buffer"); - glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer_); - - } - - CHECK_GL_ERROR_DEBUG(); - } - - return self; -} - -- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer -{ - // Allocate color buffer backing based on the current layer size - glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer_); - - if( ! [context_ renderbufferStorage:GL_RENDERBUFFER fromDrawable:layer] ) - CCLOG(@"failed to call context"); - - glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth_); - glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight_); - - CCLOG(@"cocos2d: surface size: %dx%d", (int)backingWidth_, (int)backingHeight_); - - if (multiSampling_) - { - if ( msaaColorbuffer_) { - glDeleteRenderbuffers(1, &msaaColorbuffer_); - msaaColorbuffer_ = 0; - } - - /* Create the offscreen MSAA color buffer. - After rendering, the contents of this will be blitted into ColorRenderbuffer */ - - //msaaFrameBuffer needs to be binded - glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer_); - glGenRenderbuffers(1, &msaaColorbuffer_); - NSAssert(msaaFramebuffer_, @"Can't create MSAA color buffer"); - - glBindRenderbuffer(GL_RENDERBUFFER, msaaColorbuffer_); - - glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samplesToUse_, pixelFormat_ , backingWidth_, backingHeight_); - - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msaaColorbuffer_); - - GLenum error; - if ( (error=glCheckFramebufferStatus(GL_FRAMEBUFFER)) != GL_FRAMEBUFFER_COMPLETE) - { - CCLOG(@"Failed to make complete framebuffer object 0x%X", error); - return NO; - } - } - - CHECK_GL_ERROR(); - - if (depthFormat_) - { - if( ! depthBuffer_ ) { - glGenRenderbuffers(1, &depthBuffer_); - NSAssert(depthBuffer_, @"Can't create depth buffer"); - } - - glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer_); - - if( multiSampling_ ) - glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samplesToUse_, depthFormat_,backingWidth_, backingHeight_); - else - glRenderbufferStorage(GL_RENDERBUFFER, depthFormat_, backingWidth_, backingHeight_); - - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer_); - - // bind color buffer - glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer_); - } - - CHECK_GL_ERROR(); - - GLenum error; - if( (error=glCheckFramebufferStatus(GL_FRAMEBUFFER)) != GL_FRAMEBUFFER_COMPLETE) - { - CCLOG(@"Failed to make complete framebuffer object 0x%X", error); - return NO; - } - - return YES; -} - --(CGSize) backingSize -{ - return CGSizeMake( backingWidth_, backingHeight_); -} - -- (NSString*) description -{ - return [NSString stringWithFormat:@"<%@ = %08X | size = %ix%i>", [self class], self, backingWidth_, backingHeight_]; -} - -- (unsigned int) colorRenderBuffer -{ - return colorRenderbuffer_; -} - -- (unsigned int) defaultFrameBuffer -{ - return defaultFramebuffer_; -} - -- (unsigned int) msaaFrameBuffer -{ - return msaaFramebuffer_; -} - -- (unsigned int) msaaColorBuffer -{ - return msaaColorbuffer_; -} - -- (void)dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - // Tear down GL - if (defaultFramebuffer_) { - glDeleteFramebuffers(1, &defaultFramebuffer_); - defaultFramebuffer_ = 0; - } - - if (colorRenderbuffer_) { - glDeleteRenderbuffers(1, &colorRenderbuffer_); - colorRenderbuffer_ = 0; - } - - if( depthBuffer_ ) { - glDeleteRenderbuffers(1, &depthBuffer_ ); - depthBuffer_ = 0; - } - - if ( msaaColorbuffer_) - { - glDeleteRenderbuffers(1, &msaaColorbuffer_); - msaaColorbuffer_ = 0; - } - - if ( msaaFramebuffer_) - { - glDeleteRenderbuffers(1, &msaaFramebuffer_); - msaaFramebuffer_ = 0; - } - - // Tear down context - if ([EAGLContext currentContext] == context_) - [EAGLContext setCurrentContext:nil]; - - [context_ release]; - context_ = nil; - - [super dealloc]; -} - -@end - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCESRenderer.h b/Example/libs/cocos2d/Platforms/iOS/CCESRenderer.h deleted file mode 100644 index 59768f5..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCESRenderer.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * - * File autogenerated with Xcode. Adapted for cocos2d needs. - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -#import - -#import -#import - -@protocol CCESRenderer - -- (id) initWithDepthFormat:(unsigned int)depthFormat withPixelFormat:(unsigned int)pixelFormat withSharegroup:(EAGLSharegroup*)sharegroup withMultiSampling:(BOOL) multiSampling withNumberOfSamples:(unsigned int) requestedSamples; - -- (BOOL) resizeFromLayer:(CAEAGLLayer *)layer; - -- (EAGLContext*) context; -- (CGSize) backingSize; - -- (unsigned int) colorRenderBuffer; -- (unsigned int) defaultFrameBuffer; -- (unsigned int) msaaFrameBuffer; -- (unsigned int) msaaColorBuffer; -@end - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCGLView.h b/Example/libs/cocos2d/Platforms/iOS/CCGLView.h deleted file mode 100644 index ecac2e0..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCGLView.h +++ /dev/null @@ -1,160 +0,0 @@ -/* - -===== IMPORTANT ===== - -This is sample code demonstrating API, technology or techniques in development. -Although this sample code has been reviewed for technical accuracy, it is not -final. Apple is supplying this information to help you plan for the adoption of -the technologies and programming interfaces described herein. This information -is subject to change, and software implemented based on this sample code should -be tested with final operating system software and final documentation. Newer -versions of this sample code may be provided with future seeds of the API or -technology. For information about updates to this and other developer -documentation, view the New & Updated sidebars in subsequent documentation -seeds. - -===================== - -File: CCGLView.h -Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a -UIView subclass. - -Version: 1.3 - -Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. -("Apple") in consideration of your agreement to the following terms, and your -use, installation, modification or redistribution of this Apple software -constitutes acceptance of these terms. If you do not agree with these terms, -please do not use, install, modify or redistribute this Apple software. - -In consideration of your agreement to abide by the following terms, and subject -to these terms, Apple grants you a personal, non-exclusive license, under -Apple's copyrights in this original Apple software (the "Apple Software"), to -use, reproduce, modify and redistribute the Apple Software, with or without -modifications, in source and/or binary forms; provided that if you redistribute -the Apple Software in its entirety and without modifications, you must retain -this notice and the following text and disclaimers in all such redistributions -of the Apple Software. -Neither the name, trademarks, service marks or logos of Apple Inc. may be used -to endorse or promote products derived from the Apple Software without specific -prior written permission from Apple. Except as expressly stated in this notice, -no other rights or licenses, express or implied, are granted by Apple herein, -including but not limited to any patent rights that may be infringed by your -derivative works or by other works in which the Apple Software may be -incorporated. - -The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN -COMBINATION WITH YOUR PRODUCTS. - -IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR -DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF -CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF -APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright (C) 2008 Apple Inc. All Rights Reserved. - -*/ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -#import -#import -#import -#import -#import - -#import "CCESRenderer.h" - -//CLASSES: - -@class CCGLView; - -//PROTOCOLS: - -@protocol CCTouchDelegate -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; -@end - -//CLASS INTERFACE: - -/** CCGLView Class. - * This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass. - * The view content is basically an EAGL surface you render your OpenGL scene into. - * Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel. - */ -@interface CCGLView : UIView -{ - id renderer_; - EAGLContext *context_; // weak ref - - NSString *pixelformat_; - GLuint depthFormat_; - BOOL preserveBackbuffer_; - - CGSize size_; - BOOL discardFramebufferSupported_; - id touchDelegate_; - - //fsaa addition - BOOL multisampling_; - unsigned int requestedSamples_; -} - -/** creates an initializes an CCGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer. */ -+ (id) viewWithFrame:(CGRect)frame; -/** creates an initializes an CCGLView with a frame, a color buffer format, and 0-bit depth buffer. */ -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format; -/** creates an initializes an CCGLView with a frame, a color buffer format, and a depth buffer. */ -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth; -/** creates an initializes an CCGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping */ -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples; - -/** Initializes an CCGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */ -- (id) initWithFrame:(CGRect)frame; //These also set the current context -/** Initializes an CCGLView with a frame, a color buffer format, and 0-bit depth buffer */ -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format; -/** Initializes an CCGLView with a frame, a color buffer format, a depth buffer format, a sharegroup and multisampling support */ -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples; - -/** pixel format: it could be RGBA8 (32-bit) or RGB565 (16-bit) */ -@property(nonatomic,readonly) NSString* pixelFormat; -/** depth format of the render buffer: 0, 16 or 24 bits*/ -@property(nonatomic,readonly) GLuint depthFormat; - -/** returns surface size in pixels */ -@property(nonatomic,readonly) CGSize surfaceSize; - -/** OpenGL context */ -@property(nonatomic,readonly) EAGLContext *context; - -@property(nonatomic,readwrite) BOOL multiSampling; - -/** touch delegate */ -@property(nonatomic,readwrite,assign) id touchDelegate; - -/** CCGLView uses double-buffer. This method swaps the buffers */ --(void) swapBuffers; - -/** uses and locks the OpenGL context */ --(void) lockOpenGLContext; - -/** unlocks the openGL context */ --(void) unlockOpenGLContext; - -- (CGPoint) convertPointFromViewToSurface:(CGPoint)point; -- (CGRect) convertRectFromViewToSurface:(CGRect)rect; -@end - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCGLView.m b/Example/libs/cocos2d/Platforms/iOS/CCGLView.m deleted file mode 100644 index 3347c5e..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCGLView.m +++ /dev/null @@ -1,360 +0,0 @@ -/* - -===== IMPORTANT ===== - -This is sample code demonstrating API, technology or techniques in development. -Although this sample code has been reviewed for technical accuracy, it is not -final. Apple is supplying this information to help you plan for the adoption of -the technologies and programming interfaces described herein. This information -is subject to change, and software implemented based on this sample code should -be tested with final operating system software and final documentation. Newer -versions of this sample code may be provided with future seeds of the API or -technology. For information about updates to this and other developer -documentation, view the New & Updated sidebars in subsequent documentation -seeds. - -===================== - -File: CCGLView.m -Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a -UIView subclass. - -Version: 1.3 - -Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. -("Apple") in consideration of your agreement to the following terms, and your -use, installation, modification or redistribution of this Apple software -constitutes acceptance of these terms. If you do not agree with these terms, -please do not use, install, modify or redistribute this Apple software. - -In consideration of your agreement to abide by the following terms, and subject -to these terms, Apple grants you a personal, non-exclusive license, under -Apple's copyrights in this original Apple software (the "Apple Software"), to -use, reproduce, modify and redistribute the Apple Software, with or without -modifications, in source and/or binary forms; provided that if you redistribute -the Apple Software in its entirety and without modifications, you must retain -this notice and the following text and disclaimers in all such redistributions -of the Apple Software. -Neither the name, trademarks, service marks or logos of Apple Inc. may be used -to endorse or promote products derived from the Apple Software without specific -prior written permission from Apple. Except as expressly stated in this notice, -no other rights or licenses, express or implied, are granted by Apple herein, -including but not limited to any patent rights that may be infringed by your -derivative works or by other works in which the Apple Software may be -incorporated. - -The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN -COMBINATION WITH YOUR PRODUCTS. - -IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR -DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF -CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF -APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright (C) 2008 Apple Inc. All Rights Reserved. - -*/ - -/* - Modified for cocos2d project - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -#import - -#import "CCGLView.h" -#import "CCES2Renderer.h" -#import "../../CCDirector.h" -#import "../../ccMacros.h" -#import "../../CCConfiguration.h" -#import "../../Support/OpenGL_Internal.h" - - -//CLASS IMPLEMENTATIONS: - -@interface CCGLView (Private) -- (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup; -- (unsigned int) convertPixelFormat:(NSString*) pixelFormat; -@end - -@implementation CCGLView - -@synthesize surfaceSize=size_; -@synthesize pixelFormat=pixelformat_, depthFormat=depthFormat_; -@synthesize touchDelegate=touchDelegate_; -@synthesize context=context_; -@synthesize multiSampling=multiSampling_; - -+ (Class) layerClass -{ - return [CAEAGLLayer class]; -} - -+ (id) viewWithFrame:(CGRect)frame -{ - return [[[self alloc] initWithFrame:frame] autorelease]; -} - -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format -{ - return [[[self alloc] initWithFrame:frame pixelFormat:format] autorelease]; -} - -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth -{ - return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0] autorelease]; -} - -+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples -{ - return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease]; -} - -- (id) initWithFrame:(CGRect)frame -{ - return [self initWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; -} - -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format -{ - return [self initWithFrame:frame pixelFormat:format depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; -} - -- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples -{ - if((self = [super initWithFrame:frame])) - { - pixelformat_ = format; - depthFormat_ = depth; - multiSampling_ = sampling; - requestedSamples_ = nSamples; - preserveBackbuffer_ = retained; - - if( ! [self setupSurfaceWithSharegroup:sharegroup] ) { - [self release]; - return nil; - } - - CHECK_GL_ERROR_DEBUG(); - } - - return self; -} - --(id) initWithCoder:(NSCoder *)aDecoder -{ - if( (self = [super initWithCoder:aDecoder]) ) { - - CAEAGLLayer* eaglLayer = (CAEAGLLayer*)[self layer]; - - pixelformat_ = kEAGLColorFormatRGB565; - depthFormat_ = 0; // GL_DEPTH_COMPONENT24; - multiSampling_= NO; - requestedSamples_ = 0; - size_ = [eaglLayer bounds].size; - - if( ! [self setupSurfaceWithSharegroup:nil] ) { - [self release]; - return nil; - } - - CHECK_GL_ERROR_DEBUG(); - } - - return self; -} - --(BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup -{ - CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; - - eaglLayer.opaque = YES; - eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:preserveBackbuffer_], kEAGLDrawablePropertyRetainedBacking, - pixelformat_, kEAGLDrawablePropertyColorFormat, nil]; - - // ES2 renderer only - renderer_ = [[CCES2Renderer alloc] initWithDepthFormat:depthFormat_ - withPixelFormat:[self convertPixelFormat:pixelformat_] - withSharegroup:sharegroup - withMultiSampling:multiSampling_ - withNumberOfSamples:requestedSamples_]; - - NSAssert( renderer_, @"OpenGL ES 2.0 is required"); - - if (!renderer_) - return NO; - - context_ = [renderer_ context]; - - discardFramebufferSupported_ = [[CCConfiguration sharedConfiguration] supportsDiscardFramebuffer]; - - CHECK_GL_ERROR_DEBUG(); - - return YES; -} - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - [renderer_ release]; - [super dealloc]; -} - -- (void) layoutSubviews -{ - [renderer_ resizeFromLayer:(CAEAGLLayer*)self.layer]; - - size_ = [renderer_ backingSize]; - - // Issue #914 #924 - CCDirector *director = [CCDirector sharedDirector]; - [director reshapeProjection:size_]; - - // Avoid flicker. Issue #350 - NSThread *thread = [director runningThread]; - [director performSelector:@selector(drawScene) onThread:thread withObject:nil waitUntilDone:YES]; -} - -- (void) swapBuffers -{ - // IMPORTANT: - // - preconditions - // -> context_ MUST be the OpenGL context - // -> renderbuffer_ must be the the RENDER BUFFER - - if (multiSampling_) - { - /* Resolve from msaaFramebuffer to resolveFramebuffer */ - //glDisable(GL_SCISSOR_TEST); - glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, [renderer_ msaaFrameBuffer]); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, [renderer_ defaultFrameBuffer]); - glResolveMultisampleFramebufferAPPLE(); - } - - if( discardFramebufferSupported_) - { - if (multiSampling_) - { - if (depthFormat_) - { - GLenum attachments[] = {GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT}; - glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, attachments); - } - else - { - GLenum attachments[] = {GL_COLOR_ATTACHMENT0}; - glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 1, attachments); - } - - glBindRenderbuffer(GL_RENDERBUFFER, [renderer_ colorRenderBuffer]); - - } - - // not MSAA - else if (depthFormat_ ) { - GLenum attachments[] = { GL_DEPTH_ATTACHMENT}; - glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments); - } - } - - if(![context_ presentRenderbuffer:GL_RENDERBUFFER]) - CCLOG(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__); - - // We can safely re-bind the framebuffer here, since this will be the - // 1st instruction of the new main loop - if( multiSampling_ ) - glBindFramebuffer(GL_FRAMEBUFFER, [renderer_ msaaFrameBuffer]); - - CHECK_GL_ERROR_DEBUG(); -} - --(void) lockOpenGLContext -{ - // unused on iOS -} - --(void) unlockOpenGLContext -{ - // unused on iOS -} - -- (unsigned int) convertPixelFormat:(NSString*) pixelFormat -{ - // define the pixel format - GLenum pFormat; - - - if([pixelFormat isEqualToString:@"EAGLColorFormat565"]) - pFormat = GL_RGB565; - else - pFormat = GL_RGBA8_OES; - - return pFormat; -} - -#pragma mark CCGLView - Point conversion - -- (CGPoint) convertPointFromViewToSurface:(CGPoint)point -{ - CGRect bounds = [self bounds]; - - return CGPointMake((point.x - bounds.origin.x) / bounds.size.width * size_.width, (point.y - bounds.origin.y) / bounds.size.height * size_.height); -} - -- (CGRect) convertRectFromViewToSurface:(CGRect)rect -{ - CGRect bounds = [self bounds]; - - return CGRectMake((rect.origin.x - bounds.origin.x) / bounds.size.width * size_.width, (rect.origin.y - bounds.origin.y) / bounds.size.height * size_.height, rect.size.width / bounds.size.width * size_.width, rect.size.height / bounds.size.height * size_.height); -} - -// Pass the touches to the superview -#pragma mark CCGLView - Touch Delegate - -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event -{ - if(touchDelegate_) - { - [touchDelegate_ touchesBegan:touches withEvent:event]; - } -} - -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event -{ - if(touchDelegate_) - { - [touchDelegate_ touchesMoved:touches withEvent:event]; - } -} - -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event -{ - if(touchDelegate_) - { - [touchDelegate_ touchesEnded:touches withEvent:event]; - } -} -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event -{ - if(touchDelegate_) - { - [touchDelegate_ touchesCancelled:touches withEvent:event]; - } -} - -@end - - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h b/Example/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h deleted file mode 100644 index d8e254b..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -#import - -/** - CCTargetedTouchDelegate. - - Using this type of delegate results in two benefits: - 1. You don't need to deal with NSSets, the dispatcher does the job of splitting - them. You get exactly one UITouch per call. - 2. You can *claim* a UITouch by returning YES in ccTouchBegan. Updates of claimed - touches are sent only to the delegate(s) that claimed them. So if you get a move/ - ended/cancelled update you're sure it is your touch. This frees you from doing a - lot of checks when doing multi-touch. - - (The name TargetedTouchDelegate relates to updates "targeting" their specific - handler, without bothering the other handlers.) - @since v0.8 - */ -@protocol CCTargetedTouchDelegate - -/** Return YES to claim the touch. - @since v0.8 - */ -- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event; -@optional -// touch updates: -- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event; -- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event; -- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event; -@end - -/** - CCStandardTouchDelegate. - - This type of delegate is the same one used by CocoaTouch. You will receive all the events (Began,Moved,Ended,Cancelled). - @since v0.8 -*/ -@protocol CCStandardTouchDelegate -@optional -- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; -- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; -- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; -- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; -@end - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h b/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h deleted file mode 100644 index 9995865..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -#import "CCTouchDelegateProtocol.h" -#import "CCGLView.h" - - -typedef enum -{ - kCCTouchSelectorBeganBit = 1 << 0, - kCCTouchSelectorMovedBit = 1 << 1, - kCCTouchSelectorEndedBit = 1 << 2, - kCCTouchSelectorCancelledBit = 1 << 3, - kCCTouchSelectorAllBits = ( kCCTouchSelectorBeganBit | kCCTouchSelectorMovedBit | kCCTouchSelectorEndedBit | kCCTouchSelectorCancelledBit), -} ccTouchSelectorFlag; - - -enum { - kCCTouchBegan, - kCCTouchMoved, - kCCTouchEnded, - kCCTouchCancelled, - - kCCTouchMax, -}; - -struct ccTouchHandlerHelperData { - SEL touchesSel; - SEL touchSel; - ccTouchSelectorFlag type; -}; - -/** CCTouchDispatcher. - Object that handles all the touch events. - The dispatcher dispatches events to the registered TouchHandlers. - There are 2 different type of touch handlers: - - Standard Touch Handlers - - Targeted Touch Handlers - - The Standard Touch Handlers work like the CocoaTouch touch handler: a set of touches is passed to the delegate. - On the other hand, the Targeted Touch Handlers only receive 1 touch at the time, and they can "swallow" touches (avoid the propagation of the event). - - Firstly, the dispatcher sends the received touches to the targeted touches. - These touches can be swallowed by the Targeted Touch Handlers. If there are still remaining touches, then the remaining touches will be sent - to the Standard Touch Handlers. - - @since v0.8.0 - */ -@interface CCTouchDispatcher : NSObject -{ - NSMutableArray *targetedHandlers; - NSMutableArray *standardHandlers; - - BOOL locked; - BOOL toAdd; - BOOL toRemove; - NSMutableArray *handlersToAdd; - NSMutableArray *handlersToRemove; - BOOL toQuit; - - BOOL dispatchEvents; - - // 4, 1 for each type of event - struct ccTouchHandlerHelperData handlerHelperData[kCCTouchMax]; -} - -/** Whether or not the events are going to be dispatched. Default: YES */ -@property (nonatomic,readwrite, assign) BOOL dispatchEvents; - -/** Adds a standard touch delegate to the dispatcher's list. - See StandardTouchDelegate description. - IMPORTANT: The delegate will be retained. - */ --(void) addStandardDelegate:(id) delegate priority:(int)priority; -/** Adds a targeted touch delegate to the dispatcher's list. - See TargetedTouchDelegate description. - IMPORTANT: The delegate will be retained. - */ --(void) addTargetedDelegate:(id) delegate priority:(int)priority swallowsTouches:(BOOL)swallowsTouches; -/** Removes a touch delegate. - The delegate will be released - */ --(void) removeDelegate:(id) delegate; -/** Removes all touch delegates, releasing all the delegates */ --(void) removeAllDelegates; -/** Changes the priority of a previously added delegate. The lower the number, - the higher the priority */ --(void) setPriority:(int) priority forDelegate:(id) delegate; - -NSComparisonResult sortByPriority(id first, id second, void *context); -@end - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m b/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m deleted file mode 100644 index 788e99d..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m +++ /dev/null @@ -1,341 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - - -#import "CCTouchDispatcher.h" -#import "CCTouchHandler.h" - -@implementation CCTouchDispatcher - -@synthesize dispatchEvents; - --(id) init -{ - if((self = [super init])) { - - dispatchEvents = YES; - targetedHandlers = [[NSMutableArray alloc] initWithCapacity:8]; - standardHandlers = [[NSMutableArray alloc] initWithCapacity:4]; - - handlersToAdd = [[NSMutableArray alloc] initWithCapacity:8]; - handlersToRemove = [[NSMutableArray alloc] initWithCapacity:8]; - - toRemove = NO; - toAdd = NO; - toQuit = NO; - locked = NO; - - handlerHelperData[kCCTouchBegan] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesBegan:withEvent:),@selector(ccTouchBegan:withEvent:),kCCTouchSelectorBeganBit}; - handlerHelperData[kCCTouchMoved] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesMoved:withEvent:),@selector(ccTouchMoved:withEvent:),kCCTouchSelectorMovedBit}; - handlerHelperData[kCCTouchEnded] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesEnded:withEvent:),@selector(ccTouchEnded:withEvent:),kCCTouchSelectorEndedBit}; - handlerHelperData[kCCTouchCancelled] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesCancelled:withEvent:),@selector(ccTouchCancelled:withEvent:),kCCTouchSelectorCancelledBit}; - - } - - return self; -} - --(void) dealloc -{ - [targetedHandlers release]; - [standardHandlers release]; - [handlersToAdd release]; - [handlersToRemove release]; - [super dealloc]; -} - -// -// handlers management -// - -#pragma mark TouchDispatcher - Add Hanlder - --(void) forceAddHandler:(CCTouchHandler*)handler array:(NSMutableArray*)array -{ - NSUInteger i = 0; - - for( CCTouchHandler *h in array ) { - if( h.priority < handler.priority ) - i++; - - NSAssert( h.delegate != handler.delegate, @"Delegate already added to touch dispatcher."); - } - [array insertObject:handler atIndex:i]; -} - --(void) addStandardDelegate:(id) delegate priority:(int)priority -{ - CCTouchHandler *handler = [CCStandardTouchHandler handlerWithDelegate:delegate priority:priority]; - if( ! locked ) { - [self forceAddHandler:handler array:standardHandlers]; - } else { - [handlersToAdd addObject:handler]; - toAdd = YES; - } -} - --(void) addTargetedDelegate:(id) delegate priority:(int)priority swallowsTouches:(BOOL)swallowsTouches -{ - CCTouchHandler *handler = [CCTargetedTouchHandler handlerWithDelegate:delegate priority:priority swallowsTouches:swallowsTouches]; - if( ! locked ) { - [self forceAddHandler:handler array:targetedHandlers]; - } else { - [handlersToAdd addObject:handler]; - toAdd = YES; - } -} - -#pragma mark TouchDispatcher - removeDelegate - --(void) forceRemoveDelegate:(id)delegate -{ - // XXX: remove it from both handlers ??? - - for( CCTouchHandler *handler in targetedHandlers ) { - if( handler.delegate == delegate ) { - [targetedHandlers removeObject:handler]; - break; - } - } - - for( CCTouchHandler *handler in standardHandlers ) { - if( handler.delegate == delegate ) { - [standardHandlers removeObject:handler]; - break; - } - } -} - --(void) removeDelegate:(id) delegate -{ - if( delegate == nil ) - return; - - if( ! locked ) { - [self forceRemoveDelegate:delegate]; - } else { - [handlersToRemove addObject:delegate]; - toRemove = YES; - } -} - -#pragma mark TouchDispatcher - removeAllDelegates - --(void) forceRemoveAllDelegates -{ - [standardHandlers removeAllObjects]; - [targetedHandlers removeAllObjects]; -} --(void) removeAllDelegates -{ - if( ! locked ) - [self forceRemoveAllDelegates]; - else - toQuit = YES; -} - -#pragma mark Changing priority of added handlers - --(CCTouchHandler*) findHandler:(id)delegate -{ - for( CCTouchHandler *handler in targetedHandlers ) { - if( handler.delegate == delegate ) { - return handler; - } - } - - for( CCTouchHandler *handler in standardHandlers ) { - if( handler.delegate == delegate ) { - return handler; - } - } - - if (toAdd) { - for( CCTouchHandler *handler in handlersToAdd ) { - if (handler.delegate == delegate) { - return handler; - } - } - } - - return nil; -} - -NSComparisonResult sortByPriority(id first, id second, void *context) -{ - if (((CCTouchHandler*)first).priority < ((CCTouchHandler*)second).priority) - return NSOrderedAscending; - else if (((CCTouchHandler*)first).priority > ((CCTouchHandler*)second).priority) - return NSOrderedDescending; - else - return NSOrderedSame; -} - --(void) rearrangeHandlers:(NSMutableArray*)array -{ - [array sortUsingFunction:sortByPriority context:nil]; -} - --(void) setPriority:(int) priority forDelegate:(id) delegate -{ - NSAssert(delegate != nil, @"Got nil touch delegate!"); - - CCTouchHandler *handler = nil; - handler = [self findHandler:delegate]; - - NSAssert(handler != nil, @"Delegate not found!"); - - handler.priority = priority; - - [self rearrangeHandlers:targetedHandlers]; - [self rearrangeHandlers:standardHandlers]; -} - -// -// dispatch events -// --(void) touches:(NSSet*)touches withEvent:(UIEvent*)event withTouchType:(unsigned int)idx -{ - NSAssert(idx < 4, @"Invalid idx value"); - - id mutableTouches; - locked = YES; - - // optimization to prevent a mutable copy when it is not necessary - unsigned int targetedHandlersCount = [targetedHandlers count]; - unsigned int standardHandlersCount = [standardHandlers count]; - BOOL needsMutableSet = (targetedHandlersCount && standardHandlersCount); - - mutableTouches = (needsMutableSet ? [touches mutableCopy] : touches); - - struct ccTouchHandlerHelperData helper = handlerHelperData[idx]; - // - // process the target handlers 1st - // - if( targetedHandlersCount > 0 ) { - for( UITouch *touch in touches ) { - for(CCTargetedTouchHandler *handler in targetedHandlers) { - - BOOL claimed = NO; - if( idx == kCCTouchBegan ) { - claimed = [handler.delegate ccTouchBegan:touch withEvent:event]; - if( claimed ) - [handler.claimedTouches addObject:touch]; - } - - // else (moved, ended, cancelled) - else if( [handler.claimedTouches containsObject:touch] ) { - claimed = YES; - if( handler.enabledSelectors & helper.type ) - [handler.delegate performSelector:helper.touchSel withObject:touch withObject:event]; - - if( helper.type & (kCCTouchSelectorCancelledBit | kCCTouchSelectorEndedBit) ) - [handler.claimedTouches removeObject:touch]; - } - - if( claimed && handler.swallowsTouches ) { - if( needsMutableSet ) - [mutableTouches removeObject:touch]; - break; - } - } - } - } - - // - // process standard handlers 2nd - // - if( standardHandlersCount > 0 && [mutableTouches count]>0 ) { - for( CCTouchHandler *handler in standardHandlers ) { - if( handler.enabledSelectors & helper.type ) - [handler.delegate performSelector:helper.touchesSel withObject:mutableTouches withObject:event]; - } - } - if( needsMutableSet ) - [mutableTouches release]; - - // - // Optimization. To prevent a [handlers copy] which is expensive - // the add/removes/quit is done after the iterations - // - locked = NO; - - //issue 1084, 1139 first add then remove - if( toAdd ) { - toAdd = NO; - Class targetedClass = [CCTargetedTouchHandler class]; - - for( CCTouchHandler *handler in handlersToAdd ) { - if( [handler isKindOfClass:targetedClass] ) - [self forceAddHandler:handler array:targetedHandlers]; - else - [self forceAddHandler:handler array:standardHandlers]; - } - [handlersToAdd removeAllObjects]; - } - - if( toRemove ) { - toRemove = NO; - for( id delegate in handlersToRemove ) - [self forceRemoveDelegate:delegate]; - [handlersToRemove removeAllObjects]; - } - - if( toQuit ) { - toQuit = NO; - [self forceRemoveAllDelegates]; - } -} - -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event -{ - if( dispatchEvents ) - [self touches:touches withEvent:event withTouchType:kCCTouchBegan]; -} -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event -{ - if( dispatchEvents ) - [self touches:touches withEvent:event withTouchType:kCCTouchMoved]; -} - -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event -{ - if( dispatchEvents ) - [self touches:touches withEvent:event withTouchType:kCCTouchEnded]; -} - -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event -{ - if( dispatchEvents ) - [self touches:touches withEvent:event withTouchType:kCCTouchCancelled]; -} -@end - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.h b/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.h deleted file mode 100644 index c448972..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -/* - * This file contains the delegates of the touches - * There are 2 possible delegates: - * - CCStandardTouchHandler: propagates all the events at once - * - CCTargetedTouchHandler: propagates 1 event at the time - */ - -#import "CCTouchDelegateProtocol.h" -#import "CCTouchDispatcher.h" - -/** - CCTouchHandler - Object than contains the delegate and priority of the event handler. -*/ -@interface CCTouchHandler : NSObject { - id delegate; - int priority; - ccTouchSelectorFlag enabledSelectors_; -} - -/** delegate */ -@property(nonatomic, readwrite, retain) id delegate; -/** priority */ -@property(nonatomic, readwrite) int priority; // default 0 -/** enabled selectors */ -@property(nonatomic,readwrite) ccTouchSelectorFlag enabledSelectors; - -/** allocates a TouchHandler with a delegate and a priority */ -+ (id)handlerWithDelegate:(id)aDelegate priority:(int)priority; -/** initializes a TouchHandler with a delegate and a priority */ -- (id)initWithDelegate:(id)aDelegate priority:(int)priority; -@end - -/** CCStandardTouchHandler - It forwardes each event to the delegate. - */ -@interface CCStandardTouchHandler : CCTouchHandler -{ -} -@end - -/** - CCTargetedTouchHandler - Object than contains the claimed touches and if it swallos touches. - Used internally by TouchDispatcher - */ -@interface CCTargetedTouchHandler : CCTouchHandler { - BOOL swallowsTouches; - NSMutableSet *claimedTouches; -} -/** whether or not the touches are swallowed */ -@property(nonatomic, readwrite) BOOL swallowsTouches; // default NO -/** MutableSet that contains the claimed touches */ -@property(nonatomic, readonly) NSMutableSet *claimedTouches; - -/** allocates a TargetedTouchHandler with a delegate, a priority and whether or not it swallows touches or not */ -+ (id)handlerWithDelegate:(id) aDelegate priority:(int)priority swallowsTouches:(BOOL)swallowsTouches; -/** initializes a TargetedTouchHandler with a delegate, a priority and whether or not it swallows touches or not */ -- (id)initWithDelegate:(id) aDelegate priority:(int)priority swallowsTouches:(BOOL)swallowsTouches; - -@end - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.m b/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.m deleted file mode 100644 index 2aec6ee..0000000 --- a/Example/libs/cocos2d/Platforms/iOS/CCTouchHandler.m +++ /dev/null @@ -1,135 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -// Only compile this code on iOS. These files should NOT be included on your Mac project. -// But in case they are included, it won't be compiled. -#import "../../ccMacros.h" -#ifdef __CC_PLATFORM_IOS - -/* - * This file contains the delegates of the touches - * There are 2 possible delegates: - * - CCStandardTouchHandler: propagates all the events at once - * - CCTargetedTouchHandler: propagates 1 event at the time - */ - -#import "CCTouchHandler.h" -#import "../../ccMacros.h" - -#pragma mark - -#pragma mark TouchHandler -@implementation CCTouchHandler - -@synthesize delegate, priority; -@synthesize enabledSelectors=enabledSelectors_; - -+ (id)handlerWithDelegate:(id) aDelegate priority:(int)aPriority -{ - return [[[self alloc] initWithDelegate:aDelegate priority:aPriority] autorelease]; -} - -- (id)initWithDelegate:(id) aDelegate priority:(int)aPriority -{ - NSAssert(aDelegate != nil, @"Touch delegate may not be nil"); - - if ((self = [super init])) { - self.delegate = aDelegate; - priority = aPriority; - enabledSelectors_ = 0; - } - - return self; -} - -- (void)dealloc { - CCLOGINFO(@"cocos2d: deallocing %@", self); - [delegate release]; - [super dealloc]; -} -@end - -#pragma mark - -#pragma mark StandardTouchHandler -@implementation CCStandardTouchHandler --(id) initWithDelegate:(id)del priority:(int)pri -{ - if( (self=[super initWithDelegate:del priority:pri]) ) { - if( [del respondsToSelector:@selector(ccTouchesBegan:withEvent:)] ) - enabledSelectors_ |= kCCTouchSelectorBeganBit; - if( [del respondsToSelector:@selector(ccTouchesMoved:withEvent:)] ) - enabledSelectors_ |= kCCTouchSelectorMovedBit; - if( [del respondsToSelector:@selector(ccTouchesEnded:withEvent:)] ) - enabledSelectors_ |= kCCTouchSelectorEndedBit; - if( [del respondsToSelector:@selector(ccTouchesCancelled:withEvent:)] ) - enabledSelectors_ |= kCCTouchSelectorCancelledBit; - } - return self; -} -@end - -#pragma mark - -#pragma mark TargetedTouchHandler - -@interface CCTargetedTouchHandler (private) --(void) updateKnownTouches:(NSMutableSet *)touches withEvent:(UIEvent *)event selector:(SEL)selector unclaim:(BOOL)doUnclaim; -@end - -@implementation CCTargetedTouchHandler - -@synthesize swallowsTouches, claimedTouches; - -+ (id)handlerWithDelegate:(id)aDelegate priority:(int)priority swallowsTouches:(BOOL)swallow -{ - return [[[self alloc] initWithDelegate:aDelegate priority:priority swallowsTouches:swallow] autorelease]; -} - -- (id)initWithDelegate:(id)aDelegate priority:(int)aPriority swallowsTouches:(BOOL)swallow -{ - if ((self = [super initWithDelegate:aDelegate priority:aPriority])) { - claimedTouches = [[NSMutableSet alloc] initWithCapacity:2]; - swallowsTouches = swallow; - - if( [aDelegate respondsToSelector:@selector(ccTouchBegan:withEvent:)] ) - enabledSelectors_ |= kCCTouchSelectorBeganBit; - if( [aDelegate respondsToSelector:@selector(ccTouchMoved:withEvent:)] ) - enabledSelectors_ |= kCCTouchSelectorMovedBit; - if( [aDelegate respondsToSelector:@selector(ccTouchEnded:withEvent:)] ) - enabledSelectors_ |= kCCTouchSelectorEndedBit; - if( [aDelegate respondsToSelector:@selector(ccTouchCancelled:withEvent:)] ) - enabledSelectors_ |= kCCTouchSelectorCancelledBit; - } - - return self; -} - -- (void)dealloc { - [claimedTouches release]; - [super dealloc]; -} -@end - - -#endif // __CC_PLATFORM_IOS diff --git a/Example/libs/cocos2d/Support/CCArray.h b/Example/libs/cocos2d/Support/CCArray.h deleted file mode 100644 index c8dae99..0000000 --- a/Example/libs/cocos2d/Support/CCArray.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -#import "ccCArray.h" - - -/** A faster alternative of NSArray. - CCArray uses internally a c-array. - @since v0.99.4 - */ - - -/** @def CCARRAY_FOREACH - A convience macro to iterate over a CCArray using. It is faster than the "fast enumeration" interface. - @since v0.99.4 - */ - -#define CCARRAY_FOREACH(__array__, __object__) \ -if (__array__ && __array__->data->num > 0) \ -for(const CC_ARC_UNSAFE_RETAINED id *__arr__ = __array__->data->arr, *end = __array__->data->arr + __array__->data->num-1; \ - __arr__ <= end && ((__object__ = *__arr__) != nil || true); \ - __arr__++) - -@interface CCArray : NSObject -{ - @public ccArray *data; -} - -+ (id) array; -+ (id) arrayWithCapacity:(NSUInteger)capacity; -+ (id) arrayWithArray:(CCArray*)otherArray; -+ (id) arrayWithNSArray:(NSArray*)otherArray; - - -- (id) initWithCapacity:(NSUInteger)capacity; -- (id) initWithArray:(CCArray*)otherArray; -- (id) initWithNSArray:(NSArray*)otherArray; - - -// Querying an Array - -- (NSUInteger) count; -- (NSUInteger) capacity; -- (NSUInteger) indexOfObject:(id)object; -- (id) objectAtIndex:(NSUInteger)index; -- (BOOL) containsObject:(id)object; -- (id) randomObject; -- (id) lastObject; -- (NSArray*) getNSArray; - - -// Adding Objects - -- (void) addObject:(id)object; -- (void) addObjectsFromArray:(CCArray*)otherArray; -- (void) addObjectsFromNSArray:(NSArray*)otherArray; -- (void) insertObject:(id)object atIndex:(NSUInteger)index; - - -// Removing Objects - -- (void) removeLastObject; -- (void) removeObject:(id)object; -- (void) removeObjectAtIndex:(NSUInteger)index; -- (void) removeObjectsInArray:(CCArray*)otherArray; -- (void) removeAllObjects; -- (void) fastRemoveObject:(id)object; -- (void) fastRemoveObjectAtIndex:(NSUInteger)index; - - -// Rearranging Content - -- (void) exchangeObject:(id)object1 withObject:(id)object2; -- (void) exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2; -- (void) reverseObjects; -- (void) reduceMemoryFootprint; - -// Sending Messages to Elements - -- (void) makeObjectsPerformSelector:(SEL)aSelector; -- (void) makeObjectsPerformSelector:(SEL)aSelector withObject:(id)object; - - -@end diff --git a/Example/libs/cocos2d/Support/CCArray.m b/Example/libs/cocos2d/Support/CCArray.m deleted file mode 100644 index 5dc38d3..0000000 --- a/Example/libs/cocos2d/Support/CCArray.m +++ /dev/null @@ -1,304 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "CCArray.h" -#import "../ccMacros.h" - - -@implementation CCArray - -+ (id) array -{ - return [[[self alloc] init] autorelease]; -} - -+ (id) arrayWithCapacity:(NSUInteger)capacity -{ - return [[[self alloc] initWithCapacity:capacity] autorelease]; -} - -+ (id) arrayWithArray:(CCArray*)otherArray -{ - return [[(CCArray*)[self alloc] initWithArray:otherArray] autorelease]; -} - -+ (id) arrayWithNSArray:(NSArray*)otherArray -{ - return [[(CCArray*)[self alloc] initWithNSArray:otherArray] autorelease]; -} - -- (id) init -{ - self = [self initWithCapacity:2]; - return self; -} - -- (id) initWithCapacity:(NSUInteger)capacity -{ - self = [super init]; - if (self != nil) { - data = ccArrayNew(capacity); - } - return self; -} - -- (id) initWithArray:(CCArray*)otherArray -{ - self = [self initWithCapacity:otherArray->data->num]; - if (self != nil) { - [self addObjectsFromArray:otherArray]; - } - return self; -} - -- (id) initWithNSArray:(NSArray*)otherArray -{ - self = [self initWithCapacity:otherArray.count]; - if (self != nil) { - [self addObjectsFromNSArray:otherArray]; - } - return self; -} - -- (id) initWithCoder:(NSCoder*)coder -{ - self = [self initWithNSArray:[coder decodeObjectForKey:@"nsarray"]]; - return self; -} - - -#pragma mark Querying an Array - -- (NSUInteger) count -{ - return data->num; -} - -- (NSUInteger) capacity -{ - return data->max; -} - -- (NSUInteger) indexOfObject:(id)object -{ - return ccArrayGetIndexOfObject(data, object); -} - -- (id) objectAtIndex:(NSUInteger)index -{ - NSAssert2( index < data->num, @"index out of range in objectAtIndex(%d), index %i", data->num, index ); - - return data->arr[index]; -} - -- (BOOL) containsObject:(id)object -{ - return ccArrayContainsObject(data, object); -} - -- (id) lastObject -{ - if( data->num > 0 ) - return data->arr[data->num-1]; - return nil; -} - -- (id) randomObject -{ - if(data->num==0) return nil; - return data->arr[(int)(data->num*CCRANDOM_0_1())]; -} - -- (NSArray*) getNSArray -{ - return [NSArray arrayWithObjects:data->arr count:data->num]; -} - - -#pragma mark Adding Objects - -- (void) addObject:(id)object -{ - ccArrayAppendObjectWithResize(data, object); -} - -- (void) addObjectsFromArray:(CCArray*)otherArray -{ - ccArrayAppendArrayWithResize(data, otherArray->data); -} - -- (void) addObjectsFromNSArray:(NSArray*)otherArray -{ - ccArrayEnsureExtraCapacity(data, otherArray.count); - for(id object in otherArray) - ccArrayAppendObject(data, object); -} - -- (void) insertObject:(id)object atIndex:(NSUInteger)index -{ - ccArrayInsertObjectAtIndex(data, object, index); -} - - -#pragma mark Removing Objects - -- (void) removeObject:(id)object -{ - ccArrayRemoveObject(data, object); -} - -- (void) removeObjectAtIndex:(NSUInteger)index -{ - ccArrayRemoveObjectAtIndex(data, index); -} - -- (void) fastRemoveObject:(id)object -{ - ccArrayFastRemoveObject(data, object); -} - -- (void) fastRemoveObjectAtIndex:(NSUInteger)index -{ - ccArrayFastRemoveObjectAtIndex(data, index); -} - -- (void) removeObjectsInArray:(CCArray*)otherArray -{ - ccArrayRemoveArray(data, otherArray->data); -} - -- (void) removeLastObject -{ - NSAssert( data->num > 0, @"no objects added" ); - - ccArrayRemoveObjectAtIndex(data, data->num-1); -} - -- (void) removeAllObjects -{ - ccArrayRemoveAllObjects(data); -} - - -#pragma mark Rearranging Content - -- (void) exchangeObject:(id)object1 withObject:(id)object2 -{ - NSUInteger index1 = ccArrayGetIndexOfObject(data, object1); - if(index1 == NSNotFound) return; - NSUInteger index2 = ccArrayGetIndexOfObject(data, object2); - if(index2 == NSNotFound) return; - - ccArraySwapObjectsAtIndexes(data, index1, index2); -} - -- (void) exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 -{ - ccArraySwapObjectsAtIndexes(data, index1, index2); -} - -- (void) reverseObjects -{ - if (data->num > 1) - { - //floor it since in case of a oneven number the number of swaps stays the same - int count = (int) floorf(data->num/2.f); - NSUInteger maxIndex = data->num - 1; - - for (int i = 0; i < count ; i++) - { - ccArraySwapObjectsAtIndexes(data, i, maxIndex); - maxIndex--; - } - } -} - -- (void) reduceMemoryFootprint -{ - ccArrayShrink(data); -} - -#pragma mark Sending Messages to Elements - -- (void) makeObjectsPerformSelector:(SEL)aSelector -{ - ccArrayMakeObjectsPerformSelector(data, aSelector); -} - -- (void) makeObjectsPerformSelector:(SEL)aSelector withObject:(id)object -{ - ccArrayMakeObjectsPerformSelectorWithObject(data, aSelector, object); -} - - -#pragma mark CCArray - NSFastEnumeration protocol - -- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len -{ - if(state->state == 1) return 0; - - state->mutationsPtr = (unsigned long *)self; - state->itemsPtr = &data->arr[0]; - state->state = 1; - return data->num; -} - - -#pragma mark CCArray - NSCopying protocol - -- (id)copyWithZone:(NSZone *)zone -{ - return [(CCArray*)[[self class] allocWithZone:zone] initWithArray:self]; -} - -- (void) encodeWithCoder:(NSCoder *)coder -{ - [coder encodeObject:[self getNSArray] forKey:@"nsarray"]; -} - -#pragma mark - -- (void) dealloc -{ - CCLOGINFO(@"cocos2d: deallocing %@", self); - - ccArrayFree(data); - [super dealloc]; -} - -#pragma mark - -- (NSString*) description -{ - NSMutableString *ret = [NSMutableString stringWithFormat:@"<%@ = %08X> = ( ", [self class], self]; - - for( id obj in self) - [ret appendFormat:@"%@, ",obj]; - - [ret appendString:@")"]; - - return ret; -} - -@end diff --git a/Example/libs/cocos2d/Support/CCFileUtils.h b/Example/libs/cocos2d/Support/CCFileUtils.h deleted file mode 100644 index 2589ae9..0000000 --- a/Example/libs/cocos2d/Support/CCFileUtils.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import -#import "../ccTypes.h" - -/** Helper class to handle file operations */ -@interface CCFileUtils : NSObject -{ -} - -/** Returns the fullpath of an filename. - - If in RetinaDisplay mode, and a RetinaDisplay file is found, it will return that path. - If in iPad mode, and an iPad file is found, it will return that path. - - Examples: - - * In iPad mode: "image.png" -> "/full/path/image-ipad.png" (in case the -ipad file exists) - * In RetinaDisplay mode: "image.png" -> "/full/path/image-hd.png" (in case the -hd file exists) - - */ -+(NSString*) fullPathFromRelativePath:(NSString*) relPath; - - -#ifdef __CC_PLATFORM_IOS - -/** Returns the fullpath of an filename including the resolution of the image. - - If in RetinaDisplay mode, and a RetinaDisplay file is found, it will return that path. - If in iPad mode, and an iPad file is found, it will return that path. - - Examples: - - * In iPad mode: "image.png" -> "/full/path/image-ipad.png" (in case the -ipad file exists) - * In RetinaDisplay mode: "image.png" -> "/full/path/image-hd.png" (in case the -hd file exists) - - If an iPad file is found, it will set resolution type to kCCResolutioniPad - If a RetinaDisplay file is found, it will set resolution type to kCCResolutionRetinaDisplay - - */ -+(NSString*) fullPathFromRelativePath:(NSString*)relPath resolutionType:(ccResolutionType*)resolutionType; - - -/** removes the suffix from a path - * On RetinaDisplay it will remove the -hd suffix - * On iPad it will remove the -ipad suffix - * On iPhone it will remove the (empty) suffix - Only valid on iOS. Not valid for OS X. - - @since v0.99.5 - */ -+(NSString *)removeSuffixFromFile:(NSString*) path; - -/** Sets the iPhone RetinaDisplay suffix to load resources. - By default it is "-hd". - Only valid on iOS. Not valid for OS X. - - @since v1.1 - */ -+(void) setiPhoneRetinaDisplaySuffix:(NSString*)suffix; - -/** Sets the iPad suffix to load resources. - By default it is "". - Only valid on iOS. Not valid for OS X. - - @since v1.1 - */ -+(void) setiPadSuffix:(NSString*)suffix; - -/** Sets the iPad Retina Display suffix to load resources. - By default it is "-ipadhd". - Only valid on iOS. Not valid for OS X. - - @since v1.1 - */ -+(void) setiPadRetinaDisplaySuffix:(NSString*)suffix; - -/** Returns whether or not a given filename exists with the iPad suffix. - Only available on iOS. Not supported on OS X. - @since v1.1 - */ -+(BOOL) iPadFileExistsAtPath:(NSString*)filename; - -/** Returns whether or not a given filename exists with the iPad RetinaDisplay suffix. - Only available on iOS. Not supported on OS X. - @since v2.0 - */ -+(BOOL) iPadFileExistsAtPath:(NSString*)filename; - -/** Returns whether or not a given path exists with the iPhone RetinaDisplay suffix. - Only available on iOS. Not supported on OS X. - @since v1.1 - */ -+(BOOL) iPhoneRetinaDisplayFileExistsAtPath:(NSString*)filename; - -#endif // __CC_PLATFORM_IOS - -@end - -/** loads a file into memory. - the caller should release the allocated buffer. - - @returns the size of the allocated buffer - @since v0.99.5 - */ -NSInteger ccLoadFileIntoMemory(const char *filename, unsigned char **out); - diff --git a/Example/libs/cocos2d/Support/CCFileUtils.m b/Example/libs/cocos2d/Support/CCFileUtils.m deleted file mode 100644 index 8493dcd..0000000 --- a/Example/libs/cocos2d/Support/CCFileUtils.m +++ /dev/null @@ -1,319 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CCFileUtils.h" -#import "../CCConfiguration.h" -#import "../ccMacros.h" -#import "../ccConfig.h" -#import "../ccTypes.h" - -static NSFileManager *__localFileManager=nil; - -#ifdef __CC_PLATFORM_IOS - -static NSString *__suffixiPhoneRetinaDisplay =@"-hd"; -static NSString *__suffixiPad =@"-ipad"; -static NSString *__suffixiPadRetinaDisplay =@"-ipadhd"; - -#endif // __CC_PLATFORM_IOS - - -NSString *ccRemoveSuffixFromPath( NSString *suffix, NSString *path); - -// -NSInteger ccLoadFileIntoMemory(const char *filename, unsigned char **out) -{ - NSCAssert( out, @"ccLoadFileIntoMemory: invalid 'out' parameter"); - NSCAssert( &*out, @"ccLoadFileIntoMemory: invalid 'out' parameter"); - - size_t size = 0; - FILE *f = fopen(filename, "rb"); - if( !f ) { - *out = NULL; - return -1; - } - - fseek(f, 0, SEEK_END); - size = ftell(f); - fseek(f, 0, SEEK_SET); - - *out = malloc(size); - size_t read = fread(*out, 1, size, f); - if( read != size ) { - free(*out); - *out = NULL; - return -1; - } - - fclose(f); - - return size; -} - - -#ifdef __CC_PLATFORM_IOS -@interface CCFileUtils() -+(NSString *) removeSuffix:(NSString*)suffix fromPath:(NSString*)path; -+(BOOL) fileExistsAtPath:(NSString*)string withSuffix:(NSString*)suffix; -@end -#endif // __CC_PLATFORM_IOS - -@implementation CCFileUtils - -+(void) initialize -{ - if( self == [CCFileUtils class] ) - __localFileManager = [[NSFileManager alloc] init]; -} - -+(NSString*) getPath:(NSString*)path forSuffix:(NSString*)suffix -{ - // quick return - if( ! suffix || [suffix length] == 0 ) - return path; - - NSString *pathWithoutExtension = [path stringByDeletingPathExtension]; - NSString *name = [pathWithoutExtension lastPathComponent]; - - // check if path already has the suffix. - if( [name rangeOfString:suffix].location != NSNotFound ) { - - CCLOG(@"cocos2d: WARNING Filename(%@) already has the suffix %@. Using it.", name, suffix); - return path; - } - - - NSString *extension = [path pathExtension]; - - if( [extension isEqualToString:@"ccz"] || [extension isEqualToString:@"gz"] ) - { - // All ccz / gz files should be in the format filename.xxx.ccz - // so we need to pull off the .xxx part of the extension as well - extension = [NSString stringWithFormat:@"%@.%@", [pathWithoutExtension pathExtension], extension]; - pathWithoutExtension = [pathWithoutExtension stringByDeletingPathExtension]; - } - - - NSString *newName = [pathWithoutExtension stringByAppendingString:suffix]; - newName = [newName stringByAppendingPathExtension:extension]; - - if( [__localFileManager fileExistsAtPath:newName] ) - return newName; - - CCLOG(@"cocos2d: CCFileUtils: Warning file not found: %@", [newName lastPathComponent] ); - - return nil; -} - -+(NSString*) fullPathFromRelativePath:(NSString*)relPath resolutionType:(ccResolutionType*)resolutionType -{ - NSAssert(relPath != nil, @"CCFileUtils: Invalid path"); - - NSString *fullpath = nil; - - // only if it is not an absolute path - if( ! [relPath isAbsolutePath] ) { - - // pathForResource also searches in .lproj directories. issue #1230 - NSString *file = [relPath lastPathComponent]; - NSString *imageDirectory = [relPath stringByDeletingLastPathComponent]; - - fullpath = [[NSBundle mainBundle] pathForResource:file - ofType:nil - inDirectory:imageDirectory]; - - - } - - if (fullpath == nil) - fullpath = relPath; - -#ifdef __CC_PLATFORM_IOS - - NSString *ret = nil; - - // iPad? - if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) - { - // Retina Display ? - if( CC_CONTENT_SCALE_FACTOR() == 2 ) { - ret = [self getPath:fullpath forSuffix:__suffixiPadRetinaDisplay]; - *resolutionType = kCCResolutioniPadRetinaDisplay; - } - else - { - ret = [self getPath:fullpath forSuffix:__suffixiPad]; - *resolutionType = kCCResolutioniPad; - - } - } - // iPhone ? - else - { - // Retina Display ? - if( CC_CONTENT_SCALE_FACTOR() == 2 ) { - ret = [self getPath:fullpath forSuffix:__suffixiPhoneRetinaDisplay]; - *resolutionType = kCCResolutioniPhoneRetinaDisplay; - } - } - - // If it is iPhone Non RetinaDisplay, or if the previous "getPath" failed, then use iPhone images. - if( ret == nil ) - { - *resolutionType = kCCResolutioniPhone; - ret = fullpath; - } - - return ret; - -#elif defined(__CC_PLATFORM_MAC) - - *resolutionType = kCCResolutioniPhone; - - return fullpath; - -#endif // __CC_PLATFORM_MAC - -} - -+(NSString*) fullPathFromRelativePath:(NSString*) relPath -{ - ccResolutionType ignore; - return [self fullPathFromRelativePath:relPath resolutionType:&ignore]; -} - -#pragma mark CCFileUtils - Suffix (iOS only) - - -#ifdef __CC_PLATFORM_IOS - -+(NSString *) removeSuffix:(NSString*)suffix fromPath:(NSString*)path -{ - // quick return - if( ! suffix || [suffix length] == 0 ) - return path; - - NSString *name = [path lastPathComponent]; - - // check if path already has the suffix. - if( [name rangeOfString:suffix].location != NSNotFound ) { - - CCLOGINFO(@"cocos2d: Filename(%@) contains %@ suffix. Removing it. See cocos2d issue #1040", path, suffix); - - NSString *newLastname = [name stringByReplacingOccurrencesOfString:suffix withString:@""]; - - NSString *pathWithoutLastname = [path stringByDeletingLastPathComponent]; - return [pathWithoutLastname stringByAppendingPathComponent:newLastname]; - } - - return path; -} - -+(NSString*) removeSuffixFromFile:(NSString*) path -{ - NSString *ret = nil; - - if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) - { - if( CC_CONTENT_SCALE_FACTOR() == 2 ) - ret = [self removeSuffix:__suffixiPadRetinaDisplay fromPath:path]; - else - ret = [self removeSuffix:__suffixiPad fromPath:path]; - } - else - { - if( CC_CONTENT_SCALE_FACTOR() == 2 ) - ret = [self removeSuffix:__suffixiPhoneRetinaDisplay fromPath:path]; - else - ret = path; - } - - return ret; -} - -+(void) setiPhoneRetinaDisplaySuffix:(NSString*)suffix -{ - [__suffixiPhoneRetinaDisplay release]; - __suffixiPhoneRetinaDisplay = [suffix copy]; -} - -+(void) setiPadSuffix:(NSString*)suffix -{ - [__suffixiPad release]; - __suffixiPad = [suffix copy]; -} - -+(void) setiPadRetinaDisplaySuffix:(NSString*)suffix -{ - [__suffixiPadRetinaDisplay release]; - __suffixiPadRetinaDisplay = [suffix copy]; -} - -+(BOOL) fileExistsAtPath:(NSString*)relPath withSuffix:(NSString*)suffix -{ - NSString *fullpath = nil; - - // only if it is not an absolute path - if( ! [relPath isAbsolutePath] ) { - // pathForResource also searches in .lproj directories. issue #1230 - NSString *file = [relPath lastPathComponent]; - NSString *imageDirectory = [relPath stringByDeletingLastPathComponent]; - - fullpath = [[NSBundle mainBundle] pathForResource:file - ofType:nil - inDirectory:imageDirectory]; - - } - - if (fullpath == nil) - fullpath = relPath; - - NSString *path = [self getPath:fullpath forSuffix:suffix]; - - return ( path != nil ); -} - -+(BOOL) iPhoneRetinaDisplayFileExistsAtPath:(NSString*)path -{ - return [self fileExistsAtPath:path withSuffix:__suffixiPhoneRetinaDisplay]; -} - -+(BOOL) iPadFileExistsAtPath:(NSString*)path -{ - return [self fileExistsAtPath:path withSuffix:__suffixiPad]; -} - -+(BOOL) iPadRetinaDisplayFileExistsAtPath:(NSString*)path -{ - return [self fileExistsAtPath:path withSuffix:__suffixiPadRetinaDisplay]; -} - - -#endif // __CC_PLATFORM_IOS - - -@end diff --git a/Example/libs/cocos2d/Support/CCProfiling.h b/Example/libs/cocos2d/Support/CCProfiling.h deleted file mode 100644 index 9b645f1..0000000 --- a/Example/libs/cocos2d/Support/CCProfiling.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Stuart Carnie - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import -#import - -@class CCProfilingTimer; - -/** CCProfiler - cocos2d builtin profiler. - - To use it, enable set the CC_ENABLE_PROFILERS=1 in the ccConfig.h file - */ -@interface CCProfiler : NSObject { -@public - NSMutableDictionary* activeTimers; -} - -/** shared instance */ -+ (CCProfiler*)sharedProfiler; - -/** Creates and adds a new timer */ -- (CCProfilingTimer*) createAndAddTimerWithName:(NSString*)timerName; - -/** releases a timer */ -- (void)releaseTimer:(NSString*)timerName; - -/** releases all timers */ -- (void) releaseAllTimers; - -/** display the timers */ -- (void)displayTimers; - -@end - -/** CCProfilingTimer -Profiling timers used by CCProfiler - */ -@interface CCProfilingTimer : NSObject { - -@public - NSString *name; - struct timeval startTime; - double averageTime; - double minTime; - double maxTime; - double totalTime; - NSUInteger numberOfCalls; -} - -/** resets the timer properties */ --(void) reset; -@end - -extern void CCProfilingBeginTimingBlock(NSString *timerName); -extern void CCProfilingEndTimingBlock(NSString *timerName); -extern void CCProfilingResetTimingBlock(NSString *timerName); - -/* - * cocos2d profiling categories - * used to enable / disable profilers with granularity - */ - -extern BOOL kCCProfilerCategorySprite; -extern BOOL kCCProfilerCategoryBatchSprite; -extern BOOL kCCProfilerCategoryParticles; diff --git a/Example/libs/cocos2d/Support/CCProfiling.m b/Example/libs/cocos2d/Support/CCProfiling.m deleted file mode 100644 index 057f0f5..0000000 --- a/Example/libs/cocos2d/Support/CCProfiling.m +++ /dev/null @@ -1,186 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2010 Stuart Carnie - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "../ccConfig.h" -#import "../ccMacros.h" - -#import "CCProfiling.h" - -#pragma mark - Profiling Categories - -/* set to NO the categories that you don't want to profile */ -BOOL kCCProfilerCategorySprite = NO; -BOOL kCCProfilerCategoryBatchSprite = NO; -BOOL kCCProfilerCategoryParticles = NO; - - -@interface CCProfilingTimer() -- (id)initWithName:(NSString*)timerName; -@end - - -#pragma mark - CCProfiler - -@implementation CCProfiler - -static CCProfiler* g_sharedProfiler; - -+ (CCProfiler*)sharedProfiler -{ - if (!g_sharedProfiler) - g_sharedProfiler = [[CCProfiler alloc] init]; - - return g_sharedProfiler; -} - -- (CCProfilingTimer*) createAndAddTimerWithName:(NSString*)timerName -{ - CCProfilingTimer* t = [[CCProfilingTimer alloc] initWithName:timerName]; - [activeTimers setObject:t forKey:timerName]; - [t release]; - return t; -} - -- (void)releaseTimer:(NSString*)timerName -{ - [activeTimers removeObjectForKey:timerName]; -} - -- (void) releaseAllTimers -{ - [activeTimers removeAllObjects]; -} - -- (id)init -{ - if ((self = [super init])) { - activeTimers = [[NSMutableDictionary alloc] initWithCapacity:10]; - } - - return self; -} - -- (void)dealloc -{ - [activeTimers release]; - [super dealloc]; -} - -- (void)displayTimers -{ - NSArray *values = [activeTimers allValues]; - for (CCProfilingTimer *timer in values) { - printf("%s\n", [[timer description] cStringUsingEncoding:[NSString defaultCStringEncoding]]); - } -} - -@end - -#pragma mark - CCProfilingTimer - - -@implementation CCProfilingTimer - -- (id)initWithName:(NSString*)timerName -{ - if ((self = [super init])) { - name = [timerName copy]; - numberOfCalls = 0; - averageTime = 0; - totalTime = 0; - minTime = 10000; - maxTime = 0; - gettimeofday(&startTime, NULL); - } - - return self; -} - -- (void)dealloc -{ - CCLOGINFO(@"deallocing %@", self); - [name release]; - [super dealloc]; -} - -- (NSString*)description -{ - return [NSString stringWithFormat:@"%@ ::\tavg: %fms,\tmin: %fms,\tmax: %fms,\ttotal: %.2fs,\tnr calls: %d", name, averageTime, minTime, maxTime, totalTime / 1000.0, numberOfCalls]; -} - --(void) reset -{ - numberOfCalls = 0; - averageTime = 0; - totalTime = 0; - minTime = 10000; - maxTime = 0; - gettimeofday(&startTime, NULL); -} - -@end - - -void CCProfilingBeginTimingBlock(NSString *timerName) -{ - CCProfiler* p = [CCProfiler sharedProfiler]; - CCProfilingTimer *timer = [p->activeTimers objectForKey:timerName]; - if( ! timer ) - timer = [p createAndAddTimerWithName:timerName]; - - gettimeofday(&timer->startTime, NULL); - - timer->numberOfCalls++; -} - -void CCProfilingEndTimingBlock(NSString *timerName) -{ - CCProfiler* p = [CCProfiler sharedProfiler]; - CCProfilingTimer *timer = [p->activeTimers objectForKey:timerName]; - - NSCAssert1(timer, @"CCProfilingTimer %@ not found", timerName); - - struct timeval currentTime; - gettimeofday(¤tTime, NULL); - timersub(¤tTime, &timer->startTime, ¤tTime); - double duration = currentTime.tv_sec * 1000.0 + currentTime.tv_usec / 1000.0; - - // milliseconds - timer->averageTime = (timer->averageTime + duration) / 2.0f; - timer->totalTime += duration; - timer->maxTime = MAX( timer->maxTime, duration); - timer->minTime = MIN( timer->minTime, duration); - -} - -void CCProfilingResetTimingBlock(NSString *timerName) -{ - CCProfiler* p = [CCProfiler sharedProfiler]; - CCProfilingTimer *timer = [p->activeTimers objectForKey:timerName]; - - NSCAssert1(timer, @"CCProfilingTimer %@ not found", timerName); - - [timer reset]; -} diff --git a/Example/libs/cocos2d/Support/CCVertex.h b/Example/libs/cocos2d/Support/CCVertex.h deleted file mode 100644 index 671e365..0000000 --- a/Example/libs/cocos2d/Support/CCVertex.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2011 ForzeField Studios S.L. http://forzefield.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "ccTypes.h" - -/** @file CCVertex.h */ - -/** converts a line to a polygon */ -void ccVertexLineToPolygon(CGPoint *points, float stroke, ccVertex2F *vertices, ccTex2F *texCoords, NSUInteger offset, NSUInteger nuPoints); - -/** returns wheter or not the line intersects */ -BOOL ccVertexLineIntersect(float Ax, float Ay, - float Bx, float By, - float Cx, float Cy, - float Dx, float Dy, float *T); diff --git a/Example/libs/cocos2d/Support/CCVertex.m b/Example/libs/cocos2d/Support/CCVertex.m deleted file mode 100644 index ad7d398..0000000 --- a/Example/libs/cocos2d/Support/CCVertex.m +++ /dev/null @@ -1,138 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2011 ForzeField Studios S.L. http://forzefield.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "CCVertex.h" -#import "CGPointExtension.h" -#import "../ccMacros.h" - -void ccVertexLineToPolygon(CGPoint *points, float stroke, ccVertex2F *vertices, ccTex2F *texCoords, NSUInteger offset, NSUInteger nuPoints) -{ - nuPoints += offset; - if(nuPoints<=1) return; - - stroke *= 0.5f; - - NSUInteger idx; - NSUInteger nuPointsMinus = nuPoints-1; - float texDelta = 1.0f/(float)nuPointsMinus; - - for(NSUInteger i = offset; i1.0f) - fixVertex = YES; - - if(fixVertex) - { - vertices[idx1] = p4; - vertices[idx1+1] = p3; - } - } -} - -BOOL ccVertexLineIntersect(float Ax, float Ay, - float Bx, float By, - float Cx, float Cy, - float Dx, float Dy, float *T) -{ - float distAB, theCos, theSin, newX; - - // FAIL: Line undefined - if ((Ax==Bx && Ay==By) || (Cx==Dx && Cy==Dy)) return NO; - - // Translate system to make A the origin - Bx-=Ax; By-=Ay; - Cx-=Ax; Cy-=Ay; - Dx-=Ax; Dy-=Ay; - - // Length of segment AB - distAB = sqrtf(Bx*Bx+By*By); - - // Rotate the system so that point B is on the positive X axis. - theCos = Bx/distAB; - theSin = By/distAB; - newX = Cx*theCos+Cy*theSin; - Cy = Cy*theCos-Cx*theSin; Cx = newX; - newX = Dx*theCos+Dy*theSin; - Dy = Dy*theCos-Dx*theSin; Dx = newX; - - // FAIL: Lines are parallel. - if (Cy == Dy) return NO; - - // Discover the relative position of the intersection in the line AB - *T = (Dx+(Cx-Dx)*Dy/(Dy-Cy))/distAB; - - // Success. - return YES; -} diff --git a/Example/libs/cocos2d/Support/CGPointExtension.h b/Example/libs/cocos2d/Support/CGPointExtension.h deleted file mode 100644 index 90510c4..0000000 --- a/Example/libs/cocos2d/Support/CGPointExtension.h +++ /dev/null @@ -1,344 +0,0 @@ -/* cocos2d for iPhone - * http://www.cocos2d-iphone.org - * - * Copyright (c) 2007 Scott Lembcke - * - * Copyright (c) 2010 Lam Pham - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -/* - * Some of the functions were based on Chipmunk's cpVect.h. - */ - -/** - @file - CGPoint extensions based on Chipmunk's cpVect file. - These extensions work both with CGPoint and cpVect. - - The "ccp" prefix means: "CoCos2d Point" - - Examples: - - ccpAdd( ccp(1,1), ccp(2,2) ); // preferred cocos2d way - - ccpAdd( CGPointMake(1,1), CGPointMake(2,2) ); // also ok but more verbose - - - cpvadd( cpv(1,1), cpv(2,2) ); // way of the chipmunk - - ccpAdd( cpv(1,1), cpv(2,2) ); // mixing chipmunk and cocos2d (avoid) - - cpvadd( CGPointMake(1,1), CGPointMake(2,2) ); // mixing chipmunk and CG (avoid) - */ - -#import "ccMacros.h" - -#ifdef __CC_PLATFORM_IOS -#import -#elif defined(__CC_PLATFORM_MAC) -#import -#endif - -#import -#import - -#ifdef __cplusplus -extern "C" { -#endif - -/** Helper macro that creates a CGPoint - @return CGPoint - @since v0.7.2 - */ -#define ccp(__X__,__Y__) CGPointMake(__X__,__Y__) - - -/** Returns opposite of point. - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpNeg(const CGPoint v) -{ - return ccp(-v.x, -v.y); -} - -/** Calculates sum of two points. - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpAdd(const CGPoint v1, const CGPoint v2) -{ - return ccp(v1.x + v2.x, v1.y + v2.y); -} - -/** Calculates difference of two points. - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpSub(const CGPoint v1, const CGPoint v2) -{ - return ccp(v1.x - v2.x, v1.y - v2.y); -} - -/** Returns point multiplied by given factor. - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpMult(const CGPoint v, const CGFloat s) -{ - return ccp(v.x*s, v.y*s); -} - -/** Calculates midpoint between two points. - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpMidpoint(const CGPoint v1, const CGPoint v2) -{ - return ccpMult(ccpAdd(v1, v2), 0.5f); -} - -/** Calculates dot product of two points. - @return CGFloat - @since v0.7.2 - */ -static inline CGFloat -ccpDot(const CGPoint v1, const CGPoint v2) -{ - return v1.x*v2.x + v1.y*v2.y; -} - -/** Calculates cross product of two points. - @return CGFloat - @since v0.7.2 - */ -static inline CGFloat -ccpCross(const CGPoint v1, const CGPoint v2) -{ - return v1.x*v2.y - v1.y*v2.x; -} - -/** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0 - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpPerp(const CGPoint v) -{ - return ccp(-v.y, v.x); -} - -/** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0 - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpRPerp(const CGPoint v) -{ - return ccp(v.y, -v.x); -} - -/** Calculates the projection of v1 over v2. - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpProject(const CGPoint v1, const CGPoint v2) -{ - return ccpMult(v2, ccpDot(v1, v2)/ccpDot(v2, v2)); -} - -/** Rotates two points. - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpRotate(const CGPoint v1, const CGPoint v2) -{ - return ccp(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x); -} - -/** Unrotates two points. - @return CGPoint - @since v0.7.2 - */ -static inline CGPoint -ccpUnrotate(const CGPoint v1, const CGPoint v2) -{ - return ccp(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y); -} - -/** Calculates the square length of a CGPoint (not calling sqrt() ) - @return CGFloat - @since v0.7.2 - */ -static inline CGFloat -ccpLengthSQ(const CGPoint v) -{ - return ccpDot(v, v); -} - -/** Calculates the square distance between two points (not calling sqrt() ) - @return CGFloat - @since v1.1 -*/ -static inline CGFloat -ccpDistanceSQ(const CGPoint p1, const CGPoint p2) -{ - return ccpLengthSQ(ccpSub(p1, p2)); -} - -/** Calculates distance between point an origin - @return CGFloat - @since v0.7.2 - */ -CGFloat ccpLength(const CGPoint v); - -/** Calculates the distance between two points - @return CGFloat - @since v0.7.2 - */ -CGFloat ccpDistance(const CGPoint v1, const CGPoint v2); - -/** Returns point multiplied to a length of 1. - @return CGPoint - @since v0.7.2 - */ -CGPoint ccpNormalize(const CGPoint v); - -/** Converts radians to a normalized vector. - @return CGPoint - @since v0.7.2 - */ -CGPoint ccpForAngle(const CGFloat a); - -/** Converts a vector to radians. - @return CGFloat - @since v0.7.2 - */ -CGFloat ccpToAngle(const CGPoint v); - - -/** Clamp a value between from and to. - @since v0.99.1 - */ -float clampf(float value, float min_inclusive, float max_inclusive); - -/** Clamp a point between from and to. - @since v0.99.1 - */ -CGPoint ccpClamp(CGPoint p, CGPoint from, CGPoint to); - -/** Quickly convert CGSize to a CGPoint - @since v0.99.1 - */ -CGPoint ccpFromSize(CGSize s); - -/** Run a math operation function on each point component - * absf, fllorf, ceilf, roundf - * any function that has the signature: float func(float); - * For example: let's try to take the floor of x,y - * ccpCompOp(p,floorf); - @since v0.99.1 - */ -CGPoint ccpCompOp(CGPoint p, float (*opFunc)(float)); - -/** Linear Interpolation between two points a and b - @returns - alpha == 0 ? a - alpha == 1 ? b - otherwise a value between a..b - @since v0.99.1 - */ -CGPoint ccpLerp(CGPoint a, CGPoint b, float alpha); - - -/** @returns if points have fuzzy equality which means equal with some degree of variance. - @since v0.99.1 - */ -BOOL ccpFuzzyEqual(CGPoint a, CGPoint b, float variance); - - -/** Multiplies a nd b components, a.x*b.x, a.y*b.y - @returns a component-wise multiplication - @since v0.99.1 - */ -CGPoint ccpCompMult(CGPoint a, CGPoint b); - -/** @returns the signed angle in radians between two vector directions - @since v0.99.1 - */ -float ccpAngleSigned(CGPoint a, CGPoint b); - -/** @returns the angle in radians between two vector directions - @since v0.99.1 -*/ -float ccpAngle(CGPoint a, CGPoint b); - -/** Rotates a point counter clockwise by the angle around a pivot - @param v is the point to rotate - @param pivot is the pivot, naturally - @param angle is the angle of rotation cw in radians - @returns the rotated point - @since v0.99.1 - */ -CGPoint ccpRotateByAngle(CGPoint v, CGPoint pivot, float angle); - -/** A general line-line intersection test - @param p1 - is the startpoint for the first line P1 = (p1 - p2) - @param p2 - is the endpoint for the first line P1 = (p1 - p2) - @param p3 - is the startpoint for the second line P2 = (p3 - p4) - @param p4 - is the endpoint for the second line P2 = (p3 - p4) - @param s - is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1)) - @param t - is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3)) - @return bool - indicating successful intersection of a line - note that to truly test intersection for segments we have to make - sure that s & t lie within [0..1] and for rays, make sure s & t > 0 - the hit point is p3 + t * (p4 - p3); - the hit point also is p1 + s * (p2 - p1); - @since v0.99.1 - */ -BOOL ccpLineIntersect(CGPoint p1, CGPoint p2, - CGPoint p3, CGPoint p4, - float *s, float *t); - -/* - ccpSegmentIntersect returns YES if Segment A-B intersects with segment C-D - @since v1.0.0 - */ -BOOL ccpSegmentIntersect(CGPoint A, CGPoint B, CGPoint C, CGPoint D); - -/* - ccpIntersectPoint returns the intersection point of line A-B, C-D - @since v1.0.0 - */ -CGPoint ccpIntersectPoint(CGPoint A, CGPoint B, CGPoint C, CGPoint D); - -#ifdef __cplusplus -} -#endif diff --git a/Example/libs/cocos2d/Support/CGPointExtension.m b/Example/libs/cocos2d/Support/CGPointExtension.m deleted file mode 100644 index 8343a3f..0000000 --- a/Example/libs/cocos2d/Support/CGPointExtension.m +++ /dev/null @@ -1,196 +0,0 @@ -/* cocos2d for iPhone - * http://www.cocos2d-iphone.org - * - * Copyright (c) 2007 Scott Lembcke - * - * Copyright (c) 2010 Lam Pham - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -#include "stdio.h" -#include "math.h" - -#import "../ccMacros.h" // CC_SWAP -#include "CGPointExtension.h" - -#define kCGPointEpsilon FLT_EPSILON - -CGFloat -ccpLength(const CGPoint v) -{ - return sqrtf(ccpLengthSQ(v)); -} - -CGFloat -ccpDistance(const CGPoint v1, const CGPoint v2) -{ - return ccpLength(ccpSub(v1, v2)); -} - -CGPoint -ccpNormalize(const CGPoint v) -{ - return ccpMult(v, 1.0f/ccpLength(v)); -} - -CGPoint -ccpForAngle(const CGFloat a) -{ - return ccp(cosf(a), sinf(a)); -} - -CGFloat -ccpToAngle(const CGPoint v) -{ - return atan2f(v.y, v.x); -} - -CGPoint ccpLerp(CGPoint a, CGPoint b, float alpha) -{ - return ccpAdd(ccpMult(a, 1.f - alpha), ccpMult(b, alpha)); -} - -float clampf(float value, float min_inclusive, float max_inclusive) -{ - if (min_inclusive > max_inclusive) { - CC_SWAP(min_inclusive,max_inclusive); - } - return value < min_inclusive ? min_inclusive : value < max_inclusive? value : max_inclusive; -} - -CGPoint ccpClamp(CGPoint p, CGPoint min_inclusive, CGPoint max_inclusive) -{ - return ccp(clampf(p.x,min_inclusive.x,max_inclusive.x), clampf(p.y, min_inclusive.y, max_inclusive.y)); -} - -CGPoint ccpFromSize(CGSize s) -{ - return ccp(s.width, s.height); -} - -CGPoint ccpCompOp(CGPoint p, float (*opFunc)(float)) -{ - return ccp(opFunc(p.x), opFunc(p.y)); -} - -BOOL ccpFuzzyEqual(CGPoint a, CGPoint b, float var) -{ - if(a.x - var <= b.x && b.x <= a.x + var) - if(a.y - var <= b.y && b.y <= a.y + var) - return true; - return false; -} - -CGPoint ccpCompMult(CGPoint a, CGPoint b) -{ - return ccp(a.x * b.x, a.y * b.y); -} - -float ccpAngleSigned(CGPoint a, CGPoint b) -{ - CGPoint a2 = ccpNormalize(a); - CGPoint b2 = ccpNormalize(b); - float angle = atan2f(a2.x * b2.y - a2.y * b2.x, ccpDot(a2, b2)); - if( fabs(angle) < kCGPointEpsilon ) return 0.f; - return angle; -} - -CGPoint ccpRotateByAngle(CGPoint v, CGPoint pivot, float angle) -{ - CGPoint r = ccpSub(v, pivot); - float cosa = cosf(angle), sina = sinf(angle); - float t = r.x; - r.x = t*cosa - r.y*sina + pivot.x; - r.y = t*sina + r.y*cosa + pivot.y; - return r; -} - - -BOOL ccpSegmentIntersect(CGPoint A, CGPoint B, CGPoint C, CGPoint D) -{ - float S, T; - - if( ccpLineIntersect(A, B, C, D, &S, &T ) - && (S >= 0.0f && S <= 1.0f && T >= 0.0f && T <= 1.0f) ) - return YES; - - return NO; -} - -CGPoint ccpIntersectPoint(CGPoint A, CGPoint B, CGPoint C, CGPoint D) -{ - float S, T; - - if( ccpLineIntersect(A, B, C, D, &S, &T) ) { - // Point of intersection - CGPoint P; - P.x = A.x + S * (B.x - A.x); - P.y = A.y + S * (B.y - A.y); - return P; - } - - return CGPointZero; -} - -BOOL ccpLineIntersect(CGPoint A, CGPoint B, - CGPoint C, CGPoint D, - float *S, float *T) -{ - // FAIL: Line undefined - if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) ) return NO; - - const float BAx = B.x - A.x; - const float BAy = B.y - A.y; - const float DCx = D.x - C.x; - const float DCy = D.y - C.y; - const float ACx = A.x - C.x; - const float ACy = A.y - C.y; - - const float denom = DCy*BAx - DCx*BAy; - - *S = DCx*ACy - DCy*ACx; - *T = BAx*ACy - BAy*ACx; - - if (denom == 0) { - if (*S == 0 || *T == 0) { - // Lines incident - return YES; - } - // Lines parallel and not incident - return NO; - } - - *S = *S / denom; - *T = *T / denom; - - // Point of intersection - // CGPoint P; - // P.x = A.x + *S * (B.x - A.x); - // P.y = A.y + *S * (B.y - A.y); - - return YES; -} - -float ccpAngle(CGPoint a, CGPoint b) -{ - float angle = acosf(ccpDot(ccpNormalize(a), ccpNormalize(b))); - if( fabs(angle) < kCGPointEpsilon ) return 0.f; - return angle; -} diff --git a/Example/libs/cocos2d/Support/NSThread+performBlock.h b/Example/libs/cocos2d/Support/NSThread+performBlock.h deleted file mode 100644 index bb5ec8d..0000000 --- a/Example/libs/cocos2d/Support/NSThread+performBlock.h +++ /dev/null @@ -1,22 +0,0 @@ -/* cocos2d for iPhone - * - * http://www.cocos2d-iphone.org - * - * - * Idea taken from: http://stackoverflow.com/a/3940757 - * - */ - -#import - -@interface NSThread (sendBlockToBackground) -/** performs a block on the thread. It won't wait until it is done. */ -- (void) performBlock:(void (^)(void))block; - -/** performs a block on the thread. */ -- (void) performBlock:(void (^)(void))block waitUntilDone:(BOOL)wait; - -/** performs a block on the thread. */ -- (void) performBlock:(void (^)(id param))block withObject:(id)object waitUntilDone:(BOOL)wait; - -@end diff --git a/Example/libs/cocos2d/Support/NSThread+performBlock.m b/Example/libs/cocos2d/Support/NSThread+performBlock.m deleted file mode 100644 index 65d85f5..0000000 --- a/Example/libs/cocos2d/Support/NSThread+performBlock.m +++ /dev/null @@ -1,76 +0,0 @@ -/* cocos2d for iPhone - * - * http://www.cocos2d-iphone.org - * - * - * Idea taken from: http://stackoverflow.com/a/3940757 - * - */ - - -#import "NSThread+performBlock.h" -#import "../ccMacros.h" - -typedef void (^BlockWithParam)(id param); -@interface CCObjectWith2Params : NSObject -{ -@public - BlockWithParam block; - id param; -} -@property (nonatomic,copy) id block; -@property (nonatomic,readwrite,retain) id param; -@end - -@implementation CCObjectWith2Params -@synthesize block, param; -- (void)dealloc { - CCLOG(@"cocos2d: deallocing %@", self); - [block release]; - [param release]; - - [super dealloc]; -} -@end - -@implementation NSThread (sendBlockToBackground) - -- (void) performBlock: (void (^)(void))block; -{ - return [self performBlock:block waitUntilDone:NO]; -} - -- (void) performBlock:(void (^)(void))block waitUntilDone:(BOOL)wait -{ - [self performSelector:@selector(executeBlock:) - onThread:self - withObject: block - waitUntilDone: wait]; -} - -- (void) performBlock:(void (^)(id param))block withObject:(id)object waitUntilDone:(BOOL)wait -{ - CCObjectWith2Params * obj = [[CCObjectWith2Params alloc] init]; - obj.block = block; - obj.param = object; - - [obj autorelease]; - - [self performSelector:@selector(executeBlock2:) - onThread:self - withObject:obj - waitUntilDone:wait]; -} - -- (void) executeBlock: (void (^)(void))block; -{ - block(); -} - -- (void) executeBlock2:(CCObjectWith2Params*)object -{ - BlockWithParam block = object.block; - block( object.param ); -} - -@end diff --git a/Example/libs/cocos2d/Support/OpenGL_Internal.h b/Example/libs/cocos2d/Support/OpenGL_Internal.h deleted file mode 100644 index 82dc473..0000000 --- a/Example/libs/cocos2d/Support/OpenGL_Internal.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - -===== IMPORTANT ===== - -This is sample code demonstrating API, technology or techniques in development. -Although this sample code has been reviewed for technical accuracy, it is not -final. Apple is supplying this information to help you plan for the adoption of -the technologies and programming interfaces described herein. This information -is subject to change, and software implemented based on this sample code should -be tested with final operating system software and final documentation. Newer -versions of this sample code may be provided with future seeds of the API or -technology. For information about updates to this and other developer -documentation, view the New & Updated sidebars in subsequent documentation -seeds. - -===================== - -File: OpenGL_Internal.h -Abstract: This file is included for support purposes and isn't necessary for -understanding this sample. - -Version: 1.0 - -Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. -("Apple") in consideration of your agreement to the following terms, and your -use, installation, modification or redistribution of this Apple software -constitutes acceptance of these terms. If you do not agree with these terms, -please do not use, install, modify or redistribute this Apple software. - -In consideration of your agreement to abide by the following terms, and subject -to these terms, Apple grants you a personal, non-exclusive license, under -Apple's copyrights in this original Apple software (the "Apple Software"), to -use, reproduce, modify and redistribute the Apple Software, with or without -modifications, in source and/or binary forms; provided that if you redistribute -the Apple Software in its entirety and without modifications, you must retain -this notice and the following text and disclaimers in all such redistributions -of the Apple Software. -Neither the name, trademarks, service marks or logos of Apple Inc. may be used -to endorse or promote products derived from the Apple Software without specific -prior written permission from Apple. Except as expressly stated in this notice, -no other rights or licenses, express or implied, are granted by Apple herein, -including but not limited to any patent rights that may be infringed by your -derivative works or by other works in which the Apple Software may be -incorporated. - -The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO -WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED -WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN -COMBINATION WITH YOUR PRODUCTS. - -IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR -DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF -CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF -APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright (C) 2008 Apple Inc. All Rights Reserved. - -*/ - -/* Generic error reporting */ -#define REPORT_ERROR(__FORMAT__, ...) printf("%s: %s\n", __FUNCTION__, [[NSString stringWithFormat:__FORMAT__, __VA_ARGS__] UTF8String]) - -/* EAGL and GL functions calling wrappers that log on error */ -#define CALL_EAGL_FUNCTION(__FUNC__, ...) ({ EAGLError __error = __FUNC__( __VA_ARGS__ ); if(__error != kEAGLErrorSuccess) printf("%s() called from %s returned error %i\n", #__FUNC__, __FUNCTION__, __error); (__error ? NO : YES); }) -//#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) printf("OpenGL error 0x%04X in %s\n", __error, __FUNCTION__); (__error ? NO : YES); }) -#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) printf("OpenGL error 0x%04X in %s %d\n", __error, __FUNCTION__, __LINE__); }) - -#if DEBUG -#define CHECK_GL_ERROR_DEBUG() ({ GLenum __error = glGetError(); if(__error) printf("OpenGL error 0x%04X in %s %d\n", __error, __FUNCTION__, __LINE__); }) -#else -#define CHECK_GL_ERROR_DEBUG() -#endif - -/* Optional delegate methods support */ -#ifndef __DELEGATE_IVAR__ -#define __DELEGATE_IVAR__ _delegate -#endif -#ifndef __DELEGATE_METHODS_IVAR__ -#define __DELEGATE_METHODS_IVAR__ _delegateMethods -#endif -#define TEST_DELEGATE_METHOD_BIT(__BIT__) (self->__DELEGATE_METHODS_IVAR__ & (1 << __BIT__)) -#define SET_DELEGATE_METHOD_BIT(__BIT__, __NAME__) { if([self->__DELEGATE_IVAR__ respondsToSelector:@selector(__NAME__)]) self->__DELEGATE_METHODS_IVAR__ |= (1 << __BIT__); else self->__DELEGATE_METHODS_IVAR__ &= ~(1 << __BIT__); } diff --git a/Example/libs/cocos2d/Support/TGAlib.h b/Example/libs/cocos2d/Support/TGAlib.h deleted file mode 100644 index c52a2a5..0000000 --- a/Example/libs/cocos2d/Support/TGAlib.h +++ /dev/null @@ -1,55 +0,0 @@ -// -// TGA lib for cocos2d-iphone -// -// sources from: http://www.lighthouse3d.com/opengl/terrain/index.php3?tgasource -// - -//#ifndef TGA_LIB -//#define TGA_LIB - -/** - @file - TGA image support - */ - -enum { - TGA_OK, - TGA_ERROR_FILE_OPEN, - TGA_ERROR_READING_FILE, - TGA_ERROR_INDEXED_COLOR, - TGA_ERROR_MEMORY, - TGA_ERROR_COMPRESSED_FILE, -}; - -/** TGA format */ -typedef struct sImageTGA { - int status; - unsigned char type, pixelDepth; - - /** map width */ - short int width; - - /** map height */ - short int height; - - /** raw data */ - unsigned char *imageData; - int flipped; -} tImageTGA; - -/// load the image header fields. We only keep those that matter! -void tgaLoadHeader(FILE *file, tImageTGA *info); - -/// loads the image pixels. You shouldn't call this function directly -void tgaLoadImageData(FILE *file, tImageTGA *info); - -/// this is the function to call when we want to load an image -tImageTGA * tgaLoad(const char *filename); - -// /converts RGB to greyscale -void tgaRGBtogreyscale(tImageTGA *info); - -/// releases the memory used for the image -void tgaDestroy(tImageTGA *info); - -//#endif // TGA_LIB diff --git a/Example/libs/cocos2d/Support/TGAlib.m b/Example/libs/cocos2d/Support/TGAlib.m deleted file mode 100644 index c2766d4..0000000 --- a/Example/libs/cocos2d/Support/TGAlib.m +++ /dev/null @@ -1,274 +0,0 @@ -// -// TGA lib for cocos2d-iphone -// -// sources from: http://www.lighthouse3d.com/opengl/terrain/index.php3?tgasource -// -// TGA RLE compression support by Ernesto Corvi - -#include -#include -#include - -#import "TGAlib.h" - -void tgaLoadRLEImageData(FILE *file, tImageTGA *info); -void tgaFlipImage( tImageTGA *info ); - -// load the image header fields. We only keep those that matter! -void tgaLoadHeader(FILE *file, tImageTGA *info) { - unsigned char cGarbage; - short int iGarbage; - - fread(&cGarbage, sizeof(unsigned char), 1, file); - fread(&cGarbage, sizeof(unsigned char), 1, file); - - // type must be 2 or 3 - fread(&info->type, sizeof(unsigned char), 1, file); - - fread(&iGarbage, sizeof(short int), 1, file); - fread(&iGarbage, sizeof(short int), 1, file); - fread(&cGarbage, sizeof(unsigned char), 1, file); - fread(&iGarbage, sizeof(short int), 1, file); - fread(&iGarbage, sizeof(short int), 1, file); - - fread(&info->width, sizeof(short int), 1, file); - fread(&info->height, sizeof(short int), 1, file); - fread(&info->pixelDepth, sizeof(unsigned char), 1, file); - - fread(&cGarbage, sizeof(unsigned char), 1, file); - - info->flipped = 0; - if ( cGarbage & 0x20 ) info->flipped = 1; -} - -// loads the image pixels. You shouldn't call this function directly -void tgaLoadImageData(FILE *file, tImageTGA *info) { - - int mode,total,i; - unsigned char aux; - - // mode equal the number of components for each pixel - mode = info->pixelDepth / 8; - // total is the number of unsigned chars we'll have to read - total = info->height * info->width * mode; - - fread(info->imageData,sizeof(unsigned char),total,file); - - // mode=3 or 4 implies that the image is RGB(A). However TGA - // stores it as BGR(A) so we'll have to swap R and B. - if (mode >= 3) - for (i=0; i < total; i+= mode) { - aux = info->imageData[i]; - info->imageData[i] = info->imageData[i+2]; - info->imageData[i+2] = aux; - } -} - -// loads the RLE encoded image pixels. You shouldn't call this function directly -void tgaLoadRLEImageData(FILE *file, tImageTGA *info) -{ - unsigned int mode,total,i, index = 0; - unsigned char aux[4], runlength = 0; - unsigned int skip = 0, flag = 0; - - // mode equal the number of components for each pixel - mode = info->pixelDepth / 8; - // total is the number of unsigned chars we'll have to read - total = info->height * info->width; - - for( i = 0; i < total; i++ ) - { - // if we have a run length pending, run it - if ( runlength != 0 ) - { - // we do, update the run length count - runlength--; - skip = (flag != 0); - } - else - { - // otherwise, read in the run length token - if ( fread(&runlength,sizeof(unsigned char),1,file) != 1 ) - return; - - // see if it's a RLE encoded sequence - flag = runlength & 0x80; - if ( flag ) runlength -= 128; - skip = 0; - } - - // do we need to skip reading this pixel? - if ( !skip ) - { - // no, read in the pixel data - if ( fread(aux,sizeof(unsigned char),mode,file) != mode ) - return; - - // mode=3 or 4 implies that the image is RGB(A). However TGA - // stores it as BGR(A) so we'll have to swap R and B. - if ( mode >= 3 ) - { - unsigned char tmp; - - tmp = aux[0]; - aux[0] = aux[2]; - aux[2] = tmp; - } - } - - // add the pixel to our image - memcpy(&info->imageData[index], aux, mode); - index += mode; - } -} - -void tgaFlipImage( tImageTGA *info ) -{ - // mode equal the number of components for each pixel - int mode = info->pixelDepth / 8; - int rowbytes = info->width*mode; - unsigned char *row = (unsigned char *)malloc(rowbytes); - int y; - - if (row == NULL) return; - - for( y = 0; y < (info->height/2); y++ ) - { - memcpy(row, &info->imageData[y*rowbytes],rowbytes); - memcpy(&info->imageData[y*rowbytes], &info->imageData[(info->height-(y+1))*rowbytes], rowbytes); - memcpy(&info->imageData[(info->height-(y+1))*rowbytes], row, rowbytes); - } - - free(row); - info->flipped = 0; -} - -// this is the function to call when we want to load an image -tImageTGA * tgaLoad(const char *filename) { - - FILE *file; - tImageTGA *info; - int mode,total; - - // allocate memory for the info struct and check! - info = (tImageTGA *)malloc(sizeof(tImageTGA)); - if (info == NULL) - return(NULL); - - - // open the file for reading (binary mode) - file = fopen(filename, "rb"); - if (file == NULL) { - info->status = TGA_ERROR_FILE_OPEN; - return(info); - } - - // load the header - tgaLoadHeader(file,info); - - // check for errors when loading the header - if (ferror(file)) { - info->status = TGA_ERROR_READING_FILE; - fclose(file); - return(info); - } - - // check if the image is color indexed - if (info->type == 1) { - info->status = TGA_ERROR_INDEXED_COLOR; - fclose(file); - return(info); - } - // check for other types (compressed images) - if ((info->type != 2) && (info->type !=3) && (info->type !=10) ) { - info->status = TGA_ERROR_COMPRESSED_FILE; - fclose(file); - return(info); - } - - // mode equals the number of image components - mode = info->pixelDepth / 8; - // total is the number of unsigned chars to read - total = info->height * info->width * mode; - // allocate memory for image pixels - info->imageData = (unsigned char *)malloc(sizeof(unsigned char) * - total); - - // check to make sure we have the memory required - if (info->imageData == NULL) { - info->status = TGA_ERROR_MEMORY; - fclose(file); - return(info); - } - // finally load the image pixels - if ( info->type == 10 ) - tgaLoadRLEImageData(file, info); - else - tgaLoadImageData(file,info); - - // check for errors when reading the pixels - if (ferror(file)) { - info->status = TGA_ERROR_READING_FILE; - fclose(file); - return(info); - } - fclose(file); - info->status = TGA_OK; - - if ( info->flipped ) - { - tgaFlipImage( info ); - if ( info->flipped ) info->status = TGA_ERROR_MEMORY; - } - - return(info); -} - -// converts RGB to greyscale -void tgaRGBtogreyscale(tImageTGA *info) { - - int mode,i,j; - - unsigned char *newImageData; - - // if the image is already greyscale do nothing - if (info->pixelDepth == 8) - return; - - // compute the number of actual components - mode = info->pixelDepth / 8; - - // allocate an array for the new image data - newImageData = (unsigned char *)malloc(sizeof(unsigned char) * - info->height * info->width); - if (newImageData == NULL) { - return; - } - - // convert pixels: greyscale = o.30 * R + 0.59 * G + 0.11 * B - for (i = 0,j = 0; j < info->width * info->height; i +=mode, j++) - newImageData[j] = - (unsigned char)(0.30 * info->imageData[i] + - 0.59 * info->imageData[i+1] + - 0.11 * info->imageData[i+2]); - - - //free old image data - free(info->imageData); - - // reassign pixelDepth and type according to the new image type - info->pixelDepth = 8; - info->type = 3; - // reassing imageData to the new array. - info->imageData = newImageData; -} - -// releases the memory used for the image -void tgaDestroy(tImageTGA *info) { - - if (info != NULL) { - if (info->imageData != NULL) - free(info->imageData); - free(info); - } -} diff --git a/Example/libs/cocos2d/Support/TransformUtils.h b/Example/libs/cocos2d/Support/TransformUtils.h deleted file mode 100644 index ca5ff27..0000000 --- a/Example/libs/cocos2d/Support/TransformUtils.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#import "../ccMacros.h" - -#ifdef __CC_PLATFORM_IOS -#import -#import -#elif defined(__CC_PLATFORM_MAC) -#import -#import -#endif - -void CGAffineToGL(const CGAffineTransform *t, GLfloat *m); -void GLToCGAffine(const GLfloat *m, CGAffineTransform *t); diff --git a/Example/libs/cocos2d/Support/TransformUtils.m b/Example/libs/cocos2d/Support/TransformUtils.m deleted file mode 100644 index 73e132f..0000000 --- a/Example/libs/cocos2d/Support/TransformUtils.m +++ /dev/null @@ -1,47 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2009 Valentin Milea - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "TransformUtils.h" - -void CGAffineToGL(const CGAffineTransform *t, GLfloat *m) -{ - // | m[0] m[4] m[8] m[12] | | m11 m21 m31 m41 | | a c 0 tx | - // | m[1] m[5] m[9] m[13] | | m12 m22 m32 m42 | | b d 0 ty | - // | m[2] m[6] m[10] m[14] | <=> | m13 m23 m33 m43 | <=> | 0 0 1 0 | - // | m[3] m[7] m[11] m[15] | | m14 m24 m34 m44 | | 0 0 0 1 | - - m[2] = m[3] = m[6] = m[7] = m[8] = m[9] = m[11] = m[14] = 0.0f; - m[10] = m[15] = 1.0f; - m[0] = t->a; m[4] = t->c; m[12] = t->tx; - m[1] = t->b; m[5] = t->d; m[13] = t->ty; -} - -void GLToCGAffine(const GLfloat *m, CGAffineTransform *t) -{ - t->a = m[0]; t->c = m[4]; t->tx = m[12]; - t->b = m[1]; t->d = m[5]; t->ty = m[13]; -} - diff --git a/Example/libs/cocos2d/Support/ZipUtils.h b/Example/libs/cocos2d/Support/ZipUtils.h deleted file mode 100644 index 99034a9..0000000 --- a/Example/libs/cocos2d/Support/ZipUtils.h +++ /dev/null @@ -1,91 +0,0 @@ -/* cocos2d for iPhone - * - * http://www.cocos2d-iphone.org - * - * - * inflateMemory_ based on zlib example code - * http://www.zlib.net - * - * Some ideas were taken from: - * http://themanaworld.org/ - * from the mapreader.cpp file - * - */ - -#ifndef __CC_ZIP_UTILS_H -#define __CC_ZIP_UTILS_H - -#import - -#ifdef __cplusplus -extern "C" { -#endif - - /* XXX: pragma pack ??? */ - /** @struct CCZHeader - */ - struct CCZHeader { - uint8_t sig[4]; // signature. Should be 'CCZ!' 4 bytes - uint16_t compression_type; // should 0 - uint16_t version; // should be 2 (although version type==1 is also supported) - uint32_t reserved; // Reserverd for users. - uint32_t len; // size of the uncompressed file - }; - - enum { - CCZ_COMPRESSION_ZLIB, // zlib format. - CCZ_COMPRESSION_BZIP2, // bzip2 format (not supported yet) - CCZ_COMPRESSION_GZIP, // gzip format (not supported yet) - CCZ_COMPRESSION_NONE, // plain (not supported yet) - }; - -/** @file - * Zip helper functions - */ - -/** - * Inflates either zlib or gzip deflated memory. The inflated memory is - * expected to be freed by the caller. - * - * It will allocate 256k for the destination buffer. If it is not enought it will multiply the previous buffer size per 2, until there is enough memory. - * @returns the length of the deflated buffer - * - @since v0.8.1 - */ -int ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out); - -/** - * Inflates either zlib or gzip deflated memory. The inflated memory is - * expected to be freed by the caller. - * - * outLenghtHint is assumed to be the needed room to allocate the inflated buffer. - * - * @returns the length of the deflated buffer - * - @since v1.0.0 - */ -int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLenghtHint ); - - -/** inflates a GZip file into memory - * - * @returns the length of the deflated buffer - * - * @since v0.99.5 - */ -int ccInflateGZipFile(const char *filename, unsigned char **out); - -/** inflates a CCZ file into memory - * - * @returns the length of the deflated buffer - * - * @since v0.99.5 - */ -int ccInflateCCZFile(const char *filename, unsigned char **out); - - -#ifdef __cplusplus -} -#endif - -#endif // __CC_ZIP_UTILS_H diff --git a/Example/libs/cocos2d/Support/ZipUtils.m b/Example/libs/cocos2d/Support/ZipUtils.m deleted file mode 100644 index d3a2379..0000000 --- a/Example/libs/cocos2d/Support/ZipUtils.m +++ /dev/null @@ -1,250 +0,0 @@ -/* cocos2d for iPhone - * - * http://www.cocos2d-iphone.org - * - * - * Inflates either zlib or gzip deflated memory. The inflated memory is - * expected to be freed by the caller. - * - * inflateMemory_ based on zlib example code - * http://www.zlib.net - * - * Some ideas were taken from: - * http://themanaworld.org/ - * from the mapreader.cpp file - */ - -#import -#import -#import -#import - -#import "ZipUtils.h" -#import "CCFileUtils.h" -#import "../ccMacros.h" - -// memory in iPhone is precious -// Should buffer factor be 1.5 instead of 2 ? -#define BUFFER_INC_FACTOR (2) - -static int inflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, unsigned int outLenghtHint ) -{ - /* ret value */ - int err = Z_OK; - - int bufferSize = outLenghtHint; - *out = (unsigned char*) malloc(bufferSize); - - z_stream d_stream; /* decompression stream */ - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = in; - d_stream.avail_in = inLength; - d_stream.next_out = *out; - d_stream.avail_out = bufferSize; - - /* window size to hold 256k */ - if( (err = inflateInit2(&d_stream, 15 + 32)) != Z_OK ) - return err; - - for (;;) { - err = inflate(&d_stream, Z_NO_FLUSH); - - if (err == Z_STREAM_END) - break; - - switch (err) { - case Z_NEED_DICT: - err = Z_DATA_ERROR; - case Z_DATA_ERROR: - case Z_MEM_ERROR: - inflateEnd(&d_stream); - return err; - } - - // not enough memory ? - if (err != Z_STREAM_END) { - - unsigned char *tmp = realloc(*out, bufferSize * BUFFER_INC_FACTOR); - - /* not enough memory, ouch */ - if (! tmp ) { - CCLOG(@"cocos2d: ZipUtils: realloc failed"); - inflateEnd(&d_stream); - return Z_MEM_ERROR; - } - /* only assign to *out if tmp is valid. it's not guaranteed that realloc will reuse the memory */ - *out = tmp; - - d_stream.next_out = *out + bufferSize; - d_stream.avail_out = bufferSize; - bufferSize *= BUFFER_INC_FACTOR; - } - } - - - *outLength = bufferSize - d_stream.avail_out; - err = inflateEnd(&d_stream); - return err; -} - -int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLengthHint ) -{ - unsigned int outLength = 0; - int err = inflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint ); - - if (err != Z_OK || *out == NULL) { - if (err == Z_MEM_ERROR) - CCLOG(@"cocos2d: ZipUtils: Out of memory while decompressing map data!"); - - else if (err == Z_VERSION_ERROR) - CCLOG(@"cocos2d: ZipUtils: Incompatible zlib version!"); - - else if (err == Z_DATA_ERROR) - CCLOG(@"cocos2d: ZipUtils: Incorrect zlib compressed data!"); - - else - CCLOG(@"cocos2d: ZipUtils: Unknown error while decompressing map data!"); - - free(*out); - *out = NULL; - outLength = 0; - } - - return outLength; -} - -int ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out) -{ - // 256k for hint - return ccInflateMemoryWithHint(in, inLength, out, 256 * 1024 ); -} - -int ccInflateGZipFile(const char *path, unsigned char **out) -{ - int len; - unsigned int offset = 0; - - NSCAssert( out, @"ccInflateGZipFile: invalid 'out' parameter"); - NSCAssert( &*out, @"ccInflateGZipFile: invalid 'out' parameter"); - - gzFile inFile = gzopen(path, "rb"); - if( inFile == NULL ) { - CCLOG(@"cocos2d: ZipUtils: error open gzip file: %s", path); - return -1; - } - - /* 512k initial decompress buffer */ - int bufferSize = 512 * 1024; - unsigned int totalBufferSize = bufferSize; - - *out = malloc( bufferSize ); - if( ! out ) { - CCLOG(@"cocos2d: ZipUtils: out of memory"); - return -1; - } - - for (;;) { - len = gzread(inFile, *out + offset, bufferSize); - if (len < 0) { - CCLOG(@"cocos2d: ZipUtils: error in gzread"); - free( *out ); - *out = NULL; - return -1; - } - if (len == 0) - break; - - offset += len; - - // finish reading the file - if( len < bufferSize ) - break; - - bufferSize *= BUFFER_INC_FACTOR; - totalBufferSize += bufferSize; - unsigned char *tmp = realloc(*out, totalBufferSize ); - - if( ! tmp ) { - CCLOG(@"cocos2d: ZipUtils: out of memory"); - free( *out ); - *out = NULL; - return -1; - } - - *out = tmp; - } - - if (gzclose(inFile) != Z_OK) - CCLOG(@"cocos2d: ZipUtils: gzclose failed"); - - return offset; -} - -int ccInflateCCZFile(const char *path, unsigned char **out) -{ - NSCAssert( out, @"ccInflateCCZFile: invalid 'out' parameter"); - NSCAssert( &*out, @"ccInflateCCZFile: invalid 'out' parameter"); - - // load file into memory - unsigned char *compressed = NULL; - NSInteger fileLen = ccLoadFileIntoMemory( path, &compressed ); - if( fileLen < 0 ) { - CCLOG(@"cocos2d: Error loading CCZ compressed file"); - return -1; - } - - struct CCZHeader *header = (struct CCZHeader*) compressed; - - // verify header - if( header->sig[0] != 'C' || header->sig[1] != 'C' || header->sig[2] != 'Z' || header->sig[3] != '!' ) { - CCLOG(@"cocos2d: Invalid CCZ file"); - free(compressed); - return -1; - } - - // verify header version - uint16_t version = CFSwapInt16BigToHost( header->version ); - if( version > 2 ) { - CCLOG(@"cocos2d: Unsupported CCZ header format"); - free(compressed); - return -1; - } - - // verify compression format - if( CFSwapInt16BigToHost(header->compression_type) != CCZ_COMPRESSION_ZLIB ) { - CCLOG(@"cocos2d: CCZ Unsupported compression method"); - free(compressed); - return -1; - } - - uint32_t len = CFSwapInt32BigToHost( header->len ); - - *out = malloc( len ); - if(! *out ) - { - CCLOG(@"cocos2d: CCZ: Failed to allocate memory for texture"); - free(compressed); - return -1; - } - - - uLongf destlen = len; - uLongf source = (uLongf) compressed + sizeof(*header); - int ret = uncompress(*out, &destlen, (Bytef*)source, fileLen - sizeof(*header) ); - - free( compressed ); - - if( ret != Z_OK ) - { - CCLOG(@"cocos2d: CCZ: Failed to uncompress data"); - free( *out ); - *out = NULL; - return -1; - } - - - return len; -} diff --git a/Example/libs/cocos2d/Support/base64.c b/Example/libs/cocos2d/Support/base64.c deleted file mode 100644 index 1a7df47..0000000 --- a/Example/libs/cocos2d/Support/base64.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - public domain BASE64 code - - modified for cocos2d-iphone: http://www.cocos2d-iphone.org - */ - -#include -#include - -#include "base64.h" - -unsigned char alphabet[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -int _base64Decode( unsigned char *input, unsigned int input_len, unsigned char *output, unsigned int *output_len ); - -int _base64Decode( unsigned char *input, unsigned int input_len, unsigned char *output, unsigned int *output_len ) -{ - static char inalphabet[256], decoder[256]; - int i, bits, c, char_count, errors = 0; - unsigned int input_idx = 0; - unsigned int output_idx = 0; - - for (i = (sizeof alphabet) - 1; i >= 0 ; i--) { - inalphabet[alphabet[i]] = 1; - decoder[alphabet[i]] = i; - } - - char_count = 0; - bits = 0; - for( input_idx=0; input_idx < input_len ; input_idx++ ) { - c = input[ input_idx ]; - if (c == '=') - break; - if (c > 255 || ! inalphabet[c]) - continue; - bits += decoder[c]; - char_count++; - if (char_count == 4) { - output[ output_idx++ ] = (bits >> 16); - output[ output_idx++ ] = ((bits >> 8) & 0xff); - output[ output_idx++ ] = ( bits & 0xff); - bits = 0; - char_count = 0; - } else { - bits <<= 6; - } - } - - if( c == '=' ) { - switch (char_count) { - case 1: - fprintf(stderr, "base64Decode: encoding incomplete: at least 2 bits missing"); - errors++; - break; - case 2: - output[ output_idx++ ] = ( bits >> 10 ); - break; - case 3: - output[ output_idx++ ] = ( bits >> 16 ); - output[ output_idx++ ] = (( bits >> 8 ) & 0xff); - break; - } - } else if ( input_idx < input_len ) { - if (char_count) { - fprintf(stderr, "base64 encoding incomplete: at least %d bits truncated", - ((4 - char_count) * 6)); - errors++; - } - } - - *output_len = output_idx; - return errors; -} - -int base64Decode(unsigned char *in, unsigned int inLength, unsigned char **out) -{ - unsigned int outLength = 0; - - //should be enough to store 6-bit buffers in 8-bit buffers - *out = malloc( inLength * 3.0f / 4.0f + 1 ); - if( *out ) { - int ret = _base64Decode(in, inLength, *out, &outLength); - - if (ret > 0 ) - { - printf("Base64Utils: error decoding"); - free(*out); - *out = NULL; - outLength = 0; - } - } - return outLength; -} diff --git a/Example/libs/cocos2d/Support/base64.h b/Example/libs/cocos2d/Support/base64.h deleted file mode 100644 index 095fc98..0000000 --- a/Example/libs/cocos2d/Support/base64.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - public domain BASE64 code - - modified for cocos2d-iphone: http://www.cocos2d-iphone.org - */ - -#ifndef __CC_BASE64_DECODE_H -#define __CC_BASE64_DECODE_H - -#ifdef __cplusplus -extern "C" { -#endif - - -/** @file - base64 helper functions - */ - -/** - * Decodes a 64base encoded memory. The decoded memory is - * expected to be freed by the caller. - * - * @returns the length of the out buffer - * - @since v0.8.1 - */ -int base64Decode(unsigned char *in, unsigned int inLength, unsigned char **out); - -#ifdef __cplusplus -} -#endif - -#endif // __CC_BASE64_DECODE_H diff --git a/Example/libs/cocos2d/Support/ccCArray.h b/Example/libs/cocos2d/Support/ccCArray.h deleted file mode 100644 index 156ba4e..0000000 --- a/Example/libs/cocos2d/Support/ccCArray.h +++ /dev/null @@ -1,460 +0,0 @@ -/* Copyright (c) 2007 Scott Lembcke - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -/** - @file - Based on Chipmunk cpArray. - ccArray is a faster alternative to NSMutableArray, it does pretty much the - same thing (stores NSObjects and retains/releases them appropriately). It's - faster because: - - it uses a plain C interface so it doesn't incur Objective-c messaging overhead - - it assumes you know what you're doing, so it doesn't spend time on safety checks - (index out of bounds, required capacity etc.) - - comparisons are done using pointer equality instead of isEqual - - There are 2 kind of functions: - - ccArray functions that manipulates objective-c objects (retain and release are performanced) - - ccCArray functions that manipulates values like if they were standard C structures (no retain/release is performed) - */ - -#ifndef CC_ARRAY_H -#define CC_ARRAY_H - -#import - -#import -#import - -#import "../ccMacros.h" - - -#pragma mark - -#pragma mark ccArray for Objects - -// Easy integration -#define CCARRAYDATA_FOREACH(__array__, __object__) \ -__object__=__array__->arr[0]; for(NSUInteger i=0, num=__array__->num; iarr[i]) \ - -#if defined(__has_feature) && __has_feature(objc_arc) - typedef __strong id CCARRAY_ID; -#else - typedef id CCARRAY_ID; -#endif - -typedef struct ccArray { - NSUInteger num, max; - CCARRAY_ID *arr; -} ccArray; - -/** Allocates and initializes a new array with specified capacity */ -static inline ccArray* ccArrayNew(NSUInteger capacity) { - if (capacity == 0) - capacity = 1; - - ccArray *arr = (ccArray*)malloc( sizeof(ccArray) ); - arr->num = 0; - arr->arr = (CCARRAY_ID *)calloc(capacity, sizeof(id)); - arr->max = capacity; - - return arr; -} - -static inline void ccArrayRemoveAllObjects(ccArray *arr); - -/** Frees array after removing all remaining objects. Silently ignores nil arr. */ -static inline void ccArrayFree(ccArray *arr) -{ - if( arr == nil ) return; - - ccArrayRemoveAllObjects(arr); - - free(arr->arr); - free(arr); -} - -/** Doubles array capacity */ -static inline void ccArrayDoubleCapacity(ccArray *arr) -{ - arr->max *= 2; - CCARRAY_ID *newArr = (CCARRAY_ID *)realloc( arr->arr, arr->max * sizeof(id) ); - // will fail when there's not enough memory - NSCAssert(newArr != NULL, @"ccArrayDoubleCapacity failed. Not enough memory"); - arr->arr = newArr; -} - -/** Increases array capacity such that max >= num + extra. */ -static inline void ccArrayEnsureExtraCapacity(ccArray *arr, NSUInteger extra) -{ - while (arr->max < arr->num + extra) - ccArrayDoubleCapacity(arr); -} - -/** shrinks the array so the memory footprint corresponds with the number of items */ -static inline void ccArrayShrink(ccArray *arr) -{ - NSUInteger newSize; - - //only resize when necessary - if (arr->max > arr->num && !(arr->num==0 && arr->max==1)) - { - if (arr->num!=0) - { - newSize=arr->num; - arr->max=arr->num; - } - else - {//minimum capacity of 1, with 0 elements the array would be free'd by realloc - newSize=1; - arr->max=1; - } - - arr->arr = (CCARRAY_ID *) realloc(arr->arr,newSize * sizeof(id) ); - NSCAssert(arr->arr!=NULL,@"could not reallocate the memory"); - } -} - -/** Returns index of first occurence of object, NSNotFound if object not found. */ -static inline NSUInteger ccArrayGetIndexOfObject(ccArray *arr, id object) -{ - for( NSUInteger i = 0; i < arr->num; i++) - if( arr->arr[i] == object ) return i; - - return NSNotFound; -} - -/** Returns a Boolean value that indicates whether object is present in array. */ -static inline BOOL ccArrayContainsObject(ccArray *arr, id object) -{ - return ccArrayGetIndexOfObject(arr, object) != NSNotFound; -} - -/** Appends an object. Bahaviour undefined if array doesn't have enough capacity. */ -static inline void ccArrayAppendObject(ccArray *arr, id object) -{ - arr->arr[arr->num] = CC_ARC_RETAIN(object); - arr->num++; -} - -/** Appends an object. Capacity of arr is increased if needed. */ -static inline void ccArrayAppendObjectWithResize(ccArray *arr, id object) -{ - ccArrayEnsureExtraCapacity(arr, 1); - ccArrayAppendObject(arr, object); -} - -/** Appends objects from plusArr to arr. Behaviour undefined if arr doesn't have - enough capacity. */ -static inline void ccArrayAppendArray(ccArray *arr, ccArray *plusArr) -{ - for( NSUInteger i = 0; i < plusArr->num; i++) - ccArrayAppendObject(arr, plusArr->arr[i]); -} - -/** Appends objects from plusArr to arr. Capacity of arr is increased if needed. */ -static inline void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr) -{ - ccArrayEnsureExtraCapacity(arr, plusArr->num); - ccArrayAppendArray(arr, plusArr); -} - -/** Inserts an object at index */ -static inline void ccArrayInsertObjectAtIndex(ccArray *arr, id object, NSUInteger index) -{ - NSCAssert(index<=arr->num, @"Invalid index. Out of bounds"); - - ccArrayEnsureExtraCapacity(arr, 1); - - NSUInteger remaining = arr->num - index; - if( remaining > 0) - memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(id) * remaining ); - - arr->arr[index] = CC_ARC_RETAIN(object); - arr->num++; -} - -/** Swaps two objects */ -static inline void ccArraySwapObjectsAtIndexes(ccArray *arr, NSUInteger index1, NSUInteger index2) -{ - NSCAssert(index1 < arr->num, @"(1) Invalid index. Out of bounds"); - NSCAssert(index2 < arr->num, @"(2) Invalid index. Out of bounds"); - - id object1 = arr->arr[index1]; - - arr->arr[index1] = arr->arr[index2]; - arr->arr[index2] = object1; -} - -/** Removes all objects from arr */ -static inline void ccArrayRemoveAllObjects(ccArray *arr) -{ - while( arr->num > 0 ) - CC_ARC_RELEASE(arr->arr[--arr->num]); -} - -/** Removes object at specified index and pushes back all subsequent objects. - Behaviour undefined if index outside [0, num-1]. */ -static inline void ccArrayRemoveObjectAtIndex(ccArray *arr, NSUInteger index) -{ - CC_ARC_RELEASE(arr->arr[index]); - arr->num--; - - NSUInteger remaining = arr->num - index; - if(remaining>0) - memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(id)); -} - -/** Removes object at specified index and fills the gap with the last object, - thereby avoiding the need to push back subsequent objects. - Behaviour undefined if index outside [0, num-1]. */ -static inline void ccArrayFastRemoveObjectAtIndex(ccArray *arr, NSUInteger index) -{ - CC_ARC_RELEASE(arr->arr[index]); - NSUInteger last = --arr->num; - arr->arr[index] = arr->arr[last]; -} - -static inline void ccArrayFastRemoveObject(ccArray *arr, id object) -{ - NSUInteger index = ccArrayGetIndexOfObject(arr, object); - if (index != NSNotFound) - ccArrayFastRemoveObjectAtIndex(arr, index); -} - -/** Searches for the first occurance of object and removes it. If object is not - found the function has no effect. */ -static inline void ccArrayRemoveObject(ccArray *arr, id object) -{ - NSUInteger index = ccArrayGetIndexOfObject(arr, object); - if (index != NSNotFound) - ccArrayRemoveObjectAtIndex(arr, index); -} - -/** Removes from arr all objects in minusArr. For each object in minusArr, the - first matching instance in arr will be removed. */ -static inline void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) -{ - for( NSUInteger i = 0; i < minusArr->num; i++) - ccArrayRemoveObject(arr, minusArr->arr[i]); -} - -/** Removes from arr all objects in minusArr. For each object in minusArr, all - matching instances in arr will be removed. */ -static inline void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) -{ - NSUInteger back = 0; - - for( NSUInteger i = 0; i < arr->num; i++) { - if( ccArrayContainsObject(minusArr, arr->arr[i]) ) { - CC_ARC_RELEASE(arr->arr[i]); - back++; - } else - arr->arr[i - back] = arr->arr[i]; - } - - arr->num -= back; -} - -/** Sends to each object in arr the message identified by given selector. */ -static inline void ccArrayMakeObjectsPerformSelector(ccArray *arr, SEL sel) -{ - for( NSUInteger i = 0; i < arr->num; i++) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-performSelector-leaks" - [arr->arr[i] performSelector:sel]; -#pragma clang diagnostic pop -} - -static inline void ccArrayMakeObjectsPerformSelectorWithObject(ccArray *arr, SEL sel, id object) -{ - for( NSUInteger i = 0; i < arr->num; i++) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-performSelector-leaks" - [arr->arr[i] performSelector:sel withObject:object]; -#pragma clang diagnostic pop -} - - -#pragma mark - -#pragma mark ccCArray for Values (c structures) - -typedef ccArray ccCArray; - -static inline void ccCArrayRemoveAllValues(ccCArray *arr); - -/** Allocates and initializes a new C array with specified capacity */ -static inline ccCArray* ccCArrayNew(NSUInteger capacity) { - if (capacity == 0) - capacity = 1; - - ccCArray *arr = (ccCArray*)malloc( sizeof(ccCArray) ); - arr->num = 0; - arr->arr = (CCARRAY_ID *) malloc( capacity * sizeof(id) ); - arr->max = capacity; - - return arr; -} - -/** Frees C array after removing all remaining values. Silently ignores nil arr. */ -static inline void ccCArrayFree(ccCArray *arr) -{ - if( arr == nil ) return; - - ccCArrayRemoveAllValues(arr); - - free(arr->arr); - free(arr); -} - -/** Doubles C array capacity */ -static inline void ccCArrayDoubleCapacity(ccCArray *arr) -{ - ccArrayDoubleCapacity(arr); -} - -/** Increases array capacity such that max >= num + extra. */ -static inline void ccCArrayEnsureExtraCapacity(ccCArray *arr, NSUInteger extra) -{ - ccArrayEnsureExtraCapacity(arr,extra); -} - -/** Returns index of first occurence of value, NSNotFound if value not found. */ -static inline NSUInteger ccCArrayGetIndexOfValue(ccCArray *arr, CCARRAY_ID value) -{ - for( NSUInteger i = 0; i < arr->num; i++) - if( arr->arr[i] == value ) return i; - return NSNotFound; -} - -/** Returns a Boolean value that indicates whether value is present in the C array. */ -static inline BOOL ccCArrayContainsValue(ccCArray *arr, CCARRAY_ID value) -{ - return ccCArrayGetIndexOfValue(arr, value) != NSNotFound; -} - -/** Inserts a value at a certain position. Behaviour undefined if aray doesn't have enough capacity */ -static inline void ccCArrayInsertValueAtIndex( ccCArray *arr, CCARRAY_ID value, NSUInteger index) -{ - NSCAssert( index < arr->max, @"ccCArrayInsertValueAtIndex: invalid index"); - - NSUInteger remaining = arr->num - index; - - // last Value doesn't need to be moved - if( remaining > 0) { - // tex coordinates - memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(void*) * remaining ); - } - - arr->num++; - arr->arr[index] = value; -} - -/** Appends an value. Bahaviour undefined if array doesn't have enough capacity. */ -static inline void ccCArrayAppendValue(ccCArray *arr, CCARRAY_ID value) -{ - arr->arr[arr->num] = (id) value; - arr->num++; -} - -/** Appends an value. Capacity of arr is increased if needed. */ -static inline void ccCArrayAppendValueWithResize(ccCArray *arr, CCARRAY_ID value) -{ - ccCArrayEnsureExtraCapacity(arr, 1); - ccCArrayAppendValue(arr, value); -} - -/** Appends values from plusArr to arr. Behaviour undefined if arr doesn't have - enough capacity. */ -static inline void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr) -{ - for( NSUInteger i = 0; i < plusArr->num; i++) - ccCArrayAppendValue(arr, plusArr->arr[i]); -} - -/** Appends values from plusArr to arr. Capacity of arr is increased if needed. */ -static inline void ccCArrayAppendArrayWithResize(ccCArray *arr, ccCArray *plusArr) -{ - ccCArrayEnsureExtraCapacity(arr, plusArr->num); - ccCArrayAppendArray(arr, plusArr); -} - -/** Removes all values from arr */ -static inline void ccCArrayRemoveAllValues(ccCArray *arr) -{ - arr->num = 0; -} - -/** Removes value at specified index and pushes back all subsequent values. - Behaviour undefined if index outside [0, num-1]. - @since v0.99.4 - */ -static inline void ccCArrayRemoveValueAtIndex(ccCArray *arr, NSUInteger index) -{ - for( NSUInteger last = --arr->num; index < last; index++) - arr->arr[index] = arr->arr[index + 1]; -} - -/** Removes value at specified index and fills the gap with the last value, - thereby avoiding the need to push back subsequent values. - Behaviour undefined if index outside [0, num-1]. - @since v0.99.4 - */ -static inline void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, NSUInteger index) -{ - NSUInteger last = --arr->num; - arr->arr[index] = arr->arr[last]; -} - -/** Searches for the first occurance of value and removes it. If value is not found the function has no effect. - @since v0.99.4 - */ -static inline void ccCArrayRemoveValue(ccCArray *arr, CCARRAY_ID value) -{ - NSUInteger index = ccCArrayGetIndexOfValue(arr, value); - if (index != NSNotFound) - ccCArrayRemoveValueAtIndex(arr, index); -} - -/** Removes from arr all values in minusArr. For each Value in minusArr, the first matching instance in arr will be removed. - @since v0.99.4 - */ -static inline void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) -{ - for( NSUInteger i = 0; i < minusArr->num; i++) - ccCArrayRemoveValue(arr, minusArr->arr[i]); -} - -/** Removes from arr all values in minusArr. For each value in minusArr, all matching instances in arr will be removed. - @since v0.99.4 - */ -static inline void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr) -{ - NSUInteger back = 0; - - for( NSUInteger i = 0; i < arr->num; i++) { - if( ccCArrayContainsValue(minusArr, arr->arr[i]) ) { - back++; - } else - arr->arr[i - back] = arr->arr[i]; - } - - arr->num -= back; -} -#endif // CC_ARRAY_H diff --git a/Example/libs/cocos2d/Support/ccUtils.c b/Example/libs/cocos2d/Support/ccUtils.c deleted file mode 100644 index 27a122d..0000000 --- a/Example/libs/cocos2d/Support/ccUtils.c +++ /dev/null @@ -1,20 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - */ - -/* - ccNextPOT function is licensed under the same license that is used in CCTexture2D.m. - */ -#include "ccUtils.h" - -unsigned long ccNextPOT(unsigned long x) -{ - x = x - 1; - x = x | (x >> 1); - x = x | (x >> 2); - x = x | (x >> 4); - x = x | (x >> 8); - x = x | (x >>16); - return x + 1; -} diff --git a/Example/libs/cocos2d/Support/ccUtils.h b/Example/libs/cocos2d/Support/ccUtils.h deleted file mode 100644 index 5f84ff3..0000000 --- a/Example/libs/cocos2d/Support/ccUtils.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - */ - -#ifndef __CC_UTILS_H -#define __CC_UTILS_H - -#ifdef __cplusplus -extern "C" { -#endif - -/** @file ccUtils.h - Misc free functions - */ - -/* - ccNextPOT function is licensed under the same license that is used in CCTexture2D.m. - */ - -/** returns the Next Power of Two value. - - Examples: - - If "value" is 15, it will return 16. - - If "value" is 16, it will return 16. - - If "value" is 17, it will return 32. - - @since v0.99.5 - */ -unsigned long ccNextPOT( unsigned long value ); - -#ifdef __cplusplus -} -#endif - -#endif // ! __CC_UTILS_H diff --git a/Example/libs/cocos2d/Support/uthash.h b/Example/libs/cocos2d/Support/uthash.h deleted file mode 100644 index e190ef7..0000000 --- a/Example/libs/cocos2d/Support/uthash.h +++ /dev/null @@ -1,972 +0,0 @@ -/* -Copyright (c) 2003-2010, Troy D. Hanson http://uthash.sourceforge.net -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef UTHASH_H -#define UTHASH_H - -#include /* memcmp,strlen */ -#include /* ptrdiff_t */ - -/* These macros use decltype or the earlier __typeof GNU extension. - As decltype is only available in newer compilers (VS2010 or gcc 4.3+ - when compiling c++ source) this code uses whatever method is needed - or, for VS2008 where neither is available, uses casting workarounds. */ -#ifdef _MSC_VER /* MS compiler */ -#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ -#define DECLTYPE(x) (decltype(x)) -#else /* VS2008 or older (or VS2010 in C mode) */ -#define NO_DECLTYPE -#define DECLTYPE(x) -#endif -#else /* GNU, Sun and other compilers */ -#define DECLTYPE(x) (__typeof(x)) -#endif - -#ifdef NO_DECLTYPE -#define DECLTYPE_ASSIGN(dst,src) \ -do { \ - char **_da_dst = (char**)(&(dst)); \ - *_da_dst = (char*)(src); \ -} while(0) -#else -#define DECLTYPE_ASSIGN(dst,src) \ -do { \ - (dst) = DECLTYPE(dst)(src); \ -} while(0) -#endif - -/* a number of the hash function use uint32_t which isn't defined on win32 */ -#ifdef _MSC_VER -typedef unsigned int uint32_t; -#else -#include /* uint32_t */ -#endif - -#define UTHASH_VERSION 1.9.3 - -#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ -#define uthash_malloc(sz) malloc(sz) /* malloc fcn */ -#define uthash_free(ptr,sz) free(ptr) /* free fcn */ - -#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ -#define uthash_expand_fyi(tbl) /* can be defined to log expands */ - -/* initial number of buckets */ -#define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */ -#define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of buckets */ -#define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reaches */ - -/* calculate the element whose hash handle address is hhe */ -#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) - -#define HASH_FIND(hh,head,keyptr,keylen,out) \ -do { \ - unsigned _hf_bkt,_hf_hashv; \ - out=NULL; \ - if (head) { \ - HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt); \ - if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) { \ - HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], \ - keyptr,keylen,out); \ - } \ - } \ -} while (0) - -#ifdef HASH_BLOOM -#define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM) -#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0) -#define HASH_BLOOM_MAKE(tbl) \ -do { \ - (tbl)->bloom_nbits = HASH_BLOOM; \ - (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ - if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ - memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ - (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ -} while (0); - -#define HASH_BLOOM_FREE(tbl) \ -do { \ - uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ -} while (0); - -#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) -#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) - -#define HASH_BLOOM_ADD(tbl,hashv) \ - HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) - -#define HASH_BLOOM_TEST(tbl,hashv) \ - HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) - -#else -#define HASH_BLOOM_MAKE(tbl) -#define HASH_BLOOM_FREE(tbl) -#define HASH_BLOOM_ADD(tbl,hashv) -#define HASH_BLOOM_TEST(tbl,hashv) (1) -#endif - -#define HASH_MAKE_TABLE(hh,head) \ -do { \ - (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ - sizeof(UT_hash_table)); \ - if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ - memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ - (head)->hh.tbl->tail = &((head)->hh); \ - (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ - (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ - (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ - (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ - HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ - if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ - memset((head)->hh.tbl->buckets, 0, \ - HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ - HASH_BLOOM_MAKE((head)->hh.tbl); \ - (head)->hh.tbl->signature = HASH_SIGNATURE; \ -} while(0) - -#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ - HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add) - -#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ -do { \ - unsigned _ha_bkt; \ - (add)->hh.next = NULL; \ - (add)->hh.key = (char*)keyptr; \ - (add)->hh.keylen = keylen_in; \ - if (!(head)) { \ - head = (add); \ - (head)->hh.prev = NULL; \ - HASH_MAKE_TABLE(hh,head); \ - } else { \ - (head)->hh.tbl->tail->next = (add); \ - (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ - (head)->hh.tbl->tail = &((add)->hh); \ - } \ - (head)->hh.tbl->num_items++; \ - (add)->hh.tbl = (head)->hh.tbl; \ - HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets, \ - (add)->hh.hashv, _ha_bkt); \ - HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh); \ - HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv); \ - HASH_EMIT_KEY(hh,head,keyptr,keylen_in); \ - HASH_FSCK(hh,head); \ -} while(0) - -#define HASH_TO_BKT( hashv, num_bkts, bkt ) \ -do { \ - bkt = ((hashv) & ((num_bkts) - 1)); \ -} while(0) - -/* delete "delptr" from the hash table. - * "the usual" patch-up process for the app-order doubly-linked-list. - * The use of _hd_hh_del below deserves special explanation. - * These used to be expressed using (delptr) but that led to a bug - * if someone used the same symbol for the head and deletee, like - * HASH_DELETE(hh,users,users); - * We want that to work, but by changing the head (users) below - * we were forfeiting our ability to further refer to the deletee (users) - * in the patch-up process. Solution: use scratch space to - * copy the deletee pointer, then the latter references are via that - * scratch pointer rather than through the repointed (users) symbol. - */ -#define HASH_DELETE(hh,head,delptr) \ -do { \ - unsigned _hd_bkt; \ - struct UT_hash_handle *_hd_hh_del; \ - if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ - uthash_free((head)->hh.tbl->buckets, \ - (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ - HASH_BLOOM_FREE((head)->hh.tbl); \ - uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ - head = NULL; \ - } else { \ - _hd_hh_del = &((delptr)->hh); \ - if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ - (head)->hh.tbl->tail = \ - (UT_hash_handle*)((char*)((delptr)->hh.prev) + \ - (head)->hh.tbl->hho); \ - } \ - if ((delptr)->hh.prev) { \ - ((UT_hash_handle*)((char*)((delptr)->hh.prev) + \ - (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ - } else { \ - DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ - } \ - if (_hd_hh_del->next) { \ - ((UT_hash_handle*)((char*)_hd_hh_del->next + \ - (head)->hh.tbl->hho))->prev = \ - _hd_hh_del->prev; \ - } \ - HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ - HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ - (head)->hh.tbl->num_items--; \ - } \ - HASH_FSCK(hh,head); \ -} while (0) - - -/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ -#define HASH_FIND_STR(head,findstr,out) \ - HASH_FIND(hh,head,findstr,strlen(findstr),out) -#define HASH_ADD_STR(head,strfield,add) \ - HASH_ADD(hh,head,strfield,strlen(add->strfield),add) -#define HASH_FIND_INT(head,findint,out) \ - HASH_FIND(hh,head,findint,sizeof(int),out) -#define HASH_ADD_INT(head,intfield,add) \ - HASH_ADD(hh,head,intfield,sizeof(int),add) -#define HASH_FIND_PTR(head,findptr,out) \ - HASH_FIND(hh,head,findptr,sizeof(void *),out) -#define HASH_ADD_PTR(head,ptrfield,add) \ - HASH_ADD(hh,head,ptrfield,sizeof(void *),add) -#define HASH_DEL(head,delptr) \ - HASH_DELETE(hh,head,delptr) - -/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. - * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. - */ -#ifdef HASH_DEBUG -#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) -#define HASH_FSCK(hh,head) \ -do { \ - unsigned _bkt_i; \ - unsigned _count, _bkt_count; \ - char *_prev; \ - struct UT_hash_handle *_thh; \ - if (head) { \ - _count = 0; \ - for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ - _bkt_count = 0; \ - _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ - _prev = NULL; \ - while (_thh) { \ - if (_prev != (char*)(_thh->hh_prev)) { \ - HASH_OOPS("invalid hh_prev %p, actual %p\n", \ - _thh->hh_prev, _prev ); \ - } \ - _bkt_count++; \ - _prev = (char*)(_thh); \ - _thh = _thh->hh_next; \ - } \ - _count += _bkt_count; \ - if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ - HASH_OOPS("invalid bucket count %d, actual %d\n", \ - (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ - } \ - } \ - if (_count != (head)->hh.tbl->num_items) { \ - HASH_OOPS("invalid hh item count %d, actual %d\n", \ - (head)->hh.tbl->num_items, _count ); \ - } \ - /* traverse hh in app order; check next/prev integrity, count */ \ - _count = 0; \ - _prev = NULL; \ - _thh = &(head)->hh; \ - while (_thh) { \ - _count++; \ - if (_prev !=(char*)(_thh->prev)) { \ - HASH_OOPS("invalid prev %p, actual %p\n", \ - _thh->prev, _prev ); \ - } \ - _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ - _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ - (head)->hh.tbl->hho) : NULL ); \ - } \ - if (_count != (head)->hh.tbl->num_items) { \ - HASH_OOPS("invalid app item count %d, actual %d\n", \ - (head)->hh.tbl->num_items, _count ); \ - } \ - } \ -} while (0) -#else -#define HASH_FSCK(hh,head) -#endif - -/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to - * the descriptor to which this macro is defined for tuning the hash function. - * The app can #include to get the prototype for write(2). */ -#ifdef HASH_EMIT_KEYS -#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ -do { \ - unsigned _klen = fieldlen; \ - write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ - write(HASH_EMIT_KEYS, keyptr, fieldlen); \ -} while (0) -#else -#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) -#endif - -/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ -#ifdef HASH_FUNCTION -#define HASH_FCN HASH_FUNCTION -#else -#define HASH_FCN HASH_JEN -#endif - -/* The Bernstein hash function, used in Perl prior to v5.6 */ -#define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _hb_keylen=keylen; \ - char *_hb_key=(char*)(key); \ - (hashv) = 0; \ - while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ - bkt = (hashv) & (num_bkts-1); \ -} while (0) - - -/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at - * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ -#define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _sx_i; \ - char *_hs_key=(char*)(key); \ - hashv = 0; \ - for(_sx_i=0; _sx_i < keylen; _sx_i++) \ - hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ - bkt = hashv & (num_bkts-1); \ -} while (0) - -#define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _fn_i; \ - char *_hf_key=(char*)(key); \ - hashv = 2166136261UL; \ - for(_fn_i=0; _fn_i < keylen; _fn_i++) \ - hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ - bkt = hashv & (num_bkts-1); \ -} while(0); - -#define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _ho_i; \ - char *_ho_key=(char*)(key); \ - hashv = 0; \ - for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ - hashv += _ho_key[_ho_i]; \ - hashv += (hashv << 10); \ - hashv ^= (hashv >> 6); \ - } \ - hashv += (hashv << 3); \ - hashv ^= (hashv >> 11); \ - hashv += (hashv << 15); \ - bkt = hashv & (num_bkts-1); \ -} while(0) - -#define HASH_JEN_MIX(a,b,c) \ -do { \ - a -= b; a -= c; a ^= ( c >> 13 ); \ - b -= c; b -= a; b ^= ( a << 8 ); \ - c -= a; c -= b; c ^= ( b >> 13 ); \ - a -= b; a -= c; a ^= ( c >> 12 ); \ - b -= c; b -= a; b ^= ( a << 16 ); \ - c -= a; c -= b; c ^= ( b >> 5 ); \ - a -= b; a -= c; a ^= ( c >> 3 ); \ - b -= c; b -= a; b ^= ( a << 10 ); \ - c -= a; c -= b; c ^= ( b >> 15 ); \ -} while (0) - -#define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _hj_i,_hj_j,_hj_k; \ - char *_hj_key=(char*)(key); \ - hashv = 0xfeedbeef; \ - _hj_i = _hj_j = 0x9e3779b9; \ - _hj_k = keylen; \ - while (_hj_k >= 12) { \ - _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ - + ( (unsigned)_hj_key[2] << 16 ) \ - + ( (unsigned)_hj_key[3] << 24 ) ); \ - _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ - + ( (unsigned)_hj_key[6] << 16 ) \ - + ( (unsigned)_hj_key[7] << 24 ) ); \ - hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ - + ( (unsigned)_hj_key[10] << 16 ) \ - + ( (unsigned)_hj_key[11] << 24 ) ); \ - \ - HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ - \ - _hj_key += 12; \ - _hj_k -= 12; \ - } \ - hashv += keylen; \ - switch ( _hj_k ) { \ - case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ - case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ - case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ - case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ - case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ - case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ - case 5: _hj_j += _hj_key[4]; \ - case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ - case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ - case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ - case 1: _hj_i += _hj_key[0]; \ - } \ - HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ - bkt = hashv & (num_bkts-1); \ -} while(0) - -/* The Paul Hsieh hash function */ -#undef get16bits -#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ - || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) -#define get16bits(d) (*((const uint16_t *) (d))) -#endif - -#if !defined (get16bits) -#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ - +(uint32_t)(((const uint8_t *)(d))[0]) ) -#endif -#define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ -do { \ - char *_sfh_key=(char*)(key); \ - uint32_t _sfh_tmp, _sfh_len = keylen; \ - \ - int _sfh_rem = _sfh_len & 3; \ - _sfh_len >>= 2; \ - hashv = 0xcafebabe; \ - \ - /* Main loop */ \ - for (;_sfh_len > 0; _sfh_len--) { \ - hashv += get16bits (_sfh_key); \ - _sfh_tmp = (get16bits (_sfh_key+2) << 11) ^ hashv; \ - hashv = (hashv << 16) ^ _sfh_tmp; \ - _sfh_key += 2*sizeof (uint16_t); \ - hashv += hashv >> 11; \ - } \ - \ - /* Handle end cases */ \ - switch (_sfh_rem) { \ - case 3: hashv += get16bits (_sfh_key); \ - hashv ^= hashv << 16; \ - hashv ^= _sfh_key[sizeof (uint16_t)] << 18; \ - hashv += hashv >> 11; \ - break; \ - case 2: hashv += get16bits (_sfh_key); \ - hashv ^= hashv << 11; \ - hashv += hashv >> 17; \ - break; \ - case 1: hashv += *_sfh_key; \ - hashv ^= hashv << 10; \ - hashv += hashv >> 1; \ - } \ - \ - /* Force "avalanching" of final 127 bits */ \ - hashv ^= hashv << 3; \ - hashv += hashv >> 5; \ - hashv ^= hashv << 4; \ - hashv += hashv >> 17; \ - hashv ^= hashv << 25; \ - hashv += hashv >> 6; \ - bkt = hashv & (num_bkts-1); \ -} while(0); - -#ifdef HASH_USING_NO_STRICT_ALIASING -/* The MurmurHash exploits some CPU's (e.g. x86) tolerance for unaligned reads. - * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. - * So MurmurHash comes in two versions, the faster unaligned one and the slower - * aligned one. We only use the faster one on CPU's where we know it's safe. - * - * Note the preprocessor built-in defines can be emitted using: - * - * gcc -m64 -dM -E - < /dev/null (on gcc) - * cc -## a.c (where a.c is a simple test file) (Sun Studio) - */ -#if (defined(__i386__) || defined(__x86_64__)) -#define HASH_MUR HASH_MUR_UNALIGNED -#else -#define HASH_MUR HASH_MUR_ALIGNED -#endif - -/* Appleby's MurmurHash fast version for unaligned-tolerant archs like i386 */ -#define HASH_MUR_UNALIGNED(key,keylen,num_bkts,hashv,bkt) \ -do { \ - const unsigned int _mur_m = 0x5bd1e995; \ - const int _mur_r = 24; \ - hashv = 0xcafebabe ^ keylen; \ - char *_mur_key = (char *)(key); \ - uint32_t _mur_tmp, _mur_len = keylen; \ - \ - for (;_mur_len >= 4; _mur_len-=4) { \ - _mur_tmp = *(uint32_t *)_mur_key; \ - _mur_tmp *= _mur_m; \ - _mur_tmp ^= _mur_tmp >> _mur_r; \ - _mur_tmp *= _mur_m; \ - hashv *= _mur_m; \ - hashv ^= _mur_tmp; \ - _mur_key += 4; \ - } \ - \ - switch(_mur_len) \ - { \ - case 3: hashv ^= _mur_key[2] << 16; \ - case 2: hashv ^= _mur_key[1] << 8; \ - case 1: hashv ^= _mur_key[0]; \ - hashv *= _mur_m; \ - }; \ - \ - hashv ^= hashv >> 13; \ - hashv *= _mur_m; \ - hashv ^= hashv >> 15; \ - \ - bkt = hashv & (num_bkts-1); \ -} while(0) - -/* Appleby's MurmurHash version for alignment-sensitive archs like Sparc */ -#define HASH_MUR_ALIGNED(key,keylen,num_bkts,hashv,bkt) \ -do { \ - const unsigned int _mur_m = 0x5bd1e995; \ - const int _mur_r = 24; \ - hashv = 0xcafebabe ^ (keylen); \ - char *_mur_key = (char *)(key); \ - uint32_t _mur_len = keylen; \ - int _mur_align = (int)_mur_key & 3; \ - \ - if (_mur_align && (_mur_len >= 4)) { \ - unsigned _mur_t = 0, _mur_d = 0; \ - switch(_mur_align) { \ - case 1: _mur_t |= _mur_key[2] << 16; \ - case 2: _mur_t |= _mur_key[1] << 8; \ - case 3: _mur_t |= _mur_key[0]; \ - } \ - _mur_t <<= (8 * _mur_align); \ - _mur_key += 4-_mur_align; \ - _mur_len -= 4-_mur_align; \ - int _mur_sl = 8 * (4-_mur_align); \ - int _mur_sr = 8 * _mur_align; \ - \ - for (;_mur_len >= 4; _mur_len-=4) { \ - _mur_d = *(unsigned *)_mur_key; \ - _mur_t = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ - unsigned _mur_k = _mur_t; \ - _mur_k *= _mur_m; \ - _mur_k ^= _mur_k >> _mur_r; \ - _mur_k *= _mur_m; \ - hashv *= _mur_m; \ - hashv ^= _mur_k; \ - _mur_t = _mur_d; \ - _mur_key += 4; \ - } \ - _mur_d = 0; \ - if(_mur_len >= _mur_align) { \ - switch(_mur_align) { \ - case 3: _mur_d |= _mur_key[2] << 16; \ - case 2: _mur_d |= _mur_key[1] << 8; \ - case 1: _mur_d |= _mur_key[0]; \ - } \ - unsigned _mur_k = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ - _mur_k *= _mur_m; \ - _mur_k ^= _mur_k >> _mur_r; \ - _mur_k *= _mur_m; \ - hashv *= _mur_m; \ - hashv ^= _mur_k; \ - _mur_k += _mur_align; \ - _mur_len -= _mur_align; \ - \ - switch(_mur_len) \ - { \ - case 3: hashv ^= _mur_key[2] << 16; \ - case 2: hashv ^= _mur_key[1] << 8; \ - case 1: hashv ^= _mur_key[0]; \ - hashv *= _mur_m; \ - } \ - } else { \ - switch(_mur_len) \ - { \ - case 3: _mur_d ^= _mur_key[2] << 16; \ - case 2: _mur_d ^= _mur_key[1] << 8; \ - case 1: _mur_d ^= _mur_key[0]; \ - case 0: hashv ^= (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ - hashv *= _mur_m; \ - } \ - } \ - \ - hashv ^= hashv >> 13; \ - hashv *= _mur_m; \ - hashv ^= hashv >> 15; \ - } else { \ - for (;_mur_len >= 4; _mur_len-=4) { \ - unsigned _mur_k = *(unsigned*)_mur_key; \ - _mur_k *= _mur_m; \ - _mur_k ^= _mur_k >> _mur_r; \ - _mur_k *= _mur_m; \ - hashv *= _mur_m; \ - hashv ^= _mur_k; \ - _mur_key += 4; \ - } \ - switch(_mur_len) \ - { \ - case 3: hashv ^= _mur_key[2] << 16; \ - case 2: hashv ^= _mur_key[1] << 8; \ - case 1: hashv ^= _mur_key[0]; \ - hashv *= _mur_m; \ - } \ - \ - hashv ^= hashv >> 13; \ - hashv *= _mur_m; \ - hashv ^= hashv >> 15; \ - } \ - bkt = hashv & (num_bkts-1); \ -} while(0) -#endif /* HASH_USING_NO_STRICT_ALIASING */ - -/* key comparison function; return 0 if keys equal */ -#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) - -/* iterate over items in a known bucket to find desired item */ -#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ -do { \ - if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head)); \ - else out=NULL; \ - while (out) { \ - if (out->hh.keylen == keylen_in) { \ - if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break; \ - } \ - if (out->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,out->hh.hh_next)); \ - else out = NULL; \ - } \ -} while(0) - -/* add an item to a bucket */ -#define HASH_ADD_TO_BKT(head,addhh) \ -do { \ - head.count++; \ - (addhh)->hh_next = head.hh_head; \ - (addhh)->hh_prev = NULL; \ - if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ - (head).hh_head=addhh; \ - if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH) \ - && (addhh)->tbl->noexpand != 1) { \ - HASH_EXPAND_BUCKETS((addhh)->tbl); \ - } \ -} while(0) - -/* remove an item from a given bucket */ -#define HASH_DEL_IN_BKT(hh,head,hh_del) \ - (head).count--; \ - if ((head).hh_head == hh_del) { \ - (head).hh_head = hh_del->hh_next; \ - } \ - if (hh_del->hh_prev) { \ - hh_del->hh_prev->hh_next = hh_del->hh_next; \ - } \ - if (hh_del->hh_next) { \ - hh_del->hh_next->hh_prev = hh_del->hh_prev; \ - } - -/* Bucket expansion has the effect of doubling the number of buckets - * and redistributing the items into the new buckets. Ideally the - * items will distribute more or less evenly into the new buckets - * (the extent to which this is true is a measure of the quality of - * the hash function as it applies to the key domain). - * - * With the items distributed into more buckets, the chain length - * (item count) in each bucket is reduced. Thus by expanding buckets - * the hash keeps a bound on the chain length. This bounded chain - * length is the essence of how a hash provides constant time lookup. - * - * The calculation of tbl->ideal_chain_maxlen below deserves some - * explanation. First, keep in mind that we're calculating the ideal - * maximum chain length based on the *new* (doubled) bucket count. - * In fractions this is just n/b (n=number of items,b=new num buckets). - * Since the ideal chain length is an integer, we want to calculate - * ceil(n/b). We don't depend on floating point arithmetic in this - * hash, so to calculate ceil(n/b) with integers we could write - * - * ceil(n/b) = (n/b) + ((n%b)?1:0) - * - * and in fact a previous version of this hash did just that. - * But now we have improved things a bit by recognizing that b is - * always a power of two. We keep its base 2 log handy (call it lb), - * so now we can write this with a bit shift and logical AND: - * - * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) - * - */ -#define HASH_EXPAND_BUCKETS(tbl) \ -do { \ - unsigned _he_bkt; \ - unsigned _he_bkt_i; \ - struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ - UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ - _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ - 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ - if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ - memset(_he_new_buckets, 0, \ - 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ - tbl->ideal_chain_maxlen = \ - (tbl->num_items >> (tbl->log2_num_buckets+1)) + \ - ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0); \ - tbl->nonideal_items = 0; \ - for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ - { \ - _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ - while (_he_thh) { \ - _he_hh_nxt = _he_thh->hh_next; \ - HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt); \ - _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ - if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ - tbl->nonideal_items++; \ - _he_newbkt->expand_mult = _he_newbkt->count / \ - tbl->ideal_chain_maxlen; \ - } \ - _he_thh->hh_prev = NULL; \ - _he_thh->hh_next = _he_newbkt->hh_head; \ - if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \ - _he_thh; \ - _he_newbkt->hh_head = _he_thh; \ - _he_thh = _he_hh_nxt; \ - } \ - } \ - uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ - tbl->num_buckets *= 2; \ - tbl->log2_num_buckets++; \ - tbl->buckets = _he_new_buckets; \ - tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ - (tbl->ineff_expands+1) : 0; \ - if (tbl->ineff_expands > 1) { \ - tbl->noexpand=1; \ - uthash_noexpand_fyi(tbl); \ - } \ - uthash_expand_fyi(tbl); \ -} while(0) - - -/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ -/* Note that HASH_SORT assumes the hash handle name to be hh. - * HASH_SRT was added to allow the hash handle name to be passed in. */ -#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) -#define HASH_SRT(hh,head,cmpfcn) \ -do { \ - unsigned _hs_i; \ - unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ - struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ - if (head) { \ - _hs_insize = 1; \ - _hs_looping = 1; \ - _hs_list = &((head)->hh); \ - while (_hs_looping) { \ - _hs_p = _hs_list; \ - _hs_list = NULL; \ - _hs_tail = NULL; \ - _hs_nmerges = 0; \ - while (_hs_p) { \ - _hs_nmerges++; \ - _hs_q = _hs_p; \ - _hs_psize = 0; \ - for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ - _hs_psize++; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - if (! (_hs_q) ) break; \ - } \ - _hs_qsize = _hs_insize; \ - while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ - if (_hs_psize == 0) { \ - _hs_e = _hs_q; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_qsize--; \ - } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ - _hs_e = _hs_p; \ - _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ - ((void*)((char*)(_hs_p->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_psize--; \ - } else if (( \ - cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ - DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ - ) <= 0) { \ - _hs_e = _hs_p; \ - _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ - ((void*)((char*)(_hs_p->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_psize--; \ - } else { \ - _hs_e = _hs_q; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_qsize--; \ - } \ - if ( _hs_tail ) { \ - _hs_tail->next = ((_hs_e) ? \ - ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ - } else { \ - _hs_list = _hs_e; \ - } \ - _hs_e->prev = ((_hs_tail) ? \ - ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ - _hs_tail = _hs_e; \ - } \ - _hs_p = _hs_q; \ - } \ - _hs_tail->next = NULL; \ - if ( _hs_nmerges <= 1 ) { \ - _hs_looping=0; \ - (head)->hh.tbl->tail = _hs_tail; \ - DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ - } \ - _hs_insize *= 2; \ - } \ - HASH_FSCK(hh,head); \ - } \ -} while (0) - -/* This function selects items from one hash into another hash. - * The end result is that the selected items have dual presence - * in both hashes. There is no copy of the items made; rather - * they are added into the new hash through a secondary hash - * hash handle that must be present in the structure. */ -#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ -do { \ - unsigned _src_bkt, _dst_bkt; \ - void *_last_elt=NULL, *_elt; \ - UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ - ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ - if (src) { \ - for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ - for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ - _src_hh; \ - _src_hh = _src_hh->hh_next) { \ - _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ - if (cond(_elt)) { \ - _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ - _dst_hh->key = _src_hh->key; \ - _dst_hh->keylen = _src_hh->keylen; \ - _dst_hh->hashv = _src_hh->hashv; \ - _dst_hh->prev = _last_elt; \ - _dst_hh->next = NULL; \ - if (_last_elt_hh) { _last_elt_hh->next = _elt; } \ - if (!dst) { \ - DECLTYPE_ASSIGN(dst,_elt); \ - HASH_MAKE_TABLE(hh_dst,dst); \ - } else { \ - _dst_hh->tbl = (dst)->hh_dst.tbl; \ - } \ - HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ - HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ - (dst)->hh_dst.tbl->num_items++; \ - _last_elt = _elt; \ - _last_elt_hh = _dst_hh; \ - } \ - } \ - } \ - } \ - HASH_FSCK(hh_dst,dst); \ -} while (0) - -#define HASH_CLEAR(hh,head) \ -do { \ - if (head) { \ - uthash_free((head)->hh.tbl->buckets, \ - (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ - uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ - (head)=NULL; \ - } \ -} while(0) - -#ifdef NO_DECLTYPE -#define HASH_ITER(hh,head,el,tmp) \ -for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL); \ - el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) -#else -#define HASH_ITER(hh,head,el,tmp) \ -for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL); \ - el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL)) -#endif - -/* obtain a count of items in the hash */ -#define HASH_COUNT(head) HASH_CNT(hh,head) -#define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0) - -typedef struct UT_hash_bucket { - struct UT_hash_handle *hh_head; - unsigned count; - - /* expand_mult is normally set to 0. In this situation, the max chain length - * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If - * the bucket's chain exceeds this length, bucket expansion is triggered). - * However, setting expand_mult to a non-zero value delays bucket expansion - * (that would be triggered by additions to this particular bucket) - * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. - * (The multiplier is simply expand_mult+1). The whole idea of this - * multiplier is to reduce bucket expansions, since they are expensive, in - * situations where we know that a particular bucket tends to be overused. - * It is better to let its chain length grow to a longer yet-still-bounded - * value, than to do an O(n) bucket expansion too often. - */ - unsigned expand_mult; - -} UT_hash_bucket; - -/* random signature used only to find hash tables in external analysis */ -#define HASH_SIGNATURE 0xa0111fe1 -#define HASH_BLOOM_SIGNATURE 0xb12220f2 - -typedef struct UT_hash_table { - UT_hash_bucket *buckets; - unsigned num_buckets, log2_num_buckets; - unsigned num_items; - struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ - ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ - - /* in an ideal situation (all buckets used equally), no bucket would have - * more than ceil(#items/#buckets) items. that's the ideal chain length. */ - unsigned ideal_chain_maxlen; - - /* nonideal_items is the number of items in the hash whose chain position - * exceeds the ideal chain maxlen. these items pay the penalty for an uneven - * hash distribution; reaching them in a chain traversal takes >ideal steps */ - unsigned nonideal_items; - - /* ineffective expands occur when a bucket doubling was performed, but - * afterward, more than half the items in the hash had nonideal chain - * positions. If this happens on two consecutive expansions we inhibit any - * further expansion, as it's not helping; this happens when the hash - * function isn't a good fit for the key domain. When expansion is inhibited - * the hash will still work, albeit no longer in constant time. */ - unsigned ineff_expands, noexpand; - - uint32_t signature; /* used only to find hash tables in external analysis */ -#ifdef HASH_BLOOM - uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ - uint8_t *bloom_bv; - char bloom_nbits; -#endif - -} UT_hash_table; - -typedef struct UT_hash_handle { - struct UT_hash_table *tbl; - void *prev; /* prev element in app order */ - void *next; /* next element in app order */ - struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ - struct UT_hash_handle *hh_next; /* next hh in bucket order */ - void *key; /* ptr to enclosing struct's key */ - unsigned keylen; /* enclosing struct's key len */ - unsigned hashv; /* result of hash-fcn(key) */ -} UT_hash_handle; - -#endif /* UTHASH_H */ diff --git a/Example/libs/cocos2d/Support/utlist.h b/Example/libs/cocos2d/Support/utlist.h deleted file mode 100644 index b160f1a..0000000 --- a/Example/libs/cocos2d/Support/utlist.h +++ /dev/null @@ -1,490 +0,0 @@ -/* -Copyright (c) 2007-2010, Troy D. Hanson http://uthash.sourceforge.net -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef UTLIST_H -#define UTLIST_H - -#define UTLIST_VERSION 1.9.1 - -/* - * This file contains macros to manipulate singly and doubly-linked lists. - * - * 1. LL_ macros: singly-linked lists. - * 2. DL_ macros: doubly-linked lists. - * 3. CDL_ macros: circular doubly-linked lists. - * - * To use singly-linked lists, your structure must have a "next" pointer. - * To use doubly-linked lists, your structure must "prev" and "next" pointers. - * Either way, the pointer to the head of the list must be initialized to NULL. - * - * ----------------.EXAMPLE ------------------------- - * struct item { - * int id; - * struct item *prev, *next; - * } - * - * struct item *list = NULL: - * - * int main() { - * struct item *item; - * ... allocate and populate item ... - * DL_APPEND(list, item); - * } - * -------------------------------------------------- - * - * For doubly-linked lists, the append and delete macros are O(1) - * For singly-linked lists, append and delete are O(n) but prepend is O(1) - * The sort macro is O(n log(n)) for all types of single/double/circular lists. - */ - -/* These macros use decltype or the earlier __typeof GNU extension. - As decltype is only available in newer compilers (VS2010 or gcc 4.3+ - when compiling c++ code), this code uses whatever method is needed - or, for VS2008 where neither is available, uses casting workarounds. */ -#ifdef _MSC_VER /* MS compiler */ -#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ -#define LDECLTYPE(x) decltype(x) -#else /* VS2008 or older (or VS2010 in C mode) */ -#define NO_DECLTYPE -#define LDECLTYPE(x) char* -#endif -#else /* GNU, Sun and other compilers */ -#define LDECLTYPE(x) __typeof(x) -#endif - -/* for VS2008 we use some workarounds to get around the lack of decltype, - * namely, we always reassign our tmp variable to the list head if we need - * to dereference its prev/next pointers, and save/restore the real head.*/ -#ifdef NO_DECLTYPE -#define _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); } -#define _NEXT(elt,list) ((char*)((list)->next)) -#define _NEXTASGN(elt,list,to) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); } -#define _PREV(elt,list) ((char*)((list)->prev)) -#define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } -#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } -#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } -#else -#define _SV(elt,list) -#define _NEXT(elt,list) ((elt)->next) -#define _NEXTASGN(elt,list,to) ((elt)->next)=(to) -#define _PREV(elt,list) ((elt)->prev) -#define _PREVASGN(elt,list,to) ((elt)->prev)=(to) -#define _RS(list) -#define _CASTASGN(a,b) (a)=(b) -#endif - -/****************************************************************************** - * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort * - * Unwieldy variable names used here to avoid shadowing passed-in variables. * - *****************************************************************************/ -#define LL_SORT(list, cmp) \ -do { \ - LDECLTYPE(list) _ls_p; \ - LDECLTYPE(list) _ls_q; \ - LDECLTYPE(list) _ls_e; \ - LDECLTYPE(list) _ls_tail; \ - LDECLTYPE(list) _ls_oldhead; \ - LDECLTYPE(list) _tmp; \ - int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ - if (list) { \ - _ls_insize = 1; \ - _ls_looping = 1; \ - while (_ls_looping) { \ - _CASTASGN(_ls_p,list); \ - _CASTASGN(_ls_oldhead,list); \ - list = NULL; \ - _ls_tail = NULL; \ - _ls_nmerges = 0; \ - while (_ls_p) { \ - _ls_nmerges++; \ - _ls_q = _ls_p; \ - _ls_psize = 0; \ - for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ - _ls_psize++; \ - _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ - if (!_ls_q) break; \ - } \ - _ls_qsize = _ls_insize; \ - while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ - if (_ls_psize == 0) { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - } else if (_ls_qsize == 0 || !_ls_q) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - } else if (cmp(_ls_p,_ls_q) <= 0) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - } else { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - } \ - if (_ls_tail) { \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ - } else { \ - _CASTASGN(list,_ls_e); \ - } \ - _ls_tail = _ls_e; \ - } \ - _ls_p = _ls_q; \ - } \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ - if (_ls_nmerges <= 1) { \ - _ls_looping=0; \ - } \ - _ls_insize *= 2; \ - } \ - } else _tmp=NULL; /* quiet gcc unused variable warning */ \ -} while (0) - -#define DL_SORT(list, cmp) \ -do { \ - LDECLTYPE(list) _ls_p; \ - LDECLTYPE(list) _ls_q; \ - LDECLTYPE(list) _ls_e; \ - LDECLTYPE(list) _ls_tail; \ - LDECLTYPE(list) _ls_oldhead; \ - LDECLTYPE(list) _tmp; \ - int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ - if (list) { \ - _ls_insize = 1; \ - _ls_looping = 1; \ - while (_ls_looping) { \ - _CASTASGN(_ls_p,list); \ - _CASTASGN(_ls_oldhead,list); \ - list = NULL; \ - _ls_tail = NULL; \ - _ls_nmerges = 0; \ - while (_ls_p) { \ - _ls_nmerges++; \ - _ls_q = _ls_p; \ - _ls_psize = 0; \ - for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ - _ls_psize++; \ - _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ - if (!_ls_q) break; \ - } \ - _ls_qsize = _ls_insize; \ - while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ - if (_ls_psize == 0) { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - } else if (_ls_qsize == 0 || !_ls_q) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - } else if (cmp(_ls_p,_ls_q) <= 0) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - } else { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - } \ - if (_ls_tail) { \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ - } else { \ - _CASTASGN(list,_ls_e); \ - } \ - _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ - _ls_tail = _ls_e; \ - } \ - _ls_p = _ls_q; \ - } \ - _CASTASGN(list->prev, _ls_tail); \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ - if (_ls_nmerges <= 1) { \ - _ls_looping=0; \ - } \ - _ls_insize *= 2; \ - } \ - } else _tmp=NULL; /* quiet gcc unused variable warning */ \ -} while (0) - -#define CDL_SORT(list, cmp) \ -do { \ - LDECLTYPE(list) _ls_p; \ - LDECLTYPE(list) _ls_q; \ - LDECLTYPE(list) _ls_e; \ - LDECLTYPE(list) _ls_tail; \ - LDECLTYPE(list) _ls_oldhead; \ - LDECLTYPE(list) _tmp; \ - LDECLTYPE(list) _tmp2; \ - int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ - if (list) { \ - _ls_insize = 1; \ - _ls_looping = 1; \ - while (_ls_looping) { \ - _CASTASGN(_ls_p,list); \ - _CASTASGN(_ls_oldhead,list); \ - list = NULL; \ - _ls_tail = NULL; \ - _ls_nmerges = 0; \ - while (_ls_p) { \ - _ls_nmerges++; \ - _ls_q = _ls_p; \ - _ls_psize = 0; \ - for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ - _ls_psize++; \ - _SV(_ls_q,list); \ - if (_NEXT(_ls_q,list) == _ls_oldhead) { \ - _ls_q = NULL; \ - } else { \ - _ls_q = _NEXT(_ls_q,list); \ - } \ - _RS(list); \ - if (!_ls_q) break; \ - } \ - _ls_qsize = _ls_insize; \ - while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ - if (_ls_psize == 0) { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ - } else if (_ls_qsize == 0 || !_ls_q) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ - } else if (cmp(_ls_p,_ls_q) <= 0) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ - } else { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ - } \ - if (_ls_tail) { \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ - } else { \ - _CASTASGN(list,_ls_e); \ - } \ - _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ - _ls_tail = _ls_e; \ - } \ - _ls_p = _ls_q; \ - } \ - _CASTASGN(list->prev,_ls_tail); \ - _CASTASGN(_tmp2,list); \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp2); _RS(list); \ - if (_ls_nmerges <= 1) { \ - _ls_looping=0; \ - } \ - _ls_insize *= 2; \ - } \ - } else _tmp=NULL; /* quiet gcc unused variable warning */ \ -} while (0) - -/****************************************************************************** - * singly linked list macros (non-circular) * - *****************************************************************************/ -#define LL_PREPEND(head,add) \ -do { \ - (add)->next = head; \ - head = add; \ -} while (0) - -#define LL_APPEND(head,add) \ -do { \ - LDECLTYPE(head) _tmp; \ - (add)->next=NULL; \ - if (head) { \ - _tmp = head; \ - while (_tmp->next) { _tmp = _tmp->next; } \ - _tmp->next=(add); \ - } else { \ - (head)=(add); \ - } \ -} while (0) - -#define LL_DELETE(head,del) \ -do { \ - LDECLTYPE(head) _tmp; \ - if ((head) == (del)) { \ - (head)=(head)->next; \ - } else { \ - _tmp = head; \ - while (_tmp->next && (_tmp->next != (del))) { \ - _tmp = _tmp->next; \ - } \ - if (_tmp->next) { \ - _tmp->next = ((del)->next); \ - } \ - } \ -} while (0) - -/* Here are VS2008 replacements for LL_APPEND and LL_DELETE */ -#define LL_APPEND_VS2008(head,add) \ -do { \ - if (head) { \ - (add)->next = head; /* use add->next as a temp variable */ \ - while ((add)->next->next) { (add)->next = (add)->next->next; } \ - (add)->next->next=(add); \ - } else { \ - (head)=(add); \ - } \ - (add)->next=NULL; \ -} while (0) - -#define LL_DELETE_VS2008(head,del) \ -do { \ - if ((head) == (del)) { \ - (head)=(head)->next; \ - } else { \ - char *_tmp = (char*)(head); \ - while (head->next && (head->next != (del))) { \ - head = head->next; \ - } \ - if (head->next) { \ - head->next = ((del)->next); \ - } \ - { \ - char **_head_alias = (char**)&(head); \ - *_head_alias = _tmp; \ - } \ - } \ -} while (0) -#ifdef NO_DECLTYPE -#undef LL_APPEND -#define LL_APPEND LL_APPEND_VS2008 -#undef LL_DELETE -#define LL_DELETE LL_DELETE_VS2008 -#endif -/* end VS2008 replacements */ - -#define LL_FOREACH(head,el) \ - for(el=head;el;el=el->next) - -#define LL_FOREACH_SAFE(head,el,tmp) \ - for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) - -#define LL_SEARCH_SCALAR(head,out,field,val) \ -do { \ - LL_FOREACH(head,out) { \ - if ((out)->field == (val)) break; \ - } \ -} while(0) - -#define LL_SEARCH(head,out,elt,cmp) \ -do { \ - LL_FOREACH(head,out) { \ - if ((cmp(out,elt))==0) break; \ - } \ -} while(0) - -/****************************************************************************** - * doubly linked list macros (non-circular) * - *****************************************************************************/ -#define DL_PREPEND(head,add) \ -do { \ - (add)->next = head; \ - if (head) { \ - (add)->prev = (head)->prev; \ - (head)->prev = (add); \ - } else { \ - (add)->prev = (add); \ - } \ - (head) = (add); \ -} while (0) - -#define DL_APPEND(head,add) \ -do { \ - if (head) { \ - (add)->prev = (head)->prev; \ - (head)->prev->next = (add); \ - (head)->prev = (add); \ - (add)->next = NULL; \ - } else { \ - (head)=(add); \ - (head)->prev = (head); \ - (head)->next = NULL; \ - } \ -} while (0); - -#define DL_DELETE(head,del) \ -do { \ - if ((del)->prev == (del)) { \ - (head)=NULL; \ - } else if ((del)==(head)) { \ - (del)->next->prev = (del)->prev; \ - (head) = (del)->next; \ - } else { \ - (del)->prev->next = (del)->next; \ - if ((del)->next) { \ - (del)->next->prev = (del)->prev; \ - } else { \ - (head)->prev = (del)->prev; \ - } \ - } \ -} while (0); - - -#define DL_FOREACH(head,el) \ - for(el=head;el;el=el->next) - -/* this version is safe for deleting the elements during iteration */ -#define DL_FOREACH_SAFE(head,el,tmp) \ - for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) - -/* these are identical to their singly-linked list counterparts */ -#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR -#define DL_SEARCH LL_SEARCH - -/****************************************************************************** - * circular doubly linked list macros * - *****************************************************************************/ -#define CDL_PREPEND(head,add) \ -do { \ - if (head) { \ - (add)->prev = (head)->prev; \ - (add)->next = (head); \ - (head)->prev = (add); \ - (add)->prev->next = (add); \ - } else { \ - (add)->prev = (add); \ - (add)->next = (add); \ - } \ -(head)=(add); \ -} while (0) - -#define CDL_DELETE(head,del) \ -do { \ - if ( ((head)==(del)) && ((head)->next == (head))) { \ - (head) = 0L; \ - } else { \ - (del)->next->prev = (del)->prev; \ - (del)->prev->next = (del)->next; \ - if ((del) == (head)) (head)=(del)->next; \ - } \ -} while (0); - -#define CDL_FOREACH(head,el) \ - for(el=head;el;el=(el->next==head ? 0L : el->next)) - -#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2) \ - for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL); \ - (el) && ((tmp2)=(el)->next, 1); \ - ((el) = (((el)==(tmp1)) ? 0L : (tmp2)))) - -#define CDL_SEARCH_SCALAR(head,out,field,val) \ -do { \ - CDL_FOREACH(head,out) { \ - if ((out)->field == (val)) break; \ - } \ -} while(0) - -#define CDL_SEARCH(head,out,elt,cmp) \ -do { \ - CDL_FOREACH(head,out) { \ - if ((cmp(out,elt))==0) break; \ - } \ -} while(0) - -#endif /* UTLIST_H */ - diff --git a/Example/libs/cocos2d/ccConfig.h b/Example/libs/cocos2d/ccConfig.h deleted file mode 100644 index 5eb6683..0000000 --- a/Example/libs/cocos2d/ccConfig.h +++ /dev/null @@ -1,245 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/** - @file - cocos2d (cc) configuration file -*/ - -/** @def CC_ENABLE_GL_STATE_CACHE - If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches. - In order to use them, you have to use the following functions, insead of the the GL ones: - - ccGLUseProgram() instead of glUseProgram() - - ccGLDeleteProgram() instead of glDeleteProgram() - - ccGLBlendFunc() instead of glBlendFunc() - - If this functionality is disabled, then ccGLUseProgram(), ccGLDeleteProgram(), ccGLBlendFunc() will call the GL ones, without using the cache. - - It is recommened to enable it whenever possible to improve speed. - If you are migrating your code from GL ES 1.1, then keep it disabled. Once all your code works as expected, turn it on. - - Default value: Disabled by default - - @since v2.0.0 - */ -#ifndef CC_ENABLE_GL_STATE_CACHE -#define CC_ENABLE_GL_STATE_CACHE 0 -#endif - -/** @def CC_ENABLE_DEPRECATED - If enabled, cocos2d will compile all deprecated methods, classes and free functions. Also, renamed constants will be active as well. - Enable it only when migrating a v1.0 or earlier v2.0 versions to the most recent cocdos2d version. - - Default value: Enabled by default - - @since v2.0.0 - */ -#ifndef CC_ENABLE_DEPRECATED -#define CC_ENABLE_DEPRECATED 1 -#endif - - -/** @def CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - If enabled, the texture coordinates will be calculated by using this formula: - - texCoord.left = (rect.origin.x*2+1) / (texture.wide*2); - - texCoord.right = texCoord.left + (rect.size.width*2-2)/(texture.wide*2); - - The same for bottom and top. - - This formula prevents artifacts by using 99% of the texture. - The "correct" way to prevent artifacts is by using the spritesheet-artifact-fixer.py or a similar tool. - - Affected nodes: - - CCSprite / CCSpriteBatchNode and subclasses: CCLabelBMFont, CCTMXLayer - - CCLabelAtlas - - CCParticleSystemQuad - - CCTileMap - - To enabled set it to 1. Disabled by default. - - @since v0.99.5 - */ -#ifndef CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL -#define CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL 0 -#endif - -/** @def CC_DIRECTOR_STATS_INTERVAL - Seconds between stats updates. - 0.5 seconds, means that the stats will be updated every 0.5 seconds. - Having a bigger number means more stable stats - - Default value: 0.1f - */ -#ifndef CC_DIRECTOR_STATS_INTERVAL -#define CC_DIRECTOR_STATS_INTERVAL (0.1f) -#endif - -/** @def CC_DIRECTOR_STATS_POSITION - Position of the FPS - - Default: 0,0 (bottom-left corner) - */ -#ifndef CC_DIRECTOR_STATS_POSITION -#define CC_DIRECTOR_STATS_POSITION ccp(0,0) -#endif - -/** @def CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD - If enabled, cocos2d-ios will run on a background thread. If disabled cocos2d-ios will run the main thread. - - To enable set it to a 1, to disable it set to 0. Enabled by default. - - Only valid for cocos2d-ios. Not supported on cocos2d-mac. - - This is an EXPERIMENTAL feature. Do not use it unless you are a developer. - - */ -#ifndef CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD -#define CC_DIRECTOR_IOS_USE_BACKGROUND_THREAD 0 -#endif - - -#define CC_MAC_USE_DISPLAY_LINK_THREAD 0 -#define CC_MAC_USE_OWN_THREAD 1 -#define CC_MAC_USE_MAIN_THREAD 2 - -/** @def CC_DIRECTOR_MAC_THREAD - cocos2d-mac can run on its own thread, on the Display Link thread, or in the main thread. - If you are developing a game, the Display Link or Own thread are the best alternatives. - If you are developing an editor that uses AppKit, you might need to use the Main Thread (only if you are lazy and don't want to create a sync queue). - - Options: - CC_MAC_USE_DISPLAY_LINK_THREAD (default) - CC_MAC_USE_OWN_THREAD - CC_MAC_USE_MAIN_THREAD - - Only valid for cocos2d-mac. Not supported on cocos2d-ios. - - */ -#ifndef CC_DIRECTOR_MAC_THREAD -#define CC_DIRECTOR_MAC_THREAD CC_MAC_USE_DISPLAY_LINK_THREAD -#endif - -/** @def CC_NODE_RENDER_SUBPIXEL - If enabled, the CCNode objects (CCSprite, CCLabel,etc) will be able to render in subpixels. - If disabled, integer pixels will be used. - - To enable set it to 1. Enabled by default. - */ -#ifndef CC_NODE_RENDER_SUBPIXEL -#define CC_NODE_RENDER_SUBPIXEL 1 -#endif - -/** @def CC_SPRITEBATCHNODE_RENDER_SUBPIXEL - If enabled, the CCSprite objects rendered with CCSpriteBatchNode will be able to render in subpixels. - If disabled, integer pixels will be used. - - To enable set it to 1. Enabled by default. - */ -#ifndef CC_SPRITEBATCHNODE_RENDER_SUBPIXEL -#define CC_SPRITEBATCHNODE_RENDER_SUBPIXEL 1 -#endif - -/** @def CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP - Use GL_TRIANGLE_STRIP instead of GL_TRIANGLES when rendering the texture atlas. - It seems it is the recommend way, but it is much slower, so, enable it at your own risk - - To enable set it to a value different than 0. Disabled by default. - - */ -#ifndef CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP -#define CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP 0 -#endif - -/** @def CC_TEXTURE_ATLAS_USE_VAO - By default, CCTextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects). - Apple recommends its usage but they might consume a lot of memory, specially if you use many of them. - So for certain cases, where you might need hundreds of VAO objects, it might be a good idea to disable it. - - To disable it set it to 0. Enabled by default. - - */ -#ifndef CC_TEXTURE_ATLAS_USE_VAO -#define CC_TEXTURE_ATLAS_USE_VAO 1 -#endif - - -/** @def CC_USE_LA88_LABELS - If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for CCLabelTTF objects. - If it is disabled, it will use A8 (Alpha 8-bit textures). - LA88 textures are 6% faster than A8 textures, but they will consume 2x memory. - - This feature is enabled by default. - - @since v0.99.5 - */ -#ifndef CC_USE_LA88_LABELS -#define CC_USE_LA88_LABELS 1 -#endif - -/** @def CC_SPRITE_DEBUG_DRAW - If enabled, all subclasses of CCSprite will draw a bounding box. - Useful for debugging purposes only. It is recommened to leave it disabled. - - If the CCSprite is being drawn by a CCSpriteBatchNode, the bounding box might be a bit different. - To enable set it to a value different than 0. Disabled by default: - 0 -- disabled - 1 -- draw bounding box - 2 -- draw texture box - */ -#ifndef CC_SPRITE_DEBUG_DRAW -#define CC_SPRITE_DEBUG_DRAW 0 -#endif - - -/** @def CC_LABELBMFONT_DEBUG_DRAW - If enabled, all subclasses of CCLabelBMFont will draw a bounding box - Useful for debugging purposes only. It is recommened to leave it disabled. - - To enable set it to a value different than 0. Disabled by default. - */ -#ifndef CC_LABELBMFONT_DEBUG_DRAW -#define CC_LABELBMFONT_DEBUG_DRAW 0 -#endif - -/** @def CC_LABELATLAS_DEBUG_DRAW - If enabled, all subclasses of CCLabeltAtlas will draw a bounding box - Useful for debugging purposes only. It is recommened to leave it disabled. - - To enable set it to a value different than 0. Disabled by default. - */ -#ifndef CC_LABELATLAS_DEBUG_DRAW -#define CC_LABELATLAS_DEBUG_DRAW 0 -#endif - -/** @def CC_ENABLE_PROFILERS - If enabled, it will activate various profilers within cocos2d. This statistical data will be saved in the CCProfiler singleton. - In order to display saved data, you have to call the CC_PROFILER_DISPLAY_TIMERS() macro. - Useful for profiling purposes only. If unsure, leave it disabled. - - To enable set it to a value different than 0. Disabled by default. - */ -#ifndef CC_ENABLE_PROFILERS -#define CC_ENABLE_PROFILERS 0 -#endif diff --git a/Example/libs/cocos2d/ccDeprecated.h b/Example/libs/cocos2d/ccDeprecated.h deleted file mode 100644 index 2cf3605..0000000 --- a/Example/libs/cocos2d/ccDeprecated.h +++ /dev/null @@ -1,219 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2012 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "ccConfig.h" - -#if CC_ENABLE_DEPRECATED - -#import "ccMacros.h" -#import "CCMenu.h" -#import "CCDirector.h" -#import "CCSprite.h" -#import "CCGLProgram.h" -#import "CCAnimation.h" -#import "CCScheduler.h" -#import "CCActionManager.h" -#import "CCActionInterval.h" -#import "CCRenderTexture.h" -#import "Support/CCFileUtils.h" -#import "Platforms/Mac/CCDirectorMac.h" -#import "Platforms/iOS/CCTouchDispatcher.h" -#import "Platforms/iOS/CCDirectorIOS.h" - - -/* - * - * IMPORTANT - * - * See the ccDrepecated.m file to see the name of the new methods - * - */ - -// ccTypes.h -enum { - kCCResolutionStandard DEPRECATED_ATTRIBUTE = kCCResolutioniPhone, - kCCResolutionRetinaDisplay DEPRECATED_ATTRIBUTE = kCCResolutioniPhoneRetinaDisplay, - kCCMenuTouchPriority DEPRECATED_ATTRIBUTE = kCCMenuHandlerPriority, -}; - -// CCRenderTexture.h -enum { - kCCImageFormatJPG DEPRECATED_ATTRIBUTE = kCCImageFormatJPEG, - kCCImageFormatRawData UNAVAILABLE_ATTRIBUTE, -}; - -// Free functions -void ccGLUniformModelViewProjectionMatrix(CCGLProgram* program) DEPRECATED_ATTRIBUTE; - -// Renamed classes -DEPRECATED_ATTRIBUTE @interface EAGLView : CCGLView -@end - -DEPRECATED_ATTRIBUTE @interface MacView : CCGLView -@end - -// hack to prevent "incopatible pointer type" -#define GLProgram CCGLProgram - -// Extensions -@interface CCScheduler (Deprecated) -// new: [director scheduler] -+(CCScheduler*) sharedScheduler DEPRECATED_ATTRIBUTE; -@end - -@interface CCActionManager (Deprecated) -// new: [director actionManager] -+(CCActionManager*) sharedManager DEPRECATED_ATTRIBUTE; -@end - -#if __CC_PLATFORM_IOS -@interface CCTouchDispatcher (Deprecated) -// new: [director touchDispatcher] -+(CCTouchDispatcher*) sharedDispatcher DEPRECATED_ATTRIBUTE; -@end -#elif __CC_PLATFORM_MAC -@interface CCEventDispatcher (Deprecated) -// new: [director eventDispatcher] -+(CCEventDispatcher*) sharedDispatcher DEPRECATED_ATTRIBUTE; -@end -#endif // __CC_PLATFORM_MAC - -@interface CCDirector (Deprecated) -// new: setView: --(void) setOpenGLView:(CCGLView*)view DEPRECATED_ATTRIBUTE; -// new: view --(CCGLView*) openGLView DEPRECATED_ATTRIBUTE; -// new: setDisplayStats: --(void) setDisplayFPS:(BOOL)display DEPRECATED_ATTRIBUTE; -@end - - -@interface CCSprite (Deprecated) -// new: spriteWithTexture:rect: -+(id) spriteWithBatchNode:(CCSpriteBatchNode*)node rect:(CGRect)rect DEPRECATED_ATTRIBUTE; -// new: initWithTexture:rect: --(id) initWithBatchNode:(CCSpriteBatchNode*)node rect:(CGRect)rect DEPRECATED_ATTRIBUTE; -// displayFrame --(CCSpriteFrame*) displayedFrame DEPRECATED_ATTRIBUTE; -@end - -@interface CCMenuItemAtlasFont (Deprecated) -// new itemWithStirng:charmapFile:itemWidth:itemHeight:startCharMap -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap DEPRECATED_ATTRIBUTE; -// new itemWithStirng:charmapFile:itemWidth:itemHeight:startCharMap:target:selector -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb DEPRECATED_ATTRIBUTE; -// new itemWithStirng:charmapFile:itemWidth:itemHeight:startCharMap:block -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; -// new initWithStirng:charmapFile:itemWidth:itemHeight:startCharMap:target:selector --(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb DEPRECATED_ATTRIBUTE; -// new initWithStirng:charmapFile:itemWidth:itemHeight:startCharMap:block --(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; -@end - - -@interface CCMenuItemFont (Deprecated) -// new: itemWithString: -+(id) itemFromString: (NSString*) value DEPRECATED_ATTRIBUTE; -// new: itemWithString:target:selector -+(id) itemFromString: (NSString*) value target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; -// new: itemWithString:block: -+(id) itemFromString: (NSString*) value block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; -// new: initWithString:target:selector --(id) initFromString: (NSString*) value target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; -// new: initWithString:block: --(id) initFromString: (NSString*) value block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; -@end - -@interface CCMenuItemSprite (Deprecated) -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite DEPRECATED_ATTRIBUTE; -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector DEPRECATED_ATTRIBUTE; -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector DEPRECATED_ATTRIBUTE; -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; - --(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector DEPRECATED_ATTRIBUTE; --(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; -@end - -@interface CCMenuItemImage (Deprecated) -// new: itemWithNormalImage:selectedImage: -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 DEPRECATED_ATTRIBUTE; -// new: itemWithNormalImage:selectedImage:target:selector -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; -// new: itemWithNormalImage:selectedImage:disabledImage:target:selector -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; -// new: itemWithNormalImage:selectedImage:block -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; -// new: itemWithNormalImage:selectedImage:disabledImage:block -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; -// new: initWithNormalImage:selectedImage:disabledImage:target:selector --(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s DEPRECATED_ATTRIBUTE; -// new: initWithNormalImage:selectedImage:disabledImage:block --(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block DEPRECATED_ATTRIBUTE; -@end - -@interface CCAnimation (Deprecated) -+(id) animationWithFrames:(NSArray*)arrayOfSpriteFrameNames DEPRECATED_ATTRIBUTE; -+(id) animationWithFrames:(NSArray*)arrayOfSpriteFrameNames delay:(float)delay DEPRECATED_ATTRIBUTE; --(id) initWithFrames:(NSArray*)arrayOfSpriteFrameNames DEPRECATED_ATTRIBUTE; --(id) initWithFrames:(NSArray *)arrayOfSpriteFrameNames delay:(float)delay DEPRECATED_ATTRIBUTE; --(void) addFrame:(CCSpriteFrame*)frame DEPRECATED_ATTRIBUTE; --(void) addFrameWithFilename:(NSString*)filename DEPRECATED_ATTRIBUTE; --(void) addFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect DEPRECATED_ATTRIBUTE; -@end - -@interface CCAnimate (Deprecated) -// new: actionWithAnimation: -+(id) actionWithAnimation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame DEPRECATED_ATTRIBUTE; -// new: actiontWithAnimation: -+(id) actionWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame DEPRECATED_ATTRIBUTE; -// new: initWithAnimation: --(id) initWithAnimation:(CCAnimation*) a restoreOriginalFrame:(BOOL)restoreOriginalFrame DEPRECATED_ATTRIBUTE; -// new: initWithAnimation: --(id) initWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame DEPRECATED_ATTRIBUTE; -@end - -@interface CCRenderTexture (Deprecated) -// new: saveToFile: --(BOOL)saveBuffer:(NSString*)name DEPRECATED_ATTRIBUTE; -// new: saveToFile:format: --(BOOL)saveBuffer:(NSString*)name format:(int)format DEPRECATED_ATTRIBUTE; -// new: -- not implemented on v2.0 --(NSData*)getUIImageAsDataFromBuffer:(int) format UNAVAILABLE_ATTRIBUTE; -#if __CC_PLATFORM_IOS -// new: getUIImage --(UIImage *)getUIImageFromBuffer DEPRECATED_ATTRIBUTE; -#endif -@end - -#if __CC_PLATFORM_IOS -@interface CCFileUtils (Deprecated) -// new: setiPhoneRetinaDisplaySuffix -+(void) setRetinaDisplaySuffix:(NSString*)suffix DEPRECATED_ATTRIBUTE; -@end -#endif - - -#endif // CC_ENABLE_DEPRECATED - diff --git a/Example/libs/cocos2d/ccDeprecated.m b/Example/libs/cocos2d/ccDeprecated.m deleted file mode 100644 index f0bec22..0000000 --- a/Example/libs/cocos2d/ccDeprecated.m +++ /dev/null @@ -1,328 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2012 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "ccDeprecated.h" - -#if CC_ENABLE_DEPRECATED - -#import "CCSpriteBatchNode.h" - -// Free functions -void ccGLUniformModelViewProjectionMatrix( CCGLProgram* program ) -{ - [program setUniformForModelViewProjectionMatrix]; -} - -@implementation CCScheduler (Deprecated) -+(CCScheduler*) sharedScheduler -{ - return [[CCDirector sharedDirector] scheduler]; -} -@end - -@implementation CCActionManager (Deprecated) -+(CCActionManager*) sharedManager -{ - return [[CCDirector sharedDirector] actionManager]; -} -@end - -#if __CC_PLATFORM_IOS -@implementation CCTouchDispatcher (Deprecated) -+(CCTouchDispatcher*) sharedDispatcher -{ - return [[CCDirector sharedDirector] touchDispatcher]; -} -@end -#elif __CC_PLATFORM_MAC -@implementation CCEventDispatcher (Deprecated) -+(CCEventDispatcher*) sharedDispatcher -{ - return [[CCDirector sharedDirector] eventDispatcher]; -} -@end -#endif // __CC_PLATFORM_MAC - -#pragma mark - CCDirector - -@implementation CCDirector (Deprecated) --(void) setDisplayFPS:(BOOL)display -{ - [self setDisplayStats:display]; -} - --(void) setOpenGLView:(CCGLView*)view -{ - [self setView:view]; -} - --(CCGLView*) openGLView -{ - return (CCGLView*)view_; -} -@end - -@implementation CCSprite (Deprecated) - -+(id) spriteWithBatchNode:(CCSpriteBatchNode*)node rect:(CGRect)rect -{ - id ret = [self spriteWithTexture:node.texture rect:rect]; - [ret setBatchNode:node]; - return ret; -} - --(id) initWithBatchNode:(CCSpriteBatchNode*)node rect:(CGRect)rect -{ - self = [self initWithTexture:node.texture rect:rect]; - [self setBatchNode:node]; - return self; -} - --(CCSpriteFrame*) displayedFrame -{ - return [self displayedFrame]; -} -@end - -@implementation CCMenuItemAtlasFont (Deprecated) -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap -{ - return [self itemWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap]; -} -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb -{ - return [self itemWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:rec selector:cb]; -} -+(id) itemFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block -{ - return [self itemWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap block:block]; -} --(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap target:(id) rec selector:(SEL) cb -{ - return [self initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap target:rec selector:cb]; -} --(id) initFromString: (NSString*) value charMapFile:(NSString*) charMapFile itemWidth:(int)itemWidth itemHeight:(int)itemHeight startCharMap:(char)startCharMap block:(void(^)(id sender))block -{ - return [self initWithString:value charMapFile:charMapFile itemWidth:itemWidth itemHeight:itemHeight startCharMap:startCharMap block:block]; -} -@end - -@implementation CCMenuItemFont (Deprecated) -+(id) itemFromString: (NSString*) value -{ - return [self itemWithString:value]; -} -+(id) itemFromString: (NSString*) value target:(id) r selector:(SEL) s -{ - return [self itemWithString:value target:r selector:s]; -} -+(id) itemFromString: (NSString*) value block:(void(^)(id sender))block -{ - return [self itemWithString:value block:block]; -} --(id) initFromString: (NSString*) value target:(id) r selector:(SEL) s -{ - return [self initWithString:value target:r selector:s]; -} --(id) initFromString: (NSString*) value block:(void(^)(id sender))block -{ - return [self initWithString:value block:block]; -} -@end - -@implementation CCMenuItemSprite (Deprecated) -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite -{ - return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite]; -} -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite target:(id)target selector:(SEL)selector -{ - return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite target:target selector:selector]; -} -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector -{ - return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite target:target selector:selector]; -} -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite block:(void(^)(id sender))block -{ - return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite block:block]; -} -+(id) itemFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block -{ - return [self itemWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:block]; -} - --(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite target:(id)target selector:(SEL)selector -{ - return [self initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite target:target selector:selector]; -} --(id) initFromNormalSprite:(CCNode*)normalSprite selectedSprite:(CCNode*)selectedSprite disabledSprite:(CCNode*)disabledSprite block:(void(^)(id sender))block -{ - return [self initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:block]; -} -@end - -@implementation CCMenuItemImage (Deprecated) -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 -{ - return [self itemWithNormalImage:value selectedImage:value2]; -} -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 target:(id) r selector:(SEL) s -{ - return [self itemWithNormalImage:value selectedImage:value2 target:r selector:s]; -} -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s -{ - return [self itemWithNormalImage:value selectedImage:value2 disabledImage:value3 target:r selector:s]; -} -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 block:(void(^)(id sender))block -{ - return [self itemWithNormalImage:value selectedImage:value2 block:block]; -} -+(id) itemFromNormalImage: (NSString*)value selectedImage:(NSString*) value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block -{ - return [self itemWithNormalImage:value selectedImage:value2 disabledImage:value3 block:block]; -} --(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 target:(id) r selector:(SEL) s -{ - return [self initWithNormalImage:value selectedImage:value2 disabledImage:value3 target:r selector:s]; -} --(id) initFromNormalImage: (NSString*) value selectedImage:(NSString*)value2 disabledImage:(NSString*) value3 block:(void(^)(id sender))block -{ - return [self initWithNormalImage:value selectedImage:value2 disabledImage:value3 block:block]; -} -@end - - -@implementation CCAnimation (Deprecated) -+(id) animationWithFrames:(NSArray*)arrayOfSpriteFrameNames -{ - return [self animationWithSpriteFrames:arrayOfSpriteFrameNames]; -} -+(id) animationWithFrames:(NSArray*)arrayOfSpriteFrameNames delay:(float)delay -{ - return [self animationWithSpriteFrames:arrayOfSpriteFrameNames delay:delay]; -} --(id) initWithFrames:(NSArray*)arrayOfSpriteFrameNames -{ - return [self initWithSpriteFrames:arrayOfSpriteFrameNames]; -} --(id) initWithFrames:(NSArray *)arrayOfSpriteFrameNames delay:(float)delay -{ - return [self initWithSpriteFrames:arrayOfSpriteFrameNames delay:delay]; -} --(void) addFrame:(CCSpriteFrame*)frame -{ - [self addSpriteFrame:frame]; -} --(void) addFrameWithFilename:(NSString*)filename -{ - [self addSpriteFrameWithFilename:filename]; -} --(void) addFrameWithTexture:(CCTexture2D*)texture rect:(CGRect)rect -{ - [self addSpriteFrameWithTexture:texture rect:rect]; -} -@end - -@implementation CCAnimate (Deprecated) -+(id) actionWithAnimation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame -{ - CCAnimation *anim = [[animation copy] autorelease]; - anim.restoreOriginalFrame = restoreOriginalFrame; - - return [[[self alloc] initWithAnimation:anim] autorelease]; -} -+(id) actionWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame -{ - CCAnimation *anim = [[animation copy] autorelease]; - anim.restoreOriginalFrame = restoreOriginalFrame; - anim.delayPerUnit = duration / animation.frames.count; - - return [[[self alloc] initWithAnimation:anim] autorelease]; -} --(id) initWithAnimation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame -{ - CCAnimation *anim = [[animation copy] autorelease]; - anim.restoreOriginalFrame = restoreOriginalFrame; - - return [self initWithAnimation:anim]; -} --(id) initWithDuration:(ccTime)duration animation:(CCAnimation*)animation restoreOriginalFrame:(BOOL)restoreOriginalFrame -{ - CCAnimation *anim = [[animation copy] autorelease]; - anim.restoreOriginalFrame = restoreOriginalFrame; - anim.delayPerUnit = duration / animation.frames.count; - - return [self initWithAnimation:anim]; -} -@end - - -@implementation CCRenderTexture (Deprecated) --(BOOL)saveBuffer:(NSString*)name -{ - return [self saveToFile:name]; -} --(BOOL)saveBuffer:(NSString*)name format:(int)format -{ - return [self saveToFile:name format:format]; -} - --(NSData*)getUIImageAsDataFromBuffer:(int) format -{ - NSAssert(NO, @"NOT IMPLEMENTED IN V2.0"); - - return nil; -} -#if __CC_PLATFORM_IOS --(UIImage *)getUIImageFromBuffer -{ - return [self getUIImage]; -} -#endif -@end - -#if __CC_PLATFORM_IOS -@implementation CCFileUtils (Deprecated) -+(void) setRetinaDisplaySuffix:(NSString*)suffix -{ - return [self setiPhoneRetinaDisplaySuffix:suffix]; -} -@end -#endif - - -#if __CC_PLATFORM_IOS -@implementation EAGLView -@end - -#elif __CC_PLATFORM_MAC - -@implementation MacView -@end - -#endif // __CC_PLATFORM_MAC - -#endif // CC_ENABLE_DEPRECATED diff --git a/Example/libs/cocos2d/ccGLStateCache.h b/Example/libs/cocos2d/ccGLStateCache.h deleted file mode 100644 index 6e15e07..0000000 --- a/Example/libs/cocos2d/ccGLStateCache.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import -#import "ccMacros.h" -#if __CC_PLATFORM_IOS -#import -#import -#elif __CC_PLATFORM_MAC -#import -#endif // - -@class CCGLProgram; - -/** vertex attrib flags */ -enum { - kCCVertexAttribFlag_None = 0, - - kCCVertexAttribFlag_Position = 1 << 0, - kCCVertexAttribFlag_Color = 1 << 1, - kCCVertexAttribFlag_TexCoords = 1 << 2, - - kCCVertexAttribFlag_PosColorTex = ( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_Color | kCCVertexAttribFlag_TexCoords ), -}; - -/** GL server side states */ -typedef enum { -// CC_GL_SCISSOR_TEST = 1 << 0, -// CC_GL_STENCIL_TEST = 1 << 1, -// CC_GL_DEPTH_TEST = 1 << 2, - CC_GL_BLEND = 1 << 3, -// CC_GL_DITHER = 1 << 4, - -// CC_GL_ALL = ( CC_GL_SCISSOR_TEST | CC_GL_STENCIL_TEST | CC_GL_DEPTH_TEST | CC_GL_BLEND | CC_GL_DITHER ), - CC_GL_ALL = ( CC_GL_BLEND ), - -} ccGLServerState; - -#ifdef __cplusplus -extern "C" { -#endif - -/** @file ccGLStateCache.h -*/ - -/** Invalidates the GL state cache. - If CC_ENABLE_GL_STATE_CACHE it will reset the GL state cache. - @since v2.0.0 - */ -void ccGLInvalidateStateCache( void ); - -/** Uses the GL program in case program is different than the current one. - If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly. - @since v2.0.0 - */ -void ccGLUseProgram( GLuint program ); - -/** Deletes the GL program. If it is the one that is being used, it invalidates it. - If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly. - @since v2.0.0 - */ -void ccGLDeleteProgram( GLuint program ); - -/** Uses a blending function in case it not already used. - If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly. - @since v2.0.0 - */ -void ccGLBlendFunc(GLenum sfactor, GLenum dfactor); - -/** sets the projection matrix as dirty - @since v2.0.0 - */ -void ccSetProjectionMatrixDirty( void ); - -/** Will enable the vertex attribs that are passed as flags. - Possible flags: - - * kCCVertexAttribFlag_Position - * kCCVertexAttribFlag_Color - * kCCVertexAttribFlag_TexCoords - - These flags can be ORed. The flags that are not present, will be disabled. - - @since v2.0.0 - */ -void ccGLEnableVertexAttribs( unsigned int flags ); - -/** If the active texture is not textureEnum, then it will active it. - If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glActiveTexture() directly. - @since v2.0.0 - */ -void ccGLActiveTexture(GLenum textureEnum ); - -/** Returns the active texture. - If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glGetIntegerv(GL_ACTIVE_TEXTURE); - @since v2.0.0 - */ -GLenum ccGLGetActiveTexture( void ); - - -/** If the texture is not already bound, it binds it. - If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. - @since v2.0.0 - */ -void ccGLBindTexture2D(GLuint textureId ); - -/** It will delete a given texture. If the texture was bound, it will invalidate the cached. - If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. - @since v2.0.0 - */ -void ccGLDeleteTexture(GLuint textureId); - -/** It will enable / disable the server side GL states. - If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly. - @since v2.0.0 - */ -void ccGLEnable( ccGLServerState flags ); - -#ifdef __cplusplus -} -#endif diff --git a/Example/libs/cocos2d/ccGLStateCache.m b/Example/libs/cocos2d/ccGLStateCache.m deleted file mode 100644 index 89e2b3f..0000000 --- a/Example/libs/cocos2d/ccGLStateCache.m +++ /dev/null @@ -1,226 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2011 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "ccGLStateCache.h" -#import "CCGLProgram.h" -#import "CCDirector.h" -#import "ccConfig.h" - -// extern -#import "kazmath/GL/matrix.h" -#import "kazmath/kazmath.h" - -static GLuint _ccCurrentProjectionMatrix = -1; -static BOOL _vertexAttribPosition = NO; -static BOOL _vertexAttribColor = NO; -static BOOL _vertexAttribTexCoords = NO; - -#if CC_ENABLE_GL_STATE_CACHE -#define kCCMaxActiveTexture 16 -static GLuint _ccCurrentShaderProgram = -1; -static GLuint _ccCurrentBoundTexture[kCCMaxActiveTexture] = {-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, }; -static GLenum _ccCurrentActiveTexture = (GL_TEXTURE0 - GL_TEXTURE0); -static GLenum _ccBlendingSource = -1; -static GLenum _ccBlendingDest = -1; -static ccGLServerState _ccGLServerState = 0; -#endif // CC_ENABLE_GL_STATE_CACHE - -#pragma mark - GL State Cache functions - -void ccGLInvalidateStateCache( void ) -{ - kmGLFreeAll(); - - _ccCurrentProjectionMatrix = -1; - _vertexAttribPosition = NO; - _vertexAttribColor = NO; - _vertexAttribTexCoords = NO; - -#if CC_ENABLE_GL_STATE_CACHE - _ccCurrentShaderProgram = -1; - for( NSInteger i=0; i < kCCMaxActiveTexture; i++ ) - _ccCurrentBoundTexture[i] = -1; - _ccCurrentActiveTexture = (GL_TEXTURE0 - GL_TEXTURE0); - _ccBlendingSource = -1; - _ccBlendingDest = -1; - _ccGLServerState = 0; -#endif -} - -void ccGLDeleteProgram( GLuint program ) -{ -#if CC_ENABLE_GL_STATE_CACHE - if( program == _ccCurrentShaderProgram ) - _ccCurrentShaderProgram = -1; -#endif // CC_ENABLE_GL_STATE_CACHE - - glDeleteProgram( program ); -} - -void ccGLUseProgram( GLuint program ) -{ -#if CC_ENABLE_GL_STATE_CACHE - if( program != _ccCurrentShaderProgram ) { - _ccCurrentShaderProgram = program; - glUseProgram(program); - } -#else - glUseProgram(program); -#endif // CC_ENABLE_GL_STATE_CACHE -} - - -void ccGLBlendFunc(GLenum sfactor, GLenum dfactor) -{ -#if CC_ENABLE_GL_STATE_CACHE - if( sfactor != _ccBlendingSource || dfactor != _ccBlendingDest ) { - _ccBlendingSource = sfactor; - _ccBlendingDest = dfactor; - glBlendFunc( sfactor, dfactor ); - } -#else - glBlendFunc( sfactor, dfactor ); -#endif // CC_ENABLE_GL_STATE_CACHE -} - -GLenum ccGLGetActiveTexture( void ) -{ -#if CC_ENABLE_GL_STATE_CACHE - return _ccCurrentActiveTexture + GL_TEXTURE0; -#else - GLenum activeTexture; - glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&activeTexture); - return activeTexture; -#endif -} - -void ccGLActiveTexture( GLenum textureEnum ) -{ -#if CC_ENABLE_GL_STATE_CACHE - NSCAssert1( (textureEnum - GL_TEXTURE0) < kCCMaxActiveTexture, @"cocos2d ERROR: Increase kCCMaxActiveTexture to %d!", (textureEnum-GL_TEXTURE0) ); - if( (textureEnum - GL_TEXTURE0) != _ccCurrentActiveTexture ) { - _ccCurrentActiveTexture = (textureEnum - GL_TEXTURE0); - glActiveTexture( textureEnum ); - } -#else - glActiveTexture( textureEnum ); -#endif -} - -void ccGLBindTexture2D( GLuint textureId ) -{ -#if CC_ENABLE_GL_STATE_CACHE - if( _ccCurrentBoundTexture[ _ccCurrentActiveTexture ] != textureId ) - { - _ccCurrentBoundTexture[ _ccCurrentActiveTexture ] = textureId; - glBindTexture(GL_TEXTURE_2D, textureId ); - } -#else - glBindTexture(GL_TEXTURE_2D, textureId ); -#endif -} - - -void ccGLDeleteTexture( GLuint textureId ) -{ -#if CC_ENABLE_GL_STATE_CACHE - if( textureId == _ccCurrentBoundTexture[ _ccCurrentActiveTexture ] ) - _ccCurrentBoundTexture[ _ccCurrentActiveTexture ] = -1; -#endif - glDeleteTextures(1, &textureId ); -} - -void ccGLEnable( ccGLServerState flags ) -{ -#if CC_ENABLE_GL_STATE_CACHE - - BOOL enabled = NO; - - /* GL_BLEND */ - if( (enabled=(flags & CC_GL_BLEND)) != (_ccGLServerState & CC_GL_BLEND) ) { - if( enabled ) { - glEnable( GL_BLEND ); - _ccGLServerState |= CC_GL_BLEND; - } else { - glDisable( GL_BLEND ); - _ccGLServerState &= ~CC_GL_BLEND; - } - } - -#else - if( flags & CC_GL_BLEND ) - glEnable( GL_BLEND ); - else - glDisable( GL_BLEND ); -#endif -} - -#pragma mark - GL Vertex Attrib functions - -void ccGLEnableVertexAttribs( unsigned int flags ) -{ - /* Position */ - BOOL enablePosition = flags & kCCVertexAttribFlag_Position; - - if( enablePosition != _vertexAttribPosition ) { - if( enablePosition ) - glEnableVertexAttribArray( kCCVertexAttrib_Position ); - else - glDisableVertexAttribArray( kCCVertexAttrib_Position ); - - _vertexAttribPosition = enablePosition; - } - - /* Color */ - BOOL enableColor = flags & kCCVertexAttribFlag_Color; - - if( enableColor != _vertexAttribColor ) { - if( enableColor ) - glEnableVertexAttribArray( kCCVertexAttrib_Color ); - else - glDisableVertexAttribArray( kCCVertexAttrib_Color ); - - _vertexAttribColor = enableColor; - } - - /* Tex Coords */ - BOOL enableTexCoords = flags & kCCVertexAttribFlag_TexCoords; - - if( enableTexCoords != _vertexAttribTexCoords ) { - if( enableTexCoords ) - glEnableVertexAttribArray( kCCVertexAttrib_TexCoords ); - else - glDisableVertexAttribArray( kCCVertexAttrib_TexCoords ); - - _vertexAttribTexCoords = enableTexCoords; - } -} - -#pragma mark - GL Uniforms functions - -void ccSetProjectionMatrixDirty( void ) -{ - _ccCurrentProjectionMatrix = -1; -} diff --git a/Example/libs/cocos2d/ccMacros.h b/Example/libs/cocos2d/ccMacros.h deleted file mode 100644 index 4b73887..0000000 --- a/Example/libs/cocos2d/ccMacros.h +++ /dev/null @@ -1,342 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -#import -#import "ccConfig.h" - -#import -#import - -/** - @file - cocos2d helper macros - */ - -#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED -#define __CC_PLATFORM_IOS 1 -#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) -#define __CC_PLATFORM_MAC 1 -#endif - -/* - * if COCOS2D_DEBUG is not defined, or if it is 0 then - * all CCLOGXXX macros will be disabled - * - * if COCOS2D_DEBUG==1 then: - * CCLOG() will be enabled - * CCLOGERROR() will be enabled - * CCLOGINFO() will be disabled - * - * if COCOS2D_DEBUG==2 or higher then: - * CCLOG() will be enabled - * CCLOGERROR() will be enabled - * CCLOGINFO() will be enabled - */ -#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 -#define CCLOG(...) do {} while (0) -#define CCLOGINFO(...) do {} while (0) -#define CCLOGERROR(...) do {} while (0) - -#elif COCOS2D_DEBUG == 1 -#define CCLOG(...) NSLog(__VA_ARGS__) -#define CCLOGERROR(...) NSLog(__VA_ARGS__) -#define CCLOGINFO(...) do {} while (0) - -#elif COCOS2D_DEBUG > 1 -#define CCLOG(...) NSLog(__VA_ARGS__) -#define CCLOGERROR(...) NSLog(__VA_ARGS__) -#define CCLOGINFO(...) NSLog(__VA_ARGS__) -#endif // COCOS2D_DEBUG - -/** @def CC_SWAP -simple macro that swaps 2 variables -*/ -#define CC_SWAP( x, y ) \ -({ __typeof__(x) temp = (x); \ - x = y; y = temp; \ -}) - - -/** @def CCRANDOM_MINUS1_1 - returns a random float between -1 and 1 - */ -#define CCRANDOM_MINUS1_1() ((random() / (float)0x3fffffff )-1.0f) - -/** @def CCRANDOM_0_1 - returns a random float between 0 and 1 - */ -#define CCRANDOM_0_1() ((random() / (float)0x7fffffff )) - -/** @def CC_DEGREES_TO_RADIANS - converts degrees to radians - */ -#define CC_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f) // PI / 180 - -/** @def CC_RADIANS_TO_DEGREES - converts radians to degrees - */ -#define CC_RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) * 57.29577951f) // PI * 180 - -#define kCCRepeatForever UINT_MAX -1 -/** @def CC_BLEND_SRC -default gl blend src function. Compatible with premultiplied alpha images. -*/ -#define CC_BLEND_SRC GL_ONE -#define CC_BLEND_DST GL_ONE_MINUS_SRC_ALPHA - -/** @def CC_DIRECTOR_INIT - - Initializes an CCGLView with 0-bit depth format, and RGB565 render buffer. - - The CCGLView view will have multiple touches disabled. - - It will create a UIWindow and it will assign it the 'window_' ivar. 'window_' must be declared before calling this marcro. - - It will create a UINavigationController and it will assign it the 'navigationController_' ivar. 'navController_' must be declared before using this macro. - - The director_ will be the root view controller of the navController. - - It will connect the CCGLView to the Director - - It will connect the UINavController view to the UIWindow. - - It will try to run at 60 FPS. - - It will connect the director with the CCGLView. - - IMPORTANT: If you want to use another type of render buffer (eg: RGBA8) - or if you want to use a 16-bit or 24-bit depth buffer, you should NOT - use this macro. Instead, you should create the CCGLView manually. - - @since v0.99.4 - */ - -#ifdef __CC_PLATFORM_IOS - -#define CC_DIRECTOR_INIT() \ -do { \ - window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; \ - director_ = (CCDirectorIOS*)[CCDirector sharedDirector]; \ - [director_ setDisplayStats:NO]; \ - [director_ setAnimationInterval:1.0/60]; \ - CCGLView *__glView = [CCGLView viewWithFrame:[window_ bounds] \ - pixelFormat:kEAGLColorFormatRGB565 \ - depthFormat:0 /* GL_DEPTH_COMPONENT24_OES */ \ - preserveBackbuffer:NO \ - sharegroup:nil \ - multiSampling:NO \ - numberOfSamples:0 \ - ]; \ - [director_ setView:__glView]; \ - [director_ setDelegate:self]; \ - director_.wantsFullScreenLayout = YES; \ - if( ! [director_ enableRetinaDisplay:YES] ) \ - CCLOG(@"Retina Display Not supported"); \ - navController_ = [[UINavigationController alloc] initWithRootViewController:director_]; \ - navController_.navigationBarHidden = YES; \ - [window_ addSubview:navController_.view]; \ - [window_ makeKeyAndVisible]; \ -} while(0) - - -#elif __CC_PLATFORM_MAC - -#define CC_DIRECTOR_INIT(__WINSIZE__) \ -do { \ - NSRect frameRect = NSMakeRect(0, 0, (__WINSIZE__).width, (__WINSIZE__).height); \ - window_ = [[CCWindow alloc] initWithFrame:frameRect fullscreen:NO]; \ - glView_ = [[CCGLView alloc] initWithFrame:frameRect shareContext:nil]; \ - [self.window setContentView:self.glView]; \ - director_ = (CCDirectorMac*) [CCDirector sharedDirector]; \ - [director_ setDisplayStats:NO]; \ - [director_ setView:self.glView]; \ - [director_ setOriginalWinSize:__WINSIZE__]; \ - [self.window makeMainWindow]; \ - [self.window makeKeyAndOrderFront:self]; \ - [self.window center]; \ -} while(0) - -#endif - -/** @def CC_NODE_DRAW_SETUP - Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix - @since v2.0 - */ -#define CC_NODE_DRAW_SETUP() \ -do { \ - ccGLEnable( glServerState_ ); \ - [shaderProgram_ use]; \ - [shaderProgram_ setUniformForModelViewProjectionMatrix]; \ -} while(0) - - - /** @def CC_DIRECTOR_END - Stops and removes the director from memory. - Removes the CCGLView from its parent - - @since v0.99.4 - */ -#define CC_DIRECTOR_END() \ -do { \ - CCDirector *__director = [CCDirector sharedDirector]; \ - [__director end]; \ -} while(0) - - - - -#if __CC_PLATFORM_IOS - -/****************************/ -/** RETINA DISPLAY ENABLED **/ -/****************************/ - -/** @def CC_CONTENT_SCALE_FACTOR - On Mac it returns 1; - On iPhone it returns 2 if RetinaDisplay is On. Otherwise it returns 1 - */ -extern float __ccContentScaleFactor; -#define CC_CONTENT_SCALE_FACTOR() __ccContentScaleFactor - - -/** @def CC_RECT_PIXELS_TO_POINTS - Converts a rect in pixels to points - */ -#define CC_RECT_PIXELS_TO_POINTS(__rect_in_pixels__) \ - CGRectMake( (__rect_in_pixels__).origin.x / CC_CONTENT_SCALE_FACTOR(), (__rect_in_pixels__).origin.y / CC_CONTENT_SCALE_FACTOR(), \ - (__rect_in_pixels__).size.width / CC_CONTENT_SCALE_FACTOR(), (__rect_in_pixels__).size.height / CC_CONTENT_SCALE_FACTOR() ) - -/** @def CC_RECT_POINTS_TO_PIXELS - Converts a rect in points to pixels - */ -#define CC_RECT_POINTS_TO_PIXELS(__rect_in_points_points__) \ - CGRectMake( (__rect_in_points_points__).origin.x * CC_CONTENT_SCALE_FACTOR(), (__rect_in_points_points__).origin.y * CC_CONTENT_SCALE_FACTOR(), \ - (__rect_in_points_points__).size.width * CC_CONTENT_SCALE_FACTOR(), (__rect_in_points_points__).size.height * CC_CONTENT_SCALE_FACTOR() ) - -/** @def CC_POINT_PIXELS_TO_POINTS - Converts a rect in pixels to points - */ -#define CC_POINT_PIXELS_TO_POINTS(__pixels__) \ -CGPointMake( (__pixels__).x / CC_CONTENT_SCALE_FACTOR(), (__pixels__).y / CC_CONTENT_SCALE_FACTOR()) - -/** @def CC_POINT_POINTS_TO_PIXELS - Converts a rect in points to pixels - */ -#define CC_POINT_POINTS_TO_PIXELS(__points__) \ -CGPointMake( (__points__).x * CC_CONTENT_SCALE_FACTOR(), (__points__).y * CC_CONTENT_SCALE_FACTOR()) - -/** @def CC_POINT_PIXELS_TO_POINTS - Converts a rect in pixels to points - */ -#define CC_SIZE_PIXELS_TO_POINTS(__size_in_pixels__) \ -CGSizeMake( (__size_in_pixels__).width / CC_CONTENT_SCALE_FACTOR(), (__size_in_pixels__).height / CC_CONTENT_SCALE_FACTOR()) - -/** @def CC_POINT_POINTS_TO_PIXELS - Converts a rect in points to pixels - */ -#define CC_SIZE_POINTS_TO_PIXELS(__size_in_points__) \ -CGSizeMake( (__size_in_points__).width * CC_CONTENT_SCALE_FACTOR(), (__size_in_points__).height * CC_CONTENT_SCALE_FACTOR()) - - -#elif defined(__CC_PLATFORM_MAC) - -/*****************************/ -/** RETINA DISPLAY DISABLED **/ -/*****************************/ - -#define CC_CONTENT_SCALE_FACTOR() 1 -#define CC_RECT_PIXELS_TO_POINTS(__pixels__) __pixels__ -#define CC_RECT_POINTS_TO_PIXELS(__points__) __points__ -#define CC_SIZE_PIXELS_TO_POINTS(__pixels__) __pixels__ -#define CC_SIZE_POINTS_TO_PIXELS(__points__) __points__ -#define CC_POINT_PIXELS_TO_POINTS(__pixels__) __pixels__ -#define CC_POINT_POINTS_TO_PIXELS(__points__) __points__ - - -#endif // __CC_PLATFORM_MAC - - -/**********************/ -/** Profiling Macros **/ -/**********************/ -#if CC_ENABLE_PROFILERS - -#define CC_PROFILER_DISPLAY_TIMERS() [[CCProfiler sharedProfiler] displayTimers] -#define CC_PROFILER_PURGE_ALL() [[CCProfiler sharedProfiler] releaseAllTimers] - -#define CC_PROFILER_START(__name__) CCProfilingBeginTimingBlock(__name__) -#define CC_PROFILER_STOP(__name__) CCProfilingEndTimingBlock(__name__) -#define CC_PROFILER_RESET(__name__) CCProfilingResetTimingBlock(__name__) - -#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProfilingBeginTimingBlock(__name__); } while(0) -#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProfilingEndTimingBlock(__name__); } while(0) -#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProfilingResetTimingBlock(__name__); } while(0) - -#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ CCProfilingBeginTimingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); } while(0) -#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ CCProfilingEndTimingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); } while(0) -#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ CCProfilingResetTimingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); } while(0) - - -#else - -#define CC_PROFILER_DISPLAY_TIMERS() do {} while (0) -#define CC_PROFILER_PURGE_ALL() do {} while (0) - -#define CC_PROFILER_START(__name__) do {} while (0) -#define CC_PROFILER_STOP(__name__) do {} while (0) -#define CC_PROFILER_RESET(__name__) do {} while (0) - -#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do {} while(0) -#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do {} while(0) -#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do {} while(0) - -#define CC_PROFILER_START_INSTANCE(__id__, __name__) do {} while(0) -#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do {} while(0) -#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do {} while(0) - -#endif - -/*****************/ -/** ARC Macros **/ -/*****************/ -#if defined(__has_feature) && __has_feature(objc_arc) -// ARC (used for inline functions) -#define CC_ARC_RETAIN(value) value -#define CC_ARC_RELEASE(value) value = 0 -#define CC_ARC_UNSAFE_RETAINED __unsafe_unretained - -#else -// No ARC -#define CC_ARC_RETAIN(value) [value retain] -#define CC_ARC_RELEASE(value) [value release] -#define CC_ARC_UNSAFE_RETAINED -#endif - -/** @def CC_INCREMENT_GL_DRAWS_BY_ONE - Increments the GL Draws counts by one. - The number of calls per frame are displayed on the screen when the CCDirector's stats are enabled. - */ -extern NSUInteger __ccNumberOfDraws; -#define CC_INCREMENT_GL_DRAWS(__n__) __ccNumberOfDraws += __n__ - -/*******************/ -/** Notifications **/ -/*******************/ -/** @def CCAnimationFrameDisplayedNotification - Notification name when a CCSpriteFrame is displayed - */ -#define CCAnimationFrameDisplayedNotification @"CCAnimationFrameDisplayedNotification" diff --git a/Example/libs/cocos2d/ccShader_PositionColor_frag.h b/Example/libs/cocos2d/ccShader_PositionColor_frag.h deleted file mode 100644 index 2c28489..0000000 --- a/Example/libs/cocos2d/ccShader_PositionColor_frag.h +++ /dev/null @@ -1,12 +0,0 @@ -" \n\ -#ifdef GL_ES \n\ -precision lowp float; \n\ -#endif \n\ - \n\ -varying vec4 v_fragmentColor; \n\ - \n\ -void main() \n\ -{ \n\ - gl_FragColor = v_fragmentColor; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionColor_vert.h b/Example/libs/cocos2d/ccShader_PositionColor_vert.h deleted file mode 100644 index 815e161..0000000 --- a/Example/libs/cocos2d/ccShader_PositionColor_vert.h +++ /dev/null @@ -1,17 +0,0 @@ -" \n\ -attribute vec4 a_position; \n\ -attribute vec4 a_color; \n\ -uniform mat4 u_MVPMatrix; \n\ - \n\ -#ifdef GL_ES \n\ -varying lowp vec4 v_fragmentColor; \n\ -#else \n\ -varying vec4 v_fragmentColor; \n\ -#endif \n\ - \n\ -void main() \n\ -{ \n\ - gl_Position = u_MVPMatrix * a_position; \n\ - v_fragmentColor = a_color; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureA8Color_frag.h b/Example/libs/cocos2d/ccShader_PositionTextureA8Color_frag.h deleted file mode 100644 index 0b6cd10..0000000 --- a/Example/libs/cocos2d/ccShader_PositionTextureA8Color_frag.h +++ /dev/null @@ -1,16 +0,0 @@ -" \n\ -#ifdef GL_ES \n\ -precision lowp float; \n\ -#endif \n\ - \n\ -varying vec4 v_fragmentColor; \n\ -varying vec2 v_texCoord; \n\ -uniform sampler2D u_texture; \n\ - \n\ -void main() \n\ -{ \n\ - gl_FragColor = vec4( v_fragmentColor.rgb, // RGB from uniform \n\ - v_fragmentColor.a * texture2D(u_texture, v_texCoord).a // A from texture & uniform \n\ - ); \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureA8Color_vert.h b/Example/libs/cocos2d/ccShader_PositionTextureA8Color_vert.h deleted file mode 100644 index b844932..0000000 --- a/Example/libs/cocos2d/ccShader_PositionTextureA8Color_vert.h +++ /dev/null @@ -1,21 +0,0 @@ -" \n\ -attribute vec4 a_position; \n\ -attribute vec2 a_texCoord; \n\ -attribute vec4 a_color; \n\ -uniform mat4 u_MVPMatrix; \n\ - \n\ -#ifdef GL_ES \n\ -varying lowp vec4 v_fragmentColor; \n\ -varying mediump vec2 v_texCoord; \n\ -#else \n\ -varying vec4 v_fragmentColor; \n\ -varying vec2 v_texCoord; \n\ -#endif \n\ - \n\ -void main() \n\ -{ \n\ - gl_Position = u_MVPMatrix * a_position; \n\ - v_fragmentColor = a_color; \n\ - v_texCoord = a_texCoord; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureColorAlphaTest_frag.h b/Example/libs/cocos2d/ccShader_PositionTextureColorAlphaTest_frag.h deleted file mode 100644 index 253c5e8..0000000 --- a/Example/libs/cocos2d/ccShader_PositionTextureColorAlphaTest_frag.h +++ /dev/null @@ -1,23 +0,0 @@ -" \n\ -#ifdef GL_ES \n\ -precision lowp float; \n\ -#endif \n\ - \n\ -varying vec4 v_fragmentColor; \n\ -varying vec2 v_texCoord; \n\ -uniform sampler2D u_texture; \n\ -uniform float u_alpha_value; \n\ - \n\ -void main() \n\ -{ \n\ - vec4 texColor = texture2D(u_texture, v_texCoord); \n\ - \n\ - // mimic: glAlphaFunc(GL_GREATER) \n\ - // pass if ( incoming_pixel >= u_alpha_value ) => fail if incoming_pixel < u_alpha_value \n\ - \n\ - if ( texColor.a <= u_alpha_value ) \n\ - discard; \n\ - \n\ - gl_FragColor = texColor * v_fragmentColor; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureColor_frag.h b/Example/libs/cocos2d/ccShader_PositionTextureColor_frag.h deleted file mode 100644 index aba7e21..0000000 --- a/Example/libs/cocos2d/ccShader_PositionTextureColor_frag.h +++ /dev/null @@ -1,14 +0,0 @@ -" \n\ -#ifdef GL_ES \n\ -precision lowp float; \n\ -#endif \n\ - \n\ -varying vec4 v_fragmentColor; \n\ -varying vec2 v_texCoord; \n\ -uniform sampler2D u_texture; \n\ - \n\ -void main() \n\ -{ \n\ - gl_FragColor = v_fragmentColor * texture2D(u_texture, v_texCoord); \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionTextureColor_vert.h b/Example/libs/cocos2d/ccShader_PositionTextureColor_vert.h deleted file mode 100644 index cf2361d..0000000 --- a/Example/libs/cocos2d/ccShader_PositionTextureColor_vert.h +++ /dev/null @@ -1,22 +0,0 @@ -" \n\ -attribute vec4 a_position; \n\ -attribute vec2 a_texCoord; \n\ -attribute vec4 a_color; \n\ - \n\ -uniform mat4 u_MVPMatrix; \n\ - \n\ -#ifdef GL_ES \n\ -varying lowp vec4 v_fragmentColor; \n\ -varying mediump vec2 v_texCoord; \n\ -#else \n\ -varying vec4 v_fragmentColor; \n\ -varying vec2 v_texCoord; \n\ -#endif \n\ - \n\ -void main() \n\ -{ \n\ - gl_Position = u_MVPMatrix * a_position; \n\ - v_fragmentColor = a_color; \n\ - v_texCoord = a_texCoord; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionTexture_frag.h b/Example/libs/cocos2d/ccShader_PositionTexture_frag.h deleted file mode 100644 index d7af10e..0000000 --- a/Example/libs/cocos2d/ccShader_PositionTexture_frag.h +++ /dev/null @@ -1,13 +0,0 @@ -" \n\ -#ifdef GL_ES \n\ -precision lowp float; \n\ -#endif \n\ - \n\ -varying vec2 v_texCoord; \n\ -uniform sampler2D u_texture; \n\ - \n\ -void main() \n\ -{ \n\ - gl_FragColor = texture2D(u_texture, v_texCoord); \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionTexture_uColor_frag.h b/Example/libs/cocos2d/ccShader_PositionTexture_uColor_frag.h deleted file mode 100644 index 019f2ef..0000000 --- a/Example/libs/cocos2d/ccShader_PositionTexture_uColor_frag.h +++ /dev/null @@ -1,16 +0,0 @@ -" \n\ -#ifdef GL_ES \n\ -precision lowp float; \n\ -#endif \n\ - \n\ -uniform vec4 u_color; \n\ - \n\ -varying vec2 v_texCoord; \n\ - \n\ -uniform sampler2D u_texture; \n\ - \n\ -void main() \n\ -{ \n\ - gl_FragColor = texture2D(u_texture, v_texCoord) * u_color; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionTexture_uColor_vert.h b/Example/libs/cocos2d/ccShader_PositionTexture_uColor_vert.h deleted file mode 100644 index ca36ff0..0000000 --- a/Example/libs/cocos2d/ccShader_PositionTexture_uColor_vert.h +++ /dev/null @@ -1,18 +0,0 @@ -" \n\ -attribute vec4 a_position; \n\ -attribute vec2 a_texCoord; \n\ - \n\ -uniform mat4 u_MVPMatrix; \n\ - \n\ -#ifdef GL_ES \n\ -varying mediump vec2 v_texCoord; \n\ -#else \n\ -varying vec2 v_texCoord; \n\ -#endif \n\ - \n\ -void main() \n\ -{ \n\ - gl_Position = u_MVPMatrix * a_position; \n\ - v_texCoord = a_texCoord; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_PositionTexture_vert.h b/Example/libs/cocos2d/ccShader_PositionTexture_vert.h deleted file mode 100644 index 98ceab5..0000000 --- a/Example/libs/cocos2d/ccShader_PositionTexture_vert.h +++ /dev/null @@ -1,17 +0,0 @@ -" \n\ -attribute vec4 a_position; \n\ -attribute vec2 a_texCoord; \n\ -uniform mat4 u_MVPMatrix; \n\ - \n\ -#ifdef GL_ES \n\ -varying mediump vec2 v_texCoord; \n\ -#else \n\ -varying vec2 v_texCoord; \n\ -#endif \n\ - \n\ -void main() \n\ -{ \n\ - gl_Position = u_MVPMatrix * a_position; \n\ - v_texCoord = a_texCoord; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_Position_uColor_frag.h b/Example/libs/cocos2d/ccShader_Position_uColor_frag.h deleted file mode 100644 index 48e5ae6..0000000 --- a/Example/libs/cocos2d/ccShader_Position_uColor_frag.h +++ /dev/null @@ -1,12 +0,0 @@ -" \n\ -#ifdef GL_ES \n\ -precision lowp float; \n\ -#endif \n\ - \n\ -varying vec4 v_fragmentColor; \n\ - \n\ -void main() \n\ -{ \n\ - gl_FragColor = v_fragmentColor; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShader_Position_uColor_vert.h b/Example/libs/cocos2d/ccShader_Position_uColor_vert.h deleted file mode 100644 index 9f1ba38..0000000 --- a/Example/libs/cocos2d/ccShader_Position_uColor_vert.h +++ /dev/null @@ -1,19 +0,0 @@ -" \n\ -attribute vec4 a_position; \n\ -uniform mat4 u_MVPMatrix; \n\ -uniform vec4 u_color; \n\ -uniform float u_pointSize; \n\ - \n\ -#ifdef GL_ES \n\ -varying lowp vec4 v_fragmentColor; \n\ -#else \n\ -varying vec4 v_fragmentColor; \n\ -#endif \n\ - \n\ -void main() \n\ -{ \n\ - gl_Position = u_MVPMatrix * a_position; \n\ - gl_PointSize = u_pointSize; \n\ - v_fragmentColor = u_color; \n\ -} \n\ -"; diff --git a/Example/libs/cocos2d/ccShaders.h b/Example/libs/cocos2d/ccShaders.h deleted file mode 100644 index 84b113f..0000000 --- a/Example/libs/cocos2d/ccShaders.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2012 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "Platforms/CCGL.h" - -extern const GLchar * ccPosition_uColor_frag; -extern const GLchar * ccPosition_uColor_vert; - -extern const GLchar * ccPositionColor_frag; -extern const GLchar * ccPositionColor_vert; - -extern const GLchar * ccPositionTexture_frag; -extern const GLchar * ccPositionTexture_vert; - -extern const GLchar * ccPositionTextureA8Color_frag; -extern const GLchar * ccPositionTextureA8Color_vert; - -extern const GLchar * ccPositionTextureColor_frag; -extern const GLchar * ccPositionTextureColor_vert; - -extern const GLchar * ccPositionTextureColorAlphaTest_frag; - -extern const GLchar * ccPositionTexture_uColor_frag; -extern const GLchar * ccPositionTexture_uColor_vert; diff --git a/Example/libs/cocos2d/ccShaders.m b/Example/libs/cocos2d/ccShaders.m deleted file mode 100644 index 36ca949..0000000 --- a/Example/libs/cocos2d/ccShaders.m +++ /dev/null @@ -1,65 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2012 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#import "ccShaders.h" - -// -const GLchar * ccPosition_uColor_frag = -#import "ccShader_Position_uColor_frag.h" -const GLchar * ccPosition_uColor_vert = -#import "ccShader_Position_uColor_vert.h" - -// -const GLchar * ccPositionColor_frag = -#import "ccShader_PositionColor_frag.h" -const GLchar * ccPositionColor_vert = -#import "ccShader_PositionColor_vert.h" - -// -const GLchar * ccPositionTexture_frag = -#import "ccShader_PositionTexture_frag.h" -const GLchar * ccPositionTexture_vert = -#import "ccShader_PositionTexture_vert.h" - -// -const GLchar * ccPositionTextureA8Color_frag = -#import "ccShader_PositionTextureA8Color_frag.h" -const GLchar * ccPositionTextureA8Color_vert = -#import "ccShader_PositionTextureA8Color_vert.h" - -// -const GLchar * ccPositionTextureColor_frag = -#import "ccShader_PositionTextureColor_frag.h" -const GLchar * ccPositionTextureColor_vert = -#import "ccShader_PositionTextureColor_vert.h" - -// -const GLchar * ccPositionTextureColorAlphaTest_frag = -#import "ccShader_PositionTextureColorAlphaTest_frag.h" - -// -const GLchar * ccPositionTexture_uColor_frag = -#import "ccShader_PositionTexture_uColor_frag.h" -const GLchar * ccPositionTexture_uColor_vert = -#import "ccShader_PositionTexture_uColor_vert.h" diff --git a/Example/libs/cocos2d/ccTypes.h b/Example/libs/cocos2d/ccTypes.h deleted file mode 100644 index 1a71cb0..0000000 --- a/Example/libs/cocos2d/ccTypes.h +++ /dev/null @@ -1,335 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -/** - @file - cocos2d (cc) types -*/ - -#import -#import "ccMacros.h" - -#ifdef __CC_PLATFORM_IOS -#import // CGPoint -#endif - -#import "Platforms/CCGL.h" - -/** RGB color composed of bytes 3 bytes -@since v0.8 - */ -typedef struct _ccColor3B -{ - GLubyte r; - GLubyte g; - GLubyte b; -} ccColor3B; - -//! helper macro that creates an ccColor3B type -static inline ccColor3B -ccc3(const GLubyte r, const GLubyte g, const GLubyte b) -{ - ccColor3B c = {r, g, b}; - return c; -} -//ccColor3B predefined colors -//! White color (255,255,255) -static const ccColor3B ccWHITE = {255,255,255}; -//! Yellow color (255,255,0) -static const ccColor3B ccYELLOW = {255,255,0}; -//! Blue color (0,0,255) -static const ccColor3B ccBLUE = {0,0,255}; -//! Green Color (0,255,0) -static const ccColor3B ccGREEN = {0,255,0}; -//! Red Color (255,0,0,) -static const ccColor3B ccRED = {255,0,0}; -//! Magenta Color (255,0,255) -static const ccColor3B ccMAGENTA = {255,0,255}; -//! Black Color (0,0,0) -static const ccColor3B ccBLACK = {0,0,0}; -//! Orange Color (255,127,0) -static const ccColor3B ccORANGE = {255,127,0}; -//! Gray Color (166,166,166) -static const ccColor3B ccGRAY = {166,166,166}; - -/** RGBA color composed of 4 bytes -@since v0.8 -*/ -typedef struct _ccColor4B -{ - GLubyte r; - GLubyte g; - GLubyte b; - GLubyte a; -} ccColor4B; -//! helper macro that creates an ccColor4B type -static inline ccColor4B -ccc4(const GLubyte r, const GLubyte g, const GLubyte b, const GLubyte o) -{ - ccColor4B c = {r, g, b, o}; - return c; -} - - -/** RGBA color composed of 4 floats -@since v0.8 -*/ -typedef struct _ccColor4F { - GLfloat r; - GLfloat g; - GLfloat b; - GLfloat a; -} ccColor4F; -//! helper that creates a ccColor4f type -static inline ccColor4F -ccc4f(const GLfloat r, const GLfloat g, const GLfloat b, const GLfloat a) -{ - return (ccColor4F){r, g, b, a}; -} - -/** Returns a ccColor4F from a ccColor3B. Alpha will be 1. - @since v0.99.1 - */ -static inline ccColor4F ccc4FFromccc3B(ccColor3B c) -{ - return (ccColor4F){c.r/255.f, c.g/255.f, c.b/255.f, 1.f}; -} - -/** Returns a ccColor4F from a ccColor4B. - @since v0.99.1 - */ -static inline ccColor4F ccc4FFromccc4B(ccColor4B c) -{ - return (ccColor4F){c.r/255.f, c.g/255.f, c.b/255.f, c.a/255.f}; -} - -/** returns YES if both ccColor4F are equal. Otherwise it returns NO. - @since v0.99.1 - */ -static inline BOOL ccc4FEqual(ccColor4F a, ccColor4F b) -{ - return a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a; -} - -/** A vertex composed of 2 GLfloats: x, y - @since v0.8 - */ -typedef struct _ccVertex2F -{ - GLfloat x; - GLfloat y; -} ccVertex2F; - -/** A vertex composed of 2 floats: x, y - @since v0.8 - */ -typedef struct _ccVertex3F -{ - GLfloat x; - GLfloat y; - GLfloat z; -} ccVertex3F; - -/** A texcoord composed of 2 floats: u, y - @since v0.8 - */ -typedef struct _ccTex2F { - GLfloat u; - GLfloat v; -} ccTex2F; - - -//! Point Sprite component -typedef struct _ccPointSprite -{ - ccVertex2F pos; // 8 bytes - ccColor4B color; // 4 bytes - GLfloat size; // 4 bytes -} ccPointSprite; - -//! A 2D Quad. 4 * 2 floats -typedef struct _ccQuad2 { - ccVertex2F tl; - ccVertex2F tr; - ccVertex2F bl; - ccVertex2F br; -} ccQuad2; - - -//! A 3D Quad. 4 * 3 floats -typedef struct _ccQuad3 { - ccVertex3F bl; - ccVertex3F br; - ccVertex3F tl; - ccVertex3F tr; -} ccQuad3; - -//! A 2D grid size -typedef struct _ccGridSize -{ - NSInteger x; - NSInteger y; -} ccGridSize; - -//! helper function to create a ccGridSize -static inline ccGridSize -ccg(const NSInteger x, const NSInteger y) -{ - ccGridSize v = {x, y}; - return v; -} - -//! a Point with a vertex point, a tex coord point and a color 4B -typedef struct _ccV2F_C4B_T2F -{ - //! vertices (2F) - ccVertex2F vertices; - //! colors (4B) - ccColor4B colors; - //! tex coords (2F) - ccTex2F texCoords; -} ccV2F_C4B_T2F; - -//! a Point with a vertex point, a tex coord point and a color 4F -typedef struct _ccV2F_C4F_T2F -{ - //! vertices (2F) - ccVertex2F vertices; - //! colors (4F) - ccColor4F colors; - //! tex coords (2F) - ccTex2F texCoords; -} ccV2F_C4F_T2F; - -//! a Point with a vertex point, a tex coord point and a color 4F -typedef struct _ccV3F_C4F_T2F -{ - //! vertices (3F) - ccVertex3F vertices; - //! colors (4F) - ccColor4F colors; - //! tex coords (2F) - ccTex2F texCoords; -} ccV3F_C4F_T2F; - -//! 4 ccV3F_C4F_T2F -typedef struct _ccV3F_C4F_T2F_Quad -{ - //! top left - ccV3F_C4F_T2F tl; - //! bottom left - ccV3F_C4F_T2F bl; - //! top right - ccV3F_C4F_T2F tr; - //! bottom right - ccV3F_C4F_T2F br; -} ccV3F_C4F_T2F_Quad; - -//! a Point with a vertex point, a tex coord point and a color 4B -typedef struct _ccV3F_C4B_T2F -{ - //! vertices (3F) - ccVertex3F vertices; // 12 bytes -// char __padding__[4]; - - //! colors (4B) - ccColor4B colors; // 4 bytes -// char __padding2__[4]; - - // tex coords (2F) - ccTex2F texCoords; // 8 byts -} ccV3F_C4B_T2F; - -//! 4 ccVertex2FTex2FColor4B Quad -typedef struct _ccV2F_C4B_T2F_Quad -{ - //! bottom left - ccV2F_C4B_T2F bl; - //! bottom right - ccV2F_C4B_T2F br; - //! top left - ccV2F_C4B_T2F tl; - //! top right - ccV2F_C4B_T2F tr; -} ccV2F_C4B_T2F_Quad; - -//! 4 ccVertex3FTex2FColor4B -typedef struct _ccV3F_C4B_T2F_Quad -{ - //! top left - ccV3F_C4B_T2F tl; - //! bottom left - ccV3F_C4B_T2F bl; - //! top right - ccV3F_C4B_T2F tr; - //! bottom right - ccV3F_C4B_T2F br; -} ccV3F_C4B_T2F_Quad; - -//! 4 ccVertex2FTex2FColor4F Quad -typedef struct _ccV2F_C4F_T2F_Quad -{ - //! bottom left - ccV2F_C4F_T2F bl; - //! bottom right - ccV2F_C4F_T2F br; - //! top left - ccV2F_C4F_T2F tl; - //! top right - ccV2F_C4F_T2F tr; -} ccV2F_C4F_T2F_Quad; - -//! Blend Function used for textures -typedef struct _ccBlendFunc -{ - //! source blend function - GLenum src; - //! destination blend function - GLenum dst; -} ccBlendFunc; - -//! ccResolutionType -typedef enum -{ - //! Unknonw resolution type - kCCResolutionUnknown, - //! iPhone resolution type - kCCResolutioniPhone, - //! RetinaDisplay resolution type - kCCResolutioniPhoneRetinaDisplay, - //! iPad resolution type - kCCResolutioniPad, - //! iPad Retina Display resolution type - kCCResolutioniPadRetinaDisplay, - -} ccResolutionType; - -//! delta time type -//! if you want more resolution redefine it as a double -typedef float ccTime; -//typedef double ccTime; - -typedef float ccMat4[16]; diff --git a/Example/libs/cocos2d/cocos2d.h b/Example/libs/cocos2d/cocos2d.h deleted file mode 100644 index 17c6a9f..0000000 --- a/Example/libs/cocos2d/cocos2d.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/** @mainpage cocos2d for iPhone API reference - * - * @image html Icon.png - * - * @section intro Introduction - * This is cocos2d API reference - * - * The programming guide is hosted here: http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:index - * - *
- * - * @todo A native english speaker should check the grammar. We need your help! - * - */ - -// 0x00 HI ME LO -// 00 02 00 00 -#define COCOS2D_VERSION 0x00020000 - - -// -// all cocos2d include files -// -#import "ccConfig.h" // should be included first - -#import "CCActionManager.h" -#import "CCAction.h" -#import "CCActionInstant.h" -#import "CCActionInterval.h" -#import "CCActionEase.h" -#import "CCActionCamera.h" -#import "CCActionTween.h" -#import "CCActionEase.h" -#import "CCActionTiledGrid.h" -#import "CCActionGrid3D.h" -#import "CCActionGrid.h" -#import "CCActionProgressTimer.h" -#import "CCActionPageTurn3D.h" - -#import "CCAnimation.h" -#import "CCAnimationCache.h" -#import "CCSprite.h" -#import "CCSpriteFrame.h" -#import "CCSpriteBatchNode.h" -#import "CCSpriteFrameCache.h" - -#import "CCLabelTTF.h" -#import "CCLabelBMFont.h" -#import "CCLabelAtlas.h" - -#import "CCParticleSystem.h" -#import "CCParticleSystemQuad.h" -#import "CCParticleExamples.h" -#import "CCParticleBatchNode.h" - -#import "CCTexture2D.h" -#import "CCTexturePVR.h" -#import "CCTextureCache.h" -#import "CCTextureAtlas.h" - -#import "CCTransition.h" -#import "CCTransitionPageTurn.h" -#import "CCTransitionProgress.h" - -#import "CCTMXTiledMap.h" -#import "CCTMXLayer.h" -#import "CCTMXObjectGroup.h" -#import "CCTMXXMLParser.h" -#import "CCTileMapAtlas.h" - -#import "CCLayer.h" -#import "CCMenu.h" -#import "CCMenuItem.h" -#import "CCDrawingPrimitives.h" -#import "CCScene.h" -#import "CCScheduler.h" -#import "CCCamera.h" -#import "CCProtocols.h" -#import "CCNode.h" -#import "CCDirector.h" -#import "CCAtlasNode.h" -#import "CCGrabber.h" -#import "CCGrid.h" -#import "CCParallaxNode.h" -#import "CCRenderTexture.h" -#import "CCMotionStreak.h" -#import "CCConfiguration.h" - -// Shaders -#import "CCGLProgram.h" -#import "ccGLStateCache.h" -#import "CCShaderCache.h" -#import "ccShaders.h" - -// -// cocos2d macros -// -#import "ccTypes.h" -#import "ccMacros.h" - -// -// Deprecated methods/classes/functions since v1.0 -// -#import "ccDeprecated.h" - -// Platform common -#import "Platforms/CCGL.h" -#import "Platforms/CCNS.h" - -#ifdef __CC_PLATFORM_IOS -#import "Platforms/iOS/CCTouchDispatcher.h" -#import "Platforms/iOS/CCTouchDelegateProtocol.h" -#import "Platforms/iOS/CCTouchHandler.h" -#import "Platforms/iOS/CCGLView.h" -#import "Platforms/iOS/CCDirectorIOS.h" - -#elif defined(__CC_PLATFORM_MAC) -#import "Platforms/Mac/CCGLView.h" -#import "Platforms/Mac/CCDirectorMac.h" -#import "Platforms/Mac/CCWindow.h" -#import "Platforms/Mac/CCEventDispatcher.h" -#endif - -// -// cocos2d helper files -// -#import "Support/OpenGL_Internal.h" -#import "Support/CCFileUtils.h" -#import "Support/CGPointExtension.h" -#import "Support/ccCArray.h" -#import "Support/CCArray.h" -#import "Support/ccUtils.h" -#import "Support/TransformUtils.h" -#import "Support/CCProfiling.h" - -// -// external -// -#import "kazmath/kazmath.h" -#import "kazmath/GL/matrix.h" - - - -// free functions -NSString * cocos2dVersion(void); - -#ifdef __CC_PLATFORM_IOS -#ifndef __IPHONE_4_0 -#error "If you are targeting iPad, you should set BASE SDK = 4.0 (or 4.1, or 4.2), and set the 'iOS deploy target' = 3.2" -#endif -#endif diff --git a/Example/libs/cocos2d/cocos2d.m b/Example/libs/cocos2d/cocos2d.m deleted file mode 100644 index 197ec75..0000000 --- a/Example/libs/cocos2d/cocos2d.m +++ /dev/null @@ -1,34 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * Copyright (c) 2011 Zynga Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -#import -#import "cocos2d.h" -static NSString *version = @"cocos2d v2.0.0-rc0"; - -NSString *cocos2dVersion() -{ - return version; -} diff --git a/Example/libs/cocoslive/CLScoreServerPost.h b/Example/libs/cocoslive/CLScoreServerPost.h deleted file mode 100644 index 3954fa4..0000000 --- a/Example/libs/cocoslive/CLScoreServerPost.h +++ /dev/null @@ -1,141 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - - -#import - -// for MD5 signing -#import - -// cocoslive definitions -#import "cocoslive.h" - -// Score Server protocol version -#define SCORE_SERVER_PROTOCOL_VERSION @"1.1" - -// Server URL -#ifdef USE_LOCAL_SERVER -#define SCORE_SERVER_SEND_URL @"http://localhost:8080/api/post-score" -#define SCORE_SERVER_UPDATE_URL @"http://localhost:8080/api/update-score" -#else -#define SCORE_SERVER_SEND_URL @"http://www.cocoslive.net/api/post-score" -#define SCORE_SERVER_UPDATE_URL @"http://www.cocoslive.net/api/update-score" -#endif - -/// Type of errors from the Post Score request -typedef enum { - /// post request successful - kPostStatusOK = 0, - /// post request failed to establish a connection. wi-fi isn't enabled. - /// Don't retry when this option is preset - kPostStatusConnectionFailed = 1, - /// post request failed to post the score. Server might be busy. - /// Retry is suggested - kPostStatusPostFailed = 2, -} tPostStatus; - -enum { - //! Invalid Ranking. Valid rankins are from 1 to ... - kServerPostInvalidRanking = 0, -}; - -/** - * Handles the Score Post to the cocos live server - */ -@interface CLScoreServerPost : NSObject { - /// game key. secret shared with the server. - /// used to sign the values to prevent spoofing. - NSString *gameKey; - - /// game name, used as a login name. - NSString *gameName; - - /// delegate instance of fetch score - id delegate; - - /// ranking - NSUInteger ranking_; - - /// score was updated - BOOL scoreDidUpdate_; - - /// data received - NSMutableData *receivedData; - - /// values to send in the POST - NSMutableArray *bodyValues; - - /// status of the request - tPostStatus postStatus_; - - /// mdt context - CC_MD5_CTX md5Ctx; - - /// the connection - NSURLConnection *connection_; -} - -/** status from the score post */ -@property (nonatomic,readonly) tPostStatus postStatus; - -/** connection to the server */ -@property (nonatomic, retain) NSURLConnection *connection; - -/** ranking of your score - @since v0.7.3 - */ -@property (nonatomic,readonly) NSUInteger ranking; - -/** whether or not the score was updated - @since v0.7.3 - */ -@property (nonatomic,readonly) BOOL scoreDidUpdate; - -/** creates a cocos server with a game name and a game key */ -+(id) serverWithGameName:(NSString*) name gameKey:(NSString*) key delegate:(id)delegate; - -/** initializes a cocos server with a game name and a game key */ --(id) initWithGameName:(NSString*) name gameKey:(NSString*) key delegate:(id)delegate; - -/** send the scores to the server. A new entre will be created on the server */ --(BOOL) sendScore: (NSDictionary*) dict; - -/** - * Sends a score dictionary to the server for updating an existing entry by playername and device id, or creating a new one. - * The passed dictionary must contain a cc_playername key, otherwise it will raise and exception. - * @since v0.7.1 - */ --(BOOL) updateScore: (NSDictionary*) dict; - -@end - -/** CocosLivePost protocol */ -@protocol CLPostDelegate -/** callback method that will be called if the post is successful */ --(void) scorePostOk:(id) sender; -/** callback method that will be called if the post fails */ --(void) scorePostFail:(id) sender; -@end diff --git a/Example/libs/cocoslive/CLScoreServerPost.m b/Example/libs/cocoslive/CLScoreServerPost.m deleted file mode 100644 index e5a0388..0000000 --- a/Example/libs/cocoslive/CLScoreServerPost.m +++ /dev/null @@ -1,332 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import "CLScoreServerPost.h" -#import "ccMacros.h" - -// free function used to sort -NSInteger alphabeticSort(id string1, id string2, void *reverse) -{ - if ((NSInteger *)reverse == NO) - return [string2 localizedCaseInsensitiveCompare:string1]; - return [string1 localizedCaseInsensitiveCompare:string2]; -} - - -@interface CLScoreServerPost (Private) --(void) addValue:(NSString*)value key:(NSString*)key; --(void) calculateHashAndAddValue:(id)value key:(NSString*)key; --(NSString*) getHashForData; --(NSData*) getBodyValues; --(NSString*) encodeData:(NSString*)data; --(NSMutableURLRequest *) scoreServerRequestWithURLString:(NSString *)url; --(BOOL) submitScore:(NSDictionary*)dict forUpdate:(BOOL)isUpdate; -@end - - -@implementation CLScoreServerPost - -@synthesize postStatus = postStatus_; -@synthesize ranking = ranking_; -@synthesize scoreDidUpdate = scoreDidUpdate_; -@synthesize connection = connection_; - -+(id) serverWithGameName:(NSString*) name gameKey:(NSString*) key delegate:(id) delegate -{ - return [[[self alloc] initWithGameName:name gameKey:key delegate:delegate] autorelease]; -} - --(id) initWithGameName:(NSString*) name gameKey:(NSString*) key delegate:(id)aDelegate -{ - self = [super init]; - if( self ) { - gameKey = [key retain]; - gameName = [name retain]; - bodyValues = [[NSMutableArray arrayWithCapacity:5] retain]; - delegate = [aDelegate retain]; - receivedData = [[NSMutableData data] retain]; - - ranking_ = kServerPostInvalidRanking; - } - - return self; -} - --(void) dealloc -{ - CCLOGINFO(@"deallocing %@", self); - [delegate release]; - [gameKey release]; - [gameName release]; - [bodyValues release]; - [receivedData release]; - [connection_ release]; - [super dealloc]; -} - - -#pragma mark ScoreServer send scores --(BOOL) sendScore: (NSDictionary*) dict -{ - return [self submitScore:dict forUpdate:NO]; -} - --(BOOL) updateScore: (NSDictionary*) dict -{ - if (![dict objectForKey:@"cc_playername"]) { - // fail. cc_playername + cc_device_id are needed to update an score - [NSException raise:@"cocosLive:updateScore" format:@"cc_playername not found"]; - } - return [self submitScore:dict forUpdate:YES]; -} - --(BOOL) submitScore: (NSDictionary*)dict forUpdate:(BOOL)isUpdate -{ - [receivedData setLength:0]; - [bodyValues removeAllObjects]; - - // reset status - postStatus_ = kPostStatusOK; - - // create the request - NSMutableURLRequest *post = [self scoreServerRequestWithURLString:(isUpdate ? SCORE_SERVER_UPDATE_URL : SCORE_SERVER_SEND_URL)]; - - CC_MD5_Init( &md5Ctx); - - // hash SHALL be calculated in certain order - NSArray *keys = [dict allKeys]; - int reverseSort = NO; - NSArray *sortedKeys = [keys sortedArrayUsingFunction:alphabeticSort context:&reverseSort]; - for( id key in sortedKeys ) - [self calculateHashAndAddValue:[dict objectForKey:key] key:key]; - - // device id is hashed to prevent spoofing this same score from different devices - // one way to prevent a replay attack is to send cc_id & cc_time and use it as primary keys - - [self addValue:[[UIDevice currentDevice] uniqueIdentifier] key:@"cc_device_id"]; - [self addValue:gameName key:@"cc_gamename"]; - [self addValue:[self getHashForData] key:@"cc_hash"]; - [self addValue:SCORE_SERVER_PROTOCOL_VERSION key:@"cc_prot_ver"]; - - [post setHTTPBody: [self getBodyValues] ]; - - // create the connection with the request - // and start loading the data - self.connection=[[NSURLConnection alloc] initWithRequest:post delegate:self]; - - if ( ! connection_) - return NO; - - return YES; -} - --(NSMutableURLRequest *) scoreServerRequestWithURLString:(NSString *)url { - NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString: url] - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:10.0]; - - [request setHTTPMethod: @"POST"]; - [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; - return request; -} - --(void) calculateHashAndAddValue:(id) value key:(NSString*) key -{ - NSString *val; - // value shall be a string or nsnumber - if( [value respondsToSelector:@selector(stringValue)] ) - val = [value stringValue]; - else if( [value isKindOfClass:[NSString class]] ) - val = value; - else - [NSException raise:@"Invalid format for value" format:@"Invalid format for value. addValue"]; - - [self addValue:val key:key]; - - const char * data = [val UTF8String]; - CC_MD5_Update( &md5Ctx, data, strlen(data) ); -} - --(void) addValue:(NSString*)value key:(NSString*) key -{ - - NSString *encodedValue = [self encodeData:value]; - NSString *encodedKey = [self encodeData:key]; - - [bodyValues addObject: [NSString stringWithFormat:@"%@=%@", encodedKey, encodedValue] ]; -} - --(NSData*) getBodyValues { - NSMutableData *data = [[NSMutableData alloc] init]; - - BOOL first=YES; - for( NSString *s in bodyValues ) { - if( !first) - [data appendBytes:"&" length:1]; - - [data appendBytes:[s UTF8String] length:[s length]]; - first = NO; - } - - return [data autorelease]; -} - --(NSString*) getHashForData -{ - NSString *ret; - unsigned char pTempKey[16]; - - // update the hash with the secret key - const char *data = [gameKey UTF8String]; - CC_MD5_Update(&md5Ctx, data, strlen(data)); - - // then get the hash - CC_MD5_Final( pTempKey, &md5Ctx); - -// NSData *nsdata = [NSData dataWithBytes:pTempKey length:16]; - ret = [NSString stringWithString:@""]; - for( int i=0;i<16;i++) { - ret = [NSString stringWithFormat:@"%@%02x", ret, pTempKey[i] ]; - } - - return ret; -} - --(NSString*) encodeData:(NSString*) data -{ - NSString *newData; - - newData = [data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - - // '&' and '=' should be encoded manually - newData = [newData stringByReplacingOccurrencesOfString:@"&" withString:@"%26"]; - newData = [newData stringByReplacingOccurrencesOfString:@"=" withString:@"%3D"]; - - return newData; -} - -#pragma mark NSURLConnection Delegate - -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response -{ - // this method is called when the server has determined that it - // has enough information to create the NSURLResponse - - // it can be called multiple times, for example in the case of a - // redirect, so each time we reset the data. - // receivedData is declared as a method instance elsewhere - [receivedData setLength:0]; -} - -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data -{ - // append the new data to the receivedData - // receivedData is declared as a method instance elsewhere - [receivedData appendData:data]; - -// NSString *dataString = [NSString stringWithCString:[data bytes] length: [data length]]; -// CCLOG( @"data: %@", dataString); -} - -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error -{ - CCLOG(@"Connection failed"); - - // wifi problems ? - postStatus_ = kPostStatusConnectionFailed; - - // release the connection - self.connection = nil; - - if( [delegate respondsToSelector:@selector(scorePostFail:) ] ) - [delegate scorePostFail:self]; -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)connection -{ - // release the connection - self.connection = nil; - -// NSString *dataString = [NSString stringWithCString:[receivedData bytes] length: [receivedData length]]; - NSString *dataString = [NSString stringWithCString:[receivedData bytes] encoding: NSASCIIStringEncoding]; - - if( [dataString hasPrefix:@"OK:"] ) { - // parse ranking and other possible answers - NSArray *values = [dataString componentsSeparatedByString:@":"]; - NSArray *answer = [ [values objectAtIndex:1] componentsSeparatedByString:@","]; - NSEnumerator *nse = [answer objectEnumerator]; - - // Create a holder for each line we are going to work with - NSString *line; - - // Loop through all the lines in the lines array processing each one - while( (line = [nse nextObject]) ) { - NSArray *keyvalue = [line componentsSeparatedByString:@"="]; -// NSLog(@"%@",keyvalue); - if( [[keyvalue objectAtIndex:0] isEqual:@"ranking"] ) { - ranking_ = [[keyvalue objectAtIndex:1] intValue]; - } else if( [[keyvalue objectAtIndex:0] isEqual:@"score_updated"] ) { - scoreDidUpdate_ = [[keyvalue objectAtIndex:1] boolValue]; - } - - } - if( [delegate respondsToSelector:@selector(scorePostOk:) ] ) - [delegate scorePostOk:self]; - - } else if( [dataString hasPrefix: @"OK"] ) { - - // Ok - postStatus_ = kPostStatusOK; - - if( [delegate respondsToSelector:@selector(scorePostOk:) ] ) - [delegate scorePostOk:self]; - - - } else { - - NSLog(@"cocoslive: Post Score failed. Reason: %@", dataString); - - // Error parsing answer - postStatus_ = kPostStatusPostFailed; - - if( [delegate respondsToSelector:@selector(scorePostFail:) ] ) - [delegate scorePostFail:self]; - } -} - --(NSURLRequest *)connection:(NSURLConnection *)connection - willSendRequest:(NSURLRequest *)request - redirectResponse:(NSURLResponse *)redirectResponse -{ - NSURLRequest *newRequest=request; - if (redirectResponse) { - newRequest=nil; - } - - return newRequest; -} - -@end diff --git a/Example/libs/cocoslive/CLScoreServerRequest.h b/Example/libs/cocoslive/CLScoreServerRequest.h deleted file mode 100644 index 5428b23..0000000 --- a/Example/libs/cocoslive/CLScoreServerRequest.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - - -#import - -// cocoslive definitions -#import "cocoslive.h" - -// Server URL -#if USE_LOCAL_SERVER -#define SCORE_SERVER_REQUEST_URL @"http://localhost:8080/api/get-scores" -#define SCORE_SERVER_GETRANK_URL @"http://localhost:8080/api/get-rank-for-score" -#else -#define SCORE_SERVER_REQUEST_URL @"http://www.cocoslive.net/api/get-scores" -#define SCORE_SERVER_GETRANK_URL @"http://www.cocoslive.net/api/get-rank-for-score" -#endif - -/** Type of predefined Query */ -typedef enum { - kQueryIgnore = 0, - kQueryDay = 1, - kQueryWeek = 2, - kQueryMonth = 3, - kQueryAllTime = 4, -} tQueryType; - -/** Flags that can be added to the query */ -typedef enum { - kQueryFlagIgnore = 0, - kQueryFlagByCountry = 1 << 0, - kQueryFlagByDevice = 1 << 1, -} tQueryFlags; - -/** - * Handles the Request Scores to the cocos live server - */ -@interface CLScoreServerRequest : NSObject { - - /// game name, used as a login name. - NSString *gameName; - - /// delegate instance of fetch score - id delegate; - - // data received - NSMutableData *receivedData; - - // To determine which delegate method will be called in connectionDidFinishLoading: of NSURLConnection Delegate - BOOL reqRankOnly; - - /// the connection - NSURLConnection *connection_; -} - -/** connection to the server */ -@property (nonatomic, retain) NSURLConnection *connection; - - -/** creates a ScoreServerRequest server with a game name*/ -+(id) serverWithGameName:(NSString*) name delegate:(id)delegate; - -/** initializes a ScoreServerRequest with a game name*/ --(id) initWithGameName:(NSString*) name delegate:(id)delegate; - -/** request scores from server using a predefined query. This is an asyncronous request. - * limit: how many scores are being requested. Maximun is 100 - * flags: can be kQueryFlagByCountry (fetches only scores from country) - * category: an NSString. For example: 'easy', 'medium', 'type1'... When requesting scores, they can be filtered by this field. - */ --(BOOL) requestScores: (tQueryType) type limit:(int)limit offset:(int)offset flags:(tQueryFlags)flags category:(NSString*)category; - -/** request scores from server using a predefined query. This is an asyncronous request. - * limit: how many scores are being requested. Maximun is 100 - * flags: can be kQueryFlagByCountry (fetches only scores from country) - */ --(BOOL) requestScores: (tQueryType) type limit:(int)limit offset:(int)offset flags:(tQueryFlags)flags; - -/** parse the received JSON scores and convert it to objective-c objects */ --(NSArray*) parseScores; - -/** request rank for a given score using a predefined query. This is an asyncronous request. - * score: int for a score - * category: an NSString. For example: 'easy', 'medium', 'type1'... When requesting ranks, they can be filtered by this field. - */ --(BOOL) requestRankForScore:(int)score andCategory:(NSString*)category; - -/** It's actually not parsing anything, just returning int for a rank. Kept name PARSE for convinience with parseScores */ --(int) parseRank; - -@end - -/** CocosLive Request protocol */ -@protocol CLRequestDelegate --(void) scoreRequestOk:(id) sender; --(void) scoreRequestRankOk:(id) sender; --(void) scoreRequestFail:(id) sender; -@end diff --git a/Example/libs/cocoslive/CLScoreServerRequest.m b/Example/libs/cocoslive/CLScoreServerRequest.m deleted file mode 100644 index 2e6bc76..0000000 --- a/Example/libs/cocoslive/CLScoreServerRequest.m +++ /dev/null @@ -1,256 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -// 3rd party imports -#import "CJSONDeserializer.h" - -// local imports -#import "CLScoreServerPost.h" -#import "CLScoreServerRequest.h" -#import "ccMacros.h" - -@implementation CLScoreServerRequest - -@synthesize connection=connection_; - -+(id) serverWithGameName:(NSString*) name delegate:(id)delegate -{ - return [[[self alloc] initWithGameName:name delegate:delegate] autorelease]; -} - --(id) initWithGameName:(NSString*) name delegate:(id)aDelegate -{ - self = [super init]; - if( self ) { - gameName = [[name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] retain]; - delegate = [aDelegate retain]; - receivedData = [[NSMutableData data] retain]; - } - return self; -} - --(void) dealloc -{ - CCLOGINFO(@"deallocing %@", self); - - [delegate release]; - [gameName release]; - [receivedData release]; - [connection_ release]; - [super dealloc]; -} - --(BOOL) requestScores:(tQueryType)type - limit:(int)limit - offset:(int)offset - flags:(tQueryFlags)flags - category:(NSString*)category -{ - // create the request - [receivedData setLength:0]; - - // it's not a call for rank - reqRankOnly = NO; - - NSString *device = @""; - if( flags & kQueryFlagByDevice ) - device = [[UIDevice currentDevice] uniqueIdentifier]; - - // arguments: - // query: type of query - // limit: how many scores are being requested. Default is 25. Maximun is 100 - // offset: offset of the scores - // flags: bring only country scores, world scores, etc. - // category: string user defined string used to filter - NSString *url= [NSString stringWithFormat:@"%@?gamename=%@&querytype=%d&offset=%d&limit=%d&flags=%d&category=%@&device=%@", - SCORE_SERVER_REQUEST_URL, - gameName, - type, - offset, - limit, - flags, - [category stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding], - device - ]; - - // NSLog(@"%@", url); - - NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url] - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:10.0]; - - // create the connection with the request - // and start loading the data - self.connection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; - if (! connection_) - return NO; - - return YES; -} - --(BOOL) requestScores:(tQueryType)type - limit:(int)limit - offset:(int)offset - flags:(tQueryFlags)flags -{ - // create the request - [receivedData setLength:0]; - - // arguments: - // query: type of query - // limit: how many scores are being requested. Maximun is 100 - // offset: offset of the scores - // flags: bring only country scores, world scores, etc. - return [self requestScores:type limit:limit offset:offset flags:flags category:@""]; -} - --(NSArray*) parseScores -{ - NSArray *array = nil; - NSError *error = nil; - NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:receivedData error:&error]; - -// NSLog(@"r: %@", dictionary); - if( ! error ) { - array = [dictionary objectForKey:@"scores"]; - } else { - CCLOG(@"Error parsing scores: %@", error); - } - return array; -} - -#pragma mark Request rank for score - --(BOOL) requestRankForScore:(int)score andCategory:(NSString*)category { - // create the request - [receivedData setLength:0]; - - reqRankOnly = YES; - - // arguments: - // score: score for which you need rank - // category: user defined string used to filter - NSString *url= [NSString stringWithFormat:@"%@?gamename=%@&category=%@&score=%d", - SCORE_SERVER_GETRANK_URL, - gameName, - [category stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding], - score - ]; - - NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url] - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:10.0]; - - // create the connection with the request - // and start loading the data - self.connection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; - if (! connection_) - return NO; - - return YES; -} - --(int) parseRank { -// NSString *rankStr = [NSString stringWithCString:[receivedData bytes] length: [receivedData length]]; - NSString *rankStr = [NSString stringWithCString:[receivedData bytes] encoding: NSASCIIStringEncoding]; - -// NSLog(@"XXXX: Ranking: %@", rankStr); - - // creating trimmed string by trimming everything that's not numbers from the receivedData - NSString *trimmedStr = [rankStr stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]; - - int scoreInt = [trimmedStr intValue]; - - return scoreInt; -} - - -#pragma mark NSURLConnection Delegate - -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response -{ - // this method is called when the server has determined that it - // has enough information to create the NSURLResponse - - // it can be called multiple times, for example in the case of a - // redirect, so each time we reset the data. - // receivedData is declared as a method instance elsewhere - - [receivedData setLength:0]; -} - -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data -{ - // append the new data to the receivedData - // receivedData is declared as a method instance elsewhere - [receivedData appendData:data]; -} - -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error -{ - // release the connection, and the data object - self.connection = nil; - - - CCLOG(@"Error getting scores: %@", error); - - if( [delegate respondsToSelector:@selector(scoreRequestFail:) ] ) - [delegate scoreRequestFail:self]; - -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)connection -{ - // release the connection, and the data object - self.connection = nil; - - - if(reqRankOnly) { - // because it's request for rank, different delegate method is called scoreRequestRankOk: - // if connection failed the same delegate method is used as for standard scores - scoreRequestFail: - if( [delegate respondsToSelector:@selector(scoreRequestRankOk:) ] ) { - [delegate scoreRequestRankOk:self]; - } - } else { - if( [delegate respondsToSelector:@selector(scoreRequestOk:) ] ) { - [delegate scoreRequestOk:self]; - } - - } -} - --(NSURLRequest *)connection:(NSURLConnection *)connection - willSendRequest:(NSURLRequest *)request - redirectResponse:(NSURLResponse *)redirectResponse -{ - NSURLRequest *newRequest=request; - if (redirectResponse) { - newRequest=nil; - } - return newRequest; -} - -@end diff --git a/Example/libs/cocoslive/cocoslive.h b/Example/libs/cocoslive/cocoslive.h deleted file mode 100644 index 2c7dfe4..0000000 --- a/Example/libs/cocoslive/cocoslive.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - - -// 0x00 HI ME LO -// 00 00 03 02 -#define COCOSLIVE_VERSION 0x00000302 - -// to use localserver. DEBUG ONLY -//#define USE_LOCAL_SERVER 1 - -// all cocos live include files -// -#import "CLScoreServerPost.h" -#import "CLScoreServerRequest.h" - - -// free functions -NSString * cocos2dVersion(void); diff --git a/Example/libs/cocoslive/cocoslive.m b/Example/libs/cocoslive/cocoslive.m deleted file mode 100644 index 2883659..0000000 --- a/Example/libs/cocoslive/cocoslive.m +++ /dev/null @@ -1,34 +0,0 @@ -/* - * cocos2d for iPhone: http://www.cocos2d-iphone.org - * - * Copyright (c) 2008-2010 Ricardo Quesada - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - - -#import - -static NSString *version = @"cocoslive v0.3.2"; - -NSString *cocosLiveVersion() -{ - return version; -} diff --git a/Example/libs/kazmath/include/kazmath/GL/mat4stack.h b/Example/libs/kazmath/include/kazmath/GL/mat4stack.h deleted file mode 100644 index 7de12aa..0000000 --- a/Example/libs/kazmath/include/kazmath/GL/mat4stack.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef C_STACK_H_INCLUDED -#define C_STACK_H_INCLUDED - -#include "../mat4.h" - -typedef struct km_mat4_stack { - int capacity; //The total item capacity - int item_count; //The number of items - kmMat4* top; - kmMat4* stack; -} km_mat4_stack; - -#ifdef __cplusplus -extern "C" { -#endif - -void km_mat4_stack_initialize(km_mat4_stack* stack); -void km_mat4_stack_push(km_mat4_stack* stack, const kmMat4* item); -void km_mat4_stack_pop(km_mat4_stack* stack, kmMat4* pOut); -void km_mat4_stack_release(km_mat4_stack* stack); - -#ifdef __cplusplus -} -#endif - -#endif // C_STACK_H_INCLUDED diff --git a/Example/libs/kazmath/include/kazmath/GL/matrix.h b/Example/libs/kazmath/include/kazmath/GL/matrix.h deleted file mode 100644 index 1fa0267..0000000 --- a/Example/libs/kazmath/include/kazmath/GL/matrix.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef KM_GL_MATRIX_H_INCLUDED -#define KM_GL_MATRIX_H_INCLUDED - -#define KM_GL_MODELVIEW 0x1700 -#define KM_GL_PROJECTION 0x1701 -#define KM_GL_TEXTURE 0x1702 - -typedef unsigned int kmGLEnum; - -#include "../mat4.h" -#include "../vec3.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void kmGLFreeAll(void); -void kmGLPushMatrix(void); -void kmGLPopMatrix(void); -void kmGLMatrixMode(kmGLEnum mode); -void kmGLLoadIdentity(void); -void kmGLLoadMatrix(const kmMat4* pIn); -void kmGLMultMatrix(const kmMat4* pIn); -void kmGLTranslatef(float x, float y, float z); -void kmGLRotatef(float angle, float x, float y, float z); -void kmGLScalef(float x, float y, float z); -void kmGLGetMatrix(kmGLEnum mode, kmMat4* pOut); - -#ifdef __cplusplus -} -#endif - -#endif // MATRIX_H_INCLUDED diff --git a/Example/libs/kazmath/include/kazmath/aabb.h b/Example/libs/kazmath/include/kazmath/aabb.h deleted file mode 100644 index 0e78a04..0000000 --- a/Example/libs/kazmath/include/kazmath/aabb.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef KAZMATH_AABB_H_INCLUDED -#define KAZMATH_AABB_H_INCLUDED - -#include "vec3.h" -#include "utility.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * A struture that represents an axis-aligned - * bounding box. - */ -typedef struct kmAABB { - kmVec3 min; /** The max corner of the box */ - kmVec3 max; /** The min corner of the box */ -} kmAABB; - -const int kmAABBContainsPoint(const kmVec3* pPoint, const kmAABB* pBox); -kmAABB* const kmAABBAssign(kmAABB* pOut, const kmAABB* pIn); -kmAABB* const kmAABBScale(kmAABB* pOut, const kmAABB* pIn, kmScalar s); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/Example/libs/kazmath/include/kazmath/kazmath.h b/Example/libs/kazmath/include/kazmath/kazmath.h deleted file mode 100644 index ef09870..0000000 --- a/Example/libs/kazmath/include/kazmath/kazmath.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef KAZMATH_H_INCLUDED -#define KAZMATH_H_INCLUDED - -#include "vec2.h" -#include "vec3.h" -#include "mat3.h" -#include "mat4.h" -#include "utility.h" -#include "quaternion.h" -#include "plane.h" -#include "aabb.h" -#include "ray2.h" - -#endif // KAZMATH_H_INCLUDED diff --git a/Example/libs/kazmath/include/kazmath/mat3.h b/Example/libs/kazmath/include/kazmath/mat3.h deleted file mode 100644 index f0de423..0000000 --- a/Example/libs/kazmath/include/kazmath/mat3.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - - -#ifndef MAT3_H_INCLUDED -#define MAT3_H_INCLUDED - -#include "utility.h" - -struct kmVec3; -struct kmQuaternion; - -typedef struct kmMat3{ - kmScalar mat[9]; -} kmMat3; - -#ifdef __cplusplus -extern "C" { -#endif - -kmMat3* const kmMat3Fill(kmMat3* pOut, const kmScalar* pMat); -kmMat3* const kmMat3Adjugate(kmMat3* pOut, const kmMat3* pIn); -kmMat3* const kmMat3Identity(kmMat3* pOut); -kmMat3* const kmMat3Inverse(kmMat3* pOut, const kmScalar pDeterminate, const kmMat3* pM); -const int kmMat3IsIdentity(const kmMat3* pIn); -kmMat3* const kmMat3Transpose(kmMat3* pOut, const kmMat3* pIn); -const kmScalar kmMat3Determinant(const kmMat3* pIn); -kmMat3* const kmMat3Multiply(kmMat3* pOut, const kmMat3* pM1, const kmMat3* pM2); -kmMat3* const kmMat3ScalarMultiply(kmMat3* pOut, const kmMat3* pM, const kmScalar pFactor); - -kmMat3* const kmMat3RotationAxisAngle(kmMat3* pOut, const struct kmVec3* axis, kmScalar radians); -struct kmVec3* const kmMat3RotationToAxisAngle(struct kmVec3* pAxis, kmScalar* radians, const kmMat3* pIn); - -kmMat3* const kmMat3Assign(kmMat3* pOut, const kmMat3* pIn); -const int kmMat3AreEqual(const kmMat3* pM1, const kmMat3* pM2); - -kmMat3* const kmMat3RotationX(kmMat3* pOut, const kmScalar radians); -kmMat3* const kmMat3RotationY(kmMat3* pOut, const kmScalar radians); -kmMat3* const kmMat3RotationZ(kmMat3* pOut, const kmScalar radians); - -kmMat3* const kmMat3Rotation(kmMat3* pOut, const kmScalar radians); -kmMat3* const kmMat3Scaling(kmMat3* pOut, const kmScalar x, const kmScalar y); -kmMat3* const kmMat3Translation(kmMat3* pOut, const kmScalar x, const kmScalar y); - -kmMat3* const kmMat3RotationQuaternion(kmMat3* pOut, const struct kmQuaternion* pIn); -kmMat3* const kmMat3RotationAxisAngle(kmMat3* pOut, const struct kmVec3* axis, kmScalar radians); -struct kmVec3* const kmMat3RotationToAxisAngle(struct kmVec3* pAxis, kmScalar* radians, const kmMat3* pIn); - -#ifdef __cplusplus -} -#endif -#endif // MAT3_H_INCLUDED - diff --git a/Example/libs/kazmath/include/kazmath/mat4.h b/Example/libs/kazmath/include/kazmath/mat4.h deleted file mode 100644 index 38008ba..0000000 --- a/Example/libs/kazmath/include/kazmath/mat4.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef MAT4_H_INCLUDED -#define MAT4_H_INCLUDED - -#include "utility.h" - -struct kmVec3; -struct kmMat3; -struct kmQuaternion; -struct kmPlane; - -/* -A 4x4 matrix - - | 0 4 8 12 | -mat = | 1 5 9 13 | - | 2 6 10 14 | - | 3 7 11 15 | -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct kmMat4 { - kmScalar mat[16]; -} kmMat4; - -kmMat4* const kmMat4Fill(kmMat4* pOut, const kmScalar* pMat); - - -kmMat4* const kmMat4Identity(kmMat4* pOut); - -kmMat4* const kmMat4Inverse(kmMat4* pOut, const kmMat4* pM); - - -const int kmMat4IsIdentity(const kmMat4* pIn); - -kmMat4* const kmMat4Transpose(kmMat4* pOut, const kmMat4* pIn); -kmMat4* const kmMat4Multiply(kmMat4* pOut, const kmMat4* pM1, const kmMat4* pM2); - -kmMat4* const kmMat4Assign(kmMat4* pOut, const kmMat4* pIn); -const int kmMat4AreEqual(const kmMat4* pM1, const kmMat4* pM2); - -kmMat4* const kmMat4RotationX(kmMat4* pOut, const kmScalar radians); -kmMat4* const kmMat4RotationY(kmMat4* pOut, const kmScalar radians); -kmMat4* const kmMat4RotationZ(kmMat4* pOut, const kmScalar radians); -kmMat4* const kmMat4RotationPitchYawRoll(kmMat4* pOut, const kmScalar pitch, const kmScalar yaw, const kmScalar roll); -kmMat4* const kmMat4RotationQuaternion(kmMat4* pOut, const struct kmQuaternion* pQ); -kmMat4* const kmMat4RotationTranslation(kmMat4* pOut, const struct kmMat3* rotation, const struct kmVec3* translation); -kmMat4* const kmMat4Scaling(kmMat4* pOut, const kmScalar x, const kmScalar y, const kmScalar z); -kmMat4* const kmMat4Translation(kmMat4* pOut, const kmScalar x, const kmScalar y, const kmScalar z); - -struct kmVec3* const kmMat4GetUpVec3(struct kmVec3* pOut, const kmMat4* pIn); -struct kmVec3* const kmMat4GetRightVec3(struct kmVec3* pOut, const kmMat4* pIn); -struct kmVec3* const kmMat4GetForwardVec3(struct kmVec3* pOut, const kmMat4* pIn); - -kmMat4* const kmMat4PerspectiveProjection(kmMat4* pOut, kmScalar fovY, kmScalar aspect, kmScalar zNear, kmScalar zFar); -kmMat4* const kmMat4OrthographicProjection(kmMat4* pOut, kmScalar left, kmScalar right, kmScalar bottom, kmScalar top, kmScalar nearVal, kmScalar farVal); -kmMat4* const kmMat4LookAt(kmMat4* pOut, const struct kmVec3* pEye, const struct kmVec3* pCenter, const struct kmVec3* pUp); - -kmMat4* const kmMat4RotationAxisAngle(kmMat4* pOut, const struct kmVec3* axis, kmScalar radians); -struct kmMat3* const kmMat4ExtractRotation(struct kmMat3* pOut, const kmMat4* pIn); -struct kmPlane* const kmMat4ExtractPlane(struct kmPlane* pOut, const kmMat4* pIn, const kmEnum plane); -struct kmVec3* const kmMat4RotationToAxisAngle(struct kmVec3* pAxis, kmScalar* radians, const kmMat4* pIn); -#ifdef __cplusplus -} -#endif -#endif /* MAT4_H_INCLUDED */ diff --git a/Example/libs/kazmath/include/kazmath/neon_matrix_impl.h b/Example/libs/kazmath/include/kazmath/neon_matrix_impl.h deleted file mode 100644 index 3fcf3e4..0000000 --- a/Example/libs/kazmath/include/kazmath/neon_matrix_impl.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - NEON math library for the iPhone / iPod touch - - Copyright (c) 2009 Justin Saunders - - This software is provided 'as-is', without any express or implied warranty. - In no event will the authors be held liable for any damages arising - from the use of this software. - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it freely, - subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must - not claim that you wrote the original software. If you use this - software in a product, an acknowledgment in the product documentation - would be appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must - not be misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef __NEON_MATRIX_IMPL_H__ -#define __NEON_MATRIX_IMPL_H__ - -#ifdef __arm__ -#include "arm/arch.h" -#endif - -// Matrixes are assumed to be stored in column major format according to OpenGL -// specification. - -// Multiplies two 4x4 matrices (a,b) outputing a 4x4 matrix (output) -void NEON_Matrix4Mul(const float* a, const float* b, float* output ); - -// Multiplies a 4x4 matrix (m) with a vector 4 (v), outputing a vector 4 -void NEON_Matrix4Vector4Mul(const float* m, const float* v, float* output); - - -#endif // __NEON_MATRIX_IMPL_H__ diff --git a/Example/libs/kazmath/include/kazmath/plane.h b/Example/libs/kazmath/include/kazmath/plane.h deleted file mode 100644 index 4270a8a..0000000 --- a/Example/libs/kazmath/include/kazmath/plane.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef PLANE_H_INCLUDED -#define PLANE_H_INCLUDED - -#define KM_PLANE_LEFT 0 -#define KM_PLANE_RIGHT 1 -#define KM_PLANE_BOTTOM 2 -#define KM_PLANE_TOP 3 -#define KM_PLANE_NEAR 4 -#define KM_PLANE_FAR 5 - -#include "utility.h" - -struct kmVec3; -struct kmVec4; -struct kmMat4; - -typedef struct kmPlane { - kmScalar a, b, c, d; -} kmPlane; - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum POINT_CLASSIFICATION { - POINT_INFRONT_OF_PLANE = 0, - POINT_BEHIND_PLANE, - POINT_ON_PLANE, -} POINT_CLASSIFICATION; - -const kmScalar kmPlaneDot(const kmPlane* pP, const struct kmVec4* pV); -const kmScalar kmPlaneDotCoord(const kmPlane* pP, const struct kmVec3* pV); -const kmScalar kmPlaneDotNormal(const kmPlane* pP, const struct kmVec3* pV); -kmPlane* const kmPlaneFromPointNormal(kmPlane* pOut, const struct kmVec3* pPoint, const struct kmVec3* pNormal); -kmPlane* const kmPlaneFromPoints(kmPlane* pOut, const struct kmVec3* p1, const struct kmVec3* p2, const struct kmVec3* p3); -kmVec3* const kmPlaneIntersectLine(struct kmVec3* pOut, const kmPlane* pP, const struct kmVec3* pV1, const struct kmVec3* pV2); -kmPlane* const kmPlaneNormalize(kmPlane* pOut, const kmPlane* pP); -kmPlane* const kmPlaneScale(kmPlane* pOut, const kmPlane* pP, kmScalar s); -const POINT_CLASSIFICATION kmPlaneClassifyPoint(const kmPlane* pIn, const kmVec3* pP); /** Classifys a point against a plane */ - -#ifdef __cplusplus -} -#endif - -#endif // PLANE_H_INCLUDED diff --git a/Example/libs/kazmath/include/kazmath/quaternion.h b/Example/libs/kazmath/include/kazmath/quaternion.h deleted file mode 100644 index 81ff547..0000000 --- a/Example/libs/kazmath/include/kazmath/quaternion.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef QUATERNION_H_INCLUDED -#define QUATERNION_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -#include "utility.h" - -struct kmMat4; -struct kmMat3; -struct kmVec3; - -typedef struct kmQuaternion { - kmScalar x; - kmScalar y; - kmScalar z; - kmScalar w; -} kmQuaternion; - -kmQuaternion* const kmQuaternionConjugate(kmQuaternion* pOut, const kmQuaternion* pIn); ///< Returns pOut, sets pOut to the conjugate of pIn - -const kmScalar kmQuaternionDot(const kmQuaternion* q1, const kmQuaternion* q2); ///< Returns the dot product of the 2 quaternions - -kmQuaternion* kmQuaternionExp(kmQuaternion* pOut, const kmQuaternion* pIn); ///< Returns the exponential of the quaternion - -///< Makes the passed quaternion an identity quaternion - -kmQuaternion* kmQuaternionIdentity(kmQuaternion* pOut); - -///< Returns the inverse of the passed Quaternion - -kmQuaternion* kmQuaternionInverse(kmQuaternion* pOut, - const kmQuaternion* pIn); - -///< Returns true if the quaternion is an identity quaternion - -int kmQuaternionIsIdentity(const kmQuaternion* pIn); - -///< Returns the length of the quaternion - -kmScalar kmQuaternionLength(const kmQuaternion* pIn); - -///< Returns the length of the quaternion squared (prevents a sqrt) - -kmScalar kmQuaternionLengthSq(const kmQuaternion* pIn); - -///< Returns the natural logarithm - -kmQuaternion* kmQuaternionLn(kmQuaternion* pOut, const kmQuaternion* pIn); - -///< Multiplies 2 quaternions together - -kmQuaternion* kmQuaternionMultiply(kmQuaternion* pOut, const kmQuaternion* q1, const kmQuaternion* q2); - -///< Normalizes a quaternion - -kmQuaternion* kmQuaternionNormalize(kmQuaternion* pOut, const kmQuaternion* pIn); - -///< Rotates a quaternion around an axis - -kmQuaternion* kmQuaternionRotationAxis(kmQuaternion* pOut, const struct kmVec3* pV, kmScalar angle); - -///< Creates a quaternion from a rotation matrix - -kmQuaternion* kmQuaternionRotationMatrix(kmQuaternion* pOut, const struct kmMat3* pIn); - -///< Create a quaternion from yaw, pitch and roll - -kmQuaternion* kmQuaternionRotationYawPitchRoll(kmQuaternion* pOut, kmScalar yaw, kmScalar pitch, kmScalar roll); -///< Interpolate between 2 quaternions -kmQuaternion* kmQuaternionSlerp(kmQuaternion* pOut, const kmQuaternion* q1, const kmQuaternion* q2, kmScalar t); - -///< Get the axis and angle of rotation from a quaternion -void kmQuaternionToAxisAngle(const kmQuaternion* pIn, struct kmVec3* pVector, kmScalar* pAngle); - -///< Scale a quaternion -kmQuaternion* kmQuaternionScale(kmQuaternion* pOut, const kmQuaternion* pIn, kmScalar s); -kmQuaternion* kmQuaternionAssign(kmQuaternion* pOut, const kmQuaternion* pIn); -kmQuaternion* kmQuaternionAdd(kmQuaternion* pOut, const kmQuaternion* pQ1, const kmQuaternion* pQ2); -kmQuaternion* kmQuaternionRotationBetweenVec3(kmQuaternion* pOut, const struct kmVec3* vec1, const struct kmVec3* vec2, const struct kmVec3* fallback); -struct kmVec3* kmQuaternionMultiplyVec3(struct kmVec3* pOut, const kmQuaternion* q, const struct kmVec3* v); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/Example/libs/kazmath/include/kazmath/ray2.h b/Example/libs/kazmath/include/kazmath/ray2.h deleted file mode 100644 index 609e6e5..0000000 --- a/Example/libs/kazmath/include/kazmath/ray2.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright (c) 2011, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef RAY_2_H -#define RAY_2_H - -#include "utility.h" -#include "vec2.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct kmRay2 { - kmVec2 start; - kmVec2 dir; -} kmRay2; - -void kmRay2Fill(kmRay2* ray, kmScalar px, kmScalar py, kmScalar vx, kmScalar vy); -kmBool kmRay2IntersectLineSegment(const kmRay2* ray, const kmVec2* p1, const kmVec2* p2, kmVec2* intersection); -kmBool kmRay2IntersectTriangle(const kmRay2* ray, const kmVec2* p1, const kmVec2* p2, const kmVec2* p3, kmVec2* intersection, kmVec2* normal_out); -kmBool kmRay2IntersectCircle(const kmRay2* ray, const kmVec2 centre, const kmScalar radius, kmVec2* intersection); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/Example/libs/kazmath/include/kazmath/utility.h b/Example/libs/kazmath/include/kazmath/utility.h deleted file mode 100644 index 14d66dc..0000000 --- a/Example/libs/kazmath/include/kazmath/utility.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef UTILITY_H_INCLUDED -#define UTILITY_H_INCLUDED - -#include - -#ifndef kmScalar -#define kmScalar float -#endif - -#ifndef kmBool -#define kmBool unsigned char -#endif - -#ifndef kmEnum -#define kmEnum unsigned int -#endif - -#ifndef KM_FALSE -#define KM_FALSE 0 -#endif - -#ifndef KM_TRUE -#define KM_TRUE 1 -#endif - -#define kmPI 3.141592f -#define kmPIOver180 0.017453f // PI / 180 -#define kmPIUnder180 57.295779f // 180 / PI -#define kmEpsilon 1.0 / 64.0 - - - -#ifdef __cplusplus -extern "C" { -#endif - -extern kmScalar kmSQR(kmScalar s); -extern kmScalar kmDegreesToRadians(kmScalar degrees); -extern kmScalar kmRadiansToDegrees(kmScalar radians); - -extern kmScalar min(kmScalar lhs, kmScalar rhs); -extern kmScalar max(kmScalar lhs, kmScalar rhs); -extern kmBool kmAlmostEqual(kmScalar lhs, kmScalar rhs); - -#ifdef __cplusplus -} -#endif - -#endif /* UTILITY_H_INCLUDED */ diff --git a/Example/libs/kazmath/include/kazmath/vec2.h b/Example/libs/kazmath/include/kazmath/vec2.h deleted file mode 100644 index 3ca56b3..0000000 --- a/Example/libs/kazmath/include/kazmath/vec2.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef VEC2_H_INCLUDED -#define VEC2_H_INCLUDED - -struct kmMat3; - -#ifndef kmScalar -#define kmScalar float -#endif - -#pragma pack(push) /* push current alignment to stack */ -#pragma pack(1) /* set alignment to 1 byte boundary */ -typedef struct kmVec2 { - kmScalar x; - kmScalar y; -} kmVec2; - -#pragma pack(pop) - -#ifdef __cplusplus -extern "C" { -#endif -kmVec2* kmVec2Fill(kmVec2* pOut, kmScalar x, kmScalar y); -kmScalar kmVec2Length(const kmVec2* pIn); ///< Returns the length of the vector -kmScalar kmVec2LengthSq(const kmVec2* pIn); ///< Returns the square of the length of the vector -kmVec2* kmVec2Normalize(kmVec2* pOut, const kmVec2* pIn); ///< Returns the vector passed in set to unit length -kmVec2* kmVec2Add(kmVec2* pOut, const kmVec2* pV1, const kmVec2* pV2); ///< Adds 2 vectors and returns the result -kmScalar kmVec2Dot(const kmVec2* pV1, const kmVec2* pV2); /** Returns the Dot product which is the cosine of the angle between the two vectors multiplied by their lengths */ -kmVec2* kmVec2Subtract(kmVec2* pOut, const kmVec2* pV1, const kmVec2* pV2); ///< Subtracts 2 vectors and returns the result -kmVec2* kmVec2Transform(kmVec2* pOut, const kmVec2* pV1, const struct kmMat3* pM); /** Transform the Vector */ -kmVec2* kmVec2TransformCoord(kmVec2* pOut, const kmVec2* pV, const struct kmMat3* pM); /// - -#ifndef kmScalar -#define kmScalar float -#endif - -struct kmMat4; - -typedef struct kmVec3 { - kmScalar x; - kmScalar y; - kmScalar z; -} kmVec3; - -#ifdef __cplusplus -extern "C" { -#endif - -kmVec3* kmVec3Fill(kmVec3* pOut, kmScalar x, kmScalar y, kmScalar z); -kmScalar kmVec3Length(const kmVec3* pIn); /** Returns the length of the vector */ -kmScalar kmVec3LengthSq(const kmVec3* pIn); /** Returns the square of the length of the vector */ -kmVec3* kmVec3Normalize(kmVec3* pOut, const kmVec3* pIn); /** Returns the vector passed in set to unit length */ -kmVec3* kmVec3Cross(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2); /** Returns a vector perpendicular to 2 other vectors */ -kmScalar kmVec3Dot(const kmVec3* pV1, const kmVec3* pV2); /** Returns the cosine of the angle between 2 vectors */ -kmVec3* kmVec3Add(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2); /** Adds 2 vectors and returns the result */ -kmVec3* kmVec3Subtract(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2); /** Subtracts 2 vectors and returns the result */ -kmVec3* kmVec3Transform(kmVec3* pOut, const kmVec3* pV1, const struct kmMat4* pM); /** Transforms a vector (assuming w=1) by a given matrix */ -kmVec3* kmVec3TransformNormal(kmVec3* pOut, const kmVec3* pV, const struct kmMat4* pM);/**Transforms a 3D normal by a given matrix */ -kmVec3* kmVec3TransformCoord(kmVec3* pOut, const kmVec3* pV, const struct kmMat4* pM); /**Transforms a 3D vector by a given matrix, projecting the result back into w = 1. */ -kmVec3* kmVec3Scale(kmVec3* pOut, const kmVec3* pIn, const kmScalar s); /** Scales a vector to length s */ -int kmVec3AreEqual(const kmVec3* p1, const kmVec3* p2); -kmVec3* kmVec3InverseTransform(kmVec3* pOut, const kmVec3* pV, const struct kmMat4* pM); -kmVec3* kmVec3InverseTransformNormal(kmVec3* pOut, const kmVec3* pVect, const struct kmMat4* pM); -kmVec3* kmVec3Assign(kmVec3* pOut, const kmVec3* pIn); -kmVec3* kmVec3Zero(kmVec3* pOut); - -#ifdef __cplusplus -} -#endif -#endif /* VEC3_H_INCLUDED */ diff --git a/Example/libs/kazmath/include/kazmath/vec4.h b/Example/libs/kazmath/include/kazmath/vec4.h deleted file mode 100644 index 7507ea3..0000000 --- a/Example/libs/kazmath/include/kazmath/vec4.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef VEC4_H_INCLUDED -#define VEC4_H_INCLUDED - -#include "utility.h" - -struct kmMat4; - -#pragma pack(push) /* push current alignment to stack */ -#pragma pack(1) /* set alignment to 1 byte boundary */ - -typedef struct kmVec4 { - kmScalar x; - kmScalar y; - kmScalar z; - kmScalar w; -} kmVec4; - -#pragma pack(pop) - -#ifdef __cplusplus -extern "C" { -#endif - -kmVec4* kmVec4Fill(kmVec4* pOut, kmScalar x, kmScalar y, kmScalar z, kmScalar w); -kmVec4* kmVec4Add(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2); -kmScalar kmVec4Dot(const kmVec4* pV1, const kmVec4* pV2); -kmScalar kmVec4Length(const kmVec4* pIn); -kmScalar kmVec4LengthSq(const kmVec4* pIn); -kmVec4* kmVec4Lerp(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2, kmScalar t); -kmVec4* kmVec4Normalize(kmVec4* pOut, const kmVec4* pIn); -kmVec4* kmVec4Scale(kmVec4* pOut, const kmVec4* pIn, const kmScalar s); ///< Scales a vector to length s -kmVec4* kmVec4Subtract(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2); -kmVec4* kmVec4Transform(kmVec4* pOut, const kmVec4* pV, const struct kmMat4* pM); -kmVec4* kmVec4TransformArray(kmVec4* pOut, unsigned int outStride, - const kmVec4* pV, unsigned int vStride, const struct kmMat4* pM, unsigned int count); -int kmVec4AreEqual(const kmVec4* p1, const kmVec4* p2); -kmVec4* kmVec4Assign(kmVec4* pOut, const kmVec4* pIn); - -#ifdef __cplusplus -} -#endif - -#endif // VEC4_H_INCLUDED diff --git a/Example/libs/kazmath/src/CMakeLists.txt b/Example/libs/kazmath/src/CMakeLists.txt deleted file mode 100644 index a389466..0000000 --- a/Example/libs/kazmath/src/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ - -#ADD_LIBRARY(Kazmath STATIC ${KAZMATH_SRCS}) -#INSTALL(TARGETS Kazmath ARCHIVE DESTINATION lib) - -INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/include ) - -ADD_LIBRARY(kazmath STATIC ${KAZMATH_SOURCES}) -INSTALL(TARGETS kazmath ARCHIVE DESTINATION lib) - -#ADD_LIBRARY(KazmathGL STATIC ${GL_UTILS_SRCS}) -#INSTALL(TARGETS KazmathGL ARCHIVE DESTINATION lib) - -INSTALL(FILES ${KAZMATH_HEADERS} DESTINATION include/kazmath) -INSTALL(FILES ${GL_UTILS_HEADERS} DESTINATION include/kazmath/GL) diff --git a/Example/libs/kazmath/src/ChangeLog b/Example/libs/kazmath/src/ChangeLog deleted file mode 100644 index f13b823..0000000 --- a/Example/libs/kazmath/src/ChangeLog +++ /dev/null @@ -1,738 +0,0 @@ ------------------------------------------------------------- -revno: 111 -committer: Kazade -branch nick: kazmath -timestamp: Thu 2010-08-19 12:07:29 +0100 -message: - Fix #620352. Fix a reference to kmMat4RotationAxisAngle ------------------------------------------------------------- -revno: 110 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Wed 2010-04-21 12:55:39 +0200 -message: - applied the change to the header files as well ------------------------------------------------------------- -revno: 109 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Wed 2010-04-21 12:54:06 +0200 -message: - fixed kmMat4RotationAxis ------------------------------------------------------------- -revno: 108 [merge] -committer: Carsten Haubld -branch nick: kazmath -timestamp: Wed 2010-04-21 12:27:53 +0200 -message: - fixed CMake in kazmathxx due to missing utility.h ------------------------------------------------------------- -revno: 107 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Wed 2010-04-21 12:22:40 +0200 -message: - fixed mat4 rotation axis by normalizing the axis first ------------------------------------------------------------- -revno: 106 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2010-01-09 16:56:04 +0000 -message: - Add cmake module ------------------------------------------------------------- -revno: 105 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2010-01-09 16:23:31 +0000 -message: - Remove kazmodel - it really should belong in its own repo ------------------------------------------------------------- -revno: 104 -committer: Luke Benstead -branch nick: kazmath -timestamp: Fri 2010-01-08 23:03:13 +0000 -message: - Reorganize the headers so that the tests can compile in place ------------------------------------------------------------- -revno: 103 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Mon 2009-08-31 11:21:42 +0200 -message: - Operators now inline, constructors fixed ------------------------------------------------------------- -revno: 102 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Sat 2009-08-29 11:42:59 +0200 -message: - fixed some compilation errors - still how do we define operators in headers correctly?? ------------------------------------------------------------- -revno: 101 -committer: Luke Benstead -branch nick: kazmath -timestamp: Wed 2009-08-26 10:37:52 +0100 -message: - Added the header defines ------------------------------------------------------------- -revno: 100 -committer: Luke Benstead -branch nick: kazmath -timestamp: Wed 2009-08-26 09:38:47 +0100 -message: - Added a V2 for kazmathxx ------------------------------------------------------------- -revno: 99 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-08-02 08:08:26 +0100 -message: - Added missing header file to one of the tests ------------------------------------------------------------- -revno: 98 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Sat 2009-08-01 12:05:25 +0200 -message: - No longer doing self assignment in kmMat4Inverse ------------------------------------------------------------- -revno: 97 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Sat 2009-08-01 11:15:36 +0200 -message: - Fixed kmMat4Inverse ------------------------------------------------------------- -revno: 96 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2009-08-01 09:20:33 +0100 -message: - Fixed some whitespace issues in plane.c ------------------------------------------------------------- -revno: 95 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2009-08-01 09:17:01 +0100 -message: - Rename kmAABBPointInBox to kmAABBContainsPoint ------------------------------------------------------------- -revno: 94 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2009-08-01 09:16:28 +0100 -message: - Implement kmAABBPointInBox ------------------------------------------------------------- -revno: 93 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2009-08-01 09:14:00 +0100 -message: - Implement kmAABBAssign ------------------------------------------------------------- -revno: 92 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2009-08-01 09:10:36 +0100 -message: - Fixed some whitespace and added some comments ------------------------------------------------------------- -revno: 91 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2009-08-01 08:56:13 +0100 -message: - Implemented (untested) kmMat4RotationTranslation to construct a 4x4 matrix from a 3x3 + vec3 ------------------------------------------------------------- -revno: 90 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-07-05 07:55:45 +0100 -message: - Added kmMat3RotationX, kmMat3RotationY and kmMat3RotationZ ------------------------------------------------------------- -revno: 89 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Sat 2009-06-27 09:38:20 +0200 -message: - Fixed a crash? ------------------------------------------------------------- -revno: 88 -committer: Luke Benstead -branch nick: kazmath -timestamp: Tue 2009-04-28 09:52:57 +0100 -message: - Added a test for kmMat4Transpose ------------------------------------------------------------- -revno: 87 -committer: Luke Benstead -branch nick: kazmath -timestamp: Tue 2009-04-28 08:49:59 +0100 -message: - Added a commented test for kmMat4Inverse, however kmMat4Adjugate and kmMat4Determinate need implementing ------------------------------------------------------------- -revno: 86 -committer: Luke Benstead -branch nick: kazmath -timestamp: Tue 2009-04-28 08:46:03 +0100 -message: - Fixed bug in kmQuaternionRotationMatrix ------------------------------------------------------------- -revno: 85 -committer: Luke Benstead -branch nick: kazmath -timestamp: Tue 2009-04-28 08:41:27 +0100 -message: - Added missing include to test_mat3.cpp ------------------------------------------------------------- -revno: 84 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Mon 2009-04-27 22:59:08 +0200 -message: - fixed CMakeLists.txt for the tests ------------------------------------------------------------- -revno: 83 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 21:34:20 +0100 -message: - Added a test for kmMat3Translation ------------------------------------------------------------- -revno: 82 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 21:32:19 +0100 -message: - Fixed bugs in kmMat3Scaling and kmMat3Translation, added test for kmMat3Scaling ------------------------------------------------------------- -revno: 81 [merge] -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 19:04:56 +0100 -message: - Merge from upstream. Fixed mismatching prototype in quaternion.c ------------------------------------------------------------- -revno: 80 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 19:01:35 +0100 -message: - Added a test for kmMat3AreEqual. Fixed a bug in kmMat3AreEqual ------------------------------------------------------------- -revno: 79 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 18:57:28 +0100 -message: - Added a test for kmMat3IsIdentity ------------------------------------------------------------- -revno: 78 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 18:54:48 +0100 -message: - Added a test for kmMat3Identity ------------------------------------------------------------- -revno: 77 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 18:52:14 +0100 -message: - Added a test for kmMat3Fill ------------------------------------------------------------- -revno: 76 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 18:46:30 +0100 -message: - Added some mat3 unit tests. Fixed a bug in kmMat3AreEqual ------------------------------------------------------------- -revno: 75 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 11:08:43 +0100 -message: - Added mat4 test stub ------------------------------------------------------------- -revno: 74 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 11:06:12 +0100 -message: - Enabled unit testing in cmake ------------------------------------------------------------- -revno: 73 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 10:44:37 +0100 -message: - Added cmakelists.txt to the tests subfolder ------------------------------------------------------------- -revno: 72 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 10:37:34 +0100 -message: - Added stub mat3 test file ------------------------------------------------------------- -revno: 71 -committer: Luke Benstead -branch nick: kazmath -timestamp: Mon 2009-04-27 10:35:48 +0100 -message: - Added tests folder for new boost::unit based tests ------------------------------------------------------------- -revno: 70 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Sun 2009-04-26 14:25:48 +0200 -message: - Fixed the new quaternion -> Matrix -> AngleAxis methods and added them to mat4 ------------------------------------------------------------- -revno: 69 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-04-26 12:40:08 +0100 -message: - Added kazmodel to the kazlibs repo ------------------------------------------------------------- -revno: 68 [merge] -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-04-26 12:34:27 +0100 -message: - Merge from upstream ------------------------------------------------------------- -revno: 67 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-04-26 12:33:43 +0100 -message: - Reorganized bzr ------------------------------------------------------------- -revno: 66 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-04-26 10:00:18 +0100 -message: - Renamed kmMat3RotationAxis to kmMat3RotationAxisAngle to be more accurate ------------------------------------------------------------- -revno: 65 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-04-26 09:57:19 +0100 -message: - Fixed some compilation errors ------------------------------------------------------------- -revno: 64 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-04-26 09:54:12 +0100 -message: - Added untested implementation of kmMat3RotationToAxisAngle ------------------------------------------------------------- -revno: 63 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-04-26 09:49:17 +0100 -message: - Added stub for kmMat3RotationToAxisAngle() ------------------------------------------------------------- -revno: 62 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-04-26 09:45:58 +0100 -message: - Corrected a typo ------------------------------------------------------------- -revno: 61 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sun 2009-04-26 09:44:39 +0100 -message: - Fixed broken Quaternion functions - Added (untested) kmMat3RotationAxis() ------------------------------------------------------------- -revno: 60 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2009-04-18 08:55:29 +0100 -message: - Fixed some errors in the quaternion header. - Changed kmQuaternionRotationMatrix to accept a kmMat3 instead of kmMat4 ------------------------------------------------------------- -revno: 59 -committer: Luke Benstead -branch nick: kazmath -timestamp: Sat 2009-04-18 08:42:38 +0100 -message: - Added kmMat3RotationQuaternion ------------------------------------------------------------- -revno: 58 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Sun 2009-04-05 11:58:29 +0200 -message: - Added mat3 ------------------------------------------------------------- -revno: 57 [merge] -committer: Carsten Haubld -branch nick: kazmath -timestamp: Sun 2009-04-05 11:54:15 +0200 -message: - Implemented mat4 and vec4 for kazmathxx ------------------------------------------------------------- -revno: 56 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Sun 2009-04-05 11:53:07 +0200 -message: - Implemented mat4 and vec4 for kazmathxx ------------------------------------------------------------- -revno: 55 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Fri 2009-03-13 16:46:26 +0100 -message: - added km::vec3 to kazmathxx ------------------------------------------------------------- -revno: 54 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Fri 2009-03-13 16:14:51 +0100 -message: - Fixed: kmVec2 is no longer transformed by kmMat4\nAdded km::vec2 ------------------------------------------------------------- -revno: 53 -committer: Carsten Haubld -branch nick: kazmath -timestamp: Fri 2009-03-13 15:38:53 +0100 -message: - Added folder for kazmathxx ------------------------------------------------------------- -revno: 52 [merge] -committer: Luke Benstead -branch nick: trunk -timestamp: Fri 2009-03-13 14:04:32 +0000 -message: - Merge from upstream ------------------------------------------------------------- -revno: 51 -committer: Luke Benstead -branch nick: trunk -timestamp: Fri 2009-03-13 14:00:14 +0000 -message: - Fixed for C89 ------------------------------------------------------------- -revno: 50 -committer: Carsten Haubold -timestamp: Tue 2008-12-30 12:45:23 +0100 -message: - fixed kmGLTranslate ------------------------------------------------------------- -revno: 49 -committer: Carsten Haubold -timestamp: Tue 2008-12-30 12:15:27 +0100 -message: - fixed some stack memory leaks ------------------------------------------------------------- -revno: 48 -committer: Carsten Haubold -timestamp: Tue 2008-12-30 11:01:35 +0100 -message: - The GL matrix stacks now work as expected - matrix multiplication was the wrong way round ------------------------------------------------------------- -revno: 47 -committer: Carsten Haubold -timestamp: Tue 2008-12-30 10:52:28 +0100 -message: - Debug output ------------------------------------------------------------- -revno: 46 -committer: Carsten Haubold -timestamp: Mon 2008-12-29 18:32:13 +0100 -message: - Fixed some compiler errors ------------------------------------------------------------- -revno: 45 -committer: Luke -timestamp: Wed 2008-11-19 08:36:47 +0000 -message: - Added kmGLTranslatef, kmGLScalef and kmGLRotatef ------------------------------------------------------------- -revno: 44 -committer: Luke -timestamp: Tue 2008-11-04 20:57:30 +0000 -message: - Fixed up kazmathxx ------------------------------------------------------------- -revno: 43 -committer: Luke -timestamp: Wed 2008-10-29 09:24:32 +0000 -message: - Started implementing C++ operators in kazmathxx.h ------------------------------------------------------------- -revno: 42 -committer: Luke -timestamp: Tue 2008-10-28 18:21:16 +0000 -message: - Added kazmathxx.h for C++ usage ------------------------------------------------------------- -revno: 41 -committer: Luke -timestamp: Tue 2008-10-28 11:00:41 +0000 -message: - Added Doxygen documentation ------------------------------------------------------------- -revno: 40 -committer: Luke -timestamp: Tue 2008-10-28 08:46:19 +0000 -message: - Began documenting the kmPlane functions. - Changed some assert(0)s to include a not implemented message ------------------------------------------------------------- -revno: 39 -committer: Luke -timestamp: Tue 2008-10-28 08:42:24 +0000 -message: - - Wrote stubs for the AABB functions which raise assertions if used. - - Documented the AABB functions - - Changed the definition of kmAABBPointInBox so that it actually makes sense ------------------------------------------------------------- -revno: 38 -committer: Luke -timestamp: Tue 2008-10-28 08:38:48 +0000 -message: - - Documented utility.c ------------------------------------------------------------- -revno: 37 -committer: Luke -timestamp: Tue 2008-10-28 08:36:30 +0000 -message: - - Documented vec3.c in detail. - - Fixed up a not-implemented assertion. - - Changed existing doc strings to C style - /** */ ------------------------------------------------------------- -revno: 36 -committer: Luke -timestamp: Tue 2008-10-28 08:30:00 +0000 -message: - Removed uneccessary files from git ------------------------------------------------------------- -revno: 35 -committer: Luke -timestamp: Tue 2008-10-28 08:28:49 +0000 -message: - - Documented all the functions in mat4.c - - Fixed up all asserts in mat4.c to include a message - - Tidied up the code. Mat4.c is now done. ------------------------------------------------------------- -revno: 34 -committer: Luke -timestamp: Mon 2008-10-27 21:52:33 +0000 -message: - Added potential 0.1 release binary ------------------------------------------------------------- -revno: 33 -committer: Luke Benstead -timestamp: Mon 2008-10-27 21:46:55 +0000 -message: - Changed the README to include the BSD license ------------------------------------------------------------- -revno: 32 -committer: Luke Benstead -timestamp: Mon 2008-10-27 21:45:51 +0000 -message: - Added the modified BSD license to all source files ------------------------------------------------------------- -revno: 31 -committer: Luke Benstead -timestamp: Mon 2008-10-27 21:11:51 +0000 -message: - Fixed the installation of header files in CMake ------------------------------------------------------------- -revno: 30 -committer: Luke -timestamp: Mon 2008-10-27 21:05:51 +0000 -message: - Added kazmath project files ------------------------------------------------------------- -revno: 29 [merge] -committer: Luke -timestamp: Mon 2008-10-27 21:03:22 +0000 -message: - Merge branch 'master' of git@github.com:Kazade/kazmath ------------------------------------------------------------- -revno: 28 -committer: Luke -timestamp: Mon 2008-10-27 21:02:04 +0000 -message: - Finally got kazmath compiling on VC++, man that compiler sucks! Have MS not heard of C99? ------------------------------------------------------------- -revno: 27 -committer: Luke Benstead -timestamp: Sun 2008-10-26 21:35:24 +0000 -message: - Changed the readme slightly, we need to change the license everywhere ------------------------------------------------------------- -revno: 26 -committer: Luke Benstead -timestamp: Sun 2008-10-26 21:21:47 +0000 -message: - Implemented the stacks test, fixed the undefined references I was getting ------------------------------------------------------------- -revno: 25 -committer: Luke Benstead -timestamp: Sun 2008-10-26 20:59:34 +0000 -message: - Removed the old matrix stack stuff ------------------------------------------------------------- -revno: 24 -committer: Luke Benstead -timestamp: Sun 2008-10-26 20:11:58 +0000 -message: - Started implementing the matrix stack tests ------------------------------------------------------------- -revno: 23 -committer: Luke Benstead -timestamp: Sun 2008-10-26 10:56:51 +0000 -message: - Started new implementation of the GL matrix stack ------------------------------------------------------------- -revno: 22 -committer: Carsten Haubold -timestamp: Thu 2008-08-28 12:37:41 +0200 -message: - Added kmGLRotation ------------------------------------------------------------- -revno: 21 -committer: Luke Benstead -timestamp: Thu 2008-08-28 09:24:00 +0100 -message: - We now have a working matrix stack ------------------------------------------------------------- -revno: 20 -committer: Luke Benstead -timestamp: Wed 2008-08-27 13:34:49 +0100 -message: - Fixed the stack memory constants ------------------------------------------------------------- -revno: 19 -committer: Luke Benstead -timestamp: Wed 2008-08-27 13:33:12 +0100 -message: - Added the initial gl_utils implementation for replacing the matrix functionality deprecated in OpenGL 3.0 ------------------------------------------------------------- -revno: 18 -committer: Carsten Haubold -timestamp: Mon 2008-08-25 12:46:16 +0200 -message: - Fixed a bug in kmMat4LookAt ------------------------------------------------------------- -revno: 17 [merge] -committer: Carsten Haubold -timestamp: Sun 2008-08-24 22:07:49 +0200 -message: - Merge branch 'master' of git@github.com:Kazade/kazmath ------------------------------------------------------------- -revno: 16 -committer: Carsten Haubold -timestamp: Sun 2008-08-24 22:06:45 +0200 -message: - Added kmMat4LookAt ------------------------------------------------------------- -revno: 15 -committer: Carsten Haubold -timestamp: Wed 2008-08-20 11:18:10 +0200 -message: - Added Fill methods for all Vec and Mat structs ------------------------------------------------------------- -revno: 14 -committer: Carsten Haubold -timestamp: Tue 2008-08-19 22:31:55 +0200 -message: - Added UnitTests, changed bool to int and fixed some minor bugs ------------------------------------------------------------- -revno: 13 -committer: Carsten Haubold -timestamp: Sun 2008-08-17 23:19:21 +0200 -message: - removed .svn entries which did not belong here ------------------------------------------------------------- -revno: 12 -committer: Carsten Haubold -timestamp: Sun 2008-08-17 23:17:07 +0200 -message: - some tweaks on matrices and first test-app, PerspectiveProjection is correct ! ------------------------------------------------------------- -revno: 11 -committer: Carsten Haubold -timestamp: Sun 2008-08-17 16:04:09 +0200 -message: - Renamed cotangent to cotangens ------------------------------------------------------------- -revno: 10 -committer: Luke Benstead -timestamp: Sat 2008-08-16 21:51:22 +0100 -message: - Added kmMat4PerspectiveProjection and kmMat4OrthographicProjection ------------------------------------------------------------- -revno: 9 -committer: Luke Benstead -timestamp: Thu 2008-08-14 21:15:45 +0100 -message: - Added the aabb struct ------------------------------------------------------------- -revno: 8 -committer: Luke Benstead -timestamp: Thu 2008-08-14 17:57:43 +0100 -message: - Added the kmAABB structure ------------------------------------------------------------- -revno: 7 -committer: Luke Benstead -timestamp: Thu 2008-08-14 14:32:24 +0100 -message: - Fixed broken kmMat3Transpose ------------------------------------------------------------- -revno: 6 -committer: Luke Benstead -timestamp: Thu 2008-08-14 14:21:04 +0100 -message: - Fixed broken kmMat4Translation, w component was not set ------------------------------------------------------------- -revno: 5 -committer: Luke Benstead -timestamp: Thu 2008-08-14 14:01:47 +0100 -message: - Added mat3.c and mat3.h to the cmake file ------------------------------------------------------------- -revno: 4 -committer: Luke Benstead -timestamp: Thu 2008-08-14 13:56:26 +0100 -message: - Added the authors section to the readme ------------------------------------------------------------- -revno: 3 -committer: Luke Benstead -timestamp: Thu 2008-08-14 13:55:41 +0100 -message: - Updated the readme file ------------------------------------------------------------- -revno: 2 -committer: Luke Benstead -timestamp: Thu 2008-08-14 13:53:26 +0100 -message: - Added kazmath to git ------------------------------------------------------------- -revno: 1 -committer: Luke Benstead -timestamp: Thu 2008-08-14 13:47:51 +0100 -message: - First commit ------------------------------------------------------------- -Use --include-merges or -n0 to see merged revisions. diff --git a/Example/libs/kazmath/src/GL/mat4stack.c b/Example/libs/kazmath/src/GL/mat4stack.c deleted file mode 100644 index f2ffe57..0000000 --- a/Example/libs/kazmath/src/GL/mat4stack.c +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include -#include -#include -#include - -#define INITIAL_SIZE 30 -#define INCREMENT 50 - -#include "kazmath/GL/mat4stack.h" - -void km_mat4_stack_initialize(km_mat4_stack* stack) { - stack->stack = (kmMat4*) malloc(sizeof(kmMat4) * INITIAL_SIZE); //allocate the memory - stack->capacity = INITIAL_SIZE; //Set the capacity to 10 - stack->top = NULL; //Set the top to NULL - stack->item_count = 0; -}; - -void km_mat4_stack_push(km_mat4_stack* stack, const kmMat4* item) -{ - stack->top = &stack->stack[stack->item_count]; - kmMat4Assign(stack->top, item); - stack->item_count++; - - if(stack->item_count >= stack->capacity) - { - kmMat4* temp = NULL; - stack->capacity += INCREMENT; - temp = stack->stack; - stack->stack = (kmMat4*) malloc(stack->capacity*sizeof(kmMat4)); - memcpy(stack->stack, temp, sizeof(kmMat4)*(stack->capacity - INCREMENT)); - free(temp); - stack->top = &stack->stack[stack->item_count - 1]; - } -} - -void km_mat4_stack_pop(km_mat4_stack* stack, kmMat4* pOut) -{ - assert(stack->item_count && "Cannot pop an empty stack"); - - stack->item_count--; - stack->top = &stack->stack[stack->item_count - 1]; -} - -void km_mat4_stack_release(km_mat4_stack* stack) { - free(stack->stack); - stack->top = NULL; - stack->item_count = 0; - stack->capacity = 0; -} diff --git a/Example/libs/kazmath/src/GL/matrix.c b/Example/libs/kazmath/src/GL/matrix.c deleted file mode 100644 index f63cf14..0000000 --- a/Example/libs/kazmath/src/GL/matrix.c +++ /dev/null @@ -1,191 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include -#include - -#include "kazmath/GL/matrix.h" -#include "kazmath/GL/mat4stack.h" - -km_mat4_stack modelview_matrix_stack; -km_mat4_stack projection_matrix_stack; -km_mat4_stack texture_matrix_stack; - -km_mat4_stack* current_stack = NULL; - -static unsigned char initialized = 0; - -void lazyInitialize() -{ - - if (!initialized) { - kmMat4 identity; //Temporary identity matrix - - //Initialize all 3 stacks - //modelview_matrix_stack = (km_mat4_stack*) malloc(sizeof(km_mat4_stack)); - km_mat4_stack_initialize(&modelview_matrix_stack); - - //projection_matrix_stack = (km_mat4_stack*) malloc(sizeof(km_mat4_stack)); - km_mat4_stack_initialize(&projection_matrix_stack); - - //texture_matrix_stack = (km_mat4_stack*) malloc(sizeof(km_mat4_stack)); - km_mat4_stack_initialize(&texture_matrix_stack); - - current_stack = &modelview_matrix_stack; - initialized = 1; - - kmMat4Identity(&identity); - - //Make sure that each stack has the identity matrix - km_mat4_stack_push(&modelview_matrix_stack, &identity); - km_mat4_stack_push(&projection_matrix_stack, &identity); - km_mat4_stack_push(&texture_matrix_stack, &identity); - } -} - -void kmGLMatrixMode(kmGLEnum mode) -{ - lazyInitialize(); - - switch(mode) - { - case KM_GL_MODELVIEW: - current_stack = &modelview_matrix_stack; - break; - case KM_GL_PROJECTION: - current_stack = &projection_matrix_stack; - break; - case KM_GL_TEXTURE: - current_stack = &texture_matrix_stack; - break; - default: - assert(0 && "Invalid matrix mode specified"); //TODO: Proper error handling - break; - } -} - -void kmGLPushMatrix(void) -{ - kmMat4 top; - - lazyInitialize(); //Initialize the stacks if they haven't been already - - //Duplicate the top of the stack (i.e the current matrix) - kmMat4Assign(&top, current_stack->top); - km_mat4_stack_push(current_stack, &top); -} - -void kmGLPopMatrix(void) -{ - assert(initialized && "Cannot Pop empty matrix stack"); - //No need to lazy initialize, you shouldnt be popping first anyway! - km_mat4_stack_pop(current_stack, NULL); -} - -void kmGLLoadIdentity() -{ - lazyInitialize(); - - kmMat4Identity(current_stack->top); //Replace the top matrix with the identity matrix -} - -void kmGLFreeAll() -{ - //Clear the matrix stacks - km_mat4_stack_release(&modelview_matrix_stack); - km_mat4_stack_release(&projection_matrix_stack); - km_mat4_stack_release(&texture_matrix_stack); - - //Delete the matrices - initialized = 0; //Set to uninitialized - - current_stack = NULL; //Set the current stack to point nowhere -} - -void kmGLMultMatrix(const kmMat4* pIn) -{ - lazyInitialize(); - kmMat4Multiply(current_stack->top, current_stack->top, pIn); -} - -void kmGLLoadMatrix(const kmMat4* pIn) -{ - lazyInitialize(); - kmMat4Assign(current_stack->top, pIn); -} - -void kmGLGetMatrix(kmGLEnum mode, kmMat4* pOut) -{ - lazyInitialize(); - - switch(mode) - { - case KM_GL_MODELVIEW: - kmMat4Assign(pOut, modelview_matrix_stack.top); - break; - case KM_GL_PROJECTION: - kmMat4Assign(pOut, projection_matrix_stack.top); - break; - case KM_GL_TEXTURE: - kmMat4Assign(pOut, texture_matrix_stack.top); - break; - default: - assert(1 && "Invalid matrix mode specified"); //TODO: Proper error handling - break; - } -} - -void kmGLTranslatef(float x, float y, float z) -{ - kmMat4 translation; - - //Create a rotation matrix using the axis and the angle - kmMat4Translation(&translation,x,y,z); - - //Multiply the rotation matrix by the current matrix - kmMat4Multiply(current_stack->top, current_stack->top, &translation); -} - -void kmGLRotatef(float angle, float x, float y, float z) -{ - kmVec3 axis; - kmMat4 rotation; - - //Create an axis vector - kmVec3Fill(&axis, x, y, z); - - //Create a rotation matrix using the axis and the angle - kmMat4RotationAxisAngle(&rotation, &axis, kmDegreesToRadians(angle)); - - //Multiply the rotation matrix by the current matrix - kmMat4Multiply(current_stack->top, current_stack->top, &rotation); -} - -void kmGLScalef(float x, float y, float z) -{ - kmMat4 scaling; - kmMat4Scaling(&scaling, x, y, z); - kmMat4Multiply(current_stack->top, current_stack->top, &scaling); -} diff --git a/Example/libs/kazmath/src/aabb.c b/Example/libs/kazmath/src/aabb.c deleted file mode 100644 index ea334a3..0000000 --- a/Example/libs/kazmath/src/aabb.c +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include "kazmath/aabb.h" - -/** - * Returns KM_TRUE if point is in the specified AABB, returns - * KM_FALSE otherwise. - */ -const int kmAABBContainsPoint(const kmVec3* pPoint, const kmAABB* pBox) -{ - if(pPoint->x >= pBox->min.x && pPoint->x <= pBox->max.x && - pPoint->y >= pBox->min.y && pPoint->y <= pBox->max.y && - pPoint->z >= pBox->min.z && pPoint->z <= pBox->max.z) { - return KM_TRUE; - } - - return KM_FALSE; -} - -/** - * Assigns pIn to pOut, returns pOut. - */ -kmAABB* const kmAABBAssign(kmAABB* pOut, const kmAABB* pIn) -{ - kmVec3Assign(&pOut->min, &pIn->min); - kmVec3Assign(&pOut->max, &pIn->max); - return pOut; -} - -/** - * Scales pIn by s, stores the resulting AABB in pOut. Returns pOut - */ -kmAABB* const kmAABBScale(kmAABB* pOut, const kmAABB* pIn, kmScalar s) -{ - assert(0 && "Not implemented"); - return 0; -} - - - diff --git a/Example/libs/kazmath/src/mat3.c b/Example/libs/kazmath/src/mat3.c deleted file mode 100644 index 6847caa..0000000 --- a/Example/libs/kazmath/src/mat3.c +++ /dev/null @@ -1,372 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include -#include -#include - -#include "kazmath/utility.h" -#include "kazmath/vec3.h" -#include "kazmath/mat3.h" -#include "kazmath/quaternion.h" - -kmMat3* const kmMat3Fill(kmMat3* pOut, const kmScalar* pMat) -{ - memcpy(pOut->mat, pMat, sizeof(kmScalar) * 9); - return pOut; -} - -/** Sets pOut to an identity matrix returns pOut*/ -kmMat3* const kmMat3Identity(kmMat3* pOut) -{ - memset(pOut->mat, 0, sizeof(float) * 9); - pOut->mat[0] = pOut->mat[4] = pOut->mat[8] = 1.0f; - return pOut; -} - -const kmScalar kmMat3Determinant(const kmMat3* pIn) -{ - kmScalar output; - /* - calculating the determinant following the rule of sarus, - | 0 3 6 | 0 3 | - m = | 1 4 7 | 1 4 | - | 2 5 8 | 2 5 | - now sum up the products of the diagonals going to the right (i.e. 0,4,8) - and substract the products of the other diagonals (i.e. 2,4,6) - */ - - output = pIn->mat[0] * pIn->mat[4] * pIn->mat[8] + pIn->mat[1] * pIn->mat[5] * pIn->mat[6] + pIn->mat[2] * pIn->mat[3] * pIn->mat[7]; - output -= pIn->mat[2] * pIn->mat[4] * pIn->mat[6] + pIn->mat[0] * pIn->mat[5] * pIn->mat[7] + pIn->mat[1] * pIn->mat[3] * pIn->mat[8]; - - return output; -} - - -kmMat3* const kmMat3Adjugate(kmMat3* pOut, const kmMat3* pIn) -{ - pOut->mat[0] = pIn->mat[4] * pIn->mat[8] - pIn->mat[5] * pIn->mat[7]; - pOut->mat[1] = pIn->mat[2] * pIn->mat[7] - pIn->mat[1] * pIn->mat[8]; - pOut->mat[2] = pIn->mat[1] * pIn->mat[5] - pIn->mat[2] * pIn->mat[4]; - pOut->mat[3] = pIn->mat[5] * pIn->mat[6] - pIn->mat[3] * pIn->mat[8]; - pOut->mat[4] = pIn->mat[0] * pIn->mat[8] - pIn->mat[2] * pIn->mat[6]; - pOut->mat[5] = pIn->mat[2] * pIn->mat[3] - pIn->mat[0] * pIn->mat[5]; - pOut->mat[6] = pIn->mat[3] * pIn->mat[7] - pIn->mat[4] * pIn->mat[6]; - - // XXX: pIn->mat[9] is invalid! -// pOut->mat[7] = pIn->mat[1] * pIn->mat[6] - pIn->mat[9] * pIn->mat[7]; - pOut->mat[8] = pIn->mat[0] * pIn->mat[4] - pIn->mat[1] * pIn->mat[3]; - - return pOut; -} - -kmMat3* const kmMat3Inverse(kmMat3* pOut, const kmScalar pDeterminate, const kmMat3* pM) -{ - kmScalar detInv; - kmMat3 adjugate; - - if(pDeterminate == 0.0) - { - return NULL; - } - - detInv = 1.0 / pDeterminate; - - kmMat3Adjugate(&adjugate, pM); - kmMat3ScalarMultiply(pOut, &adjugate, detInv); - - return pOut; -} - -/** Returns true if pIn is an identity matrix */ -const int kmMat3IsIdentity(const kmMat3* pIn) -{ - static const float identity [] = { 1.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 1.0f}; - - return (memcmp(identity, pIn->mat, sizeof(float) * 9) == 0); -} - -/** Sets pOut to the transpose of pIn, returns pOut */ -kmMat3* const kmMat3Transpose(kmMat3* pOut, const kmMat3* pIn) -{ - int z, x; - for (z = 0; z < 3; ++z) { - for (x = 0; x < 3; ++x) { - pOut->mat[(z * 3) + x] = pIn->mat[(x * 3) + z]; - } - } - - return pOut; -} - -/* Multiplies pM1 with pM2, stores the result in pOut, returns pOut */ -kmMat3* const kmMat3Multiply(kmMat3* pOut, const kmMat3* pM1, const kmMat3* pM2) -{ - float mat[9]; - - const float *m1 = pM1->mat, *m2 = pM2->mat; - - mat[0] = m1[0] * m2[0] + m1[3] * m2[1] + m1[6] * m2[2]; - mat[1] = m1[1] * m2[0] + m1[4] * m2[1] + m1[7] * m2[2]; - mat[2] = m1[2] * m2[0] + m1[5] * m2[1] + m1[8] * m2[2]; - - mat[3] = m1[0] * m2[3] + m1[3] * m2[4] + m1[6] * m2[5]; - mat[4] = m1[1] * m2[3] + m1[4] * m2[4] + m1[7] * m2[5]; - mat[5] = m1[2] * m2[3] + m1[5] * m2[4] + m1[8] * m2[5]; - - mat[6] = m1[0] * m2[6] + m1[3] * m2[7] + m1[6] * m2[8]; - mat[7] = m1[1] * m2[6] + m1[4] * m2[7] + m1[7] * m2[8]; - mat[8] = m1[2] * m2[6] + m1[5] * m2[7] + m1[8] * m2[8]; - - memcpy(pOut->mat, mat, sizeof(float)*9); - - return pOut; -} - -kmMat3* const kmMat3ScalarMultiply(kmMat3* pOut, const kmMat3* pM, const kmScalar pFactor) -{ - float mat[9]; - int i; - - for(i = 0; i < 9; i++) - { - mat[i] = pM->mat[i] * pFactor; - } - - memcpy(pOut->mat, mat, sizeof(float)*9); - - return pOut; -} - -/** Assigns the value of pIn to pOut */ -kmMat3* const kmMat3Assign(kmMat3* pOut, const kmMat3* pIn) -{ - assert(pOut != pIn); //You have tried to self-assign!! - - memcpy(pOut->mat, pIn->mat, sizeof(float)*9); - - return pOut; -} - -/** Returns true if the 2 matrices are equal (approximately) */ -const int kmMat3AreEqual(const kmMat3* pMat1, const kmMat3* pMat2) -{ - int i; - if (pMat1 == pMat2) { - return KM_TRUE; - } - - for (i = 0; i < 9; ++i) { - if (!(pMat1->mat[i] + kmEpsilon > pMat2->mat[i] && - pMat1->mat[i] - kmEpsilon < pMat2->mat[i])) { - return KM_FALSE; - } - } - - return KM_TRUE; -} - -/* Rotation around the z axis so everything stays planar in XY */ -kmMat3* const kmMat3Rotation(kmMat3* pOut, const float radians) -{ - /* - | cos(A) -sin(A) 0 | - M = | sin(A) cos(A) 0 | - | 0 0 1 | - */ - - pOut->mat[0] = cosf(radians); - pOut->mat[1] = sinf(radians); - pOut->mat[2] = 0.0f; - - pOut->mat[3] = -sinf(radians);; - pOut->mat[4] = cosf(radians); - pOut->mat[5] = 0.0f; - - pOut->mat[6] = 0.0f; - pOut->mat[7] = 0.0f; - pOut->mat[8] = 1.0f; - - return pOut; -} - -/** Builds a scaling matrix */ -kmMat3* const kmMat3Scaling(kmMat3* pOut, const kmScalar x, const kmScalar y) -{ -// memset(pOut->mat, 0, sizeof(float) * 9); - kmMat3Identity(pOut); - pOut->mat[0] = x; - pOut->mat[4] = y; - - return pOut; -} - -kmMat3* const kmMat3Translation(kmMat3* pOut, const kmScalar x, const kmScalar y) -{ -// memset(pOut->mat, 0, sizeof(float) * 9); - kmMat3Identity(pOut); - pOut->mat[6] = x; - pOut->mat[7] = y; -// pOut->mat[8] = 1.0; - - return pOut; -} - - -kmMat3* const kmMat3RotationQuaternion(kmMat3* pOut, const kmQuaternion* pIn) -{ - if (!pIn || !pOut) { - return NULL; - } - - // First row - pOut->mat[0] = 1.0f - 2.0f * (pIn->y * pIn->y + pIn->z * pIn->z); - pOut->mat[1] = 2.0f * (pIn->x * pIn->y - pIn->w * pIn->z); - pOut->mat[2] = 2.0f * (pIn->x * pIn->z + pIn->w * pIn->y); - - // Second row - pOut->mat[3] = 2.0f * (pIn->x * pIn->y + pIn->w * pIn->z); - pOut->mat[4] = 1.0f - 2.0f * (pIn->x * pIn->x + pIn->z * pIn->z); - pOut->mat[5] = 2.0f * (pIn->y * pIn->z - pIn->w * pIn->x); - - // Third row - pOut->mat[6] = 2.0f * (pIn->x * pIn->z - pIn->w * pIn->y); - pOut->mat[7] = 2.0f * (pIn->y * pIn->z + pIn->w * pIn->x); - pOut->mat[8] = 1.0f - 2.0f * (pIn->x * pIn->x + pIn->y * pIn->y); - - return pOut; -} - -kmMat3* const kmMat3RotationAxisAngle(kmMat3* pOut, const struct kmVec3* axis, kmScalar radians) -{ - float rcos = cosf(radians); - float rsin = sinf(radians); - - pOut->mat[0] = rcos + axis->x * axis->x * (1 - rcos); - pOut->mat[1] = axis->z * rsin + axis->y * axis->x * (1 - rcos); - pOut->mat[2] = -axis->y * rsin + axis->z * axis->x * (1 - rcos); - - pOut->mat[3] = -axis->z * rsin + axis->x * axis->y * (1 - rcos); - pOut->mat[4] = rcos + axis->y * axis->y * (1 - rcos); - pOut->mat[5] = axis->x * rsin + axis->z * axis->y * (1 - rcos); - - pOut->mat[6] = axis->y * rsin + axis->x * axis->z * (1 - rcos); - pOut->mat[7] = -axis->x * rsin + axis->y * axis->z * (1 - rcos); - pOut->mat[8] = rcos + axis->z * axis->z * (1 - rcos); - - return pOut; -} - -kmVec3* const kmMat3RotationToAxisAngle(kmVec3* pAxis, kmScalar* radians, const kmMat3* pIn) -{ - /*Surely not this easy?*/ - kmQuaternion temp; - kmQuaternionRotationMatrix(&temp, pIn); - kmQuaternionToAxisAngle(&temp, pAxis, radians); - return pAxis; -} - -/** - * Builds an X-axis rotation matrix and stores it in pOut, returns pOut - */ -kmMat3* const kmMat3RotationX(kmMat3* pOut, const float radians) -{ - /* - | 1 0 0 | - M = | 0 cos(A) -sin(A) | - | 0 sin(A) cos(A) | - - */ - - pOut->mat[0] = 1.0f; - pOut->mat[1] = 0.0f; - pOut->mat[2] = 0.0f; - - pOut->mat[3] = 0.0f; - pOut->mat[4] = cosf(radians); - pOut->mat[5] = sinf(radians); - - pOut->mat[6] = 0.0f; - pOut->mat[7] = -sinf(radians); - pOut->mat[8] = cosf(radians); - - return pOut; -} - -/** - * Builds a rotation matrix using the rotation around the Y-axis - * The result is stored in pOut, pOut is returned. - */ -kmMat3* const kmMat3RotationY(kmMat3* pOut, const float radians) -{ - /* - | cos(A) 0 sin(A) | - M = | 0 1 0 | - | -sin(A) 0 cos(A) | - */ - - pOut->mat[0] = cosf(radians); - pOut->mat[1] = 0.0f; - pOut->mat[2] = -sinf(radians); - - pOut->mat[3] = 0.0f; - pOut->mat[4] = 1.0f; - pOut->mat[5] = 0.0f; - - pOut->mat[6] = sinf(radians); - pOut->mat[7] = 0.0f; - pOut->mat[8] = cosf(radians); - - return pOut; -} - -/** - * Builds a rotation matrix around the Z-axis. The resulting - * matrix is stored in pOut. pOut is returned. - */ -kmMat3* const kmMat3RotationZ(kmMat3* pOut, const float radians) -{ - /* - | cos(A) -sin(A) 0 | - M = | sin(A) cos(A) 0 | - | 0 0 1 | - */ - - pOut->mat[0] = cosf(radians); - pOut->mat[1] =-sinf(radians); - pOut->mat[2] = 0.0f; - - pOut->mat[3] = sinf(radians);; - pOut->mat[4] = cosf(radians); - pOut->mat[5] = 0.0f; - - pOut->mat[6] = 0.0f; - pOut->mat[7] = 0.0f; - pOut->mat[8] = 1.0f; - - return pOut; -} diff --git a/Example/libs/kazmath/src/mat4.c b/Example/libs/kazmath/src/mat4.c deleted file mode 100644 index c55f5fd..0000000 --- a/Example/libs/kazmath/src/mat4.c +++ /dev/null @@ -1,789 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * @file mat4.c - */ -#include -#include -#include - -#include "kazmath/utility.h" -#include "kazmath/vec3.h" -#include "kazmath/mat4.h" -#include "kazmath/mat3.h" -#include "kazmath/quaternion.h" -#include "kazmath/plane.h" - -#include "kazmath/neon_matrix_impl.h" - -/** - * Fills a kmMat4 structure with the values from a 16 - * element array of floats - * @Params pOut - A pointer to the destination matrix - * pMat - A 16 element array of floats - * @Return Returns pOut so that the call can be nested - */ -kmMat4* const kmMat4Fill(kmMat4* pOut, const kmScalar* pMat) -{ - memcpy(pOut->mat, pMat, sizeof(kmScalar) * 16); - return pOut; -} - -/** - * Sets pOut to an identity matrix returns pOut - * @Params pOut - A pointer to the matrix to set to identity - * @Return Returns pOut so that the call can be nested - */ -kmMat4* const kmMat4Identity(kmMat4* pOut) -{ - memset(pOut->mat, 0, sizeof(float) * 16); - pOut->mat[0] = pOut->mat[5] = pOut->mat[10] = pOut->mat[15] = 1.0f; - return pOut; -} - - -float get(const kmMat4 * pIn, int row, int col) -{ - return pIn->mat[row + 4*col]; -} - -void set(kmMat4 * pIn, int row, int col, float value) -{ - pIn->mat[row + 4*col] = value; -} - -void swap(kmMat4 * pIn, int r1, int c1, int r2, int c2) -{ - float tmp = get(pIn,r1,c1); - set(pIn,r1,c1,get(pIn,r2,c2)); - set(pIn,r2,c2, tmp); -} - -//Returns an upper and a lower triangular matrix which are L and R in the Gauss algorithm -int gaussj(kmMat4 *a, kmMat4 *b) -{ - int i, icol = 0, irow = 0, j, k, l, ll, n = 4, m = 4; - float big, dum, pivinv; - int indxc[n]; - int indxr[n]; - int ipiv[n]; - - for (j = 0; j < n; j++) { - ipiv[j] = 0; - } - - for (i = 0; i < n; i++) { - big = 0.0f; - for (j = 0; j < n; j++) { - if (ipiv[j] != 1) { - for (k = 0; k < n; k++) { - if (ipiv[k] == 0) { - if (abs(get(a,j, k)) >= big) { - big = abs(get(a,j, k)); - irow = j; - icol = k; - } - } - } - } - } - ++(ipiv[icol]); - if (irow != icol) { - for (l = 0; l < n; l++) { - swap(a,irow, l, icol, l); - } - for (l = 0; l < m; l++) { - swap(b,irow, l, icol, l); - } - } - indxr[i] = irow; - indxc[i] = icol; - if (get(a,icol, icol) == 0.0) { - return KM_FALSE; - } - pivinv = 1.0f / get(a,icol, icol); - set(a,icol, icol, 1.0f); - for (l = 0; l < n; l++) { - set(a,icol, l, get(a,icol, l) * pivinv); - } - for (l = 0; l < m; l++) { - set(b,icol, l, get(b,icol, l) * pivinv); - } - - for (ll = 0; ll < n; ll++) { - if (ll != icol) { - dum = get(a,ll, icol); - set(a,ll, icol, 0.0f); - for (l = 0; l < n; l++) { - set(a,ll, l, get(a,ll, l) - get(a,icol, l) * dum); - } - for (l = 0; l < m; l++) { - set(b,ll, l, get(a,ll, l) - get(b,icol, l) * dum); - } - } - } - } -// This is the end of the main loop over columns of the reduction. It only remains to unscram- -// ble the solution in view of the column interchanges. We do this by interchanging pairs of -// columns in the reverse order that the permutation was built up. - for (l = n - 1; l >= 0; l--) { - if (indxr[l] != indxc[l]) { - for (k = 0; k < n; k++) { - swap(a,k, indxr[l], k, indxc[l]); - } - } - } - return KM_TRUE; -} - -/** - * Calculates the inverse of pM and stores the result in - * pOut. - * @Return Returns NULL if there is no inverse, else pOut - */ -kmMat4* const kmMat4Inverse(kmMat4* pOut, const kmMat4* pM) -{ - kmMat4 inv; - kmMat4Assign(&inv, pM); - - kmMat4 tmp; - kmMat4Identity(&tmp); - - if(gaussj(&inv, &tmp) == KM_FALSE) { - return NULL; - } - - kmMat4Assign(pOut, &inv); - return pOut; -} -/** - * Returns KM_TRUE if pIn is an identity matrix - * KM_FALSE otherwise - */ -const int kmMat4IsIdentity(const kmMat4* pIn) -{ - static const float identity [] = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - return (memcmp(identity, pIn->mat, sizeof(float) * 16) == 0); -} - -/** - * Sets pOut to the transpose of pIn, returns pOut - */ -kmMat4* const kmMat4Transpose(kmMat4* pOut, const kmMat4* pIn) -{ - int x, z; - - for (z = 0; z < 4; ++z) { - for (x = 0; x < 4; ++x) { - pOut->mat[(z * 4) + x] = pIn->mat[(x * 4) + z]; - } - } - - return pOut; -} - -/** - * Multiplies pM1 with pM2, stores the result in pOut, returns pOut - */ -kmMat4* const kmMat4Multiply(kmMat4* pOut, const kmMat4* pM1, const kmMat4* pM2) -{ -#if defined(__ARM_NEON__) - - float mat[16]; - - // Invert column-order with row-order - NEON_Matrix4Mul( &pM2->mat[0], &pM1->mat[0], &mat[0] ); - -#else - float mat[16]; - - const float *m1 = pM1->mat, *m2 = pM2->mat; - - mat[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]; - mat[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]; - mat[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]; - mat[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]; - - mat[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]; - mat[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]; - mat[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]; - mat[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]; - - mat[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]; - mat[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]; - mat[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]; - mat[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]; - - mat[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]; - mat[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]; - mat[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]; - mat[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]; - -#endif - - memcpy(pOut->mat, mat, sizeof(float)*16); - - return pOut; -} - -/** - * Assigns the value of pIn to pOut - */ -kmMat4* const kmMat4Assign(kmMat4* pOut, const kmMat4* pIn) -{ - assert(pOut != pIn && "You have tried to self-assign!!"); - - memcpy(pOut->mat, pIn->mat, sizeof(float)*16); - - return pOut; -} - -/** - * Returns KM_TRUE if the 2 matrices are equal (approximately) - */ -const int kmMat4AreEqual(const kmMat4* pMat1, const kmMat4* pMat2) -{ - int i = 0; - - assert(pMat1 != pMat2 && "You are comparing the same thing!"); - - for (i = 0; i < 16; ++i) - { - if (!(pMat1->mat[i] + kmEpsilon > pMat2->mat[i] && - pMat1->mat[i] - kmEpsilon < pMat2->mat[i])) { - return KM_FALSE; - } - } - - return KM_TRUE; -} - -/** - * Build a rotation matrix from an axis and an angle. Result is stored in pOut. - * pOut is returned. - */ -kmMat4* const kmMat4RotationAxisAngle(kmMat4* pOut, const kmVec3* axis, kmScalar radians) -{ - float rcos = cosf(radians); - float rsin = sinf(radians); - - kmVec3 normalizedAxis; - kmVec3Normalize(&normalizedAxis, axis); - - pOut->mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos); - pOut->mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos); - pOut->mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos); - pOut->mat[3] = 0.0f; - - pOut->mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos); - pOut->mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos); - pOut->mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos); - pOut->mat[7] = 0.0f; - - pOut->mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos); - pOut->mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos); - pOut->mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos); - pOut->mat[11] = 0.0f; - - pOut->mat[12] = 0.0f; - pOut->mat[13] = 0.0f; - pOut->mat[14] = 0.0f; - pOut->mat[15] = 1.0f; - - return pOut; -} - -/** - * Builds an X-axis rotation matrix and stores it in pOut, returns pOut - */ -kmMat4* const kmMat4RotationX(kmMat4* pOut, const float radians) -{ - /* - | 1 0 0 0 | - M = | 0 cos(A) -sin(A) 0 | - | 0 sin(A) cos(A) 0 | - | 0 0 0 1 | - - */ - - pOut->mat[0] = 1.0f; - pOut->mat[1] = 0.0f; - pOut->mat[2] = 0.0f; - pOut->mat[3] = 0.0f; - - pOut->mat[4] = 0.0f; - pOut->mat[5] = cosf(radians); - pOut->mat[6] = sinf(radians); - pOut->mat[7] = 0.0f; - - pOut->mat[8] = 0.0f; - pOut->mat[9] = -sinf(radians); - pOut->mat[10] = cosf(radians); - pOut->mat[11] = 0.0f; - - pOut->mat[12] = 0.0f; - pOut->mat[13] = 0.0f; - pOut->mat[14] = 0.0f; - pOut->mat[15] = 1.0f; - - return pOut; -} - -/** - * Builds a rotation matrix using the rotation around the Y-axis - * The result is stored in pOut, pOut is returned. - */ -kmMat4* const kmMat4RotationY(kmMat4* pOut, const float radians) -{ - /* - | cos(A) 0 sin(A) 0 | - M = | 0 1 0 0 | - | -sin(A) 0 cos(A) 0 | - | 0 0 0 1 | - */ - - pOut->mat[0] = cosf(radians); - pOut->mat[1] = 0.0f; - pOut->mat[2] = -sinf(radians); - pOut->mat[3] = 0.0f; - - pOut->mat[4] = 0.0f; - pOut->mat[5] = 1.0f; - pOut->mat[6] = 0.0f; - pOut->mat[7] = 0.0f; - - pOut->mat[8] = sinf(radians); - pOut->mat[9] = 0.0f; - pOut->mat[10] = cosf(radians); - pOut->mat[11] = 0.0f; - - pOut->mat[12] = 0.0f; - pOut->mat[13] = 0.0f; - pOut->mat[14] = 0.0f; - pOut->mat[15] = 1.0f; - - return pOut; -} - -/** - * Builds a rotation matrix around the Z-axis. The resulting - * matrix is stored in pOut. pOut is returned. - */ -kmMat4* const kmMat4RotationZ(kmMat4* pOut, const float radians) -{ - /* - | cos(A) -sin(A) 0 0 | - M = | sin(A) cos(A) 0 0 | - | 0 0 1 0 | - | 0 0 0 1 | - */ - - pOut->mat[0] = cosf(radians); - pOut->mat[1] = sinf(radians); - pOut->mat[2] = 0.0f; - pOut->mat[3] = 0.0f; - - pOut->mat[4] = -sinf(radians);; - pOut->mat[5] = cosf(radians); - pOut->mat[6] = 0.0f; - pOut->mat[7] = 0.0f; - - pOut->mat[8] = 0.0f; - pOut->mat[9] = 0.0f; - pOut->mat[10] = 1.0f; - pOut->mat[11] = 0.0f; - - pOut->mat[12] = 0.0f; - pOut->mat[13] = 0.0f; - pOut->mat[14] = 0.0f; - pOut->mat[15] = 1.0f; - - return pOut; -} - -/** - * Builds a rotation matrix from pitch, yaw and roll. The resulting - * matrix is stored in pOut and pOut is returned - */ -kmMat4* const kmMat4RotationPitchYawRoll(kmMat4* pOut, const kmScalar pitch, const kmScalar yaw, const kmScalar roll) -{ - double cr = cos(pitch); - double sr = sin(pitch); - double cp = cos(yaw); - double sp = sin(yaw); - double cy = cos(roll); - double sy = sin(roll); - double srsp = sr * sp; - double crsp = cr * sp; - - pOut->mat[0] = (kmScalar) cp * cy; - pOut->mat[4] = (kmScalar) cp * sy; - pOut->mat[8] = (kmScalar) - sp; - - pOut->mat[1] = (kmScalar) srsp * cy - cr * sy; - pOut->mat[5] = (kmScalar) srsp * sy + cr * cy; - pOut->mat[9] = (kmScalar) sr * cp; - - pOut->mat[2] = (kmScalar) crsp * cy + sr * sy; - pOut->mat[6] = (kmScalar) crsp * sy - sr * cy; - pOut->mat[10] = (kmScalar) cr * cp; - - pOut->mat[3] = pOut->mat[7] = pOut->mat[11] = 0.0; - pOut->mat[15] = 1.0; - - return pOut; -} - -/** Converts a quaternion to a rotation matrix, - * the result is stored in pOut, returns pOut - */ -kmMat4* const kmMat4RotationQuaternion(kmMat4* pOut, const kmQuaternion* pQ) -{ - pOut->mat[0] = 1.0f - 2.0f * (pQ->y * pQ->y + pQ->z * pQ->z ); - pOut->mat[1] = 2.0f * (pQ->x * pQ->y + pQ->z * pQ->w); - pOut->mat[2] = 2.0f * (pQ->x * pQ->z - pQ->y * pQ->w); - pOut->mat[3] = 0.0f; - - // Second row - pOut->mat[4] = 2.0f * ( pQ->x * pQ->y - pQ->z * pQ->w ); - pOut->mat[5] = 1.0f - 2.0f * ( pQ->x * pQ->x + pQ->z * pQ->z ); - pOut->mat[6] = 2.0f * (pQ->z * pQ->y + pQ->x * pQ->w ); - pOut->mat[7] = 0.0f; - - // Third row - pOut->mat[8] = 2.0f * ( pQ->x * pQ->z + pQ->y * pQ->w ); - pOut->mat[9] = 2.0f * ( pQ->y * pQ->z - pQ->x * pQ->w ); - pOut->mat[10] = 1.0f - 2.0f * ( pQ->x * pQ->x + pQ->y * pQ->y ); - pOut->mat[11] = 0.0f; - - // Fourth row - pOut->mat[12] = 0; - pOut->mat[13] = 0; - pOut->mat[14] = 0; - pOut->mat[15] = 1.0f; - - return pOut; -} - -/** Builds a scaling matrix */ -kmMat4* const kmMat4Scaling(kmMat4* pOut, const kmScalar x, const kmScalar y, - const kmScalar z) -{ - memset(pOut->mat, 0, sizeof(float) * 16); - pOut->mat[0] = x; - pOut->mat[5] = y; - pOut->mat[10] = z; - pOut->mat[15] = 1.0f; - - return pOut; -} - -/** - * Builds a translation matrix. All other elements in the matrix - * will be set to zero except for the diagonal which is set to 1.0 - */ -kmMat4* const kmMat4Translation(kmMat4* pOut, const kmScalar x, - const kmScalar y, const kmScalar z) -{ - //FIXME: Write a test for this - memset(pOut->mat, 0, sizeof(float) * 16); - - pOut->mat[0] = 1.0f; - pOut->mat[5] = 1.0f; - pOut->mat[10] = 1.0f; - - pOut->mat[12] = x; - pOut->mat[13] = y; - pOut->mat[14] = z; - pOut->mat[15] = 1.0f; - - return pOut; -} - -/** - * Get the up vector from a matrix. pIn is the matrix you - * wish to extract the vector from. pOut is a pointer to the - * kmVec3 structure that should hold the resulting vector - */ -kmVec3* const kmMat4GetUpVec3(kmVec3* pOut, const kmMat4* pIn) -{ - pOut->x = pIn->mat[4]; - pOut->y = pIn->mat[5]; - pOut->z = pIn->mat[6]; - - kmVec3Normalize(pOut, pOut); - - return pOut; -} - -/** Extract the right vector from a 4x4 matrix. The result is - * stored in pOut. Returns pOut. - */ -kmVec3* const kmMat4GetRightVec3(kmVec3* pOut, const kmMat4* pIn) -{ - pOut->x = pIn->mat[0]; - pOut->y = pIn->mat[1]; - pOut->z = pIn->mat[2]; - - kmVec3Normalize(pOut, pOut); - - return pOut; -} - -/** - * Extract the forward vector from a 4x4 matrix. The result is - * stored in pOut. Returns pOut. - */ -kmVec3* const kmMat4GetForwardVec3(kmVec3* pOut, const kmMat4* pIn) -{ - pOut->x = pIn->mat[8]; - pOut->y = pIn->mat[9]; - pOut->z = pIn->mat[10]; - - kmVec3Normalize(pOut, pOut); - - return pOut; -} - -/** - * Creates a perspective projection matrix in the - * same way as gluPerspective - */ -kmMat4* const kmMat4PerspectiveProjection(kmMat4* pOut, kmScalar fovY, - kmScalar aspect, kmScalar zNear, - kmScalar zFar) -{ - kmScalar r = kmDegreesToRadians(fovY / 2); - kmScalar deltaZ = zFar - zNear; - kmScalar s = sin(r); - kmScalar cotangent = 0; - - if (deltaZ == 0 || s == 0 || aspect == 0) { - return NULL; - } - - //cos(r) / sin(r) = cot(r) - cotangent = cos(r) / s; - - kmMat4Identity(pOut); - pOut->mat[0] = cotangent / aspect; - pOut->mat[5] = cotangent; - pOut->mat[10] = -(zFar + zNear) / deltaZ; - pOut->mat[11] = -1; - pOut->mat[14] = -2 * zNear * zFar / deltaZ; - pOut->mat[15] = 0; - - return pOut; -} - -/** Creates an orthographic projection matrix like glOrtho */ -kmMat4* const kmMat4OrthographicProjection(kmMat4* pOut, kmScalar left, - kmScalar right, kmScalar bottom, - kmScalar top, kmScalar nearVal, - kmScalar farVal) -{ - kmScalar tx = -((right + left) / (right - left)); - kmScalar ty = -((top + bottom) / (top - bottom)); - kmScalar tz = -((farVal + nearVal) / (farVal - nearVal)); - - kmMat4Identity(pOut); - pOut->mat[0] = 2 / (right - left); - pOut->mat[5] = 2 / (top - bottom); - pOut->mat[10] = -2 / (farVal - nearVal); - pOut->mat[12] = tx; - pOut->mat[13] = ty; - pOut->mat[14] = tz; - - return pOut; -} - -/** - * Builds a translation matrix in the same way as gluLookAt() - * the resulting matrix is stored in pOut. pOut is returned. - */ -kmMat4* const kmMat4LookAt(kmMat4* pOut, const kmVec3* pEye, - const kmVec3* pCenter, const kmVec3* pUp) -{ - kmVec3 f, up, s, u; - kmMat4 translate; - - kmVec3Subtract(&f, pCenter, pEye); - kmVec3Normalize(&f, &f); - - kmVec3Assign(&up, pUp); - kmVec3Normalize(&up, &up); - - kmVec3Cross(&s, &f, &up); - kmVec3Normalize(&s, &s); - - kmVec3Cross(&u, &s, &f); - kmVec3Normalize(&s, &s); - - kmMat4Identity(pOut); - - pOut->mat[0] = s.x; - pOut->mat[4] = s.y; - pOut->mat[8] = s.z; - - pOut->mat[1] = u.x; - pOut->mat[5] = u.y; - pOut->mat[9] = u.z; - - pOut->mat[2] = -f.x; - pOut->mat[6] = -f.y; - pOut->mat[10] = -f.z; - - kmMat4Translation(&translate, -pEye->x, -pEye->y, -pEye->z); - kmMat4Multiply(pOut, pOut, &translate); - - return pOut; -} - -/** - * Extract a 3x3 rotation matrix from the input 4x4 transformation. - * Stores the result in pOut, returns pOut - */ -kmMat3* const kmMat4ExtractRotation(kmMat3* pOut, const kmMat4* pIn) -{ - pOut->mat[0] = pIn->mat[0]; - pOut->mat[1] = pIn->mat[1]; - pOut->mat[2] = pIn->mat[2]; - - pOut->mat[3] = pIn->mat[4]; - pOut->mat[4] = pIn->mat[5]; - pOut->mat[5] = pIn->mat[6]; - - pOut->mat[6] = pIn->mat[8]; - pOut->mat[7] = pIn->mat[9]; - pOut->mat[8] = pIn->mat[10]; - - return pOut; -} - -/** - * Take the rotation from a 4x4 transformation matrix, and return it as an axis and an angle (in radians) - * returns the output axis. - */ -kmVec3* const kmMat4RotationToAxisAngle(kmVec3* pAxis, kmScalar* radians, const kmMat4* pIn) -{ - /*Surely not this easy?*/ - kmQuaternion temp; - kmMat3 rotation; - kmMat4ExtractRotation(&rotation, pIn); - kmQuaternionRotationMatrix(&temp, &rotation); - kmQuaternionToAxisAngle(&temp, pAxis, radians); - return pAxis; -} - -/** Build a 4x4 OpenGL transformation matrix using a 3x3 rotation matrix, - * and a 3d vector representing a translation. Assign the result to pOut, - * pOut is also returned. - */ -kmMat4* const kmMat4RotationTranslation(kmMat4* pOut, const kmMat3* rotation, const kmVec3* translation) -{ - pOut->mat[0] = rotation->mat[0]; - pOut->mat[1] = rotation->mat[1]; - pOut->mat[2] = rotation->mat[2]; - pOut->mat[3] = 0.0f; - - pOut->mat[4] = rotation->mat[3]; - pOut->mat[5] = rotation->mat[4]; - pOut->mat[6] = rotation->mat[5]; - pOut->mat[7] = 0.0f; - - pOut->mat[8] = rotation->mat[6]; - pOut->mat[9] = rotation->mat[7]; - pOut->mat[10] = rotation->mat[8]; - pOut->mat[11] = 0.0f; - - pOut->mat[12] = translation->x; - pOut->mat[13] = translation->y; - pOut->mat[14] = translation->z; - pOut->mat[15] = 1.0f; - - return pOut; -} - -kmPlane* const kmMat4ExtractPlane(kmPlane* pOut, const kmMat4* pIn, const kmEnum plane) -{ - float t = 1.0f; - - switch(plane) { - case KM_PLANE_RIGHT: - pOut->a = pIn->mat[3] - pIn->mat[0]; - pOut->b = pIn->mat[7] - pIn->mat[4]; - pOut->c = pIn->mat[11] - pIn->mat[8]; - pOut->d = pIn->mat[15] - pIn->mat[12]; - break; - case KM_PLANE_LEFT: - pOut->a = pIn->mat[3] + pIn->mat[0]; - pOut->b = pIn->mat[7] + pIn->mat[4]; - pOut->c = pIn->mat[11] + pIn->mat[8]; - pOut->d = pIn->mat[15] + pIn->mat[12]; - break; - case KM_PLANE_BOTTOM: - pOut->a = pIn->mat[3] + pIn->mat[1]; - pOut->b = pIn->mat[7] + pIn->mat[5]; - pOut->c = pIn->mat[11] + pIn->mat[9]; - pOut->d = pIn->mat[15] + pIn->mat[13]; - break; - case KM_PLANE_TOP: - pOut->a = pIn->mat[3] - pIn->mat[1]; - pOut->b = pIn->mat[7] - pIn->mat[5]; - pOut->c = pIn->mat[11] - pIn->mat[9]; - pOut->d = pIn->mat[15] - pIn->mat[13]; - break; - case KM_PLANE_FAR: - pOut->a = pIn->mat[3] - pIn->mat[2]; - pOut->b = pIn->mat[7] - pIn->mat[6]; - pOut->c = pIn->mat[11] - pIn->mat[10]; - pOut->d = pIn->mat[15] - pIn->mat[14]; - break; - case KM_PLANE_NEAR: - pOut->a = pIn->mat[3] + pIn->mat[2]; - pOut->b = pIn->mat[7] + pIn->mat[6]; - pOut->c = pIn->mat[11] + pIn->mat[10]; - pOut->d = pIn->mat[15] + pIn->mat[14]; - break; - default: - assert(0 && "Invalid plane index"); - } - - t = sqrtf(pOut->a * pOut->a + - pOut->b * pOut->b + - pOut->c * pOut->c); - pOut->a /= t; - pOut->b /= t; - pOut->c /= t; - pOut->d /= t; - - return pOut; -} diff --git a/Example/libs/kazmath/src/neon_matrix_impl.c b/Example/libs/kazmath/src/neon_matrix_impl.c deleted file mode 100644 index a00f771..0000000 --- a/Example/libs/kazmath/src/neon_matrix_impl.c +++ /dev/null @@ -1,97 +0,0 @@ -/* - NEON math library for the iPhone / iPod touch - - Copyright (c) 2009 Justin Saunders - - This software is provided 'as-is', without any express or implied warranty. - In no event will the authors be held liable for any damages arising - from the use of this software. - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it freely, - subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must - not claim that you wrote the original software. If you use this - software in a product, an acknowledgment in the product documentation - would be appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must - not be misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source distribution. -*/ - -#include "kazmath/neon_matrix_impl.h" - -#if defined(__ARM_NEON__) - -void NEON_Matrix4Mul(const float* a, const float* b, float* output ) -{ - __asm__ volatile - ( - // Store A & B leaving room for q4-q7, which should be preserved - "vldmia %1, { q0-q3 } \n\t" - "vldmia %2, { q8-q11 }\n\t" - - // result = first column of B x first row of A - "vmul.f32 q12, q8, d0[0]\n\t" - "vmul.f32 q13, q8, d2[0]\n\t" - "vmul.f32 q14, q8, d4[0]\n\t" - "vmul.f32 q15, q8, d6[0]\n\t" - - // result += second column of B x second row of A - "vmla.f32 q12, q9, d0[1]\n\t" - "vmla.f32 q13, q9, d2[1]\n\t" - "vmla.f32 q14, q9, d4[1]\n\t" - "vmla.f32 q15, q9, d6[1]\n\t" - - // result += third column of B x third row of A - "vmla.f32 q12, q10, d1[0]\n\t" - "vmla.f32 q13, q10, d3[0]\n\t" - "vmla.f32 q14, q10, d5[0]\n\t" - "vmla.f32 q15, q10, d7[0]\n\t" - - // result += last column of B x last row of A - "vmla.f32 q12, q11, d1[1]\n\t" - "vmla.f32 q13, q11, d3[1]\n\t" - "vmla.f32 q14, q11, d5[1]\n\t" - "vmla.f32 q15, q11, d7[1]\n\t" - - // output = result registers - "vstmia %0, { q12-q15 }" - : // no output - : "r" (output), "r" (a), "r" (b) // input - note *value* of pointer doesn't change - : "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" //clobber - ); -} - -void NEON_Matrix4Vector4Mul(const float* m, const float* v, float* output) -{ - __asm__ volatile - ( - // Store m & v - avoiding q4-q7 which need to be preserved - q0 = result - "vldmia %1, { q8-q11 } \n\t" // q8-q11 = m - "vldmia %2, { q1 } \n\t" // q1 = v - - // result = first column of A x V.x - "vmul.f32 q0, q8, d2[0]\n\t" - - // result += second column of A x V.y - "vmla.f32 q0, q9, d2[1]\n\t" - - // result += third column of A x V.z - "vmla.f32 q0, q10, d3[0]\n\t" - - // result += last column of A x V.w - "vmla.f32 q0, q11, d3[1]\n\t" - - // output = result registers - "vstmia %0, { q0 }" - - : // no output - : "r" (output), "r" (m), "r" (v) // input - note *value* of pointer doesn't change - : "memory", "q0", "q1", "q8", "q9", "q10", "q11" //clobber - ); -} - -#endif diff --git a/Example/libs/kazmath/src/plane.c b/Example/libs/kazmath/src/plane.c deleted file mode 100644 index f8dc02f..0000000 --- a/Example/libs/kazmath/src/plane.c +++ /dev/null @@ -1,175 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include -#include - -#include "kazmath/vec3.h" -#include "kazmath/vec4.h" -#include "kazmath/plane.h" - -const kmScalar kmPlaneDot(const kmPlane* pP, const kmVec4* pV) -{ - //a*x + b*y + c*z + d*w - - return (pP->a * pV->x + - pP->b * pV->y + - pP->c * pV->z + - pP->d * pV->w); -} - -const kmScalar kmPlaneDotCoord(const kmPlane* pP, const kmVec3* pV) -{ - return (pP->a * pV->x + - pP->b * pV->y + - pP->c * pV->z + pP->d); -} - -const kmScalar kmPlaneDotNormal(const kmPlane* pP, const kmVec3* pV) -{ - return (pP->a * pV->x + - pP->b * pV->y + - pP->c * pV->z); -} - -kmPlane* const kmPlaneFromPointNormal(kmPlane* pOut, const kmVec3* pPoint, const kmVec3* pNormal) -{ - /* - Planea = Nx - Planeb = Ny - Planec = Nz - Planed = −N⋅P - */ - - - pOut->a = pNormal->x; - pOut->b = pNormal->y; - pOut->c = pNormal->z; - pOut->d = -kmVec3Dot(pNormal, pPoint); - - return pOut; -} - -/** - * Creates a plane from 3 points. The result is stored in pOut. - * pOut is returned. - */ -kmPlane* const kmPlaneFromPoints(kmPlane* pOut, const kmVec3* p1, const kmVec3* p2, const kmVec3* p3) -{ - /* - v = (B − A) × (C − A) - n = 1⁄|v| v - Outa = nx - Outb = ny - Outc = nz - Outd = −n⋅A - */ - - kmVec3 n, v1, v2; - kmVec3Subtract(&v1, p2, p1); //Create the vectors for the 2 sides of the triangle - kmVec3Subtract(&v2, p3, p1); - kmVec3Cross(&n, &v1, &v2); //Use the cross product to get the normal - - kmVec3Normalize(&n, &n); //Normalize it and assign to pOut->m_N - - pOut->a = n.x; - pOut->b = n.y; - pOut->c = n.z; - pOut->d = kmVec3Dot(kmVec3Scale(&n, &n, -1.0), p1); - - return pOut; -} - -kmVec3* const kmPlaneIntersectLine(kmVec3* pOut, const kmPlane* pP, const kmVec3* pV1, const kmVec3* pV2) -{ - /* - n = (Planea, Planeb, Planec) - d = V − U - Out = U − d⋅(Pd + n⋅U)⁄(d⋅n) [iff d⋅n ≠ 0] - */ - kmVec3 d; - assert(0 && "Not implemented"); - - - kmVec3Subtract(&d, pV2, pV1); //Get the direction vector - - - //TODO: Continue here! - /*if (fabs(kmVec3Dot(&pP->m_N, &d)) > kmEpsilon) - { - //If we get here then the plane and line are parallel (i.e. no intersection) - pOut = nullptr; //Set to nullptr - - return pOut; - } */ - - return NULL; -} - -kmPlane* const kmPlaneNormalize(kmPlane* pOut, const kmPlane* pP) -{ - kmVec3 n; - kmScalar l = 0; - - n.x = pP->a; - n.y = pP->b; - n.z = pP->c; - - l = 1.0f / kmVec3Length(&n); //Get 1/length - kmVec3Normalize(&n, &n); //Normalize the vector and assign to pOut - - pOut->a = n.x; - pOut->b = n.y; - pOut->c = n.z; - - pOut->d = pP->d * l; //Scale the D value and assign to pOut - - return pOut; -} - -kmPlane* const kmPlaneScale(kmPlane* pOut, const kmPlane* pP, kmScalar s) -{ - assert(0 && "Not implemented"); - return NULL; -} - -/** - * Returns POINT_INFRONT_OF_PLANE if pP is infront of pIn. Returns - * POINT_BEHIND_PLANE if it is behind. Returns POINT_ON_PLANE otherwise - */ -const POINT_CLASSIFICATION kmPlaneClassifyPoint(const kmPlane* pIn, const kmVec3* pP) -{ - // This function will determine if a point is on, in front of, or behind - // the plane. First we store the dot product of the plane and the point. - float distance = pIn->a * pP->x + pIn->b * pP->y + pIn->c * pP->z + pIn->d; - - // Simply put if the dot product is greater than 0 then it is infront of it. - // If it is less than 0 then it is behind it. And if it is 0 then it is on it. - if(distance > 0.001) return POINT_INFRONT_OF_PLANE; - if(distance < -0.001) return POINT_BEHIND_PLANE; - - return POINT_ON_PLANE; -} - diff --git a/Example/libs/kazmath/src/quaternion.c b/Example/libs/kazmath/src/quaternion.c deleted file mode 100644 index c5bf58e..0000000 --- a/Example/libs/kazmath/src/quaternion.c +++ /dev/null @@ -1,582 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - - -#include -#include - -#include "kazmath/utility.h" -#include "kazmath/mat3.h" -#include "kazmath/vec3.h" -#include "kazmath/quaternion.h" - -///< Returns pOut, sets pOut to the conjugate of pIn -kmQuaternion* const kmQuaternionConjugate(kmQuaternion* pOut, const kmQuaternion* pIn) -{ - pOut->x = -pIn->x; - pOut->y = -pIn->y; - pOut->z = -pIn->z; - pOut->w = pIn->w; - - return pOut; -} - -///< Returns the dot product of the 2 quaternions -const kmScalar kmQuaternionDot(const kmQuaternion* q1, const kmQuaternion* q2) -{ - // A dot B = B dot A = AtBt + AxBx + AyBy + AzBz - - return (q1->w * q2->w + - q1->x * q2->x + - q1->y * q2->y + - q1->z * q2->z); -} - -///< Returns the exponential of the quaternion -kmQuaternion* kmQuaternionExp(kmQuaternion* pOut, const kmQuaternion* pIn) -{ - assert(0); - - return pOut; -} - -///< Makes the passed quaternion an identity quaternion -kmQuaternion* kmQuaternionIdentity(kmQuaternion* pOut) -{ - pOut->x = 0.0; - pOut->y = 0.0; - pOut->z = 0.0; - pOut->w = 1.0; - - return pOut; -} - -///< Returns the inverse of the passed Quaternion -kmQuaternion* kmQuaternionInverse(kmQuaternion* pOut, - const kmQuaternion* pIn) -{ - kmScalar l = kmQuaternionLength(pIn); - kmQuaternion tmp; - - if (fabs(l) > kmEpsilon) - { - pOut->x = 0.0; - pOut->y = 0.0; - pOut->z = 0.0; - pOut->w = 0.0; - - return pOut; - } - - - - ///Get the conjugute and divide by the length - kmQuaternionScale(pOut, - kmQuaternionConjugate(&tmp, pIn), 1.0f / l); - - return pOut; -} - -///< Returns true if the quaternion is an identity quaternion -int kmQuaternionIsIdentity(const kmQuaternion* pIn) -{ - return (pIn->x == 0.0 && pIn->y == 0.0 && pIn->z == 0.0 && - pIn->w == 1.0); -} - -///< Returns the length of the quaternion -kmScalar kmQuaternionLength(const kmQuaternion* pIn) -{ - return sqrtf(kmQuaternionLengthSq(pIn)); -} - -///< Returns the length of the quaternion squared (prevents a sqrt) -kmScalar kmQuaternionLengthSq(const kmQuaternion* pIn) -{ - return pIn->x * pIn->x + pIn->y * pIn->y + - pIn->z * pIn->z + pIn->w * pIn->w; -} - -///< Returns the natural logarithm -kmQuaternion* kmQuaternionLn(kmQuaternion* pOut, - const kmQuaternion* pIn) -{ - /* - A unit quaternion, is defined by: - Q == (cos(theta), sin(theta) * v) where |v| = 1 - The natural logarithm of Q is, ln(Q) = (0, theta * v) - */ - - assert(0); - - return pOut; -} - -///< Multiplies 2 quaternions together -extern -kmQuaternion* kmQuaternionMultiply(kmQuaternion* pOut, - const kmQuaternion* q1, - const kmQuaternion* q2) -{ - pOut->w = q1->w * q2->w - q1->x * q2->x - q1->y * q2->y - q1->z * q2->z; - pOut->x = q1->w * q2->x + q1->x * q2->w + q1->y * q2->z - q1->z * q2->y; - pOut->y = q1->w * q2->y + q1->y * q2->w + q1->z * q2->x - q1->x * q2->z; - pOut->z = q1->w * q2->z + q1->z * q2->w + q1->x * q2->y - q1->y * q2->x; - - return pOut; -} - -///< Normalizes a quaternion -kmQuaternion* kmQuaternionNormalize(kmQuaternion* pOut, - const kmQuaternion* pIn) -{ - kmScalar length = kmQuaternionLength(pIn); - assert(fabs(length) > kmEpsilon); - kmQuaternionScale(pOut, pIn, 1.0f / length); - - return pOut; -} - -///< Rotates a quaternion around an axis -kmQuaternion* kmQuaternionRotationAxis(kmQuaternion* pOut, - const kmVec3* pV, - kmScalar angle) -{ - kmScalar rad = angle * 0.5f; - kmScalar scale = sinf(rad); - - pOut->w = cosf(rad); - pOut->x = pV->x * scale; - pOut->y = pV->y * scale; - pOut->z = pV->z * scale; - - return pOut; -} - -///< Creates a quaternion from a rotation matrix -kmQuaternion* kmQuaternionRotationMatrix(kmQuaternion* pOut, - const kmMat3* pIn) -{ -/* -Note: The OpenGL matrices are transposed from the description below -taken from the Matrix and Quaternion FAQ - - if ( mat[0] > mat[5] && mat[0] > mat[10] ) { // Column 0: - S = sqrt( 1.0 + mat[0] - mat[5] - mat[10] ) * 2; - X = 0.25 * S; - Y = (mat[4] + mat[1] ) / S; - Z = (mat[2] + mat[8] ) / S; - W = (mat[9] - mat[6] ) / S; - } else if ( mat[5] > mat[10] ) { // Column 1: - S = sqrt( 1.0 + mat[5] - mat[0] - mat[10] ) * 2; - X = (mat[4] + mat[1] ) / S; - Y = 0.25 * S; - Z = (mat[9] + mat[6] ) / S; - W = (mat[2] - mat[8] ) / S; - } else { // Column 2: - S = sqrt( 1.0 + mat[10] - mat[0] - mat[5] ) * 2; - X = (mat[2] + mat[8] ) / S; - Y = (mat[9] + mat[6] ) / S; - Z = 0.25 * S; - W = (mat[4] - mat[1] ) / S; - } -*/ - - float x, y, z, w; - float *pMatrix = NULL; - float m4x4[16] = {0}; - float scale = 0.0f; - float diagonal = 0.0f; - - if(!pIn) { - return NULL; - } - -/* 0 3 6 - 1 4 7 - 2 5 8 - - 0 1 2 3 - 4 5 6 7 - 8 9 10 11 - 12 13 14 15*/ - - m4x4[0] = pIn->mat[0]; - m4x4[1] = pIn->mat[3]; - m4x4[2] = pIn->mat[6]; - m4x4[4] = pIn->mat[1]; - m4x4[5] = pIn->mat[4]; - m4x4[6] = pIn->mat[7]; - m4x4[8] = pIn->mat[2]; - m4x4[9] = pIn->mat[5]; - m4x4[10] = pIn->mat[8]; - m4x4[15] = 1; - pMatrix = &m4x4[0]; - - diagonal = pMatrix[0] + pMatrix[5] + pMatrix[10] + 1; - - if(diagonal > kmEpsilon) { - // Calculate the scale of the diagonal - scale = (float)sqrt(diagonal ) * 2; - - // Calculate the x, y, x and w of the quaternion through the respective equation - x = ( pMatrix[9] - pMatrix[6] ) / scale; - y = ( pMatrix[2] - pMatrix[8] ) / scale; - z = ( pMatrix[4] - pMatrix[1] ) / scale; - w = 0.25f * scale; - } - else - { - // If the first element of the diagonal is the greatest value - if ( pMatrix[0] > pMatrix[5] && pMatrix[0] > pMatrix[10] ) - { - // Find the scale according to the first element, and double that value - scale = (float)sqrt( 1.0f + pMatrix[0] - pMatrix[5] - pMatrix[10] ) * 2.0f; - - // Calculate the x, y, x and w of the quaternion through the respective equation - x = 0.25f * scale; - y = (pMatrix[4] + pMatrix[1] ) / scale; - z = (pMatrix[2] + pMatrix[8] ) / scale; - w = (pMatrix[9] - pMatrix[6] ) / scale; - } - // Else if the second element of the diagonal is the greatest value - else if (pMatrix[5] > pMatrix[10]) - { - // Find the scale according to the second element, and double that value - scale = (float)sqrt( 1.0f + pMatrix[5] - pMatrix[0] - pMatrix[10] ) * 2.0f; - - // Calculate the x, y, x and w of the quaternion through the respective equation - x = (pMatrix[4] + pMatrix[1] ) / scale; - y = 0.25f * scale; - z = (pMatrix[9] + pMatrix[6] ) / scale; - w = (pMatrix[2] - pMatrix[8] ) / scale; - } - // Else the third element of the diagonal is the greatest value - else - { - // Find the scale according to the third element, and double that value - scale = (float)sqrt( 1.0f + pMatrix[10] - pMatrix[0] - pMatrix[5] ) * 2.0f; - - // Calculate the x, y, x and w of the quaternion through the respective equation - x = (pMatrix[2] + pMatrix[8] ) / scale; - y = (pMatrix[9] + pMatrix[6] ) / scale; - z = 0.25f * scale; - w = (pMatrix[4] - pMatrix[1] ) / scale; - } - } - - pOut->x = x; - pOut->y = y; - pOut->z = z; - pOut->w = w; - - return pOut; - -#if 0 - kmScalar T = pIn->mat[0] + pIn->mat[5] + pIn->mat[10]; - - if (T > kmEpsilon) { - //If the trace is greater than zero we always use this calculation: - /* S = sqrt(T) * 2; - X = ( mat[9] - mat[6] ) / S; - Y = ( mat[2] - mat[8] ) / S; - Z = ( mat[4] - mat[1] ) / S; - W = 0.25 * S;*/ - -/* kmScalar s = sqrtf(T) * 2; - pOut->x = (pIn->mat[9] - pIn->mat[6]) / s; - pOut->y = (pIn->mat[8] - pIn->mat[2]) / s; - pOut->z = (pIn->mat[1] - pIn->mat[4]) / s; - pOut->w = 0.25f * s; - - kmQuaternionNormalize(pOut, pOut); - return pOut; - } - - //Otherwise the calculation depends on which major diagonal element has the greatest value. - - if (pIn->mat[0] > pIn->mat[5] && pIn->mat[0] > pIn->mat[10]) { - kmScalar s = sqrtf(1 + pIn->mat[0] - pIn->mat[5] - pIn->mat[10]) * 2; - pOut->x = 0.25f * s; - pOut->y = (pIn->mat[1] + pIn->mat[4]) / s; - pOut->z = (pIn->mat[8] + pIn->mat[2]) / s; - pOut->w = (pIn->mat[9] - pIn->mat[6]) / s; - } - else if (pIn->mat[5] > pIn->mat[10]) { - kmScalar s = sqrtf(1 + pIn->mat[5] - pIn->mat[0] - pIn->mat[10]) * 2; - pOut->x = (pIn->mat[1] + pIn->mat[4]) / s; - pOut->y = 0.25f * s; - pOut->z = (pIn->mat[9] + pIn->mat[6]) / s; - pOut->w = (pIn->mat[8] - pIn->mat[2]) / s; - } - else { - kmScalar s = sqrt(1.0f + pIn->mat[10] - pIn->mat[0] - pIn->mat[5]) * 2.0f; - pOut->x = (pIn->mat[8] + pIn->mat[2] ) / s; - pOut->y = (pIn->mat[6] + pIn->mat[9] ) / s; - pOut->z = 0.25f * s; - pOut->w = (pIn->mat[1] - pIn->mat[4] ) / s; - } - - kmQuaternionNormalize(pOut, pOut); - return pOut;*/ -#endif // 0 -} - -///< Create a quaternion from yaw, pitch and roll -kmQuaternion* kmQuaternionRotationYawPitchRoll(kmQuaternion* pOut, - kmScalar yaw, - kmScalar pitch, - kmScalar roll) -{ - kmScalar ex, ey, ez; // temp half euler angles - kmScalar cr, cp, cy, sr, sp, sy, cpcy, spsy; // temp vars in roll,pitch yaw - - ex = kmDegreesToRadians(pitch) / 2.0f; // convert to rads and half them - ey = kmDegreesToRadians(yaw) / 2.0f; - ez = kmDegreesToRadians(roll) / 2.0f; - - cr = cosf(ex); - cp = cosf(ey); - cy = cosf(ez); - - sr = sinf(ex); - sp = sinf(ey); - sy = sinf(ez); - - cpcy = cp * cy; - spsy = sp * sy; - - pOut->w = cr * cpcy + sr * spsy; - - pOut->x = sr * cpcy - cr * spsy; - pOut->y = cr * sp * cy + sr * cp * sy; - pOut->z = cr * cp * sy - sr * sp * cy; - - kmQuaternionNormalize(pOut, pOut); - - return pOut; -} - -///< Interpolate between 2 quaternions -kmQuaternion* kmQuaternionSlerp(kmQuaternion* pOut, - const kmQuaternion* q1, - const kmQuaternion* q2, - kmScalar t) -{ - - /*float CosTheta = Q0.DotProd(Q1); - float Theta = acosf(CosTheta); - float SinTheta = sqrtf(1.0f-CosTheta*CosTheta); - - float Sin_T_Theta = sinf(T*Theta)/SinTheta; - float Sin_OneMinusT_Theta = sinf((1.0f-T)*Theta)/SinTheta; - - Quaternion Result = Q0*Sin_OneMinusT_Theta; - Result += (Q1*Sin_T_Theta); - - return Result;*/ - - if (q1->x == q2->x && - q1->y == q2->y && - q1->z == q2->z && - q1->w == q2->w) { - - pOut->x = q1->x; - pOut->y = q1->y; - pOut->z = q1->z; - pOut->w = q1->w; - - return pOut; - } - - kmScalar ct = kmQuaternionDot(q1, q2); - kmScalar theta = acosf(ct); - kmScalar st = sqrtf(1.0 - kmSQR(ct)); - - kmScalar stt = sinf(t * theta) / st; - kmScalar somt = sinf((1.0 - t) * theta) / st; - - kmQuaternion temp, temp2; - kmQuaternionScale(&temp, q1, somt); - kmQuaternionScale(&temp2, q2, stt); - kmQuaternionAdd(pOut, &temp, &temp2); - - return pOut; -} - -///< Get the axis and angle of rotation from a quaternion -void kmQuaternionToAxisAngle(const kmQuaternion* pIn, - kmVec3* pAxis, - kmScalar* pAngle) -{ - kmScalar tempAngle; // temp angle - kmScalar scale; // temp vars - - tempAngle = acosf(pIn->w); - scale = sqrtf(kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z)); - - if (((scale > -kmEpsilon) && scale < kmEpsilon) - || (scale < 2*kmPI + kmEpsilon && scale > 2*kmPI - kmEpsilon)) // angle is 0 or 360 so just simply set axis to 0,0,1 with angle 0 - { - *pAngle = 0.0f; - - pAxis->x = 0.0f; - pAxis->y = 0.0f; - pAxis->z = 1.0f; - } - else - { - *pAngle = tempAngle * 2.0f; // angle in radians - - pAxis->x = pIn->x / scale; - pAxis->y = pIn->y / scale; - pAxis->z = pIn->z / scale; - kmVec3Normalize(pAxis, pAxis); - } -} - -kmQuaternion* kmQuaternionScale(kmQuaternion* pOut, - const kmQuaternion* pIn, - kmScalar s) -{ - pOut->x = pIn->x * s; - pOut->y = pIn->y * s; - pOut->z = pIn->z * s; - pOut->w = pIn->w * s; - - return pOut; -} - -kmQuaternion* kmQuaternionAssign(kmQuaternion* pOut, const kmQuaternion* pIn) -{ - memcpy(pOut, pIn, sizeof(float) * 4); - - return pOut; -} - -kmQuaternion* kmQuaternionAdd(kmQuaternion* pOut, const kmQuaternion* pQ1, const kmQuaternion* pQ2) -{ - pOut->x = pQ1->x + pQ2->x; - pOut->y = pQ1->y + pQ2->y; - pOut->z = pQ1->z + pQ2->z; - pOut->w = pQ1->w + pQ2->w; - - return pOut; -} - -/** Adapted from the OGRE engine! - - Gets the shortest arc quaternion to rotate this vector to the destination - vector. -@remarks - If you call this with a dest vector that is close to the inverse - of this vector, we will rotate 180 degrees around the 'fallbackAxis' - (if specified, or a generated axis if not) since in this case - ANY axis of rotation is valid. -*/ - -kmQuaternion* kmQuaternionRotationBetweenVec3(kmQuaternion* pOut, const kmVec3* vec1, const kmVec3* vec2, const kmVec3* fallback) { - - kmVec3 v1, v2; - kmScalar a; - - kmVec3Assign(&v1, vec1); - kmVec3Assign(&v2, vec2); - - kmVec3Normalize(&v1, &v1); - kmVec3Normalize(&v2, &v2); - - a = kmVec3Dot(&v1, &v2); - - if (a >= 1.0) { - kmQuaternionIdentity(pOut); - return pOut; - } - - if (a < (1e-6f - 1.0f)) { - if (fabs(kmVec3LengthSq(fallback)) < kmEpsilon) { - kmQuaternionRotationAxis(pOut, fallback, kmPI); - } else { - kmVec3 axis; - kmVec3 X; - X.x = 1.0; - X.y = 0.0; - X.z = 0.0; - - - kmVec3Cross(&axis, &X, vec1); - - //If axis is zero - if (fabs(kmVec3LengthSq(&axis)) < kmEpsilon) { - kmVec3 Y; - Y.x = 0.0; - Y.y = 1.0; - Y.z = 0.0; - - kmVec3Cross(&axis, &Y, vec1); - } - - kmVec3Normalize(&axis, &axis); - - kmQuaternionRotationAxis(pOut, &axis, kmPI); - } - } else { - kmScalar s = sqrtf((1+a) * 2); - kmScalar invs = 1 / s; - - kmVec3 c; - kmVec3Cross(&c, &v1, &v2); - - pOut->x = c.x * invs; - pOut->y = c.y * invs; - pOut->z = c.z * invs; - pOut->w = s * 0.5f; - - kmQuaternionNormalize(pOut, pOut); - } - - return pOut; - -} - -kmVec3* kmQuaternionMultiplyVec3(kmVec3* pOut, const kmQuaternion* q, const kmVec3* v) { - kmVec3 uv, uuv, qvec; - - qvec.x = q->x; - qvec.y = q->y; - qvec.z = q->z; - - kmVec3Cross(&uv, &qvec, v); - kmVec3Cross(&uuv, &qvec, &uv); - - kmVec3Scale(&uv, &uv, (2.0f * q->w)); - kmVec3Scale(&uuv, &uuv, 2.0f); - - kmVec3Add(pOut, v, &uv); - kmVec3Add(pOut, pOut, &uuv); - - return pOut; -} - diff --git a/Example/libs/kazmath/src/ray2.c b/Example/libs/kazmath/src/ray2.c deleted file mode 100644 index 514752f..0000000 --- a/Example/libs/kazmath/src/ray2.c +++ /dev/null @@ -1,184 +0,0 @@ -#include -#include -#include "kazmath/ray2.h" - -void kmRay2Fill(kmRay2* ray, kmScalar px, kmScalar py, kmScalar vx, kmScalar vy) { - ray->start.x = px; - ray->start.y = py; - ray->dir.x = vx; - ray->dir.y = vy; -} - -kmBool kmRay2IntersectLineSegment(const kmRay2* ray, const kmVec2* p1, const kmVec2* p2, kmVec2* intersection) { - - float x1 = ray->start.x; - float y1 = ray->start.y; - float x2 = ray->start.x + ray->dir.x; - float y2 = ray->start.y + ray->dir.y; - float x3 = p1->x; - float y3 = p1->y; - float x4 = p2->x; - float y4 = p2->y; - - float denom = (y4 -y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); - - //If denom is zero, the lines are parallel - if(denom > -kmEpsilon && denom < kmEpsilon) { - return KM_FALSE; - } - - float ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom; -// float ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom; - - float x = x1 + ua * (x2 - x1); - float y = y1 + ua * (y2 - y1); - - if(x < min(p1->x, p2->x) - kmEpsilon || - x > max(p1->x, p2->x) + kmEpsilon || - y < min(p1->y, p2->y) - kmEpsilon || - y > max(p1->y, p2->y) + kmEpsilon) { - //Outside of line - //printf("Outside of line, %f %f (%f %f)(%f, %f)\n", x, y, p1->x, p1->y, p2->x, p2->y); - return KM_FALSE; - } - - if(x < min(x1, x2) - kmEpsilon || - x > max(x1, x2) + kmEpsilon || - y < min(y1, y2) - kmEpsilon || - y > max(y1, y2) + kmEpsilon) { - //printf("Outside of ray, %f %f (%f %f)(%f, %f)\n", x, y, x1, y1, x2, y2); - return KM_FALSE; - } - - intersection->x = x; - intersection->y = y; - - return KM_TRUE; - - -/* - kmScalar A1, B1, C1; - kmScalar A2, B2, C2; - - A1 = ray->dir.y; - B1 = ray->dir.x; - C1 = A1 * ray->start.x + B1 * ray->start.y; - - A2 = p2->y - p1->y; - B2 = p2->x - p1->x; - C2 = A2 * p1->x + B2 * p1->y; - - double det = (A1 * B2) - (A2 * B1); - if(det == 0) { - printf("Parallel\n"); - return KM_FALSE; - } - - double x = (B2*C1 - B1*C2) / det; - double y = (A1*C2 - A2*C1) / det; - - if(x < min(p1->x, p2->x) - kmEpsilon || - x > max(p1->x, p2->x) + kmEpsilon || - y < min(p1->y, p2->y) - kmEpsilon || - y > max(p1->y, p2->y) + kmEpsilon) { - //Outside of line - printf("Outside of line, %f %f (%f %f)(%f, %f)\n", x, y, p1->x, p1->y, p2->x, p2->y); - return KM_FALSE; - } - - kmScalar x1 = ray->start.x; - kmScalar x2 = ray->start.x + ray->dir.x; - - kmScalar y1 = ray->start.y; - kmScalar y2 = ray->start.y + ray->dir.y; - - if(x < min(x1, x2) - kmEpsilon || - x > max(x1, x2) + kmEpsilon || - y < min(y1, y2) - kmEpsilon || - y > max(y1, y2) + kmEpsilon) { - printf("Outside of ray, %f %f (%f %f)(%f, %f)\n", x, y, x1, y1, x2, y2); - return KM_FALSE; - } - - intersection->x = x; - intersection->y = y; - - return KM_TRUE;*/ -} - -void calculate_line_normal(kmVec2 p1, kmVec2 p2, kmVec2* normal_out) { - kmVec2 tmp; - kmVec2Subtract(&tmp, &p2, &p1); //Get direction vector - - normal_out->x = -tmp.y; - normal_out->y = tmp.x; - kmVec2Normalize(normal_out, normal_out); - - //TODO: should check that the normal is pointing out of the triangle -} - -kmBool kmRay2IntersectTriangle(const kmRay2* ray, const kmVec2* p1, const kmVec2* p2, const kmVec2* p3, kmVec2* intersection, kmVec2* normal_out) { - kmVec2 intersect; - kmVec2 final_intersect; - kmVec2 normal; - kmScalar distance = 10000.0f; - kmBool intersected = KM_FALSE; - - if(kmRay2IntersectLineSegment(ray, p1, p2, &intersect)) { - intersected = KM_TRUE; - - kmVec2 tmp; - kmScalar this_distance = kmVec2Length(kmVec2Subtract(&tmp, &intersect, &ray->start)); - if(this_distance < distance) { - final_intersect.x = intersect.x; - final_intersect.y = intersect.y; - distance = this_distance; - - calculate_line_normal(*p1, *p2, &normal); - } - } - - if(kmRay2IntersectLineSegment(ray, p2, p3, &intersect)) { - intersected = KM_TRUE; - - kmVec2 tmp; - kmScalar this_distance = kmVec2Length(kmVec2Subtract(&tmp, &intersect, &ray->start)); - if(this_distance < distance) { - final_intersect.x = intersect.x; - final_intersect.y = intersect.y; - distance = this_distance; - - calculate_line_normal(*p2, *p3, &normal); - } - } - - if(kmRay2IntersectLineSegment(ray, p3, p1, &intersect)) { - intersected = KM_TRUE; - - kmVec2 tmp; - kmScalar this_distance = kmVec2Length(kmVec2Subtract(&tmp, &intersect, &ray->start)); - if(this_distance < distance) { - final_intersect.x = intersect.x; - final_intersect.y = intersect.y; - distance = this_distance; - - calculate_line_normal(*p3, *p1, &normal); - } - } - - if(intersected) { - intersection->x = final_intersect.x; - intersection->y = final_intersect.y; - if(normal_out) { - normal_out->x = normal.x; - normal_out->y = normal.y; - } - } - - return intersected; -} - -kmBool kmRay2IntersectCircle(const kmRay2* ray, const kmVec2 centre, const kmScalar radius, kmVec2* intersection) { - assert(0 && "Not implemented"); - return 0; -} diff --git a/Example/libs/kazmath/src/utility.c b/Example/libs/kazmath/src/utility.c deleted file mode 100644 index 1d89aca..0000000 --- a/Example/libs/kazmath/src/utility.c +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include "kazmath/utility.h" - -/** - * Returns the square of s (e.g. s*s) - */ -kmScalar kmSQR(kmScalar s) { - return s*s; -} - -/** - * Returns degrees as radians. - */ -kmScalar kmDegreesToRadians(kmScalar degrees) { - return degrees * kmPIOver180; -} - -/** - * Returns radians as degrees - */ -kmScalar kmRadiansToDegrees(kmScalar radians) { - return radians * kmPIUnder180; -} - -kmScalar min(kmScalar lhs, kmScalar rhs) { - return (lhs < rhs)? lhs : rhs; -} - -kmScalar max(kmScalar lhs, kmScalar rhs) { - return (lhs > rhs)? lhs : rhs; -} - -kmBool kmAlmostEqual(kmScalar lhs, kmScalar rhs) { - return (lhs + kmEpsilon > rhs && lhs - kmEpsilon < rhs); -} diff --git a/Example/libs/kazmath/src/vec2.c b/Example/libs/kazmath/src/vec2.c deleted file mode 100644 index 1a9511e..0000000 --- a/Example/libs/kazmath/src/vec2.c +++ /dev/null @@ -1,118 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include -#include - -#include "kazmath/mat3.h" -#include "kazmath/vec2.h" -#include "kazmath/utility.h" - -kmVec2* kmVec2Fill(kmVec2* pOut, kmScalar x, kmScalar y) -{ - pOut->x = x; - pOut->y = y; - return pOut; -} - -kmScalar kmVec2Length(const kmVec2* pIn) -{ - return sqrtf(kmSQR(pIn->x) + kmSQR(pIn->y)); -} - -kmScalar kmVec2LengthSq(const kmVec2* pIn) -{ - return kmSQR(pIn->x) + kmSQR(pIn->y); -} - -kmVec2* kmVec2Normalize(kmVec2* pOut, const kmVec2* pIn) -{ - kmScalar l = 1.0f / kmVec2Length(pIn); - - kmVec2 v; - v.x = pIn->x * l; - v.y = pIn->y * l; - - pOut->x = v.x; - pOut->y = v.y; - - return pOut; -} - -kmVec2* kmVec2Add(kmVec2* pOut, const kmVec2* pV1, const kmVec2* pV2) -{ - pOut->x = pV1->x + pV2->x; - pOut->y = pV1->y + pV2->y; - - return pOut; -} - -kmScalar kmVec2Dot(const kmVec2* pV1, const kmVec2* pV2) -{ - return pV1->x * pV2->x + pV1->y * pV2->y; -} - -kmVec2* kmVec2Subtract(kmVec2* pOut, const kmVec2* pV1, const kmVec2* pV2) -{ - pOut->x = pV1->x - pV2->x; - pOut->y = pV1->y - pV2->y; - - return pOut; -} - -kmVec2* kmVec2Transform(kmVec2* pOut, const kmVec2* pV, const kmMat3* pM) -{ - kmVec2 v; - - v.x = pV->x * pM->mat[0] + pV->y * pM->mat[3] + pM->mat[6]; - v.y = pV->x * pM->mat[1] + pV->y * pM->mat[4] + pM->mat[7]; - - pOut->x = v.x; - pOut->y = v.y; - - return pOut; -} - -kmVec2* kmVec2TransformCoord(kmVec2* pOut, const kmVec2* pV, const kmMat3* pM) -{ - assert(0); - return NULL; -} - -kmVec2* kmVec2Scale(kmVec2* pOut, const kmVec2* pIn, const kmScalar s) -{ - pOut->x = pIn->x * s; - pOut->y = pIn->y * s; - - return pOut; -} - -int kmVec2AreEqual(const kmVec2* p1, const kmVec2* p2) -{ - return ( - (p1->x < p2->x + kmEpsilon && p1->x > p2->x - kmEpsilon) && - (p1->y < p2->y + kmEpsilon && p1->y > p2->y - kmEpsilon) - ); -} diff --git a/Example/libs/kazmath/src/vec3.c b/Example/libs/kazmath/src/vec3.c deleted file mode 100644 index c520900..0000000 --- a/Example/libs/kazmath/src/vec3.c +++ /dev/null @@ -1,310 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * @file vec3.c - */ - -#include -#include - -#include "kazmath/utility.h" -#include "kazmath/vec4.h" -#include "kazmath/mat4.h" -#include "kazmath/vec3.h" - -/** - * Fill a kmVec3 structure using 3 floating point values - * The result is store in pOut, returns pOut - */ -kmVec3* kmVec3Fill(kmVec3* pOut, kmScalar x, kmScalar y, kmScalar z) -{ - pOut->x = x; - pOut->y = y; - pOut->z = z; - return pOut; -} - - -/** - * Returns the length of the vector - */ -kmScalar kmVec3Length(const kmVec3* pIn) -{ - return sqrtf(kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z)); -} - -/** - * Returns the square of the length of the vector - */ -kmScalar kmVec3LengthSq(const kmVec3* pIn) -{ - return kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z); -} - - /** - * Returns the vector passed in set to unit length - * the result is stored in pOut. - */ -kmVec3* kmVec3Normalize(kmVec3* pOut, const kmVec3* pIn) -{ - kmScalar l = 1.0f / kmVec3Length(pIn); - - kmVec3 v; - v.x = pIn->x * l; - v.y = pIn->y * l; - v.z = pIn->z * l; - - pOut->x = v.x; - pOut->y = v.y; - pOut->z = v.z; - - return pOut; -} - -/** - * Returns a vector perpendicular to 2 other vectors. - * The result is stored in pOut. - */ -kmVec3* kmVec3Cross(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2) -{ - - kmVec3 v; - - v.x = (pV1->y * pV2->z) - (pV1->z * pV2->y); - v.y = (pV1->z * pV2->x) - (pV1->x * pV2->z); - v.z = (pV1->x * pV2->y) - (pV1->y * pV2->x); - - pOut->x = v.x; - pOut->y = v.y; - pOut->z = v.z; - - return pOut; -} - -/** - * Returns the cosine of the angle between 2 vectors - */ -kmScalar kmVec3Dot(const kmVec3* pV1, const kmVec3* pV2) -{ - return ( pV1->x * pV2->x - + pV1->y * pV2->y - + pV1->z * pV2->z ); -} - -/** - * Adds 2 vectors and returns the result. The resulting - * vector is stored in pOut. - */ -kmVec3* kmVec3Add(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2) -{ - kmVec3 v; - - v.x = pV1->x + pV2->x; - v.y = pV1->y + pV2->y; - v.z = pV1->z + pV2->z; - - pOut->x = v.x; - pOut->y = v.y; - pOut->z = v.z; - - return pOut; -} - - /** - * Subtracts 2 vectors and returns the result. The result is stored in - * pOut. - */ -kmVec3* kmVec3Subtract(kmVec3* pOut, const kmVec3* pV1, const kmVec3* pV2) -{ - kmVec3 v; - - v.x = pV1->x - pV2->x; - v.y = pV1->y - pV2->y; - v.z = pV1->z - pV2->z; - - pOut->x = v.x; - pOut->y = v.y; - pOut->z = v.z; - - return pOut; -} - - /** - * Transforms vector (x, y, z, 1) by a given matrix. The result - * is stored in pOut. pOut is returned. - */ -kmVec3* kmVec3Transform(kmVec3* pOut, const kmVec3* pV, const kmMat4* pM) -{ - /* - a = (Vx, Vy, Vz, 1) - b = (a×M)T - Out = (bx, by, bz) - */ - - kmVec3 v; - - v.x = pV->x * pM->mat[0] + pV->y * pM->mat[4] + pV->z * pM->mat[8] + pM->mat[12]; - v.y = pV->x * pM->mat[1] + pV->y * pM->mat[5] + pV->z * pM->mat[9] + pM->mat[13]; - v.z = pV->x * pM->mat[2] + pV->y * pM->mat[6] + pV->z * pM->mat[10] + pM->mat[14]; - - pOut->x = v.x; - pOut->y = v.y; - pOut->z = v.z; - - return pOut; -} - -kmVec3* kmVec3InverseTransform(kmVec3* pOut, const kmVec3* pVect, const kmMat4* pM) -{ - kmVec3 v1, v2; - - v1.x = pVect->x - pM->mat[12]; - v1.y = pVect->y - pM->mat[13]; - v1.z = pVect->z - pM->mat[14]; - - v2.x = v1.x * pM->mat[0] + v1.y * pM->mat[1] + v1.z * pM->mat[2]; - v2.y = v1.x * pM->mat[4] + v1.y * pM->mat[5] + v1.z * pM->mat[6]; - v2.z = v1.x * pM->mat[8] + v1.y * pM->mat[9] + v1.z * pM->mat[10]; - - pOut->x = v2.x; - pOut->y = v2.y; - pOut->z = v2.z; - - return pOut; -} - -kmVec3* kmVec3InverseTransformNormal(kmVec3* pOut, const kmVec3* pVect, const kmMat4* pM) -{ - kmVec3 v; - - v.x = pVect->x * pM->mat[0] + pVect->y * pM->mat[1] + pVect->z * pM->mat[2]; - v.y = pVect->x * pM->mat[4] + pVect->y * pM->mat[5] + pVect->z * pM->mat[6]; - v.z = pVect->x * pM->mat[8] + pVect->y * pM->mat[9] + pVect->z * pM->mat[10]; - - pOut->x = v.x; - pOut->y = v.y; - pOut->z = v.z; - - return pOut; -} - - -kmVec3* kmVec3TransformCoord(kmVec3* pOut, const kmVec3* pV, const kmMat4* pM) -{ - /* - a = (Vx, Vy, Vz, 1) - b = (a×M)T - Out = 1⁄bw(bx, by, bz) - */ - - kmVec4 v; - kmVec4 inV; - kmVec4Fill(&inV, pV->x, pV->y, pV->z, 1.0); - - kmVec4Transform(&v, &inV,pM); - - pOut->x = v.x / v.w; - pOut->y = v.y / v.w; - pOut->z = v.z / v.w; - - return pOut; -} - -kmVec3* kmVec3TransformNormal(kmVec3* pOut, const kmVec3* pV, const kmMat4* pM) -{ -/* - a = (Vx, Vy, Vz, 0) - b = (a×M)T - Out = (bx, by, bz) -*/ - //Omits the translation, only scaling + rotating - kmVec3 v; - - v.x = pV->x * pM->mat[0] + pV->y * pM->mat[4] + pV->z * pM->mat[8]; - v.y = pV->x * pM->mat[1] + pV->y * pM->mat[5] + pV->z * pM->mat[9]; - v.z = pV->x * pM->mat[2] + pV->y * pM->mat[6] + pV->z * pM->mat[10]; - - pOut->x = v.x; - pOut->y = v.y; - pOut->z = v.z; - - return pOut; - -} - -/** - * Scales a vector to length s. Does not normalize first, - * you should do that! - */ -kmVec3* kmVec3Scale(kmVec3* pOut, const kmVec3* pIn, const kmScalar s) -{ - pOut->x = pIn->x * s; - pOut->y = pIn->y * s; - pOut->z = pIn->z * s; - - return pOut; -} - -/** - * Returns KM_TRUE if the 2 vectors are approximately equal - */ -int kmVec3AreEqual(const kmVec3* p1, const kmVec3* p2) -{ - if ((p1->x < (p2->x + kmEpsilon) && p1->x > (p2->x - kmEpsilon)) && - (p1->y < (p2->y + kmEpsilon) && p1->y > (p2->y - kmEpsilon)) && - (p1->z < (p2->z + kmEpsilon) && p1->z > (p2->z - kmEpsilon))) { - return 1; - } - - return 0; -} - -/** - * Assigns pIn to pOut. Returns pOut. If pIn and pOut are the same - * then nothing happens but pOut is still returned - */ -kmVec3* kmVec3Assign(kmVec3* pOut, const kmVec3* pIn) { - if (pOut == pIn) { - return pOut; - } - - pOut->x = pIn->x; - pOut->y = pIn->y; - pOut->z = pIn->z; - - return pOut; -} - -/** - * Sets all the elements of pOut to zero. Returns pOut. - */ -kmVec3* kmVec3Zero(kmVec3* pOut) { - pOut->x = 0.0f; - pOut->y = 0.0f; - pOut->z = 0.0f; - - return pOut; -} diff --git a/Example/libs/kazmath/src/vec4.c b/Example/libs/kazmath/src/vec4.c deleted file mode 100644 index 4842e46..0000000 --- a/Example/libs/kazmath/src/vec4.c +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright (c) 2008, Luke Benstead. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - - -#include -#include - -#include "kazmath/utility.h" -#include "kazmath/vec4.h" -#include "kazmath/mat4.h" - - -kmVec4* kmVec4Fill(kmVec4* pOut, kmScalar x, kmScalar y, kmScalar z, kmScalar w) -{ - pOut->x = x; - pOut->y = y; - pOut->z = z; - pOut->w = w; - return pOut; -} - - -/// Adds 2 4D vectors together. The result is store in pOut, the function returns -/// pOut so that it can be nested in another function. -kmVec4* kmVec4Add(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2) { - pOut->x = pV1->x + pV2->x; - pOut->y = pV1->y + pV2->y; - pOut->z = pV1->z + pV2->z; - pOut->w = pV1->w + pV2->w; - - return pOut; -} - -/// Returns the dot product of 2 4D vectors -kmScalar kmVec4Dot(const kmVec4* pV1, const kmVec4* pV2) { - return ( pV1->x * pV2->x - + pV1->y * pV2->y - + pV1->z * pV2->z - + pV1->w * pV2->w ); -} - -/// Returns the length of a 4D vector, this uses a sqrt so if the squared length will do use -/// kmVec4LengthSq -kmScalar kmVec4Length(const kmVec4* pIn) { - return sqrtf(kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z) + kmSQR(pIn->w)); -} - -/// Returns the length of the 4D vector squared. -kmScalar kmVec4LengthSq(const kmVec4* pIn) { - return kmSQR(pIn->x) + kmSQR(pIn->y) + kmSQR(pIn->z) + kmSQR(pIn->w); -} - -/// Returns the interpolation of 2 4D vectors based on t. Currently not implemented! -kmVec4* kmVec4Lerp(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2, kmScalar t) { - assert(0); - return pOut; -} - -/// Normalizes a 4D vector. The result is stored in pOut. pOut is returned -kmVec4* kmVec4Normalize(kmVec4* pOut, const kmVec4* pIn) { - kmScalar l = 1.0f / kmVec4Length(pIn); - - pOut->x *= l; - pOut->y *= l; - pOut->z *= l; - pOut->w *= l; - - return pOut; -} - -/// Scales a vector to the required length. This performs a Normalize before multiplying by S. -kmVec4* kmVec4Scale(kmVec4* pOut, const kmVec4* pIn, const kmScalar s) { - kmVec4Normalize(pOut, pIn); - - pOut->x *= s; - pOut->y *= s; - pOut->z *= s; - pOut->w *= s; - return pOut; -} - -/// Subtracts one 4D pV2 from pV1. The result is stored in pOut. pOut is returned -kmVec4* kmVec4Subtract(kmVec4* pOut, const kmVec4* pV1, const kmVec4* pV2) { - pOut->x = pV1->x - pV2->x; - pOut->y = pV1->y - pV2->y; - pOut->z = pV1->z - pV2->z; - pOut->w = pV1->w - pV2->w; - - return pOut; -} - -/// Transforms a 4D vector by a matrix, the result is stored in pOut, and pOut is returned. -kmVec4* kmVec4Transform(kmVec4* pOut, const kmVec4* pV, const kmMat4* pM) { - pOut->x = pV->x * pM->mat[0] + pV->y * pM->mat[4] + pV->z * pM->mat[8] + pV->w * pM->mat[12]; - pOut->y = pV->x * pM->mat[1] + pV->y * pM->mat[5] + pV->z * pM->mat[9] + pV->w * pM->mat[13]; - pOut->z = pV->x * pM->mat[2] + pV->y * pM->mat[6] + pV->z * pM->mat[10] + pV->w * pM->mat[14]; - pOut->w = pV->x * pM->mat[3] + pV->y * pM->mat[7] + pV->z * pM->mat[11] + pV->w * pM->mat[15]; - return pOut; -} - -/// Loops through an input array transforming each vec4 by the matrix. -kmVec4* kmVec4TransformArray(kmVec4* pOut, unsigned int outStride, - const kmVec4* pV, unsigned int vStride, const kmMat4* pM, unsigned int count) { - unsigned int i = 0; - //Go through all of the vectors - while (i < count) { - const kmVec4* in = pV + (i * vStride); //Get a pointer to the current input - kmVec4* out = pOut + (i * outStride); //and the current output - kmVec4Transform(out, in, pM); //Perform transform on it - ++i; - } - - return pOut; -} - -int kmVec4AreEqual(const kmVec4* p1, const kmVec4* p2) { - return ( - (p1->x < p2->x + kmEpsilon && p1->x > p2->x - kmEpsilon) && - (p1->y < p2->y + kmEpsilon && p1->y > p2->y - kmEpsilon) && - (p1->z < p2->z + kmEpsilon && p1->z > p2->z - kmEpsilon) && - (p1->w < p2->w + kmEpsilon && p1->w > p2->w - kmEpsilon) - ); -} - -kmVec4* kmVec4Assign(kmVec4* pOut, const kmVec4* pIn) { - assert(pOut != pIn); - - memcpy(pOut, pIn, sizeof(float) * 4); - - return pOut; -} - diff --git a/Example/main.m b/Example/main.m index 125cdc9..c20abed 100644 --- a/Example/main.m +++ b/Example/main.m @@ -9,8 +9,8 @@ #import int main(int argc, char *argv[]) { - NSAutoreleasePool *pool = [NSAutoreleasePool new]; - int retVal = UIApplicationMain(argc, argv, nil, @"ExampleAppDelegate"); - [pool release]; - return retVal; + @autoreleasepool { + int retVal = UIApplicationMain(argc, argv, nil, @"ExampleAppDelegate"); + return retVal; + } } diff --git a/TouchTrailLayer.m b/TouchTrailLayer.m index 4ca654f..ac97acb 100644 --- a/TouchTrailLayer.m +++ b/TouchTrailLayer.m @@ -52,7 +52,7 @@ - (void) ccTouchesBegan:(NSSet *) touches withEvent:(UIEvent *) event{ int rand = arc4random() % 3 + 1; w.texture = [[CCTextureCache sharedTextureCache] addImage:[NSString stringWithFormat:@"streak%d.png",rand]]; - CFDictionaryAddValue(map,touch,w); + CFDictionaryAddValue(map,(__bridge const void *)(touch),(__bridge void*)w); [self addChild:w]; CGPoint pos = [touch locationInView:touch.view]; @@ -63,7 +63,7 @@ - (void) ccTouchesBegan:(NSSet *) touches withEvent:(UIEvent *) event{ - (void) ccTouchesMoved:(NSSet *) touches withEvent:(UIEvent *) event{ for (UITouch *touch in touches) { - CCBlade *w = (CCBlade *)CFDictionaryGetValue(map, touch); + CCBlade *w = (CCBlade *)CFDictionaryGetValue(map, (__bridge const void *)(touch)); CGPoint pos = [touch locationInView:touch.view]; pos = [[CCDirector sharedDirector] convertToGL:pos]; [w push:pos]; @@ -72,14 +72,13 @@ - (void) ccTouchesMoved:(NSSet *) touches withEvent:(UIEvent *) event{ - (void) ccTouchesEnded:(NSSet *) touches withEvent:(UIEvent *) event{ for (UITouch *touch in touches) { - CCBlade *w = (CCBlade *)CFDictionaryGetValue(map, touch); + CCBlade *w = (CCBlade *)CFDictionaryGetValue(map, (__bridge const void *)(touch)); [w finish]; - CFDictionaryRemoveValue(map,touch); + CFDictionaryRemoveValue(map,(__bridge const void *)(touch)); } } - (void) dealloc{ CFRelease(map); - [super dealloc]; } @end From e09ff705bb67e4bca240c9d0ac6128388ee60770 Mon Sep 17 00:00:00 2001 From: Panajev Date: Sun, 21 Oct 2012 12:07:51 +0200 Subject: [PATCH 5/6] (x): merge with item pop patch fork. --- CCBlade.h | 24 ++++++++++------ CCBlade.m | 86 +++++++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 84 insertions(+), 26 deletions(-) diff --git a/CCBlade.h b/CCBlade.h index 4b1a073..8e637cc 100644 --- a/CCBlade.h +++ b/CCBlade.h @@ -1,5 +1,5 @@ /* - * CCBlade for iPhone + * cocos2d+ext for iPhone * * Copyright (c) 2011 - Ngo Duc Hiep * @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,8 +26,9 @@ #import #import "cocos2d.h" -#define USE_LAGRANGE 1 -#define USE_STL_LIST 0 +#define USE_LAGRANGE 1 +#define USE_STL_LIST 0 +#define USE_UPDATE_FOR_POP 1 inline float fangle(CGPoint vect); inline float lagrange1(CGPoint p1, CGPoint p2, float x); @@ -41,10 +42,14 @@ inline void f1(CGPoint p1, CGPoint p2, float d, CGPoint *o1, CGPoint *o2); int count; CGPoint *vertices; CGPoint *coordinates; - CCTexture2D *texture; + BOOL reset; + CCTexture2D *_texture; float width; - BOOL finish; - BOOL willPop; + BOOL _finish; + BOOL _willPop; + + float timeSinceLastPop; + float popTimeInterval; } @property (readonly) unsigned int pointLimit; @property(strong) CCTexture2D *texture; @@ -55,5 +60,8 @@ inline void f1(CGPoint p1, CGPoint p2, float d, CGPoint *o1, CGPoint *o2); - (id) initWithMaximumPoint:(int) limit; - (void) push:(CGPoint) v; - (void) pop:(int) n; +- (void) clear; +- (void) reset; +- (void) dim:(BOOL) dim; - (void) finish; @end diff --git a/CCBlade.m b/CCBlade.m index 2fe3cd5..73d196d 100644 --- a/CCBlade.m +++ b/CCBlade.m @@ -1,5 +1,5 @@ /* - * CCBlade for iPhone + * cocos2d+ext for iPhone * * Copyright (c) 2011 - Ngo Duc Hiep * @@ -9,10 +9,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -69,12 +69,11 @@ + (id) bladeWithMaximumPoint:(int) limit{ return [[self alloc] initWithMaximumPoint:limit]; } +#define POP_TIME_INTERVAL 1./60. + - (id) initWithMaximumPoint:(int) limit{ self = [super init]; - // shader program - self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTexture]; - pointLimit = limit; self.width = 5; @@ -82,10 +81,17 @@ - (id) initWithMaximumPoint:(int) limit{ coordinates = (CGPoint *)calloc(2*limit+5, sizeof(coordinates[0])); CGPointSet(coordinates+0, 0.00, 0.5); - finish = NO; + reset = NO; path = [[NSMutableArray alloc] init]; +#if USE_UPDATE_FOR_POP + popTimeInterval = POP_TIME_INTERVAL; + + timeSinceLastPop = 0; + [self scheduleUpdateWithPriority:0]; +#endif + return self; } @@ -113,7 +119,7 @@ - (void) populateVertices{ it = [[path objectAtIndex:i+1] CGPointValue]; } - CGPointSet(coordinates+1, 0.25, 1.0); + CGPointSet(coordinates+1, 0.25, 1.0); CGPointSet(coordinates+2, 0.25, 0.0); vertices[2*[path count]-3] = it; @@ -134,8 +140,10 @@ - (void) setWidth:(float)width_{ #define DISTANCE_TO_INTERPOLATE 10 -- (void) push:(CGPoint) v{ - if (finish) { +- (void) push:(CGPoint) v{ + _willPop = NO; + + if (reset) { return; } if (CC_CONTENT_SCALE_FACTOR() != 1.0f) { @@ -149,7 +157,6 @@ - (void) push:(CGPoint) v{ return; } - willPop = NO; CGPoint first = [[path objectAtIndex:0] CGPointValue]; if (ccpDistance(v, first) < DISTANCE_TO_INTERPOLATE) { [path insertObject:[NSValue valueWithCGPoint:v] atIndex:0]; @@ -190,19 +197,62 @@ - (void) pop:(int) n{ - (void) clear{ [path removeAllObjects]; + reset = NO; + if (_finish) + [self removeFromParentAndCleanup:YES]; +} + +- (void) reset{ + reset = TRUE; +} + +- (void) dim:(BOOL) dim{ + reset = dim; +} + +- (void) update:(ccTime)dt { + + timeSinceLastPop += dt; -} + float precision = 1./60.; + float roundedTimeSinceLastPop = precision * roundf(timeSinceLastPop/precision); // helps because fps flucuate around 1./60. + + int numberOfPops = (int) (roundedTimeSinceLastPop/popTimeInterval) ; + timeSinceLastPop = timeSinceLastPop - numberOfPops * popTimeInterval; + + for (int pop = 0; pop < numberOfPops; pop++) { + + if ((reset && [path count] > 0) || (self.autoDim && _willPop)) { + [self pop:1]; + if ([path count] < 3) { + [self clear]; + if (_finish) { + return; // if we continue self will have been deallocated + } + } + } + + } +} - (void) draw{ - if (finish || (self.autoDim && willPop)) { + +#if !USE_UPDATE_FOR_POP + if ((reset && [path count] > 0) || (self.autoDim && _willPop)) { [self pop:1]; + if ([path count] < 3) { + [self clear]; + if (_finish) { + return; // if we continue self will have been deallocated + } + } } +#endif + + if(path == nil) + return; if ([path count] < 3) { - if (finish) { - [self removeFromParentAndCleanup:NO]; - } - return; } @@ -224,7 +274,7 @@ - (void) draw{ - (void) finish { - finish = YES; + _finish = YES; } @end From 2eaf95c43aa42da3c8f18d96278d7330d6114371 Mon Sep 17 00:00:00 2001 From: Panajev Date: Sun, 21 Oct 2012 12:28:50 +0200 Subject: [PATCH 6/6] (x): modernized Objective-C code. --- CCBlade.h | 5 +- CCBlade.m | 85 +++++++++--------- Example/Example.xcodeproj/project.pbxproj | 20 ++--- .../UserInterfaceState.xcuserstate | Bin 32623 -> 15254 bytes Example/Resources/Info.plist | 5 ++ Example/libs/README | 1 - 6 files changed, 54 insertions(+), 62 deletions(-) delete mode 100644 Example/libs/README diff --git a/CCBlade.h b/CCBlade.h index 8e637cc..5e5eafd 100644 --- a/CCBlade.h +++ b/CCBlade.h @@ -37,14 +37,10 @@ inline void CGPointSet(CGPoint *v, float x, float y); inline void f1(CGPoint p1, CGPoint p2, float d, CGPoint *o1, CGPoint *o2); @interface CCBlade : CCNode { - NSMutableArray *path; - unsigned int pointLimit; int count; CGPoint *vertices; CGPoint *coordinates; BOOL reset; - CCTexture2D *_texture; - float width; BOOL _finish; BOOL _willPop; @@ -55,6 +51,7 @@ inline void f1(CGPoint p1, CGPoint p2, float d, CGPoint *o1, CGPoint *o2); @property(strong) CCTexture2D *texture; @property(nonatomic) float width; @property (nonatomic) BOOL autoDim; +@property(nonatomic,strong)NSMutableArray *path; + (id) bladeWithMaximumPoint:(int) limit; - (id) initWithMaximumPoint:(int) limit; diff --git a/CCBlade.m b/CCBlade.m index 73d196d..804b0d5 100644 --- a/CCBlade.m +++ b/CCBlade.m @@ -60,10 +60,6 @@ inline void CGPointSet(CGPoint *v, float x, float y){ } @implementation CCBlade -@synthesize texture = _texture; -@synthesize pointLimit; -@synthesize width; -@synthesize autoDim; + (id) bladeWithMaximumPoint:(int) limit{ return [[self alloc] initWithMaximumPoint:limit]; @@ -74,8 +70,8 @@ + (id) bladeWithMaximumPoint:(int) limit{ - (id) initWithMaximumPoint:(int) limit{ self = [super init]; - pointLimit = limit; - self.width = 5; + _pointLimit = limit; + _width = 5; vertices = (CGPoint *)calloc(2*limit+5, sizeof(vertices[0])); coordinates = (CGPoint *)calloc(2*limit+5, sizeof(coordinates[0])); @@ -83,7 +79,7 @@ - (id) initWithMaximumPoint:(int) limit{ CGPointSet(coordinates+0, 0.00, 0.5); reset = NO; - path = [[NSMutableArray alloc] init]; + _path = [[NSMutableArray alloc] init]; #if USE_UPDATE_FOR_POP popTimeInterval = POP_TIME_INTERVAL; @@ -92,6 +88,8 @@ - (id) initWithMaximumPoint:(int) limit{ [self scheduleUpdateWithPriority:0]; #endif + self.shaderProgram = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTexture]; + return self; } @@ -102,40 +100,40 @@ - (void) dealloc{ } - (void) populateVertices{ - vertices[0] = [[path objectAtIndex:0] CGPointValue]; + vertices[0] = [[_path objectAtIndex:0] CGPointValue]; CGPoint pre = vertices[0]; unsigned int i = 0; - CGPoint it = [[path objectAtIndex:1] CGPointValue]; - float dd = width / [path count]; - while (i < [path count] - 2){ - f1(pre, it, width - i * dd , vertices+2*i+1, vertices+2*i+2); + CGPoint it = [[_path objectAtIndex:1] CGPointValue]; + float dd = _width / [_path count]; + while (i < [_path count] - 2){ + f1(pre, it, _width - i * dd , vertices+2*i+1, vertices+2*i+2); CGPointSet(coordinates+2*i+1, .5, 1.0); CGPointSet(coordinates+2*i+2, .5, 0.0); i++; pre = it; - it = [[path objectAtIndex:i+1] CGPointValue]; + it = [[_path objectAtIndex:i+1] CGPointValue]; } CGPointSet(coordinates+1, 0.25, 1.0); CGPointSet(coordinates+2, 0.25, 0.0); - vertices[2*[path count]-3] = it; - CGPointSet(coordinates+2*[path count]-3, 0.75, 0.5); + vertices[2*[_path count]-3] = it; + CGPointSet(coordinates+2*[_path count]-3, 0.75, 0.5); } - (void) shift{ - int index = 2 * pointLimit - 1; + int index = 2 * _pointLimit - 1; for (int i = index; i > 3; i -= 2) { vertices[i] = vertices[i-2]; vertices[i-1] = vertices[i-3]; } } -- (void) setWidth:(float)width_{ - width = width_ ;//* CC_CONTENT_SCALE_FACTOR(); +- (void) set_width:(float)newWidth{ + _width = newWidth ;//* CC_CONTENT_SCALE_FACTOR(); } #define DISTANCE_TO_INTERPOLATE 10 @@ -146,37 +144,34 @@ - (void) push:(CGPoint) v{ if (reset) { return; } - if (CC_CONTENT_SCALE_FACTOR() != 1.0f) { - //v = ccpMult(v, CC_CONTENT_SCALE_FACTOR()); - } #if USE_LAGRANGE - if ([path count] == 0) { - [path insertObject:[NSValue valueWithCGPoint:v] atIndex:0]; + if ([_path count] == 0) { + [_path insertObject:[NSValue valueWithCGPoint:v] atIndex:0]; return; } - CGPoint first = [[path objectAtIndex:0] CGPointValue]; + CGPoint first = [[_path objectAtIndex:0] CGPointValue]; if (ccpDistance(v, first) < DISTANCE_TO_INTERPOLATE) { - [path insertObject:[NSValue valueWithCGPoint:v] atIndex:0]; - if ([path count] > pointLimit) { - [path removeLastObject]; + [_path insertObject:[NSValue valueWithCGPoint:v] atIndex:0]; + if ([_path count] > _pointLimit) { + [_path removeLastObject]; } }else{ int num = ccpDistance(v, first) / DISTANCE_TO_INTERPOLATE; CGPoint iv = ccpMult(ccpSub(v, first), (float)1./(num + 1)); for (int i = 1; i <= num + 1; i++) { - [path insertObject:[NSValue valueWithCGPoint:ccpAdd(first, ccpMult(iv, i))] atIndex:0]; + [_path insertObject:[NSValue valueWithCGPoint:ccpAdd(first, ccpMult(iv, i))] atIndex:0]; } - while ([path count] > pointLimit) { - [path removeLastObject]; + while ([_path count] > _pointLimit) { + [_path removeLastObject]; } } #else // !USE_LAGRANGE - path.push_front(v); - if (path.size() > pointLimit) { - path.pop_back(); + _path.push_front(v); + if (_path.size() > pointLimit) { + _path.pop_back(); } #endif // !USE_LAGRANGE @@ -185,18 +180,18 @@ - (void) push:(CGPoint) v{ } - (void) pop:(int) n{ - while ([path count] > 0 && n > 0) { - [path removeLastObject]; + while ([_path count] > 0 && n > 0) { + [_path removeLastObject]; n--; } - if ([path count] > 2) { + if ([_path count] > 2) { [self populateVertices]; } } - (void) clear{ - [path removeAllObjects]; + [_path removeAllObjects]; reset = NO; if (_finish) [self removeFromParentAndCleanup:YES]; @@ -222,9 +217,9 @@ - (void) update:(ccTime)dt { for (int pop = 0; pop < numberOfPops; pop++) { - if ((reset && [path count] > 0) || (self.autoDim && _willPop)) { + if ((reset && [_path count] > 0) || (self.autoDim && _willPop)) { [self pop:1]; - if ([path count] < 3) { + if ([_path count] < 3) { [self clear]; if (_finish) { return; // if we continue self will have been deallocated @@ -238,9 +233,9 @@ - (void) update:(ccTime)dt { - (void) draw{ #if !USE_UPDATE_FOR_POP - if ((reset && [path count] > 0) || (self.autoDim && _willPop)) { + if ((reset && [_path count] > 0) || (self.autoDim && _willPop)) { [self pop:1]; - if ([path count] < 3) { + if ([_path count] < 3) { [self clear]; if (_finish) { return; // if we continue self will have been deallocated @@ -249,14 +244,14 @@ - (void) draw{ } #endif - if(path == nil) + if(_path == nil) return; - if ([path count] < 3) { + if ([_path count] < 3) { return; } - willPop = YES; + _willPop = YES; CC_NODE_DRAW_SETUP(); ccGLEnableVertexAttribs(kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords); @@ -267,7 +262,7 @@ - (void) draw{ glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, coordinates); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 2*[path count]-2); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 2*[_path count]-2); CC_INCREMENT_GL_DRAWS(1); } diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index ffc4799..e6e5b3b 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 45; + objectVersion = 46; objects = { /* Begin PBXBuildFile section */ @@ -218,8 +218,11 @@ /* Begin PBXProject section */ 29B97313FDCFA39411CA2CEA /* Project object */ = { isa = PBXProject; + attributes = { + LastUpgradeCheck = 0450; + }; buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "Example" */; - compatibilityVersion = "Xcode 3.1"; + compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 1; knownRegions = ( @@ -290,7 +293,6 @@ COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_FIX_AND_CONTINUE = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = Example_Prefix.pch; @@ -298,11 +300,10 @@ GCC_VERSION = com.apple.compilers.llvm.clang.1_0; HEADER_SEARCH_PATHS = "~/Programming/SharedLibs/Cocos/include/**"; INFOPLIST_FILE = Resources/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 3.1; + IPHONEOS_DEPLOYMENT_TARGET = 5.0; LIBRARY_SEARCH_PATHS = "~/Programming/SharedLibs/Cocos/lib/**"; - ONLY_ACTIVE_ARCH = YES; + ONLY_ACTIVE_ARCH = NO; OTHER_LDFLAGS = "-lCocos"; - PREBINDING = NO; PRODUCT_NAME = CCBlade; "PROVISIONING_PROFILE[sdk=iphoneos*]" = "9FC23DC7-CB28-4671-9494-EB7B1F3ABCBE"; TARGETED_DEVICE_FAMILY = 1; @@ -318,18 +319,15 @@ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer: Duc Hiep Ngo (36Q6CZ7F37)"; COPY_PHASE_STRIP = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_ENABLE_FIX_AND_CONTINUE = NO; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = Example_Prefix.pch; GCC_TREAT_WARNINGS_AS_ERRORS = NO; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; HEADER_SEARCH_PATHS = "~/Programming/SharedLibs/Cocos/include/**"; INFOPLIST_FILE = Resources/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 3.1; + IPHONEOS_DEPLOYMENT_TARGET = 5.0; LIBRARY_SEARCH_PATHS = "~/Programming/SharedLibs/Cocos/lib/**"; - ONLY_ACTIVE_ARCH = NO; OTHER_LDFLAGS = "-lCocos"; - PREBINDING = NO; PRODUCT_NAME = CCBlade; "PROVISIONING_PROFILE[sdk=iphoneos*]" = "9FC23DC7-CB28-4671-9494-EB7B1F3ABCBE"; TARGETED_DEVICE_FAMILY = 1; @@ -356,7 +354,6 @@ GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 3.0; ONLY_ACTIVE_ARCH = YES; - PREBINDING = NO; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -376,7 +373,6 @@ GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 3.0; - PREBINDING = NO; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; diff --git a/Example/Example.xcodeproj/project.xcworkspace/xcuserdata/Panajev.xcuserdatad/UserInterfaceState.xcuserstate b/Example/Example.xcodeproj/project.xcworkspace/xcuserdata/Panajev.xcuserdatad/UserInterfaceState.xcuserstate index 1d4702233bdbddf7efe8d6702be5090a8b25b07d..0db3ca283b9f31cb3309748f484e4232ab855d77 100644 GIT binary patch delta 8483 zcmZ`-30PCd7M?AEKuB(GNJ7|hLm&wR6F@}VMR6BJSt=^h2mz@e77%wc*QIK$wl*$p z)hdgMwTnyDTGzJLwbr`S+E(qN)@rS`T5I>dNdhkK`N&6d@64GqXU_cd&p&hPAGmDd z3mQUplRchq%FX006)aiYvx~bL)PPzr0n~wsU=o-Nrhu7X5qJr_3|50i&;**nM({d# z3oHbiz;>_$>;n710dN?61U><0!DrwCxCp)n*T8k~1GohtL=Zy)B~S_jU?7x14b(y% z41;pYm<0>qa5w^vgoUsemcXaL0yq{v z4Xfcq=!O)Ea3-7u7r^J>Lihq)0$+hE;2PKrH^A567Pu9@4c~?P;30Sz9)Ty}DR>@U zfEVFc@Mm}%-hscsyYN?d5B>&!hyNmgq$mKnRftDwq(=r6hioVrwL@uWAj(36&|s8} zhM=J+2j!wXl#dEfA$k%Oqf%6ks?Y>99nC;)G#AZ7^U-4TBJ!Xm=uPw%+JrWvEodux z8*M||(GK(u+KE0u2hfM;AUcb_KwqM-(AVfPx`M8u>uz)t-9mTJFX$iiF9sN5gfS*q zft8rU;Wz?EVl%d2D^9^}aVqYLyW#G*H|~!I-~v1xkH8~wAs&T`unRwht8opUil^b} zSj2PjJUkyS#xG(IUV@k6SMaO&O}qtf#XImj_yGP8AH;{S`!qg-KgDP9xA+pijIZFI z@ojtu|3UzP1QAS>gd-}VBVj~Oj3kDbNGypX4w6KYNebyedXh}ii}WUaNMF*Ai6m z9OSGkFLTybRTr{?UM1!1DWlruEaKXD-V4xsmIq9VEaJ2oH8tfmwa#(1ev6uc&dF61 zYKyo~&tijmRHf`Rkbxi&42r-QU~L9Z0w)*^ia`l*fl^RLqp5)k)JS8fiN?~nW>5~E z0%kA-RDyA!3dB$|?Zm=Np(S(*ok}_C9A4q;A-CG)@(`ul^Rq&&Is>MHX<$0*W(IHr z3PjIF-2kCI1=K=2o&~eOY*sY~JOk#k>KWi!umC&<7J9T{gQDBh4jiOb4txrp2QM(Q z#o$HY0ZYJAunY|G4CRN)+R_A?M&oIU=MBES9lQeCHG&mjC0Ipm)J~JA@)TIZ8rFk` z;r&Wn<7&%G%U#tpk+x~cLQv%?&>p0NwP2kmTW!D%V7+IMIwsB6Y6EDX4%+64o)ylT z8dr_q)f=oZnHBb$UX1a(eh2I<;?$Y> zxtUeP6DnB@1FMRiwdGag8o;}r5us58>;`*0(?Syo*b6$b2V0j%)3To>=2^x_Zm^K1 zv%Gbn;FNFPJ_POR0cCk)qx25q2sm2ASv;cNBp*~&;%WfLK&O_15O0Cs>Nxn=Ged77 z-~{V!hTiNsp%37}NpKoi>%l47xgMOMU8vKuUg_u#&Vety#h=rz_25g|jXHC)oaN(M zf%6r(1o%eqHTVX6OS{ty+M^L%W&rt)_GGXa&0wwNoVnnJH_jhvCRMgJ{0aO9tn0zg z;5N7eegSvEuizf-MSIgev@h*P`_lpI!SCP?@F)0-&D}rXUpkOx(R^CSrfw81V$mJr zw!{ZPCE%N2FqFd(sGx)BV46*bG(irkKnzsVp)`k~GM9z1PBq27Jymk#?&4b`rzUr3 zo17@5v~8C%ya7w zPld)9KM3XkYZDv{v*8dpl)7jsEu&+aU@pvq`S1x^PRG(pI*!fJc1>5+DEK4;5Gyx_xRO@Y!zwzS zxyTCCC&3z6*8pqb1o||sqmx^WC&8(JZ-A5G6k1Jd8sIcIoz~I`3OS|dFRs>pHo`X_Y4aA`L}$`jY`|_^guB&h8{Ba}hwsoi)ajqt zUEVNu!#(sFI{!f!`{4(VxI6$qq;u&!nwM?rKI^4NdOr$}|Ci|rX8J76Gj*>L07zuU zts$I-p8;zlJOe+4XX$fvAzjo6&%w{(7xa0$mab#d+AK4LvMlAeDqO|2u9EwkoTpYM z^lNqVHT<4Y2mA(p3opUT@Cy76UZpS4#q>q$p-bpex@2)Ah8OZlJHxjr4W;27QyhwE@JSo+uObV!wS* zU-sRf<#7|;Ot-S%x9K+ay`AMWHs}jCdIAkwL$~-A3>uC`FeYtTFgdQ;MpiP?$29E4 z2R<~a#hghHd@qe@rkCOsq|gCi{|;Y)P0Egm;Ctd4}%*~H0zPZv(X&7hwi0$kE$+H_XU)- z>v13I=vlPzk%o)V^K?IbueH~_+VYC>+HzOTBfS=JZqHlA#h#5NQEtC5LrYOTux>=l z&~o$=dKtZfR-lz=6?zq|Mr-H+`XN0?57EQ)2t7)V(U0hH`te3!MvY(yT8q}9^{5$b zK(Be%0+VScXo?8!B1{%xnh5hmm@mSSZ1$LJV_K*Oqr9=>tIEgK)?^gddU}U9M@412 zN}UrbTEt`TYGo%p`Xx`^i(6-hxViQ=xO?^ z2zjsPG|#f6p(W2{|p}I)pw3)^+GGI)aX(W9TDvoSva)={foZJx?#LLnqKD z=p;IYPNOsQYkHMlr$5r4=pD8K;Qc)geeT=OK4nU4v2M)66&HOKpA~V>c~%$Kc;cfX zLLaoc`~z?aoHbn@V(FGOXhjWLoI*wm0l>~CVSmRRx%xAuY9=Q z+dhM@T3n~Jx~^qeri^X>^t#bz`>!qWU=`LprnwG>vF1O}8|>^cwOw)tZ|n4S{?;4&B|X*JItm+% zk7;hgv8?$`dW#Kbu@G&H$88>C<-keI>SubJS$!gem$t(l9%I!BcVsp+J z2jRgu8xNs>&_C&4^l$plTAYJ(aURacPtbow2t+6qVSor#UM#oq)W@hj2{CJ-+4rP2 zwRb;>M|&yByUpWb5yBQu!li6y#btPm2$2ZMeL})x@wkVn0Up5P>0A+F?~dtugnn=> zp7>v;lf9-Aujw;MKBg)f%<;pDnO16>>#QzwwX9Vijp7+hv|+ah1F7;1o(Z;i4=Q*T zo{i_=X9{Y3dn^;VA`BK`kO*ZWVYRvcA^SKyV8 z$SAxTuVYk!*P!F*7;a>Aaad%^{v!QCgc?Q|XV&5MxEXK2ui=gObrI@B7$HJ~2u&ii zh|u;Z6gGRIAi_}3%Hp}2`<#Hc`-`8@h*gqhIMI`mG4V z=r>JxAKuTl!9PT(7hyP~&&$+V*tfjIl~GaAucl^#tH!g?74F7|@o}$A{_n#H{urMC zG5DkiBSjcRIT1!vr#IPTCmgV9dP{_{B8>AoHT!*{HPRaaBc`UM zrLsd5V-^-?N>U1Yc@XDa?Ed4iKL5mjF`xg4&?>Tn67!kR5@*ey%Q_Z#sVybBZ9C?X zCE#I?gb+q`|C>z`M1uX3kto78{>ktm*Se@idSIB>Av@o-=8y0slr2`G7NMh_XhfLA z=x0Z1R5S@EQ4HK9g0M+p+hp4Y5=|J0QbpK~ncOb5!zCVLSsPDoS&fyLNdhA)Vj)%% zFT(aBOc!B?Mq(q0-UZQ7gt@*o;ki{-kwx0Vx+aoJ+L1KEEIWy?hX{L%aKL>=ARS3p zue(m9GwCA2&LU*rT^mU^(w$_8u$u_Gi!j4WKW5L#G0~obW2U%Ce=_KCZ3dHUGDL(u zMVKkVUM#iUIUh}cp&fLR?!9l$Rqn?C)F9q>PLyys!5%owd$JR#Xl;<+I~7du#1=EU9M8nGLp*j3Zsh zc=EJw$OA=~#YQc{K_VQyj?}<>GJ({w<0KO)*|buGY*abyR9WfGLkv3%F_BVUS6(~W z^LoWAZbCsY5y?#Np|_T8ls*LPt$S&g2#5Nkn@#5U193Hw+1^VLRc=*@bF$#96_Qgr zrlbqmS=@CWZIb!0t{#L?^k9M(lIIy}&{2A>p1dHk6Yl-dc*ruw&~CDXEEVA}5f(I% z<>Vz14j17FnwK}Ryrgza{uozz*_c{W_nG^BiM;>d?`}1$Yi1JYFliu-=s0d9>&SX0 zgU*PsP=urCMMiTXd{Ts?Sv(KK51!+vESa}V-E!(DoBV}EEeb?vRUi+G8?w!B#PaCV zF;V}cW5~OHi{b|YO7AY>l!I~xxF)+wGOCNmu*-z%lVmU1mzU$clAsU-0zK22HqZ`q z1l^bfQQ>HIk(-RuaTj)lo58Md`?5>if$YNeS-hMP_G|ccc0Id^UC_Rbx3de{Bls9T zj!)o|_%yqp{S1GOzr@#xf+UavcB8u6P0o=!5`{!33714lq9qndilmdIr=+iBh-9dw zNK!4SmDEWlNv24qNoGi>WTs@cWVz&J$qLCT$!bZxq*1a~vR<-5vQe@_a#V6o8YqpB z_Lmk)E2MLzE2XQXuSs`F_el3i-;;hI{ZM*HdPI6mdR}@_`nB|1>1FA6Qup`L>(U$2 zo6_F{_y8fm7LXB85-=%XLBPs@%>l;(z6(fL$X3c;m93FA%Qnllx@FsBdt^stXJuc@zLi~;eHSz-NDNvYv@&Q*(5|5Gf_@0r z20Mb2gWCqT3vM6WJ-BCZui!qx*}+qS-N74zw*;RHz97ePPOg?~HuWQ7!j)P~FpX$pBiwOffPg` zRRk(j3bjI`&?)qa2t}HrP%&2FQLI#KP;6D~Rvb}$thl7OqPVKKruaeeqvBV^-->^g zP>Gcir9#QMmAo=S8KpERt;z&tqB2#Pq3o&brR<}uR<2MsD>o^3EB7k*E8kZhQ=U|w zRi0N~QU1vxE|^nr9LICZaFUl>aQBC z8luWk<*ABQb*kB_g{oInt5x-?Mpd)wHP!2?H&ySdK2Uw6`cn0+>Xzy!)z7LsJm4`e z;RE>~Ud{`AJa6Zd_!K^s&)|FWefj?UV15Xn!{_lu{1|=$KgG>Y<7e=*_&NMsem=i~ zZ{j!eZ}Z#vo%}9-4}Xw9#vkWT@F)3;{3ZShf0e(%-{gPdZ}WHfztl3dLd~gpwN9;9 zN2sIJW_4S2M|Ed)S9N!FA9X+V0Ckpnu)13PjC!4VtNMNQ0rf%kVf9hQroE1Y|UKF ze9Z#QOPUp$Rhl)L22GP@v*vBhcFj)BF3ldd=BVbl=7i>y=8Wd7=91>J=8ER3Hb|?} zCTJ72c5RY2MVqQk)23@XYCCHOYlmoaw0YVmv<2D`+CpuS)~PMl&d@H@)@!$E4`|P8 zf6~cyMqRotL)Sx>smsz0*Ew}%y79WFbv3$ay6HN%Zk}$wZh>xzZmDj$u1V)!uiKz| zUH7JLlWwPOzwUkA0o_5}Vcn;?FLdX17j>6(S9Di(*K~h{Ny7LrU6?*BB1{O235yLg zhoy#f3F{v=IBZB*PS~)p;b9}gMuj~cHYMyYy-Y9YWAw3lv)-yt&?oBc`XqgdK2@Kl z&(aUp57Fo7^YsP#k@_P2Xt&;_FVmOn$LeS5SL=7`59%+3bKx=JJ;DpaCx$NyUlHCA z-W0wrygB@>@Xg^{!?%aO6aI6AEh0C<88I$md_;9bZA4wfq=+dIb0g+QEQnYb@qEPM z2v5Y)h=z!!h;5ZwPM*n}w~yHes)DNH`;WDO?b~621|>7p@C8gqy-o z!rw-zQEk*3!;BHeD5JrcXtW!Xj48%UHmx+RHr1Q9n0A}?ncg>jXgVC59a|7v8ap<2TzO6=Qf`MUX@1z3=USfrLfi^>ve(OLACNK3TEVo9}hwG6Q2TJkN!EW<4$ zEiTI#%UDaLWxS=@GSxEA@}gz6rP< zI?uYmy2!fNy2QH7+GKs*y3@MX`kwWG^@#N&>j~>g>lN$Y@k`=gj$ar5hC6;!{MPvG z@q6O;$A1uiF#d4-p9$IoM?!i+MnYynpM?GiSqXy^MkW*|lqQrXR3y|S)Fn(#n3gaj zVSU1aezEDnbw-O3?D0$-n*w D`kVKw literal 32623 zcmd752Ygdy_c(r^dv9{P(x!Vt(*aGo_o9q6N!!pi2}!zGAx+aZkPbQ+GQ1a5R9q-3 zA|M-4a3CV$0#Q-GfuOj>JrNfoD*8Y7-rO`Pg%@7@f8QT`piOetbDr~@bDs0uoTs_l z>FDjt&OU}A495tJ#6*~w`kVTvF?p7~r`OTd*_hnbJl$^V>upN5_So7T@U}U*ud6!* zL)Wc+I2g~yD9i^7#lo;~Oo63hX;?azfn{P@ST>e}ojtH&C!Myv^& zh)u#KV^grHm<6+At=J5#7wg0Nv02z`>?&*#wivq(y8*icTaMj{-Gyz#wqp-r4`YvD zk77Hp$FQB)%G7(0P|f_;j8hJAy5i~WfGg#C&A zg`LCxMkMk>QWS<_kPOL@0_C7wREkESGBg@ZKt^OjW>kmjQ3Gm3O~`_#p;pv}W}+U{ zi~7(UbR$}dZbCPsThOiOHna@gj@F?2&|0((tw$TsMzje%j2=O|&>r*@dJa90UPLdU z!{}9X1igjcM#s^I=o9n>`V#$&enG#Y)95$!7dnR%IEjmJe_V=3;n8>uo`@&m$+#TP z#Pje`co{w#*WeX+C9cPta0_n7+wmEAC*Fnk;&br%IE`O}ufkX3Yw-K&h?T^>#42JnIg7lCTu3tHHRKZVM)GFzHu4VgF7h67 z6?q@Ip4>#7FCMIi)uv%kx5i9Y7$KrSwzhuyQp0>L)0mnDe4o=7F{J;AfiQ!Mc0XL5ZxrY zRdl=PPSFa{y`nXub)t=;EusfR+eMFv9uw^nJt=xx^qlB<(Tk#&MTbPMiH?YliH?ij z6MZN;A^J@8rRW>c_o7pxpGBudzl;79{VhgfQcQ{c#1gSo94d|wM~mac@!~}B2(et8 zCe9S+i1Woo;!^Qw@i?(cTp`wqYs7l7QCuf(6i*UQ6= zp!iks8{(tlx5e*@KM;Q`{#5*h_-pZZ;vd96iGLNJ5&t1RMY zx}Lg~x`$dx-Ak>aR#R)J`>3td1Jr}mHfk631ht!bn%YafK^>vqq>fU@sJEzhsSl_R zsgI~nsZ-Q1)UVX<)LH6WU2J&UVZ*TDw1^hd z6zxO%(tfl*9dJJ;!xFGWkRlEnfsMpQ(h@q5mV!inbTAzUe^aNjTpXP(U9&5CtQ~fX zGy&ew_q5o1>@9BYW^1#mtFy1C%jpC+Y>`I0k+hu^ppIT!kKNu`+tmX2>7HWqlm~F@ zIvq3n?b;R?iKEqF@3BbZ0bFV814lkIH;Z(PCqXYsESidPO-?}ts86XW$;elhs545` z6$KeZImLO(3Qa*pc2SO}wC1iZXS20O+gtDGbu>Fc+9>x(fO5I_NAu?878j(;it`tw z%jV_eXJ@C&N{aFqEO?Wf`aG;)9To?Q40;nQ!iupHtaKtj>z$y-M*dfOFBpfir^h;X zJphbq)S2{L`0^3vaST?4$+u!-v2mCZE5}rr8q;7ESS1}ohtgqmI2}Pp(ou9Y9kUhF z!VFepHCQdCgWn9;1UeRGa2P$DPNVDKx2d#+PPIrQl)b$WMXjBEnifZ2S5I$^b#7OG zpG7K#v6|YuX6vl89Bo$kWD>jq!>+M5+np9^#s&3U*XM9L`sONo>{b&*=)QV~eKt?d zO^W?&(A;}XmD=9xXzLt;0xJ+t-(l}%jSUh-pL5v7=~MH+1G>bJF< zd#ny849nh=*&%3h8rF=-*I`yVejR3`WvnKG)%9k#z}h~0M=w8hZP@hnSUcvR6X+CL zArNq4U0BF^tOM($6X~S&ST{D4PNqlDBc}ivPm`6xYgPrd*0xSZUw@0;kTh=b3XJ{3 zo5CDy?qr=w?Etgx>a_O2+|R*A32f$J3kR{GfsLFVnKZ6T=0W5d?Aob1Q*D2r6%3U# zp$*tItP$}%mSERgq@iwr0cIPpC7$eV#BRal8?dF=P1wzJI-NmhZoqEEZpN0;S#%~n zj#bmJMjNc$Oi*^Uqc77vrJ35^-hMl*_F$9U2`QJo#r=^*D!TxVsjsKs*4N)-7lwN` zwvILM71%x4O6*>26}B2%gWZR%rL*ZAI+xC)^XUS*kS?N&w}PYEfNjJ!!Otz&{qX+- z;HpaKQo0O&j;6=J|6^Hs*)^-_>FMeLJL$9cI6B)jove~tSo3kMY$FH^lEWJ+a9Y;x zUV95`RqSY3>^a@m&K7$MKSCCbHN)QWx#qdu;1t5yH@wCS)Lp1Pwg-C} z8&#(>!3*AupLKz=foLB#eJ!ov-+#g5{R7J5Fy$bYvTLSzEH?bO?bM5ExxKZk$L?m& zgP%7WdASP~2{10+I}n=?x+RrtUkN!%ELw0Qs{7=>W+wQC0;!%?K*I#Co| zPp5KrgkrJj8&Dh?hKAD(bQ3+v?J7|MO7`+$Dl`%TRU_-ey2o)oOb{X!Wq3hWqAWUw zp2$KjrM)2YP@yLzDniBdWO@p#bT)9gV+0!t+-xjTXI5P=hMT znGWy@S+j-gDa&DK@9MOh?Y({QtF^@fP~0vuOEU*NNT=25(sq_gRqnL5*fYRXW@KF` z)}S${60$Ee7L7wnRE|_gjWno&o<>{gX4*!#(000&ZUYyF*qE(FHK-QpkRDc1JH+W& z`c8TaeLwvO>&&FA=TY06``g;=J$w|6fZ_6CkISfF*>tv8ds^6N$O7{pP4s|}hQdc` zd#knI*~gLM>BwAf8Q86JZy&fQqrJPw-V482*~r9tG=Z}_Oipxi*#f&dggKmuCWCpP zNwi}fnnF)!r5?d^cV!kAVjvK(A{$GfnVzu@wa`vF)m&?JbPAugBPSNJ0XfigG=uJ- zJL#?sr~{PNMR$X$?qCf-;l+;iBX$!cF`aGPukP3f83Z_QZ&;Ue82o;vy{p6C*E5&5 z^nS?Y&@6f;9V7@f7ct-|(N$<3nvWKsh3INT(>-)A-ADJ+v*_9MoGoY(T8yqi*P`pt z5_CO1m%fT#MBhqZN8d&-qf;k?qp_>4eO5M3OyXtYq=opU?sXuF$hU;>E2jL%E$k%jI8?o?4)^xh56~S z+?>L~1x@pEvvc7^_JX(2X0!$KNB5(x=mGQ~+J?4cT3BF$kTqR4&g`cSsEAE6IfxFh z$AP!mEd!(nbM&nO?!agCQu-SD7J4xqYmsKTlOV6DQFpQAGTr+bcTU6`+oM>)2DAe` zhIZ1|($~{Bzy<<60dil5o}B2x=Q?@`*u!})h|B)a)94wClntu`rUYDIL2z;#td5@b z=vi#ke}LimV!xs%Asj8?h1d@-ZlssEqZc{=lD&*xK?l*HNiD8TC>T^zpD^Y0P4vw) zW|7Ws1%ofm%5s95o$X!VY5xx$Gq07`(Cd&BLv}7qn=s|;(HpEXhWd!dd=nkDNadhU zuZbK`uJ<}!kB+hAE*ah;jmfatxT&=FmfPE`ou#uKeeIfA;E78u(vfa6V)Jj_RR|-< z{-Ia9v4UO9`3#TcEk!OSxES{VaBg#m z`_hp5aJs+)U?Yf2@IZPUz0sZB;K6v9XC{J&;}P_FdIM|(z2r(7H_t1B!DI2^UU>1i zjNU|VrbkY4Nyeux^SV9r9()8o(kmOo6?mFk)^vKSAZr#YYc`%kKR|CEkToAK^5R*H zm(UN=+vt%^pmpAqlEyivd2t+rE4^^aaTWa#{jiYU3Mm0E?c}{2?lHUy*W%+bf4mwU z!fSCI>~4Cxy88HuX0rtySN(}>vv)fBdwI@m-N!zskN+g9n~xdieMCPAhWjY}^xL=r zp8yPuxCu7{lWM#H3et_(*lGYMs>8;}B9F z;PfQ@6urYER^SuyNqnrJchisYuAR4zY2c`FE8dLT=$-WA^ezua4N;zVm|or!cY^nP z;sV~2_mf_O#QR{F4cKIK2%Ajr0ok6SVS@(SIeacGQoI(l!WWnD1^7aXGzF&A9aOxk zE8erP9>1D(PnQbLISib^7g?l9m%w2?zL=$cDWJmYyB5C3#I`^nUsU`bGLB`oII&Nc?t8i!aCT#P7oI##gW#Qb?O$rehf# zF*wQKz6>sBa0R3zQr2IDmBXH3Mt7H^v#*z{B|?7K0&c{W|MC{cC11T2T|M9lAx(_r z%^X4|U!yFyw?jtR)iaqdMw)ExcD5QC#=kW7cR~fL&(XrBq@E5rt_o_wO_kWmfxHg4QYxI!hASVeV z95?+RO5!RiWVuQOSygtYvkQEJvjtoLR}J-$@O4hYBmWy+wR`I77$*s&ShxNUb>-3> ztSmKb3ZVdQ_ny#qIU(P&Nay|!gyeP%UiS47C(iNz=XBOCtmjYgFTmNLyJ5e$oL&gK z#d#a>FY&MNujzN`_vrWO)Ox|f1i&|U<3m66Z9u^>ZExEIZ$QI$uBP8 zu^-fCPj_JxV#03->;OUn*q_m#v&{4IiePt{13!55&(|4N2xx7Co19mK zec2H3nS8CI2I^p$z3ds*Eba^|eF#v2wAtFzW_O*TxhM|>E^JSP050q~A;1qMxP|9f z-VZ4)RPrIEXme%D!bVVtt**Gs!+Qz?<%tUt5folS=!8uKp{LKdHW7poHW7r0Fw?)& zf4DahL<2F=b3=f26O-Xc>MUENwU6`MIuO$c+aO3gK>o=>UYE^5UQ9SHwZAMRXInL{C#MSFVFH7K1SQANnMNzGj!a+A@0SaA9cu#9UZ9#4KVq zF^55jK{$hm4a8N%JYqhBNCt@*BnI!p>#v^IoJE>=L7jQb*o74 ziXm}5aVu-$HxM@xONpC^n~7T(s)?Ip5y^0 z@Ze50yrB4V!Mq_%m8asVQGp6uvh*OrYikWQ{bA|b#C^nCVjZy_=4vCciP%hRA?_!( z5)Tj$65ELF#6!fx#3RI`#17&yVkhx9v5R>-{ao+h3lo+X|m_7eMu=ZXEq z3&e}WOT+=y;ydDd;w13{af16lL4fJ3?zd{DH%+LkfCH48BRu! zkz^DZO~#P1WE?q+98SiQGBSZoB$LQwas)Y&Od;i@f=ngT$aFG;%p|kOY%+(;CG*I9 zvVbfki^yWKge)aTk!9p)att|^97ih2a#BUANex*+R+3eumK;x3lQm>5sU!8Ift)}Z zNfT)%>&SYtfovq3$cf}6axyuEoJv~AX{42GCT(O3X(wCBHnN>`kkiQ-q?7C*JIOAx zo197ZkiBFdgMt_o%%Bhkg)%6NLE#LFU{EB3q8Jp-pcn?lGANEg!x%K2LGcWdF(`pS zi400&P%?u?FlZ!$QWzv>kb*&}3`%2AI)gG8l*ynh24yoShe5dv%41MIg9;c_$eZw3b2Z7_^>2 z8yK{aL7Nz~nL%3^bU%Z(GUx#YJ;wD<)YT@goI??G(X3Hh3^ht~h2B`}rVFzV7_oyf>XkKGwMFSE0hk9s zMk78pxTDtm`KG2?PZ_{^hKAFZkN1QF;{v!5L(r>I8d*_|8kN4*V6v#SMqzwlhk!HO zg`@B0&JpL&FR#MAWNy;>t+!8!q~af7kk!`13k zHFau@rAnhzgP4{IqrTR{j?l~!RM)A@UMhjr2ILfj$r^1yUL;j18th9 zajOy*C*b7{#xtpuI*YOfY*}AtRB0?Q01e2XH-a8Gx!mf7MGXXGg9&h!;~G6HtT1d? z`T#xxv1bV~6FiLtsptIptYR!CZKckl(V4a88ci+ybh7|20XXRw#4&1IQX1=6DGf?< zmB0@C3ZNzrLe-nAG)8VVc%~IK%1Spk@IZhPiPZLPXV+ZzaYwLivr%jCf&%vhP;p*R z${MrAsAC6RY1G#l1R21AT?AC$0A?b9f{O#t*b7jt^)MgsfdDDL0Hi@#-QZf7blbe z`8@}j;ze6)sM6~+dT>VrhUBf2Q!e_|@RW<)DTBnl-)WyeAEpi#tVO4+b<6%U2N{Qk zh6Du~-HJYaQKBZZ-n{^S=OBk)fastg@FxcxiE133GdSN=UZ+!olr?(R4-0zun}ZrL z0HtoK(UyZtsRjGdmV>)DHw_9eBE;dupNCUtG_q^YTMiM)K@anQhCtx*S*$lQ46Ha2 z#lfZwz(TaC1`ns!njq3QnJl#s0cv3OSycBY2OTjW7Au1VT&`KGbITsh0gW60Vs&C^(3-2*P^eQYjcN-_nGv#u0hPpYNZ|uW zu-dCEdW*Tq;3gc;!GsOK=#5|)oSPK{Oyod3Y={pyHEPcgA{xO#dDxIUW2jY{K$#ZE zlr$={7iBqz<1uuY5pG~G6!*lYaX`ZdB&^nG43ITw>)F_(X=J068#t2#P8a}&iGr+w zb%Pd@hE4srfa-?N8BBb@QE*db(Lf$7C?cN&_E3Z%u9qT;IH>3W5lk>_msUL@v#4~i zsCBxF+R5m_bQ_dL9h-*@nuu{6oQJ+Z1s-!@@R|XY3)o<_&9Jt)vX@$RVL;{qv^~SE zsDc9?fjoef2188~Xqe4Zw2++X4NcxSS`J6%iKA)MsOrqha&SZJ?CCs`R#6QHKI{VE zAXkO9QJ4-r2b<;z%cix48m-9;lnv}E=96fX#te(eofL_T9A<(irdvaX>PnW1mzL_z zm#V@D&Zj|dtRC#?8adb)Puc@gvFa4WpTq%X4h_gJF&M8aA%RrY%gCm3$VnGKt}`3z zV5M;xzQE3UF?L>z)SzT=L2SAuAh%qM9X~6s)Ly`7<1oDDeLxKZ>;&-X9Qa7j@vyeU znl}J*UfN`-s(`4hG%E$94h|{B6G?Cj?tO;7hIMBiX^^O!!;138;xZG@*e&Yiz>>Yd zILl(^&;s81d=<|+e-MVc@*3EuTtu9?9Fp9V51XTawQ?pXaMI{tR{`$|W1r8Vc`cL% zBdkUk?0JjoY7RC9ne0}0N>au?p~r6VYZ};K>hg+ppkr^>xQN3VF$inG?uT-x*K#-t3uq_h6)^cExLxCB!Zrj|zK_#Pl{`hTTo{;-qmb6A-~m0Z)Fj%*;m9tG!+S9S z{NeuuZmO&B2t_+CEI#YPOihph)e5v9=YSI~EDAR>?(AH&n}b)vA-mHqtEs84mD%7y z5_mGSN0y(NBg>F+)rU%Zr@e=JlxF^Xwi;9cSr?mgskppZX;ukU1kqC*y{gNg$JbmM ziwhyxvAGPlsWU8SziZPAynp+9=mSQK8~37GKsl^I9KF?IL@k` z%eV#IzrfKQeVKICO_1J$8|U^DDuEVMYGDIgeVMe}GIEPcr3WilR=P@30%a)u0_Dpc zy;cXgGvr}PBU`2OOpgV+P)YtTBxbib#yYN|0;{(Y5+Cq1`UbX;>h|MMng+_3V^i$p zYjj)|2%9^driR_jYijfcmXRPZ6uN^|Zb{P~{!HgPk#++?> zWQ|Z`2U24%lN8tt?4xU;&RP!jD7KW&J0vL71GVDIq{gjksN1?1GnDy(%;h=WLB6gQ2z|#98g;3JR2H`GT*od|VZ$v@`hlZ# z5xW==iFc%`#>NX%`-!7ga4B+mP~*1#LIq6p>!s7+6b@?{6l7}BnU(I{)ftXP;ibsI z($MO-d>C?L&+5V-9Fa?&dDm>I3~SQlwzl zz<_$#Um=h7E*^-JIdYfe16}0Kr;&1bBDvJd9Z5nVOE4_A-KTQoF4vP8lqOg`gAxgG z21n~6S&jGVG*!VdH~5V@cRgC1%~7bhRDJWwjH^s69L4fGUJsMZznk|46kL_H^(~PMOn{7I`W_Ri#l?TTD>-hf+3VBCxOYI9wK&b1WLJh=sBo zs$1;w7dSDXuRebl*}DS^Y1lzcAlo)?4y&EvylO%-&@TvF^WDKkwyvBd>)Twh9<<&k&r?Wdg@#@)fC{ ztMJ0E8y=qE)@nsv4HWX>07+G?fjJj+X69Jwu80+HPezTo4i>OSb|`M(h#RhmIQL)x zo3g;JR|gM5nB2!-;)xvjDOW_Emt9~|q1C`)iihglOM42(>&jMyH!pCjW<9GdH;-u? z597Z$9-XFvEg1-tZQ~e}|2GVTvnZ8UTG0BhX@$#3!BqJjAyhfsT5)hZE>bJG6hFZ} ztHYgk8{Nuqa&-SI>+x91CPeheB?5!a8NBJ?P98 zf-TSCm|U4}se|KHI0xgrBs@1*XV$x|ZXQRz=8DEpr>oY%gFzs;vJ%e71<4owE2O#H zOPCOWG{cd;vb9pD<4D&i%QZrAU3?8kxAqFP!O>+O)2W3BBoutaOa48X;VHg4_xir^ z-%~U9j3yjs3u?ZZBYlzGw}(qorKQ0GgWNNXoMA)Z0|Gz02ZdF{)?L|pyW2Kyy9{M; zl--H54hoRMJVX6klHf5C5o)LUmVs4@dnX)yj)#8me&FjRS|JZi!cMG%qbn=Q|HVp9q=CdluDo zYzoIdpaRBRrB{R411B)z`#2VtmcU(z1y`9u zSis>dlnWu>(z+G5>AzK++n8Wi2j>cWAcI08_pq^9uhP36&HWq;>m^x}m*U(kYU^su zS_4GLfz2wHlk$%Pn>01t0hh2Y9_094+Di7~=dq&MiGqSA)NCxua(5l_p?_gsJho_V zYv8tneB>1d@hHdY(w5-G2Em?|Yv8QhXlc+Ws|D&iIqH`dXuYVrr^IyxDCpjMsXW1v zzqAd=(B$EPM>q$D?SUE&`Msxi4@dk8mpVJK!Sl3cZ)Z&$}qT8xy=4`)CzBo}zO<4lCZzQ7B`3H8^ZC zB{XK6dleiV!?AI@-8KVi3%sogkJ7`!P^!5n*x6s;!BcqrMwsiDI8y1COsZ1l-blW} zp=Mn&YAx#v-1V5l9CrDIuwgLnxzBKWV)ux+#i2BV!*UaRog=8Z5`sFDs)DQU2-)qE5nXst zfE8Z@Wa03Z+n#CEeBDP-%}I`p>0e_5UsW(Pz~ik0b;BPy4u*e?Lv1zt?2hpCz4#Z7 z{FTkEr=E;Zl^2xr8%O(M4&*=2ttV{=tSW7_mY2OYsF5hWIyD+}N0 zAKWBh14U6jY&#{_cdg-T)NEhU!C*tTu5*1Mp7Nvoy*h|dfmD$98zB@lc-=^aQejj$ z4oT4W41xy%exwg?q@t*3Du#lSxt|$ynn9rWb6y=KC>h&PfKdx1zX9Wa={YLYw}6uQTbRR{w0IJ zXZ#9Xwce#u*~Sa16GssDa~T{ znGU|gX)oWHG`}E2ZOG5Gc6VoSo%oo>47G?_%-|9R zPhs#dcJSFSc<)AOuBK|x0>sqc!SG8*HxIsYiz*v4eVy+R5NC3=UoR z;NFm=u|M)8Y?y2Wj>+Dnp2YmAJ=9ZdXVMnvd#n$}CpQcCIU$@NMdDFqmv)cScFHG6 z8WS6rJR&V8zsPmtim#u4fFuxZ&~WL2zhDD;%+onk`}FxjDibOd};rBov8wvN&+ObVCm{PHf(sjpDZCU3Enq3 zuCfEy)(WS!truRi3q5JvNPh6a5-EG%3asLqew(AkTG_+iE09s%w-e>TP6zF zH;YT4GpC1AT6lG>FNM`M#QR*2glhX-=vU~vPV30%F=n>2Cyn4DtzfuYCJD>Ha^Z>- z4O~8AgsZZe;hv0{ST9_Vbv0a!bqieVunMkpSPOSIY=V0mw!+0&yWu*5m$4&ofxssi z+e80r>@S2+01Ah0^6_xtRTeaNSEEX#Mb*dvS6od((@+QMM*VQH)y;5))lT#TdYV@- zj`*K&LyFfQ=t_YP<2pT1&rr`!arb#(J8o})x1PgBfu7k{!qV7By$t<%V0G`OUZC!v zUZM_gYdoI8Ww6W{Jb}RzH&d^mQ`8~qFf_P5#o$Tw8U{~h@R87-hilN2c<~j=HzfTJ zKp+$Jm1LW9dOJQZ7s3LW`sT7X)cglXw)Hj#nKaIa*U+2P+prRkQ}3{L&$el119`=< zvj?DY<_KP8?@{mb+Oe;v-ec2Gsky7gI#*`xlNFX`=gADU(rYUEp330q44w(@b)Y37 z^)r_Z;b|7B@w{YmmbE9V6&4QL&3{&IR_mPZwyRoax8%>cs>E45y=QjroH^O;`Lna( zPg`e}Ig4+Zmto5*Y%R&t&HoZ!|PcO~VSXQfw@_f!s>&BA{=r9xoK z5doWw7%Gm+qH-Y5ETD?u?ygbPXlg8_q*T;oxT$L%+`{!NbrR$c@)_n6?<4cc_fh(& zeJXskKGi<8K31RUK3zUDeR_TReHQsF@wvfgsn2abxBD#jxyxsx&l5hoefIer^f~VH zfzLNSKluFU^Rv$xpR+!H`keC>`v&8tjw_HFdF_*#8!zII=yZ>Mj!Z;x-E z?{eS!eGmD*t|(M1Q$|j(@IyzW-?dG5+KHwf^J% zYy9i{>-`)3?f!lKv;61yU*$jFf1y9^zsP@?{~i8!`rqw;kN>^?tNriuU+4db|6BgQ z2KWbL1tJJ|Fl(;7fro z2ObPO9Qaz`$AO;&eirye;8%g)1b!EIGVoO3PeEkRu%NV{!l0UmYgx>34WdcX7m={D(8(r2X4N%u+jOJ9^8kiH^4Bz;Hvx%8jl(BQ1# z+Tf<({@_KyOM`C?zBPDR@EyUcg4YDE4PGC-F?e(EzTmHee+wBNk`j^^GCITK`fz4GK*PO%JUOHH3DB&I!FL zbbjcyp-Vz<2wfJsCiH>OouRuzcZco?D+wzPYYdwb)*CiIY)ja-u;XFBh7Su*4bKf9 z6Fx4yJX{@K8*U1344)d_7Ct@P8QvLwZTRis_lBHICURV)CbBY88(AG$7dbU@ zMr3znPh?-@+{k&63nH(MTo$=9^1;Zxk?%#Gjyw~2HuBHNb5Rjd@lhkAa--^^tWmZo zdsJJLBWht39knRxnyBldu8&$4wIXU|)T*d8QEQ{NMm-p{J!)6f?x;Oc`=efrIuP}G z)CW-?MV*NHH0sZ&b5Z|9qi7;JAUY^II65>sF1jMRI=Vl4Vf4o6tk#MHz%Viw2T7PBSh zy_oM~sn~?r;#f^=O{^}~5NnKWik%cYC3aeDbL_pbZ^eEZdn)#)*k58#$DWBj8~bOR zPn=&|KwMy)G%h4AEG{B0DQ-kuN}M8YZQS;_hvOcNdu&+wF#WIz!%V~Kh8-UE?y&cV zeK_pn;WLLX98M2kH2j))EM5{H6dxQP8ow!iNBooVPsKkI|6Ke_@h`_8j6WRzTKrq_ zpT>U||9kvDG9)8pB3XbeP$rdy$iid^vQ$}-Y>aH2tX!s+Rm*B+df5b-NoJ9?%lc*W zWea7rY?15+*;3ifvRh@#WNTzwWIJU~$)1rtC)+1`S$0r%SoWIi4cWW0Pi3cMzsY`= z{UQ4+fk+S~Pzk;X{t00T!xB;xG7_>9auf0s3KLWbnuN*(ZNia+j}pF1IGJ!N;irUO z5>6+aNhA}+i9U&bi2;d0i6Mz$iR#3z#5IYpCZ0AR$p zNvD#rWWQuda!_(`a#-@P20 zyq9uA%1tS^rre%#XUd9{dsEh=tV`LLvL)q#l$B4Dc_`gpK>bY=akbazo-0}^0yqxNjW9=lS|}Md8j-> z9xacP$IBDtBjj>TZkd4*gnuaWEJMtPmQQ9emNRc@8H$lK)8 z%S@}Ns3-SZz=@M*fHVoB~r2 z3bDdh5ugZCgebxlQHof_a7BV5S&^bhRb(i#6?uw6MTw$JF;-Eo&?u@D)e41b;X;Cw-oOv-dB92_(bu!;w#0sij#^T z6~8EcQ=C=&rT8ZmPZg#5r23~yQX^7jsY$7tR9)({)V9>_)VZniQ0hM(kp5G~$c(Iv+>E-6sTtOc8!~RsxHIF0j8`+>$T*XUWfGag zGDl`AGOIEtWSTR3Gv{Ysow+)5bLQ5}W0@ajp2#Ay0MU#4^sJ7o8?)}n zx-096ti4(Lv);@4EbGf`Jlj7zFuO2&Y<79})aDkM&S7xuy-krTK`-SXpvwz9{ zEhj8zSdJ`be2yunKBq5dK@OdBU(WqG59Yj*^JdOlIltxnlZ)rZ<&Mae=NfXGawq35 z%w3XuW9|dFkLB*lJ(2rO?)Q0ko_}6o-srrFJZ;{LyuQ5IdH3Y4&)byuY~F#qgL%K? z{gwAmeq_EZKPkU7UzJ~xKP}&p@62DGzdC-i;tLWBR0TB! z`T|EmPeFgdvVxTbs|)rO94vUX;G2S<3r-hC6vh`O7ODzs3iXAv3+ckeg_{c>F5FT0 zX5ssV9~A`@g%?E?l@)1G!^=|2Qp+@Dy0QsnGs^nPW|yrg+fw#G*`cyyWyj0@8SOLLe{|;PqS2+J zr;KhL?HGOI=sQN=HG0qJ{i9zR<2NRBOvD)LnCW9W#ym9Ui7|V|ipK_x4H;`3J8A6H zvD?NzK6dvwa-3wGbllW&ZR4hodwkrp}l z_o)x6U)4|=sU}p@q-oaJHJddLYj$W(YJSt4t*ERpRG2F6saRjJsp7keUn|a37F3R@ zR94stc=2sux$^RDEmpm({1Lf3B&isjF$M zd8Fpanx|{=TL0R>T6=A0?abOkwa03Y>k4&ab>+G{bgOjt>3-Jzsry?$Ro|wcu76&C zNdKB4$&hZyGV~c17-+*ghEEKiPspB7GNEk3stKDW+;0pw4mTzkZ#3RvyvumX_`C5> z6I4%36HQx9J4}z8NwdT(HBUC%&F$vh=6&WD>ZEnib#Zkw>iX(t*S%QxTHTTQVf7>H z74@_0>H5X>Z`FTP|4DvnSD$7EgL&(%wn?C!L*)PZmv9 zPp+M8n0)o*>nAUr{LJK+CciQza7yHqm?_OuW=!dvvUkcWQw~oJof8^we`K$k6S-&{i5~T z)|0J2w*K5EZX4eARNLORSKE%Y9dCQD?ZdXu+rDc1w(VrwsrJP7(e3r^miG4c8SS0z zGu!*xXSFYGzp?%1_S@R;XkXdBx_xc?hW1VEueJZ>kUMf5d5#iCg`?JCaF`tRjwz05 z4jWuo-0qm^=yS|>+~By)afjnB$32d_dCDt2N_kQ%^fp3 zdOBuz+}Lqb$DJK3I#zb9>e$q=r{kH9=Q{RvywLGd$IBfDJ6`R0qvL4DTOFTveBSY8 z$2Xm0I;%TtJN2E$&c{2S?|h;2rOsEn(!0iVsk*d$JqU-ZlGr~!uAlrX4C|`?{{W@I B-sJ!Q diff --git a/Example/Resources/Info.plist b/Example/Resources/Info.plist index a525442..f741ab1 100644 --- a/Example/Resources/Info.plist +++ b/Example/Resources/Info.plist @@ -44,5 +44,10 @@ UIStatusBarHidden + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + diff --git a/Example/libs/README b/Example/libs/README deleted file mode 100644 index 0d4d8fc..0000000 --- a/Example/libs/README +++ /dev/null @@ -1 +0,0 @@ -This directory contains the libraries used in cocos2d