source: osgVisual/src/core/visual_core.cpp @ 126

Last change on this file since 126 was 125, checked in by Torben Dannhauer, 14 years ago
File size: 15.6 KB
RevLine 
[31]1/* -*-c++-*- osgVisual - Copyright (C) 2009-2010 Torben Dannhauer
2 *
3 * This library is based on OpenSceneGraph, open source and may be redistributed and/or modified under
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * osgVisual requires for some proprietary modules a license from the correspondig manufacturer.
9 * You have to aquire licenses for all used proprietary modules.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * OpenSceneGraph Public License for more details.
15*/
16
[86]17
[31]18#include <visual_core.h>
19
20using namespace osgVisual;
21
22visual_core::visual_core(osg::ArgumentParser& arguments_) : arguments(arguments_)
23{
24        OSG_NOTIFY( osg::ALWAYS ) << "visual_core instantiated." << std::endl;
[86]25}
[31]26
[86]27visual_core::~visual_core(void)
28{
29        OSG_NOTIFY( osg::ALWAYS ) << "visual_core destroyed." << std::endl;
30}
31
32void visual_core::initialize()
33{
34        OSG_NOTIFY( osg::ALWAYS ) << "Initialize visual_core..." << std::endl;
35
36        // Configure osg to use KdTrees
37        osgDB::Registry::instance()->setBuildKdTreesHint(osgDB::ReaderWriter::Options::BUILD_KDTREES);
38
[31]39        // Setup pathes
40        osgDB::Registry::instance()->getDataFilePathList().push_back( "D:\\DA\\osgVisual\\models" );
41       
42        // Setup viewer
43        viewer = new osgViewer::Viewer(arguments);
44
45        // Setup coordinate system node
[87]46        rootNode = new osg::CoordinateSystemNode;       // todo memleakf
[31]47        rootNode->setEllipsoidModel(new osg::EllipsoidModel());
48
49        // Test memory leak (todo)
[116]50        double* test = new double[1000];
[31]51
[55]52        #ifdef USE_SPACENAVIGATOR
53                mouse = NULL;
54        #endif
55
56        //osg::DisplaySettings::instance()->setNumOfDatabaseThreadsHint( 8 );
[31]57
58        // Show model
59        viewer->setSceneData( rootNode );
60
[71]61        osg::Group* distortedSceneGraph = NULL;
[31]62#ifdef USE_DISTORTION
63        // Initialize distortion
[71]64        OSG_NOTIFY( osg::ALWAYS ) << "Using distortion." << std::endl;
[31]65        distortion = new visual_distortion( viewer, arguments );
66        distortion->initialize( rootNode, viewer->getCamera()->getClearColor() );
[71]67        distortedSceneGraph = distortion->getDistortedSceneGraph();
[31]68#endif
69
70#ifdef USE_SKY_SILVERLINING
71        // Initialize sky
72        sky = new visual_skySilverLining( viewer );
[72]73        sky->init(distortedSceneGraph, rootNode);       // Without distortedSceneGraph=NULL
[31]74#endif
75
76        // Initialize DataIO interface
77        visual_dataIO::getInstance()->init(viewer, arguments);
78
[73]79        // Add manipulators for user interaction - after dataIO to be able to skip it in slaves.
80        addManipulators();
81
[68]82        loadTerrain(arguments);
83
[31]84        // All modules are initialized - now check arguments for any unused parameter.
85        checkCommandlineArgumentsForFinalErrors();
86
87        // create the windows and run the threads.
88        viewer->realize();
89
90        // setup scenery
91        setupScenery();
92
93        // Run visual main loop
94        mainLoop();
95}
96
97void visual_core::mainLoop()
98{
99        // run main loop
100        while( !viewer->done() )
101    {
102                // next frame please....
103        viewer->advance();
104
105                /*double hat, hot, lat, lon, height;
106                util::getWGS84ofCamera( viewer->getCamera(), rootNode, lat, lon, height);
107                if (util::queryHeightOfTerrain( hot, rootNode, lat, lon) && util::queryHeightAboveTerrainInWGS84( hat, rootNode, lat, lon, height ) )
108                        OSG_NOTIFY( osg::ALWAYS ) << "HOT is: " << hot << ", HAT is: " << hat << std::endl;*/
109       
[70]110                // perform all queued events
111                viewer->eventTraversal();
112
[31]113                // update the scene by traversing it with the the update visitor which will
114        // call all node update callbacks and animations.
115        viewer->updateTraversal();
116               
117        // Render the Frame.
118        viewer->renderingTraversals();
119
120    }   // END WHILE
121}
122
123void visual_core::shutdown()
124{
125        OSG_NOTIFY( osg::ALWAYS ) << "Shutdown visual_core..." << std::endl;
126
[87]127        // Shutdown Dbug HUD
128        if(hud.valid())
129                hud->shutdown();
[31]130        // Unset scene data
131        viewer->setSceneData( NULL );
132
133#ifdef USE_SKY_SILVERLINING
134        // Shutdown sky
135        if( sky.valid() )
136                sky->shutdown();
137#endif
138
139#ifdef USE_DISTORTION
140        // Shutdown distortion
141        if( distortion.valid() )
142                distortion->shutdown();
143#endif
144
[87]145        // Shutdown data
146        rootNode = NULL;
147
[31]148        // Shutdown dataIO
149        visual_dataIO::getInstance()->shutdown();
150
151       
152#ifdef USE_SPACENAVIGATOR
153        //Delete SpaceMouse driver
154        if(mouse)
155        {
156                mouse->shutdown();
157                delete mouse;
158        }
159#endif
[86]160
161        // Destroy osgViewer
162        viewer = NULL;
[31]163}
164
165bool visual_core::loadTerrain(osg::ArgumentParser& arguments_)
166{
167        osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments_);
168        if( model.valid() )
169        {
170        rootNode->addChild( model.get() );
171                return true;
172        }
173        else
174        {
[58]175        OSG_NOTIFY( osg::FATAL ) << "Load terrain: No data loaded" << std::endl;
[31]176        return false;
177    }   
178
179        return false;
180}
181
182void visual_core::addManipulators()
183{
[73]184        if(!visual_dataIO::getInstance()->isSlave()) // set up the camera manipulators if not slave.
[31]185    {
186        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
187
188        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
189        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
190        keyswitchManipulator->addMatrixManipulator( '3', "Terrain", new osgGA::TerrainManipulator() );
191                nt = new osgGA::NodeTrackerManipulator();
192                keyswitchManipulator->addMatrixManipulator( '4', "NodeTrackerManipulator", nt );
193               
194#ifdef USE_SPACENAVIGATOR
195                // SpaceNavigator manipulator
196                mouse = new SpaceMouse();
197                mouse->initialize();
198                mouseTrackerManip = new NodeTrackerSpaceMouse(mouse);
199                mouseTrackerManip->setTrackerMode(NodeTrackerSpaceMouse::NODE_CENTER);
200                mouseTrackerManip->setRotationMode(NodeTrackerSpaceMouse::ELEVATION_AZIM);
201                mouseTrackerManip->setAutoComputeHomePosition( true );
202                keyswitchManipulator->addMatrixManipulator( '5', "Spacemouse Node Tracker", mouseTrackerManip );
203                keyswitchManipulator->addMatrixManipulator( '6', "Spacemouse Free (Airplane)", new FreeManipulator(mouse) );
204#endif
205
206                // objectMounted Manipulator for Camera control by Nodes
207                objectMountedCameraManip = new objectMountedManipulator();
208                keyswitchManipulator->addMatrixManipulator( '7', "Object mounted Camera", objectMountedCameraManip );
209
210                // Animation path manipulator
211        std::string pathfile;
212        char keyForAnimationPath = '8';
213        while (arguments.read("-p",pathfile))
214        {
215            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
216            if (apm || !apm->valid()) 
217            {
218                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
219                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
220                keyswitchManipulator->selectMatrixManipulator(num);
221                ++keyForAnimationPath;
222            }
223        }
224
225        viewer->setCameraManipulator( keyswitchManipulator.get() );
[73]226    }   // If not Slave END
[31]227
228    // add the state manipulator
229    viewer->addEventHandler( new osgGA::StateSetManipulator(rootNode->getOrCreateStateSet()) );
230   
231    // add the thread model handler
232    viewer->addEventHandler(new osgViewer::ThreadingHandler);
233
234    // add the window size toggle handler
235    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
236       
237    // add the stats handler
238    viewer->addEventHandler(new osgViewer::StatsHandler);
239
240    // add the help handler
241    viewer->addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
242
243    // add the record camera path handler
244    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);
245
246    // add the LOD Scale handler
247    viewer->addEventHandler(new osgViewer::LODScaleHandler);
248
249    // add the screen capture handler
250    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
251}
252
[125]253void visual_core::parseConfigFile(osg::ArgumentParser& arguments_)
254{
255        std::string filename;
256        if( arguments.read("-c", filename) || arguments.read("--config", filename) )
257        {
258                if( osgDB::fileExists(filename) )
259                {
260                        configFileValid = false;
261                        xmlDoc *doc = NULL;
262                        xmlNode *root_element = NULL;
263                       
264                        doc = xmlReadFile(filename.c_str(), NULL, 0);
265                        if (doc == NULL)
266                        {
267                                configFileValid = false;
268                                OSG_ALWAYS << "visual_core::parseConfigFile() - ERROR: could not parse osgVisual config file" << filename  << std::endl;
269                        }
270                        else
271                        {
272                                //  Get the root element node
273                                root_element = xmlDocGetRootElement(doc);
[67]274
[125]275                                // Parse the XML document.
276
277
278                                // free the document
279                                xmlFreeDoc(doc);;
280                        }
281                        // Free the global variables that may have been allocated by the parser.
282                        xmlCleanupParser();
283
284                        if(!configFileValid)
285                                OSG_ALWAYS << "visual_core::parseConfigFile() - ERROR: XML file seems not to be a valid osgVisual configuration file!" << std::endl;
286
287                }       // IF configfile exists
288        }       // IF -c END
289}
290
291void visual_core::checkXMLNode(xmlNode * a_node)
292{
293
294}
295
296void visual_core::parseScenery(xmlNode * a_node)
297{
298
299}
300
[67]301bool visual_core::checkCommandlineArgumentsForFinalErrors()
[31]302{
303        // Setup Application Usage
304        arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
305        arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the new FSD visualization tool, written by Torben Dannhauer");
306    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] Terrain_filename");
307        arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
308
309    // if user request help write it out to cout.
310    if (arguments.read("-h") || arguments.read("--help"))
311    {
312        arguments.getApplicationUsage()->write(std::cout);
313                //cause the viewer to exit and shut down clean.
314        viewer->setDone(true);
315    }
316
317    // report any errors if they have occurred when parsing the program arguments.
318    if (arguments.errors())
319    {
320        arguments.writeErrorMessages(std::cout);
321                //cause the viewer to exit and shut down clean.
322        viewer->setDone(true);
323    }
324
325         // any option left unread are converted into errors to write out later.
326    arguments.reportRemainingOptionsAsUnrecognized();
327
328    // report any errors if they have occurred when parsing the program arguments.
329    if (arguments.errors())
330    {
331        arguments.writeErrorMessages(std::cout);
332        return false;
333    }
334        return true;
335}
336
337void visual_core::setupScenery()
338{
[122]339        // iterate manually through one frame to allow some modules like Sky_Silverlining to initialize properly befor we configure it according to the scenery data.
340        viewer->advance();
341        viewer->eventTraversal();
342        viewer->updateTraversal();
343        viewer->renderingTraversals();
344
345        // Sky settings:       
346        sky->setTime(12,00,23);
347        sky->setVisibility(50000);
348        //addWindVolume( 0.0, 15000.0, 300.0, 90.0 );
349       
[125]350        sky->addCloudLayer( 0, 300000, 300000, 600.0, 2351.0, 0.5, STRATUS );
[122]351        //sky->addCloudLayer( 0, 5000000, 5000000, 600.0, 7351.0, 0.2, CIRRUS_FIBRATUS );
352        //sky->addCloudLayer( 0, 50000, 50000, 600.0, 7351.0, 0.2, CIRROCUMULUS );
353        ///sky->addCloudLayer( 1, 200000, 200000, 3000, 2000.0, 0.05, CUMULUS_CONGESTUS );
354        //cloudLayerSlots[1].cloudLayerPointer->SetPrecipitation(SilverLining::CloudLayer::SLEET, 25.0 );
355
[31]356        //testObj = new visual_object( rootNode, "testStab", objectMountedCameraManip );
357        //testObj->setNewPosition( osg::DegreesToRadians(47.7123), osg::DegreesToRadians(12.84088), 600 );
358        ///* using a huge cylinder to test position & orientation */
359        //testObj->setGeometry( util::getDemoCylinder(5000.0, 20.0 ) );
360        //testObj->addUpdater( new object_updater(testObj) );
361
[115]362        //osg::ref_ptr<visual_object> testObj2 = new visual_object( rootNode, "neuschwanstein" );       // todo memleak
363        ////testObj2->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
364        //testObj2->setNewPosition( osg::DegreesToRadians(47.557523564234), osg::DegreesToRadians(10.749646398595), 950 );
365        //testObj2->loadGeometry( "../models/neuschwanstein.osgb" );
366        ////testObj2->addUpdater( new object_updater(testObj2) );       // todo memleak
[31]367
[87]368        osg::ref_ptr<visual_object> testObj3 = new visual_object( rootNode, "SAENGER1" );       // todo memleak
[31]369        testObj3->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
370        testObj3->loadGeometry( "../models/saenger1.flt" );
[87]371        testObj3->addUpdater( new object_updater(testObj3) );   // todo memleak
[31]372       
373
[87]374        osg::ref_ptr<visual_object> testObj4 = new visual_object( rootNode, "SAENGER2" );       // todo memleak
[31]375        testObj4->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 650 );
376        testObj4->loadGeometry( "../models/saenger2.flt" );
[87]377        testObj4->addUpdater( new object_updater(testObj4) );   // todo memleak
[31]378        testObj4->addLabel("testLabel", "LabelTest!!\nnächste Zeile :)",osg::Vec4(1.0f,0.25f,1.0f,1.0f));
379
[87]380        osg::ref_ptr<visual_object> testObj5 = new visual_object( rootNode, "SAENGER" );        // todo memleak
[31]381        testObj5->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 550 );
382        testObj5->loadGeometry( "../models/saengerCombine.flt" );
383        //testObj5->setScale( 2 );
[87]384        testObj5->addUpdater( new object_updater(testObj5) );   // todo memleak
[31]385
386#ifdef USE_SPACENAVIGATOR
387        // Manipulatoren auf dieses Objekt binden (Primärobjekt)
388        if (objectMountedCameraManip.valid())
[115]389                objectMountedCameraManip->setAttachedObject( testObj4 );
[31]390        if (mouseTrackerManip.valid())
391        {
[115]392                mouseTrackerManip->setTrackNode( testObj4->getGeometry() );
[31]393                mouseTrackerManip->setMinimumDistance( 100 );
394        }
395#endif
396
[73]397        if(nt.valid())
398        {
399                osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
400                osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
401                nt->setTrackerMode(trackerMode);
402                nt->setRotationMode(rotationMode);
403                //nt->setAutoComputeHomePosition( true );
404                nt->setMinimumDistance( 100 );
405                nt->setTrackNode(testObj4->getGeometry());
406                //nt->computeHomePosition();
407                nt->setAutoComputeHomePosition( true );
408                nt->setDistance( 250 );
409        }
[31]410
411
412        // Load EDDF
413        //std::string filename = "D:\\DA\\EDDF_test\\eddf.ive";
414        //if( !osgDB::fileExists(filename) )
415        //{
416        //      OSG_NOTIFY(osg::ALWAYS) << "Warning: EDDF Model not loaded. File '" << filename << "' does not exist. Skipping.";
417        //}
418        //// read model
419        //osg::ref_ptr<osg::Node> tmpModel = osgDB::readNodeFile( filename );
420        //if (tmpModel.valid())
421        //      rootNode->addChild( tmpModel );
422       
423 
424        visual_draw2D::getInstance()->init( rootNode, viewer );
425        //osg::ref_ptr<visual_hud> hud = new visual_hud();
[87]426        hud = new visual_debug_hud();
[31]427        hud->init( viewer, rootNode );
428       
[122]429       
[31]430
431        //osg::ref_ptr<visual_draw3D> test = new visual_draw3D();
432        //test->init( rootNode, viewer );
433
[69]434        //// Creating Testclasses
435        //osg::ref_ptr<osgVisual::dataIO_transportContainer> test = new osgVisual::dataIO_transportContainer();
436        //osg::ref_ptr<osgVisual::dataIO_executer> testEx = new osgVisual::dataIO_executer();
437        //osg::ref_ptr<osgVisual::dataIO_slot> testSlot = new osgVisual::dataIO_slot();
438        //test->setFrameID( 22 );
439        //test->setName("ugamoep");
440        //testEx->setexecuterID( osgVisual::dataIO_executer::IS_COLLISION );
441        //testSlot->setVariableName(std::string("HalloName"));
442        //testSlot->setdataDirection( osgVisual::dataIO_slot::TO_OBJ );
443        //testSlot->setvarType( osgVisual::dataIO_slot::DOUBLE );
444        //testSlot->setValue( 0.12345 );
445        //test->addExecuter( testEx );
446        //test->addSlot( testSlot );
[31]447
[69]448        visual_dataIO::getInstance()->setSlotData("TestSlot1", osgVisual::dataIO_slot::TO_OBJ, 0.12345);
[31]449}
Note: See TracBrowser for help on using the repository browser.