root/OpenSceneGraph/trunk/examples/osgparticleeffects/osgparticleeffects.cpp @ 7964

Revision 7964, 17.3 kB (checked in by robert, 6 years ago)

Fixed moving model bug where the moving model code was looking for a transform with DataVariance? set to DYNAMIC, but the scene graph set up code was leaving the setting to default to STATIC. Fix involved setting DataVariance? on moving transoforms to DYNAMIC.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osgparticleeffects.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19
20#include <osgViewer/Viewer>
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/io_utils>
29
30#include <osgUtil/Optimizer>
31#include <osgUtil/IntersectVisitor>
32
33#include <osgDB/ReadFile>
34
35#include <osgText/Text>
36
37#include <osgParticle/ExplosionEffect>
38#include <osgParticle/ExplosionDebrisEffect>
39#include <osgParticle/SmokeEffect>
40#include <osgParticle/SmokeTrailEffect>
41#include <osgParticle/FireEffect>
42
43// for the grid data..
44#include "../osghangglide/terrain_coords.h"
45
46osg::Vec3 wind(1.0f,0.0f,0.0f);           
47
48osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
49{
50    // set up the animation path
51    osg::AnimationPath* animationPath = new osg::AnimationPath;
52    animationPath->setLoopMode(osg::AnimationPath::LOOP);
53   
54    int numSamples = 40;
55    float yaw = 0.0f;
56    float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
57    float roll = osg::inDegrees(30.0f);
58   
59    double time=0.0f;
60    double time_delta = looptime/(double)numSamples;
61    for(int i=0;i<numSamples;++i)
62    {
63        osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
64        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)));
65       
66        animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
67
68        yaw += yaw_delta;
69        time += time_delta;
70
71    }
72    return animationPath;   
73}
74
75osg::Node* createMovingModel(const osg::Vec3& center, float radius)
76{
77    float animationLength = 10.0f;
78
79    osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
80
81    osg::Group* model = new osg::Group;
82
83    osg::Node* glider = osgDB::readNodeFile("glider.osg");
84    if (glider)
85    {
86        const osg::BoundingSphere& bs = glider->getBound();
87        float size = radius/bs.radius()*0.15f;
88
89        osg::MatrixTransform* positioned = new osg::MatrixTransform;
90        positioned->setDataVariance(osg::Object::STATIC);
91        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
92                                     osg::Matrix::scale(size,size,size)*
93                                     osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));
94   
95        positioned->addChild(glider);
96   
97        osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;
98        xform->setDataVariance(osg::Object::DYNAMIC);
99        xform->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
100        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,0.5));
101        xform->addChild(positioned);
102
103        model->addChild(xform);
104    }
105 
106    osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
107    if (cessna)
108    {
109        const osg::BoundingSphere& bs = cessna->getBound();
110        float size = radius/bs.radius()*0.15f;
111
112        osg::MatrixTransform* positioned = new osg::MatrixTransform;
113        positioned->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
114        positioned->setDataVariance(osg::Object::STATIC);
115        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
116                                     osg::Matrix::scale(size,size,size)*
117                                     osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));
118   
119        //positioned->addChild(cessna);
120        positioned->addChild(cessna);
121   
122        osg::MatrixTransform* xform = new osg::MatrixTransform;
123        xform->setDataVariance(osg::Object::DYNAMIC);
124        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,1.0));
125        xform->addChild(positioned);
126
127        model->addChild(xform);
128    }
129   
130    return model;
131}
132
133
134osg::Vec3 computeTerrainIntersection(osg::Node* subgraph,float x,float y)
135{
136    osgUtil::IntersectVisitor iv;
137    osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;
138
139    const osg::BoundingSphere& bs = subgraph->getBound();
140    float zMax = bs.center().z()+bs.radius();
141    float zMin = bs.center().z()-bs.radius();
142   
143    segDown->set(osg::Vec3(x,y,zMin),osg::Vec3(x,y,zMax));
144    iv.addLineSegment(segDown.get());
145
146    subgraph->accept(iv);
147
148    if (iv.hits())
149    {
150        osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());
151        if (!hitList.empty())
152        {
153            osg::Vec3 ip = hitList.front().getWorldIntersectPoint();
154            return  ip;
155        }
156    }
157
158    return osg::Vec3(x,y,0.0f);
159}
160
161
162//////////////////////////////////////////////////////////////////////////////
163// MAIN SCENE GRAPH BUILDING FUNCTION
164//////////////////////////////////////////////////////////////////////////////
165
166void build_world(osg::Group *root)
167{
168
169    osg::Geode* terrainGeode = new osg::Geode;
170    // create terrain
171    {
172        osg::StateSet* stateset = new osg::StateSet();
173        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
174        if (image)
175        {
176            osg::Texture2D* texture = new osg::Texture2D;
177            texture->setImage(image);
178            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
179        }
180
181        terrainGeode->setStateSet( stateset );
182
183        float size = 1000; // 10km;
184        float scale = size/39.0f; // 10km;
185        float z_scale = scale*3.0f;
186
187        osg::HeightField* grid = new osg::HeightField;
188        grid->allocate(38,39);
189        grid->setXInterval(scale);
190        grid->setYInterval(scale);
191
192        for(unsigned int r=0;r<39;++r)
193        {
194            for(unsigned int c=0;c<38;++c)
195            {
196                grid->setHeight(c,r,z_scale*vertex[r+c*39][2]);
197            }
198        }
199        terrainGeode->addDrawable(new osg::ShapeDrawable(grid));
200       
201        root->addChild(terrainGeode);
202    }   
203
204
205    // create particle effects
206    {   
207        osg::Vec3 position = computeTerrainIntersection(terrainGeode,100.0f,100.0f);
208
209        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 10.0f);
210        osgParticle::ExplosionDebrisEffect* explosionDebri = new osgParticle::ExplosionDebrisEffect(position, 10.0f);
211        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 10.0f);
212        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 10.0f);
213
214        explosion->setWind(wind);
215        explosionDebri->setWind(wind);
216        smoke->setWind(wind);
217        fire->setWind(wind);
218
219        root->addChild(explosion);
220        root->addChild(explosionDebri);
221        root->addChild(smoke);
222        root->addChild(fire);
223    }
224   
225    // create particle effects
226    {   
227        osg::Vec3 position = computeTerrainIntersection(terrainGeode,200.0f,100.0f);
228
229        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 1.0f);
230        osgParticle::ExplosionDebrisEffect* explosionDebri = new osgParticle::ExplosionDebrisEffect(position, 1.0f);
231        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 1.0f);
232        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 1.0f);
233
234        explosion->setWind(wind);
235        explosionDebri->setWind(wind);
236        smoke->setWind(wind);
237        fire->setWind(wind);
238
239        root->addChild(explosion);
240        root->addChild(explosionDebri);
241        root->addChild(smoke);
242        root->addChild(fire);
243    }
244
245    // create the moving models.
246    {
247        root->addChild(createMovingModel(osg::Vec3(500.0f,500.0f,500.0f),300.0f));
248    }
249}
250
251
252// class to handle events with a pick
253class PickHandler : public osgGA::GUIEventHandler {
254public:
255
256    PickHandler() {}       
257   
258    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
259    {
260        switch(ea.getEventType())
261        {
262            case(osgGA::GUIEventAdapter::PUSH):
263            {
264                osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
265                pick(viewer,ea);
266            }
267            return false;
268
269        default:
270            return false;
271        }
272    }
273
274    void pick(osgViewer::Viewer* viewer, const osgGA::GUIEventAdapter& ea)
275    {
276        osg::Group* root = dynamic_cast<osg::Group*>(viewer->getSceneData());       
277        if (!root) return;
278
279        osgUtil::LineSegmentIntersector::Intersections intersections;
280        if (viewer->computeIntersections(ea.getX(),ea.getY(),intersections))
281        {
282            const osgUtil::LineSegmentIntersector::Intersection& hit = *intersections.begin();
283
284            bool handleMovingModels = false;
285            const osg::NodePath& nodePath = hit.nodePath;
286            for(osg::NodePath::const_iterator nitr=nodePath.begin();
287                nitr!=nodePath.end();
288                ++nitr)
289            {
290                const osg::Transform* transform = dynamic_cast<const osg::Transform*>(*nitr);
291                if (transform)
292                {
293                    if (transform->getDataVariance()==osg::Object::DYNAMIC) handleMovingModels=true;
294                }
295            }
296           
297            osg::Vec3 position = handleMovingModels ? hit.getLocalIntersectPoint() : hit.getWorldIntersectPoint();
298            float scale = 10.0f * ((float)rand() / (float)RAND_MAX);
299            float intensity = 1.0f;
300
301            osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, scale, intensity);
302            osgParticle::ExplosionDebrisEffect* explosionDebri = new osgParticle::ExplosionDebrisEffect(position, scale, intensity);
303            osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, scale, intensity);
304            osgParticle::ParticleEffect* smoke = 0;
305            if (handleMovingModels)
306                smoke =  new osgParticle::SmokeTrailEffect(position, scale, intensity);
307            else
308                smoke =  new osgParticle::SmokeEffect(position, scale, intensity);
309           
310            explosion->setWind(wind);
311            explosionDebri->setWind(wind);
312            smoke->setWind(wind);
313            fire->setWind(wind);
314
315            osg::Group* effectsGroup = new osg::Group;
316            effectsGroup->addChild(explosion);
317            effectsGroup->addChild(explosionDebri);
318            effectsGroup->addChild(smoke);
319            effectsGroup->addChild(fire);
320           
321
322            if (handleMovingModels)
323            {
324                // insert particle effects alongside the hit node, therefore able to track that nodes movement,
325                // however, this does require us to insert the ParticleSystem itself into the root of the scene graph
326                // seperately from the the main particle effects group which contains the emitters and programs.
327                // the follow code block implements this, note the path for handling particle effects which arn't attached to
328                // moving models is easy - just a single line of code!
329           
330                // tell the effects not to attach to the particle system locally for rendering, as we'll handle add it into the
331                // scene graph ourselves.
332                explosion->setUseLocalParticleSystem(false);
333                explosionDebri->setUseLocalParticleSystem(false);
334                smoke->setUseLocalParticleSystem(false);
335                fire->setUseLocalParticleSystem(false);
336
337                // find a place to insert the particle effects group alongside the hit node.
338                // there are two possible ways that this can be done, either insert it into
339                // a pre-existing group along side the hit node, or if no pre existing group
340                // is found then this needs to be inserted above the hit node, and then the
341                // particle effect can be inserted into this.
342                osg::ref_ptr<osg::Node> hitNode = hit.nodePath.back();
343                osg::Node::ParentList parents = hitNode->getParents();               
344                osg::Group* insertGroup = 0;
345                unsigned int numGroupsFound = 0;
346                for(osg::Node::ParentList::iterator itr=parents.begin();
347                    itr!=parents.end();
348                    ++itr)
349                {
350                    if (typeid(*(*itr))==typeid(osg::Group))
351                    {
352                        ++numGroupsFound;
353                        insertGroup = *itr;
354                    }
355                }               
356                if (numGroupsFound==parents.size() && numGroupsFound==1 && insertGroup)
357                {
358                    osg::notify(osg::INFO)<<"PickHandler::pick(,) hit node's parent is a single osg::Group so we can simple the insert the particle effects group here."<<std::endl;
359
360                    // just reuse the existing group.
361                    insertGroup->addChild(effectsGroup);
362                }
363                else
364                {           
365                    osg::notify(osg::INFO)<<"PickHandler::pick(,) hit node doesn't have an appropriate osg::Group node to insert particle effects into, inserting a new osg::Group."<<std::endl;
366                    insertGroup = new osg::Group;
367                    for(osg::Node::ParentList::iterator itr=parents.begin();
368                        itr!=parents.end();
369                        ++itr)
370                    {
371                        (*itr)->replaceChild(hit.nodePath.back(),insertGroup);
372                    }
373                    insertGroup->addChild(hitNode.get());
374                    insertGroup->addChild(effectsGroup);
375                }
376
377                // finally insert the particle systems into a Geode and attach to the root of the scene graph so the particle system
378                // can be rendered.
379                osg::Geode* geode = new osg::Geode;
380                geode->addDrawable(explosion->getParticleSystem());
381                geode->addDrawable(explosionDebri->getParticleSystem());
382                geode->addDrawable(smoke->getParticleSystem());
383                geode->addDrawable(fire->getParticleSystem());
384               
385                root->addChild(geode);
386
387            }
388            else
389            {
390                // when we don't have moving models we can simple insert the particle effect into the root of the scene graph
391                osg::notify(osg::INFO)<<"PickHandler::pick(,) adding particle effects to root node."<<std::endl;
392                root->addChild(effectsGroup);
393            }
394
395#if 0           
396            osg::Geode* geode = new osg::Geode;
397            geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(position,scale)));
398            group->addChild(geode);
399#endif
400 
401        }
402    }
403   
404protected:
405    virtual ~PickHandler() {}
406};
407
408// function used in debugging
409void insertParticle(osg::Group* root, const osg::Vec3& center, float radius)
410{
411    bool handleMovingModels = false;
412
413    osg::Vec3 position = center +
414               osg::Vec3( radius * (((float)rand() / (float)RAND_MAX)-0.5)*2.0,
415                          radius * (((float)rand() / (float)RAND_MAX)-0.5)*2.0,
416                          0.0f);
417
418    float scale = 10.0f * ((float)rand() / (float)RAND_MAX);
419    float intensity = 1.0f;
420
421    osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, scale, intensity);
422    osgParticle::ExplosionDebrisEffect* explosionDebri = new osgParticle::ExplosionDebrisEffect(position, scale, intensity);
423    osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, scale, intensity);
424    osgParticle::ParticleEffect* smoke = 0;
425    if (handleMovingModels)
426        smoke =  new osgParticle::SmokeTrailEffect(position, scale, intensity);
427    else
428        smoke =  new osgParticle::SmokeEffect(position, scale, intensity);
429
430    explosion->setWind(wind);
431    explosionDebri->setWind(wind);
432    smoke->setWind(wind);
433    fire->setWind(wind);
434
435    osg::Group* effectsGroup = new osg::Group;
436    effectsGroup->addChild(explosion);
437    effectsGroup->addChild(explosionDebri);
438    effectsGroup->addChild(smoke);
439    effectsGroup->addChild(fire);
440
441    root->addChild(effectsGroup);
442}
443
444//////////////////////////////////////////////////////////////////////////////
445// main()
446//////////////////////////////////////////////////////////////////////////////
447
448int main(int, char **)
449{
450    // construct the viewer.
451    osgViewer::Viewer viewer;
452
453    // register the pick handler
454    viewer.addEventHandler(new PickHandler());
455   
456    osg::Group *root = new osg::Group;
457    build_world(root);
458
459    osgUtil::Optimizer optimizer;
460    optimizer.optimize(root);
461   
462    // add a viewport to the viewer and attach the scene graph.
463    viewer.setSceneData(root);
464       
465    return viewer.run();
466}
Note: See TracBrowser for help on using the browser.