Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

trunk: some minors

File size: 13.7 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
22#include "field.h"
23#include "model.h"
24
25#include "load_param.h"
26#include "factory.h"
27#include "material.h"
28#include "state.h"
29#include "shell_command.h"
30
31#include "parser/tinyxml/tinyxml.h"
32#include <algorithm>
33
34using namespace std;
35/**
36 *  standard constructor
37 * @param maxCount the Count of particles in the System
38 * @param type The Type of the ParticleSystem
39*/
40ParticleSystem::ParticleSystem (unsigned int maxCount)
41{
42  this->init();
43
44  this->setMaxCount(maxCount);
45}
46
47/**
48 *  standard deconstructor
49*/
50ParticleSystem::~ParticleSystem()
51{
52  // deleting all the living Particles
53  while (this->particles)
54  {
55    Particle* tmpDelPart = this->particles;
56    this->particles = this->particles->next;
57    delete tmpDelPart;
58  }
59
60  // deleting all the dead particles
61  while (this->deadList)
62  {
63    Particle* tmpDelPart = this->deadList;
64    this->deadList = this->deadList->next;
65    delete tmpDelPart;
66  }
67
68  while(!this->emitters.empty())
69  {
70    this->removeEmitter(this->emitters.front());
71  }
72
73}
74
75/**
76 * @brief initializes the ParticleSystem with default values
77 */
78void ParticleSystem::init()
79{
80  this->setClassID(CL_PARTICLE_SYSTEM, "ParticleSystem");
81
82  this->setMaxCount(PARTICLE_DEFAULT_MAX_COUNT);
83  this->count = 0;
84  this->particles = NULL;
85  this->deadList = NULL;
86  this->setConserve(1);
87  this->setLifeSpan(1);
88
89  this->toList(OM_ENVIRON);
90}
91
92
93/**
94 * loads Parameters from a TiXmlElement
95 * @param root the XML-element to load from.
96 */
97void ParticleSystem::loadParams(const TiXmlElement* root)
98{
99  WorldEntity::loadParams(root);
100  PhysicsInterface::loadParams(root);
101
102  LoadParam(root, "max-count", this, ParticleSystem, setMaxCount)
103  .describe("the maximal count of Particles, that can be emitted into this system");
104
105  LoadParam(root, "life-span", this, ParticleSystem, setLifeSpan)
106  .describe("sets the life-span of the Particles.");
107
108  LoadParam(root, "conserve", this, ParticleSystem, setConserve)
109  .describe("sets the Conserve factor of the Particles (1.0: they keep all their energy, 0.0:they keep no energy)");
110
111  LoadParamXML(root, "emitters", this, ParticleSystem, loadEmitters);
112
113  LOAD_PARAM_START_CYCLE(root, element);
114  {
115    element->ToText();
116    // PER-PARTICLE-ATTRIBUTES:
117    LoadParam_CYCLE(element, "radius", this, ParticleSystem, setRadius)
118    .describe("The Radius of each particle over time (TimeIndex [0-1], radius at TimeIndex, randomRadius at TimeIndex)");
119
120    LoadParam_CYCLE(element, "mass", this, ParticleSystem, setMass)
121    .describe("The Mass of each particle over time (TimeIndex: [0-1], mass at TimeIndex, randomMass at TimeIndex)");
122
123    LoadParam_CYCLE(element, "color", this, ParticleSystem, setColor)
124    .describe("The Color of each particle over time (TimeIndex: [0-1], red: [0-1], green: [0-1], blue: [0-1], alpha: [0-1])");
125  }
126  LOAD_PARAM_END_CYCLE(element);
127
128  LoadParam(root, "precache", this, ParticleSystem, precache)
129      .describe("Precaches the ParticleSystem for %1 seconds, %2 times per Second")
130      .defaultValues(2, 1, 25);
131}
132
133/**
134 * @brief loads the Emitters from An XML-Root
135 * @param root the XML-Element to load all emitters from
136 */
137void ParticleSystem::loadEmitters(const TiXmlElement* root)
138{
139  LOAD_PARAM_START_CYCLE(root, element);
140  {
141    BaseObject* emitter = Factory::fabricate(element);
142    if (emitter->isA(CL_PARTICLE_EMITTER))
143      this->addEmitter(dynamic_cast<ParticleEmitter*>(emitter));
144    else
145    {
146      PRINTF(2)("Tried to load an Element of type '%s' that should be a ParticleEmitter onto '%s::%s'.\n",
147                emitter->getClassName(), this->getClassName(), this->getName());
148      delete emitter;
149    }
150  }
151  LOAD_PARAM_END_CYCLE(element);
152}
153
154/**
155* @param maxCount the maximum count of particles that can be emitted
156 */
157void ParticleSystem::setMaxCount(int maxCount)
158{
159  this->maxCount = maxCount;
160}
161
162// setting properties
163/**
164 *  Sets the lifespan of newly created particles
165*/
166void ParticleSystem::setLifeSpan(float lifeSpan, float randomLifeSpan)
167{
168  this->lifeSpan = lifeSpan;
169  this->randomLifeSpan = randomLifeSpan;
170}
171
172/**
173 *  sets the conserve Factor of newly created particles
174*/
175void ParticleSystem::setConserve(float conserve)
176{
177  if (conserve > 1.0)
178    this->conserve = 1.0;
179  else if (conserve < 0.0)
180    this->conserve = 0.0;
181  else
182    this->conserve = conserve;
183}
184
185/////////////////////////////
186/* Per-Particle Attributes */
187/////////////////////////////
188/**
189 *  sets a key in the radius-animation on a per-particle basis
190 * @param lifeCycleTime the time (partilceLifeTime/particleAge) [0-1]
191 * @param radius the radius at this position
192 * @param randRadius the randRadius at this position
193*/
194void ParticleSystem::setRadius(float lifeCycleTime, float radius, float randRadius)
195{
196  this->radiusAnim.changeEntry(lifeCycleTime, radius);
197  this->randRadiusAnim.changeEntry(lifeCycleTime, randRadius);
198}
199
200/**
201 *  sets a key in the mass-animation on a per-particle basis
202 * @param lifeCycleTime the time (partilceLifeTime/particleAge) [0-1]
203 * @param mass the mass at this position
204 * @param randMass the randomMass at this position
205*/
206void ParticleSystem::setMass(float lifeCycleTime, float mass, float randMass)
207{
208  this->massAnim.changeEntry(lifeCycleTime, mass);
209  this->randMassAnim.changeEntry(lifeCycleTime, randMass);
210}
211
212/**
213 *  sets a key in the color-animation on a per-particle basis
214 * @param lifeCycleTime: the time (partilceLifeTime/particleAge) [0-1]
215 * @param red: red
216 * @param green: green
217 * @param blue: blue
218 * @param alpha: alpha
219*/
220void ParticleSystem::setColor(float lifeCycleTime, float red, float green, float blue, float alpha)
221{
222  this->colorAnim[0].changeEntry(lifeCycleTime, red);
223  this->colorAnim[1].changeEntry(lifeCycleTime, green);
224  this->colorAnim[2].changeEntry(lifeCycleTime, blue);
225  this->colorAnim[3].changeEntry(lifeCycleTime, alpha);
226}
227
228/**
229 * @brief adds an Emitter to this System.
230 * @param emitter the Emitter to add.
231 */
232void ParticleSystem::addEmitter(ParticleEmitter* emitter)
233{
234  assert (emitter != NULL);
235  if (emitter->getSystem() != NULL)
236    emitter->getSystem()->removeEmitter(emitter);
237  emitter->system = this;
238  this->emitters.push_back(emitter);
239}
240
241/**
242 * @brief removes a ParticleEmitter from this System
243 * @param emitter the Emitter to remove
244 */
245void ParticleSystem::removeEmitter(ParticleEmitter* emitter)
246{
247  assert (emitter != NULL);
248  emitter->system = NULL;
249  this->emitters.remove(emitter);
250  /*  std::list<ParticleEmitter*>::iterator it = std::find(this->emitters.begin(), this->emitters.end(), emitter);
251  if (it != this->emitters.end())
252    this->emitters.erase(it);*/
253}
254
255/**
256 * @brief does a Precaching, meaning, that the ParticleSystem(and its emitters) will be ticked force
257 * @param seconds: seconds
258 * @param ticksPerSeconds times per Second.
259 */
260void ParticleSystem::precache(unsigned int seconds, unsigned int ticksPerSecond)
261{
262
263  std::list<ParticleEmitter*>::iterator emitter;
264  for (emitter = this->emitters.begin(); emitter != this->emitters.end(); emitter++)
265    (*emitter)->updateNode(.1), (*emitter)->updateNode(.1);
266
267  PRINTF(4)("Precaching %s::%s %d seconds %d timesPerSecond\n", this->getClassName(), this->getName(), seconds, ticksPerSecond);
268  this->debug();
269  for (unsigned int i = 0; i < seconds*ticksPerSecond; i++)
270    this->tick(1.0/(float)ticksPerSecond);
271}
272
273
274/**
275 *  ticks the system.
276 * @param dt the time to tick all the Particles of the System
277
278   this is used to get all the particles some motion
279*/
280void ParticleSystem::tick(float dt)
281{
282  Particle* tickPart = particles;  // the particle to Tick
283  Particle* prevPart = NULL;
284  while (likely(tickPart != NULL))
285  {
286    // applying force to the System.
287    if (likely (tickPart->mass > 0.0))
288      tickPart->velocity += tickPart->extForce / tickPart->mass * dt;
289    // rendering new position.
290    tickPart->position += tickPart->velocity * dt;
291    tickPart->orientation += tickPart->momentum *dt;
292
293    tickPart->radius = radiusAnim.getValue(tickPart->lifeCycle)
294                       + randRadiusAnim.getValue(tickPart->lifeCycle) * tickPart->radiusRand;
295
296    tickPart->mass = massAnim.getValue(tickPart->lifeCycle)
297                     + randMassAnim.getValue(tickPart->lifeCycle) * tickPart->massRand;
298
299    tickPart->extForce = Vector(0,0,0);
300
301    // applying Color
302    tickPart->color[0] = this->colorAnim[0].getValue(tickPart->lifeCycle);
303    tickPart->color[1] = this->colorAnim[1].getValue(tickPart->lifeCycle);
304    tickPart->color[2] = this->colorAnim[2].getValue(tickPart->lifeCycle);
305    tickPart->color[3] = this->colorAnim[3].getValue(tickPart->lifeCycle);
306
307    // many more to come
308
309    if (this->conserve < 1.0)
310    {
311      tickPart->velocity *= this->conserve;
312      tickPart->momentum *= this->conserve;
313    }
314    // find out if we have to delete tickPart
315    if (unlikely((tickPart->lifeCycle += dt/tickPart->lifeTime) >= 1.0))
316    {
317      // remove the particle from the list
318      if (likely(prevPart != NULL))
319      {
320        prevPart->next = tickPart->next;
321        tickPart->next = this->deadList;
322        this->deadList = tickPart;
323        tickPart = prevPart->next;
324      }
325      else
326      {
327        prevPart = NULL;
328        this->particles = tickPart->next;
329        tickPart->next = this->deadList;
330        this->deadList = tickPart;
331        tickPart = this->particles;
332      }
333      --this->count;
334    }
335    else
336    {
337      prevPart = tickPart;
338      tickPart = tickPart->next;
339    }
340  }
341
342  std::list<ParticleEmitter*>::iterator emitter;
343  for (emitter = this->emitters.begin(); emitter != this->emitters.end(); emitter++)
344    (*emitter)->tick(dt);
345}
346
347/**
348  *  applies some force to a Particle.
349  * @param field the Field to apply.
350 */
351void ParticleSystem::applyField(Field* field)
352{
353  Particle* tickPart = particles;
354  while (tickPart)
355  {
356    tickPart->extForce += field->calcForce(tickPart->position);
357    tickPart = tickPart->next;
358  }
359}
360
361
362/**
363 * @returns the count of Faces of this ParticleSystem
364 */
365unsigned int ParticleSystem::getFaceCount() const
366{
367  return this->count;
368}
369
370
371/**
372 *  draws all the Particles of this System
373
374   The Cases in this Function all do the same:
375   Drawing all the particles with the appropriate Type.
376   This is just the fastest Way to do this, but will most likely be changed in the future.
377 */
378// void ParticleSystem::draw() const
379// {
380//   glPushAttrib(GL_ENABLE_BIT);
381//
382//   Particle* drawPart = particles;
383//
384//   switch (this->particleType)
385//   {
386//
387//     case PARTICLE_MODEL:
388//       {
389//       }
390//       break;
391//
392//     case PARTICLE_DOT:
393//       glDisable(GL_LIGHTING);
394//       glBegin(GL_POINTS);
395//       while (likely(drawPart != NULL))
396//       {
397//         glColor4fv(drawPart->color);
398//
399//         glLineWidth(drawPart->radius);
400//
401//         glVertex3f(drawPart->position.x, drawPart->position.y, drawPart->position.z);
402//         drawPart = drawPart->next;
403//       }
404//       glEnd();
405//       break;
406//   }
407//   glPopAttrib();
408// }
409
410/**
411 *  adds a new Particle to the System
412 * @param position the initial position, where the particle gets emitted.
413 * @param velocity the initial velocity of the particle.
414 * @param orientation the initial orientation of the Paritcle.
415 * @param momentum the initial momentum of the Particle (the speed of its rotation).
416 * @param data some more data given by the emitter
417*/
418void ParticleSystem::addParticle(const Vector& position, const Vector& velocity, const Quaternion& orientation, const Quaternion& momentum, unsigned int data)
419{
420  if (this->count <= this->maxCount)
421  {
422    // if it is the first Particle
423    if (unlikely(particles == NULL))
424    {
425      if (likely(deadList != NULL))
426      {
427        this->particles = this->deadList;
428        deadList = deadList->next;
429      }
430      else
431      {
432        PRINTF(5)("Generating new Particle\n");
433        this->particles = new Particle;
434      }
435      this->particles->next = NULL;
436    }
437    // filling the List from the beginning
438    else
439    {
440      Particle* tmpPart;
441      if (likely(deadList != NULL))
442      {
443        tmpPart = this->deadList;
444        deadList = deadList->next;
445      }
446      else
447      {
448        PRINTF(5)("Generating new Particle\n");
449        tmpPart = new Particle;
450      }
451      tmpPart->next = this->particles;
452      this->particles = tmpPart;
453    }
454    particles->lifeTime = this->lifeSpan + (float)(rand()/RAND_MAX)* this->randomLifeSpan;
455    particles->lifeCycle = 0.0;
456    particles->position = position;
457    particles->velocity = velocity;
458
459    particles->orientation = orientation;
460    particles->momentum = momentum;
461
462    //  particle->rotation = ; //! @todo rotation is once again something to be done.
463    particles->massRand = 2*(float)rand()/RAND_MAX -1;
464    particles->radiusRand = 2* (float)rand()/RAND_MAX -1;
465    particles->mass = this->massAnim.getValue(0.0) + this->randMassAnim.getValue(0.0)*particles->massRand;
466    particles->radius = this->radiusAnim.getValue(0.0) + this->randRadiusAnim.getValue(0.0)*particles->radiusRand;
467
468    ++this->count;
469  }
470  else
471    PRINTF(5)("maximum count of particles reached not adding any more\n");
472}
473
474/**
475 *  outputs some nice debug information
476*/
477void ParticleSystem::debug() const
478{
479  PRINT(0)("  ParticleCount: %d emitters: %d, maximumCount: %d :: filled %d%%\n", this->count, this->emitters.size(), this->maxCount, 100*this->count/this->maxCount);
480  if (deadList)
481  {
482    PRINT(0)("  - ParticleDeadList is used: ");
483    int i = 1;
484    Particle* tmpPart = this->deadList;
485    while (tmpPart = tmpPart->next) ++i;
486    PRINT(0)("count: %d\n", i);
487  }
488}
Note: See TracBrowser for help on using the repository browser.