Sump/Hub/SumpHub.cs

The root component for the Sump hub, a partial class that builds the hub structures at runtime under one spawned root. It reads the healed-misfit order from the save, grows shrines, the radio room, the market and the way down as more misfits are healed, animates new pieces rising, flickers the lights, and runs the nearest-spot prompt and Use handling for hub objects.

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

/// <summary>
/// THE HUB THAT BUILDS ITSELF. The Sump starts as bare rock, junk and frightened things hiding.
/// Every healed misfit makes it more of a home:
///
///   every one   a shrine to the human object it clings to (HubShrines.cs, HubEffigy.cs)
///   1 healed    the radio room, and one more frequency for each after (HubRadio.cs, SumpRadio.cs)
///   2 healed    the junk market, with a stall for each of them (HubMarket.cs)
///   always      the chained way down, which loosens with each and opens at SumpState.FinaleNeeds
///               (HubWayDown.cs), a board of "missing" posters, a counter and lamps (HubLife.cs)
///
/// Everything is tinted boxes and balls built at runtime under one unsaved root, so hiding the
/// hub (while the player is away in a flashback or the finale) is switching that root off. What
/// was already earned is simply there when the scene loads; what is earned while playing rises
/// piece by piece once the player is back to see it.
///
/// For other modules: <see cref="Radio"/>, <see cref="StallFor"/>, <see cref="ShrineFor"/>,
/// <see cref="RadioSpotFor"/>. The hub never moves a misfit itself: a healed misfit goes to
/// whichever of the three is nearest while the player is close by (Misfit.ChoosePost).
/// </summary>
[Title( "Sump Hub" ), Category( "Sump" ), Icon( "cottage" )]
public sealed partial class SumpHub : Component
{
	public static SumpHub Current { get; private set; }

	/// <summary>The radio room's set. Never null.</summary>
	public static SumpRadio Radio { get; private set; } = new();

	// ---- Tuning -------------------------------------------------------------------------------------

	/// <summary>Healed misfits needed before the radio room is put up.</summary>
	[Property, Group( "Growth" )] public int RadioAt { get; set; } = 1;
	/// <summary>Healed misfits needed before the market opens.</summary>
	[Property, Group( "Growth" )] public int MarketAt { get; set; } = 2;
	/// <summary>Seconds a new structure takes to assemble itself.</summary>
	[Property, Group( "Growth" )] public float RiseSeconds { get; set; } = 3.5f;
	/// <summary>Seconds after the player is back in the hub before new things start to rise.</summary>
	[Property, Group( "Growth" )] public float RevealDelay { get; set; } = 1.6f;

	/// <summary>Multiplies every hub light.</summary>
	[Property, Group( "Lights" )] public float LightBrightness { get; set; } = 0.8f;
	[Property, Group( "Lights" )] public float CandleRadius { get; set; } = 300f;
	[Property, Group( "Lights" )] public float LampRadius { get; set; } = 260f;
	/// <summary>At most this many path lamps carry a real light; the rest only look lit.</summary>
	[Property, Group( "Lights" )] public int MaxPathLights { get; set; } = 8;

	/// <summary>Seconds between two uses of anything in the hub.</summary>
	[Property, Group( "Use" )] public float UseCooldown { get; set; } = 1.2f;
	/// <summary>How much calm sitting at a shrine gives back (0 to 1).</summary>
	[Property, Group( "Use" ), Range( 0f, 1f )] public float ShrineSoothe { get; set; } = 0.35f;
	/// <summary>Seconds between repeats of what the radio is saying while the player listens.</summary>
	[Property, Group( "Use" )] public float RadioRepeat { get; set; } = 9f;

	// ---- State --------------------------------------------------------------------------------------

	/// <summary>Somewhere the player can stand to be offered something.</summary>
	sealed class HubSpot
	{
		public GameObject Owner;
		public Vector3 Position;
		public float Radius = 110f;
		/// <summary>The prompt to show, or null for none right now.</summary>
		public Func<string> Prompt;
		/// <summary>What Use does; null if the prompt is only a hint.</summary>
		public Action Use;
	}

	GameObject _root;
	/// <summary>Healed misfits in the order they were healed (saved), which is also the dial order.</summary>
	readonly List<int> _order = new();
	int _grownFor = -1;
	bool _pending;
	bool _wasVisible;
	TimeSince _sinceVisible;
	TimeSince _sinceUse;
	TimeSince _sinceCheck;

	readonly List<HubSpot> _spots = new();
	readonly List<HubRise> _rises = new();
	readonly List<HubFlame> _flames = new();
	string _prompt;
	string _objective;
	SumpMode _lastMode = SumpMode.Arrival;

	// ---- For other modules --------------------------------------------------------------------------

	/// <summary>Where a healed misfit stands to keep its market stall, or null if it has none (yet).</summary>
	public static Vector3? StallFor( MisfitProfile profile )
	{
		var hub = Current;
		if ( !hub.IsValid() || profile is null || !hub._stalls.TryGetValue( profile.Index, out var stall ) ) return null;
		return stall.Keeper;
	}

	/// <summary>Where a healed misfit's shrine stands (the mat in front of it), or null.</summary>
	public static Vector3? ShrineFor( MisfitProfile profile )
	{
		var hub = Current;
		if ( !hub.IsValid() || profile is null || !hub._shrines.TryGetValue( profile.Index, out var shrine ) ) return null;
		return shrine.Seat;
	}

	/// <summary>
	/// Where a misfit stands to listen at the radio room: its own place in a loose half ring in
	/// front of the set, so several can listen at once. Null until the room exists.
	/// </summary>
	public static Vector3? RadioSpotFor( MisfitProfile profile )
	{
		var hub = Current;
		if ( !hub.IsValid() || !Radio.Built ) return null;
		int place = profile is null ? 0 : profile.Index;
		float yaw = hub._radioYaw - 70f + (place % 5) * 35f;
		return HubKit.OnFloor( HubKit.Around( Radio.ListeningSpot, yaw, 60f + (place / 5) * 55f ) );
	}

	// ---- Life cycle ---------------------------------------------------------------------------------

	protected override void OnAwake()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
		Radio = new SumpRadio();
	}

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
		SumpState.MisfitHealed += OnMisfitHealed;
		Radio.TunedChanged += OnTuned;
	}

	protected override void OnDestroy()
	{
		SumpState.MisfitHealed -= OnMisfitHealed;
		StopListening();
		DropPrompt();
		if ( Current == this ) Current = null;
	}

	void OnMisfitHealed( MisfitProfile profile )
	{
		if ( profile is not null && !_order.Contains( profile.Index ) ) _order.Add( profile.Index );
		_pending = true;
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor || !SumpCavern.Ready ) return;

		// Away in a flashback or the finale: the whole hub is switched off with the cavern.
		bool visible = SumpCavern.HubVisible;
		if ( visible != _wasVisible )
		{
			_wasVisible = visible;
			_sinceVisible = 0;
			if ( _root.IsValid() ) _root.Enabled = visible;
			if ( !visible ) StopListening();
		}
		if ( !visible )
		{
			DropPrompt();
			return;
		}

		if ( !_root.IsValid() )
		{
			_root = Sump.Spawn( "Sump Hub", SumpCavern.Centre, GameObject );
			_order.Clear();
			Grow( false );
		}

		// A heal is normally heard through the event; this also catches a reset, or one we missed.
		if ( _sinceCheck > 1f )
		{
			_sinceCheck = 0;
			int healed = SumpState.HealedCount;
			if ( healed < _grownFor ) { TearDown(); return; }
			if ( healed != _grownFor ) _pending = true;
		}

		if ( _pending && Sump.Mode == SumpMode.Hub && _sinceVisible > RevealDelay && Sump.Fade < 0.5f )
		{
			_pending = false;
			Grow( true );
		}

		UpdateRises();
		UpdateFlames();
		UpdateWayDown();
		UpdateObjective();
		if ( !UpdateListening() ) UpdateFocus();
	}

	/// <summary>Throws the whole hub away (the Sump was reset under us); it is rebuilt next frame.</summary>
	void TearDown()
	{
		StopListening();
		DropPrompt();
		if ( _root.IsValid() ) _root.Destroy();
		_root = null;
		_order.Clear();
		_grownFor = -1;
		_pending = false;
		_spots.Clear();
		_rises.Clear();
		_flames.Clear();
		_sitesPicked = false;
		ForgetShrines();
		ForgetMarket();
		ForgetRadio();
		ForgetWayDown();
		ForgetLife();
	}

	// ---- Growing ------------------------------------------------------------------------------------

	/// <summary>
	/// Builds whatever the healed count has earned and does not exist yet. With
	/// <paramref name="animate"/> the new structures assemble themselves; without, they are just there.
	/// </summary>
	void Grow( bool animate )
	{
		SyncOrder();
		int healed = _order.Count;
		int before = _grownFor;
		bool openedNow = healed >= SumpState.FinaleNeeds && before < SumpState.FinaleNeeds;

		PickFixedSites();

		foreach ( int index in _order )
			EnsureShrine( SumpState.Misfits[index], animate );

		if ( healed >= RadioAt && healed > 0 ) EnsureRadio( animate );
		Radio.Sync( _order );
		RefreshDial();

		if ( healed >= MarketAt && healed > 0 )
		{
			EnsureMarket( animate );
			foreach ( int index in _order )
				EnsureStall( SumpState.Misfits[index], animate );
		}

		EnsureWayDown();
		SetWayDown( healed, animate );
		RebuildBoard( animate );
		EnsureLamps( healed, animate );

		_grownFor = healed;

		if ( !animate || healed <= Math.Max( before, 0 ) ) return;

		// Say what has changed, newest and biggest first, without burying the player in lines.
		var newest = SumpState.Misfits[_order[healed - 1]];
		string name = MisfitVoice.ShortName( newest );
		var thing = MisfitTables.FindThing( newest.ClungObject );
		Sump.Say( "THE SUMP", $"{name} is building a shrine to {thing?.With ?? "the one thing it kept"}.", 6f );
		if ( before < RadioAt && healed >= RadioAt ) Sump.Say( "THE SUMP", "Somebody has dragged a dish up out of the junk. They are listening for their orders again.", 6f );
		else Sump.Say( "THE SUMP", $"The radio has found another frequency: {Radio.Label( Radio.Frequencies.Count - 1 )}.", 6f );
		if ( before < MarketAt && healed >= MarketAt ) Sump.Say( "THE SUMP", "A market is opening. Nothing in it is anything anyone needs. Half of it is damp.", 6f );
		if ( openedNow ) Sump.Say( "THE SUMP", "The last chain is off the way down.", 7f );
		Sump.Sfx( "hub_grow", Sump.HubSpawn, 0.8f );
	}

	/// <summary>Brings the healed order in line with the save: reads it, drops the unhealed, adds the missing, writes it back.</summary>
	void SyncOrder()
	{
		var misfits = SumpState.Misfits;
		if ( _order.Count == 0 ) _order.AddRange( HubKit.ReadInts( SumpState.GetNote( "hub_order" ) ) );
		_order.RemoveAll( index => index < 0 || index >= misfits.Count || !misfits[index].Healed );
		foreach ( var profile in misfits )
			if ( profile.Healed && !_order.Contains( profile.Index ) && profile.Index >= 0 && profile.Index < misfits.Count ) _order.Add( profile.Index );
		if ( _order.Count > 0 ) SumpState.SetNote( "hub_order", string.Join( ",", _order ) );
	}

	/// <summary>Registers a finished structure: it rises if asked, and its lights join the flicker.</summary>
	void Finish( HubBuilder built, bool animate, float seconds = 0f )
	{
		if ( animate ) _rises.Add( new HubRise( built.Root, seconds > 0f ? seconds : RiseSeconds ) );
	}

	HubFlame AddFlame( PointLight light, Color colour, float depth = 0.25f, float speed = 7f )
	{
		var flame = new HubFlame { Light = light, Base = colour, Depth = depth, Speed = speed, Phase = _flames.Count * 1.7f };
		_flames.Add( flame );
		light.LightColor = HubKit.Shade( colour, LightBrightness );
		return flame;
	}

	void AddSpot( GameObject owner, Vector3 position, float radius, Func<string> prompt, Action use )
		=> _spots.Add( new HubSpot { Owner = owner, Position = position, Radius = radius, Prompt = prompt, Use = use } );

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

	void UpdateRises()
	{
		for ( int i = _rises.Count - 1; i >= 0; i-- )
		{
			_rises[i].Update( Time.Delta );
			if ( !_rises[i].Done ) continue;
			_rises.RemoveAt( i );
			Sump.Sfx( "hub_build_done", Sump.HubSpawn, 0.5f );
		}
	}

	void UpdateFlames()
	{
		float now = Time.Now;
		for ( int i = _flames.Count - 1; i >= 0; i-- )
		{
			var flame = _flames[i];
			if ( !flame.Light.IsValid() ) { _flames.RemoveAt( i ); continue; }

			// Two sines out of step read as a flame; one reads as a machine.
			float flicker = 0.5f + 0.3f * MathF.Sin( now * flame.Speed + flame.Phase ) + 0.2f * MathF.Sin( now * flame.Speed * 2.7f + flame.Phase * 3f );
			float level = (1f - flame.Depth * flicker + flame.Boost * 1.5f) * flame.Level * LightBrightness;
			flame.Boost = MathF.Max( flame.Boost - Time.Delta * 0.6f, 0f );
			flame.Light.LightColor = HubKit.Shade( flame.Base, MathF.Max( level, 0f ) );
		}
	}

	/// <summary>Keeps the hub's goal in the top corner current, without treading on anybody else's.</summary>
	void UpdateObjective()
	{
		bool entered = Sump.Mode == SumpMode.Hub && _lastMode != SumpMode.Hub;
		_lastMode = Sump.Mode;
		if ( Sump.Mode != SumpMode.Hub ) return;

		int healed = SumpState.HealedCount;
		int more = SumpState.FinaleNeeds - healed;
		string wanted = healed == 0 ? "Find the ones who hide here"
			: more > 0 ? $"Help {more} more to open the way down"
			: "The way down is open";

		// Ours to change if we set it, if nobody has, or if the hub has just been come back to.
		bool ours = entered || string.IsNullOrEmpty( Sump.Objective ) || Sump.Objective == _objective || Sump.Objective == "Find the ones who hide here";
		if ( ours && Sump.Objective != wanted ) Sump.Objective = wanted;
		if ( ours ) _objective = wanted;
	}

	/// <summary>The nearest thing the player is standing at gets the prompt and the Use key.</summary>
	void UpdateFocus()
	{
		HubSpot best = null;
		string wanted = null;
		var player = Sump.Player;

		if ( Sump.Mode == SumpMode.Hub && player.IsValid() && !player.InputLocked && !MisfitWantsTalk() )
		{
			var feet = player.WorldPosition;
			float bestDistance = float.MaxValue;
			foreach ( var spot in _spots )
			{
				if ( !spot.Owner.IsValid() ) continue;
				var to = spot.Position - feet;
				float distance = to.WithZ( 0f ).Length;
				if ( distance > spot.Radius || MathF.Abs( to.z ) > 160f || distance >= bestDistance ) continue;
				string prompt = spot.Prompt?.Invoke();
				if ( string.IsNullOrEmpty( prompt ) ) continue;
				best = spot;
				wanted = prompt;
				bestDistance = distance;
			}
		}

		ShowPrompt( wanted );

		if ( best?.Use is not null && _sinceUse > UseCooldown && Input.Pressed( "Use" ) )
		{
			_sinceUse = 0;
			best.Use();
		}
	}

	/// <summary>A misfit that is ready to talk outranks the furniture.</summary>
	static bool MisfitWantsTalk()
	{
		foreach ( var misfit in Misfit.All )
			if ( misfit.IsValid() && misfit.WantsTalk ) return true;
		return false;
	}

	void ShowPrompt( string wanted )
	{
		if ( wanted is not null )
		{
			Sump.Prompt = wanted;
			_prompt = wanted;
		}
		else DropPrompt();
	}

	/// <summary>Takes down only what we put up; somebody else's prompt is theirs.</summary>
	void DropPrompt()
	{
		if ( _prompt is null ) return;
		if ( Sump.Prompt == _prompt ) Sump.Prompt = null;
		_prompt = null;
	}

	// ---- Places -------------------------------------------------------------------------------------

	int _radioSite = -1, _marketSite = -1;
	Vector3 _radioAt, _marketAt;
	bool _sitesPicked;

	/// <summary>
	/// The radio room and the market each take one of the cavern's outer build sites, on opposite
	/// sides of the landing, chosen from the Sump's seed. Shrines share out the rest.
	/// </summary>
	void PickFixedSites()
	{
		if ( _sitesPicked ) return;
		_sitesPicked = true;

		var sites = SumpCavern.BuildSites;
		int roll = MisfitGenerator.Mix( SumpState.Seed, 0x4AD10 );
		if ( sites.Count >= 14 )
		{
			// Sites 6 to 13 are the outer ring, in order round the landing.
			_radioSite = 6 + roll % 8;
			_marketSite = 6 + (roll % 8 + 4) % 8;
		}
		else if ( sites.Count >= 2 )
		{
			_radioSite = sites.Count - 1;
			_marketSite = sites.Count - 2;
		}

		float turn = roll % 360;
		_radioAt = _radioSite >= 0 ? sites[_radioSite] : HubKit.OnFloor( HubKit.Around( Sump.HubSpawn, turn, 900f ) );
		_marketAt = _marketSite >= 0 ? sites[_marketSite] : HubKit.OnFloor( HubKit.Around( Sump.HubSpawn, turn + 180f, 900f ) );
	}

	/// <summary>Yaw that turns a structure's front toward the landing place.</summary>
	static float FaceLanding( Vector3 from ) => HubKit.YawToward( from, Sump.HubSpawn );
}