'Projects'에 해당되는 글 2건

  1. 2010.06.24 iPhone Cool Projects
  2. 2010.06.24 iPhone Games Projects
아이폰어플개발정보2010. 6. 24. 14:13
iPhone Cool Projects

Ch1. MVC architecture using game object


Formic: simplified version of the game Frenzic

Good games are not created on the drawing board; you have to play them to see what’s great and what’s not, and alter accordingly.


* 2 approaches to the problem of synch. between game and view

1. Pieces going into an animation would be removed from the normal view storage and put into a special animation queue. View controller queries the game object.

2. Block the game until the animation is finished. (simple but not acceptable all the time)


* UIView: properties that can be animated

- frame, bounds, and center (i.e., position)

- alpha (i.e., transparency)

- transform (i.e., size)


* series of animations

- method 1

[UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationDidStop:finish:)];

- method 2

performSelector:WithObject: afterDelay:


** iPhone-Specific Functionality

* Activation and deactivation

- (void)applicationWillResignActive:(UIApplication *)application;

: sent to app delegate

: when the user pressed sleep button

: stop all timers, animations, and sound and go into pause state

- (void)applicationDidBecomeActive:(UIApplication *)application;

* Memory warnings

- (void)didReceiveMemoryWarning;

: sent to all view controllers

: When your application receives memory warnings but fails to free enough memory, the operating system will simply shut down your application. (vs. crash)

* Saving and restoring the game (when quitting and opening the application)

- applicationDidFinishLaunching:

- applicationWillTerminate:

: sent to app delegate


Ch2. P2P Netwokring (POSIX sockets using UDP, Bonjour)


Layers must be hosted by a view. When paired with a view, the view must provide event-handling for the underlying layers, while the layers provide display of the content.

uint32_t num = 'SpHn';// wow!~

#pragma pack(1)

#pragma options align=reset


self <- current object

_cmd <- current method!!!


performSelectorOnMainThread:// call main tread's method


NSMutableDictionary really dislikes being mutated while it’s being iterated.


Ch3. Threading


Threading enables you to add the responsiveness to your application.

Each thread is responsible for its own autorelease pool.


race condition: the timing of the threads' access to resources can causes unexpected results.


NSLock *myLock = [[NSLock alloc] init]; // mutex

[myLock lock];

// critical section

[myLock unlock];


NSObject's -performSelectorInBackground: withObject: method is just about the same as NSThread class method +detachNewThreadSelector


run loop processes the events that you use to schedule work and coordinate the receipt of incoming events.


Ch4. Multi Touch


"principle of least embarrassment"


UIViews and most subclasses default to userInteractionEnabled, but multipleTouchEnabled is usually disabled.


For each of the touchesX:withEvent:, the touches set will only contain the changed touches, whereas the UIEvent always contains the complete set of active touches.

NSSet* allTouches = [event touchesForView:self];


If the size of the changed touches set is the same as the size of the event’s touchesForView set, we know the last fingers are being lifted from the screen.


A UITouch object’s address does remain constant throughout its life, so Apple recommends using these addresses as keys in a CFDictionary (not NSDictionary).


A multitouch control rarely needs to track an individual touch for its lifetime.


- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;

If we override this, we can arrange for touches to be delivered to our class, not the subclass.


Many touch interfaces rely on physical metaphors: your finger interacts with controls as though they were physical machinery with weight, momentum, and inertia.


Note that the two GadgetView objects are siblings of the BackgroundView, not children of it. This ensures they’re not disrupted when the background image changes. (?? sibling vs. children ??)


// single finger drag

UITouch* anyTouch = [touches anyObject];

lastMove  = anyTouch.timestamp;

CGPoint now  = [anyTouch locationInView: self.superview];

CGPoint then  = [anyTouch previousLocationInView: self.superview];

dragDelta  = CGPointDelta(now, then);

self.center  = CGPointApplyDelta(self.center, dragDelta);



iPhone’s screen refresh rate: 60 fps


atan2f(delta.height, delta.width)

// gets us the angle described by the line

between the points.


Ch5. cocos2d


Designing a virtual world

- Design the space: constraints, boundaries, friction, elasticity, gravity, lighting, ...

- Define the rules: how the objects interact with the space


- 3D:rendering is based on sets of 3D coordinates mapped to textures

- 2D: 2D coordinates mapped to sprites


OpenGL RADIANS_TO_DEGREES() macro


Ch6. Streaming Audio


It’s very important that you always check the return codes from audio API calls. Even if you don’t do any specific error handling, you should at least log any errors. Having these log entries helps a ton when debugging mysterious audio problems.


Core Audio was designed with the goal of complete agnosticism across all file formats and audio codecs.


All audio files are treated as a series of audio packet data that are enclosed in an envelope. The encodingformat (AAC, ...)of the packet data is distinct from the envelopeformat (MPEG4-Part14 or MP4, M4A, ...).


M4A isn’t the best format for streaming audio. It contains a significant amount of data at the beginning defining the structure of the file.

Audio Data Transport Stream (ADTS) can play audio with a smaller up-front data size and more easily support playback of audio starting in the middle of a file.


ringer volume vs. media volume


session category...

By declaring our session as MediaPlayback, the operating system will know to keep our application running when the device is locked, so we can continue playing music indefinitely.


we deactivate the session by calling AudioSessionSetActive(NO) so that the phone may hibernate.


AudioFileStream may generate a magiccookie, and if it does, it needs to be passed onto AudioQueue to enable proper decoding.


iPhone allows only one AudioQueue to exist at any time.


testing URL


http://neilmix.com/book/etude.mp3

http://neilmix.com/book/etude.mp3


Ch7. Core Location, XML, SQLite


SQLite Database Manager (http://sqlitebrowser.sourceforge.net/)


SCNetworkReachability() tests network reachability


SCNetworkReachabilityFlags flags;

SCNetworkReachabilityRef reachability =

SCNetworkReachabilityCreateWithName(NULL,

[@"www.bart.gov"UTF8String]);

SCNetworkReachabilityGetFlags(reachability, &flags);

BOOL reachable = ! (flags &

kSCNetworkReachabilityFlagsConnectionRequired);


NSURLConnection *conn; NSURLRequest *request = 

[NSURLRequestrequestWithURL:[NSURL

URLWithString:@"http://www.bart.gov/dev/eta/bart_eta.xml"]];

if ([NSURLConnection canHandleRequest:request] && reachable)

{

conn = [NSURLConnectionconnectionWithRequest:request delegate:self];

if (conn)

{

self.predictionXMLData = [NSMutableDatadata];

}

}


// get distance in metres

- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location


XPath Objective-C wrapper (http://cocoawithlove.com)

// sort

NSSortDescriptor *sort = [[NSSortDescriptoralloc] initWithKey:@"distance"

ascending:YES];

[self.stationssortUsingDescriptors:[NSArrayarrayWithObject:sort]];

[sort release];



출처 : http://blog.naver.com/PostView.nhn?blogId=gonagi&logNo=150074852198
Posted by 오늘마감

댓글을 달아 주세요

아이폰어플개발정보2010. 6. 24. 14:13
iPhone Games Projects

Ch1. Simplify the UI for Complex Games


simplicity = beauty (how things look) + elegance (how things work)

Simplicity is the means for creating the feeling of control.


* The product statement describes in one sentence what your product is. (A simplistic chess application for the casual player)

- primary functionality: available all the time

- secondary functionality: one gesture away

- tertiary functionality: optional, hidden away from the rest


The power is in what’s not there, rather than in what is there.


UI that doesn’t have a function can be categorized as bloat or clutter, but some creative brilliant ideas can make users smile. (in Deep Green, gear animation when the machine is thinking...)


** Leave out secondary and tertiary features and instead invest in the user interface. **


Ch3. Rapid Game Development Using C

opportunistic gaming: Gamers tend to fire up a game when they have some spare time while doing other things


coding and then art work


OpenGLES 1.1 allows only power-of-two textures (width/height)


Ch4. Game Optimization

iPhone is probably closer in performance to a 266-MHz iMac.

The iPhone and iPod touch have only 128MB of RAM, and most of that RAM is used by the iPhone OS. Therefore, apps have use only of whatever RAM remains, and that amount is generally less than 40MB.


- (void) applicationDidReceiveMemoryWarning:(UIApplication*)application

 typically gets issued when you’re down to about 1.5MB of free RAM


* General *

C is best, ObjC is worst in performance.

In my game Bugdom 2, there are about 500,000 lines of code, but only about 700 of them are in Objective-C.


Core Foundation is the C equivalent of Cocoa.


"Compile for Thumb setting"  if your game is floating-point intensive, as most games are, then you’ll want this option turned off. The Thumb instruction set is only a benefit for integer operations, not floating-point operations.


–mthumb: turn on Thumb option for specific source files.

–O3: Fastest compiler optimization

–Os: Smallest (sometimes it can reduce the running time)


* declare a read-only pointers in the function argument as const, because compiler knows that it doesn't need to reload the variable when it's already in the register after it was passed as constant variable.


* Audio *

You should not stream MP3 files because these are not in an optimal format for the iPhone to work with. The preferred format is the MPEG-4 format, and the most reliable way to generate this is with QuickTime Player.


There are many ways to play sound effects on the iPhone, but for games you should be using OpenAL only.

All sound effects should be identically formatted and in Core Audio File Format (CAFF, 16-bit at 44.1 kHz) format. They must all be the exact same frequency, bit depth, and format, and they must be mono. Even having just one oddball effect can destroy the audio pipeline and cause serious performance issues.


To generate a 16-bit/44.1 kHz CAFF file

afconvert -f caff -d LEI16 {INPUT PATH} {OUTPUT PATH }

To generate a 16-bit/22 kHz CAFF file

afconvert -f caff -d LEI16@22050 {INPUT PATH } {OUTPUT PATH }


* OpenGLES *


You should be allocating a 16-bit buffer instead of one that is 32-bit.


CAEAGLLayer    *eaglLayer = (CAEAGLLayer*)[self layer];

eaglLayer.opaque = YES;

eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:

[NSNumber numberWithBool:FALSE],
kEAGLDrawablePropertyRetainedBacking,
kEAGLColorFormatRGB565,
kEAGLDrawablePropertyColorFormat, nil];


If you are developing a 2D sprite-based game, then you should not allocate z-buffer.


For the best performance, your OpenGL context should be full-screen, 320x480, and have no other views or windows overlaying it. That means no iPhone status bar and noUIViews or controls of any sort. You should never apply any CoreAnimationtransforms to your CAEAGLLayerobject. 


* landscape orientation

glMatrixMode(GL_PROJECTION); 

glLoadIdentity(); 

glRotatef(-90, 0,0,1);


To avoid redundant or unnecessary state changes, you need to cache the state values yourself and update the state only if the state has actually changed.


You should be careful about calling glGetError because that too can cause a pipeline stall and affect your performance. 


The reduction in texture size not only saves space, but it will also improve the performance of your game.


PowerVR Texture Compression (PVRTC) textures are lossy, compressed textures that give you an 8:1 or 16:1 compression ratio depending on which format you choose, but they work only on square, power-of-two textures.


texturetool -e PVRTC --channel-weighting-linear --bits-per-pixel-4 -o Output.pvrtc -p Preview.tif Source.tiff


** Memory, Memory, Memory... large memory access makes programs run slower.. **


Use byte instead of float for RGBA color and UV values for sprites.


For particle effect: queue up all the individual sprites and form large vertex arrays for them that get submitted as one piece of geometry.


Texture atlas: combine multiple textures into one for optimal performance.


- Instruments tool: good for tracking your memory usage and watching other system allocations such as Objective-C objects or OpenGL resources

- Shark: find performance bottlenecks in your code and to see where the CPU is spending most of its time all the way down to the opcode level


Free Physical Memory: anything over 4MB is safe.

The iPhone OS typically starts issuing the applicationDidReceiveMemoryWarning notifications once you reach about 1.5MB. If you get below 1MB, your app is likely to crash at any moment.


Ch5. Game Design Document

The more gaming experience and understanding of the market you have, the better your game will be.


* Concept -> Document

- Title 

- Game summary: App Store description

- Game detail: for co-workers 

- Game setting: location, type of surroundings, music style

- Game system/engine:rules, combat systems, scoring, power-ups, firepower, health system, character creation, quests, location descriptions... premade engines

- Game play: controls and user interface - only touch screen and accelerometer

- Level map: from concepts to storyboarding and several computerised images and models

- Aesthetic design: theme (visual style), colors and animations

- Title and information screens 

- Sound effects


** Engines **

- Torquehttp://www.garagegames.com/

- cocos2d for iPhonehttp://www.cocos2d-iphone.org/

- Unity: http://unity3d.com/

- SIO2 Interactive: Blender Exporter (3d mesh export) http://sio2interactive.com/

- Oolong: most complex  http://oolongengine.com/


Ch6. Multiplatform Game Development

By splitting the game loop into two parts (moving and rendering), you’ve created a foundation for frame skipping.


Frame skipping is a visual compromise. It’s the idea that if the previous frame took too long, you can skip drawing until you’ve caught up.


dynamic frame-rate frame skipping: To do it, you need to check system time to learn about the actual time that has passed.


Verlet physics - Thomas Jakobsen, http://www.teknikus.dk/tj/gdc2001.htm


Ch7. Code Optimization

Lazy loading of resources: Perceived performance is the only kind that matters.


* Alpha compositing is very expensive.

* Core Animation is more efficient than custom drawing code.


An application is only as fast as its slowest part.


OpenGL does not have better performance than Quartz. Using OpenGL thinking that performance will be free is a mistake.What it has is better potential performance.


Code for readability and ease of implementation first, then optimize the things that are actually slow. Never assume you know what is slow or why. Use experiments to test your intuition, always returning to hard data like Shark profiles and performance metrics.


Ch8. Networked Games

// blocking URL request

NSString *urlStr = [NSString stringWithFormat: @"%@/updateScore.php?u=%@&s=%i", server, usr, scr];
NSURL *scoreURL = [NSURL URLWithString:urlStr];
NSString *returnStr = [NSString stringWithContentsOfURL:scoreURL];


// non-blocking URL request

NSString *urlStr =[NSString stringWithFormat:@"%@/score.php?u=%@", server, user];

NSURL *scoreURL = [NSURL URLWithString:urlStr];

NSURLRequest *scoreRequest =[NSURLRequest requestWithURL:scoreURL  cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];

theConnection = [[NSURLConnection alloc] initWithRequest:scoreRequest delegate:self];


* Bonjour network

Bonjour means that a device on the network can be running a service unique to that game while using Bonjour to advertise the service to other devices over the network.


- NSNetService class: publish a service over the network

- NSNetServiceBrowser class: discover a service and connect to it.



출처 : http://blog.naver.com/PostView.nhn?blogId=gonagi&logNo=150056489841

'아이폰어플개발정보' 카테고리의 다른 글

iPhone Application Programming Guide  (0) 2010.06.24
iPhone Human Interface Guidelines  (0) 2010.06.24
iPhone Games Projects  (0) 2010.06.24
The iPhone Developers Cookbook  (0) 2010.06.24
Memory Management Programming Guide for Cocoa  (0) 2010.06.24
iPhone Development Guide  (0) 2010.06.24
Posted by 오늘마감

댓글을 달아 주세요