Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/particles/particle_system.cc @ 6612

Last change on this file since 6612 was 6612, checked in by bensch, 18 years ago

orxonox/trunk: particle_system is now loaded differently

ParticleEngine is NOT needed anymore, this is faster and better

File size: 18.5 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: ...
14*/
15
16#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_GRAPHICS
17
18#include "particle_system.h"
19
20#include "particle_emitter.h"
21#include "particle_engine.h"
22
23#include "field.h"
24#include "model.h"
25
26#include "load_param.h"
27#include "factory.h"
28#include "material.h"
29#include "state.h"
30#include "shell_command.h"
31
32#include "parser/tinyxml/tinyxml.h"
33#include <algorithm>
34
35
36CREATE_FACTORY(ParticleSystem, CL_PARTICLE_SYSTEM);
37SHELL_COMMAND(texture, ParticleSystem, setMaterialTexture)
38    ->defaultValues(1, "maps/evil-flower.png");
39
40using namespace std;
41
42/**
43 *  standard constructor
44 * @param maxCount the Count of particles in the System
45 * @param type The Type of the ParticleSystem
46*/
47ParticleSystem::ParticleSystem (unsigned int maxCount, PARTICLE_TYPE type)
48{
49  this->init();
50
51  this->setMaxCount(maxCount);
52  this->setType(type, 1);
53}
54
55/**
56 * @brief creates a Particle System out of a XML-element
57 * @param root: the XML-element to load from
58 */
59ParticleSystem::ParticleSystem(const TiXmlElement* root)
60{
61  this->init();
62
63  this->loadParams(root);
64}
65
66/**
67 *  standard deconstructor
68*/
69ParticleSystem::~ParticleSystem()
70{
71  // delete what has to be deleted here
72   ParticleEngine::getInstance()->removeSystem(this);
73
74   // deleting all the living Particles
75   while (this->particles)
76     {
77       Particle* tmpDelPart = this->particles;
78       this->particles = this->particles->next;
79       delete tmpDelPart;
80     }
81
82   // deleting all the dead particles
83   while (this->deadList)
84     {
85       Particle* tmpDelPart = this->deadList;
86       this->deadList = this->deadList->next;
87       delete tmpDelPart;
88     }
89
90   if (this->material)
91     delete this->material;
92}
93
94/**
95  \brief initializes the ParticleSystem with default values
96*/
97void ParticleSystem::init()
98{
99  this->setClassID(CL_PARTICLE_SYSTEM, "ParticleSystem");
100
101  this->material = NULL;
102  this->setMaxCount(PARTICLE_DEFAULT_MAX_COUNT);
103  this->count = 0;
104  this->particles = NULL;
105  this->deadList = NULL;
106  this->setConserve(1);
107  this->setLifeSpan(1);
108  this->glID = NULL;
109  this->setType(PARTICLE_DEFAULT_TYPE, 1);
110  ParticleEngine::getInstance()->addSystem(this);
111
112  this->toList(OM_ENVIRON);
113}
114
115
116/**
117 * loads Parameters from a TiXmlElement
118 * @param root the XML-element to load from.
119 */
120void ParticleSystem::loadParams(const TiXmlElement* root)
121{
122  WorldEntity::loadParams(root);
123  PhysicsInterface::loadParams(root);
124
125  LoadParam(root, "max-count", this, ParticleSystem, setMaxCount)
126      .describe("the maximal count of Particles, that can be emitted into this system");
127
128  LoadParam(root, "life-span", this, ParticleSystem, setLifeSpan)
129      .describe("sets the life-span of the Particles.");
130
131  LoadParam(root, "conserve", this, ParticleSystem, setConserve)
132      .describe("sets the Conserve factor of the Particles (1.0: they keep all their energy, 0.0:they keep no energy)");
133
134  LoadParam(root, "type", this, ParticleSystem, setType)
135      .describe("sets the type of the Particles, (dot, spark, sprite or model)");
136
137  LoadParam(root, "texture", this, ParticleSystem, setMaterialTexture);
138  LoadParamXML(root, "emitter", this, ParticleSystem, addEmitterXML);
139
140  LOAD_PARAM_START_CYCLE(root, element);
141  {
142    element->ToText();
143  // PER-PARTICLE-ATTRIBUTES:
144    LoadParam_CYCLE(element, "radius", this, ParticleSystem, setRadius)
145        .describe("The Radius of each particle over time (TimeIndex [0-1], radius at TimeIndex, randomRadius at TimeIndex)");
146
147    LoadParam_CYCLE(element, "mass", this, ParticleSystem, setMass)
148        .describe("The Mass of each particle over time (TimeIndex: [0-1], mass at TimeIndex, randomMass at TimeIndex)");
149
150    LoadParam_CYCLE(element, "color", this, ParticleSystem, setColor)
151        .describe("The Color of each particle over time (TimeIndex: [0-1], red: [0-1], green: [0-1], blue: [0-1], alpha: [0-1])");
152  }
153  LOAD_PARAM_END_CYCLE(element);
154}
155
156/**
157* @param maxCount the maximum count of particles that can be emitted
158 */
159void ParticleSystem::setMaxCount(int maxCount)
160{
161  this->maxCount = maxCount;
162}
163
164
165/**
166 * @param particleType the type of particles in this System
167 * @param count how many particles (in PARTICLE_MULTI-mode)
168   @todo this will be different
169*/
170void ParticleSystem::setType(const char* particleType)
171{
172  if (!strcmp(particleType, "dot"))
173    this->setType(PARTICLE_DOT);
174  else if(!strcmp(particleType, "spark"))
175    this->setType(PARTICLE_SPARK);
176  else if(!strcmp(particleType, "model"))
177    this->setType(PARTICLE_MODEL);
178  else // if (strcmp(particleType, "SPRITE"))
179    this->setType(PARTICLE_SPRITE);
180}
181
182/**
183 * @param particleType the type of particles in this System
184 * @param count how many particles (in PARTICLE_MULTI-mode)
185   @todo this MUST be different
186*/
187void ParticleSystem::setType(PARTICLE_TYPE particleType, int count)
188{
189  this->particleType = particleType;
190  this->dialectCount = count;
191  //  if (glID != NULL)
192  //    delete glID;
193
194  //  glID = new GLuint[count];
195  //  for (int i = 0; i< count; i++)
196  //    glID[i] = 0;
197
198  //  glID[0] = glGenLists(count);
199  if (this->material)
200    delete this->material;
201  this->material = NULL;
202
203  switch (this->particleType)
204    {
205      case PARTICLE_SPRITE:
206        this->material = new Material("transperencyMap");
207        this->material->setDiffuseMap("maps/radialTransparency.png");
208      //  material->setTransparency(.5);
209        break;
210  }
211}
212
213// setting properties
214/**
215 *  sets the material to an external material
216 * @param material: the material to set this material to.
217
218   !! important if the extern material gets deleted it MUST be unregistered here or segfault !!
219*/
220void ParticleSystem::setMaterial(Material* material)
221{
222  this->material = material;
223}
224
225void ParticleSystem::setMaterialTexture(const char* textureFile)
226{
227  if (this->material != NULL)
228    this->material->setDiffuseMap(textureFile);
229}
230
231/**
232 *  Sets the lifespan of newly created particles
233*/
234void ParticleSystem::setLifeSpan(float lifeSpan, float randomLifeSpan)
235{
236  this->lifeSpan = lifeSpan;
237  this->randomLifeSpan = randomLifeSpan;
238}
239
240/**
241 *  sets the conserve Factor of newly created particles
242*/
243void ParticleSystem::setConserve(float conserve)
244{
245  if (conserve > 1.0)
246    this->conserve = 1.0;
247  else if (conserve < 0.0)
248    this->conserve = 0.0;
249  else
250    this->conserve = conserve;
251}
252
253/////////////////////////////
254/* Per-Particle Attributes */
255/////////////////////////////
256/**
257 *  sets a key in the radius-animation on a per-particle basis
258 * @param lifeCycleTime the time (partilceLifeTime/particleAge) [0-1]
259 * @param radius the radius at this position
260 * @param randRadius the randRadius at this position
261*/
262void ParticleSystem::setRadius(float lifeCycleTime, float radius, float randRadius)
263{
264  this->radiusAnim.changeEntry(lifeCycleTime, radius);
265  this->randRadiusAnim.changeEntry(lifeCycleTime, randRadius);
266}
267
268/**
269 *  sets a key in the mass-animation on a per-particle basis
270 * @param lifeCycleTime the time (partilceLifeTime/particleAge) [0-1]
271 * @param mass the mass at this position
272 * @param randMass the randomMass at this position
273*/
274void ParticleSystem::setMass(float lifeCycleTime, float mass, float randMass)
275{
276  this->massAnim.changeEntry(lifeCycleTime, mass);
277  this->randMassAnim.changeEntry(lifeCycleTime, randMass);
278}
279
280/**
281 *  sets a key in the color-animation on a per-particle basis
282 * @param lifeCycleTime: the time (partilceLifeTime/particleAge) [0-1]
283 * @param red: red
284 * @param green: green
285 * @param blue: blue
286 * @param alpha: alpha
287*/
288void ParticleSystem::setColor(float lifeCycleTime, float red, float green, float blue, float alpha)
289{
290  this->colorAnim[0].changeEntry(lifeCycleTime, red);
291  this->colorAnim[1].changeEntry(lifeCycleTime, green);
292  this->colorAnim[2].changeEntry(lifeCycleTime, blue);
293  this->colorAnim[3].changeEntry(lifeCycleTime, alpha);
294}
295
296
297void ParticleSystem::addEmitter(ParticleEmitter* emitter)
298{
299  this->emitters.push_back(emitter);
300}
301
302void ParticleSystem::addEmitterXML(const TiXmlElement* emitterRoot)
303{
304  ParticleEmitter* emitter = new ParticleEmitter(emitterRoot);
305  this->addEmitter(emitter);
306}
307
308
309void ParticleSystem::removeEmitter(ParticleEmitter* emitter)
310{
311  std::list<ParticleEmitter*>::iterator it = std::find(this->emitters.begin(), this->emitters.end(), emitter);
312  if (it != this->emitters.end())
313    this->emitters.erase(it);
314}
315
316/**
317 *  ticks the system.
318 * @param dt the time to tick all the Particles of the System
319
320   this is used to get all the particles some motion
321*/
322void ParticleSystem::tick(float dt)
323{
324  Particle* tickPart = particles;  // the particle to Tick
325  Particle* prevPart = NULL;
326  while (likely(tickPart != NULL))
327    {
328      // applying force to the System.
329      if (likely (tickPart->mass > 0.0))
330        tickPart->velocity += tickPart->extForce / tickPart->mass * dt;
331      // rendering new position.
332      tickPart->position += tickPart->velocity * dt;
333      tickPart->orientation += tickPart->momentum *dt;
334
335      tickPart->radius = radiusAnim.getValue(tickPart->lifeCycle)
336        + randRadiusAnim.getValue(tickPart->lifeCycle) * tickPart->radiusRand;
337
338      tickPart->mass = massAnim.getValue(tickPart->lifeCycle)
339        + randMassAnim.getValue(tickPart->lifeCycle) * tickPart->massRand;
340
341      tickPart->extForce = Vector(0,0,0);
342
343      // applying Color
344      tickPart->color[0] = this->colorAnim[0].getValue(tickPart->lifeCycle);
345      tickPart->color[1] = this->colorAnim[1].getValue(tickPart->lifeCycle);
346      tickPart->color[2] = this->colorAnim[2].getValue(tickPart->lifeCycle);
347      tickPart->color[3] = this->colorAnim[3].getValue(tickPart->lifeCycle);
348
349      // many more to come
350
351      if (this->conserve < 1.0)
352      {
353        tickPart->velocity *= this->conserve;
354        tickPart->momentum *= this->conserve;
355      }
356      // find out if we have to delete tickPart
357      if (unlikely((tickPart->lifeCycle += dt/tickPart->lifeTime) >= 1.0))
358        {
359          // remove the particle from the list
360          if (likely(prevPart != NULL))
361            {
362              prevPart->next = tickPart->next;
363              tickPart->next = this->deadList;
364              this->deadList = tickPart;
365              tickPart = prevPart->next;
366            }
367          else
368            {
369              prevPart = NULL;
370              this->particles = tickPart->next;
371              tickPart->next = this->deadList;
372              this->deadList = tickPart;
373              tickPart = this->particles;
374            }
375          --this->count;
376        }
377      else
378        {
379          prevPart = tickPart;
380          tickPart = tickPart->next;
381        }
382    }
383
384    std::list<ParticleEmitter*>::iterator emitter;
385    for (emitter = this->emitters.begin(); emitter != this->emitters.end(); emitter++)
386      (*emitter)->tick(dt, this);
387}
388
389/**
390  *  applies some force to a Particle.
391  * @param field the Field to apply.
392 */
393void ParticleSystem::applyField(Field* field)
394{
395  Particle* tickPart = particles;
396  while (tickPart)
397    {
398      tickPart->extForce += field->calcForce(tickPart->position);
399      tickPart = tickPart->next;
400    }
401}
402
403
404/**
405 * @returns the count of Faces of this ParticleSystem
406 */
407unsigned int ParticleSystem::getFaceCount() const
408{
409  switch (this->particleType)
410  {
411    case PARTICLE_SPRITE:
412      return this->count;
413      break;
414    case PARTICLE_MODEL:
415      if (this->getModel(0))
416        return this->count * this->getModel()->getTriangleCount();
417      break;
418  }
419}
420
421
422/**
423 *  draws all the Particles of this System
424
425   The Cases in this Function all do the same:
426   Drawing all the particles with the appropriate Type.
427   This is just the fastest Way to do this, but will most likely be changed in the future.
428 */
429void ParticleSystem::draw() const
430{
431  glPushAttrib(GL_ENABLE_BIT);
432
433  Particle* drawPart = particles;
434
435  switch (this->particleType)
436  {
437    default:
438    case PARTICLE_SPRITE:
439      glDisable(GL_LIGHTING);
440      glMatrixMode(GL_MODELVIEW);
441      glDepthMask(GL_FALSE);
442
443      material->select();
444      glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA);
445
446      //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_MODULATE);
447
448
449      while (likely(drawPart != NULL))
450      {
451        glColor4fv(drawPart->color);
452          //! @todo implement a faster code for the look-at Camera algorithm.
453
454        const PNode* camera = State::getCamera();  //!< @todo MUST be different
455        Vector cameraPos = camera->getAbsCoor();
456        Vector cameraTargetPos = State::getCameraTarget()->getAbsCoor();
457        Vector view = cameraTargetPos - cameraPos;
458        Vector up = Vector(0, 1, 0);
459        up = camera->getAbsDir().apply(up);
460        Vector h = up.cross(view);
461        Vector v = h.cross(view);
462        h.normalize();
463        v.normalize();
464        v *= .5 * drawPart->radius;
465        h *= .5 * drawPart->radius;
466
467        glBegin(GL_TRIANGLE_STRIP);
468        glTexCoord2i(1, 1);
469        glVertex3f(drawPart->position.x - h.x - v.x,
470                   drawPart->position.y - h.y - v.y,
471                   drawPart->position.z - h.z - v.z);
472        glTexCoord2i(0, 1);
473        glVertex3f(drawPart->position.x - h.x + v.x,
474                   drawPart->position.y - h.y + v.y,
475                   drawPart->position.z - h.z + v.z);
476        glTexCoord2i(1, 0);
477        glVertex3f(drawPart->position.x + h.x - v.x,
478                   drawPart->position.y + h.y - v.y,
479                   drawPart->position.z + h.z - v.z);
480        glTexCoord2i(0, 0);
481        glVertex3f(drawPart->position.x + h.x + v.x,
482                   drawPart->position.y + h.y + v.y,
483                   drawPart->position.z + h.z + v.z);
484
485        glEnd();
486
487        drawPart = drawPart->next;
488      }
489      glDepthMask(GL_TRUE);
490      break;
491
492    case PARTICLE_SPARK:
493      glDisable(GL_LIGHTING);
494      glDepthMask(GL_FALSE);
495      //glEnable(GL_LINE_SMOOTH);
496      glEnable(GL_BLEND);
497
498      glBegin(GL_LINES);
499      while (likely(drawPart != NULL))
500      {
501        glColor4fv(drawPart->color);
502        glVertex3f(drawPart->position.x, drawPart->position.y, drawPart->position.z);
503        glVertex3f(drawPart->position.x - drawPart->velocity.x * drawPart->radius,
504                   drawPart->position.y - drawPart->velocity.y * drawPart->radius,
505                   drawPart->position.z - drawPart->velocity.z * drawPart->radius);
506        drawPart = drawPart->next;
507      }
508      glEnd();
509      break;
510
511    case PARTICLE_MODEL:
512      {
513        GLfloat matrix[4][4];
514
515        if (likely(this->getModel() != NULL))
516          while (likely(drawPart != NULL))
517        {
518          glPushMatrix();
519          glMatrixMode(GL_MODELVIEW);
520          /* move */
521          glTranslatef(drawPart->position.x, drawPart->position.y, drawPart->position.z);
522          /* scale */
523          glScalef(drawPart->radius, drawPart->radius, drawPart->radius);
524          /* rotate */
525          drawPart->orientation.matrix (matrix);
526          glMultMatrixf((float*)matrix);
527
528          this->getModel()->draw();
529
530          glPopMatrix();
531          drawPart = drawPart->next;
532        }
533        else
534          PRINTF(2)("no model loaded onto ParticleSystem-%s\n", this->getName());
535      }
536      break;
537
538    case PARTICLE_DOT:
539      glDisable(GL_LIGHTING);
540      glBegin(GL_POINTS);
541      while (likely(drawPart != NULL))
542      {
543        glColor4fv(drawPart->color);
544
545        glLineWidth(drawPart->radius);
546
547        glVertex3f(drawPart->position.x, drawPart->position.y, drawPart->position.z);
548        drawPart = drawPart->next;
549      }
550      glEnd();
551      break;
552  }
553  glPopAttrib();
554}
555
556/**
557 *  adds a new Particle to the System
558 * @param position the initial position, where the particle gets emitted.
559 * @param velocity the initial velocity of the particle.
560 * @param orientation the initial orientation of the Paritcle.
561 * @param momentum the initial momentum of the Particle (the speed of its rotation).
562 * @param data some more data given by the emitter
563*/
564void ParticleSystem::addParticle(const Vector& position, const Vector& velocity, const Quaternion& orientation, const Quaternion& momentum, unsigned int data)
565{
566  if (this->count <= this->maxCount)
567    {
568      // if it is the first Particle
569      if (unlikely(particles == NULL))
570        {
571          if (likely(deadList != NULL))
572            {
573              this->particles = this->deadList;
574              deadList = deadList->next;
575            }
576          else
577            {
578              PRINTF(5)("Generating new Particle\n");
579              this->particles = new Particle;
580            }
581          this->particles->next = NULL;
582        }
583      // filling the List from the beginning
584      else
585        {
586          Particle* tmpPart;
587          if (likely(deadList != NULL))
588            {
589              tmpPart = this->deadList;
590              deadList = deadList->next;
591            }
592          else
593            {
594              PRINTF(5)("Generating new Particle\n");
595              tmpPart = new Particle;
596            }
597          tmpPart->next = this->particles;
598          this->particles = tmpPart;
599        }
600      particles->lifeTime = this->lifeSpan + (float)(rand()/RAND_MAX)* this->randomLifeSpan;
601      particles->lifeCycle = 0.0;
602      particles->position = position;
603      particles->velocity = velocity;
604
605      particles->orientation = orientation;
606      particles->momentum = momentum;
607
608      //  particle->rotation = ; //! @todo rotation is once again something to be done.
609      particles->massRand = 2*(float)rand()/RAND_MAX -1;
610      particles->radiusRand = 2* (float)rand()/RAND_MAX -1;
611      particles->mass = this->massAnim.getValue(0.0) + this->randMassAnim.getValue(0.0)*particles->massRand;
612      particles->radius = this->radiusAnim.getValue(0.0) + this->randRadiusAnim.getValue(0.0)*particles->radiusRand;
613
614      ++this->count;
615    }
616  else
617    PRINTF(5)("maximum count of particles reached not adding any more\n");
618}
619
620/**
621 *  outputs some nice debug information
622*/
623void ParticleSystem::debug() const
624{
625  PRINT(0)("  ParticleSystem %s, type: ", this->getName());
626  {
627      if (this->particleType == PARTICLE_MODEL)
628        PRINT(0)("model");
629      else if (this->particleType == PARTICLE_SPRITE)
630        PRINT(0)("sprite");
631      else if (this->particleType == PARTICLE_DOT)
632        PRINT(0)("dot");
633      else if (this->particleType == PARTICLE_SPARK)
634        PRINT(0)("spark");
635
636      PRINT(0)("\n");
637  }
638
639  PRINT(0)("  ParticleCount: %d, maximumCount: %d :: filled %d%%\n", this->count, this->maxCount, 100*this->count/this->maxCount);
640  if (deadList)
641    {
642      PRINT(0)("  - ParticleDeadList is used: ");
643      int i = 1;
644      Particle* tmpPart = this->deadList;
645      while (tmpPart = tmpPart->next) ++i;
646      PRINT(0)("count: %d\n", i);
647    }
648}
Note: See TracBrowser for help on using the repository browser.