SDL & OpenGL Game with C++ – Part I
Parts in the Series
Getting Started
I think I’ve spent too many late nights playing multiplayer Modern Warfare 2 and now I feel the need to build a small game of some kind. Game programming is fun, and although I’ve never done it professionally, I have dabbled with it as a hobby for many years. I’ll be documenting my progress here over time via a number of different postings. Maybe some of you will find it useful as a reference or small SDL tutorial or game programming tutorial. That being said, time to get to work!
I have no idea what type of game to build yet so the first thing to do is just get the basic framework setup. I’ll be using C++ for this game project. I thought about using C# and XNA but I need to dust off my C++. For the graphics system I decided to use OpenGL. This is mostly because I am familiar with it and didn’t want the extra overhead of boilerplate setup stuff associated with DirectX. I just want to get something going quickly. For the rest of the stuff needed (audio, input, etc) I am going to use SDL. SDL is a great tool to get things up and running fast and it easily interfaces with OpenGL. I am also thinking about putting in some UI stuff using CEGUI (Crazy Eddie’s GUI System).
SDL Setup Prerequisites
Before we get started you’ll want to make sure you have the SDL development libraries (I am using version 1.2.14). You can find them on the SDL website: http://www.libsdl.org. The ones I used specifically are:
- Runtime – http://www.libsdl.org/release/SDL-1.2.14-win32.zip
- Library (Visual Studio 2008) – http://www.libsdl.org/release/SDL-devel-1.2.14-VC8.zip
Creating the Project
Ok enough talk, let’s get started. You’ll need to create a new project and correctly configure it to use the SDL library. Fire up Visual Studio and create a new C/C++ console project. In the project wizard, uncheck the “Using Precompiled Header” option and check the “empty project” option. Now, add a new file and call it main.cpp.
In the Solution Explorer, right click your project and select properties. Open the C/C++ settings and select the general property page. Under the item “additional include directories” enter the path to the SDL SDK header files (i.e. C:\YourSDLDir\SDL-1.2.14\include).
Now, drop down to the Code Generation page and under “Runtime Library” select “Multi-threaded DLL”. If you try to link with the debug build of the runtime you’ll see a nice error message like this one:
warning LNK4098: defaultlib ‘msvcrt.lib’ conflicts with use of other libs; use /NODEFAULTLIB:library
This is because the SDL runtime is not a debug build. I couldn’t find a debug build on the SDL website so I guess if you want one you have to build it from source.
That takes care of the C/C++ settings so now let’s do the linker settings. Under the linker settings select the general page. Under additional library directories enter the path to the lib directory for your SDL SDK (i.e. C:\YourSDLDIR\SDL-1.2.14\lib). On the input page 2 files need to be listed as additional dependencies.
- SDL.lib
- SDLmain.lib
Also, make sure you grab SDL.dll from the SDK and put it in your debug folder along side the executable you build.
And that’s it! Go ahead and compile your application to make sure you set everything up correctly.
Basic SDL Usage
Next we will fill out main.cpp to get a basic SDL skeleton application running. Start out by including the SDL header file.
#include <sdl.h>Now add the main function:
int main( int argc, char **argv) { return 0; }
Now, an interesting thing to note here is that’s not really your normal main function. It’s not even the main entry point into your application. SDL redefines main using a #define to SDL_main. This also means that you cannot change the function signature as you normally could for a main function. SDL_main just does some basic housekeeping/setup stuff on behalf of SDL.
SDL Initialization
Next up we need to initialize the SDL system. This is accomplished via SDL_Init. Go ahead and add the following to your main function.
if( SDL_Init( SDL_INIT_VIDEO ) == -1 ) { fprintf(stderr, "Failed to initialize SDL. [%s]\n", SDL_GetError()); exit(1); }
This will initialize SDL and the video subsystem. If it fails, it will print an error message to the standard error stream. Since we have a console app, this information will be printed directly to the console. Note the usage of SDL_GetError. This is a great tool to help determine why an SDL function call failed. It simply returns a pointer to a null-terminated string containing a description of the last failure.
The next thing to do is setup a video mode. This will give us a window and a drawing surface so we can actually render game content to the screen. Add the following code after the SDL_Init block.
SDL_Surface *screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); if( screen == NULL ) { fprintf(stderr, "Failed to set video mode. [%s]\n", SDL_GetError()); exit(1); }
This will get us a window and a surface to draw on that’s 640×480 with 32 bits per pixel. The video surface will be created in system memory as opposed to say video memory thanks to the SDL_SWSURFACE flag. That’s ok for now. Also note that you could create the application in fullscreen mode by specifying SDL_FULLSCREEN for the last parameter.
Now we’re going to add the main game loop. Game loops can get pretty complicated but we will keep it simple here. For now we only need to check user input. So let’s add the following code now.
Game Loop & Event Processing
SDL_Event evt; bool done = false; while( !done ) { while( SDL_PollEvent( &evt ) ) { switch( evt.type ) { case SDL_QUIT: done = true; break; case SDL_KEYUP: if( evt.key.keysym.sym == SDLK_ESCAPE ) done = true; break; default: break; } } }
Ok, so what’s going on here is that for every trip through the game loop we are emptying the SDL event queue and processing the events. SDL stores all kinds of events for us such as key presses, mouse movement, and joystick input. In this case, we want to know if the user wants to quit the application (SDL_QUIT) or if the user presses the escape key (SDL_KEYUP). In both cases we simply set done to true to signal the main loop to bail. SDL_Event is a union with all kinds of interesting structures in it. You should have a look at it in the SDL documentation.
The last thing that needs to happen is to shutdown the application. We can accomplish that with a simple call to SDL_Quit.
So, without further ado, here is the complete skeletal SDL game code that simply creates a 640×480 window and waits for the user to press escape or close the window.
Full Code Listing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #include <sdl.h> int main( int argc, char **argv) { SDL_Event evt; bool done = false; // initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) == -1 ) { fprintf(stderr, "Failed to initialize SDL. [%s]\n", SDL_GetError()); exit(1); } // create a software surface/window SDL_Surface *screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); if( screen == NULL ) { fprintf(stderr, "Failed to set video mode. [%s]\n", SDL_GetError()); exit(1); } // main game loop while( !done ) { // check for events generated from SDL while( SDL_PollEvent( &evt ) ) { switch( evt.type ) { case SDL_QUIT: done = true; break; case SDL_KEYUP: if( evt.key.keysym.sym == SDLK_ESCAPE ) done = true; break; default: break; } } } SDL_Quit(); return 0; } |
Fun Stuff to Try
So, here’s some fun stuff to try to understand a little more about making things happen in SDL.
Try adding this snippet of code to see how to fill or clear the screen (SDL surface) with a different color. Before the main game loop add this:
Uint32 color1 = SDL_MapRGB(screen->format, 0x00, 0x00, 0xFF); Uint32 color2 = SDL_MapRGB(screen->format, 0x00, 0xFF, 0x00); Uint32 currentColor = color1;
And, your SDL_KEYUP processing code in your main loop should look like this:
case SDL_KEYUP: if( evt.key.keysym.sym == SDLK_ESCAPE ) done = true; else if( evt.key.keysym.sym == SDLK_SPACE ) { currentColor = ( currentColor == color1 ) ? color2 : color1; SDL_FillRect( screen, NULL, currentColor); SDL_UpdateRect(screen, 0, 0, 0, 0); } break;
Now, every time your press the space key the screen color will alternate between green and blue.
Another thing you can do is when processing the key stroke is display the character pressed in the console window. You can do that like this:
case SDL_KEYDOWN: printf( "KEYDOWN: %c\n", evt.key.keysym.unicode); break;
But you have to remember to enable Unicode support within SDL. Do that with a call to SDL_EnableUNICODE(1) in the initialization code prior to the main game loop.
What Next?
Well that’s it for now. You now have a basic game setup using SDL. It also shows some basic ways to manipulate the screen and process SDL events. Next time I am going to start integrating OpenGL and get something fun on the screen.
If you have any questions or comments let me know. See ya next time!!!
November 23, 2009
Posted in: C/C++, Game Programming

4 Responses
Crows Programming » SDL & OpenGL Game with C++ – Part II - December 8, 2009
[...] Part I – Getting Started [...]
Thanks a lot for this tutorial! I am new to SDL and this really helped me to get a good start.
I took 1 st loans when I was very young and it supported my business a lot. But, I need the financial loan once again.
TONY - June 26, 2010
PillSpot.org. Canadian Health&Care.Special Internet Prices.No prescription online pharmacy.Pillspot.org. Vitamins@buy.online” rel=”nofollow”>.…
Categories: Weight Loss.Stomach.Skin Care.Antidepressants.Vitamins/Herbal Supplements.Mens Health.Stop SmokingAnti-allergic/Asthma.Eye Care.Blood Pressure/Heart.Antibiotics.Pain Relief.Antiviral.Anxiety/Sleep Aid.Antidiabetic.Mental HealthWomens H…
Leave a Reply