Skip to main content
Raven's CEGUI Tutorial         A CEGUI tutorial from anno 2005

Prerequisites

This tutorial assumes you have knowledge of C++ programming and are able to setup and compile an Ogre application (if you have trouble setting up your application, see this guide for specific compiler setups). This tutorial builds on the previous beginner tutorials, and it assumes you have already worked through them.

Build settings

For those using the source release:

Copy to clipboard
Additional Include Directories = $(OGRE_HOME)\Dependencies\include, $(OGRE_HOME)\Dependencies\include\CEGUI Additional Library Path = $(OGRE_HOME)\OgreMain\Dependencies\Lib\Debug

Make sure to link 'CEGUIBase' and 'OgreGUIRenderer' libraries. i.e. add the following line to your Makefile or g++ command line:

Copy to clipboard
-L/usr/local/lib -lCEGUIBase -lCEGUIOgreRenderer

For those using the SDK:

Copy to clipboard
Additional Include Directories = $(OGRE_HOME)\include\CEGUI

Make sure to add 'CEGUIBase_d.lib' and 'OgreGUIRenderer_d.lib' as Additional Dependencies in the debug configuration. (CEGUIBase.lib and OgreGUIRenderer.lib in the release configuration).

Update (ryandebraal): To add dependencies in Visual C++, click Projects -> Properties -> Configuration Properties -> Linker

Update (Spanky): The CEGUIRenderer source is now a sample project that comes with the CVS source so you must include those directories in your paths to access the OgreGUIRenderer headers and library files.

Just as a side note: The following two directories are needed. However if you go to your install path the commons folder will not be there. Just take it on faith that it will work.

Copy to clipboard
Additional Include Directories += $(OGRE_HOME)\Samples\Common\CEGUIRenderer\include Additional Library Path += $(OGRE_HOME)\Samples\Common\CEGUIRenderer\lib

Introduction



Crazy Eddies GUI System is a free library providing windowing and widgets for graphics APIs / engines where such functionality is not natively available, or severely lacking. The library is object orientated, written in C++, and targeted at games developers who should be spending their time creating great games, not building GUI sub-systems!

Getting Started

Firstly you are going to need to create the skeleton code to create an Ogre application with CEGUI elements. *NOTE*: If you are using <Windows.h>, you must add #define NOMINMAX above your Windows.h header.

Copy to clipboard
//mem probs without this next one #include <OgreNoMemoryMacros.h> #include <CEGUI/CEGUIImageset.h> #include <CEGUI/CEGUISystem.h> #include <CEGUI/CEGUILogger.h> #include <CEGUI/CEGUISchemeManager.h> #include <CEGUI/CEGUIWindowManager.h> #include <CEGUI/CEGUIWindow.h> #include "OgreCEGUIRenderer.h" #include "OgreCEGUIResourceProvider.h" //regular mem handler #include <OgreMemoryMacros.h> #include "ExampleApplication.h" class GuiFrameListener : public ExampleFrameListener { private: CEGUI::Renderer* mGUIRenderer; public: GuiFrameListener(RenderWindow* win, Camera* cam, CEGUI::Renderer* renderer) : ExampleFrameListener(win, cam, false, false), mGUIRenderer(renderer) { } };

Just an empty frame listener that will do nothing, but loop until 'Esc' is pressed.

Copy to clipboard
class TutorialApplication : public ExampleApplication { private: CEGUI::OgreCEGUIRenderer* mGUIRenderer; CEGUI::System* mGUISystem; CEGUI::Window* mEditorGuiSheet;

These are the data members that will hold all the CEGUI data.
Note that I like calling members of the CEGUI namespace explicitly, this will make things clear that they are coming from CEGUI once you start adding in calls to Ogre members.

Copy to clipboard
public: TutorialApplication() : mGUIRenderer(0), mGUISystem(0), mEditorGuiSheet(0) { } ~TutorialApplication() { if(mEditorGuiSheet) { CEGUI::WindowManager::getSingleton().destroyWindow(mEditorGuiSheet); } if(mGUISystem) { delete mGUISystem; mGUISystem = 0; } if(mGUIRenderer) { delete mGUIRenderer; mGUIRenderer = 0; } }

Here is where you can set up any Ogre scene you like, using the methods you learnt in the previous tutorials.
You still add a seperate camera and viewport for your Ogre scene.

Copy to clipboard
protected: void createScene(void) { // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5));

This is where your CEGUI log is created. It is currently set to Informative.
There are four settings: Standard, Errors, Informative and Insane.

Copy to clipboard
// Set up GUI system mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY, false, 3000, mSceneMgr); mGUISystem = new CEGUI::System(mGUIRenderer); CEGUI::Logger::getSingleton().setLoggingLevel(CEGUI::Informative);

Creates a new CEGUI System, using the 'Taharez Look' for the scheme and mouse cursor, with 'BlueHighway-12' for the font.

Copy to clipboard
CEGUI::SchemeManager::getSingleton().loadScheme((CEGUI::utf8*)"TaharezLookSkin.scheme"); mGUISystem->setDefaultMouseCursor((CEGUI::utf8*)"TaharezLook", (CEGUI::utf8*)"MouseArrow"); CEGUI::MouseCursor::getSingleton().setImage("TaharezLook", "MouseMoveCursor"); mGUISystem->setDefaultFont((CEGUI::utf8*)"BlueHighway-12"); mEditorGuiSheet= CEGUI::WindowManager::getSingleton().createWindow((CEGUI::utf8*)"DefaultWindow", (CEGUI::utf8*)"Sheet"); mGUISystem->setGUISheet(mEditorGuiSheet); }

Calls our custom made frame listener, so that we can access 'mGUIRenderer' when we need to.

Copy to clipboard
void createFrameListener(void) { mFrameListener = new GuiFrameListener(mWindow, mCamera, mGUIRenderer); mRoot->addFrameListener(mFrameListener); } };

This is the main function and lets your application loop until you exit it.
You should not need to change this code for this tutorial.

Copy to clipboard
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include "windows.h" INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT ) #else int main(int argc, char **argv) #endif { // Create application object TutorialApplication app; try { app.go(); } catch( Exception& e ) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL); #else fprintf(stderr, "An exception has occured: %s\n", e.getFullDescription().c_str()); #endif } return 0; }

This should compile and run as empty window.
Press escape to Quit and continue.

Update (kro): If you experience run-time problems, you may find help in "CEGUI.log" generated in the directory from which you run this application.

How CEGUI Works

Note: This section isn't by the original author, but was empty, so I filled it with my observations.

CEGUI essentially works by adding a second scene to the viewport that is rendered after Ogre's normal rendering queue is finished. This scene is simply comprised of a bunch of objects that are the 3D representation of a rectangle. (ie. 2 polygons slapped together along their hypotenuse) The rendering matrix is set up to be orthogonal (or nonperspective) to avoid rectangles being scaled or skewed because of their locations and depths. Take these rectangles, add texture maps, and voila, instant GUI. This is generally advantageous because a 3D drawn gui will automatically scale its elements to conform with the screen resolution, and will use hardware texture filtering to do so, which is in general a lot faster and prettier than your standard 2D blitter.

So in one sentence: CEGUI renders a 2D gui using 3D methods and hardware so you don't have to.

--zeroskill 20:27, 14 November 2005 (CST)

End of non-original explanation.

Adding Quit Button

Firstly, we will need to add the header of the element we want to put into the Application - in this case a 'Push Button'.
Add the following line after #include <CEGUI/CEGUIWindow.h>

Copy to clipboard
#include <CEGUI/elements/CEGUIPushButton.h>

Now at the bottom of the createScene() method we need to place in the Quit push button.

Copy to clipboard
CEGUI::PushButton* quitButton = (CEGUI::PushButton*)CEGUI::WindowManager::getSingleton().createWindow("TaharezLook/Button", (CEGUI::utf8*)"Quit"); mEditorGuiSheet->addChildWindow(quitButton); quitButton->setPosition(CEGUI::Point(0.35f, 0.45f)); quitButton->setSize(CEGUI::Size(0.3f, 0.1f)); quitButton->setText("Quit");

The program will now run, with a nice 'Push Button' in the middle of the screen.
But notice that the program still does not do anything, as we are not reacting to events.

If you get compile errors because of the setPosition() and setSize() calls that look like this:

'CEGUI::Window::setPosition' : cannot convert parameter 1 from 'CEGUI::Vector2' to 'const CEGUI::UVector2 &'

Replace the setPosition() and setSize() lines with these:

Copy to clipboard
quitButton->setPosition(CEGUI::UVector2(cegui_reldim(0.35f), cegui_reldim( 0.45f)) ); quitButton->setSize(CEGUI::UVector2(cegui_reldim(0.35f), cegui_reldim( 0.1f)) );

--petrocket 02:43, 20 March 2007 (GMT)

Reacting to Events

Add to TutorialApplication as public functions.

Copy to clipboard
void setupEventHandlers(void) { CEGUI::WindowManager& wmgr = CEGUI::WindowManager::getSingleton(); wmgr.getWindow((CEGUI::utf8*)"Quit")->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&TutorialApplication::handleQuit, this)); } bool handleQuit(const CEGUI::EventArgs& e) { static_cast<GuiFrameListener*>(mFrameListener)->requestShutdown(); return true; }

Redo the GuiFrameListener class to react to mouse and key inputs.

Copy to clipboard
class GuiFrameListener : public ExampleFrameListener, public MouseMotionListener, public MouseListener { private: CEGUI::Renderer* mGUIRenderer; bool mShutdownRequested; public: // NB using buffered input GuiFrameListener(RenderWindow* win, Camera* cam, CEGUI::Renderer* renderer) : ExampleFrameListener(win, cam, true, true), mGUIRenderer(renderer), mShutdownRequested(false) { mEventProcessor->addMouseMotionListener(this); mEventProcessor->addMouseListener(this); mEventProcessor->addKeyListener(this); } // Tell the frame listener to exit at the end of the next frame void requestShutdown(void) { mShutdownRequested = true; } bool frameEnded(const FrameEvent& evt) { if (mShutdownRequested) return false; else return ExampleFrameListener::frameEnded(evt); } void mouseMoved (MouseEvent *e) { CEGUI::System::getSingleton().injectMouseMove( e->getRelX() * mGUIRenderer->getWidth(), e->getRelY() * mGUIRenderer->getHeight()); e->consume(); } void mouseDragged (MouseEvent *e) { mouseMoved(e); } void mousePressed (MouseEvent *e) { CEGUI::System::getSingleton().injectMouseButtonDown( convertOgreButtonToCegui(e->getButtonID())); e->consume(); } void mouseReleased (MouseEvent *e) { CEGUI::System::getSingleton().injectMouseButtonUp( convertOgreButtonToCegui(e->getButtonID())); e->consume(); } void mouseClicked(MouseEvent* e) {} void mouseEntered(MouseEvent* e) {} void mouseExited(MouseEvent* e) {} void keyPressed(KeyEvent* e) { if(e->getKey() == KC_ESCAPE) { mShutdownRequested = true; e->consume(); return; } CEGUI::System::getSingleton().injectKeyDown(e->getKey()); CEGUI::System::getSingleton().injectChar(e->getKeyChar()); e->consume(); } void keyReleased(KeyEvent* e) { CEGUI::System::getSingleton().injectKeyUp(e->getKey()); e->consume(); } void keyClicked(KeyEvent* e) { // Do nothing e->consume(); } };

Ogre 1.4.0

If you're using Ogre 1.4.0 you need to use OIS. For more details on using OIS with Ogre3d, please refer to Using OIS and don't forget to check out Basic Tutorial 5:

Copy to clipboard
class GuiFrameListener : public ExampleFrameListener, public OIS::MouseListener, public OIS::KeyListener { private: CEGUI::Renderer* mGUIRenderer; bool mShutdownRequested; public: // NB using buffered input GuiFrameListener(RenderWindow* win, Camera* cam, CEGUI::Renderer* renderer) : ExampleFrameListener(win, cam, true, true), mGUIRenderer(renderer), mShutdownRequested(false) { mMouse->setEventCallback( this ); mKeyboard->setEventCallback( this ); } // Tell the frame listener to exit at the end of the next frame void requestShutdown(void) { mShutdownRequested = true; } bool frameEnded(const FrameEvent& evt) { if (mShutdownRequested) return false; else return ExampleFrameListener::frameEnded(evt); } bool mouseMoved( const OIS::MouseEvent &e ) { using namespace OIS; CEGUI::System::getSingleton().injectMouseMove( e.state.X.rel,e.state.Y.rel); return true; } bool mousePressed (const OIS::MouseEvent &e, OIS::MouseButtonID id) { CEGUI::System::getSingleton().injectMouseButtonDown( convertOgreButtonToCegui(id)); return true; } bool mouseReleased( const OIS::MouseEvent &e, OIS::MouseButtonID id ) { CEGUI::System::getSingleton().injectMouseButtonUp( convertOgreButtonToCegui(id)); return true; } bool keyPressed( const OIS::KeyEvent &e ) { if(e.key == OIS::KC_ESCAPE) { mShutdownRequested = true; return true; } CEGUI::System::getSingleton().injectKeyDown(e.key); CEGUI::System::getSingleton().injectChar(e.text); return true; } bool keyReleased( const OIS::KeyEvent &e ) { CEGUI::System::getSingleton().injectKeyUp(e.key); return true; } };

Add to the top of file just after includes, before GuiFrameListener declaration

Copy to clipboard
CEGUI::MouseButton convertOgreButtonToCegui(int buttonID) { switch (buttonID) { case MouseEvent::BUTTON0_MASK: return CEGUI::LeftButton; case MouseEvent::BUTTON1_MASK: return CEGUI::RightButton; case MouseEvent::BUTTON2_MASK: return CEGUI::MiddleButton; case MouseEvent::BUTTON3_MASK: return CEGUI::X1Button; default: return CEGUI::LeftButton; } }

Ogre 1.4.0

Copy to clipboard
CEGUI::MouseButton convertOgreButtonToCegui(int buttonID) { using namespace OIS; switch (buttonID) { case OIS::MB_Left: return CEGUI::LeftButton; case OIS::MB_Right: return CEGUI::RightButton; case OIS::MB_Middle: return CEGUI::MiddleButton; // Not sure what to do with this one... // case MouseEvent::BUTTON3_MASK: // return CEGUI::X1Button; default: return CEGUI::LeftButton; } }

Now add this line to the end of your create scene method

Copy to clipboard
setupEventHandlers();

This should compile and run with a quit button in the middle of the window.

Loading a Layout

CEGUI uses '.xml' format to load layouts into the Gui Sheet.
Copy the following xml code into a text editor and save as 'Tutorial Gui.xml' in the '\media\gui' folder.

Copy to clipboard
<?xml version="1.0" ?> <GUILayout> <Window Type="DefaultWindow" Name="Tutorial Gui"> <Window Type="TaharezLook/Button" Name="Quit"> <Property Name="AbsoluteRect" Value="l:224.000000 t:216.000000 r:416.000000 b:264.000000" /> <Property Name="RelativeRect" Value="l:0.350000 t:0.450000 r:0.650000 b:0.550000" /> <Property Name="Text" Value="Quit" /> </Window> </Window> </GUILayout>

Ogre 1.4.0

Updated for CEGUI >= 0.4.0

Copy to clipboard
<?xml version="1.0" ?> <GUILayout> <Window Type="DefaultWindow" Name="Tutorial Gui"> <Window Type="TaharezLook/Button" Name="Quit"> <Property Name="UnifiedPosition" Value="{{0.35,0},{0.45,0}}" /> <Property Name="UnifiedSize" Value="{{0.3,0},{0.1,0}}" /> <Property Name="Text" Value="Quit" /> </Window> </Window> </GUILayout>

Now replace

Copy to clipboard
mEditorGuiSheet= CEGUI::WindowManager::getSingleton().createWindow((CEGUI::utf8*)"DefaultWindow", (CEGUI::utf8*)"Sheet"); mGUISystem->setGUISheet(mEditorGuiSheet); CEGUI::PushButton* quitButton = (CEGUI::PushButton*)CEGUI::WindowManager::getSingleton().createWindow("TaharezLook/Button", (CEGUI::utf8*)"Quit"); mEditorGuiSheet->addChildWindow(quitButton); quitButton->setPosition(CEGUI::Point(0.35f, 0.45f)); quitButton->setSize(CEGUI::Size(0.3f, 0.1f)); quitButton->setText("Quit");

With

Copy to clipboard
mEditorGuiSheet = CEGUI::WindowManager::getSingleton().loadWindowLayout((CEGUI::utf8*)"Tutorial Gui.xml"); mGUISystem->setGUISheet(mEditorGuiSheet); CEGUI::PushButton* quitButton = (CEGUI::PushButton*)CEGUI::WindowManager::getSingleton().getWindow((CEGUI::utf8*)"Quit");

The last line is redundant as we do not use the pointer after this but it shows how to access something loaded in through a file.
Note that we have to cast to the type of window we want.

This will now compile and run, with no changes in the end program.

Things to Try

  • Ray-casting and picking the Ogre mesh — when the mouse is not over a GUI element.
    • Subscribe a mouse click to the root menu of the GUI. When a gui element gets selected, it will pick up the mouse clickand not the root window. If the mouse is not over a gui elementie when the cursor is in our 3d rendered scene--then the root window will pick up the mouse click.
    • Transform the mouse click to world coordinates and raycast (Camera::getCameraToViewportRay(mouseX, mouseY) ala

Copy to clipboard
// Start a new ray query Ogre::Ray cameraRay = root::getSingleton( ). getCamera( )->getCameraToViewportRay( mouseX, mouseY ); Ogre::RaySceneQuery *raySceneQuery = root::getSingleton( ). getSceneManager( )->createRayQuery( cameraRay ); raySceneQuery->execute( ); Ogre::RaySceneQueryResult result = raySceneQuery->getLastResults( ); Ogre::MovableObject *closestObject = NULL; real closestDistance = LONG_MAX; std::list< Ogre::RaySceneQueryResultEntry >::iterator rayIterator; for ( rayIterator = result.begin( ); rayIterator != result.end( ); rayIterator++ ) { if ( ( *rayIterator ).movable->getUserObject( ) != NULL ) { if ( ( *rayIterator ).distance < closestDistance ) { closestObject = ( *rayIterator ).movable; closestDistance = ( *rayIterator ).distance; } } } // No object clicked if ( closestObject == NULL ) { clickedObject = NULL; ---- clickedObject is a class scoped variable } else { clickedObject = static_cast< object* >( closestObject->getUserObject( ) ); } raySceneQuery->clearResults( ); root::getSingleton( ).getSceneManager( )->destroyQuery( raySceneQuery );

Credit: NSXEagle CEGUI forums & bad_camel Ogre forums

How to switch between 2 GUI (edit by alphamax)

For example: if you have a login screen and, after login success, you have your main GUI. You may want to switch between the two.

  • First step, load your login gui, :

Copy to clipboard
//First loading with this mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY, false, 3000,mSceneMgr); mGUISystem = new CEGUI::System(mGUIRenderer); CEGUI::Logger::getSingleton().setLoggingLevel(CEGUI::Informative); CEGUI::SchemeManager::getSingleton().loadScheme((CEGUI::utf8*)"WindowsLook.scheme"); mGUISystem->setDefaultMouseCursor((CEGUI::utf8*)"WindowsLook", (CEGUI::utf8*)"MouseArrow"); CEGUI::Font *f = CEGUI::FontManager::getSingleton().createFont("Commonwealth-10.font"); mGUISystem->setDefaultFont(f); //End "first loading with this" //Load a XML file mEditorGuiSheet = CEGUI::WindowManager::getSingleton().loadWindowLayout((CEGUI::utf8*)"Presentation.xml"); mGUISystem->setGUISheet(mEditorGuiSheet);
  • Step Two, if you want to destroy to recreate a GUI, you have to do :



Copy to clipboard
if(mEditorGuiSheet) CEGUI::WindowManager::getSingleton().destroyWindow(mEditorGuiSheet);
  • Last step, load an other GUI with



Copy to clipboard
mEditorGuiSheet = CEGUI::WindowManager::getSingleton().loadWindowLayout((CEGUI::utf8*)"Futura.xml"); mGUISystem->setGUISheet(mEditorGuiSheet);

Redo "Step two" and "Last step" for loading others GUI

Conclusions

This tutorial can show you a "preview" of CEGUI under OGRE3D, and how CEGUI is generally used, so you can get the feel of it.

(FINISH ME!)

What do you think?

This tutorial was designed to help out anyone who is completely new to Ogre get started with CEGUI. If you find something that is not clear, needs more explanation, or if you want to leave a comment about the tutorial, please post in this thread on the Ogre forums.

Thanks!
Raven