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

Last change on this file since 72 was 72, checked in by Torben Dannhauer, 14 years ago
File size: 15.4 KB
Line 
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
17#include <visual_core.h>
18
19using namespace osgVisual;
20
21visual_core::visual_core(osg::ArgumentParser& arguments_) : arguments(arguments_)
22{
23        OSG_NOTIFY( osg::ALWAYS ) << "visual_core instantiated." << std::endl;
24
25        // Setup pathes
26        osgDB::Registry::instance()->getDataFilePathList().push_back( "D:\\DA\\osgVisual\\models" );
27       
28        // Setup viewer
29        viewer = new osgViewer::Viewer(arguments);
30
31        // Setup coordinate system node
32        rootNode = new osg::CoordinateSystemNode;
33        rootNode->setEllipsoidModel(new osg::EllipsoidModel());
34
35        // Test memory leak (todo)
36        //double* test = new double[1000];
37
38        #ifdef USE_SPACENAVIGATOR
39                mouse = NULL;
40        #endif
41
42        //osg::DisplaySettings::instance()->setNumOfDatabaseThreadsHint( 8 );
43}
44
45visual_core::~visual_core(void)
46{
47        // shut osgVisual down
48        shutdown();
49
50        OSG_NOTIFY( osg::ALWAYS ) << "visual_core destroyed." << std::endl;
51
52}
53
54void visual_core::initialize()
55{
56        OSG_NOTIFY( osg::ALWAYS ) << "Initialize visual_core..." << std::endl;
57
58        // Add manipulators for user interaction
59        addManipulators();
60
61        // Load terrain
62        //loadTerrain(arguments);
63
64        // Show model
65        viewer->setSceneData( rootNode );
66
67        osg::Group* distortedSceneGraph = NULL;
68#ifdef USE_DISTORTION
69        // Initialize distortion
70        OSG_NOTIFY( osg::ALWAYS ) << "Using distortion." << std::endl;
71        distortion = new visual_distortion( viewer, arguments );
72        distortion->initialize( rootNode, viewer->getCamera()->getClearColor() );
73        distortedSceneGraph = distortion->getDistortedSceneGraph();
74#endif
75
76#ifdef USE_SKY_SILVERLINING
77        // Initialize sky
78        OSG_NOTIFY( osg::ALWAYS ) << "Using Sky without distortion." << std::endl;
79        sky = new visual_skySilverLining( viewer );
80        sky->init(distortedSceneGraph, rootNode);       // Without distortedSceneGraph=NULL
81#endif
82
83        // Initialize DataIO interface
84        visual_dataIO::getInstance()->init(viewer, arguments);
85
86        loadTerrain(arguments);
87
88        // All modules are initialized - now check arguments for any unused parameter.
89        checkCommandlineArgumentsForFinalErrors();
90
91        // create the windows and run the threads.
92        viewer->realize();
93
94        // setup scenery
95        setupScenery();
96
97        // Run visual main loop
98        mainLoop();
99}
100
101void visual_core::mainLoop()
102{
103        // run main loop
104        while( !viewer->done() )
105    {
106                // next frame please....
107        viewer->advance();
108                std::cout << "New frame----------------------------" << std::endl;
109
110                /*double hat, hot, lat, lon, height;
111                util::getWGS84ofCamera( viewer->getCamera(), rootNode, lat, lon, height);
112                if (util::queryHeightOfTerrain( hot, rootNode, lat, lon) && util::queryHeightAboveTerrainInWGS84( hat, rootNode, lat, lon, height ) )
113                        OSG_NOTIFY( osg::ALWAYS ) << "HOT is: " << hot << ", HAT is: " << hat << std::endl;*/
114       
115                // perform all queued events
116                viewer->eventTraversal();
117
118                // update the scene by traversing it with the the update visitor which will
119        // call all node update callbacks and animations.
120       
121        viewer->updateTraversal();
122               
123        // Render the Frame.
124        viewer->renderingTraversals();
125
126    }   // END WHILE
127}
128
129void visual_core::shutdown()
130{
131        OSG_NOTIFY( osg::ALWAYS ) << "Shutdown visual_core..." << std::endl;
132
133        // Unset scene data
134        viewer->setSceneData( NULL );
135
136#ifdef USE_SKY_SILVERLINING
137        // Shutdown sky
138        if( sky.valid() )
139                sky->shutdown();
140#endif
141
142#ifdef USE_DISTORTION
143        // Shutdown distortion
144        if( distortion.valid() )
145                distortion->shutdown();
146#endif
147
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
160}
161
162bool visual_core::loadTerrain(osg::ArgumentParser& arguments_)
163{
164        osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments_);
165        if( model.valid() )
166        {
167        rootNode->addChild( model.get() );
168                return true;
169        }
170        else
171        {
172        OSG_NOTIFY( osg::FATAL ) << "Load terrain: No data loaded" << std::endl;
173        return false;
174    }   
175
176        return false;
177}
178
179void visual_core::addManipulators()
180{
181        // set up the camera manipulators.
182    {
183        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
184
185        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
186        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
187        keyswitchManipulator->addMatrixManipulator( '3', "Terrain", new osgGA::TerrainManipulator() );
188                nt = new osgGA::NodeTrackerManipulator();
189                keyswitchManipulator->addMatrixManipulator( '4', "NodeTrackerManipulator", nt );
190               
191#ifdef USE_SPACENAVIGATOR
192                // SpaceNavigator manipulator
193                mouse = new SpaceMouse();
194                mouse->initialize();
195                mouseTrackerManip = new NodeTrackerSpaceMouse(mouse);
196                mouseTrackerManip->setTrackerMode(NodeTrackerSpaceMouse::NODE_CENTER);
197                mouseTrackerManip->setRotationMode(NodeTrackerSpaceMouse::ELEVATION_AZIM);
198                mouseTrackerManip->setAutoComputeHomePosition( true );
199                keyswitchManipulator->addMatrixManipulator( '5', "Spacemouse Node Tracker", mouseTrackerManip );
200                keyswitchManipulator->addMatrixManipulator( '6', "Spacemouse Free (Airplane)", new FreeManipulator(mouse) );
201#endif
202
203                // objectMounted Manipulator for Camera control by Nodes
204                objectMountedCameraManip = new objectMountedManipulator();
205                keyswitchManipulator->addMatrixManipulator( '7', "Object mounted Camera", objectMountedCameraManip );
206
207                // Animation path manipulator
208        std::string pathfile;
209        char keyForAnimationPath = '8';
210        while (arguments.read("-p",pathfile))
211        {
212            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
213            if (apm || !apm->valid()) 
214            {
215                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
216                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
217                keyswitchManipulator->selectMatrixManipulator(num);
218                ++keyForAnimationPath;
219            }
220        }
221
222        viewer->setCameraManipulator( keyswitchManipulator.get() );
223    }
224
225    // add the state manipulator
226    viewer->addEventHandler( new osgGA::StateSetManipulator(rootNode->getOrCreateStateSet()) );
227   
228    // add the thread model handler
229    viewer->addEventHandler(new osgViewer::ThreadingHandler);
230
231    // add the window size toggle handler
232    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
233       
234    // add the stats handler
235    viewer->addEventHandler(new osgViewer::StatsHandler);
236
237    // add the help handler
238    viewer->addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
239
240    // add the record camera path handler
241    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);
242
243    // add the LOD Scale handler
244    viewer->addEventHandler(new osgViewer::LODScaleHandler);
245
246    // add the screen capture handler
247    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
248}
249
250
251bool visual_core::checkCommandlineArgumentsForFinalErrors()
252{
253        // Setup Application Usage
254        arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
255        arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the new FSD visualization tool, written by Torben Dannhauer");
256    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] Terrain_filename");
257        arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
258
259    // if user request help write it out to cout.
260    if (arguments.read("-h") || arguments.read("--help"))
261    {
262        arguments.getApplicationUsage()->write(std::cout);
263                //cause the viewer to exit and shut down clean.
264        viewer->setDone(true);
265    }
266
267    // report any errors if they have occurred when parsing the program arguments.
268    if (arguments.errors())
269    {
270        arguments.writeErrorMessages(std::cout);
271                //cause the viewer to exit and shut down clean.
272        viewer->setDone(true);
273    }
274
275         // any option left unread are converted into errors to write out later.
276    arguments.reportRemainingOptionsAsUnrecognized();
277
278    // report any errors if they have occurred when parsing the program arguments.
279    if (arguments.errors())
280    {
281        arguments.writeErrorMessages(std::cout);
282        return false;
283    }
284        return true;
285}
286
287void visual_core::setupScenery()
288{
289        //testObj = new visual_object( rootNode, "testStab", objectMountedCameraManip );
290        //testObj->setNewPosition( osg::DegreesToRadians(47.7123), osg::DegreesToRadians(12.84088), 600 );
291        ///* using a huge cylinder to test position & orientation */
292        //testObj->setGeometry( util::getDemoCylinder(5000.0, 20.0 ) );
293        //testObj->addUpdater( new object_updater(testObj) );
294
295        osg::ref_ptr<visual_object> testObj2 = new visual_object( rootNode, "cessna" );
296        //testObj2->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
297        testObj2->setNewPosition( osg::DegreesToRadians(50.8123), osg::DegreesToRadians(8.94088), 600 );
298        testObj2->loadGeometry( "../models/cessna.osg" );
299        testObj2->addUpdater( new object_updater(testObj2) );
300
301        osg::ref_ptr<visual_object> testObj3 = new visual_object( rootNode, "SAENGER1" );
302        testObj3->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
303        testObj3->loadGeometry( "../models/saenger1.flt" );
304        testObj3->addUpdater( new object_updater(testObj3) );
305       
306
307        osg::ref_ptr<visual_object> testObj4 = new visual_object( rootNode, "SAENGER2" );
308        testObj4->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 650 );
309        testObj4->loadGeometry( "../models/saenger2.flt" );
310        testObj4->addUpdater( new object_updater(testObj4) );
311        testObj4->addLabel("testLabel", "LabelTest!!\nnächste Zeile :)",osg::Vec4(1.0f,0.25f,1.0f,1.0f));
312
313        osg::ref_ptr<visual_object> testObj5 = new visual_object( rootNode, "SAENGER" );
314        testObj5->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 550 );
315        testObj5->loadGeometry( "../models/saengerCombine.flt" );
316        //testObj5->setScale( 2 );
317        testObj5->addUpdater( new object_updater(testObj5) );
318
319#ifdef USE_SPACENAVIGATOR
320        // Manipulatoren auf dieses Objekt binden (Primärobjekt)
321        if (objectMountedCameraManip.valid())
322                objectMountedCameraManip->setAttachedObject( testObj4 );
323        if (mouseTrackerManip.valid())
324        {
325                mouseTrackerManip->setTrackNode( testObj4->getGeometry() );
326                mouseTrackerManip->setMinimumDistance( 100 );
327        }
328#endif
329
330        osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
331        osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
332        nt->setTrackerMode(trackerMode);
333    nt->setRotationMode(rotationMode);
334        //nt->setAutoComputeHomePosition( true );
335        nt->setMinimumDistance( 100 );
336        nt->setTrackNode(testObj4->getGeometry());
337        //nt->computeHomePosition();
338        nt->setAutoComputeHomePosition( true );
339        nt->setDistance( 250 );
340
341
342        // Load EDDF
343        //std::string filename = "D:\\DA\\EDDF_test\\eddf.ive";
344        //if( !osgDB::fileExists(filename) )
345        //{
346        //      OSG_NOTIFY(osg::ALWAYS) << "Warning: EDDF Model not loaded. File '" << filename << "' does not exist. Skipping.";
347        //}
348        //// read model
349        //osg::ref_ptr<osg::Node> tmpModel = osgDB::readNodeFile( filename );
350        //if (tmpModel.valid())
351        //      rootNode->addChild( tmpModel );
352       
353 
354        visual_draw2D::getInstance()->init( rootNode, viewer );
355        //osg::ref_ptr<visual_hud> hud = new visual_hud();
356        osg::ref_ptr<visual_debug_hud> hud = new visual_debug_hud();
357        hud->init( viewer, rootNode );
358       
359
360        //osg::ref_ptr<visual_draw3D> test = new visual_draw3D();
361        //test->init( rootNode, viewer );
362
363        //// Creating Testclasses
364        //osg::ref_ptr<osgVisual::dataIO_transportContainer> test = new osgVisual::dataIO_transportContainer();
365        //osg::ref_ptr<osgVisual::dataIO_executer> testEx = new osgVisual::dataIO_executer();
366        //osg::ref_ptr<osgVisual::dataIO_slot> testSlot = new osgVisual::dataIO_slot();
367        //test->setFrameID( 22 );
368        //test->setName("ugamoep");
369        //testEx->setexecuterID( osgVisual::dataIO_executer::IS_COLLISION );
370        //testSlot->setVariableName(std::string("HalloName"));
371        //testSlot->setdataDirection( osgVisual::dataIO_slot::TO_OBJ );
372        //testSlot->setvarType( osgVisual::dataIO_slot::DOUBLE );
373        //testSlot->setValue( 0.12345 );
374        //test->addExecuter( testEx );
375        //test->addSlot( testSlot );
376
377        visual_dataIO::getInstance()->setSlotData("TestSlot1", osgVisual::dataIO_slot::TO_OBJ, 0.12345);
378
379
380        //// Writing object to stream
381        ////std::ofstream myOstream("test.txt" );
382        //std::stringstream myOstream;
383        //std::string extension = "osgb";
384        //bool compressed = false;
385        //osgDB::ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension(extension.c_str());
386        //if ( rw )
387        //{
388        //      osgDB::ReaderWriter::WriteResult wr;
389
390        //      if (extension == "osgb")
391        //      {
392        //              if (compressed)
393        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("Compressor=zlib") );
394        //              else
395        //                      wr = rw->writeObject( *test, myOstream );
396        //      }
397
398        //      if (extension == "osgt")
399        //      {
400        //              if (compressed)
401        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("Ascii Compressor=zlib") );
402        //              else
403        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("Ascii") );
404        //      }
405
406        //      if (extension == "osgx")
407        //      {
408        //              if (compressed)
409        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("XML Compressor=zlib") );
410        //              else
411        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("XML") );
412        //      }
413
414
415        //      if (!wr.success() )     OSG_NOTIFY( osg::WARN ) << "ERROR: Save failed: " << wr.message() << std::endl;
416        //}
417        //else
418        //      OSG_NOTIFY( osg::WARN ) << "error getting readerWriter for osgt" << std::endl;
419
420        //// Size ermitteln.
421        //std::stringbuf *pbuf;
422        //pbuf = myOstream.rdbuf();
423        //OSG_NOTIFY( osg::WARN ) << "PBUF Bytes available: " << pbuf->in_avail() << std::endl;
424        //OSG_NOTIFY( osg::ALWAYS ) << "STRING Bytes available: " << myOstream.str().length() << std::endl;
425        //OSG_NOTIFY( osg::ALWAYS ) << "STRING content: " << myOstream.str() << std::endl;
426
427        ////Reading Stream to node
428        //if ( rw )
429        //{
430        //      osgDB::ReaderWriter::ReadResult rr = rw->readObject( myOstream );
431        //      osg::ref_ptr<osgVisual::dataIO_transportContainer> test2 = dynamic_cast<osgVisual::dataIO_transportContainer*>(rr.takeObject());
432        //      if (test2)
433        //      {
434        //              OSG_NOTIFY( osg::WARN ) << "TEST::FrameID is: " << test->getFrameID() << std::endl;
435        //      }
436        //      else
437        //              OSG_NOTIFY( osg::WARN ) << "Error converting stream to Node" << std::endl;
438        //}
439}
Note: See TracBrowser for help on using the repository browser.