Sump/Finale/SumpFinale.Lore.cs

Part of the Sump finale that handles the radio lore. Decodes fragment and orders text through a deterministic static-noise filter based on how many frequencies are open, records which fragments were heard or heard clearly in save notes, and queues reactions from healed misfits plus the Sump's picture line.

using System;
using System.Collections.Generic;
using System.Text;

// The radio lore. Each open frequency plays its misfit's lost orders through static, and under
// the orders something slower: one of the lore fragments (FinaleWriting.Fragments). The static
// eats fewer words for every frequency opened, so listening again after each healing gives more
// of the same sentences and a different fragment.
//
// How the decoding works:
//   - Clarity( open ) is how much gets through, 0 to 1: almost nothing with one frequency open,
//     KeyClarity at SumpState.FinaleNeeds, everything at nine.
//   - Decode( text, clarity, seed ) gives every word a fixed number between 0 and 1 (from the
//     seed and its place in the text). A word comes through once clarity passes its number, so
//     a word that has been heard once is never lost again. Words of a KEY sentence all come
//     through together at KeyClarity. Words that do not come through are dropped to hiss, or
//     half-broken into noise characters when clarity is close.
//   - FragmentFor( position, open ) picks the fragment. With k frequencies open the k dial
//     positions play the next k fragments in PlayOrder, so every new frequency brings a new
//     row; the three key fragments sit in the row for SumpState.FinaleNeeds.
//
// Saved notes: "lore_heard" (one character per fragment: 0 unheard, 1 heard through noise,
// 2 heard clearly), "lore_picture" ("1" once the key sentences have all been heard clearly),
// "finale_answer" (the answer given at the heart: "here", "go" or "stay").
public sealed partial class SumpFinale
{
	/// <summary>The lore fragments, in story order, as plain text.</summary>
	public static IReadOnlyList<string> LoreFragments { get; } = FinaleWriting.CleanFragments();

	/// <summary>How many of the fragments the player has heard at all (through noise counts).</summary>
	public static int FragmentsHeard
	{
		get
		{
			int count = 0;
			foreach ( char c in HeardNote() )
				if ( c != '0' ) count++;
			return count;
		}
	}

	/// <summary>How many have been heard clearly enough to read their key sentence.</summary>
	public static int FragmentsClear
	{
		get
		{
			int count = 0;
			foreach ( char c in HeardNote() )
				if ( c == '2' ) count++;
			return count;
		}
	}

	/// <summary>True once the key sentences have all been heard clearly: the Sump knows what is under it.</summary>
	public static bool PictureTogether => SumpState.GetNote( PictureKey ) == "1";

	/// <summary>The answer given at the heart ("here", "go", "stay"), or empty if it has not been answered.</summary>
	public static string AnswerGiven => SumpState.GetNote( AnswerKey );

	public const string HeardKey = "lore_heard";
	public const string PictureKey = "lore_picture";
	public const string AnswerKey = "finale_answer";

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

	/// <summary>How much gets through with a single frequency open.</summary>
	[Property, Group( "Lore" ), Range( 0f, 1f )] public float FirstClarity { get; set; } = 0.12f;
	/// <summary>How much gets through at SumpState.FinaleNeeds. Key sentences are whole from here up.</summary>
	[Property, Group( "Lore" ), Range( 0f, 1f )] public float KeyClarity { get; set; } = 0.6f;
	/// <summary>The misfit's own orders are this much clearer than what is under them.</summary>
	[Property, Group( "Lore" ), Range( 0f, 1f )] public float OrdersHeadStart { get; set; } = 0.25f;
	/// <summary>Seconds after a new fragment is heard before somebody says something about it.</summary>
	[Property, Group( "Lore" )] public float ReactionDelay { get; set; } = 3.5f;

	static readonly string[] Hiss = { "kssh", "ffff", "...", "tk-tk", "shhh", "krrk" };
	const string NoiseLetters = "~-._";

	Func<int, int, string> _decoder;
	int _reactTo = -1;
	MisfitProfile _reactor;
	float _reactAt;
	bool _picturePending;

	// ---- Hooking up the radio -------------------------------------------------------------------

	/// <summary>Gives the radio its decoder, once the room stands. The radio is new each time the scene starts.</summary>
	void UpdateLore()
	{
		var radio = SumpHub.Radio;
		if ( radio is not null && radio.Built )
		{
			_decoder ??= Heard;
			if ( !ReferenceEquals( radio.Decoder, _decoder ) ) radio.Decoder = _decoder;
		}

		// Somebody nearby has something to say about what was just heard.
		if ( _reactTo >= 0 && RealTime.Now >= _reactAt )
		{
			int fragment = _reactTo;
			_reactTo = -1;
			React( fragment );
		}
	}

	/// <summary>The radio's decoder: (dial position, frequencies open) to the words heard.</summary>
	string Heard( int position, int open )
	{
		var radio = SumpHub.Radio;
		var profile = radio?.MisfitAt( position );
		if ( profile is null ) return "";

		string label = radio.Label( position );
		string name = MisfitVoice.ShortName( profile );
		string orders = MisfitVoice.OrdersLine( profile );

		// After the answer there is no static left to decode.
		if ( SumpState.FinaleDone )
			return FinaleWriting.AfterRadio( AnswerGiven, label, name, orders );

		float clarity = Clarity( open );
		int fragment = FragmentFor( position, open );
		string under = Decode( FinaleWriting.Fragments[fragment], clarity, 0x10AE + fragment * 131 );
		string over = Decode( orders, MathF.Min( clarity + OrdersHeadStart, 1f ), MisfitGenerator.Mix( profile.Seed, 0x0D3A ) );

		NoteHeard( fragment, clarity >= KeyClarity - 0.001f, profile );

		string how = clarity < 0.3f ? "Static. Somewhere in it" : clarity < KeyClarity ? "Static, thinner than it was. In it" : clarity < 0.999f ? "A little static. Through it" : "No static at all now. Clear as a bell";
		string deep = clarity < 0.3f ? "And under that, slower, something that is probably interference" : clarity < KeyClarity ? "And under that, slower, not interference" : "And under that, slow and patient";
		return $"{label}. {how}, {name}'s own voice, years old: \"{over}\" {deep}: \"{under}\"";
	}

	// ---- The decoding itself ----------------------------------------------------------------------

	/// <summary>How much of a transmission gets through with this many frequencies open, 0 to 1.</summary>
	public float Clarity( int open )
	{
		int all = Math.Max( SumpState.MisfitCount, 2 );
		int needs = Math.Clamp( SumpState.FinaleNeeds, 1, all - 1 );
		if ( open <= 0 ) return 0f;
		if ( open >= all ) return 1f;
		if ( open <= needs )
			return needs <= 1 ? KeyClarity : FirstClarity + (KeyClarity - FirstClarity) * (open - 1) / (float)(needs - 1);
		return KeyClarity + (1f - KeyClarity) * (open - needs) / (float)(all - needs);
	}

	/// <summary>Which fragment plays at a dial position with this many frequencies open.</summary>
	public static int FragmentFor( int position, int open )
	{
		var order = PlayOrder;
		int row = Math.Max( open, 1 );
		int start = row * (row - 1) / 2;   // rows of 1, 2, 3... fragments
		return order[(start + Math.Max( position, 0 )) % order.Length];
	}

	static int[] _playOrder;

	/// <summary>
	/// The order fragments are given out in: story order, except that the key fragments are moved
	/// to the row that plays when SumpState.FinaleNeeds frequencies are open.
	/// </summary>
	static int[] PlayOrder
	{
		get
		{
			if ( _playOrder is not null ) return _playOrder;

			var keys = new List<int>();
			var rest = new List<int>();
			for ( int i = 0; i < FinaleWriting.Fragments.Length; i++ )
				(IsKey( i ) ? keys : rest).Add( i );

			int needs = Math.Max( SumpState.FinaleNeeds, 1 );
			int at = Math.Min( needs * (needs - 1) / 2, rest.Count );
			rest.InsertRange( at, keys );
			_playOrder = rest.ToArray();
			return _playOrder;
		}
	}

	static bool IsKey( int fragment ) => FinaleWriting.Fragments[fragment].Contains( '[' );

	/// <summary>
	/// Lets a growing share of a text through the static. The same text and seed always break
	/// the same way, and anything that came through at one clarity comes through at every higher
	/// one. Words inside [square brackets] are a key sentence: they come through whole from
	/// <see cref="KeyClarity"/> up. The brackets themselves are never shown.
	/// </summary>
	public string Decode( string text, float clarity, int seed )
	{
		if ( string.IsNullOrEmpty( text ) ) return "";
		clarity = Math.Clamp( clarity, 0f, 1f );

		var words = text.Split( ' ', StringSplitOptions.RemoveEmptyEntries );
		var result = new StringBuilder();
		bool inKey = false;
		bool lastWasHiss = false;

		for ( int i = 0; i < words.Length; i++ )
		{
			string word = words[i];
			if ( word.Contains( '[' ) ) inKey = true;
			bool key = inKey;
			if ( word.Contains( ']' ) ) inKey = false;
			word = word.Replace( "[", "" ).Replace( "]", "" );
			if ( word.Length == 0 ) continue;

			float chance = Unit( seed, i, 1 );
			bool through = clarity >= 0.999f
				|| (key ? clarity >= KeyClarity - 0.001f || chance < clarity * 0.8f : chance < clarity);

			string shown;
			if ( through ) { shown = word; lastWasHiss = false; }
			else if ( chance < clarity + 0.22f && clarity >= 0.25f )
			{
				// Nearly through: the shape of the word, with holes in it.
				shown = Break( word, seed, i, clarity );
				lastWasHiss = false;
			}
			else
			{
				// Gone. Runs of lost words are one stretch of hiss, not a row of them.
				if ( lastWasHiss ) continue;
				shown = Hiss[(int)(Unit( seed, i, 2 ) * Hiss.Length) % Hiss.Length];
				lastWasHiss = true;
			}

			if ( result.Length > 0 ) result.Append( ' ' );
			result.Append( shown );
		}
		return result.ToString();
	}

	/// <summary>A word with some of its letters lost to noise.</summary>
	static string Break( string word, int seed, int index, float clarity )
	{
		var broken = new StringBuilder( word.Length );
		for ( int c = 0; c < word.Length; c++ )
		{
			char letter = word[c];
			float chance = Unit( seed, index * 37 + c, 3 );
			if ( !char.IsLetter( letter ) || chance < clarity + 0.15f ) broken.Append( letter );
			else broken.Append( NoiseLetters[(int)(chance * 97f) % NoiseLetters.Length] );
		}
		return broken.ToString();
	}

	/// <summary>A fixed number from 0 up to (not including) 1 for three whole numbers.</summary>
	static float Unit( int a, int b, int c ) => (MisfitGenerator.Mix( a, b, c ) & 0xFFFF) / 65536f;

	// ---- Remembering what was heard ---------------------------------------------------------------

	static string HeardNote()
	{
		string note = SumpState.GetNote( HeardKey );
		int count = FinaleWriting.Fragments.Length;
		if ( note.Length == count ) return note;
		return note.Length > count ? note.Substring( 0, count ) : note.PadRight( count, '0' );
	}

	/// <summary>Marks a fragment heard (clearly or through noise) and lines up whatever follows from that.</summary>
	void NoteHeard( int fragment, bool clear, MisfitProfile onDial )
	{
		var note = HeardNote().ToCharArray();
		char was = note[fragment];
		char now = clear ? '2' : '1';
		if ( was >= now ) return;

		note[fragment] = now;
		SumpState.SetNote( HeardKey, new string( note ) );

		// The first hearing gets a reaction; a clearer one of a key sentence gets one too.
		if ( was == '0' || (clear && IsKey( fragment )) )
		{
			_reactTo = fragment;
			_reactor = onDial;
			_reactAt = RealTime.Now + ReactionDelay;
		}

		if ( !PictureTogether && AllKeysClear( note ) )
		{
			SumpState.SetNote( PictureKey, "1" );
			_picturePending = true;
		}
	}

	static bool AllKeysClear( char[] note )
	{
		for ( int i = 0; i < note.Length; i++ )
			if ( IsKey( i ) && note[i] != '2' ) return false;
		return true;
	}

	/// <summary>A healed misfit says what it makes of a fragment; and once the picture is whole, the Sump says so.</summary>
	void React( int fragment )
	{
		if ( Sump.Mode != SumpMode.Hub ) { _picturePending = false; return; }
		var at = Sump.Player.IsValid() ? Sump.Player.WorldPosition : WorldPosition;

		// Whoever's frequency it was speaks if they are healed, otherwise anybody who is.
		var speaker = _reactor is not null && _reactor.Healed ? _reactor : null;
		if ( speaker is null || Game.Random.Float( 0f, 1f ) < 0.4f )
		{
			var healed = new List<MisfitProfile>( SumpState.Healed );
			if ( healed.Count > 0 ) speaker = healed[Game.Random.Next( healed.Count )];
		}

		if ( speaker is not null && fragment >= 0 && fragment < FinaleWriting.Reactions.Length )
		{
			string line = FinaleWriting.Fill( FinaleWriting.Reactions[fragment], speaker );
			Sump.Say( MisfitVoice.ShortName( speaker ), MisfitVoice.Speak( speaker, line ), 7f );
			Sump.Sfx( "lore_fragment", at, 0.6f );
		}

		if ( _picturePending )
		{
			_picturePending = false;
			Sump.Say( "THE SUMP", FinaleWriting.PictureLine, 10f );
			Sump.Objective = FinaleWriting.PictureObjective;
			Sump.Sfx( "lore_picture", at, 0.9f );
		}
	}
}