Using CEGUI with SDL and OpenGL

From CEGUI Wiki - Crazy Eddie's GUI System (Open Source)
Revision as of 03:02, 1 June 2005 by Lindquist (Talk | contribs)

Jump to: navigation, search

SDL (Simple DirectMedia Layer) is an excellent library for writing portable games and other multimedia applications, but as it is a low-level library, it has no native support for GUI interfaces.

When using OpenGL for rendering, using CEGUI with SDL is not hard.

I'll assume that you've read the imbiciles tutorials, and have used SDL with OpenGL. And know C / C++ ...


Initialisation

Before we can do anything, we need to initialise our libraries. First SDL:

if (SDLInit(SDL_INIT_VIDEO|SDL_INIT_TIMER)<0)
{
  fprintf(stderr, "Unable to initialise SDL: %s", SDL_GetError());
  exit(0);
}

Here we initialise SDL with video and timer support. We need this for CEGUI. O.K. now SDL is ready to go. So let's fire up OpenGL:

if (SDL_SetVideoMode(800,600,0,SDL_OPENGL)==NULL)
{
  fprintf(stderr, "Unable to set OpenGL videomode: %s", SDL_GetError());
  SDL_Quit();
  exit(0);
}

Now OpenGL is ready. But we still need to set a decent configuration:

glEnable(GL_CULL_FACE);
glClearColor(0.0f,0.0f,0.0f,1.0f);
glViewport(0,0, 800,600);

The OpenGL renderer that comes with CEGUI sets the matrices itself, so if you're using CEGUI for all your rendering needs this would be fine. Normally you would want the normal perspective projection setup though:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, 800.0/600.0, 0.1,100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

SDL and OpenGL are now both ready for action. So it's time to initialise CEGUI. First we need the renderer.

#include "renderers/OpenGLGUIRenderer/openglrenderer.h"

It must be created before starting CEGUI.

CEGUI::OpenGLRenderer* renderer = new CEGUI::OpenGLRenderer(0,800,600);

Then the CEGUI::System must be initialised:

new CEGUI::System(renderer);

Remember that you have to load a widget set, set the mouse cursor and a default font before CEGUI is completely ready. This is described in the other tutorials.


By default the SDL cursor is displayed, so we'll remove that:

SDL_ShowCursor(SDL_DISABLE);

As keypress characters needs to be injected into CEGUI, we activate unicode translation for SDL key events:

SDL_EnableUNICODE(1);

This makes it alot easier as we don't have to worry about modifier keys and keyboard layouts ourselves. More about this later on...

Key repeat is a nice feature for the text input widgets in CEGUI, so we use SDL to generate them:

SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

Everything is ready now, and we can start the main loop :)


The Main Loop

To make it all happen, we use a simple main loop that just keeps pushing on those frames:

void main_loop()
{
  bool must_quit = false;
  
  // get "run-time" in seconds
  double last_time_pulse = 0.001*static_cast<double>(SDL_GetTicks());
  
  while (!must_quit)
  {
    inject_input(must_quit);
    inject_time_pulse(last_time_pulse);
    render_gui();
  }
}

This function will run the main loop until the bool value must_quit becomes true. In this tutorial this will happen when the user clicks the close button provided by the window manager (fx. Microsoft Windows).

The double value last_time_pulse holds the time of the latest time pulse injection. More about this later.

Each function in the while loop will be described below.

There are endless ways of making your main loop. I took a simple approach to ease writing this tutorial.


Injecting Input

When the user press or release keyboard or mouse buttons, we need to tell CEGUI about it, for this we use the injection functions of CEGUI::System.

Here is what our inject_input function looks like:

void inject_input(bool& must_quit)
{
  SDL_Event e;
  
  // go through all available events
  while (SDL_PollEvent(&e))
  {
    // we use a switch to determine the event type
    switch (e.type)
    {
      // mouse motion handler
      case SDL_MOUSEMOTION:
        // we inject the mouse position directly.
        CEGUI::System::getSingleton().injectMousePosition(
          static_cast<float>(e.motion.x),
          static_cast<float>(e.motion.y)
        );
        break;
    
    // mouse down handler
      case SDL_MOUSEBUTTONDOWN:
        // let a special function handle the mouse button down event
        handle_mouse_down(e.button.button);
        break;
    
      // mouse up handler
      case SDL_MOUSEBUTTONDOWN:
        // let a special function handle the mouse button up event
        handle_mouse_up(e.button.button);
        break;
    
    
      // key down
      case SDL_KEYDOWN:
        // to tell CEGUI that a key was pressed, we inject the scancode.
        CEGUI::System::getSingleton().injectKeyDown(e.key.keysym.scancode);
        
        // as for the character it's a litte more complicated. we'll use for translated unicode value.
        // this is described in more detail below.
        if ((e.key.keysym.unicode & 0xFF80) == 0)
        {
          CEGUI::System::getSingleton().injectChar(e.key.keysym.unicode & 0x7F);
        }
        break;
    
      // key up
      case SDL_KEYUP:
        // like before we inject the scancode directly.
        CEGUI::System::getSingleton().injectKeyUp(e.key.keysym.scancode);
        break;
    
    
      // WM quit event occured
      case SDL_QUIT:
        must_quit = true;
        break;
    
    }
  
  }

}

First I'll explain the events that get handled directly in the inject_input function.


Mouse Motion:

// we inject the mouse position directly.
CEGUI::System::getSingleton().injectMousePosition(
  static_cast<float>(e.motion.x),
  static_cast<float>(e.motion.y)
);

There is nothing special here. Like stated in the comment the mouse position is just injected directly.

There are two ways of injecting mouse motion. One where you inject how much the cursor moved, and one where you inject the mouse cursor position. The last one is failsafe. Then first one only works correctly in fullscreen mode, or with input grabbed. The reason for this is that in regular windowed mode, the mouse can be moved outside the application window, and during this time no mouse motion event are generated. So if we enter the window at another position, the real mousecursor and CEGUI's mouse cursor will be offset, which will break mouse usage.


Key Down
This event takes a little more work. CEGUI requires that key characters (the printable character the key represents) are injected alongside key codes.

// to tell CEGUI that a key was pressed, we inject the scancode.
CEGUI::System::getSingleton().injectKeyDown(e.key.keysym.scancode);

Luckily the key code is just the SDL scancode, so we inject that directly.

// as for the character it's a litte more complicated. we'll use for translated unicode value.
// this is described in more detail below.
if ((e.key.keysym.unicode & 0xFF80) == 0)
{
  CEGUI::System::getSingleton().injectChar(e.key.keysym.unicode & 0x7F);
}

Instead of formatting the keypress ourselves, we let SDL do it for us. For more information, take a look at the SDL documentation for this feature. SDL_keysym.


Key Up
This one is simple. Only the keycode need to injected. So we just use the scancode directly:

// like before we inject the scancode directly.
CEGUI::System::getSingleton().injectKeyUp(e.key.keysym.scancode);


Mouse Button Down and Mouse Wheel
CEGUI and SDL are a little different when it comes to mouse button and mouse wheel events. So a little conversion is necessary. Here's the handle_mouse_down function that gets called when a mouse button down event occurs in SDL. It takes one parameter, a Uint8 describing the mouse button that was pressed.

void handle_mouse_down(Uint8 button)
	{
	switch ( button )
		{
		// handle real mouse buttons
		case SDL_BUTTON_LEFT:
			CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::LeftButton);
			break;
		case SDL_BUTTON_MIDDLE:
			CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::MiddleButton);
			break;
		case SDL_BUTTON_RIGHT:
			CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::RightButton);
			break;
		
		// handle the mouse wheel
		case SDL_BUTTON_WHEELDOWN:
			CEGUI::System::getSingleton().injectMouseWheelChange( -1 );
			break;
		case SDL_BUTTON_WHEELUP:
			CEGUI::System::getSingleton().injectMouseWheelChange( +1 );
			break;
		}
	}

I chose a very "manual" conversion, but it works fine. Everything should be pretty self-explainatory. As you can see mouse wheel events are emitted as mouse button down events in SDL.


Mouse Button Up
The mouse button up event is handled very much like the mouse button down event, except there are no mousewheel release events. Like handle_mouse_down it takes one parameter, a Uint8 describing the mouse button that was released:

void handle_mouse_up(Uint8 button)
	{
	switch ( button )
		{
		case SDL_BUTTON_LEFT:
			CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::LeftButton);
			break;
		case SDL_BUTTON_MIDDLE:
			CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::MiddleButton);
			break;
		case SDL_BUTTON_RIGHT:
			CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::RightButton);
			break;
		}
	}


Time Pulses

SDL has a built-in millisecond counter which we will use for this example. There are other ways to use timers with SDL, but I chose this approach as it is simple to use, and provides decent precision.

Remember in the main loop where we stored the current "run-time" in seconds ? This value will be passed as a reference to inject_time_pulse function which in turn will set a new value to it.

CEGUI's interface for injecting time pulses requires that you pass the time in seconds that has passed since the last time pulse injection. Let's take a look at the function:

void inject_time_pulse(double& last_time_pulse)
{
	// get current "run-time" in seconds
	double t = 0.001*SDL_GetTicks();

	// inject the time that passed since the last call 
	CEGUI::System::getSingleton().injectTimePulse( float(t-last_time_pulse) );

	// store the new time as the last time
	last_time_pulse = t;
}
  • The first line gets the actual "run-time" when called.
  • The second line injects the time pulse as the difference between the current time and the last time.
  • The third line stores the current time as the last time a time pulse was injected.

This will work for about 47 days... After that the counter wraps to zero and it breaks... I'll leave it up to you to fix that if it's a problem.


Rendering

Now all thats left is rendering something. :)

void render_gui()
{
	// clear the colour buffer
	glClear( GL_COLOR_BUFFER_BIT );

	// render the GUI :)
	CEGUI::System::getSingleton().renderGUI();

	// Update the screen
	SDL_GL_SwapBuffers();
}

The line:

CEGUI::System::getSingleton().renderGUI();

does all the CEGUI magic and sets OpenGL state itself. As long as the viewport is setup, it will render the GUI.


Error Handling

The neat C++ architecture of CEGUI suggests that C++ exceptions are used for error handling. This is completely true. Whenever an error occurs, a sub-class of CEGUI::Exception is thrown.

There are many scenarios where an exception can be thrown. And whether or not these should be considered fatal depends on the application. To make sure you catch the CEGUI exceptions a regular try block is used. Like so:

try
{
	// do some cegui code
}
catch (CEGUI::Exception& e)
{
	fprintf(stderr,"CEGUI Exception occured: %s", e.getMessage().c_str());
	// you could quit here
}


That's it. Now you know how to use SDL, OpenGL and CEGUI together. Have fun.

--Lindquist 16:21, 8 May 2005 (BST)