111 Introduction to OGRE3D Programming: Main Loop.

Post on 05-Jan-2016

223 views 2 download

Transcript of 111 Introduction to OGRE3D Programming: Main Loop.

111

Introduction to Introduction to OGRE3D Programming:OGRE3D Programming:

Main LoopMain Loop

22

Major part of call graphMajor part of call graph

BaseApplication::go()

BaseApplication::setup()

Root::startRendering()

Root::renderOneFrame()

Root::_updateAllRenderTargets();

Root::_fireFrameStarted() Root::_fireFrameEnded();

3

Main programMain program

int main(int argc, char **argv){

BaseApplication *MyGameApp = new BaseApplication;

try {

MyGameApp go();

} catch( Exception& e ) {… …

}

return 1;}

virtual void BaseApplication::go(void){

if (!setup()) return;

mRoot->startRendering();

// clean updestroyScene();

}

The implementation of go()The implementation of go()

The implementation of setup()The implementation of setup()

The function setup() instantiates mRoot, setups resources, loads plugins, creates scene and creates frame listener.

mRoot = new Ogre::Root(mPluginsCfg); setupResources(); bool carryOn = configure(); if (!carryOn) return false; chooseSceneManager(); createCamera();

createViewports();createResourceListener();

loadResources();createScene();

createFrameListener();

6

Major functions (1/3)Major functions (1/3)

Root::startRendering() {

assert(mActiveRenderer != 0);mActiveRenderer->_initRenderTargets();

clearEventTimes();// Infinite loop, until broken out of by frame listeners// or break out by calling queueEndRendering()mQueuedEnd = false;while( !mQueuedEnd )

{//Pump messages in all registered RenderWindow windowsWindowEventUtilities::messagePump();if ( !renderOneFrame() ) break;

}}

7

Major functions (2/3)Major functions (2/3)

bool Root::renderOneFrame(void){ if( !_fireFrameStarted() ) return false;

_updateAllRenderTargets();

return _fireFrameEnded();}

class myFrameListener : public FrameListener {public: bool frameStarted (const FrameEvent &evt); bool frameRenderingQueued( const FrameEvent &evt); bool frameEnded (const FrameEvent &evt);};

bool myFrameListener::frameStarted(const FrameEvent &evt)

{// cool stuff to do before a frame is rendered return true;}//define frameRenderingQueued herebool myFrameListener::frameEnded(

const FrameEvent &evt) {// cool stuff to do after a frame is rendered return true;}

bool Root::_fireFrameStarted(FrameEvent& evt)bool Root::_fireFrameStarted(FrameEvent& evt)

OgreProfileBeginGroup("Frame", OGREPROF_GENERAL);OgreProfileBeginGroup("Frame", OGREPROF_GENERAL);

// Remove all marked listeners// Remove all marked listeners

……

// Tell all listeners// Tell all listeners

for ( i= mFrameListeners.begin(); i != mFrameListeners.end(); ++i )for ( i= mFrameListeners.begin(); i != mFrameListeners.end(); ++i )

{{

if ( !(*i)if ( !(*i)frameStarted(evt) )frameStarted(evt) )

return false;return false;

}}

return true;return true;

bool Root::_updateAllRenderTargets(void)bool Root::_updateAllRenderTargets(void)

// update all targets but don't swap buffers// update all targets but don't swap buffers

mActiveRenderer->_updateAllRenderTargets(false); mActiveRenderer->_updateAllRenderTargets(false);

// give client app opportunity to use queued GPU time// give client app opportunity to use queued GPU time

bool ret = _fireFrameRenderingQueued();bool ret = _fireFrameRenderingQueued();

// This belongs here, as all render targets must be updated // This belongs here, as all render targets must be updated

// before events are triggered, otherwise targets could be// before events are triggered, otherwise targets could be

// mismatched. This could produce artifacts, e.g. with shadows.// mismatched. This could produce artifacts, e.g. with shadows.

…………

return ret;return ret;

bool Root::_fireFrameRenderingQueued(FrameEvent& evt)bool Root::_fireFrameRenderingQueued(FrameEvent& evt)

// Increment next frame number// Increment next frame number

++mNextFrame;++mNextFrame;

// Remove all marked listeners// Remove all marked listeners

…………

// Tell all listeners// Tell all listeners

for ( i= mFrameListeners.begin(); i != mFrameListeners.end(); ++i )for ( i= mFrameListeners.begin(); i != mFrameListeners.end(); ++i )

{{

if ( !(*i)->frameRenderingQueued( evt ) )if ( !(*i)->frameRenderingQueued( evt ) )

return false;return false;

}}

return true;return true;

bool Root::_fireFrameEnded(FrameEvent& evt)bool Root::_fireFrameEnded(FrameEvent& evt)

// Remove all marked listeners// Remove all marked listeners

…………

// Tell all listeners// Tell all listeners

bool ret = true;bool ret = true;

for ( i= mFrameListeners.begin(); i != mFrameListeners.end(); ++i )for ( i= mFrameListeners.begin(); i != mFrameListeners.end(); ++i )

{{

if ( !(*i)->frameEnded(evt) ) {if ( !(*i)->frameEnded(evt) ) {

ret = false;ret = false;

break;break;

}}

}}

// Tell buffer manager to free temp buffers used this frame// Tell buffer manager to free temp buffers used this frame

return ret;return ret;

Remove all marked ListenerRemove all marked Listenerset<FrameListener*>::type::iterator i;set<FrameListener*>::type::iterator i;

for (for ( i = mRemovedFrameListeners.begin();i = mRemovedFrameListeners.begin();

i != mRemovedFrameListeners.end(); i != mRemovedFrameListeners.end();

i++)i++)

{{

mFrameListeners.erase(*i);mFrameListeners.erase(*i);

}}

mRemovedFrameListeners.clear();mRemovedFrameListeners.clear();

13

Major functions (3/3)Major functions (3/3)

bool myFrameListener::frameStarted(const FrameEvent& evt){

if(mWindow->isClosed()) return false; ... ... //Need to capture/update each devicemKeyboard->capture();mMouse->capture();if( mJoy ) mJoy->capture();... ...handleKeyEvent(evt);handleMouseEvent(evt);

... ...

... ...

... ...

return true;}

} code for game management and update of game state based on FrameEvent evt.

1414

Major part of call graphMajor part of call graph

GameApplication::go()

GameApplication::setup()

Root::startRendering()

Root::renderOneFrame()

Root::_updateAllRenderTargets();

Root::_fireFrameStarted() Root::_fireFrameEnded();

15

Frame listeners are the only way we can invoke your own code during the Ogre render loopwhen using the startRendering() method.

A frame listener is simply a class that implementsthe FrameListener interface, and is just a callback that allows OGRE to invoke our code at the beginning and/or end of each.

Frame listenerFrame listener

1616

Use ExampleApplication and ExampleFrameListener

Demo: main_loopDemo: main_loop

In the main .cpp file, we have:

class GameApplication: public ExampleApplication{public:

GameApplication() {}void createScene() {}

};

GameApplication *app = new GameApplication;

int main(int argc, char **argv){

try {app->go();

} catch( Exception& e ) {…….}

}

17

Object-Oriented Graphics Object-Oriented Graphics Rendering Engine ( OGRE 3D)Rendering Engine ( OGRE 3D)

- The Main Program- The Main Program

FrameStartedFrameStarted

18

bool myFrameListener::frameStarted(const FrameEvent& evt){

if(mWindow->isClosed()) return false;. . . . . . //Need to capture/update each devicemKeyboard->capture();mMouse->capture();if( mJoy ) mJoy->capture();. . . . . .handleKeyEvent(evt);handleMouseEvent(evt);. . . . . .moveMainChar(evt);updateCreaturesAction(evt);. . . . . .. . . . . .. . . . . .

return true;}

} code for game management and update of game state based on FrameEvent evt.

moveMainCharmoveMainChar

19

void moveMainChar(const FrameEvent& evt){

mCameraNode->yaw(mRotX);

// move the head node along the camera viewing directionconst Quaternion q = mCameraNode->getOrientation();mCameraNode->setOrientation(q);SceneNode *node = mHeadNode->getSceneNode();node->setOrientation(q);node->translate( q*(-mTranslateVector) );

// maintain the distance between the camera and mHeadNode

const Vector3 v3 = node->getPosition();Vector3 cv = v3;Vector3 hv = Vector3(0.0, 0.0, -1.0);hv = q*hv;float d0 = -mCamerViewDistanceFromMainChar;float d1 = 30;

mCameraNode->setPosition(cv-hv*d0+Vector3(0.0, d1, 0.0));}

updateCreatureActionsupdateCreatureActions

20

void updateCreaturesAction(const FrameEvent& evt){

if (mRobot) {mRobot->checkAlive(evt);

}if (mRobot && mHeadNode) {

mRobot->UpdateAction(evt, mHeadNode);

}}

FrameEventFrameEvent

21

namespace Ogre {

struct FrameEvent { /** Elapsed time in seconds since the last event. This gives you time between frame start & frame end, and between frame end and next frame start. @remarks This may not be the elapsed time but the average elapsed time between recently fired events. */ Real timeSinceLastEvent; /** Elapsed time in seconds since the last event of the same type, i.e. time for a complete frame. @remarks This may not be the elapsed time but the average elapsed time between recently fired events of the same type. */ Real timeSinceLastFrame; };};

Introduction to dynamic-link Introduction to dynamic-link library (DLL)library (DLL)

On WindowsOn Windows Microsoft’s implementation of shared libraryMicrosoft’s implementation of shared library File format same as for the Windows EXE filesFile format same as for the Windows EXE files ContainingContaining

– CodeCode– Data Data – Resources,Resources,– or in any combinationor in any combination

22

Symbol resolution and bindingSymbol resolution and binding

Each function exported by a DLL is Each function exported by a DLL is identified by a numeric ordinal and identified by a numeric ordinal and optionally a nameoptionally a name

Functions can be imported from a DLL Functions can be imported from a DLL either by ordinal or by a nameeither by ordinal or by a name

The ordinal represents the position of the The ordinal represents the position of the functions address pointer in the DLL Export functions address pointer in the DLL Export Address tableAddress table

23

Symbol resolution and bindingSymbol resolution and binding

Ordinal: subject to changeOrdinal: subject to change

Names: preserved across different Windows Names: preserved across different Windows releasesreleases

24

2525

Load-time dynamic linkingLoad-time dynamic linking Use the information the linker placed

in the file to locate the names of the DLLs that are used by the process

Fail to locate a required DLL-> terminate the process and report the error

Locate successfully -> map the DLL into the virtual address space of the process

2626

Load-time dynamic linkingLoad-time dynamic linking- Call a DLL function explicitly.- The application must be linked with the import library myMessage.lib.

extern "C" int __cdecl myMessage(LPWSTR); // a function from a DLL

int main(VOID) { int Ret = 1; Ret = myMessage (L“Message\n”); return Ret;

}

27

Explicit run-time linkingExplicit run-time linking

LoadLibrary (or LoadLibraryEx): explicitly LoadLibrary (or LoadLibraryEx): explicitly load at run timeload at run time

GetProcAddress: lookup exported symbols by name

FreeLibrary: unload the DLL

Example: creating a DLLExample: creating a DLL

2828

#ifdef __cplusplus // If used by C++ code,extern "C" { // we need to export the C interface #endif __declspec(dllexport) void* createSceneCreator() {

… …return static_cast< void* > (new

DemoApp);}}

#ifdef __cplusplus } #endif

Module definition fileModule definition file

2929

(.def) file : a text file that contains statements defining an executable (.exe) file or dynamic-link library (DLL).

Some commands:Some commands:LIBRARY: LIBRARY: Specify the internal name of the DLL

EXPORTS: MEXPORTS: Make one or more definitions available as exports to other applications

Syntax of an export definition: entryname[=internalname] [@ordinal[NONAME]]

Creating a DLL:Creating a DLL:Setup module definition fileSetup module definition file

3030

Project>properties->Linker-> input->module Project>properties->Linker-> input->module definition filedefinition file

Content of sceneCreator.defContent of sceneCreator.def

LIBRARY sceneCreator

EXPORTS

createSceneCreator @1

Explicit run-time linking DLLExplicit run-time linking DLL

3131

HINSTANCE hdll = NULL;typedef void* (*pvFunctv)();pvFunctv sceneCreator;

hdll = LoadLibrary(TEXT("./dll/sceneCreator.dll"));

if (hdll) { … } else { ……; return; }

sceneCreator = (pvFunctv) (GetProcAddress( hdll, "createSceneCreator" ) );

DemoApp *app = static_cast< DemoApp* > ( sceneCreator() );

Useful links for DLLUseful links for DLL

About DLL:About DLL:http://msdn2.microsoft.com/en-us/http://msdn2.microsoft.com/en-us/

library/ms686912(VS.85).aspxlibrary/ms686912(VS.85).aspx

Module definition file: Module definition file: http://msdn2.microsoft.com/en-us/libhttp://msdn2.microsoft.com/en-us/library/ms923590.aspxrary/ms923590.aspx

32