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

Last change on this file since 73 was 73, checked in by Torben Dannhauer, 14 years ago
File size: 13.5 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                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        viewer->updateTraversal();
121               
122        // Render the Frame.
123        viewer->renderingTraversals();
124
125    }   // END WHILE
126}
127
128void visual_core::shutdown()
129{
130        OSG_NOTIFY( osg::ALWAYS ) << "Shutdown visual_core..." << std::endl;
131
132        // Unset scene data
133        viewer->setSceneData( NULL );
134
135#ifdef USE_SKY_SILVERLINING
136        // Shutdown sky
137        if( sky.valid() )
138                sky->shutdown();
139#endif
140
141#ifdef USE_DISTORTION
142        // Shutdown distortion
143        if( distortion.valid() )
144                distortion->shutdown();
145#endif
146
147        // Shutdown dataIO
148        visual_dataIO::getInstance()->shutdown();
149
150       
151#ifdef USE_SPACENAVIGATOR
152        //Delete SpaceMouse driver
153        if(mouse)
154        {
155                mouse->shutdown();
156                delete mouse;
157        }
158#endif
159}
160
161bool visual_core::loadTerrain(osg::ArgumentParser& arguments_)
162{
163        osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments_);
164        if( model.valid() )
165        {
166        rootNode->addChild( model.get() );
167                return true;
168        }
169        else
170        {
171        OSG_NOTIFY( osg::FATAL ) << "Load terrain: No data loaded" << std::endl;
172        return false;
173    }   
174
175        return false;
176}
177
178void visual_core::addManipulators()
179{
180        if(!visual_dataIO::getInstance()->isSlave()) // set up the camera manipulators if not slave.
181    {
182        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
183
184        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
185        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
186        keyswitchManipulator->addMatrixManipulator( '3', "Terrain", new osgGA::TerrainManipulator() );
187                nt = new osgGA::NodeTrackerManipulator();
188                keyswitchManipulator->addMatrixManipulator( '4', "NodeTrackerManipulator", nt );
189               
190#ifdef USE_SPACENAVIGATOR
191                // SpaceNavigator manipulator
192                mouse = new SpaceMouse();
193                mouse->initialize();
194                mouseTrackerManip = new NodeTrackerSpaceMouse(mouse);
195                mouseTrackerManip->setTrackerMode(NodeTrackerSpaceMouse::NODE_CENTER);
196                mouseTrackerManip->setRotationMode(NodeTrackerSpaceMouse::ELEVATION_AZIM);
197                mouseTrackerManip->setAutoComputeHomePosition( true );
198                keyswitchManipulator->addMatrixManipulator( '5', "Spacemouse Node Tracker", mouseTrackerManip );
199                keyswitchManipulator->addMatrixManipulator( '6', "Spacemouse Free (Airplane)", new FreeManipulator(mouse) );
200#endif
201
202                // objectMounted Manipulator for Camera control by Nodes
203                objectMountedCameraManip = new objectMountedManipulator();
204                keyswitchManipulator->addMatrixManipulator( '7', "Object mounted Camera", objectMountedCameraManip );
205
206                // Animation path manipulator
207        std::string pathfile;
208        char keyForAnimationPath = '8';
209        while (arguments.read("-p",pathfile))
210        {
211            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
212            if (apm || !apm->valid()) 
213            {
214                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
215                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
216                keyswitchManipulator->selectMatrixManipulator(num);
217                ++keyForAnimationPath;
218            }
219        }
220
221        viewer->setCameraManipulator( keyswitchManipulator.get() );
222    }   // If not Slave END
223
224    // add the state manipulator
225    viewer->addEventHandler( new osgGA::StateSetManipulator(rootNode->getOrCreateStateSet()) );
226   
227    // add the thread model handler
228    viewer->addEventHandler(new osgViewer::ThreadingHandler);
229
230    // add the window size toggle handler
231    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
232       
233    // add the stats handler
234    viewer->addEventHandler(new osgViewer::StatsHandler);
235
236    // add the help handler
237    viewer->addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
238
239    // add the record camera path handler
240    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);
241
242    // add the LOD Scale handler
243    viewer->addEventHandler(new osgViewer::LODScaleHandler);
244
245    // add the screen capture handler
246    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
247}
248
249
250bool visual_core::checkCommandlineArgumentsForFinalErrors()
251{
252        // Setup Application Usage
253        arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
254        arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the new FSD visualization tool, written by Torben Dannhauer");
255    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] Terrain_filename");
256        arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
257
258    // if user request help write it out to cout.
259    if (arguments.read("-h") || arguments.read("--help"))
260    {
261        arguments.getApplicationUsage()->write(std::cout);
262                //cause the viewer to exit and shut down clean.
263        viewer->setDone(true);
264    }
265
266    // report any errors if they have occurred when parsing the program arguments.
267    if (arguments.errors())
268    {
269        arguments.writeErrorMessages(std::cout);
270                //cause the viewer to exit and shut down clean.
271        viewer->setDone(true);
272    }
273
274         // any option left unread are converted into errors to write out later.
275    arguments.reportRemainingOptionsAsUnrecognized();
276
277    // report any errors if they have occurred when parsing the program arguments.
278    if (arguments.errors())
279    {
280        arguments.writeErrorMessages(std::cout);
281        return false;
282    }
283        return true;
284}
285
286void visual_core::setupScenery()
287{
288        //testObj = new visual_object( rootNode, "testStab", objectMountedCameraManip );
289        //testObj->setNewPosition( osg::DegreesToRadians(47.7123), osg::DegreesToRadians(12.84088), 600 );
290        ///* using a huge cylinder to test position & orientation */
291        //testObj->setGeometry( util::getDemoCylinder(5000.0, 20.0 ) );
292        //testObj->addUpdater( new object_updater(testObj) );
293
294        osg::ref_ptr<visual_object> testObj2 = new visual_object( rootNode, "cessna" );
295        //testObj2->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
296        testObj2->setNewPosition( osg::DegreesToRadians(50.8123), osg::DegreesToRadians(8.94088), 600 );
297        testObj2->loadGeometry( "../models/cessna.osg" );
298        testObj2->addUpdater( new object_updater(testObj2) );
299
300        osg::ref_ptr<visual_object> testObj3 = new visual_object( rootNode, "SAENGER1" );
301        testObj3->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
302        testObj3->loadGeometry( "../models/saenger1.flt" );
303        testObj3->addUpdater( new object_updater(testObj3) );
304       
305
306        osg::ref_ptr<visual_object> testObj4 = new visual_object( rootNode, "SAENGER2" );
307        testObj4->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 650 );
308        testObj4->loadGeometry( "../models/saenger2.flt" );
309        testObj4->addUpdater( new object_updater(testObj4) );
310        testObj4->addLabel("testLabel", "LabelTest!!\nnächste Zeile :)",osg::Vec4(1.0f,0.25f,1.0f,1.0f));
311
312        osg::ref_ptr<visual_object> testObj5 = new visual_object( rootNode, "SAENGER" );
313        testObj5->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 550 );
314        testObj5->loadGeometry( "../models/saengerCombine.flt" );
315        //testObj5->setScale( 2 );
316        testObj5->addUpdater( new object_updater(testObj5) );
317
318#ifdef USE_SPACENAVIGATOR
319        // Manipulatoren auf dieses Objekt binden (Primärobjekt)
320        if (objectMountedCameraManip.valid())
321                objectMountedCameraManip->setAttachedObject( testObj4 );
322        if (mouseTrackerManip.valid())
323        {
324                mouseTrackerManip->setTrackNode( testObj4->getGeometry() );
325                mouseTrackerManip->setMinimumDistance( 100 );
326        }
327#endif
328
329        if(nt.valid())
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
344        // Load EDDF
345        //std::string filename = "D:\\DA\\EDDF_test\\eddf.ive";
346        //if( !osgDB::fileExists(filename) )
347        //{
348        //      OSG_NOTIFY(osg::ALWAYS) << "Warning: EDDF Model not loaded. File '" << filename << "' does not exist. Skipping.";
349        //}
350        //// read model
351        //osg::ref_ptr<osg::Node> tmpModel = osgDB::readNodeFile( filename );
352        //if (tmpModel.valid())
353        //      rootNode->addChild( tmpModel );
354       
355 
356        visual_draw2D::getInstance()->init( rootNode, viewer );
357        //osg::ref_ptr<visual_hud> hud = new visual_hud();
358        osg::ref_ptr<visual_debug_hud> hud = new visual_debug_hud();
359        hud->init( viewer, rootNode );
360       
361
362        //osg::ref_ptr<visual_draw3D> test = new visual_draw3D();
363        //test->init( rootNode, viewer );
364
365        //// Creating Testclasses
366        //osg::ref_ptr<osgVisual::dataIO_transportContainer> test = new osgVisual::dataIO_transportContainer();
367        //osg::ref_ptr<osgVisual::dataIO_executer> testEx = new osgVisual::dataIO_executer();
368        //osg::ref_ptr<osgVisual::dataIO_slot> testSlot = new osgVisual::dataIO_slot();
369        //test->setFrameID( 22 );
370        //test->setName("ugamoep");
371        //testEx->setexecuterID( osgVisual::dataIO_executer::IS_COLLISION );
372        //testSlot->setVariableName(std::string("HalloName"));
373        //testSlot->setdataDirection( osgVisual::dataIO_slot::TO_OBJ );
374        //testSlot->setvarType( osgVisual::dataIO_slot::DOUBLE );
375        //testSlot->setValue( 0.12345 );
376        //test->addExecuter( testEx );
377        //test->addSlot( testSlot );
378
379        visual_dataIO::getInstance()->setSlotData("TestSlot1", osgVisual::dataIO_slot::TO_OBJ, 0.12345);
380}
Note: See TracBrowser for help on using the repository browser.