Newbie Tutorial 2         First Steps
note This tutorial is a disorganised (and out of date) mess - go back. wink

Ogre Newbie's Tutorial 2

First Steps

This tutorial follows on from Newbie Tutorial 1, in which you were shown how to build Ogre from source code pulled by CVS.

In this tutorial, you will run your first Ogre program. As you might guess, this program is very simple and teaches you the very basics of what you'll need to do in each Ogre program. I recommend that you go over this tutorial until you understand everything in it.

I will teach you about Ogre's core objects. I will not teach you how to show things on the screen just yet, because I believe that going that far in this tutorial would compromise the amount of space I could devote to ensuring that you first understand the essentials.

Let's get started!

Ok. So, now that Ogre has built completely, we can make our own program. Unlike all of the other demos and tutorials out there, this one will teach you how to make an application without using the ExampleApplication framework. I believe the pre-made framework doesn't give the user a good idea of what they need to do in order to get Ogre running.

Part 1: Project Setup


The first thing you need to do is start a new project. I created a project in a subfolder (Tutorial_2) of the C:\Ogre_Tutorials folder that we have ogrenew in.

Create that folder, and then open Visual C++ .NET. Click "File->New->Blank Solution". Now enter the solution's name - Ogre_Tutorial. In the Location Box, press Browse and then navigate to the C:\Ogre_Tutorials\Tutorial_2\ folder. Press OK. If you look at the Solution Explorer, "Solution ‘Ogre_Tutorial’ (0 projects)" should now be present.

Now we need to create our project. Right click on the "Solution ‘Ogre_Tutorial’ (0 projects)" text and select "Add->New Project". A box should pop up. In the 'Project Types' box select 'Visual C++ Projects' / 'Win32'. Select 'Win32 Project' in the right-hand pane. In the Name box, type Ogre_Tutorial. In the Location box, browse again to the C:\Ogre_Tutorials\Tutorial_2 folder. Click OK. Another box should show up, with two links on the upper left side. Click the bottom link, "Application Settings". Leave the Application Type on 'Windows Application', and check the 'Empty Project' checkbox below.

Add an empty C++ file to the project called main.cpp . This file must exist before editing project properties in order for the 'C/C++' menu to appear!

Now that the project is created, we have a lot of settings to define. Click "Project->Properties" in the top toolbar. Now you need to configure some settings. The paths specified in these settings are appropriate to the configuration established in this and the previous tutorial (Newbie Tutorial 1).

Section  Subsection            Setting Name                     Value
 
 C/C++  / General             / Additional Include Directories = "C:/Ogre_Tutorials/ogrenew/OgreMain/include"
 C/C++  / Code Generation     / Runtime Library                = Multithreaded Debug DLL
 C/C++  / Precompiled Headers / Create/Use Precompiled Header  = Not Using Precompiled Headers
 Linker / General             / Additional Library Directories = "C:/Ogre_Tutorials/ogrenew/OgreMain/lib/Debug"
 Linker / Input               / Additional Dependencies        = OgreMain_d.lib

If you subsequently wish to compile your code in Release Mode instead of Debug: change the 'Configuration' listbox at the top of the Properties Pages to 'Release'; input the above settings again in the Properties Pages, except for: in C/C++'s 'Code Generation' section, for 'Runtime Library' change 'Multithreaded Debug DLL' to 'Multithreaded DLL'; in Linker's 'Input' section, change OgreMain_d.lib to OgreMain.lib; change Linker's 'Additional Library Directories' filepath to end in 'Release' instead of 'Debug'.

Part 2: Adding Code

Ok, now that our settings are done, it's time to add some source code. Enter this code into the source file:

#include <iostream>
 #include <string>
 #include "Ogre.h"
 
 #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
 {
      Ogre::Root* root = new Ogre::Root();
 
      if (!root->showConfigDialog())
            return -1;
 
      Ogre::ConfigFile cf;
      cf.load("resources.cfg");
 
      // Go through all sections & settings in the file
      Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
 
      Ogre::String secName, typeName, archName;
      while (seci.hasMoreElements())
      {
          secName = seci.peekNextKey();
          Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
          Ogre::ConfigFile::SettingsMultiMap::iterator i;
          for (i = settings->begin(); i != settings->end(); ++i)
          {
              typeName = i->first;
              archName = i->second;
              Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
                  archName, typeName, secName);
          }
      }
      
      Ogre::RenderWindow* window = root->initialise(true);
      Ogre::SceneManager* smgr = root->createSceneManager(Ogre::ST_GENERIC);
      Ogre::InputReader* inputDevice = Ogre::PlatformManager::getSingleton().createInputReader();
 
      inputDevice->initialise(window);
 
      while (1)
      {
            Ogre::PlatformManager::getSingleton().messagePump(window);
 
            if(root->renderOneFrame() == false)
                  break;
 
            inputDevice->capture();
 
            if (inputDevice->isKeyDown(Ogre::KC_ESCAPE))
                  break;
      }
  
      delete root;
      return 0;
 }

[ NOTE: To aviod a memory leak we have to destroy the InputReader. This can be done by putting the line
"PlatformManager::getSingleton().destroyInputReader(inputDevice);"
just before the line "delete root;" Then it runs with no mem leaks. --Klim 11:22, 4 July 2006 (CDT)]

NOTE: The previous advice was almost correct. You need to put the line in as: %22Ogre::PlatformManager::getSingleton().destroyInputReader(inputDevice);%22
or it won't build!

Once you have entered the code, try to compile and run it. If you set all the properties correctly, it should compile, and when you run it, you should get an error message saying that "OgreMain_d.dll was not found". This is fine, because we haven’t copied the DLL files required for the engine into the application's directory. Navigate to C:\Ogre_Tutorials\ogrenew\Samples\Common\bin\Debug . Copy ALL of the DLL files from that folder into C:\Ogre_Tutorials\Tutorial_2\Ogre_Tutorial\Debug .

Now, try to run the program. The Ogre configuration screen should pop up, but you won't be able to select anything. This is because OGRE can't find the plugins. We need to create the plugins.cfg and resources.cfg files now.

Create a new text document, name it plugins.cfg, and enter the following text into it:

# Defines plugins to load
 
 # Define plugin folder
 PluginFolder=.
 
 # Define plugins
 Plugin=RenderSystem_Direct3D7
 Plugin=RenderSystem_Direct3D9
 Plugin=RenderSystem_GL
 Plugin=Plugin_ParticleFX
 Plugin=Plugin_BSPSceneManager
 Plugin=Plugin_OctreeSceneManager
 Plugin=Plugin_CgProgramManager

This text tells Ogre where to find our plugins and which ones to load.

NOTE: You may want to delete the line %22Plugin=RenderSystem_Direct3D7%22 if you don't have Direct3D7 installed on your system, or it will cause a crash.

Next, create a text document named resources.cfg and save it blank.

Now try running the program. You should get the Ogre configuration box, and you should be able to input options into it. Choose whatever options you would like, then press OK. A black screen should appear. Hit Escape to exit it. Congratulations, you have made your first Ogre program!

Part 3: Explanation

The code in this tutorial is surprisingly easy to understand. Let's go through the program line by line.

#include "Ogre.h"

This line includes all of the Ogre headers needed to run the program. This is needed at the top of every file you want to use Ogre in.

#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

This section checks whether Ogre is to run on Windows, and, if it is, WIN32_LEAN_AND_MEAN specifies that it should exclude APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets, the windows.h header is included, and then INT WINAPI WinMain provides the standard function name for the 'main' function. If it is not, the alternative 'int main' is provided.

Ogre::Root* root = new Ogre::Root();
 
 if (!root->showConfigDialog())
            return -1;

Create a root object. The root object is the Ogre object that acts as a "monarch" element. It controls and initializes most things in the engine indirectly. Every program needs a root object, because it initializes all of the subsystems of the program and allows access to most other things.

1. First, you create an Ogre::Root*, and set it equal to a new Ogre::Root() .

2. You show the configuration dialog, this allows the user to set configuration options such as screen size, fullscreen, and render system.

Ogre::ConfigFile cf;
 cf.load("resources.cfg");
 
 // Go through all sections & settings in the file
 Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
 
 Ogre::String secName, typeName, archName;
 while (seci.hasMoreElements())
 {
     secName = seci.peekNextKey();
     Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
     Ogre::ConfigFile::SettingsMultiMap::iterator i;
     for (i = settings->begin(); i != settings->end(); ++i)
     {
         typeName = i->first;
         archName = i->second;
         Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
             archName, typeName, secName);
     }
 }

Here, we establish that resources are located in the file paths read from the config file. These paths are declared in statements such as:

FileSystem=../folder
 Zip=zipfile.zip

'FileSystem' means a folder on the harddrive. For example, if your .exe file was in a folder "bin" and there was a folder "data" in that folder, you would add to your config file "FileSystem=../data". Remember, ./ is the directory of your exe, ../ is one directory under.

'Zip' means the location is a zip file. It can have any extension, but it must be compressed using zip compression techniques.

Our config file in this case will be called resources.cfg .

Ogre::RenderWindow* window = root->initialise(true);

Now, we create a render window by initializing the root system. This is a simple step, and doesn't require much attention. This must be called before initializing most of the other subsystems.

Ogre::SceneManager* smgr = root->getSceneManager(Ogre::ST_GENERIC);

(Please Note: if you are receiving this error when building "main.cpp(36): error C2664: 'Ogre::Root::getSceneManager' : cannot convert parameter 1 from 'Ogre::SceneType' to 'const Ogre::String &'" Change getSceneManager to createSceneManager. This was changed in OGRE 1.2. See this forum thread: http://www.ogre3d.org/phpBB2/viewtopic.php?t=19157&highlight=root+getscenemanager)--Drwho 21:42, 12 April 2006 (CDT)

Next up is creating the scene manager. The choice of scene managers is an important step, and for the first few tutorials, we will just use the Generic scene manager. Later on, we will switch to the terrain scene manager for the final tech demo, so that we can get some pretty mountains into the engine. Below is a brief description of each of the useful scene managers.

Ogre::ST_EXTERIOR_CLOSE:  the Terrain Scene Manager
               Ogre::ST_EXTERIOR_FAR:    the Nature Scene Manager
               Ogre::ST_INTERIOR:        the Quake3 BSP Scene Manager
               Ogre::ST_GENERIC:         the Generic in engine scene manager

 Ogre::InputReader* inputDevice = Ogre::PlatformManager::getSingleton().createInputReader();
 
 inputDevice->initialise(window);

In order to simplify the later tutorials, we'll also set up the event system frameworks in this tutorial. Basically, we need to create an InputReader which will allow us to get the state of the computer's hardware. Then, in the main loop, we can poll the input reader to account for key input.

Now that OGRE is set up, all that is left is the render loop :-D

Ogre::PlatformManager::getSingleton().messagePump(renderwindow);

This statement is necessary for Ogre to handle any messages being sent to the window about procedures like closing, maximising and so on.

if(Root->renderOneFrame() == false)
       break;

Render a frame to the screen, and if it fails to render (which means an element of it has told it to stop rendering) quit the loop.

inputDevice->capture();

Capture any input from the input device so that we can handle events.

if (inputDevice->isKeyDown(Ogre::KC_ESCAPE))
            break;
 }

To show how to handle some simple key events, we'll catch the ESCAPE key if it is down, and if so, we'll leave the loop.

If we've left the loop for any reason, then finally

return 0;

exits the program.


Part 4: Conclusion

I hope that this tutorial has helped you get a grip on Ogre's design and core objects. Make sure you understand this code for the next lesson, in which you will display a mesh onscreen and add some movement. See you all next time!