Sump/Presentation/SumpHud.razor

The Sump's main HUD, a Razor PanelComponent. Refresh() gathers state from Sump, SumpState, FlashbackRunner, SumpFinale, MisfitSpawner, Patchwork and SumpHub.Radio into row lists, then BuildHash returns a hash of everything drawn so the panel only rebuilds when a value changes. Draws crosshair, prompt, objective meters, memory/finale cards, healed count, dossier, calm bar, patchwork grafts, radio dial, controls card, fade/white overlays, card text and subtitles.

@using System;
@using System.Collections.Generic;
@using System.Linq;
@using Sandbox;
@using Sandbox.UI;
@inherits PanelComponent
@namespace SumpUi

@*
	The Sump's whole HUD, drawn from the Sump noticeboard and a few things the modules publish.
	SumpPresentation puts it on the Sump object next to a ScreenPanel. Nothing calls it: every
	frame BuildHash looks at what it would draw, and the panel is rebuilt only when that changed.
	Sizes are in panel pixels (the screen is 1080 high).
*@

<root>
	@if ( ShowWorldHud )
	{
		<div class="crosshair"></div>

		@if ( !string.IsNullOrEmpty( Prompt ) )
		{
			<div class="prompt"><div class="text">@Prompt</div></div>
		}
	}

	@if ( ShowWorldHud || Sump.Mode == SumpMode.Arrival )
	{
		<!-- Top left: the goal, with any clock or meter packed into it on lines of their own. -->
		<div class="topleft">
			@if ( ObjectiveRows.Count > 0 )
			{
				<div class="objective scrap">
					@foreach ( var row in ObjectiveRows )
					{
						@if ( row.Percent >= 0 )
						{
							<div class="meterrow">
								<div class="label">@row.Text</div>
								<div class="bar"><div class="fill" style="width: @(row.Percent)%"></div></div>
							</div>
						}
						else
						{
							<div class="@(row.First ? "line first" : "line")">@row.Text</div>
						}
					}
				</div>
			}

			@if ( Memory is not null )
			{
				<div class="memory scrap">
					<div class="genre">@Memory.GenreTitle</div>
					@if ( !string.IsNullOrEmpty( Memory.Place ) )
					{
						<div class="place">@Memory.Place</div>
					}
					<div class="rewinds">@RewindsText</div>
					@if ( LeavePercent > 0 )
					{
						<div class="leave">
							<div class="label">letting go...</div>
							<div class="bar"><div class="fill" style="width: @(LeavePercent)%"></div></div>
						</div>
					}
					else
					{
						<div class="hint">hold R to let go of the memory</div>
					}
				</div>
			}

			@if ( Finale is not null )
			{
				<!-- The descent: where you are, how much you do not belong, the way out, the three answers. -->
				<div class="finale scrap">
					<div class="genre">THE WAY DOWN</div>
					@if ( !string.IsNullOrEmpty( FinaleTitle ) )
					{
						<div class="line">@FinaleTitle</div>
					}
					@if ( ForeignPercent >= 0 )
					{
						<div class="meterlabel">YOU DO NOT BELONG</div>
						<div class="bar"><div class="fill" style="width: @(ForeignPercent)%"></div></div>
						<div class="hint">running and fighting raise it. stillness lowers it.</div>
					}
					@if ( AnswerRows.Count > 0 )
					{
						<div class="meterlabel">THREE ANSWERS</div>
						@foreach ( var row in AnswerRows )
						{
							<div class="answer">@row.Text</div>
							<div class="hint">@row.Extra</div>
						}
						<div class="hint">walk to the one you mean, then E</div>
					}
					@if ( FinaleLeavePercent > 0 )
					{
						<div class="leave">
							<div class="label">turning back...</div>
							<div class="bar"><div class="fill" style="width: @(FinaleLeavePercent)%"></div></div>
						</div>
					}
					else if ( !FinaleOver )
					{
						<div class="hint">hold R to turn back to the Sump</div>
					}
				</div>
			}
		</div>

		<!-- Top right: how many are healed, and who you are looking at. -->
		<div class="topright">
			<div class="healed scrap">
				<div class="count">healed @SumpState.HealedCount / @SumpState.MisfitCount</div>
				@if ( !string.IsNullOrEmpty( HealedNote ) )
				{
					<div class="note">@HealedNote</div>
				}
			</div>

			@if ( DossierRows.Count > 0 )
			{
				<div class="dossier scrap">
					@foreach ( var row in DossierRows )
					{
						<div class="@(row.First ? "name" : "fact")" style="@(row.First ? DossierNameStyle : "")">@row.Text</div>
					}
				</div>
			}
		</div>

		<!-- Bottom left: composure, and what the player is afraid of. -->
		<div class="@CalmClass">
			<div class="caption">@CalmCaption</div>
			<div class="bar"><div class="fill" style="width: @(CalmPercent)%"></div></div>
			<div class="fears">@FearsText</div>
		</div>

		<!-- Bottom right: the patchwork body, one graft per line with its key. -->
		@if ( PatchRows.Count > 0 || !string.IsNullOrEmpty( PatchNotice ) )
		{
			<div class="patchwork">
				@if ( !string.IsNullOrEmpty( PatchNotice ) )
				{
					<div class="notice scrap">@PatchNotice</div>
				}
				@if ( PatchRows.Count > 0 )
				{
					<div class="grafts scrap">
						@foreach ( var row in PatchRows )
						{
							<div class="@(row.First ? "head" : row.Percent == 1 ? "ability" : "graft")">@row.Text</div>
						}
					</div>
				}
			</div>
		}

		@if ( RadioOn )
		{
			<!-- The radio: every open frequency on the dial, the tuned one lit. -->
			<div class="radio scrap">
				<div class="head">THE SET</div>
				@if ( RadioStations.Count == 0 )
				{
					<div class="dead">Static on every channel. Nobody has opened a frequency yet. The static is doing its best.</div>
				}
				else
				{
					<div class="dial">
						@foreach ( var station in RadioStations )
						{
							<div class="@(station.First ? "station tuned" : "station")">
								<div class="freq">@station.Text</div>
								<div class="who" style="@station.Style">@station.Extra</div>
							</div>
						}
					</div>
				}
				@if ( !string.IsNullOrEmpty( RadioLore ) )
				{
					<div class="lore">@RadioLore</div>
				}
				<div class="hint">A / D turn the dial      E take the headphones off</div>
			</div>
		}

		@if ( ShowControls )
		{
			<div class="controls scrap">
				<div class="head">HOW TO GET BY DOWN HERE</div>
				@foreach ( var row in ControlRows )
				{
					<div class="row"><div class="key">@row.Text</div><div class="does">@row.Extra</div></div>
				}
			</div>
		}
	}

	<div class="fade" style="opacity: @FadeOpacity"></div>
	<div class="white" style="opacity: @WhiteOpacity"></div>

	@if ( !string.IsNullOrEmpty( Sump.CardTitle ) || !string.IsNullOrEmpty( Sump.CardLine ) )
	{
		<div class="card">
			<div class="title">@Sump.CardTitle</div>
			<div class="rule"></div>
			@foreach ( var line in CardLines )
			{
				<div class="line">@line</div>
			}
		</div>
	}

	@if ( Subtitles.Count > 0 )
	{
		<div class="subtitles">
			@foreach ( var line in Subtitles )
			{
				<div class="@line.Class">
					@if ( !string.IsNullOrEmpty( line.Text ) )
					{
						<div class="speaker" style="@line.Style">@line.Text</div>
					}
					<div class="text">@line.Extra</div>
				</div>
			}
		</div>
	}
</root>

@code
{
	/// <summary>Seconds the controls card stays up the first time the player stands in the hub.</summary>
	[Property] public float ControlsSeconds { get; set; } = 16f;
	/// <summary>Show the controls card on every visit, not only the first of a save.</summary>
	[Property] public bool AlwaysShowControls { get; set; }
	/// <summary>Seconds a misfit's dossier stays up after the player stops looking at it.</summary>
	[Property] public float DossierHoldSeconds { get; set; } = 3f;
	/// <summary>Calm under which the meter pulses.</summary>
	[Property, Range( 0f, 1f )] public float LowCalm { get; set; } = 0.3f;
	/// <summary>How many spoken lines are shown at once.</summary>
	[Property] public int SubtitleLines { get; set; } = 3;

	/// <summary>One row of anything: text, a second text, a style, a number, and whether it is the first or lit one.</summary>
	public struct Row
	{
		public string Text, Extra, Style, Class;
		public int Percent;
		public bool First;
	}

	static readonly Row[] ControlRows =
	{
		new() { Text = "MOUSE", Extra = "look" },
		new() { Text = "W A S D", Extra = "move      SHIFT sprint      SPACE push off" },
		new() { Text = "E", Extra = "use, talk, listen, sit down heavily" },
		new() { Text = "1 - 9", Extra = "what your grafts can do (other people's bits)" },
		new() { Text = "LEFT CLICK", Extra = "bite      RIGHT CLICK (hold) reach and grab" },
		new() { Text = "Q", Extra = "sense pulse (it is not a burp)" },
		new() { Text = "R (hold)", Extra = "inside a memory: let go of it" },
	};

	// ---- What is drawn. All of it is worked out once per frame in Refresh, from BuildHash. -------

	bool ShowWorldHud;
	string Prompt;
	List<Row> ObjectiveRows = new();
	FlashbackRunner Memory;
	string RewindsText = "";
	int LeavePercent;
	SumpFinale Finale;
	string FinaleTitle = "";
	int ForeignPercent = -1;
	int FinaleLeavePercent;
	bool FinaleOver;
	List<Row> AnswerRows = new();
	string HealedNote = "";
	List<Row> DossierRows = new();
	string DossierNameStyle = "";
	string CalmClass = "calm";
	string CalmCaption = "";
	int CalmPercent = 100;
	string FearsText = "";
	List<Row> PatchRows = new();
	string PatchNotice = "";
	bool RadioOn;
	List<Row> RadioStations = new();
	string RadioLore = "";
	bool ShowControls;
	string FadeOpacity = "0";
	string WhiteOpacity = "0";
	List<string> CardLines = new();
	List<Row> Subtitles = new();

	MisfitProfile _dossier;
	float _dossierUntil;
	float _controlsUntil = -1f;
	bool _controlsDone;
	MisfitSpawner _spawner;
	PlayerPhobia _phobia;
	int _hash;
	bool _warned;

	/// <summary>The misfit a speaker's name belongs to (its full name or its short one), or null.</summary>
	public static MisfitProfile FindSpeaker( string speaker )
	{
		if ( string.IsNullOrEmpty( speaker ) ) return null;
		try
		{
			foreach ( var profile in SumpState.Misfits )
			{
				if ( profile is null ) continue;
				if ( profile.Name == speaker || MisfitVoice.ShortName( profile ) == speaker ) return profile;
			}
		}
		catch ( Exception ) { }
		return null;
	}

	/// <summary>A misfit's colour, lifted until it can be read on a dark panel.</summary>
	static string NameColor( MisfitProfile profile )
	{
		if ( profile is null ) return "";
		var c = profile.Primary.WithAlpha( 1f );
		float luminance = c.r * 0.3f + c.g * 0.59f + c.b * 0.11f;
		if ( luminance < 0.55f ) c = Color.Lerp( c, Color.White, Math.Clamp( (0.55f - luminance) * 1.4f, 0f, 0.8f ) );
		int r = (int)Math.Clamp( c.r * 255f, 0f, 255f ), g = (int)Math.Clamp( c.g * 255f, 0f, 255f ), b = (int)Math.Clamp( c.b * 255f, 0f, 255f );
		return $"color: rgb( {r}, {g}, {b} );";
	}

	static string FearName( Phobia fear ) => fear switch
	{
		Phobia.Crowds => "crowds",
		Phobia.Weight => "being held down",
		_ => "light",
	};

	/// <summary>0 to 1 as text for a style, in hundredths ("0.37"), whatever the machine's locale.</summary>
	static string Opacity( float value )
	{
		int hundredths = (int)MathF.Round( Math.Clamp( value, 0f, 1f ) * 100f );
		return hundredths >= 100 ? "1" : $"0.{hundredths:00}";
	}

	/// <summary>Works out everything the panel shows and returns a number that changes when any of it does.</summary>
	int Refresh()
	{
		var hash = new HashCode();
		var mode = Sump.Mode;
		float now = RealTime.Now;
		var presentation = SumpPresentation.Current;

		bool black = Sump.Fade > 0.97f;
		ShowWorldHud = !black && (mode == SumpMode.Hub || mode == SumpMode.Flashback || mode == SumpMode.Finale);
		hash.Add( ShowWorldHud ); hash.Add( (int)mode );

		// ---- Prompt ----
		Prompt = presentation.IsValid() ? presentation.ShownPrompt : Sump.Prompt;
		hash.Add( Prompt );

		// ---- Objective ----
		ObjectiveRows.Clear();
		string objective = Sump.Objective ?? "";
		hash.Add( objective );
		bool first = true;
		foreach ( var raw in objective.Replace( "   |   ", "\n" ).Split( '\n' ) )
		{
			string line = raw.Trim();
			if ( line.Length == 0 ) continue;
			var row = new Row { Text = line, Percent = -1, First = first };
			// "LABEL [####------]" is a meter: draw it as one.
			int open = line.LastIndexOf( '[' );
			if ( open >= 0 && line.EndsWith( "]" ) && line.Length - open > 3 )
			{
				string inside = line.Substring( open + 1, line.Length - open - 2 );
				if ( inside.All( c => c == '#' || c == '-' ) )
				{
					row.Text = line.Substring( 0, open ).Trim();
					row.Percent = inside.Count( c => c == '#' ) * 100 / inside.Length;
				}
			}
			ObjectiveRows.Add( row );
			first = false;
		}

		// ---- A memory in progress ----
		var runner = FlashbackRunner.Current;
		Memory = runner.IsValid() && runner.Playing ? runner : null;
		LeavePercent = 0;
		RewindsText = "";
		if ( Memory is not null )
		{
			LeavePercent = (int)(Math.Clamp( Memory.LeaveProgress, 0f, 1f ) * 20f) * 5;
			int left = Memory.RewindsLeft;
			RewindsText = left <= 0 ? "it will not rewind again" : left == 1 ? "it will rewind once more" : $"it will rewind {left} more times";
			hash.Add( Memory.GenreTitle ); hash.Add( Memory.Place ); hash.Add( left ); hash.Add( LeavePercent );
		}
		hash.Add( Memory is not null );

		// ---- The finale ----
		Finale = SumpPresentation.Finale;
		FinaleTitle = "";
		ForeignPercent = -1;
		FinaleLeavePercent = 0;
		FinaleOver = false;
		AnswerRows.Clear();
		if ( Finale is not null )
		{
			FinaleTitle = Finale.LayerTitle ?? "";
			FinaleOver = Finale.Ended || !string.IsNullOrEmpty( Finale.Answer );
			// Not belonging only means anything in the deep layers.
			if ( Finale.Layer == 2 && !FinaleOver ) ForeignPercent = (int)MathF.Round( Math.Clamp( Finale.Foreign, 0f, 1f ) * 50f ) * 2;
			FinaleLeavePercent = (int)(Math.Clamp( Finale.LeaveProgress, 0f, 1f ) * 20f) * 5;
			// The heart offers its answers as three pillars; its prompt says when they are up.
			bool choosing = Finale.Layer == 3 && !FinaleOver && Prompt is not null
				&& (Prompt.StartsWith( "Three answers" ) || Prompt.StartsWith( "E  answer:" ));
			if ( choosing )
				foreach ( var answer in FinaleWriting.Answers )
					AnswerRows.Add( new Row { Text = $"\"{answer.Words}\"", Extra = answer.Hint } );
			hash.Add( FinaleTitle ); hash.Add( ForeignPercent ); hash.Add( FinaleLeavePercent ); hash.Add( FinaleOver ); hash.Add( AnswerRows.Count );
		}
		hash.Add( Finale is not null );

		// ---- Healed ----
		HealedNote = SumpState.FinaleDone ? "the heart has been answered"
			: SumpState.FinaleUnlocked ? "the way down is open"
			: $"the way down opens at {SumpState.FinaleNeeds}";
		hash.Add( SumpState.HealedCount ); hash.Add( HealedNote );

		// ---- Dossier: whoever the player is looking at, held a moment after they look away ----
		if ( !_spawner.IsValid() ) _spawner = Scene.GetAllComponents<MisfitSpawner>().FirstOrDefault();
		var focus = mode == SumpMode.Hub && _spawner.IsValid() && _spawner.Focus.IsValid() ? _spawner.Focus.Profile : null;
		if ( focus is not null ) { _dossier = focus; _dossierUntil = now + DossierHoldSeconds; }
		else if ( now > _dossierUntil || mode != SumpMode.Hub ) _dossier = null;
		DossierRows.Clear();
		if ( _dossier is not null )
		{
			DossierNameStyle = NameColor( _dossier );
			string dossier = "";
			try { dossier = MisfitVoice.Dossier( _dossier ) ?? ""; } catch ( Exception ) { }
			first = true;
			foreach ( var line in dossier.Split( '\n' ) )
			{
				if ( line.Trim().Length == 0 ) continue;
				DossierRows.Add( new Row { Text = line.Trim(), First = first } );
				first = false;
			}
			hash.Add( dossier );
		}
		hash.Add( _dossier?.Index ?? -1 );

		// ---- Calm ----
		float calm = Math.Clamp( Sump.Calm, 0f, 1f );
		CalmPercent = (int)MathF.Round( calm * 50f ) * 2;
		bool low = calm < LowCalm;
		bool beat = low && ((int)(now * 4f) & 1) == 0;
		CalmClass = low ? (beat ? "calm scrap low beat" : "calm scrap low") : calm < 0.6f ? "calm scrap uneasy" : "calm scrap";
		CalmCaption = !string.IsNullOrEmpty( Sump.Dread ) ? Sump.Dread : low ? "panic" : calm < 0.6f ? "uneasy" : "calm";

		var fears = new List<Phobia>();
		try
		{
			if ( !_phobia.IsValid() && Sump.Player.IsValid() ) _phobia = Sump.Player.Components.Get<PlayerPhobia>();
			if ( _phobia.IsValid() )
				foreach ( var fear in _phobia.Fears )
					if ( fear is not null && !fears.Contains( fear.Kind ) ) fears.Add( fear.Kind );
		}
		catch ( Exception ) { }
		if ( !fears.Contains( SumpState.PlayerPhobia ) ) fears.Insert( 0, SumpState.PlayerPhobia );
		FearsText = "afraid of " + string.Join( ", ", fears.Select( FearName ) );
		hash.Add( CalmPercent ); hash.Add( CalmClass ); hash.Add( CalmCaption ); hash.Add( FearsText );

		// ---- Patchwork ----
		PatchRows.Clear();
		PatchNotice = "";
		try
		{
			var patchwork = Patchwork.Of( Sump.Player );
			if ( patchwork.IsValid() )
			{
				PatchNotice = patchwork.Notice ?? "";
				string summary = patchwork.Summary ?? "";
				first = true;
				foreach ( var line in summary.Split( '\n' ) )
				{
					if ( line.Trim().Length == 0 ) continue;
					// Ability lines come indented, with their key in brackets.
					PatchRows.Add( new Row { Text = line.Trim(), First = first, Percent = !first && line.StartsWith( " " ) ? 1 : 0 } );
					first = false;
				}
				hash.Add( summary );
			}
		}
		catch ( Exception ) { }
		hash.Add( PatchNotice );

		// ---- Radio ----
		RadioStations.Clear();
		RadioOn = false;
		try
		{
			var radio = SumpHub.Radio;
			RadioOn = radio is not null && radio.PlayerListening && mode == SumpMode.Hub;
			if ( RadioOn )
			{
				for ( int i = 0; i < radio.Frequencies.Count; i++ )
				{
					var who = radio.MisfitAt( i );
					RadioStations.Add( new Row
					{
						Text = radio.Label( i ),
						Extra = who is null ? "" : MisfitVoice.ShortName( who ),
						Style = NameColor( who ),
						First = i == radio.Tuned,
					} );
				}

				// How much of what is under the Sump has come through so far.
				int total = SumpFinale.LoreFragments.Count;
				RadioLore = total > 0
					? (SumpFinale.PictureTogether ? "the picture is together      " : "") + $"fragments heard {SumpFinale.FragmentsHeard} / {total}      clear {SumpFinale.FragmentsClear}"
					: "";
				hash.Add( RadioLore );
				hash.Add( radio.Tuned ); hash.Add( radio.Frequencies.Count );
			}
		}
		catch ( Exception ) { RadioOn = false; }
		hash.Add( RadioOn );

		// ---- Controls card: once, the first time the player has the hub to themselves ----
		if ( !_controlsDone && mode == SumpMode.Hub && string.IsNullOrEmpty( Sump.CardTitle ) && Sump.Fade < 0.05f )
		{
			_controlsDone = true;
			bool seen = !AlwaysShowControls && SumpState.GetNote( "hud_controls_seen" ) == "1";
			if ( !seen )
			{
				_controlsUntil = now + ControlsSeconds;
				if ( !AlwaysShowControls ) SumpState.SetNote( "hud_controls_seen", "1" );
			}
		}
		ShowControls = mode == SumpMode.Hub && now < _controlsUntil && !RadioOn;
		hash.Add( ShowControls );

		// ---- Fade, white-out, card ----
		float white = runner.IsValid() ? runner.WhiteOut : 0f;
		FadeOpacity = Opacity( Sump.Fade );
		WhiteOpacity = Opacity( white );
		hash.Add( FadeOpacity ); hash.Add( WhiteOpacity );

		CardLines.Clear();
		foreach ( var line in (Sump.CardLine ?? "").Split( '\n' ) )
			if ( line.Trim().Length > 0 ) CardLines.Add( line.Trim() );
		hash.Add( Sump.CardTitle ); hash.Add( Sump.CardLine );

		// ---- Subtitles: the newest few, the older ones dimmer ----
		Subtitles.Clear();
		var lines = Sump.Lines;
		int show = Math.Clamp( SubtitleLines, 1, 4 );
		int from = Math.Max( lines.Count - show, 0 );
		for ( int i = from; i < lines.Count; i++ )
		{
			var line = lines[i];
			if ( line is null ) continue;
			int age = lines.Count - 1 - i;
			var who = FindSpeaker( line.Speaker );
			string speaker = who is not null ? MisfitVoice.ShortName( who ) : line.Speaker ?? "";
			Subtitles.Add( new Row
			{
				Text = speaker,
				Extra = line.Text,
				Style = NameColor( who ),
				Class = (string.IsNullOrEmpty( speaker ) ? "sub narration" : "sub") + (age == 0 ? "" : age == 1 ? " old" : " older"),
			} );
			hash.Add( line.Text ); hash.Add( line.Speaker ); hash.Add( age );
		}

		return hash.ToHashCode();
	}

	protected override int BuildHash()
	{
		// After a failure the last picture is kept and the next try waits a moment, so a module
		// stuck in a bad state costs a few caught exceptions a second, not one every frame.
		if ( RealTime.Now < _retryAt ) return _hash;

		try { _hash = Refresh(); }
		catch ( Exception e )
		{
			// A module in a bad state must not take the HUD down with it: keep the last picture.
			if ( !_warned ) Log.Warning( $"SumpHud: {e.Message}" );
			_warned = true;
			_retryAt = RealTime.Now + 0.25f;
		}
		return _hash;
	}

	float _retryAt;
}