Error
  • To view equations Tiki needs the mathjax/mathjax package. If you do not have permission to install this package, ask the site administrator.
OogstsHowTo2         A collection of various smaller snippets - Oogst How-To part II

See also: OogstsHowTo and Snippets

How to set the Range/Attenuation of a light

The Attenuation of a light follows this rule: A = p0 + p1xR + p2xR², where R is the distance from the Light Source, p0, p1, and p2, three parameters allowing to set how the light will attenuate. The luminosity of the light is: L = 1/Attenuation.

Example 1:

If you want a light, which lost 50% of its luminosity at 1000 units, the equation will be

With the following parameters:

  • p0=1

  • p1=

  • p2=0


Light attenuation - 1st degree equation

mLight->setAttenuation(1000, 1, 0.001, 0) ;


Example 2:

An attenuation of 2nd degree will fade more rapidly. For instance, if you want a light which lost 66% of its luminosity at 1000 units, the parameters are:

  • p0=1

  • p1=1/1000

  • p2=1/(1000x1000)


light2degree.jpg

mLight->setAttenuation(1000, 1, 0.001, 0.000001) ;


See also -Point Light Attenuation.

How to choose your SceneManager

You can find more detailled information on this topic here: SceneManagersFAQ.
Don't forget to check the Ogre Terrain System and the usage example in the Basic Tutorial 3.

In the chooseSceneManager() function, replace the ST_GENERIC by the type of Scene Management you want for your aplication:

Virtual void chooseSceneManager(void)
    {
        mSceneMgr = mRoot->createSceneManager(ST_GENERIC);
    }

You have the choice between the following types of scene:

ST_GENERIC

This scene is based on a 3D world with objects, but no ground. World is rendered based on octree (far objects are not rendered). This scene fits for outer-space, etc.

This scene type also applies for the DotSceneManager plugin. As a result, you cannot use the scene type for both the OctreeSceneManager and DotSceneManager at the same time.

ST_INTERIOR

The ground is based on a Quake III BSP-file.

ST_EXTERIOR_CLOSE ( aka "Terrain")

This scene is based on a world with 3D objects and a basic terrain for ground. The scene has a simple LOD.

  • The ground is based on 1 description file, and 3 images:
    • 1 image for terrain height-map (dimension: 2n+1 x 2n+1)
    • 1 image for terrain texture (dimension: 2n x 2n)
    • 1 image for detailed terrain texture (when close to the camera)




This scene fits for small map (257x257 or 513x513). You load the description file with the setWorldGeometry(“terrainfile.cfg”) function. See TerrainSceneManager. See demo_terrain.exe

ST_EXTERIOR_FAR (aka "Nature")

This mode is not present anymore in Ogre 1.0. Use "Terrain", or "Paging Landscape" instead.

ST_EXTERIOR_REAL_FAR (plug-in)

This plug-in contains three kinds of Scene Managers: PLSM 1, PLSM2, iPLSM. It is composed of 3 Scene-manager, that uses 3 different plug-in library and 3 different configuration files. Look in the Ogre Forum for more information.

ST_EXTERIOR_REAL FAR (aka "PLSM1" or "Paging Landscape Scene Manager 1")

This scene is based on a world with 3D objects and basic paged terrain for ground. The scene uses a good LOD. The ground is divided into pages. Each page is based on images (from multiple sources heighfield, heighfieldTC and spline), and textures.
This scene fits for very wide terrain.
Note: you have to install the paging landscape plug-in and compile it, and adjust the plugin.cfg file. See also demo_pagingLandscape.exe.

ST_EXTERIOR_REAL FAR (aka "PLSM2" or "Paging Landscape Scene Manager 2")

Same as PLSM1, but the textures can be applied by height, and splatting (shader, multi-texture, multi-pass), lighting, real-time texturing, deformation and geomipmaping LOD have been added.
This scene fits for very wide terrain : see Paging Scene Manager

iPLSM

Work in Progress.

DISPLACEMENT MAPPING (plug-in)

A scene based on a height-map and needing vertex shader.

How to have debug information

For real time debug information, you can have one line displayed on the main window, with the command:

mWindow->setDebugText("debug information");
    
    int value;
    mWindow->setDebugText("Value = " + StringConverter::toString(value));

For differed time debug information, you can log the event in the default log file (ogre.log):

LogManager::getSingleton().logMessage(LML_NORMAL, "text 1",  "text 2");

If you want to use a specific logfile (instead of the default ogre.log file):

Log* mylogfile, ogrelogfile;
    
    ogrelogfile = LogManager::getSingleton().getDefaultLog();
    mylogfile   = LogManager::getSingleton().createLog("mylogfile.log");
    
    LogManager::getSingleton().setDefaultLog(mylogfile);
    LogManager::getSingleton().logMessage(LML_NORMAL, "write in mylogfile.log");
    
    LogManager::getSingleton().setDefaultLog(ogrelogfile);
    LogManager::getSingleton().logMessage(LML_NORMAL, "write in ogre.log");

How to maintain the camera above the ground



You can use different ways, according to the nature of the “floor”. The floor can be a terrain, a mesh object, a planeEntity, etc…

First, send a Ray from your camera towards the ground:

Vector3 pos = mCamera->getPosition();
    
    float  floorD = 0;
    
    RaySceneQuery* mRayQuery;
    SceneManager*  mSceneMgr;
    
    mSceneMgr = mCamera->getSceneManager();
    mRayQuery = mSceneMgr->createRayQuery(Ray(pos, Vector3::NEGATIVE_UNIT_Y));
    
    RaySceneQueryResult& queryResult = mRayQuery->execute();

You get the list of the objects crossed by the ray. Take the index of the first and last item of the list.

RaySceneQueryResult::iterator i;
    RaySceneQueryResult::iterator i_final;
    
    i_final = queryResult.end();
    i = queryResult.begin();

If the floor is a terrain, you should search a world fragment in the list.

if ( i!=queryResult.end() && i->worldFragment )
    {
        SceneQuery::WorldFragment* wf = i->worldFragment;
        mWindow->setDebugText("Detected: " + StringConverter::toString(i->worldFragment-> 
        singleIntersection.y));
    }

If the floor is an object, you should search for the first object found, or for a specified object. Note that this way is a bit inaccurate, if objects are complex or rescaled; and it does not work if objects are hollow or convex. In this example, we are looking for a plane entity named « floor ».

for ( i=queryResult.begin(); i!=i_final; ++i)
    {
        MovableObject* wf = i->movable;
        Real distance       = i->distance;
        String detected ;
        detected  = "movable found " + wf->getName();
        detected += " at "+ StringConverter::toString(distance);
    
        if (wf->getName() == "floor")
        {
            mWindow->setDebugText(detected);
            floorD=distance;
        }
    }

Finally, destroy the query.

mCamera->getSceneManager()->destroyQuery(mRayQuery);

And adjust the Y position of your camera (this is a very poor example).

// keep camera not too close of the ground
    if (floorD < MIN_Y_ALLOWED)
    {
        pos.y = floorY+ MIN_Y_ALLOWED;
        mCamera->setPosition(pos);
    }
    
    // make the camera falling if too far of the ground
    if (floorD > MIN_Y_ALLOWED)
    {
        pos.y = pos.y - 4;
        mCamera->setPosition(pos);
    }

How to get a viewer to face a target



(Code not checked yet)

Vector3 lookAt = target->getPosition() - viewer->getPosition(); 
    Vector3 axes[3]; 
    
    viewer->getOrientation().ToAxes(axes); 
    Quaternion rotQuat; 
    
    if (lookAt == axes[2]) 
    {
        rotQuat.FromAngleAxis(Math::PI, axes[1]); 
    } 
    else 
    {
        rotQuat = axes[2].getRotationTo(lookAt); 
    } 
    viewer->setOrientation(rotQuat* viewer->getOrientation());

How to make a screenshot



There are two Ogre functions to make screenshots: writeContentsToFile() and writeContentsToTimestampedFile(), you just have to call it. They have two ways of naming the screenshot files.

If you want to have files named screenshot_1.png, screenshot_2.png, you can use:

unsigned int indice = 1;
    char filename[30] ;
    sprintf (filename, “screenshot_%d.png”, ++indice);
    mWindow->writeContentsToFile(filename);

Or, if you want to have time-stamped files (named screenshot_MMDDYYY_HHMMSSmmm.jpg) in the current application directory, you can just use:

mWindow->writeContentsToTimestampedFile(“screenshot”,”.jpg”);

Note: MM is from 0 to 11. YYY is (year-1900) (ie: 2004=104)

Note: The extension you specify ( “.png”, or “.bmp”, or “.jpg”, etc) will determine the type of the generated file.

How to get some fog

mSceneMgr->setFog (FOG_LINEAR, ColourValue(0.25,1.1,0.2), 0.5, 200, 500);

The parameters are:

  • Type of fog: FOG_LINEAR, FOG_EXP, FOG_EXP2, FOG_NONE
  • Color
  • Exp_density 0..1 (small number = large zone without fog)
  • Initial density (for linear fog)
  • Final density (for linear fog)




Note that transparent objects in the fog will become opaque. You should exclude them from the fog, with the instruction fog_override true in the pass{} section of the material file.

How to render the world in wire-frame

To render the scene in solid or in wire-frame, use the following commands:

mCamera->setDetailLevel (SDL_WIREFRAME);
    mCamera->setDetailLevel (SDL_SOLID);

You can do this only with the whole scene, not with a single object.

NOTE THAT THE ABOVE DOESN'T SEEM TO WORK IN OGRE 1.2

To render the scene in solid or in wire-frame for Ogre 1.2+, use the following:

mCamera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);     /* wireframe */
    mCamera->setPolygonMode(Ogre::PolygonMode::PM_SOLID);         /* solid */

How to get and set parameters in a configuration file



You can read configuration parameters in a configuration file. The configuration file looks like this (for separators, you can use “;”, or “=”, or “TAB”):

language=french

And the code to use it, (eg: read the language parameter):

ConfigFile setupfile;
     setupfile.load("myconfig.cfg");
     
     String Lang = setupfile.getSetting(“language”);

How to have a separate configuration application



You can make a separate configuration exe with the configuration dialog box.
mRoot->showConfigDialog();

This single function will show the configuration dialog box, and store the configuration in an ogre.cfg file.

In you main program, you just have to call the functions:

mRoot->restoreConfig();
 mWindow = mRoot->initialise(true);

And it will automatically load and apply the configuration (if the file exists).

For setting other configuration parameters (audio, controls, etc), I did not manage to call the showConfigDialog() function in a standard MFC application, so I had to write a second configuration exe. (if somebody has an idea to how to do it…)

How to manage world-units

Knowing the value of your world units is useful when you create your 3D objects with a modeler. You can then set the same scale to all your objects, and you will not have to rescale individually each object in your code with the setScale() function.

To determine the world-units of your scene, you don’t have a Ogre-function: you will have to walk in your scene, and visually estimate the distance from one point to another, and check the coordinates of these two points.
So, in the Ogre demo programs, you fill find 15m=1.500wu. That is: 1wu=1cm. And, in the ExampleFrameListener, you will find the speed set at 100 wu per second (= 1 m/s = the speed of a walking man).

If you want to have a different setting, ie: 1wu = 1m, you just have to adjust the speed of your camera in the FrameListener (lets say, 1 wu per second), and eventually adjust the size of your 3D objects. You can also adjust the focal angle of your camera of a few degree (between 45 and 60) with the function setFOVy(angle).

Note:

You better choose this very early in your project, otherwise, you will have to rescale all the objects, camera, particle, etc (dimension and speed) that you already defined in your code and scripts.

How to add a Plug-in or a Library in your project

In the Visual C++ environment, adjust:

  • Project Setting
    • C++
    • Category preprocessor
    • Line additional include directory




Add the directory where the header files (.h) are located (the separator is ‘,’).
(Or adjust Tools-option-directory-include files, if you want it as a permanent setting for all your projects)

Then adjust:

  • Project Setting
    • Link
    • Category input
    • Line additional library path




Add the directory where the library file (.lib) is located (the separator is ‘,’).
(Or adjust Tools-option-directory-library files if you want it as a permanent setting for all your projects)

Then adjust:

  • Project Setting
    • Link
    • Category input
    • Line “objects/library module”




Add the name of library file (.lib) (the separator is ‘ ’).

If this is an Ogre plug-in, you should also adjust the plugin.cfg file.

How to manage N objects moving

The usual way is to write two classes for each object: for instance a class Rocket derived from UserDefinedObject, and a class RocketListener derived from FrameListener.

class Rocket  : public UserDefinedObject
 {
 public:
   Rocket ();
   virtual ~ Rocket ();
 …
 }

 class RocketListener  : public FrameListener
 {
 public:
   RocketListener ();
   virtual ~ RocketListener ();
   bool    frameStarted(const FrameEvent& evt);
 …
 }

In the Rocket code, you will call once (in the constructor function, or somewhere else):

mRoot->addFrameListener(…);

and in the destructor function (or elsewhere):

mRoot->removeFrameListener(…);

Then the function RocketListener::frameStarted will be called by Ogre at the beginning of every frame.

With this method, you will have N "Rocket" objects, and 1 "RocketListener" object. This RocketListener will make move the rockets that have registered to him. (You write the registration function).

Other method:

An other way is to have only one class derived from UserDefinedObject, and from FrameListener.

class Robot  : public UserDefinedObject, public FrameListener
 {
 public:
   Robot();
   virtual ~Robot();
   bool    frameStarted(const FrameEvent& evt);
 …
 }

In the Robot code, I call once:

mRoot->addFrameListener(this);

and when the object don’t need to move anymore:

mRoot->removeFrameListener(this);

The function frameStarted() is called by Ogre at the beginning of every frame. The frameStarted() function has also a direct access to all member variables.

Note that this method can affect performance if you have many objects of this class (because Ogre will make N calls to frameStarted() at every frame, instead of 1). In that case, it is better to use the first method.

How to have transparency

In the .material file, you can set the scene_blend parameter to add, modulate or alpha_blend.

scene_blend add

  • You can use a JPEG or PNG image file for the texture.
  • The dark parts of the picture will become transparent (black = fully transparent).
  • Use it for explosion, flare, lights, etc




scene_blend modulate

  • You can use a JPEG or PNG image file for the texture. The texture will multiply with the background. Usually, it colors and darkens the picture. The dark part of the texture will become transparent.
  • Use it for smoked glass, semi transparent objects, etc




scene_blend alpha_blend

  • You should use a PNG image file for the texture.To have transparency in your PNG file, you should prepare the file with Photoshop, by sending the background layer to the trashcan, and use the eraser on the other layers.
  • The erased parts will become transparent.



How to get some shadows in your scene

There two kinds of shadows: the shadowed side of an object, and the projected (=casted) shadow of an object.

The shadowed side

To see the shadowed sides of your objects, you have to set the appropriate parameters in the material description.

  • In the createScene function, don’t use an ambient light (or very low light).
  • In the createScene function, create a light (see the above chapter)
  • In the object.material file, set the following parameters in the pass{} section.
    • If dynamic lighting is OFF, object is fully lit, so use ON
    • Note: for colors, 000 is black and 111 is white.
    • ambient is the global ambient light. It allows having a strong or a soft contrast between the lit side and the shadowed side.
    • diffuse is the reflected colour for the lit side. You can imagine it like a coloured filter hold in front of the Light Object.
    • Specular is the reflected colour for the most lit part of the lit side. It can give a metallic aspect to the object. To see this, you have to lower the ambient light, and create a setSpecularColor for your Light.



lighting on
 ambient  1 1 1
 diffuse  1 1 1
 // specular 1 1 1 12

Note that transparent textures, and billboards cannot receive a shadow.

The casted shadows:

An entity can cast (=send) a shadow. By default, lights don’t cast shadows, you have to enable it.

There are four techniques of shadows rendering: STENCIL or TEXTURE, and ADDITIVE or MODULATIVE. (The more “cpu friendly” is SHADOWTYPE_TEXTURE_MODULATIVE).

STENCIL SHADOWS:

  • This technique uses the CPU for rendering.
  • You should set a max distance (with setShadowFarDistance) in order to keep a good framerate.




*The mesh (which cast shadows) should be completely manifold (ie: closed / no holes).(not anymore in Ogre 1.0: TBC)

  • Avoid long shadows (ie: dawn)
  • Avoid objects too close of the light.
  • This technique allows self-shadowing.
  • The shadows have hard edges (hard transition between shadow and light).




TEXTURE SHADOWS:

  • This technique uses the graphic card for rendering.
  • This technique works only with directional or spotlight.
  • This technique does not allow self-shadowing.
  • The meshes should be defined as “shadow caster” or “shadows receiver”.
  • Avoid long shadows (ie dawn)
  • Avoid objects too close of the light.
  • The shadows have smooth edges.
  • Color and definition of the shadow can be defined.




For more details, see demo_shadows.exe, and also see the chapter 7 “Shadows” of the manual.

Example:

mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE);
 mSceneMgr->setShadowColour( ColourValue(0.5, 0.5, 0.5) );
 ...
 mLight->setCastShadows(true);
 ...
 mCastingObject->setCastShadows(true);
 mReceivingObject->setCastShadows(false);
 ...
 myMaterial->setReceiveShadows(true);
 ...

Note that the instruction myMaterial->setReceiveShadows(true) can be replaced by receive_shadows on in the material file, at top level, or be omitted, as the default setting for material is ON. You can use this instruction to set the value to OFF for materials that should not receive shadows. This can save some framerate.

How to play an animated mesh

First, you need to have:

  • A mesh file (which contains the description of the mesh, and the association between the vertices and the bones)
  • A skeleton file (which contain the description of the bones, and the movements of the bones during the animation).




These two files are generated by the ogre-Exporter utility.

To load the animation:

Animation::setDefaultInterpolationMode(Animation::IM_SPLINE);
 AnimationState *mAnimState = mEntity->getAnimationState("move");
 mAnimState->setEnabled(true);
 mAnimationSpeed = 1;

To play the animation (in the frameStarted() function) :

mAnimState->addTime(evt.timeSinceLastFrame * mAnimationSpeed);

To stop the animation:

if (mAnimState->getTimePosition() >= mAnimState->getLength())      
 {
   // animation is over
 }

Or , when you load the animation, you can set:

mAnimState->setLoop(false);

To play the animation backwards:

mAnimState->addTime(evt.timeSinceLastFrame * (-mAnimationSpeed));

How to have a debug console



This is a code from johnhpus.

To get full use of this debug console, you need to run your program in windowed mode (otherwise, the console is hidden).
Create the console windows in the winmain.cpp program:

AllocConsole();
 try { app.go(); }
 
 FreeConsole();
 return 0;

And write debug information in the debug console:

#include "conio.h"
 
 _cprintf("Thanks John");

How to have a Debug Console (Alternative)



from Willi >.>

Or just these project settings in the linker, find them in the project settings (Linker->System->SubSystem and Linker->Advanced->Entry Point), or set them manually in the command line for MSVS

/SUBSYSTEM:CONSOLE /ENTRY:WinMainCRTStartup

and feel free to use any output you want.. like

#include <iostream>
...
std::cout << "Debug Message";


Note that replacing "int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)" with "int main()", and setting the subsystem to auto (which is the default) will also work, however you won't get the hInstance...


How to have a Debug Console (Easy and powerful Alternative)



This code was posted on Ogre Forums by Kristian Mortensen - Many thanks!



Add this code to your main.cpp:

#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <string>

void showWin32Console()
{
    static const WORD MAX_CONSOLE_LINES = 500;
    int hConHandle;
    long lStdHandle;
    CONSOLE_SCREEN_BUFFER_INFO coninfo;
    FILE *fp;
    // allocate a console for this app
    AllocConsole();
    // set the screen buffer to be big enough to let us scroll text
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
    coninfo.dwSize.Y = MAX_CONSOLE_LINES;
    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
    coninfo.dwSize);
    // redirect unbuffered STDOUT to the console
    lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    fp = _fdopen( hConHandle, "w" );
    *stdout = *fp;
    setvbuf( stdout, NULL, _IONBF, 0 );
    // redirect unbuffered STDIN to the console
    lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    fp = _fdopen( hConHandle, "r" );
    *stdin = *fp;
    setvbuf( stdin, NULL, _IONBF, 0 );
    // redirect unbuffered STDERR to the console
    lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    fp = _fdopen( hConHandle, "w" );
    *stderr = *fp;
    setvbuf( stderr, NULL, _IONBF, 0 );
    // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
    // point to console as well
    std::ios::sync_with_stdio();
}

Then you just do this:

SET_TERM_HANDLER;

 showWin32Console();
 try {
 app.go();
} catch( Ogre::Exception& e ) {
...
}

 FreeConsole();
 return 0;
}

Now you can use cout, printf, etc. all you want - it will be directed to your console.

And no need to change any project settings. ;-))

How to have a Debug Console (using MS Visual Studio's Output Window)

Just use

OutputDebugString("Hello World");
OutputDebugString(Ogre::StringConverter::toString(3.141).c_str());
OutputDebugString("\n");

How to Calculate the Degrees Between A SceneNode and a Point

The value returned from this function is the degrees snFrom would have to yaw() in order to look at vecTo.

Real angleBetween(SceneNode &snFrom, Vector3 &vecTo)
 {
   Radian r;
   Vector3 vsrc = snFrom.getOrientation( ) * Vector3::NEGATIVE_UNIT_Z;
   Vector3   vDiff = vecTo - snFrom.getPosition();
   vDiff.normalise();
   r = Math::ACos(vsrc.dotProduct(vDiff));
   return r.valueDegrees();
 }

How to enable NVPerfHUD



this code is from Istari

First of all download and install NVPerfHUD.
Next you will have to make some code changes, so open up the RenderSystem_Direct3D9 project.

Find the following lines in D3D9RenderWindow::createD3DResources:

hr = pD3D->CreateDevice( mDriver->getAdapterNumber(), devType, mHWnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING | extraFlags, &md3dpp, &mpD3DDevice );


And change them to look like this:

#ifdef NV_PERFHUD
                D3DADAPTER_IDENTIFIER9 Identifier;
                hr = pD3D->GetAdapterIdentifier(mDriver->getAdapterNumber(), 0, &Identifier);
                if (strcmp(Identifier.Description, "NVIDIA NVPerfHUD") == 0)
                {
                    hr = pD3D->CreateDevice( mDriver->getAdapterNumber(), D3DDEVTYPE_REF, mHWnd,
                        D3DCREATE_HARDWARE_VERTEXPROCESSING | extraFlags, &md3dpp, &mpD3DDevice );
                }
                else
                {
#endif
                hr = pD3D->CreateDevice( mDriver->getAdapterNumber(), devType, mHWnd,
                    D3DCREATE_HARDWARE_VERTEXPROCESSING | extraFlags, &md3dpp, &mpD3DDevice );
#ifdef NV_PERFHUD
                }
#endif


All you have to do now is define NV_PERFHUD before building the dll to enable it.

Now when you run your executable with NVPerfHUD you will have to select the NVIDIA NVPerfHUD rendering device.


Alias: HowTo (part II)
Alias: HowTo_(part_II)