History: Intermediate Tutorial 7
Source of version: 45
- «
- »
Copy to clipboard
%tutorialhelp%
{maketoc}
!Introduction
This tutorial covers the basics of rendering to a texture. This technique is used for a variety of effects. It is particularly useful in combination with shaders. Motion blur effects can be created in this way.
The basic idea is rather simple. Instead of just sending render information strictly to our render window, we will also send the information to be rendered directly to a texture in our scene. This texture will then be used like a texture loaded from the hard drive.
This is the scene we will produce:
{img fileId="2247" rel="box[g]"}
The full source for this tutorial is ((IntermediateTutorial7SourceCurrent|here)).
Note: There is also source available for the BaseApplication framework and Ogre 1.7 ((IntermediateTutorial7Source|here)).
!Setting Up the Scene
First, as usual, we are going to set up a basic scene. Add the following variables to your project.
{CODE(caption="BasicApp.h", wrap="1", colors="c++")}
Ogre::MovablePlane* mPlane;
Ogre::Entity* mPlaneEntity;
Ogre::SceneNode* mPlaneNode;
Ogre::Rectangle2D* mMiniscreen;
{CODE}
Remember to initalize them all in the constructor.
{CODE(caption="BasicApp.cpp", wrap="1", colors="c++")}
mPlane(0),
mPlaneEntity(0),
mPlaneNode(0),
mMiniscreen(0)
{CODE}
Finally, we'll set up the basic scene elements we need. Add the following to {MONO()createScene{MONO}:
{CODE(wrap="1", colors="c++")}
mSceneMgr->setAmbientLight(Ogre::ColourValue(0.2, 0.2, 0.2));
Ogre::Light* light = mSceneMgr->createLight("MainLight");
light->setPosition(20, 80, 50);
mCamera->setPosition(60, 200, 70);
mCamera->lookAt(0,0,0);
Ogre::MaterialPtr mat =
Ogre::MaterialManager::getSingleton().create(
"PlaneMat", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::TextureUnitState* tuisTexture =
mat->getTechnique(0)->getPass(0)->createTextureUnitState("grass_1024.jpg");
mPlane = new Ogre::MovablePlane("Plane");
mPlane->d = 0;
mPlane->normal = Ogre::Vector3::UNIT_Y;
Ogre::MeshManager::getSingleton().createPlane(
"PlaneMesh",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
*mPlane,
120, 120, 1, 1,
true,
1, 1, 1,
Ogre::Vector3::UNIT_Z);
mPlaneEntity = mSceneMgr->createEntity("PlaneMesh");
mPlaneEntity->setMaterialName("PlaneMat");
mPlaneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
mPlaneNode->attachObject(mPlaneEntity);
{CODE}
If any of this is confusing, refer to previous tutorials. Compile and run your application. You should see a rotating grass-textured plane.
{img fileId="2248" rel="box[g]"}
!Creating a Texture
The first step is to create a texture we can render to. Add the folowing to {MONO()}createScene{MONO}:
{CODE(wrap="1", colors="c++")}
Ogre::TexturePtr rttTexture =
Ogre::TextureManager::getSingleton().createManual(
"RttTex",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D,
mWindow->getWidth(), mWindow->getHeight(),
0,
Ogre::PF_R8G8B8,
Ogre::TU_RENDERTARGET);
{CODE}
The first parameter of this function is the name to give the texture ("RttTex" is somewhat standard). The second specifies the default resource group. The third specifies the type of the texture to be 2D. The fourth and fifth specify the width and height of the texture. The sixth parameter is the number of mipmaps to be used. The seventh is a texture format, and the last is a usage flag.
There are many different texture formats, but the simplest one is PF_R8G8B8. This produces a 24-bit RGB texture. If you need an alpha channel, then PFR8G8B8A8 will work fine.
Next we need to get the render target of this texture in order to set some parameters. It will also be used later to add a RenderTargetListener.
{CODE(wrap="1", colors="c++")}
Ogre::RenderTexture* renderTexture = rttTexture->getBuffer()->getRenderTarget();
renderTexture->addViewport(mCamera);
renderTexture->getViewport(0)->setClearEveryFrame(true);
renderTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
renderTexture->getViewport(0)->setOverlaysEnabled(false);
{CODE}
After getting the render texture, we have to add a viewport to it. This is the viewport with whose content the RenderTexture will be filled. We also tell the viewport to clear itself every frame, set the background color to black and request to disable all the overlays for the texture as we don't want to have them on it.
!Write the Texture to File
At this point we've got everything ready to do a first check: We just store the content of our created RenderTexture in a file. The handy thing is that the RenderTextures are derived from RenderTarget and so have a ready function to store the content of the texture in a file (as well as we can do it with RenderWindows). But before saving the content to a file, you should update your RenderTexture. You can do this manually via the update() function.
{CODE(wrap="1", colors="c++")}
renderTexture->update();
// Now save the contents
renderTexture->writeContentsToFile("start.png");
{CODE}
After running the application, you will find a new .png file in the directory your .exe is in, that should show the content of your screen (in our case the textured plane).
Note that there's also setAutoUpdated() which will automatically update the RenderTexture if Ogre's rendering loop or Root::_updateAllRenderTargets is being used.
Keep in mind that it doesn't update the RenderTexture immediately when it's called.
For example:
{CODE(wrap="1", colors="c++")}
// Don't add this code!
renderTexture->setAutoUpdated(true);
{CODE}
!Implementing the Miniscreen
Now, we will add a mini screen in the lower right corner of our application window. To do this we'll add a Rectangle2D to our scene which will get our RenderTexture as texture. Our scene will be shown twice: one time rendered to the RenderWindow as normal, and a second time as the texture on our Rectangle2D.
Using this method it is also possible to implement TV screens (or CCTV cameras, etc). You can display other parts of your level by putting a camera there, creating a RenderTexture (as described in the first section) and displaying it on the TV screen.
!!!Setting up the rectangle
Creating an Ogre::Rectangle2D is rather simple:
{CODE(wrap="1", colors="c++")}
mMiniScreen = new Ogre::Rectangle2D(true);
mMiniScreen->setCorners(0.5f, -0.5f, 1.0f, -1.0f);
mMiniScreen->setBoundingBox(Ogre::AxisAlignedBox::BOX_INFINITE);
{CODE}
In the first line, we set the parameter to true to generate texture coordinates, which we later need to map the texture on the rectangle. In the second line we have to specify the corners of the rectangle. Left is -1.0 and right +1.0, top is +1.0 and bottom -1.0. So our rectangle is just in the lower right corner of our application window.
We also give the rectangle an infinite bounding box to prevent it from being culled when we are not facing its scene node.
Now that we have created the rectangle, we just need to attach it to a SceneNode which should not be anything new for you.
{CODE(wrap="1", colors="c++")}
Ogre::SceneNode* miniScreenNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("MiniScreenNode");
miniScreenNode->attachObject(mMiniScreen);
{CODE}
If you run the application at this stage, you will see a white rectangle in the lower right corner of our application window.
{img src="img/wiki_up/RTT_rectangle.jpg" alt="-RTT rectangle.jpg"}
!Creating a Material From Scratch
The next step is now to show the RenderTexture we created in the first section on this rectangle. Therefore we have to create a material for it. We can do this either in a material script, or directly in the code during runtime. In this tutorial, we will use the second method to have everything together in one file.
{CODE(wrap="1", colors="c++")}
Ogre::MaterialPtr renderMaterial = Ogre::MaterialManager::getSingleton().create("RttMat", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
renderMaterial->getTechnique(0)->getPass(0)->setLightingEnabled(false);
renderMaterial->getTechnique(0)->getPass(0)->createTextureUnitState("RttTex");
{CODE}
In the first line we create an empty material and add a technique and a pass in the next two lines. With the third line we disable the lightning to prevent our mini screen from being darker than the actual texture. In the last line we create a new TextureUnitState by passing our created RenderTexture from the first section.
Now we can apply this material to our mini screen.
{CODE(wrap="1", colors="c++")}
mMiniScreen->setMaterial("RttMat");
{CODE}
If you run the application now, you will see an undesired effect: The mini screen itself has a miniscreen! To solve this, Ogre introduces RenderTargetListener.
!Using a RenderTargetListener
In many cases you will need RTTs with only some scene objects on it. In our case we need a texture that only contains the output of the application window without the mini screen yet on it, as this texture is intended to be applied to our mini screen. So we have to hide the mini screen each time before the window output is stored in our RenderTexture. And this is where the RenderTargetListener comes in.
This listener has two important functions: preRenderTargetUpdate() and postRenderTargetUpdate(). As the names induce, the first function is automatically called by the listener before the RenderTexture is filled (so we can hide our mini screen here) whereas the second function is automatically called after the RenderTexture has been filled (so we can show our mini screen again).
Implementing a RenderTargetListener is quite simple. First of all we let our application class derive from the RenderTargetListener to make it become its own listener. After that we just have to hide and show our mini screen in the pre- and postRenderTargetUpdate() functions. So your application class should basically look like this now:
__IntermediateTutorial7.h__
{CODE(wrap="1", colors="c++")}
class IntermediateTutorial7 : public BaseApplication, public Ogre::RenderTargetListener
{
public:
IntermediateTutorial7(void);
virtual ~IntermediateTutorial7(void);
protected:
virtual void createScene(void);
virtual void createFrameListener(void);
virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt);
virtual void preRenderTargetUpdate(const Ogre::RenderTargetEvent& evt);
virtual void postRenderTargetUpdate(const Ogre::RenderTargetEvent& evt);
Ogre::MovablePlane* mPlane;
Ogre::Entity* mPlaneEnt;
Ogre::SceneNode* mPlaneNode;
Ogre::Rectangle2D* mMiniScreen;
};
{CODE}
__IntermediateTutorial7.cpp__
{CODE(wrap="1", colors="c++")}
void IntermediateTutorial7::preRenderTargetUpdate(const Ogre::RenderTargetEvent& evt)
{
mMiniScreen->setVisible(false);
}
void IntermediateTutorial7::postRenderTargetUpdate(const Ogre::RenderTargetEvent& evt)
{
mMiniScreen->setVisible(true);
}
{CODE}
Now, the last step we need to do is to add the listener to the RenderTexture. As the application class is derived from RenderTargetListener we can just pass the this pointer as parameter at the end of the createScene function.
{CODE(wrap="1", colors="c++")}
renderTexture->addListener(this);
{CODE}
That's it. Now you have a simple mini screen in your app. It's that simple.
{img src="img/wiki_up/RTT_mini_screen.jpg" alt="-RTT mini screen.jpg"}
!Render to Texture and Shaders
As RTTs are often used with shaders, you have to know how to pass the RenderTexture to one. Fortunately, this is really simple.
The most simple case is one where you never change the texture for the shader during runtime. If it remains constant, you just have to tell your material script the name of the texture you create during runtime, in our case "RttTex". So your texture_unit in the material should look like this:
{CODE(wrap="1", colors="c++")} texture_unit
{
texture RttTex
}
{CODE}
If you need to change the texture the shader should use during runtime, just add the two following lines:
{CODE(wrap="1", colors="c++")} Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName("Sepia");
material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName("OtherRttTex");
{CODE}
With the first line we get a pointer to the material (in this case here a sepia shader material) where we change the texture name in the second line to the desired one.
Now, as you have set the correct texture name in your material script with one of these two methods, you can access the texture in your cg shader with the following line:
{CODE(wrap="1", colors="c++")}
uniform sampler2D SceneSampler : register(s0)
{CODE}
Well, that's it. Your texture of the mini screen should now be passed through your shader and look like this (with the sepia shader attached to this tutorial page):
{img src="img/wiki_up/RTT_final.jpg" alt="-RTT final.jpg"}
!Exercises
!!Easy
!!Intermediate
!!Difficult
!!Advanced
!Conclusion
These are all the basics you need to know to start with RTT. Now play around a bit with this code and discover a new world of graphical effects.
!Full Source
The full source for this tutorial is ((IntermediateTutorial7SourceCurrent|here)).
!Next
Move on to the indepth tutorials or start browsing code snippets for further study. Enjoy!
---
Alias: (alias(Intermediate_Tutorial_7))