From C++ to Objective-C

The Objective-C language (C++ “challenger”), is not very widely spread outside de MacOS X/Cocoa world. However, it is really worth studying. Unfortunately, the few documentations that can be found are targeted most of the time to OOP beginners. Therefore, an advanced C++ developer cannot find quickly the equivalents of its usual techniques : time is lost at exploring the language.

So, I have tried to gather in this document a lot of C++ and Objective-C concepts, to show how to switch from one to another and understand the Objective-C paradigms. I hope that it will help good developers to rapidly adopt Objective-C.

Cocoa on the web: 280 North, Objective-J, and Cappuccino

Last week’s news about Apple’s use of SproutCore triggered a lot of discussion about the future of rich Internet applications, run-time environments, and JavaScript frameworks. While SproutCore has been referred to as “Cocoa for the web,” its developer Charles Jolley says that the framework was “inspired by Cocoa,” not really a port of Cocoa. But what if someone ported not just Cocoa, but also an Objective-C runtime the runs entirely in JavaScript via a browser? Well, the developers at 280 North did just that.

From C++ to Objective-C Free Ebook Released

A free Ebook has been released entitled, ‘From C++ to Objective-C’ by Pierre Chatelier.

This document is designed to act as a bridge between C++ and Objective-C. Many texts exist
to teach the object model through Objective-C, but to my knowledge, none target advanced C++
developers wanting to compare these concepts with their own knowledge.

To download the entire book, please visit the link below.

GL Golf

What Went Right

NeHe and Cocoa

Learning OpenGL and Cocoa in three months is no easy task! The first step was reading my uDevGames 2002 prize, ‘Building Cocoa Applications.’ This is a great book; after reading about 200 pages and building the project with the book, I had a solid understanding of what Objective-C was, and the incredible powers of object oriented programming.

Next was learning OpenGL, which seemed twice as intimidating and complex. Actually, it turned out to be the best thing to happen to this project. Using the tutorials from NeHe, I was able to learn the basics of OpenGL in only a few days. OpenGL allowed me to get a visual start to GL Golf very quickly. Using a height map made in Photoshop, I could create decent quality levels very fast.

A Good Math Background

Having already completed trigonometry and algebra three, along with taking calculus, helped tremendously. When you go down to each line of code, everything is just a bunch of numbers, and most are very simple, but some of them are complex enough to give you a headache. After digging through about 10 different collision detection tutorials, I found one that made sense. After a few weeks of coding, I had collision detection and response implemented, but as I found out later on several occasions, the tutorials had some very big errors. For example, it gave the incorrect equation for finding where a ray and triangle intersect, which caused the detection not to work at all. So to make a long story short, keep taking higher-level math courses, because that’s what programming is all about.

iChat and iDevGames.com

Without the help of the iDevGames community there is no way I would have finished this game. Whether it was something as simple as asking how to convert a char array to NSString, or asking how to get smooth shading implemented, someone was always there. Thanks to everyone that helped!

What Went Wrong

My Stupidity

Often programmers do something wrong, but it still works anyway. This happened to me, and it was such a big mistake that it cost me an 80 percent slowdown. Luckily it was something as simple as calling GL_Begin(TRIANGLES) about 4,000 times each frame, when I really only needed it about 10 times. This alone multiplied my frames per second by five, making the game playable on almost all Macs.

Lack of Motivation

This is the biggest problem plaguing independent programmers today, and I’m no exception. If I programmed 20 hours a week every week of the contest, there’s no doubt in my mind that my game would have been twice as good. I had spurts of time where I programmed 20 hours in two days, and then times where it took me three weeks to get 20 hours of work in. I don’t know any good ways to fix this; you just have to do it, and when you see new results the urge to program will come back.

The Forum

I spent way too much time reading the forums while developing GL Golf. This was both a good and a bad thing. While I received much needed help from forum members, I also drained lots of time there. For some reason I would check the forums as often as I compiled my game, which ate up valuable developing time.

Tools

My primary IDE for GL Golf was Project Builder, with a little help from METAL Basic. I used METAL to reformat my Meshworks animated models to a nice useable text file. I used Meshworks to make the golf club (which will be changed shortly), and Photoshop 7 to do all the other graphic work. I also used Photoshop to make the levels. While it was hard to actually make a hole, one could be created in 10-20 minutes. My development system was a Quicksilver 733MHz G4 with a Geforce2 MX card. This was a good machine to use, because it was an average system, which kept my system requirments low.

Summary

Overall GL Golf was a great experience, and the uDevGames 2003 Contest made it all the better. I now have the knowledge to program a high quality 3D game, and I plan on doing so for the next uDevGames contest. I plan on continuing development on GL Golf, and within the next few months I hope to have a shareware version finished. I am already looking forward to uDevGames 2004, so get ready for another great game!

  • Genre:
  • Developer:
  • Url:
  • Team size: 1
  • Released date:
  • Project length:
  • Development hardware:
  • Critical applications:

Industrial Revolution

The second option was rejected after a long debate in iDevGames’ forum about whether or not the modern game player was tough enough for the kind of gameplay we grew up with 20 years ago. Option three was the one that I finally went for.

I knew that my choice would not appeal to a very large section of the game playing community. Pandering to the 3D high frame rate obsessed voter would have been an easier path to score votes, but I wanted to make a game that I would like to play. I wanted to make a game that requires some thinking to play and not something that you can just pick up, press fire and play.

I also suspected that, as my game would not have a story line, I would not be able to score maximum points in the voting. This was confirmed once a large chunk of the contest had elapsed. I fully respect the various issues that caused delays behind the scenes of the uDevGames 2004 Contest, but it is a bit demoralizing for a developer to find the scope of the project, i.e. the rules, going against them when clarification had been requested long before the contest started. Luckily by that time I had decided I was in the contest for the fun of taking part and not out to win otherwise there would have been one less game to vote for.

When it comes to game development I’m more interested in the logic side of the game (my other projects such as FlipSquare, Chromacell and Metamorphosis point to this) and less interested in the look and feel. I guess this is why I can’t get very enthused over the graphics stuff in FPS games even if I try. Industrial Revolution is a game that contains a lot of behind the scenes game logic.

Why Cocoa and Objective-C?

I briefly toyed with the idea of using C++ and SDL and making this a cross-platform game, however I was already working on yet another evolution of my Metamorphosis game using C++ and SDL so I wanted to do something different.

Ever since I first started developing on the Mac I’ve liked Cocoa and Objective-C, so that is what I decided to go with. I know there are some people out there who would not approve of my choices, but it was my entry and not theirs.

Organization

A very important component of any successful project is organization. In order to keep track of what I was doing and what I still had to do in the project, I used my Project Tracker application. The uDevGames Contest was a perfect chance for me to put Project Tracker through a proper test in a realistic environment. The diary function proved very useful in allowing me to keep my development blog up to date on the uDevGames site. Recording every new idea, class and feature and noting every change to the design as I went provided an easy way of checking back on what I had done. It also provided a very useful document for writing this postmortem.

Just over half way through development (September 20th to be precise) I was introduced to OmniGraffle by a fellow Mac developer who unfortunately failed to last the course in uDevGames 2004. Using a trial version of OminGraffle Professional, I produced a set of class diagrams so that I could get an overview of how everything fitted together. My intention was to publish these diagrams as part of the development blog but time did not permit this. The diagrams will be included in the source code released as part of the contest, however.

Priorities

At the very start of the contest I made the decision that I would not let the game rule me. I would do the development when I had spare time, and if the game failed to be completed in the three month window it would not be the end of the world. Taking this non-pressured approach ended up being more productive than trying to cram coding into every waking moment. I feel that knowing you have to get something potentially complex finished by a fixed deadline can sometimes lead to the ‘headless chicken’ effect where you spend the whole time sitting there thinking ‘I’ve got to do this! I’ve got to do this!’ instead of thinking about the actual project.

Most of the initial development took place during my lunch breaks at work. This meant that for the first couple of weeks I spent no more than about eight hours on the project. The first real long sessions of coding came about due to being stuck for hours on trains going to and from meetings.

Another opportunity for putting in some serious development time arose when I was away on holiday for a week. However, I again decided that a life in the real world was more important than the contest.

Even right up to the close of the contest I did not end up doing any of those “lack of sleep” coding sessions. However I must admit to losing more than a couple of hours around midnight on several occasions just playing the game and trying to claw back the money I spent on my railway!

Development Phases

Before I began coding I had an idea in my head of the distinct phases of development I planned to do. The plan was as follows:

  • Get the basic Cocoa framework up and running (this used the initial steps I had previously written for the FlipSquare tutorial).
  • Office screen — Text based display of player assets (such things as factories and trains).
  • Map screen — Graphical display of player assets on a map (this would just use placeholder graphics and text labels).
  • End of game turn logic
  • Expanding transport network
  • Invention Tree
  • Inventors
  • Computer players
  • Final graphics
  • User guide

It’s Still in Development!

Whenever I’m developing a game, or any other application involving some kind of graphical display, I always use placeholder graphics right from the start. The final, or even appropriate but not final, graphics can be added once everything else is working. You can see that an alien is in the wrong place just as well if the alien is a green square.

This placeholder approach was what I used for my menuing/button system. In fact, the system has been designed to allow full functionality and a quick game to be developed without any graphical work at all.

However I must say that I was slightly disappointed to find out just how many people who visit a game development site do not seem to understand this approach. If I was to get a positive vote for every person who questioned the point of having a tool tip appear beside a button that contained the same text then I would have won the contest! Apart from this little rant though I must say that the quality of feedback and interest for Industrial Revolution throughout development was very good. It was the public who convinced me it was worth carrying on after the rules fiasco.

How it Evolved

During the progress of the contest Industrial Revolution evolved. Some things were dropped before they were even coded. Other things were coded and then removed when it became obvious that they just did not work well. A couple of ideas only made themselves apparent during development.

The following is a list of what was dropped from the contest entry:

  • Computer opponents
  • Inventors
  • Recruiting factory and construction workers
  • Extended Invention Tree
  • Additional transport upgrades
  • Different maps

The following is a list of what was written but then dropped:

Shop Screen

Originally new transport and other things were to have been purchased from a shop screen. This screen was similar to the shop system in my uDevGames 2003 entry Garden Pests and a lot of the code came from that game also.

Office screen as main screen.

During early development the Office screen was the main screen where are all the moving of transport and other housekeeping was carried out. The enhanced Map screen made a lot of this functionality redundant so it was removed.

The following is a list of what evolved during development:

The Icon Wheel

Originally everything was controlled via buttons but this was changed to use a circle of icons along the same lines as NeverWinter Nights.

Technology Points

Originally the plan was to have various technology categories that the player built up, and reaching various levels gave access to new inventions. This changed to a system where the technology points were researched from a research budget and then used to ‘buy’ inventions. Had time permitted Inventors would have been required to build up these points using their various skill categories.

Unexpected Music

Due to the fact that Industrial Revolution had no story line to it I knew from the start that I would not be able to win the overall contest. With this knowledge I decided not to bother worrying about music for the game. This was the case right up until the first day of voting, when I showed the game to my line manager at work. As it happens, he has a Mac and a collection of music hardware and software and so he offered to create some music for me. The original idea was to have four pieces of music: title screen music, in-game music, good end-of-turn music and bad end-of-turn music for when a disaster had occurred. However due to time and file size limits we just stuck with the one piece of music.

Knowledge Gained

One of the goals of the uDevGames Contest is for the developers to expand their knowledge. In my opinion it is always easier to learn something new when you have an actual use for it, and the development of Industrial Revolution was the perfect opportunity for me to try out some new things.

Scripts

I’ve heard a lot of people going on about how using scripts for various things in games makes life in development a whole lot easier by cutting down on compile times when making small game changes. Personally I was not convinced about the idea as I find it quicker to hard code things than adding layers of additional work to process files. However the phrase, “Don’t knock it until you’ve tried it,” comes to mind so I gave it a go.

The area of the game I actually tried it out on was the in-game training tasks. One path I did consider taking the game down was to add levels that each required certain tasks to be completed. My plan was to have a script that would easily allow training tasks, and the possible level tasks, to be set up and loaded into the game. In total I must have spent about seven hours getting this system working correctly. There was no way that recompiling every time after editing the in-code task entries would take as much time as that!

What finally convinced me that I’d really wasted too much time on the scripts was that in order for me to test some additional game features using their own tasks I would have had to create multiple script files and keep copying and renaming them compared to just commenting out a couple of lines of code.

The script episode had not been completely pointless though as it gave me a chance to discover and really come to grips with a lot of Cocoa’s string handling abilities. I have put this knowledge to good use in some other projects that I’m working on.

Selectors

I finally got a handle on selectors during this project. I started off using them for a couple of simple things, such as calling the relevant screen drawing routine dependent on the current game state.

Next, I totally rewrote my Button class to use selectors instead of large chunks of switch statements.

Selectors also played a part in the training tasks, the Icon Wheel and Inventions, and briefly in the shopping system before it was dropped.

This new understanding caused me to become distracted from the contest with rewrites of sections of my planned Cocoa Desktop Games book.

The Future

The first task ahead of me is to fully document and tidy up the existing source code.

After the source code has been dealt with I will look at putting in the functionality that I had to leave out, with the exception of the computer opponents. I intend to get the game to a stage where it is completely playable with no opponents. Only when it is working will I add in the computer opponents.

However, before I think about computer opponents I’m toying with the idea of adding in some timers and giving the player the option of real time as well as turn based play, and even the option of mixing the two should they wish.

My other big plan for the game is to use the basic engine and build a construction kit for making similar kinds of games.

I also plan to produce a more detailed write-up of the development of the game and revised construction engine to turn into a series of tutorials, or maybe include it in my still to be completed book. Another alternative is to maybe turn it into a course at the iDevGames university should it ever come into being.

  • Developer: Andrew Sage
  • Language: Objective-C
  • API: Cocoa
  • Lines of Code: 8,352
  • Critical applications: Xcode, Interface Builder, ClassBuilder (personal class building wizard app), OmniGraffle Pro (trial version), Adobe Photoshop, ProjectTracker, Microsoft Word
  • Development Hardware: iBook G4 933MHz 256MB
  • Test Hardware: iMac G4 800MHz 768MB

Evolution

Even without full documentation on Cocoa, I still decided to use this framework due to the power of object oriented frameworks, and couldn’t bring myself to use Carbon. I also think that Carbon should only be used for transitions from Mac OS 9 to Mac OS X and not for new Mac OS X applications.

The Tools

Not only is Mac OS X a joy to develop with, Apple has also provided two stellar tools for developing programs for their new OS. On top of this, Apple distributes these tools for free; they can be found on one of the CDs that came with your copy of Mac OS X. You can learn more about Project Builder and Interface Builder at Apple’s Developer website. The coding for Evolution was created entirely with Project Builder and Interface Builder. Let me quickly cover what the two tools do:

Project Builder

Project Builder is an IDE that offers an editor for source code (and other types of files like RTF or property lists, among others) and provides a graphical front-end for the compiler and linker, as well as a graphical debugger. You use it to type the source code and punch buttons that cause the compiler to turn those funny lines of code into a nice little program. The tool covers a great variety of languages such as Java, C/C++ and, most important, Objective-C.

Interface Builder

Interface Builder seems to be a nice GUI editor at first glance. But it’s much more. You can derive classes within Interface Builder and connect the objects of your GUI (like buttons or pop-up menus) to methods, so-called actions, of the class that will control the GUI without writing a single line of code! Sounds confusing? Actually it’s very easy. Say you have an OK button in a dialog and you want the dialog to disappear when the user clicks that button. To achieve that you connect the button in InterfaceBuilder to the CloseThisDialogAndBeDoneWIthIt: action of the class1 that controls this dialog. You save the Interface Builder file and all the work is done for you.

image2.jpg

The art for Evolution was created in Adobe’s Photoshop. The little critters and screenshots for the on-line help were saved in TIFF and JPEG format and added to the project in Project Builder. Adobe’s WYSIWYG HTML editor GoLive was also utilized to create the on-line help. With the exception of the Adobe products, game development with Mac OS X tools allows developers with any budget to enter the world of Mac game development.

What Went Right

Some might see a two month deadline as a great hurdle towards completing a game. However, I was confident that I had a solid design document to help keep my focus and that my choice of tools would allow me to submit my game on time. Sure enough, both factors contributed to the first playable being done in record time. With a playable version, I was able to quickly move towards adding new features and do extensive testing. The structure of the code also allowed new features to be added without breaking the game.

Choosing the Cocoa framework was a smart choice in that it enabled me to use the RAD tools Apple ships with Mac OS X and build on a well-tested code base. The ‘Learning Cocoa’ book from O’Reilly press contained about 95% of all the information I needed to write the game!

Another point that went right was having a helping hand when I needed it. Due to the differences of Objective-C to C++ there were a few bugs I just couldn’t spot. Christian Schaer helped me tremendously in the final stages of the game.

iDevGames opened the uDevGames Contest to Mac game developers from around the world, and I thought that game players from non-English speaking countries would want to play my game (and hopefully vote for it!) Thus, I made an early choice to localize the game to several languages. This decision proved to be extremely wise as I received comments from players who appreciated the fact that I took the time to provide a game in their language. The effort to localize the game was a piece of cake and I’d like to thank my translator, zozo, who completed the French translation. I added a German translation myself and only a few days after the first release I have been offered a hand in translating the game to Spanish for a future release.

image3.jpg

On the audio front, it always helps to have real musicians providing the soundtrack. Axel from Lunatica was very kind in allowing me to use their songs.

What Went Wrong

Although I had my design completed ahead of the coding process, and I used excellent tools, I admit that I wasted time during some periods (a combination of playing the Airburst game and my constant posting on iDevGames’ forum). If my project management skills matched my coding skills, I would have added many extra features such as Network play and additional AI players. Hopefully with the contest behind me, I can enhance the game further if enough players bug me.

I mentioned that using Cocoa was a boon to developing Evolution, but I must admit that I did have some rough periods during the development process. I had to look through sample source and tons of Cocoa documentation before I could complete a (sometimes minor) step. I think it was time well spent because I needed to learn the framework anyway. However, I’m sure that the drawing routines suffered from my lack of knowledge.

Audio problems also plague the game. It seems that the music skips due to the Evolution algorithm hogging the CPU. For some reason I never noticed that during debugging, most likely because I turned the background music off after a while—I’m fixing that in my next release.

When I started Evolution it was called Chainreaction, and instead of Amoebae the players placed bombs on the board. The situation in the news made me rethink the design with a less violent theme. In the end, I’m glad I did.

image4.jpg

Looking ahead

I’m planning to correct the problems with the music and re-work the drawing algorithm. I’m also eager to add in network play. After those problems are fixed, I plan to write a series of articles about the game and its use of several features of Cocoa to show how easy it is to implement a load/save game feature, proper use of the user preferences, sheets and localization. Apart from that I’ll write an IRC client using Cocoa.

Working on my uDevGames entry was a lot of fun, and I was surprised to see the number of Mac OS X entries. I remember that there was a thread in iDevGames’ forum from developers who didn’t want to release their source code. Although I’m a tad embarrassed to show my peers my own code, I think it is healthy for our platform to have as much source code as possible. This way, we can all become better developers and build a stronger gaming platform. I did my best to make my source code readable and really hope that other Mac game developers can benefit from my game. I’m also eager to look at the source code to the other entries as well! I strongly support giving back to the Mac development community so if you have any questions about the code, drop me a line.

Since most developers have heard of uDevGames by now, there’s no doubt they will be down in their labs hard at work on their uDevGames 2002 entry. This means the standard will probably rise even higher next year. I’m eager for the challenge and look forward to battling with you all for the honors of uDevGames 2002. My only request would be that iDevGames allows for a three month development duration so I can spend two months killing time.

1 A class is a collection of data and code that works on this data.

  • Game: Evolution (6.7 MB)
  • Genre: Puzzle
  • Developer: Sacha Saxer
  • Team size: 2
  • Released date: September 19, 2001
  • Project length: 2 months
  • Development hardware: PowerMac G4 Cube
  • Critical applications: ProjectBuilder/InterfaceBuilder, Photoshop

Recent Forum Threads

About iDevGames

Since 1998, iDevGames has been educating, supporting and enhancing the community of game developers that produce video games for the Apple Mac and iPhone platforms. Get the latest game development news by subscribing to our news feed.