Presentation is loading. Please wait.

Presentation is loading. Please wait.

9.3. P ARTICLE S YSTEMS Development of a particle system.

Similar presentations


Presentation on theme: "9.3. P ARTICLE S YSTEMS Development of a particle system."— Presentation transcript:

1 9.3. P ARTICLE S YSTEMS Development of a particle system

2 In lecture exploration of answers to frequently asked student questions

3 Development of an XNA/Java deployable particle system

4 A particle system can be used to simulate phenomena such as fire, smoke, explosions, moving water (e.g. fountains, waterfalls), sparks, dust, snow, rain, bullet casings, etc. Particle systems can also be used to provide special effects for spells, etc. or provide a model of fur and grass. Particle effects are widely used within games.

5 A particle system is typically controlled by an emitter. The emitter acts as the source for generated particles. Particles may be emitted at a constant rate or in sudden bursts. Each update/draw can be defined in terms of a simulation stage and a rendering stage. Each generated particle can have a number of defined parameters, e.g. velocity, direction, lifetime, colour, etc. Typically each parameter value is randomly selected from within some defined range.

6 Simulation Stage New particles are spawned if needed (alongside particle parameter selection/randomisation). Any particles that exceed their lifetime are removed from the simulation. All other particles properties are updated as needed (e.g. position, rotation, etc.) based on some simulation rules. The particles may also be tested for collision against other objects, with suitable interactions introduced Rendering stage Each particle is rendered (if in 3D typically using a textured billboard)

7 We will explore the XNA ParticleSample tutorial. Based upon the XNA ParticleSample tutorial Aside: The tutorial uses a SpriteBatch to render the particles – a GPU point sprite based approach is explored in a later lecture.

8 Each particle system comprises a number of particles. Each particle is defined with properties such as position, velocity, acceleration, rotation, lifetime, etc. When drawn each particle will display a common image that is layered on top of other particles (using either normal or additive blending). The particle properties are controlled to provide the desired effect.

9 public bool isActive { get { return timeSinceStart < lifetime; } } public void Initialize ( Vector2 position, Vector2 velocity, Vector2 acceleration, float lifetime, float scale, float rotationSpeed) { // Store passed values // Set time since start to zero // Randomly select rotation (0-2π radians) } public void Update(float dt) { velocity += acceleration * dt; position += velocity * dt; rotation += rotationSpeed * dt; timeSinceStart += dt; } } Definition position, velocity, rotation acceleration, and rotation speed Define how long this particle will ‘live’ before it is removed/reborn And how long it has been alive Define how long this particle will ‘live’ before it is removed/reborn And how long it has been alive Define the scale of this particle (i.e. how close/far from the camera) public class Particle { public Vector2 position ; public Vector2 velocity ; public Vector2 acceleration ; public float rotation ; public float rotationSpeed ; public float lifetime ; public float timeSinceStart ; public float scale ; Determine if this particle is alive Initialise the particle (e.g. upon particle reuse or ‘rebirth’) Called each frame to update the particle’s position and rotation Aside: Other properties can be stored within the particle.

10 The ParticleSystem class manages a collection of particle instances. As particles die and are reborn it is important the particle system caches and reuses particle (to reduce garbage collection churn). A particle system may have to manage particle load by controlling the number of active particles. Often the draw order for particles is important (i.e. particles drawn with normal alpha blending are drawn first before those using additive blending). The presented approach uses a generic particle system that is extended/customised for each effect. Other approaches involve having a single manager manage and draw a number of different types of particle.

11 public abstract class ParticleSystem : DrawableGameComponent { private Texture2D texture ; private Vector2 origin ; private const int howManyEffects ; Particle[] particles ; Queue freeParticles ; As a DrawableGameComponent, when added to a Game instance, XNA will automatically call the update and draw method Base texture used by particles in this system, alongside a defined origin for the texture Variable controlling the maximum number of effects of this type that can be ongoing Array of particles maintained by this system Queue from which new particles are born and to which dead particles are moved protected int minNumParticles ; protected int maxNumParticles ; protected float minInitialSpeed ; protected float maxInitialSpeed ; protected float minAcceleration ; protected float maxAcceleration ; protected float minRotationSpeed ; protected float maxRotationSpeed ; protected float minLifetime ; protected float maxLifetime ; protected float minScale ; protected float maxScale ; protected SpriteBlendMode spriteBlendMode; Min-max number of particles that are added per effect call Range of initial speeds, accelerations and rotational speeds. Range of lifespans – also drives alpha value and scale Range of scales – also effected by lifespan to avoid particle ‘popping’ on creation Blendmode to combined particle images

12 protected abstract void InitializeConstants (); protected override void LoadContent () { // Load/obtain the texture // used by the particle system // Set the origin, i.e. centre, // of the texture } Initialise the constants associated with this particle system protected ParticleSystem ( Game game, int howManyEffects) : base(game) { this.howManyEffects = howManyEffects; } public override void Initialize () { InitialiseConstants(); particles = new Particle[ howManyEffects * maxNumParticles]; freeParticles = new Queue ( howManyEffects * maxNumParticles); for (int i = 0; i < particles.Length; i++) { particles[i] = new Particle(); freeParticles.Enqueue(particles[i]); } } Create the particles and add them to the particles array and also to the free particle queue This method will be overridden by extending classes to providing initial defining values

13 Add the effect offered by this particle system at the specified location Remove particles from the free queue (where possible) and initialise them public void AddParticles ( Vector2 where) { int numParticles = Random.Next( minNumParticles, maxNumParticles); for (int i = 0; i < numParticles && freeParticles.Count > 0; i++) { Particle particle = freeParticles.Dequeue(); InitializeParticle(particle, where); } } protected virtual void InitializeParticle ( Particle particle, Vector2 where) { Vector2 direction = PickRandomDirection(); float velocity = Random.Next( min, max ); float acceleration = Random.Next( min, max ); float lifetime = Random.Next( min, max ); float scale = Random.Next( min, max ); float rotationSpeed = Random.Next( min, max ); particle. Initialize ( where, velocity * direction, acceleration * direction, lifetime, scale, rotationSpeed); } protected virtual Vector2 PickRandomDirection () { float angle = Random.Next(0, MathHelper.TwoPi); return new Vector2((float) Math.Cos(angle), (float)Math.Sin(angle)); } Min/max values as defined above, e.g. maxScale, minScale, etc. Randomise particle properties within defined ranges (can be overridden by extending classes)

14 public override void Draw (GameTime gameTime) { game.SpriteBatch.Begin(spriteBlendMode); foreach (Particle p in particles) { if (!p.Active) continue; float normalizedLifetime = p.TimeSinceStart / p.Lifetime; float alpha = 4 * normalizedLifetime * (1 - normalizedLifetime); Color color = new Color( new Vector4(1, 1, 1, alpha) ); float scale = p.Scale * (.75f +.25f * normalizedLifetime); game.SpriteBatch. Draw ( texture, p.Position, null, color, p.Rotation, origin, scale, SpriteEffects.None, 0.0f); } game.SpriteBatch.End(); } Determine how long has passed Consider each particle. This will also consider non-active particles (a performance hit). Other (more complex) approaches can be used to minimise/avoid non-active consideration. Update the particle and add to free particle queue if needed public override void Update ( GameTime gameTime) { float dt = (float)gameTime. ElapsedGameTime.TotalSeconds; foreach (Particle p in particles) { if (p.Active) { p.Update(dt); if (!p.Active) freeParticles.Enqueue(p); } } } Lifetime is normalised to be between 0 (born) and 1 (dead) and is used to calc alpha value (fade-in/out) and scale. Alpha = 0 at a lifetime of 0 and 1, and a maximum of 1 at a lifetime of 0.5 Particles slowly grow over their lifespan

15 Three different particle systems are defined: SmokePlumeParticleSystem ExplosionParticleSystem ExplosionSmokeParticleSystem The explosion and explosion smoke particle systems are combined to produce a full explosion effect. Each particle system customises the values within the inherited ParticleSystem class to provide the desired effect. public class SmokePlumeParticleSystem : ParticleSystem { protected override void InitializeConstants () { textureFilename = "smoke"; minInitialSpeed = 20; maxInitialSpeed = 100; minAcceleration = 0; maxAcceleration = 0; spriteBlendMode = SpriteBlendMode.AlphaBlend; }

16 The Game class defines three instances of the particle system: ExplosionParticleSystem explosion ; explosion = new ExplosionParticleSystem(this, 1); Components.Add(explosion); ExplosionSmokeParticleSystem smoke ;... SmokePlumeParticleSystem smokePlume ;... const float TimeBetweenExplosions = 2.0f; float timeTillExplosion = 0.0f; const float TimeBetweenSmokePlumePuffs =.5f; float timeTillPuff = 0.0f; Repeat times are defined for each particle effect (one explosion every 2 seconds, one puff of smoke every 0.5 seconds). XNA Aside: As the ParticleSystem instances extend DrawableGame- Component once added to the game, XNA will automatically call their update and draw methods, i.e. the methods do not need to be explicitly called.

17 Based on the currently active particle system, update the system to ensure that new effects are added as needed. protected override void Update ( GameTime gameTime) { switch (currentState) { case State.Explosions: UpdateExplosions(dt ); break; case State.SmokePlume: UpdateSmokePlume(dt ); break; } private void UpdateExplosions (float dt) { timeTillExplosion -= dt; if (timeTillExplosion < 0) { Vector2 where = Vector2.Zero; where.X = RandomBetween(0, graphics.GraphicsDevice.Viewport.Width); where.Y = RandomBetween(0, graphics.GraphicsDevice.Viewport.Height); explosion.AddParticles(where); smoke.AddParticles(where); timeTillExplosion = TimeBetweenExplosions; } } Update the currently active particle system Determine if it’s time for another explosion effect Select a random spawn location Add the fire and smoke effects Reset the time

18 To do: Complete Question Clinic Consider if material is of use within your game. Complete section in project document on alpha hand-in Submit alpha Hand-in if desired Today we explored: Overview of particle effects Development of an introductory particle system


Download ppt "9.3. P ARTICLE S YSTEMS Development of a particle system."

Similar presentations


Ads by Google