ParticleEmitter.cpp 29 KB

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