Framework/Scripting/Api/LuaPhysics.cs

Lua binding layer for physics...

using System;
using System.Collections.Generic;
using System.Linq;
using RoleplayFramework.Lua;
using RoleplayFramework.Players;

namespace RoleplayFramework.Scripting;

internal sealed class PhysHandle
{
	public Guid Id;
}

/// <summary>
/// Physics, constraints, sounds and player movement for Lua (GMod names where they exist).
///
///   ent:GetPhysicsObject() → PhysObj (server): IsValid, Wake, Sleep, IsAsleep, EnableMotion(b), IsMotionEnabled,
///       EnableGravity(b), IsGravityEnabled, SetVelocity(v), AddVelocity(v), GetVelocity, SetAngleVelocity(v),
///       GetAngleVelocity, ApplyForceCenter(impulse), ApplyForceOffset(impulse, worldPos), SetMass(kg), GetMass,
///       GetPos, SetPos(v), GetAngles, SetAngles(a), GetEntity, ComputeShadowControl(params)
///   WorldToLocal/LocalToWorld(pos, ang, originPos, originAng), util.RotateAroundAxis(ang, axis, deg),
///   ent:WorldToLocal/LocalToWorld(pos), ent:WorldToLocalAngles/LocalToWorldAngles(ang)
///   ent:PhysicsInit() (server) gives an entity physics; ent:GetVelocity() (both)
///   constraint.Weld/Ballsocket/Rope/NoCollide/RemoveAll/RemoveConstraints/GetAll/Remove (server)
///   sound.Play(path, pos [, volume [, pitch]]) (server: everyone hears it; client: only this client),
///   ent:EmitSound(path [, volume [, pitch]]), surface.PlaySound(path) (client, 2D)
///   ply:SetMoveType(MOVETYPE_WALK|MOVETYPE_NOCLIP|MOVETYPE_NONE), ply:GetMoveType(), ply:Freeze(b), ply:IsFrozen(),
///   ply:SetVelocity(v) (adds, like GMod), ply:GetVelocity()
/// </summary>
public static class LuaPhysics
{
	public const int MaxConstraints = 4000;

	public static void Register( LuaRealm realm )
	{
		var L = realm.State;
		bool server = realm.Kind == LuaRealmKind.Server;
		var entMethods = realm.MethodTables["Entity"];
		var plyMethods = realm.MethodTables["Player"];

		L.Globals.Set( "MOVETYPE_NONE", RpMoveMode.MoveTypeNone );
		L.Globals.Set( "MOVETYPE_WALK", RpMoveMode.MoveTypeWalk );
		L.Globals.Set( "MOVETYPE_NOCLIP", RpMoveMode.MoveTypeNoclip );

		// ---------------------------------------------------------------- PhysObj
		var physMethods = new LuaTable();
		var physMeta = new LuaTable();
		physMeta.Set( "__index", physMethods );
		physMeta.Set( "__metatable", "PhysObj" );
		realm.MethodTables["PhysObj"] = physMethods;

		LuaState.Register( entMethods, "GetPhysicsObject", ( s, a ) =>
		{
			var go = Ent( a, "GetPhysicsObject" );
			return new[] { LuaValue.FromUserData( new LuaUserData( new PhysHandle { Id = go.Id }, physMeta ) ) };
		} );
		LuaState.Register( entMethods, "GetVelocity", ( s, a ) =>
		{
			var rb = Ent( a, "GetVelocity" ).Components.Get<Rigidbody>();
			return new[] { LuaConvert.FromVector( s, rb?.Velocity ?? Vector3.Zero ) };
		} );
		LuaState.Register( entMethods, "PhysicsInit", ServerOnly( server, "PhysicsInit", ( s, a ) =>
		{
			var go = Ent( a, "PhysicsInit" );
			go.Components.GetOrCreate<Rigidbody>();
			return new LuaValue[] { true };
		} ) );

		Rigidbody Body( LuaValue[] a, string m, bool needServer = true )
		{
			if ( needServer && !server ) throw new LuaRuntimeException( $"PhysObj:{m} can only be called on the server" );
			if ( LuaState.Arg( a, 0 ).Type != LuaType.UserData || LuaState.Arg( a, 0 ).AsUserData.Value is not PhysHandle h )
				throw new LuaRuntimeException( $"calling '{m}' on a non-PhysObj value" );
			var go = Game.ActiveScene?.Directory.FindByGuid( h.Id );
			return go.IsValid() ? go.Components.Get<Rigidbody>() : null;
		}
		Rigidbody Need( LuaValue[] a, string m ) => Body( a, m ) ?? throw new LuaRuntimeException( $"PhysObj:{m}: the entity has no physics (check IsValid; ents.Create{{ physics = true }} or ent:PhysicsInit())" );

		LuaState.Register( physMethods, "IsValid", ( s, a ) => new LuaValue[] { Body( a, "IsValid", false ) is not null } );
		LuaState.Register( physMethods, "Wake", ( s, a ) => { Need( a, "Wake" ).Sleeping = false; return null; } );
		LuaState.Register( physMethods, "Sleep", ( s, a ) => { Need( a, "Sleep" ).Sleeping = true; return null; } );
		LuaState.Register( physMethods, "IsAsleep", ( s, a ) => new LuaValue[] { Need( a, "IsAsleep" ).Sleeping } );
		LuaState.Register( physMethods, "EnableMotion", ( s, a ) => { var rb = Need( a, "EnableMotion" ); rb.MotionEnabled = LuaState.Arg( a, 1 ).IsTruthy; if ( rb.MotionEnabled ) rb.Sleeping = false; return null; } );
		LuaState.Register( physMethods, "IsMotionEnabled", ( s, a ) => new LuaValue[] { Need( a, "IsMotionEnabled" ).MotionEnabled } );
		LuaState.Register( physMethods, "EnableGravity", ( s, a ) => { Need( a, "EnableGravity" ).Gravity = LuaState.Arg( a, 1 ).IsTruthy; return null; } );
		LuaState.Register( physMethods, "IsGravityEnabled", ( s, a ) => new LuaValue[] { Need( a, "IsGravityEnabled" ).Gravity } );
		LuaState.Register( physMethods, "SetVelocity", ( s, a ) => { Need( a, "SetVelocity" ).Velocity = Vec( a, 1, 100000 ); return null; } );
		LuaState.Register( physMethods, "AddVelocity", ( s, a ) => { var rb = Need( a, "AddVelocity" ); rb.Velocity += Vec( a, 1, 100000 ); return null; } );
		LuaState.Register( physMethods, "GetVelocity", ( s, a ) => new[] { LuaConvert.FromVector( s, Need( a, "GetVelocity" ).Velocity ) } );
		LuaState.Register( physMethods, "SetAngleVelocity", ( s, a ) => { Need( a, "SetAngleVelocity" ).AngularVelocity = Vec( a, 1, 1000 ); return null; } );
		LuaState.Register( physMethods, "GetAngleVelocity", ( s, a ) => new[] { LuaConvert.FromVector( s, Need( a, "GetAngleVelocity" ).AngularVelocity ) } );
		LuaState.Register( physMethods, "ApplyForceCenter", ( s, a ) => { var rb = Need( a, "ApplyForceCenter" ); rb.Sleeping = false; rb.ApplyImpulse( Vec( a, 1, 1e7f ) ); return null; } );
		LuaState.Register( physMethods, "ApplyForceOffset", ( s, a ) =>
		{
			var rb = Need( a, "ApplyForceOffset" );
			rb.Sleeping = false;
			rb.ApplyImpulseAt( LuaConvert.ToVector( LuaState.Arg( a, 2 ) ), Vec( a, 1, 1e7f ) );
			return null;
		} );
		LuaState.Register( physMethods, "SetMass", ( s, a ) =>
		{
			var m = LuaState.CheckNumber( a, 1, "PhysObj:SetMass" );
			if ( m <= 0 || m > 50000 ) throw LuaState.ArgError( 1, "PhysObj:SetMass", "mass must be between 0 and 50000 kg" );
			Need( a, "SetMass" ).MassOverride = (float)m;
			return null;
		} );
		LuaState.Register( physMethods, "GetMass", ( s, a ) => new LuaValue[] { Need( a, "GetMass" ).Mass } );
		LuaState.Register( physMethods, "GetPos", ( s, a ) => new[] { LuaConvert.FromVector( s, Need( a, "GetPos" ).WorldPosition ) } );
		LuaState.Register( physMethods, "SetPos", ( s, a ) => { Need( a, "SetPos" ).WorldPosition = LuaConvert.ToVector( LuaState.Arg( a, 1 ) ); return null; } );
		LuaState.Register( physMethods, "GetAngles", ( s, a ) => new[] { LuaConvert.FromAngles( s, Need( a, "GetAngles" ).WorldRotation.Angles() ) } );
		LuaState.Register( physMethods, "SetAngles", ( s, a ) => { Need( a, "SetAngles" ).WorldRotation = LuaConvert.ToAngles( LuaState.Arg( a, 1 ) ).ToRotation(); return null; } );
		LuaState.Register( physMethods, "GetEntity", ( s, a ) =>
		{
			var rb = Body( a, "GetEntity", false );
			var ent = rb?.Components.Get<LuaEntity>();
			return new[] { ent is null ? LuaValue.Nil : LuaEntities.Wrap( realm, ent ) };
		} );

		// PhysObj:ComputeShadowControl({ pos, angle, secondstoarrive, maxspeed, maxangular, teleportdistance }) (GMod):
		// drives the body towards a target position/rotation by setting its velocities (physics guns, carrying).
		LuaState.Register( physMethods, "ComputeShadowControl", ( s, a ) =>
		{
			var rb = Need( a, "ComputeShadowControl" );
			var t = LuaState.CheckTable( a, 1, "PhysObj:ComputeShadowControl" );
			float N( string k, float d ) => LuaState.ToNumber( t.Get( k ), out var v ) && !double.IsNaN( v ) ? (float)v : d;
			float arrive = Math.Max( N( "secondstoarrive", 0.1f ), 0.01f );
			rb.Sleeping = false;
			if ( !t.Get( "pos" ).IsNil )
			{
				var target = LuaConvert.ToVector( t.Get( "pos" ), "pos" );
				var delta = target - rb.WorldPosition;
				float tp = N( "teleportdistance", 0 );
				if ( tp > 0 && delta.Length > tp ) { rb.WorldPosition = target; rb.Velocity = Vector3.Zero; }
				else
				{
					var vel = delta / arrive;
					float max = N( "maxspeed", 5000 );
					if ( vel.Length > max ) vel = vel.Normal * max;
					rb.Velocity = vel;
				}
			}
			if ( !t.Get( "angle" ).IsNil )
			{
				var target = LuaConvert.ToAngles( t.Get( "angle" ), "angle" ).ToRotation();
				var d = target * rb.WorldRotation.Inverse;
				if ( d.w < 0 ) d = new Rotation( -d.x, -d.y, -d.z, -d.w );
				float half = MathF.Acos( Math.Clamp( d.w, -1f, 1f ) );
				float sin = MathF.Sin( half );
				var w = sin < 1e-4f ? Vector3.Zero : new Vector3( d.x, d.y, d.z ) / sin * (2f * half / arrive);
				float maxAng = N( "maxangular", 3600 ) * MathF.PI / 180f;
				if ( w.Length > maxAng ) w = w.Normal * maxAng;
				rb.AngularVelocity = w;
			}
			return null;
		} );

		// ---------------------------------------------------------------- coordinate helpers (GMod)
		// WorldToLocal(pos, ang, originPos, originAng) / LocalToWorld(localPos, localAng, originPos, originAng) -> Vector, Angle
		LuaNativeFunction toLocal = ( s, a ) =>
		{
			var origin = new global::Transform( LuaConvert.ToVector( LuaState.Arg( a, 2 ), "origin" ), LuaConvert.ToAngles( LuaState.Arg( a, 3 ), "originAngle" ).ToRotation() );
			var pos = LuaConvert.ToVector( LuaState.Arg( a, 0 ), "position" );
			var rot = LuaState.Arg( a, 1 ).IsNil ? Rotation.Identity : LuaConvert.ToAngles( LuaState.Arg( a, 1 ), "angle" ).ToRotation();
			return new[] { LuaConvert.FromVector( s, origin.PointToLocal( pos ) ), LuaConvert.FromAngles( s, (origin.Rotation.Inverse * rot).Angles() ) };
		};
		LuaNativeFunction toWorld = ( s, a ) =>
		{
			var origin = new global::Transform( LuaConvert.ToVector( LuaState.Arg( a, 2 ), "origin" ), LuaConvert.ToAngles( LuaState.Arg( a, 3 ), "originAngle" ).ToRotation() );
			var pos = LuaConvert.ToVector( LuaState.Arg( a, 0 ), "position" );
			var rot = LuaState.Arg( a, 1 ).IsNil ? Rotation.Identity : LuaConvert.ToAngles( LuaState.Arg( a, 1 ), "angle" ).ToRotation();
			return new[] { LuaConvert.FromVector( s, origin.PointToWorld( pos ) ), LuaConvert.FromAngles( s, (origin.Rotation * rot).Angles() ) };
		};
		L.Register( "WorldToLocal", toLocal );
		L.Register( "LocalToWorld", toWorld );

		// util.RotateAroundAxis(ang, axis, degrees) -> Angle (Angle:RotateAroundAxis in sh_core uses it)
		var utilLib = L.GetOrCreateLibrary( "util" );
		LuaState.Register( utilLib, "RotateAroundAxis", ( s, a ) =>
		{
			var rot = LuaConvert.ToAngles( LuaState.Arg( a, 0 ), "angle" ).ToRotation();
			var axis = LuaConvert.ToVector( LuaState.Arg( a, 1 ), "axis" );
			if ( axis.Length < 1e-6f ) throw LuaState.ArgError( 1, "RotateAroundAxis", "axis must not be zero" );
			var deg = (float)LuaState.CheckNumber( a, 2, "RotateAroundAxis" );
			return new[] { LuaConvert.FromAngles( s, (Rotation.FromAxis( axis.Normal, deg ) * rot).Angles() ) };
		} );

		// ent:WorldToLocal(pos) / ent:LocalToWorld(pos) / ent:WorldToLocalAngles(ang) / ent:LocalToWorldAngles(ang)
		LuaState.Register( entMethods, "WorldToLocal", ( s, a ) => new[] { LuaConvert.FromVector( s, Ent( a, "WorldToLocal" ).WorldTransform.WithScale( 1 ).PointToLocal( LuaConvert.ToVector( LuaState.Arg( a, 1 ) ) ) ) } );
		LuaState.Register( entMethods, "LocalToWorld", ( s, a ) => new[] { LuaConvert.FromVector( s, Ent( a, "LocalToWorld" ).WorldTransform.WithScale( 1 ).PointToWorld( LuaConvert.ToVector( LuaState.Arg( a, 1 ) ) ) ) } );
		LuaState.Register( entMethods, "WorldToLocalAngles", ( s, a ) => new[] { LuaConvert.FromAngles( s, (Ent( a, "WorldToLocalAngles" ).WorldRotation.Inverse * LuaConvert.ToAngles( LuaState.Arg( a, 1 ) ).ToRotation()).Angles() ) } );
		LuaState.Register( entMethods, "LocalToWorldAngles", ( s, a ) => new[] { LuaConvert.FromAngles( s, (Ent( a, "LocalToWorldAngles" ).WorldRotation * LuaConvert.ToAngles( LuaState.Arg( a, 1 ) ).ToRotation()).Angles() ) } );

		// ---------------------------------------------------------------- constraints (server)
		if ( server ) RegisterConstraints( realm );

		// ---------------------------------------------------------------- sounds
		var sound = L.GetOrCreateLibrary( "sound" );
		LuaState.Register( sound, "Play", ( s, a ) =>
		{
			var path = SoundPath( LuaState.CheckString( a, 0, "sound.Play" ), "sound.Play" );
			var pos = LuaConvert.ToVector( LuaState.Arg( a, 1 ), "position" );
			var (vol, pitch) = VolPitch( a, 2 );
			if ( server && Networking.IsActive ) PlayAt( path, pos, vol, pitch );
			else PlayLocal( path, pos, vol, pitch, null );
			return null;
		} );
		LuaState.Register( entMethods, "EmitSound", ( s, a ) =>
		{
			var e = LuaEntities.Resolve( a, 0 ) ?? throw new LuaRuntimeException( "calling 'EmitSound' on a removed entity" );
			if ( !server && !e.IsClientside ) throw new LuaRuntimeException( "EmitSound on a server entity can only be called on the server" );
			var path = SoundPath( LuaState.CheckString( a, 1, "EmitSound" ), "EmitSound" );
			var (vol, pitch) = VolPitch( a, 2 );
			if ( server && Networking.IsActive ) PlayOn( e.GameObject.Id, path, vol, pitch );
			else PlayLocal( path, e.WorldPosition, vol, pitch, e.GameObject );
			return null;
		} );
		// ply:EmitSound(path [, volume [, pitch [, skipOwner]]]): server plays it for everyone (skipOwner: not for the
		// player themselves, who predicted it); a client plays it locally on its own player.
		LuaState.Register( plyMethods, "EmitSound", ( s, a ) =>
		{
			var p = Player( a, "EmitSound" );
			var path = SoundPath( LuaState.CheckString( a, 1, "EmitSound" ), "EmitSound" );
			var (vol, pitch) = VolPitch( a, 2 );
			bool skipOwner = LuaState.Arg( a, 4 ).IsTruthy;
			if ( !server )
			{
				if ( !p.IsLocalPlayer ) throw new LuaRuntimeException( "EmitSound on a player can only be called on the server (or on LocalPlayer())" );
				PlayLocal( path, p.WorldPosition, vol, pitch, p.GameObject );
			}
			else if ( Networking.IsActive )
			{
				var owner = p.Network.Owner;
				if ( skipOwner && owner is not null ) { using ( Rpc.FilterExclude( c => c == owner ) ) PlayOn( p.GameObject.Id, path, vol, pitch ); }
				else PlayOn( p.GameObject.Id, path, vol, pitch );
			}
			else if ( !skipOwner ) PlayLocal( path, p.WorldPosition, vol, pitch, p.GameObject );
			return null;
		} );
		if ( !server )
		{
			var surface = L.GetOrCreateLibrary( "surface" );
			LuaState.Register( surface, "PlaySound", ( s, a ) =>
			{
				var path = SoundPath( LuaState.CheckString( a, 0, "surface.PlaySound" ), "surface.PlaySound" );
				var h = Sound.Play( path );
				if ( h is not null ) h.ListenLocal = true;
				return null;
			} );
		}

		// ---------------------------------------------------------------- player movement
		LuaState.Register( plyMethods, "GetMoveType", ( s, a ) => new LuaValue[] { Player( a, "GetMoveType" ).MoveType } );
		LuaState.Register( plyMethods, "IsFrozen", ( s, a ) => new LuaValue[] { Player( a, "IsFrozen" ).MoveType == RpMoveMode.MoveTypeNone } );
		LuaState.Register( plyMethods, "GetVelocity", ( s, a ) => new[] { LuaConvert.FromVector( s, Player( a, "GetVelocity" ).Controller?.Velocity ?? Vector3.Zero ) } );
		LuaState.Register( plyMethods, "SetMoveType", ServerOnly( server, "SetMoveType", ( s, a ) =>
		{
			var t = LuaState.CheckInt( a, 1, "SetMoveType" );
			if ( t is not (RpMoveMode.MoveTypeNone or RpMoveMode.MoveTypeWalk or RpMoveMode.MoveTypeNoclip) )
				throw LuaState.ArgError( 1, "SetMoveType", "MOVETYPE_WALK, MOVETYPE_NOCLIP or MOVETYPE_NONE expected" );
			Player( a, "SetMoveType" ).MoveType = t;
			return null;
		} ) );
		LuaState.Register( plyMethods, "Freeze", ServerOnly( server, "Freeze", ( s, a ) =>
		{
			Player( a, "Freeze" ).MoveType = LuaState.Arg( a, 1 ).IsTruthy ? RpMoveMode.MoveTypeNone : RpMoveMode.MoveTypeWalk;
			return null;
		} ) );
		LuaState.Register( plyMethods, "SetVelocity", ServerOnly( server, "SetVelocity", ( s, a ) =>
		{
			Player( a, "SetVelocity" ).AddVelocity( Vec( a, 1, 10000 ) );
			return null;
		} ) );
	}

	// ------------------------------------------------------------ helpers

	static LuaNativeFunction ServerOnly( bool server, string name, LuaNativeFunction f ) =>
		server ? f : ( s, a ) => throw new LuaRuntimeException( $"{name} can only be called on the server" );

	static GameObject Ent( LuaValue[] a, string m )
	{
		var e = LuaEntities.Resolve( a, 0 ) ?? throw new LuaRuntimeException( $"calling '{m}' on a removed or non-entity value" );
		return e.GameObject;
	}

	static RpPlayer Player( LuaValue[] a, string m )
	{
		var id = LuaPlayers.HandleOf( LuaState.Arg( a, 0 ) ) ?? throw new LuaRuntimeException( $"calling '{m}' on a non-player value (use ply:{m}())" );
		return LuaPlayers.Find( id ) ?? throw new LuaRuntimeException( $"calling '{m}' on a disconnected player" );
	}

	static Vector3 Vec( LuaValue[] a, int i, float max )
	{
		var v = LuaConvert.ToVector( LuaState.Arg( a, i ) );
		if ( v.Length > max ) v = v.Normal * max;
		return v;
	}

	static (float, float) VolPitch( LuaValue[] a, int i )
	{
		float vol = LuaState.ToNumber( LuaState.Arg( a, i ), out var v ) ? (float)Math.Clamp( v, 0, 4 ) : 1f;
		float pitch = LuaState.ToNumber( LuaState.Arg( a, i + 1 ), out var p ) ? (float)Math.Clamp( p, 0.1, 4 ) : 1f;
		return (vol, pitch);
	}

	static readonly System.Text.RegularExpressions.Regex SoundPattern = new( @"^[a-z0-9_\-./]{1,200}\.(sound|vsnd)$" );

	/// <summary>A sound event path ("sounds/x.sound") or a mounted package ident whose main asset is a sound.</summary>
	static string SoundPath( string raw, string fname )
	{
		var path = raw?.Trim().ToLowerInvariant() ?? "";
		// A package's own asset path is trusted as is: authors use spaces ("sounds/usp reload sequence.sound").
		if ( !path.Contains( '/' ) && Core.ContentPackages.PrimaryAssetOf( Core.ContentPackages.Normalize( path ) ) is { } asset )
		{
			if ( !asset.Contains( ".." ) && (asset.EndsWith( ".sound", StringComparison.OrdinalIgnoreCase ) || asset.EndsWith( ".vsnd", StringComparison.OrdinalIgnoreCase )) )
				return asset;
			path = asset;
		}
		if ( path.Contains( ".." ) || !SoundPattern.IsMatch( path ) )
			throw LuaState.ArgError( 0, fname, $"'{raw}' is not a sound path (sounds/....sound) or a mounted sound package" );
		return path;
	}

	internal static void PlayLocal( string path, Vector3 pos, float vol, float pitch, GameObject follow )
	{
		var h = Sound.Play( path, pos );
		if ( h is null ) return;
		h.Volume = vol;
		h.Pitch = pitch;
		if ( follow.IsValid() ) { h.Parent = follow; h.FollowParent = true; }
	}

	[Rpc.Broadcast( NetFlags.HostOnly )]
	static void PlayAt( string path, Vector3 pos, float vol, float pitch )
	{
		try { PlayLocal( SoundPath( path, "sound" ), pos, Math.Clamp( vol, 0, 4 ), Math.Clamp( pitch, 0.1f, 4 ), null ); }
		catch ( Exception ) { /* bad data from the host: ignore */ }
	}

	[Rpc.Broadcast( NetFlags.HostOnly )]
	static void PlayOn( Guid objectId, string path, float vol, float pitch )
	{
		var go = Game.ActiveScene?.Directory.FindByGuid( objectId );
		if ( !go.IsValid() ) return;
		try { PlayLocal( SoundPath( path, "sound" ), go.WorldPosition, Math.Clamp( vol, 0, 4 ), Math.Clamp( pitch, 0.1f, 4 ), go ); }
		catch ( Exception ) { }
	}

	// ------------------------------------------------------------ constraints

	sealed class ConstraintInfo
	{
		public string Id;
		public string Type;
		public GameObject A, B;
		public Component Joint;
		public GameObject Rope;
	}

	static readonly List<ConstraintInfo> _constraints = new();

	static void Prune() => _constraints.RemoveAll( c => !c.A.IsValid() || (c.B is not null && !c.B.IsValid()) || !c.Joint.IsValid() );

	static void RegisterConstraints( LuaRealm realm )
	{
		var L = realm.State;
		var lib = L.GetOrCreateLibrary( "constraint" );

		(GameObject, GameObject) Pair( LuaValue[] a, string fname )
		{
			var e1 = LuaEntities.Resolve( a, 0 ) ?? throw LuaState.ArgError( 0, fname, "entity expected" );
			if ( e1.Components.Get<Rigidbody>() is null ) throw LuaState.ArgError( 0, fname, "the first entity needs physics" );
			GameObject b = null;
			if ( !LuaState.Arg( a, 1 ).IsNil )
			{
				var e2 = LuaEntities.Resolve( a, 1 ) ?? throw LuaState.ArgError( 1, fname, "entity or nil (the world) expected" );
				if ( e2.GameObject == e1.GameObject ) throw LuaState.ArgError( 1, fname, "can't constrain an entity to itself" );
				b = e2.GameObject;
			}
			Prune();
			if ( _constraints.Count >= MaxConstraints ) throw new LuaRuntimeException( $"too many constraints (limit {MaxConstraints})" );
			return (e1.GameObject, b);
		}

		LuaValue Add( string type, GameObject a, GameObject b, Joint j, GameObject rope = null )
		{
			var c = new ConstraintInfo { Id = j.Id.ToString(), Type = type, A = a, B = b, Joint = j, Rope = rope };
			_constraints.Add( c );
			return Describe( realm, c );
		}

		Transform LocalFrame( GameObject go, Vector3 world ) =>
			go is null ? new Transform( world ) : new Transform( go.WorldTransform.PointToLocal( world ) );

		// constraint.Weld(ent1, ent2 or nil [, breakForce]) - rigidly joined (nil = to the world)
		LuaState.Register( lib, "Weld", ( s, a ) =>
		{
			var (ga, gb) = Pair( a, "constraint.Weld" );
			var j = ga.Components.Create<FixedJoint>();
			j.Body = gb;
			j.EnableCollision = false;
			if ( LuaState.ToNumber( LuaState.Arg( a, 2 ), out var bf ) && bf > 0 ) j.BreakForce = (float)bf;
			return new[] { Add( "Weld", ga, gb, j ) };
		} );

		// constraint.Ballsocket(ent1, ent2 or nil, worldPos) - free rotation around a point
		LuaState.Register( lib, "Ballsocket", ( s, a ) =>
		{
			var (ga, gb) = Pair( a, "constraint.Ballsocket" );
			var pos = LuaConvert.ToVector( LuaState.Arg( a, 2 ), "worldPos" );
			var j = ga.Components.Create<BallJoint>();
			j.Body = gb;
			j.Attachment = Joint.AttachmentMode.LocalFrames;
			j.LocalFrame1 = LocalFrame( ga, pos );
			j.LocalFrame2 = LocalFrame( gb, pos );
			j.EnableCollision = false;
			return new[] { Add( "Ballsocket", ga, gb, j ) };
		} );

		// constraint.Rope(ent1, ent2 or nil, worldPos1, worldPos2 [, extraLength [, width [, color]]]) - at most that long
		LuaState.Register( lib, "Rope", ( s, a ) =>
		{
			var (ga, gb) = Pair( a, "constraint.Rope" );
			var p1 = LuaConvert.ToVector( LuaState.Arg( a, 2 ), "worldPos1" );
			var p2 = LuaConvert.ToVector( LuaState.Arg( a, 3 ), "worldPos2" );
			float extra = LuaState.ToNumber( LuaState.Arg( a, 4 ), out var ex ) ? (float)Math.Clamp( ex, 0, 10000 ) : 0f;
			float width = LuaState.ToNumber( LuaState.Arg( a, 5 ), out var w ) ? (float)Math.Clamp( w, 0.2, 20 ) : 1.5f;
			var j = ga.Components.Create<SpringJoint>();
			j.Body = gb;
			j.Attachment = Joint.AttachmentMode.LocalFrames;
			j.LocalFrame1 = LocalFrame( ga, p1 );
			j.LocalFrame2 = LocalFrame( gb, p2 );
			j.MinLength = 0;
			j.MaxLength = p1.Distance( p2 ) + extra;
			j.RestLength = j.MaxLength;
			j.Frequency = 0;
			j.Damping = 0;
			j.EnableCollision = true;
			var rope = RpRope.Create( ga, gb, j.LocalFrame1.Position, j.LocalFrame2.Position, width, ColorArg( LuaState.Arg( a, 6 ) ) );
			return new[] { Add( "Rope", ga, gb, j, rope ) };
		} );

		// constraint.NoCollide(ent1, ent2) - the two stop colliding with each other
		LuaState.Register( lib, "NoCollide", ( s, a ) =>
		{
			var (ga, gb) = Pair( a, "constraint.NoCollide" );
			if ( gb is null ) throw LuaState.ArgError( 1, "constraint.NoCollide", "two entities expected" );
			var j = ga.Components.Create<SpringJoint>();
			j.Body = gb;
			j.MinLength = 0;
			j.MaxLength = 1000000;
			j.Frequency = 0;
			j.Damping = 0;
			j.EnableCollision = false;
			return new[] { Add( "NoCollide", ga, gb, j ) };
		} );

		IEnumerable<ConstraintInfo> Of( LuaValue[] a, string fname )
		{
			var e = LuaEntities.Resolve( a, 0 ) ?? throw LuaState.ArgError( 0, fname, "entity expected" );
			Prune();
			return _constraints.Where( c => c.A == e.GameObject || c.B == e.GameObject ).ToList();
		}

		LuaState.Register( lib, "GetAll", ( s, a ) =>
		{
			var t = new LuaTable();
			foreach ( var c in Of( a, "constraint.GetAll" ) ) t.Append( Describe( realm, c ) );
			return new LuaValue[] { t };
		} );
		LuaState.Register( lib, "RemoveAll", ( s, a ) =>
		{
			int n = 0;
			foreach ( var c in Of( a, "constraint.RemoveAll" ) ) { Destroy( c ); n++; }
			return new LuaValue[] { n };
		} );
		LuaState.Register( lib, "RemoveConstraints", ( s, a ) =>
		{
			var type = LuaState.CheckString( a, 1, "constraint.RemoveConstraints" );
			int n = 0;
			foreach ( var c in Of( a, "constraint.RemoveConstraints" ).Where( c => c.Type == type ) ) { Destroy( c ); n++; }
			return new LuaValue[] { n };
		} );
		LuaState.Register( lib, "Remove", ( s, a ) =>
		{
			var v = LuaState.Arg( a, 0 );
			var id = v.IsTable ? v.AsTable.Get( "id" ) : v;
			if ( !id.IsString ) throw LuaState.ArgError( 0, "constraint.Remove", "a constraint (or its id) expected" );
			var c = _constraints.FirstOrDefault( x => x.Id == id.AsString );
			if ( c is null ) return new LuaValue[] { false };
			Destroy( c );
			return new LuaValue[] { true };
		} );
		LuaState.Register( lib, "HasConstraints", ( s, a ) => new LuaValue[] { Of( a, "constraint.HasConstraints" ).Any() } );
	}

	static Color ColorArg( LuaValue v )
	{
		if ( !v.IsTable ) return new Color( 0.15f, 0.12f, 0.1f );
		var t = v.AsTable;
		float Ch( string k, float d ) => LuaState.ToNumber( t.Get( k ), out var x ) ? (float)Math.Clamp( x / 255.0, 0, 1 ) : d;
		return new Color( Ch( "r", 0 ), Ch( "g", 0 ), Ch( "b", 0 ), Ch( "a", 1 ) );
	}

	static void Destroy( ConstraintInfo c )
	{
		if ( c.Joint.IsValid() ) c.Joint.Destroy();
		if ( c.Rope.IsValid() ) c.Rope.Destroy();
		_constraints.Remove( c );
		if ( c.A.IsValid() && c.A.Components.Get<Rigidbody>() is { } rb ) rb.Sleeping = false;
	}

	static LuaValue Describe( LuaRealm realm, ConstraintInfo c )
	{
		var t = new LuaTable();
		t.Set( "id", c.Id );
		t.Set( "type", c.Type );
		var e1 = c.A.IsValid() ? c.A.Components.Get<LuaEntity>() : null;
		var e2 = c.B.IsValid() ? c.B.Components.Get<LuaEntity>() : null;
		t.Set( "Ent1", e1 is null ? LuaValue.Nil : LuaEntities.Wrap( realm, e1 ) );
		t.Set( "Ent2", e2 is null ? LuaValue.Nil : LuaEntities.Wrap( realm, e2 ) );
		return t;
	}

	/// <summary>Removes every constraint (world end / reload).</summary>
	public static void Clear()
	{
		foreach ( var c in _constraints.ToList() ) Destroy( c );
		_constraints.Clear();
	}
}

/// <summary>
/// Visible rope between two objects (or an object and a fixed world point): a networked object whose endpoints are
/// synced from the host, drawn with a LineRenderer on every machine.
/// </summary>
public sealed class RpRope : Component
{
	[Sync( SyncFlags.FromHost )] public GameObject A { get; set; }
	[Sync( SyncFlags.FromHost )] public GameObject B { get; set; }
	[Sync( SyncFlags.FromHost )] public Vector3 LocalA { get; set; }
	[Sync( SyncFlags.FromHost )] public Vector3 LocalB { get; set; }
	[Sync( SyncFlags.FromHost )] public float Width { get; set; } = 1.5f;
	[Sync( SyncFlags.FromHost )] public Color Tint { get; set; } = Color.Black;

	LineRenderer _line;

	public static GameObject Create( GameObject a, GameObject b, Vector3 localA, Vector3 localB, float width, Color tint )
	{
		var go = new GameObject( true, "rope" );
		var r = go.Components.Create<RpRope>();
		r.A = a; r.B = b; r.LocalA = localA; r.LocalB = localB; r.Width = width; r.Tint = tint;
		if ( Networking.IsActive ) go.NetworkSpawn();
		return go;
	}

	protected override void OnUpdate()
	{
		if ( !A.IsValid() ) { if ( !IsProxy ) GameObject.Destroy(); return; }
		_line ??= Components.GetOrCreate<LineRenderer>();
		var p1 = A.WorldTransform.PointToWorld( LocalA );
		var p2 = B.IsValid() ? B.WorldTransform.PointToWorld( LocalB ) : LocalB;
		_line.UseVectorPoints = true;
		_line.VectorPoints = new List<Vector3> { p1, p2 };
		_line.Width = Width;
		_line.Color = Tint;
	}
}