Game Programming with the Simple DirectMedia Layer

by Bob Pendleton

Simple DirectMedia Layer (SDL, www.libsdl.org) is a simple, yet powerful, cross-platform game and multimedia development library. The library was developed by Sam Latinga while he was working for Loki Software, Inc. and was used in their commercial game projects. SDL was developed to meet the needs of game developers working in a multi-OS environment and was used in the Linux versions of Maelstrom, Hopkins FBI, Civilization: Call to Power, Descent 2, MythII: Soulblighter, Railroad Tycoon II, Tux Racer and many more. The SDL web site lists hundreds of games and applications written using SDL.

SDL officially supports Linux, Windows, BeOS, Mac OS, Mac OS X, FreeBSD, OpenBSD, BSD/OS, Solaris and IRIX. SDL also works with Windows CE, AmigaOS, Atari, QNX, NetBSD, AIX, Tru64 UNIX and SymbianOS. However, those OSes are not yet officially supported. This means if you write your application using SDL, you can port it with minimal rework to all those OSes. SDL provides a portable way to write games and multimedia applications on every major OS currently in use.

Installing SDL

If you are using a recent version of Linux, you probably have a complete SDL installation. In fact, a quick check of /usr/bin using ldd on my Red Hat 8.0 system found eight programs that depend on SDL.

The following commands show whether the SDL libraries and C/C++ include files are installed on your system:

locate SDL.h
locate libSDL
locate sdl-config

If all of these commands report the file was found, most likely you have a complete SDL installation, and you need only to make sure it is up to date. The sdl-config program checks the SDL version and acquires compile and link flags for your SDL applications. If sdl-config was found, run:

sdl-config --version
to see which version of SDL you have. If sdl-config reports a version less than 1.2.4, you should install newer libraries. Like most open-source projects, SDL is under constant development, so if you are using SDL for development, check for new versions regularly or join one of the SDL mailing lists to keep track of library updates.

If SDL is not installed, you need to download and install it. Your distribution probably has precompiled SDL packages, so you can check your regular source of packages first. If it's up to date, the easiest way to get started is to install the devel or dev packages for SDL from your distribution.

The file sdl-install.sh included with the source code used in this article is a shell script that downloads and installs version 1.2.5 of SDL and all its add-on libraries. The script must be run as root in the directory where you want the source for SDL. The script downloads the following:

If you don't use sdl-install.sh, visit the web pages listed above, download the files, unpack them and follow the instructions in the appropriate README files to install the libraries. Test your new installation by running:

sdl-config --version
If it doesn't run or gives a version number lower than the version you installed, the installation didn't work. In my experience, this happens when I don't follow the instructions or leave an old version of SDL installed in a different place. If locate sdl-config lists more than one location, either delete the old SDL installation, something I hate to do, or re-install over the old version. The sdl-install.sh file shows how to use ./configure --prefix to install SDL anywhere you want, but it's safest and easiest to install in the default location.

SDL documentation can be found at www.libsdl.org/docs.php. On-line documents are at sdldoc.csn.ul.ie. Support library documentation is either linked from their download pages, included with the source code or embedded in the .h files. Sample programs are included with SDL, and its support libraries are great starting places for your own projects.

SDL Example

The file bounce.cpp [available at ftp.linuxjournal.com/pub/lj/listings/issue110/6410.tgz] is a game written using SDL for input and graphics and SDL_ttf to load TrueType fonts. The game itself is a little over 1,300 lines of C++, and the complete package includes the source code, images, a TrueType font, a makefile, sdl-install.sh and the license files for the font and images used in the game. Finding fonts, graphics and sounds that you can use legally in your games can be more work than writing the game.

To get started learning SDL, download the Bounce source code from the Linux Journal FTP site and unpack it with tar -xzvf bounce.tar.gz. Then run make to build the program. Run the program by typing bounce at the command line. You can run it in full-screen mode by typing bounce -fullscreen. The plot of the game is that Earth has started wandering around the solar system and is in danger of falling into the Sun. Your job is to keep Earth out of the Sun by hitting it with the Moon. You score a point each time you hit the Earth with the Moon, and the game scores every time the Earth hits the Sun. The game is designed to show off features of SDL, not to be the most interesting game you've ever seen.

Game Programming with the Simple DirectMedia Layer

Figure 1. The Game Bounce

Initialize SDL

SDL must be initialized before any SDL functions are used by calling SDL_Init():

if (-1 == SDL_Init((SDL_INIT_VIDEO |
                    SDL_INIT_TIMER |
                    SDL_INIT_EVENTTHREAD)))
{
  ...
}

The parameter to SDL_Init() identifies the subsystems that need to be initialized. Here, I tell SDL to initialize the video, timer and subsystems and to use thread-based event processing. I also could have used the catch-all SDL_INIT_EVERYTHING, but you should initialize only the parts of SDL that your program uses. There is no reason to initialize the joystick or CD-ROM if you are not going to use them. You can initialize and shut down subsystems at any time by the use of the SDL_InitSubSystem() and SDL_QuitSubSystem() functions.

It is important to shut down SDL with a call to SDL_Quit() before your program shuts down. SDL_Quit() shuts down all SDL subsystems, frees all system resources used by SDL and restores the video mode. It is good practice to use atexit() to make sure that SDL_Quit() runs when your program terminates. Failure to call SDL_Quit() can leave your computer in a strange video mode.

Set the Video Mode

When selecting a video mode, decide whether to run in a window or as a full-screen application. Then, choose the size of the window or screen. If you go with a window, decide whether the user can resize it. Then, choose how to adapt to the color depth of the screen. In Bounce I use something like:

options = SDL_ANYFORMAT |  SDL_FULLSCREEN;
screen = SDL_SetVideoMode(640, 480,
                          0,
                          options);

The first two parameters specify the width and height, in pixels, of the screen or window in which the program runs. To use a particular width and height in full-screen mode, the screen section of your XF86Config-4 (or XF86Config for some versions of X) file must list the specified size. If Bounce won't run in full-screen mode on your machine, it is most likely because you don't have a 640 × 480 mode set up in the screen section of your XF86Config-4 file.

The third parameter specifies the number of bits per pixel. Or, if it is set to 0 (zero), it tells SDL to use the current display depth. It is best to adapt the game to the current display depth rather than counting on every machine on which the code will ever run to support your desired pixel format.

The last parameter lets you give SDL detailed instructions on how to set up the video mode. There are nearly a dozen options from which to chose. In Bounce, I use SDL_ANYFORMAT to let SDL pick the best available mode. This option forces your code to adapt to whatever pixel depth you have, but using it can provide better performance at the cost of some extra coding. The SDL_FULLSCREEN option tells SDL to set a full-screen mode.

The value returned by SDL_SetVideoMode() is a pointer to an SDL_Surface structure. This structure describes the screen in great detail. If the pointer is NULL, the video mode you requested is not available. But, getting a non-NULL value doesn't mean you got everything you wanted. Check the flags field of this structure against the options you specified. I have found it is best to ask for little and work with what I receive, that way I avoid hard wiring my machine and OS restrictions in my code.

Now that the video mode is configured, use SDL_WM_SetCaption() to set the window title and icon name. This isn't necessary; it's one of those touches that make the program a little easier to use:

SDL_WM_SetCaption("Bounce", "Bounce")
Loading Resources

Before Bounce can start up, it must load and initialize the resources it uses. Bounce has to initialize colors, load a few images and load the font it uses to draw text. Because the video mode was set using SDL_ANYFORMAT, all of these resources have to be converted to match an arbitrary display format. The following code creates a red pixel in the format we need:

SDL_PixelFormat *pf = screen->format;
int red = SDL_MapRGB(pf, 0xff, 0x00, 0x00);

The SDL_PixelFormat structure is a description of the screen pixels, and SDL_MapRGB() converts a standard 24-bit RGB color representation into a pixel value that shows that color when drawn on that screen.

Loading images is slightly more complex:

SDL_Surface *s0, *s1;
s0 = SDL_LoadBMP(name);
s1 = SDL_DisplayFormat(s0);
SDL_SetColorKey(s1,
                (SDL_SRCCOLORKEY |
                 SDL_RLEACCEL),
                black);
SDL_FreeSurface(s0);

Core SDL includes SDL_LoadBMP(), which loads a .bmp format image as an SDL_Surface. SDL_image provides routines for loading many other image formats. The image is in the format in which it was created. We convert it to the display format using SDL_DisplayFormat(). SDL_SetColorKey() is used to tell SDL that when it copies (blits) this surface into another surface, it should ignore all the black pixels. I do this so that when I copy an image of the Earth onto the screen, none of the black background gets copied, and only the pixels inside the round shape of the Earth are touched. The SDL_RLEACCEL flag tells SDL to run length encode (RLE) the image. Using RLE-encoded images speeds up image copying.

Bounce uses one TrueType font but in three different sizes, two different colors and three different styles. Using the SDL_ttf library, I wrote a routine that loads a TrueType font, renders each of the ASCII characters in the range of 0-127 as an SDL_Surface, converts each character to match the screen and saves the height, width and advance of each letter so I can draw strings on the screen.

The Main Loop

SDL provides an event-based input system, much like that used by X, Mac OS and Windows. When a key is pressed or the mouse is moved, an event is placed in a queue. The program can either wait for events using SDL_WaitEvent() or poll for events using SDL_PollEvent(). The main loop must process events, update the game state, draw the next frame and repeat until done.

The decision to wait or poll for events affects the overall structure of the game. I chose to wait for events and use a heartbeat timer to drive the action. I like this combination because it lets the program handle events whenever they occur while controlling CPU usage. Both of those qualities are important in networked games.

The timer is initialized using:

timer = SDL_AddTimer(10, timerCallback, NULL);

This tells SDL to call a routine named timerCallBack every ten milliseconds. My timer callback uses SDL_PushEvent() to send an event. Because timer callbacks run in a separate thread, they can send events even though the game is stopped, waiting for events. When it receives a timer event, Bounce checks to see if it is time to draw another frame. The timer makes sure the program doesn't try to draw more than 100 frames/second, while allowing the game to run at a slower rate if it must. On my machine, it runs at 85 frames/second, which matches the refresh rate of my monitor.

Bounce is organized into several different pages. The main loop handles events that are common among all the pages, such as quitting the program when you press Esc or pausing the game when you press F1. After the main loop has looked at an event, it passes the event to the current page. Each page is a function that takes an SDL_Event as its parameter. Each page has the responsibility to handle events, keep track of the time and draw the screen. Although this approach leads to some duplicate code, it gives the programmer greater flexibility, and it lends itself to an object-oriented design where each page is an instance of a page class. The following example shows parts of the main loop and illustrates how events are passed to the individual pages:

while ((!done) && SDL_WaitEvent(&event))
{
  switch (event.type)
  {
  case SDL_QUIT:
    done = true;
    break;
  case SDL_KEYDOWN:
    switch(event.key.keysym.sym)
    {
    case SDLK_ESCAPE:
      done = true;
      break;
    case SDLK_F1:
      play = !play;
      break;
    }
    break;
  }
  if (play &&
      (!done) &&
      (NULL != currentPage))
  {
    currentPage(&event);
  }
}

The global variable currentPage points to the implementation of the current page. When one page wants to start another page, it initializes the new page and sets the pointer to that page. Bounce has three pages: the welcome page you see when the program starts, another page handles game play, and the “You Won/You Lost” message is the third page.

The event handler in the welcome page looks like:

switch (e->type)
{
  case SDL_USEREVENT:
    switch (e->user.code)
    {
    case MY_TIMEREVENT:
      now = SDL_GetTicks();
      dt = now - lastTime;
      if (dt >= minFrameTime)
      {
        drawWelcome(dt);
        lastTime = now;
      }
      break;
    }
    break;
case SDL_MOUSEBUTTONDOWN:
  initBounce();
  currentPage = bounce;
  break;
}

When this code sees a timer event, it checks how long it has been since it last updated the screen and calls drawWelcome() to animate the screen. When it sees that a mouse button has been pressed, it switches to the game page by calling initBounce() to get it ready and then sets currentPage to point to the game page. The next time through, the main loop bounce() will be called.

Animation

The animation routine uses the dirty pixels technique so only a small portion of the screen is redrawn for each frame. With this technique, we keep track of the last position in which an object was drawn and the new position. When Bounce draws the Earth, first it erases the dirty pixels where it was by filling them with the background color, and then it draws the Earth in its new location. We fill rectangles and draw images using:

SDL_FillRect(screen, rectangle, color);
SDL_BlitSurface(image, NULL, screen, rectangle);

SDL_FillRect() fills a rectangle in an SDL_Surface, like the screen, with a color. The rectangle is specified using an SDL_Rect structure, and the color is created using SDL_MapRGB(). SDL_BlitSurface() copies a rectangle from one surface into a rectangle in another surface. If the source rectangle is NULL then the whole surface is copied. SDL_BlitSurface() is the routine that applies the color key and takes advantage of RLE encoding.

Summary

SDL reduces the time it takes to write games on Linux. It is small enough that learning it is a project, not a career, and it is powerful enough for commercial applications. I hope that between the information in this article and the source code for Bounce, you have learned enough of SDL to start modifying Bounce and building your own SDL games.

Resources

Game Programming with the Simple DirectMedia Layer
email: bob@pendleton.com

Bob Pendleton's first programming assignment was to port games from an HP minicomputer to a UNIVAC mainframe, and he has been fascinated by computer games ever since. He has been working with various versions of UNIX and Linux since 1981. He is an independent software developer and writer. You can reach him at Bob@Pendleton.com.

Load Disqus comments

Firstwave Cloud