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

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