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

Revision 6858, 13.9 kB (checked in by robert, 8 years ago)

Moved HelpHandler? and StatsHandler? classes into ViewerEventHandlers? header, removed HelpHandler? and StatsHandler? headers

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