Intermediate Tutorial 2         Mouse Look, Terrain Collision, and Creating Entities

%tutorialhelp%

Introduction

In this tutorial, we will be learning how to display the CEGUI mouse, and how to use it to select and place entities in our scene. We will cover:

  1. The use of the MouseListener and MouseMotionListener interfaces.
  2. How to use raycasts to keep the camera from passing through the terrain.
  3. Using the mouse to select a specific location on the terrain.

Here is the code you should begin this tutorial with. It should compile and produce a black screen with a single CEGUI label saying, "Intermediate Tutorials". As you read through the tutorial, you should be slowly adding the code to your own project.

The full source for this tutorial is here.

Note: There is also source available that uses the BaseApplication framework and Ogre 1.7 here.

Note: There is also source available that uses the BaseApplication framework, Ogre 1.7, and the SdkTrays overlay system here.

terrain_visual.png

Prerequisites

This tutorial assumes that you already know how to set up an Ogre project and compile it successfully. Knowledge of the topics from previous tutorials is also assumed.

This tutorial requires that you add some terrain into your scene before beginning. Basic Tutorial 3 gives an overview of using the new terrain system. If you have difficulties, the full source for this tutorial has all of the terrain setup done for you. You can simply copy the terrain code into your base files. Although learning how to use the new terrain system is also suggested.

This tutorial also uses CEGUI (Crazy Eddie's GUI). Basic Tutorial 7 covers setup and use of this library with Ogre.

If you have trouble with CEGUI not finding resources, then remember that the Ogre resource manager needs to know where they are. The following code should be in 'resources.cfg':

[Imagesets]
FileSystem=/usr/local/share/cegui-0/imagesets
[Fonts]
FileSystem=/usr/local/share/cegui-0/fonts
[Schemes]
FileSystem=/usr/local/share/cegui-0/schemes
[LookNFeel]
FileSystem=/usr/local/share/cegui-0/looknfeel
[Layouts]
FileSystem=/usr/local/share/cegui-0/layouts

This is the directory structure you will have if you built CEGUI 0.8x from source on linux. If you installed CEGUI through your package manager, or are using an older version, then the directory structure will be different. A package manager will use '/usr/share' instead of '/usr/local/share'. If you're using a prebuilt SDK, then everything should be in there.

The base code for this tutorial is here.

Setting up the Scene

We will now set up a basic scene. This should look familiar from previous tutorials. Add the following to the beginning of createScene:

mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));
mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);
 
mCamera->setPosition(40, 100, 580);
mCamera->pitch(Ogre::Degree(-30));
mCamera->yaw(Ogre::Degree(-45));

Since we're dealing with a large terrain, we should also set the near and far clip distances so we can see the distant terrain.

mCamera->setNearClipDistance(0.1);
mCamera->setFarClipDistance(50000);

After these two calls, we should set up the lighting that we will cast on our terrain. We'll create a directional light to act like a sun.

Ogre::Vector3 lightDir(0.55, 0.3, 0.75);
lightDir.normalise();

Ogre::Light* light = mSceneMgr->createLight("SceneLight");
light->setType(Ogre::Light::LT_DIRECTIONAL);
light->setDirection(lightDir);
light->setDiffuseColour(Ogre::ColourValue(0.4, 0.4, 0.4));
light->setSpecularColour(Ogre::ColourValue(0.2, 0.2, 0.2));

setupTerrain(light);

If you did not create a setupTerrain method, then you can look at the full source for this tutorial to see how it was written. It has all of the stuff from Basic Tutorial 3, except it has been put into a separate method.

Finally, we need to comment out the SdkCameraMan mouse injection and uncomment the CEGUI mouse injection. This is so that we can customize how the camera is controlled. In the mouseMoved method, change the commenting to look like this:

CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
context.injectMouseMove(me.state.X.rel, me.state.Y.rel);

// mCameraMan->injectMouseMove(me);

Do the same thing for mousePressed and mouseReleased. If you're still having trouble with CEGUI, then remember to refer to Basic Tutorial 7.

Compile and run the application. You should see terrain with lighting and a skybox above. You should also be able to move the mouse cursor.

The Event Listeners

We will now introduce the event listeners. In the base source code, you will see that BasicApp inherits from WindowEventListener, FrameListener, MouseListener, and KeyListener. Each of these listeners bring methods that will be called when their related events occur. For instance, the KeyListener provides the keyPressed method that is called whenever a key is pressed. Also, if you look at these methods, you'll notice that we inject the event information into CEGUI as well. This is so that CEGUI can react to events created by Ogre.

This is what we are going to accomplish with the event listeners:

  1. We will set up a "mouse look" mode that is activated when the right mouse button is held down.
  2. We will add basic terrain collision to prevent the camera from passing through the terrain.
  3. We will make it so that clicking on the terrain with the left mouse button creates an entity, and holding down the button allows the user to move the new entity.

First, let's add some variables to our header:

BasicApp.h
float mRotSpd;
bool mLMouseDown, mRMouseDown;
     
Ogre::SceneNode* mCurObject;

The variable mRotSpd will hold the rotation speed of our camera when the right mouse button is held down. mLMouseDown and mRMouseDown will keep track of when a button is held down. mCurObject holds a pointer to the most recently created scene node (we will be using this to drag the entity around).

As always, we should make sure to initialize our variables in the constructor. If you want the camera to rotate faster, then you can adjust the mRotSpd here. Add these to the end of the initializer list:

BasicApp.cpp
mRotSpd(0.1),
mLMouseDown(false),
mRMouseDown(false),
mCurObject(0)

Controlling the Camera

We are going to allow the camera to be controlled by the mouse whenever the right button is held down. We will also hide the cursor when the camera is being controlled.

First, we will hide the cursor when the right mouse button is pressed. Add the following to mousePressed:

if (id == OIS::MB_Left)
{
  mLMouseDown = true;
}
else if (id == OIS::MB_Right)
{
  mRMouseDown = true;
  CEGUI::MouseCursor::getSingleton().hide();
}

Now we need to undo this when the the buttons are released. Add the following to mouseReleased:

if (id == OIS::MB_Left)
{
  mLMouseDown = false;
}
else if (id == OIS::MB_Right)
{
  mRMouseDown = false;
  CEGUI::MouseCursor::getSingleton().show();
}

Now we are going to change the camera's orientation when the mouse is moved while the right button is held. Add the following to mouseMoved:

if (mLMouseDown)
{
}
else if (mRMouseDown)
{
  mCamera->yaw(Ogre::Degree(-me.state.X.rel * mRotSpd));
  mCamera->pitch(Ogre::Degree(-me.state.Y.rel * mRotSpd));
}

We are changing the camera's direction based on the change in the position of the cursor since the last frame. me.state.X.rel is the relative distance along the x-axis the mouse moved since the last frame, and the {MONO}yaw{MONO} method rotates the camera left and right. The negative sign is because moving to the left on the x-axis is the negative direction, but rotating to the left is a positive change in angle. So to match them up we need to flip the sign.

You might be surprised to learn the same is true for the y-axis. This is because Ogre, like many other graphics engines, uses a system where y values increase as you move down the screen, but the pitch increases as the camera rotates upwards. The point (0, 0) is actually the top-left point on the screen. Finally, multiplying by mRotSpd ensures our camera moves with the speed we chose.

Compile and run the application. You should be able to control the camera while holding down the right mouse button. Since we are still injecting the keyboard events into our SdkCameraMan, you can also move around the world with WASD. This is one of the benefits of leaving behind the Tutorial Framework. We don't have to dig around in another class to change how our application handles input.

Collision with the Terrain

We are now going to make sure the camera can't pass through the terrain. Let's add a new method to our class to keep things more organized.

ITutorial.h
void handleCameraCollision();
ITutorial.cpp
void BasicApp::handleCameraCollision()
{
}

The new terrain system handles ray intersection directly. In previous versions of Ogre, we would have needed to set up and tear down an entire ray scene query, but now the terrain group takes care of this for us. Add the following to handleCameraCollision:

Ogre::Vector3 camPos = mCamera->getPosition();
Ogre::Ray camRay(
  Ogre::Vector3(camPos.x, 5000.0, camPos.z),
  Ogre::Vector3::NEGATIVE_UNIT_Y);

The first line is simple. We are just retrieving the position vector from mCamera. After that we create a ray that has its origin at a height of 5000.0 units and is directly above our camera. The reason we don't just use the camera's y-value is because our collision detection would fail if the camera was below the terrain. We are firing the ray in the negative y direction, so the ray would never hit the terrain if the camera was below the terrain. A ray is like a vector that never ends. It has a starting point, but then it goes off to infinity. They are used to track all kinds of things like line-of-sight, bullet collisions, and lighting.

To finish up the handleCameraCollision method we are going to use our ray to check the height of the terrain at our camera's position.

Ogre::TerrainGroup::RayResult result = mTerrainGroup->rayIntersects(camRay);

if (result.terrain)
{
  Ogre::Real terrainHeight = result.position.y;

  if (camPos.y < (terrainHeight + 10.0))
    mCamera->setPosition(camPos.x, terrainHeight + 10.0, camPos.z);
}

The first thing we do is to actually cast the ray against the our terrain and retrieve the result. A RayResult is a struct with a terrain component and a position component that we can use to determine what piece of terrain was hit. The if statement checks to make sure a piece of the terrain was actually hit, then we get the height of the terrain at that point from the position vector in our result. Finally, we check to see if our current camera height is less than 10.0 units above the terrain. If the camera has moved below this point, then we simply reset the camera's position to move it 10.0 units above the terrain without changing it's x or z value.

The only thing left to do is to call our handleCameraCollision method. Add this right before the return statement in frameRenderingQueued:

handleCameraCollision();

That's it! If you compile and run the application now, you should no longer be able to move the camera through the terrain.

Selecting Points on the Terrain

Now we are going to add the ability to create new entities when the terrain is clicked. If the left mouse button is held down after clicking, then we will be able to move the new entity around until we drop it by releasing the button. The first thing we do is add some code to the mousePressed method. This code will go inside the if statement that identifies the left mouse button being pressed.

CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
CEGUI::Vector2f mousePos = context.getMouseCursor().getPosition();

The first thing we do is get a reference to the default GUI context of CEGUI. This allows us access to large amount of information taken from the GUI. Using this context, we get the position of the mouse cursor. This is a very common pattern when working with CEGUI. Notice we hold on to the reference, because it will be useful again within this very method.

Ogre::Ray mouseRay =
  mCamera->getCameraToViewportRay(
    mousePos.d_x / float(me.state.width),
    mousePos.d_y / float(me.state.height));

Ogre::TerrainGroup::RayResult result = mTerrainGroup->rayIntersects(mouseRay);

This should look familiar. We just did something similar for terrain collision, but this time our raycast is a little more complicated. We use a convenience method called getCameraToViewportRay which returns a ray that starts at our camera frustum and goes off in a direction normal to it.

The last bit of complication is that this method requires the screen coordinates of the mouse cursor in "normalized coordinates". This means they should have a maximum size of one. Similar to how a normalized vector has a length of one. The coordinates we want run from (0, 0) to (1, 1). To normalize our cursor position, we divide the cursor's current position in pixels by the width of our viewport. Finally, we check for a raycast hit the same way we did with the collision.

if (result.terrain)
{
  Ogre::Entity* ent = mSceneMgr->createEntity("robot.mesh");

  mCurObject = mSceneMgr->getRootSceneNode()->createChildSceneNode();
  mCurObject->setPosition(result.position);
  mCurObject->setScale(0.2, 0.2, 0.2);
  mCurObject->attachObject(ent);
}

This is where we actually add the new entity to our scene. We check to make sure we actually hit the terrain, and then we build a scene node to attach our entity to. Newer versions no longer require you to provide a unique name for each entity or scene node. If you don't provide a name, then Ogre will generate a unique name for you. You can still provide your own name for the sake of convenience.

Compile and run the application. You should be able to place robots on the terrain and move them around before releasing the left mouse button. We've completed everything we set out to complete in this tutorial!

Conclusion

This tutorial is a solid introduction to using raycasts with terrain in Ogre. There is much more to learn, but you now have some of the basics under control.

The first thing we did was add a "mouse look" mode that is activated by holding down the right mouse button. This replaced the SdkCameraMan who was controlling the direction of the camera. It accomplished the same thing, but allowed us more direct control over the details.

Then we used a raycast to determine whether or not the camera had collided with the terrain. After that we used a raycast to determine the point on the terrain the user had clicked. Finally, we used this information to allow the creation and manipulation of entities in our scene.

Using raycasts to select entities instead of terrain will be covered in the next tutorial.

Exercises

Easy

  1. The camera's minimum height above the terrain should be kept in a static class member instead of hardcorded as 10.0 units. Make this change, and adjust the value to your personal tastes.
  2. Sometimes you will want to be able to pass through the terrain with the camera. Add a boolean flag to your application which toggles collision detection. Bind this effect to a key of your choice.

Intermediate

  1. It is wasteful to raycast against the terrain if the camera hasn't moved. Fix this problem by making sure the raycast is only done if the camera has moved since the last frame. (Hint: Find the camera's translation vector and compare it against Vector3::ZERO.)

Difficult

  1. We have very similar code involved in casting rays each time. Try to wrap up the raycast into a method. (Hint: You might find it useful to pass this method some parameters to make the method flexible enough to handle different types of raycasts.)

Advanced

  1. Raycasts are very useful throughout game programming. Take the code from Intermediate Tutorial 1 and complete the Difficult and Advanced exercises. then merge that code with this tutorial so that the robot walks on the terrain.
  2. Add a mode to your application where clicking on the terrain causes the robots to move to that location.

Full Source

The full source for this tutorial is here.

Next

Intermediate Tutorial 3


Alias: Intermediate_Tutorial_2