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

Last change on this file since 69 was 69, checked in by Torben Dannhauer, 14 years ago

Network sync:
now works:

  • serialization of transport container
  • transport via ENet UDP
  • de-serialization of the transport container.
  • transport of viewmatrix and framenumber to the slave.

ToDo?: apply viewmatrix on slave still do not work.

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