ParticleSystem.cs 16 KB

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