Ze SDL way to do multimedia programming

vegaseat 2 Tallied Votes 211 Views Share

The Simple DirectMedia Layer (SDL) library allows for manageable multimedia programming in console mode. Now you can mix graphics, animated or otherwise, with sound and make your game project more interesting. I am showing an example for Dev-C++ using math generated graphics, purloined from the NET, and give some instructions where to get SDL and how to install it properly.

// test of the SDL (Simple DirectMedia Layer) library
//
// here are the instructions to download and install ...
// http://cone3d.gamedev.net/files/sdlgfx/sdlDevCPP-1.2.4.zip
// unzip sdlDevCPP-1.2.4.zip and
// install SDL header files to Dev-Cpp/include/SDL
// install lib files to Dev-Cpp/lib
// copy SDL.DLL to Windows/system32
//
// once that is done, all you have to do is link with libSDL.a via
// Project>>Project Options>>Parameters>>Add Lib>>libSDL.a
// a Dev-C++ console application

#include <cstdlib>
#include <SDL/SDL.h>  // should be in include/SDL

SDL_Surface *screen;

void render()
{   
  // check lock surface
  if (SDL_MUSTLOCK(screen)) 
    if (SDL_LockSurface(screen) < 0) 
      return;

  // SDL time in milliseconds
  int tick = SDL_GetTicks();

  int i, j, yofs, ofs;

  // draw some pixels to the screen
  // you can show off your math skills here!
  yofs = 0;
  for(i = 0; i < 480; i++)
  {
    for(j = 0, ofs = yofs; j < 640; j++, ofs++)
    {
      ((unsigned int*)screen->pixels)[ofs] = i * i + j * j + tick;
    }
    yofs += screen->pitch / 4;
  }

  // check unlock surface
  if (SDL_MUSTLOCK(screen)) 
    SDL_UnlockSurface(screen);

  // update the whole screen
  SDL_UpdateRect(screen, 0, 0, 640, 480);    
}


int main(int argc, char *argv[])
{
  // initialize SDL subsystem video (there are others)
  if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) 
  {
    fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
    exit(1);
  }

  // important, register SDL_Quit to be called and tidy things up on exit
  atexit(SDL_Quit);
    
  // create a 640x480 window with 32bit pixels
  screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
  
  // detect possible error
  if ( screen == NULL ) 
  {
    fprintf(stderr, "Unable to set 640x480 video: %s\n", SDL_GetError());
    exit(1);
  }

  // event loop
  while (1)
  {
    // render stuff
    render();

    // poll for events and handle the ones we need
    SDL_Event event;
    while (SDL_PollEvent(&event)) 
    {
      switch (event.type) 
      {
      case SDL_KEYDOWN:
        break;
      case SDL_KEYUP:
        // if escape key is pressed quit program
        if (event.key.keysym.sym == SDLK_ESCAPE)
          return 0;
        break;
      case SDL_QUIT:
        return 0;
      }
    }
  }
  return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.