Sump/Finale/FinaleProcession.cs

The follower procession for the Sump finale. Spawns a body and glow lamp per healed misfit, lays a crumb trail of the player's path and walks each follower into a loose column behind it, with states for posted, marked, carried and held, plus occasional chatter lines routed through MisfitVoice.

using System;
using System.Collections.Generic;

public enum FollowerState
{
	/// <summary>Walking behind the player in the column.</summary>
	Following,
	/// <summary>Walking to a place it has been given (the ring round the heart).</summary>
	Posted,
	/// <summary>Frozen: the cells have noticed it and are closing in.</summary>
	Marked,
	/// <summary>Being carried off by the cells. Whoever carries it moves it.</summary>
	Carried,
	/// <summary>Put down in a nest, waiting to be fetched.</summary>
	Held,
}

/// <summary>One healed misfit walking down with the player.</summary>
public sealed class FinaleFollower
{
	public MisfitProfile Profile;
	public string Name = "";
	public GameObject Go;
	public MisfitBody Body;
	public PointLight Glow;

	/// <summary>Feet, in the world. The layer moves it by hand while it is carried or held.</summary>
	public Vector3 Position;
	public float Yaw;
	/// <summary>Its own walking speed, in inches per second. The slowest is the one the cells take first.</summary>
	public float Pace;
	/// <summary>How far to one side of the column it walks.</summary>
	public float Side;
	public FollowerState State;
	/// <summary>Seconds in this state.</summary>
	public float StateTime;
	/// <summary>Where a <see cref="FollowerState.Posted"/> follower is walking to.</summary>
	public Vector3 Post;
	/// <summary>0 dark to 1: how brightly the thing it clings to glows.</summary>
	public float GlowLevel;
	public float Speed;

	public bool Free => State == FollowerState.Following || State == FollowerState.Posted;
	public bool AtPost => State == FollowerState.Posted && (Post - Position).WithZ( 0f ).Length < 26f;

	public void Set( FollowerState state )
	{
		if ( State == state ) return;
		State = state;
		StateTime = 0f;
	}
}

/// <summary>
/// The patchwork procession: every healed misfit walking behind the player in a loose column,
/// along the path the player actually took. They have no collision and cannot be hurt; the worst
/// that happens is that one is carried off and has to be fetched. They talk now and then, each
/// through its own speech tic.
/// </summary>
public sealed class FinaleProcession
{
	// ---- Tuning ---------------------------------------------------------------------------------
	/// <summary>Distance between one follower and the next along the column.</summary>
	public float Spacing = 85f;
	/// <summary>The first follower keeps this far behind the player.</summary>
	public float Gap = 80f;
	/// <summary>Followers walk between these speeds (the player walks at 300 and runs at 620).</summary>
	public float PaceMin = 225f, PaceMax = 275f;
	/// <summary>Further behind its place than this, a follower hurries.</summary>
	public float HurryDistance = 350f;
	public float HurryFactor = 1.35f;
	/// <summary>Seconds between one odd line and the next, least and most.</summary>
	public float ChatterMin = 14f, ChatterMax = 24f;

	const float CrumbSpacing = 30f;
	const int MaxCrumbs = 700;

	public IReadOnlyList<FinaleFollower> Followers => _followers;
	public int Count => _followers.Count;
	/// <summary>Height of the ground under a point, from whichever layer is being played.</summary>
	public Func<Vector3, float> Floor { get; set; }

	readonly List<FinaleFollower> _followers = new();
	readonly List<Vector3> _trail = new();   // where the player has been, oldest first
	readonly Random _rng;
	Vector3 _facing = Vector3.Forward;
	float _nextChatter;
	int _lastSpeaker = -1;

	public FinaleProcession( GameObject root, IEnumerable<MisfitProfile> healed, int seed )
	{
		_rng = new Random( seed );
		int i = 0;
		foreach ( var profile in healed )
		{
			var go = new GameObject( root, true, "Follower " + MisfitVoice.ShortName( profile ) );
			go.Flags |= GameObjectFlags.NotSaved;

			var follower = new FinaleFollower
			{
				Profile = profile,
				Name = MisfitVoice.ShortName( profile ),
				Go = go,
				Body = MisfitBody.Create( go, profile, 1f ),
				Pace = PaceMin + (float)_rng.NextDouble() * (PaceMax - PaceMin),
				Side = (i % 2 == 0 ? 1f : -1f) * (18f + (float)_rng.NextDouble() * 26f),
			};

			// A small light of its own colour, where the thing it clings to is. Dark until it speaks up.
			var lamp = new GameObject( go, true, "Keepsake Glow" );
			lamp.Flags |= GameObjectFlags.NotSaved;
			lamp.LocalPosition = Vector3.Up * 30f;
			follower.Glow = lamp.Components.Create<PointLight>();
			follower.Glow.LightColor = Color.Black;
			follower.Glow.Radius = 260f;
			follower.Glow.Shadows = false;
			follower.Glow.Enabled = false;

			_followers.Add( follower );
			i++;
		}
		_nextChatter = 8f;
	}

	/// <summary>Puts everybody who is free in a column behind a spot, and forgets the old trail (after a teleport).</summary>
	public void Regroup( Vector3 at, float yaw, bool everyone = false )
	{
		_facing = Rotation.FromYaw( yaw ).Forward;
		_trail.Clear();
		var left = Vector3.Cross( Vector3.Up, _facing );

		int place = 0;
		foreach ( var follower in _followers )
		{
			if ( everyone ) follower.Set( FollowerState.Following );
			if ( follower.State != FollowerState.Following ) continue;

			var spot = at - _facing * (Gap + place * Spacing) + left * follower.Side;
			follower.Position = Grounded( spot );
			follower.Yaw = yaw;
			follower.Speed = 0f;
			Apply( follower, 0f );
			place++;
		}
	}

	/// <summary>Once a frame: lays the trail, walks everybody, and keeps the bodies where their followers are.</summary>
	public void Update( float dt, Vector3 player )
	{
		// The trail: a crumb every so often where the player has been, on the ground.
		var feet = Grounded( player );
		if ( _trail.Count == 0 || (feet - _trail[^1]).WithZ( 0f ).Length > CrumbSpacing )
		{
			if ( _trail.Count > 0 )
			{
				var step = (feet - _trail[^1]).WithZ( 0f );
				if ( step.Length > 1f ) _facing = step.Normal;
			}
			_trail.Add( feet );
			if ( _trail.Count > MaxCrumbs ) _trail.RemoveAt( 0 );
		}

		int place = 0;
		foreach ( var follower in _followers )
		{
			follower.StateTime += dt;
			switch ( follower.State )
			{
				case FollowerState.Following:
					Walk( follower, PlaceBehind( feet, Gap + place * Spacing, follower.Side ), dt, true );
					place++;
					break;

				case FollowerState.Posted:
					Walk( follower, follower.Post, dt, false );
					break;

				case FollowerState.Marked:
				case FollowerState.Held:
					follower.Speed = 0f;
					follower.Position = Grounded( follower.Position );
					break;

				case FollowerState.Carried:
					break;   // moved by whoever is carrying it
			}
			Apply( follower, dt );
		}
	}

	/// <summary>The spot a given distance back along the player's trail, a little to one side.</summary>
	Vector3 PlaceBehind( Vector3 player, float distance, float side )
	{
		var previous = player;
		var direction = _facing;
		float walked = 0f;
		var point = player - _facing * distance;
		bool found = false;

		for ( int i = _trail.Count - 1; i >= 0; i-- )
		{
			var crumb = _trail[i];
			float length = (previous - crumb).WithZ( 0f ).Length;
			if ( length > 0.5f )
			{
				direction = (previous - crumb).WithZ( 0f ).Normal;
				if ( walked + length >= distance )
				{
					point = Vector3.Lerp( previous, crumb, (distance - walked) / length );
					found = true;
					break;
				}
				walked += length;
			}
			previous = crumb;
		}

		// The trail is shorter than the column (just arrived): line up behind its far end.
		if ( !found ) point = previous - direction * (distance - walked);

		var left = Vector3.Cross( Vector3.Up, direction );
		return point + left * side;
	}

	void Walk( FinaleFollower follower, Vector3 target, float dt, bool hurry )
	{
		var to = (target - follower.Position).WithZ( 0f );
		float distance = to.Length;
		if ( distance < 10f )
		{
			follower.Speed = 0f;
			follower.Position = Grounded( follower.Position );
			return;
		}

		float speed = follower.Pace * Math.Clamp( distance / 60f, 0.3f, 1f );
		if ( hurry && distance > HurryDistance ) speed *= HurryFactor;
		float step = MathF.Min( speed * dt, distance );

		var direction = to / distance;
		follower.Position = Grounded( follower.Position + direction * step );
		follower.Speed = dt > 0f ? step / dt : 0f;

		float wanted = MathF.Atan2( direction.y, direction.x ) * (180f / MathF.PI);
		float turn = ((wanted - follower.Yaw) % 360f + 540f) % 360f - 180f;
		follower.Yaw += turn * Math.Clamp( dt * 6f, 0f, 1f );
	}

	Vector3 Grounded( Vector3 point ) => Floor is null ? point : point.WithZ( Floor( point ) );

	/// <summary>Puts the body where the follower is and shows how it feels about that.</summary>
	void Apply( FinaleFollower follower, float dt )
	{
		if ( !follower.Go.IsValid() ) return;
		follower.Go.WorldPosition = follower.Position;
		follower.Go.WorldRotation = Rotation.FromYaw( follower.Yaw );

		if ( follower.Body.IsValid() )
		{
			float fear = follower.State switch
			{
				FollowerState.Marked => 0.9f,
				FollowerState.Carried => 1f,
				FollowerState.Held => 0.7f,
				_ => 0.08f,
			};
			follower.Body.MoveSpeed = follower.Speed;
			follower.Body.Agitation += (fear - follower.Body.Agitation) * Math.Clamp( dt * 3f, 0f, 1f );
		}

		if ( follower.Glow.IsValid() )
		{
			bool lit = follower.GlowLevel > 0.01f;
			if ( follower.Glow.Enabled != lit ) follower.Glow.Enabled = lit;
			if ( lit )
			{
				var colour = follower.Profile?.Primary ?? Color.White;
				follower.Glow.LightColor = (colour * (follower.GlowLevel * 2.2f)).WithAlpha( 1f );
				if ( follower.Body.IsValid() && follower.Body.Prop.IsValid() )
					follower.Glow.WorldPosition = follower.Body.Prop.WorldPosition + Vector3.Up * 6f;
			}
		}
	}

	// ---- Questions the layers ask -----------------------------------------------------------------

	/// <summary>How many followers walking free are within a distance of a point.</summary>
	public int CountNear( Vector3 at, float radius, FinaleFollower except = null )
	{
		int count = 0;
		foreach ( var follower in _followers )
			if ( follower != except && follower.Free && (follower.Position - at).WithZ( 0f ).Length <= radius ) count++;
		return count;
	}

	/// <summary>True when everybody still following is within a distance of the player (true with nobody following).</summary>
	public bool Gathered( Vector3 player, float radius )
	{
		foreach ( var follower in _followers )
			if ( follower.State == FollowerState.Following && (follower.Position - player).WithZ( 0f ).Length > radius ) return false;
		return true;
	}

	/// <summary>Anybody who has been noticed, carried off or put in a nest; null if nobody.</summary>
	public FinaleFollower FirstTaken()
	{
		foreach ( var follower in _followers )
			if ( !follower.Free ) return follower;
		return null;
	}

	/// <summary>The follower nearest a point (free ones only), or null.</summary>
	public FinaleFollower Nearest( Vector3 at )
	{
		FinaleFollower best = null;
		float nearest = float.MaxValue;
		foreach ( var follower in _followers )
		{
			if ( !follower.Free ) continue;
			float d = (follower.Position - at).LengthSquared;
			if ( d < nearest ) { nearest = d; best = follower; }
		}
		return best;
	}

	// ---- Talking ----------------------------------------------------------------------------------

	/// <summary>A follower says a plain line, in its own way of speaking. {object} and {arole} are filled in.</summary>
	public void Say( FinaleFollower follower, string plain, float seconds = 5.5f )
	{
		if ( follower is null || string.IsNullOrEmpty( plain ) ) return;
		Sump.Say( follower.Name, MisfitVoice.Speak( follower.Profile, FinaleWriting.Fill( plain, follower.Profile ) ), seconds );
		if ( follower.Body.IsValid() ) follower.Body.Flinch();
		_nextChatter = MathF.Max( _nextChatter, 7f );
	}

	/// <summary>The follower nearest the player says a plain line (or nobody does, if there is nobody).</summary>
	public void SayNearest( Vector3 player, string plain, float seconds = 5.5f ) => Say( Nearest( player ), plain, seconds );

	/// <summary>Now and then somebody says one of the layer's odd lines.</summary>
	public void Chatter( float dt, IReadOnlyList<string> pool )
	{
		_nextChatter -= dt;
		if ( _nextChatter > 0f || pool is null || pool.Count == 0 || _followers.Count == 0 ) return;
		_nextChatter = ChatterMin + (float)_rng.NextDouble() * (ChatterMax - ChatterMin);

		// Not the same one twice running, and nobody who is busy being carried off.
		for ( int tries = 0; tries < 6; tries++ )
		{
			int pick = _rng.Next( _followers.Count );
			if ( (pick == _lastSpeaker && _followers.Count > 1) || !_followers[pick].Free ) continue;
			_lastSpeaker = pick;
			Say( _followers[pick], pool[_rng.Next( pool.Count )] );
			_nextChatter = ChatterMin + (float)_rng.NextDouble() * (ChatterMax - ChatterMin);
			return;
		}
	}
}