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

Revision 3977, 12.0 kB (checked in by robert, 10 years ago)

Introduced a flight path that goes around the earth going into the north and sound
hemisphere's with heading and roll adjustment.

  • 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 <osgProducer/Viewer>
20
21#include <osg/Group>
22#include <osg/Geode>
23#include <osg/ShapeDrawable>
24#include <osg/Texture2D>
25#include <osg/PositionAttitudeTransform>
26#include <osg/MatrixTransform>
27#include <osg/CoordinateSystemNode>
28
29#include <osgDB/FileUtils>
30#include <osgDB/ReadFile>
31
32#include <osgText/Text>
33
34#include <osgTerrain/DataSet>
35
36#include <osgGA/NodeTrackerManipulator>
37
38class GraphicsContext {
39    public:
40        GraphicsContext()
41        {
42            rs = new Producer::RenderSurface;
43            rs->setWindowRectangle(0,0,1,1);
44            rs->useBorder(false);
45            rs->useConfigEventThread(false);
46            rs->realize();
47        }
48
49        virtual ~GraphicsContext()
50        {
51        }
52       
53    private:
54        Producer::ref_ptr<Producer::RenderSurface> rs;
55};
56
57osg::Node* createEarth()
58{
59    osg::ref_ptr<osg::Node> scene;
60   
61    {
62        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
63
64        // make osgTerrain::DataSet quieter..
65        osgTerrain::DataSet::setNotifyOffset(1);
66
67        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;
68
69        // register the source imagery
70        {
71            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);
72
73            source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
74            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));
75
76            source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
77            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);
78
79            dataSet->addSource(source);
80        }
81
82        // set up destination database paramters.
83        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
84        dataSet->setConvertFromGeographicToGeocentric(true);
85        dataSet->setDestinationName("test.osg");
86
87        // load the source data and record sizes.
88        dataSet->loadSources();
89
90        GraphicsContext context;
91        dataSet->createDestination(30);
92
93        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
94        else dataSet->writeDestination();
95       
96        scene = dataSet->getDestinationRootNode();
97    }
98       
99    return scene.release();
100   
101}
102
103
104class ModelPositionCallback : public osg::NodeCallback
105{
106public:
107
108    ModelPositionCallback():
109        _latitude(0.0),
110        _longitude(0.0),
111        _height(100000.0)
112    {
113        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
114    }
115   
116    void updateParameters()
117    {
118        _longitude += ((2.0*osg::PI)/360.0)/20.0;
119        _latitude = sin(_longitude);
120
121        // adjust the heading and roll to roughly look ok,
122        // but bearing no reality to physics..       
123        osg::Quat heading;
124        heading.makeRotate(osg::DegreesToRadians(90.0)+cos(_longitude),0.0,0.0,1.0);
125       
126        osg::Quat roll;
127        roll.makeRotate(-_latitude*0.5f,0.0,1.0,0.0);
128       
129        _rotation = roll*heading;
130    }
131
132
133    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
134    {
135        updateParameters();
136       
137        osg::NodePath nodePath = nv->getNodePath();
138
139        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
140        if (mt)
141        {
142            osg::CoordinateSystemNode* csn = 0;
143
144            // find coordinate system node from our parental chain
145            unsigned int i;
146            for(i=0; i<nodePath.size() && csn==0; ++i)
147            {
148                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
149            }
150           
151            if (csn)
152            {
153
154
155                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
156                if (ellipsoid)
157                {
158                    osg::Matrixd matrix;
159                    for(i+=1; i<nodePath.size()-1; ++i)
160                    {
161                        osg::Transform* transform = nodePath[i]->asTransform();
162                        if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
163                    }
164
165                    //osg::Matrixd matrix;
166                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
167                    matrix.preMult(osg::Matrixd::rotate(_rotation));
168                   
169                    mt->setMatrix(matrix);
170                }
171
172            }       
173        }
174           
175        traverse(node,nv);
176    }   
177   
178    double                  _latitude;
179    double                  _longitude;
180    double                  _height;
181    osg::Quat               _rotation;
182};
183
184
185class FindNamedNodeVisitor : public osg::NodeVisitor
186{
187public:
188    FindNamedNodeVisitor(const std::string& name):
189        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
190        _name(name) {}
191   
192    virtual void apply(osg::Node& node)
193    {
194        if (node.getName()==_name)
195        {
196            _foundNodes.push_back(&node);
197        }
198        traverse(node);
199    }
200   
201    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;
202
203    std::string _name;
204    NodeList _foundNodes;
205};
206
207
208int main(int argc, char **argv)
209{
210    // use an ArgumentParser object to manage the program arguments.
211    osg::ArgumentParser arguments(&argc,argv);
212   
213    // set up the usage document, in case we need to print out how to use this program.
214    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
215    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
216    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
217    arguments.getApplicationUsage()->addCommandLineOption("--rotate-model angle x y z","Rotate model");
218    arguments.getApplicationUsage()->addCommandLineOption("--flight-path","");
219    arguments.getApplicationUsage()->addCommandLineOption("--tracker-mode","NODE_CENTER_AND_ROTATION | NODE_CENTER_AND_AZIM | NODE_CENTER");
220    arguments.getApplicationUsage()->addCommandLineOption("--rotation-mode","TRACKBALL | ELEVATION_AZIM");
221   
222
223    // construct the viewer.
224    osgProducer::Viewer viewer(arguments);
225
226    // set up the value with sensible default event handlers.
227    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
228
229    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
230    viewer.getCullSettings().setNearFarRatio(0.00001f);
231
232    // get details on keyboard and mouse bindings used by the viewer.
233    viewer.getUsage(*arguments.getApplicationUsage());
234
235    osg::Quat rotation;
236    osg::Vec4 vec4;
237    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
238    {
239        osg::Quat local_rotate;
240        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);
241       
242        rotation = rotation * local_rotate;
243    }
244
245    osg::NodeCallback* nc = 0;
246    std::string flightpath_filename;
247    while (arguments.read("--flight-path",flightpath_filename))
248    {
249        std::ifstream fin(flightpath_filename.c_str());
250        if (fin)
251        {
252            osg::AnimationPath* path = new osg::AnimationPath;
253            path->read(fin);
254            nc = new osg::AnimationPathCallback(path);
255        }
256    }
257   
258    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
259    std::string mode;
260    while (arguments.read("--tracker-mode",mode))
261    {
262        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
263        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
264        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
265        else
266        {
267            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
268            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
269            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
270            std::cout<<"    NODE_CENTER"<<std::endl;
271            return 1;
272        }
273    }
274   
275   
276    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
277    while (arguments.read("--rotation-mode",mode))
278    {
279        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
280        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
281        else
282        {
283            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
284            std::cout<<"    TRACKBALL"<<std::endl;
285            std::cout<<"    ELEVATION_AZIM"<<std::endl;
286            return 1;
287        }
288    }
289
290    // if user request help write it out to cout.
291    if (arguments.read("-h") || arguments.read("--help"))
292    {
293        arguments.getApplicationUsage()->write(std::cout);
294        return 1;
295    }
296
297    // any option left unread are converted into errors to write out later.
298    arguments.reportRemainingOptionsAsUnrecognized();
299
300    // report any errors if they have occured when parsing the program aguments.
301    if (arguments.errors())
302    {
303        arguments.writeErrorMessages(std::cout);
304        return 1;
305    }
306   
307    osg::ref_ptr<osg::Node> root = createEarth();
308   
309    if (!root) return 0;
310
311    // add a viewport to the viewer and attach the scene graph.
312    viewer.setSceneData(root.get());
313
314    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
315    if (csn)
316    {
317        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
318        if (cessna)
319        {
320            double s = 30000.0 / cessna->getBound().radius();
321       
322            osg::MatrixTransform* scaler = new osg::MatrixTransform;
323            scaler->addChild(cessna);
324            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
325            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);       
326       
327            osg::MatrixTransform* mt = new osg::MatrixTransform;
328            mt->addChild(scaler);
329
330
331            if (!nc) nc = new ModelPositionCallback;
332
333            mt->setUpdateCallback(nc);
334
335            csn->addChild(mt);
336
337            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
338            tm->setTrackerMode(trackerMode);
339            tm->setRotationMode(rotationMode);
340            tm->setTrackNode(scaler);
341
342            unsigned int num = viewer.addCameraManipulator(tm);
343            viewer.selectCameraManipulator(num);
344        }
345        else
346        {
347             std::cout<<"Failed to read cessna.osg"<<std::endl;
348        }
349    }   
350
351       
352
353    // create the windows and run the threads.
354    viewer.realize();
355
356    while( !viewer.done() )
357    {
358        // wait for all cull and draw threads to complete.
359        viewer.sync();
360
361        // update the scene by traversing it with the the update visitor which will
362        // call all node update callbacks and animations.
363        viewer.update();
364         
365        // fire off the cull and draw traversals of the scene.
366        viewer.frame();
367       
368    }
369   
370    // wait for all cull and draw threads to complete before exit.
371    viewer.sync();
372
373    return 0;
374}
Note: See TracBrowser for help on using the browser.