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
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.
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.
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.
21 # include <simgear_config.h>
24 #include <simgear/misc/sg_path.hxx>
25 #include <simgear/props/props.hxx>
26 #include <simgear/props/props_io.hxx>
27 #include <simgear/scene/util/OsgMath.hxx>
28 #include <simgear/structure/OSGVersion.hxx>
30 #include <osgParticle/SmokeTrailEffect>
31 #include <osgParticle/FireEffect>
32 #include <osgParticle/ConnectedParticleSystem>
33 #include <osgParticle/MultiSegmentPlacer>
34 #include <osgParticle/SectorPlacer>
35 #include <osgParticle/ConstantRateCounter>
36 #include <osgParticle/ParticleSystemUpdater>
37 #include <osgParticle/ParticleSystem>
38 #include <osgParticle/FluidProgram>
42 #include <osg/MatrixTransform>
45 #include "particles.hxx"
47 #if SG_OSG_VERSION >= 27004
48 #define OSG_PARTICLE_FIX 1
53 void GlobalParticleCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
55 enabled = !enabledNode || enabledNode->getBoolValue();
59 = SGQuatd::fromLonLatDeg(modelRoot->getFloatValue("/position/longitude-deg",0),
60 modelRoot->getFloatValue("/position/latitude-deg",0));
61 osg::Matrix om(toOsg(q));
62 osg::Vec3 v(0,0,9.81);
63 gravity = om.preMult(v);
64 // NOTE: THIS WIND COMPUTATION DOESN'T SEEM TO AFFECT PARTICLES
65 const osg::Vec3& zUpWind = Particles::getWindVector();
66 osg::Vec3 w(zUpWind.y(), zUpWind.x(), -zUpWind.z());
69 // SG_LOG(SG_GENERAL, SG_ALERT,
70 // "wind vector:" << w[0] << "," <<w[1] << "," << w[2]);
75 osg::Vec3 GlobalParticleCallback::gravity;
76 osg::Vec3 GlobalParticleCallback::wind;
77 bool GlobalParticleCallback::enabled = true;
78 SGConstPropertyNode_ptr GlobalParticleCallback::enabledNode = 0;
80 osg::ref_ptr<osg::Group> Particles::commonRoot;
81 osg::ref_ptr<osgParticle::ParticleSystemUpdater> Particles::psu = new osgParticle::ParticleSystemUpdater;
82 osg::ref_ptr<osg::Geode> Particles::commonGeode = new osg::Geode;;
83 osg::Vec3 Particles::_wind;
84 bool Particles::_frozen = false;
86 Particles::Particles() :
92 template <typename Object>
95 PointerGuard() : _ptr(0) {}
96 Object* get() { return _ptr; }
97 Object* operator () ()
107 osg::Group* Particles::getCommonRoot()
109 if(!commonRoot.valid())
111 SG_LOG(SG_GENERAL, SG_DEBUG, "Particle common root called!\n");
112 commonRoot = new osg::Group;
113 commonRoot.get()->setName("common particle system root");
114 commonGeode.get()->setName("common particle system geode");
115 commonRoot.get()->addChild(commonGeode.get());
116 commonRoot.get()->addChild(psu.get());
118 return commonRoot.get();
121 void transformParticles(osgParticle::ParticleSystem* particleSys,
122 const osg::Matrix& mat)
124 const int numParticles = particleSys->numParticles();
125 if (particleSys->areAllParticlesDead())
127 for (int i = 0; i < numParticles; ++i) {
128 osgParticle::Particle* P = particleSys->getParticle(i);
131 P->transformPositionVelocity(mat);
135 osg::Group * Particles::appendParticles(const SGPropertyNode* configNode,
136 SGPropertyNode* modelRoot,
137 const osgDB::Options*
140 SG_LOG(SG_GENERAL, SG_DEBUG, "Setting up a particle system!\n");
142 osgParticle::ParticleSystem *particleSys;
144 //create a generic particle system
145 std::string type = configNode->getStringValue("type", "normal");
146 if (type == "normal")
147 particleSys = new osgParticle::ParticleSystem;
149 particleSys = new osgParticle::ConnectedParticleSystem;
150 //may not be used depending on the configuration
151 PointerGuard<Particles> callback;
153 getPSU()->addParticleSystem(particleSys);
154 getPSU()->setUpdateCallback(new GlobalParticleCallback(modelRoot));
155 //contains counter, placer and shooter by default
156 osgParticle::ModularEmitter* emitter = new osgParticle::ModularEmitter;
158 emitter->setParticleSystem(particleSys);
160 // Set up the alignment node ("stolen" from animation.cxx)
161 // XXX Order of rotations is probably not correct.
162 osg::MatrixTransform *align = new osg::MatrixTransform;
163 osg::Matrix res_matrix;
164 res_matrix.makeRotate(
165 configNode->getFloatValue("offsets/pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
167 configNode->getFloatValue("offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
169 configNode->getFloatValue("offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
173 tmat.makeTranslate(configNode->getFloatValue("offsets/x-m", 0.0),
174 configNode->getFloatValue("offsets/y-m", 0.0),
175 configNode->getFloatValue("offsets/z-m", 0.0));
176 align->setMatrix(res_matrix * tmat);
178 align->setName("particle align");
180 //if (dynamic_cast<CustomModularEmitter*>(emitter)==0) SG_LOG(SG_GENERAL, SG_ALERT, "observer error\n");
181 //align->addObserver(dynamic_cast<CustomModularEmitter*>(emitter));
183 align->addChild(emitter);
185 //this name can be used in the XML animation as if it was a submodel
186 std::string name = configNode->getStringValue("name", "");
188 align->setName(name);
189 std::string attach = configNode->getStringValue("attach", "world");
190 if (attach == "local") { //local means attached to the model and not the world
191 osg::Geode* g = new osg::Geode;
193 g->addDrawable(particleSys);
194 #ifndef OSG_PARTICLE_FIX
195 emitter->setReferenceFrame(osgParticle::Emitter::ABSOLUTE_RF);
198 #ifdef OSG_PARTICLE_FIX
199 callback()->particleFrame = new osg::MatrixTransform();
200 osg::Geode* g = new osg::Geode;
201 g->addDrawable(particleSys);
202 callback()->particleFrame->addChild(g);
203 getCommonRoot()->addChild(callback()->particleFrame.get());
205 getCommonGeode()->addDrawable(particleSys);
208 std::string textureFile;
209 if (configNode->hasValue("texture")) {
210 //SG_LOG(SG_GENERAL, SG_ALERT,
211 // "requested:"<<configNode->getStringValue("texture","")<<"\n");
212 textureFile= osgDB::findFileInPath(configNode->getStringValue("texture",
214 options->getDatabasePathList());
215 //SG_LOG(SG_GENERAL, SG_ALERT, "found:"<<textureFile<<"\n");
217 //for(unsigned i = 0; i < options->getDatabasePathList().size(); ++i)
218 // SG_LOG(SG_GENERAL, SG_ALERT,
219 // "opts:"<<options->getDatabasePathList()[i]<<"\n");
222 particleSys->setDefaultAttributes(textureFile,
223 configNode->getBoolValue("emissive",
225 configNode->getBoolValue("lighting",
228 std::string alignstr = configNode->getStringValue("align", "billboard");
230 if (alignstr == "fixed")
231 particleSys->setParticleAlignment(osgParticle::ParticleSystem::FIXED);
233 const SGPropertyNode* placernode = configNode->getChild("placer");
236 std::string emitterType = placernode->getStringValue("type", "point");
238 if (emitterType == "sector") {
239 osgParticle::SectorPlacer *splacer = new osgParticle::SectorPlacer;
240 float minRadius, maxRadius, minPhi, maxPhi;
242 minRadius = placernode->getFloatValue("radius-min-m",0);
243 maxRadius = placernode->getFloatValue("radius-max-m",1);
244 minPhi = (placernode->getFloatValue("phi-min-deg",0)
245 * SG_DEGREES_TO_RADIANS);
246 maxPhi = (placernode->getFloatValue("phi-max-deg",360.0f)
247 * SG_DEGREES_TO_RADIANS);
249 splacer->setRadiusRange(minRadius, maxRadius);
250 splacer->setPhiRange(minPhi, maxPhi);
251 emitter->setPlacer(splacer);
252 } else if (emitterType == "segments") {
253 std::vector<SGPropertyNode_ptr> segments
254 = placernode->getChildren("vertex");
255 if (segments.size()>1) {
256 osgParticle::MultiSegmentPlacer *msplacer
257 = new osgParticle::MultiSegmentPlacer();
260 for (unsigned i = 0; i < segments.size(); ++i) {
261 x = segments[i]->getFloatValue("x-m",0);
262 y = segments[i]->getFloatValue("y-m",0);
263 z = segments[i]->getFloatValue("z-m",0);
264 msplacer->addVertex(x, y, z);
266 emitter->setPlacer(msplacer);
268 SG_LOG(SG_GENERAL, SG_ALERT,
269 "Detected particle system using segment(s) with less than 2 vertices\n");
271 } //else the default placer in ModularEmitter is used (PointPlacer)
274 const SGPropertyNode* shnode = configNode->getChild("shooter");
277 float minTheta, maxTheta, minPhi, maxPhi, speed, spread;
279 minTheta = (shnode->getFloatValue("theta-min-deg",0)
280 * SG_DEGREES_TO_RADIANS);
281 maxTheta = (shnode->getFloatValue("theta-max-deg",360.0f)
282 * SG_DEGREES_TO_RADIANS);
283 minPhi = shnode->getFloatValue("phi-min-deg",0)* SG_DEGREES_TO_RADIANS;
284 maxPhi = (shnode->getFloatValue("phi-max-deg",360.0f)
285 * SG_DEGREES_TO_RADIANS);
287 osgParticle::RadialShooter *shooter = new osgParticle::RadialShooter;
288 emitter->setShooter(shooter);
290 shooter->setThetaRange(minTheta, maxTheta);
291 shooter->setPhiRange(minPhi, maxPhi);
293 const SGPropertyNode* speednode = shnode->getChild("speed-mps");
296 if (speednode->hasValue("value")) {
297 speed = speednode->getFloatValue("value",0);
298 spread = speednode->getFloatValue("spread",0);
299 shooter->setInitialSpeedRange(speed-spread, speed+spread);
301 callback()->setupShooterSpeedData(speednode, modelRoot);
305 const SGPropertyNode* rotspeednode = shnode->getChild("rotation-speed");
308 float x1,y1,z1,x2,y2,z2;
309 x1 = rotspeednode->getFloatValue("x-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
310 y1 = rotspeednode->getFloatValue("y-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
311 z1 = rotspeednode->getFloatValue("z-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
312 x2 = rotspeednode->getFloatValue("x-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
313 y2 = rotspeednode->getFloatValue("y-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
314 z2 = rotspeednode->getFloatValue("z-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
315 shooter->setInitialRotationalSpeedRange(osg::Vec3f(x1,y1,z1), osg::Vec3f(x2,y2,z2));
317 } //else ModularEmitter uses the default RadialShooter
320 const SGPropertyNode* conditionNode = configNode->getChild("condition");
321 const SGPropertyNode* counternode = configNode->getChild("counter");
323 if (conditionNode || counternode) {
324 osgParticle::RandomRateCounter* counter
325 = new osgParticle::RandomRateCounter;
326 emitter->setCounter(counter);
327 float pps = 0.0f, spread = 0.0f;
330 const SGPropertyNode* ppsnode = counternode->getChild("particles-per-sec");
332 if (ppsnode->hasValue("value")) {
333 pps = ppsnode->getFloatValue("value",0);
334 spread = ppsnode->getFloatValue("spread",0);
335 counter->setRateRange(pps-spread, pps+spread);
337 callback()->setupCounterData(ppsnode, modelRoot);
343 callback()->setupCounterCondition(conditionNode, modelRoot);
344 callback()->setupCounterCondition(pps, spread);
346 } //TODO: else perhaps set higher values than default?
348 const SGPropertyNode* particlenode = configNode->getChild("particle");
350 osgParticle::Particle &particle
351 = particleSys->getDefaultParticleTemplate();
352 float r1=0, g1=0, b1=0, a1=1, r2=0, g2=0, b2=0, a2=1;
353 const SGPropertyNode* startcolornode
354 = particlenode->getNode("start/color");
355 if (startcolornode) {
356 const SGPropertyNode* componentnode
357 = startcolornode->getChild("red");
359 if (componentnode->hasValue("value"))
360 r1 = componentnode->getFloatValue("value",0);
362 callback()->setupColorComponent(componentnode, modelRoot,
365 componentnode = startcolornode->getChild("green");
367 if (componentnode->hasValue("value"))
368 g1 = componentnode->getFloatValue("value", 0);
370 callback()->setupColorComponent(componentnode, modelRoot,
373 componentnode = startcolornode->getChild("blue");
375 if (componentnode->hasValue("value"))
376 b1 = componentnode->getFloatValue("value",0);
378 callback()->setupColorComponent(componentnode, modelRoot,
381 componentnode = startcolornode->getChild("alpha");
383 if (componentnode->hasValue("value"))
384 a1 = componentnode->getFloatValue("value",0);
386 callback()->setupColorComponent(componentnode, modelRoot,
390 const SGPropertyNode* endcolornode = particlenode->getNode("end/color");
392 const SGPropertyNode* componentnode = endcolornode->getChild("red");
395 if (componentnode->hasValue("value"))
396 r2 = componentnode->getFloatValue("value",0);
398 callback()->setupColorComponent(componentnode, modelRoot,
401 componentnode = endcolornode->getChild("green");
403 if (componentnode->hasValue("value"))
404 g2 = componentnode->getFloatValue("value",0);
406 callback()->setupColorComponent(componentnode, modelRoot,
409 componentnode = endcolornode->getChild("blue");
411 if (componentnode->hasValue("value"))
412 b2 = componentnode->getFloatValue("value",0);
414 callback()->setupColorComponent(componentnode, modelRoot,
417 componentnode = endcolornode->getChild("alpha");
419 if (componentnode->hasValue("value"))
420 a2 = componentnode->getFloatValue("value",0);
422 callback()->setupColorComponent(componentnode, modelRoot,
426 particle.setColorRange(osgParticle::rangev4(osg::Vec4(r1,g1,b1,a1),
427 osg::Vec4(r2,g2,b2,a2)));
429 float startsize=1, endsize=0.1f;
430 const SGPropertyNode* startsizenode = particlenode->getNode("start/size");
432 if (startsizenode->hasValue("value"))
433 startsize = startsizenode->getFloatValue("value",0);
435 callback()->setupStartSizeData(startsizenode, modelRoot);
437 const SGPropertyNode* endsizenode = particlenode->getNode("end/size");
439 if (endsizenode->hasValue("value"))
440 endsize = endsizenode->getFloatValue("value",0);
442 callback()->setupEndSizeData(endsizenode, modelRoot);
444 particle.setSizeRange(osgParticle::rangef(startsize, endsize));
446 const SGPropertyNode* lifenode = particlenode->getChild("life-sec");
448 if (lifenode->hasValue("value"))
449 life = lifenode->getFloatValue("value",0);
451 callback()->setupLifeData(lifenode, modelRoot);
454 particle.setLifeTime(life);
455 if (particlenode->hasValue("radius-m"))
456 particle.setRadius(particlenode->getFloatValue("radius-m",0));
457 if (particlenode->hasValue("mass-kg"))
458 particle.setMass(particlenode->getFloatValue("mass-kg",0));
459 if (callback.get()) {
460 callback.get()->setupStaticColorComponent(r1, g1, b1, a1,
462 callback.get()->setupStaticSizeData(startsize, endsize);
464 //particle.setColorRange(osgParticle::rangev4( osg::Vec4(r1, g1, b1, a1), osg::Vec4(r2, g2, b2, a2)));
467 const SGPropertyNode* programnode = configNode->getChild("program");
468 osgParticle::FluidProgram *program = new osgParticle::FluidProgram();
471 std::string fluid = programnode->getStringValue("fluid", "air");
474 program->setFluidToAir();
476 program->setFluidToWater();
478 if (programnode->getBoolValue("gravity", true)) {
479 #ifdef OSG_PARTICLE_FIX
480 program->setToGravity();
482 if (attach == "world")
483 callback()->setupProgramGravity(true);
485 program->setToGravity();
488 program->setAcceleration(osg::Vec3(0,0,0));
490 if (programnode->getBoolValue("wind", true))
491 callback()->setupProgramWind(true);
493 program->setWind(osg::Vec3(0,0,0));
495 align->addChild(program);
497 program->setParticleSystem(particleSys);
500 if (callback.get()) { //this means we want property-driven changes
501 SG_LOG(SG_GENERAL, SG_DEBUG, "setting up particle system user data and callback\n");
502 //setup data and callback
503 callback.get()->setGeneralData(dynamic_cast<osgParticle::RadialShooter*>(emitter->getShooter()),
504 dynamic_cast<osgParticle::RandomRateCounter*>(emitter->getCounter()),
505 particleSys, program);
506 emitter->setUpdateCallback(callback.get());
512 void Particles::operator()(osg::Node* node, osg::NodeVisitor* nv)
514 //SG_LOG(SG_GENERAL, SG_ALERT, "callback!\n");
515 this->particleSys->setFrozen(_frozen);
519 shooter->setInitialSpeedRange(shooterValue->getValue(),
520 (shooterValue->getValue()
521 + shooterExtraRange));
523 counter->setRateRange(counterValue->getValue(),
524 counterValue->getValue() + counterExtraRange);
525 else if (counterCond)
526 counter->setRateRange(counterStaticValue,
527 counterStaticValue + counterStaticExtraRange);
528 if (!GlobalParticleCallback::getEnabled() || (counterCond && !counterCond->test()))
529 counter->setRateRange(0, 0);
530 bool colorchange=false;
531 for (int i = 0; i < 8; ++i) {
532 if (colorComponents[i]) {
533 staticColorComponents[i] = colorComponents[i]->getValue();
538 particleSys->getDefaultParticleTemplate().setColorRange(osgParticle::rangev4( Vec4(staticColorComponents[0], staticColorComponents[1], staticColorComponents[2], staticColorComponents[3]), Vec4(staticColorComponents[4], staticColorComponents[5], staticColorComponents[6], staticColorComponents[7])));
540 startSize = startSizeValue->getValue();
542 endSize = endSizeValue->getValue();
543 if (startSizeValue || endSizeValue)
544 particleSys->getDefaultParticleTemplate().setSizeRange(osgParticle::rangef(startSize, endSize));
546 particleSys->getDefaultParticleTemplate().setLifeTime(lifeValue->getValue());
547 #ifdef OSG_PARTICLE_FIX
548 if (particleFrame.valid()) {
549 MatrixList mlist = node->getWorldMatrices();
550 if (!mlist.empty()) {
551 const Matrix& particleMat = particleFrame->getMatrix();
552 Vec3d emitOrigin(mlist[0](3, 0), mlist[0](3, 1), mlist[0](3, 2));
554 = emitOrigin - Vec3d(particleMat(3, 0), particleMat(3, 1),
556 if (displace * displace > 10000.0 * 10000.0) {
557 // Make new frame for particle system, coincident with
558 // the emitter frame, but oriented with local Z.
559 SGGeod geod = SGGeod::fromCart(toSG(emitOrigin));
560 Matrix newParticleMat = makeZUpFrame(geod);
561 Matrix changeParticleFrame
562 = particleMat * Matrix::inverse(newParticleMat);
563 particleFrame->setMatrix(newParticleMat);
564 transformParticles(particleSys.get(), changeParticleFrame);
568 if (program.valid() && useWind)
569 program->setWind(_wind);
571 if (program.valid()) {
573 program->setAcceleration(GlobalParticleCallback::getGravityVector());
575 program->setWind(GlobalParticleCallback::getWindVector());
579 } // namespace simgear