The player's phobia owner component. Creates and tracks the IPhobia components on the player, drains and recovers Sump.Calm from the strongest fear's dread, applies the summed PhobiaMods to the ReptileController (camera, look, speed, slips, flinches), post-processing on the camera (vignette, colour, bloom) and the heartbeat/breath loops, and runs the panic attack sequence that takes input, bolts, fades to black and restores calm. Restores everything it borrowed on disable or destroy.
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The player's own trauma. The stadium was THEIR first contact: a crowd that grabbed them, a Fat
/// Guy who sat on them, a white flash of stage lights. Each fear is its own small component on
/// the player (<see cref="CrowdsPhobia"/>, <see cref="WeightPhobia"/>, <see cref="LightPhobia"/>,
/// or anything else implementing <see cref="IPhobia"/>); this is the thin owner. It creates the
/// one rolled for the run (<see cref="SumpState.PlayerPhobia"/>), and more can be stacked on with
/// <see cref="Add"/>. It holds what the fears share:
/// - the calm meter (<see cref="Sump.Calm"/>): drained by the strongest fear, coming back when
/// the cause is gone, faster while still or clinging to a wall or ceiling;
/// - the stages: first the senses go (heartbeat jolts, breath, tunnel vision, colour), then the
/// body (grip, steering, flinches), on top of what each fear does by itself;
/// - the panic attack at zero calm: a few seconds out of control (led by the strongest fear), a
/// short blackout, calm partly restored;
/// - applying everybody's modifiers (<see cref="PhobiaMods"/>) to camera, post-processing and
/// input in one place, and putting it all back afterwards.
///
/// Tags other modules can use (this module only reads them):
/// "sump_body" - counts as a body for the fear of crowds (as do "crowd", "misfit" and unhealed
/// Misfit / MisfitBody objects that are not part of the player).
/// "sump_heavy" - something heavy; frightening when it is above the player (fear of weight).
/// "sump_bright" - something bright that is not a PointLight or SpotLight (fear of light).
/// "sump_unseen" - on the PLAYER: hidden from view, so crowds dread does not rise.
///
/// It does nothing during the Arrival, or while somebody else has locked input.
/// </summary>
[Title( "Player Phobia" ), Category( "Sump" ), Icon( "psychology_alt" )]
public sealed class PlayerPhobia : Component
{
public const string BodyTag = "sump_body";
public const string HeavyTag = "sump_heavy";
public const string BrightTag = "sump_bright";
public const string UnseenTag = "sump_unseen";
const string SpeedName = "phobia";
/// <summary>For testing: start with <see cref="ForcedKind"/> instead of the phobia rolled for the run.</summary>
[Property, Group( "Testing" )] public bool OverrideKind { get; set; }
[Property, Group( "Testing" )] public Phobia ForcedKind { get; set; } = Phobia.Crowds;
// ---- Tuning: the meter --------------------------------------------------------------------
/// <summary>Calm lost per second at full dread.</summary>
[Property, Group( "Calm" )] public float DrainPerSecond { get; set; } = 0.15f;
/// <summary>Calm regained per second once the cause is gone.</summary>
[Property, Group( "Calm" )] public float RecoverPerSecond { get; set; } = 0.06f;
/// <summary>Seconds after the cause is gone before calm starts to come back.</summary>
[Property, Group( "Calm" )] public float RecoverDelay { get; set; } = 1.2f;
/// <summary>Recovery is multiplied by this while the lizard keeps still.</summary>
[Property, Group( "Calm" )] public float StillBonus { get; set; } = 2f;
/// <summary>Recovery is multiplied by this while it clings to a wall or ceiling: hiding helps.</summary>
[Property, Group( "Calm" )] public float HideBonus { get; set; } = 2f;
/// <summary>Calm level under which the first-time line is spoken.</summary>
[Property, Group( "Calm" ), Range( 0f, 1f )] public float FirstBiteAt { get; set; } = 0.8f;
// ---- Tuning: the stages -------------------------------------------------------------------
/// <summary>Panic (1 - calm) at which the senses start to go.</summary>
[Property, Group( "Stages" ), Range( 0f, 1f )] public float SensesAt { get; set; } = 0.25f;
/// <summary>Panic at which the body starts to go.</summary>
[Property, Group( "Stages" ), Range( 0f, 1f )] public float BodyAt { get; set; } = 0.55f;
/// <summary>Size of the camera jolt on each heartbeat at full panic, in inches.</summary>
[Property, Group( "Stages" )] public float KickSize { get; set; } = 4f;
/// <summary>Volume of the breath and heartbeat loops at full panic.</summary>
[Property, Group( "Stages" )] public float SoundVolume { get; set; } = 0.9f;
/// <summary>Use the camera's post-processing (vignette, colour, bloom). Off leaves the camera alone.</summary>
[Property, Group( "Stages" )] public bool UsePostProcess { get; set; } = true;
/// <summary>Vignette strength at full panic.</summary>
[Property, Group( "Stages" ), Range( 0f, 1f )] public float VignetteMax { get; set; } = 0.75f;
/// <summary>Colour left at full panic (1 = all of it).</summary>
[Property, Group( "Stages" ), Range( 0f, 1f )] public float SaturationMin { get; set; } = 0.35f;
/// <summary>How hard the steering wanders when fully shaken, in degrees per second. 0 turns it off.</summary>
[Property, Group( "Stages" )] public float SteerWobble { get; set; } = 22f;
/// <summary>How often the hands lose a wall or ceiling when fully shaken, per second. 0 turns it off.</summary>
[Property, Group( "Stages" )] public float SlipsPerSecond { get; set; } = 0.3f;
/// <summary>Seconds between flinches away from the cause when fully shaken.</summary>
[Property, Group( "Stages" )] public float FlinchInterval { get; set; } = 2.2f;
/// <summary>Speed of a flinch, in inches per second.</summary>
[Property, Group( "Stages" )] public float FlinchSpeed { get; set; } = 260f;
// ---- Tuning: the panic attack -------------------------------------------------------------
/// <summary>Seconds a panic attack keeps the controls.</summary>
[Property, Group( "Attack" )] public float AttackSeconds { get; set; } = 3f;
/// <summary>How fast it bolts during an attack, as a multiple of walking speed.</summary>
[Property, Group( "Attack" )] public float BoltSpeed { get; set; } = 1.9f;
/// <summary>Seconds the screen takes to go black at the end of an attack.</summary>
[Property, Group( "Attack" )] public float BlackoutIn { get; set; } = 0.6f;
/// <summary>Seconds it stays black.</summary>
[Property, Group( "Attack" )] public float BlackoutHold { get; set; } = 0.5f;
/// <summary>Seconds it takes to come back.</summary>
[Property, Group( "Attack" )] public float BlackoutOut { get; set; } = 1.2f;
/// <summary>Calm given back after an attack.</summary>
[Property, Group( "Attack" ), Range( 0.1f, 1f )] public float AttackRestore { get; set; } = 0.45f;
/// <summary>Seconds after an attack during which nothing drains calm, so it can get away.</summary>
[Property, Group( "Attack" )] public float AttackGrace { get; set; } = 5f;
// ---- Read by the HUD and other modules ----------------------------------------------------
/// <summary>The fear that is strongest right now; when nothing frightens, the one rolled for the run.</summary>
public Phobia Kind => _strongest?.Kind ?? StartKind;
/// <summary>Every fear on the player at the moment.</summary>
public IReadOnlyList<IPhobia> Fears => _fears;
/// <summary>How frightening the surroundings are right now, 0 to 1 (the strongest fear, before resistance).</summary>
public float Dread01 { get; private set; }
/// <summary>Composure, 1 calm to 0 panic. The same number as <see cref="Sump.Calm"/>.</summary>
public float Calm01 => _calm;
/// <summary>True during a panic attack (controls taken, then the blackout).</summary>
public bool Panicking => _phase == AttackPhase.Act || _phase == AttackPhase.Hold;
/// <summary>Short name of what is frightening the player ("the crowd"), or empty.</summary>
public string CauseText { get; private set; } = "";
/// <summary>Where the cause is, when there is one.</summary>
public Vector3? CausePosition { get; private set; }
/// <summary>0 to 1. Grafts raise it. Setting it sets it on every fear the player has; each can also be set by itself.</summary>
public float Resistance
{
get => _resistance;
set
{
_resistance = Math.Clamp( value, 0f, 1f );
foreach ( var fear in Components.GetAll<IPhobia>() ) fear.Resistance = _resistance;
}
}
float _resistance;
/// <summary>Gives the player one more fear (or returns the one of that kind they already have).</summary>
public IPhobia Add( Phobia kind )
{
foreach ( var fear in Components.GetAll<IPhobia>() )
if ( fear.Kind == kind ) return fear;
IPhobia added = kind switch
{
Phobia.Crowds => Components.Create<CrowdsPhobia>(),
Phobia.Weight => Components.Create<WeightPhobia>(),
_ => Components.Create<LightPhobia>(),
};
added.Resistance = _resistance;
_sinceFearList = 10f;
return added;
}
/// <summary>Gives calm back at once (a healed misfit at your side, a graft settling in). 1 is a full meter.</summary>
public void Soothe( float amount )
{
if ( amount <= 0f ) return;
_calm = Math.Clamp( _calm + amount, 0f, 1f );
Sump.Calm = _calm;
}
/// <summary>Frightens the player at once, whatever their phobia (a jump scare from another module).</summary>
public void Startle( float amount, string cause = null )
{
if ( amount <= 0f || !IsLive() || Panicking ) return;
_calm = Math.Clamp( _calm - amount * (1f - _resistance * 0.8f), 0f, 1f );
if ( !string.IsNullOrEmpty( cause ) ) { CauseText = cause; _sinceDread = 0; }
}
/// <summary>True in the modes where the fears act at all.</summary>
public static bool ModeAllows() =>
Sump.Mode == SumpMode.Hub || Sump.Mode == SumpMode.Flashback || Sump.Mode == SumpMode.Finale;
/// <summary>True when the fears are allowed to act: the right mode, and nobody else's cutscene has the controls.</summary>
public bool IsLive()
{
if ( Scene.IsEditor || !ModeAllows() ) return false;
if ( !_player.IsValid() || !_player.Active ) return false;
if ( _player.InputLocked && !_lockedByMe ) return false;
return true;
}
// ---- State --------------------------------------------------------------------------------
enum AttackPhase { None, Act, Hold, FadeOut }
Phobia StartKind => OverrideKind ? ForcedKind : SumpState.PlayerPhobia;
ReptileController _player;
readonly List<IPhobia> _fears = new();
TimeSince _sinceFearList = 10f;
IPhobia _strongest;
readonly HashSet<Phobia> _firstSaid = new();
bool _afterLineSaid;
/// <summary>How much of the usual drain applies inside a flashback.</summary>
[Property, Range( 0f, 1f )] public float MemoryDrain { get; set; } = 0.4f;
float _calm = 1f;
TimeSince _sinceDread = 10f;
TimeSince _sinceAttack = 100f;
AttackPhase _phase;
float _phaseTime;
bool _lockedByMe;
Vector3? _boltDir;
PhobiaBase _attackBy;
bool _fadeMine;
float _beat; // counts down to the next heartbeat jolt
float _flinch; // counts down to the next flinch
float _wobbleTime;
bool _speedSet;
readonly Owned _camHeight = new();
readonly Owned _camDistance = new();
readonly Loop _breath = new();
readonly Loop _heart = new();
// Post-processing we added or borrowed, and how we found it.
bool _postTried;
Vignette _vignette;
bool _vignetteMine;
float _vignetteWas, _roundnessWas;
ColorAdjustments _colour;
bool _colourMine;
float _saturationWas = 1f, _brightnessWas = 1f;
Bloom _bloom;
bool _bloomMine;
float _bloomWas;
protected override void OnStart()
{
if ( Scene.IsEditor ) return;
_player = Components.Get<ReptileController>();
_calm = 1f;
Sump.Calm = 1f;
Sump.Dread = "";
Add( StartKind );
}
protected override void OnDisabled() => LetGoOfEverything();
protected override void OnDestroy() => LetGoOfEverything();
protected override void OnUpdate()
{
if ( Scene.IsEditor ) return;
if ( !_player.IsValid() ) _player = Components.Get<ReptileController>() ?? Sump.Player;
if ( !_player.IsValid() ) return;
float dt = Time.Delta;
// Somebody else let go of the lock we were holding: the attack is over, whatever stage it was at.
if ( _lockedByMe && !_player.InputLocked ) { _lockedByMe = false; EndAttack(); }
if ( _sinceFearList > 0.5f )
{
_sinceFearList = 0;
_fears.Clear();
_fears.AddRange( Components.GetAll<IPhobia>() );
}
if ( !IsLive() )
{
if ( _phase != AttackPhase.None ) EndAttack();
_strongest = null;
Dread01 = 0f;
CauseText = "";
CausePosition = null;
Sump.Dread = "";
Sump.Calm = _calm;
Apply( PhobiaMods.None, 0f, 0f, dt );
return;
}
// The strongest fear drives the meter; sudden frights from any of them land at once.
float felt = 0f, dread = 0f;
IPhobia strongest = null;
foreach ( var fear in _fears )
{
if ( fear is not Component { IsValid: true, Active: true } ) continue;
float f = FeltOf( fear );
dread = MathF.Max( dread, fear.Dread );
if ( f > felt ) { felt = f; strongest = fear; }
if ( fear is PhobiaBase shocked && _sinceAttack > AttackGrace && _phase == AttackPhase.None )
_calm = MathF.Max( 0f, _calm - shocked.TakeShock() );
}
Dread01 = Math.Clamp( dread, 0f, 1f );
if ( felt > 0.001f && strongest is not null )
{
_strongest = strongest;
_sinceDread = 0;
CauseText = strongest.Cause ?? "";
CausePosition = strongest.CausePosition;
}
else if ( _sinceDread > RecoverDelay )
{
_strongest = null;
CauseText = "";
CausePosition = null;
}
if ( _phase == AttackPhase.None || _phase == AttackPhase.FadeOut )
{
if ( felt > 0.001f && _sinceAttack > AttackGrace )
{
// A memory is somebody else's nightmare: the lizard's own fear bites less hard inside one,
// or a bright lab or a hot studio would be unplayable for a light-fearing lizard.
_calm -= DrainPerSecond * felt * dt * (Sump.Mode == SumpMode.Flashback ? MemoryDrain : 1f);
}
else if ( _sinceDread > RecoverDelay )
{
float rate = RecoverPerSecond;
if ( _player.Velocity.Length < 25f ) rate *= StillBonus;
// Tucked up on a wall or under a ceiling, unless one of the fears finds no comfort there.
if ( _player.Attached && _player.Up.z < 0.6f && HidingHelps() ) rate *= HideBonus;
_calm += rate * dt;
}
_calm = Math.Clamp( _calm, 0f, 1f );
}
if ( _calm < FirstBiteAt && felt > 0.001f && strongest is PhobiaBase biting && _firstSaid.Add( biting.Kind ) )
Sump.Say( "", biting.FirstLine, 6f );
if ( _phase == AttackPhase.None && _calm <= 0f ) BeginAttack();
if ( _phase != AttackPhase.None ) UpdateAttack( dt );
Sump.Calm = _calm;
Sump.Dread = CauseText ?? "";
// Everybody's modifiers, added up and applied once.
float panic = 1f - _calm;
float senses = Panicking ? 1f : Stage( panic, SensesAt );
float body = Panicking ? 0f : Stage( panic, BodyAt );
var mods = PhobiaMods.None;
foreach ( var fear in _fears )
{
if ( fear is not PhobiaBase { IsValid: true, Active: true, Broken: false } own ) continue;
try { own.Modify( ref mods, senses, body, Panicking, dt ); }
catch ( Exception e ) { own.Fail( $"its modifiers failed: {e.Message}" ); } // once, not every frame
}
Apply( mods, senses, body, dt );
}
float FeltOf( IPhobia fear )
{
if ( fear is PhobiaBase own ) return own.Felt;
// Somebody else's fear: the usual floor and resistance.
return Math.Clamp( (fear.Dread - 0.22f) / 0.78f, 0f, 1f ) * (1f - Math.Clamp( fear.Resistance, 0f, 1f ) * 0.8f);
}
bool HidingHelps()
{
foreach ( var fear in _fears )
if ( fear is PhobiaBase { IsValid: true, HidingHelps: false } ) return false;
return true;
}
/// <summary>0 below the threshold, rising to 1 at full panic.</summary>
static float Stage( float panic, float from )
{
from = Math.Clamp( from, 0f, 0.99f );
return Math.Clamp( (panic - from) / (1f - from), 0f, 1f );
}
// ---- Applying the modifiers ---------------------------------------------------------------
void Apply( PhobiaMods mods, float senses, float body, float dt )
{
bool attack = Panicking;
var center = _player.WorldPosition + _player.Up * _player.Radius;
// -- Camera --
// Heartbeat: a small jolt on every beat, quicker and bigger as panic rises.
if ( senses > 0.01f && KickSize > 0f )
{
_beat -= dt;
if ( _beat <= 0f )
{
_beat = 0.95f - 0.6f * senses;
_player.Kick( PhobiaBase.RandomUnit() * KickSize * (0.3f + 0.7f * senses) );
}
}
// Steady shake: the kick settles quickly, so feeding it every frame holds it at about this size.
if ( mods.Shake > 0.01f )
_player.Kick( PhobiaBase.RandomUnit() * MathF.Min( mods.Shake, 12f ) * Math.Clamp( dt * 14f, 0f, 1f ) );
_player.CameraHeight = _camHeight.Apply( _player.CameraHeight, Math.Clamp( mods.CameraHeight, 0.1f, 2f ) );
_player.CameraDistance = _camDistance.Apply( _player.CameraDistance, Math.Clamp( mods.CameraDistance, 0.2f, 2f ) );
// -- Sound --
_heart.Update( "heartbeat_loop", senses * SoundVolume, 1f + 0.35f * senses, center );
_breath.Update( "panic_breath_loop", Math.Clamp( senses * 1.3f - 0.3f, 0f, 1f ) * SoundVolume, 1f + 0.15f * senses, center );
// -- Post-processing --
ApplyPostProcess( mods, senses );
// -- Input --
float speed = attack ? (_phase == AttackPhase.Act && _boltDir.HasValue ? BoltSpeed : 1f) : mods.Speed;
speed = float.IsNaN( speed ) ? 1f : Math.Clamp( speed, 0.05f, 3f );
if ( _speedSet || MathF.Abs( speed - 1f ) > 0.0001f )
{
_player.SetSpeedFactor( SpeedName, speed );
_speedSet = MathF.Abs( speed - 1f ) > 0.0001f;
}
if ( attack || _player.IsPinned ) return;
ApplyLook( mods, body, dt );
if ( body > 0.001f )
{
Slip( body * (1f + mods.Slip), dt );
Flinch( body, dt );
}
}
/// <summary>The look: damped, tugged and wandering. One write to the controller, only if something changed.</summary>
void ApplyLook( PhobiaMods mods, float body, float dt )
{
if ( !_player.MouseCaptured ) return;
float yaw = mods.LookYaw, pitch = mods.LookPitch;
// Damping: take back a share of this frame's mouse movement. The controller adds the
// whole of it, before or after us, so the sum is the damped look either way.
float damp = Math.Clamp( mods.LookDamp, 0f, 0.9f );
if ( damp > 0.001f )
{
var moved = Input.AnalogLook;
yaw -= moved.yaw * damp;
pitch -= moved.pitch * damp;
}
// Steering wander: movement follows the view, so turning the view turns the run.
float wobble = SteerWobble * body * (1f + mods.Wobble);
if ( wobble > 0.001f )
{
_wobbleTime += dt;
yaw += (MathF.Sin( _wobbleTime * 3.1f ) + 0.6f * MathF.Sin( _wobbleTime * 7.3f + 1f )) * wobble * dt;
pitch += MathF.Sin( _wobbleTime * 4.7f + 2f ) * wobble * 0.3f * dt;
}
if ( MathF.Abs( yaw ) < 0.0001f && MathF.Abs( pitch ) < 0.0001f ) return;
if ( float.IsNaN( yaw ) || float.IsNaN( pitch ) ) return;
var look = _player.Look;
look.yaw += yaw;
look.pitch = Math.Clamp( look.pitch + pitch, -85f, 85f );
_player.SetLook( look );
}
/// <summary>Shaking hands: now and then they lose the wall or ceiling. On a floor it is only a stagger.</summary>
void Slip( float amount, float dt )
{
if ( SlipsPerSecond <= 0f || !_player.Attached || _player.IsLatching ) return;
if ( Game.Random.NextSingle() > SlipsPerSecond * amount * dt ) return;
_player.ShakeLoose( _player.Up * 60f + PhobiaBase.RandomUnit() * 50f );
_player.Kick( PhobiaBase.RandomUnit() * KickSize );
}
void Flinch( float amount, float dt )
{
if ( FlinchInterval <= 0f || FlinchSpeed <= 0f ) return;
_flinch -= dt * (0.4f + 0.6f * amount);
if ( _flinch > 0f ) return;
_flinch = FlinchInterval * (0.7f + 0.6f * Game.Random.NextSingle());
if ( _sinceDread > 0.5f ) return; // nothing to flinch from right now
if ( _strongest is PhobiaBase { IsValid: true } own ) own.Flinch( amount, FlinchSpeed, KickSize );
else if ( CausePosition is { } spot )
{
var away = _player.WorldPosition - spot;
if ( away.Length > 1f ) _player.Lunge( away.Normal, FlinchSpeed * amount );
}
}
void ApplyPostProcess( PhobiaMods mods, float senses )
{
if ( !UsePostProcess ) { mods = PhobiaMods.None; senses = 0f; }
float vignette = Math.Clamp( VignetteMax * senses + mods.Vignette + 0.5f * mods.Squint, 0f, 1f );
float saturation = Math.Clamp( (1f + (SaturationMin - 1f) * senses) * mods.Saturation, 0f, 1f );
float brightness = Math.Clamp( mods.Brightness, 0.2f, 1f );
float bloom = MathF.Max( mods.Bloom, 0f );
bool any = vignette > 0.01f || saturation < 0.99f || brightness < 0.99f || bloom > 0.01f;
try
{
if ( any && !_postTried )
{
_postTried = true;
FindPostProcess();
}
if ( _vignette.IsValid() )
{
_vignette.Intensity = _vignetteWas + (MathF.Max( vignette, _vignetteWas ) - _vignetteWas);
// A squint flattens the vignette toward a slit: dark above and below.
_vignette.Roundness = _roundnessWas + (0.05f - _roundnessWas) * Math.Clamp( mods.Squint, 0f, 1f );
if ( _vignetteMine ) _vignette.Enabled = vignette > 0.01f;
}
if ( _colour.IsValid() )
{
_colour.Saturation = _saturationWas * saturation;
_colour.Brightness = _brightnessWas * brightness;
if ( _colourMine ) _colour.Enabled = saturation < 0.99f || brightness < 0.99f;
}
if ( _bloom.IsValid() )
{
_bloom.Strength = _bloomWas + bloom;
if ( _bloomMine ) _bloom.Enabled = bloom > 0.01f;
}
}
catch ( Exception e )
{
UsePostProcess = false;
Log.Warning( $"PlayerPhobia: post-processing switched off: {e.Message}" );
}
}
/// <summary>Borrows the camera's vignette, colour and bloom, or adds them. Each is separate: a missing one costs only its own effect.</summary>
void FindPostProcess()
{
var camera = Scene.Camera;
if ( !camera.IsValid() ) return;
try
{
_vignette = camera.Components.Get<Vignette>();
_vignetteMine = !_vignette.IsValid();
if ( _vignetteMine )
{
_vignette = camera.Components.Create<Vignette>();
_vignette.Color = Color.Black;
_vignette.Intensity = 0f;
_vignette.Smoothness = 1f;
_vignette.Roundness = 0.7f;
}
_vignetteWas = _vignetteMine ? 0f : _vignette.Intensity;
_roundnessWas = _vignette.Roundness;
}
catch ( Exception e ) { _vignette = null; Log.Warning( $"PlayerPhobia: no vignette: {e.Message}" ); }
try
{
_colour = camera.Components.Get<ColorAdjustments>();
_colourMine = !_colour.IsValid();
if ( _colourMine ) _colour = camera.Components.Create<ColorAdjustments>();
_saturationWas = _colour.Saturation;
_brightnessWas = _colour.Brightness;
}
catch ( Exception e ) { _colour = null; Log.Warning( $"PlayerPhobia: no colour adjustments: {e.Message}" ); }
try
{
_bloom = camera.Components.Get<Bloom>();
if ( !_bloom.IsValid() ) _bloom = Scene.GetAllComponents<Bloom>().FirstOrDefault();
_bloomMine = !_bloom.IsValid();
if ( _bloomMine )
{
_bloom = camera.Components.Create<Bloom>();
_bloom.Strength = 0f;
}
_bloomWas = _bloomMine ? 0f : _bloom.Strength;
}
catch ( Exception e ) { _bloom = null; Log.Warning( $"PlayerPhobia: no bloom: {e.Message}" ); }
}
// ---- The panic attack ---------------------------------------------------------------------
void BeginAttack()
{
if ( _player.InputLocked || _player.IsPinned ) { _calm = 0.02f; return; }
_phase = AttackPhase.Act;
_phaseTime = 0f;
_lockedByMe = true;
_player.InputLocked = true;
_player.ForcedWish = null;
// The strongest fear leads: it says which way to bolt, or to freeze.
_attackBy = _strongest as PhobiaBase;
_boltDir = null;
try
{
if ( _attackBy.IsValid() ) _boltDir = _attackBy.AttackStart();
else if ( CausePosition is { } spot && (_player.WorldPosition - spot).Length > 1f ) _boltDir = (_player.WorldPosition - spot).Normal;
}
catch ( Exception ) { _boltDir = null; }
Sump.Sfx( "panic_attack", _player.WorldPosition );
}
void UpdateAttack( float dt )
{
_phaseTime += dt;
switch ( _phase )
{
case AttackPhase.Act:
{
if ( _attackBy.IsValid() )
{
try { _boltDir = _attackBy.AttackSteer( _boltDir, dt ); }
catch ( Exception ) { }
}
_player.ForcedWish = _boltDir is { } dir && dir.Length > 0.05f ? dir.Normal : null;
float left = AttackSeconds - _phaseTime;
if ( BlackoutIn > 0f && left < BlackoutIn ) SetFade( 1f - left / BlackoutIn );
if ( left <= 0f )
{
_phase = AttackPhase.Hold;
_phaseTime = 0f;
_player.ForcedWish = null;
SetFade( 1f );
}
break;
}
case AttackPhase.Hold:
SetFade( 1f );
if ( _phaseTime >= BlackoutHold )
{
ReleaseControls();
_phase = AttackPhase.FadeOut;
_phaseTime = 0f;
_calm = MathF.Max( _calm, AttackRestore );
_sinceAttack = 0;
if ( !_afterLineSaid && _attackBy.IsValid() ) { _afterLineSaid = true; Sump.Say( "", _attackBy.AfterLine, 6f ); }
}
break;
case AttackPhase.FadeOut:
if ( BlackoutOut <= 0f || _phaseTime >= BlackoutOut )
{
SetFade( 0f );
_fadeMine = false;
_phase = AttackPhase.None;
}
else SetFade( 1f - _phaseTime / BlackoutOut );
break;
}
}
void SetFade( float value )
{
_fadeMine = true;
Sump.Fade = Math.Clamp( value, 0f, 1f );
}
void ReleaseControls()
{
if ( !_lockedByMe ) return;
_lockedByMe = false;
if ( !_player.IsValid() ) return;
_player.InputLocked = false;
_player.ForcedWish = null;
}
/// <summary>Stops an attack wherever it is, giving the controls and the screen back.</summary>
void EndAttack()
{
bool wasPanicking = Panicking;
ReleaseControls();
if ( _fadeMine ) { Sump.Fade = 0f; _fadeMine = false; }
_phase = AttackPhase.None;
if ( wasPanicking )
{
_calm = MathF.Max( _calm, AttackRestore );
_sinceAttack = 0;
}
}
/// <summary>Puts back everything this component changed on the controller, the camera and the screen.</summary>
void LetGoOfEverything()
{
ReleaseControls();
if ( _fadeMine ) { Sump.Fade = 0f; _fadeMine = false; }
_phase = AttackPhase.None;
if ( _player.IsValid() )
{
_player.SetSpeedFactor( SpeedName, 1f );
_speedSet = false;
_player.CameraHeight = _camHeight.Restore( _player.CameraHeight );
_player.CameraDistance = _camDistance.Restore( _player.CameraDistance );
}
_heart.Stop();
_breath.Stop();
try
{
if ( _vignette.IsValid() )
{
if ( _vignetteMine ) _vignette.Destroy();
else { _vignette.Intensity = _vignetteWas; _vignette.Roundness = _roundnessWas; }
}
if ( _colour.IsValid() )
{
if ( _colourMine ) _colour.Destroy();
else { _colour.Saturation = _saturationWas; _colour.Brightness = _brightnessWas; }
}
if ( _bloom.IsValid() )
{
if ( _bloomMine ) _bloom.Destroy();
else _bloom.Strength = _bloomWas;
}
}
catch ( Exception ) { }
_vignette = null;
_colour = null;
_bloom = null;
_postTried = false;
}
// ---- Small helpers ------------------------------------------------------------------------
/// <summary>
/// Our share of a number other code also sets (the controller's camera height and distance).
/// The value we find is taken as everybody else's, unless it is still exactly what we wrote
/// last time; ours is multiplied on top, and taken off again by <see cref="Restore"/>.
/// </summary>
sealed class Owned
{
float _base, _written;
bool _active;
static bool Differs( float a, float b ) => MathF.Abs( a - b ) > 0.0001f * MathF.Max( 1f, MathF.Abs( a ) );
public float Apply( float current, float factor )
{
if ( !_active && MathF.Abs( factor - 1f ) < 0.0001f ) return current; // nothing of ours in it
if ( !_active || Differs( current, _written ) ) _base = current;
_active = true;
_written = _base * factor;
return _written;
}
public float Restore( float current )
{
if ( !_active ) return current;
_active = false;
return Differs( current, _written ) ? current : _base;
}
}
/// <summary>A looping Sump sound whose volume follows a number. Silent, and soon gives up, if the sound does not exist.</summary>
sealed class Loop
{
SoundHandle _handle;
float _nextTry;
int _fails;
public void Update( string name, float volume, float pitch, Vector3 position )
{
try
{
if ( volume <= 0.01f ) { Stop(); return; }
bool playing = _handle is not null && _handle.IsValid() && !_handle.IsStopped;
if ( !playing && _fails < 3 && RealTime.Now >= _nextTry )
{
_nextTry = RealTime.Now + 2f;
_handle = Sump.Sfx( name, position, volume );
playing = _handle is not null && _handle.IsValid();
if ( !playing ) { _fails++; _handle = null; }
}
if ( !playing ) return;
_handle.Volume = volume;
_handle.Pitch = pitch;
_handle.Position = position;
}
catch ( Exception ) { _fails = 99; _handle = null; }
}
public void Stop()
{
try { if ( _handle is not null && _handle.IsValid() && !_handle.IsStopped ) _handle.Stop( 0.4f ); }
catch ( Exception ) { }
_handle = null;
}
}
}