ParticleEmitter.cpp 20 KB

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