Rampage/Weapon/DongWeapon.cs

The main partial of the Rampage giant's weapon component. Holds the size/spring growth, the Hint enum, input reading for Attack1/Attack2 (tap, hold, both), and the per-frame sequencing that dispatches to the dong, balls and joint moves defined in its sibling partial files. Also carries hit-stop and camera pull bookkeeping and the engage/release lifecycle that puts the lizard back as it was.

using System;
using System.Collections.Generic;

/// <summary>What the player's hands are doing with the weapon right now, for the HUD's control hints.</summary>
[Flags]
public enum WeaponHint
{
	None = 0,
	/// <summary>Left held: the mouse is driving the dong.</summary>
	Aim = 1,
	/// <summary>Left tapped: the whip combo.</summary>
	Combo = 2,
	/// <summary>The helicopter.</summary>
	Spin = 4,
	/// <summary>Right tapped: the flail.</summary>
	Flail = 8,
	/// <summary>Right held: the slingshot.</summary>
	Sling = 16,
	/// <summary>Both held: charging, or the mega-swing.</summary>
	Charge = 32,
	/// <summary>The clap is on offer (right click now), or happening.</summary>
	Clap = 64,
	/// <summary>In the air: ground pound and sit-down.</summary>
	Air = 128,
}

/// <summary>
/// The Rampage's weapons: the giant's own dong, swung as a floppy cartoon club, and the balls, a
/// wrecking ball on an elastic. Slapstick only. They are two separate weapons on two separate
/// buttons, and there are several quite different ways to throw them about, all there at once:
///
///  - AIM AND WHIP (hold left): the mouse stops turning the camera and drives the dong like a
///    held rope. Flick it to crack it, drag it to sweep, let go and it follows through.
///  - HELICOPTER (hold left and Run, or circle the mouse): it winds up into a spin whose speed
///    is kept and built on, lifts the giant at full speed, and is spent in one release.
///  - COMBO (tap left): left whip, right whip, overhead slam. Right click after the second is
///    THE CLAP: both weapons arrive from either side and what is between them goes straight up.
///  - FLAIL (tap right): the balls, once round on a short chain. Slow, huge, bounces off buildings.
///  - SLINGSHOT (hold right): drawn back between the legs, aimed with the camera, fired out and
///    snapped back. It hits on the way out and on the way back.
///  - MEGA-SWING (hold both): charge, let go, and the whole body goes into one swing. A full one
///    clears a street; a missed one puts the giant on its backside.
///  - In the air: left is the GROUND POUND, right is the SIT-DOWN.
///
/// Nothing here is an animation. Both weapons are the rig's simulated chain (see
/// <see cref="LizardRig.WeaponMode"/>): this component only says which way each is being thrown and
/// how hard, moment by moment, and the weight follows, lags, whips through and overshoots. What
/// is hit is read back from where the weight really went, so damage and knock come from the real
/// speed of the part that connected (the tip is fastest), and the weight pulls back on the giant.
///
/// It is in several files: this one (what there is, life, size, input), DongWeapon.Dong.cs (aim,
/// helicopter, combo), DongWeapon.Balls.cs (flail, slingshot), DongWeapon.Mega.cs (the moves that
/// take both: mega-swing, clap, ground pound, sit-down, the stumble), DongWeapon.Hits.cs (what
/// the weight hits, catches on and carries) and DongWeapon.Show.cs (streaks, markers, furrows, the
/// first-minute lessons).
///
/// Sizes come from <see cref="RampageGiant"/>; how hard it hits is one scale shared with the
/// town (<see cref="Rampage.Might"/>). Outside the Rampage it does nothing, and everything it
/// changes on the lizard is put back by <see cref="Release"/>.
/// </summary>
[Title( "Dong Weapon" ), Category( "Rampage" ), Icon( "sports_cricket" )]
public sealed partial class DongWeapon : Component
{
	public static DongWeapon Current { get; private set; }

	enum DongMode { Carried, Aim, Follow, Whip, Spin, Release }
	enum BallMode { Hang, Draw, Flail, Snap, Out, Back }
	enum Joint { None, Charge, Mega, Clap, Pound, SitDown, Stumble }

	// ---- For the HUD, the riders and the other modules -------------------------------------------

	/// <summary>The headline attack in progress, in capitals ("HELICOPTER", "MEGA-SWING"...), or empty.</summary>
	public string AttackName { get; private set; } = "";
	/// <summary>What each weapon is doing, in a word or two.</summary>
	public string DongState { get; private set; } = "DRAGGING";
	public string BallsState { get; private set; } = "HANGING";
	/// <summary>How charged the mega-swing is, 0 to 1.</summary>
	public float Charge01 { get; private set; }
	/// <summary>Which hit of the whip combo this is (1 to 3), 0 when not in one.</summary>
	public int Combo { get; private set; }
	/// <summary>Current length of the dong in inches.</summary>
	public float Reach { get; private set; }
	/// <summary>How fast the tip is going, in inches a second, and whether that is past the speed at which it cracks.</summary>
	public float TipSpeed { get; private set; }
	public bool TipCracking => TipSpeed >= CrackSpeed * G;
	/// <summary>The helicopter: how wound up it is (0 to 1) and how fast it is going round (turns a minute).</summary>
	public float Spin01 => SpinMax > 0f ? Math.Clamp( MathF.Abs( _spinRate ) / (SpinMax / Slow), 0f, 1f ) : 0f;
	public float SpinRpm => MathF.Abs( _spinRate ) / 6f;
	/// <summary>How far back the slingshot is drawn, 0 to 1.</summary>
	public float Draw01 { get; private set; }
	/// <summary>What is hooked on the end of the dong ("CAR"), or empty.</summary>
	public string HookedName { get; private set; } = "";
	/// <summary>True while any attack is in progress.</summary>
	public bool Swinging => _joint != Joint.None || _dong != DongMode.Carried || _balls != BallMode.Hang;
	/// <summary>True while the giant is on its backside after a missed mega-swing.</summary>
	public bool Stumbling => _joint == Joint.Stumble;
	/// <summary>What the hands are doing now, for the control hints.</summary>
	public WeaponHint Lit { get; private set; }
	/// <summary>The first-minute lesson showing now (empty when they are done).</summary>
	public string Lesson { get; private set; } = "";
	/// <summary>How heavy the weapon is to throw about: 1 at the start, growing with its size.</summary>
	public float Heft => MathF.Sqrt( MathF.Max( Rampage.WeaponScale, 0.1f ) );

	/// <summary>
	/// Something worth reacting to has happened, by name, with a size from 0 to 1: "crack", "slam",
	/// "charge", "mega", "miss", "spin", "spin_release", "flail", "flail_bounce", "sling", "sling_back",
	/// "clap", "pound", "sitdown", "hook", "fling", "snag", "tear". The riders listen.
	/// </summary>
	public event Action<string, float> Did;

	// ---- Size ------------------------------------------------------------------------------------

	/// <summary>Length at the start, in inches at the lizard's ordinary size (the giant's size multiplies it): about as long as it is tall.</summary>
	[Property, Group( "Size" )] public float BaseReach { get; set; } = 40f;
	/// <summary>Reach grows with Rampage.WeaponScale to this power (the giant itself grows too).</summary>
	[Property, Group( "Size" )] public float ReachPower { get; set; } = 0.6f;
	/// <summary>Size of the balls at the start, as a multiple of their natural size, and how fast they grow with the weapon.</summary>
	[Property, Group( "Size" )] public float SackBaseScale { get; set; } = 2f;
	[Property, Group( "Size" )] public float SackGrowth { get; set; } = 0.5f;
	/// <summary>Growing is a spring: it overshoots and wobbles into its new size.</summary>
	[Property, Group( "Size" )] public float GrowSpring { get; set; } = 60f;
	[Property, Group( "Size" )] public float GrowDamping { get; set; } = 5f;
	/// <summary>Extra shove a new tier gives the growth, as a share of the new length per second.</summary>
	[Property, Group( "Size" )] public float GrowKick { get; set; } = 3f;
	/// <summary>How much slower every swing gets as it grows heavier (0: never slower).</summary>
	[Property, Group( "Size" )] public float SlowWithSize { get; set; } = 0.3f;
	/// <summary>Seconds after a tier-up before this component's own silly line goes on the banner.</summary>
	[Property, Group( "Size" )] public float AnnounceDelay { get; set; } = 2.4f;

	// ---- The weight ------------------------------------------------------------------------------

	/// <summary>The chain's gravity against the rig's own: with a chain this long, lower is slower and heavier.</summary>
	[Property, Group( "Weight" )] public float GravityScale { get; set; } = 1.15f;
	/// <summary>How hard it is pulled to trail behind the body when nothing is going on (low: it mostly just drags).</summary>
	[Property, Group( "Weight" )] public float IdleStrength { get; set; } = 5f;
	/// <summary>
	/// How much the weight being thrown pulls the giant after it: inches a second of shove per
	/// thousand inches a second of tip speed (at the giant's starting size), each second.
	/// </summary>
	[Property, Group( "Weight" )] public float PullPerSpeed { get; set; } = 260f;
	/// <summary>The most any one shove may move the giant, at the lizard's ordinary size, so the weight is funny, never unplayable.</summary>
	[Property, Group( "Weight" )] public float MaxShove { get; set; } = 150f;
	/// <summary>How far the body twists toward the weapon while it is being thrown, in degrees at most.</summary>
	[Property, Group( "Weight" )] public float BodyTwist { get; set; } = 34f;

	// ---- Camera ----------------------------------------------------------------------------------

	/// <summary>Camera distance and height added per inch of weapon.</summary>
	[Property, Group( "Camera" )] public float CameraPerReach { get; set; } = 0.6f;
	[Property, Group( "Camera" )] public float CameraLiftPerReach { get; set; } = 0.1f;
	/// <summary>Camera pull-back at full charge, as a multiple of the reach.</summary>
	[Property, Group( "Camera" )] public float ChargePullBack { get; set; } = 1.4f;

	// ---- Hits ------------------------------------------------------------------------------------

	/// <summary>A part of the weapon moving slower than this does not hit: inches a second at the lizard's ordinary size (it grows with the root of the giant's size, as its walking speed does).</summary>
	[Property, Group( "Hits" )] public float MinHitSpeed { get; set; } = 160f;
	/// <summary>
	/// Damage per 1000 inches a second of the part that hit, measured at the lizard's ordinary size
	/// (so the giant's longer, faster tip does not count twice), times the attack's power and
	/// <see cref="Rampage.Might"/>. At 700 an honest whip (about 500) is a car.
	/// </summary>
	[Property, Group( "Hits" )] public float DamagePerSpeed { get; set; } = 850f;
	/// <summary>Share of the weapon's real velocity the target is thrown with, the share of its speed added straight up so things FLY, and a floor for that.</summary>
	[Property, Group( "Hits" )] public float KnockShare { get; set; } = 1.05f;
	[Property, Group( "Hits" )] public float UpShare { get; set; } = 0.5f;
	[Property, Group( "Hits" )] public float UpBase { get; set; } = 340f;
	[Property, Group( "Hits" )] public float MaxKnock { get; set; } = 6500f;
	/// <summary>Seconds before the same thing can be hit again, so one swing hits it once.</summary>
	[Property, Group( "Hits" )] public float HitCooldown { get; set; } = 0.55f;
	/// <summary>Power of a hit from the weapon just being dragged or flopping about, next to a whip's 1.</summary>
	[Property, Group( "Hits" )] public float DragPower { get; set; } = 0.3f;
	/// <summary>
	/// The giant has to be walking this fast (as a share of its walking speed), falling this fast or
	/// turning this fast (degrees a second) for a weapon it is only carrying to hit anything.
	/// </summary>
	[Property, Group( "Hits" )] public float DragFromPace { get; set; } = 0.4f;
	[Property, Group( "Hits" )] public float DragFromFall { get; set; } = 320f;
	[Property, Group( "Hits" )] public float DragFromTurn { get; set; } = 90f;
	/// <summary>Damage in one hit that gives the camera a full shake.</summary>
	[Property, Group( "Hits" )] public float ShakeDamage { get; set; } = 650f;

	// ---- Weight: the pace of the whole thing, and what a hit feels like ----------------------------

	/// <summary>Every swing takes this many times as long (1: as quick as it was). Damage does not drop with it.</summary>
	[Property, Group( "Feel" ), Range( 0.6f, 2f )] public float SwingWeight { get; set; } = 1.2f;
	/// <summary>The giant's own walking pace while the weapon is out (1: unchanged).</summary>
	[Property, Group( "Feel" ), Range( 0.5f, 1.2f )] public float GiantPace { get; set; } = 0.9f;
	/// <summary>A hit that shakes the camera this hard or harder (0..1) also stops the clock for a moment.</summary>
	[Property, Group( "Feel" ), Range( 0f, 1f )] public float HitStopFrom { get; set; } = 0.5f;
	/// <summary>Real seconds the clock is held for the hardest hit (about half that for one just hard enough). 0: no hit-stop.</summary>
	[Property, Group( "Feel" )] public float HitStopSeconds { get; set; } = 0.09f;
	/// <summary>How slowly time runs during a hit-stop.</summary>
	[Property, Group( "Feel" ), Range( 0.02f, 1f )] public float HitStopScale { get; set; } = 0.05f;
	/// <summary>Real seconds after one hit-stop before there can be another, so each one registers.</summary>
	[Property, Group( "Feel" )] public float HitStopGap { get; set; } = 0.3f;
	/// <summary>Seconds between the heavy thuds laid under a hard hit.</summary>
	[Property, Group( "Feel" )] public float ThudGap { get; set; } = 0.22f;
	[Property, Group( "Hits" )] public float SoundVolume { get; set; } = 1f;

	ReptileController _controller;
	LizardRig _rig;
	LizardAttack _bite;
	bool _engaged, _biteWas;
	string _aimAction;

	// Size.
	float _reach, _reachSpeed, _spurt = 10f, _announceAt;
	int _tier;

	// What each weapon, and both together, are doing.
	DongMode _dong;
	BallMode _balls;
	Joint _joint;
	float _dongT, _ballT, _jointT;
	float _power = 1f, _knock = 1f, _ballPower = 1f, _ballKnock = 1f;
	float _restUntil, _ballRestUntil;
	bool _was1, _was2;
	float _bothHeld;
	float _hop, _speedFactor = 1f;
	float _bodySpin;           // extra turn of the whole model, in degrees (the helicopter, the mega-swing, the stumble)

	float Slow => (1f + (Heft - 1f) * SlowWithSize) * Math.Clamp( SwingWeight, 0.6f, 2f );
	/// <summary>The giant's size (1 with no giant).</summary>
	float G => MathF.Max( RampageGiant.ScaleNow, 1f );
	/// <summary>How much faster than at the lizard's ordinary size and the starting length the tip moves for the same swing.</summary>
	float SizeSpeed => G * MathF.Max( MathF.Max( _reach, 1f ) / MathF.Max( BaseReach * G, 1f ) / Slow, 1f );

	Action<Vector3, float> _onDongLanded, _onSackLanded;
	bool CanAct => _controller.IsValid() && !_controller.InputLocked && !_controller.IsPinned && _controller.MouseCaptured
		&& _controller.SinceRecapture > 0.2f && Rampage.Started;

	static readonly string[] TierLines =
	{
		"",
		"IT GREW. NOBODY ASKED IT TO. NOBODY EVER DOES.",
		"NOW LONGER THAN THE QUEUE AT THE POST OFFICE.",
		"PLANNING PERMISSION: DENIED. IT GREW ANYWAY.",
		"IT HAS BROKEN THE SOUND BARRIER. AND A BAKERY.",
		"AIR TRAFFIC CONTROL HAS QUESTIONS. RUDE ONES.",
		"IT NOW HAS ITS OWN POSTCODE, AND A DRAUGHT.",
		"CARTOGRAPHERS ARE REDRAWING THE MAP AROUND IT. BLUSHING.",
		"VISIBLE FROM ORBIT. THE ASTRONAUTS WAVED, THEN LOOKED AWAY.",
		"PHYSICS HAS FILED A FORMAL COMPLAINT. SO HAS DECENCY.",
		"THE HORIZON WOULD LIKE IT TO STOP.",
	};

	// ---- Life -----------------------------------------------------------------------------------

	protected override void OnUpdate()
	{
		if ( _stopUntil > 0f && RealTime.Now >= _stopUntil ) EndHitStop();
		if ( !Ready() ) { Release(); return; }
		if ( !_engaged ) Engage();

		// The old bite shares Attack1; it is put away (once it has finished) while the weapon is out.
		if ( _bite.IsValid() && _bite.Enabled && _bite.Phase <= 0f ) _bite.Enabled = false;

		float dt = MathF.Min( Time.Delta, 0.05f );
		if ( dt <= 0f ) return;

		Grow( dt );
		ReadInput( dt );
		Advance( dt );
		// The look is only ever held by an aim or a spin of the dong, with the button down and the lizard free to act.
		if ( _holdLook && (_joint != Joint.None || (_dong != DongMode.Aim && _dong != DongMode.Spin) || !CanAct) ) _holdLook = false;
		MarchCrack();
		Carry( dt );
		WatchBody( dt );
		Show( dt );
		Teach( dt );
	}

	/// <summary>
	/// While the mouse is driving the dong it must not also turn the camera: the controller is told
	/// to leave the look alone (<see cref="ReptileController.LookLocked"/>). Every way out of an aim
	/// or a spin sets this false, and so does <see cref="Release"/>.
	/// </summary>
	bool _holdLook
	{
		get => _holdLookNow;
		set
		{
			_holdLookNow = value;
			if ( _controller.IsValid() ) _controller.LookLocked = value;
		}
	}
	bool _holdLookNow;

	// ---- For the results ----
	/// <summary>The fastest the tip has gone in a swing this run, in inches a second.</summary>
	public float BestTipSpeed { get; private set; }
	public int Cracks { get; private set; }
	/// <summary>Mega-swings that connected, and ones that did not.</summary>
	public int Megas { get; private set; }
	public int Misses { get; private set; }
	/// <summary>Things flung off the end.</summary>
	public int Flung { get; private set; }

	/// <summary>
	/// Whether anything is throwing the weapon about: an attack, or the giant itself walking,
	/// falling or turning sharply (then it is dragged, and that hits too). Standing still with
	/// nothing going on, the chain may still twitch and stretch, a growth spurt above all, and
	/// that must not count as a blow: the weapon would score by itself.
	/// </summary>
	void WatchBody( float dt )
	{
		float yaw = _controller.WorldRotation.Yaw();
		float turned = (yaw - _bodyYaw) % 360f;
		if ( turned > 180f ) turned -= 360f;
		if ( turned < -180f ) turned += 360f;
		_bodyYaw = yaw;

		var velocity = _controller.Velocity;
		bool thrown = Swinging || velocity.WithZ( 0f ).Length > _controller.Speed * DragFromPace || MathF.Abs( velocity.z ) > DragFromFall
			|| MathF.Abs( turned ) > DragFromTurn * dt;
		if ( thrown ) _liveUntil = Time.Now + 0.6f;

		var tip = _rig.DongTipVelocity;
		TipSpeed = tip.Length;
		if ( Swinging && TipSpeed > BestTipSpeed && TipSpeed < 60000f ) BestTipSpeed = TipSpeed;
	}

	/// <summary>True while the weapon is being swung or dragged (and for a moment after, for the follow-through).</summary>
	bool Live => Time.Now < _liveUntil;
	float _bodyYaw, _liveUntil;

	protected override void OnFixedUpdate()
	{
		if ( !_engaged || !Ready() ) return;
		float dt = Time.Delta;

		if ( _controller.Attached ) _hover = HoverSeconds * GiantRiders.HoverBonus;
		else _fallSpeed = MathF.Max( _fallSpeed, -_controller.Velocity.z );

		// Helicopter: at full speed the spin takes most of the giant's weight for a few seconds.
		if ( _dong == DongMode.Spin && _joint == Joint.None && !_controller.Attached && Spin01 >= HoverAt && _hover > 0f )
		{
			_hover -= dt;
			if ( _controller.Velocity.z < HoverRise ) _controller.Lunge( Vector3.Up, _controller.Gravity * HoverLift * dt );
		}

		if ( _joint == Joint.SitDown ) WatchSitDown( dt );

		SweepChain();
		SweepSack();
	}

	protected override void OnDisabled() => Release();
	protected override void OnDestroy() => Release();

	bool Ready()
	{
		if ( !Rampage.Running ) return false;
		if ( !_controller.IsValid() ) _controller = Components.Get<ReptileController>() ?? Rampage.Player;
		if ( !_controller.IsValid() ) return false;
		var rig = _controller.Rig;
		if ( !rig.IsValid() ) return false;
		if ( rig != _rig )
		{
			_rig = rig;
			_lastPoints = Array.Empty<Vector3>();
			_hasSack = false;
		}
		return true;
	}

	/// <summary>Takes the weapon out: remembers everything it is about to change.</summary>
	void Engage()
	{
		_engaged = true;
		Current = this;
		_aimAction = _controller.AimAction;
		_controller.AimAction = "";   // Attack2 is the balls here, not the hand-aimed grip
		_bite = _controller.Components.Get<LizardAttack>();
		_biteWas = _bite.IsValid() && _bite.Enabled;

		_tier = Rampage.Tier;
		_reach = WantedReach();
		_reachSpeed = 0f;
		_hover = HoverSeconds;
		ResetMoves();
		_speedFactor = 1f;
		_lesson = 0;
		_lessonT = 0f;
	}

	void ResetMoves()
	{
		_dong = DongMode.Carried;
		_balls = BallMode.Hang;
		_joint = Joint.None;
		_combo = 0;
		_spinRate = 0f;
		_bodySpin = 0f;
		_holdLook = false;
		_was1 = _was2 = false;
		_bothHeld = 0f;
		Draw01 = 0f;
		Charge01 = 0f;
		Combo = 0;
		AttackName = "";
		Lit = WeaponHint.None;
	}

	/// <summary>Puts the weapon away and everything back as it was.</summary>
	void Release()
	{
		if ( !_engaged ) return;
		_engaged = false;

		Unhook( false );
		if ( _rig.IsValid() )
		{
			_rig.FreeDong();
			_rig.WeaponMode = false;
			_rig.DongScale = 1f; _rig.SackScale = 1f; _rig.SackChain = 0f;
			_rig.DongDriveStrength = 0f; _rig.SackDriveStrength = 0f;
			_rig.BodyThrow = default; _rig.SpinYaw = 0f; _rig.BodyOffset = Vector3.Zero;
			_rig.DongLanded = null; _rig.SackLanded = null;
			_rig.WeaponGravityScale = 1f; _rig.DongTipLoad = 0f;
		}
		if ( _controller.IsValid() )
		{
			_controller.SetSpeedFactor( "weapon", 1f );
			_controller.AimAction = _aimAction;
			_controller.LookLocked = false;
		}
		var giant = RampageGiant.Current;
		if ( giant.IsValid() ) { giant.CameraPull = 0f; giant.CameraLift = 0f; }
		if ( _bite.IsValid() ) _bite.Enabled = _biteWas;
		StopCharge();
		EndTimeDip();
		EndHitStop();
		ClearShow();

		ResetMoves();
		_crackLeft = 0;
		_speedFactor = 1f;
		Lesson = "";
		DongState = "DRAGGING";
		BallsState = "HANGING";
		_lastPoints = Array.Empty<Vector3>();
		_hasSack = false;
		_cool.Clear();
		Did = null;
		if ( Current == this ) Current = null;
	}

	/// <summary>Tells whoever is listening (the riders, the lessons) that something happened.</summary>
	void Tell( string what, float amount = 1f )
	{
		Learned( what );
		switch ( what )
		{
			case "crack": Cracks++; break;
			case "mega": Megas++; break;
			case "miss": Misses++; Megas = Math.Max( Megas - 1, 0 ); break;   // it was counted as a swing before it was known to have missed
			case "fling": Flung++; break;
		}
		Did?.Invoke( what, amount );
	}

	// ---- Size -----------------------------------------------------------------------------------

	float WantedReach() => BaseReach * G * MathF.Pow( MathF.Max( Rampage.WeaponScale, 0.1f ), ReachPower );

	/// <summary>
	/// The weapon follows the Rampage's weapon scale (and the giant's size) on a spring, so growth
	/// overshoots and wobbles. A new tier is a growth spurt: a shove on the spring, a throb, a shake
	/// and a silly line.
	/// </summary>
	void Grow( float dt )
	{
		float want = WantedReach();
		if ( Rampage.Tier != _tier )
		{
			bool up = Rampage.Tier > _tier;
			_tier = Rampage.Tier;
			if ( up )
			{
				_reachSpeed += want * GrowKick;
				_spurt = 0f;
				_announceAt = Time.Now + AnnounceDelay;
				Play( "dong_grow", _controller.WorldPosition, 1f, 1f );
				Thump( 0.5f );
				_controller.Kick( Vector3.Up * 10f );
			}
		}
		if ( _announceAt > 0f && Time.Now >= _announceAt )
		{
			_announceAt = 0f;
			string line = _tier < TierLines.Length ? TierLines[_tier] : TierLines[7 + (_tier - 7) % (TierLines.Length - 7)];
			if ( !string.IsNullOrEmpty( line ) ) Rampage.Announce( line, 4f );
		}

		_reachSpeed += ((want - _reach) * GrowSpring - _reachSpeed * GrowDamping) * dt;
		_reach = Math.Clamp( _reach + _reachSpeed * dt, BaseReach * 0.5f, want * 2.5f + BaseReach );

		// It throbs for a moment after a spurt, swells and trembles while charging, stretches as the
		// helicopter winds up (the ring it hits widens), and a mega-swing goes round longer than it went back.
		_spurt += dt;
		float throb = _spurt < 1.4f ? MathF.Sin( _spurt * 26f ) * 0.12f * (1f - _spurt / 1.4f) : 0f;
		float swell = 1f + throb;
		if ( _joint == Joint.Charge ) swell += Charge01 * ChargeSwell + MathF.Sin( Time.Now * 31f ) * 0.05f * Charge01;
		else if ( _joint == Joint.Mega ) swell += _megaCharge * MegaReach;
		else if ( _dong == DongMode.Spin || _dong == DongMode.Release ) swell += Spin01 * SpinStretch;

		Reach = _reach * swell;
		_rig.WeaponMode = true;
		_rig.WeaponGravityScale = GravityScale;
		_rig.DongLanded = _onDongLanded ??= OnDongLanded;
		_rig.SackLanded = _onSackLanded ??= OnSackLanded;
		_rig.DongScale = Reach / MathF.Max( _rig.DongRestLength, 0.1f );
		float sack = SackBaseScale * MathF.Pow( MathF.Max( Rampage.WeaponScale, 0.1f ), SackGrowth ) * (1f + throb * 1.5f);
		if ( _joint == Joint.Charge ) sack *= 1f + Charge01 * ChargeSwell;
		_rig.SackScale = sack;
	}

	// ---- Input ----------------------------------------------------------------------------------

	/// <summary>
	/// Reads the two buttons. Each weapon has its own: the dong on Attack1, the balls on Attack2,
	/// and they can be used at the same moment. A tap and a hold of the same button are different
	/// moves, told apart when the button comes up (the hold has already begun by then, so nothing
	/// waits). Both held together is the charge.
	/// </summary>
	void ReadInput( float dt )
	{
		bool can = CanAct;
		bool down1 = can && Input.Down( "Attack1" );
		bool down2 = can && Input.Down( "Attack2" );
		bool pressed1 = down1 && !_was1, pressed2 = down2 && !_was2;
		_was1 = down1;
		_was2 = down2;
		_bothHeld = down1 && down2 ? _bothHeld + dt : 0f;
		_down1 = down1;
		_down2 = down2;

		if ( !can || _joint != Joint.None ) return;
		bool air = !_controller.Attached && _dong != DongMode.Spin;
		float now = Time.Now;

		// In the air each button is that weapon's dive.
		if ( air && pressed1 && FreeForJoint ) { StartPound(); return; }
		if ( air && pressed2 && FreeForJoint ) { StartSitDown(); return; }

		// The clap: right click as the second whip lands (or as the third goes up).
		if ( pressed2 && ClapOpen ) { StartClap(); return; }

		// Both held: the charge.
		if ( _bothHeld >= BothSeconds && FreeForJoint ) { StartCharge(); return; }

		if ( pressed1 )
		{
			if ( _dong == DongMode.Whip ) _buffered = true;
			else if ( (_dong == DongMode.Carried || _dong == DongMode.Follow) && now >= _restUntil ) StartAim();
		}
		if ( pressed2 && _balls == BallMode.Hang && now >= _ballRestUntil ) StartDraw();
	}

	bool _down1, _down2;

	/// <summary>Neither weapon is committed to something that cannot be dropped for a move that takes both.</summary>
	bool FreeForJoint => (_dong == DongMode.Carried || _dong == DongMode.Aim || _dong == DongMode.Follow)
		&& (_balls == BallMode.Hang || _balls == BallMode.Draw);

	// ---- Running the moves ----------------------------------------------------------------------

	void Advance( float dt )
	{
		_dongT += dt;
		_ballT += dt;
		_jointT += dt;
		float factor = 1f;
		var body = new Angles();
		_hop = 0f;
		var lit = WeaponHint.None;

		if ( _joint != Joint.None )
		{
			switch ( _joint )
			{
				case Joint.Charge: body = UpdateCharge( dt ); factor = ChargeSlow; lit = WeaponHint.Charge; break;
				case Joint.Mega: body = UpdateMega( dt ); factor = 0.2f; lit = WeaponHint.Charge; break;
				case Joint.Clap: body = UpdateClap(); factor = 0.3f; lit = WeaponHint.Clap; break;
				case Joint.Pound: body = UpdatePound(); lit = WeaponHint.Air; break;
				case Joint.SitDown: body = UpdateSitDown(); lit = WeaponHint.Air; break;
				case Joint.Stumble: body = UpdateStumble( dt ); factor = StumbleCrawl; break;
			}
		}
		else
		{
			body = UpdateDong( dt, ref factor, ref lit );
			var more = UpdateBalls( dt, ref factor, ref lit );
			body = new Angles( body.pitch + more.pitch, body.yaw + more.yaw, body.roll + more.roll );
			if ( !_controller.Attached && _dong != DongMode.Spin ) lit |= WeaponHint.Air;
			if ( ClapOpen ) lit |= WeaponHint.Clap;
		}
		Lit = lit;

		// The turn of the whole model unwinds the short way once nothing is spinning it.
		bool spinning = (_joint == Joint.None && _dong == DongMode.Spin) || _joint == Joint.Mega || _joint == Joint.Stumble;
		if ( !spinning )
		{
			_bodySpin %= 360f;
			if ( _bodySpin > 180f ) _bodySpin -= 360f;
			if ( _bodySpin < -180f ) _bodySpin += 360f;
			_bodySpin += (0f - _bodySpin) * MathF.Min( dt * 7f, 1f );
			if ( MathF.Abs( _bodySpin ) < 0.5f ) _bodySpin = 0f;
		}

		_rig.SpinYaw = _bodySpin;
		_rig.BodyThrow = body;
		_rig.BodyOffset = MathF.Abs( _hop ) > 0.05f ? Vector3.Up * _hop : Vector3.Zero;
		_rig.DongTipLoad = _hooked.IsValid() ? HookLoad : 0f;

		if ( MathF.Abs( factor - _speedFactor ) > 0.001f )
		{
			_speedFactor = factor;
			_controller.SetSpeedFactor( "weapon", factor * Math.Clamp( GiantPace, 0.5f, 1.2f ) );
		}

		AttackName = HeadlineName();
		Pull( dt );
	}

	string HeadlineName() => _joint switch
	{
		Joint.Charge => Charge01 >= 1f ? "MEGA-SWING: LET GO!" : "CHARGING",
		Joint.Mega => "MEGA-SWING",
		Joint.Clap => "THE CLAP",
		Joint.Pound => "GROUND POUND",
		Joint.SitDown => "SIT-DOWN",
		Joint.Stumble => "FLAT ON HIS BACKSIDE",
		_ => _dong switch
		{
			DongMode.Spin => Spin01 >= HoverAt ? "HELICOPTER" : "WINDING UP",
			DongMode.Release => "THE RELEASE",
			DongMode.Whip => _whipIndex >= 2 ? "OVERHEAD SLAM" : "WHIP",
			_ => _balls switch
			{
				BallMode.Flail => "THE OLD WRECKING BALL",
				BallMode.Draw => Draw01 > 0f ? "SLINGSHOT" : "",
				BallMode.Snap or BallMode.Out or BallMode.Back => "SLINGSHOT",
				_ => _dong == DongMode.Aim ? "WHIPPING" : "",
			},
		},
	};

	/// <summary>
	/// The weight pulls back. Whatever the dong's far end is doing, the giant is dragged a little
	/// after it: a swing turns and tugs him, a helicopter walks him round in circles.
	/// </summary>
	void Pull( float dt )
	{
		if ( !Live || PullPerSpeed <= 0f ) return;
		var tip = _rig.DongTipVelocity.WithZ( 0f );
		float speed = tip.Length / SizeSpeed;      // as if at the lizard's ordinary size
		if ( speed < 220f ) return;
		Shove( tip, PullPerSpeed * (speed / 1000f) * Heft * MathF.Sqrt( G ) * dt );
	}

	/// <summary>A direction: so many degrees to the left of a compass yaw, and so many up from level (past 90 is up and over the back).</summary>
	static Vector3 Dir( float baseYaw, float yaw, float elevation )
	{
		var flat = Rotation.FromYaw( baseYaw + yaw ).Forward;
		float e = elevation * (MathF.PI / 180f);
		return flat * MathF.Cos( e ) + Vector3.Up * MathF.Sin( e );
	}

	/// <summary>Shoves the giant itself: the recoil of the weight it is throwing. Capped.</summary>
	void Shove( Vector3 direction, float speed )
	{
		if ( speed <= 0f || direction.Length < 0.01f ) return;
		_controller.Lunge( direction.Normal, MathF.Min( speed, MaxShove * G ) );
	}

	/// <summary>The dong is left to trail: behind and a little to one side, clear of the legs, mostly under its own weight.</summary>
	void TrailDong()
	{
		var facing = _controller.WorldRotation;
		_rig.DongDrive = facing.Backward + facing.Right * 0.5f + Vector3.Down * 0.15f;
		_rig.DongDriveStrength = IdleStrength;
	}

	void HangBalls()
	{
		_rig.SackDriveStrength = 0f;
		_rig.SackChain += (0f - _rig.SackChain) * MathF.Min( Time.Delta * 10f, 1f );
		if ( _rig.SackChain < 0.5f ) _rig.SackChain = 0f;
	}

	// ---- Carrying it ----------------------------------------------------------------------------

	/// <summary>The camera backs off as the weapon grows, and further while a mega-swing is charging or a helicopter is up to speed.</summary>
	void Carry( float dt )
	{
		var giant = RampageGiant.Current;
		if ( giant.IsValid() )
		{
			float pull = Reach * CameraPerReach;
			if ( _joint == Joint.Charge || _joint == Joint.Mega ) pull += Charge01 * ChargePullBack * Reach;
			else if ( _dong == DongMode.Spin ) pull += Spin01 * 0.5f * Reach;
			else if ( _balls == BallMode.Draw || _balls == BallMode.Out ) pull += Draw01 * 0.6f * Reach;
			giant.CameraPull = pull;
			giant.CameraLift = Reach * CameraLiftPerReach;
		}

		if ( _joint == Joint.None && _dong == DongMode.Carried ) Furrow();
		CarryHooked();
		WatchSnag();
	}

	/// <summary>The chain came down on the ground (called by the rig): the slap, and a slam's landing.</summary>
	void OnDongLanded( Vector3 at, float speed )
	{
		if ( _dong == DongMode.Whip && _whipIndex >= 2 && speed > 200f ) _slamLanded = true;
		if ( speed < 260f * MathF.Sqrt( G ) || Time.Now < _nextSlapSound ) return;
		_nextSlapSound = Time.Now + 0.16f;
		Play( "dong_slap", at, Math.Clamp( speed / (1400f * MathF.Sqrt( G )), 0.2f, 1f ), SizePitch( 1f ) );
		Puff( at, 2, Reach * 0.04f );
	}

	void OnSackLanded( Vector3 at, float speed )
	{
		if ( speed < 300f * MathF.Sqrt( G ) || Time.Now < _nextSlapSound ) return;
		_nextSlapSound = Time.Now + 0.16f;
		Play( "sack_boing", at, Math.Clamp( speed / (1400f * MathF.Sqrt( G )), 0.2f, 1f ), SizePitch( 1.1f ) );
	}

	// ---- Small things ---------------------------------------------------------------------------

	/// <summary>Distance from a point to the stretch between two others, and how far along it the nearest place is (0 to 1).</summary>
	static float Closest( Vector3 a, Vector3 b, Vector3 point, out float along )
	{
		var span = b - a;
		float length = span.LengthSquared;
		along = length > 0.0001f ? Math.Clamp( Vector3.Dot( point - a, span ) / length, 0f, 1f ) : 0f;
		return (a + span * along - point).Length;
	}

	static float Lerp( float a, float b, float t ) => a + (b - a) * Math.Clamp( t, 0f, 1f );

	static float Ease( float t )
	{
		t = Math.Clamp( t, 0f, 1f );
		return t * t * (3f - 2f * t);
	}

	static float Wrap180( float degrees )
	{
		degrees %= 360f;
		if ( degrees > 180f ) degrees -= 360f;
		if ( degrees < -180f ) degrees += 360f;
		return degrees;
	}

	/// <summary>The bigger it is, the lower it sounds.</summary>
	float SizePitch( float pitch ) => pitch * Math.Clamp( 0.9f - 0.1f * Heft, 0.5f, 0.82f );

	/// <summary>Plays sounds/rampage/&lt;name&gt;.sound at a place. A missing sound is just silence.</summary>
	SoundHandle Play( string name, Vector3 at, float volume, float pitch )
	{
		var handle = Rampage.PlaySound( name, at );
		if ( handle is null ) return null;
		handle.Volume = volume * SoundVolume;
		handle.Pitch = pitch;
		return handle;
	}

	float _nextHitSound, _nextSlapSound, _nextShake, _nextThud;
	float _stopUntil, _nextStop, _stopSet;

	/// <summary>
	/// Shakes the camera, and for a hard enough hit holds the clock for a moment so the blow
	/// lands. Only ever from full speed (a charge's slow-down, the game's own slow motion and a
	/// test's time scale are left alone), and it is put back in real time.
	/// </summary>
	void Thump( float strength )
	{
		Rampage.Shake( strength );
		if ( HitStopSeconds <= 0f || strength < HitStopFrom || _dipping || Scene is null ) return;
		float real = RealTime.Now;
		if ( _stopUntil > 0f || real < _nextStop ) return;
		if ( MathF.Abs( Scene.TimeScale - 1f ) > 0.01f ) return;

		float hard = Math.Clamp( (strength - HitStopFrom) / MathF.Max( 1f - HitStopFrom, 0.01f ), 0f, 1f );
		_stopSet = Math.Clamp( HitStopScale, 0.02f, 1f );
		Scene.TimeScale = _stopSet;
		_stopUntil = real + HitStopSeconds * (0.5f + 0.5f * hard);
		_nextStop = _stopUntil + MathF.Max( HitStopGap, 0f );
	}

	void EndHitStop()
	{
		if ( _stopUntil <= 0f ) return;
		_stopUntil = 0f;
		if ( Scene is not null && MathF.Abs( Scene.TimeScale - _stopSet ) < 0.01f ) Scene.TimeScale = 1f;
	}
}