Story/LightShaft.cs

Component that renders a spotlight's visible beam as a column of additive sprite glows. Placed on the same GameObject as a SpotLight, it traces along the cone to find where the beam stops, sizes and fades the sprites based on cone angle, intensity and light colour, and hides when the light is off or in the editor.

using System;
using System.Collections.Generic;

/// <summary>
/// Makes a spotlight's beam visible in the air: a column of soft glowing sprites along the cone,
/// from the light to whatever it hits. Put it on the same object as a SpotLight. It follows the
/// light's direction, colour, cone and brightness, and hides when the light is off.
/// </summary>
[Title( "Light Shaft" ), Category( "Story" ), Icon( "flare" )]
public sealed class LightShaft : Component
{
	/// <summary>How many sprites make up the shaft. More is smoother.</summary>
	[Property] public int Sprites { get; set; } = 64;

	/// <summary>Longest the shaft can be, in inches.</summary>
	[Property] public float MaxLength { get; set; } = 2400f;

	/// <summary>Distance along the beam to skip before the shaft starts (and before looking for what it hits).</summary>
	[Property] public float StartOffset { get; set; } = 0f;

	/// <summary>How bright the shaft is for a light of intensity 1.</summary>
	[Property] public float Brightness { get; set; } = 0.008f;

	/// <summary>Cap on the shaft's brightness however strong the light is.</summary>
	[Property] public float MaxBrightness { get; set; } = 0.11f;

	/// <summary>How much distance fog dims the shaft (0 = it cuts straight through the murk).</summary>
	[Property, Range( 0f, 1f )] public float FogStrength { get; set; } = 0.25f;

	/// <summary>Widest the shaft's glow may get, however far the cone has spread.</summary>
	[Property] public float MaxWidth { get; set; } = 520f;

	[Property] public string SpritePath { get; set; } = "materials/dust/shaft_glow.sprite";

	SpotLight _light;
	GameObject _holder;
	readonly List<SpriteRenderer> _sprites = new();
	float _length;
	TimeSince _sinceTrace = 10f;

	protected override void OnDisabled()
	{
		if ( _holder.IsValid() ) _holder.Destroy();
		_holder = null;
		_sprites.Clear();
	}

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

		_light ??= Components.Get<SpotLight>();
		bool on = _light.IsValid() && _light.Active && _light.Intensity > 0.01f;
		if ( !on )
		{
			if ( _holder.IsValid() ) _holder.Enabled = false;
			return;
		}

		if ( !_holder.IsValid() ) Build();
		if ( _sprites.Count == 0 ) return;
		_holder.Enabled = true;

		var origin = _light.WorldPosition;
		var forward = _light.WorldRotation.Forward;

		// Find where the beam ends, a few times a second.
		if ( _sinceTrace > 0.1f )
		{
			_sinceTrace = 0;
			var from = origin + forward * StartOffset;
			var tr = Scene.Trace.Ray( from, from + forward * MaxLength ).IgnoreGameObjectHierarchy( GameObject.Root ).Run();
			_length = tr.Hit ? tr.Distance : MaxLength;
		}

		float glow = MathF.Min( _light.Intensity * Brightness, MaxBrightness );
		float spread = MathF.Tan( _light.ConeOuter * MathF.PI / 180f );
		var colour = _light.LightColor;

		for ( int i = 0; i < _sprites.Count; i++ )
		{
			float t = (i + 0.5f) / _sprites.Count;
			float along = StartOffset + _length * t;
			// Wider than the lit cone, and at least as wide as the gap to the next sprite, so the
			// glows overlap into one continuous column.
			float size = MathF.Max( along * spread * 2.3f, _length / _sprites.Count * 3.5f );
			size = MathF.Min( size, MaxWidth );

			// Fade in at the source and out before the surface, so there's no hard disc at either end.
			float fade = Math.Clamp( t * 6f, 0f, 1f ) * Math.Clamp( (1f - t) * 4f, 0f, 1f );

			var sprite = _sprites[i];
			sprite.WorldPosition = origin + forward * along;
			sprite.Size = new Vector2( size, size );
			float k = glow * fade;
			sprite.Color = new Color( colour.r * k, colour.g * k, colour.b * k, 1f );
		}
	}

	void Build()
	{
		_holder = new GameObject( true, "Light Shaft" );
		_holder.Flags |= GameObjectFlags.NotSaved;

		var sprite = ResourceLibrary.Get<Sprite>( SpritePath );
		if ( sprite is null ) return;

		for ( int i = 0; i < Math.Clamp( Sprites, 2, 80 ); i++ )
		{
			var go = new GameObject( _holder, true, "Shaft Sprite" );
			go.Flags |= GameObjectFlags.NotSaved;
			var renderer = go.Components.Create<SpriteRenderer>();
			renderer.Sprite = sprite;
			renderer.Additive = true;
			renderer.Lighting = false;
			renderer.Shadows = false;
			renderer.FogStrength = FogStrength;
			renderer.DepthFeather = 80f;      // melt into rock instead of cutting a hard line across it
			renderer.CameraFadeNear = 160f;   // and thin out close to the camera, so standing in a beam is haze, not a wall
			_sprites.Add( renderer );
		}
	}
}