Skip to main content
Mogre Basic Tutorial VB 2        

Basic Tutorial 2: Cameras, Lights, and Shadows

Original version by Clay Culver

Ported to VB.NET by Aeauseth

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

Prerequisites

This tutorial assumes you have knowledge of VB.NET programming and are able to setup and compile an Mogre application (if you have trouble setting up your application, see Mogre Basic Tutorial VB 0 for a detailed setup walkthrough). This tutorial builds on the first tutorial, and it assumes you have already worked through it.

Introduction

In this tutorial I will be introducing you to a few more Ogre constructs, as well as expanding on what you have already learned. This tutorial will deal mainly with Light objects and how they are used to create shadows in Ogre. We will also cover the absolute basics about Cameras.

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 pre-constructed code base as our starting point:

Copy to clipboard
Imports Mogre Module Module1 Public myKeyboard As MOIS.Keyboard Public myMouse As MOIS.Mouse Public myCamera As Camera Public MyWindow As RenderWindow Public myTranslation As Vector3 = Vector3.ZERO Public Quitting As Boolean = False Public myRotating As Boolean = False Sub Main() Try 'Initialization of Ogre Root and RenderWindow Dim myRoot As Root = New Root("Plugins.cfg", "ogre.cfg", "ogre.log") 'Show Ogre Rendering Subsystem setup dialog box If Not myRoot.RestoreConfig Then If Not myRoot.ShowConfigDialog Then Exit Sub End If End If 'Create an Ogre render window MyWindow = myRoot.Initialise(True, "Application") AddHandler myRoot.FrameStarted, AddressOf FrameStarted 'Create Ogre SceneManager Dim mySceneManager As SceneManager = myRoot.CreateSceneManager(SceneType.ST_GENERIC) mySceneManager.AmbientLight = ColourValue.Black mySceneManager.ShadowTechnique = ShadowTechnique.SHADOWTYPE_STENCIL_ADDITIVE 'Read Resources Dim cf As New ConfigFile cf.Load("resources.cfg", vbTab + ":=", True) Dim seci As ConfigFile.SectionIterator = cf.GetSectionIterator Dim secName As String, typeName As String, archName As String While (seci.MoveNext()) secName = seci.CurrentKey Dim settings As ConfigFile.SettingsMultiMap = seci.Current For Each pair As KeyValuePair(Of String, String) In settings typeName = pair.Key archName = pair.Value ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName) Next End While ResourceGroupManager.Singleton.InitialiseAllResourceGroups() 'Create Camera myCamera = mySceneManager.CreateCamera("Camera") myCamera.SetPosition(0, 10, 500) myCamera.LookAt(Vector3.ZERO) myCamera.NearClipDistance = 5 'Viewport Dim myViewport As Viewport = MyWindow.AddViewport(myCamera) myViewport.BackgroundColour = ColourValue.Black myCamera.AspectRatio = myViewport.ActualWidth / myViewport.ActualHeight 'Create Ninja Dim myNinja As Entity = mySceneManager.CreateEntity("ninja", "ninja.mesh") myNinja.CastShadows = True mySceneManager.RootSceneNode.CreateChildSceneNode.AttachObject(myNinja) 'Ground to stand on Dim myPlane As Plane = New Plane(Vector3.UNIT_Y, 0) MeshManager.Singleton.CreatePlane("ground", _ ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, _ myPlane, 1500, 1500, 20, 20, True, 1, 5, 5, Vector3.UNIT_Z) Dim myGround As Entity = mySceneManager.CreateEntity("GroundEntity", "ground") mySceneManager.RootSceneNode.CreateChildSceneNode.AttachObject(myGround) myGround.SetMaterialName("Examples/Rockwall") myGround.CastShadows = False 'Lights 'Keyboard Dim windowHnd As Integer MyWindow.GetCustomAttribute("WINDOW", windowHnd) Dim myInputManager As MOIS.InputManager = MOIS.InputManager.CreateInputSystem(windowHnd) myKeyboard = myInputManager.CreateInputObject(MOIS.Type.OISKeyboard, True) AddHandler myKeyboard.KeyPressed, AddressOf InputClass.KeyPressed AddHandler myKeyboard.KeyReleased, AddressOf InputClass.KeyReleased 'Mouse myMouse = myInputManager.CreateInputObject(MOIS.Type.OISMouse, True) AddHandler myMouse.MouseMoved, AddressOf InputClass.MouseMovedListener AddHandler myMouse.MousePressed, AddressOf InputClass.MousePressedListener AddHandler myMouse.MouseReleased, AddressOf InputClass.MouseReleasedListener 'Start rendering myRoot.StartRendering() Catch ex As System.Runtime.InteropServices.SEHException If OgreException.IsThrown Then MsgBox(OgreException.LastException.FullDescription, MsgBoxStyle.Critical, _ "An Ogre exception has occured!") Else MsgBox(ex.ToString, "An error has occured") End If End Try End Sub Public Function FrameStarted(ByVal e As FrameEvent) As Boolean 'Capture buffered input myKeyboard.Capture() myMouse.Capture() 'Handle player/camera movement InputClass.ProcessKeyboard() myCamera.Position += myCamera.Orientation * myTranslation * e.timeSinceLastFrame Return Not Quitting End Function Public Class InputClass Const TRANSLATE As Single = 200 Const ROTATE As Single = 0.003 Shared Function KeyPressed(ByVal e As MOIS.KeyEvent) As Boolean Select Case e.key Case MOIS.KeyCode.KC_ESCAPE Quitting = True End Select Return Nothing End Function Shared Function KeyReleased(ByVal e As MOIS.KeyEvent) As Boolean 'This function is just a placeholder 'It is unlikely you will ever use this 'Tyipcally you either process unbuffered keyboard input (as in ProcessKeyboard) 'or you process buffered Keypress Return Nothing End Function Shared Sub ProcessKeyboard() 'Clear previous translation myTranslation.z = 0 myTranslation.x = 0 myTranslation.y = 0 If myKeyboard.IsKeyDown(MOIS.KeyCode.KC_UP) Or _ myKeyboard.IsKeyDown(MOIS.KeyCode.KC_W) Then myTranslation.z += -TRANSLATE End If If myKeyboard.IsKeyDown(MOIS.KeyCode.KC_S) Or _ myKeyboard.IsKeyDown(MOIS.KeyCode.KC_DOWN) Then myTranslation.z += TRANSLATE End If If myKeyboard.IsKeyDown(MOIS.KeyCode.KC_A) Or _ myKeyboard.IsKeyDown(MOIS.KeyCode.KC_LEFT) Then myTranslation.x += -TRANSLATE End If If myKeyboard.IsKeyDown(MOIS.KeyCode.KC_D) Or _ myKeyboard.IsKeyDown(MOIS.KeyCode.KC_RIGHT) Then myTranslation.x += TRANSLATE End If If myKeyboard.IsKeyDown(MOIS.KeyCode.KC_Q) Or _ myKeyboard.IsKeyDown(MOIS.KeyCode.KC_PGUP) Or _ myKeyboard.IsKeyDown(MOIS.KeyCode.KC_SPACE) Then myTranslation.y += TRANSLATE End If If myKeyboard.IsKeyDown(MOIS.KeyCode.KC_Z) Or _ myKeyboard.IsKeyDown(MOIS.KeyCode.KC_PGDOWN) Then myTranslation.y += -TRANSLATE End If End Sub Shared Function MouseMovedListener(ByVal e As MOIS.MouseEvent) As Boolean Static myLastX As Integer = e.state.X.abs Static myLastY As Integer = e.state.Y.abs If myRotating Then myCamera.Yaw(e.state.X.rel * -ROTATE) myCamera.Pitch(e.state.Y.rel * -ROTATE) End If End Function Shared Function MousePressedListener(ByVal e As MOIS.MouseEvent, ByVal id As MOIS.MouseButtonID) As Boolean If e.state.ButtonDown(MOIS.MouseButtonID.MB_Right) Then myRotating = True End If End Function Shared Function MouseReleasedListener(ByVal e As MOIS.MouseEvent, ByVal id As MOIS.MouseButtonID) As Boolean If Not e.state.ButtonDown(MOIS.MouseButtonID.MB_Right) Then myRotating = False End If End Function End Class End Module

Make sure you can compile and run the application before continuing. If you are having difficulty, refer to the Tutorial 0 or post to the forums.

Cameras

Ogre Cameras

A Camera is what we use to view the scene that we have created. A Camera is a special object which works somewhat like a SceneNode does. The Camera object has the Position property, and the Yaw, Roll, and Pitch functions, and you can optionally attach it to any SceneNode. Just like SceneNodes, a Camera's position is relative to its parents (it's nice to respect one's elders). For all movement and rotation, you can basically consider a Camera a SceneNode.

One thing about Ogre Cameras that is different from what you may expect is that you should only be using one Camera at a time (for now). That is, we do not create a Camera for viewing one portion of a scene, a second camera for viewing another portion of the scene and then enabling or disabling cameras based on what portion of the scene we want to display. Instead the way to accomplish this is to create SceneNodes which act as "camera holders". These SceneNodes simply sit in the scene and point at what the Camera might want to look at. When it is time to display a portion of the Scene, the Camera simply attaches itself to the appropriate SceneNode. We will revisit this technique in the FrameListener tutorial.

Creating a Camera

You will note that we already have Camera code in Module1.vb. Cameras are tied to the SceneManager which they reside in, we use the SceneManager object to create them.

Copy to clipboard
Dim myCamera As Camera = mySceneManager.CreateCamera("Camera")

This creates a Camera with the name "Camera". You can use the GetCamera function of SceneManager to get Cameras based on their name if you decide not to hold a reference to it. Note that the OgreWindow class we have subclassed provides a property containing the current SceneManager object called "SceneManager". It also contains a property for the current Camera, which is where we assigned the newly created camera object.

The next few lines set the position of the Camera and the way that it's facing. In most of our tutorials we will be placing objects around the origin, so we'll put the Camera a good distance in the +z direction and have the Camera face the origin.

Copy to clipboard
myCamera.SetPosition(0, 10, 500) myCamera.LookAt(Vector3.ZERO)

The LookAt function is pretty nifty. You can have the Camera face any position you want to instead of having to Yaw, Rotate, and Pitch your way there. SceneNodes have this function as well, which can make setting Entities facing the right direction much easier in many cases.

Finally we will set a near clipping distance of 5 units. The clipping distance of a Camera specifies how close or far something can be before you no longer see it. Setting the near clipping distance makes it easier to see through Entities on the screen when you are very close to them. The alternative is being so close to an object that it fills the screen and you can't see anything but a tiny portion of it. You can also set the far clipping distance as well. This will stop the engine from rendering anything farther away than the given value. This is primarily used to increase the framerate if you are rendering large amounts of things on the screen for very long distances. To set the near clipping distance, add this line:

Copy to clipboard
myCamera.NearClipDistance = 5

You can also change the far clipping distance by setting the FarClipDistance property (though you should not use a far clip distance with Stencil Shadows, which we will be using in this tutorial).

Viewports

Ogre Viewports

When you start dealing with multiple Cameras, the concept of a Viewport class will become much more useful to you. I bring up the topic now because I think it is important for you to understand how Ogre decides which Camera to use when rendering a scene. It is possible in Ogre to have multiple SceneManagers running at the same time. It is also possible to split the screen up into multiple areas, and have seperate cameras render to separate areas on the screen (think of a split view for 2 players in a console game, for example). While it is possible to do these things, we will not cover how to do them until the advanced tutorials.

To understand how Ogre renders a scene, consider three of Ogre's constructs: the Camera, the SceneManager, and the RenderWindow. The RenderWindow we have not covered, but it is basically the window in which everything is displayed. The SceneManager object creates Cameras to view the scene. You must tell the RenderWindow which Cameras to display on the screen, and what portion of the window to render it in. The area in which you tell the RenderWindow to display the Camera is your Viewport. Under most typical uses of Ogre, you will generally create only one Camera, register the Camera to use the entire RenderWindow, and thus only have one Viewport object.

In this tutorial we will go over how to use the Camera to create the Viewport. We can then use this Viewport object to set the background color of the scene we are rendering.

Creating the Viewport

You will note that we already have Camera code in Module1.vb. To create the Viewport we simply call the AddViewport function of RenderWindow and supply it with the Camera we are using.

Copy to clipboard
Dim myViewport As Viewport = myWindow.AddViewport(myCamera)

Now that we have our Viewport, what can we do with it? The answer is: not much. The most important thing we can do with it is set the BackgroundColour property to set the background to whatever color we choose. Since we are dealing with lighting in this tutorial we will set the color to black. Go ahead and add this line to Module1.vb:

Copy to clipboard
myViewport.BackgroundColour = ColourValue.Black

The last, and most important thing we need to do is to set the aspect ratio of our Camera. If you are using something other than the standard full-window viewport, then failing to set this can result in a very strange looking scene. We will go ahead and set it even though we are using the default aspect ratio:

Copy to clipboard
myCamera.AspectRatio = myViewport.ActualWidth / myViewport.ActualHeight

That's all that has to be done for our simple use of the Viewport class.

Lights and Shadows

Shadow Types that Ogre Supports

Ogre currently supports three types of Shadows:

  1. Modulative Texture Shadows (SHADOWTYPE_TEXTURE_MODULATIVE) - The least intensive of the three. This creates a black and white render-to-texture of shadow casters, which is then applied to the scene.
  2. Modulative Stencil Shadows (SHADOWTYPE_STENCIL_MODULATIVE) - This technique renders all shadow volumes as a modulation after all non-transparent objects have been rendered to the scene. This is not as intensive as Additive Stencil Shadows, but it is also not as accurate.
  3. Additive Stencil Shadows (SHADOWTYPE_STENCIL_ADDITIVE) - This technique renders each light as a separate additive pass on the scene. This is very hard on the graphics card because each additional light requires an additional pass at rendering the scene.


Ogre does not support soft shadows as part of the engine. If you want soft shadows you will need to write your own vertex and fragment programs. Note that this is just a quick introduction here. The Ogre manual fully describes shadows in Ogre and the implications of using them.

Using Shadows in Ogre

Using shadows in Ogre is relatively simple. The SceneManager class has a ShadowTechnique property that we can use to set the type of Shadows we want. Then whenever you create an Entity, set the CastShadows property to set whether or not it casts shadows.

We will now set the ambient light to complete darkness, and set the shadow type:

Copy to clipboard
'Create Ogre SceneManager Dim mySceneManager As SceneManager = myRoot.CreateSceneManager(SceneType.ST_GENERIC) mySceneManager.AmbientLight = ColourValue.Black mySceneManager.ShadowTechnique = ShadowTechnique.SHADOWTYPE_STENCIL_ADDITIVE

We add a Ninja entity and set it to cast shadows:

Copy to clipboard
'Create Ninja Dim myNinja As Entity = mySceneManager.CreateEntity("ninja", "ninja.mesh") myNinja.CastShadows = True mySceneManager.RootSceneNode.CreateChildSceneNode.AttachObject(myNinja)

We also need something for the Ninja to stand on (so that he has something to cast shadows onto). To do this we will create a simple plane for him to stand on. This is not meant to be a tutorial on using MeshManager, but we will go over the very basics since we have to use it to create a plane. First we need to define the Plane object itself, which is done by supplying a normal and the distance from the origin. We could (for example) use planes to make up parts of world geometry, in which case we would need to specify something other than 0 for our origin distance. For now we just want a plane to have the positive y axis as its normal (that means we want it to face up), and no distance from the origin:

Copy to clipboard
'Ground to stand on Dim myPlane As Plane = New Plane(Vector3.UNIT_Y, 0)

Now we need to register the plane so that we can use it in our application. The MeshManager class keeps track of all the meshes we have loaded into our application (for example, this keeps track of the robot.mesh and the ninja.mesh that we have been using). The CreatePlane method takes in a Plane definition and makes a mesh from the parameters. This registers our plane for use:

Copy to clipboard
MeshManager.Singleton.CreatePlane("ground", _ ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, _ myPlane, 1500, 1500, 20, 20, True, 1, 5, 5, Vector3.UNIT_Z)

Again, I do not wish to go into the specifics of how to use the MeshManager just yet (consult the api reference if you want to see exactly what each parameter is doing). Basically we have registered our plane to be 1500 by 1500 in size and new mesh is called "ground". Now, we can create an Entity from this mesh and place it on the scene:

Copy to clipboard
Dim myGround As Entity = mySceneManager.CreateEntity("GroundEntity", "ground") mySceneManager.RootSceneNode.CreateChildSceneNode.AttachObject(myGround)

Neat huh? There's two more things we need to do with our ground before we are finished with it. The first is to tell the SceneManager that we don't want it to cast shadows since it is what's being used for shadows to project on. The second thing is we need to put a texture on it. Our robot and ninja meshes already have material scripts defined for them. When we manually created our ground mesh, we did not specify what texture to use on it. We will use the "Examples/Rockwall" material script that Ogre includes with its samples:

Copy to clipboard
myGround.SetMaterialName("Examples/Rockwall") myGround.CastShadows = False

Now that we have a Ninja and ground in the scene, lets compile and run the program. We see...nothing! What's going on? In the previous tutorial we added Robots and they displayed fine. The reason the Ninja doesn't show up is because the scene's ambient light has been set to total darkness. So let's add a light to see what is going on.

Types of Lights

There are three types of lighting that Ogre provides.

  1. Point (LT_POINT) - Point light sources emit light from them in every direction.
  2. Spotlight (LT_SPOTLIGHT) - A spotlight works exactly like a flashlight does. You have a position where the light starts, and then light heads out in a direction. You can also tell the light how large of an angle to use for the inner circle of light and the outer circle of light (you know how flashlights are brighter in the center, then lighter after a certain point?).
  3. Directional (LT_DIRECTIONAL) - Directional light simulates far away light that hits everything in the scene from a direction. Lets say you have a night time scene and you want to simulate moonlight. You could do this by setting the ambient light for the scene, but that's not exactly realistic since the moon does not light everything equally (neither does the sun). One way to do this would be to set a directional light and point in the direction the moon would be shining.


Lights have a wide range of properties that describes how the light looks. Two of the most important properties of a light is its diffuse and specular color. Each material script defines how much diffuse and specular lighting the material reflects, which we will learn how to control in a later tutorial.

Creating the Lights

To create a Light in Ogre we call SceneManager's CreateLight method and supply the light's name, very much like how we create an Entity or Camera. After we create a Light, we can either set the position of it manually or attach it to a SceneNode for movement. Unlike the Camera object, light only has Position and Direction Properties (and not the full suite of movement functions like translate, pitch, yaw, roll, etc). So if you need to create a stationary light, you should set the Position property. If you need the light to move (such as creating a light that follows a character), then you should attach it to a SceneNode instead.

So, lets start with a basic point Light. The first thing we will do is create the light, set its type, and set its position. Add the following code:

Copy to clipboard
'Lights Dim myLight As Light = mySceneManager.CreateLight("Light1") myLight.Type = Light.LightTypes.LT_POINT myLight.Position = New Vector3(0, 150, 250)


Now that we have created the light, we can set its diffuse and specular color. Let's make it red:

Copy to clipboard
myLight.DiffuseColour = ColourValue.Red myLight.SpecularColour = ColourValue.Red

Now compile and run the application. Success! We can now see the Ninja and he casts a shadow. Be sure to also look at him from the front, a complete silhouette. One thing to notice is that you do not "see" the light source. You see the light it generates but not the actual light object itself. Many of Ogre's tutorials add a simple entity to show where the light is being emitted from. If you are having trouble with lights in your application you should consider creating something similar to what they do so you can see exactly where your light is.

Next, lets try out directional light. Notice how the front of the ninja is pitch black? Lets add a small amount of green directional light that is shining towards the front of his body. We create the light and set the color just like we do for a point light:

Copy to clipboard
myLight = mySceneManager.CreateLight("Light2") myLight.Type = Light.LightTypes.LT_DIRECTIONAL myLight.DiffuseColour = New ColourValue(0.25, 0.25, 0) myLight.SpecularColour = New ColourValue(0.25, 0.25, 0)

Since directional light is supposed to come from a far off distance, we do not have to set its position, only its direction. We'll set the direction of the light to be in the positive z and negative y direction (like it is coming from 45 degrees in front and above the ninja):

Copy to clipboard
myLight.Direction = New Vector3(0, -1, -1)

Compile and run the application. We now have two shadows on the screen, though since the directional light is so faint, the shadow is also faint. The last type of light we are going to play with is the spotlight. We will now create a blue spotlight:

Copy to clipboard
myLight = mySceneManager.CreateLight("Light3") myLight.Type = Light.LightTypes.LT_SPOTLIGHT myLight.DiffuseColour = ColourValue.Blue myLight.SpecularColour = ColourValue.Blue

We also need to set both the position and the direction that the spotlight shines in. We will create a spotlight that hovers above the Ninja's right shoulder, and shines down directly on him:

Copy to clipboard
myLight.Direction = New Vector3(-1, -1, 0) myLight.Position = New Vector3(300, 300, 0)

Spotlights also allow us to specify how wide the beam of the light is. Imagine a flashlight beam for a second. There is a core beam in the center that is brighter than the surrounding light. We can set the width of both of these beams by calling the setSpotlightRange member function:

Copy to clipboard
myLight.SetSpotlightRange(New Degree(35), New Degree(50))

Compile and run the application. Purple Ninja...dangerous!

Things to Try

Different Shadow Types

In this demo we only set the shadow type to be SHADOWTYPE_STENCIL_ADDITIVE. Try setting it to the other two types of shadows and see what happens. There are also many other shadow-related functions in the SceneManager class. Try playing with some of them and seeing what you come up with.

Light Attenuation

Lights define an Attenuation property which allows you to control how the light dissipates as you get farther away from it. Add a function call to the Point light that sets the attenuation to different values. How does this affect the light?

SceneManager.AmbientLight

Experiment with the AmbientLight property.

Viewport Background Colour

Change the default ColourValue in the CreateViewport function. While it is not really appropriate to change it to something other than black in this situation, it is a good thing to know how to change.

Camera.FarClipDistance

In CreateCamera we set the near clip distance. Set the FarClipDistance property to be 500, watch what happens when you move from seeing the Ninja and not seeing the Ninja with stencil shadows turned on. Notice the slowup?

Note: You'll need to call mgr.setShadowUseInfiniteFarPlane(false), for this to work, and you might get some strange shadows. (See this thread.)

Planes

We did not cover much about Planes in this tutorial (it was not the focus of this article). If you are interested you should look up the CreatePlane function and try playing with some of the inputs to the function.

Proceed to Mogre Basic Tutorial VB 3 Terrain, Sky, and Fog