Stadium/StadiumAudio.cs

Audio controller for the stadium scene. Plays a flash sting, a looping crowd murmur, the shapeshift sound, a gasp, randomly positioned screams and a looping panic bed, fading everything out when the scene ends. Uses StadiumGame to read phase, shift progress and pinned state, and retries missing loop files a limited number of times.

using System;

/// <summary>
/// The sound of Scene 2, one per scene. A murmuring crowd while you walk in and stand at the
/// podium; the wet noise of the skin failing; one great gasp, then screams breaking out all
/// round the hall; and a wall of panic for as long as you are running. Everything fades when
/// the scene ends, either way. Play mode only.
/// </summary>
[Title( "Stadium Audio" ), Category( "Stadium" ), Icon( "campaign" )]
public sealed class StadiumAudio : Component
{
	// ---- Sounds ------------------------------------------------------------------------------
	/// <summary>The white flash at the very start. Its sound event is flagged as UI, so it has no position.</summary>
	[Property, Group( "Sounds" )] public string FlashSound { get; set; } = "sounds/stadium/flash_in.sound";

	/// <summary>The looping murmur of the waiting crowd (UI, looping).</summary>
	[Property, Group( "Sounds" )] public string MurmurSound { get; set; } = "sounds/stadium/crowd_murmur_loop.sound";

	/// <summary>The skin failing (UI).</summary>
	[Property, Group( "Sounds" )] public string ShiftSound { get; set; } = "sounds/stadium/shift.sound";

	/// <summary>The whole hall breathing in (UI).</summary>
	[Property, Group( "Sounds" )] public string GaspSound { get; set; } = "sounds/stadium/gasp.sound";

	/// <summary>A knot of people screaming. Positional: played at spots around the player.</summary>
	[Property, Group( "Sounds" )] public string ScreamSound { get; set; } = "sounds/stadium/scream.sound";

	/// <summary>The looping chaos of the escape (UI, looping).</summary>
	[Property, Group( "Sounds" )] public string PanicSound { get; set; } = "sounds/stadium/panic_loop.sound";

	// ---- Volumes -----------------------------------------------------------------------------
	[Property, Group( "Volume" ), Range( 0f, 2f )] public float FlashVolume { get; set; } = 0.9f;
	[Property, Group( "Volume" ), Range( 0f, 2f )] public float MurmurVolume { get; set; } = 0.7f;
	[Property, Group( "Volume" ), Range( 0f, 2f )] public float ShiftVolume { get; set; } = 1f;
	[Property, Group( "Volume" ), Range( 0f, 2f )] public float GaspVolume { get; set; } = 1.1f;
	[Property, Group( "Volume" ), Range( 0f, 2f )] public float ScreamVolume { get; set; } = 1f;
	[Property, Group( "Volume" ), Range( 0f, 2f )] public float PanicVolume { get; set; } = 0.65f;

	/// <summary>How loud the panic loop is while the lizard is pinned under the pile.</summary>
	[Property, Group( "Volume" ), Range( 0f, 2f )] public float PinnedPanicVolume { get; set; } = 1f;

	// ---- Timing ------------------------------------------------------------------------------
	/// <summary>How far through the shapeshift (0..1) the crowd gasps.</summary>
	[Property, Group( "Timing" ), Range( 0f, 1f )] public float GaspAt { get; set; } = 0.25f;

	/// <summary>How far through the shapeshift the first screams break out.</summary>
	[Property, Group( "Timing" ), Range( 0f, 1f )] public float ScreamsFrom { get; set; } = 0.55f;

	/// <summary>How far through the shapeshift the murmur starts to die and the panic to rise.</summary>
	[Property, Group( "Timing" ), Range( 0f, 1f )] public float MurmurFadeFrom { get; set; } = 0.6f;

	/// <summary>Seconds between scattered screams during the escape: shortest and longest gap.</summary>
	[Property, Group( "Timing" )] public Vector2 EscapeScreamGap { get; set; } = new( 0.7f, 2.2f );

	/// <summary>Seconds everything takes to fade once the scene has ended.</summary>
	[Property, Group( "Timing" )] public float EndFadeSeconds { get; set; } = 2.5f;

	StadiumGame _game;
	SoundHandle _murmur, _panic, _shift;
	float _murmurLevel = 1f;   // 0..1, multiplied by the volume property
	float _panicLevel;         // already in volume units
	float _endLevel = 1f;      // 1 until the scene ends, then down to 0
	bool _started, _shiftPlayed, _gasped;
	TimeUntil _nextScream;
	TimeSince _sinceMurmurTry = 10f, _sincePanicTry = 10f;

	// A loop that will not start (a missing file) is given up on, not asked for twice a second for good.
	const int MaxTries = 4;
	int _murmurFails, _panicFails;

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

		if ( !_game.IsValid() ) _game = StadiumGame.Get( Scene );
		if ( !_game.IsValid() ) return;

		if ( !_started )
		{
			_started = true;
			var flash = PlayFlat( FlashSound );
			if ( flash.IsValid() ) flash.Volume *= FlashVolume;
		}

		var phase = _game.Phase;
		float shift = _game.ShiftProgress;
		bool ended = phase is StadiumPhase.GameOver or StadiumPhase.Won;

		// The scene is over: everything sinks away together.
		_endLevel = Approach( _endLevel, ended ? 0f : 1f, Time.Delta / MathF.Max( EndFadeSeconds, 0.1f ) );

		UpdateMurmur( phase, shift );
		UpdateShift( phase );
		UpdateReactions( phase, shift, ended );
		UpdatePanic( phase, shift, ended );
	}

	protected override void OnDisabled()
	{
		StorySound.Stop( _murmur );
		StorySound.Stop( _panic );
		StorySound.Stop( _shift );
		_murmur = _panic = _shift = null;
	}

	// The murmur runs from the first frame. It is started again if it ever ends (in case the
	// file's loop flag didn't take), and dies away as the crowd sees what is on the stage.
	void UpdateMurmur( StadiumPhase phase, float shift )
	{
		float target = phase switch
		{
			StadiumPhase.FlashIn or StadiumPhase.Speech => 1f,
			StadiumPhase.Shapeshift => 1f - Math.Clamp( (shift - MurmurFadeFrom) / 0.2f, 0f, 1f ),
			_ => 0f,
		};
		_murmurLevel = Approach( _murmurLevel, target, Time.Delta * 2.5f );

		float volume = MurmurVolume * _murmurLevel * _endLevel;
		if ( volume <= 0.001f )
		{
			if ( target <= 0f ) { StorySound.Stop( _murmur ); _murmur = null; }
			return;
		}

		if ( !StorySound.IsPlaying( _murmur ) && _sinceMurmurTry >= 0.5f && _murmurFails < MaxTries )
		{
			_sinceMurmurTry = 0f;
			_murmur = PlayFlat( MurmurSound );
			_murmurFails = _murmur.IsValid() ? 0 : _murmurFails + 1;
		}
		if ( _murmur.IsValid() ) _murmur.Volume = volume;
	}

	void UpdateShift( StadiumPhase phase )
	{
		if ( phase == StadiumPhase.Shapeshift && !_shiftPlayed )
		{
			_shiftPlayed = true;
			_shift = PlayFlat( ShiftSound );
			if ( _shift.IsValid() ) _shift.Volume *= ShiftVolume;
		}
	}

	// One gasp, then screams: thick and fast while the shift finishes, scattered during the escape.
	void UpdateReactions( StadiumPhase phase, float shift, bool ended )
	{
		if ( phase < StadiumPhase.Shapeshift || ended ) return;

		if ( !_gasped && shift >= GaspAt )
		{
			_gasped = true;
			_nextScream = 0f;
			var gasp = PlayFlat( GaspSound );
			if ( gasp.IsValid() ) gasp.Volume *= GaspVolume;
		}

		if ( shift < ScreamsFrom || !_nextScream ) return;

		bool shifting = phase == StadiumPhase.Shapeshift;
		_nextScream = shifting ? Game.Random.Float( 0.15f, 0.55f ) : Game.Random.Float( EscapeScreamGap.x, MathF.Max( EscapeScreamGap.y, EscapeScreamGap.x ) );

		// Somewhere out in the hall, off to one side of whoever is listening.
		var centre = _game.Player.IsValid() ? _game.Player.WorldPosition : StadiumLayout.Podium;
		float angle = Game.Random.Float( 0f, MathF.PI * 2f );
		float distance = Game.Random.Float( 350f, 1000f );
		var at = centre + new Vector3( MathF.Cos( angle ) * distance, MathF.Sin( angle ) * distance, Game.Random.Float( 40f, 200f ) );

		var scream = StorySound.Play( ScreamSound, at );
		if ( scream.IsValid() ) scream.Volume *= ScreamVolume * (shifting ? 1f : 0.8f);
	}

	// The panic loop creeps in under the last of the shift, runs through the escape, and is
	// louder while the lizard is under the pile.
	void UpdatePanic( StadiumPhase phase, float shift, bool ended )
	{
		float target = phase switch
		{
			StadiumPhase.Shapeshift => PanicVolume * 0.7f * Math.Clamp( (shift - MurmurFadeFrom) / MathF.Max( 1f - MurmurFadeFrom, 0.05f ), 0f, 1f ),
			StadiumPhase.Escape => _game.Pinned ? PinnedPanicVolume : PanicVolume,
			StadiumPhase.GameOver or StadiumPhase.Won => _panicLevel, // held; _endLevel does the fading
			_ => 0f,
		};
		_panicLevel = Approach( _panicLevel, target, Time.Delta * 1.2f );

		float volume = _panicLevel * _endLevel;
		if ( volume <= 0.001f )
		{
			if ( ended || target <= 0f ) { StorySound.Stop( _panic ); _panic = null; }
			return;
		}

		if ( !StorySound.IsPlaying( _panic ) && _sincePanicTry >= 0.5f && _panicFails < MaxTries )
		{
			_sincePanicTry = 0f;
			_panic = PlayFlat( PanicSound );
			_panicFails = _panic.IsValid() ? 0 : _panicFails + 1;
		}
		if ( _panic.IsValid() ) _panic.Volume = volume;
	}

	/// <summary>Plays a sound with no position (its event is flagged as UI). Null if it is missing.</summary>
	static SoundHandle PlayFlat( string path )
	{
		if ( string.IsNullOrWhiteSpace( path ) ) return null;
		try
		{
			var handle = Sound.Play( path );
			return handle.IsValid() ? handle : null;
		}
		catch ( Exception )
		{
			return null;
		}
	}

	static float Approach( float value, float target, float step )
	{
		return value < target ? MathF.Min( value + step, target ) : MathF.Max( value - step, target );
	}
}