Story/EnvoySpawner.cs
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// When the story reaches the Envoy stage, the owners break in. In order: something drills at
/// the wall from outside (noise, sparks, a growing tremor); the wall is blasted open; harsh
/// lights stab in through the hole; and the envoy walks in with its escorts. Happens once.
/// </summary>
[Title( "Envoy Spawner" ), Category( "Story" ), Icon( "sensor_door" )]
public sealed class EnvoySpawner : Component
{
	/// <summary>The envoy to clone. Left empty, a plain citizen is built in code.</summary>
	[Property] public GameObject EnvoyPrefab { get; set; }

	/// <summary>The escort to clone. Left empty, plain citizens are built in code.</summary>
	[Property] public GameObject EscortPrefab { get; set; }

	[Property] public int EscortCount { get; set; } = 3;

	/// <summary>World direction from the cave's centre toward the wall that gets breached.</summary>
	[Property] public Vector3 BreachDirection { get; set; } = new( 1f, 0.25f, -0.12f );

	[Property] public float BreachRadius { get; set; } = 170f;

	/// <summary>How far in from the breach the envoy appears, in inches.</summary>
	[Property] public float SpawnInset { get; set; } = 180f;

	/// <summary>Seconds of drilling before the wall goes.</summary>
	[Property, Group( "Timing" )] public float DrillSeconds { get; set; } = 7f;

	/// <summary>Seconds between the blast and the team stepping in.</summary>
	[Property, Group( "Timing" )] public float EntryDelay { get; set; } = 1.5f;

	/// <summary>Seconds the white flash of the blast takes to die away.</summary>
	[Property, Group( "Timing" )] public float FlashSeconds { get; set; } = 0.6f;

	/// <summary>Camera shake of the blast.</summary>
	[Property, Group( "Shake" )] public float ShakeStrength { get; set; } = 16f;
	[Property, Group( "Shake" )] public float ShakeSeconds { get; set; } = 1.6f;

	/// <summary>Camera shake of the drilling just before the blast; it builds up to this from almost nothing.</summary>
	[Property, Group( "Shake" )] public float DrillShakeStrength { get; set; } = 2.5f;

	[Property, Group( "Sound" )] public string DrillSound { get; set; } = "sounds/opening/drill_loop.sound";
	[Property, Group( "Sound" )] public string BlastSound { get; set; } = "sounds/opening/breach_blast.sound";

	[Property, Group( "Light" )] public Color SparkColor { get; set; } = new( 1f, 0.45f, 0.1f );
	[Property, Group( "Light" )] public float SparkIntensity { get; set; } = 6f;
	[Property, Group( "Light" )] public float SparkRadius { get; set; } = 260f;
	[Property, Group( "Light" )] public float FlashIntensity { get; set; } = 400f;
	[Property, Group( "Light" )] public float FlashRadius { get; set; } = 4000f;

	/// <summary>The envoy, once it has arrived.</summary>
	public GameObject Spawned { get; private set; }

	/// <summary>The escorts, once they have arrived.</summary>
	public List<GameObject> Escorts { get; } = new();

	/// <summary>The lights in the breach, once it has been opened.</summary>
	public BreachLights Lights { get; private set; }

	/// <summary>World position of the breach: the drill point on the wall at first, the centre of the hole once it is open.</summary>
	public Vector3 BreachPosition { get; private set; }

	enum Phase { Waiting, Drilling, Blasted, Done }
	Phase _phase = Phase.Waiting;
	TimeSince _sincePhase;
	TimeSince _sincePulse;
	TimeSince _sinceDrillTry = 10f;

	CaveGenerator _cave;
	GameObject _player;
	Vector3 _inward;        // level direction from the breach into the cave
	SoundHandle _drill;
	PointLight _glow;       // the drill's sparks, then the flash of the blast

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor || _phase == Phase.Done ) return;

		// Checked every frame rather than on StageChanged, so it also works when the stage is
		// already Envoy at the start, or the director appears after this does.
		var director = StoryDirector.Get( Scene );

		switch ( _phase )
		{
			case Phase.Waiting:
				if ( director is null || director.Stage < StoryStage.Envoy ) return;
				_cave = Scene.GetAllComponents<CaveGenerator>().FirstOrDefault();
				if ( _cave is null ) return;
				StartDrilling();
				break;

			case Phase.Drilling:
				Drill( director );
				if ( _sincePhase >= DrillSeconds ) Blast( director );
				break;

			case Phase.Blasted:
				FadeFlash();
				if ( _sincePhase >= EntryDelay ) SpawnTeam();
				break;
		}
	}

	protected override void OnDisabled()
	{
		StopDrillSound();
		if ( _glow.IsValid() ) _glow.GameObject.Destroy();
		_glow = null;
	}

	// ---- Drilling -----------------------------------------------------------------------------

	void StartDrilling()
	{
		var centre = _cave.WorldPosition;
		var direction = BreachDirection.Length > 0.001f ? BreachDirection.Normal : Vector3.Forward;
		_player = Scene.GetAllComponents<ReptileController>().FirstOrDefault()?.GameObject;

		// Find the wall: a ray from the middle of the cave outward.
		var wallTrace = Scene.Trace.Ray( centre, centre + direction * 20000f );
		if ( _player.IsValid() ) wallTrace = wallTrace.IgnoreGameObjectHierarchy( _player );
		var wall = wallTrace.Run();
		BreachPosition = wall.Hit ? wall.HitPosition : centre + direction * _cave.Size.x;
		SetInward( direction );

		// The sparks: a small hot light just off the rock, so it lights the wall around it.
		var go = new GameObject( GameObject, true, "Breach Glow" );
		go.Flags |= GameObjectFlags.NotSaved;
		go.WorldPosition = BreachPosition - direction * 14f;
		_glow = go.Components.Create<PointLight>();
		_glow.Shadows = false;
		_glow.LightColor = SparkColor;
		_glow.Radius = SparkRadius;
		_glow.Intensity = 0f;

		_phase = Phase.Drilling;
		_sincePhase = 0f;
		_sincePulse = 10f; // first tremor straight away
	}

	/// <summary>The level direction from the breach toward the middle of the cave.</summary>
	void SetInward( Vector3 fallbackOutward )
	{
		_inward = (_cave.WorldPosition - BreachPosition).WithZ( 0 );
		_inward = _inward.Length > 0.01f ? _inward.Normal : -fallbackOutward.WithZ( 0 ).Normal;
		if ( _inward.Length < 0.5f ) _inward = Vector3.Forward; // breach straight above or below the centre
	}

	void Drill( StoryDirector director )
	{
		float progress = DrillSeconds <= 0f ? 1f : MathF.Min( _sincePhase / DrillSeconds, 1f );

		// The loop is restarted if it ever stops (a sound that isn't set to loop, say).
		// Tried at most twice a second, so a missing sound doesn't fill the log.
		if ( !StorySound.IsPlaying( _drill ) && _sinceDrillTry >= 0.5f )
		{
			_sinceDrillTry = 0f;
			_drill = StorySound.Play( DrillSound, BreachPosition );
		}

		// Sparks: a jittery glow that gets hotter as the drill comes through.
		if ( _glow.IsValid() )
		{
			float flicker = Game.Random.Float( 0f, 1f ) < 0.25f ? Game.Random.Float( 0f, 0.3f ) : Game.Random.Float( 0.5f, 1f );
			_glow.Intensity = SparkIntensity * (0.35f + 0.65f * progress) * flicker;
		}

		// Tremors: short pulses, stronger and closer together toward the end.
		float gap = 0.45f - 0.25f * progress;
		if ( director is not null && _sincePulse >= gap )
		{
			_sincePulse = 0f;
			director.Shake( DrillShakeStrength * (0.1f + 0.9f * progress * progress), gap * 1.5f );
		}
	}

	void StopDrillSound()
	{
		StorySound.Stop( _drill );
		_drill = null;
	}

	// ---- Blast --------------------------------------------------------------------------------

	void Blast( StoryDirector director )
	{
		StopDrillSound();
		StorySound.Play( BlastSound, BreachPosition );
		director?.Shake( ShakeStrength, ShakeSeconds );

		var drillPoint = BreachPosition;
		BreachPosition = _cave.IsValid() ? _cave.OpenHole( drillPoint, BreachRadius ) : drillPoint;
		SetInward( -_inward );

		// The flash: the spark light turns white and blinding, then dies away (see FadeFlash).
		if ( _glow.IsValid() )
		{
			_glow.WorldPosition = BreachPosition + _inward * 30f;
			_glow.LightColor = Color.White;
			_glow.Radius = FlashRadius;
			_glow.Intensity = FlashIntensity;
		}

		// The lights outside, shining in. Forward (+X) of the object is the way into the cave.
		var lights = new GameObject( GameObject, true, "Breach Lights" );
		lights.Flags |= GameObjectFlags.NotSaved;
		lights.WorldPosition = BreachPosition;
		lights.WorldRotation = Rotation.LookAt( _inward, Vector3.Up );
		Lights = lights.Components.Create<BreachLights>();

		ThrowDebris();

		_phase = Phase.Blasted;
		_sincePhase = 0f;
	}

	/// <summary>Skin asset given to escorts, so a dead escort can be worn.</summary>
	[Property] public string EscortSkin { get; set; } = "skins/escort.skin";

	/// <summary>How many chunks of rock the blast throws into the cave.</summary>
	[Property, Group( "Debris" )] public int DebrisCount { get; set; } = 14;

	[Property, Group( "Debris" )] public string DebrisModel { get; set; } = "models/props/rock_scatter/rock_scatter_01.vmdl";

	[Property, Group( "Debris" )] public string DebrisMaterial { get; set; } = "materials/cave/cave_rock.vmat";

	/// <summary>Speed the chunks leave the wall at, in inches per second.</summary>
	[Property, Group( "Debris" )] public float DebrisSpeed { get; set; } = 650f;

	/// <summary>Rock blown inward by the blast: real physics chunks that bounce and settle on the floor.</summary>
	void ThrowDebris()
	{
		for ( int i = 0; i < DebrisCount; i++ )
		{
			var position = BreachPosition + _inward * Game.Random.Float( 30f, 90f ) + Vector3.Random * 45f;
			var velocity = (_inward + Vector3.Random * 0.45f + Vector3.Up * 0.25f).Normal * DebrisSpeed * Game.Random.Float( 0.4f, 1f );
			RockDebris.Spawn( position, velocity, Game.Random.Float( 1.5f, 5f ), DebrisModel, DebrisMaterial );
		}
	}

	void FadeFlash()
	{
		if ( !_glow.IsValid() ) return;

		float left = FlashSeconds <= 0f ? 0f : 1f - _sincePhase / FlashSeconds;
		if ( left <= 0f )
		{
			_glow.GameObject.Destroy();
			_glow = null;
			return;
		}
		_glow.Intensity = FlashIntensity * left * left; // drops fast, then lingers
	}

	// ---- The team -----------------------------------------------------------------------------

	void SpawnTeam()
	{
		_phase = Phase.Done;
		if ( _glow.IsValid() ) _glow.GameObject.Destroy();
		_glow = null;

		// Step back in from the breach toward the middle, then drop to the floor.
		var rotation = Rotation.LookAt( _inward, Vector3.Up );
		var envoyAt = FloorBelow( BreachPosition + _inward * SpawnInset );

		Spawned = EnvoyPrefab.IsValid() ? EnvoyPrefab.Clone( envoyAt, rotation ) : BuildEnvoy( envoyAt, rotation );
		var envoy = Spawned.IsValid() ? Spawned.Components.Get<Envoy>( FindMode.EverythingInSelfAndDescendants ) : null;

		// Escorts: a loose wedge behind the envoy, two to a row, each row further back and wider.
		var left = rotation.Left;
		for ( int i = 0; i < EscortCount; i++ )
		{
			int row = i / 2 + 1;
			float side = i % 2 == 0 ? 1f : -1f;
			var offset = new Vector3( -62f * row + Game.Random.Float( -10f, 10f ), side * 58f * row + Game.Random.Float( -8f, 8f ), 0f );

			var at = FloorBelow( envoyAt + _inward * offset.x + left * offset.y );
			var go = EscortPrefab.IsValid() ? EscortPrefab.Clone( at, rotation ) : BuildEscort( at, rotation );
			if ( !go.IsValid() ) continue;
			go.Name = $"Escort {i + 1}";

			var escort = go.Components.Get<Escort>( FindMode.EverythingInSelfAndDescendants ) ?? go.Components.Create<Escort>();

			// Escorts can be worn too: give each the escort skin unless its prefab already has one.
			if ( go.Components.Get<Skin>( FindMode.EverythingInSelfAndDescendants ) is null && !string.IsNullOrEmpty( EscortSkin ) )
			{
				var definition = ResourceLibrary.Get<SkinDefinition>( EscortSkin );
				if ( definition is not null ) go.Components.Create<Skin>().Definition = definition;
			}
			escort.Leader = envoy;
			escort.FormationOffset = offset;
			Escorts.Add( go );
		}
	}

	/// <summary>The cave floor under a point (the ray starts at mid height so it begins inside the cave).</summary>
	Vector3 FloorBelow( Vector3 point )
	{
		var above = point;
		if ( _cave.IsValid() ) above.z = MathF.Max( above.z, _cave.WorldPosition.z );

		var trace = Scene.Trace.Ray( above, above + Vector3.Down * 5000f );
		if ( _player.IsValid() ) trace = trace.IgnoreGameObjectHierarchy( _player );
		if ( Spawned.IsValid() ) trace = trace.IgnoreGameObjectHierarchy( Spawned );
		foreach ( var escort in Escorts )
			if ( escort.IsValid() ) trace = trace.IgnoreGameObjectHierarchy( escort );

		var floor = trace.Run();
		return floor.Hit ? floor.HitPosition : above;
	}

	/// <summary>A stand-in envoy for when no prefab is set: a bare citizen with the needed components.</summary>
	GameObject BuildEnvoy( Vector3 position, Rotation rotation )
	{
		var go = BuildCitizen( "Envoy", position, rotation );
		go.Components.Create<Envoy>();
		return go;
	}

	/// <summary>A stand-in escort for when no prefab is set.</summary>
	GameObject BuildEscort( Vector3 position, Rotation rotation )
	{
		var go = BuildCitizen( "Escort", position, rotation );
		go.Components.Create<Escort>();
		return go;
	}

	GameObject BuildCitizen( string name, Vector3 position, Rotation rotation )
	{
		var go = Scene.CreateObject();
		go.Name = name;
		go.WorldPosition = position;
		go.WorldRotation = rotation;

		var renderer = go.Components.Create<SkinnedModelRenderer>();
		renderer.Model = Model.Load( "models/citizen/citizen.vmdl" );

		// A capsule 72 tall standing on the object's origin.
		var capsule = go.Components.Create<CapsuleCollider>();
		capsule.Radius = 14f;
		capsule.Start = new Vector3( 0, 0, 14f );
		capsule.End = new Vector3( 0, 0, 58f );

		go.Components.Create<Health>().MaxHealth = 60f;
		go.Components.Create<FactionTag>().Faction = FactionTag.Owners;
		return go;
	}
}

/// <summary>
/// Plays the opening's sounds by path. The sound assets may not exist yet, so everything here
/// is safe with a missing sound: playing returns null and the rest do nothing.
/// </summary>
public static class StorySound
{
	public static SoundHandle Play( string path, Vector3 position )
	{
		if ( string.IsNullOrWhiteSpace( path ) ) return null;
		try
		{
			var handle = Sound.Play( path, position );
			return handle.IsValid() ? handle : null;
		}
		catch ( Exception )
		{
			return null;
		}
	}

	public static bool IsPlaying( SoundHandle handle ) => handle.IsValid() && !handle.IsStopped;

	public static void Stop( SoundHandle handle, float fadeSeconds = 0.1f )
	{
		if ( handle.IsValid() && !handle.IsStopped ) handle.Stop( fadeSeconds );
	}
}