ParticleEmitter.cpp 16 KB

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