root/OpenSceneGraph/trunk/examples/osgsimulation/osgsimulation.cpp @ 6941

Revision 6941, 16.9 kB (checked in by robert, 8 years ago)

From Martin Lavery and Robert Osfield, Updated examples to use a variation of the MIT License

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osgsimulation.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19#ifdef WIN32
20/////////////////////////////////////////////////////////////////////////////
21// Disable unavoidable warning messages:
22
23//  4103: used #pragma pack to change alignment
24//  4114: same type qualifier used more than once
25//  4201: nonstandard extension used : nameless struct/union
26//  4237: "keyword" reserved for future use
27//  4251: class needs to have dll-interface to export class
28//  4275: non DLL-interface class used as base for DLL-interface class
29//  4290: C++ Exception Specification ignored
30//  4503: decorated name length exceeded, name was truncated
31//  4786: string too long - truncated to 255 characters
32
33#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)
34
35#endif // WIN32
36
37#include <osgViewer/Viewer>
38#include <osgViewer/ViewerEventHandlers>
39
40#include <osg/Group>
41#include <osg/Geode>
42#include <osg/ShapeDrawable>
43#include <osg/Texture2D>
44#include <osg/PositionAttitudeTransform>
45#include <osg/MatrixTransform>
46#include <osg/CoordinateSystemNode>
47
48#include <osgDB/FileUtils>
49#include <osgDB/ReadFile>
50
51#include <osgText/Text>
52
53#include <osg/CoordinateSystemNode>
54
55#include <osgSim/OverlayNode>
56#include <osgSim/SphereSegment>
57
58#include <osgGA/NodeTrackerManipulator>
59#include <osgGA/StateSetManipulator>
60#include <osgGA/TrackballManipulator>
61#include <osgGA/FlightManipulator>
62#include <osgGA/DriveManipulator>
63#include <osgGA/KeySwitchMatrixManipulator>
64#include <osgGA/AnimationPathManipulator>
65#include <osgGA/TerrainManipulator>
66
67#include <iostream>
68
69osg::Node* createEarth()
70{
71    osg::TessellationHints* hints = new osg::TessellationHints;
72    hints->setDetailRatio(5.0f);
73
74   
75    osg::ShapeDrawable* sd = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0,0.0,0.0), osg::WGS_84_RADIUS_POLAR), hints);
76   
77    osg::Geode* geode = new osg::Geode;
78    geode->addDrawable(sd);
79   
80    std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
81    geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile(filename)));
82   
83    osg::CoordinateSystemNode* csn = new osg::CoordinateSystemNode;
84    csn->setEllipsoidModel(new osg::EllipsoidModel());
85    csn->addChild(geode);
86   
87    return csn;
88   
89}
90
91
92class ModelPositionCallback : public osg::NodeCallback
93{
94public:
95
96    ModelPositionCallback(double speed):
97        _latitude(0.0),
98        _longitude(0.0),
99        _height(100000.0),
100        _speed(speed)
101    {
102        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
103    }
104   
105    void updateParameters()
106    {
107        _longitude += _speed * ((2.0*osg::PI)/360.0)/20.0;
108    }
109
110
111    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
112    {
113        updateParameters();
114       
115        osg::NodePath nodePath = nv->getNodePath();
116
117        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
118        if (mt)
119        {
120            osg::CoordinateSystemNode* csn = 0;
121
122            // find coordinate system node from our parental chain
123            unsigned int i;
124            for(i=0; i<nodePath.size() && csn==0; ++i)
125            {
126                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
127            }
128           
129            if (csn)
130            {
131
132
133                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
134                if (ellipsoid)
135                {
136                    osg::Matrix inheritedMatrix;
137                    for(i+=1; i<nodePath.size()-1; ++i)
138                    {
139                        osg::Transform* transform = nodePath[i]->asTransform();
140                        if (transform) transform->computeLocalToWorldMatrix(inheritedMatrix, nv);
141                    }
142                   
143                    osg::Matrixd matrix(inheritedMatrix);
144
145                    //osg::Matrixd matrix;
146                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
147                    matrix.preMult(osg::Matrix::rotate(_rotation));
148                   
149                    mt->setMatrix(matrix);
150                }
151
152            }       
153        }
154           
155        traverse(node,nv);
156    }   
157   
158    double                  _latitude;
159    double                  _longitude;
160    double                  _height;
161    osg::Quat               _rotation;
162    double                  _speed;
163};
164
165
166class FindNamedNodeVisitor : public osg::NodeVisitor
167{
168public:
169    FindNamedNodeVisitor(const std::string& name):
170        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
171        _name(name) {}
172   
173    virtual void apply(osg::Node& node)
174    {
175        if (node.getName()==_name)
176        {
177            _foundNodes.push_back(&node);
178        }
179        traverse(node);
180    }
181   
182    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;
183
184    std::string _name;
185    NodeList _foundNodes;
186};
187
188
189int main(int argc, char **argv)
190{
191    // use an ArgumentParser object to manage the program arguments.
192    osg::ArgumentParser arguments(&argc,argv);
193   
194    // set up the usage document, in case we need to print out how to use this program.
195    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of node tracker.");
196    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
197    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
198   
199
200    // construct the viewer.
201    osgViewer::Viewer viewer;
202
203    // add the state manipulator
204    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
205   
206    // add the thread model handler
207    viewer.addEventHandler(new osgViewer::ThreadingHandler);
208
209    // add the window size toggle handler
210    viewer.addEventHandler(new osgViewer::WindowSizeHandler);
211       
212    // add the stats handler
213    viewer.addEventHandler(new osgViewer::StatsHandler);
214       
215    // add the record camera path  handler
216    viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);
217
218    // add the help handler
219    viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
220
221    // set the near far ration computation up.
222    viewer.getCamera()->setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
223    viewer.getCamera()->setNearFarRatio(0.000003f);
224
225
226    double speed = 1.0;
227    while (arguments.read("-f") || arguments.read("--fixed")) speed = 0.0;
228
229
230    osg::Quat rotation;
231    osg::Vec4 vec4;
232    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
233    {
234        osg::Quat local_rotate;
235        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);
236       
237        rotation = rotation * local_rotate;
238    }
239
240    osg::NodeCallback* nc = 0;
241    std::string flightpath_filename;
242    while (arguments.read("--flight-path",flightpath_filename))
243    {
244        std::ifstream fin(flightpath_filename.c_str());
245        if (fin)
246        {
247            osg::AnimationPath* path = new osg::AnimationPath;
248            path->read(fin);
249            nc = new osg::AnimationPathCallback(path);
250        }
251    }
252   
253    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
254    std::string mode;
255    while (arguments.read("--tracker-mode",mode))
256    {
257        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
258        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
259        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
260        else
261        {
262            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
263            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
264            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
265            std::cout<<"    NODE_CENTER"<<std::endl;
266            return 1;
267        }
268    }
269   
270   
271    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
272    while (arguments.read("--rotation-mode",mode))
273    {
274        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
275        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
276        else
277        {
278            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
279            std::cout<<"    TRACKBALL"<<std::endl;
280            std::cout<<"    ELEVATION_AZIM"<<std::endl;
281            return 1;
282        }
283    }
284
285    bool useOverlay = true;
286    while (arguments.read("--no-overlay") || arguments.read("-n")) useOverlay = false;
287   
288    osgSim::OverlayNode::OverlayTechnique technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
289    while (arguments.read("--object")) technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
290    while (arguments.read("--ortho") || arguments.read("--orthographic")) technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
291    while (arguments.read("--persp") || arguments.read("--perspective")) technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY;
292
293    unsigned int screenNum = 0;   
294    while (arguments.read("--screen", screenNum) || arguments.read("-s", screenNum)) viewer.setUpViewOnSingleScreen(screenNum);
295
296    std::string pathfile;
297    while (arguments.read("-p",pathfile)) {}
298
299
300    // if user request help write it out to cout.
301    if (arguments.read("-h") || arguments.read("--help"))
302    {
303        arguments.getApplicationUsage()->write(std::cout);
304        return 1;
305    }
306   
307   
308    osg::ref_ptr<osgGA::NodeTrackerManipulator> tm;
309   
310    std::string overlayFilename;
311    while(arguments.read("--overlay", overlayFilename)) {}
312
313    // read the scene from the list of file specified commandline args.
314    osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(arguments);
315
316    if (!root) root = createEarth();
317
318    if (!root) return 0;
319
320
321    if (!overlayFilename.empty())
322    {
323        //osg::Object *pObj = osgDB::readObjectFile("alaska_clean.shp");
324        //osg::ref_ptr<osg::Geode> shapefile = dynamic_cast<osg::Geode*> (pObj);
325        //
326        //ConvertLatLon2EllipsoidCoordinates latlon2em;
327        //shapefile->accept(latlon2em);
328
329        osg::ref_ptr<osg::Node> shapefile = osgDB::readNodeFile(overlayFilename);
330       
331        if (!shapefile)
332        {
333            osg::notify(osg::NOTICE)<<"File `"<<overlayFilename<<"` not found"<<std::endl;
334            return 1;
335        }
336
337        osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
338        if (csn)
339        {
340
341            osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode(technique);
342            overlayNode->getOrCreateStateSet()->setTextureAttribute(1, new osg::TexEnv(osg::TexEnv::DECAL));
343            overlayNode->setOverlaySubgraph(shapefile.get());
344            overlayNode->setOverlayTextureSizeHint(1024);
345
346            // insert the OverlayNode between the coordinate system node and its children.
347            for(unsigned int i=0; i<csn->getNumChildren(); ++i)
348            {
349                overlayNode->addChild( csn->getChild(i) );
350            }
351
352            csn->removeChildren(0, csn->getNumChildren());
353            csn->addChild(overlayNode);
354
355            viewer.setSceneData(csn);
356        }
357        else
358        {
359            osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode(technique);
360            overlayNode->getOrCreateStateSet()->setTextureAttribute(1, new osg::TexEnv(osg::TexEnv::DECAL));
361            overlayNode->setOverlaySubgraph(shapefile.get());
362            overlayNode->setOverlayTextureSizeHint(1024);
363            overlayNode->addChild(root.get());
364
365            viewer.setSceneData(overlayNode);
366        }
367    }
368    else
369    {
370   
371
372        // add a viewport to the viewer and attach the scene graph.
373        viewer.setSceneData(root.get());
374
375        osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
376        if (csn)
377        {
378
379            osg::ref_ptr<osgSim::OverlayNode> overlayNode;
380            if (useOverlay)
381            {
382                overlayNode = new osgSim::OverlayNode(technique);
383
384                // insert the OverlayNode between the coordinate system node and its children.
385                for(unsigned int i=0; i<csn->getNumChildren(); ++i)
386                {
387                    overlayNode->addChild( csn->getChild(i) );
388                }
389
390                csn->removeChildren(0, csn->getNumChildren());
391                csn->addChild(overlayNode.get());
392
393                // tell the overlay node to continously update its overlay texture
394                // as we know we'll be tracking a moving target.
395                overlayNode->setContinuousUpdate(true);
396            }
397
398
399            osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
400            if (cessna)
401            {
402                double s = 200000.0 / cessna->getBound().radius();
403
404                osg::MatrixTransform* scaler = new osg::MatrixTransform;
405                scaler->addChild(cessna);
406                scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
407                scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);       
408
409                if (false)
410                {
411                    osgSim::SphereSegment* ss = new osgSim::SphereSegment(
412                                        osg::Vec3(0.0f,0.0f,0.0f), // center
413                                        19.9f, // radius
414                                        osg::DegreesToRadians(135.0f),
415                                        osg::DegreesToRadians(240.0f),
416                                        osg::DegreesToRadians(-10.0f),
417                                        osg::DegreesToRadians(30.0f),
418                                        60);
419
420                    scaler->addChild(ss);
421                }
422
423                osg::MatrixTransform* mt = new osg::MatrixTransform;
424                mt->addChild(scaler);
425
426
427                if (!nc) nc = new ModelPositionCallback(speed);
428
429                mt->setUpdateCallback(nc);
430
431                csn->addChild(mt);
432
433                // if we are using an overaly node, use the cessna subgraph as the overlay subgraph
434                if (overlayNode.valid())
435                {
436                    overlayNode->setOverlaySubgraph(mt);
437                }
438
439                tm = new osgGA::NodeTrackerManipulator;
440                tm->setTrackerMode(trackerMode);
441                tm->setRotationMode(rotationMode);
442                tm->setTrackNode(scaler);
443            }
444            else
445            {
446                 std::cout<<"Failed to read cessna.osg"<<std::endl;
447            }
448
449        }   
450    }
451
452    // set up camera manipulators.
453    {
454        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
455
456        if (tm.valid()) keyswitchManipulator->addMatrixManipulator( '0', "NodeTracker", tm.get() );
457
458        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
459        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
460        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
461        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
462
463        if (!pathfile.empty())
464        {
465            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
466            if (apm || !apm->valid())
467            {
468                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
469                keyswitchManipulator->addMatrixManipulator( '5', "Path", apm );
470                keyswitchManipulator->selectMatrixManipulator(num);
471            }
472        }
473
474        viewer.setCameraManipulator( keyswitchManipulator.get() );
475    }
476
477    // viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
478
479    return viewer.run();
480}
Note: See TracBrowser for help on using the browser.