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/math/SGMath.hxx>
25 #include <simgear/math/SGGeod.hxx>
26 #include <simgear/misc/sg_path.hxx>
27 #include <simgear/props/props.hxx>
28 #include <simgear/props/props_io.hxx>
29 #include <simgear/structure/OSGVersion.hxx>
31 #include <osgParticle/SmokeTrailEffect>
32 #include <osgParticle/FireEffect>
33 #include <osgParticle/ConnectedParticleSystem>
34 #include <osgParticle/MultiSegmentPlacer>
35 #include <osgParticle/SectorPlacer>
36 #include <osgParticle/ConstantRateCounter>
37 #include <osgParticle/ParticleSystemUpdater>
38 #include <osgParticle/ParticleSystem>
39 #include <osgParticle/FluidProgram>
43 #include <osg/MatrixTransform>
46 #include "particles.hxx"
48 #if SG_OSG_VERSION >= 27004
49 #define OSG_PARTICLE_FIX 1
54 void GlobalParticleCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
56 enabled = !enabledNode || enabledNode->getBoolValue();
60 = SGQuatd::fromLonLatDeg(modelRoot->getFloatValue("/position/longitude-deg",0),
61 modelRoot->getFloatValue("/position/latitude-deg",0));
62 osg::Matrix om(q.osg());
63 osg::Vec3 v(0,0,9.81);
64 gravity = om.preMult(v);
65 const osg::Vec3& zUpWind = Particles::getWindVector();
66 osg::Vec3 w(zUpWind.y(), zUpWind.x(), - zUpWind.z());
69 //SG_LOG(SG_GENERAL, SG_ALERT, "wind vector:"<<w[0]<<","<<w[1]<<","<<w[2]<<"\n");
74 osg::Vec3 GlobalParticleCallback::gravity;
75 osg::Vec3 GlobalParticleCallback::wind;
76 bool GlobalParticleCallback::enabled = true;
77 SGConstPropertyNode_ptr GlobalParticleCallback::enabledNode = 0;
79 osg::ref_ptr<osg::Group> Particles::commonRoot;
80 osg::ref_ptr<osgParticle::ParticleSystemUpdater> Particles::psu = new osgParticle::ParticleSystemUpdater;
81 osg::ref_ptr<osg::Geode> Particles::commonGeode = new osg::Geode;;
82 osg::Vec3 Particles::_wind;
84 Particles::Particles() :
90 template <typename Object>
93 PointerGuard() : _ptr(0) {}
94 Object* get() { return _ptr; }
95 Object* operator () ()
105 osg::Group* Particles::getCommonRoot()
107 if(!commonRoot.valid())
109 SG_LOG(SG_GENERAL, SG_DEBUG, "Particle common root called!\n");
110 commonRoot = new osg::Group;
111 commonRoot.get()->setName("common particle system root");
112 commonGeode.get()->setName("common particle system geode");
113 commonRoot.get()->addChild(commonGeode.get());
114 commonRoot.get()->addChild(psu.get());
116 return commonRoot.get();
119 void transformParticles(osgParticle::ParticleSystem* particleSys,
120 const osg::Matrix& mat)
122 const int numParticles = particleSys->numParticles();
123 if (particleSys->areAllParticlesDead())
125 for (int i = 0; i < numParticles; ++i) {
126 osgParticle::Particle* P = particleSys->getParticle(i);
129 P->transformPositionVelocity(mat);
133 osg::Group * Particles::appendParticles(const SGPropertyNode* configNode,
134 SGPropertyNode* modelRoot,
135 const osgDB::ReaderWriter::Options*
138 SG_LOG(SG_GENERAL, SG_DEBUG, "Setting up a particle system!\n");
140 osgParticle::ParticleSystem *particleSys;
142 //create a generic particle system
143 std::string type = configNode->getStringValue("type", "normal");
144 if (type == "normal")
145 particleSys = new osgParticle::ParticleSystem;
147 particleSys = new osgParticle::ConnectedParticleSystem;
148 //may not be used depending on the configuration
149 PointerGuard<Particles> callback;
151 getPSU()->addParticleSystem(particleSys);
152 getPSU()->setUpdateCallback(new GlobalParticleCallback(modelRoot));
153 //contains counter, placer and shooter by default
154 osgParticle::ModularEmitter* emitter = new osgParticle::ModularEmitter;
156 emitter->setParticleSystem(particleSys);
158 // Set up the alignment node ("stolen" from animation.cxx)
159 // XXX Order of rotations is probably not correct.
160 osg::MatrixTransform *align = new osg::MatrixTransform;
161 osg::Matrix res_matrix;
162 res_matrix.makeRotate(
163 configNode->getFloatValue("offsets/pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
165 configNode->getFloatValue("offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
167 configNode->getFloatValue("offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
171 tmat.makeTranslate(configNode->getFloatValue("offsets/x-m", 0.0),
172 configNode->getFloatValue("offsets/y-m", 0.0),
173 configNode->getFloatValue("offsets/z-m", 0.0));
174 align->setMatrix(res_matrix * tmat);
176 align->setName("particle align");
178 //if (dynamic_cast<CustomModularEmitter*>(emitter)==0) SG_LOG(SG_GENERAL, SG_ALERT, "observer error\n");
179 //align->addObserver(dynamic_cast<CustomModularEmitter*>(emitter));
181 align->addChild(emitter);
183 //this name can be used in the XML animation as if it was a submodel
184 std::string name = configNode->getStringValue("name", "");
186 align->setName(name);
187 std::string attach = configNode->getStringValue("attach", "world");
188 if (attach == "local") { //local means attached to the model and not the world
189 osg::Geode* g = new osg::Geode;
191 g->addDrawable(particleSys);
192 #ifndef OSG_PARTICLE_FIX
193 emitter->setReferenceFrame(osgParticle::Emitter::ABSOLUTE_RF);
196 #ifdef OSG_PARTICLE_FIX
197 callback()->particleFrame = new osg::MatrixTransform();
198 osg::Geode* g = new osg::Geode;
199 g->addDrawable(particleSys);
200 callback()->particleFrame->addChild(g);
201 getCommonRoot()->addChild(callback()->particleFrame.get());
203 getCommonGeode()->addDrawable(particleSys);
206 std::string textureFile;
207 if (configNode->hasValue("texture")) {
208 //SG_LOG(SG_GENERAL, SG_ALERT,
209 // "requested:"<<configNode->getStringValue("texture","")<<"\n");
210 textureFile= osgDB::findFileInPath(configNode->getStringValue("texture",
212 options->getDatabasePathList());
213 //SG_LOG(SG_GENERAL, SG_ALERT, "found:"<<textureFile<<"\n");
215 //for(unsigned i = 0; i < options->getDatabasePathList().size(); ++i)
216 // SG_LOG(SG_GENERAL, SG_ALERT,
217 // "opts:"<<options->getDatabasePathList()[i]<<"\n");
220 particleSys->setDefaultAttributes(textureFile,
221 configNode->getBoolValue("emissive",
223 configNode->getBoolValue("lighting",
226 std::string alignstr = configNode->getStringValue("align", "billboard");
228 if (alignstr == "fixed")
229 particleSys->setParticleAlignment(osgParticle::ParticleSystem::FIXED);
231 const SGPropertyNode* placernode = configNode->getChild("placer");
234 std::string emitterType = placernode->getStringValue("type", "point");
236 if (emitterType == "sector") {
237 osgParticle::SectorPlacer *splacer = new osgParticle::SectorPlacer;
238 float minRadius, maxRadius, minPhi, maxPhi;
240 minRadius = placernode->getFloatValue("radius-min-m",0);
241 maxRadius = placernode->getFloatValue("radius-max-m",1);
242 minPhi = (placernode->getFloatValue("phi-min-deg",0)
243 * SG_DEGREES_TO_RADIANS);
244 maxPhi = (placernode->getFloatValue("phi-max-deg",360.0f)
245 * SG_DEGREES_TO_RADIANS);
247 splacer->setRadiusRange(minRadius, maxRadius);
248 splacer->setPhiRange(minPhi, maxPhi);
249 emitter->setPlacer(splacer);
250 } else if (emitterType == "segments") {
251 std::vector<SGPropertyNode_ptr> segments
252 = placernode->getChildren("vertex");
253 if (segments.size()>1) {
254 osgParticle::MultiSegmentPlacer *msplacer
255 = new osgParticle::MultiSegmentPlacer();
258 for (unsigned i = 0; i < segments.size(); ++i) {
259 x = segments[i]->getFloatValue("x-m",0);
260 y = segments[i]->getFloatValue("y-m",0);
261 z = segments[i]->getFloatValue("z-m",0);
262 msplacer->addVertex(x, y, z);
264 emitter->setPlacer(msplacer);
266 SG_LOG(SG_GENERAL, SG_ALERT,
267 "Detected particle system using segment(s) with less than 2 vertices\n");
269 } //else the default placer in ModularEmitter is used (PointPlacer)
272 const SGPropertyNode* shnode = configNode->getChild("shooter");
275 float minTheta, maxTheta, minPhi, maxPhi, speed, spread;
277 minTheta = (shnode->getFloatValue("theta-min-deg",0)
278 * SG_DEGREES_TO_RADIANS);
279 maxTheta = (shnode->getFloatValue("theta-max-deg",360.0f)
280 * SG_DEGREES_TO_RADIANS);
281 minPhi = shnode->getFloatValue("phi-min-deg",0)* SG_DEGREES_TO_RADIANS;
282 maxPhi = (shnode->getFloatValue("phi-max-deg",360.0f)
283 * SG_DEGREES_TO_RADIANS);
285 osgParticle::RadialShooter *shooter = new osgParticle::RadialShooter;
286 emitter->setShooter(shooter);
288 shooter->setThetaRange(minTheta, maxTheta);
289 shooter->setPhiRange(minPhi, maxPhi);
291 const SGPropertyNode* speednode = shnode->getChild("speed-mps");
294 if (speednode->hasValue("value")) {
295 speed = speednode->getFloatValue("value",0);
296 spread = speednode->getFloatValue("spread",0);
297 shooter->setInitialSpeedRange(speed-spread, speed+spread);
299 callback()->setupShooterSpeedData(speednode, modelRoot);
303 const SGPropertyNode* rotspeednode = shnode->getChild("rotation-speed");
306 float x1,y1,z1,x2,y2,z2;
307 x1 = rotspeednode->getFloatValue("x-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
308 y1 = rotspeednode->getFloatValue("y-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
309 z1 = rotspeednode->getFloatValue("z-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
310 x2 = rotspeednode->getFloatValue("x-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
311 y2 = rotspeednode->getFloatValue("y-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
312 z2 = rotspeednode->getFloatValue("z-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
313 shooter->setInitialRotationalSpeedRange(osg::Vec3f(x1,y1,z1), osg::Vec3f(x2,y2,z2));
315 } //else ModularEmitter uses the default RadialShooter
318 const SGPropertyNode* conditionNode = configNode->getChild("condition");
319 const SGPropertyNode* counternode = configNode->getChild("counter");
321 if (conditionNode || counternode) {
322 osgParticle::RandomRateCounter* counter
323 = new osgParticle::RandomRateCounter;
324 emitter->setCounter(counter);
325 float pps = 0.0f, spread = 0.0f;
328 const SGPropertyNode* ppsnode = counternode->getChild("particles-per-sec");
330 if (ppsnode->hasValue("value")) {
331 pps = ppsnode->getFloatValue("value",0);
332 spread = ppsnode->getFloatValue("spread",0);
333 counter->setRateRange(pps-spread, pps+spread);
335 callback()->setupCounterData(ppsnode, modelRoot);
341 callback()->setupCounterCondition(conditionNode, modelRoot);
342 callback()->setupCounterCondition(pps, spread);
344 } //TODO: else perhaps set higher values than default?
346 const SGPropertyNode* particlenode = configNode->getChild("particle");
348 osgParticle::Particle &particle
349 = particleSys->getDefaultParticleTemplate();
350 float r1=0, g1=0, b1=0, a1=1, r2=0, g2=0, b2=0, a2=1;
351 const SGPropertyNode* startcolornode
352 = particlenode->getNode("start/color");
353 if (startcolornode) {
354 const SGPropertyNode* componentnode
355 = startcolornode->getChild("red");
357 if (componentnode->hasValue("value"))
358 r1 = componentnode->getFloatValue("value",0);
360 callback()->setupColorComponent(componentnode, modelRoot,
363 componentnode = startcolornode->getChild("green");
365 if (componentnode->hasValue("value"))
366 g1 = componentnode->getFloatValue("value", 0);
368 callback()->setupColorComponent(componentnode, modelRoot,
371 componentnode = startcolornode->getChild("blue");
373 if (componentnode->hasValue("value"))
374 b1 = componentnode->getFloatValue("value",0);
376 callback()->setupColorComponent(componentnode, modelRoot,
379 componentnode = startcolornode->getChild("alpha");
381 if (componentnode->hasValue("value"))
382 a1 = componentnode->getFloatValue("value",0);
384 callback()->setupColorComponent(componentnode, modelRoot,
388 const SGPropertyNode* endcolornode = particlenode->getNode("end/color");
390 const SGPropertyNode* componentnode = endcolornode->getChild("red");
393 if (componentnode->hasValue("value"))
394 r2 = componentnode->getFloatValue("value",0);
396 callback()->setupColorComponent(componentnode, modelRoot,
399 componentnode = endcolornode->getChild("green");
401 if (componentnode->hasValue("value"))
402 g2 = componentnode->getFloatValue("value",0);
404 callback()->setupColorComponent(componentnode, modelRoot,
407 componentnode = endcolornode->getChild("blue");
409 if (componentnode->hasValue("value"))
410 b2 = componentnode->getFloatValue("value",0);
412 callback()->setupColorComponent(componentnode, modelRoot,
415 componentnode = endcolornode->getChild("alpha");
417 if (componentnode->hasValue("value"))
418 a2 = componentnode->getFloatValue("value",0);
420 callback()->setupColorComponent(componentnode, modelRoot,
424 particle.setColorRange(osgParticle::rangev4(osg::Vec4(r1,g1,b1,a1),
425 osg::Vec4(r2,g2,b2,a2)));
427 float startsize=1, endsize=0.1f;
428 const SGPropertyNode* startsizenode = particlenode->getNode("start/size");
430 if (startsizenode->hasValue("value"))
431 startsize = startsizenode->getFloatValue("value",0);
433 callback()->setupStartSizeData(startsizenode, modelRoot);
435 const SGPropertyNode* endsizenode = particlenode->getNode("end/size");
437 if (endsizenode->hasValue("value"))
438 endsize = endsizenode->getFloatValue("value",0);
440 callback()->setupEndSizeData(endsizenode, modelRoot);
442 particle.setSizeRange(osgParticle::rangef(startsize, endsize));
444 const SGPropertyNode* lifenode = particlenode->getChild("life-sec");
446 if (lifenode->hasValue("value"))
447 life = lifenode->getFloatValue("value",0);
449 callback()->setupLifeData(lifenode, modelRoot);
452 particle.setLifeTime(life);
453 if (particlenode->hasValue("radius-m"))
454 particle.setRadius(particlenode->getFloatValue("radius-m",0));
455 if (particlenode->hasValue("mass-kg"))
456 particle.setMass(particlenode->getFloatValue("mass-kg",0));
457 if (callback.get()) {
458 callback.get()->setupStaticColorComponent(r1, g1, b1, a1,
460 callback.get()->setupStaticSizeData(startsize, endsize);
462 //particle.setColorRange(osgParticle::rangev4( osg::Vec4(r1, g1, b1, a1), osg::Vec4(r2, g2, b2, a2)));
465 const SGPropertyNode* programnode = configNode->getChild("program");
466 osgParticle::FluidProgram *program = new osgParticle::FluidProgram();
469 std::string fluid = programnode->getStringValue("fluid", "air");
472 program->setFluidToAir();
474 program->setFluidToWater();
476 if (programnode->getBoolValue("gravity", true)) {
477 #ifdef OSG_PARTICLE_FIX
478 program->setToGravity();
480 if (attach == "world")
481 callback()->setupProgramGravity(true);
483 program->setToGravity();
486 program->setAcceleration(osg::Vec3(0,0,0));
488 if (programnode->getBoolValue("wind", true))
489 callback()->setupProgramWind(true);
491 program->setWind(osg::Vec3(0,0,0));
493 align->addChild(program);
495 program->setParticleSystem(particleSys);
498 if (callback.get()) { //this means we want property-driven changes
499 SG_LOG(SG_GENERAL, SG_DEBUG, "setting up particle system user data and callback\n");
500 //setup data and callback
501 callback.get()->setGeneralData(dynamic_cast<osgParticle::RadialShooter*>(emitter->getShooter()),
502 dynamic_cast<osgParticle::RandomRateCounter*>(emitter->getCounter()),
503 particleSys, program);
504 emitter->setUpdateCallback(callback.get());
510 void Particles::operator()(osg::Node* node, osg::NodeVisitor* nv)
512 //SG_LOG(SG_GENERAL, SG_ALERT, "callback!\n");
515 shooter->setInitialSpeedRange(shooterValue->getValue(),
516 (shooterValue->getValue()
517 + shooterExtraRange));
519 counter->setRateRange(counterValue->getValue(),
520 counterValue->getValue() + counterExtraRange);
521 else if (counterCond)
522 counter->setRateRange(counterStaticValue,
523 counterStaticValue + counterStaticExtraRange);
524 if (!GlobalParticleCallback::getEnabled() || (counterCond && !counterCond->test()))
525 counter->setRateRange(0, 0);
526 bool colorchange=false;
527 for (int i = 0; i < 8; ++i) {
528 if (colorComponents[i]) {
529 staticColorComponents[i] = colorComponents[i]->getValue();
534 particleSys->getDefaultParticleTemplate().setColorRange(osgParticle::rangev4( Vec4(staticColorComponents[0], staticColorComponents[1], staticColorComponents[2], staticColorComponents[3]), Vec4(staticColorComponents[4], staticColorComponents[5], staticColorComponents[6], staticColorComponents[7])));
536 startSize = startSizeValue->getValue();
538 endSize = endSizeValue->getValue();
539 if (startSizeValue || endSizeValue)
540 particleSys->getDefaultParticleTemplate().setSizeRange(osgParticle::rangef(startSize, endSize));
542 particleSys->getDefaultParticleTemplate().setLifeTime(lifeValue->getValue());
543 #ifdef OSG_PARTICLE_FIX
544 if (particleFrame.valid()) {
545 MatrixList mlist = node->getWorldMatrices();
546 if (!mlist.empty()) {
547 const Matrix& particleMat = particleFrame->getMatrix();
548 Vec3d emitOrigin(mlist[0](3, 0), mlist[0](3, 1), mlist[0](3, 2));
550 = emitOrigin - Vec3d(particleMat(3, 0), particleMat(3, 1),
552 if (displace * displace > 10000.0 * 10000.0) {
553 // Make new frame for particle system, coincident with
554 // the emitter frame, but oriented with local Z.
555 SGGeod geod = SGGeod::fromCart(SGVec3d(emitOrigin));
556 Matrix newParticleMat = geod.makeZUpFrame();
557 Matrix changeParticleFrame
558 = particleMat * Matrix::inverse(newParticleMat);
559 particleFrame->setMatrix(newParticleMat);
560 transformParticles(particleSys.get(), changeParticleFrame);
564 if (program.valid() && useWind)
565 program->setWind(_wind);
567 if (program.valid()) {
569 program->setAcceleration(GlobalParticleCallback::getGravityVector());
571 program->setWind(GlobalParticleCallback::getWindVector());
575 } // namespace simgear