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

Last change on this file since 75 was 75, checked in by Torben Dannhauer, 14 years ago
File size: 13.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        // Load terrain
59        //loadTerrain(arguments);
60
61        // Show model
62        viewer->setSceneData( rootNode );
63
64        osg::Group* distortedSceneGraph = NULL;
65#ifdef USE_DISTORTION
66        // Initialize distortion
67        OSG_NOTIFY( osg::ALWAYS ) << "Using distortion." << std::endl;
68        distortion = new visual_distortion( viewer, arguments );
69        distortion->initialize( rootNode, viewer->getCamera()->getClearColor() );
70        distortedSceneGraph = distortion->getDistortedSceneGraph();
71#endif
72
73#ifdef USE_SKY_SILVERLINING
74        // Initialize sky
75        OSG_NOTIFY( osg::ALWAYS ) << "Using Sky without distortion." << std::endl;
76        sky = new visual_skySilverLining( viewer );
77        sky->init(distortedSceneGraph, rootNode);       // Without distortedSceneGraph=NULL
78#endif
79
80        // Initialize DataIO interface
81        visual_dataIO::getInstance()->init(viewer, arguments);
82
83        // Add manipulators for user interaction - after dataIO to be able to skip it in slaves.
84        addManipulators();
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
109                /*double hat, hot, lat, lon, height;
110                util::getWGS84ofCamera( viewer->getCamera(), rootNode, lat, lon, height);
111                if (util::queryHeightOfTerrain( hot, rootNode, lat, lon) && util::queryHeightAboveTerrainInWGS84( hat, rootNode, lat, lon, height ) )
112                        OSG_NOTIFY( osg::ALWAYS ) << "HOT is: " << hot << ", HAT is: " << hat << std::endl;*/
113       
114                // perform all queued events
115                viewer->eventTraversal();
116
117                // update the scene by traversing it with the the update visitor which will
118        // call all node update callbacks and animations.
119        viewer->updateTraversal();
120               
121        // Render the Frame.
122        viewer->renderingTraversals();
123
124    }   // END WHILE
125}
126
127void visual_core::shutdown()
128{
129        OSG_NOTIFY( osg::ALWAYS ) << "Shutdown visual_core..." << std::endl;
130
131        // Unset scene data
132        viewer->setSceneData( NULL );
133
134#ifdef USE_SKY_SILVERLINING
135        // Shutdown sky
136        if( sky.valid() )
137                sky->shutdown();
138#endif
139
140#ifdef USE_DISTORTION
141        // Shutdown distortion
142        if( distortion.valid() )
143                distortion->shutdown();
144#endif
145
146        // Shutdown dataIO
147        visual_dataIO::getInstance()->shutdown();
148
149       
150#ifdef USE_SPACENAVIGATOR
151        //Delete SpaceMouse driver
152        if(mouse)
153        {
154                mouse->shutdown();
155                delete mouse;
156        }
157#endif
158}
159
160bool visual_core::loadTerrain(osg::ArgumentParser& arguments_)
161{
162        osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments_);
163        if( model.valid() )
164        {
165        rootNode->addChild( model.get() );
166                return true;
167        }
168        else
169        {
170        OSG_NOTIFY( osg::FATAL ) << "Load terrain: No data loaded" << std::endl;
171        return false;
172    }   
173
174        return false;
175}
176
177void visual_core::addManipulators()
178{
179        if(!visual_dataIO::getInstance()->isSlave()) // set up the camera manipulators if not slave.
180    {
181        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
182
183        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
184        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
185        keyswitchManipulator->addMatrixManipulator( '3', "Terrain", new osgGA::TerrainManipulator() );
186                nt = new osgGA::NodeTrackerManipulator();
187                keyswitchManipulator->addMatrixManipulator( '4', "NodeTrackerManipulator", nt );
188               
189#ifdef USE_SPACENAVIGATOR
190                // SpaceNavigator manipulator
191                mouse = new SpaceMouse();
192                mouse->initialize();
193                mouseTrackerManip = new NodeTrackerSpaceMouse(mouse);
194                mouseTrackerManip->setTrackerMode(NodeTrackerSpaceMouse::NODE_CENTER);
195                mouseTrackerManip->setRotationMode(NodeTrackerSpaceMouse::ELEVATION_AZIM);
196                mouseTrackerManip->setAutoComputeHomePosition( true );
197                keyswitchManipulator->addMatrixManipulator( '5', "Spacemouse Node Tracker", mouseTrackerManip );
198                keyswitchManipulator->addMatrixManipulator( '6', "Spacemouse Free (Airplane)", new FreeManipulator(mouse) );
199#endif
200
201                // objectMounted Manipulator for Camera control by Nodes
202                objectMountedCameraManip = new objectMountedManipulator();
203                keyswitchManipulator->addMatrixManipulator( '7', "Object mounted Camera", objectMountedCameraManip );
204
205                // Animation path manipulator
206        std::string pathfile;
207        char keyForAnimationPath = '8';
208        while (arguments.read("-p",pathfile))
209        {
210            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
211            if (apm || !apm->valid()) 
212            {
213                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
214                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
215                keyswitchManipulator->selectMatrixManipulator(num);
216                ++keyForAnimationPath;
217            }
218        }
219
220        viewer->setCameraManipulator( keyswitchManipulator.get() );
221    }   // If not Slave END
222
223    // add the state manipulator
224    viewer->addEventHandler( new osgGA::StateSetManipulator(rootNode->getOrCreateStateSet()) );
225   
226    // add the thread model handler
227    viewer->addEventHandler(new osgViewer::ThreadingHandler);
228
229    // add the window size toggle handler
230    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
231       
232    // add the stats handler
233    viewer->addEventHandler(new osgViewer::StatsHandler);
234
235    // add the help handler
236    viewer->addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
237
238    // add the record camera path handler
239    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);
240
241    // add the LOD Scale handler
242    viewer->addEventHandler(new osgViewer::LODScaleHandler);
243
244    // add the screen capture handler
245    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
246}
247
248
249bool visual_core::checkCommandlineArgumentsForFinalErrors()
250{
251        // Setup Application Usage
252        arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
253        arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the new FSD visualization tool, written by Torben Dannhauer");
254    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] Terrain_filename");
255        arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
256
257    // if user request help write it out to cout.
258    if (arguments.read("-h") || arguments.read("--help"))
259    {
260        arguments.getApplicationUsage()->write(std::cout);
261                //cause the viewer to exit and shut down clean.
262        viewer->setDone(true);
263    }
264
265    // report any errors if they have occurred when parsing the program arguments.
266    if (arguments.errors())
267    {
268        arguments.writeErrorMessages(std::cout);
269                //cause the viewer to exit and shut down clean.
270        viewer->setDone(true);
271    }
272
273         // any option left unread are converted into errors to write out later.
274    arguments.reportRemainingOptionsAsUnrecognized();
275
276    // report any errors if they have occurred when parsing the program arguments.
277    if (arguments.errors())
278    {
279        arguments.writeErrorMessages(std::cout);
280        return false;
281    }
282        return true;
283}
284
285void visual_core::setupScenery()
286{
287        //testObj = new visual_object( rootNode, "testStab", objectMountedCameraManip );
288        //testObj->setNewPosition( osg::DegreesToRadians(47.7123), osg::DegreesToRadians(12.84088), 600 );
289        ///* using a huge cylinder to test position & orientation */
290        //testObj->setGeometry( util::getDemoCylinder(5000.0, 20.0 ) );
291        //testObj->addUpdater( new object_updater(testObj) );
292
293        osg::ref_ptr<visual_object> testObj2 = new visual_object( rootNode, "cessna" );
294        //testObj2->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
295        testObj2->setNewPosition( osg::DegreesToRadians(50.8123), osg::DegreesToRadians(8.94088), 600 );
296        testObj2->loadGeometry( "../models/cessna.osg" );
297        testObj2->addUpdater( new object_updater(testObj2) );
298
299        osg::ref_ptr<visual_object> testObj3 = new visual_object( rootNode, "SAENGER1" );
300        testObj3->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
301        testObj3->loadGeometry( "../models/saenger1.flt" );
302        testObj3->addUpdater( new object_updater(testObj3) );
303       
304
305        osg::ref_ptr<visual_object> testObj4 = new visual_object( rootNode, "SAENGER2" );
306        testObj4->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 650 );
307        testObj4->loadGeometry( "../models/saenger2.flt" );
308        testObj4->addUpdater( new object_updater(testObj4) );
309        testObj4->addLabel("testLabel", "LabelTest!!\nnächste Zeile :)",osg::Vec4(1.0f,0.25f,1.0f,1.0f));
310
311        osg::ref_ptr<visual_object> testObj5 = new visual_object( rootNode, "SAENGER" );
312        testObj5->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 550 );
313        testObj5->loadGeometry( "../models/saengerCombine.flt" );
314        //testObj5->setScale( 2 );
315        testObj5->addUpdater( new object_updater(testObj5) );
316
317#ifdef USE_SPACENAVIGATOR
318        // Manipulatoren auf dieses Objekt binden (Primärobjekt)
319        if (objectMountedCameraManip.valid())
320                objectMountedCameraManip->setAttachedObject( testObj4 );
321        if (mouseTrackerManip.valid())
322        {
323                mouseTrackerManip->setTrackNode( testObj4->getGeometry() );
324                mouseTrackerManip->setMinimumDistance( 100 );
325        }
326#endif
327
328        if(nt.valid())
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
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}
Note: See TracBrowser for help on using the repository browser.