Sump/Trauma/PhobiaBase.cs

Abstract base for a single phobia component on the player. Scans the surroundings on an interval via Sense(), eases the result into Dread, applies resistance, and exposes the felt values plus per-frame camera, post-processing and input modifiers through Modify(). Also holds the panic attack hooks, flinch, shock and shared trace/geometry helpers, with a PhobiaMods struct that accumulates the frame's effects.

using System;

/// <summary>
/// What the fears on the player ask for this frame, added up by <see cref="PlayerPhobia"/> and
/// applied in one place: to the camera, to post-processing and to input. Multipliers start at 1
/// and are multiplied together; the rest start at 0 and add up.
/// </summary>
public struct PhobiaMods
{
	// ---- Input ----
	/// <summary>Movement speed multiplier.</summary>
	public float Speed;
	/// <summary>Share of mouse look taken away, 0 to 1 (the largest asked for wins).</summary>
	public float LookDamp;
	/// <summary>Degrees the view is turned this frame, whatever the mouse does.</summary>
	public float LookYaw, LookPitch;
	/// <summary>Extra steering wander, in degrees per second.</summary>
	public float Wobble;
	/// <summary>Extra chance of the hands losing a wall or ceiling, as a multiple of the usual.</summary>
	public float Slip;

	// ---- Camera ----
	/// <summary>Camera height and distance multipliers.</summary>
	public float CameraHeight, CameraDistance;
	/// <summary>Steady camera shake, in inches.</summary>
	public float Shake;

	// ---- Post-processing ----
	/// <summary>Bloom strength added to the camera's.</summary>
	public float Bloom;
	/// <summary>Picture brightness multiplier.</summary>
	public float Brightness;
	/// <summary>Colour multiplier (1 = all of it).</summary>
	public float Saturation;
	/// <summary>Vignette strength added, 0 to 1.</summary>
	public float Vignette;
	/// <summary>Eyes narrowed, 0 to 1: the vignette flattens toward a slit.</summary>
	public float Squint;

	public static PhobiaMods None => new()
	{
		Speed = 1f, CameraHeight = 1f, CameraDistance = 1f, Brightness = 1f, Saturation = 1f,
	};
}

/// <summary>
/// One fear on the player, as its own component. It looks at the surroundings a few times a
/// second, reports how frightening they are (<see cref="IPhobia"/>), and says what that does to
/// the camera, post-processing and input (<see cref="Modify"/>). The shared calm meter, the
/// stages and the panic attack belong to <see cref="PlayerPhobia"/> on the same object.
/// A new fear is one more class like this.
/// </summary>
public abstract class PhobiaBase : Component, IPhobia
{
	public abstract Phobia Kind { get; }

	/// <summary>How often the surroundings are looked at, in seconds. The scans are the costly part.</summary>
	[Property, Group( "Sensing" )] public float SenseInterval { get; set; } = 0.25f;

	/// <summary>Dread below this does not drain calm at all.</summary>
	[Property, Group( "Sensing" ), Range( 0f, 0.9f )] public float DreadFloor { get; set; } = 0.22f;

	/// <summary>How much of the dread full <see cref="Resistance"/> takes away (1 = all of it).</summary>
	[Property, Group( "Sensing" ), Range( 0f, 1f )] public float ResistanceStrength { get; set; } = 0.8f;

	/// <summary>How frightening things are for this fear right now, 0 to 1 (before resistance).</summary>
	public float Dread { get; private set; }
	public string Cause { get; private set; } = "";
	public Vector3? CausePosition { get; private set; }

	public float Resistance
	{
		get => _resistance;
		set => _resistance = Math.Clamp( value, 0f, 1f );
	}
	float _resistance;

	/// <summary>What resistance leaves of anything this fear does, 1 untouched to near 0.</summary>
	public float Keep => 1f - _resistance * ResistanceStrength;

	/// <summary>The dread as it is felt: after resistance, 0 to 1. Drives effects that follow the cause directly.</summary>
	public float Pressure => Dread * Keep;

	/// <summary>The part of the dread that drains calm: above the floor, after resistance.</summary>
	public float Felt
	{
		get
		{
			float floor = Math.Clamp( DreadFloor, 0f, 0.95f );
			return Math.Clamp( (Dread - floor) / (1f - floor), 0f, 1f ) * Keep;
		}
	}

	protected ReptileController Player { get; private set; }
	protected PlayerPhobia Owner { get; private set; }
	protected Vector3 Center => Player.WorldPosition + Player.Up * Player.Radius;

	/// <summary>Set by <see cref="Sense"/>: short words for the cause, and the way to it from the player.</summary>
	protected string RawCause = "";
	protected Vector3 CauseDir;

	float _raw;
	float _shock;
	TimeSince _sinceSense = 10f;
	int _senseFails;

	/// <summary>True once this fear has failed for good and been switched off: it senses nothing and changes nothing.</summary>
	public bool Broken { get; private set; }

	/// <summary>Switches this fear off for good, with one line in the log saying why.</summary>
	public void Fail( string why )
	{
		if ( Broken ) return;
		Broken = true;
		Log.Warning( $"{GetType().Name} switched off: {why}" );
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;
		if ( !Player.IsValid() ) Player = Components.Get<ReptileController>() ?? Sump.Player;
		if ( !Owner.IsValid() ) Owner = Components.Get<PlayerPhobia>();

		if ( Broken || !Player.IsValid() || (Owner.IsValid() ? !Owner.IsLive() : !PlayerPhobia.ModeAllows()) )
		{
			_raw = 0f; Dread = 0f; Cause = ""; CausePosition = null;
			return;
		}

		if ( _sinceSense >= MathF.Max( SenseInterval, 0.05f ) )
		{
			_sinceSense = 0;
			RawCause = "";
			CauseDir = Vector3.Zero;
			try { _raw = Sense(); _senseFails = 0; }
			catch ( Exception e )
			{
				// A fear that keeps failing is switched off for good, with one line in the log:
				// not a caught exception and a warning several times a second for ever.
				_raw = 0f;
				if ( ++_senseFails >= 3 ) Fail( $"sensing keeps failing: {e.Message}" );
			}
			_raw = float.IsNaN( _raw ) ? 0f : Math.Clamp( _raw, 0f, 1f );

			Cause = _raw > 0.01f ? RawCause : "";
			CausePosition = _raw > 0.01f && CauseDir.LengthSquared > 0.0001f ? Player.WorldPosition + CauseDir : null;
		}

		// Eased, so it does not step four times a second.
		Dread += (_raw - Dread) * Math.Clamp( Time.Delta * 5f, 0f, 1f );
	}

	/// <summary>Looks at the surroundings: returns the dread (0..1) and sets <see cref="RawCause"/> and <see cref="CauseDir"/>.</summary>
	protected abstract float Sense();

	/// <summary>
	/// Adds this fear's share to the frame's modifiers. senses and body are the shared stages
	/// (0..1) from the calm meter; attack is true while a panic attack has the controls.
	/// </summary>
	public virtual void Modify( ref PhobiaMods mods, float senses, float body, bool attack, float dt ) { }

	/// <summary>A flinch from the cause, when the body is shaken. amount is 0..1.</summary>
	public virtual void Flinch( float amount, float speed, float kick ) { }

	/// <summary>A panic attack begins and this fear is the cause: the way to bolt, or null to freeze.</summary>
	public virtual Vector3? AttackStart() => CauseDir.LengthSquared > 0.0001f ? -CauseDir.Normal : -Player.WorldRotation.Forward;

	/// <summary>Called every frame of the attack to steer the bolt.</summary>
	public virtual Vector3? AttackSteer( Vector3? current, float dt ) => current;

	/// <summary>Whether clinging to a wall or ceiling calms this fear.</summary>
	public virtual bool HidingHelps => true;

	/// <summary>The player's inner voice the first time this fear bites, and after its first attack.</summary>
	public abstract string FirstLine { get; }
	public abstract string AfterLine { get; }

	/// <summary>A sudden fright (a flash): calm lost at once. The owner takes it and it is cleared.</summary>
	protected void Shock( float calmLost ) => _shock += calmLost * Keep;
	public float TakeShock() { float s = _shock; _shock = 0f; return s; }

	// ---- Helpers for the fears ----

	protected static bool IsUnder( GameObject go, GameObject root )
	{
		for ( int i = 0; go is not null && i < 32; i++ )
		{
			if ( go == root ) return true;
			go = go.Parent;
		}
		return false;
	}

	protected SceneTraceResult Ray( Vector3 from, Vector3 to ) =>
		Scene.Trace.Ray( from, to ).IgnoreGameObjectHierarchy( GameObject ).WithoutTags( "debris" ).Run();

	protected static Vector3 Flatten( Vector3 v, Vector3 normal ) => v - normal * Vector3.Dot( v, normal );

	public static Vector3 RandomUnit()
	{
		var v = new Vector3( Game.Random.NextSingle() - 0.5f, Game.Random.NextSingle() - 0.5f, Game.Random.NextSingle() - 0.5f );
		return v.Length > 0.001f ? v.Normal : Vector3.Up;
	}
}