source: GTP/trunk/App/Demos/Vis/HillyTerrain/OGRE/TestCullingTerrainApplication.cpp @ 2121

Revision 2121, 24.5 KB checked in by mattausch, 17 years ago (diff)
Line 
1#include <OgreNoMemoryMacros.h>
2#include <CEGUI/CEGUI.h>
3#include <../CEGUIRenderer/include/OgreCEGUIRenderer.h>
4#include <../CEGUIRenderer/include/OgreCEGUIResourceProvider.h>
5#include <../CEGUIRenderer/include/OgreCEGUITexture.h>
6#include <OgreMemoryMacros.h>
7#include <OgreIteratorWrappers.h>
8#include <Ogre.h>
9#include "TestCullingTerrainApplication.h"
10#include "TerrainFrameListener.h"
11
12#if COLLADA
13#include "OgreColladaPrerequisites.h"
14#include "OgreColladaDocument.h"
15#include "OgreColladaScene.h"
16#endif
17
18#include "IVReader.h"
19
20#define WIN32_LEAN_AND_MEAN
21#include <windows.h>
22
23const static bool USE_STATIC_GEOMETRY = false;
24bool TestCullingTerrainApplication::msShowHillyTerrain = false;
25
26
27//using namespace GtpVisibility;
28
29/*************************************************************/
30/*                EntityState implementation                 */
31/*************************************************************/
32
33
34Vector3 EntityState::msMinPos = Vector3::ZERO;
35Vector3 EntityState::msMaxPos = Vector3::ZERO;
36
37EntityState::EntityState(Entity *ent, State entityState, Real speed):
38mEntity(ent), mState(entityState), mAnimationSpeed(speed)
39{
40        switch(entityState)
41        {
42        case MOVING:
43                mAnimationState = mEntity->getAnimationState("Walk");
44                break;
45        case WAITING:
46                mAnimationState = mEntity->getAnimationState("Idle");
47                break;
48        case STOP:
49                mAnimationState = NULL;
50                break;
51        default:
52                break;
53        }
54        // enable animation state
55        if (mAnimationState)
56        {
57                mAnimationState->setLoop(true);
58                mAnimationState->setEnabled(true);
59        }
60
61        mTimeElapsed = Math::RangeRandom(1, 5);
62}
63//-----------------------------------------------------------------------
64EntityState::~EntityState()
65{
66        mAnimationState = NULL;
67        mEntity = NULL;
68}
69//-----------------------------------------------------------------------
70Entity *EntityState::GetEntity()
71{
72        return mEntity;
73}
74//-----------------------------------------------------------------------
75EntityState::State EntityState::GetState()
76{
77        return mState;
78}
79//-----------------------------------------------------------------------
80void EntityState::update(Real timeSinceLastFrame)
81{
82        mTimeElapsed -= timeSinceLastFrame * mAnimationSpeed;
83
84        if (!mEntity || !mAnimationState)
85                return;
86       
87        if (mState == MOVING) // toggle between moving (longer) and waiting (short)
88        {
89                SceneNode *parent = mEntity->getParentSceneNode();
90               
91                if (!parent)
92                        return;
93
94                if (mTimeElapsed <= 0) // toggle animation state
95                {
96                        if (mAnimationState->getAnimationName() == "Idle")
97                        {
98                                SetAnimationState("Walk", true);
99                               
100                                mTimeElapsed = walk_duration; // walk for mTimeElapsed units
101
102                                // choose random rotation
103                                Radian rnd = Radian(Math::UnitRandom() * Math::PI * rotate_factor);
104
105                                //mEntity->getParentSceneNode()->rotate();
106                                parent->yaw(rnd);                                               
107                        }
108                        else
109                        {
110                                SetAnimationState("Idle", true);
111                                mTimeElapsed = wait_duration; // wait for mTimeElapsed seconds
112                        }
113                }
114
115                if (mAnimationState->getAnimationName() == "Walk") // move forward
116                {
117                        // store old position, just in case we get out of bounds
118                        Vector3 oldPos = parent->getPosition();
119                        parent->translate(parent->getLocalAxes(), Vector3(move_factor * mAnimationSpeed, 0, 0));
120
121                        // HACK: if out of bounds => reset to old position and set animationstate to idle
122                        if (OutOfBounds(parent))
123                        {
124                                parent->setPosition(oldPos);
125                                SetAnimationState("Idle", true);
126                               
127                                mTimeElapsed = wait_duration;
128                        }
129                }
130        }
131               
132        // add time to drive animation
133        mAnimationState->addTime(timeSinceLastFrame * mAnimationSpeed);
134}
135//-----------------------------------------------------------------------
136void EntityState::SetAnimationState(String stateStr, bool loop)
137{
138        if (!mEntity)
139                return;
140
141        mAnimationState = mEntity->getAnimationState(stateStr);
142        mAnimationState->setLoop(loop);
143        mAnimationState->setEnabled(true);
144}
145//-----------------------------------------------------------------------
146bool EntityState::OutOfBounds(SceneNode *node)
147{
148        Vector3 pos = node->getPosition();
149
150        if ((pos > msMinPos) && (pos < msMaxPos))
151                return false;
152
153        return true;
154}
155
156
157
158/********************************************************************/
159/*            TestCullingTerrainApplication implementation          */
160/********************************************************************/
161
162
163TestCullingTerrainApplication::TestCullingTerrainApplication():
164mTerrainContentGenerator(NULL),
165mRayQueryExecutor(NULL),
166mIVReader(NULL),
167mFilename("terrain"),
168mViewCellsFilename(""),
169mAlgorithm(GtpVisibility::VisibilityEnvironment::COHERENT_HIERARCHICAL_CULLING)
170{
171}
172//-------------------------------------------------------------------------
173void TestCullingTerrainApplication::loadConfig(const String& filename)
174{
175        // TODO matt
176        // Set up the options
177        ConfigFile config;
178        String val;
179
180        config.load(filename);
181
182        std::stringstream d; d << "reading the config file from: " << filename;
183        LogManager::getSingleton().logMessage(d.str());
184
185        val = config.getSetting("Scene");
186
187    if (!val.empty())
188        {
189                 mFilename = val.c_str();
190                 d << "\nloading scene from file: " << mFilename;
191                 LogManager::getSingleton().logMessage(d.str());
192        }
193
194/*      val = config.getSetting("ViewCells");
195
196        if (!val.empty())
197        {
198                 mViewCellsFilename = val.c_str();
199                 std::stringstream d; d << "view cells file name: " << mViewCellsFilename;
200                 LogManager::getSingleton().logMessage(d.str());
201        }
202
203        mInitialPosition = Vector3::UNIT_SCALE;
204
205        val = config.getSetting("ViewX");
206
207        if (!val.empty())
208                mInitialPosition.x = atof( val.c_str() );
209
210        val = config.getSetting("ViewY");
211       
212        if (!val.empty())
213                mInitialPosition.y = atof(val.c_str());
214
215        val = config.getSetting("ViewZ");
216       
217        if (!val.empty())
218                mInitialPosition.z = atof( val.c_str());
219*/
220
221/*      val = config.getSetting("OnlineCullingAlgorithm");
222
223        if (!val.empty())
224        {
225                 if (val == "CHC")
226                 {
227                         mAlgorithm =
228                                 GtpVisibility::VisibilityEnvironment::COHERENT_HIERARCHICAL_CULLING;
229                 }
230                 else if (val == "SWC")
231                 {
232                         mAlgorithm =
233                                 GtpVisibility::VisibilityEnvironment::STOP_AND_WAIT_CULLING;
234                 }
235                 else if (val == "VFC")
236                 {
237                         mAlgorithm =
238                                 GtpVisibility::VisibilityEnvironment::FRUSTUM_CULLING;
239                 }
240                 else // default rendering
241                 {
242                         mAlgorithm =
243                                 GtpVisibility::VisibilityEnvironment::NUM_CULLING_MANAGERS;
244                 }
245        }
246
247        /////////////
248        // setup scene
249
250        // set camera position accordingly
251        mCamNode->setPosition(mInitialPosition);
252        */
253}
254//-----------------------------------------------------------------------
255TestCullingTerrainApplication::~TestCullingTerrainApplication()
256{
257        OGRE_DELETE(mTerrainContentGenerator);
258        OGRE_DELETE(mRayQueryExecutor);
259        OGRE_DELETE(mIVReader);
260
261        deleteEntityStates();   
262}
263//-----------------------------------------------------------------------
264void TestCullingTerrainApplication::deleteEntityStates()
265{
266        for (int i = 0; i < (int)mEntityStates.size(); ++i)
267        {
268                OGRE_DELETE(mEntityStates[i]);
269        }
270
271        mEntityStates.clear();
272}
273//-----------------------------------------------------------------------
274void TestCullingTerrainApplication::createCamera()
275{
276        // create the camera
277        mCamera = mSceneMgr->createCamera("PlayerCam");
278       
279        /** set a nice viewpoint
280        *       we use a camera node here and apply all transformations on it instead
281        *       of applying all transformations directly to the camera
282        *       because then the camera is displayed correctly in the visualization
283        */
284        //Vector3 viewPoint(707, 5000, 528);
285        Vector3 viewPoint(830, 300, -540);
286        std::stringstream d; d << "here3: " << viewPoint;
287        Ogre::LogManager::getSingleton().logMessage(d.str());
288        mCamNode = mSceneMgr->getRootSceneNode()->
289                createChildSceneNode("CamNode1", viewPoint);
290       
291        mCamNode->setOrientation(Quaternion(-0.3486, 0.0122, 0.9365, 0.0329));
292        mCamNode->attachObject(mCamera);
293       
294        ///////////////////
295        //-- create visualization camera
296
297        mVizCamera = mSceneMgr->createCamera("VizCam");
298        mVizCamera->setPosition(mCamNode->getPosition());
299
300        mVizCamera->setNearClipDistance(1);
301        mCamera->setNearClipDistance(1);
302
303        // infinite far plane?
304        if (mRoot->getRenderSystem()->getCapabilities()->hasCapability(RSC_INFINITE_FAR_PLANE))
305        {
306                mVizCamera->setFarClipDistance(0);
307                mCamera->setFarClipDistance(0);
308        }
309        else
310        {
311                 mVizCamera->setFarClipDistance(20000);
312                 mCamera->setFarClipDistance(20000);
313        }       
314}
315
316//-----------------------------------------------------------------------
317bool TestCullingTerrainApplication::setup()
318{
319        bool carryOn = ExampleApplication::setup();
320
321        if (carryOn)
322                createRenderTargetListener();
323
324        return carryOn;
325}
326//-----------------------------------------------------------------------
327void TestCullingTerrainApplication::createRenderTargetListener()
328{
329        mWindow->addListener(new VisualizationRenderTargetListener(mSceneMgr));
330}
331//-----------------------------------------------------------------------
332bool TestCullingTerrainApplication::LoadSceneCollada(const String &filename,
333                                                                                                         SceneNode *root,
334                                                                                                         const int index)
335{
336#if COLLADA
337        // Collada
338        ColladaDocument *daeDoc = new ColladaDocument(mSceneMgr);
339
340        String daeName = filename;
341        //if (daeName.empty())
342        //      daeName = "City_1500.dae";
343
344        // default directory
345        //daeName.insert(0, "../../media/models/collada/City");
346        LogManager::getSingleton().logMessage("ColladaDocument - import started");
347
348        // full import
349        if (daeDoc->doImport(daeName))
350        {
351                LogManager::getSingleton().logMessage("yuppi");
352                /**
353                 * build up scene
354                 * if you only want a specific part of the scene graph, you must fetch a scene node
355                 * by its unique node name and give it as parameter
356                 * e.g.
357                 * ColladaSceneNode *box = mScene->getNode("Box2");
358                 * if (box != NULL) box->createOgreInstance(NULL);
359                 */
360                daeDoc->getScene()->createOgreInstance(NULL);
361
362                // everything is loaded, we do not need the collada document anymore
363                delete daeDoc;
364
365                return true;
366        }
367        else
368        {
369                LogManager::getSingleton().logMessage("ColladaDocument - import failed");
370                return false;
371        }
372#endif
373        return true;
374}
375//-----------------------------------------------------------------------
376bool TestCullingTerrainApplication::LoadSceneIV(const String &filename,
377                                                                                                SceneNode *root,
378                                                                                                const int index)
379{
380        mIVReader = new IVReader();
381
382        Timer *timer = PlatformManager::getSingleton().createTimer();
383        timer->reset();
384
385        if (1)
386        {
387                std::string logFilename = "IVLog" + Ogre::StringConverter().toString(index) + ".log";
388               
389                Log *log = LogManager::getSingleton().createLog(logFilename);
390                mIVReader->setLog(log);
391        }
392       
393        //viennaNode->translate(Vector3(-300, -300, 0));
394
395        if (mIVReader->loadFile(filename.c_str()))
396        {
397                SceneNode *node = root->createChildSceneNode("IVSceneNode" + index);
398
399                mIVReader->buildTree(mSceneMgr, node);
400               
401                mIVReader->collapse();
402                OGRE_DELETE(mIVReader);
403
404                std::stringstream d;
405                d << "loaded " << filename << " in " << timer->getMilliseconds() * 1e-3 << " secs";
406                LogManager::getSingleton().logMessage(d.str());
407               
408                PlatformManager::getSingleton().destroyTimer(timer);
409
410                //-- bake into static geometry
411                if (USE_STATIC_GEOMETRY)
412                {
413                        BakeSceneIntoStaticGeometry("staticVienna", "Vienna");
414                }
415       
416                return true;
417        }
418
419        return false;
420}
421//--------------------------------------------------------
422void TestCullingTerrainApplication::BakeSceneIntoStaticGeometry(const String &staticGeomName,
423                                                                                                                                const String &nodeName)
424{
425#if OGRE_103
426        // note: different static geom for roofs, roads, ..., becazse they have same material
427        StaticGeometry *staticGeom = mSceneMgr->createStaticGeometry(staticGeomName);
428
429        // note: looping over entities here. why does scene node not work?
430        SceneManager::EntityIterator it = mSceneMgr->getEntityIterator();
431        while (it.hasMoreElements())
432        {
433                Entity *ent = it.getNext();
434                ent->setVisible(false);
435                staticGeom->addEntity(ent, ent->getParentSceneNode()->getPosition());
436        }
437
438        staticGeom->setRegionDimensions(Vector3(100,100,100));
439        staticGeom->build();
440
441        // cleanup node
442        //wallsNode->detachAllObjects();
443       
444        //roofsNode->detachAllObjects();
445        //roadsNode->detachAllObjects();
446        //planeNode->detachAllObjects();
447       
448        //viennaNode->removeChild("Walls");
449        mSceneMgr->destroySceneNode(nodeName);
450#endif
451}
452//--------------------------------------------------------
453void TestCullingTerrainApplication::createScene()
454{
455        /////////
456        //-- load scene
457        loadConfig("terrainCulling.cfg");
458       
459        if (0 && !LoadScene(mFilename))
460                LogManager::getSingleton().logMessage("error loading scene");
461       
462       
463        /////////////////////////////////////
464
465        // Set ambient light
466        mAmbientLight = ColourValue(0.5, 0.5, 0.5);
467        mSceneMgr->setAmbientLight(mAmbientLight);
468       
469        //-- create light
470        mSunLight = mSceneMgr->createLight("SunLight");
471        mSunLight->setType(Light::LT_DIRECTIONAL);
472        //mSunLight->setType(Light::LT_SPOTLIGHT);
473        //mSunLight->setSpotlightRange(Degree(30), Degree(50));
474
475    mSunLight->setPosition(707, 2000, 500);
476        mSunLight->setCastShadows(true);
477
478        // set light angle not too small over the surface,
479        // otherwise shadows textures will be broken
480        Vector3 dir(0.5, 1, 0.5);
481        dir.normalise();
482        mSunLight->setDirection(dir);
483        //mSunLight->setDirection(Vector3::NEGATIVE_UNIT_Y);
484        mSunLight->setDiffuseColour(1, 1, 1);
485        mSunLight->setSpecularColour(1, 1, 1);
486
487        //-- Fog
488
489        // NB it's VERY important to set this before calling setWorldGeometry
490        // because the vertex program picked will be different
491        ColourValue fadeColour(0.93, 0.86, 0.76);
492        mWindow->getViewport(0)->setBackgroundColour(fadeColour);
493        //mSceneMgr->setFog(FOG_LINEAR, fadeColour, .001, 500, 1000);
494       
495        // Create a skybox
496        mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox", 50000, true);
497       
498        // terrain creation
499        if (1)//||msShowHillyTerrain)
500        {
501        std::string terrain_cfg("terrainCulling.cfg");
502                mSceneMgr->setWorldGeometry(terrain_cfg);
503
504                mSceneMgr->getOption("ShowTerrain", &msShowHillyTerrain);
505        }
506       
507        //////
508        //-- CEGUI setup
509        setupGui();
510
511        // Warning: In GL since we can't go higher than the window res
512        mSceneMgr->setShadowTextureSettings(1024, 2);
513        mSceneMgr->setShadowColour(ColourValue(0.5, 0.5, 0.5));
514
515        //////////////
516        //-- terrain content setup
517
518        // HACK: necessary to call once here for terrain initialisation
519        mSceneMgr->_renderScene(mCamera, mWindow->getViewport(0), true);
520
521        // ray query executor: needed to clamp to terrain
522        mRayQueryExecutor = new RayQueryExecutor(mSceneMgr);
523
524        mTerrainMinPos = EntityState::msMinPos = Vector3(0, 0, 0);
525        mTerrainMaxPos = EntityState::msMaxPos = Vector3(5000, 5000, 5000);
526
527        mTerrainContentGenerator = new TerrainContentGenerator(mSceneMgr);
528               
529        if (!msShowHillyTerrain)
530                return;
531
532        // if no objects in file, we generate new objects
533        if (!mTerrainContentGenerator->LoadObjects("objects.out"))
534        {
535                // the objects are generated randomly distributed over the terrain
536                if (1) generateScene(1500, 0); // create robots
537                if (0) generateScene(100, 1); // create trees
538                if (0) generateScene(100, 2); // create ninjas
539        }
540}
541//-----------------------------------------------------------------------
542void  TestCullingTerrainApplication::generateScene(int num, int objectType)
543{
544        const float val = TerrainFrameListener::msObjectScales[objectType];
545        Vector3 scale(val, val, val);
546        const float maxHeight = 75;
547       
548        // In order to provide much occlusion,
549        // height is restricted to maxHeight => no objects are created on peaks
550        mTerrainContentGenerator->SetMinPos(Vector3(mTerrainMinPos));
551        mTerrainContentGenerator->SetMaxPos(Vector3(mTerrainMaxPos.x, maxHeight, mTerrainMaxPos.z));
552       
553        mTerrainContentGenerator->SetScale(scale);
554        mTerrainContentGenerator->SetOffset(TerrainFrameListener::msObjectTerrainOffsets[objectType]);
555        mTerrainContentGenerator->GenerateScene(num, TerrainFrameListener::msObjectCaptions[objectType]);
556
557        if (objectType != 0) // from our objects, only robot has animation phases
558                return;
559
560        EntityList *entList = mTerrainContentGenerator->GetGeneratedEntities();
561
562        /////////////
563        //-- add animation state for new robots (located at the end of the list)
564       
565        for (int i = (int)entList->size() - num; i < (int)entList->size(); ++i)
566        {
567                mEntityStates.push_back(new EntityState((*entList)[i],
568                        EntityState::WAITING, Math::RangeRandom(0.5, 1.5)));
569        }
570
571        // release limitations on height => it is possible for the user to put single
572        // objects on peaks of the terrain (will be only few, not relevant for occlusion)
573        mTerrainContentGenerator->SetMaxPos(mTerrainMaxPos);
574}
575//-----------------------------------------------------------------------
576void TestCullingTerrainApplication::updateAnimations(Real timeSinceLastFrame)
577{
578        for (int i = 0; i < (int)mEntityStates.size(); ++i)
579        {
580                SceneNode *sn = mEntityStates[i]->GetEntity()->getParentSceneNode();
581
582                mEntityStates[i]->update(timeSinceLastFrame);
583
584                if (mEntityStates[i]->GetState() == EntityState::MOVING)
585                {
586                        Clamp2Terrain(sn, 0); //sn->setNodeVisible(false);
587                }
588        }
589}
590//-----------------------------------------------------------------------
591EntityStates  &TestCullingTerrainApplication::getEntityStates()
592{
593        return mEntityStates;
594}
595//-----------------------------------------------------------------------
596void TestCullingTerrainApplication::setupGui()
597{
598#if OGRE103
599         mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY,
600                 false, 3000, ST_EXTERIOR_CLOSE);
601#else
602          mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY,
603                 false, 3000, mSceneMgr);
604#endif
605     mGUISystem = new CEGUI::System(mGUIRenderer);
606
607         // Mouse
608     CEGUI::SchemeManager::getSingleton().loadScheme((CEGUI::utf8*)"TaharezLook.scheme");
609     CEGUI::MouseCursor::getSingleton().setImage("TaharezLook", "MouseArrow");
610         mGUISystem->setDefaultMouseCursor((CEGUI::utf8*)"TaharezLook",
611                                                                           (CEGUI::utf8*)"MouseArrow");
612
613         CEGUI::MouseCursor::getSingleton().hide();
614}
615//-----------------------------------------------------------------------
616void TestCullingTerrainApplication::createFrameListener()
617{
618        mTerrainFrameListener =
619                new TerrainFrameListener(mWindow,
620                                                                 mCamera,
621                                                                 mSceneMgr,
622                                                                 mGUIRenderer,
623                                                                 mTerrainContentGenerator,
624                                                                 mVizCamera,
625                                                                 mCamNode,
626                                                                 mSunLight,
627                                                                 this);
628       
629        mRoot->addFrameListener(mTerrainFrameListener);
630}
631//-----------------------------------------------------------------------
632void TestCullingTerrainApplication::chooseSceneManager()
633{
634#ifdef OGRE_103
635        if (msShowHillyTerrain)
636        {
637                // Terrain scene manager
638                mSceneMgr = mRoot->getSceneManager(ST_EXTERIOR_CLOSE);
639        }
640        else
641        {       // octree scene manager
642                mSceneMgr = mRoot->getSceneManager(ST_GENERIC);
643        }
644#else
645       
646        mSceneMgr = mRoot->createSceneManager("OcclusionCullingSceneManager");
647        //mSceneMgr = mRoot->createSceneManager("TerrainSceneManager");
648        //mSceneMgr = mRoot->createSceneManager("OctreeSceneManager");
649
650        //mSceneMgr = mRoot->createSceneManager("KdTreeSceneManager");
651       
652#endif
653}
654//-----------------------------------------------------------------------
655bool TestCullingTerrainApplication::Clamp2Terrain(SceneNode *node, int terrainOffs)
656{
657        // clamp scene node to terrain
658        Vector3 pos = node->getPosition();
659        Vector3 queryResult;
660
661        if (mRayQueryExecutor->executeRayQuery(&queryResult,
662                        Vector3(pos.x, MAX_HEIGHT, pos.z), Vector3::NEGATIVE_UNIT_Y))
663        {
664        node->setPosition(pos.x, queryResult.y + terrainOffs, pos.z);
665                return true;
666        }
667
668        return false;
669}
670
671//-----------------------------------------------------------------------
672bool TestCullingTerrainApplication::Clamp2FloorPlane(const float dist)
673{
674    // clamp to floor plane
675        RaySceneQuery *raySceneQuery = mSceneMgr->createRayQuery(
676                Ray(mCamNode->getPosition(), Vector3::NEGATIVE_UNIT_Y));
677
678        RaySceneQueryResult& qryResult = raySceneQuery->execute();
679   
680        RaySceneQueryResult::iterator rit = qryResult.begin();
681        bool success = false;
682       
683        float yVal = 0;
684        float minVal = 999999999999;
685
686        while (rit != qryResult.end() && rit->movable)
687        {
688                if (rit->movable->getName() != "PlayerCam")
689                {
690                        // place on the ground object
691                        yVal = rit->movable->getWorldBoundingBox().getCenter().y;
692                                if (yVal < minVal)
693                                        minVal = yVal;
694
695                        //std::stringstream d; d << "dist: " << dist << endl;
696                        //Ogre::LogManager()
697                        success = true;
698                }
699
700                ++ rit;
701        }
702   
703        // place on the ground object
704        if (success)
705                        mCamNode->setPosition(
706                                mCamNode->getPosition().x,
707                                minVal + dist,
708                                mCamNode->getPosition().z);
709
710        OGRE_DELETE(raySceneQuery);
711        return success;
712}
713
714//-----------------------------------------------------------------------
715// splits strings containing multiple file names
716static int SplitFilenames(const std::string str, std::vector<std::string> &filenames)
717{
718        int pos = 0;
719
720        while(1)
721        {
722                int npos = (int)str.find(';', pos);
723               
724                if (npos < 0 || npos - pos < 1)
725                        break;
726                filenames.push_back(std::string(str, pos, npos - pos));
727                pos = npos + 1;
728        }
729       
730        filenames.push_back(std::string(str, pos, str.size() - pos));
731        return (int)filenames.size();
732}
733//-----------------------------------------------------------------------
734bool TestCullingTerrainApplication::LoadScene(const String &filename)
735{
736        using namespace std;
737        // use leaf nodes of the original spatial hierarchy as occludees
738        vector<string> filenames;
739        int files = SplitFilenames(filename, filenames);
740       
741        std::stringstream d;
742        d << "number of input files: " << files << "\n";
743        LogManager::getSingleton().logMessage(d.str());
744
745        bool result = false;
746        vector<string>::const_iterator fit, fit_end = filenames.end();
747        int i = 0;
748
749        for (fit = filenames.begin(); fit != fit_end; ++ fit, ++ i)
750        {
751                const string fn = *fit;
752
753                if (strstr(fn.c_str(), ".iv") || strstr(fn.c_str(), ".wrl"))
754                {
755                        // load iv files
756                        if (!LoadSceneIV(fn, mSceneMgr->getRootSceneNode(), i))
757                        {
758                                // terrain hack
759                                //msShowHillyTerrain = true;
760                                LogManager::getSingleton().logMessage("error loading scene => load terrain");
761                        }
762                }
763                else if (strstr(filename.c_str(), ".dae"))
764                {
765                        // load collada files
766                        LoadSceneCollada(fn, mSceneMgr->getRootSceneNode(), i);         
767                }
768                else //if (filename == "terrain")
769                {
770                        // terrain hack
771                        msShowHillyTerrain = true;
772                        LogManager::getSingleton().logMessage("loading terrain");
773                }
774       
775                result = true;
776        }
777       
778        return result;
779}
780//-----------------------------------------------------------------------
781bool TestCullingTerrainApplication::LoadViewCells(const String &filename)
782{
783        // if not already loaded,
784        // the scene manager will load the view cells
785        return mSceneMgr->setOption("UseViewCells", filename.c_str());
786}
787
788
789/**********************************************************************/
790/*           VisualizationRenderTargetListener implementation         */
791/**********************************************************************/
792
793
794//-----------------------------------------------------------------------
795VisualizationRenderTargetListener::VisualizationRenderTargetListener(SceneManager *sceneMgr)
796:RenderTargetListener(), mSceneMgr(sceneMgr)
797{
798}
799//-----------------------------------------------------------------------
800void VisualizationRenderTargetListener::preViewportUpdate(const RenderTargetViewportEvent &evt)
801{
802        // visualization viewport
803        const bool showViz = evt.source->getZOrder() == VIZ_VIEWPORT_Z_ORDER;
804        const bool nShowViz = !showViz;
805
806        mSavedShadowTechnique = mSceneMgr->getShadowTechnique();
807        mSavedAmbientLight = mSceneMgr->getAmbientLight();
808
809        // -- ambient light must be full for visualization, shadows disabled
810    if (showViz)
811        {
812                mSceneMgr->setAmbientLight(ColourValue(1, 1, 1));
813                mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);
814        }
815       
816    mSceneMgr->setOption("PrepareVisualization", &showViz);
817        mSceneMgr->setOption("SkyBoxEnabled", &nShowViz);
818       
819        RenderTargetListener::preViewportUpdate(evt);
820}
821//-----------------------------------------------------------------------
822void VisualizationRenderTargetListener::postRenderTargetUpdate(const RenderTargetEvent &evt)
823{
824        // reset values
825        mSceneMgr->setShadowTechnique(mSavedShadowTechnique);
826        mSceneMgr->setAmbientLight(mSavedAmbientLight);
827       
828        RenderTargetListener::postRenderTargetUpdate(evt);
829}
830//-----------------------------------------------------------------------
831INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
832{
833    // Create application object
834    TestCullingTerrainApplication app;
835
836        try
837        {
838        app.go();
839    }
840        catch( Ogre::Exception& e )
841        {
842        MessageBox( NULL, e.getFullDescription().c_str(),
843                        "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
844    }   
845
846    return 0;
847}
Note: See TracBrowser for help on using the repository browser.