Manage your Blog

Create your blog now! Easy and Free

Ubuntuland

Get Paid to Blog About the Things You Love

24/04/2008 GMT 1

Programming Linux Games: The Anatomy of a Game

ubuntuland @ 07:53

In 1991 a Finnish university student named Linus Torvalds began working on a new operating system in his spare time. He didn’t work in isolation, nor did hemake a big deal about what he was doing; rather, he modestly invitedprogrammers from all over the world to join his project, which he dubbed “Linux.” This loosely knit team of students, professionals, and hobbyistscollaborated 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 o ers a sizable audience for computer games. 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.

linux_games.jpg


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 di erent software libraries, and how to set up OpenGL to create uid 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 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.

A Quick Survey of Game Genres
Computer games tend to fall into any one of a number of distinct 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 di erence in its success.

Simulation Games
The simulation genre encompasses a wide variety of games, from ight 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 Heavy Gear II, MechWarrior, and 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 Heavy Gear and 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 MechWarrior and 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. Microsoft Flight Simulator is a popular ight simulator for the PC (and is in fact the current iteration of a long line of ight 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.1 An experienced pilot could certainly tell the di erence between Microsoft Flight Simulator and a real airplane, but it’s nonetheless an enjoyable simulation.

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 WINE2), it’s certainly worth a look if ou’re thinking of writing a ight simulator.
On another front, the Flight Gear project is presently developing a free ight simulator for Linux. The simulator already sports a realistic physics model and an excellent terrain engine, and it is slated to ventually become one of the best ight simulators ever. Flight Gear is portable to many platforms, as it is based lmost entirely on open technology.
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). 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 MechWarrior titles that are very similar to the Heavy Gear series.
Finally, one of my personal favorite simulation games (from many years ago) is Corncob 3D, a completely unrealistic shareware, DOS-based ight simulator.
Guised as a ight 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. Corncob 3D is a good example of a simulator
that trades realism for entertainment value.

First-Person Shooters
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 Quake 3, Half-Life, and 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 di cult 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.



Banner1_468x60


Valve’s 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. Half-Life is based on Quake II’s rendering technology, but that is where the similarities end. Unlike the Quake series, 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 Soldier of Fortune. Decried by critics as gratuitously violent (and hence “indexed” in Germany and classified as an adult title elsewhere), 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.

Deus Ex is one such example, a role-playing game based on the Unreal engine.
Deus Ex has been ported to Linux, and I strongly recommend giving it a try.

Real-time Strategy Games
The genre of games known as Real-Time Strategy (RTS ) games includes such popular titles as StarCraft, Command and Conquer, and 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, 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.

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 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.

Turn-Based Strategy Games
Turn-Based Strategy (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 di erent feel from the faster-paced strategy games. TBS games are not decided by re exes, but rather
by careful planning, which often makes them more di cult, and more attractive to many players. Sid Meier’s Civilization I I is widely regarded as the best turn-based strategy game, because of its balance and replay value.

Deceptively Complex
I once thought that TBS games were easy to write, but then I saw the source code to Sid Meier’s Alpha Centauri (SMAC). Most players don’trealize it, but SMAC actually uses a 3D technique called voxels to
render its units on the y and to draw a height-sensitive landscape with perspective texture mapping and dynamic palette mapping (made possible by self-modifying assembly code). 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.

Role-Playing Games
Role-Playing Games (RPGs) stem from the Dungeons and Dragons role-playing system.3 In this type of game, the player assumes the role of one or more 3 There are lots of similar role-playing systems; I just give DND as an example.
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 e ectively become someone else.
The quality of a role-playing game depends much more on its storyline, interaction, and depth than on its graphics. 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 (http://www.simutronics.com).



Amici_News/468x60.jpg


Puzzle Games
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 (Boxxel and the dangerously addictive Sokoban) to the animated and
ubiquitous 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 di culty 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.

Multiuser Dungeons
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 ROM and DikuMud, which may be downloaded from the Internet. There are untold thousands of private 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 e ect.

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.”

A Quick Look Under the Hood
Most games have a lot in common behind the scenes. The 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 brie y at each of
these subsystems now, and throughout the rest of the book we will explore possible ways to implement each.
This Code Is Awful!
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 co ding!
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.

The 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 di cult, it should be done carefully, because awed input processing can easily ruin an otherwise excellent game. The first version of Apogee’s Rise of the Triad (a first-person shooter from several years ago) su ered 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 e ort (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 4, and we’ll touch on the lower levels of input handling in Linux later on.
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 di erent key locations, and you’ll end up cutting o a lot of would-be players unless you allow them to configure the game
to work with their keyboards. Fortunately, this is not di cult; 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 di erent configuration.


uBid is the marketplace you can trust!


The 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 no t automatic and requires special e ort by the programmer, which is usually accomplished through an API (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 4.
Before you can show o 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.

The 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 di cult 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 e ects for a game is as much an art as creating graphics, and should be left to a specialist. Stellar sound e ects can boost a game’s atmosphere, and lousy sound e ects can
seriously damage a game’s potential.
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 Doppler e ect 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 e ects in hardware.

The 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 di cult 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 exible, 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 a ects 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.

Toys! Free 			shipping on Toys!


Free 			Shipping!


The 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 in icts injuries. It could almost be said that the other
game modules are merely interfaces to the update subsystem.

Keyboard
Input Subsystem
Mouse
Game Pad
Network Subsystem LAN or
Internet
Update Subsystem
3D Hardware /
Framebuffer
Display Subsystem

Audio Subsystem Sound Card

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 o ense, Activision) Civilization: Call To Power.

The Game Loop
The game loop is the “glue” that binds the various game subsystems. It is simply a 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 in uences the decisions of the other subsystems, so it should be invoked first. The graphics subsystem should probably be last, since it re ects the data generated by all of the other subsystems.
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.

Latest Posts


iPods - Hot Christmas Gifts!

Linux Links

Comments

No Comments »

Post a Comment


<a href> <em> <blockquote> <strong> <cite> <code> <ul> <li> <dl> <dt> <dd>

Social Bookmarking
Add to: Mr. Wong Add to: Webnews Add to: Icio Add to: Oneview Add to: Linkarena Add to: Favoriten Add to: Seekxl Add to: Kledy.de Add to: Social Bookmarking Tool Add to: BoniTrust Add to: Power Oldie Add to: Bookmarks.cc Add to: Favit Add to: Newskick Add to: Newsider Add to: Linksilo Add to: Readster Add to: Folkd Add to: Yigg Add to: Digg Add to: Del.icio.us Add to: Reddit Add to: Jumptags Add to: Upchuckr Add to: Simpy Add to: StumbleUpon Add to: Slashdot Add to: Netscape Add to: Furl Add to: Yahoo Add to: Spurl Add to: Google Add to: Blinklist Add to: Blogmarks Add to: Diigo Add to: Technorati Add to: Newsvine Add to: Blinkbits Add to: Ma.Gnolia Add to: Smarking Add to: Netvouz Information