]> git.mxchange.org Git - simgear.git/blob - simgear/scene/model/particles.cxx
9fdc4bf51a1f3d5c8ab8746d2fb26a827004a67c
[simgear.git] / simgear / scene / model / particles.cxx
1 // particles.cxx - classes to manage particles
2 // started in 2008 by Tiago Gusmão, using animation.hxx as reference
3 // Copyright (C) 2008 Tiago Gusmão
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19
20 #ifdef HAVE_CONFIG_H
21 #  include <simgear_config.h>
22 #endif
23
24 #include <simgear/misc/sg_path.hxx>
25 #include <simgear/props/props.hxx>
26 #include <simgear/props/props_io.hxx>
27
28 #include <osgParticle/SmokeTrailEffect>
29 #include <osgParticle/FireEffect>
30 #include <osgParticle/ConnectedParticleSystem>
31 #include <osgParticle/MultiSegmentPlacer>
32 #include <osgParticle/SectorPlacer>
33 #include <osgParticle/ConstantRateCounter>
34 #include <osgParticle/ParticleSystemUpdater>
35 #include <osgParticle/FluidProgram>
36
37 #include <osg/Geode>
38 #include <osg/MatrixTransform>
39
40 #include "particles.hxx"
41
42 namespace simgear
43 {
44 void GlobalParticleCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
45 {
46     SGQuatd q
47         = SGQuatd::fromLonLatDeg(modelRoot->getFloatValue("/position/longitude-deg",0),
48                                  modelRoot->getFloatValue("/position/latitude-deg",0));
49     osg::Matrix om(q.osg());
50     osg::Vec3 v(0,0,9.81);
51     gravity = om.preMult(v);
52
53     osg::Vec3 w(-modelRoot->getFloatValue("/environment/wind-from-north-fps",0) * SG_FEET_TO_METER, 
54                 -modelRoot->getFloatValue("/environment/wind-from-east-fps",0) * SG_FEET_TO_METER, 0);
55     wind = om.preMult(w);
56
57     //SG_LOG(SG_GENERAL, SG_ALERT, "wind vector:"<<w[0]<<","<<w[1]<<","<<w[2]<<"\n");
58 }
59
60
61 //static members
62 osg::Vec3 GlobalParticleCallback::gravity;
63 osg::Vec3 GlobalParticleCallback::wind;
64
65 osg::ref_ptr<osg::Group> Particles::commonRoot;
66 osg::ref_ptr<osgParticle::ParticleSystemUpdater> Particles::psu = new osgParticle::ParticleSystemUpdater;
67 osg::ref_ptr<osg::Geode> Particles::commonGeode = new osg::Geode;;
68
69 template <typename Object>
70 class PointerGuard{
71 public:
72     PointerGuard() : _ptr(0) {}
73     Object* get() { return _ptr; }
74     Object* operator () ()
75     {
76         if (!_ptr)
77             _ptr = new Object;
78         return _ptr;
79     }
80 private:
81     Object* _ptr;
82 };
83
84 osg::Group * Particles::appendParticles(const SGPropertyNode* configNode,
85                                           SGPropertyNode* modelRoot,
86                                           const osgDB::ReaderWriter::Options*
87                                           options)
88 {
89     SG_LOG(SG_GENERAL, SG_DEBUG, "Setting up a particle system!\n");
90
91     osgParticle::ParticleSystem *particleSys;
92
93     //create a generic particle system
94     std::string type = configNode->getStringValue("type", "normal");
95     if (type == "normal")
96         particleSys = new osgParticle::ParticleSystem;
97     else
98         particleSys = new osgParticle::ConnectedParticleSystem;
99     //may not be used depending on the configuration
100     PointerGuard<Particles> callback;
101
102     getPSU()->addParticleSystem(particleSys); 
103     getPSU()->setUpdateCallback(new GlobalParticleCallback(modelRoot));
104     //contains counter, placer and shooter by default
105     osgParticle::ModularEmitter* emitter = new osgParticle::ModularEmitter;
106
107     emitter->setParticleSystem(particleSys);
108
109     // Set up the alignment node ("stolen" from animation.cxx)
110     // XXX Order of rotations is probably not correct.
111     osg::MatrixTransform *align = new osg::MatrixTransform;
112     osg::Matrix res_matrix;
113     res_matrix.makeRotate(
114         configNode->getFloatValue("offsets/pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
115         osg::Vec3(0, 1, 0),
116         configNode->getFloatValue("offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
117         osg::Vec3(1, 0, 0),
118         configNode->getFloatValue("offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
119         osg::Vec3(0, 0, 1));
120
121     osg::Matrix tmat;
122     tmat.makeTranslate(configNode->getFloatValue("offsets/x-m", 0.0),
123                        configNode->getFloatValue("offsets/y-m", 0.0),
124                        configNode->getFloatValue("offsets/z-m", 0.0));
125     align->setMatrix(res_matrix * tmat);
126
127     align->setName("particle align");
128
129     //if (dynamic_cast<CustomModularEmitter*>(emitter)==0) SG_LOG(SG_GENERAL, SG_ALERT, "observer error\n");
130     //align->addObserver(dynamic_cast<CustomModularEmitter*>(emitter));
131
132     align->addChild(emitter);
133
134     //this name can be used in the XML animation as if it was a submodel
135     std::string name = configNode->getStringValue("name", "");
136     if (!name.empty())
137         align->setName(name);
138     std::string attach = configNode->getStringValue("attach", "world");
139     if (attach == "local") { //local means attached to the model and not the world
140         osg::Geode* g = new osg::Geode;
141         align->addChild(g);
142         g->addDrawable(particleSys);
143         emitter->setReferenceFrame(osgParticle::Emitter::ABSOLUTE_RF);
144     } else {
145         getCommonGeode()->addDrawable(particleSys);
146     }
147     std::string textureFile;
148     if (configNode->hasValue("texture")) {
149         //SG_LOG(SG_GENERAL, SG_ALERT,
150         //       "requested:"<<configNode->getStringValue("texture","")<<"\n");
151         textureFile= osgDB::findFileInPath(configNode->getStringValue("texture",
152                                                                       ""),
153                                            options->getDatabasePathList());
154         //SG_LOG(SG_GENERAL, SG_ALERT, "found:"<<textureFile<<"\n");
155
156         //for(unsigned i = 0; i < options->getDatabasePathList().size(); ++i)
157         //    SG_LOG(SG_GENERAL, SG_ALERT,
158         //           "opts:"<<options->getDatabasePathList()[i]<<"\n");
159     }
160
161     particleSys->setDefaultAttributes(textureFile,
162                                       configNode->getBoolValue("emissive",
163                                                                true),
164                                       configNode->getBoolValue("lighting",
165                                                                false));
166
167     std::string alignstr = configNode->getStringValue("align", "billboard");
168
169     if (alignstr == "fixed")
170         particleSys->setParticleAlignment(osgParticle::ParticleSystem::FIXED);
171
172     const SGPropertyNode* placernode = configNode->getChild("placer");
173
174     if (placernode) {
175         std::string emitterType = placernode->getStringValue("type", "point");
176
177         if (emitterType == "sector") {
178             osgParticle::SectorPlacer *splacer = new  osgParticle::SectorPlacer;
179             float minRadius, maxRadius, minPhi, maxPhi;
180
181             minRadius = placernode->getFloatValue("radius-min-m",0);
182             maxRadius = placernode->getFloatValue("radius-max-m",1);
183             minPhi = (placernode->getFloatValue("phi-min-deg",0)
184                       * SG_DEGREES_TO_RADIANS);
185             maxPhi = (placernode->getFloatValue("phi-max-deg",360.0f)
186                       * SG_DEGREES_TO_RADIANS);
187
188             splacer->setRadiusRange(minRadius, maxRadius);
189             splacer->setPhiRange(minPhi, maxPhi);
190             emitter->setPlacer(splacer);
191         } else if (emitterType == "segments") {
192             std::vector<SGPropertyNode_ptr> segments
193                 = placernode->getChildren("vertex");
194             if (segments.size()>1) {
195                 osgParticle::MultiSegmentPlacer *msplacer
196                     = new osgParticle::MultiSegmentPlacer();
197                 float x,y,z;
198
199                 for (unsigned i = 0; i < segments.size(); ++i) {
200                     x = segments[i]->getFloatValue("x-m",0);
201                     y = segments[i]->getFloatValue("y-m",0);
202                     z = segments[i]->getFloatValue("z-m",0);
203                     msplacer->addVertex(x, y, z);
204                 }
205                 emitter->setPlacer(msplacer);
206             } else {
207                 SG_LOG(SG_GENERAL, SG_ALERT,
208                        "Detected particle system using segment(s) with less than 2 vertices\n");
209             }
210         } //else the default placer in ModularEmitter is used (PointPlacer)
211     }
212
213     const SGPropertyNode* shnode = configNode->getChild("shooter");
214
215     if (shnode) {
216         float minTheta, maxTheta, minPhi, maxPhi, speed, spread;
217
218         minTheta = (shnode->getFloatValue("theta-min-deg",0)
219                     * SG_DEGREES_TO_RADIANS);
220         maxTheta = (shnode->getFloatValue("theta-max-deg",360.0f)
221                     * SG_DEGREES_TO_RADIANS);
222         minPhi = shnode->getFloatValue("phi-min-deg",0)* SG_DEGREES_TO_RADIANS;
223         maxPhi = (shnode->getFloatValue("phi-max-deg",360.0f)
224                   * SG_DEGREES_TO_RADIANS); 
225
226         osgParticle::RadialShooter *shooter = new osgParticle::RadialShooter;
227         emitter->setShooter(shooter);
228
229         shooter->setThetaRange(minTheta, maxTheta);
230         shooter->setPhiRange(minPhi, maxPhi);
231
232         const SGPropertyNode* speednode = shnode->getChild("speed-mps");
233
234         if (speednode) {
235             if (speednode->hasValue("value")) {
236                 speed = speednode->getFloatValue("value",0);
237                 spread = speednode->getFloatValue("spread",0);
238                 shooter->setInitialSpeedRange(speed-spread, speed+spread);
239             } else {
240                 callback()->setupShooterSpeedData(speednode, modelRoot);
241             }
242         }
243
244         const SGPropertyNode* rotspeednode = shnode->getChild("rotation-speed");
245
246         if (rotspeednode) {
247             float x1,y1,z1,x2,y2,z2;
248             x1 = rotspeednode->getFloatValue("x-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
249             y1 = rotspeednode->getFloatValue("y-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
250             z1 = rotspeednode->getFloatValue("z-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
251             x2 = rotspeednode->getFloatValue("x-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
252             y2 = rotspeednode->getFloatValue("y-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
253             z2 = rotspeednode->getFloatValue("z-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
254             shooter->setInitialRotationalSpeedRange(osg::Vec3f(x1,y1,z1), osg::Vec3f(x2,y2,z2));
255         }
256     } //else ModularEmitter uses the default RadialShooter
257
258
259     const SGPropertyNode* conditionNode = configNode->getChild("condition");
260     const SGPropertyNode* counternode = configNode->getChild("counter");
261
262     if (conditionNode || counternode) {
263         osgParticle::RandomRateCounter* counter
264             = new osgParticle::RandomRateCounter;
265         emitter->setCounter(counter);
266         float pps = 0.0f, spread = 0.0f;
267
268         if (counternode) {
269             const SGPropertyNode* ppsnode = counternode->getChild("particles-per-sec");
270             if (ppsnode) {
271                 if (ppsnode->hasValue("value")) {
272                     pps = ppsnode->getFloatValue("value",0);
273                     spread = ppsnode->getFloatValue("spread",0);
274                     counter->setRateRange(pps-spread, pps+spread);
275                 } else {
276                     callback()->setupCounterData(ppsnode, modelRoot);
277                 }
278             }
279         }
280
281         if (conditionNode) {
282             callback()->setupCounterCondition(conditionNode, modelRoot);
283             callback()->setupCounterCondition(pps, spread);
284         }
285     } //TODO: else perhaps set higher values than default? 
286
287     const SGPropertyNode* particlenode = configNode->getChild("particle");
288     if (particlenode) {
289         osgParticle::Particle &particle
290             = particleSys->getDefaultParticleTemplate();
291         float r1=0, g1=0, b1=0, a1=1, r2=0, g2=0, b2=0, a2=1;
292         const SGPropertyNode* startcolornode
293             = particlenode->getNode("start/color");
294         if (startcolornode) {
295             const SGPropertyNode* componentnode
296                 = startcolornode->getChild("red");
297             if (componentnode) {
298                 if (componentnode->hasValue("value"))
299                     r1 = componentnode->getFloatValue("value",0);
300                 else 
301                     callback()->setupColorComponent(componentnode, modelRoot,
302                                                     0, 0);
303             }
304             componentnode = startcolornode->getChild("green");
305             if (componentnode) {
306                 if (componentnode->hasValue("value"))
307                     g1 = componentnode->getFloatValue("value", 0);
308                 else
309                     callback()->setupColorComponent(componentnode, modelRoot,
310                                                     0, 1);
311             }
312             componentnode = startcolornode->getChild("blue");
313             if (componentnode) {
314                 if (componentnode->hasValue("value"))
315                     b1 = componentnode->getFloatValue("value",0);
316                 else
317                     callback()->setupColorComponent(componentnode, modelRoot,
318                                                     0, 2);
319             }
320             componentnode = startcolornode->getChild("alpha");
321             if (componentnode) {
322                 if (componentnode->hasValue("value"))
323                     a1 = componentnode->getFloatValue("value",0);
324                 else
325                     callback()->setupColorComponent(componentnode, modelRoot,
326                                                     0, 3);
327             }
328         }
329         const SGPropertyNode* endcolornode = particlenode->getNode("end/color");
330         if (endcolornode) {
331             const SGPropertyNode* componentnode = endcolornode->getChild("red");
332
333             if (componentnode) {
334                 if (componentnode->hasValue("value"))
335                     r2 = componentnode->getFloatValue("value",0);
336                 else
337                     callback()->setupColorComponent(componentnode, modelRoot,
338                                                     1, 0);
339             }
340             componentnode = endcolornode->getChild("green");
341             if (componentnode) {
342                 if (componentnode->hasValue("value"))
343                     g2 = componentnode->getFloatValue("value",0);
344                 else
345                     callback()->setupColorComponent(componentnode, modelRoot,
346                                                     1, 1);
347             }
348             componentnode = endcolornode->getChild("blue");
349             if (componentnode) {
350                 if (componentnode->hasValue("value"))
351                     b2 = componentnode->getFloatValue("value",0);
352                 else
353                     callback()->setupColorComponent(componentnode, modelRoot,
354                                                     1, 2);
355             }
356             componentnode = endcolornode->getChild("alpha");
357             if (componentnode) {
358                 if (componentnode->hasValue("value"))
359                     a2 = componentnode->getFloatValue("value",0);
360                 else
361                     callback()->setupColorComponent(componentnode, modelRoot,
362                                                     1, 3);
363             }
364         }
365         particle.setColorRange(osgParticle::rangev4(osg::Vec4(r1,g1,b1,a1),
366                                                     osg::Vec4(r2,g2,b2,a2)));
367
368         float startsize=1, endsize=0.1f;
369         const SGPropertyNode* startsizenode = particlenode->getNode("start/size");
370         if (startsizenode) {
371             if (startsizenode->hasValue("value"))
372                 startsize = startsizenode->getFloatValue("value",0);
373             else
374                 callback()->setupStartSizeData(startsizenode, modelRoot);
375         }
376         const SGPropertyNode* endsizenode = particlenode->getNode("end/size");
377         if (endsizenode) {
378             if (endsizenode->hasValue("value"))
379                 endsize = endsizenode->getFloatValue("value",0);
380             else
381                 callback()->setupEndSizeData(endsizenode, modelRoot);
382         }
383         particle.setSizeRange(osgParticle::rangef(startsize, endsize));
384         float life=5;
385         const SGPropertyNode* lifenode = particlenode->getChild("life-sec");
386         if (lifenode) {
387             if (lifenode->hasValue("value"))
388                 life =  lifenode->getFloatValue("value",0);
389             else
390                 callback()->setupLifeData(lifenode, modelRoot);
391         }
392
393         particle.setLifeTime(life);
394         if (particlenode->hasValue("radius-m"))
395             particle.setRadius(particlenode->getFloatValue("radius-m",0));
396         if (particlenode->hasValue("mass-kg"))
397             particle.setMass(particlenode->getFloatValue("mass-kg",0));
398         if (callback.get()) {
399             callback.get()->setupStaticColorComponent(r1, g1, b1, a1,
400                                                       r2, g2, b2, a2);
401             callback.get()->setupStaticSizeData(startsize, endsize);
402         }
403         //particle.setColorRange(osgParticle::rangev4( osg::Vec4(r1, g1, b1, a1), osg::Vec4(r2, g2, b2, a2)));
404     }
405
406     const SGPropertyNode* programnode = configNode->getChild("program");
407     osgParticle::FluidProgram *program = new osgParticle::FluidProgram();
408
409     if (programnode) {
410         std::string fluid = programnode->getStringValue("fluid", "air");
411
412         if (fluid=="air")
413             program->setFluidToAir();
414         else
415             program->setFluidToWater();
416
417         if (programnode->getBoolValue("gravity", true)) {
418             if (attach == "world")
419                 callback()->setupProgramGravity(true);
420             else
421                 program->setToGravity();
422         } else
423             program->setAcceleration(osg::Vec3(0,0,0));
424
425         if (programnode->getBoolValue("wind", true))
426             callback()->setupProgramWind(true);
427         else
428             program->setWind(osg::Vec3(0,0,0));
429
430         align->addChild(program);
431
432         program->setParticleSystem(particleSys);
433     }
434
435     if (callback.get()) {  //this means we want property-driven changes
436         SG_LOG(SG_GENERAL, SG_DEBUG, "setting up particle system user data and callback\n");
437         //setup data and callback
438         callback.get()->setGeneralData(dynamic_cast<osgParticle::RadialShooter*>(emitter->getShooter()),
439                                        dynamic_cast<osgParticle::RandomRateCounter*>(emitter->getCounter()),
440                                        particleSys, program);
441         emitter->setUpdateCallback(callback.get());
442     }
443
444     return align;
445 }
446
447 void Particles::operator()(osg::Node* node, osg::NodeVisitor* nv)
448 {
449     //SG_LOG(SG_GENERAL, SG_ALERT, "callback!\n");
450
451     if (shooterValue)
452         shooter->setInitialSpeedRange(shooterValue->getValue(),
453                                       (shooterValue->getValue()
454                                        + shooterExtraRange));
455     if (counterValue)
456         counter->setRateRange(counterValue->getValue(),
457                               counterValue->getValue() + counterExtraRange);
458     else if (counterCond)
459         counter->setRateRange(counterStaticValue,
460                               counterStaticValue + counterStaticExtraRange);
461     if (counterCond && !counterCond->test())
462         counter->setRateRange(0, 0);
463     bool colorchange=false;
464     for (int i = 0; i < 8; ++i) {
465         if (colorComponents[i]) {
466             staticColorComponents[i] = colorComponents[i]->getValue();
467             colorchange=true;
468         }
469     }
470     if (colorchange)
471         particleSys->getDefaultParticleTemplate().setColorRange(osgParticle::rangev4( osg::Vec4(staticColorComponents[0], staticColorComponents[1], staticColorComponents[2], staticColorComponents[3]), osg::Vec4(staticColorComponents[4], staticColorComponents[5], staticColorComponents[6], staticColorComponents[7])));
472     if (startSizeValue)
473         startSize = startSizeValue->getValue();
474     if (endSizeValue)
475         endSize = endSizeValue->getValue();
476     if (startSizeValue || endSizeValue)
477         particleSys->getDefaultParticleTemplate().setSizeRange(osgParticle::rangef(startSize, endSize));
478     if (lifeValue)
479         particleSys->getDefaultParticleTemplate().setLifeTime(lifeValue->getValue());
480     if (program.valid()) {
481         if (useGravity)
482             program->setAcceleration(GlobalParticleCallback::getGravityVector());
483         if (useWind)
484             program->setWind(GlobalParticleCallback::getWindVector());
485     }
486 }
487 } // namespace simgear