Other SDL Screen Modes

So far, our SDL example program only supports one particular graphics mode, i.e. 640x480 at 32 bit colour depth (or 4 bytes per pixel). But this is not convenient if one wishes to use a different mode, or if the mode we want is not available.

One way we could fix this is to edit our setpixel routine and have it check each time which mode we are using and then write to screen memory in an appropriate way. But there is one problem with this approach: it is slow. Even a simple switch statement in our setpixel routine is going to take quite a bit of time each time a pixel needs to be drawn. We are always better inserting the case statement further out in the layers of code that we have, to make sure things run as fast as possible.

To achieve this, we write three different setpixel routines, one for 8 bit, one for 16 bit and another for 32 bit (we'll save ourselves some trouble by not supporting 24 bit mode, which is slow anyway). So, before we call one of the loops that is used for filling the screen with pixels, we check the colour depth and call a different routine for each of the possibilities.

The example program already contains code for 32 bit mode, so here is the 8 bit version of setpixel:

void setpixel8(SDL_Surface *screen, int x, int y, Uint8 r, Uint8 g, Uint8 b)
{
   Uint8 *pixmem8;
   Uint32 colour;  
 
   colour = SDL_MapRGB( screen->format, r, g, b );
  
   pixmem8 = (Uint8*) screen->pixels  + y + x;
   *pixmem8 = colour;
}

and the version for 16 bit mode

void setpixel16(SDL_Surface *screen, int x, int y, Uint8 r, Uint8 g, Uint8 b)
{
   Uint16 *pixmem16;
   Uint32 colour;  
 
   colour = SDL_MapRGB( screen->format, r, g, b );
  
   pixmem16 = (Uint16*) screen->pixels  + y + x;
   *pixmem16 = colour;
}

Here is a modified version of our example program which allows-na one to change to a different mode simply by changing the constants at the top of the file (note you need to set BPP to 1 for 8 bit, 2 for 16 bit and 4 for 32 bit mode).

We've also modified the program so that if SDL is unable to supply the exact bit depth we requested, the program will still work with the bit depth that SDL provides. This program will now serve quite well as a base for a graphical game and also for the remainder of our tutorial.