ParticleSystem.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // SmokePlumeParticleSystem.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Text;
  13. using Microsoft.Xna.Framework;
  14. using Microsoft.Xna.Framework.Graphics;
  15. #endregion
  16. namespace ParticleSample
  17. {
  18. /// <summary>
  19. /// ParticleSystem is an abstract class that provides the basic functionality to
  20. /// create a particle effect. Different subclasses will have different effects,
  21. /// such as fire, explosions, and plumes of smoke. To use these subclasses,
  22. /// simply call AddParticles, and pass in where the particles should exist
  23. /// </summary>
  24. public abstract class ParticleSystem : DrawableGameComponent
  25. {
  26. // these two values control the order that particle systems are drawn in.
  27. // typically, particles that use additive blending should be drawn on top of
  28. // particles that use regular alpha blending. ParticleSystems should therefore
  29. // set their DrawOrder to the appropriate value in InitializeConstants, though
  30. // it is possible to use other values for more advanced effects.
  31. public const int AlphaBlendDrawOrder = 100;
  32. public const int AdditiveDrawOrder = 200;
  33. // a reference to the main game; we'll keep this around because it exposes a
  34. // content manager and a sprite batch for us to use.
  35. private ParticleSampleGame game;
  36. // the texture this particle system will use.
  37. private Texture2D texture;
  38. // the origin when we're drawing textures. this will be the middle of the
  39. // texture.
  40. private Vector2 origin;
  41. // this number represents the maximum number of effects this particle system
  42. // will be expected to draw at one time. this is set in the constructor and is
  43. // used to calculate how many particles we will need.
  44. private int howManyEffects;
  45. // the array of particles used by this system. these are reused, so that calling
  46. // AddParticles will not cause any allocations.
  47. Particle[] particles;
  48. // the queue of free particles keeps track of particles that are not curently
  49. // being used by an effect. when a new effect is requested, particles are taken
  50. // from this queue. when particles are finished they are put onto this queue.
  51. Queue<Particle> freeParticles;
  52. /// <summary>
  53. /// returns the number of particles that are available for a new effect.
  54. /// </summary>
  55. public int FreeParticleCount
  56. {
  57. get { return freeParticles.Count; }
  58. }
  59. // This region of values control the "look" of the particle system, and should
  60. // be set by deriving particle systems in the InitializeConstants method. The
  61. // values are then used by the virtual function InitializeParticle. Subclasses
  62. // can override InitializeParticle for further
  63. // customization.
  64. #region constants to be set by subclasses
  65. /// <summary>
  66. /// minNumParticles and maxNumParticles control the number of particles that are
  67. /// added when AddParticles is called. The number of particles will be a random
  68. /// number between minNumParticles and maxNumParticles.
  69. /// </summary>
  70. protected int minNumParticles;
  71. protected int maxNumParticles;
  72. /// <summary>
  73. /// this controls the texture that the particle system uses. It will be used as
  74. /// an argument to ContentManager.Load.
  75. /// </summary>
  76. protected string textureFilename;
  77. /// <summary>
  78. /// minInitialSpeed and maxInitialSpeed are used to control the initial velocity
  79. /// of the particles. The particle's initial speed will be a random number
  80. /// between these two. The direction is determined by the function
  81. /// PickRandomDirection, which can be overriden.
  82. /// </summary>
  83. protected float minInitialSpeed;
  84. protected float maxInitialSpeed;
  85. /// <summary>
  86. /// minAcceleration and maxAcceleration are used to control the acceleration of
  87. /// the particles. The particle's acceleration will be a random number between
  88. /// these two. By default, the direction of acceleration is the same as the
  89. /// direction of the initial velocity.
  90. /// </summary>
  91. protected float minAcceleration;
  92. protected float maxAcceleration;
  93. /// <summary>
  94. /// minRotationSpeed and maxRotationSpeed control the particles' angular
  95. /// velocity: the speed at which particles will rotate. Each particle's rotation
  96. /// speed will be a random number between minRotationSpeed and maxRotationSpeed.
  97. /// Use smaller numbers to make particle systems look calm and wispy, and large
  98. /// numbers for more violent effects.
  99. /// </summary>
  100. protected float minRotationSpeed;
  101. protected float maxRotationSpeed;
  102. /// <summary>
  103. /// minLifetime and maxLifetime are used to control the lifetime. Each
  104. /// particle's lifetime will be a random number between these two. Lifetime
  105. /// is used to determine how long a particle "lasts." Also, in the base
  106. /// implementation of Draw, lifetime is also used to calculate alpha and scale
  107. /// values to avoid particles suddenly "popping" into view
  108. /// </summary>
  109. protected float minLifetime;
  110. protected float maxLifetime;
  111. /// <summary>
  112. /// to get some additional variance in the appearance of the particles, we give
  113. /// them all random scales. the scale is a value between minScale and maxScale,
  114. /// and is additionally affected by the particle's lifetime to avoid particles
  115. /// "popping" into view.
  116. /// </summary>
  117. protected float minScale;
  118. protected float maxScale;
  119. /// <summary>
  120. /// different effects can use different blend states. fire and explosions work
  121. /// well with additive blending, for example.
  122. /// </summary>
  123. protected BlendState blendState;
  124. #endregion
  125. /// <summary>
  126. /// Constructs a new ParticleSystem.
  127. /// </summary>
  128. /// <param name="game">The host for this particle system. The game keeps the
  129. /// content manager and sprite batch for us.</param>
  130. /// <param name="howManyEffects">the maximum number of particle effects that
  131. /// are expected on screen at once.</param>
  132. /// <remarks>it is tempting to set the value of howManyEffects very high.
  133. /// However, this value should be set to the minimum possible, because
  134. /// it has a large impact on the amount of memory required, and slows down the
  135. /// Update and Draw functions.</remarks>
  136. protected ParticleSystem(ParticleSampleGame game, int howManyEffects)
  137. : base(game)
  138. {
  139. this.game = game;
  140. this.howManyEffects = howManyEffects;
  141. }
  142. /// <summary>
  143. /// override the base class's Initialize to do some additional work; we want to
  144. /// call InitializeConstants to let subclasses set the constants that we'll use.
  145. ///
  146. /// also, the particle array and freeParticles queue are set up here.
  147. /// </summary>
  148. public override void Initialize()
  149. {
  150. InitializeConstants();
  151. // calculate the total number of particles we will ever need, using the
  152. // max number of effects and the max number of particles per effect.
  153. // once these particles are allocated, they will be reused, so that
  154. // we don't put any pressure on the garbage collector.
  155. particles = new Particle[howManyEffects * maxNumParticles];
  156. freeParticles = new Queue<Particle>(howManyEffects * maxNumParticles);
  157. for (int i = 0; i < particles.Length; i++)
  158. {
  159. particles[i] = new Particle();
  160. freeParticles.Enqueue(particles[i]);
  161. }
  162. base.Initialize();
  163. }
  164. /// <summary>
  165. /// this abstract function must be overriden by subclasses of ParticleSystem.
  166. /// It's here that they should set all the constants marked in the region
  167. /// "constants to be set by subclasses", which give each ParticleSystem its
  168. /// specific flavor.
  169. /// </summary>
  170. protected abstract void InitializeConstants();
  171. /// <summary>
  172. /// Override the base class LoadContent to load the texture. once it's
  173. /// loaded, calculate the origin.
  174. /// </summary>
  175. protected override void LoadContent()
  176. {
  177. // make sure sub classes properly set textureFilename.
  178. if (string.IsNullOrEmpty(textureFilename))
  179. {
  180. string message = "textureFilename wasn't set properly, so the " +
  181. "particle system doesn't know what texture to load. Make " +
  182. "sure your particle system's InitializeConstants function " +
  183. "properly sets textureFilename.";
  184. throw new InvalidOperationException(message);
  185. }
  186. // load the texture....
  187. texture = game.Content.Load<Texture2D>(textureFilename);
  188. // ... and calculate the center. this'll be used in the draw call, we
  189. // always want to rotate and scale around this point.
  190. origin.X = texture.Width / 2;
  191. origin.Y = texture.Height / 2;
  192. base.LoadContent();
  193. }
  194. /// <summary>
  195. /// AddParticles's job is to add an effect somewhere on the screen. If there
  196. /// aren't enough particles in the freeParticles queue, it will use as many as
  197. /// it can. This means that if there not enough particles available, calling
  198. /// AddParticles will have no effect.
  199. /// </summary>
  200. /// <param name="where">where the particle effect should be created</param>
  201. public void AddParticles(Vector2 where)
  202. {
  203. // the number of particles we want for this effect is a random number
  204. // somewhere between the two constants specified by the subclasses.
  205. int numParticles =
  206. ParticleSampleGame.Random.Next(minNumParticles, maxNumParticles);
  207. // create that many particles, if you can.
  208. for (int i = 0; i < numParticles && freeParticles.Count > 0; i++)
  209. {
  210. // grab a particle from the freeParticles queue, and Initialize it.
  211. Particle p = freeParticles.Dequeue();
  212. InitializeParticle(p, where);
  213. }
  214. }
  215. /// <summary>
  216. /// InitializeParticle randomizes some properties for a particle, then
  217. /// calls initialize on it. It can be overriden by subclasses if they
  218. /// want to modify the way particles are created. For example,
  219. /// SmokePlumeParticleSystem overrides this function make all particles
  220. /// accelerate to the right, simulating wind.
  221. /// </summary>
  222. /// <param name="p">the particle to initialize</param>
  223. /// <param name="where">the position on the screen that the particle should be
  224. /// </param>
  225. protected virtual void InitializeParticle(Particle p, Vector2 where)
  226. {
  227. // first, call PickRandomDirection to figure out which way the particle
  228. // will be moving. velocity and acceleration's values will come from this.
  229. Vector2 direction = PickRandomDirection();
  230. // pick some random values for our particle
  231. float velocity =
  232. ParticleSampleGame.RandomBetween(minInitialSpeed, maxInitialSpeed);
  233. float acceleration =
  234. ParticleSampleGame.RandomBetween(minAcceleration, maxAcceleration);
  235. float lifetime =
  236. ParticleSampleGame.RandomBetween(minLifetime, maxLifetime);
  237. float scale =
  238. ParticleSampleGame.RandomBetween(minScale, maxScale);
  239. float rotationSpeed =
  240. ParticleSampleGame.RandomBetween(minRotationSpeed, maxRotationSpeed);
  241. // then initialize it with those random values. initialize will save those,
  242. // and make sure it is marked as active.
  243. p.Initialize(
  244. where, velocity * direction, acceleration * direction,
  245. lifetime, scale, rotationSpeed);
  246. }
  247. /// <summary>
  248. /// PickRandomDirection is used by InitializeParticles to decide which direction
  249. /// particles will move. The default implementation is a random vector in a
  250. /// circular pattern.
  251. /// </summary>
  252. protected virtual Vector2 PickRandomDirection()
  253. {
  254. float angle = ParticleSampleGame.RandomBetween(0, MathHelper.TwoPi);
  255. return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
  256. }
  257. /// <summary>
  258. /// overriden from DrawableGameComponent, Update will update all of the active
  259. /// particles.
  260. /// </summary>
  261. public override void Update(GameTime gameTime)
  262. {
  263. // calculate dt, the change in the since the last frame. the particle
  264. // updates will use this value.
  265. float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
  266. // go through all of the particles...
  267. foreach (Particle p in particles)
  268. {
  269. if (p.Active)
  270. {
  271. // ... and if they're active, update them.
  272. p.Update(dt);
  273. // if that update finishes them, put them onto the free particles
  274. // queue.
  275. if (!p.Active)
  276. {
  277. freeParticles.Enqueue(p);
  278. }
  279. }
  280. }
  281. base.Update(gameTime);
  282. }
  283. /// <summary>
  284. /// overriden from DrawableGameComponent, Draw will use ParticleSampleGame's
  285. /// sprite batch to render all of the active particles.
  286. /// </summary>
  287. public override void Draw(GameTime gameTime)
  288. {
  289. // tell sprite batch to begin, using the spriteBlendMode specified in
  290. // initializeConstants
  291. game.SpriteBatch.Begin(SpriteSortMode.Deferred, blendState);
  292. foreach (Particle p in particles)
  293. {
  294. // skip inactive particles
  295. if (!p.Active)
  296. continue;
  297. // normalized lifetime is a value from 0 to 1 and represents how far
  298. // a particle is through its life. 0 means it just started, .5 is half
  299. // way through, and 1.0 means it's just about to be finished.
  300. // this value will be used to calculate alpha and scale, to avoid
  301. // having particles suddenly appear or disappear.
  302. float normalizedLifetime = p.TimeSinceStart / p.Lifetime;
  303. // we want particles to fade in and fade out, so we'll calculate alpha
  304. // to be (normalizedLifetime) * (1-normalizedLifetime). this way, when
  305. // normalizedLifetime is 0 or 1, alpha is 0. the maximum value is at
  306. // normalizedLifetime = .5, and is
  307. // (normalizedLifetime) * (1-normalizedLifetime)
  308. // (.5) * (1-.5)
  309. // .25
  310. // since we want the maximum alpha to be 1, not .25, we'll scale the
  311. // entire equation by 4.
  312. float alpha = 4 * normalizedLifetime * (1 - normalizedLifetime);
  313. Color color = Color.White * alpha;
  314. // make particles grow as they age. they'll start at 75% of their size,
  315. // and increase to 100% once they're finished.
  316. float scale = p.Scale * (.75f + .25f * normalizedLifetime);
  317. game.SpriteBatch.Draw(texture, p.Position, null, color,
  318. p.Rotation, origin, scale, SpriteEffects.None, 0.0f);
  319. }
  320. game.SpriteBatch.End();
  321. base.Draw(gameTime);
  322. }
  323. }
  324. }