\chapter{The Anatomy of a Game}
\label{ch:gameanatomy}

In 1991 a Finnish university student named \index{Torvalds, Linus}Linus Torvalds began working on a new operating system in his spare time. He didn't work in isolation, nor did he make a big deal about what he was doing; rather, he modestly invited programmers from all over the world to join his project, which he dubbed \index{Linux!origin}``Linux.'' This loosely knit team of students, professionals, and hobbyists collaborated through the Internet, with the expectation of learning a bit about programming and having a good time. Linus never thought that his project would spawn an entire industry.

Since then, Linux has grown into a general-purpose operating system for a wide variety of hardware platforms. With more than 10 million users (a number that is constantly growing), the Linux platform offers a sizable audience for computer games. \index{Linux!capabilities}It is now capable of accelerated 3D graphics, environmental audio, and seamless game controller handling, in addition to the server tasks that UNIX-like operating systems generally carry out. Although Linux is still evolving, it is already a solid environment for serious game development.

This book describes the toolkits and the environments that allow programmers to write 2D and 3D games for Linux. We will learn how to draw animated graphics on the screen, how to play high-quality digital sound through several different software libraries, and how to set up OpenGL to create fluid 3D graphics. By the end of this book, you will know what makes Linux games tick, and how to create your own games for this platform.

This book is \emph{not} about game design, the mathematics of 3D graphics, or advanced OpenGL programming. These topics are best left to books of their own; I could not hope to do them justice here. However, with the knowledge you will gain from this book, you will be prepared to tackle these topics later on.
 
Before we begin our discussion of Linux game programming, let's take a quick glance at our surroundings in the gaming industry so that you can better understand what goes into this type of project.

\section{A Quick Survey of Game Genres}
Computer games tend to fall into any one of a number of distinct \index{genres}genres. Many players have strong preferences for certain genres, which makes this an important issue for game designers to consider. And, the presentation of a game concept can make an enormous difference in its success.

\subsection{Simulation Games}
\index{simulations|see{genres, simulation}}
\index{genres!simulation|(}
The \firstterm{simulation} genre encompasses a wide variety of games, from flight simulators to Mech combat scenarios. An ideal simulator provides a high level of realism in graphics, sound, and game physics. Some popular simulation games are \index{Heavy Gear II}\gametitle{Heavy Gear II}, \index{MechWarrior}\gametitle{MechWarrior}, and \index{Microsoft Flight Simulator}\gametitle{Microsoft Flight Simulator}. The basic goal of any simulation game is to put the player behind the controls of something exciting, something that he or she probably would not have access to in real life. Simulations strive for immersion.

Simulation games (sims) are basically at two extremes. Some simulations aim for absolute realism, seeking to entertain the player with an almost completely accurate portrayal of real life. These ``games'' are sometimes even used for real-life training purposes. Other sims, like the \gametitle{Heavy Gear} and \gametitle{MechWarrior} series, trade realism for pure entertainment value. These games are based only loosely on reality; they simulate imaginary vehicles with extraordinary but rather impossible capabilities. (Interestingly, the \gametitle{MechWarrior} and \gametitle{Heavy Gear} computer games are based on pencil-and-paper role-playing games.)

Simulations pose a serious development challenge. Since a good modern simulation requires high-quality 3D graphics, detailed vehicle models, a game physics system for simulating the physics of the real world, realistic input response, network capabilities, and possibly a certain amount of artificial intelligence for the computer-controlled players, a contemporay sim is not trivial to construct.

What makes a simulation game successful? Let's look at a couple of examples: a ``realistic'' simulator and an ``action'' simulator. \gametitle{Microsoft Flight Simulator} is a popular flight simulator for the PC (and is in fact the current iteration of a long line of flight simulators by the same developers, dating back to the Commodore 64) that combines realistic control with excellent 3D graphics and interesting airplanes, and the terrain looks reasonably close to the real world's.\footnote{One of the first rules of game design (and, to some extent, of computer graphics in general) is that it doesn't matter if something \emph{is} realistic as long as it \emph{looks} realistic. Unfortunately, most people don't have 5-terahertz machines, so game creators have to take a few shortcuts. Most flight simulators really aren't that realistic when it comes down to it, but they sure \emph{seem} realistic.} An experienced pilot could certainly tell the difference between \gametitle{Microsoft Flight Simulator} and a real airplane, but it's nonetheless an enjoyable simulation.

\gametitle{Microsoft Flight Simulator} tries to make the players feel like they were in the cockpit, not just collecting cellulite behind the keyboard of a fast computer. Although this game will not run under Linux (except possibly under WINE\footnote{\ulink{http://www.winehq.com}.}), it's certainly worth a look if you're thinking of writing a flight simulator.

On another front, the \index{Flight Gear}\gametitle{Flight Gear} project is presently developing a free flight simulator for Linux. The simulator already sports a realistic physics model and an excellent terrain engine, and it is slated to eventually become one of the best flight simulators ever. \gametitle{Flight Gear} is portable to many platforms, as it is based almost entirely on open technology.

\extfiguren{figures/fg-screenshot}{Screen shot from Flight Gear\\ Image courtesy of David Megginson}

\gametitle{Heavy Gear II} from Activision is a good example of an action simulator. It puts the player behind the controls of a multiton Gear (a two-legged walking vehicle with big guns) and succeeds because of its realistic graphics, simple but capable control system, damage simulation, and interesting gameplay. The player is in complete control of his or her Gear and is free to do anything during the game (although accomplishing the mission without getting killed is usually the best plan). \gametitle{Heavy Gear II} creates a sense of power and euphoria in the player, and this makes it a pleasant experience. Activision has also published several \gametitle{MechWarrior} titles that are very similar to the \gametitle{Heavy Gear} series.

Finally, one of my personal favorite simulation games (from many years ago) is \index{Corncob 3D}\gametitle{Corncob 3D}, a completely unrealistic shareware, DOS-based flight simulator. Guised as a flight simulator, this is a classic ``Defend Earth from Space Invasion'' game with lots of missions, missiles, and mayhem. By today's standards, of course, this game is laughable. But it ran well on the low-end hardware of the day, and it was a lot of fun to play. \gametitle{Corncob 3D} is a good example of a simulator that trades realism for entertainment value.

\extfiguren{figures/gltron-screenshot}{Screen shot from GLTron, based on an 80's sci-fi movie\\ Image courtesy of Andreas Umbach}

\index{genres!simulation|)}

\subsection{First-Person Shooters}
\index{first-person shooters|see{genres, first-person shooters}}
\index{genres!first-person shooters|(}
\label{sect:fps}

\firstterm{First-person shooters} are some of the most popular games today. They typically involve a weak story line (with exceptions, of course), hordes of enemies, big explosions, and lots of blood. The basic premise of most first-person shooters is to give the player an adrenaline rush by putting him in the middle of a hostile environment with insidious monsters and powerful weapons. These games have improved in quality over the years and are beginning to reach a very high level of realism. Some popular ones are \index{Quake 3}\gametitle{Quake 3}, \index{Half-Life}\gametitle{Half-Life}, and \index{Soldier of Fortune}\gametitle{Soldier of Fortune}, all of which are available for Linux (although Half-Life is not native to Linux, and requires the WINE library to run).

High-quality first-person shooters are difficult to produce, not just because they're hard to program (facilitated by standard 3D libraries such as OpenGL), but also because they require detailed 3D character models and levels. 3D game-engine programming requires a solid knowledge of linear algebra and a firm grasp of certain types of data structures. However, mathematically inclined people are likely to find 3D game programming both challenging and rewarding.
\shortpage

Valve's \gametitle{Half-Life} is one of the most successful first-person shooters, combining the thrill of a typical FPS with a compelling storyline, amazingly realistic enemies, and an excellent multiplayer mode. \gametitle{Half-Life} is based on \gametitle{Quake II}'s rendering technology, but that is where the similarities end. Unlike the Quake series, \gametitle{Half-Life} has a plot, an excellent single-player mode as well as network game support, and a more complex virtual environment (complete with moveable objects and vehicles).

Another interesting first-person shooter (also based on the Quake II engine) is Activision's \gametitle{Soldier of Fortune}. Decried by critics as gratuitously violent (and hence ``indexed'' in Germany and classified as an adult title elsewhere), \gametitle{Soldier of Fortune} combines traditional first-person shooter action with frightening realism, even going so far as to correctly simulate bodily damage due to gunshot wounds. It also has a solid plot that develops throughout the game. Overall, a very enjoyable title, if you're not disturbed by the violence. (I won't go into the highly emotional politics surrounding this subject.)

A current trend is to mix first-person 3D technology with the role-playing game. \index{Deus Ex}\gametitle{Deus Ex} is one such example, a role-playing game based on the Unreal engine. \gametitle{Deus Ex} has been ported to Linux, and I strongly recommend giving it a try.
\index{genres!first-person shooters|)}

\subsection{Real-time Strategy Games}
\index{real-time strategy games|see{genres, real-time strategy}}
\index{genres!real-time strategy|(}
\label{sect:rts}
The genre of games known as \firstterm{Real-Time Strategy} (\firstterm{RTS}) games includes such popular titles as \index{StarCraft}\gametitle{StarCraft}, \index{Command and Conquer}\gametitle{Command and Conquer}, and \index{Total Annihilation}\gametitle{Total Annihilation}---games that allow the player to command individual parts of an army from an overhead view, with success in battle usually leading to better equipment and soldiers. Because success is usually determined by a player's tactics, these are considered strategy games. RTS games often have a high replay value; they're fun to play again and again.

RTS games are comparatively easy to program, because, with some exceptions, they do not involve 3D graphics or complicated mathematics; however, \emph{good} RTS games are hard to produce, and they tend to be few and far between. They often involve a certain amount of artificial intelligence (AI) programming for controlling the simulated opponents in single-player games---a fascinating field, but one that we'll leave to other sources.

\gametitle{StarCraft} is by far the most successful RTS game, combining pleasing graphics, a large selection of well-balanced units, and interesting battlefields in a very well-rounded game and exciting game. Solid game design is by far the most important issue in creating a real-time strategy game, and \gametitle{StarCraft} is an excellent example. This is not the first notable game from Blizzard Entertainment, and it will be interesting to see what Blizzard comes up with in the future.

\index{genres!real-time strategy|)}

\subsection{Turn-Based Strategy Games}
\index{turn-based strategy games|see{genres, turn-based strategy}}
\index{genres!turn-based strategy|(}
\label{sect:tbs}
\firstterm{Turn-Based Strategy} (\firstterm{TBS}) games are like real-time strategy games, but the gameplay is divided into turns, usually with no time limit, thus giving the player time to think and relax, and lending the game an entirely different feel from the faster-paced strategy games. TBS games are not decided by reflexes, but rather by careful planning, which often makes them more difficult, and more attractive to many players. Sid Meier's \index{Civilization II}\gametitle{Civilization II} is widely regarded as the best turn-based strategy game, because of its balance and replay value.

\begin{note}{Deceptively Complex}
I once thought that TBS games were easy to write, but then I saw the source code to \index{Alpha Centauri}\gametitle{Sid Meier's Alpha Centauri} (SMAC). Most players don't realize it, but SMAC actually uses a 3D technique called \index{voxels}\firstterm{voxels} to render its units on the fly and to draw a height-sensitive landscape with perspective texture mapping and dynamic palette mapping (made possible by self-modifying assembly code). \gametitle{Sid Meier's Alpha Centauri} was obviously not easy to port to Linux. While it's possible to write a good TBS game without such sophistication, don't think of the TBS genre as an easy way out---its complexity can be deceiving.
\end{note}

\extfiguren{figures/freeciv-screenshot}{Screen shot from FreeCiv, a free TBS game\\ Image courtesy of Paul Zastoupil}

\index{genres!turn-based strategy|)}

\subsection{Role-Playing Games}
\index{role-playing games|see{genres, role-playing}}
\index{genres!role-playing|(}

\longpage
\firstterm{Role-Playing Games} (\firstterm{RPGs}) stem from the \index{Dungeons and Dragons} Dungeons and Dragons role-playing system.\footnote{There are lots of similar role-playing systems; I just give DND as an example.} In this type of game, the player assumes the role of one or more characters on some sort of quest. Role-playing games put the player in a world with many possibilities; a good RPG gives its players a sense of immersion and true interaction, and allows them to effectively become someone else.

The quality of a role-playing game depends much more on its storyline, interaction, and depth than on its graphics. \index{Ultima Online}\gametitle{Ultima Online} is an example of a good online RPG. While its graphics are not spectacular, the depth of its gameplay is incredible, because it allows for complex interactions between players in a virtual universe. Ultima is not exactly a ``hard~core'' RPG, however; true die-hard RPG gamers often prefer other types of RPGs, such as those published by Simutronics (\ulink{http://www.simutronics.com}).

\extfiguren{figures/nethack-screenshot}{Screen shot from NetHack, a very strange free RPG project}

\index{genres!role-playing|)}

\subsection{Puzzle Games}
\index{puzzle games|see{genres, puzzle}}
\index{genres!puzzle|(}
Puzzle games receive less attention than the other game genres, but they deserve to be mentioned. Puzzle games challenge the player with problems that require thought and patience. This genre includes everything from simple box-pushing games (\gametitle{Boxxel} and the dangerously addictive \index{Sokoban}\gametitle{Sokoban}) to the animated and ubiquitous \index{Tetris}\gametitle{Tetris}.

A successful puzzle game is usually challenging (but not impossible), pleasant to look at (graphics should not be ignored), and replayable (one-shot puzzle games are usually not very enjoyable the second time around, and players don't appreciate that). The difficulty involved in creating a puzzle game depends on the particular game; some are extremely complex, involving massive amounts of artwork and graphics processing, while others are simple to implement.

\extfiguren{figures/ksokoban-screenshot}{Screen shot from KSokoban, a version of Sokoban for KDE}
\index{genres!puzzle|)}

\subsection{Multiuser Dungeons}
\index{Multiuser Dungeons|see{genres, MUD}}
\index{genres!MUD|(}
Multiuser Dungeons (commonly known as MUDs) are massively multiplayer games, typically hosted on Internet servers and accessed with special MUD client programs. MUDs are extremely popular because one's opponents are real people, not computer-controlled robots. MUDs are essentially text-based role-playing games, immersing their players in worlds with magical objects, wizardry, and battle. MUD fans wishing to host a game of their own often obtain a prewritten MUD server program and develop their own ``world'' through configuration files and scripting languages. If they do a good job, they may attract lots of players, which is very satisfying. Two popular MUD server programs are \index{ROM (MUD system)}\gametitle{ROM} and \index{DikuMud}\gametitle{DikuMud}, which may be downloaded from the Internet. There are untold thousands of private \gametitle{ROM}-based MUDs on the Internet.

MUDs are relatively easy to create, though writing a MUD server is not trivial, requiring a solid background in C or similar and a knowledge of network programming. Creating MUD datafiles requires little programming knowledge but a lot of creativity. A good MUD has an interesting game world to explore and a good balance of races and abilities. Also, some MUDs are prone to ``god moding,'' or abuse by the person running the server; while this obviously depends on the players, good design can lessen this undesirable effect.

\longpage
If you've never been ``mudding,'' give it a try. A good MUD can provide a truly interesting experience. You can find MUDs all over the Internet; just search the Web for the word ``mud.''

%TODO: links to popular MUDs /jh
\index{genres!MUD|)}

\section{A Quick Look Under the Hood}
\label{sect:engineoverview}
Most games have a lot in common behind the scenes. The \index{engine!defined}\firstterm{engine}, or main code, of a ``typical'' game (if there is such a thing) can be logically divided into several subsystems: the input subsystem, the display subsystem, the audio subsystem, the networking subsystem, the update subsystem, and the main loop. These subsystems are rarely labelled as such, but you are likely to find all of these components in any given game engine. Each subsystem is most often implemented with several separate source files; two or three in small games, but easily a hundred or more in a large production. We'll look briefly at each of these subsystems now, and throughout the rest of the book we will explore possible ways to implement each.

\begin{note}{This Code Is Awful!}
\index{sloppy coding}If you ever get a peek at the code behind a major commercial game, please do not take it as a treatise on proper software design or coding! Games often start out as well-designed software, and they sometimes even make it to the shelves in a tolerable state of internal organization, but more often than not a game's code falls into disarray during the last few months of development.

Why, you might ask? The gaming industry is volatile, dangerous, and extremely competitive. Game studios seem to find themselves in a perpetual struggle to meet release deadlines, get their games out ahead of their competitors, and implement the features that players demand, lest they be left in the dust with a stack of unsold games. This often results in extremely hurried and sloppy code. Unfortunately, this often causes serious problems if someone later tries to add an expansion pack to the game or port the game to another operating system.
\end{note}

\subsection{The Input Subsystem}
\index{input subsystem|see{engine, input subsystem}}
\index{engine!input subsystem|(}
The input subsystem receives the user's commands through an input device (like the keyboard or a joystick) and records these commands for further processing. While input device programming is not difficult, it should be done carefully, because flawed input processing can easily ruin an otherwise excellent game. The first version of Apogee's \index{Rise of the Triad}\gametitle{Rise of the Triad} (a first-person shooter from several years ago) suffered from particularly bad input handling, and the game was aggravating to play until this problem was fixed.

One of the input subsystem's most important jobs is to simultaneously support a variety of input devices. A well-written input subsystem should be able to integrate just about any type of oddball game controller with minimal effort (this is made a bit easier by libraries like SDL, but it's still something to keep in mind as you code). Some players prefer to use joysticks rather than mice, and an input subsystem should be able to accommodate this preference without modification to the main game code. As far as the game is concerned, the joystick should appear as a generic device, capable of producing ``left,'' ``right,'' ``up,'' and ``down'' commands. We will discuss SDL's input handling and abstraction in Chapter \ref{ch:masteringsdl}, and we'll touch on the lower levels of input handling in Linux later on.

\index{input customization}Nearly every game on the market allows you to remap the keyboard and other input devices to your liking, and this is a feature that players demand. Many people have non-US keyboards with different key locations, and you'll end up cutting off a lot of would-be players unless you allow them to configure the game to work with their keyboards. Fortunately, this is not difficult; it can be accomplished with a simple lookup table. It is also a good idea to allow the player to store and retrieve multiple key mappings, in case a friend prefers a different configuration.
\index{engine!input subsystem|)}

\subsection{The Display Subsystem}
\index{display subsystem|see{engine, display subsystem}}
\index{engine!display subsystem|(}
The display subsystem conveys the game's status to the player in a visually impressive way, whether through simple 2D graphics, or advanced 3D rendering (the type of graphics you use doesn't matter, as long as they are appropriate for the game). Regardless of the type of graphics produced by the display subsystem, the structure of the code is substantially the same.

The display subsystem is responsible for taking advantage of the available display hardware. Serious gamers often equip their machines with snazzy 3D graphics cards, which can bring enormous performance and quality improvement to 3D games. However, this performance boost is not automatic and requires special effort by the programmer, which is usually accomplished through an \firstterm{API} (\firstterm{application programming interface}, essentially a big library of routines) like OpenGL. 3D acceleration is beyond the scope of this book, but we'll demonstrate how to get OpenGL up and running in Chapter \ref{ch:masteringsdl}.

Before you can show off your graphics code, you'll need something to display. Although it is common for programmers to develop temporary artwork for testing purposes, few are skilled artists, and they usually find it necessary to enlist the help of a skilled digital artist to produce acceptable game artwork. Players are a finicky bunch, and they are most intolerant of subpar graphics. Game programmers should spend a great deal of time developing a good graphics engine, and a designer should place a high priority on obtaining quality artwork for a game.
\index{engine!display subsystem|)}

\subsection{The Audio Subsystem}
\index{audio subsystem|see{engine, audio subsystem}}
\index{engine!audio subsystem|(}
Although computer audio technology has not been hyped as much as computer rendering technology during the past few years, a game's audio subsystem is every bit as important as its graphics subsystem. Fortunately, producing high-quality sound on a computer is not as difficult as producing high-quality graphics.

Sound is easy to play back (usually a simple matter of a few function calls with a multimedia toolkit), but creating production-quality sound effects for a game is as much an art as creating graphics, and should be left to a specialist. Stellar sound effects can boost a game's atmosphere, and lousy sound effects can seriously damage a game's potential. 

\index{environmental audio}3D enhanced audio is one of the latest trends in computer sound technology with modern sound cards (like Creative's SB Live!\ series) supporting four-speaker surround-sound, and 3D-aware sound-processing to simulate the \index{Doppler effect}Doppler effect and other complex sound wave interactions. (Simple two-channel stereo sound just falls short of the immersive environments of today's 3D games.) In fact, some sound cards can even accelerate these effects in hardware. Several competing 3D sound APIs have emerged, and we will discuss one of these (OpenAL) in Chapter \ref{ch:linuxaudio}.
\index{engine!audio subsystem|)}

\subsection{The Network Subsystem}
\index{network subsystem|see{engine, network subsystem}}
\index{engine!network subsystem|(}
Multiplayer gaming is very popular these days, and it is reasonable to assume that this trend will continue. The network subsystem connects a game to other computers over a network so that multiple players can participate in the action. Network programming is not as difficult as it used to be, especially with the advent of the Internet as we know it. Still, the network subsystem must be extremely robust and flexible, as, not surprisingly, gamers are rather intolerant of network failures during games.

Basically, the network subsystem informs the other computers in a network of the current state of the game so that the players stay synchronized. This can be quite a trick, and so it is wise to develop the game with network capabilities in mind. You may find that a networking library such as Apple's OpenPlay makes this job a bit easier.

Above all, do not implement network support as an afterthought, because it often affects the entire design of the game. Decide whether your game lends itself to netwok play and build this requirement into the fundamental game design; doing so will save headaches later on when the designer invariably demands that multiplayer capabilities be added.
\index{engine!network subsystem|)}

\subsection{The Update Subsystem}
\index{update subsystem|see{engine, update subsystem}}
\index{engine!update subsystem|(}
Games generally have to track a lot of rapidly changing data, including the state of the player and the condition of each enemy---information that must be updated frame by frame to keep the game moving. The update subsystem manages this data.

The update subsystem is the game's brain. It enforces the game's rules for movement upon the player, ``plays'' the role of each enemy (which might involve a certain amount of artificial intelligence), ensures that every object is within the allowed boundaries, and inflicts injuries. It could almost be said that the other game modules are merely interfaces to the update subsystem.

Although it may be tempting to haphazardly throw the update subsystem into the game loop (discussed in the next section), do not do so. Game projects tend to get out of hand quickly if they are not kept in a reasonable amount of order, and the update subsystem usually grows steadily throughout the development cycle; make the update system a separate module to begin with. If you don't pay attention to code organization, you'll end up with code that looks like the 500,000 lines of spaghetti behind (no offense, Activision) \gametitle{Civilization: Call To Power}.
\index{engine!update subsystem|)}

\subsection{The Game Loop}
\index{game loop|(}
\index{engine!game loop|(}
\extfigure{figures/gameloop-figure}{fig:gameloop}{A typical game loop}

The game (see Figure \ref{fig:gameloop}) loop is the ``glue'' that binds the various game subsystems. It is simply a \code{while} loop that runs throughout the entire game, looping anywhere from 30 to 60 times per second. The game loop invokes the correct routines to gather input from the player and from the network, updates the status of all objects in the game, draws the next frame of graphics, and produces audio. While this process may sound complicated, it is actually quite trivial, because all of this functionality is provided by the game's input, network, graphics, and audio subsystems.

The game loop should start as soon as the game's other subsystems have been initialized, and should end when the player exits the game. It may be a good idea to separate the menu system from the main game loop in some cases, but doing so could actually complicate the game's code. With a properly written game loop, a game becomes a ``state machine'' that acts on its current state based on the player's input.

Organization is important too, since the game loop sequences the other subsystems. This should not be a haphazard decision; for instance, the data gathered from the networking subsystem often influences the decisions of the other subsystems, so it should be invoked first. The graphics subsystem should probably be last, since it reflects the data generated by all of the other subsystems.
\index{engine!game loop|)}
\index{game loop|)}

As you can see, a game engine is conceptually simple, but the devil is in the details. In the next chapter we'll become familiar with the tools we'll use for Linux game programming, and then we'll start to work with the libraries and interfaces that make it all possible. If you're already familiar with development tools like gcc and gdb, you may wish to skim over Chapter \ref{ch:linuxdevel} and move on to Chapter \ref{ch:gamingapis} or \ref{ch:masteringsdl}.
