Rampage/World/Destructible.cs
using System;
using System.Collections.Generic;

/// <summary>
/// A prop of the town: a car, a mailbox, a hot dog stand. It stands still and costs nothing until
/// something hits it. A hit that does not break it knocks it loose: it becomes a rigid body and
/// flies off with the blow, hurting whatever it lands on. Enough damage and it bursts into a few
/// chunky pieces and scores. Once a loose prop comes to rest it is frozen again.
///
/// It has no update of its own: <see cref="RampageWorld"/> ticks only the props that are loose.
/// </summary>
[Title( "Destructible" ), Category( "Rampage" ), Icon( "broken_image" )]
public sealed class Destructible : Component, IRampageTarget, Component.ICollisionListener
{
	public PropKind Kind { get; private set; }
	public Color BodyColour { get; private set; }
	public string Label { get; private set; }

	/// <summary>The stretch of town it was put down in.</summary>
	public TownCell Home { get; private set; }

	RampageWorld _world;
	Rigidbody _body;
	BoxCollider _collider;
	ModelRenderer _bodyRenderer;
	Vector3 _aim, _origin, _kick;
	float _radius, _health, _nextHit, _nextPassOn, _stillSince, _bump;
	bool _broken, _kickPending;

	// ---- IRampageTarget ------------------------------------------------------------------------

	public bool Alive => !_broken && Kind is not null;
	public Vector3 Centre => WorldTransform.PointToWorld( _aim );
	public float Radius => _radius;

	/// <summary>True while it is a moving rigid body.</summary>
	public bool Loose => _body.IsValid() && _body.MotionEnabled;

	/// <summary>Called once by the world, straight after the object is made.</summary>
	public void Setup( RampageWorld world, PropKind kind, Color body, string label, TownCell home )
	{
		_world = world;
		Kind = kind;
		BodyColour = body;
		Label = label;
		Home = home;
		_health = kind.Health;
		_origin = WorldPosition;

		var shape = kind.Shape;
		shape.Bake( world.Kit );
		for ( int i = 0; i < shape.Models.Length; i++ )
		{
			if ( shape.Models[i] is null ) continue;
			var renderer = world.Kit.Draw( GameObject, shape.Models[i], shape.IsBody[i] ? body : shape.Tints[i], kind.Shadows );
			if ( shape.IsBody[i] ) _bodyRenderer = renderer;
		}

		// Aim low on tall thin things, so a swing at street level finds the lamppost.
		var size = shape.Size;
		_aim = shape.Centre.WithZ( MathF.Min( shape.Centre.z, 40f ) );
		_radius = MathF.Max( MathF.Sqrt( size.x * size.x + size.y * size.y ) * 0.5f, MathF.Min( size.z * 0.5f, 40f ) );

		_collider = Components.Create<BoxCollider>();
		_collider.Center = shape.Centre;
		_collider.Scale = size;
		_collider.Static = true;

		// The giant walks straight through every prop (and its feet and shins send them flying, see
		// RampageGiant) instead of snagging on a parked car. Only buildings and towers stop it.
		GameObject.Tags.Add( "debris" );

		// It stands still until something knocks it loose (see MarkLoose and Settle).
		Rampage.Register( this, false );
	}

	public void Hit( Vector3 velocity, float damage, Vector3 at )
	{
		if ( _broken || !_world.IsValid() ) return;
		float now = Time.Now;
		if ( now < _nextHit ) return;
		_nextHit = now + 0.1f;

		Take( velocity, _world.Force( velocity, damage ) );
	}

	/// <summary>Kicked aside by the running lizard: thrown, and hurt by exactly this much.</summary>
	public void Kick( Vector3 velocity, float damage )
	{
		if ( _broken || !_world.IsValid() ) return;
		_nextHit = Time.Now + 0.1f;
		Take( velocity, damage );
	}

	void Take( Vector3 velocity, float force )
	{
		_health -= force;
		if ( _health <= 0f )
		{
			Break( velocity );
			return;
		}

		Shove( velocity );
		TownKit.Play( Kind.Weight >= PropWeight.Heavy ? "car_crunch" : "prop_knock", WorldPosition, 0.1f );
	}

	/// <summary>Knocked without being hurt: carried by a flood, bowled over by a blast.</summary>
	public void Shove( Vector3 velocity )
	{
		if ( _broken || velocity.LengthSquared < 1f ) return;
		bool fresh = Loosen();

		// A bit of lift, so it tumbles instead of grinding along the road.
		var kick = velocity * Kind.Give;
		if ( kick.z < 140f ) kick.z += 140f + velocity.Length * 0.12f;

		_kick = (fresh ? Vector3.Zero : _body.Velocity) + kick;
		_kickPending = true;
		_body.Velocity = _kick;
		_body.AngularVelocity += Vector3.Random * (2f + velocity.Length * 0.004f);
	}

	/// <summary>Makes it a moving body. True if the body was made just now.</summary>
	bool Loosen()
	{
		_stillSince = 0f;
		if ( _body.IsValid() )
		{
			if ( !_body.MotionEnabled )
			{
				_body.MotionEnabled = true;
				MarkLoose();
			}
			return false;
		}

		_collider.Static = false;
		_body = Components.Create<Rigidbody>();
		_body.MassOverride = Kind.Mass;
		_body.AngularDamping = 0.6f;
		_body.LinearDamping = 0.15f;
		MarkLoose();
		return true;
	}

	void MarkLoose()
	{
		// Nothing in flight blocks the lizard: it cannot be flattened by its own thrown car.
		GameObject.Tags.Add( "debris" );
		Rampage.SetMoving( this, true );
		_world.TrackLoose( this );
	}

	/// <summary>Frozen where it lies. It can be knocked loose again.</summary>
	public void Settle()
	{
		if ( _body.IsValid() ) _body.MotionEnabled = false;
		if ( !_broken ) Rampage.SetMoving( this, false );
	}

	/// <summary>One frame of being loose. False once it has come to rest, broken or left the world.</summary>
	public bool TickLoose( float now )
	{
		if ( _broken || !_body.IsValid() || !_body.MotionEnabled ) return false;

		// A body made this frame may not have had its speed yet: give it again.
		if ( _kickPending )
		{
			_kickPending = false;
			if ( _body.Velocity.LengthSquared < _kick.LengthSquared * 0.25f ) _body.Velocity = _kick;
			return true;
		}

		if ( _bump > 0f )
		{
			// What it took from landing on something, kept back until the physics step was over.
			_health -= _bump;
			_bump = 0f;
			if ( _health <= 0f ) { Break( _body.Velocity ); return false; }
		}

		var p = WorldPosition;
		float edge = RampageWorld.HalfSize + 500f;
		if ( p.z < -300f || MathF.Abs( p.x ) > edge || MathF.Abs( p.y ) > edge )
		{
			Vanish();
			return false;
		}

		bool still = _body.Sleeping || (_body.Velocity.LengthSquared < 20f * 20f && _body.AngularVelocity.LengthSquared < 0.5f);
		if ( !still ) { _stillSince = 0f; return true; }
		if ( _stillSince <= 0f ) _stillSince = now;
		if ( now - _stillSince < 1.2f ) return true;

		Settle();
		return false;
	}

	// ---- Landing on things ---------------------------------------------------------------------

	public void OnCollisionStart( Collision collision )
	{
		if ( _broken || !_world.IsValid() || !_body.IsValid() || !_body.MotionEnabled ) return;

		float speed = MathF.Abs( collision.Contact.NormalSpeed );
		if ( speed < _world.PassOnSpeed ) return;
		float now = Time.Now;
		if ( now < _nextPassOn ) return;

		var other = collision.Other.GameObject;
		var target = other.IsValid() ? other.Components.Get<IRampageTarget>( FindMode.EverythingInSelfAndAncestors ) : null;
		if ( target is not null && !ReferenceEquals( target, this ) && target.Alive )
		{
			// It passes on a share of the blow, then not again for a moment, so chains die down.
			_nextPassOn = now + 0.4f;
			_world.PassOn( target, _body.Velocity * _world.PassOnShare, speed * Kind.Clout, WorldPosition );
		}
		else
		{
			_nextPassOn = now + 0.15f;
		}

		// And takes a knock itself: a flung mailbox does not survive the landing.
		_bump += speed * (Kind.Weight == PropWeight.Light ? 0.03f : 0.015f);
	}

	public void OnCollisionUpdate( Collision collision ) { }
	public void OnCollisionStop( CollisionStop collision ) { }

	// ---- Breaking ------------------------------------------------------------------------------

	void Break( Vector3 velocity )
	{
		if ( _broken ) return;
		_broken = true;
		Rampage.Unregister( this );
		Home?.Live.Remove( this );

		var centre = WorldTransform.PointToWorld( Kind.Shape.Centre );
		Rampage.Score( centre, Kind.Points, Label );
		if ( Kind.Points >= 60f ) _world.ShakeAt( centre, Kind.Weight == PropWeight.Huge ? 0.5f : 0.25f );

		_world.Fx.Shatter( Kind.Shape, WorldPosition, WorldRotation, BodyColour, velocity * Kind.Give, Kind.Pieces );
		TownKit.Play( Kind.Weight switch { PropWeight.Light => "prop_break_small", PropWeight.Medium => "prop_break_big", _ => "car_crunch" }, centre );

		switch ( Kind.Quirk )
		{
			case PropQuirk.Hydrant:
				// It gushes from where it stood, however far the hydrant itself went.
				_world.Fx.Gusher( _origin, 8f );
				TownKit.Play( "hydrant_gush", _origin );
				break;
			case PropQuirk.Pump:
				bool tanker = Kind.Weight == PropWeight.Huge;
				_world.Boom( centre, 0.15f, tanker ? 1300f : 800f, tanker ? 1500f : 1000f );
				break;
			case PropQuirk.Transformer:
				_world.Fx.Sparks( centre, 4f );
				TownKit.Play( "electric_zap", centre );
				break;
		}

		GameObject.Destroy();
	}

	/// <summary>Gone without a score: it fell out of the world.</summary>
	void Vanish()
	{
		if ( _broken ) return;
		_broken = true;
		Rampage.Unregister( this );
		Home?.Live.Remove( this );
		GameObject.Destroy();
	}

	/// <summary>A siren's lamp, or a police car's light bar, one colour or the other.</summary>
	public void Flash( bool on )
	{
		if ( _bodyRenderer.IsValid() ) _bodyRenderer.Tint = on ? Tone.Red : Tone.Blue;
	}

	protected override void OnDestroy()
	{
		if ( !_broken ) Rampage.Unregister( this );
		_broken = true;
	}
}