Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/ColladaPlugin/demo/src/ColladaDemo.cpp @ 55

Last change on this file since 55 was 21, checked in by nicolasc, 17 years ago

added ogreode and Colladaplugin

File size: 19.1 KB
Line 
1/*
2-----------------------------------------------------------------------------
3This source file is part of OGRE
4    (Object-oriented Graphics Rendering Engine)
5For the latest info, see http://www.ogre3d.org/
6
7Copyright (c) 2000-2005 The OGRE Team
8Also see acknowledgements in Readme.html
9
10You may use this sample code for anything you like, it is not covered by the
11LGPL like the rest of the engine.
12-----------------------------------------------------------------------------
13*/
14#include "OgreColladaManager.h"
15#include "OgreColladaScene.h"
16#include "ColladaDemo.h"
17#include "UIHandler.h"
18
19#include "OgreConfigFile.h"
20#include "OgreException.h"
21#include "OgreRoot.h"
22#include "OgreTextureManager.h"
23#include "OgreCamera.h"
24#include "OgreRenderWindow.h"
25#include "OgreMeshManager.h"
26#include "OgreSkeletonManager.h"
27#include "OgreMaterialManager.h"
28
29#include "OgreCEGUIRenderer.h"
30#include "OgreCEGUIResourceProvider.h"
31
32#include <sys/types.h>
33#include <sys/stat.h>
34
35#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
36#define WIN32_LEAN_AND_MEAN
37#include "windows.h"
38#endif
39
40
41#define DEFAULT_CAMERA_NAME "DefaultCamera"
42//-----------------------------------------------------------------------------
43//      sub-class for ListboxTextItem that auto-sets the selection brush
44//      image.
45//-----------------------------------------------------------------------------
46class MyListItem : public CEGUI::ListboxTextItem
47{
48public:
49    MyListItem(const CEGUI::String& text, CEGUI::uint id) : CEGUI::ListboxTextItem(text, id)
50        {
51                setSelectionBrushImage("TaharezLook", "MultiListSelectionBrush");
52        }
53};
54
55//-----------------------------------------------------------------------------
56//      ColladaDemo Methods
57//-----------------------------------------------------------------------------
58ColladaDemo::~ColladaDemo()
59{
60        delete mGUISystem;
61        delete mGUIRenderer;
62    delete mFrameListener;
63
64    // get rid of the shared pointers before shutting down ogre or exceptions occure
65
66    delete mRoot;
67}
68
69//--------------------------------------------------------------------------
70void ColladaDemo::go()
71{
72    if (!setup())
73        return;
74
75    mRoot->startRendering();
76}
77
78//--------------------------------------------------------------------------
79bool ColladaDemo::setup()
80{
81    bool setupCompleted = false;
82
83    mRoot = new Ogre::Root();
84
85    setupResources();
86    if (configure())
87    {
88
89        mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC, "ExampleSMInstance");
90        createDefaultCamera();
91        createViewports();
92
93        // Set default mipmap level (NB some APIs ignore this)
94        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
95
96        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
97        if (setupGUI())
98        {
99            // Set default ambient light level
100            mSceneMgr->setAmbientLight(Ogre::ColourValue(0.3, 0.3, 0.3));
101            createFrameListener();
102                // load some GUI stuff for demo.
103                initDemoEventWiring();
104                updateAvailableCameras();
105            setupCompleted = true;
106        }
107    }
108
109        return setupCompleted;
110}
111
112//--------------------------------------------------------------------------
113bool ColladaDemo::configure()
114{
115    // Show the configuration dialog and initialise the system
116    if(mRoot->showConfigDialog())
117    {
118        // If returned true, user clicked OK so initialise
119        // Here we choose to let the system create a default rendering window by passing 'true'
120        mWindow = mRoot->initialise(true);
121        return true;
122    }
123    else
124    {
125        return false;
126    }
127}
128
129//--------------------------------------------------------------------------
130void ColladaDemo::createDefaultCamera()
131{
132    // Create the default camera to be used if the dae document does not provide one
133    mActiveCamera = mSceneMgr->createCamera(DEFAULT_CAMERA_NAME);
134
135    // Default Position it at 500 in Z direction
136    mActiveCamera->setPosition(Ogre::Vector3(0,100,500));
137    // Look back along -Z
138    mActiveCamera->lookAt(Ogre::Vector3(0,0,-100));
139    mActiveCamera->setNearClipDistance(1);
140}
141
142//--------------------------------------------------------------------------
143void ColladaDemo::createViewports()
144{
145    // Create one viewport, entire window
146    Ogre::Viewport* vp = mWindow->addViewport(mActiveCamera);
147    vp->setBackgroundColour(Ogre::ColourValue(0,0,0));
148
149    // Alter the camera aspect ratio to match the viewport
150    mActiveCamera->setAspectRatio(
151        Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
152}
153
154//--------------------------------------------------------------------------
155void ColladaDemo::setupResources()
156{
157    // Load resource paths from config file
158    Ogre::ConfigFile cf;
159
160    #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
161        Ogre::String mResourcePath;
162        mResourcePath = bundlePath() + "/Contents/Resources/";
163        cf.load(mResourcePath + "resources.cfg");
164    #else
165        cf.load("resources.cfg");
166    #endif
167
168    // Go through all sections & settings in the file
169    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
170
171    Ogre::String secName, typeName, archName;
172    while (seci.hasMoreElements())
173    {
174        secName = seci.peekNextKey();
175        Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
176        Ogre::ConfigFile::SettingsMultiMap::iterator i;
177        for (i = settings->begin(); i != settings->end(); ++i)
178        {
179            typeName = i->first;
180            archName = i->second;
181            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
182                archName, typeName, secName);
183        }
184    }
185
186        Ogre::LogManager::getSingleton().logMessage( "Resource directories setup" );
187
188}
189
190//--------------------------------------------------------------------------
191bool ColladaDemo::setupGUI()
192{
193    bool setupGUICompleted = false;
194        // setup GUI system
195        try
196        {
197        mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY, false, 3000, mSceneMgr);
198        // load scheme and set up defaults
199
200        mGUISystem = new CEGUI::System(mGUIRenderer,(CEGUI::OgreCEGUIResourceProvider *)0,
201                        (CEGUI::XMLParser *)0,
202                        (CEGUI::ScriptModule *)0,
203                        (CEGUI::utf8*)"ColladaDemoCegui.config");
204        CEGUI::System::getSingleton().setDefaultMouseCursor("TaharezLook", "MouseArrow");
205        setupGUICompleted = true;
206        }
207        catch(...)
208        {
209        Ogre::LogManager::getSingleton().logMessage("failed to setup the GUI so shutting down...");
210        }
211       
212        return setupGUICompleted;
213
214}
215
216//--------------------------------------------------------------------------
217void ColladaDemo::updateDaeFileList()
218{
219        using namespace CEGUI;
220
221        Combobox* cbobox = (Combobox*)WindowManager::getSingleton().getWindow("DaeCombos");
222    cbobox->resetList();
223
224    Ogre::StringVectorPtr daeStringVector = Ogre::ResourceGroupManager::getSingleton().findResourceNames( Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "*.dae" );
225    std::vector<Ogre::String>::iterator daeFileNameIterator = daeStringVector->begin();
226
227    while ( daeFileNameIterator != daeStringVector->end() )
228        {
229        cbobox->addItem(new MyListItem( (*daeFileNameIterator).c_str(), 0 ));
230        ++daeFileNameIterator;
231        }
232}
233
234//--------------------------------------------------------------------------
235void ColladaDemo::initDemoEventWiring()
236{
237        using namespace CEGUI;
238
239        WindowManager::getSingleton().getWindow("ExitDemoBtn")->
240                subscribeEvent(PushButton::EventClicked, CEGUI::Event::Subscriber(&ColladaDemo::handleQuit, this));
241
242        WindowManager::getSingleton().getWindow("DaeCombos")->
243        subscribeEvent(Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&ColladaDemo::handleDaeComboChanged, this));
244        WindowManager::getSingleton().getWindow("DaeCombos")->
245        subscribeEvent(Combobox::EventDropListDisplayed, CEGUI::Event::Subscriber(&ColladaDemo::handleUpdateList, this));
246        WindowManager::getSingleton().getWindow("CameraCombos")->
247        subscribeEvent(Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&ColladaDemo::handleCameraComboChanged, this));
248        WindowManager::getSingleton().getWindow("AutoReloadCB")->
249        subscribeEvent(Checkbox::EventCheckStateChanged, CEGUI::Event::Subscriber(&ColladaDemo::handleAutoReloadChanged, this));
250
251    Window* wndw = WindowManager::getSingleton().getWindow("root");
252
253        wndw->subscribeEvent(Window::EventMouseMove, CEGUI::Event::Subscriber(&UIHandler::handleMouseMove, mFrameListener));
254
255        wndw->subscribeEvent(Window::EventMouseButtonUp, CEGUI::Event::Subscriber(&UIHandler::handleMouseButtonUp, mFrameListener));
256
257        wndw->subscribeEvent(Window::EventMouseButtonDown, CEGUI::Event::Subscriber(&UIHandler::handleMouseButtonDown, mFrameListener));
258
259        wndw->subscribeEvent(Window::EventMouseWheel, CEGUI::Event::Subscriber(&UIHandler::handleMouseWheelEvent, mFrameListener));
260        wndw->subscribeEvent(Window::EventKeyDown, CEGUI::Event::Subscriber(&UIHandler::handleKeyDownEvent, mFrameListener ));
261        wndw->subscribeEvent(Window::EventKeyUp, CEGUI::Event::Subscriber(&UIHandler::handleKeyUpEvent, mFrameListener ));
262
263    showLoadingWindow(false);
264}
265
266//--------------------------------------------------------------------------
267void ColladaDemo::doErrorBox(const char* text)
268{
269        using namespace CEGUI;
270
271        WindowManager& winMgr = WindowManager::getSingleton();
272        Window* root = winMgr.getWindow("root_wnd");
273
274        FrameWindow* errbox;
275
276        try
277        {
278                errbox = (FrameWindow*)winMgr.getWindow("ErrorBox");
279        }
280        catch(UnknownObjectException x)
281        {
282#if 0
283                // create frame window for box
284                FrameWindow* fwnd = (FrameWindow*)winMgr.createWindow("TaharezLook/FrameWindow", "ErrorBox");
285                root->addChildWindow(fwnd);
286        //      fwnd->setPosition(Point(0.25, 0.25f));
287//              fwnd->setMaximumSize(Size(1.0f, 1.0f));
288                fwnd->setSize(Size(0.5f, 0.5f));
289                fwnd->setText("CEGUI Demo - Error!");
290                fwnd->setDragMovingEnabled(false);
291                fwnd->setSizingEnabled(false);
292                fwnd->setAlwaysOnTop(true);
293                fwnd->setCloseButtonEnabled(false);
294
295                // create error text message
296                StaticText* msg = (StaticText*)winMgr.createWindow("TaharezLook/StaticText", "ErrorBox/Message");
297                fwnd->addChildWindow(msg);
298                msg->setPosition(Point(0.1f, 0.1f));
299                msg->setSize(Size(0.8f, 0.5f));
300                msg->setVerticalFormatting(StaticText::VertCentred);
301                msg->setHorizontalFormatting(StaticText::HorzCentred);
302                msg->setBackgroundEnabled(false);
303                msg->setFrameEnabled(false);
304
305                // create ok button
306                PushButton* btn = (PushButton*)winMgr.createWindow("TaharezLook/Button", "ErrorBox/OkButton");
307                fwnd->addChildWindow(btn);
308                btn->setPosition(Point(0.3f, 0.80f));
309                btn->setSize(Size(0.4f, 0.1f));
310                btn->setText("Okay!");
311
312                // subscribe event
313                btn->subscribeEvent(PushButton::EventClicked, CEGUI::Event::Subscriber(&ColladaDemo::handleErrorBox, this ));
314
315                errbox = fwnd;
316#endif
317        }
318
319        errbox->getChild("ErrorBox/Message")->setText(text);
320        errbox->show();
321        errbox->activate();
322}
323
324//--------------------------------------------------------------------------
325void ColladaDemo::viewColladaDocument(const Ogre::String& daeFileName)
326{
327
328    Ogre::LogManager::getSingleton().logMessage("ColladaDocument - import started");
329    try
330    {
331        Ogre::ColladaDocumentPtr daeDoc = Ogre::ColladaManager::getSingleton().load(daeFileName,
332            mSceneMgr);
333        // build up scene fully if document was loaded
334        if (!daeDoc.isNull())
335        {
336            Ogre::ColladaSceneNode* node = daeDoc->getScene();
337            if (node)
338            {
339                daeDoc->getScene()->createOgreInstance(NULL);
340                Ogre::LogManager::getSingleton().logMessage("ColladaDocument - import finished");
341            }
342            else
343            {
344                Ogre::LogManager::getSingleton().logMessage("ColladaDocument - import failed");
345            }
346        }
347    }
348    catch(...)
349    {
350        Ogre::LogManager::getSingleton().logMessage("ColladaDocument - failed to load");
351    }
352    // reset last update time so file update checking starts all over again if enabled
353    mLastUpdateTime = 0;
354}
355
356//--------------------------------------------------------------------------
357bool ColladaDemo::checkActiveFileUpdated()
358{
359    // get time stamp of file which will be used for auto reload feature
360    // Note: this will fail if the file was obtained from a zip archive
361    // Note2: we cheat here and only allow files loaded from ..\..\media\dae path to auto reload
362    Ogre::String filename = "..\\..\\media\\dae\\" + mActiveDaeFileName;
363    bool fileUpdated = false;
364    struct stat tagStat;
365    int ret = stat(filename.c_str(), &tagStat);
366    // only check update if file was accessible
367    if (ret == 0)
368    {
369        if (tagStat.st_mtime != mLastUpdateTime)
370        {
371            // file is updated only if this not the first time checking
372            fileUpdated = mLastUpdateTime != 0;
373            mLastUpdateTime = tagStat.st_mtime;
374        }
375    }
376    return fileUpdated;
377}
378
379//--------------------------------------------------------------------------
380bool ColladaDemo::handleQuit(const CEGUI::EventArgs& e)
381{
382        mRoot->queueEndRendering();
383    return true;
384}
385
386//--------------------------------------------------------------------------
387bool ColladaDemo::handleDaeComboChanged(const CEGUI::EventArgs& e)
388{
389        using namespace CEGUI;
390
391    // get the selected mesh filename from the combo box
392        CEGUI::ListboxItem* item = ((Combobox*)((const WindowEventArgs&)e).window)->getSelectedItem();
393    mActiveDaeFileName = item->getText().c_str();
394    loadActiveDae();
395    return true;
396}
397
398//--------------------------------------------------------------------------
399bool ColladaDemo::handleCameraComboChanged(const CEGUI::EventArgs& e)
400{
401        using namespace CEGUI;
402
403    // get the selected mesh filename from the combo box
404        CEGUI::ListboxItem* item = ((Combobox*)((const WindowEventArgs&)e).window)->getSelectedItem();
405
406    // view the selected document
407    setActiveCamera(item->getText().c_str());
408    return true;
409}
410
411//--------------------------------------------------------------------------
412bool ColladaDemo::handleAutoReloadChanged(const CEGUI::EventArgs& e)
413{
414        using namespace CEGUI;
415
416    mAutoReload = ((Checkbox*)((const WindowEventArgs&)e).window)->isSelected();
417    return true;
418}
419
420//--------------------------------------------------------------------------
421void ColladaDemo::updateAvailableCameras()
422{
423        using namespace CEGUI;
424
425    Combobox* cbobox = (Combobox*)WindowManager::getSingleton().getWindow("CameraCombos");
426    cbobox->resetList();
427
428    // find first non default camera and make it active
429    Ogre::String activeCameraName;
430    Ogre::SceneManager::CameraIterator cameras = mSceneMgr->getCameraIterator();
431
432    while (cameras.hasMoreElements())
433    {
434        Ogre::Camera* camera = cameras.getNext();
435        cbobox->addItem(new MyListItem( camera->getName().c_str(), 0 ));
436        // make the first non default camera the active camera
437        if (activeCameraName.empty() && (camera->getName() != DEFAULT_CAMERA_NAME))
438        {
439            activeCameraName = camera->getName();
440        }
441    }
442
443    // if no dae camera was found then use the default camera
444    if (activeCameraName.empty()) activeCameraName = DEFAULT_CAMERA_NAME;
445
446        // make camera item visible
447    Editbox* eb = static_cast<Editbox*>(WindowManager::getSingleton().getWindow(cbobox->getName()
448        + "__auto_editbox__"));
449    eb->setText(activeCameraName.c_str());
450
451    setActiveCamera(activeCameraName);
452}
453
454//--------------------------------------------------------------------------
455void ColladaDemo::setActiveCamera(const Ogre::String& cameraName)
456{
457    assert(mSceneMgr);
458    assert(mWindow);
459    // get the camera by name from the scenemanager and tell the first viewport of the
460    // current render window to use it.
461    try
462    {
463        mActiveCamera = mSceneMgr->getCamera(cameraName);
464        mWindow->getViewport(0)->setCamera(mActiveCamera);
465    }
466        catch (Ogre::Exception& e)
467        {
468        Ogre::LogManager::getSingleton().logMessage("ColladaDemo::setActiveCamera(\"" +
469            cameraName + ") failed: " + e.getFullDescription());
470        }
471}
472
473//--------------------------------------------------------------------------
474bool ColladaDemo::handleErrorBox(const CEGUI::EventArgs& e)
475{
476        CEGUI::WindowManager::getSingleton().getWindow((CEGUI::utf8*)"ErrorBox")->hide();
477    return true;
478}
479
480bool ColladaDemo::handleUpdateList(const CEGUI::EventArgs& e)
481{
482    updateDaeFileList();
483    return true;
484}
485
486//--------------------------------------------------------------------------
487void ColladaDemo::createFrameListener()
488{
489        mFrameListener= new UIHandler(this);
490        mRoot->addFrameListener(mFrameListener);
491}
492
493//--------------------------------------------------------------------------
494void ColladaDemo::clearScene()
495{
496        using namespace Ogre;
497
498        try
499    {
500                mWindow->removeAllViewports();
501                mSceneMgr->destroyAllCameras();
502
503        if( mSceneMgr )
504                {
505                        mSceneMgr->clearScene();
506                }
507
508                MeshManager::getSingleton().removeAll();
509                SkeletonManager::getSingleton().removeAll();
510        ColladaManager::getSingleton().removeAll();
511        MaterialManager::getSingleton().removeAll();
512
513                createDefaultCamera();
514        createViewports();
515        }
516        catch (Ogre::Exception& e)
517        {
518        Ogre::LogManager::getSingleton().logMessage("Clear Scene failed: " + e.getFullDescription());
519        }
520}
521
522//--------------------------------------------------------------------------
523void ColladaDemo::loadActiveDae()
524{
525    // que the loading so that Loading window can get a chance to be rendered
526    if (!mLoadQued)
527    {
528        showLoadingWindow(true);
529        mLoadQued = true;
530        mLastFrameNumber = mRoot->getCurrentFrameNumber();
531    }
532    // perform loading and view if load was qued and rendering has advanced to the next frame
533    else if (mRoot->getCurrentFrameNumber() > mLastFrameNumber)
534    {
535        // erase current scene
536        clearScene();
537        // view the selected document
538        viewColladaDocument(mActiveDaeFileName);
539        updateAvailableCameras();
540        showLoadingWindow(false);
541        mLoadQued = false;
542    }
543}
544
545//--------------------------------------------------------------------------
546void ColladaDemo::updateAutoReload(float time)
547{
548    if (mLoadQued)
549    {
550        loadActiveDae();
551    }
552
553    if (mAutoReload)
554    {
555        mElapsedTime += time;
556        if (mElapsedTime > 1.0)
557        {
558            mElapsedTime = 0.0;
559            if (!mActiveDaeFileName.empty())
560            {
561                if (checkActiveFileUpdated())
562                {
563                    loadActiveDae();
564                }
565            }
566        }
567    }
568}
569
570//--------------------------------------------------------------------------
571void ColladaDemo::showLoadingWindow(const bool show)
572{
573    if (!mLoadingWindow)
574    {
575        mLoadingWindow = CEGUI::WindowManager::getSingleton().getWindow("ColladaDemo/LoadWin");
576    }
577   
578    mLoadingWindow->setVisible(show);
579}
580
581//--------------------------------------------------------------------------
582#ifdef __cplusplus
583extern "C" {
584#endif
585
586#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
587INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
588#else
589int main(int argc, char *argv[])
590#endif
591{
592    // Create application object
593    ColladaDemo app;
594
595//    SET_TERM_HANDLER;
596   
597    try {
598        app.go();
599    } catch( Ogre::Exception& e ) {
600#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
601        MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
602#else
603        std::cerr << "An exception has occured: " <<
604            e.getFullDescription().c_str() << std::endl;
605#endif
606    }
607
608    return 0;
609}
610
611#ifdef __cplusplus
612}
613#endif
Note: See TracBrowser for help on using the repository browser.