Framework/Scripting/Api/LuaDraw.cs

Client-side Lua drawing API for a roleplay framework. Runs the PostDrawOpaqueRenderables, PostDrawTranslucentRenderables and HUDPaint hooks each frame and maps cam.Start3D2D, draw.* and surface.* calls onto pooled UI panels on a WorldPanel or the screen root, restyling a panel only when what it draws changes.

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

namespace RoleplayFramework.Scripting;

/// <summary>
/// GMod-style immediate drawing (client only). Each frame the client realm runs:
///   hook "PostDrawOpaqueRenderables"(false, false), hook "PostDrawTranslucentRenderables"(false, false)  → 3D2D
///   hook "HUDPaint"                                                                                      → screen
/// Inside them:
///   cam.Start3D2D(pos, ang, scale) ... cam.End3D2D()
///   draw.SimpleText(text, font, x, y, color, xalign, yalign)   draw.SimpleTextOutlined(..., outlineWidth, outlineColor)
///   draw.DrawText(text, font, x, y, color, xalign)             draw.RoundedBox(radius, x, y, w, h, color)
///   surface.SetDrawColor(r, g, b, a | Color)  surface.DrawRect(x, y, w, h)  surface.DrawOutlinedRect(x, y, w, h [, t])
///   surface.SetFont(name)  surface.SetTextColor(..)  surface.SetTextPos(x, y)  surface.DrawText(text)
///   surface.CreateFont(name, { font, size, weight })  surface.GetTextSize(text) (estimate)
///   ScrW()  ScrH()  TEXT_ALIGN_LEFT/CENTER/RIGHT/TOP/BOTTOM
///
/// Drawing is mapped onto pooled panels that are only restyled when what is drawn changes, so static text costs
/// almost nothing per frame. Outside the hooks the functions raise an error.
/// </summary>
public static class LuaDraw
{
	public const int MaxCanvases = 256;
	public const int MaxOpsPerFrame = 6000;
	const float Half = 2048f;                 // 3D2D canvases are 4096 px with (0,0) at the centre
	const float AlignBox = 4000f;             // width/height of the flex box used to align text

	public const int AlignLeft = 0, AlignCenter = 1, AlignRight = 2, AlignTop = 3, AlignBottom = 4;

	sealed class Slot
	{
		public Panel Box;
		public Label Text;
		public string Sig;
	}

	sealed class Canvas
	{
		public GameObject Go;          // null for the screen canvas
		public Panel Root;
		public readonly List<Slot> Slots = new();
		public int Used;
		public double Scale = -1;
	}

	sealed class Font { public string Family; public int Size; public int Weight; }

	static readonly List<Canvas> _canvases = new();
	static Canvas _screen;
	static Canvas _current;
	static int _canvasIndex, _ops;
	static bool _inHook;
	static float _offset;              // Half for 3D2D canvases, 0 on screen

	static readonly Dictionary<string, Font> _fonts = new( StringComparer.OrdinalIgnoreCase );
	static string _font = "DermaDefault";
	static Color _drawColor = Color.White, _textColor = Color.White;
	static Vector2 _textPos;

	static LuaDraw() => ResetFonts();

	static void ResetFonts()
	{
		_fonts.Clear();
		void F( string n, int size, int weight = 500, string family = "Inter" ) => _fonts[n] = new Font { Family = family, Size = size, Weight = weight };
		F( "DermaDefault", 13 ); F( "DermaDefaultBold", 13, 800 ); F( "DermaLarge", 32 );
		F( "Trebuchet18", 18 ); F( "Trebuchet24", 24 ); F( "ChatFont", 18, 800 ); F( "TargetID", 24, 800 ); F( "TargetIDSmall", 18, 800 );
		F( "HudHintTextLarge", 14 ); F( "HudHintTextSmall", 11 ); F( "CloseCaption_Normal", 26 ); F( "CloseCaption_Bold", 26, 800 );
		F( "GModNotify", 20 ); F( "HudSelectionText", 13, 800 ); F( "BudgetLabel", 14 ); F( "Default", 13 ); F( "HUDNumber5", 45, 800 );
	}

	public static void Reset()
	{
		foreach ( var c in _canvases ) if ( c.Go.IsValid() ) c.Go.Destroy();
		_canvases.Clear();
		if ( _screen?.Root is { } r && r.IsValid() ) r.Delete( true );
		_screen = null;
		_current = null;
		_inHook = false;
		ResetFonts();
	}

	// ------------------------------------------------------------------ frame

	/// <summary>Called every frame by the client tick: runs the draw hooks and hides whatever wasn't drawn.</summary>
	/// <summary>True while the 3D/HUD drawing hooks run (render.DrawBeam is only allowed then).</summary>
	internal static bool InHook => _inHook;

	public static void Frame( LuaRealm realm )
	{
		LuaRender.BeginFrame();
		_canvasIndex = 0;
		_ops = 0;
		_inHook = true;
		try
		{
			realm.RunHook( "PostDrawOpaqueRenderables", false, false );
			Close();
			realm.RunHook( "PostDrawTranslucentRenderables", false, false );
			Close();

			var screen = Screen2D();
			if ( screen is not null )
			{
				screen.Used = 0;
				_current = screen; _offset = 0;
				realm.RunHook( "HUDPaint" );
				HideRest( screen );
				_current = null;
			}
		}
		finally
		{
			_inHook = false;
			_current = null;
			LuaRender.EndFrame();
		}

		for ( int i = 0; i < _canvases.Count; i++ )
		{
			var c = _canvases[i];
			bool on = i < _canvasIndex;
			if ( c.Go.IsValid() && c.Go.Enabled != on ) c.Go.Enabled = on;
		}
	}

	static void Close()
	{
		if ( _current is not null && _current != _screen ) { HideRest( _current ); _current = null; }
	}

	static Canvas Screen2D()
	{
		if ( _screen?.Root is { } r && r.IsValid() ) return _screen;
		try
		{
			var root = LuaUi.ScreenRoot;
			var p = new Panel( root, "lua-hudpaint" );
			p.Style.Set( "position: absolute; left: 0; top: 0; right: 0; bottom: 0; pointer-events: none;" );
			_screen = new Canvas { Root = p };
			return _screen;
		}
		catch ( LuaRuntimeException ) { return null; } // world without a ScreenPanel
	}

	static void HideRest( Canvas c )
	{
		for ( int i = c.Used; i < c.Slots.Count; i++ )
		{
			var s = c.Slots[i];
			if ( s.Sig == "hidden" ) continue;
			s.Sig = "hidden";
			s.Box.Style.Set( "display: none;" );
		}
	}

	static Canvas Need( string fname )
	{
		if ( _current is null )
			throw new LuaRuntimeException( $"{fname} can only be used inside HUDPaint or between cam.Start3D2D and cam.End3D2D (in PostDrawOpaqueRenderables / PostDrawTranslucentRenderables)" );
		if ( ++_ops > MaxOpsPerFrame ) throw new LuaRuntimeException( $"too many draw calls this frame (limit {MaxOpsPerFrame})" );
		return _current;
	}

	static Slot NextSlot( Canvas c )
	{
		if ( c.Used < c.Slots.Count ) return c.Slots[c.Used++];
		var box = new Panel( c.Root );
		var slot = new Slot { Box = box, Sig = null };
		c.Slots.Add( slot );
		c.Used++;
		return slot;
	}

	// ------------------------------------------------------------------ primitives

	static string Css( Color c ) => $"rgba({(int)(c.r * 255)},{(int)(c.g * 255)},{(int)(c.b * 255)},{c.a.ToString( "0.###", CultureInfo.InvariantCulture )})";
	static string Px( double v ) => v.ToString( "0.##", CultureInfo.InvariantCulture ) + "px";

	static void Rect( double x, double y, double w, double h, Color color, double radius, double border, string fname )
	{
		var c = Need( fname );
		var slot = NextSlot( c );
		x += _offset; y += _offset;
		var sig = $"r|{x}|{y}|{w}|{h}|{color}|{radius}|{border}";
		if ( slot.Sig == sig ) return;
		slot.Sig = sig;
		if ( slot.Text is not null ) { slot.Text.Delete( true ); slot.Text = null; }
		var fill = border > 0 ? $"background-color: transparent; border: {Px( border )} solid {Css( color )};" : $"background-color: {Css( color )}; border-width: 0px;";
		slot.Box.Style.Set( $"display: flex; position: absolute; left: {Px( x )}; top: {Px( y )}; width: {Px( Math.Max( 0, w ) )}; height: {Px( Math.Max( 0, h ) )}; {fill} border-radius: {Px( radius )};" );
	}

	static void Text( string text, string font, double x, double y, Color color, int xalign, int yalign, double outline, Color outlineColor, bool multiline, string fname )
	{
		var c = Need( fname );
		var slot = NextSlot( c );
		x += _offset; y += _offset;
		var f = _fonts.TryGetValue( font ?? "", out var ff ) ? ff : _fonts["DermaDefault"];
		var sig = $"t|{text}|{font}|{x}|{y}|{color}|{xalign}|{yalign}|{outline}|{outlineColor}";
		if ( slot.Sig == sig ) return;
		slot.Sig = sig;

		// A big flex box positioned so that its left/centre/right (top/middle/bottom) edge lands on (x, y).
		double left = xalign switch { AlignCenter => x - AlignBox / 2, AlignRight => x - AlignBox, _ => x };
		double top = yalign switch { AlignCenter => y - AlignBox / 2, AlignBottom => y - AlignBox, _ => y };
		string justify = xalign switch { AlignCenter => "center", AlignRight => "flex-end", _ => "flex-start" };
		string alignItems = yalign switch { AlignCenter => "center", AlignBottom => "flex-end", _ => "flex-start" };
		slot.Box.Style.Set( $"display: flex; position: absolute; left: {Px( left )}; top: {Px( top )}; width: {Px( AlignBox )}; height: {Px( AlignBox )}; " +
			$"justify-content: {justify}; align-items: {alignItems}; background-color: transparent; border-width: 0px; pointer-events: none;" );

		slot.Text ??= new Label { Parent = slot.Box };
		slot.Text.Text = text;
		var shadow = outline > 0
			? $"text-stroke: {Px( outline * 2 )} {Css( outlineColor )};"
			: "";
		slot.Text.Style.Set( $"font-family: {f.Family}; font-size: {f.Size}px; font-weight: {f.Weight}; color: {Css( color )}; white-space: {(multiline ? "pre" : "nowrap")}; " +
			$"text-align: {(xalign == AlignCenter ? "center" : xalign == AlignRight ? "right" : "left")}; {shadow}" );
	}

	// ------------------------------------------------------------------ Lua

	static Color ColorArg( LuaValue[] a, int i, Color fallback )
	{
		var v = LuaState.Arg( a, i );
		if ( !v.IsTable ) return fallback;
		var t = v.AsTable;
		float Ch( string k, double def ) => (float)Math.Clamp( (LuaState.ToNumber( t.Get( k ), out var d ) ? d : def) / 255.0, 0, 1 );
		return new Color( Ch( "r", 255 ), Ch( "g", 255 ), Ch( "b", 255 ), Ch( "a", 255 ) );
	}

	static Color Rgba( LuaValue[] a, int i )
	{
		if ( LuaState.Arg( a, i ).IsTable ) return ColorArg( a, i, Color.White );
		float N( int k, double def ) => (float)Math.Clamp( (LuaState.ToNumber( LuaState.Arg( a, k ), out var d ) ? d : def) / 255.0, 0, 1 );
		return new Color( N( i, 255 ), N( i + 1, 255 ), N( i + 2, 255 ), N( i + 3, 255 ) );
	}

	static double Num( LuaValue[] a, int i, double def = 0 ) => LuaState.ToNumber( LuaState.Arg( a, i ), out var d ) && !double.IsNaN( d ) && !double.IsInfinity( d ) ? d : def;
	static int Align( LuaValue[] a, int i, int def ) => LuaState.ToNumber( LuaState.Arg( a, i ), out var d ) ? (int)d : def;
	static string Str( LuaState L, LuaValue[] a, int i ) { var s = L.ToStringMeta( LuaState.Arg( a, i ) ); return s.Length > 2000 ? s.Substring( 0, 2000 ) : s; }
	static string FontArg( LuaValue[] a, int i ) => LuaState.Arg( a, i ).IsString ? LuaState.Arg( a, i ).AsString : _font;

	public static void Register( LuaRealm realm )
	{
		if ( realm.Kind != LuaRealmKind.Client ) return;
		var L = realm.State;
		var G = L.Globals;
		G.Set( "TEXT_ALIGN_LEFT", AlignLeft ); G.Set( "TEXT_ALIGN_CENTER", AlignCenter ); G.Set( "TEXT_ALIGN_RIGHT", AlignRight );
		G.Set( "TEXT_ALIGN_TOP", AlignTop ); G.Set( "TEXT_ALIGN_BOTTOM", AlignBottom );
		// HUDPaint coordinates are UI units (the screen panel scales with resolution), so ScrW/ScrH are too.
		L.Register( "ScrW", ( s, a ) => new LuaValue[] { Math.Round( Screen.Width / UiScale() ) } );
		L.Register( "ScrH", ( s, a ) => new LuaValue[] { Math.Round( Screen.Height / UiScale() ) } );

		var cam = L.GetOrCreateLibrary( "cam" );
		LuaState.Register( cam, "Start3D2D", ( s, a ) =>
		{
			if ( !_inHook ) throw new LuaRuntimeException( "cam.Start3D2D can only be used in PostDrawOpaqueRenderables / PostDrawTranslucentRenderables" );
			if ( _current is not null && _current != _screen ) throw new LuaRuntimeException( "cam.Start3D2D: already inside a 3D2D block (call cam.End3D2D first)" );
			if ( _canvasIndex >= MaxCanvases ) throw new LuaRuntimeException( $"too many 3D2D blocks this frame (limit {MaxCanvases})" );
			var pos = LuaConvert.ToVector( LuaState.Arg( a, 0 ), "pos" );
			var ang = LuaConvert.ToAngles( LuaState.Arg( a, 1 ), "ang" );
			var scale = LuaState.CheckNumber( a, 2, "cam.Start3D2D" );

			if ( _canvasIndex >= _canvases.Count )
			{
				var go = LuaUi.CreateWorldObject( "lua 3d2d", new Vector2( Half * 2, Half * 2 ), true );
				var root = go.Components.Get<Sandbox.WorldPanel>().GetPanel();
				root.Style.Set( "pointer-events: none;" );
				_canvases.Add( new Canvas { Go = go, Root = root } );
			}
			var c = _canvases[_canvasIndex++];
			c.Go.WorldPosition = pos;
			c.Go.WorldRotation = LuaUi.From3D2D( ang );
			if ( c.Scale != scale ) { LuaUi.ApplyScale( c.Go, new Vector2( Half * 2, Half * 2 ), scale ); c.Scale = scale; }
			c.Used = 0;
			_current = c;
			_offset = Half;
			return null;
		} );
		LuaState.Register( cam, "End3D2D", ( s, a ) =>
		{
			if ( _current is null || _current == _screen ) throw new LuaRuntimeException( "cam.End3D2D without cam.Start3D2D" );
			HideRest( _current );
			_current = null;
			return null;
		} );

		var draw = L.GetOrCreateLibrary( "draw" );
		LuaState.Register( draw, "SimpleText", ( s, a ) =>
		{
			Text( Str( s, a, 0 ), FontArg( a, 1 ), Num( a, 2 ), Num( a, 3 ), ColorArg( a, 4, Color.White ), Align( a, 5, AlignLeft ), Align( a, 6, AlignTop ), 0, Color.Black, false, "draw.SimpleText" );
			return null;
		} );
		LuaState.Register( draw, "SimpleTextOutlined", ( s, a ) =>
		{
			Text( Str( s, a, 0 ), FontArg( a, 1 ), Num( a, 2 ), Num( a, 3 ), ColorArg( a, 4, Color.White ), Align( a, 5, AlignLeft ), Align( a, 6, AlignTop ),
				Math.Clamp( Num( a, 7 ), 0, 10 ), ColorArg( a, 8, Color.Black ), false, "draw.SimpleTextOutlined" );
			return null;
		} );
		LuaState.Register( draw, "DrawText", ( s, a ) =>
		{
			Text( Str( s, a, 0 ), FontArg( a, 1 ), Num( a, 2 ), Num( a, 3 ), ColorArg( a, 4, Color.White ), Align( a, 5, AlignLeft ), AlignTop, 0, Color.Black, true, "draw.DrawText" );
			return null;
		} );
		LuaNativeFunction rounded = ( s, a ) =>
		{
			Rect( Num( a, 1 ), Num( a, 2 ), Num( a, 3 ), Num( a, 4 ), ColorArg( a, 5, Color.White ), Math.Max( 0, Num( a, 0 ) ), 0, "draw.RoundedBox" );
			return null;
		};
		LuaState.Register( draw, "RoundedBox", rounded );
		LuaState.Register( draw, "RoundedBoxEx", rounded ); // per-corner flags are ignored: all corners are rounded

		var surface = L.GetOrCreateLibrary( "surface" );
		LuaState.Register( surface, "SetDrawColor", ( s, a ) => { _drawColor = Rgba( a, 0 ); return null; } );
		LuaState.Register( surface, "SetTextColor", ( s, a ) => { _textColor = Rgba( a, 0 ); return null; } );
		LuaState.Register( surface, "SetFont", ( s, a ) => { _font = LuaState.CheckString( a, 0, "surface.SetFont" ); return null; } );
		LuaState.Register( surface, "SetTextPos", ( s, a ) => { _textPos = new Vector2( (float)Num( a, 0 ), (float)Num( a, 1 ) ); return null; } );
		LuaState.Register( surface, "DrawRect", ( s, a ) => { Rect( Num( a, 0 ), Num( a, 1 ), Num( a, 2 ), Num( a, 3 ), _drawColor, 0, 0, "surface.DrawRect" ); return null; } );
		LuaState.Register( surface, "DrawOutlinedRect", ( s, a ) =>
		{
			Rect( Num( a, 0 ), Num( a, 1 ), Num( a, 2 ), Num( a, 3 ), _drawColor, 0, Math.Max( 1, Num( a, 4, 1 ) ), "surface.DrawOutlinedRect" );
			return null;
		} );
		LuaState.Register( surface, "DrawText", ( s, a ) =>
		{
			var text = Str( s, a, 0 );
			Text( text, _font, _textPos.x, _textPos.y, _textColor, AlignLeft, AlignTop, 0, Color.Black, false, "surface.DrawText" );
			_textPos.x += (float)EstimateWidth( text, _font );
			return null;
		} );
		LuaState.Register( surface, "GetTextSize", ( s, a ) =>
		{
			var text = Str( s, a, 0 );
			var f = _fonts.TryGetValue( _font, out var ff ) ? ff : _fonts["DermaDefault"];
			return new LuaValue[] { Math.Round( EstimateWidth( text, _font ) ), f.Size };
		} );
		LuaState.Register( surface, "CreateFont", ( s, a ) =>
		{
			var name = LuaState.CheckString( a, 0, "surface.CreateFont" );
			var data = LuaState.CheckTable( a, 1, "surface.CreateFont" );
			if ( name.Length > 64 ) throw LuaState.ArgError( 0, "surface.CreateFont", "name longer than 64 characters" );
			if ( _fonts.Count >= 256 && !_fonts.ContainsKey( name ) ) throw new LuaRuntimeException( "too many fonts (limit 256)" );
			var family = data.Get( "font" ).IsString ? data.Get( "font" ).AsString : "Inter";
			if ( family.Length > 64 || family.Any( ch => ch is ';' or '{' or '}' or ':' ) ) throw LuaState.ArgError( 1, "surface.CreateFont", "invalid font name" );
			int size = LuaState.ToNumber( data.Get( "size" ), out var sz ) ? (int)Math.Clamp( sz, 4, 512 ) : 13;
			int weight = LuaState.ToNumber( data.Get( "weight" ), out var wt ) ? (int)Math.Clamp( wt, 100, 900 ) : 500;
			_fonts[name] = new Font { Family = family, Size = size, Weight = weight };
			return null;
		} );
	}

	static float UiScale()
	{
		try { var s = LuaUi.ScreenRoot.ScaleToScreen; return s > 0.01f ? s : 1f; }
		catch ( LuaRuntimeException ) { return 1f; }
	}

	/// <summary>Rough text width (no font metrics are available to Lua): 0.55 em per character.</summary>
	static double EstimateWidth( string text, string font )
	{
		var f = _fonts.TryGetValue( font ?? "", out var ff ) ? ff : _fonts["DermaDefault"];
		return text.Length * f.Size * 0.55;
	}
}