Intermediate Tutorial 4: Using multiple SceneManagers
Original version by Clay Culver
OrgeDotNet C# port/conversion by DigitalCyborg.
Note: This was written for Ogre 1.2, and is known to compile against it. Any problems you encounter while working with this tutorial should be posted to the OgreDotNet Forum.
Table of contents
Introduction
In this tutorial we will be covering how to use multiple SceneManagers in an Ogre application. Mr Turner has written a quick snippet of the the essential code to make this work. If you are not interested in a full walkthrough, you should start there instead and you should think about converting his snippet to C# and putting it up in the code snippets section of the ODN wiki..
The full code for this tutorial is included at the bottom if you get lost, but try to follow along without looking! As you go through the tutorial you should be slowly adding code to your own project and watching the results as we build it.
Prerequisites
We will be using the Dictionary class (.NET framework 2.0 System.Collections.Generic) in this tutorial. If you are not familiar with this you should brush up on it before you begin this tutorial. We will also use the conditional operator ? : in several places, so if you are not familiar with it you should brush up on that too.
Getting Started
Create a file called SMTutorial.cs and add the following code to it:
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using Math3D; using OgreDotNet; namespace OgreDotNetTutorial { class IntermediateTutorial4 : ExampleApplication { protected MultiSceneManager mMSM; // The multiScene Manager ushort mSceneType; // The current SceneManager type float mTimeUntilNextToggle; ushort tsmType; // Terrain SceneManager type ushort gsmType; // Generic SceneManager type public IntermediateTutorial4() { mMSM = new MultiSceneManager(); gsmType = (ushort) SceneType.Generic; tsmType = (ushort) SceneType.ExteriorClose; mSceneType = gsmType; mTimeUntilNextToggle = 1.0f; } ~IntermediateTutorial4() { } protected override void CreateSceneManager() { } protected override bool FrameStarted(FrameEvent e) { if(! base.FrameStarted(e)) return false; return true; } protected override void CreateScene() { } protected override void CreateCamera() { } protected override void CreateViewPort() { } protected override void KeyClicked(KeyEvent e) { base.KeyClicked(e); } static void Main(string[] args) { using (IntermediateTutorial4 app = new IntermediateTutorial4()) { app.Start(); } } } }
Next create another file called SceneManagerState.cs and add the following code to it:
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using Math3D; using OgreDotNet; namespace OgreDotNetTutorial { // SceneManagerState class SceneManagerState { protected Vector3 mCamPosition; protected Quaternion mCamOrientation; // The camera orientation protected SceneManager mSceneManager; // The SceneManager this object wraps protected RenderWindow mRenderWindow; // The RenderWindow the application uses public SceneManagerState(SceneManager sceneManager, RenderWindow renderWindow) { mSceneManager = sceneManager; mRenderWindow = renderWindow; } ~SceneManagerState() { } // Called when this SceneManager is being displayed public void showScene() { } // called when this SceneManager is no longer being displayed public void hideScene() { } // returns the SceneManager public SceneManager getSceneManager() { return mSceneManager; } } }
Finally create one more file MultiSceneManager.cs with this code:
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using Math3D; using OgreDotNet; namespace OgreDotNetTutorial { // MultiSceneManager class MultiSceneManager { protected Dictionary<ushort, SceneManagerState> mStateMap; // The map of registered states protected SceneManagerState mCurrentSMState; // the current state protected Root mRoot; // the Root object protected RenderWindow mRenderWindow; // the RenderWindow public MultiSceneManager() { mCurrentSMState = null; mRoot = null; mRenderWindow = null; mStateMap = new Dictionary<ushort, SceneManagerState>(); } ~MultiSceneManager( ) { } // sets the Root object public void setRoot( Root root ) { mRoot = root; } // sets the RenderWindow public void setRenderWindow( RenderWindow renderWindow ) { mRenderWindow = renderWindow; } // registers a scene manager class for usage, you cannot call // setSceneManager on any type without first calling registerSceneManager public void registerSceneManager( ushort st ) { } // makes st the current SceneManager public void setSceneManager( ushort st ) { } // returns the SceneManager that's currently rendering public SceneManager getCurrentSceneManager( ) { return null; } // returns the SceneManager associated with type st (must already be registered) public SceneManager getSceneManager( ushort st ) { return null; } // finds and returns the SceneManagerState associated with st protected SceneManagerState findState( ushort st ) { return null; } } }
Note: This code should compile at this point, but don't run it yet.
Before we Begin
In this tutorial we will be using multiple SceneManagers in a single OgreDotNet application. Generally speaking this really only involves three steps.
First, destroy all Viewports and Cameras associated with the current SceneManager.
Second, get the SceneManager you want to use next and register it using Root._setCurrentSceneManager.
Finally, recreate your cameras and viewports. This is a fairly straightforward process. In this tutorial we will be building a very simplistic MultiSceneManager class which allows us to swap back and forth between several different SceneManagers. In the next tutorial we will be extending this simplistic manager class into a more powerful version able to handle multiple contexts of the same SceneManager type.
'''Note: At the time of writing this tutorial _setCurrentSceneManager is not available in OgreDotNet without making a small change to OgreRoot.i, reswigging and recompiling''' thankfully, this is a relatively painless process. just open OgreRoot.i & remove the line which says %ignore _setCurrentSceneManager, reswig and then recompile. I've asked Rastaman to make this change in the CVS source or to update this tutorial with a better (or the proper) way to do what that function does.
One thing you will notice in this tutorial is that the Example Framework gets in our way a LOT. The Example Framework was written with the idea that the mCamera variable would be permanent after you create it, which is simply not the case when we are swapping SceneManagers. I have opted to keep the Example Framework for the Tutorial so that you do not have to learn a new framework as you learn other concepts. However, if you are actually going to do something like this in a program, you need to stop using the Example Framework and write your own Application class that's tailored to your needs instead.
The SceneManagerState class
We've defined two classes to handle swapping SceneManagers - SceneManagerState and MultiSceneManager The MultiSceneManager class will be the public interface for swapping SceneManagers, and the SceneManagerState will keep track of SceneManager variables which get destroyed when we swap SceneManagers.
The SceneManagerState class contains basic information about the Camera, because when we destroy the camera, we lose position and orientation that has been set. The showScene method is called whenever the SceneManager wrapped by this class is about to be shown. The hideScene method is called whenever we are going to unload this SceneManager and display another one.
The showScene method needs to create the Camera for use, set the aspect ratio, and restore the Camera's position and orientation. Add this code to the showScene method:
// create the camera and viewport Camera cam = mSceneManager.CreateCamera("SceneCamera"); Viewport vp = mRenderWindow.AddViewport(cam); vp.SetBackgroundColour(Color.Black); // Set the aspect ratio cam.SetAspectRatio((float)vp.GetWidth() / (float)vp.GetHeight());//p.GetActualWidth() / (float)vp.GetHeight()); cam.SetNearClipDistance(5.0f); // Set the camera's position and orientation cam.SetPosition(mCamPosition); cam.SetOrientation(mCamOrientation);
The hideScene method needs to save the Camera's position and orientation, then destroy all viewports and cameras. This is done in a very straight forward manner in the hideScene method:
int numViewports; // save camera position and orientation Camera cam = mSceneManager.GetCamera("SceneCamera"); mCamPosition = cam.GetPosition(); mCamOrientation = cam.GetOrientation(); // destroy the camera and viewport numViewports = mRenderWindow.GetNumViewports(); for (int i = 0; i < numViewports; i++) { mRenderWindow.RemoveViewport(i); } mSceneManager.DestroyAllCameras();
The MultiSceneManager class
The other half of this system is the MultiSceneManager class. In order to use this object, you must first feed it the Root object and the RenderWindow object. After this is done, you will need to register every SceneManager type that you wish to use, such as SceneType.Generic, SceneType.ExteriorClose, etc. After you have set the Root/RenderWindow objects and registered SceneManager types, you can then begin to use the class and set up your SceneManagers.
To configure a SceneManager (such as setting it up for initial display), call the getSceneManager method with the SceneManager type you wish to manipulate. This will return a SceneManager object which you can then manipulate. In order to set the current SceneManager (or swap during runtime), simply call the setSceneManager method with the type of SceneManager you wish to use.
We will start with the registerSceneManager method first. This method needs to create an entry in mStateMap pretaining to the SceneType specified. To do this, we need to create a new SceneManagerState object and have st map to it, like so:
mStateMap[st] = new SceneManagerState(mRoot.CreateSceneManager(st), mRenderWindow);
We will now implement the helper function findState. The findState function searches the map for the specified state, and returns it (or 0 if it's not found).
SceneManagerState retval; // Search map //return the result or null if(mStateMap.TryGetValue(st,out retval)) return retval; else return null;
Now that findState is implemented, we can implement the getSceneManager function easily. The getSceneManager function returns the SceneManager assocated with the SceneType specified, but does NOT set it as the current SceneManager. We will first search for the requested SceneType, then return it (or 0 if the SceneType was not registered):
SceneManagerState sms = findState(st); if (sms != null) return sms.getSceneManager(); else return null;
The last function we have to implement is the setSceneManager method. The basic flow of the method is to first hide the current SceneManager, find the requested SceneManager and start it rendering:
// hide the current SceneManager if (mCurrentSMState != null) mCurrentSMState.hideScene(); // find the next SceneManager mCurrentSMState = findState(st); // set the current SceneManager in the Root class after initializing if (mCurrentSMState != null) { mCurrentSMState.showScene(); mRoot._setCurrentSceneManager(mCurrentSMState.getSceneManager()); }
That wraps up the MultiSceneManager class. Be sure your code compiles before continuing.
The SMTutorialApplication class
The first thing we have to do in the SMTutorialApplication class is stop the ExampleApplication class from trying to create cameras and viewports on its own. To do this, we've overridden the createCamera and createViewports with empty functions in the protected portion of the class:
// We overide this method with an empty class and hide the base method // since all of this functionality is contained in the CreateSceneManager // method now. void createCamera() { } // We overide this method with an empty class and hide the base method // since all of this functionality is contained in the CreateSceneManager // method now. void createViewports() { }
Now we need to set up the MultiSceneManager class. We do this by adding code to the chooseSceneManager method. First we register the information that the MultiSceneManager class needs to operate. We cannot pass these as constructor values, since at the time the mMSM object is constructed the Root and RenderWindow variables are not yet set.
// Set the required information mMSM.setRoot( mRoot ); mMSM.setRenderWindow( mRenderWindow );
Now we need to register the SceneTypes that we will be using in the application. You may register these as you use them instead of all at the beginning if you like. The only restriction is that a SceneType must be registered before you call setSceneManager or getSceneManager with that type.
// Register SceneTypes we will be using: mMSM.registerSceneManager( gsmType ); mMSM.registerSceneManager( tsmType );
Now we need to set the startup SceneManager:
// Set the startup SceneType: mMSM.setSceneManager( gsmType );
Normally this would be all that you need to do during your SceneManager creation method. However, ExampleApplication uses two internal variables mSceneMgr and mCamera, which we should populate if we are using the ExampleFramework. Note however that as soon as we swap states both variables are invalid. If you rewrite the Example framework you should make the classes aware of this and query for the SceneManager/Camera when they are needed. This is the last chunk of code that is needed in the chooseSceneManager method:
// Add variables that ExampleApplication expects mSceneManager = mMSM.getSceneManager( gsmType ); mCamera = mSceneManager.GetCamera("SceneCamera");
Now we are going to setup the scene for each of our SceneManagers. Find the createScene method. We will set the Terrain and sky box for the TerrainSceneManager, and add a Robot to the Generic SceneManager:
// Setup the TerrainSceneManager SceneManager tsm = mMSM.getSceneManager(tsmType); mMSM.setSceneManager(tsmType); mCamera = tsm.GetCamera("SceneCamera"); tsm.SetWorldGeometry("terrain.cfg"); tsm.SetSkyBox(true, "Examples/SpaceSkyBox", 50); mCamera.SetPosition(new Vector3(60, 60, 500)); mCamera.LookAt = new Vector3(0, 0, 0); // Setup the Generic SceneManager Entity ent; SceneNode sn; SceneManager gsm = mMSM.getSceneManager(gsmType); mMSM.setSceneManager(gsmType); mCamera = gsm.GetCamera("SceneCamera"); ent = gsm.CreateEntity("Robot", "robot.mesh"); sn = gsm.GetRootSceneNode().CreateChildSceneNode("RobotNode"); sn.AttachObject(ent); sn.SetPosition(0, 0, -250); mCamera.LookAt = new Vector3(0, 0, -250);
Note that we have used mCamera here. We can do this for the current SceneManager, but due to the limitations of this design, we have to use the setSceneManager function if we want to manipulate the camera for a SceneManager. Compile and run the application. You should now be staring at a Robot, but since we have not added any key bindings for swapping SceneManagers we currently don't have any way to swap SceneManagers.
Binding a key click to swap SceneManagers
The last thing we need to do is add a way to swap SceneManagers. To do this, we will add some code to the KeyClicked method to swap between SceneManagers every time the C key is pressed:
base.KeyClicked(e); switch (e.KeyCode) { case KeyCode.C: if (mTimeUntilNextToggle <= 1.0f) { mSceneType = (mSceneType == gsmType ) ? tsmType : gsmType ; mMSM.setSceneManager(mSceneType); mCamera = mMSM.getSceneManager(mSceneType).GetCamera("SceneCamera"); mTimeUntilNextToggle = 1.0f; } break; }
Note that we have to update mCamera every time we swap the SceneManager due to limitations of the Example framework. Compile and run the application. We are now done! C swaps SceneManagers and the Camera position is saved when we swap SceneManagers.
Complete Code for the tutorial
SceneManagerState.cs
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using Math3D; using OgreDotNet; namespace OgreDotNetTutorial { // SceneManagerState class SceneManagerState { protected Vector3 mCamPosition; protected Quaternion mCamOrientation; // The camera orientation protected SceneManager mSceneManager; // The SceneManager this object wraps protected RenderWindow mRenderWindow; // The RenderWindow the application uses public SceneManagerState(SceneManager sceneManager, RenderWindow renderWindow) { mSceneManager = sceneManager; mRenderWindow = renderWindow; } ~SceneManagerState() { } // Called when this SceneManager is being displayed public void showScene() { // create the camera and viewport Camera cam = mSceneManager.CreateCamera("SceneCamera"); Viewport vp = mRenderWindow.AddViewport(cam); vp.SetBackgroundColour(Color.Black); // Set the aspect ratio cam.SetAspectRatio((float)vp.GetWidth() / (float)vp.GetHeight());//p.GetActualWidth() / (float)vp.GetHeight()); cam.SetNearClipDistance(5.0f); // Set the camera's position and orientation cam.SetPosition(mCamPosition); cam.SetOrientation(mCamOrientation); } // called when this SceneManager is no longer being displayed public void hideScene() { int numViewports; // save camera position and orientation Camera cam = mSceneManager.GetCamera("SceneCamera"); mCamPosition = cam.GetPosition(); mCamOrientation = cam.GetOrientation(); // destroy the camera and viewport numViewports = mRenderWindow.GetNumViewports(); for (int i = 0; i < numViewports; i++) { mRenderWindow.RemoveViewport(i); } mSceneManager.DestroyAllCameras(); } // returns the SceneManager public SceneManager getSceneManager() { return mSceneManager; } } }
MultiSceneManager.cs
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using Math3D; using OgreDotNet; namespace OgreDotNetTutorial { // MultiSceneManager class MultiSceneManager { protected Dictionary<ushort, SceneManagerState> mStateMap; // The map of registered states protected SceneManagerState mCurrentSMState; // the current state protected Root mRoot; // the Root object protected RenderWindow mRenderWindow; // the RenderWindow public MultiSceneManager() { mCurrentSMState = null; mRoot = null; mRenderWindow = null; mStateMap = new Dictionary<ushort, SceneManagerState>(); } ~MultiSceneManager( ) { } // sets the Root object public void setRoot( Root root ) { mRoot = root; } // sets the RenderWindow public void setRenderWindow( RenderWindow renderWindow ) { mRenderWindow = renderWindow; } // registers a scene manager class for usage, you cannot call // setSceneManager on any type without first calling registerSceneManager public void registerSceneManager( ushort st ) { mStateMap[st] = new SceneManagerState(mRoot.CreateSceneManager(st), mRenderWindow); Console.WriteLine("SceneType {0} registered", st); } // makes st the current SceneManager public void setSceneManager( ushort st ) { // hide the current SceneManager if (mCurrentSMState != null) mCurrentSMState.hideScene(); // find the next SceneManager mCurrentSMState = findState(st); // set the current SceneManager in the Root class after initializing if (mCurrentSMState != null) { mCurrentSMState.showScene(); mRoot._setCurrentSceneManager(mCurrentSMState.getSceneManager()); } } // returns the SceneManager that's currently rendering public SceneManager getCurrentSceneManager( ) { if(mCurrentSMState != null) return mCurrentSMState.getSceneManager(); else return null; } // returns the SceneManager associated with type st (must already be registered) public SceneManager getSceneManager( ushort st ) //SceneType st) { SceneManagerState sms = findState(st); if (sms != null) return sms.getSceneManager(); else return null; } // finds and returns the SceneManagerState associated with st protected SceneManagerState findState( ushort st ) { SceneManagerState retval; // Search map //return the result or null if(mStateMap.TryGetValue(st,out retval)) return retval; else return null; } } }
SMTutorial.cs
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using Math3D; using OgreDotNet; namespace OgreDotNetTutorial { class IntermediateTutorial4 : ExampleApplication { protected MultiSceneManager mMSM; // The multiScene Manager ushort mSceneType; // The current SceneManager type float mTimeUntilNextToggle; ushort tsmType; // Terrain SceneManager type ushort gsmType; // Generic SceneManager type public IntermediateTutorial4() { mMSM = new MultiSceneManager(); gsmType = (ushort) SceneType.Generic; tsmType = (ushort) SceneType.ExteriorClose; mSceneType = gsmType; mTimeUntilNextToggle = 1.0f; } ~IntermediateTutorial4() { } protected override void CreateSceneManager() { // Set the required information mMSM.setRoot( mRoot ); mMSM.setRenderWindow( mRenderWindow ); // Register SceneTypes we will be using: mMSM.registerSceneManager( gsmType ); mMSM.registerSceneManager( tsmType ); // Set the startup SceneType: mMSM.setSceneManager( gsmType ); // Add variables that ExampleApplication expects mSceneManager = mMSM.getSceneManager( gsmType ); mCamera = mSceneManager.GetCamera("SceneCamera"); } protected override bool FrameStarted(FrameEvent e) { if(! base.FrameStarted(e)) return false; // decrement the timelimit before scene toggling is allowed mTimeUntilNextToggle -= e.TimeSinceLastFrame; return true; } protected override void CreateScene() { // Setup the TerrainSceneManager SceneManager tsm = mMSM.getSceneManager(tsmType); mMSM.setSceneManager(tsmType); mCamera = tsm.GetCamera("SceneCamera"); tsm.SetWorldGeometry("terrain.cfg"); tsm.SetSkyBox(true, "Examples/SpaceSkyBox", 50); mCamera.SetPosition(new Vector3(60, 60, 500)); mCamera.LookAt = new Vector3(0, 0, 0); // Setup the Generic SceneManager Entity ent; SceneNode sn; SceneManager gsm = mMSM.getSceneManager(gsmType); mMSM.setSceneManager(gsmType); mCamera = gsm.GetCamera("SceneCamera"); ent = gsm.CreateEntity("Robot", "robot.mesh"); sn = gsm.GetRootSceneNode().CreateChildSceneNode("RobotNode"); sn.AttachObject(ent); sn.SetPosition(0, 0, -250); mCamera.LookAt = new Vector3(0, 0, -250); } protected override void CreateCamera() {} protected override void CreateViewPort() {} protected override void KeyClicked(KeyEvent e) { base.KeyClicked(e); switch (e.KeyCode) { case KeyCode.C: if (mTimeUntilNextToggle <= 1.0f) { mSceneType = (mSceneType == gsmType ) ? tsmType : gsmType ; mMSM.setSceneManager(mSceneType); mCamera = mMSM.getSceneManager(mSceneType).GetCamera("SceneCamera"); mTimeUntilNextToggle = 1.0f; } break; } } static void Main(string[] args) { using (IntermediateTutorial4 app = new IntermediateTutorial4()) { app.Start(); } } } }
Exercises
Easy Exercises
- Registering the same SceneType multiple times is unnecessary. Instead of allowing the user to register the same SceneType multiple times, throw an exception class when the user tries to do this.
- Currently if a SceneType is not registered, the MultiSceneManager will just ignore it and return null. Instead, throw an Exception every time the user tries to use a SceneType that's not registered.
- setSceneManager should check whether or not we are already using the requested SceneType and since there is nothing to do in that case, it should just return. update the code.
- There are still some C++ style getVariable and setVariable functions. update the code to use properties since this fits the C# code style
Intermediate Exercises
- Modify the MultiSceneManager class so that instead of throwing an exception for unregistered SceneTypes, it creates a new one whenever it encounters a SceneType that's unregistered. Now that you have implemented both methods, which do you think is better?
- There really should only ever be one MultiSceneManager class. Make the MultiSceneManager class inherit from Ogre.Singleton.
Advanced Exercises
- Modify the code so that you can set a default Camera position and Orientation.
- The way cameras are currently handled there is only one camera ever, and it is retrieved based on the string "SceneCamera". Make this system more robust by adding a method to add multiple Cameras to each SceneManager and to be able to query for them. Don't forget that every Camera that is created will need to be stored when they are destroyed during the hideScene method.
- When a SceneManager is swapped for another SceneManager, some classes will need to be made aware of this. For example, it would be inefficient to query for the current SceneManager and Camera EVERY frame if the SceneManager is changed very rarely. Implement a SceneChangeEvent which is fired every time the SceneManager is changed. Create a SceneChangeListener with an abstract interface for receiving these events. Note that the SceneChangeEvent should probably include the SceneManager which is being hidden and the SceneManager which is being shown. When should this event occur? Before the current SceneManager is hidden? After the new SceneManager is shown? In between the two events?
Exercises for Further Study
- Design and implement a similar set of classes which manipulate "SceneManager contexts" instead of SceneManagers. You may need to have a single SceneManager do multiple things. For example, you may need have the TerrainSceneManager display two seperate sets of Geometry and Entities which you swap back and forth between. This is currently not possible with the methods implemented here.