
\begin{DoxyItemize}
\item Getting Started
\begin{DoxyItemize}
\item \mbox{\hyperlink{building-ogre}{Guide to building O\+G\+RE}}
\item \mbox{\hyperlink{setup}{Setting up an O\+G\+RE project}}
\item \mbox{\hyperlink{tut_FirstScene}{Your First Scene}}
\item \mbox{\hyperlink{tut_LightsCamerasShadows}{Lights, Cameras, and Shadows}}
\item \mbox{\hyperlink{tut_TerrainSkyFog}{Terrain, Sky and Fog}}
\item \mbox{\hyperlink{working-with-numpy}{Working with Num\+Py}}
\end{DoxyItemize}
\item Components
\begin{DoxyItemize}
\item \mbox{\hyperlink{trays}{Trays G\+UI System}}
\item \mbox{\hyperlink{volume}{Volume Component}}
\end{DoxyItemize}
\item In Depth
\begin{DoxyItemize}
\item \mbox{\hyperlink{manual-mesh-creation}{Manual mesh creation}}
\item \mbox{\hyperlink{profiler}{Using the Profiler}}
\item \mbox{\hyperlink{External-Texture-Sources}{External Texture Sources}}
\item \mbox{\hyperlink{ShadowMappingOgre}{Shadow Mapping in Ogre}}
\item \mbox{\hyperlink{deferred}{Deferred Shading}}
\item \mbox{\hyperlink{pczscenemanager}{Using the P\+CZ Scene Manager}} 
\end{DoxyItemize}
\end{DoxyItemize}\hypertarget{building-ogre}{}\doxysection{Guide to building O\+G\+RE}\label{building-ogre}
\mbox{\hyperlink{namespace_ogre}{Ogre}} uses \href{https://cmake.org/}{\texttt{ C\+Make}} as its build system on all supported platforms. This guide will explain to you how to use C\+Make to build \mbox{\hyperlink{namespace_ogre}{Ogre}} from source. You need a C\+Make version $>$= 3.\+3.\hypertarget{building-ogre_autotoc_md244}{}\doxysubsection{What is C\+Make?}\label{building-ogre_autotoc_md244}
C\+Make is a cross-\/platform build system -\/ or perhaps more accurately a build configurator. It is a program which, from a set of C\+Make scripts, creates a native build system for your platform that allows you to build \mbox{\hyperlink{namespace_ogre}{Ogre}}. The build process is configurable via C\+Make. \mbox{\hyperlink{namespace_ogre}{Ogre}} provides several options which you can use to customise your build.\hypertarget{building-ogre_autotoc_md245}{}\doxysubsection{Preparing the build environment}\label{building-ogre_autotoc_md245}
You should now create a build directory for \mbox{\hyperlink{namespace_ogre}{Ogre}} somewhere outside \mbox{\hyperlink{namespace_ogre}{Ogre}}\textquotesingle{}s sources. This is the directory where C\+Make will create the build system for your chosen platform and compiler, and this is also where the \mbox{\hyperlink{namespace_ogre}{Ogre}} libraries will be compiled. This way, the \mbox{\hyperlink{namespace_ogre}{Ogre}} source dir stays clean, and you can have multiple build directories all working from the same \mbox{\hyperlink{namespace_ogre}{Ogre}} source.\hypertarget{building-ogre_autotoc_md246}{}\doxysubsection{Getting dependencies}\label{building-ogre_autotoc_md246}
By default ogre will build the essential dependencies automatically when you run cmake the first time. If you would rather use system wide libraries set {\ttfamily O\+G\+R\+E\+\_\+\+B\+U\+I\+L\+D\+\_\+\+D\+E\+P\+E\+N\+D\+E\+N\+C\+I\+ES=O\+FF}.

\mbox{\hyperlink{namespace_ogre}{Ogre}} will install the dependencies into the subfolder {\ttfamily Dependencies} in the build dir by default. You can configure it by setting {\ttfamily O\+G\+R\+E\+\_\+\+D\+E\+P\+E\+N\+D\+E\+N\+C\+I\+E\+S\+\_\+\+D\+IR} in cmake. For instance to point to a common dependencies folder for all of your projects. Inside this directory you must have the subdirectories bin, lib and include where you place .dll, .lib and header files of the dependencies, respectively

On linux you additionally need the following system headers to build the GL Render\+Systems (command for Ubuntu)\+: \begin{DoxyVerb}sudo apt-get install libgles2-mesa-dev libxt-dev libxaw7-dev
\end{DoxyVerb}


furthermore we recommend installing the following optional packages \begin{DoxyVerb}sudo apt-get install nvidia-cg-toolkit libsdl2-dev doxygen
\end{DoxyVerb}


these will enable input handling in the Sample\+Browser and building the documentation.

If you cannot obtain prebuilt binaries of a dependency for your platform, please refer to the list below and get a source package from the website, then build it according to its documentation.\hypertarget{building-ogre_autotoc_md247}{}\doxysubsubsection{Essential dependencies\+:}\label{building-ogre_autotoc_md247}

\begin{DoxyItemize}
\item freetype\+: \href{http://www.freetype.org}{\texttt{ http\+://www.\+freetype.\+org}}
\end{DoxyItemize}\hypertarget{building-ogre_autotoc_md248}{}\doxysubsubsection{Recommended dependencies\+:}\label{building-ogre_autotoc_md248}

\begin{DoxyItemize}
\item zlib\+: \href{http://www.zlib.net}{\texttt{ http\+://www.\+zlib.\+net}}
\item zziplib\+: \href{https://github.com/gdraheim/zziplib}{\texttt{ https\+://github.\+com/gdraheim/zziplib}}
\item pugixml\+: \href{https://github.com/zeux/pugixml}{\texttt{ https\+://github.\+com/zeux/pugixml}}
\item S\+DL\+: \href{https://www.libsdl.org/}{\texttt{ https\+://www.\+libsdl.\+org/}}
\end{DoxyItemize}\hypertarget{building-ogre_autotoc_md249}{}\doxysubsubsection{Optional dependencies\+:}\label{building-ogre_autotoc_md249}

\begin{DoxyItemize}
\item DirectX S\+DK\+: \href{http://msdn.microsoft.com/en-us/directx/}{\texttt{ http\+://msdn.\+microsoft.\+com/en-\/us/directx/}}
\item Free\+Image\+: \href{http://freeimage.sourceforge.net}{\texttt{ http\+://freeimage.\+sourceforge.\+net}}
\item Doxygen\+: \href{http://doxygen.org}{\texttt{ http\+://doxygen.\+org}}
\item Cg\+: \href{http://developer.nvidia.com/object/cg_toolkit.html}{\texttt{ http\+://developer.\+nvidia.\+com/object/cg\+\_\+toolkit.\+html}}
\item Remotery\+: \href{https://github.com/Celtoys/Remotery}{\texttt{ https\+://github.\+com/\+Celtoys/\+Remotery}}
\item Boost\+: \href{http://www.boost.org}{\texttt{ http\+://www.\+boost.\+org}} (+)
\item P\+O\+CO\+: \href{http://pocoproject.org}{\texttt{ http\+://pocoproject.\+org}} (+)
\item T\+BB\+: \href{http://www.threadingbuildingblocks.org}{\texttt{ http\+://www.\+threadingbuildingblocks.\+org}} (+)
\end{DoxyItemize}

(+) can be used for threading instead of {\ttfamily std\+::thread}\hypertarget{building-ogre_autotoc_md250}{}\doxysubsection{Running C\+Make}\label{building-ogre_autotoc_md250}
Now start the program cmake-\/gui by either typing the name in a console or selecting it from the start menu. In the field {\itshape Where is the source code} enter the path to the \mbox{\hyperlink{namespace_ogre}{Ogre}} source directory (the directory which contains this file). In the field {\itshape Where to build the binaries} enter the path to the build directory you created. Hit {\itshape Configure}. A dialogue will appear asking you to select a generator.

Check the \href{https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html}{\texttt{ C\+Make documentation}} for details on which one is appropriate for your platform and compiler. ~\newline
 \begin{DoxyNote}{Note}
on O\+SX, you must to use the Xcode generator to get a proper Sample\+Browser .app bundle.
\end{DoxyNote}
Click {\itshape Finish}. C\+Make will now gather some information about your build environment and try to locate the dependencies. It will then show a list of build options. You can adjust the settings to your liking;
\begin{DoxyItemize}
\item unchecking any of the {\ttfamily O\+G\+R\+E\+\_\+\+B\+U\+I\+L\+D\+\_\+\+X\+XX} options will disable that particular component/ plugin from being built
\item {\ttfamily O\+G\+R\+E\+\_\+\+C\+O\+N\+F\+I\+G\+\_\+\+X\+XX} on the other hand allows you to configure Core features e.\+g. threading or zip file support.
\item {\ttfamily O\+G\+R\+E\+\_\+\+C\+O\+N\+F\+I\+G\+\_\+\+N\+O\+D\+E\+\_\+\+I\+N\+H\+E\+R\+I\+T\+\_\+\+T\+R\+A\+N\+S\+F\+O\+RM} enables shearing and non-\/uniform scaling for \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}}. This requires slightly more storage and computation time.
\item {\ttfamily O\+G\+R\+E\+\_\+\+P\+R\+O\+F\+I\+L\+I\+NG} add profiling instrumentation the ogre library.
\item {\ttfamily O\+G\+R\+E\+\_\+\+P\+R\+O\+F\+I\+L\+I\+N\+G\+\_\+\+R\+E\+M\+O\+T\+E\+R\+Y\+\_\+\+P\+A\+TH} if set, Remotery is used for profiling instead of the \mbox{\hyperlink{namespace_ogre}{Ogre}} internal profiler.
\item {\ttfamily O\+G\+R\+E\+\_\+\+A\+S\+S\+E\+R\+T\+\_\+\+M\+O\+DE} allows you to to disable all runtime assertion exceptions or turn them into calls to {\ttfamily std\+::abort}.
\item {\ttfamily O\+G\+R\+E\+\_\+\+R\+E\+S\+O\+U\+R\+C\+E\+M\+A\+N\+G\+E\+R\+\_\+\+S\+T\+R\+I\+CT} allows you to turn on resource lookup related quirks for pre ogre 1.\+10 compatibility.
\end{DoxyItemize}

Once you are satisfied, hit {\itshape Configure} again and then click on {\itshape Generate}. C\+Make will then create the build system for you.\hypertarget{building-ogre_autotoc_md251}{}\doxysubsection{Building}\label{building-ogre_autotoc_md251}
Go to your chosen build directory. C\+Make has generated a build system for you which you will now use to build \mbox{\hyperlink{namespace_ogre}{Ogre}}. If you are using Visual Studio, you should find the file O\+G\+R\+E.\+sln. Open it and compile the target {\itshape B\+U\+I\+L\+D\+\_\+\+A\+LL}. Similarly you will find an Xcode project to build \mbox{\hyperlink{namespace_ogre}{Ogre}} on Mac\+OS.

If you rather want to trigger the build form a console, then cd to your build directory and call the appropriate make program as \begin{DoxyVerb}cmake --build . --config release
\end{DoxyVerb}


to start the build process.

If you have doxygen installed and C\+Make picked it up, then there will be an additional build target called {\itshape Ogre\+Doc} which you can optionally build. This will freshly generate the A\+PI documentation for \mbox{\hyperlink{namespace_ogre}{Ogre}}\textquotesingle{}s classes from the header files. In Visual Studio, just select and build the target {\itshape Ogre\+Doc}, on Linux type\+: \begin{DoxyVerb} make OgreDoc
\end{DoxyVerb}
\hypertarget{building-ogre_autotoc_md252}{}\doxysubsection{Installing}\label{building-ogre_autotoc_md252}
Once the build is complete, you can optionally have the build system copy the built libraries and headers to a clean location. We recommend you do this step as it will make it easier to use \mbox{\hyperlink{namespace_ogre}{Ogre}} in your projects. In Visual Studio, just select and build the target {\itshape I\+N\+S\+T\+A\+LL}. When using the command line with M\+S\+VC, type\+: \begin{DoxyVerb}cmake --build . --config release --target INSTALL
\end{DoxyVerb}


For Makefile based generators, type\+: \begin{DoxyVerb}make install  # (or sudo make install, if root privileges are required)
\end{DoxyVerb}


On Linux \mbox{\hyperlink{namespace_ogre}{Ogre}} will be installed to {\ttfamily /usr/local} by default. On Windows this will create the folder {\ttfamily sdk} inside your build directory and copy all the required libraries there. You can change the install location by changing the variable {\ttfamily C\+M\+A\+K\+E\+\_\+\+I\+N\+S\+T\+A\+L\+L\+\_\+\+P\+R\+E\+F\+IX} in C\+Make.\hypertarget{building-ogre_autotoc_md253}{}\doxysubsection{Building on Ubuntu for Android}\label{building-ogre_autotoc_md253}
To build \mbox{\hyperlink{namespace_ogre}{Ogre}} for Android, you need to specify the android cross toolchain to cmake as \begin{DoxyVerb}cmake -DCMAKE_TOOLCHAIN_FILE=path/to/android-ndk/build/cmake/android.toolchain.cmake -DANDROID_NDK=path/to/android-ndk .
\end{DoxyVerb}


this will build the core \mbox{\hyperlink{namespace_ogre}{Ogre}} libraries. Additionally it will create gradle projects {\ttfamily Ogre\+J\+NI} for using Java bindings and {\ttfamily Sample\+Browser\+N\+DK} for the C++ only Sample Browser.

You can now import these projects in Android Studio or manually trigger the A\+PK creation by changing into the project folders and running \begin{DoxyVerb}gradle assembleRelease
\end{DoxyVerb}
\hypertarget{building-ogre_autotoc_md254}{}\doxysubsection{Building for Web\+Assembly (using Emscripten)}\label{building-ogre_autotoc_md254}
Install the Emscripten S\+DK (see full documentation on \href{https://emscripten.org/docs/getting_started/downloads.html}{\texttt{ www.\+emscripten.\+org}}), and make sure that the environment variables are correctly set (eg. run source $<$emsdk\+\_\+path$>$/emsdk\+\_\+env.sh before attempting to build)

Run cmake in cross compile mode using emscripten as following\+: \begin{DoxyVerb}mkdir build-wasm
emcmake cmake .. -DCMAKE_BUILD_TYPE=Release
emmake make
\end{DoxyVerb}


NB\+: to simplify the process, \textquotesingle{}emcmake\textquotesingle{} and \textquotesingle{}emmake\textquotesingle{} wrappers are used. These tools are provided by Emscripten to correctly setup the cross compilation environment

This will not build the full Sample\+Browser, but just a minimal Sample. The resulting {\ttfamily Emscripten\+Sample.\+html} will be placed in {\ttfamily \$\{C\+M\+A\+K\+E\+\_\+\+B\+I\+N\+A\+R\+Y\+\_\+\+D\+IR\}/bin/}.

To prevent any cross-\/origin issues, start a local webserver as {\ttfamily python3 -\/m http.\+server 8000} and visit \href{http://localhost:8000}{\texttt{ http\+://localhost\+:8000}}.\hypertarget{building-ogre_autotoc_md255}{}\doxysubsection{Building on Mac O\+S X for i\+O\+S OS}\label{building-ogre_autotoc_md255}
To build \mbox{\hyperlink{namespace_ogre}{Ogre}} for i\+OS, you need to specify the ios cross toolchain to cmake as \begin{DoxyVerb}cmake -DCMAKE_TOOLCHAIN_FILE=CMake/toolchain/ios.toolchain.xcode.cmake -G Xcode .
\end{DoxyVerb}


Unfortunately, you will now have to do a few manual steps to make the generated build system work properly.

A Xcode project has now been generated in the build directory, so to start the \mbox{\hyperlink{namespace_ogre}{Ogre}} build, open O\+G\+R\+E.\+xcodeproj and build as usual. To run samples on your device you will need to have a valid i\+OS Developer certificate installed. For each sample, double click on target in the Groups \& Files list. Ensure that a valid identity is selected in the Code Signing Identity drop menu. Also, because we can\textquotesingle{}t tell C\+Make what Xcode project format you want, you will have to change it yourself. Open the Project Menu, choose Edit Project Settings. Click on the General tab in the settings window. Change Project Format to Xcode 3.\+1-\/compatible. And another thing. You will need to manually set the Bundle Identifier property of the Info.\+plist file to match the App ID of the chosen code signing identity. This can be done from the Target Properties panel. It must match the bundle identifier of a valid developer certificate if you are building for devices.\hypertarget{building-ogre_autotoc_md256}{}\doxysubsection{Building as Windows Store or Windows Phone application}\label{building-ogre_autotoc_md256}
You need Windows 8.\+0 or later, Windows 10 is recommended.

You need Visual Studio 2012 or later, Visual Studio 2015 is recommended as it is bundled with Universal 10.\+0.\+240.\+0, Win\+Store 8.\+0/8.1 and Win\+Phone 8.\+0/8.1 S\+D\+Ks.

Download and install C\+Make 3.\+4 or later.

Patched dependencies must be used, compiled with appropriate W\+I\+N\+A\+P\+I\+\_\+\+F\+A\+M\+I\+LY. Cg is not supported. You can use \href{https://bitbucket.org/eugene_gff/ogre-dependencies-winrt}{\texttt{ https\+://bitbucket.\+org/eugene\+\_\+gff/ogre-\/dependencies-\/winrt}} -\/ has V\+S2012 and V\+S2013 projects for Win32, Win\+RT (can be reused for Win\+Phone) Compile dependencies for all configurations that you plan to use before running C\+Make. Dependencies for Win32 and for Win\+RT must be located in separate folders, Win32 version can be built from Ogre\+Dependencies.\+V\+S201x.\+sln, Win\+RT from Ogre\+Dependencies.\+V\+S201x.\+Win\+R\+T.\+sln

Run C\+Make, specify source and binaries folders, than \char`\"{}\+Configure\char`\"{}, select \char`\"{}\+Visual Studio 14 2015\char`\"{} generator and \char`\"{}\+Specify options for cross-\/compiling\char`\"{} option, specify Operating System = \char`\"{}\+Windows\+Store\char`\"{} or \char`\"{}\+Windows\+Phone\char`\"{}, Version = \char`\"{}8.\+0\char`\"{}, \char`\"{}8.\+1\char`\"{} or for U\+AP Operating System = \char`\"{}\+Windows\+Store\char`\"{}, Version = \char`\"{}10.\+0.\+10240.\+0\char`\"{}, \char`\"{}10.\+0.\+10586.\+0\char`\"{} then \char`\"{}\+Finish\char`\"{}, specify Win\+RT dependencies folder for O\+G\+R\+E\+\_\+\+D\+E\+P\+E\+N\+D\+E\+N\+C\+I\+E\+S\+\_\+\+D\+IR, \char`\"{}\+Configure\char`\"{}, should be no more errors, then press \char`\"{}\+Generate\char`\"{}.

Select Sample\+Browser as the start up project and run.\hypertarget{building-ogre_autotoc_md257}{}\doxysubsubsection{Notes}\label{building-ogre_autotoc_md257}

\begin{DoxyEnumerate}
\item The code and generated C\+Make solution should be on local N\+T\+FS drive, and can\textquotesingle{}t be on a network drive, including V\+M\+Ware shared folders -\/ or you will get a errors when you will try to compile/link/run resulting exe.
\item \mbox{\hyperlink{namespace_ogre}{Ogre}} uses d3dcompiler\+\_\+xx.\+dll to compile shaders, and Win\+Store and Win\+Phone 8.\+1 projects can use it without restriction as it is part of OS. But Win\+Store and Win\+Phone 8.\+0 applications should load already compiled shaders from cache, as d3dcompiler\+\_\+xx.\+dll is available to them only during development. Therefore to avoid necessity to deploy d3dcompiler\+\_\+xx.\+dll during development (additional configurations with d3dcompiler\+\_\+xx.\+dll) and generation of such cache -\/ use version 8.\+1 of these platforms.
\item Running Win\+Phone emulator in OS running under V\+Mware\+: We were able to run the emulation and debug without an issue by using two steps\+: (a) Under the settings of the VM $>$ C\+PU, make sure you have the option to pass-\/through the Intel V\+T-\/x/\+E\+PT feature, (b) Edit the config file .vmx and add the parameter\+: hypervisor.\+cpuid.\+v0 = \char`\"{}\+F\+A\+L\+S\+E\char`\"{} All versions of Visual Studio 2012 have a window refresh issue when running in V\+Mware and the window is maximized, the solution is just to change the size of the Visual Studio window to be less the the screen width and height. 
\end{DoxyEnumerate}\hypertarget{setup}{}\doxysection{Setting up an O\+G\+RE project}\label{setup}
\begin{DoxyNote}{Note}
see \mbox{\hyperlink{building-ogre}{Guide to building O\+G\+RE}} for instructions how to build O\+G\+RE itself 
\end{DoxyNote}
\hypertarget{setup_cmake}{}\doxysubsection{C\+Make Configuration}\label{setup_cmake}
\mbox{\hyperlink{namespace_ogre}{Ogre}} uses C\+Make as its build system. It is recommended that you use it in your project as well. ~\newline
 Then all you need is to add the following lines to your project 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{\textcolor{comment}{\# specify which version and components you need}}
\DoxyCodeLine{find\_package(OGRE 1.11 REQUIRED COMPONENTS Bites RTShaderSystem)}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{comment}{\# copy resource.cfg next to our binaries where OGRE looks for it}}
\DoxyCodeLine{file(COPY \$\{OGRE\_CONFIG\_DIR\}/resources.cfg DESTINATION \$\{CMAKE\_CURRENT\_BINARY\_DIR\})}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{comment}{\# add the source files as usual}}
\DoxyCodeLine{add\_executable(0\_Bootstrap Bootstrap.cpp)}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{comment}{\# this also sets the includes and pulls third party dependencies}}
\DoxyCodeLine{target\_link\_libraries(0\_Bootstrap OgreBites OgreRTShaderSystem)}
\end{DoxyCodeInclude}
These settings already include any third party libraries the Components depends on (e.\+g. S\+DL) -\/ nothing more to do. Alternatively use {\ttfamily \$\{O\+G\+R\+E\+\_\+\+L\+I\+B\+R\+A\+R\+I\+ES\}} to link against all available O\+G\+RE components.

If you installed O\+G\+RE in a non-\/standard path, you will have to set {\ttfamily O\+G\+R\+E\+\_\+\+D\+IR} to the location of {\ttfamily O\+G\+R\+E\+Config.\+cmake} so {\ttfamily find\+\_\+package} can figure out the rest.

For inspecting the detected O\+G\+RE installation, the following C\+Make variables are available
\begin{DoxyItemize}
\item {\ttfamily O\+G\+R\+E\+\_\+\+S\+T\+A\+T\+IC} -\/ whether ogre was build as static lib
\item {\ttfamily O\+G\+R\+E\+\_\+\$\{C\+O\+M\+P\+O\+N\+E\+NT\}\+\_\+\+F\+O\+U\+ND} -\/ \$\{C\+O\+M\+P\+O\+N\+E\+NT\} is available
\item {\ttfamily O\+G\+R\+E\+\_\+\+P\+L\+U\+G\+I\+N\+\_\+\+D\+IR} -\/ The directory where the O\+G\+RE plugins are located
\item {\ttfamily O\+G\+R\+E\+\_\+\+M\+E\+D\+I\+A\+\_\+\+D\+IR} -\/ The directory where the O\+G\+RE sample media is located
\item {\ttfamily O\+G\+R\+E\+\_\+\+C\+O\+N\+F\+I\+G\+\_\+\+D\+IR} -\/ The directory where the O\+G\+RE config files are located
\end{DoxyItemize}\hypertarget{setup_skeleton}{}\doxysubsection{Application skeleton}\label{setup_skeleton}
The easiest way to get started is the \mbox{\hyperlink{namespace_ogre_bites}{Ogre\+Bites}} Component. It handles \mbox{\hyperlink{namespace_ogre}{Ogre}} startup/ tear down (including \mbox{\hyperlink{class_ogre_1_1_overlay}{Ogre\+::\+Overlay}}, \mbox{\hyperlink{rtss}{R\+T\+SS}}), input using S\+D\+L2 and even includes a \mbox{\hyperlink{trays}{Simple G\+UI System}}.

This is useful if all you want is to get a Scene with a F\+PS counter up and running (rapid prototyping). If available it also uses S\+D\+L2 for input -\/ you now just have to implement the callbacks.

To use it, simply derive from \mbox{\hyperlink{namespace_ogre_bites_a579bb62eef4503f5d9bc93c0fb613a6f}{Ogre\+Bites\+::\+Application\+Context}} and if you want to get input events from \mbox{\hyperlink{struct_ogre_bites_1_1_input_listener}{Ogre\+Bites\+::\+Input\+Listener}}


\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{keyword}{class }MyTestApp : \textcolor{keyword}{public} \mbox{\hyperlink{class_ogre_bites_1_1_application_context_base}{OgreBites::ApplicationContext}}, \textcolor{keyword}{public} \mbox{\hyperlink{struct_ogre_bites_1_1_input_listener}{OgreBites::InputListener}}}
\DoxyCodeLine{\{}
\DoxyCodeLine{    ...}
\DoxyCodeLine{\}}
\end{DoxyCode}
 in the constructor we set our application name. The ogre configuration files will be stored in a system dependant location specific to our app. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{MyTestApp::MyTestApp() : \mbox{\hyperlink{namespace_ogre_bites}{OgreBites}}::\mbox{\hyperlink{namespace_ogre_bites_a579bb62eef4503f5d9bc93c0fb613a6f}{ApplicationContext}}(\textcolor{stringliteral}{"OgreTutorialApp"})}
\DoxyCodeLine{\{}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}
 to handle input events, we then override the according method 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{\textcolor{keywordtype}{bool} MyTestApp::keyPressed(\textcolor{keyword}{const} \mbox{\hyperlink{struct_ogre_bites_1_1_keyboard_event}{OgreBites::KeyboardEvent}}\& evt)}
\DoxyCodeLine{\{}
\DoxyCodeLine{    \textcolor{keywordflow}{if} (evt.\mbox{\hyperlink{struct_ogre_bites_1_1_keyboard_event_a675789f0663c8e7c8ac38db339a98a60}{keysym}}.\mbox{\hyperlink{struct_ogre_bites_1_1_keysym_a0174848a10c2790beb05a3f21317a5c3}{sym}} == \mbox{\hyperlink{namespace_ogre_bites_aa3f92c9c582664d88fe3d488fb9b16e1a02467a4c39b543a4c53cbfd192837cfc}{OgreBites::SDLK\_ESCAPE}})}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        getRoot()-\/>queueEndRendering();}
\DoxyCodeLine{    \}}
\DoxyCodeLine{    \textcolor{keywordflow}{return} \textcolor{keyword}{true};}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}
 the interesting part however is the setup method 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{\textcolor{keywordtype}{void} MyTestApp::setup(\textcolor{keywordtype}{void})}
\DoxyCodeLine{\{}
\DoxyCodeLine{    \textcolor{comment}{// do not forget to call the base first}}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_bites_1_1_application_context_base_a2696046f826adc323b5ed166eba91558}{OgreBites::ApplicationContext::setup}}();}
\DoxyCodeLine{    }
\DoxyCodeLine{    \textcolor{comment}{// register for input events}}
\DoxyCodeLine{    addInputListener(\textcolor{keyword}{this});}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// get a pointer to the already created root}}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_root}{Ogre::Root}}* root = getRoot();}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_scene_manager}{Ogre::SceneManager}}* scnMgr = root-\/>\mbox{\hyperlink{class_ogre_1_1_root_a8bb8655f823a98007775f69278c1b0f9}{createSceneManager}}();}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// register our scene with the RTSS}}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_r_t_shader_1_1_shader_generator}{Ogre::RTShader::ShaderGenerator}}* shadergen = \mbox{\hyperlink{class_ogre_1_1_r_t_shader_1_1_shader_generator_acd96bb2cad55be69d0fe8c6dc28d3590}{Ogre::RTShader::ShaderGenerator::getSingletonPtr}}();}
\DoxyCodeLine{    shadergen-\/>\mbox{\hyperlink{class_ogre_1_1_r_t_shader_1_1_shader_generator_a60704776c069e2a6bd37692f88c56815}{addSceneManager}}(scnMgr);}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// without light we would just get a black screen    }}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_light}{Ogre::Light}}* light = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}}(\textcolor{stringliteral}{"MainLight"});}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}}* lightNode = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    lightNode-\/>\mbox{\hyperlink{class_ogre_1_1_node_a72e58d4789cfe29e4538399b4250ce5a}{setPosition}}(0, 10, 15);}
\DoxyCodeLine{    lightNode-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(light);}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// also need to tell where we are}}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}}* camNode = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    camNode-\/>\mbox{\hyperlink{class_ogre_1_1_node_a72e58d4789cfe29e4538399b4250ce5a}{setPosition}}(0, 0, 15);}
\DoxyCodeLine{    camNode-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a665c4750906917dd061b141c03d432de}{lookAt}}(\mbox{\hyperlink{class_ogre_1_1_vector}{Ogre::Vector3}}(0, 0, -\/1), \mbox{\hyperlink{class_ogre_1_1_node_ac42e2063379286eb673eaffff6ca5e99a34e6c3ebabc2e9fa00de4f62be0ce7ce}{Ogre::Node::TS\_PARENT}});}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// create the camera}}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_camera}{Ogre::Camera}}* cam = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a62ca781b4c6d23dc3aab1f3a45d61843}{createCamera}}(\textcolor{stringliteral}{"myCam"});}
\DoxyCodeLine{    cam-\/>\mbox{\hyperlink{class_ogre_1_1_frustum_a7bc8b601d85642059f23e739fb4438bb}{setNearClipDistance}}(5); \textcolor{comment}{// specific to this sample}}
\DoxyCodeLine{    cam-\/>\mbox{\hyperlink{class_ogre_1_1_camera_aac250bb57c630543b8241bfc8eb8b88a}{setAutoAspectRatio}}(\textcolor{keyword}{true});}
\DoxyCodeLine{    camNode-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(cam);}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// and tell it to render into the main window}}
\DoxyCodeLine{    getRenderWindow()-\/>addViewport(cam);}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// finally something to render}}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_entity}{Ogre::Entity}}* ent = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}}(\textcolor{stringliteral}{"Sinbad.mesh"});}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}}* node = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    node-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(ent);}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}
\begin{DoxyNote}{Note}
The above code is explained in detail in \mbox{\hyperlink{tut_FirstScene}{Your First Scene}}.
\end{DoxyNote}
finally we start everything as 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{\textcolor{keywordtype}{int} main(\textcolor{keywordtype}{int} argc, \textcolor{keywordtype}{char} *argv[])}
\DoxyCodeLine{\{}
\DoxyCodeLine{    MyTestApp app;}
\DoxyCodeLine{    app.initApp();}
\DoxyCodeLine{    app.getRoot()-\/>startRendering();}
\DoxyCodeLine{    app.closeApp();}
\DoxyCodeLine{    \textcolor{keywordflow}{return} 0;}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}
\begin{DoxyNote}{Note}
You can find the full code of the above example at
\begin{DoxyItemize}
\item {\ttfamily Samples/\+Tutorials/\+Bootstrap.\+cpp} for C++
\item {\ttfamily Samples/\+Python/bites\+\_\+sample.\+py} for Python
\item {\ttfamily Samples/\+Android\+J\+N\+I/\+Main\+Activity.\+java} for Java (Android)
\end{DoxyItemize}
\end{DoxyNote}
\mbox{\hyperlink{namespace_ogre_bites}{Ogre\+Bites}} itself is also a good starting point if you need more control over the Camera or the Window creation. For instance to render into an existing Qt Window.

\begin{DoxySeeAlso}{See also}
\mbox{\hyperlink{class_ogre_1_1_file_system_layer_a7af51345a08a299fde4ec672b00ce9f8}{Ogre\+::\+File\+System\+Layer\+::get\+Config\+File\+Path}} 

\mbox{\hyperlink{class_ogre_1_1_root_aeaad25268c0ad8007ce8961a32242c77}{Ogre\+::\+Root\+::render\+One\+Frame}} 

\mbox{\hyperlink{class_ogre_1_1_render_system_aaf156b9f935396e6c17f532f6e6c847e}{Ogre\+::\+Render\+System\+::\+\_\+create\+Render\+Window}} 

\mbox{\hyperlink{class_ogre_1_1_render_system_a77766da49c29112c390fde51069f543a}{Ogre\+::\+Render\+System\+::pre\+Extra\+Threads\+Started}}
\end{DoxySeeAlso}
\hypertarget{setup_autotoc_md291}{}\doxysubsection{Running your App}\label{setup_autotoc_md291}
On Linux you will typically install O\+G\+RE into {\ttfamily /usr/local/} which is automatically searched by the linker, so nothing more to do. On Windows however, you will have to either add the {\ttfamily sdk/bin} folder to {\ttfamily P\+A\+TH} or copy your executable into {\ttfamily sdk/bin}. \hypertarget{tut_FirstScene}{}\doxysection{Your First Scene}\label{tut_FirstScene}
This first tutorial will cover the basic elements of building a scene in \mbox{\hyperlink{namespace_ogre}{Ogre}}. The primary focus will be the \mbox{\hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager}}, \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}}, and Entity(external link). An \mbox{\hyperlink{class_ogre_1_1_entity}{Ogre\+::\+Entity}} is anything represented by a mesh. A \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}} is what attaches an object to your scene. Finally, the Scene\+Manager is the object that organizes everything. It keeps track of the entities and nodes in your scene and determines how to display them.

We\textquotesingle{}ll start with an explanation of some of the basic concepts in \mbox{\hyperlink{namespace_ogre}{Ogre}}. Don\textquotesingle{}t worry, this first tutorial has a little more explanation than the rest, but that changes very quickly once you get to the later tutorials. We will be building plenty of things. We just have to lay a little groundwork first, so you have somewhere to stand.

The full source for this tutorial (Basic\+Tutorial1.\+cpp) can be found in samples directory {\bfseries{Samples/\+Tutorials}}.

\begin{DoxyNote}{Note}
Refer to \mbox{\hyperlink{setup}{Setting up an O\+G\+RE project}} for instructions how set up an \mbox{\hyperlink{namespace_ogre}{Ogre}} project and compile it successfully.
\end{DoxyNote}
\hypertarget{tut__first_scene_howogreworks}{}\doxysubsection{How Ogre Works}\label{tut__first_scene_howogreworks}
We are going to provide a quick introduction to the basic elements of an \mbox{\hyperlink{namespace_ogre}{Ogre}} scene.\hypertarget{tut__first_scene_scenemanager}{}\doxysubsubsection{Scene\+Manager}\label{tut__first_scene_scenemanager}
Everything that appears on the screen is managed by the Scene\+Manager. The Scene\+Manager keeps track of the locations and other attributes of the objects in your scene. The Scene\+Manager also manages any cameras that you add to your scene. There are multiples types of Scene\+Managers. There are managers focused on rendering terrain and other managers focused on rendering B\+SP maps. The different types of Scene\+Manager are listed \href{http://www.ogre3d.org/tikiwiki/tiki-index.php?page=SceneManagersFAQ}{\texttt{ here}}.\hypertarget{tut__first_scene_SceneNode}{}\doxysubsubsection{Scene\+Node}\label{tut__first_scene_SceneNode}
Scene\+Nodes carry information that is used for all of the objects that are attached to it. An Entity is not rendered in your scene until it is attached to a Scene\+Node. In addition, a Scene\+Node is not a visible object in your scene. It only holds abstract information like location and orientation. Only when it is connected to something like an Entity is that information used to actually render something in the scene.

Scene\+Nodes can have more than one object attached to them. We may want to have a light that will follow a character around in a scene. To do this, we could attach both the character Entity and the light to the same Scene\+Node. This will cause them both to share the same location information. We can even attach Scene\+Nodes to other Scene\+Nodes. This is useful in many circumstances. Imagine you have a character and you want to attach a tool to their hand. You wouldn\textquotesingle{}t want to attach the tool to Scene\+Node for the entire character. Instead, you could attach a Scene\+Node representing their hand to the character\textquotesingle{}s main Scene\+Node, and then attach the tool Entity to that \char`\"{}child\char`\"{} Scene\+Node. more complicated uses of Scene\+Nodes will be covered in later tutorials.

One final thing to keep in mind about Scene\+Nodes is that their position is relative to their parent Scene\+Node and each Scene\+Manager creates a root Node to which all other Scene\+Nodes are attached.\hypertarget{tut__first_scene_Entity}{}\doxysubsubsection{Entity}\label{tut__first_scene_Entity}
An Entity is one type of object that you can render in your scene. It is anything that is represented by a 3D mesh. Even terrain objects are very large entities. Lights, Billboards, Particles, and Cameras are examples of scene elements that are not entities. \mbox{\hyperlink{namespace_ogre}{Ogre}} uses a well-\/known design pattern that separates renderable objects from information like their location. This means that you don\textquotesingle{}t directly place an Entity into your scene. Instead, you place a Scene\+Node into your scene, then attach your Entity to that Scene\+Node. The Entity is then rendered using information taken from the Scene\+Node.\hypertarget{tut__first_scene_SettingUptheScene}{}\doxysubsection{Setting Up the Scene}\label{tut__first_scene_SettingUptheScene}
It\textquotesingle{}s finally time to start building something in our scene. All source addition will be in \char`\"{}tutorial section\char`\"{} in cpp file of the tutorial Tutorial\+Application\+::setup method.

The first thing we want to do is turn on the lights.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a7c26cdbb5703cf10a99add1f6a930ca2}{setAmbientLight}}(ColourValue(0.5, 0.5, 0.5));}
\end{DoxyCodeInclude}
 The set\+Ambient\+Light method takes an \mbox{\hyperlink{class_ogre_1_1_colour_value}{Ogre\+::\+Colour\+Value}}. The three values represent the red, green, and blue values of the colour, and they range between 0 and 1.

scn\+Mgr is a variable that is defined in \mbox{\hyperlink{namespace_ogre_bites_a579bb62eef4503f5d9bc93c0fb613a6f}{Ogre\+Bites\+::\+Application\+Context}}. There are a number of features avariables, like setting up resources and initialization of required routines for rendering. They will be introduced as we need them.

Lights will be covered in detail in the next tutorial, but we will still add a simple one to this scene as a teaser. New Light objects can also be requested from the \mbox{\hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager}}. We give the Light a unique name when it is created.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Light* light = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}}(\textcolor{stringliteral}{"MainLight"});}
\DoxyCodeLine{    SceneNode* lightNode = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    lightNode-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(light);}
\end{DoxyCodeInclude}
 Starting from \mbox{\hyperlink{namespace_ogre}{Ogre}} 1.\+10 camera and lights require to create separate scene node for them so that they need to be attached to them.

Once the Light is created and attached to its Scene\+Node, we set its position. The three parameters are the x, y, and z coordinates of the location we want to place the Light.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    lightNode-\/>setPosition(20, 80, 50);}
\end{DoxyCodeInclude}
 Next step is to create a camera.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    SceneNode* camNode = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// create the camera}}
\DoxyCodeLine{    Camera* cam = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a62ca781b4c6d23dc3aab1f3a45d61843}{createCamera}}(\textcolor{stringliteral}{"myCam"});}
\DoxyCodeLine{    cam-\/>\mbox{\hyperlink{class_ogre_1_1_frustum_a7bc8b601d85642059f23e739fb4438bb}{setNearClipDistance}}(5); \textcolor{comment}{// specific to this sample}}
\DoxyCodeLine{    cam-\/>setAutoAspectRatio(\textcolor{keyword}{true});}
\DoxyCodeLine{    camNode-\/>attachObject(cam);}
\DoxyCodeLine{    camNode-\/>setPosition(0, 0, 140);}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// and tell it to render into the main window}}
\DoxyCodeLine{    getRenderWindow()-\/>addViewport(cam);}
\end{DoxyCodeInclude}
 Details about camera will be covered in the following tutorial.

The next thing we do is ask the Scene\+Manager to create an Entity.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Entity* ogreEntity = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}}(\textcolor{stringliteral}{"ogrehead.mesh"});}
\end{DoxyCodeInclude}
 The parameter given to this function must be a mesh that was loaded by \mbox{\hyperlink{namespace_ogre}{Ogre}}\textquotesingle{}s resource manager. For now, resource loading is one of the many things that \mbox{\hyperlink{namespace_ogre_bites_a579bb62eef4503f5d9bc93c0fb613a6f}{Ogre\+Bites\+::\+Application\+Context}} is taking care of for us. It will be explained further in later tutorials.

Now that we have an Entity, we need to create a Scene\+Node so the Entity can be displayed in our scene. Every Scene\+Manager has a root node. That node has a method called create\+Child\+Scene\+Node that will return a new Scene\+Node attached to the root. In older versions of \mbox{\hyperlink{namespace_ogre}{Ogre}}, you were required to provide a unique name for your Entities and Scene\+Nodes. This is now optional. \mbox{\hyperlink{namespace_ogre}{Ogre}} will generate names for them if you do not provide one.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    SceneNode* ogreNode = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\end{DoxyCodeInclude}
 We save the Scene\+Node pointer that is returned by the method so that we can attach our Entity to it.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    ogreNode-\/>attachObject(ogreEntity);}
\end{DoxyCodeInclude}
 We now have a basic scene set up. Compile and run your application. You should see an \mbox{\hyperlink{namespace_ogre}{Ogre}}\textquotesingle{}s head on your screen. This is only the beginning...

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt1_first_run.png}}
\end{DoxyImageNoCaption}
  \hypertarget{tut__first_scene_CoordinatesSystems}{}\doxysubsection{Coordinates Systems}\label{tut__first_scene_CoordinatesSystems}
Before we go on, let\textquotesingle{}s cover some basics of \mbox{\hyperlink{namespace_ogre}{Ogre}}\textquotesingle{}s coordinate system. \mbox{\hyperlink{namespace_ogre}{Ogre}}, like many other graphics engines, uses the x-\/z plane as the \char`\"{}floor\char`\"{} in a scene. This means that the y-\/axis is the vertical axis to ensure \mbox{\hyperlink{namespace_ogre}{Ogre}} is using a \href{http://mathworld.wolfram.com/Right-HandedCoordinateSystem.html}{\texttt{ right-\/handed coordinate system}}

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt1_display1921.png}}
\end{DoxyImageNoCaption}
  

The x-\/axis starts with negative values to the left and increases to the right (passing through zero at the origin). The z-\/axis runs forwards and backwards. The positive direction of the z-\/axis points \char`\"{}out of the screen\char`\"{}. So if a character walks towards the screen, then its z value will be increasing. Finally, the y-\/axis runs from the bottom to the top. Values that are \char`\"{}below ground\char`\"{} are negative. Don\textquotesingle{}t take these terms in parenthesis literally. You can put the ground wherever you want. It is just to help you orient yourself in the scene.

When you run your application, notice how your \mbox{\hyperlink{namespace_ogre}{Ogre}} head is facing towards the camera down the positive z-\/axis. This is a property of the mesh itself and the orientation of the camera. Cameras are covered in a later tutorial. The \mbox{\hyperlink{namespace_ogre}{Ogre}} head is sitting at the origin of our world, (0, 0, 0). The direction the head is facing by default is a result of which way it was facing when it was originally modeled. You can effectively change this from within \mbox{\hyperlink{namespace_ogre}{Ogre}} as well, but it will require some knowledge of quaternions, which aren\textquotesingle{}t really covered until the \href{\#}{\texttt{ Intermediate Tutorials}}.

\mbox{\hyperlink{namespace_ogre}{Ogre}} uses a vector class to represent positions and directions. There are vectors defined for 2-\/4 dimensions. They are called \mbox{\hyperlink{namespace_ogre_a8542e5da4c0e0bda0d0bf5745329ea88}{Ogre\+::\+Vector2}}, \mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Ogre\+::\+Vector3}}, and \mbox{\hyperlink{namespace_ogre_a739a289a4d5235f5f509a1795f5ffd5b}{Ogre\+::\+Vector4}} -\/ Vector3 being the most commonly used by far. If you are not familiar with the concept of vectors it is highly recommended to learn a little before attempting these tutorials. Even though \mbox{\hyperlink{namespace_ogre}{Ogre}} is an abstraction over many of the complications involved with Open\+GL and DirectX, there is still no escaping some mathematical concepts. Vectors and basic linear algebra will be some of the most useful things you can learn if you intend to proceed with 3D rendering. This \href{http://www.wildbunny.co.uk/blog/vector-maths-a-primer-for-games-programmers/}{\texttt{ site}} has produced a nice primer on vectors focused on game programmers.\hypertarget{tut__first_scene_AddingAnotherEntity}{}\doxysubsection{Adding Another Entity}\label{tut__first_scene_AddingAnotherEntity}
It\textquotesingle{}s time to get back to the coding. With our first Entity, we did not specify the location we wanted anywhere. Many of the functions in \mbox{\hyperlink{namespace_ogre}{Ogre}} have default parameters. The Scene\+Node\+::create\+Child\+Scene\+Node(external link) method can take three parameters, but we called it with none. The parameters are the name, position, and rotation of the Scene\+Node being created. We\textquotesingle{}ve already mentioned that \mbox{\hyperlink{namespace_ogre}{Ogre}} generates a unique name for us. It also uses (0, 0, 0) as a default position.

First, let\textquotesingle{}s move the camera so we can fit more Entities on screen. Place this call right after you set the ambient light in create\+Scene\+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    camNode-\/>setPosition(0, 47, 222);}
\end{DoxyCodeInclude}
 Now, let\textquotesingle{}s create another Entity and Scene\+Node, but this time we\textquotesingle{}ll give it a new position.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Entity* ogreEntity2 = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}}(\textcolor{stringliteral}{"ogrehead.mesh"});}
\DoxyCodeLine{    SceneNode* ogreNode2 = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}(\mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(84, 48, 0));}
\DoxyCodeLine{    ogreNode2-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(ogreEntity2);}
\end{DoxyCodeInclude}
 This is the same thing we did the first time, except we are now providing a Vector3 to our create\+Child\+Scene\+Node method. This will override the default position. Remember, the Scene\+Node\textquotesingle{}s position is always relative to its parent. In this case, the parent Scene\+Node is the root Scene\+Node, which is positioned at (0, 0, 0) by default.

Compile and run your application. Your \mbox{\hyperlink{namespace_ogre}{Ogre}} head should have a buddy.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt1_added_entity.png}}
\end{DoxyImageNoCaption}
  \hypertarget{tut__first_scene_MoreAboutEntities}{}\doxysubsection{More About Entities}\label{tut__first_scene_MoreAboutEntities}
The \mbox{\hyperlink{class_ogre_1_1_entity}{Ogre\+::\+Entity}} class is very extensive. We will now introduce just a few more of its methods that will be useful. The Entity class has set\+Visible and is\+Visible methods. If you want an Entity to be hidden, but you still need it later, then you can use this function instead of destroying the Entity and rebuilding it later.

\begin{DoxyNote}{Note}
Entities do not need to be pooled like they are in some graphics engines. Only one copy of each mesh and texture is ever loaded into memory, so there is not a big savings from trying to minimize the number of Entities.
\end{DoxyNote}
The get\+Name method returns the name of an Entity, and the get\+Parent\+Scene\+Node method returns the Scene\+Node that the Entity is attached to. In our case, this would be the root Scene\+Node.\hypertarget{tut__first_scene_MoreAboutSceneNodes}{}\doxysubsection{More About Scene\+Nodes}\label{tut__first_scene_MoreAboutSceneNodes}
The \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}} class is very complex. For now, we will only cover some of the most useful methods.

You can set the position after creating the node with set\+Position. This is still relative to its parent node. You can move an objective relative to its current position by using translate.

Scene\+Nodes are used to set a lot more than just position. They also manage the scale and rotation of objects. You can set the scale of an object with set\+Scale. And you can use yaw, pitch, and roll to set the object\textquotesingle{}s orientation. You can use reset\+Rotation to return the object to its default orientation. Finally, you can use rotate to perform more complicated rotations. This will again involve the use of quaternions, which will not be covered until the \href{\#}{\texttt{ Intermediate Tutorials}}.

We\textquotesingle{}ve already used the attach\+Object method of a Scene\+Node. There are few more methods that are useful for dealing with the objects that are attached to a Scene\+Node. You can use num\+Attached\+Objects to return the number of children attached to your node. You can use one of the many versions of \mbox{\hyperlink{class_ogre_1_1_scene_node_a2ff8d20961b48225690e1561bc39f993}{Ogre\+::\+Scene\+Node\+::get\+Attached\+Object}} to retrieve one of the Scene\+Node\textquotesingle{}s children. The method detach\+Object can be used to remove a specific child node, and detach\+All\+Objects can be used to remove all.

Since the position of a child node is relative to its parent, it makes it very easy to move large groups of nodes together. For example, if we changed this line\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}}* ogreNode2 = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}(\mbox{\hyperlink{class_ogre_1_1_vector}{Ogre::Vector3}}(84, 48, 0));}
\end{DoxyCode}


To this\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}}* ogreNode2 = ogreNode-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}(\mbox{\hyperlink{class_ogre_1_1_vector}{Ogre::Vector3}}(84, 48, 0));}
\end{DoxyCode}


Then our new node would be parented directly to the Scene\+Node for our first Entity. This would mean that moving ogre\+Node would also move ogre\+Node2. It would also mean that the position of ogre\+Node2 would be relative to ogre\+Node.

If you\textquotesingle{}re having trouble with the idea of a relative location, then maybe an example will help. Let\textquotesingle{}s say we put our first node, ogre\+Node, at (10, 10, 10) and attach ogre\+Node2 directly to ogre\+Node. Then we set the position of ogre\+Node2 to be (-\/10, -\/10, -\/10). To figure out where ogre\+Node2 will be displayed we add its position to the position of its parent.


\begin{DoxyCode}{0}
\DoxyCodeLine{(10, 10, 10) + (-\/10, -\/10, -\/10) = (0, 0, 0)}
\DoxyCodeLine{  ogreNode        ogreNode2}
\DoxyCodeLine{   parent           child}
\end{DoxyCode}


So this means that ogre\+Node2 would actually be placed at (0, 0, 0) in our world, even though we set its position to (-\/10, -\/10, -\/10). If we detached this node and reattached it to the root Scene\+Node, then it would really be displayed at (-\/10, -\/10, -\/10), because\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{(0, 0, 0) + (-\/10, -\/10, -\/10) = (-\/10, -\/10, -\/10)}
\DoxyCodeLine{   root        ogreNode2}
\DoxyCodeLine{  parent         child}
\end{DoxyCode}


Take a few seconds to soak this in. Relativity is hard. That\textquotesingle{}s why it took an Einstein to really figure it out.

Lastly, you can get a Scene\+Node or Entity by its name (if you gave it one), by calling get\+Scene\+Node or get\+Entity, which are \mbox{\hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager}} methods. This way you don\textquotesingle{}t have to keep a pointer to all of your Scene\+Nodes. You should generally only define pointers for nodes you will use often.\hypertarget{tut__first_scene_ChangingAnEntitysScale}{}\doxysubsection{Changing An Entity\textquotesingle{}s Scale}\label{tut__first_scene_ChangingAnEntitysScale}
We can set the scale of an Entity by calling set\+Scale. This method allows us to provide a scale factor for each dimension. Let\textquotesingle{}s add another \mbox{\hyperlink{namespace_ogre}{Ogre}} head and give it a different scale for demonstration. We will also position it so it fits well on the screen.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Entity* ogreEntity3 = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}}(\textcolor{stringliteral}{"ogrehead.mesh"});}
\DoxyCodeLine{    SceneNode* ogreNode3 = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    ogreNode3-\/>\mbox{\hyperlink{class_ogre_1_1_node_a72e58d4789cfe29e4538399b4250ce5a}{setPosition}}(0, 104, 0);}
\DoxyCodeLine{    ogreNode3-\/>setScale(2, 1.2, 1);}
\DoxyCodeLine{    ogreNode3-\/>attachObject(ogreEntity3);}
\end{DoxyCodeInclude}
 Compile and run your application. You should see a fat \mbox{\hyperlink{namespace_ogre}{Ogre}} head up top.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt_1scaled_entity.png}}
\end{DoxyImageNoCaption}
  \hypertarget{tut__first_scene_RotatingAnEntity}{}\doxysubsection{Rotating An Entity}\label{tut__first_scene_RotatingAnEntity}
An Entity\textquotesingle{}s rotation can be changed using the yaw, pitch, and roll methods.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{tiki-download_file_rotation_axis.png}}
\end{DoxyImageNoCaption}
  

These methods will take either an \mbox{\hyperlink{class_ogre_1_1_degree}{Ogre\+::\+Degree}} or \mbox{\hyperlink{class_ogre_1_1_radian}{Ogre\+::\+Radian}}. As the picture demonstrates, rotation around the y-\/axis is called yaw, around the x-\/axis is called pitch, and around the z-\/axis is called roll. These are terms often used in describing the movements of an aircraft.

There is a well-\/known trick for remembering which direction is a positive rotation around an axis. It is called the \href{http://en.wikipedia.org/wiki/Right-hand_rule}{\texttt{ right-\/hand rule}}. Point your thumb in the direction of the axis, and the direction your fingers curl towards is the positive direction. You can now see why these are often called \char`\"{}right-\/handed coordinate systems\char`\"{}. There are about a million ways of doing the right-\/hand rule. This is why you might see a group of physics students throwing gang signs while doing their homework. They\textquotesingle{}re trying to remember which direction the magnetic field is headed.

Let\textquotesingle{}s put this to use and place a rotated Entity into our scene. We will also position it nicely.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Entity* ogreEntity4 = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}}(\textcolor{stringliteral}{"ogrehead.mesh"});}
\DoxyCodeLine{    SceneNode* ogreNode4 = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    ogreNode4-\/>\mbox{\hyperlink{class_ogre_1_1_node_a72e58d4789cfe29e4538399b4250ce5a}{setPosition}}(-\/84, 48, 0);}
\DoxyCodeLine{    ogreNode4-\/>roll(Degree(-\/90));}
\DoxyCodeLine{    ogreNode4-\/>attachObject(ogreEntity4);}
\end{DoxyCodeInclude}
 Compile and run your application. We should now have a rotated \mbox{\hyperlink{namespace_ogre}{Ogre}} head in our scene.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt1_rotated_entity.png}}
\end{DoxyImageNoCaption}
  \hypertarget{tut__first_scene_TheOgreEnvironment}{}\doxysubsection{The Ogre Environment}\label{tut__first_scene_TheOgreEnvironment}
The library and configuration files for \mbox{\hyperlink{namespace_ogre}{Ogre}} can be found in the \textquotesingle{}bin\textquotesingle{} folder of your Ogre\+S\+DK. You should use the debug files when building your application in debug mod\hypertarget{tut__first_scene_LibrariesandPlugins}{}\doxysubsubsection{Libraries and Plugins}\label{tut__first_scene_LibrariesandPlugins}
\mbox{\hyperlink{namespace_ogre}{Ogre}} is divided into three shared library groups\+: main library, plugins, and third-\/party libraries.\hypertarget{tut__first_scene_autotoc_md310}{}\doxyparagraph{Main library}\label{tut__first_scene_autotoc_md310}
The main library group contains the \mbox{\hyperlink{namespace_ogre}{Ogre}} library itself and the shared libraries it relies on. The \mbox{\hyperlink{namespace_ogre}{Ogre}} library is contained within {\ttfamily Ogre\+Main.\+dll} or {\ttfamily lib\+Ogre\+Main.\+so} depending on your platform. This library must be included in all of your \mbox{\hyperlink{namespace_ogre}{Ogre}} applications. Ogre\+Main only depends on {\ttfamily libz} and {\ttfamily libzzip}.\hypertarget{tut__first_scene_autotoc_md311}{}\doxyparagraph{Plugins}\label{tut__first_scene_autotoc_md311}
The second group of shared libraries are the plugins. \mbox{\hyperlink{namespace_ogre}{Ogre}} pushes a good portion of its functionality into shared libraries so that they may be turned on or off easily. The core plugins that are included with \mbox{\hyperlink{namespace_ogre}{Ogre}} have names that start with \char`\"{}\+Plugin\+\_\+\char`\"{} and \char`\"{}\+Codec\+\_\+\char`\"{}. You can also write your own plugins.

\mbox{\hyperlink{namespace_ogre}{Ogre}} also uses plugins for the different render systems (such as Open\+GL, DirectX, etc). These plugins start with \char`\"{}\+Render\+System\+\_\+\char`\"{}. This is also so that you can add only the systems you will need. This can be useful if you write shaders that rely on a particular system, because you can simply remove the incompatible system so that the program won\textquotesingle{}t try to run incorrect code. This also means you can write your own plugins if you want to extend \mbox{\hyperlink{namespace_ogre}{Ogre}} into another render system.\hypertarget{tut__first_scene_autotoc_md312}{}\doxyparagraph{Third-\/party Plugins}\label{tut__first_scene_autotoc_md312}
The last major group contains third-\/party libraries and other general support libraries. \mbox{\hyperlink{namespace_ogre}{Ogre}} is focused sharply on being a graphics rendering library. This group makes it easy to integrate external libraries to add things like physics, input, and G\+UI systems. These libraries are used together to form a full game development environment. You might find this piecemeal approach a little strange, but it is a very common design pattern in large software projects. It is harder to comprehend at first, but it is a much more flexible approach when you want to start building more complicated scenes.

The \mbox{\hyperlink{namespace_ogre}{Ogre}} demos and S\+DK include some of these third-\/party libraries. The \href{https://www.libsdl.org/}{\texttt{ Simple Direct\+Media}} can be used to manage input events and distribute them to \mbox{\hyperlink{namespace_ogre}{Ogre}}. You can also make use of Cg, which is used by Cg\+Program\+Manager. This library allows you to produce materials with custom shaders. There are other libraries (not included with \mbox{\hyperlink{namespace_ogre}{Ogre}}) that offer functionality such as sound and physics.\hypertarget{tut__first_scene_autotoc_md313}{}\doxyparagraph{Testing vs Release}\label{tut__first_scene_autotoc_md313}
When you\textquotesingle{}re building your application you can just leave every plugin activated. This will allow you to experiment with using them or not. But when you get ready to distribute a release build of your work, then you will want to deactivate any of the plugins you are not using.\hypertarget{tut__first_scene_ConfigurationFiles}{}\doxysubsubsection{Configuration Files}\label{tut__first_scene_ConfigurationFiles}
\mbox{\hyperlink{namespace_ogre}{Ogre}} uses several configuration files ($\ast$.cfg). They control things like which plugins are loaded and where your application will search for resource files. We will briefly introduce you to each of these files. You\textquotesingle{}ll slowly read more about them as you progress through the tutorials as well.

You can place these files the same directory as your executable or in any of \mbox{\hyperlink{class_ogre_1_1_file_system_layer_a7af51345a08a299fde4ec672b00ce9f8}{the default lookup paths described here}}.\hypertarget{tut__first_scene_autotoc_md314}{}\doxyparagraph{plugins.\+cfg}\label{tut__first_scene_autotoc_md314}
This file tells \mbox{\hyperlink{namespace_ogre}{Ogre}} which plugins to load. You modify this file when you want to load a different set of plugins. It is often most useful to simply \char`\"{}comment out\char`\"{} lines instead of removing them, because you never know when a stroke of inspiration will mean you want to reload some unused plugins. Here is some sample content\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{\# Plugin=RenderSystem\_Direct3D9}
\DoxyCodeLine{\# Plugin=RenderSystem\_Direct3D10}
\DoxyCodeLine{\# Plugin=RenderSystem\_Direct3D11}
\DoxyCodeLine{Plugin=RenderSystem\_GL}
\end{DoxyCode}


We have the three DirectX systems commented out, and an active line for Open\+GL. On a windows system, you may have this reversed. You can see why it might be helpful not to delete unused lines, because then you have to try and remember whether it was Render\+System\+\_\+\+Open\+GL or Render\+System\+\_\+\+GL.

You can also decide where \mbox{\hyperlink{namespace_ogre}{Ogre}} looks for plugins by changing the \textquotesingle{}Plugin\+Folder\textquotesingle{} variable. You can use both absolute and relative paths, but you cannot use environment variables like . For example, if you have built \mbox{\hyperlink{namespace_ogre}{Ogre}} from source on a linux machine, then you will need a line like this at the beginning of your file\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{PluginFolder=/usr/local/lib/OGRE}
\end{DoxyCode}


By default, \mbox{\hyperlink{namespace_ogre}{Ogre}} would have been looking in \textquotesingle{}/usr/lib/\+O\+G\+RE\textquotesingle{}. This is where it would be placed if you installed \mbox{\hyperlink{namespace_ogre}{Ogre}} from a package manager. You may have to do something similar on Mac.\hypertarget{tut__first_scene_autotoc_md315}{}\doxyparagraph{resources.\+cfg}\label{tut__first_scene_autotoc_md315}
This file contains a list of the directories \mbox{\hyperlink{namespace_ogre}{Ogre}} will use to search for resources. Resources include scripts, meshes, textures, G\+UI layouts, and others. You can also use both absolute and relative paths in this file, but you still cannot use environment variables. \mbox{\hyperlink{namespace_ogre}{Ogre}} will {\bfseries{not}} search subdirectories, so you have to manually enter them. Here is an example\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{[General]}
\DoxyCodeLine{FileSystem=../media}
\DoxyCodeLine{FileSystem=../media/materials/scripts}
\DoxyCodeLine{FileSystem=../media/materials/textures}
\DoxyCodeLine{FileSystem=../media/models}
\end{DoxyCode}


Here is an example of a relative path being used and the need to list subdirectories. Including the \textquotesingle{}../media\textquotesingle{} directory did not automatically include the \textquotesingle{}../media/models\textquotesingle{} directory. This is so that \mbox{\hyperlink{namespace_ogre}{Ogre}} doesn\textquotesingle{}t get greedy and waste time loading up unneeded resources.\hypertarget{tut__first_scene_autotoc_md316}{}\doxyparagraph{ogre.\+cfg}\label{tut__first_scene_autotoc_md316}
This file is generated by the Render Settings dialog that appears when you run your application. {\bfseries{Do not}} distribute this file with your application. This file will be specific to your own setup. This file will contain your choices for things like screen resolution. Do not modify this file directly. Change the settings with the dialog and it will be automatically updated.

That covers all of the configuration files that \mbox{\hyperlink{namespace_ogre}{Ogre}} manipulates directly. \mbox{\hyperlink{namespace_ogre}{Ogre}} must find \textquotesingle{}plugins.\+cfg\textquotesingle{} and \textquotesingle{}resources.\+cfg\textquotesingle{} to function properly. Later tutorials will cover more of their use.\hypertarget{tut__first_scene_Conclusion1}{}\doxysubsection{Conclusion}\label{tut__first_scene_Conclusion1}
You should now have a basic understanding of setting up an \mbox{\hyperlink{namespace_ogre}{Ogre}} scene. This tutorial provided an introduction to three of the most important objects in \mbox{\hyperlink{namespace_ogre}{Ogre}}\+: \mbox{\hyperlink{class_ogre_1_1_entity}{Ogre\+::\+Entity}}, \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}}, and \mbox{\hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager}}. These objects allow us to render and manipulate a scene filled with 3D objects.

An \mbox{\hyperlink{class_ogre_1_1_entity}{Ogre\+::\+Entity}} represents anything that has an \mbox{\hyperlink{namespace_ogre}{Ogre}} mesh. A \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}} is used to hold properties like location, scale, and rotation. It is also the anchor that attaches your Entities to your scene and allows them to be rendered on screen. Finally, The \mbox{\hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager}} is the object that orchestrates it all. It has methods that allow you to create Entities and Scene\+Nodes and keep them organized within a complicated scene. \hypertarget{tut_LightsCamerasShadows}{}\doxysection{Lights, Cameras, and Shadows}\label{tut_LightsCamerasShadows}
This tutorial will expand on the use of Lights in a scene and using them to cast shadows.

The full source for this tutorial (Basic\+Tutorial2.\+cpp) can be found in samples directory {\bfseries{Samples/\+Tutorials}}.

\begin{DoxyNote}{Note}
Refer to \mbox{\hyperlink{setup}{Setting up an O\+G\+RE project}} for instructions how set up an \mbox{\hyperlink{namespace_ogre}{Ogre}} project and compile it successfully.
\end{DoxyNote}
\hypertarget{tut__lights_cameras_shadows_bt2TheOgreCameraClass}{}\doxysubsection{The Ogre Camera Class}\label{tut__lights_cameras_shadows_bt2TheOgreCameraClass}
A Camera is the object we use to view our scene. A \mbox{\hyperlink{class_ogre_1_1_camera}{Ogre\+::\+Camera}} is a special object that works similar to a \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}}. It has methods like set\+Position and yaw. You can also attach it to a Scene\+Node. For instance, you might want to temporarily attach your Camera to a Scene\+Node that follows a path through the sky to create an aerial cutscene. Just like a Scene\+Node the Camera\textquotesingle{}s position will be relative to its parent Scene\+Node. The Camera is not a Scene\+Node (it actually inherits from the Frustum class), but for movement and rotation, you can treat it like a Scene\+Node.

\begin{DoxyNote}{Note}
Starting from version 1.\+10 functionality related to rotate and translate camera are deprecated. You should attach camera to \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}} and do all transformation with this node.
\end{DoxyNote}
\hypertarget{tut__lights_cameras_shadows_bt2CreatingaCamera}{}\doxysubsection{Creating a Camera}\label{tut__lights_cameras_shadows_bt2CreatingaCamera}
We will now cover camera creation part which we just applied in previous tutorial. We remeber that now we need to have Scene\+Node for camera. The first step will be doing is creating that Scene\+Node and asking the Scene\+Manager to create a new Camera. Add the following to create Scene\+Node and Camera\+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    SceneNode* camNode = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    Camera* cam = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a62ca781b4c6d23dc3aab1f3a45d61843}{createCamera}}(\textcolor{stringliteral}{"myCam"});}
\end{DoxyCodeInclude}
You can retrieve the Camera by name using the Scene\+Manager\textquotesingle{}s get\+Camera method.

Next, we will position the Camera and use a method called look\+At to set its direction using cam\+Node. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    camNode-\/>setPosition(200, 300, 400);}
\DoxyCodeLine{    camNode-\/>lookAt(\mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(0, 0, 0), Node::TransformSpace::TS\_WORLD);}
\end{DoxyCodeInclude}
The \mbox{\hyperlink{class_ogre_1_1_scene_node_a665c4750906917dd061b141c03d432de}{Ogre\+::\+Scene\+Node\+::look\+At}} method is very useful. It does exactly what it says. It rotates the Scene\+Node so that its line of sight focuses on the vector you give it. It makes the Camera \char`\"{}look at\char`\"{} the point.

The last thing we\textquotesingle{}ll do (apart of attachning camera to a Scene\+Node) is set the near clipping distance to 5 units. This is the distance at which the Camera will no longer render any mesh. If you get very close to a mesh, this will sometimes cut the mesh and allow you to see inside of it. The alternative is filling the entire screen with a tiny, highly magnified piece of the mesh\textquotesingle{}s texture. It\textquotesingle{}s up to you what you want in your scene. For demonstration, we\textquotesingle{}ll set it here.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    cam-\/>setNearClipDistance(5);}
\DoxyCodeLine{    camNode-\/>attachObject(cam);}
\end{DoxyCodeInclude}
 \hypertarget{tut__lights_cameras_shadows_bt2Viewports}{}\doxysubsection{Viewports}\label{tut__lights_cameras_shadows_bt2Viewports}
When dealing with multiple Cameras in a scene, the concept of a Viewport becomes very useful. We will touch on it now, because it will help you understand more about how \mbox{\hyperlink{namespace_ogre}{Ogre}} decides which Camera to use when rendering a scene. \mbox{\hyperlink{namespace_ogre}{Ogre}} makes it possible to have multiple Scene\+Managers running at the same time. It also allows you to break up the screen and use separate Cameras to render different views of a scene. This would allow the creation of things like splitscreens and minimaps. These kinds of things will be covered in later tutorials.

There are three constructs that are crucial to understanding how \mbox{\hyperlink{namespace_ogre}{Ogre}} renders a scene\+: the Camera, the Scene\+Manager, and the Render\+Window. We have not yet covered the Render\+Window. It basically represents the whole window we are rendering to. The Scene\+Manager will create Cameras to view the scene, and then we tell the Render\+Window where to display each Camera\textquotesingle{}s view. The way we tell the Render\+Window which area of the screen to use is by giving it a \mbox{\hyperlink{class_ogre_1_1_viewport}{Ogre\+::\+Viewport}}. For many circumstances, we will simply create one Camera and create a Viewport which represents the whole screen.\hypertarget{tut__lights_cameras_shadows_bt2CreatingaViewport}{}\doxysubsection{Creating a Viewport}\label{tut__lights_cameras_shadows_bt2CreatingaViewport}
Let\textquotesingle{}s create a Viewport for our scene. To do this, we will use the add\+Viewport method of the Render\+Window. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Viewport* vp = getRenderWindow()-\/>addViewport(cam);}
\end{DoxyCodeInclude}
get\+Render\+Window() is a method defined for us in \mbox{\hyperlink{namespace_ogre_bites_a579bb62eef4503f5d9bc93c0fb613a6f}{Ogre\+Bites\+::\+Application\+Context}} which returns \mbox{\hyperlink{class_ogre_1_1_render_window}{Ogre\+::\+Render\+Window}}.

Now let\textquotesingle{}s set the background color of the Viewport. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    vp-\/>setBackgroundColour(ColourValue(0, 0, 0));}
\end{DoxyCodeInclude}
 We\textquotesingle{}ve set it to black because we are going to add colored lighting later, and we don\textquotesingle{}t want the background color affecting how we see the lighting.

The last thing we are going to do is set the aspect ratio of our Camera. If you are using something other than a standard full-\/window viewport, then failing to set this can result in a distorted scene. We will set it here for demonstration even though we are using the default aspect ratio.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    cam-\/>setAspectRatio(\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}}(vp-\/>getActualWidth()) / \mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}}(vp-\/>getActualHeight()));}
\end{DoxyCodeInclude}
 We have retrieved the width and height from the Viewport to set the aspect ratio. As we mentioned, the default is already set to use the full screen\textquotesingle{}s dimensions.

Compile and run your application. You should still only see a black screen, just make sure it runs.\hypertarget{tut__lights_cameras_shadows_bt2BuildingtheScene}{}\doxysubsection{Building the Scene}\label{tut__lights_cameras_shadows_bt2BuildingtheScene}
Before we get to shadows and lighting, let\textquotesingle{}s add some elements to our scene. Let\textquotesingle{}s put a ninja right in the middle of things. Add the following code right after we set the ambient light\+: 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Entity* ninjaEntity = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}}(\textcolor{stringliteral}{"ninja.mesh"});}
\DoxyCodeLine{    ninjaEntity-\/>\mbox{\hyperlink{class_ogre_1_1_movable_object_acbfc4840224e8b6ed6e27849d3341675}{setCastShadows}}(\textcolor{keyword}{true});}
\DoxyCodeLine{}
\DoxyCodeLine{    scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(ninjaEntity);}
\end{DoxyCodeInclude}
 This should look familiar, except we are asking the mesh to cast shadows this time. And notice that we have created a child scene node and attached the ninja\+Entity all in one call this time.

We will also create something for the ninja to be standing on. We can use the \mbox{\hyperlink{class_ogre_1_1_mesh_manager}{Ogre\+::\+Mesh\+Manager}} to create meshes from scratch. We will use it to generate a textured plane to use as the ground.

The first thing we\textquotesingle{}ll do is create an abstract Plane object. This is not the mesh, it is more of a blueprint. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Plane plane(Vector3::UNIT\_Y, 0);}
\end{DoxyCodeInclude}
 We create a plane by supplying a vector that is normal to our plane and its distance from the origin. So we have created a plane that is perpendicular to the y-\/axis and zero units from the origin. Here\textquotesingle{}s a picture\+:

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt2_plane_normal.png}}
\end{DoxyImageNoCaption}
  

There are other overloads of the Plane constructor that let us pass a second vector instead of a distance from the origin. This allows us to build any plane in 3D space we want.

Now we\textquotesingle{}ll ask the Mesh\+Manager to create us a mesh using our Plane blueprint. The Mesh\+Manager is already keeping track of the resources we loaded when initializing our application. On top of this, it can create new meshes for us.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    MeshManager::getSingleton().createPlane(}
\DoxyCodeLine{            \textcolor{stringliteral}{"ground"}, \mbox{\hyperlink{group___resources_gad0e16ff2458722373e3eea3b303e52da}{RGN\_DEFAULT}},}
\DoxyCodeLine{            plane,}
\DoxyCodeLine{            1500, 1500, 20, 20,}
\DoxyCodeLine{            \textcolor{keyword}{true},}
\DoxyCodeLine{            1, 5, 5,}
\DoxyCodeLine{            Vector3::UNIT\_Z);}
\end{DoxyCodeInclude}
This is a complicated method, and we\textquotesingle{}re not entirely equipped to understand all of it yet. You can read through the \mbox{\hyperlink{class_ogre_1_1_mesh_manager}{Ogre\+::\+Mesh\+Manager}} class specification if you want to learn more now. Basically, we\textquotesingle{}ve created a new mesh called \char`\"{}ground\char`\"{} with a size of 1500x1500.

Now we will create a new Entity using this mesh. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Entity* groundEntity = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}}(\textcolor{stringliteral}{"ground"});}
\DoxyCodeLine{    scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(groundEntity);}
\end{DoxyCodeInclude}
 Be careful that you don\textquotesingle{}t confuse the parameter given to create\+Entity for the Entity\textquotesingle{}s name. It is actually the name of the mesh we just created. We\textquotesingle{}re used to seeing mesh names end with \textquotesingle{}.mesh\textquotesingle{}.

We want to tell our Scene\+Manager not to cast shadows from our ground Entity. It would just be a waste. Don\textquotesingle{}t get confused, this means the ground won\textquotesingle{}t cast a shadow, it doesn\textquotesingle{}t mean we can\textquotesingle{}t cast shadows on to the {\itshape ground}. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    groundEntity-\/>setCastShadows(\textcolor{keyword}{false});}
\end{DoxyCodeInclude}
 And finally we need to give our ground a material. For now, it will be easiest to use a material from the script that \mbox{\hyperlink{namespace_ogre}{Ogre}} includes with its samples. You should have these resources in your S\+DK or the source directory you downloaded to build \mbox{\hyperlink{namespace_ogre}{Ogre}}. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    groundEntity-\/>setMaterialName(\textcolor{stringliteral}{"Examples/Rockwall"});}
\end{DoxyCodeInclude}
 Make sure you add the texture for the material and the Examples.\+material script to your resource loading path. In our case, the texture is called \textquotesingle{}rockwall.\+tga\textquotesingle{}. You can find the name yourself by reading the entry in the material script.\hypertarget{tut__lights_cameras_shadows_bt2UsingShadowsinOgre}{}\doxysubsection{Using Shadows in Ogre}\label{tut__lights_cameras_shadows_bt2UsingShadowsinOgre}
Enabling shadows in \mbox{\hyperlink{namespace_ogre}{Ogre}} is easy. The Scene\+Manager class has a \mbox{\hyperlink{class_ogre_1_1_scene_manager_ad716d3752418408f073d9be9bbfe62d0}{Ogre\+::\+Scene\+Manager\+::set\+Shadow\+Technique}} method we can use. Then whenever we create an Entity, we call set\+Cast\+Shadows to choose which Entities will cast shadows. set\+Shadow\+Techinique method takes several of different techniques. Refer to \mbox{\hyperlink{group___general_ga79dcd426d291c31072c1ad6f183715d6}{Ogre\+::\+Shadow\+Technique}} for more details.

Let\textquotesingle{}s turn off the ambient light so we can see the full effect of our lights. Add the following changes\+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a7c26cdbb5703cf10a99add1f6a930ca2}{setAmbientLight}}(ColourValue(0, 0, 0));}
\DoxyCodeLine{    scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_ad716d3752418408f073d9be9bbfe62d0}{setShadowTechnique}}(\mbox{\hyperlink{group___general_gga79dcd426d291c31072c1ad6f183715d6af1b698ef34b8d97c261b7ade00010b7f}{ShadowTechnique::SHADOWTYPE\_STENCIL\_MODULATIVE}});}
\end{DoxyCodeInclude}
 Now the Scene\+Manager will use modulative stencil shadows. Let\textquotesingle{}s add some lights to see this in action.\hypertarget{tut__lights_cameras_shadows_bt2Lights}{}\doxysubsection{Lights}\label{tut__lights_cameras_shadows_bt2Lights}
\mbox{\hyperlink{namespace_ogre}{Ogre}} provides three types of lighting.
\begin{DoxyItemize}
\item \mbox{\hyperlink{class_ogre_1_1_light_a4f1dea084d1497c6f49e802ade940dbca0d59bfdcfeb338dbfe06e2e2999e752f}{Ogre\+::\+Light\+::\+L\+T\+\_\+\+P\+O\+I\+NT}} -\/ This Light speads out equally in all directions from a point.
\item \mbox{\hyperlink{class_ogre_1_1_light_a4f1dea084d1497c6f49e802ade940dbca8fc40a1ccfb026944417ef92b7ddaefe}{Ogre\+::\+Light\+::\+L\+T\+\_\+\+S\+P\+O\+T\+L\+I\+G\+HT}} -\/ This Light works like a flashlight. It produces a solid cylinder of light that is brighter at the center and fades off.
\item \mbox{\hyperlink{class_ogre_1_1_light_a4f1dea084d1497c6f49e802ade940dbca4c5582d28848ce40c2b652488494b4a3}{Ogre\+::\+Light\+::\+L\+T\+\_\+\+D\+I\+R\+E\+C\+T\+I\+O\+N\+AL}} -\/ This Light simulates a huge source that is very far away -\/ like daylight. Light hits the entire scene at the same angle everywhere.
\end{DoxyItemize}

The \mbox{\hyperlink{class_ogre_1_1_light}{Ogre\+::\+Light}} class has a wide range of properties. Two of the most important are the \href{http://www.ogre3d.org/tikiwiki/tiki-index.php?page=-Diffuse+\%28Light\%29}{\texttt{ diffuse}} and \href{http://www.ogre3d.org/tikiwiki/tiki-index.php?page=-Specular+\%28Light\%29}{\texttt{ specular}} color. Each material script defines how much specular and diffuse lighting a material reflects. These properties will be covered in some of the later tutorials.\hypertarget{tut__lights_cameras_shadows_CreatingaLight}{}\doxysubsection{Creating a Light}\label{tut__lights_cameras_shadows_CreatingaLight}
Let\textquotesingle{}s add a Light to our scene. We do this by calling the \mbox{\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{Ogre\+::\+Scene\+Manager\+::create\+Light}} method. Add the following code right after we finish creating the ground\+Entity\+: 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Light* spotLight = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}}(\textcolor{stringliteral}{"SpotLight"});}
\end{DoxyCodeInclude}
 We\textquotesingle{}ll set the diffuse and specular colors to pure blue. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    spotLight-\/>setDiffuseColour(0, 0, 1.0);}
\DoxyCodeLine{    spotLight-\/>setSpecularColour(0, 0, 1.0);}
\end{DoxyCodeInclude}
 Next we will set the type of the light to spotlight.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    spotLight-\/>setType(Light::LT\_SPOTLIGHT);}
\end{DoxyCodeInclude}
 The spotlight requires both a position and a direction -\/ remember it acts like a flashlight. We\textquotesingle{}ll place the spotlight above the right shoulder of the ninja shining down on him at a 45 degree angle.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    SceneNode* spotLightNode = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    spotLightNode-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(spotLight);}
\DoxyCodeLine{    spotLightNode-\/>setDirection(-\/1, -\/1, 0);}
\DoxyCodeLine{    spotLightNode-\/>setPosition(\mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(200, 200, 0));}
\end{DoxyCodeInclude}
  
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt2_light_dir_1.png}}
\end{DoxyImageNoCaption}
  

Finally, we set what is called the spotlight range. These are the angles that determine where the light fades from bright in the middle to dimmer on the outside edges.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    spotLight-\/>setSpotlightRange(Degree(35), Degree(50));}
\end{DoxyCodeInclude}
Compile and run the application. You should see the shadowy blue figure of a ninja.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt2_ninja1.jpg}}
\end{DoxyImageNoCaption}
  \hypertarget{tut__lights_cameras_shadows_CreatingMoreLights}{}\doxysubsection{Creating More Lights}\label{tut__lights_cameras_shadows_CreatingMoreLights}
Next we\textquotesingle{}ll add a directional light to our scene. This type of light essentially simulates daylight or moonlight. The light is cast at the same angle across the entire scene equally. As before, we\textquotesingle{}ll start by creating the Light and setting its type.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Light* directionalLight = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}}(\textcolor{stringliteral}{"DirectionalLight"});}
\DoxyCodeLine{    directionalLight-\/>\mbox{\hyperlink{class_ogre_1_1_light_a6019f7fa89624e35316ba444e519d8f8}{setType}}(Light::LT\_DIRECTIONAL);}
\end{DoxyCodeInclude}
 Now we\textquotesingle{}ll set the diffuse and specular colors to a dark red. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    directionalLight-\/>setDiffuseColour(ColourValue(0.4, 0, 0));}
\DoxyCodeLine{    directionalLight-\/>setSpecularColour(ColourValue(0.4, 0, 0));}
\end{DoxyCodeInclude}
 Finally, we need to set the Light\textquotesingle{}s direction. A directional light does not have a position because it is modeled as a point light that is infinitely far away.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    SceneNode* directionalLightNode = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    directionalLightNode-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(directionalLight);}
\DoxyCodeLine{    directionalLightNode-\/>setDirection(\mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(0, -\/1, 1));}
\end{DoxyCodeInclude}
  
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt2_light_dir_2.png}}
\end{DoxyImageNoCaption}
  

The Light class also defines a \mbox{\hyperlink{class_ogre_1_1_light_a43f763d809bc7da9a85fec15f57380f4}{Ogre\+::\+Light\+::set\+Attenuation}} function which allows you to control how the light dissipates as you get farther away from it. After you finish this tutorial, try using this method in your scene to see how it affects your lights.

Compile and run the application. Your ninja should now have a shadow cast behind him, and the scene should be filled with red light.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt2_ninja2.jpg}}
\end{DoxyImageNoCaption}
  

To complete the set, we will now add a point light to our scene. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    Light* pointLight = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}}(\textcolor{stringliteral}{"PointLight"});}
\DoxyCodeLine{    pointLight-\/>\mbox{\hyperlink{class_ogre_1_1_light_a6019f7fa89624e35316ba444e519d8f8}{setType}}(Light::LT\_POINT);}
\end{DoxyCodeInclude}
 We\textquotesingle{}ll set the the specular and diffuse colors to a dark gray.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    pointLight-\/>setDiffuseColour(0.3, 0.3, 0.3);}
\DoxyCodeLine{    pointLight-\/>setSpecularColour(0.3, 0.3, 0.3);}
\end{DoxyCodeInclude}
 A point light has no direction. It only has a position. We will place our last light above and behind the ninja.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    SceneNode* pointLightNode = scnMgr-\/>\mbox{\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}}()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}();}
\DoxyCodeLine{    pointLightNode-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(pointLight);}
\DoxyCodeLine{    pointLightNode-\/>setPosition(\mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(0, 150, 250));}
\end{DoxyCodeInclude}
 Compile and run the application. You should see a long shadow cast in front of the ninja now. And you should see the effects of the point light brightening up the area behind the ninja. Try to think about why the colors turn out the way they do. For instance, why does the shadow behind the ninja appear to have no red at all?

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt2_ninja3.jpg}}
\end{DoxyImageNoCaption}
  \hypertarget{tut__lights_cameras_shadows_ShadowTypes}{}\doxysubsection{Shadow Types}\label{tut__lights_cameras_shadows_ShadowTypes}
\mbox{\hyperlink{namespace_ogre}{Ogre}} supports set of different shadow types. Please refer to \mbox{\hyperlink{group___general_ga79dcd426d291c31072c1ad6f183715d6}{Ogre\+::\+Shadow\+Technique}} enumerator for more details.

Try experimenting with the different shadow types. There are also other shadow-\/related methods in the \mbox{\hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager}} class that you can play with.

\mbox{\hyperlink{namespace_ogre}{Ogre}} does not provide soft shadows as part of the engine. You can write your own vertex and fragment programs to implement soft shadows and many other things. The \mbox{\hyperlink{namespace_ogre}{Ogre}} Manual has a full description of \mbox{\hyperlink{Shadows}{Shadows}}.\hypertarget{tut__lights_cameras_shadows_Conclusion2}{}\doxysubsection{Conclusion}\label{tut__lights_cameras_shadows_Conclusion2}
This tutorial introduced the use of lights and shadows into the scene. To begin, we covered how to use the Mesh\+Manager to generate meshes from scratch. We then chose which shadow type \mbox{\hyperlink{namespace_ogre}{Ogre}} should use. Finally, we begin adding an example of each type of Light to our scene. We created a spotlight, a directional light, and a point light. You can even extend \mbox{\hyperlink{namespace_ogre}{Ogre}}\textquotesingle{}s lighting and shadow systems by writing your own vertex and fragment programs. Refer to the \mbox{\hyperlink{namespace_ogre}{Ogre}} Manual for more details.

There are a lot of different settings we\textquotesingle{}ve covered that allow you to customize how \mbox{\hyperlink{namespace_ogre}{Ogre}} renders light and shadow. After you\textquotesingle{}ve finished each tutorial, it is a good idea to play around with the new tools you have. This will greatly increase your comfort level working with the library, and it is an excellent way to learn how to navigate A\+PI documentation. \hypertarget{tut_TerrainSkyFog}{}\doxysection{Terrain, Sky and Fog}\label{tut_TerrainSkyFog}
This tutorial will focus on rendering terrain in a scene. We will cover the basic set up that needs to be done, and we will introduce the use of lighting with terrains. We will also give a brief introduction to simulating a sky using Skyboxes, Skydomes, and Skyplanes. Finally, we will explain how to add a fog effect to the scene.

The full source for this tutorial can be found in samples directory {\bfseries{Samples/\+Terrain/include/\+Terrain.\+h}}.

\begin{DoxyNote}{Note}
Refer to \mbox{\hyperlink{setup}{Setting up an O\+G\+RE project}} for instructions how set up an \mbox{\hyperlink{namespace_ogre}{Ogre}} project and compile it successfully.
\end{DoxyNote}
 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt3_fog_visual.png}}
\end{DoxyImageNoCaption}
  

Ignore the F\+PS stats in the screenshots. They were rendered on an ancient computer.\hypertarget{tut__terrain_sky_fog_tut_terrain}{}\doxysubsection{An Introduction to Terrain}\label{tut__terrain_sky_fog_tut_terrain}
With older versions of Ogre, we had to use the \char`\"{}\+Terrain Scene Manager\char`\"{} to render terrain in a scene. This is a separate Scene\+Manager that runs alongside your other managers. The new \mbox{\hyperlink{namespace_ogre}{Ogre}} Terrain Component doesn\textquotesingle{}t require using a separate manager. Since \mbox{\hyperlink{namespace_ogre}{Ogre}} 1.\+7 (Cthugha), there are two terrain components\+: Terrain and Paging. The Paging component is used optimize large terrains. It will be covered in later tutorials. This tutorial will focus largely on the Terrain component.

To set up the terrain we will focus on two main classes\+:
\begin{DoxyItemize}
\item \mbox{\hyperlink{class_ogre_1_1_terrain}{Ogre\+::\+Terrain}} and
\item \mbox{\hyperlink{class_ogre_1_1_terrain_group}{Ogre\+::\+Terrain\+Group}}
\end{DoxyItemize}

The Terrain class represents one chunk of terrain and the Terrain\+Group holds a series of Terrain pieces. It is used for L\+OD (Level of Detail) rendering. L\+OD rendering reduces the resolution for terrain that is farther away from the camera. An individual Terrain object consists of tiles with a material mapped on to them. We will use a single Terrain\+Group without paging. Paging will be covered in later tutorials.\hypertarget{tut__terrain_sky_fog_autotoc_md317}{}\doxysubsubsection{Setting Up the Camera}\label{tut__terrain_sky_fog_autotoc_md317}
Let\textquotesingle{}s first set up our Camera. Add the following to the beginning of {\ttfamily setup}\+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        mCameraNode-\/>setPosition(mTerrainPos + \mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(1683, 50, 2116));}
\DoxyCodeLine{        mCameraNode-\/>lookAt(\mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(1963, 50, 1660), Node::TS\_PARENT);}
\DoxyCodeLine{        mCamera-\/>setNearClipDistance(40); \textcolor{comment}{// tight near plane important for shadows}}
\DoxyCodeLine{        mCamera-\/>setFarClipDistance(50000);}
\end{DoxyCodeInclude}
 This should look familiar from the previous tutorial.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \textcolor{keywordflow}{if} (mRoot-\/>getRenderSystem()-\/>getCapabilities()-\/>hasCapability(\mbox{\hyperlink{group___render_system_gga3d2965b7f378ebdcfe8a4a6cf74c3de7a86b8fb59223a3d16e1c7556385c87e58}{RSC\_INFINITE\_FAR\_PLANE}}))}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            mCamera-\/>setFarClipDistance(0);   \textcolor{comment}{// enable infinite far clip distance if we can}}
\DoxyCodeLine{        \}}
\end{DoxyCodeInclude}
 The last thing we do is check to see if our current render system has the capability to handle an infinite far clip distance. If it does, then we set the far clip distance to zero (which means \textquotesingle{}\textquotesingle{}no\textquotesingle{}\textquotesingle{} far clipping). \hypertarget{tut__terrain_sky_fog_autotoc_md318}{}\doxysubsubsection{Setting Up a Light for Our Terrain}\label{tut__terrain_sky_fog_autotoc_md318}
The Terrain component can use a directional light to compute a lightmap. Let\textquotesingle{}s add a Light for this purpose and add some ambient light to the scene while we\textquotesingle{}re at it.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}} lightdir(0.55, -\/0.3, 0.75);}
\DoxyCodeLine{        lightdir.normalise();}
\DoxyCodeLine{}
\DoxyCodeLine{        \mbox{\hyperlink{class_ogre_1_1_light}{Ogre::Light}}* l = mSceneMgr-\/>createLight(\textcolor{stringliteral}{"tstLight"});}
\DoxyCodeLine{        l-\/>\mbox{\hyperlink{class_ogre_1_1_light_a6019f7fa89624e35316ba444e519d8f8}{setType}}(Light::LT\_DIRECTIONAL);}
\DoxyCodeLine{        l-\/>\mbox{\hyperlink{class_ogre_1_1_light_aa9c6df55eafb28a2a0bab287bc9596f7}{setDirection}}(lightdir);}
\DoxyCodeLine{        l-\/>\mbox{\hyperlink{class_ogre_1_1_light_ae7ade1a5befac759d77fa3fe9a399e5c}{setDiffuseColour}}(ColourValue::White);}
\DoxyCodeLine{        l-\/>\mbox{\hyperlink{class_ogre_1_1_light_a8ae9c19d6fd9d0d3a961225abd29126e}{setSpecularColour}}(ColourValue(0.4, 0.4, 0.4));}
\end{DoxyCodeInclude}
 This was also covered in the previous tutorial if you\textquotesingle{}re confused by any of it. The {\ttfamily normalise} method will make the vector\textquotesingle{}s length equal to one while maintaining its direction. This is something that you will see a lot of when working with vectors. It is done to avoid extra factors showing up in calculations. \hypertarget{tut__terrain_sky_fog_bt3Overview}{}\doxysubsubsection{Terrain loading overview}\label{tut__terrain_sky_fog_bt3Overview}
Now we\textquotesingle{}ll get into the actual terrain setup. First, we create Terrain\+Global\+Options.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        mTerrainGlobals = \textcolor{keyword}{new} \mbox{\hyperlink{class_ogre_1_1_terrain_global_options}{Ogre::TerrainGlobalOptions}}();}
\end{DoxyCodeInclude}
 This is a class that holds information for all of the terrains we might create -\/ that is why they are called \textquotesingle{}\textquotesingle{}global\textquotesingle{}\textquotesingle{} options. It also provides a few getters and setters. There are also local options for each Terrain\+Group that we will see later in this tutorial.

Next we construct our Terrain\+Group object. This will manage a grid of Terrains.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        mTerrainGroup = \textcolor{keyword}{new} \mbox{\hyperlink{class_ogre_1_1_terrain_group}{Ogre::TerrainGroup}}(mSceneMgr, \mbox{\hyperlink{class_ogre_1_1_terrain_aca4fcebfb7ed4684682347d325477e91ac4699c4f99bea344a309d5544b33c140}{Ogre::Terrain::ALIGN\_X\_Z}}, TERRAIN\_SIZE, TERRAIN\_WORLD\_SIZE);}
\DoxyCodeLine{        mTerrainGroup-\/>setFilenameConvention(TERRAIN\_FILE\_PREFIX, TERRAIN\_FILE\_SUFFIX);}
\DoxyCodeLine{        mTerrainGroup-\/>setOrigin(mTerrainPos);}
\end{DoxyCodeInclude}
 The Terrain\+Group constructor takes the Scene\+Manager as its first parameter. It then takes an alignment option, terrain size, and terrain world size. You can read the \mbox{\hyperlink{class_ogre_1_1_terrain_group}{Ogre\+::\+Terrain\+Group}} for more information. The {\ttfamily set\+Filename\+Convention} allows us to choose how our terrain will be saved. Finally, we set the origin to be used for our terrain.

The next thing we will do is call our terrain configuration method, which we will fill in soon. Make sure to pass the Light we created as a parameter. 
\begin{DoxyCode}{0}
\DoxyCodeLine{configureTerrainDefaults(light);}
\end{DoxyCode}
 The next thing we do is define our terrains and ask the Terrain\+Group to load them all.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \textcolor{keywordflow}{for} (\textcolor{keywordtype}{long} x = TERRAIN\_PAGE\_MIN\_X; x <= TERRAIN\_PAGE\_MAX\_X; ++x)}
\DoxyCodeLine{            \textcolor{keywordflow}{for} (\textcolor{keywordtype}{long} y = TERRAIN\_PAGE\_MIN\_Y; y <= TERRAIN\_PAGE\_MAX\_Y; ++y)}
\DoxyCodeLine{                defineTerrain(x, y);}
\DoxyCodeLine{        \textcolor{comment}{// sync load since we want everything in place when we start}}
\DoxyCodeLine{        mTerrainGroup-\/>loadAllTerrains(\textcolor{keyword}{true});}
\end{DoxyCodeInclude}
 We are only using a single terrain, so the method will only be called once. The for loops are just for demonstration in our case. Again, we will fill in the {\ttfamily define\+Terrain} method soon.

We will now initialize the blend maps for our terrain.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \textcolor{keywordflow}{if} (mTerrainsImported)}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            TerrainGroup::TerrainIterator ti = mTerrainGroup-\/>getTerrainIterator();}
\DoxyCodeLine{            \textcolor{keywordflow}{while}(ti.hasMoreElements())}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                Terrain* t = ti.getNext()-\/>instance;}
\DoxyCodeLine{                initBlendMaps(t);}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{}
\DoxyCodeLine{        mTerrainGroup-\/>freeTemporaryResources();}
\end{DoxyCodeInclude}
 We get a Terrain\+Iterator from our Terrain\+Group and then loop through any Terrain elements and initialize their blend maps -\/ {\ttfamily init\+Blend\+Maps} will also be written soon. The {\ttfamily m\+Terrains\+Imported} variable will be set during the {\ttfamily configure\+Terrain\+Defaults} function when we complete it.

The last thing we will do is make sure to cleanup any temporary resources that were created while configuring our terrain.

That completes our {\ttfamily create\+Scene} method. Now we just have to complete all of the methods we jumped over. \hypertarget{tut__terrain_sky_fog_bt3Appearance}{}\doxysubsubsection{Terrain appearance}\label{tut__terrain_sky_fog_bt3Appearance}
The \mbox{\hyperlink{namespace_ogre}{Ogre}} Terrain component has a large number of options that can be set to change how the terrain is rendered. To start out, we configure the level of detail as\+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        mTerrainGlobals-\/>setMaxPixelError(8);}
\DoxyCodeLine{        mTerrainGlobals-\/>setCompositeMapDistance(3000);}
\end{DoxyCodeInclude}
 We are setting two global options here. The first call sets the largest error in pixels allowed between our ideal terrain and the mesh that is created to render it. A smaller number will mean a more accurate terrain, because it will require more vertices to reduce the error. The second call determines the distance at which \mbox{\hyperlink{namespace_ogre}{Ogre}} will still apply our lightmap. If you increase this, then you will see \mbox{\hyperlink{namespace_ogre}{Ogre}} apply lighting effects out to a farther distance.

The next thing we\textquotesingle{}ll do is pass our lighting information to our terrain.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \textcolor{comment}{// Important to set these so that the terrain knows what to use for baked (non-\/realtime) data}}
\DoxyCodeLine{        mTerrainGlobals-\/>setLightMapDirection(l-\/>\mbox{\hyperlink{class_ogre_1_1_light_ad0a45fbfeb651ce0e7ea810b3fe47f23}{getDerivedDirection}}());}
\DoxyCodeLine{        mTerrainGlobals-\/>setCompositeMapAmbient(mSceneMgr-\/>getAmbientLight());}
\DoxyCodeLine{        mTerrainGlobals-\/>setCompositeMapDiffuse(l-\/>\mbox{\hyperlink{class_ogre_1_1_light_ae32394134198d3cb6dd5541e6fec37b2}{getDiffuseColour}}());}
\end{DoxyCodeInclude}
 In the first call, we are sure to call {\ttfamily get\+Derived\+Direction}, because this will apply any transforms that are applied to our Light\textquotesingle{}s direction by any Scene\+Node it may be attached to. Since our Light is attached to the root Node, this will be the same as calling {\ttfamily get\+Direction}, but the difference is important to know about. The next two calls should be pretty self-\/explanatory. We simply set the ambient light and diffuse color for our terrain to match our scene lighting.

The next thing we do is get a reference to the import settings of our Terrain\+Group and set some basic values.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data}{Ogre::Terrain::ImportData}}\& defaultimp = mTerrainGroup-\/>getDefaultImportSettings();}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a0b5bc1f24bcc9003e5ed0ccb850711f8}{terrainSize}} = TERRAIN\_SIZE;}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a43509d8a986b1b733d010300487425a5}{worldSize}} = TERRAIN\_WORLD\_SIZE;}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_ae97c725c89e0c789e5099fd387953020}{inputScale}} = 600;}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a60b1682048188053cc885097eb2383c6}{minBatchSize}} = 33;}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_acebf6cfa7dcb63b4725ed1dc2e63a9f2}{maxBatchSize}} = 65;}
\end{DoxyCodeInclude}
 We are not going to cover the exact meaning of these options in this tutorial, but you may have noticed that {\ttfamily terrain\+Size} and {\ttfamily world\+Size} are set to match the global options we set in {\ttfamily create\+Scene}. The {\ttfamily input\+Scale} determines how the heightmap image will be scaled up for the scene. We are using a somewhat large scale because our heightmap image has limited precision. You can use floating point raw heightmaps to avoid applying any input scaling, but these images usually require some data compression.

The last step is adding the textures our terrain will use. First, we resize the list to hold three textures. After that, we set each texture\textquotesingle{}s {\ttfamily world\+Size} and add them to the list.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}.resize(3);}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}[0].worldSize = 100;}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}[0].textureNames.push\_back(\textcolor{stringliteral}{"grass\_green-\/01\_diffusespecular.dds"});}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}[0].textureNames.push\_back(\textcolor{stringliteral}{"grass\_green-\/01\_normalheight.dds"});}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}[1].worldSize = 100;}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}[1].textureNames.push\_back(\textcolor{stringliteral}{"dirt\_grayrocky\_diffusespecular.dds"});}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}[1].textureNames.push\_back(\textcolor{stringliteral}{"dirt\_grayrocky\_normalheight.dds"});}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}[2].worldSize = 200;}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}[2].textureNames.push\_back(\textcolor{stringliteral}{"growth\_weirdfungus-\/03\_diffusespecular.dds"});}
\DoxyCodeLine{        defaultimp.\mbox{\hyperlink{struct_ogre_1_1_terrain_1_1_import_data_a3d892ce610f8e6aec873528d042fe72b}{layerList}}[2].textureNames.push\_back(\textcolor{stringliteral}{"growth\_weirdfungus-\/03\_normalheight.dds"});}
\end{DoxyCodeInclude}
 The texture\textquotesingle{}s {\ttfamily world\+Size} determines how big each splat of texture is going to be when applied to the terrain. A smaller value will increase the resolution of the rendered texture layer because each piece will be stretched less to fill in the terrain.

The default material generator requires two textures per layer\+:
\begin{DoxyEnumerate}
\item a diffuse specular texture and
\item a heightmap texture.
\end{DoxyEnumerate}

The textures used in the tutorial reside in the Samples directory of your S\+DK or source distribution. As of this writing, they are included in this directory\+: {\ttfamily Samples/\+Media/materials/textures/nvidia/}. Remember that \mbox{\hyperlink{namespace_ogre}{Ogre}} will not automatically search subdirectories when loading resources, so you will have to add a line to your {\ttfamily resources.\+cfg} file telling it to include the nvidia directory, and, of course, you\textquotesingle{}ll have to copy the actual textures into your project\textquotesingle{}s media folder.\hypertarget{tut__terrain_sky_fog_bt3TerrainChunk}{}\doxysubsubsection{Defining a terrain chunk}\label{tut__terrain_sky_fog_bt3TerrainChunk}
Now we will tackle our {\ttfamily define\+Terrain} method. The first thing we do is ask the Terrain\+Group to define a unique filename for this Terrain. If it has already been generated, then we can call {\ttfamily Terrain\+Group\+::define\+Terrain} method to set up this grid location with the previously generated filename automatically. If it has not been generated, then we generate an image with {\ttfamily get\+Terrain\+Image} and then call a different overload of {\ttfamily Terrain\+Group\+::define\+Terrain} that takes a reference to our generated image. Finally, we set the {\ttfamily m\+Terrains\+Imported} flag to true.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \mbox{\hyperlink{namespace_ogre_af73bbdc8bed8a3e6fcd56bb8fa188c45}{String}} filename = mTerrainGroup-\/>generateFilename(x, y);}
\DoxyCodeLine{        \textcolor{keywordflow}{if} (ResourceGroupManager::getSingleton().resourceExists(mTerrainGroup-\/>getResourceGroup(), filename))}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            mTerrainGroup-\/>defineTerrain(x, y);}
\DoxyCodeLine{        \}}
\DoxyCodeLine{        \textcolor{keywordflow}{else}}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            Image img;}
\DoxyCodeLine{            getTerrainImage(x \% 2 != 0, y \% 2 != 0, img);}
\DoxyCodeLine{            mTerrainGroup-\/>defineTerrain(x, y, \&img);}
\DoxyCodeLine{            mTerrainsImported = \textcolor{keyword}{true};}
\DoxyCodeLine{        \}}
\end{DoxyCodeInclude}
 You might have to look at this method for a little while to fully understand it. Make sure you notice that there are \textquotesingle{}\textquotesingle{}three\textquotesingle{}\textquotesingle{} different {\ttfamily define\+Terrain} methods in use. One of them from Tutorial\+Application and two of them from Terrain\+Group. \hypertarget{tut__terrain_sky_fog_bt3Heightmap}{}\doxysubsubsection{Loading a heightmap}\label{tut__terrain_sky_fog_bt3Heightmap}
We need to write the helper function that was used by {\ttfamily define\+Terrain} in the last step. This will load our {\ttfamily terrain.\+png} heightmap. Make sure it has been added to one of your resource loading paths. It is also included in the \mbox{\hyperlink{namespace_ogre}{Ogre}} Samples directory.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        img.load(\textcolor{stringliteral}{"terrain.png"}, mTerrainGroup-\/>getResourceGroup());}
\DoxyCodeLine{        \textcolor{keywordflow}{if} (flipX)}
\DoxyCodeLine{            img.flipAroundY();}
\DoxyCodeLine{        \textcolor{keywordflow}{if} (flipY)}
\DoxyCodeLine{            img.flipAroundX();}
\end{DoxyCodeInclude}
 Flipping is used to create seamless terrain so that unlimited terrain can be created using a single heightmap. If your terrain\textquotesingle{}s heightmap is already seamless, then you don\textquotesingle{}t need to use this trick. In our case, the flipping code is also useless, because we are using a 1x1 Terrain\+Group. Flipping a 1x1 tile doesn\textquotesingle{}t change anything. It is just for demonstration. \hypertarget{tut__terrain_sky_fog_bt3Blendmap}{}\doxysubsubsection{Height based blending}\label{tut__terrain_sky_fog_bt3Blendmap}
Finally, we will finish up our configuration methods by completing the {\ttfamily init\+Blend\+Maps} method. This method will blend together the different layers we defined in {\ttfamily configure\+Terrain\+Defaults}. For now, you should pretty much view this method as a magic. The details will not be covered in this tutorial. Basically, the method blends the textures based on the height of the terrain at that point. This is not the only way of doing blending. It\textquotesingle{}s a complicated topic and sits right at the verge between \mbox{\hyperlink{namespace_ogre}{Ogre}} and the things it tries to abstract away.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \textcolor{keyword}{using namespace }\mbox{\hyperlink{namespace_ogre}{Ogre}};}
\DoxyCodeLine{        \mbox{\hyperlink{class_ogre_1_1_terrain_layer_blend_map}{TerrainLayerBlendMap}}* blendMap0 = terrain-\/>getLayerBlendMap(1);}
\DoxyCodeLine{        \mbox{\hyperlink{class_ogre_1_1_terrain_layer_blend_map}{TerrainLayerBlendMap}}* blendMap1 = terrain-\/>getLayerBlendMap(2);}
\DoxyCodeLine{        \textcolor{keywordtype}{float} minHeight0 = 20;}
\DoxyCodeLine{        \textcolor{keywordtype}{float} fadeDist0 = 15;}
\DoxyCodeLine{        \textcolor{keywordtype}{float} minHeight1 = 70;}
\DoxyCodeLine{        \textcolor{keywordtype}{float} fadeDist1 = 15;}
\DoxyCodeLine{        \textcolor{keywordtype}{float}* pBlend0 = blendMap0-\/>\mbox{\hyperlink{class_ogre_1_1_terrain_layer_blend_map_a7a2e86bf826528459f4c9813d9f11b18}{getBlendPointer}}();}
\DoxyCodeLine{        \textcolor{keywordtype}{float}* pBlend1 = blendMap1-\/>\mbox{\hyperlink{class_ogre_1_1_terrain_layer_blend_map_a7a2e86bf826528459f4c9813d9f11b18}{getBlendPointer}}();}
\DoxyCodeLine{        \textcolor{keywordflow}{for} (\mbox{\hyperlink{namespace_ogre_aa8263b218e7d187ad5ef03a73a6ad7fd}{uint16}} y = 0; y < terrain-\/>getLayerBlendMapSize(); ++y)}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            \textcolor{keywordflow}{for} (\mbox{\hyperlink{namespace_ogre_aa8263b218e7d187ad5ef03a73a6ad7fd}{uint16}} x = 0; x < terrain-\/>getLayerBlendMapSize(); ++x)}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                \mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}} tx, ty;}
\DoxyCodeLine{}
\DoxyCodeLine{                blendMap0-\/>\mbox{\hyperlink{class_ogre_1_1_terrain_layer_blend_map_abe74e7c92015442d95044887b492875d}{convertImageToTerrainSpace}}(x, y, \&tx, \&ty);}
\DoxyCodeLine{                \textcolor{keywordtype}{float} height = terrain-\/>getHeightAtTerrainPosition(tx, ty);}
\DoxyCodeLine{}
\DoxyCodeLine{                *pBlend0++ = \mbox{\hyperlink{class_ogre_1_1_math_a11a5dc9a435892a7b4786f9e1c9b997a}{Math::saturate}}((height -\/ minHeight0) / fadeDist0);}
\DoxyCodeLine{                *pBlend1++ = \mbox{\hyperlink{class_ogre_1_1_math_a11a5dc9a435892a7b4786f9e1c9b997a}{Math::saturate}}((height -\/ minHeight1) / fadeDist1);}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{        blendMap0-\/>\mbox{\hyperlink{class_ogre_1_1_terrain_layer_blend_map_afc1e25e221980f7b3ce696dfc22223ca}{dirty}}();}
\DoxyCodeLine{        blendMap1-\/>\mbox{\hyperlink{class_ogre_1_1_terrain_layer_blend_map_afc1e25e221980f7b3ce696dfc22223ca}{dirty}}();}
\DoxyCodeLine{        blendMap0-\/>\mbox{\hyperlink{class_ogre_1_1_terrain_layer_blend_map_a7b84ae6db639c23977a433047ec955bb}{update}}();}
\DoxyCodeLine{        blendMap1-\/>\mbox{\hyperlink{class_ogre_1_1_terrain_layer_blend_map_a7b84ae6db639c23977a433047ec955bb}{update}}();}
\end{DoxyCodeInclude}
 \hypertarget{tut__terrain_sky_fog_bt3LoadingLabel}{}\doxysubsubsection{Terrain Loading Label}\label{tut__terrain_sky_fog_bt3LoadingLabel}
There are a number of things we will improve. We will add a label to the overlay that allows us to see when the terrain generation has finished. We will also make sure to save our terrain so that it can be reloaded instead of rebuilding it every time. Finally, we will make sure to clean up after ourselves.

First, we need to add a data member to private section of our Sample\+\_\+\+Terrain header.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_bites_1_1_label}{OgreBites::Label}}* mInfoLabel = \textcolor{keyword}{nullptr};}
\end{DoxyCodeInclude}
 Let\textquotesingle{}s construct this label in the {\ttfamily create\+Frame\+Listener} method.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        mInfoLabel = mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a15375d59b5c57059c9c6549fc5a1bfcd}{createLabel}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530ae4e5c068e88e5c0561a2c30dca2ec5a5}{TL\_TOP}}, \textcolor{stringliteral}{"TInfo"}, \textcolor{stringliteral}{""}, 350);}
\end{DoxyCodeInclude}
 We use the Tray\+Manager pointer that was defined in Sdk\+Sample to request the creation of a new label. This method takes a Tray\+Location, a name for the label, a caption to display, and a width.

Next we will add logic to {\ttfamily frame\+Rendering\+Queued} that tracks whether the terrain is still loading or not. We will also take care of saving our terrain after it has been loaded. Add the following to {\ttfamily frame\+Rendering\+Queued} right after the call to the parent method\+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \textcolor{keywordflow}{if} (mTerrainGroup-\/>isDerivedDataUpdateInProgress())}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}}(mInfoLabel, \mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530ae4e5c068e88e5c0561a2c30dca2ec5a5}{TL\_TOP}}, 0);}
\DoxyCodeLine{            mInfoLabel-\/>\mbox{\hyperlink{class_ogre_bites_1_1_widget_aa90966b039159924d827c75b0f80dace}{show}}();}
\DoxyCodeLine{            \textcolor{keywordflow}{if} (mTerrainsImported)}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                mInfoLabel-\/>\mbox{\hyperlink{class_ogre_bites_1_1_label_a96ddab8a64ea9159d370f32af392e08a}{setCaption}}(\textcolor{stringliteral}{"Building terrain, please wait..."});}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            \textcolor{keywordflow}{else}}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                mInfoLabel-\/>\mbox{\hyperlink{class_ogre_bites_1_1_label_a96ddab8a64ea9159d370f32af392e08a}{setCaption}}(\textcolor{stringliteral}{"Updating textures, patience..."});}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{        \textcolor{keywordflow}{else}}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_ac2f939d0bd36af335a78589b462506e9}{removeWidgetFromTray}}(mInfoLabel);}
\DoxyCodeLine{            mInfoLabel-\/>\mbox{\hyperlink{class_ogre_bites_1_1_widget_abf26dfc708c02ef494a53ca2cd1450c9}{hide}}();}
\DoxyCodeLine{            \textcolor{keywordflow}{if} (mTerrainsImported)}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                saveTerrains(\textcolor{keyword}{true});}
\DoxyCodeLine{                mTerrainsImported = \textcolor{keyword}{false};}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\end{DoxyCodeInclude}
 The first thing we do is determine if our terrain is still being built. If it is, then we add our Label to the tray and ask for it to be shown. Then we check to see if any new terrains have been imported. If they have, then we display text saying that the terrain is still being built. Otherwise we assume the textures are being updated.

If the terrain is no longer being updated, then we ask the \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager}{Ogre\+Bites\+::\+Tray\+Manager}} to remove the our Label widget and hide the Label. We also check to see if new terrains have been imported and save them for future use. In our case, the file will be named \textquotesingle{}terrain\+\_\+00000000.\+dat\textquotesingle{} and it will reside in your \textquotesingle{}bin\textquotesingle{} directory alongside your application\textquotesingle{}s executable. After saving any new terrains, we reset the {\ttfamily m\+Terrains\+Imported} flag.

Compile and run your application again. You should now see a Label at the top of the screen while the terrain is being built. While the terrain is loading, you will not be able to press escape to exit and your movement controls will be choppy. This is what loading screens are for in games. But if you exit and run the application a second time, then it should load the terrain file that was saved the first time. This should be a much faster process.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt3_building_terrain_label_visual.png}}
\end{DoxyImageNoCaption}
  \hypertarget{tut__terrain_sky_fog_bt3sky}{}\doxysubsection{Simulating a sky}\label{tut__terrain_sky_fog_bt3sky}
\hypertarget{tut__terrain_sky_fog_autotoc_md319}{}\doxysubsubsection{Sky\+Boxes}\label{tut__terrain_sky_fog_autotoc_md319}
A Sky\+Box is basically a huge textured cube that surrounds all of the objects in your scene. It is one of the methods for simulating a sky. We will need six textures to cover all of the interior faces of the Sky\+Box.

It is very easy to include a Sky\+Box in your scene. Add the following to the end of {\ttfamily create\+Scene}\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mSceneMgr-\/>setSkyBox(\textcolor{keyword}{true}, \textcolor{stringliteral}{"Examples/SpaceSkyBox"});}
\end{DoxyCode}
 Compile and run your application. That\textquotesingle{}s all there is to it. The Sky\+Box will look really grainy because we are using a rather low resolution collection of textures.

The first parameter of this method determines whether or not to immediately enable the Sky\+Box. If you want to later disable the Sky\+Box you can call {\ttfamily m\+Scene\+Mgr-\/$>$set\+Sky\+Box(false, \char`\"{}\char`\"{})}. This disables the Sky\+Box.

The third and fourth parameters to {\ttfamily set\+Sky\+Box} are important to understand. We have allowed them to take their default values in our call. The third parameter is the distance between the Camera and the Sky\+Box. Make this change to your call\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mSceneMgr-\/>setSkyBox(\textcolor{keyword}{true}, \textcolor{stringliteral}{"Examples/SpaceSkyBox"}, 300);}
\end{DoxyCode}
 Compile and run your application. Nothing has changed. This is because the fourth parameter sets whether or not to render the Sky\+Box before the rest of the scene. If the Sky\+Box is rendered first, then no matter how close it is the rest of your scene objects will be rendered on top of it. Now try this call\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mSceneMgr-\/>setSkyBox(\textcolor{keyword}{true}, \textcolor{stringliteral}{"Examples/SpaceSkyBox"}, 300, \textcolor{keyword}{false});}
\end{DoxyCode}
 Compile and run your application again. This time you should definitely see something different. Only a small patch of terrain should exist below the camera. Move around and notice what is happening. The Sky\+Box is being rendered only 300 pixels away from the Camera and it is no longer being rendered before everything else. This means the Sky\+Box is drawn over terrain that is farther than 300 units away from the Camera.

You can get a modest performance boost by not rendering the Sky\+Box first, but as you can see, you\textquotesingle{}ll need to make sure not to cause strange problems like this when doing it. For the most part, leaving these additional parameters at their defaults is good enough. Although you may want to purposely use this strange culling behavior in your application. Try not to get to locked into how things are \char`\"{}supposed to work\char`\"{}. If something catches your eye, then play around with it. \hypertarget{tut__terrain_sky_fog_autotoc_md320}{}\doxysubsubsection{Sky\+Domes}\label{tut__terrain_sky_fog_autotoc_md320}
Another method of simulating a sky is the Sky\+Dome. The sky texture is still applied to a huge cube that surrounds the scene, but the textures is projected in such a way that it appears to create a dome over the scene. The best way to understand this is to see it in practice. Comment out our call to {\ttfamily set\+Sky\+Box} and add the following line\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mSceneMgr-\/>setSkyDome(\textcolor{keyword}{true}, \textcolor{stringliteral}{"Examples/CloudySky"}, 5, 8);}
\end{DoxyCode}
 Compile and run your application. Make sure to move the Camera to the edge of the terrain so you can better idea of what is being done. The main drawback to this method is that the texture won\textquotesingle{}t cover the bottom face of the cube. You would need to make sure a user could not accidentally see behind the curtain.

The first two parameters of the {\ttfamily set\+Sky\+Dome} method are the same as {\ttfamily set\+Sky\+Box}. You can disable the Sky\+Dome in the same way as well. The third parameter is the curvature for the dome projection. It is suggested to use values between 2 and 65. Lower values will produce a better effect at far distances, but higher values will cause less distortion of the texture. The fourth parameter is the number of times the texture will be tiled. This parameter is a \mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Ogre\+::\+Real}} value. You can tile your texture 3.\+14 times if you want. The last two parameters are the distance and whether or not to draw the Sky\+Dome first. These are the same last two parameters we had with {\ttfamily set\+Sky\+Box}.\hypertarget{tut__terrain_sky_fog_autotoc_md321}{}\doxysubsubsection{Sky\+Planes}\label{tut__terrain_sky_fog_autotoc_md321}
The third method for simulating sky is rather different from the first two. This method will use a single plane. The first thing we need to do is create a Plane object. Comment out our call to {\ttfamily set\+Sky\+Dome} and add the following\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_plane}{Ogre::Plane}} plane;}
\DoxyCodeLine{plane.\mbox{\hyperlink{class_ogre_1_1_plane_a8e7de1712320968bee111002bc2938b8}{d}} = 1000;}
\DoxyCodeLine{plane.\mbox{\hyperlink{class_ogre_1_1_plane_a3f97462d3822f6add8c070048f6c2d92}{normal}} = Ogre::Vector3::NEGATIVE\_UNIT\_Y;}
\end{DoxyCode}
 We\textquotesingle{}ve defined a plane by providing a distance from the origin (d) and a vector that is normal to our plane (normal). By choosing the the \textquotesingle{}\textquotesingle{}negative\textquotesingle{}\textquotesingle{} unit vector along the y-\/axis we have a plane that is parallel to the ground and facing downwards.

Now we can create the Sky\+Plane. 
\begin{DoxyCode}{0}
\DoxyCodeLine{mSceneMgr-\/>setSkyPlane(\textcolor{keyword}{true}, plane, \textcolor{stringliteral}{"Examples/SpaceSkyPlane"}, 1500, 75);}
\end{DoxyCode}
 The fourth parameter is the size of the Sky\+Plane (1500x1500 units), and the fifth parameter is number of times to tile the texture.

Compile and run your application. Again, the texture we are using is rather low-\/resolution. A high definition texture would look much better. It also doesn\textquotesingle{}t tile very well. These issuse can both be fixed by using higher quality resources. The real problem is that it is very likely a user will be able to see the end of the Sky\+Plane as soon as they move anywhere near the edge of the terrain. For this reason, a Sky\+Plane is often used most in scenes that have high walls. In these cases, a Sky\+Plane offers a decent increase in performance over the other techniques.

The Sky\+Plane has some other attributes that can be used to produce a better effect. The sixth parameter of the {\ttfamily set\+Sky\+Plane} method is the \char`\"{}render\+First\char`\"{} parameter we covered for the past two methods. The seventh parameter allows us to specify a curvature for the Sky\+Plane. This will pull down the corners of the Sky\+Plane turning it into a curved surface instead of a flat plane. If we set the curvature to something other flat, we also need to set the number of segments \mbox{\hyperlink{namespace_ogre}{Ogre}} should use to render the Sky\+Plane. When the Sky\+Plane was a flat plane, everything was one large square, but if we add curvature, then it will require a more complicated geometry. The eighth and ninth parameters to the function are the number of segments for each dimension of the plane.

Let\textquotesingle{}s test this out. Make these changes to our call\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mSceneMgr-\/>setSkyPlane(}
\DoxyCodeLine{  \textcolor{keyword}{true}, plane, \textcolor{stringliteral}{"Examples/SpaceSkyPlane"}, 1500, 50, \textcolor{keyword}{true}, 1.5, 150, 150);}
\end{DoxyCode}
 Compile and run the application. This should help the look of our Sky\+Plane a bit. Go to the edge of the terrain to get a better look at what was done with the curvature. \hypertarget{tut__terrain_sky_fog_tut_fog}{}\doxysubsection{Fog}\label{tut__terrain_sky_fog_tut_fog}
Like practically everything in graphics programming, the fog effect in \mbox{\hyperlink{namespace_ogre}{Ogre}} is an illusion. \mbox{\hyperlink{namespace_ogre}{Ogre}} does not render a fog object into our scene. Instead, it simply applies a filter to our scene. This filter allows the Viewport\textquotesingle{}s background color to show through our scenery to varying degrees based on the object\textquotesingle{}s distance from the Camera. What this means is that your fog will have the same color has your Viewport\textquotesingle{}s background color.

There are two basic types of fog in \mbox{\hyperlink{namespace_ogre}{Ogre}}\+: linear and exponential. The difference is the rate at which the fog gets thicker as you move away from the Camera.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{bt3_linear_exp_visual.png}}
\end{DoxyImageNoCaption}
  \hypertarget{tut__terrain_sky_fog_autotoc_md322}{}\doxysubsubsection{Adding Fog to Our Scene}\label{tut__terrain_sky_fog_autotoc_md322}
We will first add linear fog to our scene. We need to make sure to set our Viewport\textquotesingle{}s background color to our desired fog color. Add the following to {\ttfamily create\+Scene} right \textquotesingle{}\textquotesingle{}before\textquotesingle{}\textquotesingle{} our code for setting up the terrain\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_colour_value}{Ogre::ColourValue}} fadeColour(0.9, 0.9, 0.9);}
\DoxyCodeLine{mWindow-\/>getViewport(0)-\/>setBackgroundColour(fadeColour);}
\end{DoxyCode}
 Make sure you add this before the terrain code otherwise it won\textquotesingle{}t work. If you were using more than one Viewport, then you may have to iterate through them all by using \mbox{\hyperlink{class_ogre_1_1_render_target_ab82d2cf13a93ae6406cee9d2d044aa06}{Ogre\+::\+Render\+Target\+::get\+Num\+Viewports}}.

Now we can create the fog. 
\begin{DoxyCode}{0}
\DoxyCodeLine{mSceneMgr-\/>setFog(\mbox{\hyperlink{group___general_gga83edeb2e5d33a3ca8f15834ba40020baacd90839d2d222db939530a9fba6f9dad}{Ogre::FOG\_LINEAR}}, fadeColour, 0, 600, 900);}
\end{DoxyCode}
 The first parameter is the fog type. The second parameter is the color we used to set our Viewport\textquotesingle{}s background color. The third parameter is not used for linear fog. The fourth and fifth parameters specify the beginning and the end of the range for the fog. In our example, the fog will begin at 600 units out from the Camera, and it will end at 900 units. The reason this is called linear fog is because the thickness increases between these two values in a linear fashion. Compile and run your application.

The next type of fog is exponential fog. Like the picture suggests, exponential fog grows slowly at first and then gets dense very quickly. We do not set a range for this fog, instead we simply supply a desired density. 
\begin{DoxyCode}{0}
\DoxyCodeLine{mSceneMgr-\/>setFog(\mbox{\hyperlink{group___general_gga83edeb2e5d33a3ca8f15834ba40020baa5c51ab0c88827f1f30b6c08a32f282a2}{Ogre::FOG\_EXP}}, fadeColour, 0.002);}
\end{DoxyCode}
 Compile and run the application. You can see this creates a different kind of fog effect. It is more like a haze that fills the area surrounding the Camera. There is a variation of the exponential fog that increases at a faster rate. 
\begin{DoxyCode}{0}
\DoxyCodeLine{mSceneMgr-\/>setFog(\mbox{\hyperlink{group___general_gga83edeb2e5d33a3ca8f15834ba40020baac3413d47a9e6c30ba39da21339bd1d7f}{Ogre::FOG\_EXP2}}, fadeColour, 0.002);}
\end{DoxyCode}
 Compile and run your application to see the difference this makes. \hypertarget{tut__terrain_sky_fog_conclusion3}{}\doxysubsection{Conclusion}\label{tut__terrain_sky_fog_conclusion3}
This tutorial covered the basics of using the \mbox{\hyperlink{namespace_ogre}{Ogre}} Terrain Component. We gave a brief overview of the setup that needs to be done to allow the importing of a terrain heightmap into our scene. We mentioned the notion of a \mbox{\hyperlink{class_ogre_1_1_terrain_group}{Ogre\+::\+Terrain\+Group}} although we only used one \mbox{\hyperlink{class_ogre_1_1_terrain}{Ogre\+::\+Terrain}} object in our \char`\"{}group\char`\"{} for this tutorial. We also made sure to initialize our terrain with a directional light so that we would get specular reflections and shadows cast across our terrain.

We also covered the different methods \mbox{\hyperlink{namespace_ogre}{Ogre}} offers to simulate a sky in your scene. These included\+: Sky\+Boxes, Sky\+Domes, and Sky\+Planes. Finally, we introduced \mbox{\hyperlink{namespace_ogre}{Ogre}}\textquotesingle{}s fog effects. Fog is rendered by applying a filter to our scene that allows the Viewport\textquotesingle{}s background color to bleed through our scene based on distance from our Camera.

This is a tutorial that you should spend a lot of time experimenting with. All of these features can be configured a great deal, and you can create some very convincing scenes with just what we\textquotesingle{}ve covered so far. \hypertarget{working-with-numpy}{}\doxysection{Working with Num\+Py}\label{working-with-numpy}
\mbox{\hyperlink{namespace_ogre}{Ogre}} includes a Python component which automatically generates Python bindings from the C++ headers. However with Python you most likely do not only want to just use \mbox{\hyperlink{namespace_ogre}{Ogre}}, but connect it to other components. For this we ship a small module called {\ttfamily Ogre\+Numpy} that helps you converting between \mbox{\hyperlink{namespace_ogre}{Ogre}} and Num\+Py.

We start with a simple 3 channel python array representing a green gradient\+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    arr = np.zeros((256, 256, 3), dtype=np.uint8)}
\DoxyCodeLine{    arr[:,:,1] = np.mgrid[0:256,0:256][1]}
\end{DoxyCodeInclude}
  
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{numpy_arr.png}}
\end{DoxyImageNoCaption}
  

To be able to load it into Ogre we need a pointer that we can pass to \mbox{\hyperlink{class_ogre_1_1_image}{Ogre.\+Image}}. For this we {\itshape copy} the contents of our array into an \mbox{\hyperlink{class_ogre_1_1_memory_data_stream}{Ogre.\+Memory\+Data\+Stream}}. Here Ogre\+Numpy.\+As\+Data\+Stream automatically allocates the Memory\+Data\+Stream of the according size and takes care of the copying.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    mem = Ogre.Numpy.AsDataStream(arr)}
\DoxyCodeLine{    ogre\_img = \mbox{\hyperlink{class_ogre_1_1_image}{Ogre.Image}}()}
\DoxyCodeLine{    ogre\_img.loadDynamicImage(mem.getPtr(), 256, 256, Ogre.PF\_BYTE\_RGB)}
\DoxyCodeLine{    }
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_texture_manager_ac6fb858ee86f3b7b75de32e3e04ee5c8}{Ogre.TextureManager.getSingleton}}().loadImage(\textcolor{stringliteral}{"gradient"}, \textcolor{stringliteral}{"General"}, ogre\_img)}
\end{DoxyCodeInclude}
 While this is not the fastest option, we now have an \mbox{\hyperlink{namespace_ogre}{Ogre}} data type, that we can use as usual and upload to an Texture.

For completeness we also create a small scene where we map the texture on a screen-\/centred rectangle. 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    mat = \mbox{\hyperlink{class_ogre_1_1_material_manager_a100f413d9d2316028e7ae740e5a43161}{Ogre.MaterialManager.getSingleton}}().create(\textcolor{stringliteral}{"gradient\_mat"}, \textcolor{stringliteral}{"General"})}
\DoxyCodeLine{    rpass = mat.getTechniques()[0].getPasses()[0]}
\DoxyCodeLine{    rpass.setLightingEnabled(\textcolor{keyword}{False})}
\DoxyCodeLine{    rpass.createTextureUnitState(\textcolor{stringliteral}{"gradient"})}
\DoxyCodeLine{}
\DoxyCodeLine{    rect = \mbox{\hyperlink{class_ogre_1_1_rectangle2_d}{Ogre.Rectangle2D}}(\textcolor{keyword}{True})}
\DoxyCodeLine{    rect.setCorners(-\/0.5, 0.5, 0.5, -\/0.5) \textcolor{comment}{\# in normalized screen space}}
\DoxyCodeLine{    rect.setMaterial(mat)}
\DoxyCodeLine{    rect.setBoundingBox(Ogre.AxisAlignedBox.BOX\_INFINITE)}
\DoxyCodeLine{}
\DoxyCodeLine{    scn\_mgr.getRootSceneNode().createChildSceneNode().attachObject(rect)}
\end{DoxyCodeInclude}
 As the rectangle does not cover the full scene, we also set a background colour 
\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    gray = (0.3, 0.3, 0.3)}
\DoxyCodeLine{    vp.setBackgroundColour(\mbox{\hyperlink{class_ogre_1_1_colour_value}{Ogre.ColourValue}}(*gray))}
\end{DoxyCodeInclude}
Here we use the normal python iterable unpacking. Again this is copying the data.

Finally we want to store the rendered image into a file. This time we manually allocate the memory with \mbox{\hyperlink{class_ogre_1_1_memory_data_stream}{Ogre.\+Memory\+Data\+Stream}} to store the pixel values.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    mem = \mbox{\hyperlink{class_ogre_1_1_memory_data_stream}{Ogre.MemoryDataStream}}(win.getWidth() * win.getHeight() * 3)}
\DoxyCodeLine{    pb = \mbox{\hyperlink{class_ogre_1_1_pixel_box}{Ogre.PixelBox}}(win.getWidth(), win.getHeight(), 1, Ogre.PF\_BYTE\_RGB, mem.getPtr())}
\DoxyCodeLine{    win.copyContentsToMemory(pb, pb)}
\end{DoxyCodeInclude}
 Finally we store the image to disk using pyplot.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    pyplot.imsave(\textcolor{stringliteral}{"screenshot.png"}, Ogre.Numpy.view(pb))}
\end{DoxyCodeInclude}
 To convert the \mbox{\hyperlink{class_ogre_1_1_pixel_box}{Ogre.\+Pixel\+Box}} to a Num\+Py array we use Ogre\+Numpy.\+view. This function does {\itshape not} copy the data, but as the name suggests just creates a Num\+Py view on the underlying \mbox{\hyperlink{class_ogre_1_1_memory_data_stream}{Ogre.\+Memory\+Data\+Stream}}. Using this pattern we could also have avoided the copy when loading the numpy array as a Texture.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{numpy_final.png}}
\end{DoxyImageNoCaption}
  

\begin{DoxyNote}{Note}
There is also \mbox{\hyperlink{class_ogre_1_1_render_target_afb7ac36166a3e7c38a102edc6e7d2c1d}{Ogre\+::\+Render\+Target\+::write\+Contents\+To\+File}} if you do not need the pixel data in Python. 
\end{DoxyNote}
\hypertarget{trays}{}\doxysection{Trays G\+UI System}\label{trays}
Ever wanted really simple G\+UI controls for your sample? Don\textquotesingle{}t want to write one from scratch, but C\+E\+G\+UI\textquotesingle{}s just a little too much? The Trays system was created to address this issue. It\textquotesingle{}s a simple G\+UI system based on the O\+G\+RE \mbox{\hyperlink{_the-_core-_objects_Overlays}{Overlays}} system and designed just for samples. Because it\textquotesingle{}s simple, you\textquotesingle{}re not going to be able to skin it or build very unique interfaces, but you\textquotesingle{}ll also find it much easier to use.\hypertarget{trays_trays-1}{}\doxysubsection{Trays}\label{trays_trays-1}
Why trays? The concept of trays is central to the system in that it removes the need for the G\+UI designer (you) to calculate or specify positional coordinates of any kind. Think about the widget locations in a typical G\+UI. They are almost always in any of the four corners, along any of the four edges or, on the rare occasion, in the center of the screen. In Trays, there are nine \char`\"{}trays\char`\"{}, one in each of the locations previously mentioned. When you create a widget, you specify one of these nine locations, and the widget will be added to the tray at that location. Your widget will be added directly beneath the last widget in that tray. When you add a widget to a tray, the tray grows in size. Trays along the top of the screen grow downward, Trays along the bottom grow upward, and the trays in the middle row grow vertically in both directions. Visually, the trays are semi-\/transparent panels that fit the widgets they contain. Only non-\/empty trays are visible. If this is hard to visualise, don\textquotesingle{}t worry, here\textquotesingle{}s a picture to help you out.  
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{Gui2.jpg}}
\end{DoxyImageNoCaption}
  \hypertarget{trays_traymanager}{}\doxysubsection{Tray\+Manager}\label{trays_traymanager}
To use Trays, you have to create an Tray\+Manager. This is the class through which you will create and manage all your widgets, manipulate the cursor, change the backdrop image, adjust tray properties, pop up dialogs, show/hide the loading bar, etc. You can have multiple tray managers in one application. For example, the O\+G\+RE Sample Browser uses its own tray manager and hides it when a sample is running, and the S\+DK samples also have their own tray managers, which are hidden when the samples are paused by the browser.

\begin{DoxyNote}{Note}
The Tray\+Manager requires {\ttfamily Trays.\+zip}, so you can only create it after loading that resource. Also, make sure you\textquotesingle{}re correctly initialized the \mbox{\hyperlink{_the-_core-_objects_Overlays}{Overlays}} Component as the Trays Framework depends on it.
\end{DoxyNote}
Create your tray manager like so\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager}{OgreBites::TrayManager}}* mTrayMgr = \textcolor{keyword}{new} \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager}{OgreBites::TrayManager}}(\textcolor{stringliteral}{"InterfaceName"}, mWindow);}
\end{DoxyCode}
 You must pass in a name for your interface and a \mbox{\hyperlink{class_ogre_1_1_render_window}{Ogre\+::\+Render\+Window}}. Optionally pass a {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_listener}{Ogre\+Bites\+::\+Tray\+Listener}}} as a third argument if you want to be notified on e.\+g. button press. You can extend your sample or sample context to be a tray listener. Remember to destroy your tray manager like so\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{keyword}{delete} mTrayMgr;}
\end{DoxyCode}
 Once you have your tray manager, make sure you relay input events to it. 
\begin{DoxyCode}{0}
\DoxyCodeLine{addInputListener(mTrayMgr);}
\end{DoxyCode}
 \begin{DoxyNote}{Note}
In case you also want to handle the events yourself\+: The listener methods on Tray\+Manager return true if the event was relevant to the tray manager, and should not be processed again by you. For example, if you click a button that is over an interactive part of your scene, you want the button to be pressed, but you don\textquotesingle{}t want the scene interaction to take place. So the listener methods double as filters for your mouse events.
\end{DoxyNote}
You\textquotesingle{}re now free to create widgets! Try adding a button to the top-\/left tray\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{Button* b = mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a7486bcec7a51e1d6df53bfdead3281dd}{createButton}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530afe04de8736168ab0dd6e7938e679c292}{TL\_TOPLEFT}}, \textcolor{stringliteral}{"MyButton"}, \textcolor{stringliteral}{"Click Me!"});}
\end{DoxyCode}
 Tray\+Manager is a huge class, and you can do tons of things with it. For some examples, see the Things to Try section below.\hypertarget{trays_autotoc_md292}{}\doxysubsubsection{The Cursor}\label{trays_autotoc_md292}
The cursor has three parts in the Trays system\+: The layer it moves around in Overlay, the container which positions the cursor (Overlay\+Container), and the cursor image, which is a child of the container (Overlay\+Element). When hiding/showing the cursor, the entire cursor layer is hidden/shown. The top left corner of the cursor container is used as the hotspot of the cursor. By positioning the cursor image relative to the cursor container, you can basically decide which part of the cursor image is the \char`\"{}clicking part\char`\"{}. For the default arrow cursor, the image is simply lined up with the container, meaning the top left is the hotspot. However, for something like a crosshair cursor, you could move the cursor image so that its center is over the top left corner of the cursor container. To show the cursor, use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a1cc48ac157278b5845d425abbe9acefd}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Cursor}}}, which takes an optional material name for the cursor image. If unspecified, the cursor image is not changed. To hide the cursor, use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a979ff2ad2d729223259b3bebb237cafb}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Cursor}}}. You can get the cursor\textquotesingle{}s different parts using get\+Cursor\+Layer, get\+Cursor\+Container, and get\+Cursor\+Image. Note that if the cursor is hidden, all interactions with widgets are disabled.\hypertarget{trays_autotoc_md293}{}\doxysubsubsection{The Backdrop}\label{trays_autotoc_md293}
If you want to show a backdrop, use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_ad554418c27edb907f0e3bead8659b83c}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Backdrop}}}, which takes an optional material name for the backdrop. If unspecified, the backdrop image is not changed. To hide it, use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a6129a1e92ac22789a4602cf36f9c5394}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Backdrop}}}.\hypertarget{trays_widgets}{}\doxysubsection{Widgets}\label{trays_widgets}
There are 10 basic widgets. Each widget is just an instance of an Overlay\+Element template, and all widgets use \{L\+E\+X()\}pixel\{L\+EX\} metrics. You can get access to any widget\textquotesingle{}s underlying Overlay\+Element through {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_widget_a379d3f1a2ca6eaf13fc5c52afaafd0d2}{Ogre\+Bites\+::\+Widget\+::get\+Overlay\+Element}}}. Do not instantiate and delete widgets manually. Create and destroy them using the Tray\+Manager. The first argument to any one of Tray\+Manager\textquotesingle{}s widget creation methods is the location of the tray you want the widget to be in. This is of the enumerated type Tray\+Location. The second argument is the name of your widget (this is not your widget\textquotesingle{}s caption, but a unique string identifier for your widget). The rest of the arguments are specific to the type of widget.\hypertarget{trays_autotoc_md294}{}\doxysubsubsection{Button}\label{trays_autotoc_md294}
This is the most basic widget of all. To create a button, use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a7486bcec7a51e1d6df53bfdead3281dd}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Button}}}. In addition to a tray location and a name, you must specify a caption for your button, and an optional width. If width is not specified, the button will automatically resize to fit its caption. There are no button states. You only get notified when a button is pushed. To see how to respond to button push events, see the Tray\+Listener section below.\hypertarget{trays_autotoc_md295}{}\doxysubsubsection{Text\+Box}\label{trays_autotoc_md295}
This widget consists of a bold caption bar and a text area that can be scrolled vertically. In addition to a tray location and a name, {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a07a8d212939266339e877ff2118250a6}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Text\+Box}}} takes a caption, width, and height. You can set/get the caption, the text area contents, text padding, text alignment, manually change the scroll bar position, among other things.\hypertarget{trays_autotoc_md296}{}\doxysubsubsection{Select\+Menu}\label{trays_autotoc_md296}
A basic drop-\/down menu. To create it, use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a60864ca00d65b2bf1b97bb8545fab737}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Long\+Select\+Menu}}} or {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a98f478c8daa5084b53146de03adbc216}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Thick\+Select\+Menu}}}. Both these methods return a Select\+Menu object, but they give one of two different visual styles to the widget. One is thicker, but shorter, because it places the caption over the item box. This style of menu is good for putting in the side trays. The other is longer, but thinner, because it places the item box next to the caption. This style of menu is good for putting in the top or bottom trays. create\+Thick\+Select\+Menu takes a tray location, a name, a caption, the width of the whole widget, the maximum number of visible items when expanded, and an optional string vector of items. The medthod {\ttfamily create\+Long\+Select\+Menu} takes nearly the same arguments, except that it needs the width of the text box that shows the currently selected item. Also, for long menus, it is optional to specify the total width because it will automatically resize to fit the item box and the caption. You can set/get the caption, and set/get the items in many different ways. You can also manually change the selection, with the option of not firing an event. To see how to respond to menu item selection events, see the Tray\+Listener section below.\hypertarget{trays_autotoc_md297}{}\doxysubsubsection{Label}\label{trays_autotoc_md297}
A big, semi-\/transparent, tabby-\/looking label. This widget uses a different font from the rest of the widgets, and is good for section headings and such. In addition to a tray location and a name, {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a15375d59b5c57059c9c6549fc5a1bfcd}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Label}}} takes a caption, and an optional width. If the width is not specified, the label automatically adjusts its width to fill the tray it\textquotesingle{}s currently in, so it matches the other contents of the tray. Labels can also be clicked. To see how to respond to label click events, see the Tray\+Listener section below.\hypertarget{trays_autotoc_md298}{}\doxysubsubsection{Separator}\label{trays_autotoc_md298}
A horizontal line which looks like it was etched into the tray. Good for dividing up other widgets into sections without taking up as much space as a label. {\ttfamily Tray\+Manager\+::create\+Separator} takes a tray location, name, and an optional width. If the width is not specified, the behaviour is the same as a Label\textquotesingle{}s.\hypertarget{trays_autotoc_md299}{}\doxysubsubsection{Slider}\label{trays_autotoc_md299}
A slider bar consists of a container box, a small text box to display the value, and a track + handle. Sliders are type-\/agnostic. Using three parameters -\/ a minimum value, a maximum value, and the number of \char`\"{}snapping points\char`\"{}, you can give your slider track of any kind of discrete scale -\/ integer, floating point, or even nominal. Snapping points are basically the \char`\"{}steps\char`\"{} on your slider track. By specifying how many of them there are, you are in effect specifying an entire range of values all the way from your minimum value to your maximum value. Let\textquotesingle{}s say you have minimum value 0, maximum value 1, and 6 snapping points. Underneath the surface, each slider stores a floating point value, so in this case you would be able to display 6 floating point values\+: \{0, 0.\+2, 0.\+4, 0.\+6, 0.\+8, 1\}. The slider will display your value in the cleanest way possible (using {\ttfamily \mbox{\hyperlink{class_ogre_1_1_string_converter_a1ca7f17dfe0a0d60cfd4aa4eae388a1a}{Ogre\+::\+String\+Converter\+::to\+String}}}). This means that if all your values happen to land on integers, then they will be displayed as integers without decimals. You can also exploit this by using your slider\textquotesingle{}s integer values as indices into an array of string values, and manually set your slider\textquotesingle{}s value to the new string value. Basically, you can make your slider display things like Low, Medium, High, 1/4, 3/4, \$4.\+00, N/A, etc. This requires you to respond to slider move events. More on this in the Tray\+Listener section below. Then your Like select menus, sliders also come in two flavours -\/ thick and long. The thick style places the caption and the value box above the track, while the long style places the caption, track, and value box side by side in that order. {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a597ec173c1b424980e18fd92e0c56905}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Thick\+Slider}}} takes a tray location, name, caption, total width, value box width, minimum value, maximum value, and the number of snapping points. {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a321429ade975d3a63dfc1125b4375e78}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Long\+Slider}}} takes a an optional total width, track width, value box width, minimum value, maximum value, and the number of snapping points. If the total width is not specified, the slider will automatically scale to fit the track, the value box, and the caption text. You can get/set the slider\textquotesingle{}s caption, displayed value, actual value, and range of values. When you change the range, the value is reset to be the minimum value. When you change the value, you also have the option of not firing an event. To respond to slider move events, see the Tray\+Listener section below.\hypertarget{trays_autotoc_md300}{}\doxysubsubsection{Params\+Panel}\label{trays_autotoc_md300}
This panel displays an arbitrary number of parameters and their values. This could be anything you want. For example, the stats panel in the S\+DK samples shows the average framerate, best framerate, batch count, etc. The details panel in the S\+DK samples shows the texture filtering technique, the polygon mode, and the camera position and orientation. To create a Params\+Panel, use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a5ae6b66603e05193b3077f30900209eb}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Params\+Panel}}}, which takes a tray location, a name, a width, and then either a string vector of parameter names or the number of parameters (lines) to leave room for. The parameter names will be left justified, and their values will be right justified on the same line. At any time, you can set/get the parameter names and values either one at a time, or all at once using a string vector.\hypertarget{trays_autotoc_md301}{}\doxysubsubsection{Check\+Box}\label{trays_autotoc_md301}
Self-\/explanatory. {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a7433f3e89c5b3a1b1b0012dfcb121f1d}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Check\+Box}}} takes a tray location, name, caption, and an optional width. Unspecified width means auto-\/fit to caption. You can set/get the state of the check box, with the option of not triggering an event. To respond to check box state change events, see the Tray\+Listener section below. \hypertarget{trays_autotoc_md302}{}\doxysubsubsection{Decor\+Widget}\label{trays_autotoc_md302}
This widget takes any Overlay\+Element template, and creates a widget out of it. If you want to put your own picture, icons, or other static objects into the trays, make an Overlay\+Element template out of it, and then turn it into a Decor\+Widget. {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a24d1b3a3b95ddcf274bf899b7600deba}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Decor\+Widget}}} takes a tray location, a name, and an Overlay\+Element template name. These are basically the same things you would normally use to create an Overlay\+Element from a template. The O\+G\+RE logo in the S\+DK samples is a Decor\+Widget. \hypertarget{trays_autotoc_md303}{}\doxysubsubsection{Progress\+Bar}\label{trays_autotoc_md303}
A progress bar with a caption, a comment/details box, and a meter that fills up. {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a431a347db6465bbf66af82ef363c875f}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Progress\+Bar}}} takes a tray location, a name, a caption, a total width, and comment box width. You can use progress bars to show any kind of progress you want, but for the most common kind (loading resources), there\textquotesingle{}s a special instance of Progress\+Bar already created by Tray\+Manager which you can use. See Loading Bar below.\hypertarget{trays_autotoc_md304}{}\doxysubsubsection{The Null Tray}\label{trays_autotoc_md304}
In addition to the nine trays you can place your widgets in, there is also a \char`\"{}null tray\char`\"{}. This is an imaginary tray, whose location is specified by {\ttfamily T\+L\+\_\+\+N\+O\+NE}. This tray is virtual, invisible, and does not arrange widgets within it. Basically, if you place a widget in this tray, it becomes \char`\"{}free-\/floating\char`\"{}, and you\textquotesingle{}re allowed to manually position it anywhere on the screen. Widgets must always reside in a tray for as long as they exist, so when a widget is removed from a tray, it is automatically placed in the null tray.\hypertarget{trays_special-widgets}{}\doxysubsection{Special Widgets}\label{trays_special-widgets}
Some widgets are so common they deserve special treatment.\hypertarget{trays_autotoc_md305}{}\doxysubsubsection{Frame Stats}\label{trays_autotoc_md305}
This is not exactly one widget, but a combination of Label that displays the current F\+PS, and a Params\+Panel that displays advanced frame statistics (such as average F\+PS and batch count). Use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a49e2f792fee94e75b1b472826bcc8019}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Frame\+Stats}}} and {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a1c2e9618a3e6b061a9cfeac4f2cb55e9}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Frame\+Stats}}} to show/hide this special widget. You can choose where to put it. When the user clicks the F\+PS label, it toggles the visibility of the advanced frame stats, so they can be out of the way when they\textquotesingle{}re unwanted. You can also manually toggle the visibility of the advanced frame stats using {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_aed00f8a1009f2ebf6806774cb894d0d7}{Ogre\+Bites\+::\+Tray\+Manager\+::toggle\+Advanced\+Frame\+Stats}}}.\hypertarget{trays_autotoc_md306}{}\doxysubsubsection{Logo}\label{trays_autotoc_md306}
This is just a decor widget of the O\+G\+RE logo. Use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_affee57f47066e25437649d64daaa7dd9}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Logo}}} and {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_ac1ee637b7ef5e887170c8a9aca1c4c7b}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Logo}}} to show/hide the logo. You can choose where to put it.\hypertarget{trays_autotoc_md307}{}\doxysubsubsection{Loading Bar}\label{trays_autotoc_md307}
This is a progress bar that shows you the progress of your current resource loading job. The comment box will show the current resource being loaded. Use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_acec7b35846346ca3937a575f5c696ffd}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Loading\+Bar}}} before you begin your loading job. Specify the number of resource groups you will initialise, the number of groups you will load, and, if you want to, the proportion of time you think will go to initialisation (default estimate is 70\%). You cannot decide where to place this loading bar. The screen will be darkened, and the loading bar will appear in the center. Any other dialog or loading bar will be closed. When you finish your loading job, call {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_aab014a2c48c8f91556182e42684d44ad}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Loading\+Bar}}}.\hypertarget{trays_autotoc_md308}{}\doxysubsubsection{Information Dialog}\label{trays_autotoc_md308}
This is a dialog which tells the user something and displays an OK button. It\textquotesingle{}s a combination of a Text\+Box and a Button. Use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_abf3bd8e4ef9a6d0d76f27535a6010623}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Ok\+Dialog}}} to display an information dialog. Specify the caption of the Text\+Box, and the message you want to display in it. Any other dialog or loading bar will be closed. The screen will be darkened, and the dialog will appear in the center. All other widget interactions are disabled until the dialog is closed. You can manually close a dialog using {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_af5d95dcaa7c74d3345308e4f4e3035e8}{Ogre\+Bites\+::\+Tray\+Manager\+::close\+Dialog}}}. To respond to information dialog closing events, see the Tray\+Listenersection below.\hypertarget{trays_autotoc_md309}{}\doxysubsubsection{Question Dialog}\label{trays_autotoc_md309}
Same as the Information Dialog except it asks the user something and displays a Yes button and a No button. Use {\ttfamily \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a85d47aa11d761742884dc6457ec11cdf}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Yes\+No\+Dialog}}} to display a question dialog. Specify the caption of the Text\+Box, and the question you want to display in it. To respond to question dialog closing events, see the Tray\+Listener section below.\hypertarget{trays_tray-listener}{}\doxysubsection{Tray\+Listener}\label{trays_tray-listener}
This class contains handlers for all the different events that your widgets can fire. The Tray\+Manager class itself is an Tray\+Listener, because it responds to events from its special widgets. You should extend your sample class from Tray\+Listener as well as Sample if you want to handle widget events. If you\textquotesingle{}re using Sdk\+Sample, you\textquotesingle{}re all set because it\textquotesingle{}s already an Tray\+Listener. Some widgets give you an option of not firing an event when you change their state. This is helpful for initialising or resetting a widget, in which case there shouldn\textquotesingle{}t be a response of any sort. For example, if you\textquotesingle{}re initialising your slider bar before the scene is set up, and your slider bar is used to control some part of your scene, firing an event would cause an error. Below is a list of the different handlers. All handlers have return type void.
\begin{DoxyItemize}
\item {\bfseries{button\+Hit}}\+: Gives you a pointer to the Button which was hit.
\item {\bfseries{item\+Selected}}\+: Gives you a pointer to the Select\+Menu the item was chosen from. You can then use the Select\+Menu to see which item was selected.
\item {\bfseries{label\+Hit}}\+: Gives you a pointer to the Label that was clicked.
\item {\bfseries{slider\+Moved}}\+: Gives you a pointer to the Slider whose value was changed. You can then use the Slider to see what its new value is. Also, you can convert this value into a more suitable form and display it using Slider\+::set\+Displayed\+Value.
\item {\bfseries{check\+Box\+Toggled}}\+: Gives you a pointer to the Check\+Box whose state was changed. You can then use the Check\+Box to see if it\textquotesingle{}s been checked or unchecked.
\item {\bfseries{ok\+Dialog\+Closed}}\+: Gives you the message of the OK dialog that was closed.
\item {\bfseries{yes\+No\+Dialog\+Closed}}\+: Gives you the question of the Yes-\/\+No dialog that was closed, and a boolean indicating whether or not the Yes button was pressed.
\end{DoxyItemize}\hypertarget{trays_things-to-try}{}\doxysubsection{Things to Try}\label{trays_things-to-try}
Getting access to widgets\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{Button* b;}
\DoxyCodeLine{b = (Button*)mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a97c3f74f3b947200c6fed0c465b78556}{getWidget}}(\textcolor{stringliteral}{"MyButton"});  \textcolor{comment}{// by name}}
\DoxyCodeLine{b = (Button*)mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a97c3f74f3b947200c6fed0c465b78556}{getWidget}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}}, 0);  \textcolor{comment}{// by tray and position}}
\DoxyCodeLine{b = (Button*)mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a97c3f74f3b947200c6fed0c465b78556}{getWidget}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}}, \textcolor{stringliteral}{"MyButton"});  \textcolor{comment}{// by tray and name}}
\DoxyCodeLine{b = (Button*)mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_ad14e715431ce4375119e2aaad852db10}{getWidgets}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}}).front();  \textcolor{comment}{// by tray}}
\end{DoxyCode}
 Counting widgets\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{int} n = mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a992a25c65079b1882fd29806d5d4467b}{getNumWidgets}}();  \textcolor{comment}{// total}}
\DoxyCodeLine{\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{int} n = mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a992a25c65079b1882fd29806d5d4467b}{getNumWidgets}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}});  \textcolor{comment}{// by tray}}
\end{DoxyCode}
 Moving widgets to other trays\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}}(b, \mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530ae4e5c068e88e5c0561a2c30dca2ec5a5}{TL\_TOP}});}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}}(b, \mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6a2d593eb6164a5b842e985e8252c3bd}{TL\_BOTTOM}}, 1);}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6a2d593eb6164a5b842e985e8252c3bd}{TL\_BOTTOM}}, 1, \mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6bc278d85090ab3af3dc01472c1a83f2}{TL\_RIGHT}}, 3);}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6bc278d85090ab3af3dc01472c1a83f2}{TL\_RIGHT}}, 3, \mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6a2d593eb6164a5b842e985e8252c3bd}{TL\_BOTTOM}});}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}}(\textcolor{stringliteral}{"MyButton"}, \mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530ae4e5c068e88e5c0561a2c30dca2ec5a5}{TL\_TOP}});}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530ae4e5c068e88e5c0561a2c30dca2ec5a5}{TL\_TOP}}, \textcolor{stringliteral}{"MyButton"}, \mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}});}
\end{DoxyCode}
 Removing widgets from trays\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_ac2f939d0bd36af335a78589b462506e9}{removeWidgetFromTray}}(b);}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_ac2f939d0bd36af335a78589b462506e9}{removeWidgetFromTray}}(\textcolor{stringliteral}{"MyButton"});}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_ac2f939d0bd36af335a78589b462506e9}{removeWidgetFromTray}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}}, 0);}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}}(b, \mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a04a1085bdee61d7234849663cce08664}{TL\_NONE}});}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a77ba6e4d641c146e262b6cdd2c8b04a0}{clearTray}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}});}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a9787ec5e8989bf6cfa89d03c6ddd27b6}{clearAllTrays}}();}
\end{DoxyCode}
 Destroying widgets\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a4ba9ec359b55a612fc860f69cecd96a7}{destroyWidget}}(b);}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a4ba9ec359b55a612fc860f69cecd96a7}{destroyWidget}}(\textcolor{stringliteral}{"MyButton"});}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a4ba9ec359b55a612fc860f69cecd96a7}{destroyWidget}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}}, 0);}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a4a89cd6f7d87e0e538aa842f1a42a7bc}{destroyAllWidgetsInTray}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}});}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_aadb1f5a3b7e3b5397b10bdd3449e1603}{destroyAllWidgets}}();}
\end{DoxyCode}
 Finding the position of a widget in a tray\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{int} pos = mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_aa993d2b60cfbcb903aecbff1c4896b67}{locateWidgetInTray}}(b);}
\end{DoxyCode}
 Finding the tray a widget is in\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530}{TrayLocation}} trayLoc = b-\/>getTrayLocation();}
\end{DoxyCode}
 Changing the tray listener object\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a3235fea714a0c61e463dee69ae308be8}{setListener}}(newListener);}
\end{DoxyCode}
 Toggling system visibility\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a075805136b2241cbb03eeb2c3d27b40d}{showAll}}();}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a188f1d5f5ca16af3b28d11ecd553105a}{hideAll}}();}
\end{DoxyCode}
 Changing horizontal widget alignment in one tray\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_adfbbc97615fd5f1a939be6e7a1f00c07}{setTrayWidgetAlignment}}(\mbox{\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}}, \mbox{\hyperlink{group___overlays_gga3396780cdb2d731aa5e4389148bdc5f3a270f18cf07dbe4e75e1b790d02924205}{GHA\_RIGHT}});}
\end{DoxyCode}
 Changing spacing and padding\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a33a3e3f66a3989dd3de48b4c4577422f}{setWidgetSpacing}}(5);}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a52d3fc8638533540232232c37b257de6}{setWidgetPadding}}(3);}
\DoxyCodeLine{mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a866229b6d88dc9d3a609115eaab46e67}{setTrayPadding}}(12);}
\end{DoxyCode}
 Casting 3D ray from under cursor into the scene\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{Ray r = mTrayMgr-\/>\mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a9dd5d303968329462e9bf4225f59722e}{getCursorRay}}(mCamera);}
\end{DoxyCode}
 Casting 3D ray from any 2D screen coordinate into the scene\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{Ray r = \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_a6833f46b0303b559a050f310fa0204fc}{OgreBites::TrayManager::screenToScene}}(mCamera, \mbox{\hyperlink{namespace_ogre_a8542e5da4c0e0bda0d0bf5745329ea88}{Vector2}}(320, 240));}
\end{DoxyCode}
 Converting a 3D scene coordinate to a 2D screen coordinate\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{namespace_ogre_a8542e5da4c0e0bda0d0bf5745329ea88}{Vector2}} p = \mbox{\hyperlink{class_ogre_bites_1_1_tray_manager_aa7a456c2c0c37123e2ab0e497f2c0ccc}{OgreBites::TrayManager::sceneToScreen}}(mCamera, Vector3::ZERO);}
\end{DoxyCode}
 \hypertarget{volume}{}\doxysection{Volume Component}\label{volume}
Welcome to the Volume Component of O\+G\+RE. It is a component to render volumes. It can handle any volume data but featurewise has a tedency towards terrains. The terrain aspect means, that it\textquotesingle{}s all about huge meshes being displayed with high performance via a level of detail mechanism. Thanks to volume rendering, caves, cliffes, holes and similar geometry can be displayed. Also constructive solid geometry gets easy.

A dense list of the features\+:
\begin{DoxyItemize}
\item Volume Rendering via Dual Marching Cubes
\item L\+OD mechanism via a chunk tree and marching squares skirts for crack patching
\item Data-\/\+Sources\+: 3D Textures with density values and the ability to buildup a C\+S\+G-\/\+Tree with 3D Textures, Spheres, Cubes, Planes, Intersection, Union, Difference and Negation, Simplex\+Noise addition
\item Loading a 3D Texture Scene from config files
\item An own file format for discrete density values which compresses a lot better
\item Realtime editing
\item Serialization and Deserialization from and to an own file format for discrete density values which compresses a lot better than 3D textures
\item A triplanar texturing example material
\item A triplanar texturing Sub\+Render\+State for the R\+T\+SS
\end{DoxyItemize}

This documentation is only intended for the usage of the Volume Component, not the algorithms which make it work. If you want to get to know the theory behind it, you can read the articles on this page\+: \href{http://volume-gfx.com/}{\texttt{ http\+://volume-\/gfx.\+com/}}\hypertarget{volume_howto}{}\doxysubsection{How to use it}\label{volume_howto}
Here is an example loading the volume scene from a configuration file. The configuration file must be findable by the resource system of course. Only \char`\"{}\+Ogre\+Volume\+Chunk.\+h\char`\"{} has to be included. 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk}{Ogre::Volume::Chunk}} *volumeRoot = \mbox{\hyperlink{group___general_gab5fc1358fd5a889de0a06d07e45df1ff}{OGRE\_NEW}} \mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk}{Ogre::Volume::Chunk}}();}
\DoxyCodeLine{SceneNode *volumeRootNode = mSceneMgr-\/>getRootSceneNode()-\/>createChildSceneNode(\textcolor{stringliteral}{"VolumeParent"});}
\DoxyCodeLine{volumeRoot-\/>\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk_a9557d5a30cbf29a46d4f8246a1e6d176}{load}}(volumeRootNode, mSceneMgr, \textcolor{stringliteral}{"volumeTerrain.cfg"});}
\end{DoxyCode}
 The first line creates the volume chunk which is the Movable\+Object holding the Volume-\/\+Root. Next, a Scene\+Node is created where the volume(-\/tree) is attached to. And lastly, the volume is loaded from the configuration file \char`\"{}volume\+Terrain.\+cfg\char`\"{}. m\+Scene\+Mgr is the Scene\+Manager who should show the volume. Later, when you don\textquotesingle{}t need it anymore, you have to free the volume\+Root Chunk via O\+G\+R\+E\+\_\+\+D\+E\+L\+E\+TE.\hypertarget{volume_creation}{}\doxysubsection{Manual creation of a C\+S\+G-\/\+Tree}\label{volume_creation}
This example skips the configuration file and loads a simple C\+S\+G-\/\+Scene\+: An union of a 3D Texture and a sphere with 5 L\+OD levels. It also setups a material L\+OD system. First, create a sphere with the radius 5 at the coordinates 128, 150, 128\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_volume_1_1_c_s_g_sphere_source}{Ogre::Volume::CSGSphereSource}} sphere (5, \mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(128, 150, 128));}
\end{DoxyCode}
 Now a 3D texture from \char`\"{}volume\+Terrain\+Big.\+dds\char`\"{} which has the world dimensions 256, 256, 256. The next flag indicates that the trilinear interpolation of the value-\/selection should be activated. We switch off the trilinear interpolation and the sobel filter of the normal for the sake of faster loading times\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_volume_1_1_texture_source}{Ogre::Volume::TextureSource}} volumeTexture (\textcolor{stringliteral}{"volumeTerrainBig.dds"}, 256, 256, 256, \textcolor{keyword}{true}, \textcolor{keyword}{false}, \textcolor{keyword}{false});}
\end{DoxyCode}
 Now combine them\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_volume_1_1_c_s_g_union_source}{Ogre::Volume::CSGUnionSource}} unionSrc (\&sphere, \&volumeTexture);}
\end{DoxyCode}
 Set the general parameters, see the comments for their meaning\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters}{Ogre::Volume::ChunkParameters}} parameters;}
\DoxyCodeLine{parameters.\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a3e154a179b8c824f79b1b426608743ad}{sceneManager}} = mSceneMgr;       \textcolor{comment}{// The SceneManager to use}}
\DoxyCodeLine{parameters.\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a111c9e9333e7ae3497fc818190a03fd8}{src}} = \&unionSrc;                \textcolor{comment}{// The just created density source.}}
\DoxyCodeLine{parameters.\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a4444eac27c71e02886615dcf7fbfed27}{baseError}} = (\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}})1.8;          \textcolor{comment}{// The error of the highest LOD-\/level}}
\DoxyCodeLine{parameters.\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_aa6186649b7323f937b83828eb86711fa}{errorMultiplicator}} = (\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}})0.9; \textcolor{comment}{// The factor between each LOD-\/level (error = baseError * errorMultiplicator  * level)}}
\DoxyCodeLine{parameters.\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a986b4a97b153d50f65603ab507bb4614}{skirtFactor}} = (\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}})0.7;        \textcolor{comment}{// Controls how long the skirts are. The lower the number, the shorter the skirts are. This saves geometry. But if they are too short, cracks might occure.}}
\DoxyCodeLine{parameters.\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_af6ed62b76c67d04eb98424414fb1dc72}{scale}} = 10;                     \textcolor{comment}{// The displayed volume will be scaled by this factor.}}
\DoxyCodeLine{parameters.\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_ae125003c00de0d6c0a1a4bd6b99c4ebf}{maxScreenSpaceError}} = 30;       \textcolor{comment}{// The screen space error controlling when the LOD-\/levels change.}}
\end{DoxyCode}


Create the root-\/chunk and load now. The two vectors define the area to be scanned in the volume-\/source. The following integer determines the amount of L\+O\+D-\/levels. 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk}{Ogre::Volume::Chunk}} *volumeRoot = \mbox{\hyperlink{group___general_gab5fc1358fd5a889de0a06d07e45df1ff}{OGRE\_NEW}} Chunk();}
\DoxyCodeLine{volumeRoot-\/>\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk_a9557d5a30cbf29a46d4f8246a1e6d176}{load}}(mVolumeRootNode, Vector3::ZERO, \mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(256), 5, \&parameters);}
\end{DoxyCode}
 Now setup the global volume material\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{volumeRoot-\/>\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk_a5129bccc53d17060635ada67443324f7}{setMaterial}}(\textcolor{stringliteral}{"triplanarReference"});}
\end{DoxyCode}
 \hypertarget{volume_triangles}{}\doxysubsection{Getting the triangles of the chunks}\label{volume_triangles}
When you want to integrate the volume triangles in a physics engine for example, you need to hand over the exact triangles. For this scenario, the Chunk\+Parameters hold a pointer to a \textquotesingle{}\textquotesingle{}Mesh\+Builder\+Callback\textquotesingle{}\textquotesingle{} and a number \textquotesingle{}\textquotesingle{}lod\+Callback\+Lod\textquotesingle{}\textquotesingle{}. The first is an interface with a single function \textquotesingle{}\textquotesingle{}triangles\+Ready\textquotesingle{}\textquotesingle{} which is called, when the triangles of a chunk are ready. The chunks are chosen via the \textquotesingle{}\textquotesingle{}lod\+Callback\+Lod\textquotesingle{}\textquotesingle{}. If you build a volume with 3 L\+OD levels and you want the triangles of the highest detail level, you set this parameter to 3. Example\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{keyword}{class }MyMeshBuilderCallback : \textcolor{keyword}{public} MeshBuilderCallback}
\DoxyCodeLine{\{}
\DoxyCodeLine{\textcolor{keyword}{public}:}
\DoxyCodeLine{    \textcolor{keyword}{virtual}  ready(\textcolor{keyword}{const} SimpleRenderable *simpleRenderable, \textcolor{keyword}{const} \mbox{\hyperlink{group___volume_ga42533278f4be6a1aeae58d18255d0ca1}{VecVertex}} \&vertices, \textcolor{keyword}{const} \mbox{\hyperlink{group___volume_ga00db3f974951d99d4a0902580eeb8151}{VecIndices}} \&indices, \textcolor{keywordtype}{size\_t} level, \textcolor{keywordtype}{int} inProcess)}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        \textcolor{keywordtype}{size\_t} count = indices.size();}
\DoxyCodeLine{        \textcolor{keywordflow}{for} (\textcolor{keywordtype}{size\_t} i = 0; i < count; i += 3)}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            \mbox{\hyperlink{group___volume_ga90facc4b1e8fd828ae06b8edd0f5b701}{Vertex}} v1 = vertices[indices[i]];}
\DoxyCodeLine{            \mbox{\hyperlink{group___volume_ga90facc4b1e8fd828ae06b8edd0f5b701}{Vertex}} v2 = vertices[indices[i + 1]];}
\DoxyCodeLine{            \mbox{\hyperlink{group___volume_ga90facc4b1e8fd828ae06b8edd0f5b701}{Vertex}} v3 = vertices[indices[i + 2]];}
\DoxyCodeLine{            \textcolor{comment}{// Do something with the Triangle...}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \}}
\DoxyCodeLine{\};}
\end{DoxyCode}


And using it like this\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{group___volume_ga89fbc5eed010b8802358563eb88e674a}{ChunkParameters}} parameters;}
\DoxyCodeLine{...}
\DoxyCodeLine{MyMeshBuilderCallback callback;}
\DoxyCodeLine{parameters.\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a6403e2875cc7b81aefd43ba9f22c2b31}{lodCallback}} = \&callback;}
\DoxyCodeLine{parameters.lodCallbackLod = 3;}
\DoxyCodeLine{...}
\DoxyCodeLine{rootChunk-\/>load(parent, from, to, 3, \&parameters);}
\end{DoxyCode}
 Or in case of loading from a configuration file\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{MyMeshBuilderCallback callback;}
\DoxyCodeLine{rootChunk-\/>load(parent, sceneManager, \textcolor{stringliteral}{"myVolume.cfg"}, 0, \&callback, 3);}
\end{DoxyCode}


You might have seen, that a pointer to a Simple\+Renderable is handed in, too. This is actually the Chunk whose triangles are loaded. It\textquotesingle{}s parent class is used to not create a circular dependency. You might get the triangle data from it, too by getting the Renderoperation.\hypertarget{volume_intersecting}{}\doxysubsection{Intersecting a ray with a volume}\label{volume_intersecting}
When you want to do something exactly on the volume surface, you can cast rays and find their first intersection point. Behold that the triangle representation might be slightly different than the actual volume surface. And you have to scale the ray origin just like the volume. Here is an example which uses the negative z-\/axis of the camera as ray as it might be done like in an ego-\/shooter\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{Ray ray(mCamera-\/>getPosition() / rootChunk-\/>getScale(), -\/mCamera-\/>getOrientation().zAxis());}
\DoxyCodeLine{\mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}} intersection;}
\DoxyCodeLine{\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}} scale = mVolumeRoot-\/>getChunkParameters()-\/>scale;}
\DoxyCodeLine{\textcolor{keywordtype}{bool} intersects = mVolumeRoot-\/>getChunkParameters()-\/>src-\/>getFirstRayIntersection(ray, intersection, scale);}
\DoxyCodeLine{\textcolor{keywordflow}{if} (intersects)}
\DoxyCodeLine{\{}
\DoxyCodeLine{    intersection *= scale; \textcolor{comment}{// As it is in volume space.}}
\DoxyCodeLine{    \textcolor{comment}{// Do something with intersection.}}
\DoxyCodeLine{\}}
\end{DoxyCode}
\hypertarget{volume_editing}{}\doxysubsection{Editing a Volume made from a Grid\+Source}\label{volume_editing}
A usecase is realtime editing of volume terrain as seen as in the sample. Let\textquotesingle{}s union the terrain with a sphere of the radius 2.\+5 and the center 123/123/123. {\bfseries{volume\+Root}} is the Chunk instance with which the terrain was initially loaded. The factor 1.\+5 is just to have a save border arround the sphere which also gets updated. The rest of the parameters are 5 L\+OD levels and a volume mesh covering an area of 384$^\wedge$3. 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}} center(123);}
\DoxyCodeLine{\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}} radius = (\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}})2.5;}
\DoxyCodeLine{CSGSphereSource sphere(radius, center);}
\DoxyCodeLine{CSGUnionSource operation;}
\DoxyCodeLine{static\_cast<GridSource*>(volumeRoot-\/>\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk_acdc6b1e00c67353f3317e1e0ce6d19d9}{getChunkParameters}}()-\/>\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a111c9e9333e7ae3497fc818190a03fd8}{src}})-\/>combineWithSource(\&operation, \&sphere, center, radius * (\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}})1.5);}
\DoxyCodeLine{volumeRoot-\/>\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk_acdc6b1e00c67353f3317e1e0ce6d19d9}{getChunkParameters}}()-\/>\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_aeefacd1d618206fcb432ed947b58e06e}{updateFrom}} = center -\/ radius * (\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}})1.5;}
\DoxyCodeLine{volumeRoot-\/>\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk_acdc6b1e00c67353f3317e1e0ce6d19d9}{getChunkParameters}}()-\/>\mbox{\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_afe30999e8cc71a1f48d87d68bf43059d}{updateTo}} = center + radius * (\mbox{\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}})1.5;}
\DoxyCodeLine{volumeRoot-\/>\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk_a9557d5a30cbf29a46d4f8246a1e6d176}{load}}(volumeRootNode, Vector3::ZERO, \mbox{\hyperlink{namespace_ogre_ac94fc4008c1165dea017263fee56b273}{Vector3}}(384), 5, volumeRoot-\/>\mbox{\hyperlink{class_ogre_1_1_volume_1_1_chunk_acdc6b1e00c67353f3317e1e0ce6d19d9}{getChunkParameters}}());}
\end{DoxyCode}
 \hypertarget{manual-mesh-creation}{}\doxysection{Manual mesh creation}\label{manual-mesh-creation}
There are two ways to create your own mesh. The first way is to create a \mbox{\hyperlink{class_ogre_1_1_mesh}{Ogre\+::\+Mesh}} instance and provide it with the vertex and index buffers directly.

The second way is the high level \mbox{\hyperlink{class_ogre_1_1_manual_object}{Ogre\+::\+Manual\+Object}} interface. Instead of filling position and color buffers, you simply call the \char`\"{}position\char`\"{} and \char`\"{}colour\char`\"{} functions.\hypertarget{manual-mesh-creation_autotoc_md283}{}\doxysubsection{Using Manual Object}\label{manual-mesh-creation_autotoc_md283}
Building one-\/off geometry objects manually usually requires getting down and dirty with the vertex buffer and vertex declaration A\+PI, which some people find a steep learning curve. This class gives you a simpler interface specifically for the purpose of building a 3D object simply and quickly. Note that if you intend to instance your object you will still need to become familiar with the Mesh class.

This class draws heavily on the interface for Open\+GL immediate-\/mode ({\ttfamily gl\+Begin}, {\ttfamily gl\+Vertex}, {\ttfamily gl\+Normal} etc), since this is generally well-\/liked by people. There are a couple of differences in the results though -\/ internally this class still builds hardware buffers which can be re-\/used, so you can render the resulting object multiple times without re-\/issuing all the same commands again. Secondly, the rendering is not immediate, it is still queued just like all O\+G\+RE objects. This makes this object more efficient than the equivalent GL immediate-\/mode commands, so it\textquotesingle{}s feasible to use it for large objects if you really want to.

To construct some geometry with this object\+:
\begin{DoxyEnumerate}
\item If you know roughly how many vertices (and indices, if you use them) you\textquotesingle{}re going to submit, call estimate\+Vertex\+Count() and estimate\+Index\+Count(). This is not essential but will make the process more efficient by saving memory reallocations.
\item Call begin() to begin entering data
\item For each vertex, call position(), normal(), texture\+Coord(), colour() to define your vertex data. Note that each time you call position() you start a new vertex. Note that the first vertex defines the components of the vertex -\/ you can\textquotesingle{}t add more after that. For example if you didn\textquotesingle{}t call normal() in the first vertex, you cannot call it in any others. You ought to call the same combination of methods per vertex.
\item If you want to define triangles (or lines/points) by indexing into the vertex list, you can call index() as many times as you need to define them. If you don\textquotesingle{}t do this, the class will assume you want triangles drawn directly as defined by the vertex list, i.\+e. non-\/indexed geometry. Note that stencil shadows are only supported on indexed geometry, and that indexed geometry is a little faster; so you should try to use it.
\item Call end() to finish entering data.
\item Optionally repeat the begin-\/end cycle if you want more geometry using different rendering operation types, or different materials After calling end(), the class will organise the data for that section internally and make it ready to render with. Like any other Movable\+Object you should attach the object to a Scene\+Node to make it visible. Other aspects like the relative render order can be controlled using standard Movable\+Object methods like set\+Render\+Queue\+Group.
\end{DoxyEnumerate}

You can also use begin\+Update() to alter the geometry later on if you wish. If you do this, you should call set\+Dynamic(true) before your first call to begin(), and also consider using estimate\+Vertex\+Count() / estimate\+Index\+Count() if your geometry is going to be growing, to avoid buffer recreation during growth.

\begin{DoxyNote}{Note}
like all O\+G\+RE geometry, triangles should be specified in anti-\/clockwise winding order (whether you\textquotesingle{}re doing it with just vertices, or using indexes too). That is to say that the front of the face is the one where the vertices are listed in anti-\/clockwise order.
\end{DoxyNote}
\hypertarget{manual-mesh-creation_autotoc_md284}{}\doxysubsubsection{Example}\label{manual-mesh-creation_autotoc_md284}
We will use the Manual\+Object to create a single textured plane. After creating the object, we start a new geometry block that will use the given material


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_manual_object}{Ogre::ManualObject}}* man = mSceneMgr-\/>createManualObject(\textcolor{stringliteral}{"test"});}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a70d5945478fbc7fa056cecd88fdf2781}{begin}}(\textcolor{stringliteral}{"Examples/OgreLogo"}, \mbox{\hyperlink{class_ogre_1_1_render_operation_a7a272218dae54048c87f31176c19e10da8c00ee152b44fe8000c2fd675437c087}{Ogre::RenderOperation::OT\_TRIANGLE\_LIST}});}
\end{DoxyCodeInclude}
 Next we specify the vertices of the plane


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a9986bd2627b75deeba14636c81efcde0}{position}}(-\/20, 20, 20);}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a59c0b0a41e2a4ced5ff89589c9a924a1}{normal}}(0, 0, 1);}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a64854d64967680d2294788768ebbd1d7}{textureCoord}}(0, 0);}
\DoxyCodeLine{}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a9986bd2627b75deeba14636c81efcde0}{position}}(-\/20, -\/20, 20);}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a59c0b0a41e2a4ced5ff89589c9a924a1}{normal}}(0, 0, 1);}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a64854d64967680d2294788768ebbd1d7}{textureCoord}}(0, 1);}
\DoxyCodeLine{}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a9986bd2627b75deeba14636c81efcde0}{position}}(20, -\/20, 20);}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a59c0b0a41e2a4ced5ff89589c9a924a1}{normal}}(0, 0, 1);}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a64854d64967680d2294788768ebbd1d7}{textureCoord}}(1, 1);}
\DoxyCodeLine{}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a9986bd2627b75deeba14636c81efcde0}{position}}(20, 20, 20);}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a59c0b0a41e2a4ced5ff89589c9a924a1}{normal}}(0, 0, 1);}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a64854d64967680d2294788768ebbd1d7}{textureCoord}}(1, 0);}
\end{DoxyCodeInclude}
 Now we can define the face. Ogre will split the quad into triangles for us.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a1ac70dbc6f35180d5c8bab671c3f2257}{quad}}(0, 1, 2, 3);}
\end{DoxyCodeInclude}
 Calling {\ttfamily end()} creates the actual Hardware Buffers to be used for rendering and we can attach the Object to a \mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}}.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{    man-\/>\mbox{\hyperlink{class_ogre_1_1_manual_object_a49d6bfe460ff1e0178c6d77b95d3dc5a}{end}}();}
\DoxyCodeLine{    mSceneMgr-\/>getRootSceneNode()-\/>createChildSceneNode()-\/>attachObject(man);}
\end{DoxyCodeInclude}
 In case you need multiple Ogre\+::\+Entities of the plane, you should call \mbox{\hyperlink{class_ogre_1_1_manual_object_a657275e617d9558951a3037f02b07efe}{Ogre\+::\+Manual\+Object\+::convert\+To\+Mesh}} first and then use \mbox{\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{Ogre\+::\+Scene\+Manager\+::create\+Entity}} as usual.\hypertarget{manual-mesh-creation_autotoc_md285}{}\doxysubsection{Using vertex and index buffers directly}\label{manual-mesh-creation_autotoc_md285}
This time we are going to create a plane using the lower level \mbox{\hyperlink{class_ogre_1_1_hardware_buffer}{Ogre\+::\+Hardware\+Buffer}} primitives.

We start by creating a Mesh object. As this is a manual Mesh, we have to set the bounds of it explicitly. 
\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{keyword}{using namespace }\mbox{\hyperlink{namespace_ogre}{Ogre}};}
\DoxyCodeLine{}
\DoxyCodeLine{        \mbox{\hyperlink{class_ogre_1_1_shared_ptr}{MeshPtr}} mesh = \mbox{\hyperlink{class_ogre_1_1_mesh_manager_a2efefa307b7987c5fcff7e8c47f79758}{MeshManager::getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_mesh_manager_ad99f5f2e2d045e5a4af301974e45c918}{createManual}}(yourMeshName, \mbox{\hyperlink{group___resources_gad0e16ff2458722373e3eea3b303e52da}{RGN\_DEFAULT}});}
\DoxyCodeLine{        mesh-\/>\mbox{\hyperlink{class_ogre_1_1_mesh_a8c40c34ec7c32009904c0cd730f68b5d}{\_setBounds}}(\mbox{\hyperlink{class_ogre_1_1_axis_aligned_box}{AxisAlignedBox}}(\{-\/100,-\/100,0\}, \{100,100,0\});}
\end{DoxyCode}


Next we define what should end up in our vertex and index buffer. We will store all data interleaved in one buffer. This typically has some advantages due to cache coherency and also is what Manual\+Object does automatically for us.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \textcolor{keywordtype}{float} vertices[32] = \{}
\DoxyCodeLine{            -\/100, -\/100, 0,  \textcolor{comment}{// pos}}
\DoxyCodeLine{            0,0,1,          \textcolor{comment}{// normal}}
\DoxyCodeLine{            0,1,            \textcolor{comment}{// texcoord}}
\DoxyCodeLine{            100, -\/100, 0,}
\DoxyCodeLine{            0,0,1,}
\DoxyCodeLine{            1,1,}
\DoxyCodeLine{            100,  100, 0,}
\DoxyCodeLine{            0,0,1,}
\DoxyCodeLine{            1,0,}
\DoxyCodeLine{            -\/100,  100, 0 ,}
\DoxyCodeLine{            0,0,1,}
\DoxyCodeLine{            0,0 }
\DoxyCodeLine{        \};}
\DoxyCodeLine{}
\DoxyCodeLine{        \mbox{\hyperlink{namespace_ogre_aa8263b218e7d187ad5ef03a73a6ad7fd}{uint16}} faces[6] = \{0,1,2,}
\DoxyCodeLine{                           0,2,3 \};}
\end{DoxyCodeInclude}
 However we could also split the data into multiple buffers with lower precision to save some bytes on texture coordinates and normals.

To describe the vertex sources, we have to create a \mbox{\hyperlink{class_ogre_1_1_vertex_data}{Ogre\+::\+Vertex\+Data}} object. Notably it stores how many vertices we have.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        mesh-\/>\mbox{\hyperlink{class_ogre_1_1_mesh_a1fd9968ccd424f913a7f3f68639f3ecf}{sharedVertexData}} = \textcolor{keyword}{new} VertexData();}
\DoxyCodeLine{        mesh-\/>\mbox{\hyperlink{class_ogre_1_1_mesh_a1fd9968ccd424f913a7f3f68639f3ecf}{sharedVertexData}}-\/>\mbox{\hyperlink{class_ogre_1_1_vertex_data_a0b59b63cc2dbede1c5fc6a932fd2c10d}{vertexCount}} = 4;}
\DoxyCodeLine{        VertexDeclaration* decl = mesh-\/>\mbox{\hyperlink{class_ogre_1_1_mesh_a1fd9968ccd424f913a7f3f68639f3ecf}{sharedVertexData}}-\/>\mbox{\hyperlink{class_ogre_1_1_vertex_data_abac9cde9c001b97cf1fea7fd05b79cf4}{vertexDeclaration}};}
\DoxyCodeLine{        VertexBufferBinding* bind = mesh-\/>\mbox{\hyperlink{class_ogre_1_1_mesh_a1fd9968ccd424f913a7f3f68639f3ecf}{sharedVertexData}}-\/>\mbox{\hyperlink{class_ogre_1_1_vertex_data_a1cf7dacb2a133d71620abd59cb3180b0}{vertexBufferBinding}};}
\end{DoxyCodeInclude}
 The actual description of our vertex buffer however is stored inside the \mbox{\hyperlink{class_ogre_1_1_vertex_declaration}{Ogre\+::\+Vertex\+Declaration}}.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \textcolor{keywordtype}{size\_t} offset = 0;}
\DoxyCodeLine{        offset += decl-\/>addElement(0, offset, \mbox{\hyperlink{group___render_system_gga027109503a988ba85f4c63b55082907fa9ccf920d2572b15896f75ccf30fb150c}{VET\_FLOAT3}}, \mbox{\hyperlink{group___render_system_gga0a62b3f2ede8992ff365bb013a8bc00dad04d50e91c2ec5377e610b3f5b9b07f2}{VES\_POSITION}}).getSize();}
\DoxyCodeLine{        offset += decl-\/>addElement(0, offset, \mbox{\hyperlink{group___render_system_gga027109503a988ba85f4c63b55082907fa9ccf920d2572b15896f75ccf30fb150c}{VET\_FLOAT3}}, \mbox{\hyperlink{group___render_system_gga0a62b3f2ede8992ff365bb013a8bc00da1dec7d36a64625348e23af26c9231227}{VES\_NORMAL}}).getSize();}
\DoxyCodeLine{        offset += decl-\/>addElement(0, offset, \mbox{\hyperlink{group___render_system_gga027109503a988ba85f4c63b55082907fa0993ccf616ec6e7bf60fff2ef1705ce6}{VET\_FLOAT2}}, \mbox{\hyperlink{group___render_system_gga0a62b3f2ede8992ff365bb013a8bc00da17abb855311f3a67bc31414cad8d6212}{VES\_TEXTURE\_COORDINATES}}, 0).getSize();}
\end{DoxyCodeInclude}
 Now we can continue to create the Hardware Buffers and upload our data.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        \mbox{\hyperlink{namespace_ogre_a05ef9b65d4ed446b994636e371bf5aab}{HardwareVertexBufferSharedPtr}} vbuf =}
\DoxyCodeLine{            HardwareBufferManager::getSingleton().createVertexBuffer(}
\DoxyCodeLine{                offset, 4, HardwareBuffer::HBU\_STATIC\_WRITE\_ONLY);}
\DoxyCodeLine{        vbuf-\/>\mbox{\hyperlink{class_ogre_1_1_hardware_buffer_a8c313688a0df3c28a36738c31fcbc3ee}{writeData}}(0, vbuf-\/>getSizeInBytes(), vertices, \textcolor{keyword}{true});}
\DoxyCodeLine{        bind-\/>setBinding(0, vbuf);}
\DoxyCodeLine{}
\DoxyCodeLine{        \mbox{\hyperlink{namespace_ogre_ae906cf8e579ba8ade19879ec05b1a456}{HardwareIndexBufferSharedPtr}} ibuf = HardwareBufferManager::getSingleton().createIndexBuffer(}
\DoxyCodeLine{            HardwareIndexBuffer::IT\_16BIT, 6, HardwareBuffer::HBU\_STATIC\_WRITE\_ONLY);}
\DoxyCodeLine{        ibuf-\/>\mbox{\hyperlink{class_ogre_1_1_hardware_buffer_a8c313688a0df3c28a36738c31fcbc3ee}{writeData}}(0, ibuf-\/>getSizeInBytes(), faces, \textcolor{keyword}{true});}
\end{DoxyCodeInclude}
 Note how we used the symbolical constant {\ttfamily 0} to link the \mbox{\hyperlink{class_ogre_1_1_hardware_vertex_buffer}{Ogre\+::\+Hardware\+Vertex\+Buffer}} to the \mbox{\hyperlink{class_ogre_1_1_vertex_declaration}{Ogre\+::\+Vertex\+Declaration}}. This allows the underlying Render\+System to swap Vertex\+Buffers without changing the Vertex\+Declaration. i.\+e. render different Meshes that share the same vertex layout, without changing the state.

Finally we create the \mbox{\hyperlink{class_ogre_1_1_sub_mesh}{Ogre\+::\+Sub\+Mesh}} that will be ultimately rendered.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{        SubMesh* sub = mesh-\/>\mbox{\hyperlink{class_ogre_1_1_mesh_a23d5c021503b8fac8938be4ba956f2ce}{createSubMesh}}();}
\DoxyCodeLine{        sub-\/>\mbox{\hyperlink{class_ogre_1_1_sub_mesh_a931e3764e3bf1c3ef7431fc852770fb1}{useSharedVertices}} = \textcolor{keyword}{true};}
\DoxyCodeLine{        sub-\/>indexData-\/>indexBuffer = ibuf;}
\DoxyCodeLine{        sub-\/>indexData-\/>indexCount = 6;}
\DoxyCodeLine{        sub-\/>indexData-\/>indexStart = 0;}
\end{DoxyCodeInclude}
 Note that while our Vertex\+Buffer is shared, the Index\+Buffer is not. This allows rendering different faces of the same object using different Materials. Here, each Sub\+Mesh links the faces (Index\+Buffer) to the according material.

Finally, we have to update the loading state of the mesh as 
\begin{DoxyCode}{0}
\DoxyCodeLine{mesh-\/>\mbox{\hyperlink{class_ogre_1_1_resource_a699d1c851f494a8d5d23d23b695ceb47}{load}}();}
\end{DoxyCode}
 If you have registered a \mbox{\hyperlink{class_ogre_1_1_manual_resource_loader}{Ogre\+::\+Manual\+Resource\+Loader}}, the resource loading would only happen now.

\begin{DoxyNote}{Note}
Using the \mbox{\hyperlink{class_ogre_1_1_manual_resource_loader}{Ogre\+::\+Manual\+Resource\+Loader}} is highly recommended. It allows lazy-\/loading the data on demand as well as unloading and re-\/loading resources when running out of memory. 
\end{DoxyNote}
\hypertarget{profiler}{}\doxysection{Using the Profiler}\label{profiler}
\begin{DoxyNote}{Note}
If you are using the \mbox{\hyperlink{namespace_ogre}{Ogre}} S\+DK and you want to use the Profiler, it is advisable to switch to the source code version of \mbox{\hyperlink{namespace_ogre}{Ogre}}, because the S\+DK is shipped with {\ttfamily O\+G\+R\+E\+\_\+\+P\+R\+O\+F\+I\+L\+I\+NG=O\+FF}, so instrumentation is disabled by default.
\end{DoxyNote}
First you want to initialize the Profiler like this\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_a91c40e21a3fc96003504ea21fec80d77}{setEnabled}}(\textcolor{keyword}{true});}
\end{DoxyCode}
 This sets up the media that the profiler uses. The reason this is not in the constructor is because the profiler contains media dependencies that people who aren\textquotesingle{}t using the profiler shouldn\textquotesingle{}t have to worry about. The profiler will need you to specify the main program loop. To do this, you call the following at the very beginning of the frame\+Started() function in your Frame\+Listener class\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{_ogre_profiler_8h_af9d7ab83c5a5d7de7579eebe9d27e53d}{OgreProfileBegin}}(\textcolor{stringliteral}{"Ogre Main Loop"});}
\end{DoxyCode}
 and add this at the very end of the frame\+Ended() function\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{_ogre_profiler_8h_a292ec22b5d851ef26fa9d7685c18b1f5}{OgreProfileEnd}}(\textcolor{stringliteral}{"Ogre Main Loop"});}
\end{DoxyCode}
 Make sure the names match exactly, otherwise the profiler will fail an assert. Next you want to profile some of your code. You do this by calling \mbox{\hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{Ogre\+Profile()}} and using braces (\{\}) to limit the scope. Note that Ogre\+Profile cannot be called in the same scope as another \mbox{\hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{Ogre\+Profile()}}. Doing so will result in a compile-\/time error. Here is an example of using Ogre\+Profile\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\{}
\DoxyCodeLine{   \mbox{\hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{OgreProfile}}(\textcolor{stringliteral}{"Collision Detection"});}
\DoxyCodeLine{   mISQR = mISQ-\/>execute();}
\DoxyCodeLine{\}}
\DoxyCodeLine{\{}
\DoxyCodeLine{   \mbox{\hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{OgreProfile}}(\textcolor{stringliteral}{"Collision Response"});}
\DoxyCodeLine{   SceneQueryMovableIntersectionList::iterator iter;}
\DoxyCodeLine{   \textcolor{keywordflow}{for} (iter = mISQR.movables2movables.begin(); iter != mISQR.movables2movables.end(); iter++) \{}
\DoxyCodeLine{      \textcolor{comment}{// do stuff}}
\DoxyCodeLine{      \mbox{\hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{OgreProfile}}(\textcolor{stringliteral}{"Explosions"});}
\DoxyCodeLine{      createExplosion();}
\DoxyCodeLine{   \}}
\DoxyCodeLine{\}}
\end{DoxyCode}
 If you want a profile to last outside of its scope, use \mbox{\hyperlink{_ogre_profiler_8h_af9d7ab83c5a5d7de7579eebe9d27e53d}{Ogre\+Profile\+Begin($<$name$>$)}} and \mbox{\hyperlink{_ogre_profiler_8h_a292ec22b5d851ef26fa9d7685c18b1f5}{Ogre\+Profile\+End($<$name$>$)}} like you did when creating the main loop profile.\hypertarget{profiler_profRead}{}\doxysubsection{Reading the Display}\label{profiler_profRead}
 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{profiler.jpg}}
\end{DoxyImageNoCaption}
  

On the left side are the profile names with a number in parentheses next to it. This number is the number of times this profile was called during this frame. If this number is 0, that means that the profile was called before, but is not being called currently. The bars on the left represent the frame time statistics. You can see indicators above which show that a profile can take anywhere from 0\% to 100\% of the frame time. The big yellow bars show the current frame percentage that the profile is taking. The green line shows the minimum frame time, the red line is the maximum frame time, and the blue line is the average frame time. Big discrepancies between the average and maximum can possibly be the sign of a performance bottleneck (however it could be the profiler acting strangely, see the \textquotesingle{}\textquotesingle{}Known Issues\textquotesingle{}\textquotesingle{} section). These results will be printed to the log when the application ends or you can manually do it by calling log\+Results().\hypertarget{profiler_profFeatures}{}\doxysubsection{Features}\label{profiler_profFeatures}
\hypertarget{profiler_autotoc_md286}{}\doxysubsubsection{Disabling the Profiler}\label{profiler_autotoc_md286}
You can disable the profiler by calling\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_a91c40e21a3fc96003504ea21fec80d77}{setEnabled}}(\textcolor{keyword}{false});}
\end{DoxyCode}
 and enable it again by calling\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_a91c40e21a3fc96003504ea21fec80d77}{setEnabled}}(\textcolor{keyword}{true});}
\end{DoxyCode}
 Note that this is a temporary solution. If you want to completely disable the profiler for your release version, see the section \textquotesingle{}\textquotesingle{}Release Version Considerations\textquotesingle{}\textquotesingle{}.\hypertarget{profiler_autotoc_md287}{}\doxysubsubsection{Disabling Individual Profiles}\label{profiler_autotoc_md287}
Disabling profiles can be useful if there are certain core functions that you want to profile on occasion. For example, you could profile certain rendering operations when you are checking general performance and then disable those profiles when you want to profile your AI code. You can disable a profile like this\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}}.\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_a144fc3944f41b1198a44590beda4ce3f}{disableProfile}}(\textcolor{stringliteral}{"<profile name>"});}
\end{DoxyCode}
 and you can enable it again with this\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}}.\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_a52e2f0d3530febbbf7199173d91ad4e2}{enableProfile}}(\textcolor{stringliteral}{"<profile name>"});}
\end{DoxyCode}
 Please note that trying to enable or disable a profile while that profile is running will have no effect.\hypertarget{profiler_autotoc_md288}{}\doxysubsubsection{Analyzing Application State}\label{profiler_autotoc_md288}
It is helpful to see the state of your application when a profile reaches a maximum level or some other condition. To check if a specific has reached a new maximum level, use\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}}.\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_afc737d10ba6b5732df9a538a196ee3e6}{watchForMax}}(\textcolor{stringliteral}{"<profile name>"}); \textcolor{comment}{// return true if it reaches a new maximum}}
\end{DoxyCode}
 or to see if a profile has reached a new minimum level, use\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}}.\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_ad37efd3a99cf736a0424fd0c1c92efb4}{watchForMin}}(\textcolor{stringliteral}{"<profile name>"}); \textcolor{comment}{// returns true if it reaches a new minimum}}
\end{DoxyCode}
 or to set an arbitrary level\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{comment}{//returns true when AI code takes over 60\% of the frame time}}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}}.\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_adfd868a7f9213baece5687bd36e23279}{watchForLimit}}(\textcolor{stringliteral}{"AI code"}, .6, \textcolor{keyword}{true});}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{comment}{//returns true when graphics code takes less than 10\% of the frame time}}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}}.\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_adfd868a7f9213baece5687bd36e23279}{watchForLimit}}(\textcolor{stringliteral}{"Graphics code"}, .1, \textcolor{keyword}{false});}
\end{DoxyCode}


These functions should be used at the end of the main game loop for more accuracy. Otherwise, it will represent the results of the previous frame.\hypertarget{profiler_autotoc_md289}{}\doxysubsubsection{Logging Results}\label{profiler_autotoc_md289}
You can log the results of the current profiler statistics like this\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}}.\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_a456a0f133ccea3eb515626edd22963ec}{logResults}}();}
\end{DoxyCode}
 This is called automatically when you quit your \mbox{\hyperlink{namespace_ogre}{Ogre}} application.\hypertarget{profiler_autotoc_md290}{}\doxysubsubsection{Changing the Frequency of Updating the Display}\label{profiler_autotoc_md290}
You can change how frequently the display is updated to suit your tastes like this\+: 
\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}}.\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_ac29d425e0f0b531f2c7f643907c9402d}{setUpdateDisplayFrequency}}(<numberOfFrames>);}
\end{DoxyCode}
 Basically the tradeoff is between how accurate the display is and the amount of flicker. The default is that the display is updated every 10 frames.\hypertarget{profiler_profAccuracy}{}\doxysubsection{Performance and Accuracy}\label{profiler_profAccuracy}
I\textquotesingle{}ve tried to minimize the performance hit from using the profiler. However, like anything else, it still takes some time to perform the necessary calculations. There are some steps you can take to increase the accuracy of the results. Firstly, although the profiler supports multiple calls of a profile during each frame, doing this more than a few times can cause the profiler to take significantly longer than the actual code you are trying to profile. Therefore it is recommended that you move the profile up one level (such as outside of a for loop) so that it is called fewer times.

To maximize the accuracy of a profile, it is best to remove the child profiles of the profile you are analysing. Child profiles increases the frame time of the parent due to the overhead of using the profiler.

Some tests I\textquotesingle{}ve conducted show that the profiling code will max out unexpectedly, so take the maximum frame time value with a grain of salt (See the {\itshape Known Issues} section). I think this only happens when a profile is first created, so you can possibly get around this issue by calling the reset() function after the first frame.\hypertarget{profiler_profRemotery}{}\doxysubsection{Remotery Backend}\label{profiler_profRemotery}
If you need some more overview or want to profile a remote device, the profiler optionally supports using \href{https://github.com/Celtoys/Remotery}{\texttt{ Remotery}}.

To enable the Remotery backend set {\ttfamily O\+G\+R\+E\+\_\+\+P\+R\+O\+F\+I\+L\+I\+N\+G\+\_\+\+R\+E\+M\+O\+T\+E\+R\+Y\+\_\+\+P\+A\+TH} in C\+Make to point to the {\ttfamily Remotery/lib} directory (containing {\ttfamily Remotery.\+c}). Remotery will be compiled into Ogre\+Main and can be accessed as usual.

Note that no features besides \mbox{\hyperlink{class_ogre_1_1_profiler_a91c40e21a3fc96003504ea21fec80d77}{Ogre\+::\+Profiler\+::set\+Enabled}} are available when using Remotery.\hypertarget{profiler_profRelmode}{}\doxysubsection{Release Version Considerations}\label{profiler_profRelmode}
For the release version of your app, you should set {\ttfamily O\+G\+R\+E\+\_\+\+P\+R\+O\+F\+I\+L\+I\+NG=O\+FF} in C\+Make. If the build you are using has been compiled with the {\ttfamily O\+G\+R\+E\+\_\+\+P\+R\+O\+F\+I\+L\+I\+NG=O\+FF} and you still want to use instrumentation, you can instantiate a dummy profiler like this\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{comment}{// Create dummy profile to set singleton pointer}}
\DoxyCodeLine{\textcolor{keyword}{new} \mbox{\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}}();}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{comment}{// Give it a timer and enable it}}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_a53a2d2681a3995555df6d789c5596381}{setTimer}}(Root::getSingleton().getTimer());}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}}().\mbox{\hyperlink{class_ogre_1_1_profiler_a91c40e21a3fc96003504ea21fec80d77}{setEnabled}}(\textcolor{keyword}{true});}
\end{DoxyCode}


The profiler will now work but the 3 Ogre\+Profile macro will not work. You will have to manually use the begin\+Profile() and end\+Profile() method. You can also instantiate scope-\/limited Profile objects or simply define your own macros somewhere in your code.


\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{preprocessor}{\#define MyScopedProfile( a ) Ogre::Profile \_OgreProfileInstance( (a) )}}
\DoxyCodeLine{\textcolor{preprocessor}{\#define MyProfileBegin( a ) Ogre::Profiler::getSingleton().beginProfile( (a) )}}
\DoxyCodeLine{\textcolor{preprocessor}{\#define MyProfileEnd( a ) Ogre::Profiler::getSingleton().endProfile( (a) )}}
\end{DoxyCode}
 \hypertarget{External-Texture-Sources}{}\doxysection{External Texture Sources}\label{External-Texture-Sources}
This tutorial will provide a brief introduction of External\+Texture\+Source and External\+Texture\+Source\+Manager classes, their relationship, and how the Plug\+Ins work. For those interested in developing a Texture Source Plugin or maybe just wanting to know more about this system, take a look the ffmpeg\+Video\+System plugin, which you can find more about on the O\+G\+RE forums.

\label{_What-Is-An-External-Texture-Source_003f}%
\hypertarget{_external-_texture-_sources_autotoc_md278}{}\doxysubsection{What Is An External Texture Source?}\label{_external-_texture-_sources_autotoc_md278}
What is a texture source? Well, a texture source could be anything -\/ png, bmp, jpeg, etc. However, loading textures from traditional bitmap files is already handled by another part O\+G\+RE. There are, however, other types of sources to get texture data from -\/ i.\+e. mpeg/avi/etc movie files, flash, run-\/time generated source, user defined, etc.

How do external texture source plugins benefit O\+G\+RE? Well, the main answer is\+: adding support for any type of texture source does not require changing O\+G\+RE to support it... all that is involved is writing a new plugin. Additionally, because the manager uses the String\+Interface class to issue commands/params, no change to the material script reader is needs to be made. As a result, if a plugin needs a special parameter set, it just creates a new command in it’s Parameter Dictionary. -\/ see ffmpeg\+Video\+System plugin for an example. To make this work, two classes have been added to O\+G\+RE\+: External\+Texture\+Source \& External\+Texture\+Source\+Manager.

\label{_ExternalTextureSource-Class}%
\hypertarget{_external-_texture-_sources_autotoc_md279}{}\doxysubsection{External\+Texture\+Source Class}\label{_external-_texture-_sources_autotoc_md279}
The \mbox{\hyperlink{class_ogre_1_1_external_texture_source}{Ogre\+::\+External\+Texture\+Source}} class is the base class that Texture Source Plug\+Ins must be derived from. It provides a generic framework (via String\+Interface class) with a very limited amount of functionality. The most common of parameters can be set through the Texture\+Plug\+In\+Source class interface or via the String\+Interface commands contained within this class. While this may seem like duplication of code, it is not. By using the string command interface, it becomes extremely easy for derived plugins to add any new types of parameters that it may need.

Default Command Parameters defined in External\+Texture\+Source base class are\+:


\begin{DoxyParams}{Parameters}
{\em filename} & Sets a filename plugin will read from \\
\hline
{\em play\+\_\+mode} & Sets initial play mode to be used by the plugin -\/ \char`\"{}play\char`\"{}, \char`\"{}loop\char`\"{}, \char`\"{}pause\char`\"{} \\
\hline
{\em set\+\_\+\+T\+\_\+\+P\+\_\+S} & Used to set the technique, pass, and texture unit level to apply this texture to. As an example\+: To set a technique level of 1, a pass level of 2, and a texture unit level of 3, send this string \char`\"{}1 2 3\char`\"{}. \\
\hline
{\em frames\+\_\+per\+\_\+second} & Set a Frames per second update speed. (Integer Values only)\\
\hline
\end{DoxyParams}
\label{_ExternalTextureSourceManager-Class}%
\hypertarget{_external-_texture-_sources_autotoc_md280}{}\doxysubsection{External\+Texture\+Source\+Manager Class}\label{_external-_texture-_sources_autotoc_md280}
External\+Texture\+Source\+Manager is responsible for keeping track of loaded Texture Source Plug\+Ins. It also aids in the creation of texture source textures from scripts. It also is the interface you should use when dealing with texture source plugins.

\begin{DoxyNote}{Note}
The function prototypes shown below are mockups -\/ param names are simplified to better illustrate purpose here...
\end{DoxyNote}
Steps needed to create a new texture via External\+Texture\+Source\+Manager\+:


\begin{DoxyItemize}
\item Obviously, the first step is to have the desired plugin included in plugin.\+cfg for it to be loaded.
\item Set the desired Plug\+In as Active via Advanced\+Texture\+Manager\+::get\+Singleton().Set\+Current\+Plug\+In( String Type ); – type is whatever the plugin registers as handling (e.\+g. \char`\"{}video\char`\"{}, \char`\"{}flash\char`\"{}, \char`\"{}whatever\char`\"{}, etc).
\item Note\+: Consult Desired Plug\+In to see what params it needs/expects. Set params/value pairs via Advanced\+Texture\+Manager\+::get\+Singleton().get\+Current\+Plug\+In()-\/$>$set\+Parameter( String Param, String Value );
\item After required params are set, a simple call to Advanced\+Texture\+Manager\+::get\+Singleton().get\+Current\+Plug\+In()-\/$>$create\+Defined\+Texture( s\+Material\+Name ); will create a texture to the material name given.
\end{DoxyItemize}

The manager also provides a method for deleting a texture source material\+: Advanced\+Texture\+Manager\+::\+Destroy\+Advanced\+Texture( String s\+Texture\+Name ); The destroy method works by broadcasting the material name to all loaded Texture\+Source\+Plug\+Ins, and the Plug\+In who actually created the material is responsible for the deletion, while other Plug\+Ins will just ignore the request. What this means is that you do not need to worry about which Plug\+In created the material, or activating the Plug\+In yourself. Just call the manager method to remove the material. Also, all texture plugins should handle cleanup when they are shutdown.

\label{_Texture-Source-Material-Script}%
\hypertarget{_external-_texture-_sources_autotoc_md281}{}\doxysubsection{Texture Source Material Script}\label{_external-_texture-_sources_autotoc_md281}
As mentioned earlier, the process of defining/creating texture sources can be done within material script file. Here is an example of a material script definition -\/ Note\+: This example is based off the ffmpeg\+Video\+System plugin parameters.


\begin{DoxyCode}{0}
\DoxyCodeLine{material Example/MyVideoExample}
\DoxyCodeLine{\{}
\DoxyCodeLine{    technique}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        pass}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            texture\_unit}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                texture\_source video}
\DoxyCodeLine{                \{}
\DoxyCodeLine{                    filename mymovie.mpeg}
\DoxyCodeLine{                    play\_mode play}
\DoxyCodeLine{                    sound\_mode on}
\DoxyCodeLine{                \}}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \}}
\DoxyCodeLine{\}}
\end{DoxyCode}


Notice that the first two param/value pairs are defined in the External\+Texture\+Source base class and that the third parameter/value pair is not defined in the base class... That parameter is added to the param dictionary by the ffmpeg\+Video\+Plugin... This shows that extending the functionality with the plugins is extremely easy. Also, pay particular attention to the line\+: texture\+\_\+source video. This line identifies that this texture unit will come from a texture source plugin. It requires one parameter that determines which texture plugin will be used. In the example shown, the plugin requested is one that registered with \char`\"{}video\char`\"{} name.

\label{_Simplified-Diagram-of-Process}%
\hypertarget{_external-_texture-_sources_autotoc_md282}{}\doxysubsection{Simplified Diagram of Process}\label{_external-_texture-_sources_autotoc_md282}
This diagram uses ffmpeg\+Video\+Plugin as example, but all plug ins will work the same in how they are registered/used here. Also note that Texture\+Source Plugins are loaded/registered before scripts are parsed. This does not mean that they are initialized... Plugins are not initialized until they are set active! This is to ensure that a rendersystem is set up before the plugins might make a call the rendersystem.

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{TextureSource.svg}}
\end{DoxyImageNoCaption}
   \hypertarget{ShadowMappingOgre}{}\doxysection{Shadow Mapping in Ogre}\label{ShadowMappingOgre}
\hypertarget{_shadow_mapping_ogre_ShadowMappingIntro}{}\doxysubsection{Introduction to the Shadow Mapping Algorithm}\label{_shadow_mapping_ogre_ShadowMappingIntro}
Shadow mapping, an algorithm introduced by Lance Williams ~{\bfseries [W\+I\+L78]} and now prevalent in real-\/time and off-\/line rendering, is based on a simple idea\+: First, a snapshot of the scene is taken from the viewpoint of the light. Then, when creating an image from the perspective of the camera, the light’s snapshot is used to determine visibility. Parts of the scene seen by both the light and the camera must be lit (by the light in question). Parts of the scene visible only to the camera must be shadowed. We do not care about parts of the scene seen only by the light.

In practice, the snapshot from the viewpoint of the light is stored as a floating point depth buffer. It is important to use a format that supports enough precision to avoid shadow acne (z-\/fighting) on lit surfaces. In \mbox{\hyperlink{namespace_ogre}{Ogre}}, we can specify the depth format to use; in the example code, we will choose the 32-\/bit format.

Once shadow determination has occurred (whether a fragment is in shadow or not), \mbox{\hyperlink{namespace_ogre}{Ogre}} provides two different ways to render the shadows into the final image. The modulative technique will uniformly darken regions of the image determined to be in shadow. This is a cheaper and less accurate lighting model. For instance, specular highlights in shadow will appear as darkened specular highlights. The other technique is additive light masking. This technique builds up contributions from each light in non-\/shadowed areas and adds them together to create the final image. The code in section \mbox{\hyperlink{_shadow_mapping_ogre_Implementation}{Implementation}} will use additive light masking, but could just as easily be adapted for modulative shadows.\hypertarget{_shadow_mapping_ogre_sm_formalism}{}\doxysubsubsection{Formalism}\label{_shadow_mapping_ogre_sm_formalism}
Mathematically, the process can be represented as follows\+: Let $P_l$ and $P_c$ be the projection matrices for the light and camera respectively. Let $M_l$ and $M_c$ be the modelview matrices for the light and camera coordinate systems. Let $\vec{x} = [x_1,x_2,x_3,1]^t$ be a point in object space, $\vec{y} = [y_1,y_2,y_3,1]^t$ the screen space coordinates, and $\vec{u} = [u_1,u_2,u_3,1]^t$ the shadow map coordinates.

\[ \begin{aligned} \left[ \begin{array}{c} u_1 w_l \\ u_2 w_l \\ u_3 w_l \\ w_l \end{array} \right] = P_l M_l \left[ \begin{array}{c} x_1 \\ x_2 \\ x_3 \\ 1 \end{array} \right]\end{aligned} \]

\[\begin{aligned} \left[ \begin{array}{c} y_1 w_c \\ y_2 w_c \\ y_3 w_c \\ w_c \end{array} \right] = P_c M_c \left[ \begin{array}{c} x_1 \\ x_2 \\ x_3 \\ 1 \end{array} \right]\end{aligned}\]

These equations can be written more concisely as\+: $\vec{u}w_l = P_l M_l \vec{x}$ and $\vec{y} w_c = P_c M_c \vec{x}$. Division of $\vec{u}w_l$ and $\vec{y}w_c$ by their respective homogeneous coordinates yields the Euclidean representations $\vec{u}$ and $\vec{y}$.

Note that while $P_c$ and $M_c$ are completely determined by the camera image we want to produce, we have some ambiguity in the $P_l$ and $M_l$ chosen for shadow mapping. The degrees of freedom here are later exploited to combat the aliasing issue.\hypertarget{_shadow_mapping_ogre_DepthBias}{}\doxysubsubsection{Depth Biasing}\label{_shadow_mapping_ogre_DepthBias}
 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{depthbias.svg}}
\end{DoxyImageNoCaption}
   Shadow map sample must use one float to represent a range of possible depth values. A depth sample is chosen in the middle. Any camera image point in between the two camera rays will see the geometry, and depending on distance from light will report differently on shadowed versus lit. However, every such point should be lit.

Due to the finite precision of floating point representations and inherent inability of one number to represent a range of values, it is often necessary to add a little bias to the depth values stored in a shadow map. One does not simply store the $u_3$ value. Figure \mbox{[}fig\+:bias\mbox{]} illustrates the issue. Here we have used blue dots on the light’s image plane to represent boundaries between shadow “texels.\+” The interval in between the dots then represents a shadow map sample for which a single depth value (float) is stored. For the sample whose boundary rays are shown, the red dot’s depth is saved. However, note that from the camera’s perspective, any (camera) image point in between the two drawn camera rays will hit the scene geometry within the shadow map sample’s interval. Hence, the same shadow map sample depth will be used to determine visibility for all such camera pixels. Camera pixels whose rays fall to the right of the red dot will be marked as shadowed, while pixels whose rays fall to the left of the red dot will be marked as lit. This is not the right behavior because clearly all the pixels should be marked as lit. As we can see, a depth bias is needed. By pushing the shadow map sample’s depth farther (to the 2nd red dot), we can achieve correct shadow determination.

One could approach the depth bias issue in a completely $\ast$ad hoc$\ast$ manner, but it is possible to do better. One would ideally compute a bias that depends on how depth ( $u_3$) changes between shadow map samples. The change in depth as one moves a unit step (to the next shadow map sample) represents the ambiguity of the depth value. Such a value may seem intractable to compute, but calculus and linear algebra save the day. From calculus, we learn that the derivative provides the best linear approximation to any function ( $u_3 = u_3(u_1, u_2)$ in particular). In multiple dimensions, this role is played by the Jacobian (matrix of partial derivatives). In other words, we want to compute $\frac{du_3}{du_1}$ and $\frac{du_3}{du_2}$, where we have treated $u_3$ as a function of $u_1$ and $u_2$. Once these values are computed, it makes sense to then add some weighted combination of these to the stored depth value (e.\+g., some scale of the Jacobian’s Frobenius norm).

But even if the light is staring at a plane straight on (view direciton lines up with plane’s normal), making $\frac{du_3}{du_1}$ and $\frac{du_3}{du_2}$ both zero, we would still need a slight offset because rounding due to the float’s finite representation may still cause shadow acne. In this case, we’d like to offset the depth by a small value that pushes it beyond rounding ambiguity. While one could use an arbitrary constant offset, this is unsatisfactory since the constant in light image space corresponds to varying amounts of offset in light space (pre-\/projection Euclidean space with light’s position at origin). Let us instead choose a constant offset in the z direction of $\ast$light space$\ast$ and compute what the offset for a particular sample should be in $\ast$light image space$\ast$. In Ogre’s example code, the small constant offset in light space is chosen to be 1 unit. If 1 is not a small amount in your engine’s chosen scale, you can easily change this choice. At any rate, the relevant quantity is $\frac{\partial u_3}{\partial X_3}$ where $\vec{X} = M_l \vec{x}$.

The choices here closely mirror what Open\+GL implements through gl\+Polygon\+Offset. The second adjustment is slightly different since Open\+GL chooses a vendor specific fudge factor.

Equations for computing the stated quantities are provided below. One need not wade through these to use the depth biasing code. Understanding what the relevant parameters explained above are (in case adjustment is needed) is sufficient.

\[\begin{aligned} \label{eqn:dxqdu} \frac{\partial (\vec{x} q_l)}{\partial u_i} = \mbox{i-th column of } M_l^{-1} P_l^{-1} V_l^{-1} \end{aligned}\]

where $V_l$ is the viewport matrix for the light and $i=1,2,3$. $q_l$ turns out to be $1/w_l$.

\[\begin{aligned} \label{eqn:dxdu} \frac{\partial \vec{x}}{\partial u_i} = \frac{1}{q_l} \left( \frac{\partial (\vec{x} q_l)}{\partial u_i} - \vec{x}\frac{\partial q_l}{\partial u_i} \right) \\ \label{eqn:du3du} \frac{du_3}{du_j} = \left( \vec{n} \cdot \frac{\partial \vec{x}}{\partial u_3} \right)^{-1} \left( \vec{n} \cdot \frac{\partial \vec{x}}{\partial u_j} \right)\end{aligned}\]

where $\vec{n}$ is the normal at point $\vec{x}$ and $j=1,2$. Note that (\mbox{[}eqn\+:du3du\mbox{]}) is exactly the set of values needed for the first part.

\[\begin{aligned} \label{eqn:duwdX3} \frac{\partial (\vec{u} w_l)}{\partial X_3} = \mbox{3rd column of } P_l \\ \label{eqn:dudX3} \frac{\partial \vec{u}}{\partial X_3} = \frac{1}{w_l} \left( \frac{\partial (\vec{u} w_l)}{\partial X_3} - \vec{u}\frac{\partial w_l}{\partial X_3} \right)\end{aligned}\]

Note that (\mbox{[}eqn\+:dud\+X3\mbox{]}) is the quantity needed for the second bias term. This is also the term to scale for different choices of small offset in light space. If 0.\+01 units is the small offset, scale this value by 0.\+01.\hypertarget{_shadow_mapping_ogre_sm_pcm}{}\doxysubsubsection{Percentage Closest Filtering}\label{_shadow_mapping_ogre_sm_pcm}
As widely known, shadow mapping can exhibit significant aliasing. When this happens during texture mapping we apply filtering. We’d like to apply a similar principle with shadow maps, but filtering depth values is categorically the wrong thing to do. As described in ~{\bfseries [R\+S\+C87]}, one should instead filter depth test results. This is termed percentage closest filtering. Ideally this would be a filtering technique much like anisotropic texture filtering, but for simplicity and efficiency, Ogre’s example code implements the bilinear analogue.\hypertarget{_shadow_mapping_ogre_sm_variants}{}\doxysubsection{Variants}\label{_shadow_mapping_ogre_sm_variants}
There are many shadow mapping variants. Enumerating (much less describing) all of them would take us too far afield in this article. We instead defer to the provided references and google for such coverage. The many variants can, however, be broken up into three broad categories\+:
\begin{DoxyEnumerate}
\item Those that store additional information beyond a single float,
\item those that divide up shadow frusta into multiple frusta to be handled separately, and
\item those that propose less naive $P_l$ and $M_l$ to use and thereby affect the sampling distribution.
\end{DoxyEnumerate}

Algorithms in each category usually work quite independently and so many hybrid approaches are easily conceivable.\hypertarget{_shadow_mapping_ogre_sm_additional_info}{}\doxysubsubsection{Storing Additional Info}\label{_shadow_mapping_ogre_sm_additional_info}
One example of this is Deep Shadow Maps ~{\bfseries [L\+V00]}. In this work, instead of storing a single depth value and treating visibility as a binary value, a transfer function is stored and visibility is continuous. This algorithm is important in offline movie rendering, but also relevant to the Variance Shadow Mapping algorithm elucidated by the game developer community ~{\bfseries [D\+L06]}.

While variance shadow maps are motivated by statistical considerations, it is perhaps more properly understood in the Deep Shadow Maps framework. Analyzing it in terms of distributions is flawed for two reasons\+:
\begin{DoxyEnumerate}
\item the inequality considered is valid only for unimodal distributions whereas depth values are often discontinuous in regions that matter;
\item the inequality is treated as equality. The equations are justified with a very specific example in which two planes are viewed straight on. In practice there are very noticeable halo effects around objects, which makes more heuristic tweaks necessary.
\end{DoxyEnumerate}

Recasting this into the framework of deep shadow maps, we see that the proposed equality is simply a particular functional approximation to the transfer function. Variance shadow maps proposes a two-\/parameter family of approximation functions whose parameters are linearly interpolated in the usual way. This viewpoint allows for analysis and also suggests the possibility of getting improvements via other approximating functional forms.\hypertarget{_shadow_mapping_ogre_sm_breaking_frusta}{}\doxysubsubsection{Breaking up Shadow Frusta}\label{_shadow_mapping_ogre_sm_breaking_frusta}
Adaptive Shadow Maps ~{\bfseries [F\+F\+B01]} are an example of this. It is still largely considered too expensive for real-\/time rendering, but continued research and growing G\+PU power may make some variant worthwhile.\hypertarget{_shadow_mapping_ogre_sect_planeopt}{}\doxysubsubsection{Playing with Projection Matrices}\label{_shadow_mapping_ogre_sect_planeopt}
There are various heuristic approaches for choosing $P_l$ and $M_l$, but here we will focus on one method, the Plane Optimal algorithm ~{\bfseries [Chong04]}, that provides a particular guarantee. For this algorithm, we specify a plane of interest (e.\+g., ground plane, wall, table top) for which we want perfect shadowing no matter the configuration of light and camera in the scene (even dueling frusta). The algorithm will then compute $P_l$ and $M_l$ so that the mapping between camera image and light image is the identity when restricted to the plane. If the shadow map matches the resolution of the screen, then each pixel gets exactly one shadow sample. Shadows off the plane of interest have no guarantees. One limitation of the method is shown in Figure \mbox{[}fig\+:planeopt\mbox{]}. Only region I will be shadowed and self-\/shadowed properly, with points on the plane being shadowed perfectly (alias-\/free). This makes the method perhaps most useful for games where the view is top-\/down or isometric (like R\+TS games). It is also useful for cases like dueling frusta (where just about all other methods fail).

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{optfrust.svg}}
\end{DoxyImageNoCaption}
   Region I is defined as the set of all points along rays between the light and a point on the plane of interest in the camera’s view. Everything in region I is shadowed and self-\/shadowed properly. Objects in region II are not self-\/shadowed properly.\hypertarget{_shadow_mapping_ogre_sm_theory}{}\doxysubsection{Theory and Analysis}\label{_shadow_mapping_ogre_sm_theory}
A full discussion of shadow map analysis is beyond the scope of this article. For those interested, the references ~{\bfseries [Chong06]} and ~{\bfseries [Chong04]} are good (in my extremely biased opinion). Note that as research papers, they are quite concise. Unfortunately there don’t seem to more step-\/by-\/step expositions available at this moment.

There has been a lot of academic and industry research on improving shadow maps. However, analyses presented on shadow maps often do not say what people claim they say. These faulty conclusions usually come from considering very special cases and assuming the general case is very similar. For clarification, we explore some of these misconceptions here.\hypertarget{_shadow_mapping_ogre_sm_nonopt}{}\doxysubsubsection{(\+Non)\+Optimality of Logarithmic Shadow Maps}\label{_shadow_mapping_ogre_sm_nonopt}
We start with one {\itshape heuristic} that has gained quite a bit of traction\+: the idea of using some logarithmic mapping between light space and light image space instead of a projective transform. A number of algorithms based on this idea have been proposed, and even some hardware changes. Much of this work seems to be motivated by the incorrect assumption that logarithmic mappings are optimal.

The very special motivating case is this\+: The camera looks down the z axis. Directional light illuminates the scene perpendicular to the z axis. An angled piece of a plane is viewed by the camera. As the angled piece of plane is pulled along the camera ray direction, using a logarithmic shadow map gives us constant shadow quality on this geometric piece. But unless we’re rendering translucent dust particles along a camera ray, this analysis is irrelevant. If the dust particles are not translucent, we only care about shadow determination on the first one, not a whole line of them. If we are rendering continuous surfaces (resp. curves), we care about the quality as one moves in the tangent plane (resp. tangent) direction because this is the best linear approximation to the surface (resp. curve), not the camera ray direction.

In fact, in the case of a chosen plane of interest for example, we know we can get completely alias free shadow mapping using a projective transform (section \mbox{\hyperlink{_shadow_mapping_ogre_sect_planeopt}{Playing with Projection Matrices}}). Logarithmic shadow maps may be an interesting heuristic to try out, but certainly not worth changing hardware over in my opinion. If you’re going to change hardware, might as well aim for true optimality.\hypertarget{_shadow_mapping_ogre_sm_aliasing}{}\doxysubsubsection{Sampling Aliasing versus Depth Precision Aliasing}\label{_shadow_mapping_ogre_sm_aliasing}
Sometimes people tend to conflate these two sources of aliasing. They note that after applying some sort of custom projective transform, the depth values are warped as well. This problem can be completely overcome via the depth replacement method prescribed in Trapezoidal Shadow Maps ~{\bfseries [M\+T04]}. So this is a completely orthogonal issue. Depth precision can be just as good as “normal” shadow maps, no matter the perspective warp used to affect sampling.\hypertarget{_shadow_mapping_ogre_sm_proj_aliasing}{}\doxysubsubsection{Projective versus Perspective Aliasing}\label{_shadow_mapping_ogre_sm_proj_aliasing}
The terms perspective and projective aliasing appeared in the Perspective Shadow Maps ~{\bfseries [S\+D02]} paper and has since been used extensively by those who work on improving shadow heuristics. Often it is claimed that methods ameliorate perspective aliasing while projective aliasing is either unavoidable or must be addressed via completely separate means. However, the distinction between the two is somewhat artificial. Both result from not allocating enough shadow map samples to regions that matter to the viewer. As the Plane Optimal algorithm demonstrates, it is possible to completely remove projective aliasing (as well as perspective aliasing) in certain scenes. In general, there should be one combined measure of aliasing and algorithms must minimize this quantity. See ~{\bfseries [Chong06]} for a unified notion of aliasing.\hypertarget{_shadow_mapping_ogre_Implementation}{}\doxysubsection{Implementation}\label{_shadow_mapping_ogre_Implementation}
\mbox{\hyperlink{namespace_ogre}{Ogre}} provides a powerful framework that allows us to do a lot of shadow map customization. In \mbox{\hyperlink{namespace_ogre}{Ogre}}, we turn on custom shadow mapping through the scene manager (here, scene\+Mgr). It is recommended that this happen early as it may affect how certain resources are loaded.


\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{comment}{// Use Ogre's custom shadow mapping ability}}
\DoxyCodeLine{sceneMgr-\/>setShadowTexturePixelFormat(\mbox{\hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39ca2da3ec4fe727d552337e02069cd9efd9}{PF\_FLOAT32\_R}});}
\DoxyCodeLine{sceneMgr-\/>setShadowTechnique( \mbox{\hyperlink{group___general_gga79dcd426d291c31072c1ad6f183715d6a8a2b43e30e6d8d590e6853e4f46b8103}{SHADOWTYPE\_TEXTURE\_ADDITIVE}} );}
\DoxyCodeLine{sceneMgr-\/>setShadowTextureCasterMaterial(\textcolor{stringliteral}{"Ogre/DepthShadowmap/Caster/Float"});}
\DoxyCodeLine{sceneMgr-\/>setShadowTextureReceiverMaterial(\textcolor{stringliteral}{"Ogre/DepthShadowmap/Receiver/Float"});}
\DoxyCodeLine{sceneMgr-\/>setShadowTextureSelfShadow(\textcolor{keyword}{true}); }
\DoxyCodeLine{sceneMgr-\/>setShadowTextureSize(1024);}
\end{DoxyCode}


The set\+Shadow\+Technique call is all that is required for Ogre’s default shadow mapping. In the code above, we have told \mbox{\hyperlink{namespace_ogre}{Ogre}} to use the R channel of a floating point texture to store depth values. This tends to be a very portable method (over graphics cards and A\+P\+Is). The sample uses 1024x1024 shadow maps. Self-\/shadowing is turned on, but be warned that this will only work properly if appropriate depth biasing is also used. The example code will manually account for depth biasing via the method described above in section \mbox{\hyperlink{_shadow_mapping_ogre_DepthBias}{Depth Biasing}}. The shadow caster and shadow receiver materials are defined in a materials script. They tell \mbox{\hyperlink{namespace_ogre}{Ogre}} which shaders to use when rendering shadow casters into the shadow map and rendering shadow receivers during shadow determination.

The {\ttfamily Depth\+Shadowmap.\+material} script is given below\+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{\textcolor{comment}{// Generic Shadow caster material (floating point shadowmap)}}
\DoxyCodeLine{material \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/Caster/Float}
\DoxyCodeLine{\{}
\DoxyCodeLine{    technique}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        pass }
\DoxyCodeLine{        \{}
\DoxyCodeLine{            vertex\_program\_ref \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/CasterVP}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            fragment\_program\_ref \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/CasterFP}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \}}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{comment}{// Generic Shadow receiver material (floating point shadowmap)}}
\DoxyCodeLine{material \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/Receiver/Float}
\DoxyCodeLine{\{}
\DoxyCodeLine{    technique}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        pass }
\DoxyCodeLine{        \{}
\DoxyCodeLine{            vertex\_program\_ref \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/ReceiverVP}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            fragment\_program\_ref \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/ReceiverFP}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            texture\_unit ShadowMap}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                tex\_address\_mode clamp}
\DoxyCodeLine{                filtering none}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \}}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{comment}{// Specific receiver material for rockwall}}
\DoxyCodeLine{material \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/Receiver/RockWall}
\DoxyCodeLine{\{}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// This is the preferred technique which uses both vertex and}}
\DoxyCodeLine{    \textcolor{comment}{// fragment programs, supports coloured lights}}
\DoxyCodeLine{    technique}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        \textcolor{comment}{// Base ambient pass}}
\DoxyCodeLine{        pass}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            \textcolor{comment}{// base colours, not needed for rendering, but as information}}
\DoxyCodeLine{            \textcolor{comment}{// to lighting pass categorisation routine}}
\DoxyCodeLine{            ambient 1 1 1}
\DoxyCodeLine{            diffuse 0 0 0 }
\DoxyCodeLine{            specular 0 0 0 0 }
\DoxyCodeLine{            }
\DoxyCodeLine{            depth\_bias -\/1}
\DoxyCodeLine{        \}}
\DoxyCodeLine{        \textcolor{comment}{// Now do the lighting pass}}
\DoxyCodeLine{        \textcolor{comment}{// NB we don't do decal texture here because this is repeated per light}}
\DoxyCodeLine{        pass lighting}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            \textcolor{comment}{// base colours, not needed for rendering, but as information}}
\DoxyCodeLine{            \textcolor{comment}{// to lighting pass categorisation routine}}
\DoxyCodeLine{            ambient 0 0 0 }
\DoxyCodeLine{            }
\DoxyCodeLine{            \textcolor{comment}{// do this for each light}}
\DoxyCodeLine{            iteration once\_per\_light}
\DoxyCodeLine{}
\DoxyCodeLine{        }
\DoxyCodeLine{            scene\_blend add}
\DoxyCodeLine{            }
\DoxyCodeLine{            \textcolor{comment}{// Vertex program reference}}
\DoxyCodeLine{            vertex\_program\_ref \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/ReceiverVP}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            shadow\_receiver\_vertex\_program\_ref \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/ReceiverVP}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{}
\DoxyCodeLine{            \textcolor{comment}{// Fragment program}}
\DoxyCodeLine{            fragment\_program\_ref \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/ReceiverFP}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            shadow\_receiver\_fragment\_program\_ref \mbox{\hyperlink{namespace_ogre}{Ogre}}/DepthShadowmap/ReceiverFP}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{}
\DoxyCodeLine{            \textcolor{comment}{// shadowmap texture will be bound by code}}
\DoxyCodeLine{}
\DoxyCodeLine{        \}}
\DoxyCodeLine{        }
\DoxyCodeLine{        \textcolor{comment}{// Decal pass}}
\DoxyCodeLine{        pass}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            \textcolor{comment}{// base colours, not needed for rendering, but as information}}
\DoxyCodeLine{            \textcolor{comment}{// to lighting pass categorisation routine}}
\DoxyCodeLine{            lighting off}
\DoxyCodeLine{}
\DoxyCodeLine{}
\DoxyCodeLine{            scene\_blend dest\_colour zero}
\DoxyCodeLine{}
\DoxyCodeLine{            depth\_bias 1}
\DoxyCodeLine{            }
\DoxyCodeLine{            texture\_unit}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                texture rockwall.tga}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            }
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \}}
\DoxyCodeLine{}
\DoxyCodeLine{}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}
 The material uses unified programs for H\+L\+SL, G\+L\+SL and G\+L\+S\+L\+ES. We’ll present the G\+L\+SL code below. Note that while most of the shader files are direct translations of each other, DirectX H\+L\+SL shaders must handle percentage closest filtering slightly differently from Open\+GL. Open\+GL chooses the convention of having integers index sample centers whereas DirectX chooses integers to index sample corners. Also note the variable names in the shaders presented below are slightly different from those presented earlier in this document. This is due in part to the awkwardness of expressing subscripts in variable names and also in part because $u_3$ is less evocative of depth than $z$, etc. With minimal effort one can match the shader equations with those presented earlier. The code is presented here mostly to demonstrate how things fit together.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{uniform mat4 worldViewProj;}
\DoxyCodeLine{uniform vec4 texelOffsets;}
\DoxyCodeLine{}
\DoxyCodeLine{attribute vec4 vertex;}
\DoxyCodeLine{}
\DoxyCodeLine{varying vec2 depth;}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{keywordtype}{void} main()}
\DoxyCodeLine{\{}
\DoxyCodeLine{    vec4 outPos = worldViewProj * vertex;}
\DoxyCodeLine{    outPos.xy += texelOffsets.zw * outPos.w;}
\DoxyCodeLine{    \textcolor{comment}{// fix pixel / texel alignment}}
\DoxyCodeLine{    depth = outPos.zw;}
\DoxyCodeLine{    gl\_Position = outPos;}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\end{DoxyCodeInclude}


This is a pretty standard vertex shader.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{varying vec2 depth;}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{keywordtype}{void} main()}
\DoxyCodeLine{\{}
\DoxyCodeLine{    \textcolor{keywordtype}{float} finalDepth = depth.x / depth.y;}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// just smear across all components }}
\DoxyCodeLine{    \textcolor{comment}{// therefore this one needs high individual channel precision}}
\DoxyCodeLine{    gl\_FragColor = vec4(finalDepth, finalDepth, finalDepth, 1.0);}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\end{DoxyCodeInclude}


Just write out the depth values here. We compute the bias and derivatives in the receiver.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{uniform mat4 world;}
\DoxyCodeLine{uniform mat4 worldIT;}
\DoxyCodeLine{uniform mat4 worldViewProj;}
\DoxyCodeLine{uniform mat4 texViewProj;}
\DoxyCodeLine{uniform vec4 lightPosition;}
\DoxyCodeLine{uniform vec4 lightColour;}
\DoxyCodeLine{}
\DoxyCodeLine{attribute vec4 vertex;}
\DoxyCodeLine{attribute vec3 normal;}
\DoxyCodeLine{}
\DoxyCodeLine{varying vec4 oUv;}
\DoxyCodeLine{varying vec4 outColor;}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{keywordtype}{void} main()}
\DoxyCodeLine{\{}
\DoxyCodeLine{    gl\_Position = worldViewProj * vertex;}
\DoxyCodeLine{    }
\DoxyCodeLine{    vec4 worldPos = world * vertex;}
\DoxyCodeLine{}
\DoxyCodeLine{    vec3 worldNorm = (worldIT * vec4(normal, 1.0)).xyz;}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// calculate lighting (simple vertex lighting)}}
\DoxyCodeLine{    vec3 lightDir = normalize(}
\DoxyCodeLine{        lightPosition.xyz -\/ (worldPos.xyz * lightPosition.w));}
\DoxyCodeLine{}
\DoxyCodeLine{    outColor = lightColour * max(dot(lightDir, worldNorm), 0.0);}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// calculate shadow map coords}}
\DoxyCodeLine{    oUv = texViewProj * worldPos;}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\end{DoxyCodeInclude}


This is a pretty standard vertex shader as well.


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{uniform \textcolor{keywordtype}{float} inverseShadowmapSize;}
\DoxyCodeLine{uniform \textcolor{keywordtype}{float} fixedDepthBias;}
\DoxyCodeLine{uniform \textcolor{keywordtype}{float} gradientClamp;}
\DoxyCodeLine{uniform \textcolor{keywordtype}{float} gradientScaleBias;}
\DoxyCodeLine{}
\DoxyCodeLine{uniform sampler2D shadowMap;}
\DoxyCodeLine{}
\DoxyCodeLine{varying vec4 oUv;}
\DoxyCodeLine{varying vec4 outColor;}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{keywordtype}{void} main()}
\DoxyCodeLine{\{}
\DoxyCodeLine{    vec4 shadowUV = oUv;}
\DoxyCodeLine{    \textcolor{comment}{// point on shadowmap}}
\DoxyCodeLine{    shadowUV = shadowUV / shadowUV.w;}
\DoxyCodeLine{    \textcolor{keywordtype}{float} centerdepth = texture2D(shadowMap, shadowUV.xy).x;}
\DoxyCodeLine{    }
\DoxyCodeLine{    \textcolor{comment}{// gradient calculation}}
\DoxyCodeLine{    \textcolor{keywordtype}{float} pixeloffset = inverseShadowmapSize;}
\DoxyCodeLine{    vec4 depths = vec4(}
\DoxyCodeLine{        texture2D(shadowMap, shadowUV.xy + vec2(-\/pixeloffset, 0.0)).x,}
\DoxyCodeLine{        texture2D(shadowMap, shadowUV.xy + vec2(+pixeloffset, 0.0)).x,}
\DoxyCodeLine{        texture2D(shadowMap, shadowUV.xy + vec2(0.0, -\/pixeloffset)).x,}
\DoxyCodeLine{        texture2D(shadowMap, shadowUV.xy + vec2(0.0, +pixeloffset)).x);}
\DoxyCodeLine{}
\DoxyCodeLine{    vec2 differences = abs( depths.yw -\/ depths.xz );}
\DoxyCodeLine{    \textcolor{keywordtype}{float} gradient = min(gradientClamp, max(differences.x, differences.y));}
\DoxyCodeLine{    \textcolor{keywordtype}{float} gradientFactor = gradient * gradientScaleBias;}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// visibility function}}
\DoxyCodeLine{    \textcolor{keywordtype}{float} depthAdjust = gradientFactor + (fixedDepthBias * centerdepth);}
\DoxyCodeLine{    \textcolor{keywordtype}{float} finalCenterDepth = centerdepth + depthAdjust;}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{comment}{// shadowUV.z contains lightspace position of current object}}
\DoxyCodeLine{\textcolor{preprocessor}{\#if PCF}}
\DoxyCodeLine{    \textcolor{comment}{// use depths from prev, calculate diff}}
\DoxyCodeLine{    depths += depthAdjust;}
\DoxyCodeLine{    \textcolor{keywordtype}{float} \textcolor{keyword}{final} = (finalCenterDepth > shadowUV.z) ? 1.0 : 0.0;}
\DoxyCodeLine{    \textcolor{keyword}{final} += (depths.x > shadowUV.z) ? 1.0 : 0.0;}
\DoxyCodeLine{    \textcolor{keyword}{final} += (depths.y > shadowUV.z) ? 1.0 : 0.0;}
\DoxyCodeLine{    \textcolor{keyword}{final} += (depths.z > shadowUV.z) ? 1.0 : 0.0;}
\DoxyCodeLine{    \textcolor{keyword}{final} += (depths.w > shadowUV.z) ? 1.0 : 0.0;}
\DoxyCodeLine{    }
\DoxyCodeLine{    \textcolor{keyword}{final} *= 0.2;}
\DoxyCodeLine{}
\DoxyCodeLine{    gl\_FragColor = vec4(outColor.xyz * \textcolor{keyword}{final}, 1.0);}
\DoxyCodeLine{    }
\DoxyCodeLine{\textcolor{preprocessor}{\#else}}
\DoxyCodeLine{    gl\_FragColor = (centerdepth > shadowUV.z) ? vec4(outColor.xyz,1) : vec4(0,0,0,1);}
\DoxyCodeLine{\textcolor{preprocessor}{\#endif}}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\end{DoxyCodeInclude}


This shader computes the two depth bias pieces described in section \mbox{\hyperlink{_shadow_mapping_ogre_DepthBias}{Depth Biasing}}. These are used to offset the stored depth value. This is where the notation differs from above, but the translation is quite straightforward.

Additionally this file implements percentage closest filtering. To use unfiltered shadow mapping, comment out the P\+CF block as noted and uncomment the Non-\/\+P\+CF block. Note that after doing this, the u\+S\+Tex\+Width and u\+S\+Tex\+Height variables are likely to be optimized away and so you should uncomment these variables in the materials script as well.

The following shows how to activate plane optimal shadow mapping given some pointer to a Movable\+Plane and a pointer to a light.


\begin{DoxyCode}{0}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_plane_optimal_shadow_camera_setup}{Ogre::PlaneOptimalShadowCameraSetup}} *planeOptShadowCamera = }
\DoxyCodeLine{                                \textcolor{keyword}{new} PlaneOptimalShadowCameraSetup(movablePlane);}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_entity}{Ogre::Entity}} *movablePlaneEntity = sceneMgr-\/>createEntity( \textcolor{stringliteral}{"movablePlane"}, \textcolor{stringliteral}{"plane.mesh"} );}
\DoxyCodeLine{\mbox{\hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}} *movablePlaneNode = }
\DoxyCodeLine{                sceneMgr-\/>getRootSceneNode()-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}}(\textcolor{stringliteral}{"MovablePlaneNode"});}
\DoxyCodeLine{movablePlaneNode-\/>\mbox{\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}}(movablePlaneEntity);}
\DoxyCodeLine{light-\/>setCustomShadowCameraSetup(\mbox{\hyperlink{class_ogre_1_1_shared_ptr}{Ogre::ShadowCameraSetupPtr}}(planeOptShadowCamera));}
\end{DoxyCode}
 \hypertarget{deferred}{}\doxysection{Deferred Shading}\label{deferred}
This tutorial is complementary to the deferred shading sample that is part of \mbox{\hyperlink{namespace_ogre}{Ogre}}. It will reference the code quite a bit and explain some of the decisions made when implementing the deferred shading framework for the demo.\hypertarget{deferred_what}{}\doxysubsection{What is Deferred Shading?}\label{deferred_what}
Deferred shading is an alternative approach to rendering 3d scenes. The classic rendering approach involves rendering each object and applying lighting passes to it. So, if an ogre head is affected by 6 lights, it will be rendered 6 times, once for each light, in order to accumulate the affection of each light. Deferred shading takes another approach \+: In the beginning, all of the objects render their \char`\"{}lighting related info\char`\"{} to a texture, often called the G-\/\+Buffer. This means their colours, normals, depths and any other info that might be relevant to calculating their final colour. Afterwards, the lights in the scene are rendered as geometry (sphere for point light, cone for spotlight and full screen quad for directional light), and they use the G-\/buffer to calculate the colour contribution of that light to that pixel.

See the links in \mbox{\hyperlink{deferred_further}{Further reading}} to read more about it. It is recommended to understand deferred shading before reading this article, as the article focuses on implementing it in ogre, and not explaining how it works.\hypertarget{deferred_autotoc_md258}{}\doxysubsubsection{Deferred Shading Advantages}\label{deferred_autotoc_md258}
The main reason for using deferred shading is performance related. Classing rendering (also called forward rendering) can, in the worst case, require num\+\_\+objects $\ast$ num\+\_\+lights batches to render a scene. Deferred shading changes that to num\+\_\+objects + num\+\_\+lights, which can often be a lot less. Another reason is that some new post-\/processing effects are easily achievable using the G-\/\+Buffer as input. If you wanted to perform these effects without deferred shading, you would\textquotesingle{}ve had to render the whole scene again.\hypertarget{deferred_autotoc_md259}{}\doxysubsubsection{Deferred Shading Disadvantages}\label{deferred_autotoc_md259}
There are several algorithmic drawbacks with deferred shading -\/ transparent objects are hard to handle, anti aliasing can not be used in D\+X9 class hardware, additional memory consumption because of the G-\/\+Buffer. In addition to that, deferred shading is harder to implement -\/ it overrides the entire fixed function pipeline. Pretty much everything is rendered using manual shaders -\/ which probably means a lot of shader code.\hypertarget{deferred_creating}{}\doxysubsection{Creating the G-\/\+Buffer}\label{deferred_creating}
The first part of the deferred shading pipeline involves rendering all the (non-\/transparent) objects of the scene to the G-\/\+Buffer. This is done using a compositor \+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{compositor DeferredShading/GBuffer}
\DoxyCodeLine{\{}
\DoxyCodeLine{    technique}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        \textcolor{comment}{// temporary textures}}
\DoxyCodeLine{        texture mrt\_output target\_width target\_height \mbox{\hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39caf91793bc9707d6541f4851722267317a}{PF\_FLOAT16\_RGBA}} \mbox{\hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39caf91793bc9707d6541f4851722267317a}{PF\_FLOAT16\_RGBA}} chain\_scope}
\DoxyCodeLine{        }
\DoxyCodeLine{        target mrt\_output}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            input none}
\DoxyCodeLine{            pass clear}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            }
\DoxyCodeLine{            shadows off}
\DoxyCodeLine{            material\_scheme GBuffer}
\DoxyCodeLine{            }
\DoxyCodeLine{            \textcolor{comment}{// everything but the lights and their meshes}}
\DoxyCodeLine{            \textcolor{comment}{// could do this with something like a visibility mask too}}
\DoxyCodeLine{            pass render\_scene}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                \textcolor{comment}{//These values are synchronized with the code}}
\DoxyCodeLine{                first\_render\_queue 10}
\DoxyCodeLine{                last\_render\_queue  79   }
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \}}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}
 Things to note about this compositor \+:
\begin{DoxyItemize}
\item mrt\+\_\+output (the G\+Buffer) is an M\+RT because there are two pixel formats defined.
\item mrt\+\_\+output will be accessible to the next compositors in the chain because it is marked as chain\+\_\+scope, meaning it is visible to the next compositors in the chain.
\item The material scheme tells ogre that objects shouldn\textquotesingle{}t be rendered in normal fashion, but in some other way (we\textquotesingle{}ll get to that soon)
\item Not all the objects are rendered to the G\+Buffer. Skies and \textquotesingle{}late objects\textquotesingle{} (which can be specified manually using render queues) will be forward rendered.
\item This compositor does N\+OT have a target\+\_\+output pass, because it does not contribute directly to the final image.
\end{DoxyItemize}\hypertarget{deferred_autotoc_md260}{}\doxysubsubsection{Deciding on the G\+Buffer format}\label{deferred_autotoc_md260}
This in an important decision in deferred shading, as it has performance and visual implications.

Also, the entire pipeline has to be coordinated with this format -\/ all the writing shaders have to write the same data to the same places, and all the reading shaders (for lighting later) have to be synchronized with it.

We chose two P\+F\+\_\+\+F\+L\+O\+A\+T16\+\_\+\+R\+G\+BA textures. The first one will contain the colour in R\+GB, specular intensity in A.

The second one will contain the view-\/space-\/normal in R\+GB (we keep all 3 coordinates) and the (linear) depth in A.

See the references for other possibilities.\hypertarget{deferred_autotoc_md261}{}\doxysubsubsection{Preparing the objects for G-\/\+Buffer rendering}\label{deferred_autotoc_md261}
The only indicator that ogre has when rendering the scene is that the material scheme is different. Material schemes in ogre allow materials to specify different rendering techniques for different scenarios. In this case, we would like to output the lighting related information instead of the lighting calculation result.

Materials that have a technique associated with the G\+Buffer scheme will render using that, but we don\textquotesingle{}t want to modify the materials of all the objects in our art pipeline to use them in deferred shading.

The solution is to use scheme listeners! The material manager has a method for registering listeners when objects don\textquotesingle{}t have a technique defined for the current scheme\+: \mbox{\hyperlink{class_ogre_1_1_material_manager_a8ac18f4bd2e6302f1d92ae8f64195694}{Ogre\+::\+Material\+Manager\+::add\+Listener()}}.

The listener has a callback method that gets called whenever an object is about to be rendered without a matching technique\+: \mbox{\hyperlink{class_ogre_1_1_material_manager_1_1_listener_a54bc384ab1102063aa00db4c3a5f3fc4}{Ogre\+::\+Material\+Manager\+::\+Listener\+::handle\+Scheme\+Not\+Found()}}.

We will implement such a listener for the G\+Buffer scheme. It is G\+Buffer\+Scheme\+Handler from the demo. The G\+Buffer\+Scheme\+Handlers works like this \+:\hypertarget{deferred_autotoc_md262}{}\doxyparagraph{Inspect the classic technique}\label{deferred_autotoc_md262}
For each pass in the technique that would have been used normally, the G\+Buffer\+Scheme\+Handler\+::inspect\+Pass is called, inspects the pass, and returns the Pass\+Properties -\/ does this pass have a texture? a normal map? is it skinned? tranpsarent? Etc. The Pass\+Properties (should) contain all the information required to build a G\+Buffer technique for an object.\hypertarget{deferred_autotoc_md263}{}\doxyparagraph{Generate the G-\/\+Buffer technique}\label{deferred_autotoc_md263}
After a pass has been inspected and understood, the next stage is to generate the G-\/\+Buffer-\/writing technique. This is done using the class G\+Buffer\+Material\+Generator. The class receives the flags of the features needed by the material, and dynamically generates the (CG) shaders and material to render an object with those properties to the G-\/\+Buffer. This greatly reduces the number of shaders that you need to manage when using deferred shading, as most of them are created on the fly. Here is an example of what they look like \+:


\begin{DoxyCode}{0}
\DoxyCodeLine{\textcolor{keywordtype}{void} ToGBufferVP(}
\DoxyCodeLine{         float4 iPosition : POSITION,}
\DoxyCodeLine{         float3 iNormal   : NORMAL,}
\DoxyCodeLine{         float2 iUV0 : TEXCOORD0,}
\DoxyCodeLine{ }
\DoxyCodeLine{         out float4 oPosition : POSITION,}
\DoxyCodeLine{         out float3 oViewPos : TEXCOORD0,}
\DoxyCodeLine{         out float3 oNormal : TEXCOORD1,}
\DoxyCodeLine{         out float2 oUV0 : TEXCOORD2,}
\DoxyCodeLine{ }
\DoxyCodeLine{         uniform float4x4 cWorldViewProj,}
\DoxyCodeLine{         uniform float4x4 cWorldView}
\DoxyCodeLine{         )}
\DoxyCodeLine{ \{}
\DoxyCodeLine{         oPosition = mul(cWorldViewProj, iPosition);}
\DoxyCodeLine{         oNormal = mul(cWorldView, float4(iNormal,0)).xyz;}
\DoxyCodeLine{         oViewPos = mul(cWorldView, iPosition).xyz;}
\DoxyCodeLine{         oUV0 = iUV0;}
\DoxyCodeLine{ \}}
\DoxyCodeLine{ }
\DoxyCodeLine{ \textcolor{keywordtype}{void} ToGBufferFP(}
\DoxyCodeLine{         float3 iViewPos : TEXCOORD0,}
\DoxyCodeLine{         float3 iNormal   : TEXCOORD1,}
\DoxyCodeLine{         float3 iTangent : TEXCOORD2,}
\DoxyCodeLine{         float3 iBiNormal : TEXCOORD3,}
\DoxyCodeLine{         float2 iUV0 : TEXCOORD4,}
\DoxyCodeLine{ }
\DoxyCodeLine{         out float4 oColor0 : COLOR0,}
\DoxyCodeLine{         out float4 oColor1 : COLOR1,}
\DoxyCodeLine{ }
\DoxyCodeLine{         uniform sampler sNormalMap : \textcolor{keyword}{register}(s0),}
\DoxyCodeLine{         uniform sampler sTex0 : \textcolor{keyword}{register}(s1),}
\DoxyCodeLine{         uniform float4 cDiffuseColour,}
\DoxyCodeLine{         uniform \textcolor{keywordtype}{float} cFarDistance,}
\DoxyCodeLine{         uniform \textcolor{keywordtype}{float} cSpecularity}
\DoxyCodeLine{         )}
\DoxyCodeLine{ \{}
\DoxyCodeLine{         oColor0.rgb = tex2D(sTex0, iUV0);}
\DoxyCodeLine{         oColor0.rgb *= cDiffuseColour.rgb;}
\DoxyCodeLine{         oColor0.a = cSpecularity;}
\DoxyCodeLine{         float3 texNormal = (tex2D(sNormalMap, iUV0)-\/0.5)*2;}
\DoxyCodeLine{         float3x3 normalRotation = float3x3(iTangent, iBiNormal, iNormal);}
\DoxyCodeLine{         oColor1.rgb = normalize(mul(texNormal, normalRotation));}
\DoxyCodeLine{         oColor1.a = length(iViewPos) / cFarDistance;}
\DoxyCodeLine{ \}}
\end{DoxyCode}
 (This is for an object with a texture and a normal map)\hypertarget{deferred_autotoc_md264}{}\doxyparagraph{Add the G-\/\+Buffer technique to the original material}\label{deferred_autotoc_md264}
We don\textquotesingle{}t want to inspect the passes and generate the material each time an object is rendered, so we create a technique in the original material, and fill it with the auto-\/generated information. After copying the information from the G\+Buffer technique, texture references have to be updated, to use the correct textures when rendering the object. This happens in {\ttfamily G\+Buffer\+Scheme\+Handler\+::fill\+Pass}. The next time the object will be rendered, it W\+I\+LL have a technique for the G\+Buffer scheme, so the listener won\textquotesingle{}t get called.\hypertarget{deferred_autotoc_md265}{}\doxyparagraph{Postponing transparent objects}\label{deferred_autotoc_md265}
We don\textquotesingle{}t want to render transparent objects to the G\+Buffer, as it doesn\textquotesingle{}t work properly later.

To address this, we also create a technique with a scheme called called \textquotesingle{}No\+G\+Buffer\textquotesingle{}. If the inspect\+Pass decided that the object is transparent, we will not add an auto-\/generated pass to the \textquotesingle{}G\+Buffer\textquotesingle{} technique, but instead copy the regular pass to the \textquotesingle{}No\+G\+Buffer\textquotesingle{} technique, to render it regularly later.\hypertarget{deferred_autotoc_md266}{}\doxyparagraph{Putting it all together}\label{deferred_autotoc_md266}
This is how {\ttfamily G\+Buffer\+Scheme\+Handler\+::handle\+Scheme\+Not\+Found} works\+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{Technique* GBufferSchemeHandler::handleSchemeNotFound(\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{short} schemeIndex, }
\DoxyCodeLine{        \textcolor{keyword}{const} \mbox{\hyperlink{namespace_ogre_af73bbdc8bed8a3e6fcd56bb8fa188c45}{String}}\& schemeName, Material* originalMaterial, \textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{short} lodIndex, }
\DoxyCodeLine{        \textcolor{keyword}{const} Renderable* rend)}
\DoxyCodeLine{\{}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_material_manager}{Ogre::MaterialManager}}\& matMgr = \mbox{\hyperlink{class_ogre_1_1_material_manager_a100f413d9d2316028e7ae740e5a43161}{Ogre::MaterialManager::getSingleton}}();}
\DoxyCodeLine{    \mbox{\hyperlink{namespace_ogre_af73bbdc8bed8a3e6fcd56bb8fa188c45}{String}} curSchemeName = matMgr.\mbox{\hyperlink{class_ogre_1_1_material_manager_ad03ea02e140fc1e7312d14626e59d45d}{getActiveScheme}}();}
\DoxyCodeLine{    matMgr.\mbox{\hyperlink{class_ogre_1_1_material_manager_a95decc3900f547bb68b74ba28d3013e0}{setActiveScheme}}(MaterialManager::DEFAULT\_SCHEME\_NAME);}
\DoxyCodeLine{    Technique* originalTechnique = originalMaterial-\/>getBestTechnique(lodIndex, rend);}
\DoxyCodeLine{    matMgr.\mbox{\hyperlink{class_ogre_1_1_material_manager_a95decc3900f547bb68b74ba28d3013e0}{setActiveScheme}}(curSchemeName);}
\DoxyCodeLine{}
\DoxyCodeLine{    Technique* gBufferTech = originalMaterial-\/>createTechnique();}
\DoxyCodeLine{    gBufferTech-\/>removeAllPasses();}
\DoxyCodeLine{    gBufferTech-\/>setSchemeName(schemeName);}
\DoxyCodeLine{}
\DoxyCodeLine{\textcolor{preprocessor}{\#ifdef OGRE\_BUILD\_COMPONENT\_RTSHADERSYSTEM}}
\DoxyCodeLine{    RTShader::ShaderGenerator\& rtShaderGen = RTShader::ShaderGenerator::getSingleton();}
\DoxyCodeLine{    rtShaderGen.createShaderBasedTechnique(originalTechnique, \textcolor{stringliteral}{"NoGBuffer"});}
\DoxyCodeLine{\textcolor{preprocessor}{\#else}}
\DoxyCodeLine{    Technique* noGBufferTech = originalMaterial-\/>createTechnique();}
\DoxyCodeLine{    noGBufferTech-\/>removeAllPasses();}
\DoxyCodeLine{    noGBufferTech-\/>setSchemeName(\textcolor{stringliteral}{"NoGBuffer"});}
\DoxyCodeLine{\textcolor{preprocessor}{\#endif}}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{keywordflow}{for} (\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{short} i=0; i<originalTechnique-\/>getNumPasses(); i++)}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        Pass* originalPass = originalTechnique-\/>getPass(i);}
\DoxyCodeLine{        PassProperties props = inspectPass(originalPass, lodIndex, rend);}
\DoxyCodeLine{        }
\DoxyCodeLine{        \textcolor{keywordflow}{if} (!props.isDeferred)}
\DoxyCodeLine{        \{}
\DoxyCodeLine{\textcolor{preprocessor}{\#ifdef OGRE\_BUILD\_COMPONENT\_RTSHADERSYSTEM}}
\DoxyCodeLine{            rtShaderGen.validateMaterial(\textcolor{stringliteral}{"NoGBuffer"}, originalMaterial-\/>getName(), originalMaterial-\/>getGroup());}
\DoxyCodeLine{\textcolor{preprocessor}{\#else}}
\DoxyCodeLine{            \textcolor{comment}{//Just copy the technique so it gets rendered regularly}}
\DoxyCodeLine{            Pass* clonePass = noGBufferTech-\/>createPass();}
\DoxyCodeLine{            *clonePass = *originalPass;}
\DoxyCodeLine{\textcolor{preprocessor}{\#endif}}
\DoxyCodeLine{            \textcolor{keywordflow}{continue};}
\DoxyCodeLine{        \}}
\DoxyCodeLine{}
\DoxyCodeLine{        Pass* newPass = gBufferTech-\/>createPass();}
\DoxyCodeLine{        MaterialGenerator::Perm perm = getPermutation(props);}
\DoxyCodeLine{}
\DoxyCodeLine{        \textcolor{keyword}{const} \mbox{\hyperlink{class_ogre_1_1_shared_ptr}{Ogre::MaterialPtr}}\& templateMat = mMaterialGenerator.getMaterial(perm);}
\DoxyCodeLine{        }
\DoxyCodeLine{        \textcolor{comment}{//We assume that the GBuffer technique contains only one pass. But its true.}}
\DoxyCodeLine{        *newPass = *(templateMat-\/>\mbox{\hyperlink{class_ogre_1_1_material_a011abd64ab54e84c516068caa5001c91}{getTechnique}}(0)-\/>\mbox{\hyperlink{class_ogre_1_1_technique_ab0014ffd501b4e1bef5eaae0340e71a7}{getPass}}(0));}
\DoxyCodeLine{        fillPass(newPass, originalPass, props);    }
\DoxyCodeLine{    \}}
\DoxyCodeLine{    }
\DoxyCodeLine{    \textcolor{keywordflow}{return} gBufferTech;}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}
 \hypertarget{deferred_autotoc_md267}{}\doxysubsubsection{Overriding the automatic process}\label{deferred_autotoc_md267}
In some cases the automatic material generation will not be good enough. We want to keep the option of manually writing G\+Buffer materials and shaders.

How do we do this? Easily! Since G\+Buffer\+Scheme\+Handler\+::handle\+Scheme\+Not\+Found only gets called when an object doesn\textquotesingle{}t already have a G\+Buffer scheme, adding a \textquotesingle{}G\+Buffer\textquotesingle{} technique to the material will cause it to not get passed to the listener even once.\hypertarget{deferred_autotoc_md268}{}\doxysubsubsection{Seeing it in action}\label{deferred_autotoc_md268}
Using tools like N\+V\+I\+D\+IA\textquotesingle{}s Perf\+H\+UD, we can see the texture being built during the frame \+:

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{GBufferPerfHUD.PNG}}
\end{DoxyImageNoCaption}
  

Note that nothing has been written to the final output yet (main view is completely black) and that two textures are being written to (see right hand side).\hypertarget{deferred_lighting}{}\doxysubsection{Lighting the scene}\label{deferred_lighting}
In the G\+Buffer compositor, we built the G-\/\+Buffer for the current frame. It is now the time to use it to calculate the final lighting of the scene. This is what the compositor looks like \+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{compositor DeferredShading/ShowLit}
\DoxyCodeLine{\{}
\DoxyCodeLine{}
\DoxyCodeLine{    technique}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        \textcolor{comment}{//Reference the main Gbuffer texture}}
\DoxyCodeLine{        texture\_ref mrt\_output DeferredShading/GBuffer mrt\_output}
\DoxyCodeLine{        }
\DoxyCodeLine{        target\_output}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            input none}
\DoxyCodeLine{            \textcolor{comment}{//We will dispatch the shadow texture rendering ourselves}}
\DoxyCodeLine{            shadows off}
\DoxyCodeLine{            }
\DoxyCodeLine{            pass clear}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                }
\DoxyCodeLine{            \}}
\DoxyCodeLine{            }
\DoxyCodeLine{            \textcolor{comment}{// render skies and other pre-\/gbuffer objects}}
\DoxyCodeLine{            pass render\_scene}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                first\_render\_queue 1}
\DoxyCodeLine{                last\_render\_queue  9            }
\DoxyCodeLine{            \}}
\DoxyCodeLine{            }
\DoxyCodeLine{            \textcolor{comment}{//Render the lights and their meshes}}
\DoxyCodeLine{            pass render\_custom DeferredLight}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                input 0 mrt\_output 0}
\DoxyCodeLine{                input 1 mrt\_output 1}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            }
\DoxyCodeLine{            \textcolor{comment}{//Render the objects that skipped rendering into the gbuffer}}
\DoxyCodeLine{            pass render\_scene}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                material\_scheme NoGBuffer}
\DoxyCodeLine{                first\_render\_queue 10}
\DoxyCodeLine{                last\_render\_queue 79}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            }
\DoxyCodeLine{            \textcolor{comment}{//Render the post-\/GBuffer render queue objects}}
\DoxyCodeLine{            pass render\_scene}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                \textcolor{comment}{//This value is synchronized with the code}}
\DoxyCodeLine{                first\_render\_queue 80}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \}}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}
 Yes, it\textquotesingle{}s a long one. Here is a breakdown of the compositor \+:
\begin{DoxyItemize}
\item The \textquotesingle{}texture\+\_\+ref\textquotesingle{} definition means that we are referencing a texture from another compositor. In the case of a chain-\/scoped texture (like the G\+Buffer), this means that we can only apply this compositor on chains that have the G\+Buffer creating compositor earlier in the chain than this one. \mbox{\hyperlink{namespace_ogre}{Ogre}} will check that this is the case.
\end{DoxyItemize}

There are four target passes in this compositor.
\begin{DoxyEnumerate}
\item Render the skies and then the lights using the render\+\_\+custom directive (more on this later)
\item Render the objects that are in the G\+Buffer render queues but didn\textquotesingle{}t get rendered to the G\+Buffer
\item Render the post-\/\+G\+Buffer render queue objects
\item Output the result
\end{DoxyEnumerate}\hypertarget{deferred_lightgeom}{}\doxysubsubsection{Rendering the light geometry}\label{deferred_lightgeom}
The geometry that we want to render to calculate lighting information doesn\textquotesingle{}t really fit in any classic category. It is not really a part of the scene, as the light geometry aren\textquotesingle{}t objects in the world. But it is geometry (not always a quad) that needs to be rendered.

For these kind of operations, the render\+\_\+custom target pass was introduced into \mbox{\hyperlink{namespace_ogre}{Ogre}}. It is possible to register custom (named) composition passes that will be performed in the compositor. In this case, it is \textquotesingle{}Deferred\+Light\textquotesingle{}. The composition pass will receive a call each frame telling it \textquotesingle{}it\textquotesingle{}s your turn, do your thing\textquotesingle{}. The class in the demo is Deferred\+Light\+CP.

The registration of the custom composition pass has to be done once, using \mbox{\hyperlink{class_ogre_1_1_compositor_manager_ae9b8ca4c2a51c0720bb31393d20fe7c9}{Ogre\+::\+Compositor\+Manager\+::register\+Custom\+Composition\+Pass()}}.

Custom\+Composition\+Pass is essentially just a factory for Render\+System\+Operations, which are the operations that get executed during a compositor chain. This is the single A\+PI call\+: \mbox{\hyperlink{class_ogre_1_1_custom_composition_pass_a6b8c7a3743f9bb44e27c0348a0035e7b}{Ogre\+::\+Custom\+Composition\+Pass\+::create\+Operation()}}.

So, now we get called exactly when we want, after the G-\/\+Buffer has been built and the (early) skies have been rendered. What will we do?\hypertarget{deferred_autotoc_md269}{}\doxyparagraph{Prepare ambient colour and rebuild original depth buffer}\label{deferred_autotoc_md269}
Since we rendered the original scene to a different R\+TT, the depth buffer won\textquotesingle{}t necessarily get reused for the output target, so we need to rebuild it so that future objects (lights and non-\/g-\/buffer objects) will be able to interact with the depth naturally.

Also, we need to apply the ambient light to the scene. For the purpose of the demo, the ambient light is not a separate colour channel, just the object\textquotesingle{}s original textures applied with the scene\textquotesingle{}s global ambient light factor. In theory, you could set up a different G-\/\+Buffer to allow more flexibility, but we didn\textquotesingle{}t do that.

These two actions happen in a single full-\/screen quad render, that comes from the Ambient\+Light class.\hypertarget{deferred_autotoc_md270}{}\doxyparagraph{Render the light geometries}\label{deferred_autotoc_md270}
The most important stage is the light geometry. The code scans the original scene\textquotesingle{}s lights, builds a matching D\+Light (deferred light) instance for each light in the scene, and renders away using the G-\/\+Buffer.

These lights use pretty sophisticated shaders, since they perform the lighting calculations of the fixed function pipeline themselves, and have to account for many options (specularity, attenuation, different light types and shadows, which will get talked about soon). In contrast to the G-\/\+Buffer building stage, the shaders here do not get generated on the fly. There is one big shader (sometimes referred to as an Uber-\/\+Shader) with many preprocessor options that account for all the options. (See Light\+Material\+\_\+ps.\+cg) Note that the shaders have to be synchronized with the G-\/\+Buffer layout. A change in the layout would need a parallel change in the deferred lighting shaders.

The material generator for this section (Light\+Material\+Generator class) just scans the flags of input and generates the correct preprocessor defines for the uber-\/shader. Some people prefer to use this approach for the G-\/\+Buffer stage as well, but I wanted to show both options in the demo.

In order to dispatch render operations manually, the following call exists in Scene\+Manager\+: \mbox{\hyperlink{class_ogre_1_1_scene_manager_a1593fab748d1b0820e93e49d5732350b}{Ogre\+::\+Scene\+Manager\+::\+\_\+inject\+Render\+With\+Pass()}}.

When rendering a light, we pass the light we are rendering as the manual light list in order to have the auto params for that light available in the shader.\hypertarget{deferred_autotoc_md271}{}\doxyparagraph{Rendering shadow casting lights}\label{deferred_autotoc_md271}
The \textquotesingle{}classic\textquotesingle{} approach to rendering texture shadows is to prepare all of them before the scene rendering starts, and then apply them to the rendered objects using shadow receiver passes or integrated shaders. The downside of this approach is that you need to allocate a texture per-\/light (5 shadow casting lights -\/$>$ 5 shadow textures) and that if you don\textquotesingle{}t integrate it in your shaders you also contribute even more passes to the scene.

One of the advantages of deferred shading is that we render the lights completely, and one by one. So, we can generate the shadow texture for a light just before the light\textquotesingle{}s geometry is rendered, allowing us to reuse the same texture for as many lights as we want. (We still have an overhead of rendering the scene from the light\textquotesingle{}s perspective per-\/light).

The A\+PI call that prepares shadow textures on demand is \mbox{\hyperlink{class_ogre_1_1_scene_manager_a95cd8ff86a7178c2e37b2fcb485f64fa}{Ogre\+::\+Scene\+Manager\+::prepare\+Shadow\+Textures()}}. The light\+List parameter allows specification of which lights to prepare shadow textures for.

Important note -\/ Render\+System\+Operations get executed in the middle of scene rendering. This means that there is an active render target being rendered to. In order to render the shadow texture we need to be able to pause rendering mid frame, render the shadow texture, and resume rendering immediately afterwards. For this, Scene\+Manager has two methods that do just that \mbox{\hyperlink{class_ogre_1_1_scene_manager_a90d0e7484ed4580ec980eef15808bfee}{Ogre\+::\+Scene\+Manager\+::\+\_\+pause\+Rendering()}} and \mbox{\hyperlink{class_ogre_1_1_scene_manager_a794e03ea25dd798346414c1dba31337d}{Ogre\+::\+Scene\+Manager\+::\+\_\+resume\+Rendering()}}, so the prepare\+Shadow\+Textures call has to be inside this.

The demo currently supports just spotlight shadow casting (since it is the cheapest to implement) but the other options can be supported as well.\hypertarget{deferred_autotoc_md272}{}\doxyparagraph{Putting it all together}\label{deferred_autotoc_md272}

\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{\textcolor{keywordtype}{void} DeferredLightRenderOperation::execute(SceneManager *sm, RenderSystem *rs)}
\DoxyCodeLine{\{}
\DoxyCodeLine{    \mbox{\hyperlink{class_ogre_1_1_camera}{Ogre::Camera}}* cam = mViewport-\/>getCamera();}
\DoxyCodeLine{}
\DoxyCodeLine{    mAmbientLight-\/>updateFromCamera(cam);}
\DoxyCodeLine{    Technique* tech = mAmbientLight-\/>\mbox{\hyperlink{class_ogre_1_1_frustum_af31f1095812cd5fe300cd176bbde969e}{getMaterial}}()-\/>\mbox{\hyperlink{class_ogre_1_1_material_a37ae7259ce89bdc38828ea1b977bdbcf}{getBestTechnique}}();}
\DoxyCodeLine{    injectTechnique(sm, tech, mAmbientLight, 0);}
\DoxyCodeLine{}
\DoxyCodeLine{    \textcolor{keyword}{const} \mbox{\hyperlink{group___general_gaab30ef14aae93306a6044cb38d835f0c}{LightList}}\& lightList = sm-\/>\_getLightsAffectingFrustum();}
\DoxyCodeLine{    \textcolor{keywordflow}{for} (LightList::const\_iterator it = lightList.begin(); it != lightList.end(); it++) }
\DoxyCodeLine{    \{}
\DoxyCodeLine{        Light* light = *it;}
\DoxyCodeLine{        \mbox{\hyperlink{class_ogre_1_1_hashed_vector}{Ogre::LightList}} ll;}
\DoxyCodeLine{        ll.\mbox{\hyperlink{class_ogre_1_1_hashed_vector_a87bfcde773502ee964a677580724188f}{push\_back}}(light);}
\DoxyCodeLine{}
\DoxyCodeLine{        \textcolor{comment}{//if (++i != 2) continue;}}
\DoxyCodeLine{        \textcolor{comment}{//if (light-\/>getType() != Light::LT\_DIRECTIONAL) continue;}}
\DoxyCodeLine{        \textcolor{comment}{//if (light-\/>getDiffuseColour() != ColourValue::Red) continue;}}
\DoxyCodeLine{}
\DoxyCodeLine{        LightsMap::iterator dLightIt = mLights.find(light);}
\DoxyCodeLine{        DLight* dLight = 0;}
\DoxyCodeLine{        \textcolor{keywordflow}{if} (dLightIt == mLights.end()) }
\DoxyCodeLine{        \{}
\DoxyCodeLine{            dLight = createDLight(light);}
\DoxyCodeLine{        \}}
\DoxyCodeLine{        \textcolor{keywordflow}{else} }
\DoxyCodeLine{        \{}
\DoxyCodeLine{            dLight = dLightIt-\/>second;}
\DoxyCodeLine{            dLight-\/>updateFromParent();}
\DoxyCodeLine{        \}}
\DoxyCodeLine{        dLight-\/>updateFromCamera(cam);}
\DoxyCodeLine{        tech = dLight-\/>getMaterial()-\/>getBestTechnique();}
\DoxyCodeLine{}
\DoxyCodeLine{        \textcolor{comment}{//Update shadow texture}}
\DoxyCodeLine{        \textcolor{keywordflow}{if} (dLight-\/>getCastChadows())}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            SceneManager::RenderContext* context = sm-\/>\_pauseRendering();}
\DoxyCodeLine{}
\DoxyCodeLine{            sm-\/>prepareShadowTextures(cam, mViewport, \&ll);}
\DoxyCodeLine{            sm-\/>\_resumeRendering(context);}
\DoxyCodeLine{            }
\DoxyCodeLine{            Pass* pass = tech-\/>getPass(0);}
\DoxyCodeLine{            TextureUnitState* tus = pass-\/>getTextureUnitState(\textcolor{stringliteral}{"ShadowMap"});}
\DoxyCodeLine{            assert(tus);}
\DoxyCodeLine{            \textcolor{keyword}{const} \mbox{\hyperlink{namespace_ogre_aa381890787803da43b614dee8d9c8994}{TexturePtr}}\& shadowTex = sm-\/>getShadowTexture(0);}
\DoxyCodeLine{            \textcolor{keywordflow}{if} (tus-\/>\_getTexturePtr() != shadowTex)}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                tus-\/>\_setTexturePtr(shadowTex);}
\DoxyCodeLine{            \}}
\DoxyCodeLine{            }
\DoxyCodeLine{        \}}
\DoxyCodeLine{        }
\DoxyCodeLine{        injectTechnique(sm, tech, dLight, \&ll);}
\DoxyCodeLine{    \}}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}
 \hypertarget{deferred_autotoc_md273}{}\doxyparagraph{Seeing it in action}\label{deferred_autotoc_md273}
Here is a screenshot from Perf\+H\+UD of the draw call that renders a spotlight that casts shadows. See the two G-\/\+Buffer textures and one shadow texture on the left \+:

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{DeferredCone1.PNG}}
\end{DoxyImageNoCaption}
  

Here is a visualization of the texture being built \+:

 
\begin{DoxyImageNoCaption}
  \mbox{\includegraphics[width=\textwidth,height=\textheight/2,keepaspectratio=true]{DeferredCone2.PNG}}
\end{DoxyImageNoCaption}
  

After all the lights are rendered, the scene is fully lit!\hypertarget{deferred_post}{}\doxysubsection{Post Processing}\label{deferred_post}
The compositor framework used to be a post processing framework, but as this article shows -\/ it is now a \textquotesingle{}custom render pipeline\textquotesingle{} framework, allowing different rendering approaches. However, it can still be used to post process the scene, even under deferred rendering.\hypertarget{deferred_autotoc_md274}{}\doxysubsubsection{Screen Space Ambient Occlusion}\label{deferred_autotoc_md274}
\textquotesingle{}Screen Space Ambient Occlusion\textquotesingle{} is a global illumination technique that adds a bit of realism to the scene, where classic lighting often fails. However, it requires the normals and depths of the scene in order to calculate its contribution. Normally, the S\+S\+AO compositor would have a render\+\_\+scene directive that does that.

However, with deferred shading, we already have that information from the G-\/\+Buffer stage, so we just need to access it!

This is what the compositor looks like \+:


\begin{DoxyCodeInclude}{0}
\DoxyCodeLine{compositor DeferredShading/SSAO}
\DoxyCodeLine{\{}
\DoxyCodeLine{    technique}
\DoxyCodeLine{    \{}
\DoxyCodeLine{        compositor\_logic SSAOLogic}
\DoxyCodeLine{        }
\DoxyCodeLine{        texture\_ref geom DeferredShading/GBuffer mrt\_output}
\DoxyCodeLine{        texture scene target\_width target\_height \mbox{\hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39cae0afb06af1cb73f624e66540c64bb2cb}{PF\_BYTE\_RGBA}}}
\DoxyCodeLine{        texture ssao target\_width\_scaled 0.5 target\_height\_scaled 0.5 \mbox{\hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39caa2fa4ac766d61fa65b4c86ea5c035218}{PF\_BYTE\_RGB}}}
\DoxyCodeLine{        texture ssaoBlurX target\_width target\_height \mbox{\hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39caa2fa4ac766d61fa65b4c86ea5c035218}{PF\_BYTE\_RGB}}}
\DoxyCodeLine{        texture ssaoBlurY target\_width target\_height \mbox{\hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39caa2fa4ac766d61fa65b4c86ea5c035218}{PF\_BYTE\_RGB}}}
\DoxyCodeLine{}
\DoxyCodeLine{        \textcolor{comment}{// the scene we want to modulate}}
\DoxyCodeLine{        target scene}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            input previous}
\DoxyCodeLine{        \}}
\DoxyCodeLine{}
\DoxyCodeLine{        }
\DoxyCodeLine{}
\DoxyCodeLine{        target ssao}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            input none}
\DoxyCodeLine{}
\DoxyCodeLine{            pass clear}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{}
\DoxyCodeLine{            pass render\_quad}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                \textcolor{comment}{// our SSAO listener number}}
\DoxyCodeLine{                identifier 42}
\DoxyCodeLine{}
\DoxyCodeLine{                material ssao}
\DoxyCodeLine{                \textcolor{comment}{// pass in the "geometry map"}}
\DoxyCodeLine{                input 0 geom 1}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{}
\DoxyCodeLine{        target ssaoBlurX}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            input none}
\DoxyCodeLine{}
\DoxyCodeLine{            pass clear}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{}
\DoxyCodeLine{            pass render\_quad}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                identifier 43}
\DoxyCodeLine{}
\DoxyCodeLine{                material ssaoBlurX}
\DoxyCodeLine{                input 0 ssao}
\DoxyCodeLine{                input 1 geom 1}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{}
\DoxyCodeLine{        target ssaoBlurY}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            input none}
\DoxyCodeLine{}
\DoxyCodeLine{            pass clear}
\DoxyCodeLine{            \{}
\DoxyCodeLine{            \}}
\DoxyCodeLine{}
\DoxyCodeLine{            pass render\_quad}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                identifier 43}
\DoxyCodeLine{}
\DoxyCodeLine{                material ssaoBlurY}
\DoxyCodeLine{                input 0 ssaoBlurX}
\DoxyCodeLine{                input 1 geom 1}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{}
\DoxyCodeLine{}
\DoxyCodeLine{}
\DoxyCodeLine{        target\_output}
\DoxyCodeLine{        \{}
\DoxyCodeLine{            input none}
\DoxyCodeLine{}
\DoxyCodeLine{            pass render\_quad}
\DoxyCodeLine{            \{}
\DoxyCodeLine{                \textcolor{comment}{// just output something, for example, use a modulate}}
\DoxyCodeLine{                \textcolor{comment}{// material to just multiply the scene by the ssao}}
\DoxyCodeLine{                material modulate}
\DoxyCodeLine{                input 0 scene}
\DoxyCodeLine{                input 1 ssaoBlurY}
\DoxyCodeLine{                \textcolor{comment}{//input 1 ssao}}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \}}
\DoxyCodeLine{\}}
\end{DoxyCodeInclude}


Some notes \+:
\begin{DoxyItemize}
\item Again, texture\+\_\+ref is used to access a chain\+\_\+scoped texture from the G\+Buffer compositor
\item compositor\+\_\+logic is used to couple between the compositor and some code that it requires to run. A Compositor\+Logic class is created and registered with the Compositor\+Manager with \mbox{\hyperlink{class_ogre_1_1_compositor_manager_a9c7d4168d56868599badb2789d54157c}{Ogre\+::\+Compositor\+Manager\+::register\+Compositor\+Logic()}}. Which will cause the binding code to run whenever an instance of this compositor is created.
\item \textquotesingle{}Regular\textquotesingle{} compositors that don\textquotesingle{}t use the G\+Buffer are also still possible of course, they can be used regularly, as long as they are placed after the Deferred\+Shading/\+Show\+Lit compositor.
\end{DoxyItemize}\hypertarget{deferred_realprojects}{}\doxysubsection{Integration in real projects}\label{deferred_realprojects}
The framework that this demo uses was designed to be pluggable into other projects. Some of the design considerations that contribute to that are \+:
\begin{DoxyEnumerate}
\item The scene setup does not change in any way. You still set the scene up with normal lights and modify their parameters just like you would regularly.
\item The G\+Buffer scheme handler and shader generator allow existing materials to work in a deferred shading pipeline unmodified. It might not cover all the cases, but it can.
\item Easy to integrate -\/ see next section
\end{DoxyEnumerate}\hypertarget{deferred_autotoc_md275}{}\doxysubsubsection{Integration steps}\label{deferred_autotoc_md275}
The framework created for a demo fits the plugin architecture pretty well. The G\+Buffer\+Scheme\+Handler and Deferred\+Light\+Composition\+Pass classes could be instantiated once on plugin setup and registered with ogre\textquotesingle{}s systems. This is not the case currently just to keep the S\+DK build simpler.

So, the steps are \+:
\begin{DoxyEnumerate}
\item Register G\+Buffer\+Scheme\+Handler and Deferred\+Light\+Composition\+Pass with their respective managers.
\item Add the G\+Buffer and Show\+Lit compositors to the viewports you want deferred shaded.
\end{DoxyEnumerate}

And thats it! In the demo, the Deferred\+Shading class takes care of that.\hypertarget{deferred_autotoc_md276}{}\doxysubsubsection{Adapting the framework}\label{deferred_autotoc_md276}
The deferred shading framework in the demo was designed to be usable in real applications. Where would one want to modify it ?
\begin{DoxyEnumerate}
\item G\+Buffer\+Scheme\+Handler / Material\+Generator -\/ support more options out of the box. Skinning, specular maps, and whatever you have in your project that can be solved in a generic fashion.
\item Light\+Material\+Generator -\/ support more lighting options (fog, etc), more shadow types, different shadow techniques (currently using very basic depth shadow mapping)
\item Tweak the framework to your pipeline -\/ The material inspection relies on naming (among other things) to decide what its looking at. Just modify it to fit your art pipeline\textquotesingle{}s conventions! (For example, how does a texture get flagged as a normal map?)
\end{DoxyEnumerate}

Indeed, it means that the framework is not 100\% plug and play. But, if understood correctly, it can be adapted to real life scenarios with relative ease.\hypertarget{deferred_autotoc_md277}{}\doxysubsubsection{Adding features to the framework}\label{deferred_autotoc_md277}
Post processing compositors that rely on certain aspects of the scene (like S\+S\+AO does) are now much easier to create and integrate with the earlier processes. An example could be edge-\/based anti aliasing, to address the lack of anti aliasing in D\+X9-\/based deferred shading systems.

In addition to that, the deferred shading implementation was focused on simplicity. There are many optimization options and most of them were not done, mainly to keep the demo as simple and understandable as possible.\hypertarget{deferred_summary}{}\doxysubsection{Summary}\label{deferred_summary}
Deferred Shading is an advanced rendering technique, that brings a pretty big implementation challenge along with it. This article, along with the demo, shows that it is possible to implement without relying on hacks and bypassing ogre\textquotesingle{}s systems. Yes, it involves more advanced usage of ogre\textquotesingle{}s A\+P\+Is and requires a bit of knowledge about what happens behind the scenes, but is in no way impossible.\hypertarget{deferred_further}{}\doxysubsubsection{Further reading}\label{deferred_further}

\begin{DoxyItemize}
\item \href{http://www.guerrilla-games.com/publications/dr_kz2_rsx_dev07.pdf}{\texttt{ Kill\+Zone 2 Deferred Shading overview}} -\/ Great resource for understanding deferred shading in general before diving into implemeting it in \mbox{\hyperlink{namespace_ogre}{Ogre}}.
\item \href{http://www.ogre3d.org/tikiwiki/tiki-index.php?page=SoC2009+Compositor}{\texttt{ Improving Ogre\textquotesingle{}s Compositor Framework G\+SoC project page}}
\item \href{http://www.gamedev.net/page/reference/index.html/_//feature/fprogramming/deferred-rendering-demystified-r2746}{\texttt{ Deferred Rendering Demystified}} -\/ An article written around this project that explains the design behind the deferred renderer. 
\end{DoxyItemize}\hypertarget{pczscenemanager}{}\doxysection{Using the P\+CZ Scene Manager}\label{pczscenemanager}
The Portal-\/\+Connected-\/\+Zone Scene Manager (P\+C\+Z\+SM) is a plugin for Ogre3D (see www.\+ogre3d.\+org for more information about Ogre3d) which allows traversal of a scene which is non-\/homogeneous in structure. Specifically, the P\+C\+Z\+SM uses \char`\"{}\+Zones\char`\"{} which have their own hierarchy. Zones are connected to other zones by \char`\"{}\+Portals\char`\"{} which can be envisioned as 4-\/point convex planar polygons (or Spheres or A\+AB\textquotesingle{}s). ~\newline


This document gives basic information on the usage of the P\+C\+Z\+Scene\+Manager. It is not complete, and will change \& expand as needed. Note that as of this writing, the P\+C\+Z\+SM has not undergone very extensive testing, nor is it optimized very much. Assistance in these two areas would be greatly appreciated. For support or to report bugs, please see the Developer Forum at Ogre3\+D.\+org

Cheers,

Eric \char`\"{}\+Chaster\char`\"{} Cha\hypertarget{pczscenemanager_autotoc_md0}{}\doxysubsection{U\+S\+I\+N\+G T\+H\+E P\+C\+Z\+\_\+\+S\+C\+E\+N\+E\+M\+A\+N\+A\+G\+ER}\label{pczscenemanager_autotoc_md0}
N\+O\+TE\+: For an example of P\+C\+Z\+SM usage, see the P\+C\+Z\+Test\+App Application. It is probably a lot easier to understand than trying to figure it all out from this.\hypertarget{pczscenemanager_autotoc_md1}{}\doxysubsection{L\+O\+A\+D\+I\+N\+G \& I\+N\+I\+T\+I\+A\+L\+I\+Z\+A\+T\+I\+O\+N\+:}\label{pczscenemanager_autotoc_md1}
The P\+C\+Z\+SM is loaded just like any other Scene Manager plugin. Included in the standard P\+C\+Z\+SM plugin is the \char`\"{}default\char`\"{} zone. If the user wishes to utilize the Octree\+Zone or Terrain\+Zone, the \char`\"{}\+Plugin\+\_\+\+Octree\+Zone\char`\"{} should be loaded {\itshape after} the P\+C\+Z\+SM plugin is loaded. ~\newline


Before using the P\+C\+Z\+SM, the P\+C\+Z\+Scene\+Manager\+::init(zone\+Type) function should be called. During intialization, the user specifies what type of zone (Zone\+Type\+\_\+\+Default, Zone\+Type\+\_\+\+O\+Ctree, Zone\+Type\+\_\+\+Terrain) the P\+C\+Z\+SM should use for the default zone. The default zone is the zone where entities are placed if they are not specified to be in other zones. ~\newline
\hypertarget{pczscenemanager_autotoc_md2}{}\doxysubsection{C\+R\+E\+A\+T\+I\+N\+G Z\+O\+N\+E\+S\+:}\label{pczscenemanager_autotoc_md2}
Once the P\+C\+Z\+SM has been initialized, the user can proceed with creating zones (P\+C\+Z\+Scene\+Manager\+::create\+Zone(zone\+Type, zone\+Name)). Zones can be anything from the outdoors (i.\+e. a Terrain) to a room in a building, or a tunnel in a dungeon. Zones can be of any size or shape, and can move. ~\newline


N\+O\+TE\+: In the P\+C\+Z\+SM, sky rendering (domes, boxes, planes) is associated with a specific zone. For example, if the user has a building on a terrain, the sky could be associated with the terrain (i.\+e. the \char`\"{}outdoors\char`\"{}) using the function P\+C\+Z\+Scene\+Manager\+::set\+Sky\+Zone(zone). This tells the P\+C\+Z\+SM to only draw the sky when the designated zone is visible. (i.\+e. only draw the sky when the \textquotesingle{}outdoor\textquotesingle{} zone is visible). Usually, the Sky should be associated with the default zone (which is usually used as the \char`\"{}all
encompassing exterior zone\char`\"{}).\hypertarget{pczscenemanager_autotoc_md3}{}\doxysubsection{C\+R\+E\+A\+T\+I\+N\+G P\+O\+R\+T\+A\+L\+S\+:}\label{pczscenemanager_autotoc_md3}
Once the user has created a zone (in addition to the default zone), they can create portals to attach two zones together. ~\newline


$\ast$$\ast$$\ast$ N\+EW AS OF 9/25/07\+:

To create a portal, the user just calls P\+C\+Z\+Scene\+Manager\+::create\+Portal(). N\+O\+TE\+: The user should N\+OT just instantiate a portal manually (i.\+e. portal = new Portal) because the clean up of portals is handled by the scene manager directly. Instantiating portals using the C++ \textquotesingle{}new\textquotesingle{} command will result in memory leaks and errors if the scene is destroyed and recreated.

To destroy a portal use P\+C\+Z\+Scene\+Manager\+::destroy\+Portal(\+Portal $\ast$p) or P\+C\+Z\+Scene\+Manager\+::destroy\+Portal(\+String \& portal\+Name).

Then set the portal corner points, attaches it to a node, and then adds it to the zone (see P\+C\+Z\+Test\+App -\/$>$ Room\+Object.\+cpp -\/$>$ create\+Portals() function). ~\newline


N\+O\+TE\+: Portals currently only connect different zones. The user can\textquotesingle{}t connect portals to the same zone yet (i.\+e. no teleporters). This functionality could be added later.

U\+P\+D\+A\+TE as of 3/17/09\+: Portals can be \char`\"{}closed\char`\"{} (and opened) by calling Portal\+::set\+Enable(false) (and Portal\+::set\+Enable(false)). Disabling a portal prevents the scene manager from traversing through the portal and also prevents scenenodes \& ray queries from crossing the portal. Basically, it turns a portal \char`\"{}off\char`\"{}. Disabling an antiportal (see note below about Creating antiportals) prevents the antiportal from blocking scene traversal through regular portals.

N\+EW IN V\+E\+R\+S\+I\+ON 1.\+2\+: Portals can take 3 different forms\+: quad portals, A\+AB portals, and Sphere portals. A\+AB and Sphere portals do not add any culling planes to the frustum, and just serve to serve as enclosures for zones which aren\textquotesingle{}t naturally surrounded by geometry. They function a little different than traditional quad portals in that they are volumetric, instead of planar (crossing is determined by going from \char`\"{}inside\char`\"{} to \char`\"{}outside\char`\"{} or vice versa).

Quad Portals require 4 corner points which are co-\/planar and form a polygon which is convex. Quad Portal corners are specified in right-\/handed counter-\/ clockwise winding order so that the norm of the portal would be facing the viewer. ~\newline


A\+AB Portals require 2 corner points (minimum \& maximum corners) and form an axis-\/ aligned box around the zone. I\+M\+P\+O\+R\+T\+A\+NT\+: The A\+AB portals that are associated with a node require a node which has the correct size A\+AB (node-\/$>$\+\_\+get\+World\+A\+A\+B\+B()).

Sphere Portals require 2 corner points (center point, and point on the surface of the sphere). ~\newline


The \char`\"{}direction\char`\"{} norm of A\+AB and Sphere portals is specified as either Vector3\+::\+U\+N\+I\+T\+\_\+\+N\+E\+G\+A\+T\+I\+V\+E\+\_\+Z or Vector3\+::\+U\+N\+I\+T\+\_\+Z. The first corresponds to a portal with norm facing \textquotesingle{}inward\textquotesingle{} and the latter corresponds to a portal with norm facing \textquotesingle{}outward\textquotesingle{}. ~\newline


N\+O\+TE regarding Portal Norms\+: The Norm of a portal should always point away from the zone the portal leads to. Another way to think of this is a node will only cross a portal if it crosses the portal traveling opposite direction of the norm).

Portals also (currently) require a \char`\"{}matching\char`\"{} portal for proper scene traversal. In other words, portals always exist in pairs -\/ one in each zone connected and co-\/existing in the same location, but facing in opposite directions. ~\newline


It is R\+E\+Q\+U\+I\+R\+ED that a portal be associated with a scene node. Use Portal\+::set\+Node() to associate the portal with a scene node. Once the portal is associated with a scene node, it will move with the scene node (including rotations or translations). Because of this, it is also highly recommended (although not required) that the node a portal is associated with be located at the center of the portal.

N\+O\+TE\+: Scaling of a portal is not yet {\itshape tested}. Scaling a node should scale the portal (but don\textquotesingle{}t cry to me if it doesn\textquotesingle{}t work right yet...) ~\newline


Once all portals in the scene have been created, the user can either manually assign their zone targets (i.\+e. the zone which they connect to) or they can call P\+C\+Z\+Scene\+Manager\+::connect\+Portals\+To\+Target\+Zones\+By\+Location() to do it automatically. Note that this function requires all portals to have a matching portal in the target zone. ~\newline
\hypertarget{pczscenemanager_autotoc_md4}{}\doxysubsection{A\+N\+T\+I\+P\+O\+R\+T\+A\+L\+S  $\ast$$\ast$ N\+E\+W As of 3/17/09 $\ast$$\ast$}\label{pczscenemanager_autotoc_md4}
Antiportals are a new feature (thanks to Lf3thn4d). Antiportals prevent traversal of portals located behind them (as viewed from the camera). They are created and manipulated the same as regular portals (except you don\textquotesingle{}t need to create them in pairs, since they block scene traversal to other zones instead of connecting them). Only Quad Antiportals are supported. ~\newline


To Create an antiportal, it\textquotesingle{}s very similar to regular portals. All you need to do is call P\+C\+Z\+Scene\+Manager\+::create\+Anti\+Portal(\char`\"{}name of the antiportal\char`\"{}), set the corner values, attach it to a node, and add it to the proper zone. ~\newline
\hypertarget{pczscenemanager_autotoc_md5}{}\doxysubsection{C\+R\+E\+A\+T\+I\+N\+G O\+B\+J\+E\+C\+T\+S/\+E\+N\+T\+I\+T\+I\+E\+S\+:}\label{pczscenemanager_autotoc_md5}
Once the zones and portals have been created, the user can create objects/entities. The user should use Scene\+Manager\+::create\+Scene\+Node() to create all scene nodes.

N\+O\+TE\+: A\+LL O\+B\+J\+E\+C\+TS {\itshape M\+U\+ST} BE A\+T\+T\+A\+C\+H\+ED TO S\+C\+E\+N\+E\+N\+O\+D\+E\+S!!! Unlike the other SM\textquotesingle{}s available in Ogre3d, the P\+C\+Z\+SM relies on Scene Nodes to determine zone locality of all entities -\/ including cameras and lights. Consequently, when a camera (or light) is created, the user should also attach the camera (or light) to a scene node and use that node to manipulate the object.

Scene\+Nodes can be assigned (by the user) to a zone upon creation of the Scene\+Node. Use the functions \char`\"{}\+P\+C\+Z\+Scene\+Node\+::set\+Home\+Zone(\+P\+C\+Zone $\ast$ zone)\char`\"{} followed by \char`\"{}\+P\+C\+Zone\+::\+\_\+add\+Node(\+P\+C\+Z\+Scene\+Node $\ast$ node)\char`\"{} to do this. ~\newline


If the user doesn\textquotesingle{}t do this, the P\+C\+Z\+SM will try to figure out which zone the node belongs in using volumetric testing, but since there are situations when this can fail, it is highly recommended that the user does so explicitly instead of relying on the SM to figure it out. Note that this only has to be done when adding a node to the scene. Once the node is in the proper zone, the SM will handle moving it to other zones as necessary.

N\+O\+TE\+: In order for the automatic zone assignment function to work, zones must have an \char`\"{}enclosure\char`\"{} object/node assigned to them (using the "P\+C\+Zone\+::set\+Enclosure\+Node() function). The enclosure node (or more specifically, the object attached to it) supplies the axis-\/aligned bounding box that determines the bounds of the zone. ~\newline
 So for example, the enclosure node/object for a room would be the model of the walls, ceiling, and floor (assuming they are all modeled as one object or at least all attached to the same node). See the P\+C\+Z\+Test\+App for an example.\hypertarget{pczscenemanager_autotoc_md6}{}\doxysubsection{S\+C\+E\+N\+E Q\+U\+E\+R\+I\+E\+S\+:}\label{pczscenemanager_autotoc_md6}
I have implemented Scene Query functions for Default \& Octree Zones. In general, they are used the same way as Scene Queries for any other Scene Manager, with one difference. The user must specify the \char`\"{}start zone\char`\"{} for any scene query using X\+X\+X\+Scene\+Query\+::set\+Start\+Zone(zone) where \char`\"{}\+X\+X\+X\char`\"{} is Ray, Sphere, Axis\+Aligned\+Box, etc.\hypertarget{pczscenemanager_autotoc_md7}{}\doxysubsection{K\+N\+O\+W\+N B\+U\+G\+S\+:}\label{pczscenemanager_autotoc_md7}

\begin{DoxyItemize}
\item Light traversal is not quite correct. In order to avoid infinite recursion, I had to put in a hack which can potentially result in lighting not traversing into some zones properly. It will probably not be noticeable in most situations, but could potentially show up in very complex portal/zone setups. 
\end{DoxyItemize}