June 18th, 2013
SDL 2.0 has been released, which changes the way you create OpenGL contexts. This post details the changes so you can convert your old SDL/OpenGL code to SDL 2. If you are new to SDL and OpenGL, you should also read my SDL and OpenGL article, as that article covers some topics that aren’t covered here, such as initializing SDL.
To create an OpenGL context with SDL 2, you need to be aware of two new SDL data types: SDL_Window and SDL_GLContext. As the type names indicate, SDL_WIndow is a window, and SDL_GLContext is an OpenGL context. To create an OpenGL context with SDL 2, you must create a window, then create a context. The code to do this comes later, but for now, what you need to know is that your game needs variables to store the window and OpenGL context.
SDL_Window* mainWindow; SDL_GLContext mainGLContext;
When you create an SDL window, you must supply flags that describe the type of window you want to create. The following are common flags to use:
Use the bitwise OR operator (|) to combine multiple flags.
Call the function SDL_CreateWindow() to create a window. The function takes the following arguments:
After creating the window, call the function SDL_GL_CreateContext() to create the OpenGL context. Supply the SDL window you created by calling SDL_CreateWindow(). The following code creates a 1024 by 768 pixel window and OpenGL context:
Uint32 flags = SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL; int width = 1024; int height = 768; mainWindow = SDL_CreateWindow("SDL2 OpenGL Example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); mainGLContext = SDL_GL_CreateContext(mainWindow);
Most OpenGL games use double buffered drawing. When using double buffering, OpenGL erases the old scene and draws the new scene offscreen so the player doesn’t see the erasing and redrawing. After drawing the scene offscreen, swap the buffers to make the newly drawn scene appear on the screen. Call the function SDL_GL_SwapWindow() in your scene drawing code to swap the buffers in SDL 2, supplying the SDL window you created.
Call the function SDL_GL_DeleteContext() to delete the OpenGL context you created. Call the function SDL_DestroyWindow() to destroy the SDL window you created.
I have a small sample program on Github that creates an OpenGL context and draws a rectangle. Look at the sdl2 branch for the SDL 2 code.