Rampage/Humans/RampagePopulace.Hits.cs

Part of RampagePopulace, the town crowd system. Wraps each person and each sleeping block in an IRampageTarget so weapons can hit them, awards points per role, delays the actual launch to the next frame, and handles shockwaves and the indignity reflex blast.

using System;
using System.Collections.Generic;

// Being clubbed: everybody in town as something the weapon can hit, what a hit does to them at
// each level, the score for it, shockwaves, and the indignity reflex.
public sealed partial class RampagePopulace
{
	/// <summary>One person as a target, whatever level they are at just now.</summary>
	sealed class PersonTarget : IRampageTarget
	{
		readonly RampagePopulace _town;
		readonly int _index;
		public PersonTarget( RampagePopulace town, int index ) { _town = town; _index = index; }

		// The index is checked each time: the people can be cleared away and built again under us.
		bool There => _town.IsValid() && _town._agents is { } agents && (uint)_index < (uint)agents.Length && ReferenceEquals( agents[_index].Target, this );
		public bool Alive => There && _town.CanHit( _index );
		public Vector3 Centre => There ? _town._agents[_index].Position + Vector3.Up * 36f : default;
		public float Radius => 24f;
		public void Hit( Vector3 velocity, float damage, Vector3 at ) { if ( There ) _town.HitAgent( _index, velocity, damage, at, 0 ); }
	}

	/// <summary>A whole sleeping block as one target: hit it and the lump wakes and scatters.</summary>
	sealed class LumpTarget : IRampageTarget
	{
		readonly RampagePopulace _town;
		readonly Cell _cell;
		public LumpTarget( RampagePopulace town, Cell cell ) { _town = town; _cell = cell; }

		public bool Alive => _town.IsValid() && !_cell.Awake;
		public Vector3 Centre => _cell.Centre + Vector3.Up * 36f;
		public float Radius => _cell.Radius;
		public void Hit( Vector3 velocity, float damage, Vector3 at ) => _town.HitLump( _cell, velocity, at );
	}

	struct QueuedHit { public int Agent, Chain; public Vector3 Velocity; }
	readonly List<QueuedHit> _hits = new();
	int _hitSpawns;

	// Scores: a few a frame are named one by one, the rest go on one line, so a shockwave through
	// a crowd is not two hundred labels.
	const int NamedScoresPerFrame = 4;
	int _scoresThisFrame, _lumpedCount;
	float _lumpedPoints;
	Vector3 _lumpedAt;

	bool CanHit( int i )
	{
		if ( (uint)i >= (uint)_agents.Length ) return false;
		ref var a = ref _agents[i];
		if ( a.Level != Level.StandIn && a.Level != Level.Real && a.Level != Level.Tossed ) return false;
		return Time.Now >= a.HitAt + RehitSeconds;
	}

	/// <summary>
	/// Somebody is hit. The score and the fright happen at once; the throwing is done on the next
	/// frame (see <see cref="ApplyHits"/>), because it may mean swapping a stand-in for a real body.
	/// False if the hit did not count (hit a moment ago, or not there to be hit).
	/// </summary>
	bool HitAgent( int i, Vector3 velocity, float damage, Vector3 at, int chain )
	{
		if ( !_built || i < 0 || i >= _agents.Length || !CanHit( i ) ) return false;
		ref var a = ref _agents[i];
		var role = HumanRoles.All[a.Role];
		if ( role.Manner == HumanManner.Child ) return false;       // never the child
		float now = Time.Now;
		a.HitAt = now;

		// A riot shield takes the first one: they slide, on their feet, very surprised.
		if ( a.Shielded )
		{
			a.Shielded = false;
			var slide = velocity.WithZ( 0f ) * 0.55f;
			if ( a.Level == Level.Real && a.Body is { } shield && shield.Person.IsValid() )
			{
				if ( shield.Prop.IsValid() ) shield.Prop.Destroy();
				shield.Person.Push( slide, 0.9f, now );
			}
			else if ( a.StandIn is { } s )
			{
				if ( s.Prop.IsValid() ) s.Prop.Enabled = false;
				a.Velocity = slide.ClampLength( 900f );
				a.Panic = 0.6f;
			}
			PopulaceFx.Sound( "shield_clang", a.Position );
			Named( a.Position, 5f, "RIOT SHIELD" );
			return true;
		}

		bool airborne = (a.Level == Level.Real && a.Body is { Flying: true }) || (a.Level == Level.Tossed && !a.Dazed);
		if ( !airborne )
		{
			Award( ref a, role, a.Position, a.Hits > 0 ? " (AGAIN)" : "" );
			if ( a.Hits < 250 ) a.Hits++;
			AddScare( a.Position, HitScareRadius );

			float speed = velocity.Length;
			PopulaceFx.Sound( speed > 1500f ? "whack_big" : "whack", a.Position, 1f, Game.Random.Float( 0.9f, 1.15f ) );
			if ( Game.Random.Float( 0f, 1f ) < 0.12f ) PopulaceFx.Sound( "wilhelm", a.Position, 0.9f );
			else if ( Game.Random.Float( 0f, 1f ) < 0.4f ) PopulaceFx.Sound( "yelp", a.Position, 0.8f, Game.Random.Float( 0.85f, 1.25f ) );
		}

		_hits.Add( new QueuedHit { Agent = i, Chain = chain, Velocity = Arc( velocity, role ) } );
		return true;
	}

	/// <summary>
	/// The cartoon arc: whatever the weapon did, they go up as well as along, never so slowly that
	/// it looks like a shove and never so fast that they leave town.
	/// </summary>
	Vector3 Arc( Vector3 velocity, HumanRole role )
	{
		var flat = velocity.WithZ( 0f );
		float along = flat.Length;
		if ( along < 1f )
		{
			float angle = Game.Random.Float( 0f, MathF.PI * 2f );
			flat = new Vector3( MathF.Cos( angle ), MathF.Sin( angle ), 0f );
			along = 1f;
		}

		float speed = Math.Clamp( velocity.Length * role.Flight, MinLaunch, MaxLaunch );
		float up = MathF.Max( MathF.Max( velocity.z, 0f ), along * ArcLift );
		var thrown = new Vector3( flat.x, flat.y, MathF.Max( up, along * 0.25f + 1f ) ).Normal * speed;
		thrown.z = MathF.Max( thrown.z, 340f );
		return thrown;
	}

	/// <summary>Does the throwing for every hit since the last time: real bodies are launched, stand-ins are made real if there is room, and thrown the cheap way if not.</summary>
	void ApplyHits()
	{
		if ( _hits.Count == 0 ) return;
		float now = Time.Now;
		int hitCap = _strained ? Math.Min( HitSpawnPerFrame, 2 ) : HitSpawnPerFrame;

		for ( int n = 0; n < _hits.Count; n++ )
		{
			var hit = _hits[n];
			ref var a = ref _agents[hit.Agent];

			if ( a.Level == Level.Asleep ) WakeAgent( hit.Agent );      // hit in a sleeping lump

			if ( a.Level == Level.Real && a.Body is { } body )
			{
				a.Chain = (byte)Math.Min( hit.Chain, 250 );
				a.Squad = -1;
				if ( body.Rb.IsValid() ) Launch( body, hit.Velocity, now );
				else { body.HasPending = true; body.Pending = hit.Velocity; }
				continue;
			}

			if ( a.Level == Level.Tossed ) { Toss( hit.Agent, hit.Velocity, hit.Chain ); continue; }
			if ( a.Level != Level.StandIn ) continue;

			// A stand-in: a real body if the frame can stand one more, else the cheap way.
			if ( _real.Count < MaxReal && _flying + _hitSpawns < MaxAirborne && _hitSpawns < hitCap && !a.Stranded )
			{
				_hitSpawns++;
				var made = Promote( hit.Agent );
				a.Chain = (byte)Math.Min( hit.Chain, 250 );
				a.Squad = -1;
				made.HasPending = true;
				made.Pending = hit.Velocity;
			}
			else if ( _tossed.Count < MaxTossed ) Toss( hit.Agent, hit.Velocity, hit.Chain );
			else
			{
				// Even the cheap sky is full: knocked sideways, and very frightened.
				a.Velocity = hit.Velocity.WithZ( 0f ).ClampLength( 700f );
				a.Panic = 1f;
				a.Cowed = true;
			}
		}
		_hits.Clear();
	}

	/// <summary>A sleeping block was hit as a lump: it wakes, everybody in it panics, and the ones where the blow fell go flying.</summary>
	void HitLump( Cell cell, Vector3 velocity, Vector3 at )
	{
		if ( !_built || cell.Awake ) return;
		WakeCell( cell );
		PopulaceFx.Sound( "lump_scatter", at );
		AddScare( at, cell.Radius * 2f );

		int thrown = 0;
		foreach ( int i in cell.Agents )
		{
			ref var a = ref _agents[i];
			a.Panic = 1f;
			if ( thrown >= 12 || FlatDistance( a.Position, at ) > 280f ) continue;
			var outward = (a.Position - at).WithZ( 0f );
			if ( HitAgent( i, velocity + outward.ClampLength( 1f ) * 200f, 0f, a.Position, 0 ) ) thrown++;
		}
	}

	// ---- The score ----------------------------------------------------------------------------------

	/// <summary>Points for somebody, under their own name.</summary>
	void Award( ref Agent a, HumanRole role, Vector3 at, string suffix )
	{
		float points = role.Points * (a.Hits > 0 ? 0.5f : 1f);
		if ( points <= 0f ) return;
		Named( at, points, role.Label + suffix );
	}

	void Named( Vector3 at, float points, string label )
	{
		if ( _scoresThisFrame < NamedScoresPerFrame )
		{
			_scoresThisFrame++;
			Rampage.Score( at + Vector3.Up * 60f, points, label, human: true );
			return;
		}
		_lumpedCount++;
		_lumpedPoints += points;
		_lumpedAt = at;
	}

	static readonly string[] LumpLabels = { "MORE BYSTANDERS", "OTHER PILLOCKS", "ASSORTED PUBLIC", "PEOPLE WHO WERE WARNED", "MORE (NOT WORTH NAMING)" };

	/// <summary>Everybody who was hit this frame beyond the first few, on one line.</summary>
	void FlushScores()
	{
		if ( _lumpedCount == 0 ) return;
		string label = _lumpedCount == 1 ? "ONE MORE" : $"{_lumpedCount} {LumpLabels[Game.Random.Next( LumpLabels.Length )]}";
		Rampage.Score( _lumpedAt + Vector3.Up * 90f, _lumpedPoints, label, human: true );
		_lumpedCount = 0;
		_lumpedPoints = 0f;
	}

	// ---- Shockwaves ---------------------------------------------------------------------------------

	/// <summary>A shockwave: everybody in range is thrown outward, hardest in the middle. Further out they are only shoved, and frightened.</summary>
	void OnShockwave( Vector3 centre, float radius, float speed )
	{
		if ( !_built || radius <= 1f ) return;
		Blast( centre, radius, speed, 0.65f );
	}

	void Blast( Vector3 centre, float radius, float speed, float lift )
	{
		float now = Time.Now;

		// Sleeping lumps in range wake first, so their people are in the lists below.
		foreach ( var cell in _cells )
			if ( !cell.Awake && FlatDistance( cell.Centre, centre ) < radius * 0.8f + cell.Radius ) WakeCell( cell );

		for ( int n = _awake.Count - 1; n >= 0; n-- )
		{
			int i = _awake[n];
			ref var a = ref _agents[i];
			var offset = a.Position - centre;
			float distance = offset.WithZ( 0f ).Length;
			if ( distance > radius * 1.5f ) continue;
			a.Panic = 1f;
			if ( distance > radius || MathF.Abs( offset.z ) > radius ) continue;

			float force = speed * (1f - distance / radius);
			var outward = distance > 1f ? offset.WithZ( 0f ) / distance : Vector3.Random.WithZ( 0f ).Normal;
			var thrown = outward * force + Vector3.Up * force * lift;
			if ( force > 160f ) HitAgent( i, thrown, 0f, a.Position, 0 );
			else if ( a.Level == Level.StandIn ) a.Velocity += outward * force;
		}

		for ( int n = 0; n < _real.Count; n++ )
		{
			var body = _real[n];
			if ( !body.Person.IsValid() ) continue;
			var offset = body.Person.WorldPosition - centre;
			float distance = offset.WithZ( 0f ).Length;
			if ( distance > radius || MathF.Abs( offset.z ) > radius ) continue;

			float force = speed * (1f - distance / radius);
			var outward = distance > 1f ? offset.WithZ( 0f ) / distance : Vector3.Random.WithZ( 0f ).Normal;
			if ( force > 160f ) HitAgent( body.Agent, outward * force + Vector3.Up * force * lift, 0f, body.Person.WorldPosition, 0 );
			else body.Person.Push( outward * force, 0.5f, now );
		}

		AddScare( centre, radius * 1.5f );
		_alarm = 1f;
	}

	// ---- The indignity reflex -----------------------------------------------------------------------

	/// <summary>
	/// The lizard has been under a pile for long enough. The grips have already let go (see
	/// <see cref="PopulaceGrips"/>); this throws everybody near it outward in a ring.
	/// </summary>
	void OnReflex( Vector3 at )
	{
		Blast( at, 380f, 1500f, 0.8f );
		PopulaceFx.Sound( "indignity", at );
		Rampage.Shake( 0.8f );
		Rampage.Announce( "THE INDIGNITY REFLEX. HANDS OFF.", 2f );
		IndignityReflex?.Invoke( at );
	}
}