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

Revision 1200, 17.1 KB checked in by szydlowski, 18 years ago (diff)

demo record and playback working

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        createMaterials();
104
105        Entity *deaths;
106        SceneNode *nodes;
107        std::string entName = "death";
108        std::string nodeName = "DeathNode";
109        int i, j, x, z;
110        Real planeHalf = mPlaneDim / 2;
111        Real planeThreeEights = mPlaneDim * 3 / 8;
112        Real planeSixth = mPlaneDim / 6;
113
114        // load scene from file
115        if (mSceneFiles != "")
116        {
117                // don't load the other stuff
118                loadScene(mSceneFiles);
119                //mCamera->setPosition(Vector3(830, 300, -540));
120                //mCamera->setOrientation(Quaternion(-0.3486, 0.0122, 0.9365, 0.0329));
121                // total view
122                //mCamera->setPosition(Vector3(688, 866, 944));
123                //mCamera->setOrientation(Quaternion(-0.979419, 0.201128, 0.0165594, 0.00340038));
124                mTopCam->setPosition(Vector3(1232, 3990, -1477));
125                // walkthrough view
126                mCamNode->setPosition(Vector3(1102.56, 181.845, -350.305));
127                //mCamNode->setOrientation(Quaternion(-0.977321, -0.117497, -0.174903, 0.0210273));
128
129                mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox", 5000, true);
130        }
131        else
132        {
133                mCamNode->setPosition(Vector3(1280,600,1666));
134                mCamNode->setOrientation(Quaternion(0.936893, -0.124586, 0.323813, 0.04306));
135                //mCamera->lookAt(Vector3(-20,30,10));
136
137                SceneNode *anchor = mSceneMgr->getRootSceneNode()->createChildSceneNode("AnchorNode");
138                //SceneNode *grndan = anchor->createChildSceneNode("GroundAnchor");
139                SceneNode *grndan = mSceneMgr->getRootSceneNode();
140
141                if (mSelectEntities & ENT_GRID)
142                {
143                        for (j = 0, z =  -(mModelCount / 2 * mModelSpacing); j < mModelCount; j++, z += mModelSpacing)
144                        {
145                                for (i = 0, x = -(mModelCount / 2 * mModelSpacing); i < mModelCount; i++, x += mModelSpacing)
146                                {
147                                        deaths = mSceneMgr->createEntity(cat(entName, i, j).c_str(),"robot.mesh");
148                                        if (mShadowsEnabled)
149                                                deaths->setCastShadows(true);
150                                        nodes = /*mSceneMgr->getRootSceneNode()*/anchor->createChildSceneNode(cat(nodeName, i, j).c_str(), Vector3(x, 0 , z));
151                                        nodes->attachObject(deaths);
152                                }
153                        }
154                }
155
156                if (mSelectEntities & ENT_RND)
157                {
158                        entName = "randomdeath";
159                        nodeName = "RandomDeathNode";
160                        for (i = 0; i < mRandomCount; i++)
161                        {
162                                Vector3 pos(
163                                        Math::RangeRandom(-planeHalf,-planeSixth),
164                                        0,
165                                        Math::RangeRandom(-planeThreeEights, planeThreeEights));
166                                deaths = mSceneMgr->createEntity(cat(entName,666,i),"robot.mesh");
167                                if (mShadowsEnabled)
168                                        deaths->setCastShadows(true);
169                                nodes = /*mSceneMgr->getRootSceneNode()*/anchor->createChildSceneNode(cat(nodeName,666,i), pos,
170                                        Quaternion(Radian(Math::RangeRandom(-Math::PI, Math::PI)), Vector3::UNIT_Y));
171                                nodes->attachObject(deaths);
172                        }
173                }
174
175                if (mSelectEntities & ENT_SPC)
176                {
177                        entName = "randomspaceship";
178                        nodeName = "RandomSpaceshipNode";
179                        for (i = 0; i < mRandomCount; i++)
180                        {
181                                Vector3 pos(
182                                        //Math::RangeRandom(-planeHalf,-planeSixth),
183                                        Math::RangeRandom(planeSixth,planeHalf),
184                                        Math::RangeRandom(planeHalf * 0.1, planeHalf),
185                                        Math::RangeRandom(-planeThreeEights, planeThreeEights));
186                                deaths = mSceneMgr->createEntity(cat(entName,666,i),"razor.mesh");
187                                if (mShadowsEnabled)
188                                        deaths->setCastShadows(true);
189                                nodes = /*mSceneMgr->getRootSceneNode()*/anchor->createChildSceneNode(cat(nodeName,666,i), pos,
190                                        Quaternion(Radian(Math::RangeRandom(-Math::PI, Math::PI)), Vector3::UNIT_Y));
191                                nodes->attachObject(deaths);
192                        }
193                }
194
195                if (mSelectEntities & ENT_MOV)
196                {
197                        Entity *movingDeath = mSceneMgr->createEntity("movingDeath","robot.mesh");
198                        if (mShadowsEnabled)
199                                movingDeath->setCastShadows( true );
200
201                        SceneNode *deathPivotNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("deathPivotNode");
202                        mDeathNode = deathPivotNode->createChildSceneNode("movingNode", Vector3(0, 0, mRotationRadius)/*,
203                                Quaternion(Radian(Math::HALF_PI), Vector3::UNIT_Y)*/);
204                        mDeathNode->attachObject(movingDeath);
205
206                        Entity *ent_ball = mSceneMgr->createEntity("ball","sphere.mesh");
207                        SceneNode *node_pivot = mDeathNode->createChildSceneNode("pivotNode");
208                        SceneNode *node_ball = node_pivot->createChildSceneNode("orbitNode", Vector3(120, 40, 0));
209                        node_ball->attachObject(ent_ball);
210                        node_ball->scale(0.1, 0.1, 0.1);
211                       
212
213                        mFollowCam->setAutoTracking(true, mDeathNode);
214                }
215               
216                if (mSelectEntities & ENT_PLN)
217                {
218                        Plane ground(Vector3::UNIT_Y, 0);
219                        MeshManager::getSingleton().createPlane("ground", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
220                                ground, mPlaneDim * 4 / 3, mPlaneDim, 20, 20, true, 1, 20, 20, Vector3::UNIT_Z);
221                        Entity *ent_ground = mSceneMgr->createEntity("GroundEntity", "ground");
222                        ent_ground->setCastShadows(false);
223                        ent_ground->setMaterialName("Examples/RustySteel");//("Examples/Rockwall");
224                        SceneNode *node_ground = /*mSceneMgr->getRootSceneNode()*/grndan->createChildSceneNode("GroundNode", Vector3(0, 0, 0));
225                        node_ground->attachObject(ent_ground);
226
227                        //MeshManager::getSingleton().createPlane("ground2", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
228                        //      ground, mPlaneDim/2, mPlaneDim, 10, 20, true, 1, 10, 20, Vector3::UNIT_Z);
229                        //ent_ground = mSceneMgr->createEntity("GroundEntity2", "ground2");
230                        //ent_ground->setCastShadows(false);
231                        //ent_ground->setMaterialName("Examples/RustySteel");
232                        //node_ground = /*mSceneMgr->getRootSceneNode()*/grndan->createChildSceneNode("GroundNode2", Vector3(-mPlaneDim/4, 0, 0));
233                        //node_ground->attachObject(ent_ground);
234                }
235
236                // Lights
237                mSceneMgr->setAmbientLight(ColourValue(0.1,0.1,0.1));
238                Light *light = mSceneMgr->createLight("light");
239                if (mShadowsEnabled)
240                {
241                        mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE);
242                        light->setType(Light::LT_POINT);
243                        light->setPosition(Vector3(x, 300, z + 200));
244                }
245                else
246                {
247                        light->setType(Light::LT_DIRECTIONAL);
248                        light->setDirection(-1,-1,-1);
249                }
250                light->setDiffuseColour(ColourValue::White);
251                light->setSpecularColour(ColourValue(1, 1, 0.2));
252
253                // Skybox
254                mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", mPlaneDim * 2);
255        }
256
257        /* Some math tests
258        Plane planeX(Vector3::UNIT_X, Vector3(10,10,10));
259        Plane planeY(Vector3::UNIT_Y, Vector3(10,10,10));
260        Plane planeZ(Vector3::UNIT_Z, Vector3(10,10,10));
261        Vector3 vect(20,20,20);
262        Vector3 interX = planeX.projectVector(vect);
263        Vector3 interY = planeY.projectVector(vect);
264        Vector3 interZ = planeZ.projectVector(vect);
265        std::stringstream ssX, ssY, ssZ;
266        ssX << "The intersection of " << planeX << " and " << vect << " is at: " << interX;
267        ssY << "The intersection of " << planeY << " and " << vect << " is at: " << interY;
268        ssZ << "The intersection of " << planeZ << " and " << vect << " is at: " << interZ;
269        LogManager::getSingleton().logMessage(ssX.str());
270        LogManager::getSingleton().logMessage(ssY.str());
271        LogManager::getSingleton().logMessage(ssZ.str());
272        */
273}
274
275void KdTreeApp::createFrameListener(void)
276{
277        mFrameListener = new KdTreeAppListener(mWindow, mSceneMgr, mRotateSpeed, mMoveSpeed, mRotationPeriod);
278        mFrameListener->showDebugOverlay( true );
279        mRoot->addFrameListener(mFrameListener);
280        mRenderTargerListener = new KdTreeAppRenderTargetListener(mSceneMgr);
281        mWindow->addListener(mRenderTargerListener);
282}
283
284void KdTreeApp::chooseSceneManager(void)
285{
286        // Get the SceneManager
287        mSceneMgr = mRoot->createSceneManager(mSelectedSceneManager,"MySceneManager");
288}
289
290void KdTreeApp::createCamera(void)
291{
292    // Create the camera
293    mCamera = mSceneMgr->createCamera("PlayerCam");
294        mCamera->setNearClipDistance(1);
295
296        mCamNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("PlayerCamNode", Vector3(0,0,0));
297        mCamNode->attachObject(mCamera);
298       
299
300    // Position it at 500 in Z direction
301    //mCamera->setPosition(Vector3(0,50,500));
302        //mCamera->setPosition(Vector3(500,256,666));
303        //mCamera->setPosition(Vector3(1280,600,1666));
304    // Look back along -Z
305    //mCamera->lookAt(Vector3(0,50,-300));
306        //mCamera->lookAt(Vector3(-20,30,10));
307
308        //mFollowCam = mSceneMgr->createCamera("FollowCam");
309        //mFollowCam->setPosition(Vector3(800,150,800));
310        //mFollowCam->setNearClipDistance(5);
311        //mFollowCam->setFOVy(Angle(15));
312
313        mTopCam = mSceneMgr->createCamera("TopCam");
314        mTopCam->setPosition(Vector3(0,mPlaneDim * 1.25,0));
315        mTopCam->setDirection(0,0,-1);
316        mTopCam->pitch(Radian(-Math::HALF_PI));
317        //mTopCam->setCullingFrustum(mCamera);
318        mTopCam->setNearClipDistance(1);
319
320        // infinite far plane?
321        if (mRoot->getRenderSystem()->getCapabilities()->hasCapability(RSC_INFINITE_FAR_PLANE))
322        {
323                mTopCam->setFarClipDistance(0);
324                mCamera->setFarClipDistance(0);
325        }
326        else
327        {
328                mTopCam->setFarClipDistance(20000);
329                mCamera->setFarClipDistance(20000);
330        }       
331}
332
333void KdTreeApp::createViewports(void)
334{
335    // Create one viewport, entire window
336    Viewport* vp = mWindow->addViewport(mCamera);
337    vp->setBackgroundColour(ColourValue(0,0,100));
338
339    // Alter the camera aspect ratio to match the viewport
340    mCamera->setAspectRatio(
341        Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
342/*
343        Viewport* fvp = mWindow->addViewport(mFollowCam,2,0.75,0.75,0.25,0.25);
344        fvp->setBackgroundColour(ColourValue(100,0,0));
345        fvp->setOverlaysEnabled( false );
346
347        mFollowCam->setAspectRatio(
348                Real(fvp->getActualWidth()) / Real(fvp->getActualHeight()));
349*/
350}
351
352bool KdTreeApp::configure(void)
353{
354    // Show the configuration dialog and initialise the system
355    // You can skip this and use root.restoreConfig() to load configuration
356    // settings if you were sure there are valid ones saved in ogre.cfg
357#ifdef KDTREE_FASTSTART
358    if(mRoot->restoreConfig())
359#else
360        if(mRoot->showConfigDialog())
361#endif
362    {
363        // If returned true, user clicked OK so initialise
364        // Here we choose to let the system create a default rendering window by passing 'true'
365        mWindow = mRoot->initialise(true);
366        return true;
367    }
368    else
369    {
370        return false;
371    }
372}
373
374void KdTreeApp::createMaterials()
375{
376        MaterialPtr mat;
377        Technique * tech;
378        Pass * pass;
379        TextureUnitState * tex;
380
381        // create play button
382        mat = MaterialManager::getSingleton().create("KdTree/DemoPlayButton", "General");
383        mat->setLightingEnabled(false);
384        tech = mat->getTechnique(0);
385        tech->setSceneBlending(SBT_TRANSPARENT_ALPHA);
386        tech->setDepthCheckEnabled(false);
387        pass = tech->getPass(0);
388        tex = pass->createTextureUnitState();
389        tex->setTextureName("DemoPlayButton.png");
390
391        // create record button
392        mat = MaterialManager::getSingleton().create("KdTree/DemoRecordButton", "General");
393        mat->setLightingEnabled(false);
394        tech = mat->getTechnique(0);
395        tech->setSceneBlending(SBT_TRANSPARENT_ALPHA);
396        tech->setDepthCheckEnabled(false);
397        pass = tech->getPass(0);
398        tex = pass->createTextureUnitState();
399        tex->setTextureName("DemoRecordButton.png");
400}
401
402
403//-----------------------------------------------------------------------
404// splits strings containing multiple file names
405static int splitFilenames(const std::string str, std::vector<std::string> &filenames)
406{
407        int pos = 0;
408
409        while(1)
410        {
411                int npos = (int)str.find(';', pos);
412
413                if (npos < 0 || npos - pos < 1)
414                        break;
415                filenames.push_back(std::string(str, pos, npos - pos));
416                pos = npos + 1;
417        }
418
419        filenames.push_back(std::string(str, pos, str.size() - pos));
420        return (int)filenames.size();
421}
422
423bool KdTreeApp::loadScene(const String &filename)
424{
425        // use leaf nodes of the original spatial hierarchy as occludees
426        std::vector<std::string> filenames;
427        int files = splitFilenames(filename, filenames);
428
429        std::stringstream d;
430        d << "number of input files: " << files << "\n";
431        LogManager::getSingleton().logMessage(d.str());
432
433        bool result = false;
434        std::vector<std::string>::const_iterator fit, fit_end = filenames.end();
435        int i = 0;
436        // root for different files
437        for (fit = filenames.begin(); fit != fit_end; ++ fit, ++ i)
438        {
439                const std::string fn = *fit;
440
441                if (strstr(fn.c_str(), ".iv") || strstr(fn.c_str(), ".wrl"))
442                {
443                        // hack: set postion manually for vienna
444                        //mCamNode->setPosition(Vector3(830, 300, -540));
445                        //mCamNode->setOrientation(Quaternion(-0.3486, 0.0122, 0.9365, 0.0329));
446
447                        // load iv files
448                        loadSceneIV(fn, mSceneMgr->getRootSceneNode(), i);                     
449                }
450
451                result = true;
452        }
453
454
455        /*
456        if (result)
457        {
458        int intersectables, faces;
459
460        std::stringstream d;
461        d << filename << " parsed successfully.\n"
462        << "#NUM_OBJECTS (Total numner of objects)\n" << intersectables << "\n"
463        << "#NUM_FACES (Total numner of faces)\n" << faces << "\n";
464        }
465        */
466
467        return result;
468}
469
470//-----------------------------------------------------------------------
471bool KdTreeApp::loadSceneIV(const String &filename, SceneNode *root, const int index)
472{
473        IVReader * mIVReader = new IVReader();
474
475        if (1)
476        {
477                String logFilename = "IVLog" + Ogre::StringConverter().toString(index) + ".log";
478
479                Log *log = LogManager::getSingleton().createLog(logFilename);
480                mIVReader->setLog(log);
481        }
482
483        //viennaNode->translate(Vector3(-300, -300, 0));
484
485        if (mIVReader->loadFile(filename.c_str()))
486        {
487                SceneNode *node = root->createChildSceneNode("IVSceneNode" + index);
488
489                mIVReader->buildTree(mSceneMgr, node);
490
491                mIVReader->collapse();
492                OGRE_DELETE(mIVReader);
493
494                return true;
495        }
496
497        return false;
498}
499
500/**********************************************************************/
501/*           VisualizationRenderTargetListener implementation         */
502/**********************************************************************/
503
504
505//-----------------------------------------------------------------------
506KdTreeAppRenderTargetListener::KdTreeAppRenderTargetListener(SceneManager *sceneMgr)
507:RenderTargetListener(), mSceneMgr(sceneMgr)
508{
509}
510//-----------------------------------------------------------------------
511void KdTreeAppRenderTargetListener::preViewportUpdate(const RenderTargetViewportEvent &evt)
512{
513        // visualization viewport
514        const bool showViz = evt.source->getZOrder() == VIZ_VIEWPORT_Z_ORDER;
515        const bool nShowViz = !showViz;
516
517        mSavedShadowTechnique = mSceneMgr->getShadowTechnique();
518        mSavedAmbientLight = mSceneMgr->getAmbientLight();
519
520        // -- ambient light must be full for visualization, shadows disabled
521        if (showViz)
522        {
523                mSceneMgr->setAmbientLight(ColourValue(1, 1, 1));
524                mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);
525        }
526
527        mSceneMgr->setOption("PrepareVisualization", &showViz);
528        SceneNode * skybox = mSceneMgr->getSkyBoxNode();
529        if (skybox != 0)
530                mSceneMgr->setOption("SkyBoxEnabled", &nShowViz);
531        //if ((SceneNode * skyplane = mSceneMgr->getSkyPlaneNode()) != 0)
532        //      mSceneMgr->setOption("SkyPlaneEnabled", &showViz);
533
534        RenderTargetListener::preViewportUpdate(evt);
535}
536//-----------------------------------------------------------------------
537void KdTreeAppRenderTargetListener::postRenderTargetUpdate(const RenderTargetEvent &evt)
538{
539        // reset values
540        mSceneMgr->setShadowTechnique(mSavedShadowTechnique);
541        mSceneMgr->setAmbientLight(mSavedAmbientLight);
542
543        RenderTargetListener::postRenderTargetUpdate(evt);
544}
Note: See TracBrowser for help on using the repository browser.