iPhone OpenGL tips

March 22nd, 2009

I'd strongly recommend using Jeff LaMarche's iPhone OpenGL ES template

I'd also recommend you getting your hands on Texture2D.h. This is a file that comes from Apple that you can find attached to various demos or code example. It makes it really easy to load and attach a texture in OpenGL ES.

For 2D game development on the iPhone check out Cocos2d. I've been tinkering with it lately and it is quite good. You don't even have to bother with OpenGL ES if you use Cocos2d and it comes with Chipmunk, an awesome 2D physics engine.

I'm going to post more about how to use Cocos2D for iPhone game development later. I've been busy learning to use it myself.

rjett Uncategorized

Using the iPhone accelerometer

March 14th, 2009

I've discovered that it is quite easy to gain access to the iPhone accelerometer. Below are some simple code fragments that can be utilized to gain access to the sensor:

In the header of an Objective-C interface you need to add the protocol for the accelerometer. In my example I am going to add it to an EAGLView, which is a subclass of UIView used for OpenGL ES:

 
@interface EAGLView : UIView <UIAccelerometerDelegate> {
   //your code here
}
//your methods
- (void)accelerometer:(UIAccelerometer *)accelerometer
      didAccelerate:(UIAcceleration *)acceleration;
@end
 

In your implementation file you simply need to add the following lines in an init function, or in the case of EAGLView you could add them in initWithCoder:

 
//You may need to change the interval to optimize your app's performance:
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(0.1f)];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
 

The final line you need to add to the implementation file is the function we added to the header:

 
- (void) accelerometer:(UIAccelerometer*)
accelerometer didAccelerate:(UIAcceleration*)acceleration {
	NSLog(@"X: %g, Y: %g, Z: %g", acceleration.x,
             acceleration.y, acceleration.z);
}
 

rjett Uncategorized

Cocoa Foundation: NSArray and NSMutableArray

March 2nd, 2009

NSArray and NSMutableArray are two classes provided by Apple in the Cocoa Foundation Framework. The main different between the two is mutability. Once created, an instance of NSArray cannot be changed (is not mutable), while NSMutableArray can be changed.

NSArray will hold only Objective-C objects. You can't put C types, like int, float, enum, struct, or pointers in an NSArray. You also can't store nil in an NSArray, as it is used to indicate the end of an array during allocation.

NSArray Example Code

 
#import <Foundation/Foundation.h>
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
	//NSArray Magic:
 
	//Creating an Array
	NSArray *array = [NSArray arrayWithObjects: @"One", @"Two", nil];
 
	//Accessing an Array's contents using NSEnumerator
	NSEnumerator *enumerator = [array objectEnumerator];
    id obj;
 
    while ( obj = [enumerator nextObject] ) {
       NSLog( @"%@", obj);
    }
 
	//You could use NSLog to dump the array contents like so
	//NSLog(@"%@", array);
 
    [pool release];
    return 0;
}
 

NSMutableArray Example Code

 
#import <Foundation/Foundation.h>
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
	//NSMutableArray Magic:
 
	//Creating a mutable array!
	//A mutable array will expand as needed, but we
        //must specify an inital capcity:
	NSMutableArray *array = [NSMutableArray arrayWithCapacity: 2];
 
	//Add an object
	[array addObject: @"One"];
 
	//Add another object
	[array addObject: @"Three"];
 
	//Insert an object at a particular index
	[array insertObject: @"Two" atIndex: 1];
 
	//Accessing an Array's contents using NSEnumerator
	NSEnumerator *enumerator = [array objectEnumerator];
    id obj;
 
    while ( obj = [enumerator nextObject] ) {
       NSLog( @"%@", obj);
    }
 
    [pool release];
    return 0;
}
 

rjett Uncategorized

Cocoa Foundation

March 2nd, 2009

What is Cocoa Foundation? Cocoa Foundation is a framework of all the basic building blocks a developer will need. According to Apple, the goal of the framework is to, "Provide a small set of basic utility classes, Make software development easier by introducing consistent conventions for things such as deallocation, Support Unicode strings, object persistence, and object distribution, and Provide a level of OS independence to enhance portability."

Cocoa Foundation provides a lot of basic functionality that helps developers manage XML, Strings, Collections, Net Services, Threading, and more.

rjett Uncategorized

Bit fields

February 22nd, 2009

Bit fields are a way to specify a specific size for your variable in C. For example:

 
unsigned int someNumber:4 = 2; //defines a variable that is 4 bits long.
 

Cool, eh?

rjett Uncategorized

Structs

February 21st, 2009

Structs are like objects without methods. Structs are basically a collection of variables. Here is some code that creates a rudimentary linked list using a C struct:

 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
typedef struct node {
      struct node *next;
      int data;
} linked_node;
 
linked_node *head;
 
void insert(int val)
{
      if(head == NULL)
      {
         linked_node *temp = malloc(sizeof(linked_node));
         temp->data = val;
         temp->next = NULL;
         head=temp;
       }
      else
      {
        linked_node *temp = malloc(sizeof(linked_node));
        temp->data = val;
        temp->next = head;
        head = temp;
      }
}
 
int main (int argc, const char * argv[]) {
 
srand((unsigned) time(NULL));
 
for(int i = 0; i &lt; 10; i++)
{
       insert(rand() % 20);
}
 
while(head != NULL)
{
       printf("%d ",head->data);
       head = head->next;
}
return 0;
}
 

rjett Uncategorized

*Pointers

February 20th, 2009

In "The C Programming Language" by Kerinighan and Ritchie (K&R), pointers are defined as, "a variable that contains the address of another variable." By address, they mean memory address, a number used by the CPU to indicate a given portion of memory. In Java, a developer never has to deal with memory addresses it is all handled behind the scenes. In C, pointers can "create more compact and efficient code" and "are sometimes the only way to express a computation," according to K&R. Below are some visual examples to help with understanding pointers:

Pointing to a variable with a pointer

Pointing to a variable with a pointer

In the above image we are create a variable of type int and setting it to 5. Then, we are creating a pointer of type int and pointing it to our variable's memory address. The ampersand (&) is used to get the memory address, in our example 0xFE, of a variable. In the next image, you can see some of the power of using pointers:

Pointer math to access array elements

Pointer math to access array elements

In the above image, an integer array is being created with a size of 3. The numbers 0, 1, and 2 are being loaded into the array and then a pointer is then getting pointed to the array. At the bottom are examples of using pointer arithmetic to access array elements. Calling *ptr++ twice is the same thing as calling *ptr+=2.

Behind the scenes the address is merely being increased by the size of the data type. Let's say an int is 32 bits (4 bytes) long, then when you increment a pointer, you are merely adding 32 bits or 4 bytes to your memory address. Giving you the starting point of the next element in the array.

You can also set up an array of pointers or set pointers to functions as well. If you want to learn more about pointers I suggest: http://boredzo.org/pointers/

rjett Uncategorized ,

Floating on C

February 18th, 2009

My previous post talked about how Objective-C is a thin Smalltalk based layer of object oriented functionality that sits on top of the programming language C. In this post I will revist C in all of its glory. Since C, is at the heart of Objective-C it is probably a good idea to have a good understanding of it before beginning a quest towards mastering Mac development.

C was developed by Dennis Ritchie while working at Bell Labs in 1972. I have sometimes heard C referred to as being a medium level language (if you consider assembly to be low and Java to be high). C was designed to be portable, yet still allow developers to take advantage of all the power found under the hood. The primary use of C is systems programming. It is used extensively for operating systems, hardware control, and embedded systems.

Much of the syntax found in C is replicated in many other languages. Things like methods, parameters, for loops, return types, main function, import statements, etc. can all be found in many other languages like Java. I will glaze over the functionalities of C that can be found in Java and focus on C specific features in the following sections.

Operators

When looking at C code the biggest difference in syntax that I can see are some of the operators that are used. Let's take a look at some operators that may be foreign to a Java programmer. The first set of operators that a Java programmer may not be familiar with are bitwise operations.

Bit shifting

The first operator is the bitwise shift, which comes in two flavors, shift left (<<) and shift right (>>). This operator is used to shift binary numbers left or right. Why would you want to shift binary numbers? Well, shifting binary numbers left or right gives you the best performance possible when you need to divide or multiple by powers of 2. For example, the number four (100), shifted right, will result in 2 (010). 4/2 = 2! If you shift left four (100) would become eight (1000).

Just like we can utilize + or - for assignment (+= / -=), bit shifts can be utilized for assignment as well (<<= / >>=). For example, instead of writing i = i >> 2, we can write i >>= 2. Both of which would result in i being set to the result of 2 right bit shift operations.

One's Complement

In Computer Science, one's complement is one method of representing negative numbers. The most significant bit, determines whether a number is negative or not. This method limits a byte to storing (+/- 127). Without getting into too much more detail, we'll say that the operator (~a), inverts the bits (a boolean NOT operation). For example we will apply the operator to the number 2 (0010). i = ~2; The result of this operation would set i's bits to 1101.

Other Bitwise Boolean Logic Operators: AND (&), OR (|), and XOR (^)

I'm not going to review boolean logic here, but here are a few examples of these operators in use using 5 (101) and 2 (010):

5 & 2 = 0 (000)
5 | 2 = 7 (111)
5 ^ 2 = 7 (111)

The operators can also be used with assignment: &=, |=, ^=

Next time: Pointers

rjett Uncategorized

Objective-C: A Brief History & Overview

February 18th, 2009

Objective-C was developed by Brad Cox and Tom Love in the early 1980s. Cox developed the language out of his desire to give the programming language C some of the properties of Smalltalk. Smalltalk is an object oriented language. Object Oriented languages were seen as being a solution to many of the software engineering issues that came up regarding complex programs and code reuse in the 80s. One of the downsides to Smalltalk was that it ran in a virtual machine. Cox began developing Objective-C by simply modifying a C compiler to add Smalltalk capabilities.

In 1988, Apple and Objective-C first cross paths. Ex-Apple CEO Steve Jobs licensed Objective-C for his new computer company NeXT. When Steve came back to Apple in 1996, he purchased his old company NeXT. Apple then began utilizing the tools and resources of NeXT, including Objective-C, to develop Mac OS X.

Objective-C, being merely an extension of C, is referred to as being a strict superset of the C language. This means that any C code will compile in an Objective-C compiler.

Since Objective-C is C plus Smalltalk like OO syntax, let's look at some Smalltalk code and compare it to other languages:

Rectangle width: 100 height: 200

In this example, Rectangle is the receiver class, which is receiving the parameters for width and height via a message. When the Rectangle class receives this message, it will return a new Rectangle object with width and height properties of 100.

In Java or C++, this same functionality might look something like this:

 new Rectangle(100,200);

Now, let's take a look at some Objective-C code. Let's call an operation called loop on an object called MusicBox:

[musicBox loop:songName];

This same code in Java might look something like this:

musicBox.loop(songName);

Or in C++:

musicBox->loop(songName);

From these examples it is easy to see how Smalltalk's messaging features were utilized in the development of the Objective-C language.

rjett Uncategorized

The Path to Mac Development Enlightenment

February 17th, 2009

This is entry number one in hopefully a series of regularly updated content on my path to learning Apple development. This blog will serve as an output for all work that I do towards learning Objective-C, Cocoa, iPhone, and/or Machintosh desktop development.

Hopefully I will be able to keep this site up to date and have it turn in to a good resource for myself and possibly others.

To get things started I'm going to begin this blog reviewing some of the basics of C and Objective-C.

Beyond Objective-C I will dive into the frameworks that Apple provides and really try to wrap my head around the core functionality found in each one. I will also do some searching for third party frameworks that may fill some gaps or provide extended functionality.

rjett Uncategorized