Sump/Grafts/GraftAbilities.cs

The graft ability half of the Sump graft system: an abstract GraftAbility component with press/cooldown/HUD plumbing, plus five concrete abilities (body door portal pair, unwatched invisibility, bullet-magnet point that pulls rigidbodies, price-tag freeze that disables brains and rigidbodies, toy stillness that shrinks and hides the player). All effects undo themselves when the component is disabled or destroyed.

using System;
using System.Collections.Generic;

// The ability half of a graft: the misfit's twisted ability, now the player's, on a key
// (Slot1..Slot9 in the order grafted; Patchwork reads the keys and calls Press). Each is one small
// component next to its Graft. Disabling the component (grafts switched off for a flashback)
// undoes whatever it was doing at once.

/// <summary>
/// Something a frozen (priced) thing can implement on any of its components to be told about it,
/// instead of being stopped from outside. See <see cref="PriceTagGraft"/>.
/// </summary>
public interface IPriceable
{
	/// <summary>True when the price goes on (hold still for about that many seconds), false when it comes off.</summary>
	void OnPriced( bool priced, float seconds );
}

/// <summary>Shared by every graft ability: the key press, the cooldown, the words for the HUD.</summary>
public abstract class GraftAbility : Component
{
	/// <summary>The graft this belongs to. Set by <see cref="Graft.Create"/>.</summary>
	public Graft Graft { get; set; }

	public abstract TwistedAbility Kind { get; }
	/// <summary>Short name for the HUD ("Body door").</summary>
	public abstract string Title { get; }
	/// <summary>One line on how to use it.</summary>
	public abstract string HowTo { get; }
	/// <summary>Seconds before it can be used again.</summary>
	protected abstract float CooldownTime { get; }

	/// <summary>True while its effect is going on.</summary>
	public virtual bool Running => false;
	public float CooldownLeft => MathF.Max( 0f, _readyAt - Time.Now );
	public bool Ready => !Running && CooldownLeft <= 0f;

	/// <summary>A word or two for the HUD: "ready", "in use", "12s".</summary>
	public virtual string Status => Running ? "in use" : CooldownLeft > 0f ? $"{MathF.Ceiling( CooldownLeft ):0}s" : "ready";

	protected Patchwork Owner => Graft.IsValid() ? Graft.Owner : null;
	protected ReptileController Player => Owner.IsValid() ? Owner.Player : null;
	protected string MisfitName => Graft.IsValid() ? Graft.Name : "Nobody";

	float _readyAt;

	/// <summary>The key was pressed.</summary>
	public void Press()
	{
		if ( !Enabled || !Player.IsValid() ) return;
		if ( !Running && CooldownLeft > 0f )
		{
			Owner.Note( $"{Title}: not yet ({MathF.Ceiling( CooldownLeft ):0}s)." );
			return;
		}
		try { OnPress(); }
		catch ( Exception e ) { Log.Warning( $"Graft ability {Kind} failed: {e.Message}" ); Cancel(); }
	}

	protected abstract void OnPress();

	/// <summary>Undoes everything it is doing right now, with no cooldown. Safe to call at any time.</summary>
	public virtual void Cancel() { }

	protected void StartCooldown() => _readyAt = Time.Now + MathF.Max( CooldownTime, 0f );

	protected SoundHandle Sfx( string name, float volume = 1f ) =>
		Sump.Sfx( name, Player.IsValid() ? Player.WorldPosition : WorldPosition, volume );

	protected override void OnDisabled() => Cancel();
	protected override void OnDestroy() => Cancel();
}

/// <summary>
/// BodyDoor (the dissected one). Open your own chest as a door: press once to leave one end where
/// you stand, press again somewhere near to leave the other, then walk into either end (or press
/// the key next to one) to step out of the other. The doors close by themselves after a while, or
/// when the key is pressed away from both.
/// </summary>
[Title( "Graft: Body Door" ), Category( "Sump" ), Icon( "door_front" )]
public sealed class BodyDoorGraft : GraftAbility
{
	public override TwistedAbility Kind => TwistedAbility.BodyDoor;
	public override string Title => "Body door";
	public override string HowTo => "press to leave one end, again for the other, then walk through";
	protected override float CooldownTime => CooldownSeconds;

	[Property] public float CooldownSeconds { get; set; } = 10f;
	/// <summary>The two ends can be no further apart than this, in inches.</summary>
	[Property] public float MaxSpan { get; set; } = 800f;
	/// <summary>Seconds the pair stays open.</summary>
	[Property] public float OpenSeconds { get; set; } = 45f;
	/// <summary>Seconds a single end waits for its partner before it closes.</summary>
	[Property] public float LonelySeconds { get; set; } = 25f;
	/// <summary>Walk this close to an end to step through it, in inches.</summary>
	[Property] public float StepRadius { get; set; } = 32f;
	/// <summary>Seconds after stepping through before a door will take you again.</summary>
	[Property] public float StepPause { get; set; } = 0.8f;

	/// <summary>Where the ends are (feet positions), for other modules and the HUD. None, one or two.</summary>
	public IReadOnlyList<Vector3> Ends => _ends;
	public override bool Running => _ends.Count > 0;
	public override string Status => _ends.Count == 1 ? "one end placed" : _ends.Count == 2 ? "open" : base.Status;

	readonly List<Vector3> _ends = new();
	readonly List<GameObject> _marks = new();
	float _closeAt, _stepAt;
	bool _armed;

	protected override void OnPress()
	{
		var player = Player;
		var feet = player.WorldPosition;

		if ( _ends.Count == 2 )
		{
			// Next to an end: step through. Anywhere else: shut them.
			int near = Nearest( feet, StepRadius * 3f );
			if ( near >= 0 ) Step( 1 - near );
			else Close( true );
			return;
		}

		if ( !player.Attached )
		{
			Owner.Note( "Body door: stand on something first." );
			return;
		}
		if ( _ends.Count == 1 && (feet - _ends[0]).Length > MaxSpan )
		{
			Owner.Note( "Body door: too far from the other end. Come closer." );
			return;
		}
		if ( _ends.Count == 1 && (feet - _ends[0]).Length < StepRadius * 2.5f )
		{
			Owner.Note( "Body door: the other end is right here. Go somewhere else first." );
			return;
		}

		var spot = feet + player.Up * 1f;
		_ends.Add( spot );
		_marks.Add( MakeSeam( spot, player.Up, player.WorldRotation.Forward ) );
		Sfx( "graft_door_open" );
		player.Kick( player.Up * -3f );

		if ( _ends.Count == 1 )
		{
			_closeAt = Time.Now + LonelySeconds;
			Sump.Say( "", "I open down the middle. One end of me stays here. It is draughty.", 3.5f );
		}
		else
		{
			_closeAt = Time.Now + OpenSeconds;
			_armed = false; // we are standing in this end: leave it before it counts
			Sump.Say( "", "And the other end here. In one side of me, out the other. Like lunch.", 3.5f );
		}
	}

	int Nearest( Vector3 feet, float within )
	{
		int best = -1;
		float bestDistance = within;
		for ( int i = 0; i < _ends.Count; i++ )
		{
			float d = (feet - _ends[i]).Length;
			if ( d < bestDistance ) { bestDistance = d; best = i; }
		}
		return best;
	}

	void Step( int to )
	{
		var player = Player;
		if ( !player.IsValid() || to < 0 || to >= _ends.Count ) return;
		player.Teleport( _ends[to] );
		player.Kick( Vector3.Up * 4f );
		_armed = false;
		_stepAt = Time.Now;
		Sfx( "graft_door_step" );
	}

	/// <summary>A tall glowing slit standing on the surface, in the misfit's colours.</summary>
	GameObject MakeSeam( Vector3 spot, Vector3 up, Vector3 facing )
	{
		var tint = Color.Lerp( Graft.IsValid() ? Graft.Secondary : Color.White, Color.White, 0.75f );
		var go = Sump.Box( null, "Body Door", spot + up * 22f, new Vector3( 3f, 14f, 44f ), tint, false );
		var flat = facing - up * Vector3.Dot( facing, up );
		if ( flat.Length < 0.01f ) flat = Vector3.Forward - up * Vector3.Dot( Vector3.Forward, up );
		if ( flat.Length < 0.01f ) flat = Vector3.Left;
		go.WorldRotation = Rotation.LookAt( flat.Normal, up );
		return go;
	}

	void Close( bool cooldown )
	{
		bool had = _ends.Count > 0;
		foreach ( var mark in _marks ) if ( mark.IsValid() ) mark.Destroy();
		_marks.Clear();
		_ends.Clear();
		if ( had && cooldown ) { StartCooldown(); Sfx( "graft_door_close", 0.7f ); }
	}

	public override void Cancel() => Close( false );

	protected override void OnUpdate()
	{
		if ( _ends.Count == 0 ) return;
		if ( Time.Now > _closeAt ) { Close( true ); return; }

		// The slits breathe, and flutter as they are about to close.
		float left = _closeAt - Time.Now;
		float flutter = left < 4f ? 0.5f + 0.5f * MathF.Sin( Time.Now * 30f ) : 1f;
		float wide = (10f + MathF.Sin( Time.Now * 5f ) * 4f) * flutter;
		foreach ( var mark in _marks )
			if ( mark.IsValid() ) mark.WorldScale = new Vector3( 3f, MathF.Max( wide, 0.5f ), 44f ) / 50f;

		var player = Player;
		if ( _ends.Count < 2 || !player.IsValid() || Time.Now - _stepAt < StepPause ) return;

		var feet = player.WorldPosition;
		float d0 = (feet - _ends[0]).Length, d1 = (feet - _ends[1]).Length;
		if ( !_armed )
		{
			// Having just come out of one (or placed it), you must walk clear before either takes you.
			if ( MathF.Min( d0, d1 ) > StepRadius * 1.8f ) _armed = true;
			return;
		}
		if ( d0 < StepRadius ) Step( 1 );
		else if ( d1 < StepRadius ) Step( 0 );
	}
}

/// <summary>
/// OnlyWhileWatched (the meme), turned inside out. For a few seconds you stop existing for anyone
/// who is not looking straight at you: <see cref="Patchwork.Unseen"/> is true and the player object
/// carries the tag "sump_unseen". Other modules ask <see cref="Patchwork.HiddenFrom"/> with an
/// eye position and facing before they see or grab the player.
/// </summary>
[Title( "Graft: Unwatched" ), Category( "Sump" ), Icon( "visibility_off" )]
public sealed class UnwatchedGraft : GraftAbility
{
	public override TwistedAbility Kind => TwistedAbility.OnlyWhileWatched;
	public override string Title => "Unwatched";
	public override string HowTo => "for a few seconds, whoever is not facing you cannot see or grab you";
	protected override float CooldownTime => CooldownSeconds;

	[Property] public float CooldownSeconds { get; set; } = 14f;
	/// <summary>Seconds it lasts.</summary>
	[Property] public float Seconds { get; set; } = 5f;

	public override bool Running => _on;
	bool _on;
	float _until;

	protected override void OnPress()
	{
		if ( _on ) return;
		_on = true;
		_until = Time.Now + Seconds;
		Owner.SetUnseen( this, false, true );
		Owner.SetGhost( this, true );
		Sfx( "graft_unwatched" );
		Sump.Say( "", "Nobody is looking. So I am not here. Neither is the dangly bit.", 3f );
	}

	protected override void OnUpdate()
	{
		if ( _on && Time.Now > _until ) { Stop(); StartCooldown(); }
	}

	void Stop()
	{
		if ( !_on ) return;
		_on = false;
		if ( Owner.IsValid() )
		{
			Owner.SetUnseen( this, false, false );
			Owner.SetGhost( this, false );
		}
	}

	public override void Cancel() => Stop();
}

/// <summary>
/// BulletMagnet (shot on a farm). Pick a spot with the camera: for a few seconds loose things and
/// anything thrown or fired bend toward that spot instead of toward you. This component pulls
/// every moving rigid body near the spot; anything with its own idea of a target (a thrown
/// bottle, a human's aim) should read the static <see cref="Patchwork.MagnetPoint"/> and go there
/// instead of at the player while it is set.
/// </summary>
[Title( "Graft: Magnet" ), Category( "Sump" ), Icon( "adjust" )]
public sealed class MagnetGraft : GraftAbility
{
	public override TwistedAbility Kind => TwistedAbility.BulletMagnet;
	public override string Title => "Bullet magnet";
	public override string HowTo => "look at a spot and press: loose and thrown things go there, not at you";
	protected override float CooldownTime => CooldownSeconds;

	[Property] public float CooldownSeconds { get; set; } = 12f;
	/// <summary>How far away the spot can be, in inches.</summary>
	[Property] public float Range { get; set; } = 900f;
	/// <summary>Things within this of the spot are pulled, in inches.</summary>
	[Property] public float Radius { get; set; } = 650f;
	/// <summary>How hard, in inches per second per second.</summary>
	[Property] public float Pull { get; set; } = 1400f;
	/// <summary>Pulled things are not sped up past this, in inches per second.</summary>
	[Property] public float MaxSpeed { get; set; } = 900f;
	/// <summary>Seconds it lasts.</summary>
	[Property] public float Seconds { get; set; } = 6f;

	public override bool Running => _on;
	bool _on;
	float _until, _nextScan;
	Vector3 _point;
	GameObject _mark;
	readonly List<Rigidbody> _pulled = new();

	protected override void OnPress()
	{
		if ( _on ) { Stop(); StartCooldown(); return; }

		_point = Owner.AimPoint( Range, out _, out var normal ) + normal * 14f;
		_on = true;
		_until = Time.Now + Seconds;
		_nextScan = 0f;
		Patchwork.MagnetPoint = _point;
		Patchwork.MagnetRadius = Radius;

		var tint = Graft.IsValid() ? Color.Lerp( Graft.Primary, Color.White, 0.4f ) : Color.White;
		_mark = Sump.Ball( null, "Magnet Point", _point, new Vector3( 7f ), tint );
		Sfx( "graft_magnet" );
		Sump.Say( "", "Everything that flies was always coming for me. Now it goes over there.", 3.5f );
	}

	protected override void OnFixedUpdate()
	{
		if ( !_on ) return;
		if ( Time.Now > _until ) { Stop(); StartCooldown(); return; }

		// Somebody else's magnet may have taken the point over; keep ours where we put it.
		Patchwork.MagnetPoint = _point;

		if ( Time.Now >= _nextScan )
		{
			_nextScan = Time.Now + 0.2f;
			_pulled.Clear();
			var player = Player;
			foreach ( var body in Scene.GetAllComponents<Rigidbody>() )
			{
				if ( !body.IsValid() || !body.Active || !body.MotionEnabled ) continue;
				if ( (body.WorldPosition - _point).LengthSquared > Radius * Radius ) continue;
				if ( player.IsValid() && IsUnder( body.GameObject, player.GameObject ) ) continue;
				_pulled.Add( body );
				if ( _pulled.Count >= 64 ) break;
			}
		}

		float dt = Time.Delta;
		foreach ( var body in _pulled )
		{
			if ( !body.IsValid() || !body.MotionEnabled ) continue;
			var to = _point - body.WorldPosition;
			float distance = to.Length;
			if ( distance < 10f ) { body.Velocity *= 0.9f; continue; } // arrived: it hangs there
			var velocity = body.Velocity + to / distance * (Pull * dt);
			if ( velocity.Length > MaxSpeed ) velocity = velocity.Normal * MaxSpeed;
			body.Velocity = velocity;
		}
	}

	protected override void OnUpdate()
	{
		if ( !_on || !_mark.IsValid() ) return;
		float pulse = 7f + MathF.Sin( Time.Now * 9f ) * 2.5f;
		_mark.WorldScale = new Vector3( pulse ) / 32f;
	}

	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;
	}

	void Stop()
	{
		if ( !_on ) return;
		_on = false;
		_pulled.Clear();
		if ( _mark.IsValid() ) _mark.Destroy();
		_mark = null;
		if ( Patchwork.MagnetPoint is { } current && (current - _point).LengthSquared < 1f ) Patchwork.MagnetPoint = null;
	}

	public override void Cancel() => Stop();
}

/// <summary>
/// PriceTag (worshipped, then sold). Look at a human or a loose object and press: a price is hung
/// on it and it holds still, obeying the price, for a few seconds.
/// What this relies on, in order:
///   1. the object gets the tag "sump_priced" (any module can check it and hold still);
///   2. every <see cref="IPriceable"/> component on it or under it is told (the polite hook);
///   3. its Rigidbody, if it has one, is stopped and has MotionEnabled switched off;
///   4. a CrowdPerson, FatGuy or Misfit component on it is disabled for the duration (none of them
///      do anything on being disabled, so they simply stop thinking) and enabled again after.
/// A thing counts as priceable if it, or something above it, has a Rigidbody, an IPriceable, one
/// of those three components, or one of the tags "crowd", "fatguy", "misfit", "sump_body", "sump_human".
/// </summary>
[Title( "Graft: Price Tag" ), Category( "Sump" ), Icon( "sell" )]
public sealed class PriceTagGraft : GraftAbility
{
	public override TwistedAbility Kind => TwistedAbility.PriceTag;
	public override string Title => "Price tag";
	public override string HowTo => "look at someone or something and press: it freezes, obeying its price";
	protected override float CooldownTime => CooldownSeconds;

	[Property] public float CooldownSeconds { get; set; } = 14f;
	/// <summary>How far away the thing can be, in inches.</summary>
	[Property] public float Range { get; set; } = 520f;
	/// <summary>Seconds it stays frozen.</summary>
	[Property] public float Seconds { get; set; } = 6f;
	/// <summary>Things with no collider (misfits) are picked if the camera points within this of them (cosine).</summary>
	[Property, Range( 0.8f, 1f )] public float AimDot { get; set; } = 0.965f;

	/// <summary>What is frozen right now, or null.</summary>
	public GameObject Target => _on ? _target : null;
	public override bool Running => _on;

	static readonly string[] BodyTags = { "crowd", "fatguy", "misfit", "sump_body", "sump_human" };

	bool _on, _hadMotion;
	float _until;
	GameObject _target, _label;
	Rigidbody _body;
	readonly List<Component> _stopped = new();

	protected override void OnPress()
	{
		if ( _on ) return;

		var target = FindTarget();
		if ( !target.IsValid() )
		{
			Owner.Note( "Price tag: nothing here has a price. Look at someone, or something loose." );
			return;
		}

		_on = true;
		_target = target;
		_until = Time.Now + Seconds;
		target.Tags.Add( Patchwork.PricedTag );

		foreach ( var hook in target.Components.GetAll<IPriceable>( FindMode.EverythingInSelfAndDescendants ) )
		{
			try { hook.OnPriced( true, Seconds ); } catch ( Exception e ) { Log.Warning( $"Price tag hook failed: {e.Message}" ); }
		}

		_body = target.Components.Get<Rigidbody>();
		if ( _body.IsValid() )
		{
			_hadMotion = _body.MotionEnabled;
			_body.Velocity = Vector3.Zero;
			_body.AngularVelocity = Vector3.Zero;
			_body.MotionEnabled = false;
		}

		Stop( target.Components.Get<CrowdPerson>() );
		Stop( target.Components.Get<FatGuy>() );
		Stop( target.Components.Get<Misfit>() );

		// The tag itself: a paper label on a string, bobbing over its head.
		_label = Sump.Box( null, "Price Tag", target.WorldPosition + Vector3.Up * 84f, new Vector3( 1f, 12f, 8f ), new Color( 0.95f, 0.92f, 0.8f ), false );
		var colour = Graft.IsValid() ? Graft.Primary : Color.Red;
		Sump.Box( _label, "Price", _label.WorldPosition + Vector3.Down * 0.5f, new Vector3( 1.4f, 8f, 3f ), colour, false );

		Sfx( "graft_price" );
		Sump.Say( MisfitName, $"That one is {Price( target )}. It stays on the shelf until somebody pays.", 3.5f );
	}

	void Stop( Component brain )
	{
		if ( !brain.IsValid() || !brain.Enabled ) return;
		brain.Enabled = false;
		_stopped.Add( brain );
	}

	/// <summary>A price that is always the same for the same thing.</summary>
	static string Price( GameObject go )
	{
		int hash = 17;
		foreach ( char c in go.Name ?? "" ) hash = unchecked(hash * 31 + c);
		hash = unchecked(hash * 31 + go.Id.GetHashCode());
		int dollars = Math.Abs( hash % 40 );
		return dollars == 0 ? "99 cents" : $"${dollars}.99";
	}

	GameObject FindTarget()
	{
		var player = Player;

		// What the camera is pointing at, if it has a collider.
		Owner.AimPoint( Range, out var hit, out _ );
		var found = Priceable( hit, player );
		if ( found.IsValid() ) return found;

		// Misfits have no colliders: take whoever is closest to the middle of the view.
		if ( !Owner.AimRay( out var eye, out var forward ) ) return null;
		GameObject best = null;
		float bestDot = AimDot;

		void Consider( GameObject go )
		{
			if ( !go.IsValid() || !go.Active ) return;
			var to = go.WorldPosition + Vector3.Up * 30f - eye;
			if ( (go.WorldPosition - player.WorldPosition).Length > Range ) return;
			float dot = Vector3.Dot( forward, to.Normal );
			if ( dot <= bestDot ) return;
			var candidate = Priceable( go, player );
			if ( !candidate.IsValid() ) return;
			bestDot = dot;
			best = candidate;
		}

		foreach ( var misfit in Misfit.All ) if ( misfit.IsValid() ) Consider( misfit.GameObject );
		foreach ( var tag in BodyTags )
		{
			int looked = 0;
			foreach ( var go in Scene.FindAllWithTag( tag ) )
			{
				if ( ++looked > 200 ) break;
				Consider( go );
			}
		}
		return best;
	}

	/// <summary>The object to freeze for something that was hit: itself or the nearest thing above it that can be priced.</summary>
	static GameObject Priceable( GameObject go, ReptileController player )
	{
		for ( int i = 0; go is not null && go.IsValid() && i < 16; i++ )
		{
			if ( go is Scene ) return null;
			if ( player.IsValid() && go == player.GameObject ) return null;
			if ( go.Tags.Has( Patchwork.PricedTag ) ) return null; // one price at a time

			bool yes = go.Components.Get<Rigidbody>().IsValid()
				|| go.Components.Get<IPriceable>() is not null
				|| go.Components.Get<CrowdPerson>().IsValid()
				|| go.Components.Get<FatGuy>().IsValid()
				|| go.Components.Get<Misfit>().IsValid();
			if ( !yes )
				foreach ( var tag in BodyTags ) if ( go.Tags.Has( tag ) ) { yes = true; break; }
			if ( yes ) return go;
			go = go.Parent;
		}
		return null;
	}

	protected override void OnUpdate()
	{
		if ( !_on ) return;
		if ( !_target.IsValid() || Time.Now > _until ) { Release(); StartCooldown(); return; }

		if ( _label.IsValid() )
		{
			_label.WorldPosition = _target.WorldPosition + Vector3.Up * (84f + MathF.Sin( Time.Now * 3f ) * 2f);
			_label.WorldRotation = Rotation.FromYaw( Time.Now * 70f ) * Rotation.FromRoll( MathF.Sin( Time.Now * 2.3f ) * 12f );
		}

		// Something may have woken its body up again (a shove from the crowd): hold it.
		if ( _body.IsValid() && _body.MotionEnabled ) _body.MotionEnabled = false;
	}

	void Release()
	{
		if ( !_on ) return;
		_on = false;

		if ( _label.IsValid() ) _label.Destroy();
		_label = null;

		foreach ( var brain in _stopped ) if ( brain.IsValid() ) brain.Enabled = true;
		_stopped.Clear();

		if ( _body.IsValid() ) _body.MotionEnabled = _hadMotion;
		_body = null;

		if ( _target.IsValid() )
		{
			_target.Tags.Remove( Patchwork.PricedTag );
			foreach ( var hook in _target.Components.GetAll<IPriceable>( FindMode.EverythingInSelfAndDescendants ) )
			{
				try { hook.OnPriced( false, 0f ); } catch ( Exception ) { }
			}
		}
		_target = null;
	}

	public override void Cancel() => Release();
}

/// <summary>
/// ToyStillness (adopted, then forgotten). Go toy-small and perfectly still: the lizard's body
/// shrinks, <see cref="Patchwork.Unseen"/> is true and the player carries the tag "sump_unseen",
/// and nobody notices a toy. It lasts until you move (or press the key again).
/// </summary>
[Title( "Graft: Toy" ), Category( "Sump" ), Icon( "toys" )]
public sealed class ToyGraft : GraftAbility
{
	public override TwistedAbility Kind => TwistedAbility.ToyStillness;
	public override string Title => "Toy stillness";
	public override string HowTo => "go toy-small and still: you are ignored until you move";
	protected override float CooldownTime => CooldownSeconds;

	[Property] public float CooldownSeconds { get; set; } = 8f;
	/// <summary>How small the lizard goes, against its full size.</summary>
	[Property, Range( 0.1f, 1f )] public float ToyScale { get; set; } = 0.35f;
	/// <summary>Seconds after pressing during which moving does not break it yet (time to come to a stop).</summary>
	[Property] public float SettleSeconds { get; set; } = 0.7f;
	/// <summary>Moving faster than this breaks it, in inches per second.</summary>
	[Property] public float BreakSpeed { get; set; } = 35f;
	/// <summary>The longest it can last, in seconds.</summary>
	[Property] public float MaxSeconds { get; set; } = 30f;

	public override bool Running => _on;
	bool _on;
	float _since;

	protected override void OnPress()
	{
		if ( _on ) { Stop(); StartCooldown(); return; }

		_on = true;
		_since = 0f;
		Owner.SetToy( this, ToyScale );
		Owner.SetUnseen( this, true, true );
		Sfx( "graft_toy" );
		Sump.Say( "", "Small. Still. Something left on a shelf. Nobody looks at a toy. Not even an anatomically ambitious one.", 3.5f );
	}

	protected override void OnUpdate()
	{
		if ( !_on ) return;
		_since += Time.Delta;

		var player = Player;
		bool moved = player.IsValid() && _since > SettleSeconds
			&& (player.Velocity.Length > BreakSpeed || (!player.InputLocked && Input.AnalogMove.Length > 0.3f));
		if ( moved || _since > MaxSeconds ) { Stop(); StartCooldown(); }
	}

	void Stop()
	{
		if ( !_on ) return;
		_on = false;
		if ( Owner.IsValid() )
		{
			Owner.SetToy( this, 1f );
			Owner.SetUnseen( this, true, false );
		}
	}

	public override void Cancel() => Stop();
}