Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 5322 was 5155, checked in by bensch, 19 years ago

orxonox/trunk: now one should be able to create entities on the Fly

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