Framework/Scripting/Api/LuaUi.World.cs

Lua bindings for retained 3D UI: ui.CreateWorld makes a Sandbox.WorldPanel GameObject with a Lua panel as its root, and the file exposes SetWorldPos, SetWorldAngles, SetWorldScale, SetFaceCamera and AttachTo. Placement uses GMod cam.Start3D2D orientation conventions, with a cap of 512 world panels and per-panel CSS size tracked for scale changes.

using System;
using System.Collections.Generic;
using System.Linq;
using RoleplayFramework.Lua;
using Sandbox.UI;

namespace RoleplayFramework.Scripting;

/// <summary>
/// Retained 3D UI: panels placed in the world (client only).
///
///   local p = ui.CreateWorld({ pos = Vector, ang = Angle, scale = 0.1, width = 512, height = 256,
///                              parent = ent|ply, facecamera = false, anchor = "center"|"topleft", classes = "" })
///   p:SetWorldPos(v)  p:SetWorldAngles(a)  p:SetWorldScale(s)  p:AttachTo(ent|ply|nil [, offset [, ang]])  p:SetFaceCamera(b)
///
/// The returned panel is a normal Lua panel: add children with ui.Create(kind, p), style them with ui.AddStyle/SetStyle.
/// Orientation follows GMod's cam.Start3D2D: x runs along ang:Forward(), y along ang:Right(), and the readable side
/// faces ang:Up(). scale = world units per pixel (GMod's 0.1 means 10 pixels per unit).
/// </summary>
public static partial class LuaUi
{
	public const int MaxWorldPanels = 512;

	/// <summary>Engine world panels: 1 pixel = this many units at GameObject scale 1.</summary>
	public const float EnginePixelSize = 0.05f;

	static readonly Dictionary<Panel, GameObject> _worldRoots = new();
	static readonly Dictionary<Panel, Vector2> _worldCssSize = new();

	/// <summary>
	/// The object scale also scales the CSS pixels inside an engine world panel, but not its PanelSize, so the panel
	/// area has to grow with it for the CSS size to stay what Lua asked for.
	/// </summary>
	internal static void ApplyScale( GameObject go, Vector2 cssSize, double unitsPerPixel )
	{
		var s = ObjectScaleFor( unitsPerPixel );
		go.WorldScale = s;
		go.Components.Get<Sandbox.WorldPanel>().PanelSize = cssSize * s;
	}

	static void ResetWorld()
	{
		foreach ( var go in _worldRoots.Values ) if ( go.IsValid() ) go.Destroy();
		_worldRoots.Clear();
		_worldCssSize.Clear();
		LuaDraw.Reset();
	}

	/// <summary>GMod 3D2D angles → the rotation of an engine world panel (which faces its Forward, x along Left).</summary>
	public static Rotation From3D2D( Angles a )
	{
		var r = a.ToRotation();
		return Rotation.LookAt( r.Up, -r.Right );
	}

	public static float ObjectScaleFor( double unitsPerPixel ) => (float)Math.Clamp( unitsPerPixel, 0.001, 10 ) / EnginePixelSize;

	internal static GameObject CreateWorldObject( string name, Vector2 size, bool centered )
	{
		var go = new GameObject( true, name );
		go.NetworkMode = NetworkMode.Never;
		var wp = go.Components.Create<Sandbox.WorldPanel>();
		wp.PanelSize = size;
		wp.HorizontalAlign = centered ? Sandbox.WorldPanel.HAlignment.Center : Sandbox.WorldPanel.HAlignment.Left;
		wp.VerticalAlign = centered ? Sandbox.WorldPanel.VAlignment.Center : Sandbox.WorldPanel.VAlignment.Top;
		wp.InteractionRange = 0;
		return go;
	}

	static GameObject ObjectOf( LuaValue v )
	{
		if ( LuaEntities.HandleOf( v ) is { } eid ) return Game.ActiveScene?.Directory.FindByGuid( eid );
		if ( LuaPlayers.HandleOf( v ) is { } pid ) return LuaPlayers.Find( pid )?.GameObject;
		return null;
	}

	static void RegisterWorld( LuaRealm realm, LuaTable ui, Action<string, LuaNativeFunction> M )
	{
		LuaState.Register( ui, "CreateWorld", ( s, a ) =>
		{
			var o = LuaState.Arg( a, 0 ).IsTable ? LuaState.Arg( a, 0 ).AsTable : new LuaTable();
			_worldRoots.Keys.Where( p => !p.IsValid() ).ToList().ForEach( p => _worldRoots.Remove( p ) );
			if ( _worldRoots.Count >= MaxWorldPanels ) throw new LuaRuntimeException( $"too many world panels (limit {MaxWorldPanels})" );

			double Num( string k, double def ) => LuaState.ToNumber( o.Get( k ), out var d ) ? d : def;
			var w = (float)Math.Clamp( Num( "width", 512 ), 1, 4096 );
			var h = (float)Math.Clamp( Num( "height", 256 ), 1, 4096 );
			var centered = !(o.Get( "anchor" ).IsString && o.Get( "anchor" ).AsString == "topleft");

			var go = CreateWorldObject( "lua world panel", new Vector2( w, h ), centered );
			var wp = go.Components.Get<Sandbox.WorldPanel>();
			wp.LookAtCamera = o.Get( "facecamera" ).IsTruthy;

			var parentObj = ObjectOf( o.Get( "parent" ) );
			var pos = o.Get( "pos" ).IsNil ? Vector3.Zero : LuaConvert.ToVector( o.Get( "pos" ), "pos" );
			var ang = o.Get( "ang" ).IsNil ? new Angles( 0, 0, 0 ) : LuaConvert.ToAngles( o.Get( "ang" ), "ang" );
			if ( parentObj is not null )
			{
				go.SetParent( parentObj, false );
				go.LocalPosition = pos;
				go.LocalRotation = From3D2D( ang );
			}
			else
			{
				go.WorldPosition = pos;
				go.WorldRotation = From3D2D( ang );
			}

			ApplyScale( go, new Vector2( w, h ), Num( "scale", 0.1 ) ); // after parenting: world scale, not relative to the entity

			var root = wp.GetPanel();
			root.StyleSheet.Parse( BaseCss, false );
			foreach ( var css in _css ) root.StyleSheet.Parse( css, false );
			root.AddClass( "lua-world" );
			var classes = o.Get( "classes" ).IsString ? o.Get( "classes" ).AsString : "";
			if ( !string.IsNullOrWhiteSpace( classes ) ) root.AddClass( classes );

			_worldRoots[root] = go;
			_worldCssSize[root] = new Vector2( w, h );
			return new[] { Wrap( root ) };
		} );

		GameObject WorldGo( LuaValue[] a, string name )
		{
			var p = Check( a, name );
			return _worldRoots.TryGetValue( p, out var go ) && go.IsValid() ? go
				: throw new LuaRuntimeException( $"{name} needs a panel made with ui.CreateWorld" );
		}

		M( "SetWorldPos", ( s, a ) =>
		{
			var go = WorldGo( a, "SetWorldPos" );
			var v = LuaConvert.ToVector( LuaState.Arg( a, 1 ) );
			if ( go.Parent is not null && go.Parent != Game.ActiveScene ) go.LocalPosition = v; else go.WorldPosition = v;
			return null;
		} );
		M( "SetWorldAngles", ( s, a ) =>
		{
			var go = WorldGo( a, "SetWorldAngles" );
			var r = From3D2D( LuaConvert.ToAngles( LuaState.Arg( a, 1 ) ) );
			if ( go.Parent is not null && go.Parent != Game.ActiveScene ) go.LocalRotation = r; else go.WorldRotation = r;
			return null;
		} );
		M( "SetWorldScale", ( s, a ) =>
		{
			var go = WorldGo( a, "SetWorldScale" );
			ApplyScale( go, _worldCssSize.TryGetValue( Check( a, "SetWorldScale" ), out var css ) ? css : new Vector2( 512, 256 ), LuaState.CheckNumber( a, 1, "SetWorldScale" ) );
			return null;
		} );
		M( "SetFaceCamera", ( s, a ) =>
		{
			WorldGo( a, "SetFaceCamera" ).Components.Get<Sandbox.WorldPanel>().LookAtCamera = LuaState.Arg( a, 1 ).IsTruthy;
			return null;
		} );
		M( "AttachTo", ( s, a ) =>
		{
			var go = WorldGo( a, "AttachTo" );
			var scale = go.WorldScale;
			var target = ObjectOf( LuaState.Arg( a, 1 ) );
			if ( target is null )
			{
				var wpos = go.WorldPosition; var wrot = go.WorldRotation;
				go.SetParent( null, false );
				go.WorldPosition = wpos; go.WorldRotation = wrot;
			}
			else
			{
				go.SetParent( target, false );
				go.LocalPosition = LuaState.Arg( a, 2 ).IsNil ? Vector3.Zero : LuaConvert.ToVector( LuaState.Arg( a, 2 ), "offset" );
				go.LocalRotation = From3D2D( LuaState.Arg( a, 3 ).IsNil ? new Angles( 0, 0, 0 ) : LuaConvert.ToAngles( LuaState.Arg( a, 3 ), "ang" ) );
			}
			go.WorldScale = scale;
			return null;
		} );
	}
}