Sump/Misfits/MisfitSpawner.cs

The MisfitSpawner component of the Sump game. Places one Misfit per profile around the cavern once the player arrives, using spots supplied through SpotSource or a seeded ring of traced floor positions, and re-spawns them when the Sump is rolled again. Also picks the misfit most in view for the prompt, hint text and Use key handling.

using System.Linq;
using System;
using System.Collections.Generic;

/// <summary>
/// Puts every misfit of this Sump into the cavern, one <see cref="Misfit"/> per profile, once the
/// player has arrived. It also decides which misfit the player is talking to: the one most
/// squarely in view gets the prompt and the Use key. Added to the Sump object by SumpBootstrap.
/// </summary>
[Title( "Misfit Spawner" ), Category( "Sump" ), Icon( "groups" )]
public sealed class MisfitSpawner : Component
{
	/// <summary>
	/// Where the misfits go, one spot each (feet on the floor). Set by whoever knows the cavern;
	/// while it is null or gives nothing, the spawner finds its own spots on a ring round the hub.
	/// </summary>
	public static Func<IReadOnlyList<Vector3>> SpotSource { get; set; }

	/// <summary>Seconds to wait for the player to arrive before placing the misfits anyway.</summary>
	[Property] public float WaitSeconds { get; set; } = 6f;

	/// <summary>With no spots given: misfits are placed between these distances from the hub spawn.</summary>
	[Property] public float RingMin { get; set; } = 500f;
	[Property] public float RingMax { get; set; } = 1400f;

	/// <summary>Show a hint under the crosshair while a misfit does not trust the player yet.</summary>
	[Property] public bool ShowHints { get; set; } = true;

	/// <summary>True once the misfits are in the cavern.</summary>
	public bool Spawned { get; private set; }

	/// <summary>The misfit whose prompt is up right now, or null.</summary>
	public Misfit Focus { get; private set; }

	float _startedAt;
	string _prompt;                 // the prompt this spawner last put up, so it only clears its own
	MisfitProfile _first;           // to notice the Sump being rolled again
	readonly List<Misfit> _mine = new();

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;
		_startedAt = Time.Now;
		SumpState.MisfitHealed += OnMisfitHealed;
	}

	protected override void OnDestroy()
	{
		SumpState.MisfitHealed -= OnMisfitHealed;
	}

	void OnMisfitHealed( MisfitProfile profile )
	{
		var misfit = Misfit.Find( profile );
		if ( misfit.IsValid() ) misfit.OnHealed();
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;

		// A new Sump was rolled under us: start again with the new residents.
		if ( Spawned && (SumpState.Misfits.Count == 0 || SumpState.Misfits[0] != _first) ) Clear();

		if ( !Spawned )
		{
			float waited = Time.Now - _startedAt;
			bool arrived = Sump.Mode != SumpMode.Arrival;
			// With no hub position yet there is nowhere sensible to put them: give the cavern longer.
			bool placeable = SpotSource is not null || Sump.HubSpawn != Vector3.Zero || waited > WaitSeconds * 4f;
			if ( (arrived || waited > WaitSeconds) && placeable && SumpState.Misfits.Count > 0 ) SpawnAll();
			return;
		}

		UpdateFocus();
	}

	void Clear()
	{
		foreach ( var misfit in _mine )
			if ( misfit.IsValid() ) misfit.GameObject.Destroy();
		_mine.Clear();
		Spawned = false;
		Focus = null;
	}

	// ---- Placing ------------------------------------------------------------------------------------

	void SpawnAll()
	{
		Spawned = true;
		var profiles = SumpState.Misfits;
		_first = profiles[0];

		IReadOnlyList<Vector3> given = null;
		try { given = SpotSource?.Invoke()?.ToArray(); }   // a copy: the source list can change under us
		catch ( Exception e ) { Log.Warning( $"Misfit spots unavailable, finding our own: {e.Message}" ); }

		var rng = new Random( SumpState.Seed );
		var centre = Sump.HubSpawn;
		if ( centre == Vector3.Zero && Sump.Player.IsValid() ) centre = Sump.Player.WorldPosition;

		for ( int i = 0; i < profiles.Count; i++ )
		{
			Vector3 spot;
			if ( given is not null && given.Count > 0 )
			{
				spot = given[i % given.Count];
				// More misfits than spots: the extra ones stand a little way off the shared spot.
				if ( i >= given.Count ) spot = FloorNear( spot + Rotation.FromYaw( i * 97f ).Forward * 90f ) ?? spot;
			}
			else spot = RingSpot( centre, i, profiles.Count, rng );

			var go = Sump.Spawn( "Misfit " + profiles[i].Name, spot, GameObject );
			var misfit = go.Components.Create<Misfit>();
			misfit.Profile = profiles[i];
			misfit.Home = spot;
			_mine.Add( misfit );
		}
	}

	/// <summary>A spot on the ring for misfit number <paramref name="index"/>: its own slice of the circle, a seeded distance out, on the floor.</summary>
	Vector3 RingSpot( Vector3 centre, int index, int count, Random rng )
	{
		float slice = 360f / Math.Max( count, 1 );
		var eye = centre + Vector3.Up * 120f;

		for ( int attempt = 0; attempt < 5; attempt++ )
		{
			float angle = index * slice + ((float)rng.NextDouble() - 0.5f) * slice * 0.7f + attempt * 23f;
			float reach = RingMin + (float)rng.NextDouble() * (RingMax - RingMin);
			reach *= 1f - attempt * 0.15f; // each failure tries a little nearer in
			var direction = Rotation.FromYaw( angle ).Forward;

			// Not through a wall: stop short of whatever the line from the hub runs into.
			var wall = Scene.Trace.Ray( eye, eye + direction * reach ).Run();
			if ( wall.Hit ) reach = wall.Distance - 80f;
			if ( reach < 150f ) continue;

			if ( FloorNear( eye + direction * reach, 1600f ) is Vector3 floor ) return floor;
		}

		// No floor found anywhere: stand near the hub and let the misfit sort itself out.
		return centre + Rotation.FromYaw( index * slice ).Forward * 220f;
	}

	/// <summary>The floor below a position, looking down from a little above it.</summary>
	Vector3? FloorNear( Vector3 position, float depth = 300f )
	{
		var tr = Scene.Trace.Ray( position + Vector3.Up * 40f, position + Vector3.Down * depth ).Run();
		return tr.Hit && !tr.StartedSolid ? tr.HitPosition : null;
	}

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

	/// <summary>The misfit most squarely in view that is willing to talk gets the prompt and the Use key.</summary>
	void UpdateFocus()
	{
		Misfit best = null, hint = null;
		if ( Sump.Mode == SumpMode.Hub )
		{
			foreach ( var misfit in Misfit.All )
			{
				if ( !misfit.IsValid() ) continue;
				if ( misfit.WantsTalk && (best is null || misfit.LookDot > best.LookDot) ) best = misfit;
				else if ( misfit.WantsHint && (hint is null || misfit.LookDot > hint.LookDot) ) hint = misfit;
			}
		}

		Focus = best;
		string wanted = best is not null ? best.PromptText : ShowHints && hint is not null ? hint.HintText : null;

		if ( wanted is not null )
		{
			Sump.Prompt = wanted;
			_prompt = wanted;
		}
		else if ( _prompt is not null )
		{
			// Take down only what we put up; somebody else's prompt is theirs.
			if ( Sump.Prompt == _prompt ) Sump.Prompt = null;
			_prompt = null;
		}

		if ( best is not null && Input.Pressed( "Use" ) ) best.Use();
	}
}