Rampage/World/TownFx.cs

Pooled visual effects for the rampage town. Spawns rigidbody debris chunks with a cap and lifetime, physics-free puff balls for dust, fire, sparks and water, timed emitters such as a gushing hydrant or a sparking transformer, and expanding flood discs that shove nearby targets outward.

using System;
using System.Collections.Generic;

/// <summary>
/// Everything that flies off when the town breaks, all of it pooled and capped:
///  - chunks: rigid-body boxes in the colours of what broke, which scatter, bounce, lie about
///    and are taken back after a while (the oldest first, when the cap is reached);
///  - puffs: balls with no physics at all, moved by hand, for dust, water, fire and sparks;
///  - emitters that keep puffing for a while (a gushing hydrant, a sparking transformer);
///  - floods: a spreading sheet of water that carries loose things along with it.
/// Chunks are asked for and then made a few per frame, so a falling building never hitches.
/// </summary>
public sealed class TownFx
{
	readonly RampageWorld _world;
	// Asked of the town each time: it makes them again if they are ever lost.
	TownKit _kit => _world.Kit;
	GameObject _root => _world.FxRoot;

	public TownFx( RampageWorld world )
	{
		_world = world;
	}

	/// <summary>False if a hotload has left this without its town or its lists: the town then makes a new one.</summary>
	public bool Sound => _world.IsValid() && _chunks is not null && _orders is not null && _puffs is not null
		&& _freePuffs is not null && _emitters is not null && _pools is not null;

	static float Rand( float a, float b ) => Game.Random.Float( a, b );

	// ---- Chunks --------------------------------------------------------------------------------

	sealed class Lump
	{
		public GameObject Object;
		public ModelRenderer Renderer;
		public Rigidbody Body;
		public Vector3 Kick;
		public float Born, Dies;
		public bool Live, Kicked;
	}

	struct Order { public Vector3 At, Size, Velocity; public Color Colour; }

	readonly List<Lump> _chunks = new();
	readonly Queue<Order> _orders = new();

	public int LiveChunks { get; private set; }

	/// <summary>Asks for one chunk. It appears within a few frames.</summary>
	public void Chunk( Vector3 at, Vector3 size, Color colour, Vector3 velocity )
	{
		if ( _orders.Count >= 160 ) return;
		_orders.Enqueue( new Order { At = at, Size = size * Math.Clamp( _world.ChunkSize, 0.5f, 3f ), Colour = colour, Velocity = velocity } );
	}

	/// <summary>A prop bursts: pieces the size and colour of its own boxes, thrown the way it was hit.</summary>
	public void Shatter( TownShape shape, Vector3 position, Rotation rotation, Color body, Vector3 velocity, int pieces )
	{
		if ( shape.Parts.Count == 0 ) return;
		float biggest = Math.Clamp( shape.Radius * 0.5f, 24f, 110f );
		for ( int i = 0; i < pieces; i++ )
		{
			var part = shape.Parts[Game.Random.Next( shape.Parts.Count )];
			var size = new Vector3( Math.Clamp( part.Size.x, 8f, biggest ), Math.Clamp( part.Size.y, 8f, biggest ), Math.Clamp( part.Size.z, 8f, biggest ) );
			var fling = velocity * Rand( 0.4f, 1f ) + Vector3.Random * Rand( 120f, 320f ) + Vector3.Up * Rand( 150f, 380f );
			Chunk( position + rotation * part.Centre, size, part.Body ? body : part.Colour, fling );
		}
	}

	/// <summary>Loose lumps from somewhere inside a box (given by its half size), thrown up and outward.</summary>
	public void Rubble( Vector3 at, Vector3 half, Vector3 velocity, int count, float size, params Color[] colours )
	{
		float hx = MathF.Abs( half.x ), hy = MathF.Abs( half.y ), hz = MathF.Abs( half.z );
		for ( int i = 0; i < count; i++ )
		{
			var offset = new Vector3( Rand( -hx, hx ), Rand( -hy, hy ), Rand( -hz, hz ) );
			var outward = offset.WithZ( 0f );
			outward = outward.LengthSquared > 1f ? outward.Normal : Vector3.Zero;
			var lump = new Vector3( size * Rand( 0.6f, 1.3f ), size * Rand( 0.6f, 1.3f ), size * Rand( 0.5f, 1f ) );
			var colour = colours.Length > 0 ? colours[Game.Random.Next( colours.Length )] : Tone.Stone;
			Chunk( at + offset, lump, colour, velocity * Rand( 0.5f, 1.2f ) + outward * Rand( 150f, 420f ) );
		}
	}

	Lump NewChunk()
	{
		var chunk = new Lump { Object = _kit.Empty( _root, "Chunk" ) };
		chunk.Object.Tags.Add( "debris" );   // the lizard runs through rubble
		chunk.Renderer = _kit.Draw( chunk.Object, _kit.Cube, Color.White, false );
		var collider = chunk.Object.Components.Create<BoxCollider>();
		collider.Scale = new Vector3( TownKit.BoxSize, TownKit.BoxSize, TownKit.BoxSize );
		chunk.Body = chunk.Object.Components.Create<Rigidbody>();
		chunk.Body.AngularDamping = 0.8f;
		chunk.Body.LinearDamping = 0.2f;
		_chunks.Add( chunk );
		return chunk;
	}

	Puff NewPuff()
	{
		var puff = new Puff { Object = _kit.Empty( _root, "Puff" ) };
		puff.Renderer = _kit.Draw( puff.Object, _kit.Ball, Color.White, false );
		_puffs.Add( puff );
		return puff;
	}

	/// <summary>
	/// Makes a few more of the pooled chunks and puffs, switched off, ready for use. Called while
	/// the town is being raised, so that nothing has to be made in the middle of a collapse.
	/// False once the pools are full.
	/// </summary>
	public bool Prewarm( int count )
	{
		for ( int i = 0; i < count; i++ )
		{
			if ( _chunks.Count < _world.MaxChunks )
			{
				var chunk = NewChunk();
				chunk.Object.Enabled = false;
			}
			else if ( _puffs.Count < _world.MaxPuffs )
			{
				var puff = NewPuff();
				puff.Object.Enabled = false;
				_freePuffs.Push( puff );
			}
			else return false;
		}
		return true;
	}

	void MakeChunk( Order order )
	{
		Lump chunk = null;
		Lump oldest = null;
		foreach ( var c in _chunks )
		{
			if ( !c.Live ) { chunk = c; break; }
			if ( oldest is null || c.Born < oldest.Born ) oldest = c;
		}

		if ( chunk is null && _chunks.Count < _world.MaxChunks ) chunk = NewChunk();
		chunk ??= oldest;   // at the cap: the oldest piece lying about is the one nobody will miss
		if ( chunk is null || !chunk.Object.IsValid() ) return;

		float now = Time.Now;
		chunk.Object.Enabled = true;
		chunk.Object.WorldPosition = order.At.WithZ( MathF.Max( order.At.z, order.Size.z * 0.5f + 2f ) );
		chunk.Object.WorldRotation = Rotation.From( Rand( 0f, 360f ), Rand( 0f, 360f ), Rand( 0f, 360f ) );
		chunk.Object.WorldScale = order.Size / TownKit.BoxSize;
		if ( chunk.Renderer.IsValid() ) chunk.Renderer.Tint = order.Colour;

		chunk.Kick = order.Velocity;
		chunk.Kicked = false;
		chunk.Born = now;
		chunk.Dies = now + _world.ChunkLife * Rand( 0.8f, 1.25f );
		chunk.Live = true;
		if ( chunk.Body.IsValid() )
		{
			chunk.Body.Velocity = order.Velocity;
			chunk.Body.AngularVelocity = Vector3.Random * 8f;
		}
	}

	void TickChunks( float now )
	{
		int live = 0;
		foreach ( var chunk in _chunks )
		{
			if ( !chunk.Live ) continue;
			if ( !chunk.Object.IsValid() ) { chunk.Live = false; continue; }

			// A body switched on this frame may not have taken its speed: give it once more.
			if ( !chunk.Kicked )
			{
				chunk.Kicked = true;
				if ( chunk.Body.IsValid() && chunk.Body.Velocity.LengthSquared < chunk.Kick.LengthSquared * 0.25f )
				{
					chunk.Body.Velocity = chunk.Kick;
					chunk.Body.AngularVelocity = Vector3.Random * 8f;
				}
			}

			if ( now >= chunk.Dies || chunk.Object.WorldPosition.z < -300f )
			{
				chunk.Object.Enabled = false;
				chunk.Live = false;
				continue;
			}
			live++;
		}
		LiveChunks = live;

		for ( int i = 0; i < _world.ChunksPerFrame && _orders.Count > 0; i++ ) MakeChunk( _orders.Dequeue() );
	}

	// ---- Puffs ---------------------------------------------------------------------------------

	sealed class Puff
	{
		public GameObject Object;
		public ModelRenderer Renderer;
		public Vector3 Position, Velocity;
		public float Gravity, Drag, Born, Life, Size0, Size1;
		public bool Live;
	}

	readonly List<Puff> _puffs = new();
	readonly Stack<Puff> _freePuffs = new();

	/// <summary>One ball that drifts, grows from one size to another and shrinks away at the end of its life.</summary>
	public void Emit( Vector3 at, Vector3 velocity, float gravity, float drag, float life, float size0, float size1, Color colour )
	{
		Puff puff;
		if ( _freePuffs.Count > 0 ) puff = _freePuffs.Pop();
		else if ( _puffs.Count < _world.MaxPuffs ) puff = NewPuff();
		else return;

		if ( !puff.Object.IsValid() ) return;
		puff.Position = at;
		puff.Velocity = velocity;
		puff.Gravity = gravity;
		puff.Drag = drag;
		puff.Born = Time.Now;
		puff.Life = MathF.Max( life, 0.05f );
		puff.Size0 = size0;
		puff.Size1 = size1;
		puff.Live = true;
		puff.Object.WorldPosition = at;
		puff.Object.WorldScale = size0 / (TownKit.BallRadius * 2f);
		if ( puff.Renderer.IsValid() ) puff.Renderer.Tint = colour;
		puff.Object.Enabled = true;
	}

	void TickPuffs( float now, float dt )
	{
		foreach ( var puff in _puffs )
		{
			if ( !puff.Live ) continue;
			float t = (now - puff.Born) / puff.Life;
			if ( t >= 1f || !puff.Object.IsValid() )
			{
				puff.Live = false;
				if ( puff.Object.IsValid() ) { puff.Object.Enabled = false; _freePuffs.Push( puff ); }
				continue;
			}

			puff.Velocity += Vector3.Down * (puff.Gravity * dt);
			puff.Velocity *= MathF.Max( 0f, 1f - puff.Drag * dt );
			puff.Position += puff.Velocity * dt;
			if ( puff.Position.z < 4f && puff.Gravity > 0f )
			{
				// Landed: it sits where it fell for what is left of its life.
				puff.Position = puff.Position.WithZ( 4f );
				puff.Velocity = Vector3.Zero;
			}

			float size = puff.Size0 + (puff.Size1 - puff.Size0) * t;
			if ( t > 0.7f ) size *= (1f - t) / 0.3f;
			puff.Object.WorldPosition = puff.Position;
			puff.Object.WorldScale = MathF.Max( size, 0.5f ) / (TownKit.BallRadius * 2f);
		}
	}

	/// <summary>Pale dust rolling out from the foot of something that has just come down.</summary>
	public void Dust( Vector3 at, Vector3 half, int count )
	{
		float hx = MathF.Abs( half.x ), hy = MathF.Abs( half.y ), hz = MathF.Abs( half.z );
		float big = Math.Clamp( MathF.Max( hx, hy ) * 0.5f, 90f, 280f );
		for ( int i = 0; i < count; i++ )
		{
			var offset = new Vector3( Rand( -hx, hx ), Rand( -hy, hy ), Rand( 0f, hz ) );
			var outward = offset.WithZ( 0f );
			outward = outward.LengthSquared > 1f ? outward.Normal : Vector3.Random.WithZ( 0f );
			Emit( at + offset + Vector3.Up * 20f, outward * Rand( 80f, 240f ) + Vector3.Up * Rand( 30f, 130f ), 0f, 1.4f, Rand( 1.1f, 1.9f ),
				big * 0.4f, big * Rand( 0.8f, 1.2f ), Tone.Shade( Tone.Dust, Rand( 0.85f, 1.05f ) ) );
		}
	}

	/// <summary>A spray of balls thrown up and out, which fall back down.</summary>
	public void Burst( Vector3 at, int count, Color colour, float speed, float size0, float size1, float life )
	{
		for ( int i = 0; i < count; i++ )
		{
			var dir = Vector3.Random;
			dir = dir.WithZ( MathF.Abs( dir.z ) + 0.4f );
			Emit( at, dir * (speed * Rand( 0.5f, 1f )), 800f, 0.3f, life * Rand( 0.7f, 1.1f ), size0, size1, colour );
		}
	}

	/// <summary>A cartoon fireball: a ball of orange and yellow that swells and rises, and the black smoke after it.</summary>
	public void Fireball( Vector3 at, float scale )
	{
		for ( int i = 0; i < 12; i++ )
		{
			var dir = Vector3.Random;
			Emit( at + dir * (30f * scale), dir * (320f * scale) + Vector3.Up * 220f, -120f, 2.2f, Rand( 0.5f, 0.85f ), 70f * scale, 240f * scale,
				i % 3 == 0 ? Tone.Yellow : Tone.Fire );
		}
		for ( int i = 0; i < 6; i++ )
		{
			var dir = Vector3.Random.WithZ( 0f );
			Emit( at + Vector3.Up * 40f, dir * 120f + Vector3.Up * Rand( 160f, 300f ), 0f, 0.8f, Rand( 1.6f, 2.4f ), 80f * scale, 260f * scale, Tone.Smoke );
		}
		Rubble( at, new Vector3( 30f, 30f, 20f ), Vector3.Up * 500f, 6, 22f, Tone.Dark, Tone.Smoke, Tone.Red );
		_emitters.Add( new Emitter { At = at, Kind = EmitKind.Smoke, Until = Time.Now + 4f, Next = Time.Now + 0.3f } );
	}

	// ---- Things that keep going ------------------------------------------------------------------

	enum EmitKind { Gusher, Sparks, Smoke }
	struct Emitter { public Vector3 At; public EmitKind Kind; public float Until, Next; }
	readonly List<Emitter> _emitters = new();

	/// <summary>A broken hydrant: a column of water for a while.</summary>
	public void Gusher( Vector3 at, float seconds )
		=> _emitters.Add( new Emitter { At = at, Kind = EmitKind.Gusher, Until = Time.Now + seconds, Next = Time.Now } );

	/// <summary>A broken transformer: it spits sparks for a while.</summary>
	public void Sparks( Vector3 at, float seconds )
		=> _emitters.Add( new Emitter { At = at, Kind = EmitKind.Sparks, Until = Time.Now + seconds, Next = Time.Now } );

	void TickEmitters( float now )
	{
		for ( int i = _emitters.Count - 1; i >= 0; i-- )
		{
			var e = _emitters[i];
			if ( now >= e.Until ) { _emitters.RemoveAt( i ); continue; }
			if ( now < e.Next ) continue;

			switch ( e.Kind )
			{
				case EmitKind.Gusher:
					e.Next = now + 0.05f;
					Emit( e.At + Vector3.Up * 20f, new Vector3( Rand( -70f, 70f ), Rand( -70f, 70f ), Rand( 640f, 860f ) ), 1100f, 0f, 1.5f, 16f, 32f, Tone.Water );
					break;
				case EmitKind.Sparks:
					e.Next = now + 0.07f;
					var dir = Vector3.Random;
					Emit( e.At, dir.WithZ( MathF.Abs( dir.z ) + 0.3f ) * Rand( 200f, 420f ), 900f, 0f, 0.45f, 8f, 3f, Tone.Yellow );
					break;
				default:
					e.Next = now + 0.16f;
					Emit( e.At + Vector3.Up * 30f, new Vector3( Rand( -25f, 25f ), Rand( -25f, 25f ), Rand( 130f, 200f ) ), 0f, 0.3f, 2f, 40f, 130f, Tone.Smoke );
					break;
			}
			_emitters[i] = e;
		}
	}

	// ---- Floods --------------------------------------------------------------------------------

	sealed class Pool
	{
		public GameObject Disc;
		public Vector3 Centre;
		public float Born, MaxRadius, NextPush;
	}

	const float FloodGrow = 6f, FloodHold = 5f, FloodSink = 3f;
	readonly List<Pool> _pools = new();

	/// <summary>The water tower has gone over: a sheet of water spreads from here and carries the street with it.</summary>
	public void Flood( Vector3 at, float radius )
	{
		var disc = _kit.Blob( _root, "Flood", at.WithZ( at.z + 3f ), new Vector3( 10f, 10f, 14f ), Tone.Water );
		_pools.Add( new Pool { Disc = disc, Centre = at, Born = Time.Now, MaxRadius = radius } );
		Burst( at + Vector3.Up * 60f, 18, Tone.Water, 700f, 30f, 60f, 1.4f );
	}

	void TickPools( float now )
	{
		for ( int i = _pools.Count - 1; i >= 0; i-- )
		{
			var pool = _pools[i];
			float age = now - pool.Born;
			if ( age > FloodGrow + FloodHold + FloodSink || !pool.Disc.IsValid() )
			{
				if ( pool.Disc.IsValid() ) pool.Disc.Destroy();
				_pools.RemoveAt( i );
				continue;
			}

			// Fast at first and slowing as it thins out, then it lies there, then it drains away.
			float grown = MathF.Sqrt( Math.Clamp( age / FloodGrow, 0f, 1f ) );
			float radius = MathF.Max( pool.MaxRadius * grown, 20f );
			float depth = 14f * Math.Clamp( (FloodGrow + FloodHold + FloodSink - age) / FloodSink, 0.02f, 1f );
			float ball = TownKit.BallRadius * 2f;
			pool.Disc.WorldScale = new Vector3( radius * 2f / ball, radius * 2f / ball, depth / ball );

			if ( age >= FloodGrow || now < pool.NextPush ) continue;
			pool.NextPush = now + 0.25f;

			// Whatever the front of the water reaches is swept outward.
			const float front = 420f;
			var swept = Rampage.Borrow();
			Rampage.TargetsNear( pool.Centre, radius, swept );
			for ( int n = 0; n < swept.Count; n++ )
			{
				var target = swept[n];
				if ( target is Building || target is Toppler ) continue;
				var to = (target.Centre - pool.Centre).WithZ( 0f );
				float distance = to.Length;
				if ( distance < radius - front || distance < 1f ) continue;
				var sweep = to / distance * 380f + Vector3.Up * 80f;
				if ( target is Destructible prop ) { if ( prop.Kind.Weight != PropWeight.Huge ) prop.Shove( sweep ); }
				else target.Hit( sweep, 0f, pool.Centre );
			}
			Rampage.Return( swept );

			for ( int k = 0; k < 4; k++ )
			{
				float angle = Rand( 0f, MathF.PI * 2f );
				var edge = pool.Centre + new Vector3( MathF.Cos( angle ), MathF.Sin( angle ), 0f ) * radius;
				Emit( edge + Vector3.Up * 10f, new Vector3( Rand( -60f, 60f ), Rand( -60f, 60f ), Rand( 200f, 320f ) ), 900f, 0f, 0.7f, 26f, 44f, Tone.Water );
			}
		}
	}

	// ---- Every frame ---------------------------------------------------------------------------

	public void Tick( float dt )
	{
		float now = Time.Now;
		TickEmitters( now );
		TickPools( now );
		TickPuffs( now, dt );
		TickChunks( now );
	}
}