ParticleEmitter.cpp 15 KB

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