ParticleEmitter.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "Log.h"
  26. #include "Material.h"
  27. #include "MemoryBuffer.h"
  28. #include "ParticleEmitter.h"
  29. #include "Profiler.h"
  30. #include "ResourceCache.h"
  31. #include "Scene.h"
  32. #include "SceneEvents.h"
  33. #include "XMLFile.h"
  34. #include "DebugNew.h"
  35. OBJECTTYPESTATIC(ParticleEmitter);
  36. ParticleEmitter::ParticleEmitter(Context* context) :
  37. BillboardSet(context),
  38. emitterType_(EMITTER_POINT),
  39. emitterSize_(Vector3::ZERO),
  40. directionMin_(Vector3(-1.0f, -1.0f, -1.0f)),
  41. directionMax_(Vector3(1.0f, 1.0f, 1.0f)),
  42. constanceForce_(Vector3::ZERO),
  43. sizeMin_(Vector2(0.1f, 0.1f)),
  44. sizeMax_(Vector2(0.1f, 0.1f)),
  45. dampingForce_(0.0f),
  46. emitterRadius_(0.0f),
  47. periodTimer_(0.0f),
  48. emissionTimer_(0.0f),
  49. activeTime_(0.0f),
  50. inactiveTime_(0.0f),
  51. intervalMin_(0.1f),
  52. intervalMax_(0.1f),
  53. timeToLiveMin_(1.0f),
  54. timeToLiveMax_(1.0f),
  55. velocityMin_(1.0f),
  56. velocityMax_(1.0f),
  57. rotationMin_(0.0f),
  58. rotationMax_(0.0f),
  59. rotationSpeedMin_(0.0f),
  60. rotationSpeedMax_(0.0f),
  61. sizeAdd_(0.0f),
  62. sizeMul_(1.0f),
  63. active_(true),
  64. updateInvisible_(false),
  65. lastUpdateFrameNumber_(M_MAX_UNSIGNED)
  66. {
  67. SetParticleColor(Color(1.0f, 1.0f, 1.0f));
  68. SetNumParticles(10);
  69. }
  70. ParticleEmitter::~ParticleEmitter()
  71. {
  72. }
  73. void ParticleEmitter::RegisterObject(Context* context)
  74. {
  75. context->RegisterFactory<ParticleEmitter>();
  76. ATTRIBUTE(ParticleEmitter, VAR_FLOAT, "Animation LOD Bias", animationLodBias_, 1.0f, AM_DEFAULT);
  77. ATTRIBUTE(ParticleEmitter, VAR_BOOL, "Relative Scale", scaled_, true, AM_DEFAULT);
  78. ATTRIBUTE(ParticleEmitter, VAR_BOOL, "Is Active", active_, true, AM_DEFAULT);
  79. ATTRIBUTE(ParticleEmitter, VAR_FLOAT, "Period Timer", periodTimer_, 0.0f, AM_DEFAULT);
  80. ATTRIBUTE(ParticleEmitter, VAR_FLOAT, "Emission Timer", emissionTimer_, 0.0f, AM_DEFAULT);
  81. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_RESOURCEREF, "Parameter Source", GetParameterSourceAttr, SetParameterSourceAttr, ResourceRef, ResourceRef(XMLFile::GetTypeStatic()), AM_DEFAULT);
  82. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_BUFFER, "Particles", GetParticlesAttr, SetParticlesAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_FILE);
  83. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_BUFFER, "Billboards", GetBillboardsAttr, SetBillboardsAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_FILE);
  84. }
  85. void ParticleEmitter::Update(float timeStep)
  86. {
  87. // If no invisible update, check that the billboardset is in view (framenumber has changed)
  88. if (!updateInvisible_)
  89. {
  90. if (viewFrameNumber_ == lastUpdateFrameNumber_)
  91. return;
  92. }
  93. lastUpdateFrameNumber_ = viewFrameNumber_;
  94. PROFILE(UpdateParticleEmitter);
  95. // If there is an amount mismatch between particles and billboards, correct it
  96. if (particles_.Size() != billboards_.Size())
  97. SetNumBillboards(particles_.Size());
  98. bool needBillboardUpdate = false;
  99. // Check active/inactive period switching
  100. periodTimer_ += timeStep;
  101. if (active_)
  102. {
  103. if (activeTime_ && periodTimer_ >= activeTime_)
  104. {
  105. active_ = false;
  106. periodTimer_ -= activeTime_;
  107. }
  108. }
  109. else
  110. {
  111. if (inactiveTime_ && periodTimer_ >= inactiveTime_)
  112. {
  113. active_ = true;
  114. periodTimer_ -= inactiveTime_;
  115. }
  116. }
  117. // Check for emitting a new particle
  118. if (active_)
  119. {
  120. emissionTimer_ += timeStep;
  121. if (emissionTimer_ > 0.0f)
  122. {
  123. emissionTimer_ -= Lerp(intervalMin_, intervalMax_, Random(1.0f));
  124. if (EmitNewParticle())
  125. needBillboardUpdate = true;
  126. }
  127. }
  128. // Update existing particles
  129. Vector3 relativeConstantForce = GetWorldRotation().Inverse() * constanceForce_;
  130. // If billboards are not relative, apply scaling to the position update
  131. Vector3 scaleVector = Vector3::UNITY;
  132. if (scaled_ && !relative_)
  133. scaleVector = GetWorldScale();
  134. for (unsigned i = 0; i < particles_.Size(); ++i)
  135. {
  136. Particle& particle = particles_[i];
  137. Billboard& billboard = billboards_[i];
  138. if (billboard.enabled_)
  139. {
  140. needBillboardUpdate = true;
  141. // Time to live
  142. if (particle.timer_ >= particle.timeToLive_)
  143. {
  144. billboard.enabled_ = false;
  145. continue;
  146. }
  147. particle.timer_ += timeStep;
  148. // Velocity & position
  149. if (constanceForce_ != Vector3::ZERO)
  150. {
  151. if (relative_)
  152. particle.velocity_ += timeStep * relativeConstantForce;
  153. else
  154. particle.velocity_ += timeStep * constanceForce_;
  155. }
  156. if (dampingForce_ != 0.0f)
  157. {
  158. Vector3 force = -dampingForce_ * particle.velocity_;
  159. particle.velocity_ += timeStep * force;
  160. }
  161. billboard.position_ += timeStep * particle.velocity_ * scaleVector;
  162. // Rotation
  163. billboard.rotation_ += timeStep * particle.rotationSpeed_;
  164. // Scaling
  165. if (sizeAdd_ != 0.0f || sizeMul_ != 1.0f)
  166. {
  167. particle.scale_ += timeStep * sizeAdd_;
  168. if (sizeMul_ != 1.0f)
  169. particle.scale_ *= (timeStep * (sizeMul_ - 1.0f)) + 1.0f;
  170. billboard.size_ = particle.size_ * particle.scale_;
  171. }
  172. // Color interpolation
  173. unsigned& index = particle.colorIndex_;
  174. if (index < colors_.Size())
  175. {
  176. if (index < colors_.Size() - 1)
  177. {
  178. if (particle.timer_ >= colors_[index + 1].time_)
  179. ++index;
  180. }
  181. if (index < colors_.Size() - 1)
  182. billboard.color_ = colors_[index].interpolate(colors_[index + 1], particle.timer_);
  183. else
  184. billboard.color_ = colors_[index].color_;
  185. }
  186. // Texture animation
  187. unsigned& texIndex = particle.texIndex_;
  188. if (textureAnimation_.Size() && texIndex < textureAnimation_.Size() - 1)
  189. {
  190. if (particle.timer_ >= textureAnimation_[texIndex + 1].time_)
  191. {
  192. billboard.uv_ = textureAnimation_[texIndex + 1].uv_;
  193. ++texIndex;
  194. }
  195. }
  196. }
  197. }
  198. if (needBillboardUpdate)
  199. Updated();
  200. }
  201. bool ParticleEmitter::LoadParameters(XMLFile* file)
  202. {
  203. ResourceCache* cache = GetSubsystem<ResourceCache>();
  204. if (!file || !cache)
  205. return false;
  206. parameterSource_ = file;
  207. XMLElement rootElem = parameterSource_->GetRoot();
  208. if (!rootElem)
  209. return false;
  210. if (rootElem.HasChild("material"))
  211. SetMaterial(cache->GetResource<Material>(rootElem.GetChild("material").GetString("name")));
  212. if (rootElem.HasChild("numparticles"))
  213. SetNumParticles(rootElem.GetChild("numparticles").GetInt("value"));
  214. if (rootElem.HasChild("sorted"))
  215. sorted_ = rootElem.GetChild("sorted").GetBool("enable");
  216. if (rootElem.HasChild("updateinvisible"))
  217. updateInvisible_ = rootElem.GetChild("updateinvisible").GetBool("enable");
  218. if (rootElem.HasChild("relative"))
  219. relative_ = rootElem.GetChild("relative").GetBool("enable");
  220. if (rootElem.HasChild("animlodbias"))
  221. SetAnimationLodBias(rootElem.GetChild("relative").GetFloat("value"));
  222. if (rootElem.HasChild("emittertype"))
  223. {
  224. String type = rootElem.GetChild("emittertype").GetStringLower("value");
  225. if (type == "point")
  226. emitterType_ = EMITTER_POINT;
  227. else if (type == "box")
  228. emitterType_ = EMITTER_BOX;
  229. else if (type == "sphere")
  230. emitterType_ = EMITTER_SPHERE;
  231. else
  232. LOGERROR("Unknown particle emitter type " + type);
  233. }
  234. if (rootElem.HasChild("emittersize"))
  235. emitterSize_ = rootElem.GetChild("emittersize").GetVector3("value");
  236. if (rootElem.HasChild("direction"))
  237. GetVector3MinMax(rootElem.GetChild("direction"), directionMin_, directionMax_);
  238. if (rootElem.HasChild("constantforce"))
  239. constanceForce_ = rootElem.GetChild("constantforce").GetVector3("value");
  240. if (rootElem.HasChild("dampingforce"))
  241. dampingForce_ = rootElem.GetChild("dampingforce").GetFloat("value");
  242. if (rootElem.HasChild("activetime"))
  243. activeTime_ = rootElem.GetChild("activetime").GetFloat("value");
  244. if (activeTime_ < 0.0f)
  245. activeTime_ = M_INFINITY;
  246. if (rootElem.HasChild("inactivetime"))
  247. inactiveTime_ = rootElem.GetChild("inactivetime").GetFloat("value");
  248. if (inactiveTime_ < 0.0f)
  249. inactiveTime_ = M_INFINITY;
  250. if (rootElem.HasChild("interval"))
  251. GetFloatMinMax(rootElem.GetChild("interval"), intervalMin_, intervalMax_);
  252. if (rootElem.HasChild("particlesize"))
  253. GetVector2MinMax(rootElem.GetChild("particlesize"), sizeMin_, sizeMax_);
  254. if (rootElem.HasChild("timetolive"))
  255. GetFloatMinMax(rootElem.GetChild("timetolive"), timeToLiveMin_, timeToLiveMax_);
  256. if (rootElem.HasChild("velocity"))
  257. GetFloatMinMax(rootElem.GetChild("velocity"), velocityMin_, velocityMax_);
  258. if (rootElem.HasChild("rotation"))
  259. GetFloatMinMax(rootElem.GetChild("rotation"), rotationMin_, rotationMax_);
  260. if (rootElem.HasChild("rotationspeed"))
  261. GetFloatMinMax(rootElem.GetChild("rotationspeed"), rotationSpeedMin_, rotationSpeedMax_);
  262. if (rootElem.HasChild("sizedelta"))
  263. {
  264. XMLElement deltaElem = rootElem.GetChild("sizedelta");
  265. if (deltaElem.HasAttribute("add"))
  266. sizeAdd_ = deltaElem.GetFloat("add");
  267. if (deltaElem.HasAttribute("mul"))
  268. sizeMul_ = deltaElem.GetFloat("mul");
  269. }
  270. if (rootElem.HasChild("color"))
  271. SetParticleColor(rootElem.GetChild("color").GetColor("value"));
  272. if (rootElem.HasChild("colorfade"))
  273. {
  274. Vector<ColorFade> fades;
  275. XMLElement colorFadeElem = rootElem.GetChild("colorfade");
  276. while (colorFadeElem)
  277. {
  278. ColorFade fade;
  279. fade.color_ = colorFadeElem.GetColor("color");
  280. fade.time_ = colorFadeElem.GetFloat("time");
  281. fades.Push(fade);
  282. colorFadeElem = colorFadeElem.GetNext("colorfade");
  283. }
  284. SetParticleColors(fades);
  285. }
  286. if (rootElem.HasChild("texanim"))
  287. {
  288. Vector<TextureAnimation> animations;
  289. XMLElement animElem = rootElem.GetChild("texanim");
  290. while (animElem)
  291. {
  292. TextureAnimation animation;
  293. animation.uv_ = animElem.GetRect("uv");
  294. animation.time_ = animElem.GetFloat("time");
  295. animations.Push(animation);
  296. animElem = animElem.GetNext("texanim");
  297. }
  298. textureAnimation_ = animations;
  299. }
  300. return true;
  301. }
  302. void ParticleEmitter::SetActive(bool enable, bool resetPeriod)
  303. {
  304. if (enable != active_ || resetPeriod)
  305. {
  306. active_ = enable;
  307. periodTimer_ = 0.0f;
  308. }
  309. }
  310. void ParticleEmitter::SetParameterSourceAttr(ResourceRef value)
  311. {
  312. ResourceCache* cache = GetSubsystem<ResourceCache>();
  313. LoadParameters(cache->GetResource<XMLFile>(value.id_));
  314. }
  315. void ParticleEmitter::SetParticlesAttr(PODVector<unsigned char> value)
  316. {
  317. MemoryBuffer buf(value);
  318. SetNumParticles(buf.ReadVLE());
  319. for (PODVector<Particle>::Iterator i = particles_.Begin(); i != particles_.End(); ++i)
  320. {
  321. i->velocity_ = buf.ReadVector3();
  322. i->size_ = buf.ReadVector2();
  323. i->timer_ = buf.ReadFloat();
  324. i->timeToLive_ = buf.ReadFloat();
  325. i->scale_ = buf.ReadFloat();
  326. i->rotationSpeed_ = buf.ReadFloat();
  327. i->colorIndex_ = buf.ReadVLE();
  328. i->texIndex_ = buf.ReadVLE();
  329. }
  330. }
  331. ResourceRef ParticleEmitter::GetParameterSourceAttr() const
  332. {
  333. return GetResourceRef(parameterSource_, XMLFile::GetTypeStatic());
  334. }
  335. PODVector<unsigned char> ParticleEmitter::GetParticlesAttr() const
  336. {
  337. VectorBuffer buf;
  338. buf.WriteVLE(particles_.Size());
  339. for (PODVector<Particle>::ConstIterator i = particles_.Begin(); i != particles_.End(); ++i)
  340. {
  341. buf.WriteVector3(i->velocity_);
  342. buf.WriteVector2(i->size_);
  343. buf.WriteFloat(i->timer_);
  344. buf.WriteFloat(i->timeToLive_);
  345. buf.WriteFloat(i->scale_);
  346. buf.WriteFloat(i->rotationSpeed_);
  347. buf.WriteVLE(i->colorIndex_);
  348. buf.WriteVLE(i->texIndex_);
  349. }
  350. return buf.GetBuffer();
  351. }
  352. void ParticleEmitter::OnNodeSet(Node* node)
  353. {
  354. if (node)
  355. {
  356. Scene* scene = node->GetScene();
  357. if (scene)
  358. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(ParticleEmitter, HandleScenePostUpdate));
  359. }
  360. BillboardSet::OnNodeSet(node);
  361. }
  362. void ParticleEmitter::SetNumParticles(int num)
  363. {
  364. num = Max(num, 0);
  365. particles_.Resize(num);
  366. SetNumBillboards(num);
  367. }
  368. void ParticleEmitter::SetParticleColor(const Color& color)
  369. {
  370. ColorFade newColor;
  371. newColor.color_ = color;
  372. newColor.time_ = 0.0f;
  373. colors_.Clear();
  374. colors_.Push(newColor);
  375. }
  376. void ParticleEmitter::SetParticleColors(const Vector<ColorFade>& colors)
  377. {
  378. if (!colors.Size())
  379. return;
  380. colors_ = colors;
  381. }
  382. bool ParticleEmitter::EmitNewParticle()
  383. {
  384. unsigned index = GetFreeParticle();
  385. if (index >= particles_.Size())
  386. return false;
  387. Particle& particle = particles_[index];
  388. Billboard& billboard = billboards_[index];
  389. Vector3 startPos;
  390. Vector3 startDir;
  391. switch (emitterType_)
  392. {
  393. case EMITTER_POINT:
  394. startPos = Vector3::ZERO;
  395. break;
  396. case EMITTER_BOX:
  397. startPos = Vector3(
  398. Random(emitterSize_.x_) - emitterSize_.x_ * 0.5f,
  399. Random(emitterSize_.y_) - emitterSize_.y_ * 0.5f,
  400. Random(emitterSize_.z_) - emitterSize_.z_ * 0.5f
  401. );
  402. break;
  403. case EMITTER_SPHERE:
  404. {
  405. Vector3 dir(
  406. Random(2.0f) - 1.0f,
  407. Random(2.0f) - 1.0f,
  408. Random(2.0f) - 1.0f
  409. );
  410. dir.Normalize();
  411. startPos = Random(emitterRadius_) * dir;
  412. }
  413. break;
  414. }
  415. startDir = Vector3(
  416. Lerp(directionMin_.x_, directionMax_.x_, Random(1.0f)),
  417. Lerp(directionMin_.y_, directionMax_.y_, Random(1.0f)),
  418. Lerp(directionMin_.z_, directionMax_.z_, Random(1.0f))
  419. );
  420. startDir.Normalize();
  421. if (!relative_)
  422. {
  423. startPos = GetWorldTransform() * startPos;
  424. startDir = GetWorldRotation() * startDir;
  425. };
  426. particle.velocity_ = Lerp(velocityMin_, velocityMax_, Random(1.0f)) * startDir;
  427. particle.size_ = sizeMin_.Lerp(sizeMax_, Random(1.0f));
  428. particle.timer_ = 0.0f;
  429. particle.timeToLive_ = Lerp(timeToLiveMin_, timeToLiveMax_, Random(1.0f));
  430. particle.scale_ = 1.0f;
  431. particle.rotationSpeed_ = Lerp(rotationSpeedMin_, rotationSpeedMax_, Random(1.0f));
  432. particle.colorIndex_ = 0;
  433. particle.texIndex_ = 0;
  434. billboard.position_ = startPos;
  435. billboard.size_ = particles_[index].size_;
  436. billboard.uv_ = textureAnimation_.Size() ? textureAnimation_[0].uv_ : Rect::POSITIVE;
  437. billboard.rotation_ = Lerp(rotationMin_, rotationMax_, Random(1.0f));
  438. billboard.color_ = colors_[0].color_;
  439. billboard.enabled_ = true;
  440. return true;
  441. }
  442. unsigned ParticleEmitter::GetFreeParticle() const
  443. {
  444. for (unsigned i = 0; i < billboards_.Size(); ++i)
  445. {
  446. if (!billboards_[i].enabled_)
  447. return i;
  448. }
  449. return M_MAX_UNSIGNED;
  450. }
  451. void ParticleEmitter::GetFloatMinMax(const XMLElement& element, float& minValue, float& maxValue)
  452. {
  453. if (element.IsNull())
  454. return;
  455. if (element.HasAttribute("value"))
  456. minValue = maxValue = element.GetFloat("value");
  457. if (element.HasAttribute("min") && element.HasAttribute("max"))
  458. {
  459. minValue = element.GetFloat("min");
  460. maxValue = element.GetFloat("max");
  461. }
  462. }
  463. void ParticleEmitter::GetVector2MinMax(const XMLElement& element, Vector2& minValue, Vector2& maxValue)
  464. {
  465. if (element.IsNull())
  466. return;
  467. if (element.HasAttribute("value"))
  468. minValue = maxValue = element.GetVector2("value");
  469. if (element.HasAttribute("min") && element.HasAttribute("max"))
  470. {
  471. minValue = element.GetVector2("min");
  472. maxValue = element.GetVector2("max");
  473. }
  474. }
  475. void ParticleEmitter::GetVector3MinMax(const XMLElement& element, Vector3& minValue, Vector3& maxValue)
  476. {
  477. if (element.IsNull())
  478. return;
  479. if (element.HasAttribute("value"))
  480. minValue = maxValue = element.GetVector3("value");
  481. if (element.HasAttribute("min") && element.HasAttribute("max"))
  482. {
  483. minValue = element.GetVector3("min");
  484. maxValue = element.GetVector3("max");
  485. }
  486. }
  487. void ParticleEmitter::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  488. {
  489. using namespace ScenePostUpdate;
  490. Update(eventData[P_TIMESTEP].GetFloat());
  491. }