ParticleEmitter.cpp 29 KB

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