Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

init

  • Loading branch information...
commit 781c7e0627f3c6bd2a4b4a963ac6957927504395 1 parent 3e483bf
@saberma authored
Showing with 37,528 additions and 0 deletions.
  1. +1 −0  .gitattributes
  2. +13 −0 .gitignore
  3. +1,236 −0 BrainShot.xcodeproj/project.pbxproj
  4. +8 −0 BrainShot_Prefix.pch
  5. +25 −0 Classes/Ball.h
  6. +69 −0 Classes/Ball.m
  7. +17 −0 Classes/BrainShotAppDelegate.h
  8. +83 −0 Classes/BrainShotAppDelegate.m
  9. +13 −0 Classes/HelloWorldScene.h
  10. +67 −0 Classes/HelloWorldScene.m
  11. +21 −0 LICENSE.cocos2d
  12. +22 −0 LICENSE.cocosdenshion
  13. +99 −0 Makefile
  14. BIN  Resources/Default.png
  15. BIN  Resources/Icon.png
  16. +33 −0 Resources/Info.plist
  17. BIN  Resources/circle_blue.png
  18. BIN  Resources/circle_green.png
  19. BIN  Resources/circle_orange.png
  20. BIN  Resources/circle_red.png
  21. BIN  Resources/fps_images.png
  22. +209 −0 libs/CocosDenshion/CDAudioManager.h
  23. +680 −0 libs/CocosDenshion/CDAudioManager.m
  24. +56 −0 libs/CocosDenshion/CDConfig.h
  25. +286 −0 libs/CocosDenshion/CDOpenALSupport.h
  26. +235 −0 libs/CocosDenshion/CocosDenshion.h
  27. +877 −0 libs/CocosDenshion/CocosDenshion.m
  28. +73 −0 libs/CocosDenshion/SimpleAudioEngine.h
  29. +249 −0 libs/CocosDenshion/SimpleAudioEngine.m
  30. +44 −0 libs/FontLabel/FontLabel.h
  31. +186 −0 libs/FontLabel/FontLabel.m
  32. +69 −0 libs/FontLabel/FontLabelStringDrawing.h
  33. +890 −0 libs/FontLabel/FontLabelStringDrawing.m
  34. +85 −0 libs/FontLabel/FontManager.h
  35. +124 −0 libs/FontLabel/FontManager.m
  36. +77 −0 libs/FontLabel/ZAttributedString.h
  37. +596 −0 libs/FontLabel/ZAttributedString.m
  38. +24 −0 libs/FontLabel/ZAttributedStringPrivate.h
  39. +47 −0 libs/FontLabel/ZFont.h
  40. +170 −0 libs/FontLabel/ZFont.m
  41. +1 −0  libs/README
  42. +68 −0 libs/TouchJSON/CDataScanner.h
  43. +270 −0 libs/TouchJSON/CDataScanner.m
  44. +37 −0 libs/TouchJSON/Extensions/CDataScanner_Extensions.h
  45. +80 −0 libs/TouchJSON/Extensions/CDataScanner_Extensions.m
  46. +36 −0 libs/TouchJSON/Extensions/NSCharacterSet_Extensions.h
  47. +48 −0 libs/TouchJSON/Extensions/NSCharacterSet_Extensions.m
  48. +36 −0 libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.h
  49. +41 −0 libs/TouchJSON/Extensions/NSDictionary_JSONExtensions.m
  50. +44 −0 libs/TouchJSON/Extensions/NSScanner_Extensions.h
  51. +118 −0 libs/TouchJSON/Extensions/NSScanner_Extensions.m
  52. +59 −0 libs/TouchJSON/JSON/CJSONDeserializer.h
  53. +84 −0 libs/TouchJSON/JSON/CJSONDeserializer.m
  54. +43 −0 libs/TouchJSON/JSON/CJSONScanner.h
  55. +536 −0 libs/TouchJSON/JSON/CJSONScanner.m
  56. +45 −0 libs/TouchJSON/JSON/CJSONSerializer.h
  57. +184 −0 libs/TouchJSON/JSON/CJSONSerializer.m
  58. +126 −0 libs/cocos2d/CCAction.h
  59. +230 −0 libs/cocos2d/CCAction.m
  60. +97 −0 libs/cocos2d/CCActionManager.h
  61. +352 −0 libs/cocos2d/CCActionManager.m
  62. +80 −0 libs/cocos2d/CCAtlasNode.h
  63. +200 −0 libs/cocos2d/CCAtlasNode.m
  64. +146 −0 libs/cocos2d/CCBitmapFontAtlas.h
  65. +601 −0 libs/cocos2d/CCBitmapFontAtlas.m
  66. +77 −0 libs/cocos2d/CCCamera.h
  67. +123 −0 libs/cocos2d/CCCamera.m
  68. +60 −0 libs/cocos2d/CCCameraAction.h
  69. +130 −0 libs/cocos2d/CCCameraAction.m
  70. +213 −0 libs/cocos2d/CCCompatibility.h
  71. +585 −0 libs/cocos2d/CCCompatibility.m
  72. +45 −0 libs/cocos2d/CCConfiguration.h
  73. +83 −0 libs/cocos2d/CCConfiguration.m
  74. +450 −0 libs/cocos2d/CCDirector.h
  75. +1,073 −0 libs/cocos2d/CCDirector.m
  76. +71 −0 libs/cocos2d/CCDrawingPrimitives.h
  77. +206 −0 libs/cocos2d/CCDrawingPrimitives.m
  78. +147 −0 libs/cocos2d/CCEaseAction.h
  79. +520 −0 libs/cocos2d/CCEaseAction.m
  80. +32 −0 libs/cocos2d/CCGrabber.h
  81. +83 −0 libs/cocos2d/CCGrabber.m
  82. +114 −0 libs/cocos2d/CCGrid.h
  83. +519 −0 libs/cocos2d/CCGrid.m
  84. +193 −0 libs/cocos2d/CCGrid3DAction.h
  85. +603 −0 libs/cocos2d/CCGrid3DAction.m
  86. +157 −0 libs/cocos2d/CCGridAction.h
  87. +379 −0 libs/cocos2d/CCGridAction.m
  88. +121 −0 libs/cocos2d/CCInstantAction.h
  89. +296 −0 libs/cocos2d/CCInstantAction.m
  90. +374 −0 libs/cocos2d/CCIntervalAction.h
  91. +1,208 −0 libs/cocos2d/CCIntervalAction.m
  92. +47 −0 libs/cocos2d/CCLabel.h
  93. +94 −0 libs/cocos2d/CCLabel.m
  94. +43 −0 libs/cocos2d/CCLabelAtlas.h
  95. +151 −0 libs/cocos2d/CCLabelAtlas.m
  96. +132 −0 libs/cocos2d/CCLayer.h
  97. +327 −0 libs/cocos2d/CCLayer.m
  98. +74 −0 libs/cocos2d/CCMenu.h
  99. +448 −0 libs/cocos2d/CCMenu.m
  100. +235 −0 libs/cocos2d/CCMenuItem.h
  101. +577 −0 libs/cocos2d/CCMenuItem.m
  102. +56 −0 libs/cocos2d/CCMotionStreak.h
  103. +92 −0 libs/cocos2d/CCMotionStreak.m
  104. +429 −0 libs/cocos2d/CCNode.h
  105. +754 −0 libs/cocos2d/CCNode.m
  106. +81 −0 libs/cocos2d/CCPVRTexture.h
  107. +283 −0 libs/cocos2d/CCPVRTexture.m
  108. +29 −0 libs/cocos2d/CCPageTurn3DAction.h
  109. +78 −0 libs/cocos2d/CCPageTurn3DAction.m
  110. +48 −0 libs/cocos2d/CCPageTurnTransition.h
  111. +103 −0 libs/cocos2d/CCPageTurnTransition.m
  112. +37 −0 libs/cocos2d/CCParallaxNode.h
  113. +150 −0 libs/cocos2d/CCParallaxNode.m
  114. +82 −0 libs/cocos2d/CCParticleExamples.h
  115. +892 −0 libs/cocos2d/CCParticleExamples.m
  116. +270 −0 libs/cocos2d/CCParticleSystem.h
  117. +345 −0 libs/cocos2d/CCParticleSystem.m
  118. +34 −0 libs/cocos2d/CCPointParticleSystem.h
  119. +178 −0 libs/cocos2d/CCPointParticleSystem.m
  120. +72 −0 libs/cocos2d/CCProgressTimer.h
  121. +477 −0 libs/cocos2d/CCProgressTimer.m
  122. +47 −0 libs/cocos2d/CCProgressTimerActions.h
  123. +90 −0 libs/cocos2d/CCProgressTimerActions.m
  124. +136 −0 libs/cocos2d/CCProtocols.h
  125. +45 −0 libs/cocos2d/CCQuadParticleSystem.h
  126. +242 −0 libs/cocos2d/CCQuadParticleSystem.m
  127. +28 −0 libs/cocos2d/CCRadialTransition.h
  128. +94 −0 libs/cocos2d/CCRadialTransition.m
  129. +65 −0 libs/cocos2d/CCRenderTexture.h
  130. +220 −0 libs/cocos2d/CCRenderTexture.m
  131. +106 −0 libs/cocos2d/CCRibbon.h
  132. +366 −0 libs/cocos2d/CCRibbon.m
  133. +33 −0 libs/cocos2d/CCScene.h
  134. +32 −0 libs/cocos2d/CCScene.m
  135. +115 −0 libs/cocos2d/CCScheduler.h
  136. +214 −0 libs/cocos2d/CCScheduler.m
  137. +289 −0 libs/cocos2d/CCSprite.h
  138. +876 −0 libs/cocos2d/CCSprite.m
  139. +107 −0 libs/cocos2d/CCSpriteFrame.h
  140. +142 −0 libs/cocos2d/CCSpriteFrame.m
  141. +97 −0 libs/cocos2d/CCSpriteFrameCache.h
  142. +210 −0 libs/cocos2d/CCSpriteFrameCache.m
  143. +111 −0 libs/cocos2d/CCSpriteSheet.h
  144. +484 −0 libs/cocos2d/CCSpriteSheet.m
  145. +141 −0 libs/cocos2d/CCTMXLayer.h
  146. +647 −0 libs/cocos2d/CCTMXLayer.m
  147. +55 −0 libs/cocos2d/CCTMXObjectGroup.h
  148. +71 −0 libs/cocos2d/CCTMXObjectGroup.m
  149. +128 −0 libs/cocos2d/CCTMXTiledMap.h
  150. +185 −0 libs/cocos2d/CCTMXTiledMap.m
  151. +169 −0 libs/cocos2d/CCTMXXMLParser.h
  152. +413 −0 libs/cocos2d/CCTMXXMLParser.m
  153. +245 −0 libs/cocos2d/CCTexture2D.h
  154. +752 −0 libs/cocos2d/CCTexture2D.m
  155. +126 −0 libs/cocos2d/CCTextureAtlas.h
  156. +326 −0 libs/cocos2d/CCTextureAtlas.m
  157. +99 −0 libs/cocos2d/CCTextureCache.h
  158. +303 −0 libs/cocos2d/CCTextureCache.m
  159. +19 −0 libs/cocos2d/CCTextureNode.h
  160. +19 −0 libs/cocos2d/CCTextureNode.m
  161. +70 −0 libs/cocos2d/CCTileMapAtlas.h
  162. +204 −0 libs/cocos2d/CCTileMapAtlas.m
  163. +200 −0 libs/cocos2d/CCTiledGridAction.h
  164. +753 −0 libs/cocos2d/CCTiledGridAction.m
  165. +56 −0 libs/cocos2d/CCTouchDelegateProtocol.h
  166. +104 −0 libs/cocos2d/CCTouchDispatcher.h
  167. +308 −0 libs/cocos2d/CCTouchDispatcher.m
  168. +69 −0 libs/cocos2d/CCTouchHandler.h
  169. +115 −0 libs/cocos2d/CCTouchHandler.m
  170. +283 −0 libs/cocos2d/CCTransition.h
  171. +1,034 −0 libs/cocos2d/CCTransition.m
  172. +24 −0 libs/cocos2d/Support/CCFileUtils.h
  173. +42 −0 libs/cocos2d/Support/CCFileUtils.m
  174. +315 −0 libs/cocos2d/Support/CGPointExtension.h
  175. +167 −0 libs/cocos2d/Support/CGPointExtension.m
  176. +145 −0 libs/cocos2d/Support/EAGLView.h
  177. +317 −0 libs/cocos2d/Support/EAGLView.m
  178. +79 −0 libs/cocos2d/Support/OpenGL_Internal.h
  179. +55 −0 libs/cocos2d/Support/TGAlib.h
  180. +272 −0 libs/cocos2d/Support/TGAlib.m
  181. +19 −0 libs/cocos2d/Support/TransformUtils.h
  182. +34 −0 libs/cocos2d/Support/TransformUtils.m
  183. +41 −0 libs/cocos2d/Support/ZipUtils.h
  184. +125 −0 libs/cocos2d/Support/ZipUtils.m
  185. +90 −0 libs/cocos2d/Support/base64.c
  186. +34 −0 libs/cocos2d/Support/base64.h
Sorry, we could not display the entire diff because it was too big.
View
1  .gitattributes
@@ -0,0 +1 @@
+*.pbxproj -crlf -diff -merge
View
13 .gitignore
@@ -0,0 +1,13 @@
+# xcode noise
+build/*
+*.pbxuser
+*.mode1v3
+
+# old skool
+.svn
+
+# osx noise
+.DS_Store
+profile
+**.sw?
+**.o
View
1,236 BrainShot.xcodeproj/project.pbxproj
1,236 additions, 0 deletions not shown
View
8 BrainShot_Prefix.pch
@@ -0,0 +1,8 @@
+//
+// Prefix header for all source files of the 'BrainShot' target in the 'BrainShot' project
+//
+
+#ifdef __OBJC__
+ #import <Foundation/Foundation.h>
+ #import <UIKit/UIKit.h>
+#endif
View
25 Classes/Ball.h
@@ -0,0 +1,25 @@
+//
+// Ball.h
+// BrainShot
+//
+// Created by cogent on 10-3-29.
+// Copyright 2010 __MyCompanyName__. All rights reserved.
+//
+
+#import "cocos2d.h"
+#import <Foundation/Foundation.h>
+
+#define ballSize 48
+
+
+@interface Ball : CCSprite <CCTargetedTouchDelegate> {
+ int number;
+}
+
+@property (nonatomic) int number;
+@property(nonatomic, readonly) CGRect rect;
+
++ (Ball *)withLabel:(int)number AtLeftIndex:(int)leftIndex AndRightIndex:(int)rightIndex;
+
+
+@end
View
69 Classes/Ball.m
@@ -0,0 +1,69 @@
+//
+// Ball.m
+// BrainShot
+//
+// Created by cogent on 10-3-29.
+// Copyright 2010 __MyCompanyName__. All rights reserved.
+//
+
+#import "Ball.h"
+#import "cocos2d.h"
+
+
+@implementation Ball
+
+@synthesize number;
+
++ (Ball *)withLabel:(int)number AtLeftIndex:(int)leftIndex AndRightIndex:(int)rightIndex
+{
+ int left = leftIndex * ballSize + ballSize/2;
+ int right = rightIndex * ballSize + ballSize/2;
+
+ Ball *ball = [Ball spriteWithFile:@"circle_green.png"];
+ ball.position = ccp( left , right );
+
+ // create and initialize a Label
+ CCLabel* label = [CCLabel labelWithString:[NSString stringWithFormat:@"%d", number] fontName:@"Marker Felt" fontSize:32];
+ // position the label on the center of the screen
+ label.position = ccp(ballSize/2, ballSize/2);
+
+ [ball setNumber:number];
+ [ball addChild:label];
+
+ return ball;
+}
+
+- (CGRect)rect
+{
+ CGSize s = [self.texture contentSize];
+ return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
+}
+
+- (void)onEnter
+{
+ [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
+ [super onEnter];
+}
+
+- (void)onExit
+{
+ [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
+ [super onExit];
+}
+
+- (BOOL)containsTouchLocation:(UITouch *)touch
+{
+ return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
+}
+
+- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
+{
+ if ( ![self containsTouchLocation:touch] ) return NO;
+
+ id flip = [CCFlipX3D actionWithDuration:0.5];
+ [self runAction:flip];
+ NSLog([NSString stringWithFormat:@"touch:%d", [self number]]);
+ return YES;
+}
+
+@end
View
17 Classes/BrainShotAppDelegate.h
@@ -0,0 +1,17 @@
+//
+// BrainShotAppDelegate.h
+// BrainShot
+//
+// Created by cogent on 10-3-29.
+// Copyright __MyCompanyName__ 2010. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+
+@interface BrainShotAppDelegate : NSObject <UIApplicationDelegate> {
+ UIWindow *window;
+}
+
+@property (nonatomic, retain) UIWindow *window;
+
+@end
View
83 Classes/BrainShotAppDelegate.m
@@ -0,0 +1,83 @@
+//
+// BrainShotAppDelegate.m
+// BrainShot
+//
+// Created by cogent on 10-3-29.
+// Copyright __MyCompanyName__ 2010. All rights reserved.
+//
+
+#import "BrainShotAppDelegate.h"
+#import "cocos2d.h"
+#import "HelloWorldScene.h"
+
+@implementation BrainShotAppDelegate
+
+@synthesize window;
+
+- (void) applicationDidFinishLaunching:(UIApplication*)application
+{
+ // Init the window
+ window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
+
+ // cocos2d will inherit these values
+ [window setUserInteractionEnabled:YES];
+ [window setMultipleTouchEnabled:YES];
+
+ // Try to use CADisplayLink director
+ // if it fails (SDK < 3.1) use the default director
+ if( ! [CCDirector setDirectorType:CCDirectorTypeDisplayLink] )
+ [CCDirector setDirectorType:CCDirectorTypeDefault];
+
+ // Use RGBA_8888 buffers
+ // Default is: RGB_565 buffers
+ [[CCDirector sharedDirector] setPixelFormat:kPixelFormatRGBA8888];
+
+ // Create a depth buffer of 16 bits
+ // Enable it if you are going to use 3D transitions or 3d objects
+// [[CCDirector sharedDirector] setDepthBufferFormat:kDepthBuffer16];
+
+ // Default texture format for PNG/BMP/TIFF/JPEG/GIF images
+ // It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
+ // You can change anytime.
+ [CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];
+
+ // before creating any layer, set the landscape mode
+ [[CCDirector sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
+ [[CCDirector sharedDirector] setAnimationInterval:1.0/60];
+ [[CCDirector sharedDirector] setDisplayFPS:YES];
+
+ // create an openGL view inside a window
+ [[CCDirector sharedDirector] attachInView:window];
+ [window makeKeyAndVisible];
+
+ [[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];
+}
+
+
+- (void)applicationWillResignActive:(UIApplication *)application {
+ [[CCDirector sharedDirector] pause];
+}
+
+- (void)applicationDidBecomeActive:(UIApplication *)application {
+ [[CCDirector sharedDirector] resume];
+}
+
+- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
+ [[CCTextureCache sharedTextureCache] removeUnusedTextures];
+}
+
+- (void)applicationWillTerminate:(UIApplication *)application {
+ [[CCDirector sharedDirector] end];
+}
+
+- (void)applicationSignificantTimeChange:(UIApplication *)application {
+ [[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
+}
+
+- (void)dealloc {
+ [[CCDirector sharedDirector] release];
+ [window release];
+ [super dealloc];
+}
+
+@end
View
13 Classes/HelloWorldScene.h
@@ -0,0 +1,13 @@
+
+// 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
View
67 Classes/HelloWorldScene.m
@@ -0,0 +1,67 @@
+//
+// cocos2d Hello World example
+// http://www.cocos2d-iphone.org
+//
+
+// Import the interfaces
+#import "HelloWorldScene.h"
+#import "Ball.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] )) {
+
+ // ask director the the window size
+ //CGSize size = [[CCDirector sharedDirector] winSize];
+
+ int sum = 0;
+ for (int left=0; left<10; left++) {
+ for (int right=0; right<6; right++) {
+ sum++;
+ Ball *ball = [Ball withLabel:sum AtLeftIndex:left AndRightIndex:right];
+ [self addChild:ball];
+ }
+ }
+
+ //[self schedule:@selector(hideNumber:)];
+ }
+ return self;
+}
+
+-(void) hideNumber:(ccTime)dt
+{
+ //NSLog(@"hide");
+}
+
+// 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
View
21 LICENSE.cocos2d
@@ -0,0 +1,21 @@
+cocos2d for iPhone license:
+---------------------------
+
+cocos2d for iPhone was originally licensed under the GNU LGPL v3 license.
+But since it is impossible to distribute 3rd party dynamic libraries
+for the iPhone, this license extends the GNU LGPL v3 license by allowing you:
+ a) to use cocos2d for iPhone as a static library
+ b) to include all or part of the cocos2d for iPhone sources inside your project
+
+This means that if you do a) and/or b) you are NOT forced to release your
+source code under the GNU LGPL v3 license.
+
+What is an improvement to the library and what's part of your game is
+decided by the your own good faith.
+
+Remember that cocos2d for iPhone follows the copyleft idea. So if you think that
+you're improving the library, share your changes with the community with this same
+license.
+
+
+If you have any doubt regarding the license, please contact Ricardo Quesada.
View
22 LICENSE.cocosdenshion
@@ -0,0 +1,22 @@
+/* CocosDenshion Sound Engine
+ *
+ * Copyright (C) 2009 Steve Oldmeadow
+ *
+ * For independent entities this program is free software; you can redistribute
+ * it and/or modify it under the terms of the 'cocos2d for iPhone' license with
+ * the additional proviso that 'cocos2D for iPhone' must be credited in a manner
+ * that can be be observed by end users, for example, in the credits or during
+ * start up. Failure to include such notice is deemed to be acceptance of a
+ * non independent license (see below).
+ *
+ * For the purpose of this software non independent entities are defined as
+ * those where the annual revenue of the entity employing, partnering, or
+ * affiliated in any way with the Licensee is greater than $250,000 USD annually.
+ *
+ * Non independent entities may license this software or a derivation of it
+ * by a donation of $500 USD per application to the cocos2d for iPhone project.
+ *
+ * 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.
+ */
View
99 Makefile
@@ -0,0 +1,99 @@
+# Makefile for iPhone Application for Xcode gcc compiler (SDK Headers)
+
+PROJECTNAME=iphone
+APPFOLDER=$(PROJECTNAME).app
+INSTALLFOLDER=$(PROJECTNAME).app
+
+IPHONE_IP=192.168.1.76
+
+CC=arm-apple-darwin9-gcc
+LD=$(CC)
+
+LDFLAGS= -lobjc \
+ -bind_at_load \
+ -framework Foundation \
+ -framework CoreFoundation \
+ -framework UIKit \
+ -framework CoreGraphics \
+ -lsqlite3.0 \
+ -w
+#LDFLAGS += -framework AddressBookUI
+#LDFLAGS += -framework AddressBook
+#LDFLAGS += -framework QuartzCore
+#LDFLAGS += -framework CoreAudio
+#LDFLAGS += -framework AudioToolbox
+#LDFLAGS += -framework SystemConfiguration
+#LDFLAGS += -framework CFNetwork
+#LDFLAGS += -framework MediaPlayer
+
+CFLAGS = -DDEBUG -std=c99
+#TODO:how to make it search subdir
+CFLAGS += -I./Classes/ObjectiveResource
+CFLAGS += -I./Classes/ObjectiveResource/objective_support/Core
+CFLAGS += -I./Classes/ObjectiveResource/objective_support/Core/Inflections
+CFLAGS += -I./Classes/ObjectiveResource/objective_support/Serialization
+CFLAGS += -I./Classes/ObjectiveResource/objective_support/Serialization/XML
+CFLAGS += -I./Classes/ObjectiveResource/objective_support/Serialization/JSON
+CFLAGS += -I./Classes/ObjectiveResource/objective_support/json-framework
+CFLAGS += -I./Classes/SQLPO
+CFLAGS += -I./Classes/Models
+
+#一定要引入pre-compiled header,否则每个source要手动引入Foundation/Foundation.h
+CFLAGS += -include ./*_Prefix.pch
+#以下内容会导致iphone报 No class named iphoneAppDelegate is loaded的错误
+#CFLAGS += -x objective-c-header
+
+
+BUILDDIR=./build
+SRCDIR=./Classes
+RESDIR=./Resources
+OBJS=$(patsubst %.m,%.o,$(wildcard $(SRCDIR)/*.m))
+OBJS+=$(patsubst %.m,%.o,$(wildcard $(SRCDIR)/**/*.m))
+OBJS+=$(patsubst %.m,%.o,$(wildcard $(SRCDIR)/**/**/*.m))
+OBJS+=$(patsubst %.m,%.o,$(wildcard $(SRCDIR)/**/**/**/*.m))
+OBJS+=$(patsubst %.m,%.o,$(wildcard $(SRCDIR)/**/**/**/**/*.m))
+OBJS+=$(patsubst %.m,%.o,$(wildcard $(SRCDIR)/**/**/**/**/**/*.m))
+OBJS+=$(patsubst %.c,%.o,$(wildcard $(SRCDIR)/**/*.c))
+#指定根目录下的main.m,否则会出现编译MakeFile.o
+OBJS+=$(patsubst %.m,%.o,$(wildcard *.m))
+RESOURCES=$(wildcard $(RESDIR)/*)
+
+all: $(PROJECTNAME) bundle
+
+$(PROJECTNAME): $(OBJS)
+ $(LD) $(LDFLAGS) -o $@ $^
+
+bundle: $(PROJECTNAME)
+ @mkdir -p $(BUILDDIR)/$(APPFOLDER)
+ @mv $(PROJECTNAME) $(BUILDDIR)/$(APPFOLDER)/$(PROJECTNAME)_
+ @cp -r $(RESOURCES) $(BUILDDIR)/$(APPFOLDER)
+ @#破解签名的需要使用sh文件转向至已签名的可执行文件
+ @cat toolchain.sh | sed 's/$${PRODUCT_NAME.*}/$(PROJECTNAME)/' > $(BUILDDIR)/$(APPFOLDER)/$(PROJECTNAME)
+ @chmod +x $(BUILDDIR)/$(APPFOLDER)/$(PROJECTNAME)
+ @#替换Info.plist中的变量
+ @cat $(PROJECTNAME)-Info.plist | sed 's/$${PRODUCT_NAME.*}/$(PROJECTNAME)/' | sed 's/$${EXECUTABLE_NAME}/$(PROJECTNAME)/' > $(BUILDDIR)/$(APPFOLDER)/Info.plist
+ @echo "APPL????" > $(BUILDDIR)/$(APPFOLDER)/PkgInfo
+
+main.o: main.m
+ $(CC) -c $< -o $@
+
+%.o: %.m
+ $(CC) -c $(CFLAGS) $< -o $@
+
+deploy: all
+ @ssh root@$(IPHONE_IP) "cd /Applications/$(INSTALLFOLDER) && rm -R * || echo 'not found' "
+ @scp -r $(BUILDDIR)/$(APPFOLDER) root@$(IPHONE_IP):/Applications
+ @ssh root@$(IPHONE_IP) "cd /Applications/$(INSTALLFOLDER) ; ldid -S $(PROJECTNAME)_;"
+
+#不用每次deploy都kill spring,修改的代码会生效
+spring:
+ @ssh root@$(IPHONE_IP) "killall SpringBoard"
+
+uninstall:
+ @ssh root@$(IPHONE_IP) 'rm -fr /Applications/$(INSTALLFOLDER); killall SpringBoard'
+ @echo "Application $(INSTALLFOLDER) uninstalled"
+
+clean:
+ @rm -f $(SRCDIR)/*.o $(SRCDIR)/**/*.o *.o
+ @rm -rf $(BUILDDIR)
+ @rm -f $(PROJECTNAME)
View
BIN  Resources/Default.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  Resources/Icon.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
33 Resources/Info.plist
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleDisplayName</key>
+ <string>${PRODUCT_NAME}</string>
+ <key>CFBundleExecutable</key>
+ <string>${EXECUTABLE_NAME}</string>
+ <key>CFBundleIconFile</key>
+ <string></string>
+ <key>CFBundleIdentifier</key>
+ <string>com.yourcompany.${PRODUCT_NAME:rfc1034identifier}</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleVersion</key>
+ <string>2.0</string>
+ <key>LSRequiresIPhoneOS</key>
+ <true/>
+ <key>UIStatusBarHidden</key>
+ <true/>
+ <key>UIRequiredDeviceCapabilities</key>
+ <dict>
+ <key>accelerometer</key>
+ <true/>
+ <key>opengles-1</key>
+ <true/>
+ </dict>
+</dict>
+</plist>
View
BIN  Resources/circle_blue.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  Resources/circle_green.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  Resources/circle_orange.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  Resources/circle_red.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  Resources/fps_images.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
209 libs/CocosDenshion/CDAudioManager.h
@@ -0,0 +1,209 @@
+/* CocosDenshion Audio Manager
+ *
+ * Copyright (C) 2009 Steve Oldmeadow
+ *
+ * For independent entities this program is free software; you can redistribute
+ * it and/or modify it under the terms of the 'cocos2d for iPhone' license with
+ * the additional proviso that 'cocos2D for iPhone' must be credited in a manner
+ * that can be be observed by end users, for example, in the credits or during
+ * start up. Failure to include such notice is deemed to be acceptance of a
+ * non independent license (see below).
+ *
+ * For the purpose of this software non independent entities are defined as
+ * those where the annual revenue of the entity employing, partnering, or
+ * affiliated in any way with the Licensee is greater than $250,000 USD annually.
+ *
+ * Non independent entities may license this software or a derivation of it
+ * by a donation of $500 USD per application to the cocos2d for iPhone project.
+ *
+ * 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.
+ *
+ */
+
+#import "CocosDenshion.h"
+#import <AVFoundation/AVFoundation.h>
+
+/** 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 <NSObject>
+@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 <AVAudioPlayerDelegate>{
+ AVAudioPlayer *audioSourcePlayer;
+ NSString *audioSourceFilePath;
+ NSInteger numberOfLoops;
+ float volume;
+ id<CDLongAudioSourceDelegate> delegate;
+ BOOL mute;
+@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;
+/** If mute is NO then no audio is output, however, audio will continue to advance.
+ If you do not want that to happen then pause or stop the audio.
+ */
+@property (readwrite, nonatomic) BOOL mute;
+@property(assign) id<CDLongAudioSourceDelegate> delegate;
+
+/** 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 <CDLongAudioSourceDelegate> {
+ CDSoundEngine *soundEngine;
+ CDLongAudioSource *backgroundMusic;
+ NSMutableArray *audioSourceChannels;
+ UInt32 _audioSessionCategory;
+ BOOL _audioWasPlayingAtStartup;
+ tAudioManagerMode _mode;
+ SEL backgroundMusicCompletionSelector;
+ id backgroundMusicCompletionListener;
+ BOOL willPlayBackgroundMusic;
+ BOOL _mute;
+ BOOL _muteStoppedMusic;
+
+ //For handling resign/become active
+ BOOL _isObservingAppEvents;
+ tAudioManagerResignBehavior _resignBehavior;
+}
+
+@property (readonly) CDSoundEngine *soundEngine;
+@property (readonly) CDLongAudioSource *backgroundMusic;
+@property (readonly) BOOL willPlayBackgroundMusic;
+@property (readwrite) BOOL mute;
+
+/** Returns the shared singleton */
++ (CDAudioManager *) sharedManager;
++ (tAudioManagerState) sharedManagerState;
+/** Configures the shared singleton with a mode, a channel definition and a total number of channels */
++ (void) configure: (tAudioManagerMode) mode channelGroupDefinitions:(int[]) channelGroupDefinitions channelGroupTotal:(int) channelGroupTotal;
+/** Initializes the engine asynchronously with a mode, channel definition and a total number of channels */
++ (void) initAsynchronously: (tAudioManagerMode) mode channelGroupDefinitions:(int[]) channelGroupDefinitions channelGroupTotal:(int) channelGroupTotal;
+/** Initializes the engine synchronously with a mode, channel definition and a total number of channels */
+- (id) init: (tAudioManagerMode) mode channelGroupDefinitions:(int[]) channelGroupDefinitions channelGroupTotal:(int) channelGroupTotal;
+-(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;
+
+//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 .mp3 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
View
680 libs/CocosDenshion/CDAudioManager.m
@@ -0,0 +1,680 @@
+/* CocosDenshion Audio Manager
+ *
+ * Copyright (C) 2009 Steve Oldmeadow
+ *
+ * For independent entities this program is free software; you can redistribute
+ * it and/or modify it under the terms of the 'cocos2d for iPhone' license with
+ * the additional proviso that 'cocos2D for iPhone' must be credited in a manner
+ * that can be be observed by end users, for example, in the credits or during
+ * start up. Failure to include such notice is deemed to be acceptance of a
+ * non independent license (see below).
+ *
+ * For the purpose of this software non independent entities are defined as
+ * those where the annual revenue of the entity employing, partnering, or
+ * affiliated in any way with the Licensee is greater than $250,000 USD annually.
+ *
+ * Non independent entities may license this software or a derivation of it
+ * by a donation of $500 USD per application to the cocos2d for iPhone project.
+ *
+ * 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.
+ *
+ */
+
+#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;
+
+-(id) init {
+ if ((self = [super init])) {
+ state = kLAS_Init;
+ volume = 1.0f;
+ mute = NO;
+ }
+ return self;
+}
+
+-(void) dealloc {
+ [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;
+ NSString *path = [CDUtilities fullPathFromRelativePath:audioSourceFilePath];
+ audioSourcePlayer = [[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 stop];
+ [self rewind];
+ }
+ audioSourcePlayer.volume = volume;
+ audioSourcePlayer.numberOfLoops = numberOfLoops;
+ state = kLAS_Loaded;
+}
+
+-(void) play {
+ self->systemPaused = NO;
+ [audioSourcePlayer play];
+}
+
+-(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) {
+ audioSourcePlayer.volume = newVolume;
+ }
+}
+
+-(float) volume
+{
+ return volume;
+}
+
+-(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;
+ }
+}
+
+-(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");
+ [player play];
+}
+
+@end
+
+
+@interface CDAudioManager (PrivateMethods)
+
+@end
+
+
+@implementation CDAudioManager
+#define BACKGROUND_MUSIC_CHANNEL kASC_Left
+
+@synthesize soundEngine, willPlayBackgroundMusic;
+static CDAudioManager *sharedManager;
+static tAudioManagerState _sharedManagerState = kAMStateUninitialised;
+static tAudioManagerMode configuredMode;
+static int *configuredChannelGroupDefinitions;
+static int configuredChannelGroupTotal;
+static BOOL configured = FALSE;
+
+// Init
++ (CDAudioManager *) sharedManager
+{
+ @synchronized(self) {
+ if (!sharedManager) {
+ if (!configured) {
+ //Set defaults here
+ configuredMode = kAMM_FxPlusMusicIfNoOtherAudio;
+ //Just create one channel group with all the sources
+ //configuredChannelGroupDefinitions = new int[1];
+ configuredChannelGroupDefinitions = (int *)malloc( sizeof(configuredChannelGroupDefinitions[0]) * 1);
+ configuredChannelGroupDefinitions[0] = CD_MAX_SOURCES;
+ configuredChannelGroupTotal = 1;
+ }
+ sharedManager = [[CDAudioManager alloc] init:configuredMode channelGroupDefinitions:configuredChannelGroupDefinitions channelGroupTotal:configuredChannelGroupTotal];
+ _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 channelGroupDefinitions:(int[]) channelGroupDefinitions channelGroupTotal:(int) channelGroupTotal {
+ @synchronized(self) {
+ if (_sharedManagerState == kAMStateUninitialised) {
+ _sharedManagerState = kAMStateInitialising;
+ [CDAudioManager configure:mode channelGroupDefinitions:channelGroupDefinitions channelGroupTotal:channelGroupTotal];
+ 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 channelGroupDefinitions:(int[]) channelGroupDefinitions channelGroupTotal:(int) channelGroupTotal {
+ configuredMode = mode;
+ //configuredChannelGroupDefinitions = new int[channelGroupTotal];
+ //NB: memory leak here if configure is called more than once, it is not intended to be used that way though (SO).
+ configuredChannelGroupDefinitions = (int *)malloc( sizeof(configuredChannelGroupDefinitions[0]) * channelGroupTotal);
+ if(!configuredChannelGroupDefinitions) {
+ CDLOG(@"Denshion::CDAudioManager - configuredChannelGroupDefinitions memory allocation failed");
+ //If this happens we are toast, basically run out of memory but we'll return to avoid a null
+ //pointer reference below and keep clang happy.
+ configured = FALSE;
+ return;
+ }
+
+ for (int i=0; i < channelGroupTotal; i++) {
+ configuredChannelGroupDefinitions[i] = channelGroupDefinitions[i];
+ }
+ configuredChannelGroupTotal = channelGroupTotal;
+ configured = TRUE;
+}
+
+//Experimental TODO: review this
+/*
+- (void) determineCapabilities {
+ Class audioSessionClass = NSClassFromString(@"AVAudioSession");
+ if (audioSessionClass != nil) {
+ CDLOG(@"Denshion::CDAudioManager - AVAudioSession exists");
+ }
+}
+*/
+
+-(BOOL) isOtherAudioPlaying {
+ UInt32 isPlaying;
+ UInt32 varSize = sizeof(isPlaying);
+ AudioSessionGetProperty (kAudioSessionProperty_OtherAudioIsPlaying, &varSize, &isPlaying);
+ return (isPlaying != 0);
+}
+
+-(void) setMode:(tAudioManagerMode) mode {
+
+ AudioSessionSetActive(NO);
+ _mode = mode;
+ switch (_mode) {
+
+ case kAMM_FxOnly:
+ //Share audio with other app
+ CDLOG(@"Denshion::CDAudioManager - Audio will be shared");
+ _audioSessionCategory = kAudioSessionCategory_AmbientSound;
+ 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;
+ 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;
+ 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;
+ willPlayBackgroundMusic = YES;
+ break;
+
+ default:
+ //kAudioManagerFxPlusMusicIfNoOtherAudio
+ if ([self isOtherAudioPlaying]) {
+ CDLOG(@"Denshion::CDAudioManager - Other audio is playing audio will be shared");
+ _audioSessionCategory = kAudioSessionCategory_AmbientSound;
+ willPlayBackgroundMusic = NO;
+ } else {
+ CDLOG(@"Denshion::CDAudioManager - Other audio is not playing audio will be exclusive");
+ _audioSessionCategory = kAudioSessionCategory_SoloAmbientSound;
+ willPlayBackgroundMusic = YES;
+ }
+
+ break;
+ }
+
+ //Set audio session category
+ if (willPlayBackgroundMusic) {
+ //Work around to ensure background music is not decoded in software
+ //on OS 3.0. Thanks to Bryan Acceleroto (SO 2009.07.02)
+ UInt32 fakeCategory = kAudioSessionCategory_MediaPlayback;
+ AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(fakeCategory), &fakeCategory);
+ AudioSessionSetActive(YES);
+ AudioSessionSetActive(NO);
+ }
+ AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(_audioSessionCategory), &_audioSessionCategory);
+ AudioSessionSetActive(YES);
+
+}
+
+- (id) init: (tAudioManagerMode) mode channelGroupDefinitions:(int[]) channelGroupDefinitions channelGroupTotal:(int) channelGroupTotal {
+ if ((self = [super init])) {
+
+ //Initialise the audio session
+ AudioSessionInitialize(NULL, NULL,managerInterruptionCallback, self);
+
+ _mode = mode;
+ backgroundMusicCompletionSelector = nil;
+ _isObservingAppEvents = FALSE;
+ _muteStoppedMusic = FALSE;
+ [self setMode:mode];
+ soundEngine = [[CDSoundEngine alloc] init:channelGroupDefinitions channelGroupTotal:channelGroupTotal];
+
+ //Set up audioSource channels
+ audioSourceChannels = [[NSMutableArray alloc] init];
+ CDLongAudioSource *leftChannel = [[CDLongAudioSource alloc] init];
+ CDLongAudioSource *rightChannel = [[CDLongAudioSource alloc] init];
+ [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;
+ }
+ return self;
+}
+
+-(void) dealloc {
+ [self stopBackgroundMusic];
+ [soundEngine release];
+ if (_isObservingAppEvents) {
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
+ }
+ AudioSessionSetActive(FALSE);
+ if (configuredChannelGroupDefinitions) {
+ free(configuredChannelGroupDefinitions);
+ }
+ [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
+}
+
+-(BOOL) mute {
+ return _mute;
+}
+
+-(void) setMute:(BOOL) muteValue {
+ [soundEngine setMute:muteValue];
+ _mute = muteValue;
+ for( CDLongAudioSource *audioSource in audioSourceChannels) {
+ audioSource.mute = muteValue;
+ }
+}
+
+-(CDLongAudioSource*) backgroundMusic
+{
+ return backgroundMusic;
+}
+
+//Load background music ready for playing
+-(void) preloadBackgroundMusic:(NSString*) filePath
+{
+ if (!willPlayBackgroundMusic) {
+ CDLOG(@"Denshion::CDAudioManager - preload background music aborted because audio is not exclusive");
+ return;
+ }
+ [self.backgroundMusic load:filePath];
+}
+
+-(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop
+{
+ if (!willPlayBackgroundMusic || _mute) {
+ CDLOG(@"Denshion::CDAudioManager - play bgm aborted because audio is not exclusive or sound is muted");
+ return;
+ }
+
+ [self.backgroundMusic load:filePath];
+ 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
+{
+ [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;
+}
+
+//Called when application resigns active only if setResignBehavior has been called
+- (void) applicationWillResignActive:(NSNotification *) notification
+{
+
+ 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 - handling resign active");
+}
+
+//Called when application becomes active only if setResignBehavior has been called
+- (void) applicationDidBecomeActive:(NSNotification *) notification
+{
+
+ 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
+ for( CDLongAudioSource *audioSource in audioSourceChannels) {
+ if (audioSource->systemPaused) {
+ [audioSource resume];
+ audioSource->systemPaused = NO;
+ }
+ }
+ break;
+
+ default:
+ break;
+
+ }
+ CDLOG(@"Denshion::CDAudioManager - audio manager handling become active");
+
+}
+
+//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];
+ }
+}
+
+//Code to handle audio session interruption. Thanks to Andy Fitter and Ben Britten.
+-(void)audioSessionInterrupted
+{
+ CDLOG(@"Denshion::CDAudioManager - Audio session interrupted");
+ ALenum error = AL_NO_ERROR;
+ // Deactivate the current audio session
+ AudioSessionSetActive(NO);
+ // 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);
+ }
+ // now suspend your context to 'pause' your sound world
+ alcSuspendContext([soundEngine openALContext]);
+ if((error = alGetError()) != AL_NO_ERROR) {
+ CDLOG(@"Denshion::CDAudioManager - Error suspending context %x\n", error);
+ }
+ #pragma unused(error)
+}
+
+//Code to handle audio session resumption. Thanks to Andy Fitter and Ben Britten.
+-(void)audioSessionResumed
+{
+ ALenum error = AL_NO_ERROR;
+ CDLOG(@"Denshion::CDAudioManager - Audio session resumed");
+ // Reset audio session
+ OSStatus result = AudioSessionSetProperty ( kAudioSessionProperty_AudioCategory, sizeof(_audioSessionCategory), &_audioSessionCategory );
+
+ // Reactivate the current audio session
+ result = AudioSessionSetActive(YES);
+ #pragma unused(result)
+
+ // 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)
+ // 'unpause' my context
+ alcProcessContext([soundEngine openALContext]);
+ if((error = alGetError()) != AL_NO_ERROR) {
+ CDLOG(@"Denshion::CDAudioManager - Error processing context%x\n", error);
+ }
+}
+
++(void) end {
+ [sharedManager release];
+}
+
+@end
View
56 libs/CocosDenshion/CDConfig.h
@@ -0,0 +1,56 @@
+/* CocosDenshion Configuration
+ *
+ * Copyright (C) 2010 Steve Oldmeadow
+ *
+ * For independent entities this program is free software; you can redistribute
+ * it and/or modify it under the terms of the 'cocos2d for iPhone' license with
+ * the additional proviso that 'cocos2D for iPhone' must be credited in a manner
+ * that can be be observed by end users, for example, in the credits or during
+ * start up. Failure to include such notice is deemed to be acceptance of a
+ * non independent license (see below).
+ *
+ * For the purpose of this software non independent entities are defined as
+ * those where the annual revenue of the entity employing, partnering, or
+ * affiliated in any way with the Licensee is greater than $250,000 USD annually.
+ *
+ * Non independent entities may license this software or a derivation of it
+ * by a donation of $500 USD per application to the cocos2d for iPhone project.
+ *
+ * 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.
+ */
+
+/**
+ 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
+ */
+#define CD_MAX_BUFFERS 64
+
+/**
+ 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
+
+
+
+
View
286 libs/CocosDenshion/CDOpenALSupport.h
@@ -0,0 +1,286 @@
+/*
+
+ 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.
+
+
+ */
+
+/*
+ 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.
+ */
+
+#import <OpenAL/al.h>
+#import <OpenAL/alc.h>
+#import <AudioToolbox/AudioToolbox.h>
+#import <AudioToolbox/ExtendedAudioFile.h>
+
+//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);
+ }
+}
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+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;
+}
+
+
View
235 libs/CocosDenshion/CocosDenshion.h
@@ -0,0 +1,235 @@
+/* CocosDenshion Sound Engine
+ *
+ * Copyright (C) 2009 Steve Oldmeadow
+ *
+ * For independent entities this program is free software; you can redistribute
+ * it and/or modify it under the terms of the 'cocos2d for iPhone' license with
+ * the additional proviso that 'cocos2D for iPhone' must be credited in a manner
+ * that can be be observed by end users, for example, in the credits or during
+ * start up. Failure to include such notice is deemed to be acceptance of a
+ * non independent license (see below).
+ *
+ * For the purpose of this software non independent entities are defined as
+ * those where the annual revenue of the entity employing, partnering, or
+ * affiliated in any way with the Licensee is greater than $250,000 USD annually.
+ *
+ * Non independent entities may license this software or a derivation of it
+ * by a donation of $500 USD per application to the cocos2d for iPhone project.
+ *
+ * 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.
+ *
+ */
+
+/**
+@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 <UIKit/UIKit.h>
+#import <OpenAL/al.h>
+#import <OpenAL/alc.h>
+#import <AudioToolbox/AudioToolbox.h>
+#import "CDConfig.h"
+
+#if CD_DEBUG
+#define CDLOG(...) NSLog(__VA_ARGS__)
+#else
+#define CDLOG(...) do {} while (0)
+#endif
+
+
+#define CD_MAX_SOURCES 32 //Total number of playback channels that can be created (32 is the limit)
+#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_CHANNEL_GROUP_NON_INTERRUPTIBLE 0xFEDEEFF //User internally to indicate channel group is not interruptible
+#define CD_MUTE 0xFEEDBAB //Return value indicating sound engine is muted or non functioning
+
+#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
+
+enum bufferState {
+ CD_BS_EMPTY = 0,
+ CD_BS_LOADED = 1,
+ CD_BS_FAILED = 2
+};
+
+typedef struct _channelGroup {
+ int startIndex;
+ int endIndex;
+ int currentIndex;
+ bool mute;
+} channelGroup;
+
+/**
+ Collectin 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
+
+
+////////////////////////////////////////////////////////////////////////////
+
+/** 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
+ */
+@interface CDSoundEngine : NSObject {
+
+ ALuint *_sources;
+ ALuint *_buffers;
+ int *_bufferStates;
+ ALuint *_sourceBufferAttachments;
+#ifdef CD_USE_STATIC_BUFFERS
+ ALvoid **_bufferData;
+#endif
+ channelGroup *_channelGroups;
+ ALCcontext *context;
+ int _channelGroupTotal;
+ int _channelTotal;
+ UInt32 _audioSessionCategory;
+ BOOL _handleAudioSession;
+ BOOL _mute;
+ ALfloat _preMuteGain;
+
+ ALenum lastErrorCode;
+ BOOL functioning;
+ float asynchLoadProgress;
+
+}
+
+@property (readwrite, nonatomic) ALfloat masterGain;
+@property (readwrite, nonatomic) BOOL mute;
+@property (readonly) ALenum lastErrorCode;//Last OpenAL error code that was generated
+@property (readonly) BOOL functioning;//Is the sound engine functioning
+@property (readwrite) float asynchLoadProgress;
+
+/** 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:(int[]) channelGroupDefinitions channelGroupTotal:(int) channelGroupTotal;
+/** Initializes the engine with a group definition, a total number of groups and an audio session category */
+- (id)init:(int[]) channelGroupDefinitions channelGroupTotal:(int) channelGroupTotal audioSessionCategory:(UInt32) audioSessionCategory;
+
+/** Plays a sound in a channel group with a pitch, pan and gain. The sound could played looped or not */
+- (ALuint) playSound:(int) soundId channelGroupId:(int)channelGroupId pitch:(float) pitch pan:(float) pan gain:(float) gain loop:(BOOL) loop;
+
+/** Stops playing a sound */
+- (void) stopSound:(ALuint) sourceId;
+/** Stops playing a channel group */
+- (void) stopChannelGroup:(int) channelGroupId;
+/** Stops all playing sounds */
+-(void) stopAllSounds;
+- (void) setChannelGroupNonInterruptible:(int) channelGroupId isNonInterruptible:(BOOL) isNonInterruptible;
+- (void) setChannelGroupMute:(int) channelGroupId mute:(BOOL) mute;
+- (BOOL) channelGroupMute:(int) channelGroupId;
+- (BOOL) loadBuffer:(int) soundId filePath:(NSString*) filePath;
+- (void) loadBuffersAsynchronously:(NSArray *) loadRequests;
+- (BOOL) unloadBuffer:(int) soundId;
+- (ALCcontext *) openALContext;
+- (void) audioSessionInterrupted;
+- (void) audioSessionResumed;
+
+@end
+
+////////////////////////////////////////////////////////////////////////////
+@interface CDSourceWrapper : NSObject {
+ ALuint sourceId;
+ float lastPitch;
+ float lastPan;
+ float lastGain;
+ BOOL lastLooping;
+}
+@property (readwrite, nonatomic) ALuint sourceId;
+@property (readwrite, nonatomic) float pitch;
+@property (readwrite, nonatomic) float gain;
+@property (readwrite, nonatomic) float pan;
+@property (readwrite, nonatomic) BOOL looping;
+@property (readonly) BOOL isPlaying;
+
+@end
+
+////////////////////////////////////////////////////////////////////////////
+@interface CDAsynchBufferLoader : NSOperation {
+ NSArray *_loadRequests;
+ CDSoundEngine *_soundEngine;
+}
+
+-(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine;
+
+@end
+
+////////////////////////////////////////////////////////////////////////////
+
+@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
View
877 libs/CocosDenshion/CocosDenshion.m
@@ -0,0 +1,877 @@
+/* CocosDenshion Sound Engine
+ *
+ * Copyright (C) 2009 Steve Oldmeadow
+ *
+ * For independent entities this program is free software; you can redistribute
+ * it and/or modify it under the terms of the 'cocos2d for iPhone' license with
+ * the additional proviso that 'cocos2D for iPhone' must be credited in a manner
+ * that can be be observed by end users, for example, in the credits or during
+ * start up. Failure to include such notice is deemed to be acceptance of a
+ * non independent license (see below).
+ *
+ * For the purpose of this software non independent entities are defined as
+ * those where the annual revenue of the entity employing, partnering, or
+ * affiliated in any way with the Licensee is greater than $250,000 USD annually.
+ *
+ * Non independent entities may license this software or a derivation of it
+ * by a donation of $500 USD per application to the cocos2d for iPhone project.
+ *
+ * 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.
+ *
+ */
+
+#import "CocosDenshion.h"
+#import "CDOpenALSupport.h"
+
+
+//Audio session interruption callback - used if sound engine is
+//handling audio session interruption automatically
+extern void interruptionListenerCallback (void *inUserData, UInt32 interruptionState ) {
+ CDSoundEngine *controller = (CDSoundEngine *) inUserData;
+ if (interruptionState == kAudioSessionBeginInterruption) {
+ [controller audioSessionInterrupted];
+ } else if (interruptionState == kAudioSessionEndInterruption) {
+ [controller audioSessionResumed];
+ }
+}
+
+@interface CDSoundEngine (PrivateMethods)
+-(ALuint) _startSound:(int) soundId channelId:(int) channelId pitchVal:(float) pitchVal panVal:(float) panVal gainVal:(float) gainVal looping:(BOOL) looping checkState:(BOOL) checkState;
+- (BOOL) _initOpenAL;
+@end
+
+@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
+
+
+@implementation CDSoundEngine
+
+static Float32 _mixerSampleRate;
+static BOOL _mixerRateSet = NO;
+
+@synthesize lastErrorCode, functioning, asynchLoadProgress;
+
++ (void) setMixerSampleRate:(Float32) sampleRate {
+ _mixerRateSet = YES;
+ _mixerSampleRate = sampleRate;
+}
+
+/**
+ * Internal method called during init
+ */
+- (BOOL) _initOpenAL
+{
+ //ALenum error;
+ context = NULL;
+ ALCdevice *newDevice = NULL;
+
+ //_buffers = new ALuint[CD_MAX_BUFFERS];
+ _buffers = (ALuint *)malloc( sizeof(_buffers[0]) * CD_MAX_BUFFERS );
+ if(!_buffers) {
+ CDLOG(@"Denshion::CDSoundEngine - buffer memory allocation failed");
+ return FALSE;
+ }
+
+ //_sources = new ALuint[CD_MAX_SOURCES];
+ _sources = (ALuint *)malloc( sizeof(_sources[0]) * CD_MAX_SOURCES );
+ if(!_sources) {
+ CDLOG(@"Denshion::CDSoundEngine - source memory allocation failed");
+ return FALSE;
+ }
+
+ //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)