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

Revision 3205, 11.4 kB (checked in by robert, 10 years ago)

Added beginnings of new TrackballManipulator?

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osgProducer/Viewer>
2
3#include <osg/Group>
4#include <osg/Geode>
5#include <osg/ShapeDrawable>
6#include <osg/Texture2D>
7#include <osg/PositionAttitudeTransform>
8#include <osg/MatrixTransform>
9
10#include <osgDB/ReadFile>
11
12#include <osgText/Text>
13
14#include <osgSim/SphereSegment>
15
16#include <osgParticle/ExplosionEffect>
17#include <osgParticle/SmokeEffect>
18#include <osgParticle/FireEffect>
19#include <osgParticle/ParticleSystemUpdater>
20
21#include <osgGA/TrackerManipulator>
22
23// for the grid data..
24#include "../osghangglide/terrain_coords.h"
25
26osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
27{
28    // set up the animation path
29    osg::AnimationPath* animationPath = new osg::AnimationPath;
30    animationPath->setLoopMode(osg::AnimationPath::LOOP);
31   
32    int numSamples = 40;
33    float yaw = 0.0f;
34    float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
35    float roll = osg::inDegrees(30.0f);
36   
37    double time=0.0f;
38    double time_delta = looptime/(double)numSamples;
39    for(int i=0;i<numSamples;++i)
40    {
41        osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
42        osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
43       
44        animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
45
46        yaw += yaw_delta;
47        time += time_delta;
48
49    }
50    return animationPath;   
51}
52
53osg::Node* createMovingModel(const osg::Vec3& center, float radius)
54{
55    float animationLength = 10.0f;
56
57    osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
58
59    osg::Group* model = new osg::Group;
60
61    osg::Node* glider = osgDB::readNodeFile("glider.osg");
62    if (glider)
63    {
64        glider->setName("glider");
65
66        const osg::BoundingSphere& bs = glider->getBound();
67
68        float size = radius/bs.radius()*0.3f;
69        osg::MatrixTransform* positioned = new osg::MatrixTransform;
70        positioned->setDataVariance(osg::Object::STATIC);
71        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
72                                     osg::Matrix::scale(size,size,size)*
73                                     osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));
74   
75        positioned->addChild(glider);
76   
77        osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;   
78        xform->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
79        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));
80        xform->addChild(positioned);
81
82        model->addChild(xform);
83    }
84 
85    osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
86    if (cessna)
87    {
88        cessna->setName("cessna");
89   
90        const osg::BoundingSphere& bs = cessna->getBound();
91
92        osgText::Text* text = new osgText::Text;
93        float size = radius/bs.radius()*0.3f;
94
95        text->setPosition(bs.center());
96        text->setText("Cessna");
97        text->setAlignment(osgText::Text::CENTER_CENTER);
98        text->setAxisAlignment(osgText::Text::SCREEN);
99        text->setCharacterSize(40.0f);
100        text->setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
101       
102        osg::Geode* geode = new osg::Geode;
103        geode->addDrawable(text);
104   
105        osg::LOD* lod = new osg::LOD;
106        lod->setRangeMode(osg::LOD::PIXEL_SIZE_ON_SCREEN);
107        lod->addChild(geode,0.0f,100.0f);
108        lod->addChild(cessna,100.0f,10000.0f);
109
110
111        osg::MatrixTransform* positioned = new osg::MatrixTransform;
112        positioned->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
113        positioned->setDataVariance(osg::Object::STATIC);
114        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
115                                     osg::Matrix::scale(size,size,size)*
116                                     osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));
117   
118        //positioned->addChild(cessna);
119        positioned->addChild(lod);
120   
121        osg::MatrixTransform* xform = new osg::MatrixTransform;
122        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
123        xform->addChild(positioned);
124
125        model->addChild(xform);
126    }
127   
128    return model;
129}
130
131
132osg::Vec3 computeTerrainIntersection(osg::Node* subgraph,float x,float y)
133{
134    osgUtil::IntersectVisitor iv;
135    osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;
136
137    const osg::BoundingSphere& bs = subgraph->getBound();
138    float zMax = bs.center().z()+bs.radius();
139    float zMin = bs.center().z()-bs.radius();
140   
141    segDown->set(osg::Vec3(x,y,zMin),osg::Vec3(x,y,zMax));
142    iv.addLineSegment(segDown.get());
143
144    subgraph->accept(iv);
145
146    if (iv.hits())
147    {
148        osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());
149        if (!hitList.empty())
150        {
151            osg::Vec3 ip = hitList.front().getWorldIntersectPoint();
152            return  ip;
153        }
154    }
155
156    return osg::Vec3(x,y,0.0f);
157}
158
159
160//////////////////////////////////////////////////////////////////////////////
161// MAIN SCENE GRAPH BUILDING FUNCTION
162//////////////////////////////////////////////////////////////////////////////
163
164void build_world(osg::Group *root)
165{
166
167    osg::Geode* terrainGeode = new osg::Geode;
168    // create terrain
169    {
170        osg::StateSet* stateset = new osg::StateSet();
171        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
172        if (image)
173        {
174            osg::Texture2D* texture = new osg::Texture2D;
175            texture->setImage(image);
176            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
177        }
178
179        terrainGeode->setStateSet( stateset );
180
181        float size = 1000; // 10km;
182        float scale = size/39.0f; // 10km;
183        float z_scale = scale*3.0f;
184
185        osg::HeightField* grid = new osg::HeightField;
186        grid->allocateGrid(38,39);
187        grid->setXInterval(scale);
188        grid->setYInterval(scale);
189
190        for(unsigned int r=0;r<39;++r)
191        {
192            for(unsigned int c=0;c<38;++c)
193            {
194                grid->setHeight(c,r,z_scale*vertex[r+c*39][2]);
195            }
196        }
197        terrainGeode->addDrawable(new osg::ShapeDrawable(grid));
198       
199        root->addChild(terrainGeode);
200    }   
201
202    // create sphere segment
203    {
204        osgSim::SphereSegment* ss = new osgSim::SphereSegment(
205                        computeTerrainIntersection(terrainGeode,550.0f,780.0f), // center
206                        500.0f, // radius
207                        osg::DegreesToRadians(135.0f),
208                        osg::DegreesToRadians(245.0f),
209                        osg::DegreesToRadians(-10.0f),
210                        osg::DegreesToRadians(30.0f),
211                        60);
212        ss->setAllColors(osg::Vec4(1.0f,1.0f,1.0f,0.5f));
213        ss->setSideColor(osg::Vec4(0.0f,1.0f,1.0f,0.1f));
214
215        root->addChild(ss);       
216    }
217
218
219    // create particle effects
220    {   
221        osg::PositionAttitudeTransform* positionEffects = new osg::PositionAttitudeTransform;
222        positionEffects->setPosition(computeTerrainIntersection(terrainGeode,100.0f,100.0f));
223        root->addChild(positionEffects);
224
225        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect;
226        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect;
227        osgParticle::FireEffect* fire = new osgParticle::FireEffect;
228
229        osg::Geode* geode = new osg::Geode;
230        geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),10.0f)));
231        positionEffects->addChild(geode);
232
233        positionEffects->addChild(explosion);
234        positionEffects->addChild(smoke);
235        positionEffects->addChild(fire);
236
237        osgParticle::ParticleSystemUpdater *psu = new osgParticle::ParticleSystemUpdater;
238
239        psu->addParticleSystem(explosion->getParticleSystem());
240        psu->addParticleSystem(smoke->getParticleSystem());
241        psu->addParticleSystem(fire->getParticleSystem());
242
243        // add the updater node to the scene graph
244        root->addChild(psu);
245    }
246   
247   
248    // create the moving models.
249    {
250        root->addChild(createMovingModel(osg::Vec3(500.0f,500.0f,500.0f),100.0f));
251    }
252}
253
254class FindNamedNodeVisitor : public osg::NodeVisitor
255{
256public:
257    FindNamedNodeVisitor(const std::string& name):
258        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
259        _name(name) {}
260   
261    virtual void apply(osg::Node& node)
262    {
263        if (node.getName()==_name)
264        {
265            _foundNodes.push_back(&node);
266        }
267        traverse(node);
268    }
269   
270    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;
271
272    std::string _name;
273    NodeList _foundNodes;
274};
275
276
277
278//////////////////////////////////////////////////////////////////////////////
279// main()
280//////////////////////////////////////////////////////////////////////////////
281
282
283int main(int argc, char **argv)
284{
285    // use an ArgumentParser object to manage the program arguments.
286    osg::ArgumentParser arguments(&argc,argv);
287   
288    // set up the usage document, in case we need to print out how to use this program.
289    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
290    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
291    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
292   
293
294    // construct the viewer.
295    osgProducer::Viewer viewer(arguments);
296
297    // set up the value with sensible default event handlers.
298    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
299
300
301
302    // get details on keyboard and mouse bindings used by the viewer.
303    viewer.getUsage(*arguments.getApplicationUsage());
304
305    // if user request help write it out to cout.
306    if (arguments.read("-h") || arguments.read("--help"))
307    {
308        arguments.getApplicationUsage()->write(std::cout);
309        return 1;
310    }
311
312    // any option left unread are converted into errors to write out later.
313    arguments.reportRemainingOptionsAsUnrecognized();
314
315    // report any errors if they have occured when parsing the program aguments.
316    if (arguments.errors())
317    {
318        arguments.writeErrorMessages(std::cout);
319        return 1;
320    }
321   
322    osg::Group *root = new osg::Group;
323    build_world(root);
324   
325    // add a viewport to the viewer and attach the scene graph.
326    viewer.setSceneData(root);
327       
328       
329    FindNamedNodeVisitor fnnv("cessna");
330    root->accept(fnnv);
331   
332    if (!fnnv._foundNodes.empty())
333    {
334        osgGA::TrackerManipulator* tm = new osgGA::TrackerManipulator;
335        tm->setTrackNode(fnnv._foundNodes[0].get());
336       
337        std::cout<<"Found "<<std::endl;
338       
339        unsigned int num = viewer.addCameraManipulator(tm);
340        viewer.selectCameraManipulator(num);
341    }
342
343
344
345    // create the windows and run the threads.
346    viewer.realize();
347
348    while( !viewer.done() )
349    {
350        // wait for all cull and draw threads to complete.
351        viewer.sync();
352
353        // update the scene by traversing it with the the update visitor which will
354        // call all node update callbacks and animations.
355        viewer.update();
356         
357        // fire off the cull and draw traversals of the scene.
358        viewer.frame();
359       
360    }
361   
362    // wait for all cull and draw threads to complete before exit.
363    viewer.sync();
364
365    return 0;
366}
Note: See TracBrowser for help on using the browser.