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

Revision 4539, 16.2 kB (checked in by robert, 9 years ago)

Added TexEnv? DECAL mode.

  • 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
178        osg::Vec4ubArray& color = *(new osg::Vec4ubArray(1));
179        color[0].set(0,0,0,255);
180        geom->setColorArray(&color);
181        geom->setColorBinding(osg::Geometry::BIND_OVERALL);
182
183        geom->addPrimitiveSet(new osg::DrawArrays(GL_LINES,0,vertices->getNumElements()));
184
185        geom->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
186
187        osg::Geode* geode = new osg::Geode;
188        geode->addDrawable(geom);
189        group->addChild(geode);       
190    }
191   
192    return group;
193}
194
195osg::Vec3 computeTerrainIntersection(osg::Node* subgraph,float x,float y)
196{
197    osgUtil::IntersectVisitor iv;
198    osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;
199
200    const osg::BoundingSphere& bs = subgraph->getBound();
201    float zMax = bs.center().z()+bs.radius();
202    float zMin = bs.center().z()-bs.radius();
203   
204    segDown->set(osg::Vec3(x,y,zMin),osg::Vec3(x,y,zMax));
205    iv.addLineSegment(segDown.get());
206
207    subgraph->accept(iv);
208
209    if (iv.hits())
210    {
211        osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());
212        if (!hitList.empty())
213        {
214            osg::Vec3 ip = hitList.front().getWorldIntersectPoint();
215            return  ip;
216        }
217    }
218
219    return osg::Vec3(x,y,0.0f);
220}
221
222
223//////////////////////////////////////////////////////////////////////////////
224// MAIN SCENE GRAPH BUILDING FUNCTION
225//////////////////////////////////////////////////////////////////////////////
226
227void build_world(osg::Group *root)
228{
229
230    // create terrain
231    osg::ref_ptr<osg::Geode> terrainGeode = 0;
232    {
233        terrainGeode = new osg::Geode;
234
235        osg::StateSet* stateset = new osg::StateSet();
236        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
237        if (image)
238        {
239            osg::Texture2D* texture = new osg::Texture2D;
240            texture->setImage(image);
241            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
242        }
243
244        terrainGeode->setStateSet( stateset );
245
246       
247        {
248            unsigned int numColumns = 38;
249            unsigned int numRows = 39;
250            unsigned int r, c;
251           
252            osg::Vec3 origin(0.0f,0.0f,0.0f);
253            osg::Vec3 size(1000.0f,1000.0f,250.0f);
254
255            osg::Geometry* geometry = new osg::Geometry;
256
257            osg::Vec3Array& v = *(new osg::Vec3Array(numColumns*numRows));
258            osg::Vec2Array& tc = *(new osg::Vec2Array(numColumns*numRows));
259            osg::Vec4ubArray& color = *(new osg::Vec4ubArray(1));
260
261            color[0].set(255,255,255,255);
262
263            float rowCoordDelta = size.y()/(float)(numRows-1);
264            float columnCoordDelta = size.x()/(float)(numColumns-1);
265
266            float rowTexDelta = 1.0f/(float)(numRows-1);
267            float columnTexDelta = 1.0f/(float)(numColumns-1);
268
269            // compute z range of z values of grid data so we can scale it.
270            float min_z = FLT_MAX;
271            float max_z = -FLT_MAX;
272            for(r=0;r<numRows;++r)
273            {
274                for(c=0;c<numColumns;++c)
275                {
276                    min_z = osg::minimum(min_z,vertex[r+c*numRows][2]);
277                    max_z = osg::maximum(max_z,vertex[r+c*numRows][2]);
278                }
279            }
280
281            float scale_z = size.z()/(max_z-min_z);
282
283            osg::Vec3 pos = origin;
284            osg::Vec2 tex(0.0f,0.0f);
285            int vi=0;
286            for(r=0;r<numRows;++r)
287            {
288                pos.x() = origin.x();
289                tex.x() = 0.0f;
290                for(c=0;c<numColumns;++c)
291                {
292                    v[vi].set(pos.x(),pos.y(),pos.z()+(vertex[r+c*numRows][2]-min_z)*scale_z);
293                    tc[vi] = tex;
294                    pos.x()+=columnCoordDelta;
295                    tex.x()+=columnTexDelta;
296                    ++vi;
297                }
298                pos.y() += rowCoordDelta;
299                tex.y() += rowTexDelta;
300            }
301
302            geometry->setVertexArray(&v);
303            geometry->setTexCoordArray(0, &tc);
304            geometry->setColorArray(&color);
305            geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
306
307            for(r=0;r<numRows-1;++r)
308            {
309                osg::DrawElementsUShort& drawElements = *(new osg::DrawElementsUShort(GL_QUAD_STRIP,2*numColumns));
310                geometry->addPrimitiveSet(&drawElements);
311                int ei=0;
312                for(c=0;c<numColumns;++c)
313                {
314                    drawElements[ei++] = (r+1)*numColumns+c;
315                    drawElements[ei++] = (r)*numColumns+c;
316                }
317            }
318           
319            osgUtil::SmoothingVisitor smoother;
320            smoother.smooth(*geometry);
321           
322            terrainGeode->addDrawable(geometry);
323        }
324       
325    }   
326
327
328    // create sphere segment
329    osg::ref_ptr<osgSim::SphereSegment> ss = 0;
330    {
331        ss = new osgSim::SphereSegment(
332                        computeTerrainIntersection(terrainGeode.get(),550.0f,780.0f), // center
333                        500.0f, // radius
334                        osg::DegreesToRadians(135.0f),
335                        osg::DegreesToRadians(245.0f),
336                        osg::DegreesToRadians(-10.0f),
337                        osg::DegreesToRadians(30.0f),
338                        60);
339        ss->setAllColors(osg::Vec4(1.0f,1.0f,1.0f,0.5f));
340        ss->setSideColor(osg::Vec4(0.0f,1.0f,1.0f,0.1f));
341
342        root->addChild(ss.get());
343    }
344
345    osgSim::SphereSegment::LineList lines = ss->computeIntersection(osg::Matrixd::identity(), terrainGeode.get());
346    if (!lines.empty())
347    {
348        osg::notify(osg::NOTICE)<<"We've found intersections!!!!"<<std::endl;
349
350        osg::Geode* geode = new osg::Geode;
351        root->addChild(geode);
352
353        geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
354
355        for(osgSim::SphereSegment::LineList::iterator itr=lines.begin();
356           itr!=lines.end();
357           ++itr)
358        {
359            osg::Geometry* geom = new osg::Geometry;
360            geode->addDrawable(geom);
361           
362            osg::Vec3Array* vertices = itr->get();
363            geom->setVertexArray(vertices);
364            geom->addPrimitiveSet(new osg::DrawArrays(GL_LINE_STRIP, 0, vertices->getNumElements()));
365        }
366    }
367    else
368    {
369       osg::notify(osg::NOTICE)<<"No intersections found"<<std::endl;
370    }
371
372#if 1
373
374
375    osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode;
376   
377    overlayNode->getOrCreateStateSet()->setTextureAttribute(1, new osg::TexEnv(osg::TexEnv::DECAL));
378
379    const osg::BoundingSphere& bs = terrainGeode->getBound();
380    osg::Group* overlaySubgraph = createOverlay(bs.center(), bs.radius()*0.5f);
381    overlaySubgraph->addChild(ss.get());
382    overlayNode->setOverlaySubgraph(overlaySubgraph);
383    overlayNode->setOverlayTextureSizeHint(2048);
384    overlayNode->addChild(terrainGeode.get());
385
386    root->addChild(overlayNode);
387   
388   
389#else
390    root->addChild(terrainGeode);
391#endif
392
393
394    // create particle effects
395    {   
396        osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),100.0f,100.0f);
397
398        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 10.0f);
399        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 10.0f);
400        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 10.0f);
401
402        root->addChild(explosion);
403        root->addChild(smoke);
404        root->addChild(fire);
405    }
406   
407    // create particle effects
408    {   
409        osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),200.0f,100.0f);
410
411        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 1.0f);
412        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 1.0f);
413        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 1.0f);
414
415        root->addChild(explosion);
416        root->addChild(smoke);
417        root->addChild(fire);
418    }
419   
420    // create the moving models.
421    {
422        root->addChild(createMovingModel(osg::Vec3(500.0f,500.0f,500.0f),100.0f));
423    }
424}
425
426
427//////////////////////////////////////////////////////////////////////////////
428// main()
429//////////////////////////////////////////////////////////////////////////////
430
431
432int main(int argc, char **argv)
433{
434    // use an ArgumentParser object to manage the program arguments.
435    osg::ArgumentParser arguments(&argc,argv);
436   
437    // set up the usage document, in case we need to print out how to use this program.
438    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
439    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
440    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
441   
442
443    // construct the viewer.
444    osgProducer::Viewer viewer(arguments);
445
446    // set up the value with sensible default event handlers.
447    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
448
449    // get details on keyboard and mouse bindings used by the viewer.
450    viewer.getUsage(*arguments.getApplicationUsage());
451
452    // if user request help write it out to cout.
453    if (arguments.read("-h") || arguments.read("--help"))
454    {
455        arguments.getApplicationUsage()->write(std::cout);
456        return 1;
457    }
458
459    // any option left unread are converted into errors to write out later.
460    arguments.reportRemainingOptionsAsUnrecognized();
461
462    // report any errors if they have occured when parsing the program aguments.
463    if (arguments.errors())
464    {
465        arguments.writeErrorMessages(std::cout);
466        return 1;
467    }
468   
469    osg::Group *root = new osg::Group;
470    build_world(root);
471   
472    // add a viewport to the viewer and attach the scene graph.
473    viewer.setSceneData(root);
474       
475    // create the windows and run the threads.
476    viewer.realize();
477
478    while( !viewer.done() )
479    {
480        // wait for all cull and draw threads to complete.
481        viewer.sync();
482
483        // update the scene by traversing it with the the update visitor which will
484        // call all node update callbacks and animations.
485        viewer.update();
486         
487        // fire off the cull and draw traversals of the scene.
488        viewer.frame();
489       
490    }
491   
492    // wait for all cull and draw threads to complete before exit.
493    viewer.sync();
494
495    return 0;
496}
Note: See TracBrowser for help on using the browser.