ParticleEmitter.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. #include "Base.h"
  2. #include "ParticleEmitter.h"
  3. #include "Game.h"
  4. #include "Node.h"
  5. #include "Scene.h"
  6. #include "Quaternion.h"
  7. #include "Properties.h"
  8. #define PARTICLE_COUNT_MAX 100
  9. #define PARTICLE_EMISSION_RATE 10
  10. #define PARTICLE_EMISSION_RATE_TIME_INTERVAL 1000.0f / (float)PARTICLE_EMISSION_RATE
  11. namespace gameplay
  12. {
  13. ParticleEmitter::ParticleEmitter(SpriteBatch* batch, unsigned int particleCountMax) :
  14. _particleCountMax(particleCountMax), _particleCount(0), _particles(NULL),
  15. _emissionRate(PARTICLE_EMISSION_RATE), _started(false), _ellipsoid(false),
  16. _sizeStartMin(1.0f), _sizeStartMax(1.0f), _sizeEndMin(1.0f), _sizeEndMax(1.0f),
  17. _energyMin(1000L), _energyMax(1000L),
  18. _colorStart(Vector4::zero()), _colorStartVar(Vector4::zero()), _colorEnd(Vector4::one()), _colorEndVar(Vector4::zero()),
  19. _position(Vector3::zero()), _positionVar(Vector3::zero()),
  20. _velocity(Vector3::zero()), _velocityVar(Vector3::one()),
  21. _acceleration(Vector3::zero()), _accelerationVar(Vector3::zero()),
  22. _rotationPerParticleSpeedMin(0.0f), _rotationPerParticleSpeedMax(0.0f),
  23. _rotationSpeedMin(0.0f), _rotationSpeedMax(0.0f),
  24. _rotationAxis(Vector3::zero()), _rotation(Matrix::identity()),
  25. _spriteBatch(batch), _spriteTextureBlending(BLEND_TRANSPARENT), _spriteTextureWidth(0), _spriteTextureHeight(0), _spriteTextureWidthRatio(0), _spriteTextureHeightRatio(0), _spriteTextureCoords(NULL),
  26. _spriteAnimated(false), _spriteLooped(false), _spriteFrameCount(1), _spriteFrameRandomOffset(0),_spriteFrameDuration(0L), _spriteFrameDurationSecs(0.0f), _spritePercentPerFrame(0.0f),
  27. _node(NULL), _orbitPosition(false), _orbitVelocity(false), _orbitAcceleration(false),
  28. _timePerEmission(PARTICLE_EMISSION_RATE_TIME_INTERVAL), _timeLast(0L), _timeRunning(0L)
  29. {
  30. GP_ASSERT(particleCountMax);
  31. _particles = new Particle[particleCountMax];
  32. GP_ASSERT(_spriteBatch);
  33. GP_ASSERT(_spriteBatch->getStateBlock());
  34. _spriteBatch->getStateBlock()->setDepthWrite(false);
  35. _spriteBatch->getStateBlock()->setDepthTest(true);
  36. }
  37. ParticleEmitter::~ParticleEmitter()
  38. {
  39. SAFE_DELETE(_spriteBatch);
  40. SAFE_DELETE_ARRAY(_particles);
  41. SAFE_DELETE_ARRAY(_spriteTextureCoords);
  42. }
  43. ParticleEmitter* ParticleEmitter::create(const char* textureFile, TextureBlending textureBlending, unsigned int particleCountMax)
  44. {
  45. Texture* texture = NULL;
  46. texture = Texture::create(textureFile, false);
  47. if (!texture)
  48. {
  49. GP_ERROR("Failed to create texture for particle emitter.");
  50. return NULL;
  51. }
  52. GP_ASSERT(texture->getWidth());
  53. GP_ASSERT(texture->getHeight());
  54. // Use default SpriteBatch material.
  55. SpriteBatch* batch = SpriteBatch::create(texture, NULL, particleCountMax);
  56. texture->release(); // batch owns the texture.
  57. GP_ASSERT(batch);
  58. ParticleEmitter* emitter = new ParticleEmitter(batch, particleCountMax);
  59. GP_ASSERT(emitter);
  60. // By default assume only one frame which uses the entire texture.
  61. emitter->setTextureBlending(textureBlending);
  62. emitter->_spriteTextureWidth = texture->getWidth();
  63. emitter->_spriteTextureHeight = texture->getHeight();
  64. emitter->_spriteTextureWidthRatio = 1.0f / (float)texture->getWidth();
  65. emitter->_spriteTextureHeightRatio = 1.0f / (float)texture->getHeight();
  66. Rectangle texCoord((float)texture->getWidth(), (float)texture->getHeight());
  67. emitter->setSpriteFrameCoords(1, &texCoord);
  68. return emitter;
  69. }
  70. ParticleEmitter* ParticleEmitter::create(const char* url)
  71. {
  72. Properties* properties = Properties::create(url);
  73. if (!properties)
  74. {
  75. GP_ERROR("Failed to create particle emitter from file.");
  76. return NULL;
  77. }
  78. ParticleEmitter* particle = create((strlen(properties->getNamespace()) > 0) ? properties : properties->getNextNamespace());
  79. SAFE_DELETE(properties);
  80. return particle;
  81. }
  82. ParticleEmitter* ParticleEmitter::create(Properties* properties)
  83. {
  84. if (!properties || strcmp(properties->getNamespace(), "particle") != 0)
  85. {
  86. GP_ERROR("Properties object must be non-null and have namespace equal to 'particle'.");
  87. return NULL;
  88. }
  89. Properties* sprite = properties->getNextNamespace();
  90. if (!sprite || strcmp(sprite->getNamespace(), "sprite") != 0)
  91. {
  92. GP_ERROR("Failed to load particle emitter: required namespace 'sprite' is missing.");
  93. return NULL;
  94. }
  95. // Load sprite properties.
  96. // Path to image file is required.
  97. const char* texturePath = sprite->getString("path");
  98. if (!texturePath || strlen(texturePath) == 0)
  99. {
  100. GP_ERROR("Failed to load particle emitter: required image file path ('path') is missing.");
  101. return NULL;
  102. }
  103. const char* blendingString = sprite->getString("blending");
  104. TextureBlending textureBlending = getTextureBlendingFromString(blendingString);
  105. int spriteWidth = sprite->getInt("width");
  106. int spriteHeight = sprite->getInt("height");
  107. bool spriteAnimated = sprite->getBool("animated");
  108. bool spriteLooped = sprite->getBool("looped");
  109. int spriteFrameCount = sprite->getInt("frameCount");
  110. int spriteFrameRandomOffset = sprite->getInt("frameRandomOffset");
  111. float spriteFrameDuration = sprite->getFloat("frameDuration");
  112. // Emitter properties.
  113. unsigned int particleCountMax = (unsigned int)properties->getInt("particleCountMax");
  114. if (particleCountMax == 0)
  115. {
  116. // Set sensible default.
  117. particleCountMax = PARTICLE_COUNT_MAX;
  118. }
  119. unsigned int emissionRate = (unsigned int)properties->getInt("emissionRate");
  120. if (emissionRate == 0)
  121. {
  122. emissionRate = PARTICLE_EMISSION_RATE;
  123. }
  124. bool ellipsoid = properties->getBool("ellipsoid");
  125. float sizeStartMin = properties->getFloat("sizeStartMin");
  126. float sizeStartMax = properties->getFloat("sizeStartMax");
  127. float sizeEndMin = properties->getFloat("sizeEndMin");
  128. float sizeEndMax = properties->getFloat("sizeEndMax");
  129. long energyMin = properties->getLong("energyMin");
  130. long energyMax = properties->getLong("energyMax");
  131. Vector4 colorStart;
  132. Vector4 colorStartVar;
  133. Vector4 colorEnd;
  134. Vector4 colorEndVar;
  135. properties->getVector4("colorStart", &colorStart);
  136. properties->getVector4("colorStartVar", &colorStartVar);
  137. properties->getVector4("colorEnd", &colorEnd);
  138. properties->getVector4("colorEndVar", &colorEndVar);
  139. Vector3 position;
  140. Vector3 positionVar;
  141. Vector3 velocity;
  142. Vector3 velocityVar;
  143. Vector3 acceleration;
  144. Vector3 accelerationVar;
  145. Vector3 rotationAxis;
  146. Vector3 rotationAxisVar;
  147. properties->getVector3("position", &position);
  148. properties->getVector3("positionVar", &positionVar);
  149. properties->getVector3("velocity", &velocity);
  150. properties->getVector3("velocityVar", &velocityVar);
  151. properties->getVector3("acceleration", &acceleration);
  152. properties->getVector3("accelerationVar", &accelerationVar);
  153. float rotationPerParticleSpeedMin = properties->getFloat("rotationPerParticleSpeedMin");
  154. float rotationPerParticleSpeedMax = properties->getFloat("rotationPerParticleSpeedMax");
  155. float rotationSpeedMin = properties->getFloat("rotationSpeedMin");
  156. float rotationSpeedMax = properties->getFloat("rotationSpeedMax");
  157. properties->getVector3("rotationAxis", &rotationAxis);
  158. properties->getVector3("rotationAxisVar", &rotationAxisVar);
  159. bool orbitPosition = properties->getBool("orbitPosition");
  160. bool orbitVelocity = properties->getBool("orbitVelocity");
  161. bool orbitAcceleration = properties->getBool("orbitAcceleration");
  162. // Apply all properties to a newly created ParticleEmitter.
  163. ParticleEmitter* emitter = ParticleEmitter::create(texturePath, textureBlending, particleCountMax);
  164. if (!emitter)
  165. {
  166. GP_ERROR("Failed to create particle emitter.");
  167. return NULL;
  168. }
  169. emitter->setEmissionRate(emissionRate);
  170. emitter->setEllipsoid(ellipsoid);
  171. emitter->setSize(sizeStartMin, sizeStartMax, sizeEndMin, sizeEndMax);
  172. emitter->setEnergy(energyMin, energyMax);
  173. emitter->setColor(colorStart, colorStartVar, colorEnd, colorEndVar);
  174. emitter->setPosition(position, positionVar);
  175. emitter->setVelocity(velocity, velocityVar);
  176. emitter->setAcceleration(acceleration, accelerationVar);
  177. emitter->setRotationPerParticle(rotationPerParticleSpeedMin, rotationPerParticleSpeedMax);
  178. emitter->setRotation(rotationSpeedMin, rotationSpeedMax, rotationAxis, rotationAxisVar);
  179. emitter->setSpriteAnimated(spriteAnimated);
  180. emitter->setSpriteLooped(spriteLooped);
  181. emitter->setSpriteFrameRandomOffset(spriteFrameRandomOffset);
  182. emitter->setSpriteFrameDuration(spriteFrameDuration);
  183. emitter->setSpriteFrameCoords(spriteFrameCount, spriteWidth, spriteHeight);
  184. emitter->setOrbit(orbitPosition, orbitVelocity, orbitAcceleration);
  185. return emitter;
  186. }
  187. unsigned int ParticleEmitter::getEmissionRate() const
  188. {
  189. return _emissionRate;
  190. }
  191. void ParticleEmitter::setEmissionRate(unsigned int rate)
  192. {
  193. GP_ASSERT(rate);
  194. _emissionRate = rate;
  195. _timePerEmission = 1000.0f / (float)_emissionRate;
  196. }
  197. void ParticleEmitter::start()
  198. {
  199. _started = true;
  200. _timeLast = Game::getGameTime();
  201. }
  202. void ParticleEmitter::stop()
  203. {
  204. _started = false;
  205. }
  206. bool ParticleEmitter::isStarted() const
  207. {
  208. return _started;
  209. }
  210. bool ParticleEmitter::isActive() const
  211. {
  212. if (_started)
  213. return true;
  214. if (!_node)
  215. return false;
  216. GP_ASSERT(_particles);
  217. bool active = false;
  218. for (unsigned int i = 0; i < _particleCount; i++)
  219. {
  220. if (_particles[i]._energy > 0)
  221. {
  222. active = true;
  223. break;
  224. }
  225. }
  226. return active;
  227. }
  228. void ParticleEmitter::emit(unsigned int particleCount)
  229. {
  230. GP_ASSERT(_node);
  231. GP_ASSERT(_particles);
  232. // Limit particleCount so as not to go over _particleCountMax.
  233. if (particleCount + _particleCount > _particleCountMax)
  234. {
  235. particleCount = _particleCountMax - _particleCount;
  236. }
  237. Vector3 translation;
  238. Matrix world = _node->getWorldMatrix();
  239. world.getTranslation(&translation);
  240. // Take translation out of world matrix so it can be used to rotate orbiting properties.
  241. world.m[12] = 0.0f;
  242. world.m[13] = 0.0f;
  243. world.m[14] = 0.0f;
  244. // Emit the new particles.
  245. for (unsigned int i = 0; i < particleCount; i++)
  246. {
  247. Particle* p = &_particles[_particleCount];
  248. p->_visible = true;
  249. generateColor(_colorStart, _colorStartVar, &p->_colorStart);
  250. generateColor(_colorEnd, _colorEndVar, &p->_colorEnd);
  251. p->_color.set(p->_colorStart);
  252. p->_energy = p->_energyStart = generateScalar(_energyMin, _energyMax);
  253. p->_size = p->_sizeStart = generateScalar(_sizeStartMin, _sizeStartMax);
  254. p->_sizeEnd = generateScalar(_sizeEndMin, _sizeEndMax);
  255. p->_rotationPerParticleSpeed = generateScalar(_rotationPerParticleSpeedMin, _rotationPerParticleSpeedMax);
  256. p->_angle = generateScalar(0.0f, p->_rotationPerParticleSpeed);
  257. p->_rotationSpeed = generateScalar(_rotationSpeedMin, _rotationSpeedMax);
  258. // Only initial position can be generated within an ellipsoidal domain.
  259. generateVector(_position, _positionVar, &p->_position, _ellipsoid);
  260. generateVector(_velocity, _velocityVar, &p->_velocity, false);
  261. generateVector(_acceleration, _accelerationVar, &p->_acceleration, false);
  262. generateVector(_rotationAxis, _rotationAxisVar, &p->_rotationAxis, false);
  263. // Initial position, velocity and acceleration can all be relative to the emitter's transform.
  264. // Rotate specified properties by the node's rotation.
  265. if (_orbitPosition)
  266. {
  267. world.transformPoint(p->_position, &p->_position);
  268. }
  269. if (_orbitVelocity)
  270. {
  271. world.transformPoint(p->_velocity, &p->_velocity);
  272. }
  273. if (_orbitAcceleration)
  274. {
  275. world.transformPoint(p->_acceleration, &p->_acceleration);
  276. }
  277. // The rotation axis always orbits the node.
  278. if (p->_rotationSpeed != 0.0f && !p->_rotationAxis.isZero())
  279. {
  280. world.transformPoint(p->_rotationAxis, &p->_rotationAxis);
  281. }
  282. // Translate position relative to the node's world space.
  283. p->_position.add(translation);
  284. // Initial sprite frame.
  285. if (_spriteFrameRandomOffset > 0)
  286. {
  287. p->_frame = rand() % _spriteFrameRandomOffset;
  288. }
  289. else
  290. {
  291. p->_frame = 0;
  292. }
  293. p->_timeOnCurrentFrame = 0.0f;
  294. ++_particleCount;
  295. }
  296. }
  297. unsigned int ParticleEmitter::getParticlesCount() const
  298. {
  299. return _particleCount;
  300. }
  301. void ParticleEmitter::setEllipsoid(bool ellipsoid)
  302. {
  303. _ellipsoid = ellipsoid;
  304. }
  305. void ParticleEmitter::setSize(float startMin, float startMax, float endMin, float endMax)
  306. {
  307. _sizeStartMin = startMin;
  308. _sizeStartMax = startMax;
  309. _sizeEndMin = endMin;
  310. _sizeEndMax = endMax;
  311. }
  312. float ParticleEmitter::getSizeStartMin() const
  313. {
  314. return _sizeStartMin;
  315. }
  316. float ParticleEmitter::getSizeStartMax() const
  317. {
  318. return _sizeStartMax;
  319. }
  320. float ParticleEmitter::getSizeEndMin() const
  321. {
  322. return _sizeEndMin;
  323. }
  324. float ParticleEmitter::getSizeEndMax() const
  325. {
  326. return _sizeEndMax;
  327. }
  328. void ParticleEmitter::setEnergy(long energyMin, long energyMax)
  329. {
  330. _energyMin = energyMin;
  331. _energyMax = energyMax;
  332. }
  333. long ParticleEmitter::getEnergyMin() const
  334. {
  335. return _energyMin;
  336. }
  337. long ParticleEmitter::getEnergyMax() const
  338. {
  339. return _energyMax;
  340. }
  341. void ParticleEmitter::setColor(const Vector4& startColor, const Vector4& startColorVar, const Vector4& endColor, const Vector4& endColorVar)
  342. {
  343. _colorStart.set(startColor);
  344. _colorStartVar.set(startColorVar);
  345. _colorEnd.set(endColor);
  346. _colorEndVar.set(endColorVar);
  347. }
  348. const Vector4& ParticleEmitter::getColorStart() const
  349. {
  350. return _colorStart;
  351. }
  352. const Vector4& ParticleEmitter::getColorStartVariance() const
  353. {
  354. return _colorStartVar;
  355. }
  356. const Vector4& ParticleEmitter::getColorEnd() const
  357. {
  358. return _colorEnd;
  359. }
  360. const Vector4& ParticleEmitter::getColorEndVariance() const
  361. {
  362. return _colorEndVar;
  363. }
  364. void ParticleEmitter::setPosition(const Vector3& position, const Vector3& positionVar)
  365. {
  366. _position.set(position);
  367. _positionVar.set(positionVar);
  368. }
  369. const Vector3& ParticleEmitter::getPosition() const
  370. {
  371. return _position;
  372. }
  373. const Vector3& ParticleEmitter::getPositionVariance() const
  374. {
  375. return _positionVar;
  376. }
  377. const Vector3& ParticleEmitter::getVelocity() const
  378. {
  379. return _velocity;
  380. }
  381. const Vector3& ParticleEmitter::getVelocityVariance() const
  382. {
  383. return _velocityVar;
  384. }
  385. void ParticleEmitter::setVelocity(const Vector3& velocity, const Vector3& velocityVar)
  386. {
  387. _velocity.set(velocity);
  388. _velocityVar.set(velocityVar);
  389. }
  390. const Vector3& ParticleEmitter::getAcceleration() const
  391. {
  392. return _acceleration;
  393. }
  394. const Vector3& ParticleEmitter::getAccelerationVariance() const
  395. {
  396. return _accelerationVar;
  397. }
  398. void ParticleEmitter::setAcceleration(const Vector3& acceleration, const Vector3& accelerationVar)
  399. {
  400. _acceleration.set(acceleration);
  401. _accelerationVar.set(accelerationVar);
  402. }
  403. void ParticleEmitter::setRotationPerParticle(float speedMin, float speedMax)
  404. {
  405. _rotationPerParticleSpeedMin = speedMin;
  406. _rotationPerParticleSpeedMax = speedMax;
  407. }
  408. float ParticleEmitter::getRotationPerParticleSpeedMin() const
  409. {
  410. return _rotationPerParticleSpeedMin;
  411. }
  412. float ParticleEmitter::getRotationPerParticleSpeedMax() const
  413. {
  414. return _rotationPerParticleSpeedMax;
  415. }
  416. void ParticleEmitter::setRotation(float speedMin, float speedMax, const Vector3& axis, const Vector3& axisVariance)
  417. {
  418. _rotationSpeedMin = speedMin;
  419. _rotationSpeedMax = speedMax;
  420. _rotationAxis.set(axis);
  421. _rotationAxisVar.set(axisVariance);
  422. }
  423. float ParticleEmitter::getRotationSpeedMin() const
  424. {
  425. return _rotationSpeedMin;
  426. }
  427. float ParticleEmitter::getRotationSpeedMax() const
  428. {
  429. return _rotationSpeedMax;
  430. }
  431. const Vector3& ParticleEmitter::getRotationAxis() const
  432. {
  433. return _rotationAxis;
  434. }
  435. const Vector3& ParticleEmitter::getRotationAxisVariance() const
  436. {
  437. return _rotationAxisVar;
  438. }
  439. void ParticleEmitter::setTextureBlending(TextureBlending textureBlending)
  440. {
  441. GP_ASSERT(_spriteBatch);
  442. GP_ASSERT(_spriteBatch->getStateBlock());
  443. switch (textureBlending)
  444. {
  445. case BLEND_OPAQUE:
  446. _spriteBatch->getStateBlock()->setBlend(false);
  447. break;
  448. case BLEND_TRANSPARENT:
  449. _spriteBatch->getStateBlock()->setBlend(true);
  450. _spriteBatch->getStateBlock()->setBlendSrc(RenderState::BLEND_SRC_ALPHA);
  451. _spriteBatch->getStateBlock()->setBlendDst(RenderState::BLEND_ONE_MINUS_SRC_ALPHA);
  452. break;
  453. case BLEND_ADDITIVE:
  454. _spriteBatch->getStateBlock()->setBlend(true);
  455. _spriteBatch->getStateBlock()->setBlendSrc(RenderState::BLEND_SRC_ALPHA);
  456. _spriteBatch->getStateBlock()->setBlendDst(RenderState::BLEND_ONE);
  457. break;
  458. case BLEND_MULTIPLIED:
  459. _spriteBatch->getStateBlock()->setBlend(true);
  460. _spriteBatch->getStateBlock()->setBlendSrc(RenderState::BLEND_ZERO);
  461. _spriteBatch->getStateBlock()->setBlendDst(RenderState::BLEND_SRC_COLOR);
  462. break;
  463. default:
  464. GP_ERROR("Unsupported texture blending mode (%d).", textureBlending);
  465. break;
  466. }
  467. }
  468. void ParticleEmitter::setSpriteAnimated(bool animated)
  469. {
  470. _spriteAnimated = animated;
  471. }
  472. bool ParticleEmitter::isSpriteAnimated() const
  473. {
  474. return _spriteAnimated;
  475. }
  476. void ParticleEmitter::setSpriteLooped(bool looped)
  477. {
  478. _spriteLooped = looped;
  479. }
  480. bool ParticleEmitter::isSpriteLooped() const
  481. {
  482. return _spriteLooped;
  483. }
  484. void ParticleEmitter::setSpriteFrameRandomOffset(int maxOffset)
  485. {
  486. _spriteFrameRandomOffset = maxOffset;
  487. }
  488. int ParticleEmitter::getSpriteFrameRandomOffset() const
  489. {
  490. return _spriteFrameRandomOffset;
  491. }
  492. void ParticleEmitter::setSpriteFrameDuration(long duration)
  493. {
  494. _spriteFrameDuration = duration;
  495. _spriteFrameDurationSecs = (float)duration / 1000.0f;
  496. }
  497. long ParticleEmitter::getSpriteFrameDuration() const
  498. {
  499. return _spriteFrameDuration;
  500. }
  501. void ParticleEmitter::setSpriteTexCoords(unsigned int frameCount, float* texCoords)
  502. {
  503. GP_ASSERT(frameCount);
  504. GP_ASSERT(texCoords);
  505. _spriteFrameCount = frameCount;
  506. _spritePercentPerFrame = 1.0f / (float)frameCount;
  507. SAFE_DELETE_ARRAY(_spriteTextureCoords);
  508. _spriteTextureCoords = new float[frameCount * 4];
  509. memcpy(_spriteTextureCoords, texCoords, frameCount * 4 * sizeof(float));
  510. }
  511. void ParticleEmitter::setSpriteFrameCoords(unsigned int frameCount, Rectangle* frameCoords)
  512. {
  513. GP_ASSERT(frameCount);
  514. GP_ASSERT(frameCoords);
  515. _spriteFrameCount = frameCount;
  516. _spritePercentPerFrame = 1.0f / (float)frameCount;
  517. SAFE_DELETE_ARRAY(_spriteTextureCoords);
  518. _spriteTextureCoords = new float[frameCount * 4];
  519. // Pre-compute texture coordinates from rects.
  520. for (unsigned int i = 0; i < frameCount; i++)
  521. {
  522. _spriteTextureCoords[i*4] = _spriteTextureWidthRatio * frameCoords[i].x;
  523. _spriteTextureCoords[i*4 + 1] = 1.0f - _spriteTextureHeightRatio * frameCoords[i].y;
  524. _spriteTextureCoords[i*4 + 2] = _spriteTextureCoords[i*4] + _spriteTextureWidthRatio * frameCoords[i].width;
  525. _spriteTextureCoords[i*4 + 3] = _spriteTextureCoords[i*4 + 1] - _spriteTextureHeightRatio * frameCoords[i].height;
  526. }
  527. }
  528. void ParticleEmitter::setSpriteFrameCoords(unsigned int frameCount, int width, int height)
  529. {
  530. GP_ASSERT(width);
  531. GP_ASSERT(height);
  532. int x;
  533. int y;
  534. Rectangle* frameCoords = new Rectangle[frameCount];
  535. unsigned int cols = _spriteTextureWidth / width;
  536. unsigned int rows = _spriteTextureHeight / height;
  537. unsigned int n = 0;
  538. for (unsigned int i = 0; i < rows; ++i)
  539. {
  540. y = i * height;
  541. for (unsigned int j = 0; j < cols; ++j)
  542. {
  543. x = j * width;
  544. frameCoords[i*cols + j] = Rectangle(x, y, width, height);
  545. if (++n == frameCount)
  546. {
  547. break;
  548. }
  549. }
  550. if (n == frameCount)
  551. {
  552. break;
  553. }
  554. }
  555. setSpriteFrameCoords(frameCount, frameCoords);
  556. SAFE_DELETE_ARRAY(frameCoords);
  557. }
  558. Node* ParticleEmitter::getNode() const
  559. {
  560. return _node;
  561. }
  562. void ParticleEmitter::setNode(Node* node)
  563. {
  564. // Connect the new node.
  565. _node = node;
  566. }
  567. void ParticleEmitter::setOrbit(bool orbitPosition, bool orbitVelocity, bool orbitAcceleration)
  568. {
  569. _orbitPosition = orbitPosition;
  570. _orbitVelocity = orbitVelocity;
  571. _orbitAcceleration = orbitAcceleration;
  572. }
  573. long ParticleEmitter::generateScalar(long min, long max)
  574. {
  575. // Note: this is not a very good RNG, but it should be suitable for our purposes.
  576. long r = 0;
  577. for (unsigned int i = 0; i < sizeof(long)/sizeof(int); i++)
  578. {
  579. r = r << 8; // sizeof(int) * CHAR_BITS
  580. r |= rand();
  581. }
  582. // Now we have a random long between 0 and MAX_LONG. We need to clamp it between min and max.
  583. r %= max - min;
  584. r += min;
  585. return r;
  586. }
  587. float ParticleEmitter::generateScalar(float min, float max)
  588. {
  589. return min + (max - min) * MATH_RANDOM_0_1();
  590. }
  591. void ParticleEmitter::generateVectorInRect(const Vector3& base, const Vector3& variance, Vector3* dst)
  592. {
  593. GP_ASSERT(dst);
  594. // Scale each component of the variance vector by a random float
  595. // between -1 and 1, then add this to the corresponding base component.
  596. dst->x = base.x + variance.x * MATH_RANDOM_MINUS1_1();
  597. dst->y = base.y + variance.y * MATH_RANDOM_MINUS1_1();
  598. dst->z = base.z + variance.z * MATH_RANDOM_MINUS1_1();
  599. }
  600. void ParticleEmitter::generateVectorInEllipsoid(const Vector3& center, const Vector3& scale, Vector3* dst)
  601. {
  602. GP_ASSERT(dst);
  603. // Generate a point within a unit cube, then reject if the point is not in a unit sphere.
  604. do
  605. {
  606. dst->x = MATH_RANDOM_MINUS1_1();
  607. dst->y = MATH_RANDOM_MINUS1_1();
  608. dst->z = MATH_RANDOM_MINUS1_1();
  609. } while (dst->length() > 1.0f);
  610. // Scale this point by the scaling vector.
  611. dst->x *= scale.x;
  612. dst->y *= scale.y;
  613. dst->z *= scale.z;
  614. // Translate by the center point.
  615. dst->add(center);
  616. }
  617. void ParticleEmitter::generateVector(const Vector3& base, const Vector3& variance, Vector3* dst, bool ellipsoid)
  618. {
  619. if (ellipsoid)
  620. {
  621. generateVectorInEllipsoid(base, variance, dst);
  622. }
  623. else
  624. {
  625. generateVectorInRect(base, variance, dst);
  626. }
  627. }
  628. void ParticleEmitter::generateColor(const Vector4& base, const Vector4& variance, Vector4* dst)
  629. {
  630. GP_ASSERT(dst);
  631. // Scale each component of the variance color by a random float
  632. // between -1 and 1, then add this to the corresponding base component.
  633. dst->x = base.x + variance.x * MATH_RANDOM_MINUS1_1();
  634. dst->y = base.y + variance.y * MATH_RANDOM_MINUS1_1();
  635. dst->z = base.z + variance.z * MATH_RANDOM_MINUS1_1();
  636. dst->w = base.w + variance.w * MATH_RANDOM_MINUS1_1();
  637. }
  638. ParticleEmitter::TextureBlending ParticleEmitter::getTextureBlendingFromString(const char* str)
  639. {
  640. GP_ASSERT(str);
  641. if (strcmp(str, "BLEND_OPAQUE") == 0 || strcmp(str, "OPAQUE") == 0)
  642. {
  643. return BLEND_OPAQUE;
  644. }
  645. else if (strcmp(str, "BLEND_TRANSPARENT") == 0 || strcmp(str, "TRANSPARENT") == 0)
  646. {
  647. return BLEND_TRANSPARENT;
  648. }
  649. else if (strcmp(str, "BLEND_ADDITIVE") == 0 || strcmp(str, "ADDITIVE") == 0)
  650. {
  651. return BLEND_ADDITIVE;
  652. }
  653. else if (strcmp(str, "BLEND_MULTIPLIED") == 0 || strcmp(str, "MULTIPLIED") == 0)
  654. {
  655. return BLEND_MULTIPLIED;
  656. }
  657. else
  658. {
  659. return BLEND_TRANSPARENT;
  660. }
  661. }
  662. void ParticleEmitter::update(long elapsedTime)
  663. {
  664. if (!isActive())
  665. {
  666. return;
  667. }
  668. // Calculate the time passed since last update.
  669. float elapsedSecs = (float)elapsedTime * 0.001f;
  670. if (_started && _emissionRate)
  671. {
  672. // Calculate how much time has passed since we last emitted particles.
  673. _timeRunning += elapsedTime;
  674. // How many particles should we emit this frame?
  675. GP_ASSERT(_timePerEmission);
  676. unsigned int emitCount = _timeRunning / _timePerEmission;
  677. if (emitCount)
  678. {
  679. if ((int)_timePerEmission > 0)
  680. {
  681. _timeRunning %= (int)_timePerEmission;
  682. }
  683. emit(emitCount);
  684. }
  685. }
  686. GP_ASSERT(_node && _node->getScene() && _node->getScene()->getActiveCamera());
  687. const Frustum& frustum = _node->getScene()->getActiveCamera()->getFrustum();
  688. // Now update all currently living particles.
  689. GP_ASSERT(_particles);
  690. for (unsigned int particlesIndex = 0; particlesIndex < _particleCount; ++particlesIndex)
  691. {
  692. Particle* p = &_particles[particlesIndex];
  693. p->_energy -= elapsedTime;
  694. if (p->_energy > 0L)
  695. {
  696. if (p->_rotationSpeed != 0.0f && !p->_rotationAxis.isZero())
  697. {
  698. Matrix::createRotation(p->_rotationAxis, p->_rotationSpeed * elapsedSecs, &_rotation);
  699. _rotation.transformPoint(p->_velocity, &p->_velocity);
  700. _rotation.transformPoint(p->_acceleration, &p->_acceleration);
  701. }
  702. // Particle is still alive.
  703. p->_velocity.x += p->_acceleration.x * elapsedSecs;
  704. p->_velocity.y += p->_acceleration.y * elapsedSecs;
  705. p->_velocity.z += p->_acceleration.z * elapsedSecs;
  706. p->_position.x += p->_velocity.x * elapsedSecs;
  707. p->_position.y += p->_velocity.y * elapsedSecs;
  708. p->_position.z += p->_velocity.z * elapsedSecs;
  709. if (!frustum.intersects(p->_position))
  710. {
  711. p->_visible = false;
  712. continue;
  713. }
  714. p->_angle += p->_rotationPerParticleSpeed * elapsedSecs;
  715. // Simple linear interpolation of color and size.
  716. float percent = 1.0f - ((float)p->_energy / (float)p->_energyStart);
  717. p->_color.x = p->_colorStart.x + (p->_colorEnd.x - p->_colorStart.x) * percent;
  718. p->_color.y = p->_colorStart.y + (p->_colorEnd.y - p->_colorStart.y) * percent;
  719. p->_color.z = p->_colorStart.z + (p->_colorEnd.z - p->_colorStart.z) * percent;
  720. p->_color.w = p->_colorStart.w + (p->_colorEnd.w - p->_colorStart.w) * percent;
  721. p->_size = p->_sizeStart + (p->_sizeEnd - p->_sizeStart) * percent;
  722. // Handle sprite animations.
  723. if (_spriteAnimated)
  724. {
  725. if (!_spriteLooped)
  726. {
  727. // The last frame should finish exactly when the particle dies.
  728. float percentSpent = 0.0f;
  729. for (unsigned int i = 0; i < p->_frame; i++)
  730. {
  731. percentSpent += _spritePercentPerFrame;
  732. }
  733. p->_timeOnCurrentFrame = percent - percentSpent;
  734. if (p->_frame < _spriteFrameCount - 1 &&
  735. p->_timeOnCurrentFrame >= _spritePercentPerFrame)
  736. {
  737. ++p->_frame;
  738. }
  739. }
  740. else
  741. {
  742. // _spriteFrameDurationSecs is an absolute time measured in seconds,
  743. // and the animation repeats indefinitely.
  744. p->_timeOnCurrentFrame += elapsedSecs;
  745. if (p->_timeOnCurrentFrame >= _spriteFrameDurationSecs)
  746. {
  747. p->_timeOnCurrentFrame -= _spriteFrameDurationSecs;
  748. ++p->_frame;
  749. if (p->_frame == _spriteFrameCount)
  750. {
  751. p->_frame = 0;
  752. }
  753. }
  754. }
  755. }
  756. }
  757. else
  758. {
  759. // Particle is dead. Move the particle furthest from the start of the array
  760. // down to take its place, and re-use the slot at the end of the list of living particles.
  761. if (particlesIndex != _particleCount - 1)
  762. {
  763. _particles[particlesIndex] = _particles[_particleCount - 1];
  764. }
  765. --_particleCount;
  766. }
  767. }
  768. }
  769. void ParticleEmitter::draw()
  770. {
  771. if (!isActive())
  772. {
  773. return;
  774. }
  775. if (_particleCount > 0)
  776. {
  777. GP_ASSERT(_spriteBatch);
  778. GP_ASSERT(_particles);
  779. GP_ASSERT(_spriteTextureCoords);
  780. // Set our node's view projection matrix to this emitter's effect.
  781. if (_node)
  782. {
  783. _spriteBatch->setProjectionMatrix(_node->getViewProjectionMatrix());
  784. }
  785. // Begin sprite batch drawing
  786. _spriteBatch->begin();
  787. // 2D Rotation.
  788. static const Vector2 pivot(0.5f, 0.5f);
  789. // 3D Rotation so that particles always face the camera.
  790. GP_ASSERT(_node && _node->getScene() && _node->getScene()->getActiveCamera() && _node->getScene()->getActiveCamera()->getNode());
  791. const Matrix& cameraWorldMatrix = _node->getScene()->getActiveCamera()->getNode()->getWorldMatrix();
  792. Vector3 right;
  793. cameraWorldMatrix.getRightVector(&right);
  794. Vector3 up;
  795. cameraWorldMatrix.getUpVector(&up);
  796. for (unsigned int i = 0; i < _particleCount; i++)
  797. {
  798. Particle* p = &_particles[i];
  799. if (p->_visible)
  800. {
  801. _spriteBatch->draw(p->_position, right, up, p->_size, p->_size,
  802. _spriteTextureCoords[p->_frame * 4], _spriteTextureCoords[p->_frame * 4 + 1], _spriteTextureCoords[p->_frame * 4 + 2], _spriteTextureCoords[p->_frame * 4 + 3],
  803. p->_color, pivot, p->_angle);
  804. }
  805. }
  806. // Render.
  807. _spriteBatch->end();
  808. }
  809. }
  810. }