ParticleEmitter.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Core/Context.h"
  23. #include "../Graphics/ParticleEffect.h"
  24. #include "../Graphics/ParticleEmitter.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Resource/ResourceCache.h"
  27. #include "../Resource/ResourceEvents.h"
  28. #include "../Scene/Scene.h"
  29. #include "../Scene/SceneEvents.h"
  30. #include "../DebugNew.h"
  31. namespace Urho3D
  32. {
  33. extern const char* GEOMETRY_CATEGORY;
  34. extern const char* faceCameraModeNames[];
  35. static const unsigned MAX_PARTICLES_IN_FRAME = 100;
  36. ParticleEmitter::ParticleEmitter(Context* context) :
  37. BillboardSet(context),
  38. periodTimer_(0.0f),
  39. emissionTimer_(0.0f),
  40. lastTimeStep_(0.0f),
  41. lastUpdateFrameNumber_(M_MAX_UNSIGNED),
  42. serializeParticles_(true)
  43. {
  44. SetNumParticles(DEFAULT_NUM_PARTICLES);
  45. }
  46. ParticleEmitter::~ParticleEmitter()
  47. {
  48. }
  49. void ParticleEmitter::RegisterObject(Context* context)
  50. {
  51. context->RegisterFactory<ParticleEmitter>(GEOMETRY_CATEGORY);
  52. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  53. MIXED_ACCESSOR_ATTRIBUTE("Effect", GetEffectAttr, SetEffectAttr, ResourceRef, ResourceRef(ParticleEffect::GetTypeStatic()), AM_DEFAULT);
  54. ENUM_ATTRIBUTE("Face Camera Mode", faceCameraMode_, faceCameraModeNames, FC_ROTATE_XYZ, AM_DEFAULT);
  55. ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  56. ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  57. ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  58. ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  59. ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  60. ATTRIBUTE("Is Emitting", bool, emitting_, true, AM_FILE);
  61. ATTRIBUTE("Period Timer", float, periodTimer_, 0.0f, AM_FILE | AM_NOEDIT);
  62. ATTRIBUTE("Emission Timer", float, emissionTimer_, 0.0f, AM_FILE | AM_NOEDIT);
  63. COPY_BASE_ATTRIBUTES(Drawable);
  64. MIXED_ACCESSOR_ATTRIBUTE("Particles", GetParticlesAttr, SetParticlesAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  65. MIXED_ACCESSOR_ATTRIBUTE("Billboards", GetParticleBillboardsAttr, SetBillboardsAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  66. ATTRIBUTE("Serialize Particles", bool, serializeParticles_, true, AM_FILE);
  67. }
  68. void ParticleEmitter::OnSetEnabled()
  69. {
  70. BillboardSet::OnSetEnabled();
  71. Scene* scene = GetScene();
  72. if (scene)
  73. {
  74. if (IsEnabledEffective())
  75. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(ParticleEmitter, HandleScenePostUpdate));
  76. else
  77. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  78. }
  79. }
  80. void ParticleEmitter::Update(const FrameInfo& frame)
  81. {
  82. if (!effect_)
  83. return;
  84. // Cancel update if has only moved but does not actually need to animate the particles
  85. if (!needUpdate_)
  86. return;
  87. // If there is an amount mismatch between particles and billboards, correct it
  88. if (particles_.Size() != billboards_.Size())
  89. SetNumBillboards(particles_.Size());
  90. bool needCommit = false;
  91. // Check active/inactive period switching
  92. periodTimer_ += lastTimeStep_;
  93. if (emitting_)
  94. {
  95. float activeTime = effect_->GetActiveTime();
  96. if (activeTime && periodTimer_ >= activeTime)
  97. {
  98. emitting_ = false;
  99. periodTimer_ -= activeTime;
  100. }
  101. }
  102. else
  103. {
  104. float inactiveTime = effect_->GetInactiveTime();
  105. if (inactiveTime && periodTimer_ >= inactiveTime)
  106. {
  107. emitting_ = true;
  108. periodTimer_ -= inactiveTime;
  109. }
  110. // If emitter has an indefinite stop interval, keep period timer reset to allow restarting emission in the editor
  111. if (inactiveTime == 0.0f)
  112. periodTimer_ = 0.0f;
  113. }
  114. // Check for emitting new particles
  115. if (emitting_)
  116. {
  117. emissionTimer_ += lastTimeStep_;
  118. float intervalMin = 1.0f / effect_->GetMaxEmissionRate();
  119. float intervalMax = 1.0f / effect_->GetMinEmissionRate();
  120. // If emission timer has a longer delay than max. interval, clamp it
  121. if (emissionTimer_ < -intervalMax)
  122. emissionTimer_ = -intervalMax;
  123. unsigned counter = MAX_PARTICLES_IN_FRAME;
  124. while (emissionTimer_ > 0.0f && counter)
  125. {
  126. emissionTimer_ -= Lerp(intervalMin, intervalMax, Random(1.0f));
  127. if (EmitNewParticle())
  128. {
  129. --counter;
  130. needCommit = true;
  131. }
  132. else
  133. break;
  134. }
  135. }
  136. // Update existing particles
  137. Vector3 relativeConstantForce = node_->GetWorldRotation().Inverse() * effect_->GetConstantForce();
  138. // If billboards are not relative, apply scaling to the position update
  139. Vector3 scaleVector = Vector3::ONE;
  140. if (scaled_ && !relative_)
  141. scaleVector = node_->GetWorldScale();
  142. for (unsigned i = 0; i < particles_.Size(); ++i)
  143. {
  144. Particle& particle = particles_[i];
  145. Billboard& billboard = billboards_[i];
  146. if (billboard.enabled_)
  147. {
  148. needCommit = true;
  149. // Time to live
  150. if (particle.timer_ >= particle.timeToLive_)
  151. {
  152. billboard.enabled_ = false;
  153. continue;
  154. }
  155. particle.timer_ += lastTimeStep_;
  156. // Velocity & position
  157. const Vector3& constantForce = effect_->GetConstantForce();
  158. if (constantForce != Vector3::ZERO)
  159. {
  160. if (relative_)
  161. particle.velocity_ += lastTimeStep_ * relativeConstantForce;
  162. else
  163. particle.velocity_ += lastTimeStep_ * constantForce;
  164. }
  165. float dampingForce = effect_->GetDampingForce();
  166. if (dampingForce != 0.0f)
  167. {
  168. Vector3 force = -dampingForce * particle.velocity_;
  169. particle.velocity_ += lastTimeStep_ * force;
  170. }
  171. billboard.position_ += lastTimeStep_ * particle.velocity_ * scaleVector;
  172. // Rotation
  173. billboard.rotation_ += lastTimeStep_ * particle.rotationSpeed_;
  174. // Scaling
  175. float sizeAdd = effect_->GetSizeAdd();
  176. float sizeMul = effect_->GetSizeMul();
  177. if (sizeAdd != 0.0f || sizeMul != 1.0f)
  178. {
  179. particle.scale_ += lastTimeStep_ * sizeAdd;
  180. if (particle.scale_ < 0.0f)
  181. particle.scale_ = 0.0f;
  182. if (sizeMul != 1.0f)
  183. particle.scale_ *= (lastTimeStep_ * (sizeMul - 1.0f)) + 1.0f;
  184. billboard.size_ = particle.size_ * particle.scale_;
  185. }
  186. // Color interpolation
  187. unsigned& index = particle.colorIndex_;
  188. const Vector<ColorFrame>& colorFrames_ = effect_->GetColorFrames();
  189. if (index < colorFrames_.Size())
  190. {
  191. if (index < colorFrames_.Size() - 1)
  192. {
  193. if (particle.timer_ >= colorFrames_[index + 1].time_)
  194. ++index;
  195. }
  196. if (index < colorFrames_.Size() - 1)
  197. billboard.color_ = colorFrames_[index].Interpolate(colorFrames_[index + 1], particle.timer_);
  198. else
  199. billboard.color_ = colorFrames_[index].color_;
  200. }
  201. // Texture animation
  202. unsigned& texIndex = particle.texIndex_;
  203. const Vector<TextureFrame>& textureFrames_ = effect_->GetTextureFrames();
  204. if (textureFrames_.Size() && texIndex < textureFrames_.Size() - 1)
  205. {
  206. if (particle.timer_ >= textureFrames_[texIndex + 1].time_)
  207. {
  208. billboard.uv_ = textureFrames_[texIndex + 1].uv_;
  209. ++texIndex;
  210. }
  211. }
  212. }
  213. }
  214. if (needCommit)
  215. Commit();
  216. needUpdate_ = false;
  217. }
  218. void ParticleEmitter::SetEffect(ParticleEffect* effect)
  219. {
  220. if (effect == effect_)
  221. return;
  222. Reset();
  223. // Unsubscribe from the reload event of previous effect (if any), then subscribe to the new
  224. if (effect_)
  225. UnsubscribeFromEvent(effect_, E_RELOADFINISHED);
  226. effect_ = effect;
  227. if (effect_)
  228. SubscribeToEvent(effect_, E_RELOADFINISHED, HANDLER(ParticleEmitter, HandleEffectReloadFinished));
  229. ApplyEffect();
  230. MarkNetworkUpdate();
  231. }
  232. void ParticleEmitter::SetNumParticles(unsigned num)
  233. {
  234. // Prevent negative value being assigned from the editor
  235. if (num > M_MAX_INT)
  236. num = 0;
  237. if (num > MAX_BILLBOARDS)
  238. num = MAX_BILLBOARDS;
  239. particles_.Resize(num);
  240. SetNumBillboards(num);
  241. }
  242. void ParticleEmitter::SetEmitting(bool enable)
  243. {
  244. if (enable != emitting_)
  245. {
  246. emitting_ = enable;
  247. periodTimer_ = 0.0f;
  248. // Note: network update does not need to be marked as this is a file only attribute
  249. }
  250. }
  251. void ParticleEmitter::SetSerializeParticles(bool enable)
  252. {
  253. serializeParticles_ = enable;
  254. // Note: network update does not need to be marked as this is a file only attribute
  255. }
  256. void ParticleEmitter::ResetEmissionTimer()
  257. {
  258. emissionTimer_ = 0.0f;
  259. }
  260. void ParticleEmitter::RemoveAllParticles()
  261. {
  262. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  263. i->enabled_ = false;
  264. Commit();
  265. }
  266. void ParticleEmitter::Reset()
  267. {
  268. RemoveAllParticles();
  269. ResetEmissionTimer();
  270. SetEmitting(true);
  271. }
  272. void ParticleEmitter::ApplyEffect()
  273. {
  274. if (!effect_)
  275. return;
  276. SetMaterial(effect_->GetMaterial());
  277. SetNumParticles(effect_->GetNumParticles());
  278. SetRelative(effect_->IsRelative());
  279. SetScaled(effect_->IsScaled());
  280. SetSorted(effect_->IsSorted());
  281. SetAnimationLodBias(effect_->GetAnimationLodBias());
  282. }
  283. void ParticleEmitter::SetEffectAttr(const ResourceRef& value)
  284. {
  285. ResourceCache* cache = GetSubsystem<ResourceCache>();
  286. SetEffect(cache->GetResource<ParticleEffect>(value.name_));
  287. }
  288. ResourceRef ParticleEmitter::GetEffectAttr() const
  289. {
  290. return GetResourceRef(effect_, ParticleEffect::GetTypeStatic());
  291. }
  292. void ParticleEmitter::SetParticlesAttr(const VariantVector& value)
  293. {
  294. unsigned index = 0;
  295. SetNumParticles(index < value.Size() ? value[index++].GetUInt() : 0);
  296. for (PODVector<Particle>::Iterator i = particles_.Begin(); i != particles_.End() && index < value.Size(); ++i)
  297. {
  298. i->velocity_ = value[index++].GetVector3();
  299. i->size_ = value[index++].GetVector2();
  300. i->timer_ = value[index++].GetFloat();
  301. i->timeToLive_ = value[index++].GetFloat();
  302. i->scale_ = value[index++].GetFloat();
  303. i->rotationSpeed_ = value[index++].GetFloat();
  304. i->colorIndex_ = value[index++].GetInt();
  305. i->texIndex_ = value[index++].GetInt();
  306. }
  307. }
  308. VariantVector ParticleEmitter::GetParticlesAttr() const
  309. {
  310. VariantVector ret;
  311. if (!serializeParticles_)
  312. {
  313. ret.Push(particles_.Size());
  314. return ret;
  315. }
  316. ret.Reserve(particles_.Size() * 8 + 1);
  317. ret.Push(particles_.Size());
  318. for (PODVector<Particle>::ConstIterator i = particles_.Begin(); i != particles_.End(); ++i)
  319. {
  320. ret.Push(i->velocity_);
  321. ret.Push(i->size_);
  322. ret.Push(i->timer_);
  323. ret.Push(i->timeToLive_);
  324. ret.Push(i->scale_);
  325. ret.Push(i->rotationSpeed_);
  326. ret.Push(i->colorIndex_);
  327. ret.Push(i->texIndex_);
  328. }
  329. return ret;
  330. }
  331. VariantVector ParticleEmitter::GetParticleBillboardsAttr() const
  332. {
  333. VariantVector ret;
  334. if (!serializeParticles_)
  335. {
  336. ret.Push(billboards_.Size());
  337. return ret;
  338. }
  339. ret.Reserve(billboards_.Size() * 6 + 1);
  340. ret.Push(billboards_.Size());
  341. for (PODVector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  342. {
  343. ret.Push(i->position_);
  344. ret.Push(i->size_);
  345. ret.Push(Vector4(i->uv_.min_.x_, i->uv_.min_.y_, i->uv_.max_.x_, i->uv_.max_.y_));
  346. ret.Push(i->color_);
  347. ret.Push(i->rotation_);
  348. ret.Push(i->enabled_);
  349. }
  350. return ret;
  351. }
  352. void ParticleEmitter::OnNodeSet(Node* node)
  353. {
  354. BillboardSet::OnNodeSet(node);
  355. if (node)
  356. {
  357. Scene* scene = GetScene();
  358. if (scene && IsEnabledEffective())
  359. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(ParticleEmitter, HandleScenePostUpdate));
  360. }
  361. }
  362. bool ParticleEmitter::EmitNewParticle()
  363. {
  364. unsigned index = GetFreeParticle();
  365. if (index == M_MAX_UNSIGNED)
  366. return false;
  367. assert(index < particles_.Size());
  368. Particle& particle = particles_[index];
  369. Billboard& billboard = billboards_[index];
  370. Vector3 startPos;
  371. Vector3 startDir;
  372. switch (effect_->GetEmitterType())
  373. {
  374. case EMITTER_SPHERE:
  375. {
  376. Vector3 dir(
  377. Random(2.0f) - 1.0f,
  378. Random(2.0f) - 1.0f,
  379. Random(2.0f) - 1.0f
  380. );
  381. dir.Normalize();
  382. startPos = effect_->GetEmitterSize() * dir * 0.5f;
  383. }
  384. break;
  385. case EMITTER_BOX:
  386. {
  387. const Vector3& emitterSize = effect_->GetEmitterSize();
  388. startPos = Vector3(
  389. Random(emitterSize.x_) - emitterSize.x_ * 0.5f,
  390. Random(emitterSize.y_) - emitterSize.y_ * 0.5f,
  391. Random(emitterSize.z_) - emitterSize.z_ * 0.5f
  392. );
  393. }
  394. break;
  395. }
  396. startDir = effect_->GetRandomDirection();
  397. startDir.Normalize();
  398. if (!relative_)
  399. {
  400. startPos = node_->GetWorldTransform() * startPos;
  401. startDir = node_->GetWorldRotation() * startDir;
  402. };
  403. particle.velocity_ = effect_->GetRandomVelocity() * startDir;
  404. particle.size_ = effect_->GetRandomSize();
  405. particle.timer_ = 0.0f;
  406. particle.timeToLive_ = effect_->GetRandomTimeToLive();
  407. particle.scale_ = 1.0f;
  408. particle.rotationSpeed_ = effect_->GetRandomRotationSpeed();
  409. particle.colorIndex_ = 0;
  410. particle.texIndex_ = 0;
  411. billboard.position_ = startPos;
  412. billboard.size_ = particles_[index].size_;
  413. const Vector<TextureFrame>& textureFrames_ = effect_->GetTextureFrames();
  414. billboard.uv_ = textureFrames_.Size() ? textureFrames_[0].uv_ : Rect::POSITIVE;
  415. billboard.rotation_ = effect_->GetRandomRotation();
  416. const Vector<ColorFrame>& colorFrames_ = effect_->GetColorFrames();
  417. billboard.color_ = colorFrames_.Size() ? colorFrames_[0].color_ : Color();
  418. billboard.enabled_ = true;
  419. return true;
  420. }
  421. unsigned ParticleEmitter::GetFreeParticle() const
  422. {
  423. for (unsigned i = 0; i < billboards_.Size(); ++i)
  424. {
  425. if (!billboards_[i].enabled_)
  426. return i;
  427. }
  428. return M_MAX_UNSIGNED;
  429. }
  430. void ParticleEmitter::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  431. {
  432. // Store scene's timestep and use it instead of global timestep, as time scale may be other than 1
  433. using namespace ScenePostUpdate;
  434. lastTimeStep_ = eventData[P_TIMESTEP].GetFloat();
  435. // If no invisible update, check that the billboardset is in view (framenumber has changed)
  436. if ((effect_ && effect_->GetUpdateInvisible()) || viewFrameNumber_ != lastUpdateFrameNumber_)
  437. {
  438. lastUpdateFrameNumber_ = viewFrameNumber_;
  439. needUpdate_ = true;
  440. MarkForUpdate();
  441. }
  442. }
  443. void ParticleEmitter::HandleEffectReloadFinished(StringHash eventType, VariantMap& eventData)
  444. {
  445. // When particle effect file is live-edited, remove existing particles and reapply the effect parameters
  446. Reset();
  447. ApplyEffect();
  448. }
  449. }