Mogre Basic Tutorial 5

From Ogre Wiki

Jump to: navigation, search

Basic Tutorial 5: The Ogre startup sequence

Original version by Clay Culver

Any problems you encounter while working with this tutorial should be posted to the Mogre Forums.

Contents

Prerequisites

This tutorial assumes you have knowledge of C# programming and are able to setup and compile an Mogre application (if you have trouble setting up your application, see Mogre Basic Tutorial 0 for a detailed setup walkthrough).

Introduction

In this tutorial I will be walking you through how to setup ogre in your own environment. Ogre has a very specific order in which you need to understand before you can write your own Ogre application from scratch. At the end of this tutorial you know how to set up Ogre in a way which no longer requries the MogreFramework to get started.

As you go through the tutorial you should be slowly adding code to your own project and watching the results as we build it.

Getting Started

As with the last tutorial, we will be using a pre-constructed code base as our starting point. Create a new Mogre project and replace the code in program.cs with the following code:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Mogre;
using System.Drawing;

namespace Tutorial05
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            OgreStartup ogre = new OgreStartup();
            ogre.Go();
        }
    }

    class OgreStartup
    {
        Root mRoot = null;
        float ticks = 0;

        public void Go()
        {
            CreateRoot();
            DefineResources();
            SetupRenderSystem();
            CreateRenderWindow();
            InitializeResourceGroups();
            CreateScene();
            StartRenderLoop();
        }

        void CreateRoot()
        {
        }

        void DefineResources()
        {
        }

        void SetupRenderSystem()
        {
        }

        void CreateRenderWindow()
        {
        }

        void InitializeResourceGroups()
        {
        }

        private void CreateScene()
        {
        }

        void StartRenderLoop()
        {
        }
    }
}

Make sure you can compile and run the application before continuing. If you are having difficulty, refer to the project setup guide or post to the forums. Note that this program should do nothing until we add code to it. Additionally, the program won't work until we reach the very end of this tutorial, so unlike previous tutorials you will not be running the program as you go along.

Creating the Root Object

The first thing that any Ogre application needs to do is to create the Root object. Find the CreateRoot function in the OgreStartup class and add the following line of code:

           mRoot = new Root();

That's it. Note that the Root's constructor takes in three parameters. The first is the name of the plugin file, the second is the config file name, and the last is the log file name. We have left these as their default value.

Defining the Resources

The next thing we need to do is to parse the resource config file and load resources into Ogre. Adding a resource location to ogre is done through a call to a single function:

    ResourceGroupManager.Singleton.AddResourceLocation(location, type, group);

The first parameter of this function is the location of the resource on disk (file/directory name). The second parameter is the type of resource which is generally either "FileSystem" (for a directory) or "Zip" (for a zip file). The last paramter is the resource group to add the resource to.

Ogre provides a convenient way of dealing with resources. There is a config file parser class which allows you to place all of your resources into one file. Find the DefineResources function and add this code to it:

           ConfigFile cf = new ConfigFile();
           cf.Load("resources.cfg", "\t:=", true);
           ConfigFile.SectionIterator seci = cf.GetSectionIterator();
           String secName, typeName, archName;

           while (seci.MoveNext())
           {
               secName = seci.CurrentKey;
               ConfigFile.SettingsMultiMap settings = seci.Current;
               foreach (KeyValuePair<string, string> pair in settings)
               {
                   typeName = pair.Key;
                   archName = pair.Value;
                   ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
               }
           }

This is the standard way of parsing the resources.cfg file to populate the ResourceGroupManager. Note that the AddResourceLocation function only tells Ogre where resources are located and what resource groups they are in. This does not parse the scripts and load resources. We will be loading these resources shortly.

Setting up the RenderSystem

Ogre offers a configuration dialog to set the graphics settings for your application. Find the SetupRenderSystem method and add the following code to it:

           if (!mRoot.ShowConfigDialog())
               throw new Exception("The user canceled the configuration dialog.");

Alternatively you can manually setup the RenderSystem this way (don't add this code to your project):

           RenderSystem rs = mRoot.GetRenderSystemByName("Direct3D9 Rendering Subsystem");
                                               // or use "OpenGL Rendering Subsystem"
           mRoot.RenderSystem = rs;
           rs.SetConfigOption("Full Screen", "No");
           rs.SetConfigOption("Video Mode", "800 x 600 @ 32-bit colour");

Creating the Render Window

Ogre can create the window in which we are rendering for us, or we can do it manually. Find the CreateRenderWindow function and add the following code:

           mRoot.Initialise(true, "Main Ogre Window");

The Initialise function is actually a misnomer. This function creates a window to render Ogre in with the second parameter setting the window text. If we are trying to embed Ogre into a window which has already been created, we need to use the windows handle which contains it. Assuming the handle was stored in the variable "handle", this would be how you create the RenderWindow (do not add this code to the project):

           NameValuePairList misc = new NameValuePairList();
           misc["externalWindowHandle"] = handle.ToString();
           RenderWindow win = mRoot.CreateRenderWindow("Main RenderWindow", 800, 600, false, misc);

Initializing Resource Groups

Before we can create the scene and place objects into it, we must first intialize the resources groups which contain our textures, materials, and models. In the LoadResources function, we told Ogre where all of the resources for the program are. Now we need to actually parse those scripts and resources. Failing to call IntializeAllResourceGroups (or InitializeResourceGroup) will result in your program not being able to find the meshes, textures, etc which your program uses.

Before we intialize the resourses we will set the default number of mipmaps which Ogre uses for the textures it loads. Find the InitializeResourceGroups function and add the following code:

           TextureManager.Singleton.DefaultNumMipmaps = 5;
           ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

You can individually initialize each resource group in your application only when it's needed to save startup time and a little memory (use the InitializeResourceGroup function to do this). However, this is not the common approach in most Ogre applications. Note that when you initialize a resource group, it parses and loads scripts, but does not actually load the resources (such as models and textures) into memory until the program actually needs to use it.

You can change this behavior by pre-loading resource groups which you know you will be using. You can do this by calling the LoadResourceGroup, UnloadResourceGroup, and UnloadUnreferencedResourcesInGroup methods. By carefully selecting which resource groups to place scripts and models in (and manually loading and unloading resources), it's possible to drastically reduce the amount of memory ogre consumes.

For most commons uses of Ogre calling InitializeAllResourceGroups (and not manually Loading/Unloading resource groups) should be sufficient. If your program is using too much memory or if you are working with a very large scale application/game which uses a very large set of meshes, textures, scripts, and so on, you may want to actually plan out a strategy to deal with your resource allocation.

Creating the Scene

After the RenderWindow is created, we then need to create the SceneManagers, Viewports, and Cameras which the scene uses. We will create a simple scene to view for this tutorial. Add the following code to the CreateScene function:

           SceneManager mgr = mRoot.CreateSceneManager(SceneType.ST_GENERIC);
           Camera cam = mgr.CreateCamera("Camera");
           mRoot.AutoCreatedWindow.AddViewport(cam);

           Entity ent = mgr.CreateEntity("ninja", "ninja.mesh");
           mgr.RootSceneNode.CreateChildSceneNode().AttachObject(ent);

           cam.Position = new Vector3(0, 200, -400);
           cam.LookAt(ent.BoundingBox.Center);

This program will render the scene and then terminate itself after 5 seconds has elapsed. I am doing this so that we can avoid trying to handle user input at this time. Unfortunently there is not an easy way to obtain user input in this application without needlessly complicating it, so terminating the program after 5 seconds is the easiest way to solve this problem. In an actual application you should probably use SDL, DirectInput, or some other input system to get user input.

To do this we will need to register a frame listener and keep track of when the application started. Add the following to the end of the CreateScene function:

           mRoot.FrameEnded += new FrameListener.FrameEndedHandler(FrameEnded);
           ticks = Environment.TickCount;

Finally, we need to add code to the FrameEnded method to terminate the program after the elapsed time (remember that returning false from a frame listener terminates the program):

       bool FrameEnded(FrameEvent evt)
       {
           if (Environment.TickCount - ticks > 5000)
               return false;

           return true;
       }

The Render Loop

In games (and other applications), it is very common to have Ogre render as fast as the computer can handle (creating the highest FPS possible). Ogre provides a function which will do just that: Root's StartRendering method. This will keep rendering the scene until a frame listener returns false. Find the StartRenderingLoop method and add the following code:

           mRoot.StartRendering();

That's it. You may now run the program and see the results.

We can also have Ogre render a single frame by calling the RenderOneFrame method. This will return false when a single frame listener has returned false. A common approach to this would be something like this (do not add this code to your project):

           while (mRoot.RenderOneFrame())
           {
               // Do other things here, such as sleep for a short period of time
           }

This allows you to perform other incremental actions, such as sleeping for a short time to lower the frames per second to a maximum amount (like 60fps).

Conclusion

In this tutorial we have gone over the basics of getting Ogre started as a stand-alone application (without Windows.Forms). By this point you should be able to write your own Mogre application which no longer uses the MogreFramework. In the next turorial I will show you how to embed Mogre into a Windows.Forms application.

This tutorial lacked one major component which you will need to start writing your own games: input. Ogre itself once contained a rudimentary input system which could be used for basic keyboard and mouse input, but was removed in favor of OIS (Open Input System). For Mogre you use the wrapped library MOIS.

Source Code

You can see the final state of this tutorial here: Mogre Basic Tutorial 5 Source

Proceed to Basic Tutorial 6 Embedding Mogre in Windows.Forms
Personal tools
administration