source: GTP/trunk/App/Demos/Vis/KdTreeDemo/OGRE/src/TestKdTree.cpp @ 1187

Revision 1187, 16.0 KB checked in by szydlowski, 18 years ago (diff)

visualization in test app working, some issues to resolve

Line 
1#include "TestKdTree.h"
2
3#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
4#define WIN32_LEAN_AND_MEAN
5#include "windows.h"
6#endif
7
8#ifdef __cplusplus
9extern "C" {
10#endif
11
12#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
13        INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
14#else
15        int main(int argc, char *argv[])
16#endif
17        {
18                // Create application object
19                KdTreeApp app;
20
21                SET_TERM_HANDLER;
22
23                // init random number generator
24                // srand(time(0));
25
26                try {
27                        app.go();
28                } catch( Ogre::Exception& e ) {
29#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
30                        MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
31#else
32                        std::cerr << "An exception has occured: " <<
33                                e.getFullDescription().c_str() << std::endl;
34#endif
35                }
36
37                return 0;
38        }
39
40#ifdef __cplusplus
41}
42#endif
43
44#define ENT_GRID        0x01
45#define ENT_RND         0x02
46#define ENT_SPC         0x04
47#define ENT_MOV         0x08
48#define ENT_PLN         0x10
49
50void KdTreeApp::setupResources(void)
51{
52        String tmp;
53        ConfigFile cfDeath;
54        char *errptr;
55        int base = 10;
56
57        cfDeath.load("testKdTree.cfg");
58
59        mSelectedSceneManager = cfDeath.getSetting("scenemanager");
60        mSceneFiles = cfDeath.getSetting("scene");
61
62        tmp = cfDeath.getSetting("shadows");
63        StringUtil::toLowerCase(tmp);
64        if (tmp == "on")
65                mShadowsEnabled = true;
66        else
67                mShadowsEnabled = false;
68
69
70        tmp = cfDeath.getSetting("planedim");
71        mPlaneDim = static_cast<Real>(strtod(tmp.c_str(), &errptr));
72
73        tmp = cfDeath.getSetting("randomcount");
74        mRandomCount = static_cast<int>(strtol(tmp.c_str(), &errptr, base));
75
76        tmp = cfDeath.getSetting("selectentities");
77        mSelectEntities = static_cast<int>(strtol(tmp.c_str(), &errptr, base));
78
79        tmp = cfDeath.getSetting("count");
80        mModelCount = static_cast<int>(strtol(tmp.c_str(), &errptr, base));
81
82        tmp = cfDeath.getSetting("spacing");
83        mModelSpacing = static_cast<int>(strtol(tmp.c_str(), &errptr, base));
84       
85        tmp = cfDeath.getSetting("radius");
86        mRotationRadius = static_cast<Real>(strtod(tmp.c_str(), &errptr));
87       
88        tmp = cfDeath.getSetting("period");
89        mRotationPeriod = static_cast<Real>(strtod(tmp.c_str(), &errptr));
90
91        tmp = cfDeath.getSetting("movespeed");
92        mMoveSpeed = static_cast<Real>(strtod(tmp.c_str(), &errptr));
93
94        tmp = cfDeath.getSetting("rotatespeed");
95        mRotateSpeed = static_cast<Real>(strtod(tmp.c_str(), &errptr));
96
97        ExampleApplication::setupResources();
98}
99
100
101void KdTreeApp::createScene(void)
102{
103        Entity *deaths;
104        SceneNode *nodes;
105        std::string entName = "death";
106        std::string nodeName = "DeathNode";
107        int i, j, x, z;
108        Real planeHalf = mPlaneDim / 2;
109        Real planeThreeEights = mPlaneDim * 3 / 8;
110        Real planeSixth = mPlaneDim / 6;
111
112        // load scene from file
113        if (mSceneFiles != "")
114        {
115                // don't load the other stuff
116                loadScene(mSceneFiles);
117                //mCamera->setPosition(Vector3(830, 300, -540));
118                //mCamera->setOrientation(Quaternion(-0.3486, 0.0122, 0.9365, 0.0329));
119                // total view
120                //mCamera->setPosition(Vector3(688, 866, 944));
121                //mCamera->setOrientation(Quaternion(-0.979419, 0.201128, 0.0165594, 0.00340038));
122                mTopCam->setPosition(Vector3(1232, 3990, -1477));
123                // walkthrough view
124                mCamNode->setPosition(Vector3(1102.56, 181.845, -350.305));
125                //mCamNode->setOrientation(Quaternion(-0.977321, -0.117497, -0.174903, 0.0210273));
126
127                mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox", 5000, true);
128        }
129        else
130        {
131                mCamNode->setPosition(Vector3(1280,600,1666));
132                mCamNode->setOrientation(Quaternion(0.936893, -0.124586, 0.323813, 0.04306));
133                //mCamera->lookAt(Vector3(-20,30,10));
134
135                SceneNode *anchor = mSceneMgr->getRootSceneNode()->createChildSceneNode("AnchorNode");
136                //SceneNode *grndan = anchor->createChildSceneNode("GroundAnchor");
137                SceneNode *grndan = mSceneMgr->getRootSceneNode();
138
139                if (mSelectEntities & ENT_GRID)
140                {
141                        for (j = 0, z =  -(mModelCount / 2 * mModelSpacing); j < mModelCount; j++, z += mModelSpacing)
142                        {
143                                for (i = 0, x = -(mModelCount / 2 * mModelSpacing); i < mModelCount; i++, x += mModelSpacing)
144                                {
145                                        deaths = mSceneMgr->createEntity(cat(entName, i, j).c_str(),"robot.mesh");
146                                        if (mShadowsEnabled)
147                                                deaths->setCastShadows(true);
148                                        nodes = /*mSceneMgr->getRootSceneNode()*/anchor->createChildSceneNode(cat(nodeName, i, j).c_str(), Vector3(x, 0 , z));
149                                        nodes->attachObject(deaths);
150                                }
151                        }
152                }
153
154                if (mSelectEntities & ENT_RND)
155                {
156                        entName = "randomdeath";
157                        nodeName = "RandomDeathNode";
158                        for (i = 0; i < mRandomCount; i++)
159                        {
160                                Vector3 pos(
161                                        Math::RangeRandom(-planeHalf,-planeSixth),
162                                        0,
163                                        Math::RangeRandom(-planeThreeEights, planeThreeEights));
164                                deaths = mSceneMgr->createEntity(cat(entName,666,i),"robot.mesh");
165                                if (mShadowsEnabled)
166                                        deaths->setCastShadows(true);
167                                nodes = /*mSceneMgr->getRootSceneNode()*/anchor->createChildSceneNode(cat(nodeName,666,i), pos,
168                                        Quaternion(Radian(Math::RangeRandom(-Math::PI, Math::PI)), Vector3::UNIT_Y));
169                                nodes->attachObject(deaths);
170                        }
171                }
172
173                if (mSelectEntities & ENT_SPC)
174                {
175                        entName = "randomspaceship";
176                        nodeName = "RandomSpaceshipNode";
177                        for (i = 0; i < mRandomCount; i++)
178                        {
179                                Vector3 pos(
180                                        //Math::RangeRandom(-planeHalf,-planeSixth),
181                                        Math::RangeRandom(planeSixth,planeHalf),
182                                        Math::RangeRandom(planeHalf * 0.1, planeHalf),
183                                        Math::RangeRandom(-planeThreeEights, planeThreeEights));
184                                deaths = mSceneMgr->createEntity(cat(entName,666,i),"razor.mesh");
185                                if (mShadowsEnabled)
186                                        deaths->setCastShadows(true);
187                                nodes = /*mSceneMgr->getRootSceneNode()*/anchor->createChildSceneNode(cat(nodeName,666,i), pos,
188                                        Quaternion(Radian(Math::RangeRandom(-Math::PI, Math::PI)), Vector3::UNIT_Y));
189                                nodes->attachObject(deaths);
190                        }
191                }
192
193                if (mSelectEntities & ENT_MOV)
194                {
195                        Entity *movingDeath = mSceneMgr->createEntity("movingDeath","robot.mesh");
196                        if (mShadowsEnabled)
197                                movingDeath->setCastShadows( true );
198
199                        SceneNode *deathPivotNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("deathPivotNode");
200                        mDeathNode = deathPivotNode->createChildSceneNode("movingNode", Vector3(0, 0, mRotationRadius)/*,
201                                Quaternion(Radian(Math::HALF_PI), Vector3::UNIT_Y)*/);
202                        mDeathNode->attachObject(movingDeath);
203
204                        Entity *ent_ball = mSceneMgr->createEntity("ball","sphere.mesh");
205                        SceneNode *node_pivot = mDeathNode->createChildSceneNode("pivotNode");
206                        SceneNode *node_ball = node_pivot->createChildSceneNode("orbitNode", Vector3(120, 40, 0));
207                        node_ball->attachObject(ent_ball);
208                        node_ball->scale(0.1, 0.1, 0.1);
209                       
210
211                        mFollowCam->setAutoTracking(true, mDeathNode);
212                }
213               
214                if (mSelectEntities & ENT_PLN)
215                {
216                        Plane ground(Vector3::UNIT_Y, 0);
217                        MeshManager::getSingleton().createPlane("ground", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
218                                ground, mPlaneDim * 4 / 3, mPlaneDim, 20, 20, true, 1, 20, 20, Vector3::UNIT_Z);
219                        Entity *ent_ground = mSceneMgr->createEntity("GroundEntity", "ground");
220                        ent_ground->setCastShadows(false);
221                        ent_ground->setMaterialName("Examples/RustySteel");//("Examples/Rockwall");
222                        SceneNode *node_ground = /*mSceneMgr->getRootSceneNode()*/grndan->createChildSceneNode("GroundNode", Vector3(0, 0, 0));
223                        node_ground->attachObject(ent_ground);
224
225                        //MeshManager::getSingleton().createPlane("ground2", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
226                        //      ground, mPlaneDim/2, mPlaneDim, 10, 20, true, 1, 10, 20, Vector3::UNIT_Z);
227                        //ent_ground = mSceneMgr->createEntity("GroundEntity2", "ground2");
228                        //ent_ground->setCastShadows(false);
229                        //ent_ground->setMaterialName("Examples/RustySteel");
230                        //node_ground = /*mSceneMgr->getRootSceneNode()*/grndan->createChildSceneNode("GroundNode2", Vector3(-mPlaneDim/4, 0, 0));
231                        //node_ground->attachObject(ent_ground);
232                }
233
234                // Lights
235                mSceneMgr->setAmbientLight(ColourValue(0.1,0.1,0.1));
236                Light *light = mSceneMgr->createLight("light");
237                if (mShadowsEnabled)
238                {
239                        mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE);
240                        light->setType(Light::LT_POINT);
241                        light->setPosition(Vector3(x, 300, z + 200));
242                }
243                else
244                {
245                        light->setType(Light::LT_DIRECTIONAL);
246                        light->setDirection(-1,-1,-1);
247                }
248                light->setDiffuseColour(ColourValue());
249                light->setSpecularColour(ColourValue(1, 1, 0.2));
250
251                // Skybox
252                mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", mPlaneDim * 2);
253        }
254
255        /* Some math tests
256        Plane planeX(Vector3::UNIT_X, Vector3(10,10,10));
257        Plane planeY(Vector3::UNIT_Y, Vector3(10,10,10));
258        Plane planeZ(Vector3::UNIT_Z, Vector3(10,10,10));
259        Vector3 vect(20,20,20);
260        Vector3 interX = planeX.projectVector(vect);
261        Vector3 interY = planeY.projectVector(vect);
262        Vector3 interZ = planeZ.projectVector(vect);
263        std::stringstream ssX, ssY, ssZ;
264        ssX << "The intersection of " << planeX << " and " << vect << " is at: " << interX;
265        ssY << "The intersection of " << planeY << " and " << vect << " is at: " << interY;
266        ssZ << "The intersection of " << planeZ << " and " << vect << " is at: " << interZ;
267        LogManager::getSingleton().logMessage(ssX.str());
268        LogManager::getSingleton().logMessage(ssY.str());
269        LogManager::getSingleton().logMessage(ssZ.str());
270        */
271}
272
273void KdTreeApp::createFrameListener(void)
274{
275        mFrameListener = new KdTreeAppListener(mWindow, mSceneMgr, mRotateSpeed, mMoveSpeed, mRotationPeriod);
276        mFrameListener->showDebugOverlay( true );
277        mRoot->addFrameListener(mFrameListener);
278        mWindow->addListener(new KdTreeAppRenderTargetListener(mSceneMgr));
279}
280
281void KdTreeApp::chooseSceneManager(void)
282{
283        // Get the SceneManager
284        mSceneMgr = mRoot->createSceneManager(mSelectedSceneManager,"MySceneManager");
285}
286
287void KdTreeApp::createCamera(void)
288{
289    // Create the camera
290    mCamera = mSceneMgr->createCamera("PlayerCam");
291        mCamera->setNearClipDistance(1);
292
293        mCamNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("PlayerCamNode", Vector3(0,0,0));
294        mCamNode->attachObject(mCamera);
295       
296
297    // Position it at 500 in Z direction
298    //mCamera->setPosition(Vector3(0,50,500));
299        //mCamera->setPosition(Vector3(500,256,666));
300        //mCamera->setPosition(Vector3(1280,600,1666));
301    // Look back along -Z
302    //mCamera->lookAt(Vector3(0,50,-300));
303        //mCamera->lookAt(Vector3(-20,30,10));
304
305        //mFollowCam = mSceneMgr->createCamera("FollowCam");
306        //mFollowCam->setPosition(Vector3(800,150,800));
307        //mFollowCam->setNearClipDistance(5);
308        //mFollowCam->setFOVy(Angle(15));
309
310        mTopCam = mSceneMgr->createCamera("TopCam");
311        mTopCam->setPosition(Vector3(0,mPlaneDim * 1.25,0));
312        mTopCam->setDirection(0,0,-1);
313        mTopCam->pitch(Radian(-Math::HALF_PI));
314        mTopCam->setCullingFrustum(mCamera);
315        mTopCam->setNearClipDistance(1);
316
317        // infinite far plane?
318        if (mRoot->getRenderSystem()->getCapabilities()->hasCapability(RSC_INFINITE_FAR_PLANE))
319        {
320                mTopCam->setFarClipDistance(0);
321                mCamera->setFarClipDistance(0);
322        }
323        else
324        {
325                mTopCam->setFarClipDistance(20000);
326                mCamera->setFarClipDistance(20000);
327        }       
328}
329
330void KdTreeApp::createViewports(void)
331{
332    // Create one viewport, entire window
333    Viewport* vp = mWindow->addViewport(mCamera);
334    vp->setBackgroundColour(ColourValue(0,0,100));
335
336    // Alter the camera aspect ratio to match the viewport
337    mCamera->setAspectRatio(
338        Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
339/*
340        Viewport* fvp = mWindow->addViewport(mFollowCam,2,0.75,0.75,0.25,0.25);
341        fvp->setBackgroundColour(ColourValue(100,0,0));
342        fvp->setOverlaysEnabled( false );
343
344        mFollowCam->setAspectRatio(
345                Real(fvp->getActualWidth()) / Real(fvp->getActualHeight()));
346*/
347}
348
349bool KdTreeApp::configure(void)
350{
351    // Show the configuration dialog and initialise the system
352    // You can skip this and use root.restoreConfig() to load configuration
353    // settings if you were sure there are valid ones saved in ogre.cfg
354#ifdef KDTREE_FASTSTART
355    if(mRoot->restoreConfig())
356#else
357        if(mRoot->showConfigDialog())
358#endif
359    {
360        // If returned true, user clicked OK so initialise
361        // Here we choose to let the system create a default rendering window by passing 'true'
362        mWindow = mRoot->initialise(true);
363        return true;
364    }
365    else
366    {
367        return false;
368    }
369}
370
371
372//-----------------------------------------------------------------------
373// splits strings containing multiple file names
374static int splitFilenames(const std::string str, std::vector<std::string> &filenames)
375{
376        int pos = 0;
377
378        while(1)
379        {
380                int npos = (int)str.find(';', pos);
381
382                if (npos < 0 || npos - pos < 1)
383                        break;
384                filenames.push_back(std::string(str, pos, npos - pos));
385                pos = npos + 1;
386        }
387
388        filenames.push_back(std::string(str, pos, str.size() - pos));
389        return (int)filenames.size();
390}
391
392bool KdTreeApp::loadScene(const String &filename)
393{
394        // use leaf nodes of the original spatial hierarchy as occludees
395        std::vector<std::string> filenames;
396        int files = splitFilenames(filename, filenames);
397
398        std::stringstream d;
399        d << "number of input files: " << files << "\n";
400        LogManager::getSingleton().logMessage(d.str());
401
402        bool result = false;
403        std::vector<std::string>::const_iterator fit, fit_end = filenames.end();
404        int i = 0;
405        // root for different files
406        for (fit = filenames.begin(); fit != fit_end; ++ fit, ++ i)
407        {
408                const std::string fn = *fit;
409
410                if (strstr(fn.c_str(), ".iv") || strstr(fn.c_str(), ".wrl"))
411                {
412                        // hack: set postion manually for vienna
413                        //mCamNode->setPosition(Vector3(830, 300, -540));
414                        //mCamNode->setOrientation(Quaternion(-0.3486, 0.0122, 0.9365, 0.0329));
415
416                        // load iv files
417                        loadSceneIV(fn, mSceneMgr->getRootSceneNode(), i);                     
418                }
419
420                result = true;
421        }
422
423
424        /*
425        if (result)
426        {
427        int intersectables, faces;
428
429        std::stringstream d;
430        d << filename << " parsed successfully.\n"
431        << "#NUM_OBJECTS (Total numner of objects)\n" << intersectables << "\n"
432        << "#NUM_FACES (Total numner of faces)\n" << faces << "\n";
433        }
434        */
435
436        return result;
437}
438
439//-----------------------------------------------------------------------
440bool KdTreeApp::loadSceneIV(const String &filename, SceneNode *root, const int index)
441{
442        IVReader * mIVReader = new IVReader();
443
444        if (1)
445        {
446                String logFilename = "IVLog" + Ogre::StringConverter().toString(index) + ".log";
447
448                Log *log = LogManager::getSingleton().createLog(logFilename);
449                mIVReader->setLog(log);
450        }
451
452        //viennaNode->translate(Vector3(-300, -300, 0));
453
454        if (mIVReader->loadFile(filename.c_str()))
455        {
456                SceneNode *node = root->createChildSceneNode("IVSceneNode" + index);
457
458                mIVReader->buildTree(mSceneMgr, node);
459
460                mIVReader->collapse();
461                OGRE_DELETE(mIVReader);
462
463                return true;
464        }
465
466        return false;
467}
468
469/**********************************************************************/
470/*           VisualizationRenderTargetListener implementation         */
471/**********************************************************************/
472
473
474//-----------------------------------------------------------------------
475KdTreeAppRenderTargetListener::KdTreeAppRenderTargetListener(SceneManager *sceneMgr)
476:RenderTargetListener(), mSceneMgr(sceneMgr)
477{
478}
479//-----------------------------------------------------------------------
480void KdTreeAppRenderTargetListener::preViewportUpdate(const RenderTargetViewportEvent &evt)
481{
482        // visualization viewport
483        const bool showViz = evt.source->getZOrder() == VIZ_VIEWPORT_Z_ORDER;
484        const bool nShowViz = !showViz;
485
486        mSavedShadowTechnique = mSceneMgr->getShadowTechnique();
487        mSavedAmbientLight = mSceneMgr->getAmbientLight();
488
489        // -- ambient light must be full for visualization, shadows disabled
490        if (showViz)
491        {
492                mSceneMgr->setAmbientLight(ColourValue(1, 1, 1));
493                mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);
494        }
495
496        mSceneMgr->setOption("PrepareVisualization", &showViz);
497        mSceneMgr->setOption("SkyBoxEnabled", &nShowViz);
498        //mSceneMgr->setOption("SkyPlaneEnabled", &showViz);
499
500        RenderTargetListener::preViewportUpdate(evt);
501}
502//-----------------------------------------------------------------------
503void KdTreeAppRenderTargetListener::postRenderTargetUpdate(const RenderTargetEvent &evt)
504{
505        // reset values
506        mSceneMgr->setShadowTechnique(mSavedShadowTechnique);
507        mSceneMgr->setAmbientLight(mSavedAmbientLight);
508
509        RenderTargetListener::postRenderTargetUpdate(evt);
510}
Note: See TracBrowser for help on using the repository browser.