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!

<HR>
Creative Commons Copyright -- Some rights reserved.


THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  • "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
  • "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
  • "Licensor" means the individual or entity that offers the Work under the terms of this License.
  • "Original Author" means the individual or entity who created the Work.
  • "Work" means the copyrightable work of authorship offered under the terms of this License.
  • "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  • "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.

2. Fair Use Rights

Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.

3. License Grant

Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  • to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
  • to create and reproduce Derivative Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
  • For the avoidance of doubt, where the work is a musical composition:
    • Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
    • Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
    • Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).


The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.

4. Restrictions

The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  • You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested.
  • You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License.
  • If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability.

EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination

  • This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  • Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  • Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  • Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  • If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  • No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
  • This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.