root/OpenSceneGraph/trunk/examples/osgspheresegment/osgspheresegment.cpp @ 4525

Revision 4525, 15.8 kB (checked in by robert, 9 years ago)

Added line connectivity code.

  • 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#include <osg/Geometry>
10
11#include <osgUtil/SmoothingVisitor>
12
13#include <osgDB/ReadFile>
14
15#include <osgText/Text>
16
17#include <osgSim/SphereSegment>
18#include <osgSim/OverlayNode>
19
20#include <osgParticle/ExplosionEffect>
21#include <osgParticle/SmokeEffect>
22#include <osgParticle/FireEffect>
23#include <osgParticle/ParticleSystemUpdater>
24
25// for the grid data..
26#include "../osghangglide/terrain_coords.h"
27
28osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
29{
30    // set up the animation path
31    osg::AnimationPath* animationPath = new osg::AnimationPath;
32    animationPath->setLoopMode(osg::AnimationPath::LOOP);
33   
34    int numSamples = 40;
35    float yaw = 0.0f;
36    float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
37    float roll = osg::inDegrees(30.0f);
38   
39    double time=0.0f;
40    double time_delta = looptime/(double)numSamples;
41    for(int i=0;i<numSamples;++i)
42    {
43        osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
44        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)));
45       
46        animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
47
48        yaw += yaw_delta;
49        time += time_delta;
50
51    }
52    return animationPath;   
53}
54
55osg::Node* createMovingModel(const osg::Vec3& center, float radius)
56{
57    float animationLength = 10.0f;
58
59    osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
60
61    osg::Group* model = new osg::Group;
62
63    osg::Node* glider = osgDB::readNodeFile("glider.osg");
64    if (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        const osg::BoundingSphere& bs = cessna->getBound();
89
90        osgText::Text* text = new osgText::Text;
91        float size = radius/bs.radius()*0.3f;
92
93        text->setPosition(bs.center());
94        text->setText("Cessna");
95        text->setAlignment(osgText::Text::CENTER_CENTER);
96        text->setAxisAlignment(osgText::Text::SCREEN);
97        text->setCharacterSize(40.0f);
98        text->setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
99       
100        osg::Geode* geode = new osg::Geode;
101        geode->addDrawable(text);
102   
103        osg::LOD* lod = new osg::LOD;
104        lod->setRangeMode(osg::LOD::PIXEL_SIZE_ON_SCREEN);
105        lod->addChild(geode,0.0f,100.0f);
106        lod->addChild(cessna,100.0f,10000.0f);
107
108
109        osg::MatrixTransform* positioned = new osg::MatrixTransform;
110        positioned->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
111        positioned->setDataVariance(osg::Object::STATIC);
112        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
113                                     osg::Matrix::scale(size,size,size)*
114                                     osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));
115   
116        //positioned->addChild(cessna);
117        positioned->addChild(lod);
118   
119        osg::MatrixTransform* xform = new osg::MatrixTransform;
120        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
121        xform->addChild(positioned);
122
123        // add particle effects to cessna.
124        {
125            osg::PositionAttitudeTransform* positionEffects = new osg::PositionAttitudeTransform;
126            positionEffects->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
127            xform->addChild(positionEffects);
128
129            osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect;
130            osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect;
131            osgParticle::FireEffect* fire = new osgParticle::FireEffect;
132
133            positionEffects->addChild(explosion);
134            positionEffects->addChild(smoke);
135            positionEffects->addChild(fire);
136        }
137       
138        model->addChild(xform);
139    }
140   
141    return model;
142}
143
144osg::Group* createOverlay(const osg::Vec3& center, float radius)
145{
146    osg::Group* group = new osg::Group;
147   
148    // create a grid of lines.
149    {
150        osg::Geometry* geom = new osg::Geometry;
151       
152        unsigned int num_rows = 10;
153
154        osg::Vec3 left = center+osg::Vec3(-radius,-radius,0.0f);
155        osg::Vec3 right = center+osg::Vec3(radius,-radius,0.0f);
156        osg::Vec3 delta_row = osg::Vec3(0.0f,2.0f*radius/float(num_rows-1),0.0f);
157
158        osg::Vec3 top = center+osg::Vec3(-radius,radius,0.0f);
159        osg::Vec3 bottom = center+osg::Vec3(-radius,-radius,0.0f);
160        osg::Vec3 delta_column = osg::Vec3(2.0f*radius/float(num_rows-1),0.0f,0.0f);
161
162        osg::Vec3Array* vertices = new osg::Vec3Array;
163        for(unsigned int i=0; i<num_rows; ++i)
164        {
165            vertices->push_back(left);
166            vertices->push_back(right);
167            left += delta_row;
168            right += delta_row;
169
170            vertices->push_back(top);
171            vertices->push_back(bottom);
172            top += delta_column;
173            bottom += delta_column;
174        }
175       
176        geom->setVertexArray(vertices);
177        geom->addPrimitiveSet(new osg::DrawArrays(GL_LINES,0,vertices->getNumElements()));
178
179        osg::Geode* geode = new osg::Geode;
180        geode->addDrawable(geom);
181        group->addChild(geode);       
182    }
183   
184    return group;
185}
186
187osg::Vec3 computeTerrainIntersection(osg::Node* subgraph,float x,float y)
188{
189    osgUtil::IntersectVisitor iv;
190    osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;
191
192    const osg::BoundingSphere& bs = subgraph->getBound();
193    float zMax = bs.center().z()+bs.radius();
194    float zMin = bs.center().z()-bs.radius();
195   
196    segDown->set(osg::Vec3(x,y,zMin),osg::Vec3(x,y,zMax));
197    iv.addLineSegment(segDown.get());
198
199    subgraph->accept(iv);
200
201    if (iv.hits())
202    {
203        osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());
204        if (!hitList.empty())
205        {
206            osg::Vec3 ip = hitList.front().getWorldIntersectPoint();
207            return  ip;
208        }
209    }
210
211    return osg::Vec3(x,y,0.0f);
212}
213
214
215//////////////////////////////////////////////////////////////////////////////
216// MAIN SCENE GRAPH BUILDING FUNCTION
217//////////////////////////////////////////////////////////////////////////////
218
219void build_world(osg::Group *root)
220{
221
222    // create terrain
223    osg::ref_ptr<osg::Geode> terrainGeode = 0;
224    {
225        terrainGeode = new osg::Geode;
226
227        osg::StateSet* stateset = new osg::StateSet();
228        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
229        if (image)
230        {
231            osg::Texture2D* texture = new osg::Texture2D;
232            texture->setImage(image);
233            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
234        }
235
236        terrainGeode->setStateSet( stateset );
237
238       
239        {
240            unsigned int numColumns = 38;
241            unsigned int numRows = 39;
242            unsigned int r, c;
243           
244            osg::Vec3 origin(0.0f,0.0f,0.0f);
245            osg::Vec3 size(1000.0f,1000.0f,250.0f);
246
247            osg::Geometry* geometry = new osg::Geometry;
248
249            osg::Vec3Array& v = *(new osg::Vec3Array(numColumns*numRows));
250            osg::Vec2Array& tc = *(new osg::Vec2Array(numColumns*numRows));
251            osg::Vec4ubArray& color = *(new osg::Vec4ubArray(1));
252
253            color[0].set(255,255,255,255);
254
255            float rowCoordDelta = size.y()/(float)(numRows-1);
256            float columnCoordDelta = size.x()/(float)(numColumns-1);
257
258            float rowTexDelta = 1.0f/(float)(numRows-1);
259            float columnTexDelta = 1.0f/(float)(numColumns-1);
260
261            // compute z range of z values of grid data so we can scale it.
262            float min_z = FLT_MAX;
263            float max_z = -FLT_MAX;
264            for(r=0;r<numRows;++r)
265            {
266                for(c=0;c<numColumns;++c)
267                {
268                    min_z = osg::minimum(min_z,vertex[r+c*numRows][2]);
269                    max_z = osg::maximum(max_z,vertex[r+c*numRows][2]);
270                }
271            }
272
273            float scale_z = size.z()/(max_z-min_z);
274
275            osg::Vec3 pos = origin;
276            osg::Vec2 tex(0.0f,0.0f);
277            int vi=0;
278            for(r=0;r<numRows;++r)
279            {
280                pos.x() = origin.x();
281                tex.x() = 0.0f;
282                for(c=0;c<numColumns;++c)
283                {
284                    v[vi].set(pos.x(),pos.y(),pos.z()+(vertex[r+c*numRows][2]-min_z)*scale_z);
285                    tc[vi] = tex;
286                    pos.x()+=columnCoordDelta;
287                    tex.x()+=columnTexDelta;
288                    ++vi;
289                }
290                pos.y() += rowCoordDelta;
291                tex.y() += rowTexDelta;
292            }
293
294            geometry->setVertexArray(&v);
295            geometry->setTexCoordArray(0, &tc);
296            geometry->setColorArray(&color);
297            geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
298
299            for(r=0;r<numRows-1;++r)
300            {
301                osg::DrawElementsUShort& drawElements = *(new osg::DrawElementsUShort(GL_QUAD_STRIP,2*numColumns));
302                geometry->addPrimitiveSet(&drawElements);
303                int ei=0;
304                for(c=0;c<numColumns;++c)
305                {
306                    drawElements[ei++] = (r+1)*numColumns+c;
307                    drawElements[ei++] = (r)*numColumns+c;
308                }
309            }
310           
311            osgUtil::SmoothingVisitor smoother;
312            smoother.smooth(*geometry);
313           
314            terrainGeode->addDrawable(geometry);
315        }
316       
317    }   
318
319
320    // create sphere segment
321    osg::ref_ptr<osgSim::SphereSegment> ss = 0;
322    {
323        ss = new osgSim::SphereSegment(
324                        computeTerrainIntersection(terrainGeode.get(),550.0f,780.0f), // center
325                        500.0f, // radius
326                        osg::DegreesToRadians(135.0f),
327                        osg::DegreesToRadians(245.0f),
328                        osg::DegreesToRadians(-10.0f),
329                        osg::DegreesToRadians(30.0f),
330                        60);
331        ss->setAllColors(osg::Vec4(1.0f,1.0f,1.0f,0.5f));
332        ss->setSideColor(osg::Vec4(0.0f,1.0f,1.0f,0.1f));
333
334        root->addChild(ss.get());
335    }
336
337    osgSim::SphereSegment::LineList lines = ss->computeIntersection(osg::Matrixd::identity(), terrainGeode.get());
338    if (!lines.empty())
339    {
340        osg::notify(osg::NOTICE)<<"We've found intersections!!!!"<<std::endl;
341
342        osg::Geode* geode = new osg::Geode;
343        root->addChild(geode);
344
345        geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
346
347        for(osgSim::SphereSegment::LineList::iterator itr=lines.begin();
348           itr!=lines.end();
349           ++itr)
350        {
351            osg::Geometry* geom = new osg::Geometry;
352            geode->addDrawable(geom);
353           
354            osg::Vec3Array* vertices = itr->get();
355            geom->setVertexArray(vertices);
356            geom->addPrimitiveSet(new osg::DrawArrays(GL_LINE_STRIP, 0, vertices->getNumElements()));
357        }
358    }
359    else
360    {
361       osg::notify(osg::NOTICE)<<"No intersections found"<<std::endl;
362    }
363
364#if 1
365
366
367    osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode;
368
369    const osg::BoundingSphere& bs = terrainGeode->getBound();
370    osg::Group* overlaySubgraph = createOverlay(bs.center(), bs.radius()*0.5f);
371    overlaySubgraph->addChild(ss.get());
372    overlayNode->setOverlaySubgraph(overlaySubgraph);
373    overlayNode->setOverlayTextureSizeHint(2048);
374    overlayNode->addChild(terrainGeode.get());
375
376    root->addChild(overlayNode);
377   
378   
379#else
380    root->addChild(terrainGeode);
381#endif
382
383
384    // create particle effects
385    {   
386        osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),100.0f,100.0f);
387
388        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 10.0f);
389        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 10.0f);
390        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 10.0f);
391
392        root->addChild(explosion);
393        root->addChild(smoke);
394        root->addChild(fire);
395    }
396   
397    // create particle effects
398    {   
399        osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),200.0f,100.0f);
400
401        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 1.0f);
402        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 1.0f);
403        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 1.0f);
404
405        root->addChild(explosion);
406        root->addChild(smoke);
407        root->addChild(fire);
408    }
409   
410    // create the moving models.
411    {
412        root->addChild(createMovingModel(osg::Vec3(500.0f,500.0f,500.0f),100.0f));
413    }
414}
415
416
417//////////////////////////////////////////////////////////////////////////////
418// main()
419//////////////////////////////////////////////////////////////////////////////
420
421
422int main(int argc, char **argv)
423{
424    // use an ArgumentParser object to manage the program arguments.
425    osg::ArgumentParser arguments(&argc,argv);
426   
427    // set up the usage document, in case we need to print out how to use this program.
428    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
429    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
430    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
431   
432
433    // construct the viewer.
434    osgProducer::Viewer viewer(arguments);
435
436    // set up the value with sensible default event handlers.
437    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
438
439    // get details on keyboard and mouse bindings used by the viewer.
440    viewer.getUsage(*arguments.getApplicationUsage());
441
442    // if user request help write it out to cout.
443    if (arguments.read("-h") || arguments.read("--help"))
444    {
445        arguments.getApplicationUsage()->write(std::cout);
446        return 1;
447    }
448
449    // any option left unread are converted into errors to write out later.
450    arguments.reportRemainingOptionsAsUnrecognized();
451
452    // report any errors if they have occured when parsing the program aguments.
453    if (arguments.errors())
454    {
455        arguments.writeErrorMessages(std::cout);
456        return 1;
457    }
458   
459    osg::Group *root = new osg::Group;
460    build_world(root);
461   
462    // add a viewport to the viewer and attach the scene graph.
463    viewer.setSceneData(root);
464       
465    // create the windows and run the threads.
466    viewer.realize();
467
468    while( !viewer.done() )
469    {
470        // wait for all cull and draw threads to complete.
471        viewer.sync();
472
473        // update the scene by traversing it with the the update visitor which will
474        // call all node update callbacks and animations.
475        viewer.update();
476         
477        // fire off the cull and draw traversals of the scene.
478        viewer.frame();
479       
480    }
481   
482    // wait for all cull and draw threads to complete before exit.
483    viewer.sync();
484
485    return 0;
486}
Note: See TracBrowser for help on using the browser.